Skip to content

Commit 79b590a

Browse files
fix(server): legacy checkpoints restore files again, and a moved thread stops blocking its old worktree
Drop the blanket refusal for the pre-change root scope: when its cwd matches the thread's current worktree the normal isolation check applies, as on main, and a mismatch is already refused as another worktree. The isolation check now counts only another thread's newest root scope, so a thread that moved away no longer blocks restores in the worktree it left. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 01fe070 commit 79b590a

6 files changed

Lines changed: 78 additions & 104 deletions

File tree

‎apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts‎

Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,9 @@ import * as ServerConfig from "../config.ts";
1717
import * as ServerSettings from "../serverSettings.ts";
1818
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
1919
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
20-
import {
21-
checkpointRestoreRefusal,
22-
LEGACY_CHECKPOINT_RESTORE_MESSAGE,
23-
} from "./CheckpointRestoreSafety.ts";
20+
import { checkpointRestoreRefusal } from "./CheckpointRestoreSafety.ts";
2421
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
25-
import { CheckpointServiceV2, legacyRootScopeId } from "./CheckpointService.ts";
22+
import { CheckpointServiceV2 } from "./CheckpointService.ts";
2623
import { EventSinkV2 } from "./EventSink.ts";
2724
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
2825
import { ProjectionStoreV2, type ProjectionCheckpointRollbackContext } from "./ProjectionStore.ts";
@@ -37,8 +34,7 @@ it.effect.each([
3734
"sibling",
3835
"shared-provider",
3936
"conversation",
40-
"legacy",
41-
"legacy-conversation",
37+
"moved",
4238
] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
4339
Effect.gen(function* () {
4440
const fs = yield* FileSystem.FileSystem;
@@ -58,10 +54,7 @@ it.effect.each([
5854
const providerSessionId = ProviderSessionId.make("restore-session");
5955
const instanceId = ProviderInstanceId.make("restore-instance");
6056
const checkpointId = CheckpointId.make("restore-checkpoint");
61-
// A thread that never moved still keeps one legacy root scope from before per-workspace scopes.
62-
const scopeId = owner.startsWith("legacy")
63-
? yield* legacyRootScopeId(yield* IdAllocator.IdAllocatorV2, threadId)
64-
: CheckpointScopeId.make("restore-scope");
57+
const scopeId = CheckpointScopeId.make("restore-scope");
6558
const calls: string[] = [];
6659
const providerThread = {
6760
id: providerThreadId,
@@ -124,10 +117,20 @@ it.effect.each([
124117
}),
125118
getCheckpointContext: () =>
126119
Effect.succeed({
127-
runs: [],
120+
runs: [
121+
{ id: "other-run-1", ordinal: 1 },
122+
{ id: "other-run-2", ordinal: 2 },
123+
],
128124
checkpoints: [],
129-
checkpointScopes: [],
130-
}),
125+
// A thread that left this worktree keeps its old root scope here.
126+
checkpointScopes:
127+
owner === "moved"
128+
? [
129+
{ kind: "root_run", runId: "other-run-1", cwd: nested },
130+
{ kind: "root_run", runId: "other-run-2", cwd: sibling },
131+
]
132+
: [],
133+
}) as never,
131134
getThreadProviderContext: () =>
132135
Effect.succeed({
133136
thread: otherThread as never,
@@ -174,31 +177,21 @@ it.effect.each([
174177
const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2.pipe(
175178
Effect.provide(layerTest),
176179
);
177-
const restoreFiles = !owner.endsWith("conversation");
178-
const rejected = ![
179-
"sibling",
180-
"shared-provider",
181-
"conversation",
182-
"legacy-conversation",
183-
].includes(owner);
180+
const restoreFiles = owner !== "conversation";
181+
const rejected = !["sibling", "shared-provider", "conversation", "moved"].includes(owner);
184182
if (rejected) {
185183
const error = yield* service
186184
.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
187185
.pipe(Effect.flip);
188-
if (owner === "legacy") {
189-
assert.equal(error.reason, "legacy-checkpoint");
190-
assert.equal(error.message, LEGACY_CHECKPOINT_RESTORE_MESSAGE);
191-
} else {
192-
assert.equal(error.reason, "shared-workspace");
193-
}
186+
assert.equal(error.reason, "shared-workspace");
194187
assert.deepEqual(calls, []);
195188
assert.equal(yield* fs.readFileString(otherFile), "other thread's uncommitted work");
196189
} else {
197190
yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles });
198191
assert.deepEqual(calls, restoreFiles ? ["provider", "files"] : ["provider"]);
199192
assert.equal(yield* fs.exists(otherFile), !restoreFiles);
200193
}
201-
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
194+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
202195
);
203196

204197
it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
@@ -209,10 +202,9 @@ it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
209202
const worktreePath = path.join(parent, "worktree");
210203
const refusal = yield* checkpointRestoreRefusal(
211204
{ id: ThreadId.make("restore-removed"), worktreePath },
212-
{ id: CheckpointScopeId.make("restore-removed-scope"), cwd: worktreePath },
205+
{ cwd: worktreePath },
213206
{
214207
fileSystem,
215-
idAllocator: yield* IdAllocator.IdAllocatorV2,
216208
path,
217209
projections: {
218210
getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
@@ -221,7 +213,7 @@ it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
221213
},
222214
);
223215
assert.isNull(refusal);
224-
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
216+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
225217
);
226218

227219
it.effect.each([
@@ -253,23 +245,22 @@ it.effect.each([
253245
};
254246
const refusal = yield* checkpointRestoreRefusal(
255247
{ id: parentId, worktreePath },
256-
{ id: CheckpointScopeId.make("restore-side-chat-scope"), cwd: worktreePath },
248+
{ cwd: worktreePath },
257249
{
258250
fileSystem,
259-
idAllocator: yield* IdAllocator.IdAllocatorV2,
260251
path,
261252
projections: {
262253
getShellSnapshot: () => Effect.succeed({ threads: [sideChat], archivedThreads: [] }),
263254
getThreadRecords: () =>
264255
Effect.succeed({
265256
turnItems: Array.from({ length: toolItems }, () => ({ type: "command_execution" })),
266257
}),
267-
getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] }),
258+
getCheckpointContext: () => Effect.succeed({ runs: [], checkpointScopes: [] }),
268259
getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
269260
} as never,
270261
projects: {} as never,
271262
},
272263
);
273264
assert.equal(refusal === null, isolated);
274-
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
265+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
275266
);

‎apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,19 @@ import * as Effect from "effect/Effect";
33
import type * as FileSystem from "effect/FileSystem";
44
import * as Option from "effect/Option";
55
import type * as Path from "effect/Path";
6-
import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
7-
import { legacyRootScopeId } from "./CheckpointService.ts";
86
import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
97
import type * as ProjectStore from "./ProjectStore.ts";
108

119
const SHARED_WORKSPACE_RESTORE_MESSAGE =
1210
"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.";
1311

14-
export const LEGACY_CHECKPOINT_RESTORE_MESSAGE =
15-
"This turn was recorded before T3 Code tracked which worktree each turn ran in, so its files can't be restored. Rewind the conversation without restoring files instead.";
16-
1712
const OTHER_WORKSPACE_RESTORE_MESSAGE =
1813
"This turn ran in a different worktree, so its files can't be restored into this one. Rewind the conversation without restoring files instead.";
1914

20-
export type CheckpointRestoreRefusal = "shared-workspace" | "legacy-checkpoint" | "other-workspace";
15+
export type CheckpointRestoreRefusal = "shared-workspace" | "other-workspace";
2116

2217
const REFUSAL_MESSAGES: Record<CheckpointRestoreRefusal, string> = {
2318
"shared-workspace": SHARED_WORKSPACE_RESTORE_MESSAGE,
24-
"legacy-checkpoint": LEGACY_CHECKPOINT_RESTORE_MESSAGE,
2519
"other-workspace": OTHER_WORKSPACE_RESTORE_MESSAGE,
2620
};
2721

@@ -32,20 +26,15 @@ export const checkpointRestoreRefusalMessage = (refusal: CheckpointRestoreRefusa
3226
export const checkpointRestoreRefusal = Effect.fn("orchestrationV2.checkpointRestoreRefusal")(
3327
function* (
3428
thread: Pick<OrchestrationV2AppThread, "id" | "worktreePath">,
35-
scope: Pick<OrchestrationV2CheckpointScope, "id" | "cwd">,
29+
scope: Pick<OrchestrationV2CheckpointScope, "cwd">,
3630
dependencies: {
3731
readonly fileSystem: FileSystem.FileSystem;
38-
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
3932
readonly projections: ProjectionStoreV2["Service"];
4033
readonly projects: ProjectStore.ProjectStoreV2["Service"];
4134
readonly path: Path.Path;
4235
},
4336
) {
44-
const { fileSystem, idAllocator, projections, projects, path } = dependencies;
45-
// The legacy scope's projected cwd is only its latest; older checkpoints may hold another workspace.
46-
if (scope.id === (yield* legacyRootScopeId(idAllocator, thread.id))) {
47-
return "legacy-checkpoint" as const;
48-
}
37+
const { fileSystem, projections, projects, path } = dependencies;
4938
const contains = (parent: string, child: string) => {
5039
const relative = path.relative(parent, child);
5140
return (
@@ -87,10 +76,26 @@ export const checkpointRestoreRefusal = Effect.fn("orchestrationV2.checkpointRes
8776
if (turnItems.length === 0) continue;
8877
}
8978
const other = yield* projections.getCheckpointContext(otherThread.id);
79+
// A thread keeps a root scope per workspace it used; only its newest is where it works now.
80+
const runOrdinals = new Map(other.runs.map((run) => [run.id, run.ordinal]));
81+
const scopeRunOrdinal = (candidate: (typeof other.checkpointScopes)[number]) =>
82+
(candidate.runId === null ? undefined : runOrdinals.get(candidate.runId)) ?? 0;
83+
const latestRootRunOrdinal = Math.max(
84+
-1,
85+
...other.checkpointScopes
86+
.filter((candidate) => candidate.kind === "root_run")
87+
.map(scopeRunOrdinal),
88+
);
9089
const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
9190
const paths = [
9291
otherThread.worktreePath,
93-
...other.checkpointScopes.map((candidate) => candidate.cwd),
92+
...other.checkpointScopes
93+
.filter(
94+
(candidate) =>
95+
candidate.kind !== "root_run" ||
96+
scopeRunOrdinal(candidate) === latestRootRunOrdinal,
97+
)
98+
.map((candidate) => candidate.cwd),
9499
// Errored sessions can still stream. Shared sessions retain another thread's opening cwd;
95100
// turn worktrees and project roots are already covered here.
96101
...providerContext.providerSessions

‎apps/server/src/orchestration-v2/CheckpointRollbackService.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
4848
"provider-turn-unavailable",
4949
"unexpected-failure",
5050
"shared-workspace",
51-
"legacy-checkpoint",
5251
"other-workspace",
5352
]),
5453
threadId: ThreadId,
@@ -66,7 +65,6 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
6665
case "provider-turn-unavailable":
6766
return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
6867
case "shared-workspace":
69-
case "legacy-checkpoint":
7068
case "other-workspace":
7169
return checkpointRestoreRefusalMessage(this.reason);
7270
case "unexpected-failure":
@@ -243,7 +241,6 @@ export const layer: Layer.Layer<
243241
? null
244242
: yield* checkpointRestoreRefusal(context.thread, scope, {
245243
fileSystem,
246-
idAllocator: ids,
247244
projections,
248245
projects,
249246
path,

‎apps/server/src/orchestration-v2/CheckpointService.test.ts‎

Lines changed: 32 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -162,16 +162,12 @@ const layerGitCheckpoints = CheckpointService.layer.pipe(
162162
);
163163

164164
// Turn 1 runs in worktree A, then the thread moves to worktree B (a branch with its own
165-
// committed file) of the same repository, and turn 2 adds one file there. A legacy thread
166-
// kept its one root scope across both, as threads did before root scopes were per workspace.
167-
const runTurnsAcrossWorktrees = Effect.fn("runTurnsAcrossWorktrees")(function* (
168-
scopes: "per-workspace" | "legacy",
169-
) {
165+
// committed file) of the same repository, and turn 2 adds one file there.
166+
const runTurnsAcrossWorktrees = Effect.fn("runTurnsAcrossWorktrees")(function* () {
170167
const fileSystem = yield* FileSystem.FileSystem;
171168
const path = yield* Path.Path;
172169
const vcsProcess = yield* VcsProcess.VcsProcess;
173170
const checkpoints = yield* CheckpointService.CheckpointServiceV2;
174-
const idAllocator = yield* IdAllocator.IdAllocatorV2;
175171
const git = (cwd: string, ...args: ReadonlyArray<string>) =>
176172
vcsProcess.run({ operation: "CheckpointService.test.git", command: "git", cwd, args });
177173
const root = yield* fileSystem.realPath(
@@ -201,18 +197,14 @@ const runTurnsAcrossWorktrees = Effect.fn("runTurnsAcrossWorktrees")(function* (
201197
const runTurn = Effect.fn("runTurn")(function* (ordinal: number, cwd: string, file: string) {
202198
const runId = RunId.make(`run:worktree-move:${ordinal}`);
203199
const nodeId = NodeId.make(`node:worktree-move:${ordinal}`);
204-
const prepared = yield* checkpoints.prepareRootRunScope({
200+
const scope = yield* checkpoints.prepareRootRunScope({
205201
threadId,
206202
runId,
207203
rootNodeId: nodeId,
208204
providerThreadId,
209205
cwd,
210206
createdAt,
211207
});
212-
const scope =
213-
scopes === "legacy"
214-
? { ...prepared, id: yield* CheckpointService.legacyRootScopeId(idAllocator, threadId) }
215-
: prepared;
216208
projectedScopes.set(scope.id, scope);
217209
yield* checkpoints.captureBaseline({ scope, ordinalWithinScope: ordinal - 1 });
218210
yield* fileSystem.writeFileString(path.join(cwd, file), `${file}\n`);
@@ -233,7 +225,7 @@ const runTurnsAcrossWorktrees = Effect.fn("runTurnsAcrossWorktrees")(function* (
233225

234226
it.live("lists only turn 2's edit after the thread moves to another worktree of the repo", () =>
235227
Effect.gen(function* () {
236-
const { turn2 } = yield* runTurnsAcrossWorktrees("per-workspace");
228+
const { turn2 } = yield* runTurnsAcrossWorktrees();
237229

238230
assert.deepEqual(
239231
turn2.files.map((file) => file.path),
@@ -247,7 +239,7 @@ it.live("a worktree recreated after a rollback lists only its next turn's edit",
247239
Effect.gen(function* () {
248240
const checkpoints = yield* CheckpointService.CheckpointServiceV2;
249241
const { git, repo, worktreeA, worktreeB, turn2, projectedScopes, runTurn } =
250-
yield* runTurnsAcrossWorktrees("per-workspace");
242+
yield* runTurnsAcrossWorktrees();
251243

252244
// Back in worktree A with B removed, a rollback to the thread start discards turn 2.
253245
yield* git(repo, "worktree", "remove", "--force", worktreeB);
@@ -266,37 +258,33 @@ it.live("a worktree recreated after a rollback lists only its next turn's edit",
266258
}).pipe(Effect.provide(layerGitCheckpoints)),
267259
);
268260

269-
it.live.each(["per-workspace", "legacy"] as const)(
270-
"does not restore a checkpoint taken in another worktree into the thread's worktree, %s scopes",
271-
(scopes) =>
272-
Effect.gen(function* () {
273-
const fileSystem = yield* FileSystem.FileSystem;
274-
const path = yield* Path.Path;
275-
const checkpoints = yield* CheckpointService.CheckpointServiceV2;
276-
const { threadId, worktreeB, turn1, projectedScopes } =
277-
yield* runTurnsAcrossWorktrees(scopes);
278-
const scope = projectedScopes.get(turn1.scopeId)!;
261+
it.live("does not restore a checkpoint taken in another worktree into the thread's worktree", () =>
262+
Effect.gen(function* () {
263+
const fileSystem = yield* FileSystem.FileSystem;
264+
const path = yield* Path.Path;
265+
const checkpoints = yield* CheckpointService.CheckpointServiceV2;
266+
const { threadId, worktreeB, turn1, projectedScopes } = yield* runTurnsAcrossWorktrees();
267+
const scope = projectedScopes.get(turn1.scopeId)!;
279268

280-
// "Edit from here?" on turn 1 with "Revert files too", as CheckpointRollbackService runs it.
281-
const refusal = yield* checkpointRestoreRefusal(
282-
{ id: threadId, worktreePath: worktreeB },
283-
scope,
284-
{
285-
fileSystem,
286-
path,
287-
idAllocator: yield* IdAllocator.IdAllocatorV2,
288-
projections: {
289-
getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
290-
} as never,
291-
projects: {} as never,
292-
},
293-
);
294-
if (refusal === null) yield* checkpoints.restore({ scope, checkpoint: turn1 });
269+
// "Edit from here?" on turn 1 with "Revert files too", as CheckpointRollbackService runs it.
270+
const refusal = yield* checkpointRestoreRefusal(
271+
{ id: threadId, worktreePath: worktreeB },
272+
scope,
273+
{
274+
fileSystem,
275+
path,
276+
projections: {
277+
getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
278+
} as never,
279+
projects: {} as never,
280+
},
281+
);
282+
if (refusal === null) yield* checkpoints.restore({ scope, checkpoint: turn1 });
295283

296-
assert.deepEqual(
297-
(yield* fileSystem.readDirectory(worktreeB)).filter((entry) => entry !== ".git").toSorted(),
298-
["b-only.txt", "shared.txt", "turn-2.txt"],
299-
);
300-
assert.strictEqual(refusal, scopes === "legacy" ? "legacy-checkpoint" : "other-workspace");
301-
}).pipe(Effect.provide(layerGitCheckpoints)),
284+
assert.deepEqual(
285+
(yield* fileSystem.readDirectory(worktreeB)).filter((entry) => entry !== ".git").toSorted(),
286+
["b-only.txt", "shared.txt", "turn-2.txt"],
287+
);
288+
assert.strictEqual(refusal, "other-workspace");
289+
}).pipe(Effect.provide(layerGitCheckpoints)),
302290
);

‎apps/server/src/orchestration-v2/CheckpointService.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,12 +184,6 @@ export const rootScopeId = (
184184
) =>
185185
idAllocator.allocate.checkpointScope({ threadId, name: `${ROOT_CHECKPOINT_SCOPE_NAME}:${cwd}` });
186186

187-
/** Before root scopes were per workspace, every workspace a thread used shared this one scope. */
188-
export const legacyRootScopeId = (
189-
idAllocator: IdAllocator.IdAllocatorV2["Service"],
190-
threadId: ThreadId,
191-
) => idAllocator.allocate.checkpointScope({ threadId, name: ROOT_CHECKPOINT_SCOPE_NAME });
192-
193187
const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
194188
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
195189
readonly threadId: ThreadId;

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12550,7 +12550,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1255012550
}
1255112551
if (command.restoreFiles !== false) {
1255212552
const refusal = yield* checkpointRestoreRefusal(projection.thread, targetScope, {
12553-
idAllocator,
1255412553
projects,
1255512554
path,
1255612555
fileSystem,

0 commit comments

Comments
 (0)