Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointRestoreSafety.ts

58 lines2.5 KB

1import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import type * as FileSystem from "effect/FileSystem";
4import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
5​
6export const SHARED_WORKSPACE_RESTORE_MESSAGE =
7 "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.";
8​
9// A checkpoint snapshots the whole checkout. Check at command admission and
10// again before provider rollback so a newly shared worktree is rejected too.
11export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(
12 function* (
13 thread: Pick<OrchestrationV2AppThread, "id" | "worktreePath">,
14 scope: Pick<OrchestrationV2CheckpointScope, "cwd">,
15 dependencies: {
16 readonly fileSystem: FileSystem.FileSystem;
17 readonly projections: ProjectionStoreV2["Service"];
18 },
19 ) {
20 const { fileSystem, projections } = dependencies;
21 const worktreePath = thread.worktreePath;
22 let shared = worktreePath == null;
23 if (!shared && worktreePath !== null) {
24 const cwd = yield* fileSystem.realPath(scope.cwd);
25 const worktreeCwd = yield* fileSystem.realPath(worktreePath);
26 shared = cwd !== worktreeCwd;
27 if (!shared) {
28 const shell = yield* projections.getShellSnapshot();
29 const checkedPaths = new Set<string>();
30 for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
31 if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
32 const other = yield* projections.getCheckpointContext(otherThread.id);
33 const paths = [
34 otherThread.worktreePath,
35 ...other.checkpointScopes.map((candidate) => candidate.cwd),
36 ].filter((value): value is string => value !== null);
37 for (const candidate of paths) {
38 if (checkedPaths.has(candidate)) continue;
39 checkedPaths.add(candidate);
40 const otherCwd = yield* fileSystem
41 .realPath(candidate)
42 .pipe(
43 Effect.catch((error) =>
44 error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error),
45 ),
46 );
47 if (otherCwd === cwd) {
48 shared = true;
49 break;
50 }
51 }
52 if (shared) break;
53 }
54 }
55 }
56 return !shared;
57 },
58);