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