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