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

CheckpointRestoreSafety.ts

220 lines9.8 KB

1import {
2 isLiveSubagentShell,
3 isProviderNativeSubagentThread,
4 type OrchestrationV2AppThread,
5 type OrchestrationV2CheckpointScope,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2ThreadShell,
8 type TaskFolder,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import type * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import type * as Path from "effect/Path";
14import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
15import type * as ProjectStore from "./ProjectStore.ts";
16​
17const UNFINISHED_RUN_STATUSES = new Set(["queued", "preparing", "starting", "running", "waiting"]);
18​
19export const SHARED_WORKSPACE_RESTORE_MESSAGE =
20 "File restore requires an isolated worktree. This workspace may contain changes from another thread or a side chat. Rewind the conversation without restoring files instead, or delete side chats you no longer need.";
21​
22// Check isolation at admission and rollback; checkpoints restore whole checkouts, which may become shared.
23export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(
24 function* (
25 thread: Pick<OrchestrationV2AppThread, "id" | "worktreePath">,
26 scope: Pick<OrchestrationV2CheckpointScope, "cwd">,
27 /** The task folder the thread works in: a file restore reaches its repository worktrees too. */
28 taskFolder: Pick<TaskFolder, "repositories"> | null,
29 dependencies: {
30 readonly fileSystem: FileSystem.FileSystem;
31 readonly projections: ProjectionStoreV2["Service"];
32 readonly projects: ProjectStore.ProjectStoreV2["Service"];
33 readonly path: Path.Path;
34 },
35 ) {
36 const { fileSystem, projections, projects, path } = dependencies;
37 const contains = (parent: string, child: string) => {
38 const relative = path.relative(parent, child);
39 return (
40 relative === "" ||
41 (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
42 );
43 };
44 const worktreePath = thread.worktreePath;
45 let shared = worktreePath == null;
46 if (!shared && worktreePath !== null) {
47 // Storage cleanup may have removed the worktree; rollback recreates it.
48 const resolve = (target: string) =>
49 fileSystem.realPath(target).pipe(
50 Effect.catchIf(
51 (error) => error.reason._tag === "NotFound",
52 (_error) => Effect.succeed(path.resolve(target)),
53 ),
54 );
55 const cwd = yield* resolve(scope.cwd);
56 const worktreeCwd = yield* resolve(worktreePath);
57 shared = cwd !== worktreeCwd;
58 if (!shared) {
59 const restored = [
60 cwd,
61 ...(yield* Effect.forEach(taskFolder?.repositories ?? [], (repository) =>
62 resolve(repository.worktreePath),
63 )),
64 ];
65 const shell = yield* projections.getShellSnapshot();
66 const threads = [...shell.threads, ...shell.archivedThreads];
67 const threadsById = new Map(threads.map((candidate) => [candidate.id, candidate]));
68 const subagentAncestors = (candidate: OrchestrationV2ThreadShell) => {
69 const ancestors: OrchestrationV2AppThread["id"][] = [];
70 const seen = new Set<string>();
71 let current: OrchestrationV2ThreadShell | undefined = candidate;
72 while (current !== undefined && !seen.has(current.id)) {
73 seen.add(current.id);
74 if (current.lineage.relationshipToParent !== "subagent") return undefined;
75 const parentId: OrchestrationV2AppThread["id"] | null = current.lineage.parentThreadId;
76 if (parentId === null) return undefined;
77 ancestors.push(parentId);
78 if (parentId === thread.id) return ancestors;
79 current = threadsById.get(parentId);
80 }
81 return undefined;
82 };
83 const ancestorProviders = new Map<
84 OrchestrationV2AppThread["id"],
85 ReadonlyArray<OrchestrationV2ProviderThread>
86 >();
87 const checkedPaths = new Set<string>();
88 for (const otherThread of threads) {
89 if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
90 // An idle side chat that only answered questions never touched the shared worktree.
91 if (
92 otherThread.lineage.sideChat === true &&
93 otherThread.activeRunId === null &&
94 otherThread.worktreePath === worktreePath
95 ) {
96 const { turnItems } = yield* projections.getThreadRecords(
97 otherThread.id,
98 ["turnItems"],
99 {
100 turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],
101 },
102 );
103 if (turnItems.length === 0) continue;
104 }
105 const other = yield* projections.getCheckpointContext(otherThread.id);
106 const nativeSubagent = isProviderNativeSubagentThread(otherThread);
107 const ancestors = subagentAncestors(otherThread);
108 // Native children can be runless; their completion lives on the parent's task record.
109 if (
110 otherThread.worktreePath === worktreePath &&
111 (otherThread.status === "completed" ||
112 (nativeSubagent && otherThread.status === "idle" && other.runs.length === 0)) &&
113 otherThread.activeRunId === null &&
114 !isLiveSubagentShell(otherThread) &&
115 ancestors !== undefined &&
116 !other.runs.some((run) => UNFINISHED_RUN_STATUSES.has(run.status)) &&
117 otherThread.lineage.parentThreadId !== null &&
118 otherThread.forkedFrom?.type === "node"
119 ) {
120 const taskNodeId = otherThread.forkedFrom.nodeId;
121 const { subagents } = yield* projections.getThreadRecords(
122 otherThread.lineage.parentThreadId,
123 ["subagents"],
124 { subagentIds: [taskNodeId] },
125 );
126 const task = subagents.find(
127 (candidate) =>
128 candidate.id === taskNodeId && candidate.childThreadId === otherThread.id,
129 );
130 if (
131 task?.status === "completed" &&
132 task.origin === (nativeSubagent ? "provider_native" : "app_owned")
133 ) {
134 if (!nativeSubagent) continue;
135 // Runless shells omit background work; inspect the raw records before restoring files.
136 const { providerThreads, turnItems } = yield* projections.getThreadRecords(
137 otherThread.id,
138 ["providerThreads", "turnItems"],
139 {
140 turnItemTypes: ["command_execution", "file_change", "dynamic_tool", "subagent"],
141 turnItemStatuses: ["pending", "running", "waiting"],
142 },
143 );
144 if (
145 turnItems.length === 0 &&
146 !providerThreads.some(
147 (providerThread) =>
148 providerThread.status === "active" ||
149 (providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
150 )
151 ) {
152 // Claude can keep a child's unattributed background commands on an ancestor session.
153 let pendingAncestorWork = false;
154 for (const ancestorId of ancestors) {
155 let providers = ancestorProviders.get(ancestorId);
156 if (providers === undefined) {
157 const records = yield* projections.getThreadRecords(ancestorId, [
158 "providerThreads",
159 ]);
160 providers = records.providerThreads;
161 ancestorProviders.set(ancestorId, providers);
162 }
163 if (
164 providers.some(
165 (provider) =>
166 provider.providerInstanceId === task.providerInstanceId &&
167 (provider.pendingBackgroundTasks?.length ?? 0) > 0,
168 )
169 ) {
170 pendingAncestorWork = true;
171 break;
172 }
173 }
174 if (!pendingAncestorWork) continue;
175 }
176 }
177 }
178 const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
179 const paths = [
180 otherThread.worktreePath,
181 ...other.checkpointScopes.map((candidate) => candidate.cwd),
182 // Errored sessions can still stream. Shared sessions retain another thread's opening cwd;
183 // turn worktrees and project roots are already covered here.
184 ...providerContext.providerSessions
185 .filter(
186 (session) =>
187 session.status !== "stopped" &&
188 !session.capabilities.sessions.supportsMultipleProviderThreadsPerSession,
189 )
190 .map((session) => session.cwd),
191 ].filter((value): value is string => value !== null);
192 if (otherThread.worktreePath === null) {
193 const project = yield* projects.get(otherThread.projectId, { includeDeleted: true });
194 if (Option.isNone(project)) return false;
195 paths.push(project.value.workspaceRoot);
196 }
197 for (const candidate of paths) {
198 if (checkedPaths.has(candidate)) continue;
199 checkedPaths.add(candidate);
200 const otherCwd = yield* fileSystem.realPath(candidate).pipe(
201 Effect.catchIf(
202 (error) => error.reason._tag === "NotFound",
203 (_error) => Effect.succeed(null),
204 ),
205 );
206 if (
207 otherCwd !== null &&
208 restored.some((folder) => contains(folder, otherCwd) || contains(otherCwd, folder))
209 ) {
210 shared = true;
211 break;
212 }
213 }
214 if (shared) break;
215 }
216 }
217 }
218 return !shared;
219 },
220);