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