Skip to content

Commit 1ee1d04

Browse files
fix(server): reject v2 file restore in shared workspaces
1 parent 9cdae5f commit 1ee1d04

5 files changed

Lines changed: 260 additions & 8 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts";
2+
import * as Effect from "effect/Effect";
3+
import type * as FileSystem from "effect/FileSystem";
4+
import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
5+
6+
export 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.
11+
export 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+
);

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

Lines changed: 119 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
12
import { assert, it, vi } from "@effect/vitest";
23
import {
34
CheckpointId,
@@ -9,19 +10,27 @@ import {
910
ThreadId,
1011
} from "@t3tools/contracts";
1112
import * as Effect from "effect/Effect";
13+
import * as FileSystem from "effect/FileSystem";
14+
import * as Path from "effect/Path";
15+
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
1216
import * as Layer from "effect/Layer";
1317

18+
import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
1419
import { CheckpointServiceV2 } from "./CheckpointService.ts";
1520
import {
1621
CheckpointRollbackServiceV2,
17-
layer as checkpointRollbackServiceLayer,
22+
layer as checkpointRollbackLayer,
1823
} from "./CheckpointRollbackService.ts";
1924
import { EventSinkV2 } from "./EventSink.ts";
2025
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
2126
import { ProjectionStoreReadError, ProjectionStoreV2 } from "./ProjectionStore.ts";
2227
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
2328
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
2429

30+
const checkpointRollbackServiceLayer = checkpointRollbackLayer.pipe(
31+
Layer.provide(NodeServices.layer),
32+
);
33+
2534
it.effect("rejects a non-ready checkpoint before opening a session or restoring files", () => {
2635
const threadId = ThreadId.make("thread:rollback-non-ready");
2736
const providerThreadId = ProviderThreadId.make("provider-thread:rollback-non-ready");
@@ -34,12 +43,13 @@ it.effect("rejects a non-ready checkpoint before opening a session or restoring
3443
const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
3544
const projection = {
3645
thread: {
46+
worktreePath: process.cwd(),
3747
activeProviderThreadId: providerThreadId,
3848
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
3949
},
4050
providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
4151
checkpoints: [{ id: checkpointId, scopeId, status: "stale" }],
42-
checkpointScopes: [{ id: scopeId }],
52+
checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
4353
} as unknown as OrchestrationV2ThreadProjection;
4454
const testLayer = checkpointRollbackServiceLayer.pipe(
4555
Layer.provide(
@@ -49,6 +59,13 @@ it.effect("rejects a non-ready checkpoint before opening a session or restoring
4959
idAllocatorLayer,
5060
Layer.mock(ProjectionStoreV2)({
5161
getThreadProjection: () => Effect.succeed(projection),
62+
getShellSnapshot: () =>
63+
Effect.succeed({
64+
schemaVersion: 1,
65+
snapshotSequence: 0,
66+
threads: [],
67+
archivedThreads: [],
68+
}),
5269
}),
5370
Layer.mock(ProviderSessionManagerV2)({ open }),
5471
Layer.mock(RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
@@ -109,7 +126,7 @@ it.effect("rejects a rollback when another provider thread became active", () =>
109126
},
110127
],
111128
checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
112-
checkpointScopes: [{ id: scopeId }],
129+
checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
113130
} as unknown as OrchestrationV2ThreadProjection;
114131
const testLayer = checkpointRollbackServiceLayer.pipe(
115132
Layer.provide(
@@ -119,6 +136,13 @@ it.effect("rejects a rollback when another provider thread became active", () =>
119136
idAllocatorLayer,
120137
Layer.mock(ProjectionStoreV2)({
121138
getThreadProjection: () => Effect.succeed(projection),
139+
getShellSnapshot: () =>
140+
Effect.succeed({
141+
schemaVersion: 1,
142+
snapshotSequence: 0,
143+
threads: [],
144+
archivedThreads: [],
145+
}),
122146
}),
123147
Layer.mock(ProviderSessionManagerV2)({ open }),
124148
Layer.mock(RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
@@ -170,6 +194,7 @@ it.effect("rejects a rollback when provider selection changed before execution",
170194
const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
171195
const projection = {
172196
thread: {
197+
worktreePath: process.cwd(),
173198
activeProviderThreadId: providerThreadId,
174199
modelSelection: { instanceId: selectedProviderInstanceId, model: "test-model" },
175200
},
@@ -181,7 +206,7 @@ it.effect("rejects a rollback when provider selection changed before execution",
181206
},
182207
],
183208
checkpoints: [{ id: checkpointId, scopeId, status: "ready" }],
184-
checkpointScopes: [{ id: scopeId }],
209+
checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
185210
} as unknown as OrchestrationV2ThreadProjection;
186211
const testLayer = checkpointRollbackServiceLayer.pipe(
187212
Layer.provide(
@@ -191,6 +216,13 @@ it.effect("rejects a rollback when provider selection changed before execution",
191216
idAllocatorLayer,
192217
Layer.mock(ProjectionStoreV2)({
193218
getThreadProjection: () => Effect.succeed(projection),
219+
getShellSnapshot: () =>
220+
Effect.succeed({
221+
schemaVersion: 1,
222+
snapshotSequence: 0,
223+
threads: [],
224+
archivedThreads: [],
225+
}),
194226
}),
195227
Layer.mock(ProviderSessionManagerV2)({ open }),
196228
Layer.mock(RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
@@ -235,13 +267,14 @@ it.effect("reports a missing provider turn as a structured rollback failure", ()
235267
const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
236268
const projection = {
237269
thread: {
270+
worktreePath: process.cwd(),
238271
activeProviderThreadId: providerThreadId,
239272
modelSelection: { instanceId: providerInstanceId, model: "test-model" },
240273
},
241274
providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }],
242275
providerSessions: [],
243276
checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 }],
244-
checkpointScopes: [{ id: scopeId }],
277+
checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
245278
runs: [],
246279
attempts: [],
247280
providerTurns: [],
@@ -254,6 +287,13 @@ it.effect("reports a missing provider turn as a structured rollback failure", ()
254287
idAllocatorLayer,
255288
Layer.mock(ProjectionStoreV2)({
256289
getThreadProjection: () => Effect.succeed(projection),
290+
getShellSnapshot: () =>
291+
Effect.succeed({
292+
schemaVersion: 1,
293+
snapshotSequence: 0,
294+
threads: [],
295+
archivedThreads: [],
296+
}),
257297
}),
258298
Layer.mock(ProviderSessionManagerV2)({
259299
open: () => Effect.succeed({} as never),
@@ -330,7 +370,14 @@ it.effect("wraps underlying failures with an unexpected-failure reason and cause
330370
}).pipe(Effect.provide(testLayer));
331371
});
332372

333-
it.effect.each([true, false])("rewinds provider history with restoreFiles=%s", (restoreFiles) => {
373+
it.effect.each([
374+
{ restoreFiles: true, shared: "none" },
375+
{ restoreFiles: false, shared: "root" },
376+
{ restoreFiles: true, shared: "root" },
377+
{ restoreFiles: true, shared: "worktree" },
378+
{ restoreFiles: false, shared: "worktree" },
379+
{ restoreFiles: true, shared: "historical" },
380+
])("rewinds safely with %s", ({ restoreFiles, shared }) => {
334381
const threadId = ThreadId.make("rewind-files");
335382
const providerThreadId = ProviderThreadId.make("rewind-provider");
336383
const providerSessionId = ProviderSessionId.make("rewind-session");
@@ -345,6 +392,7 @@ it.effect.each([true, false])("rewinds provider history with restoreFiles=%s", (
345392
};
346393
const projection = {
347394
thread: {
395+
worktreePath: shared === "root" ? null : process.cwd(),
348396
activeProviderThreadId: providerThreadId,
349397
modelSelection: { instanceId, model: "test" },
350398
},
@@ -353,7 +401,7 @@ it.effect.each([true, false])("rewinds provider history with restoreFiles=%s", (
353401
providerTurns: [],
354402
nodes: [],
355403
checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: null }],
356-
checkpointScopes: [{ id: scopeId }],
404+
checkpointScopes: [{ id: scopeId, cwd: process.cwd() }],
357405
runs: [{ id: "run-1", ordinal: 1, status: "completed", rootNodeId: null }],
358406
} as unknown as OrchestrationV2ThreadProjection;
359407
const testLayer = checkpointRollbackServiceLayer.pipe(
@@ -378,7 +426,31 @@ it.effect.each([true, false])("rewinds provider history with restoreFiles=%s", (
378426
}),
379427
}),
380428
idAllocatorLayer,
381-
Layer.mock(ProjectionStoreV2)({ getThreadProjection: () => Effect.succeed(projection) }),
429+
Layer.mock(ProjectionStoreV2)({
430+
getThreadProjection: () => Effect.succeed(projection),
431+
getCheckpointContext: () =>
432+
Effect.succeed({
433+
checkpointScopes: [{ cwd: process.cwd() }],
434+
runs: [],
435+
checkpoints: [],
436+
} as never),
437+
getShellSnapshot: () =>
438+
Effect.succeed({
439+
schemaVersion: 1,
440+
snapshotSequence: 0,
441+
threads: [],
442+
archivedThreads:
443+
shared === "worktree" || shared === "historical"
444+
? [
445+
{
446+
id: ThreadId.make("other-thread"),
447+
deletedAt: null,
448+
worktreePath: shared === "worktree" ? process.cwd() : null,
449+
} as never,
450+
]
451+
: [],
452+
}),
453+
}),
382454
Layer.mock(ProviderSessionManagerV2)({
383455
open: () =>
384456
Effect.succeed({
@@ -395,10 +467,49 @@ it.effect.each([true, false])("rewinds provider history with restoreFiles=%s", (
395467
);
396468
return Effect.gen(function* () {
397469
const service = yield* CheckpointRollbackServiceV2;
470+
if (restoreFiles && shared !== "none") {
471+
const error = yield* Effect.flip(
472+
service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }),
473+
);
474+
assert.equal(error.reason, "shared-workspace");
475+
assert.deepEqual(calls, []);
476+
return;
477+
}
398478
yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles });
399479
assert.deepEqual(
400480
calls,
401481
restoreFiles ? ["provider", "files", "projection"] : ["provider", "projection"],
402482
);
403483
}).pipe(Effect.provide(testLayer));
404484
});
485+
486+
it.effect.skipIf(!symlinksSupported)(
487+
"rejects an archived thread sharing a worktree through a symlink",
488+
() =>
489+
Effect.gen(function* () {
490+
const fileSystem = yield* FileSystem.FileSystem;
491+
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-isolation-" });
492+
const path = yield* Path.Path;
493+
const alias = path.join(cwd, "alias");
494+
yield* fileSystem.symlink(cwd, alias);
495+
const threadId = ThreadId.make("restore-alias-current");
496+
const otherId = ThreadId.make("restore-alias-archived");
497+
const projections = ProjectionStoreV2.of({
498+
getShellSnapshot: () =>
499+
Effect.succeed({
500+
schemaVersion: 1,
501+
snapshotSequence: 0,
502+
threads: [],
503+
archivedThreads: [{ id: otherId, deletedAt: null, worktreePath: alias } as never],
504+
}),
505+
getCheckpointContext: () =>
506+
Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
507+
} as never);
508+
const isolated = yield* isCheckpointRestoreIsolated(
509+
{ id: threadId, worktreePath: cwd },
510+
{ cwd },
511+
{ fileSystem, projections },
512+
);
513+
assert.isFalse(isolated);
514+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
515+
);

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ import {
88
import * as Context from "effect/Context";
99
import * as DateTime from "effect/DateTime";
1010
import * as Effect from "effect/Effect";
11+
import * as FileSystem from "effect/FileSystem";
1112
import * as Layer from "effect/Layer";
1213
import * as Schema from "effect/Schema";
1314

15+
import {
16+
isCheckpointRestoreIsolated,
17+
SHARED_WORKSPACE_RESTORE_MESSAGE,
18+
} from "./CheckpointRestoreSafety.ts";
1419
import { CheckpointServiceV2 } from "./CheckpointService.ts";
1520
import { EventSinkV2 } from "./EventSink.ts";
1621
import { IdAllocatorV2 } from "./IdAllocator.ts";
@@ -27,6 +32,7 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
2732
"active-provider-changed",
2833
"provider-turn-unavailable",
2934
"unexpected-failure",
35+
"shared-workspace",
3036
]),
3137
threadId: ThreadId,
3238
providerThreadId: ProviderThreadId,
@@ -42,6 +48,8 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
4248
return `Active provider changed before rollback target ${this.checkpointId} could execute on thread ${this.threadId}.`;
4349
case "provider-turn-unavailable":
4450
return `Provider turn for rollback target ${this.checkpointId} is unavailable on provider thread ${this.providerThreadId}.`;
51+
case "shared-workspace":
52+
return SHARED_WORKSPACE_RESTORE_MESSAGE;
4553
case "unexpected-failure":
4654
return `Failed to execute rollback target ${this.checkpointId} on provider thread ${this.providerThreadId} for thread ${this.threadId}.`;
4755
}
@@ -74,6 +82,7 @@ export const layer: Layer.Layer<
7482
| ProjectionStoreV2
7583
| ProviderSessionManagerV2
7684
| RuntimePolicyV2
85+
| FileSystem.FileSystem
7786
> = Layer.effect(
7887
CheckpointRollbackServiceV2,
7988
Effect.gen(function* () {
@@ -83,6 +92,7 @@ export const layer: Layer.Layer<
8392
const projections = yield* ProjectionStoreV2;
8493
const sessions = yield* ProviderSessionManagerV2;
8594
const runtimePolicy = yield* RuntimePolicyV2;
95+
const fileSystem = yield* FileSystem.FileSystem;
8696

8797
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
8898
readonly threadId: ThreadId;
@@ -126,6 +136,18 @@ export const layer: Layer.Layer<
126136
});
127137
}
128138

139+
if (
140+
input.restoreFiles !== false &&
141+
!(yield* isCheckpointRestoreIsolated(projection.thread, scope, { fileSystem, projections }))
142+
) {
143+
return yield* new CheckpointRollbackExecutionError({
144+
reason: "shared-workspace",
145+
threadId: input.threadId,
146+
providerThreadId: input.providerThreadId,
147+
checkpointId: input.checkpointId,
148+
});
149+
}
150+
129151
const modelSelection = projection.thread.modelSelection;
130152
const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
131153
thread: projection.thread,

0 commit comments

Comments
 (0)