Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationProjectShell,
4 ProjectId,
5 type Project,
6 type ProjectCreatePayload,
7 type ProjectUpdatePayload,
8 type ProjectSnapshot,
9 type ThreadId,
10} from "@t3tools/contracts";
11import * as KeyedLock from "@t3tools/shared/KeyedLock";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Result from "effect/Result";
18import * as Schema from "effect/Schema";
19
20import { withCommandMetrics } from "../observability/Metrics.ts";
21import * as EventSink from "../orchestration-v2/EventSink.ts";
22import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
23import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
24import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
25import {
26 decodeProjectCommandRejection,
27 encodeProjectCommandRejection,
28 planProjectCommand,
29 type ProjectCommand,
30} from "../orchestration-v2/ProjectCommands.ts";
31import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
32import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
33import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
36import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
37
38export interface ProjectCreateInput extends ProjectCreatePayload {
39 readonly commandId: CommandId;
40 readonly projectId: ProjectId;
41}
42
43export interface ProjectUpdateInput extends ProjectUpdatePayload {
44 readonly commandId: CommandId;
45 readonly projectId: ProjectId;
46}
47
48export interface ProjectBootstrapInput extends ProjectCreateInput {}
49
50export interface ProjectDeleteInput {
51 readonly commandId: CommandId;
52 readonly projectId: ProjectId;
53 readonly force?: boolean;
54}
55
56export class ProjectNotFoundError extends Schema.TaggedError<ProjectNotFoundError>()(
57 "ProjectNotFoundError",
58 { projectId: ProjectId },
59) {
60 override get message(): string {
61 return `Project ${this.projectId} was not found.`;
62 }
63}
64
65export class ProjectConflictError extends Schema.TaggedError<ProjectConflictError>()(
66 "ProjectConflictError",
67 {
68 projectId: ProjectId,
69 workspaceRoot: Schema.String,
70 conflictingProjectId: ProjectId,
71 },
72) {
73 override get message(): string {
74 return `Workspace ${this.workspaceRoot} already belongs to project ${this.conflictingProjectId}.`;
75 }
76}
77
78export class ProjectNotEmptyError extends Schema.TaggedError<ProjectNotEmptyError>()(
79 "ProjectNotEmptyError",
80 { projectId: ProjectId },
81) {
82 override get message(): string {
83 return `Project ${this.projectId} is not empty.`;
84 }
85}
86
87export class ProjectOperationError extends Schema.TaggedError<ProjectOperationError>()(
88 "ProjectOperationError",
89 {
90 operation: Schema.Literals([
91 "normalize-workspace",
92 "read-project",
93 "list-projects",
94 "list-threads",
95 "delete-thread",
96 "dispatch-project-command",
97 ]),
98 projectId: Schema.optional(ProjectId),
99 workspaceRoot: Schema.optional(Schema.String),
100 cause: Schema.Defect(),
101 },
102) {
103 override get message(): string {
104 return `Project operation '${this.operation}' failed${this.projectId === undefined ? "" : ` for ${this.projectId}`}.`;
105 }
106}
107
108export type ProjectServiceError =
109 | ProjectNotFoundError
110 | ProjectConflictError
111 | ProjectNotEmptyError
112 | ProjectOperationError;
113
114export class ProjectService extends Context.Service<
115 ProjectService,
116 {
117 readonly create: (input: ProjectCreateInput) => Effect.Effect<Project, ProjectServiceError>;
118 readonly bootstrap: (
119 input: ProjectBootstrapInput,
120 ) => Effect.Effect<
121 { readonly project: Project; readonly created: boolean },
122 ProjectServiceError
123 >;
124 readonly update: (input: ProjectUpdateInput) => Effect.Effect<Project, ProjectServiceError>;
125 readonly delete: (input: ProjectDeleteInput) => Effect.Effect<Project, ProjectServiceError>;
126 readonly getById: (
127 projectId: ProjectId,
128 options?: { readonly includeDeleted?: boolean },
129 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
130 readonly getByWorkspaceRoot: (
131 workspaceRoot: string,
132 options?: { readonly includeDeleted?: boolean },
133 ) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
134 readonly snapshot: Effect.Effect<ProjectSnapshot, ProjectOperationError>;
135 /**
136 * A page of active projects in creation order, each with its repository
137 * identity resolved, so a caller can match projects by repository.
138 */
139 readonly listPage: (input: {
140 readonly cursor: number;
141 readonly limit: number;
142 }) => Effect.Effect<
143 { readonly projects: ReadonlyArray<Project>; readonly nextCursor: number | null },
144 ProjectOperationError
145 >;
146 readonly getShell: (
147 projectId: ProjectId,
148 ) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectOperationError>;
149 readonly listShells: (options?: {
150 readonly projectIds?: ReadonlyArray<ProjectId>;
151 }) => Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, ProjectOperationError>;
152 }
153>()("t3/project/ProjectService") {}
154
155export const make = Effect.gen(function* () {
156 const projects = yield* ProjectStore.ProjectStoreV2;
157 const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
158 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
159 const threadProjections = yield* ProjectionStore.ProjectionStoreV2;
160 const eventSink = yield* EventSink.EventSinkV2;
161 const idAllocator = yield* IdAllocator.IdAllocatorV2;
162 const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
163 const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
164 const serverSettings = yield* ServerSettings.ServerSettingsService;
165 const projectLocks = yield* KeyedLock.make<ProjectId>();
166 const workspaceLocks = yield* KeyedLock.make<string>();
167
168 const toProject = (
169 row: ProjectStore.ProjectRow,
170 enrichment: ProjectEnrichmentService.ProjectEnrichment | null,
171 ): Project => ({
172 id: row.projectId,
173 title: row.title,
174 workspaceRoot: row.workspaceRoot,
175 repositoryIdentity: enrichment?.repositoryIdentity ?? null,
176 faviconPath: row.faviconPath ?? enrichment?.faviconPath ?? null,
177 defaultModelSelection: row.defaultModelSelection,
178 defaultThreadEnvMode: row.defaultThreadEnvMode,
179 autoPull: row.autoPull,
180 projectIcon: row.projectIcon,
181 scripts: row.scripts,
182 createdAt: row.createdAt,
183 updatedAt: row.updatedAt,
184 deletedAt: row.deletedAt,
185 });
186
187 const hydrate = Effect.fn("ProjectService.hydrate")(function* (row: ProjectStore.ProjectRow) {
188 const enrichment =
189 row.deletedAt === null
190 ? yield* projectEnrichment.getAvailable(row.workspaceRoot)
191 : yield* projectEnrichment.peek(row.workspaceRoot);
192 return toProject(row, enrichment);
193 });
194
195 const readRow = (projectId: ProjectId, options?: { readonly includeDeleted?: boolean }) =>
196 projects
197 .get(projectId, options)
198 .pipe(
199 Effect.mapError(
200 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
201 ),
202 );
203
204 const normalizeWorkspaceRoot = (input: {
205 readonly projectId?: ProjectId;
206 readonly workspaceRoot: string;
207 readonly createIfMissing?: boolean;
208 }) =>
209 workspacePaths
210 .normalizeWorkspaceRoot(input.workspaceRoot, {
211 createIfMissing: input.createIfMissing ?? false,
212 })
213 .pipe(
214 Effect.mapError(
215 (cause) =>
216 new ProjectOperationError({
217 operation: "normalize-workspace",
218 ...(input.projectId === undefined ? {} : { projectId: input.projectId }),
219 workspaceRoot: input.workspaceRoot,
220 cause,
221 }),
222 ),
223 );
224
225 const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) {
226 const { projectId } = command;
227 const dispatchError = (cause: unknown) =>
228 new ProjectOperationError({ operation: "dispatch-project-command", projectId, cause });
229 const workspaceRoot = command.type === "project.delete" ? undefined : command.workspaceRoot;
230 const planAndCommit = Effect.gen(function* () {
231 const project = Option.getOrUndefined(yield* readRow(projectId, { includeDeleted: true }));
232 const workspaceOwner =
233 workspaceRoot === undefined
234 ? undefined
235 : Option.getOrUndefined(
236 yield* projects
237 .findActiveByWorkspaceRoot(workspaceRoot)
238 .pipe(Effect.mapError(dispatchError)),
239 );
240 const now = yield* DateTime.now;
241 const eventId = yield* idAllocator.allocate
242 .event({ commandId: command.commandId })
243 .pipe(Effect.mapError(dispatchError));
244 const planned = planProjectCommand({
245 command,
246 state: { project, workspaceOwner },
247 eventId,
248 now,
249 });
250 if (Result.isSuccess(planned)) {
251 const { receipt } = yield* eventSink.commitProjectCommand({
252 commandId: command.commandId,
253 projectId,
254 commandType: command.type,
255 acceptedAt: now,
256 event: planned.success,
257 });
258 return receipt;
259 }
260 return yield* eventSink.commitRejectedProjectCommand({
261 commandId: command.commandId,
262 projectId,
263 commandType: command.type,
264 rejectedAt: now,
265 error: encodeProjectCommandRejection(planned.failure),
266 });
267 });
268 const receipt = yield* projectLocks
269 .withLock(
270 projectId,
271 workspaceRoot === undefined
272 ? planAndCommit
273 : workspaceLocks.withLock(workspaceRoot, planAndCommit),
274 )
275 .pipe(Effect.mapError(dispatchError));
276 if (receipt.projectId !== projectId || receipt.commandType !== command.type) {
277 return yield* dispatchError(
278 `Command ${command.commandId} was already used by ${receipt.commandType} for ${receipt.projectId}.`,
279 );
280 }
281 // Retries re-plan against their own effects; the first receipt determines the outcome.
282 if (receipt.status === "accepted") return;
283 const rejection = Option.getOrUndefined(decodeProjectCommandRejection(receipt.error));
284 switch (rejection?._tag) {
285 case "ProjectWorkspaceConflictError":
286 return yield* new ProjectConflictError({
287 projectId,
288 workspaceRoot: rejection.workspaceRoot,
289 conflictingProjectId: rejection.conflictingProjectId,
290 });
291 case "ProjectCommandMissingProjectError":
292 return yield* new ProjectNotFoundError({ projectId });
293 default:
294 return yield* dispatchError(
295 rejection ?? receipt.error ?? "The command was previously rejected.",
296 );
297 }
298 }, withCommandMetrics);
299
300 const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
301 const row = yield* readRow(projectId, { includeDeleted: true });
302 if (Option.isNone(row)) {
303 return yield* new ProjectOperationError({
304 operation: "read-project",
305 projectId,
306 cause: "The accepted project command did not produce a project row.",
307 });
308 }
309 return yield* hydrate(row.value);
310 });
311
312 const getById: ProjectService["Service"]["getById"] = Effect.fn("ProjectService.getById")(
313 function* (projectId, options) {
314 const row = yield* readRow(projectId, options);
315 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
316 },
317 );
318
319 const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(
320 "ProjectService.getByWorkspaceRoot",
321 )(function* (workspaceRoot, options) {
322 const normalized = yield* normalizeWorkspaceRoot({ workspaceRoot });
323 const row = yield* (
324 options?.includeDeleted === true
325 ? projects
326 .list({ includeDeleted: true })
327 .pipe(
328 Effect.map((rows) =>
329 Option.fromUndefinedOr(rows.find((row) => row.workspaceRoot === normalized)),
330 ),
331 )
332 : projects.findActiveByWorkspaceRoot(normalized)
333 ).pipe(
334 Effect.mapError((cause) => new ProjectOperationError({ operation: "list-projects", cause })),
335 );
336 return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value));
337 });
338
339 const create: ProjectService["Service"]["create"] = Effect.fn("ProjectService.create")(
340 function* (input) {
341 const workspaceRoot = yield* normalizeWorkspaceRoot({
342 projectId: input.projectId,
343 workspaceRoot: input.workspaceRoot,
344 createIfMissing: input.createWorkspaceRootIfMissing ?? false,
345 });
346 yield* commit({
347 type: "project.create",
348 commandId: input.commandId,
349 projectId: input.projectId,
350 title: input.title,
351 workspaceRoot,
352 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
353 });
354 yield* projectEnrichment.invalidate([workspaceRoot]);
355 return yield* readCommitted(input.projectId);
356 },
357 );
358
359 const update: ProjectService["Service"]["update"] = Effect.fn("ProjectService.update")(
360 function* (input) {
361 const existing = yield* readRow(input.projectId);
362 if (Option.isNone(existing)) {
363 return yield* new ProjectNotFoundError({ projectId: input.projectId });
364 }
365 const previousRoot = existing.value.workspaceRoot;
366 const workspaceRoot =
367 input.workspaceRoot === undefined
368 ? previousRoot
369 : yield* normalizeWorkspaceRoot({
370 projectId: input.projectId,
371 workspaceRoot: input.workspaceRoot,
372 });
373 yield* commit({
374 type: "project.meta.update",
375 commandId: input.commandId,
376 projectId: input.projectId,
377 ...(input.title === undefined ? {} : { title: input.title }),
378 ...(workspaceRoot === previousRoot ? {} : { workspaceRoot }),
379 ...(input.defaultModelSelection === undefined
380 ? {}
381 : { defaultModelSelection: input.defaultModelSelection }),
382 ...(input.autoPull === undefined ? {} : { autoPull: input.autoPull }),
383 ...(input.projectIcon === undefined ? {} : { projectIcon: input.projectIcon }),
384 ...(input.faviconPath === undefined ? {} : { faviconPath: input.faviconPath }),
385 ...(input.defaultThreadEnvMode === undefined
386 ? {}
387 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
388 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
389 });
390 if (workspaceRoot !== previousRoot) {
391 yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]);
392 }
393 return yield* readCommitted(input.projectId);
394 },
395 );
396
397 const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
398 function* (input) {
399 const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
400 if (Option.isSome(existing)) return { project: existing.value, created: false };
401 return { project: yield* create(input), created: true };
402 },
403 );
404
405 const deleteChildThread = Effect.fn("ProjectService.deleteChildThread")(function* (
406 input: ProjectDeleteInput,
407 threadId: ThreadId,
408 ) {
409 yield* legacyImporter.ensureTranscript(threadId);
410 const projection = yield* threadProjections.getThreadRecords(threadId, [
411 "runs",
412 "attempts",
413 "nodes",
414 "runtimeRequests",
415 "subagents",
416 "providerSessions",
417 ]);
418 if (projection.thread.deletedAt !== null || projection.thread.projectId !== input.projectId) {
419 return;
420 }
421 const command = {
422 type: "thread.delete" as const,
423 commandId: CommandId.make(`${input.commandId}:delete-thread:${threadId}`),
424 threadId,
425 };
426 const now = yield* DateTime.now;
427 const plan = yield* planThreadDeletion({
428 command,
429 projection,
430 attachmentIds: yield* threadProjections.getThreadAttachmentIds(threadId),
431 now,
432 idAllocator,
433 });
434 const committed = yield* eventSink.commitCommand({
435 commandId: command.commandId,
436 commandType: command.type,
437 threadId,
438 acceptedAt: now,
439 events: plan.events,
440 effects: plan.effects,
441 });
442 if (
443 committed.receipt.threadId !== command.threadId ||
444 committed.receipt.commandType !== command.type
445 ) {
446 return yield* Effect.fail("The thread deletion command ID belongs to a different command.");
447 }
448 if (committed.receipt.status === "rejected") {
449 return yield* Effect.fail(
450 committed.receipt.error ?? "Thread deletion was previously rejected.",
451 );
452 }
453 });
454
455 const deleteChildThreads = Effect.fn("ProjectService.deleteChildThreads")(function* (
456 input: ProjectDeleteInput,
457 ) {
458 const { projectId } = input;
459 const snapshot = yield* threadProjections
460 .getShellSnapshot({ projectId })
461 .pipe(
462 Effect.mapError(
463 (cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }),
464 ),
465 );
466 const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads];
467 if (projectThreads.length > 0 && input.force !== true) {
468 return yield* new ProjectNotEmptyError({ projectId });
469 }
470 // Delete children durably before the project so a failed cascade can be retried.
471 yield* Effect.forEach(
472 projectThreads,
473 (thread) =>
474 threadCommands
475 .withLock(thread.id, deleteChildThread(input, thread.id))
476 .pipe(
477 Effect.mapError(
478 (cause) =>
479 new ProjectOperationError({ operation: "delete-thread", projectId, cause }),
480 ),
481 ),
482 { concurrency: 1, discard: true },
483 );
484 });
485
486 // Best-effort cleanup releases disabled instances kept alive by overrides; crashes have no replay to revisit deletion.
487 const clearProjectSettingsOverrides = (projectId: ProjectId) =>
488 serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe(
489 Effect.asVoid,
490 Effect.catchCause((cause) =>
491 Effect.logWarning(
492 `Failed to clear settings overrides for deleted project ${projectId}.`,
493 cause,
494 ),
495 ),
496 );
497
498 const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
499 function* (input) {
500 const { projectId } = input;
501 // Read deleted rows so retries replay receipts and other command ids fail as not found.
502 const existing = yield* readRow(projectId, { includeDeleted: true });
503 if (Option.isNone(existing)) {
504 return yield* new ProjectNotFoundError({ projectId });
505 }
506
507 const isFirstDelete = existing.value.deletedAt === null;
508 if (isFirstDelete) {
509 yield* deleteChildThreads(input);
510 }
511 yield* commit({ type: "project.delete", commandId: input.commandId, projectId });
512 if (isFirstDelete) {
513 yield* clearProjectSettingsOverrides(projectId);
514 }
515 yield* projectEnrichment.invalidate([existing.value.workspaceRoot]);
516 return yield* readCommitted(projectId);
517 },
518 );
519
520 const enrichShell = (shell: OrchestrationProjectShell) =>
521 projectEnrichment.getAvailable(shell.workspaceRoot).pipe(
522 Effect.map((enrichment) => ({
523 ...shell,
524 repositoryIdentity: enrichment.repositoryIdentity,
525 })),
526 );
527
528 const getShell: ProjectService["Service"]["getShell"] = Effect.fn("ProjectService.getShell")(
529 function* (projectId) {
530 const shell = yield* projects
531 .getShell(projectId)
532 .pipe(
533 Effect.mapError(
534 (cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
535 ),
536 );
537 return Option.isNone(shell) ? shell : Option.some(yield* enrichShell(shell.value));
538 },
539 );
540
541 const listShells: ProjectService["Service"]["listShells"] = Effect.fn(
542 "ProjectService.listShells",
543 )(function* (options) {
544 const shells = yield* projects
545 .listShells(options)
546 .pipe(
547 Effect.mapError(
548 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
549 ),
550 );
551 return yield* Effect.forEach(shells, enrichShell, { concurrency: 16 });
552 });
553
554 const snapshot = Effect.gen(function* () {
555 const rows = yield* projects
556 .list()
557 .pipe(
558 Effect.mapError(
559 (cause) => new ProjectOperationError({ operation: "list-projects", cause }),
560 ),
561 );
562 const hydrated = yield* Effect.forEach(rows, hydrate, { concurrency: 8 });
563 return {
564 projects: hydrated,
565 updatedAt: DateTime.formatIso(yield* DateTime.now),
566 } satisfies ProjectSnapshot;
567 });
568
569 const listPage: ProjectService["Service"]["listPage"] = Effect.fn("ProjectService.listPage")(
570 function* ({ cursor, limit }) {
571 const rows = (yield* snapshot).projects.filter((project) => project.deletedAt === null);
572 const projects = yield* Effect.forEach(
573 rows.slice(cursor, cursor + limit),
574 (project) =>
575 project.repositoryIdentity !== null
576 ? Effect.succeed(project)
577 : projectEnrichment
578 .readRepositoryIdentity(project.workspaceRoot)
579 .pipe(Effect.map((repositoryIdentity) => ({ ...project, repositoryIdentity }))),
580 { concurrency: 8 },
581 );
582 return { projects, nextCursor: cursor + limit < rows.length ? cursor + limit : null };
583 },
584 );
585
586 return ProjectService.of({
587 create,
588 bootstrap,
589 update,
590 delete: deleteProject,
591 getById,
592 getByWorkspaceRoot,
593 snapshot,
594 listPage,
595 getShell,
596 listShells,
597 });
598});
599
600export const layer = Layer.effect(ProjectService, make).pipe(
601 Layer.provide(ThreadCommandExecutor.layer),
602);