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