Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import {
5 CommandId,
6 EventId,
7 MessageId,
8 NodeId,
9 type OrchestrationV2DomainEvent,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunAttemptId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as TestClock from "effect/testing/TestClock";
25
26import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
27import * as ServerConfig from "../config.ts";
28import * as GitWorkflow from "../git/GitWorkflowService.ts";
29import * as SqlitePersistence from "../persistence/Sqlite.ts";
30import * as ServerSettings from "../serverSettings.ts";
31import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
32import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
33import * as VcsProcess from "../vcs/VcsProcess.ts";
34import * as TaskFolders from "../workspace/TaskFolders.ts";
35import {
36 layerTaskFoldersWithGit,
37 taskFoldersTestProjectId as projectId,
38 type TaskFoldersTestState,
39} from "../workspace/TaskFolders.testkit.ts";
40import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts";
41import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
42import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
43import * as CheckpointService from "./CheckpointService.ts";
44import * as EventSink from "./EventSink.ts";
45import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
46import * as ProjectionStore from "./ProjectionStore.ts";
47import * as ProjectStore from "./ProjectStore.ts";
48import * as ProviderSessionManager from "./ProviderSessionManager.ts";
49import * as RuntimePolicy from "./RuntimePolicy.ts";
50import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
51
52const threadId = ThreadId.make("thread:task-folder-rewind");
53const providerThreadId = ProviderThreadId.make("provider-thread:task-folder-rewind");
54const providerInstanceId = ProviderInstanceId.make("codex");
55const driver = ProviderDriverKind.make("codex");
56const modelSelection = { instanceId: providerInstanceId, model: "test" };
57const branch = "feature/rewind";
58
59interface Options {
60 /** The project folder is a repository, so the task folder checks it out; otherwise it is linked. */
61 readonly projectIsRepository: boolean;
62 /** The worktrees directory is reached through a symlink. */
63 readonly symlinkedWorktrees?: boolean;
64}
65
66/** What the test supplies before the layer is built; the last commit's events land in `committed`. */
67interface State extends TaskFoldersTestState {
68 readonly committed: Array<OrchestrationV2DomainEvent>;
69}
70
71const layerFor = (state: State, options: Options) => {
72 const layerNode = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer);
73 const layerConfig = Layer.effect(
74 ServerConfig.ServerConfig,
75 Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const config = yield* ServerConfig.ServerConfig;
79 const base = yield* fileSystem.realPath(
80 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rewind-worktrees-" }),
81 );
82 const real = path.join(base, "real");
83 yield* fileSystem.makeDirectory(real);
84 if (options.symlinkedWorktrees !== true) return { ...config, worktreesDir: real };
85 yield* fileSystem.symlink(real, path.join(base, "linked"));
86 return { ...config, worktreesDir: path.join(base, "linked") };
87 }),
88 ).pipe(
89 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-rewind-" })),
90 Layer.provide(layerNode),
91 );
92 const layerGit = GitVcsDriver.layer.pipe(
93 Layer.provideMerge(layerConfig),
94 Layer.provideMerge(layerNode),
95 );
96 const layerTaskFolders = layerTaskFoldersWithGit(state).pipe(Layer.provide(layerGit));
97 const layerProjections = ProjectionStore.layer.pipe(
98 Layer.provide(NodeCrypto.layer),
99 Layer.provideMerge(SqlitePersistence.layerMemory),
100 );
101 const layerProjects = Layer.mock(ProjectStore.ProjectStoreV2)({
102 get: () => Effect.succeedNone,
103 });
104 const layerCheckpointStore = CheckpointStore.layer.pipe(
105 Layer.provide(
106 VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer.pipe(Layer.provide(layerNode)))),
107 ),
108 Layer.provide(layerNode),
109 );
110 const layerCheckpoints = CheckpointService.layer.pipe(
111 Layer.provide(
112 Layer.mergeAll(
113 IdAllocator.layer,
114 layerNode,
115 layerCheckpointStore,
116 WorkspaceFolders.layer.pipe(
117 Layer.provide(Layer.mergeAll(layerProjects, layerTaskFolders, layerGit)),
118 ),
119 ),
120 ),
121 );
122 const { committed } = state;
123 const layerEventSink = Layer.effect(
124 EventSink.EventSinkV2,
125 Effect.gen(function* () {
126 const store = yield* ProjectionStore.ProjectionStoreV2;
127 const record = (events: ReadonlyArray<OrchestrationV2DomainEvent>) =>
128 Effect.forEach(events, (event) => store.apply(event), { discard: true }).pipe(
129 Effect.andThen(Effect.sync(() => committed.splice(0, committed.length, ...events))),
130 Effect.orDie,
131 );
132 type Written = { readonly events: ReadonlyArray<OrchestrationV2DomainEvent> };
133 return {
134 commitCommand: (input: Written) =>
135 record(input.events).pipe(Effect.as({ committed: true })),
136 write: (input: Written) => record(input.events).pipe(Effect.as([])),
137 } as never;
138 }),
139 ).pipe(Layer.provide(layerProjections));
140 const layerWorkflow = Layer.unwrap(
141 Effect.gen(function* () {
142 const git = yield* GitVcsDriver.GitVcsDriver;
143 return Layer.mock(GitWorkflow.GitWorkflowService)({
144 createWorktree: git.createWorktree,
145 pruneWorktrees: git.pruneWorktrees,
146 });
147 }),
148 ).pipe(Layer.provide(layerGit));
149 return Layer.mergeAll(
150 layerGit,
151 layerTaskFolders,
152 layerProjections,
153 layerCheckpoints,
154 IdAllocator.layer,
155 CheckpointCaptureService.layer.pipe(
156 Layer.provide(
157 Layer.mergeAll(
158 layerCheckpoints,
159 layerEventSink,
160 IdAllocator.layer,
161 layerProjections,
162 ThreadCommandExecutor.layer,
163 ),
164 ),
165 ),
166 CheckpointRollbackService.layer.pipe(
167 Layer.provide(
168 Layer.mergeAll(
169 layerCheckpoints,
170 layerEventSink,
171 layerWorkflow,
172 IdAllocator.layer,
173 layerProjections,
174 layerProjects,
175 layerTaskFolders,
176 layerConfig,
177 layerNode,
178 ServerSettings.layerTest(),
179 ThreadCommandExecutor.layer,
180 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
181 checkCompatible: () => Effect.void,
182 open: () =>
183 Effect.succeed({
184 rollbackThread: (input: { readonly providerThread: unknown }) =>
185 Effect.succeed({ providerThread: input.providerThread }),
186 } as never),
187 }),
188 Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
189 ),
190 ),
191 ),
192 );
193};
194
195/**
196 * A worktree thread of a project tracking the `api` and `web` repositories, on real Git. `api`
197 * sits inside the project folder and `web` beside it.
198 */
199const taskFolderThread = Effect.fn(function* (state: State, options: Options) {
200 const fileSystem = yield* FileSystem.FileSystem;
201 const path = yield* Path.Path;
202 const git = yield* GitVcsDriver.GitVcsDriver;
203 const store = yield* ProjectionStore.ProjectionStoreV2;
204 const taskFolders = yield* TaskFolders.TaskFolders;
205 const checkpoints = yield* CheckpointService.CheckpointServiceV2;
206 const capture = yield* CheckpointCaptureService.CheckpointCaptureServiceV2;
207 const rollbacks = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
208 const ids = yield* IdAllocator.IdAllocatorV2;
209 const { committed } = state;
210 const now = yield* DateTime.now;
211 const tmp = yield* fileSystem.realPath(
212 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rewind-" }),
213 );
214 const run = (cwd: string, ...args: ReadonlyArray<string>) =>
215 git.execute({ operation: "rewind-test", cwd, args }).pipe(
216 Effect.map((result) => result.stdout.trim()),
217 Effect.orDie,
218 );
219 const write = (file: string, contents: string) =>
220 fileSystem
221 .makeDirectory(path.dirname(file), { recursive: true })
222 .pipe(Effect.andThen(fileSystem.writeFileString(file, contents)), Effect.orDie);
223 const read = (file: string) =>
224 fileSystem.readFileString(file).pipe(Effect.orElseSucceed(() => null));
225 const repository = Effect.fnUntraced(function* (folder: string) {
226 yield* write(path.join(folder, "README.md"), "start\n");
227 yield* run(folder, "init", "-b", "main");
228 yield* run(folder, "config", "user.email", "rewind@example.test");
229 yield* run(folder, "config", "user.name", "Rewind");
230 yield* run(folder, "add", ".");
231 yield* run(folder, "commit", "-m", "initial");
232 });
233 const shop = path.join(tmp, "shop");
234 yield* write(path.join(shop, "AGENTS.md"), "rules\n");
235 if (options.projectIsRepository) yield* repository(shop);
236 yield* repository(path.join(shop, "api"));
237 yield* repository(path.join(tmp, "web"));
238 state.workspaceRoot = shop;
239 state.trackedFolders = [
240 { path: path.join(shop, "api"), name: "api" },
241 { path: path.join(tmp, "web"), name: "web" },
242 ];
243 const plan = yield* taskFolders.plan({ projectId });
244 // On the live clock a new worktree swaps in a refreshed index a second later, briefly holding
245 // index.lock; a rewind landing then fails. The test clock keeps that refresh in the foreground.
246 const { taskFolder } = yield* taskFolders
247 .create({
248 plan: plan!,
249 branch,
250 projectStart: { refName: "main", baseRefName: "main" },
251 startFromOrigin: false,
252 projectCommands: "permitted",
253 })
254 .pipe(Effect.provide(TestClock.layer()));
255 const worktreePath = taskFolder.projectPath;
256 const folders = {
257 shop: worktreePath,
258 api: path.join(worktreePath, "api"),
259 web: path.join(taskFolder.root, "web"),
260 };
261
262 const rootScope = yield* checkpoints.prepareRootRunScope({
263 threadId,
264 runId: RunId.make("run:rewind:1"),
265 rootNodeId: NodeId.make("node:rewind:1"),
266 providerThreadId,
267 cwd: worktreePath,
268 createdAt: now,
269 });
270 let sequence = 0;
271 type EventInput<Event = OrchestrationV2DomainEvent> = Event extends OrchestrationV2DomainEvent
272 ? Omit<Event, "id" | "occurredAt" | "threadId">
273 : never;
274 const apply = (event: EventInput) =>
275 store
276 .apply({
277 ...event,
278 id: EventId.make(`event:rewind:${sequence++}`),
279 threadId,
280 occurredAt: now,
281 } as OrchestrationV2DomainEvent)
282 .pipe(Effect.orDie);
283 yield* apply({
284 type: "thread.created",
285 payload: {
286 id: threadId,
287 createdBy: "user",
288 creationSource: "web",
289 projectId,
290 title: "Rewind",
291 providerInstanceId,
292 modelSelection,
293 runtimeMode: "full-access",
294 interactionMode: "default",
295 branch,
296 worktreePath,
297 activeProviderThreadId: providerThreadId,
298 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
299 forkedFrom: null,
300 createdAt: now,
301 updatedAt: now,
302 archivedAt: null,
303 settledOverride: null,
304 settledAt: null,
305 lastVisitedAt: null,
306 deletedAt: null,
307 },
308 });
309 yield* apply({
310 type: "provider-thread.updated",
311 payload: {
312 id: providerThreadId,
313 driver,
314 providerInstanceId,
315 providerSessionId: ProviderSessionId.make("provider-session:rewind"),
316 appThreadId: threadId,
317 ownerNodeId: null,
318 nativeThreadRef: null,
319 nativeConversationHeadRef: null,
320 status: "idle",
321 firstRunOrdinal: 1,
322 lastRunOrdinal: 1,
323 handoffIds: [],
324 forkedFrom: null,
325 createdAt: now,
326 updatedAt: now,
327 },
328 });
329 yield* apply({ type: "checkpoint-scope.created", payload: rootScope });
330
331 /** One turn: baseline, the turn's edits, then the capture. Returns the files each folder recorded. */
332 const turn = Effect.fnUntraced(function* (ordinal: number, edits: Effect.Effect<void>) {
333 const key = String(ordinal);
334 const runId = RunId.make(`run:rewind:${key}`);
335 const nodeId = NodeId.make(`node:rewind:${key}`);
336 const attemptId = RunAttemptId.make(`attempt:rewind:${key}`);
337 const turnId = ProviderTurnId.make(`turn:rewind:${key}`);
338 yield* apply({
339 type: "run.created",
340 payload: {
341 id: runId,
342 threadId,
343 ordinal,
344 providerInstanceId,
345 modelSelection,
346 providerThreadId,
347 userMessageId: MessageId.make(`message:rewind:${key}`),
348 rootNodeId: nodeId,
349 activeAttemptId: attemptId,
350 status: "waiting",
351 requestedAt: now,
352 startedAt: now,
353 completedAt: null,
354 checkpointId: null,
355 contextHandoffId: null,
356 },
357 });
358 yield* apply({
359 type: "node.updated",
360 payload: {
361 id: nodeId,
362 threadId,
363 runId,
364 parentNodeId: null,
365 rootNodeId: nodeId,
366 kind: "root_turn",
367 status: "waiting",
368 countsForRun: true,
369 providerThreadId,
370 providerTurnId: turnId,
371 nativeItemRef: null,
372 runtimeRequestId: null,
373 checkpointScopeId: rootScope.id,
374 startedAt: now,
375 completedAt: null,
376 },
377 });
378 yield* apply({
379 type: "run-attempt.created",
380 runId,
381 payload: {
382 id: attemptId,
383 runId,
384 attemptOrdinal: 1,
385 rootNodeId: nodeId,
386 providerInstanceId,
387 providerThreadId,
388 providerTurnId: turnId,
389 reason: "initial",
390 status: "completed",
391 startedAt: now,
392 completedAt: now,
393 },
394 });
395 yield* apply({
396 type: "provider-turn.updated",
397 payload: {
398 id: turnId,
399 providerThreadId,
400 nodeId,
401 runAttemptId: attemptId,
402 nativeTurnRef: { driver, nativeId: `native-turn:${key}`, strength: "strong" },
403 ordinal,
404 status: "completed",
405 startedAt: now,
406 completedAt: now,
407 },
408 });
409 yield* checkpoints
410 .captureBaseline({
411 scope: rootScope,
412 ordinalWithinScope: ordinal - 1,
413 thread: { projectId, worktreePath },
414 })
415 .pipe(Effect.orDie);
416 yield* edits;
417 yield* capture.execute({ threadId, runId, scopeId: rootScope.id }).pipe(Effect.orDie);
418 const scopes = yield* recordedScopes;
419 return Object.fromEntries(
420 committed.flatMap((event) =>
421 event.type === "checkpoint.captured" && event.payload.runId !== null
422 ? [
423 [
424 scopes.get(event.payload.scopeId) ?? "shop",
425 event.payload.files.map((file) => file.path),
426 ],
427 ]
428 : [],
429 ),
430 );
431 });
432 const records = store
433 .getThreadRecords(threadId, ["runs", "checkpoints", "checkpointScopes"])
434 .pipe(Effect.orDie);
435 const recordedScopes = records.pipe(
436 Effect.map(
437 ({ checkpointScopes }) =>
438 new Map(
439 checkpointScopes.flatMap((scope) =>
440 scope.label === undefined ? [] : [[scope.id, scope.label] as const],
441 ),
442 ),
443 ),
444 );
445 /** Rewinds to the end of run `ordinal`, restoring files. */
446 const rewind = Effect.fnUntraced(function* (ordinal: number, requestId?: CommandId) {
447 const checkpointId = yield* ids.allocate
448 .checkpoint({ checkpointScopeId: rootScope.id, name: String(ordinal) })
449 .pipe(Effect.orDie);
450 yield* rollbacks.execute({
451 threadId,
452 providerThreadId,
453 checkpointId,
454 scopeId: rootScope.id,
455 ...(requestId === undefined ? {} : { requestId }),
456 });
457 });
458 /** Run statuses by ordinal, and each folder's checkpoint statuses by ordinal. */
459 const recorded = Effect.gen(function* () {
460 const { runs, checkpoints: all } = yield* records;
461 const scopes = yield* recordedScopes;
462 const statuses: Record<string, Record<number, string>> = {};
463 for (const checkpoint of all) {
464 (statuses[scopes.get(checkpoint.scopeId) ?? "shop"] ??= {})[checkpoint.ordinalWithinScope] =
465 checkpoint.status;
466 }
467 return {
468 runs: runs.toSorted((left, right) => left.ordinal - right.ordinal).map((run) => run.status),
469 checkpoints: statuses,
470 };
471 });
472 return {
473 path,
474 fileSystem,
475 run,
476 write,
477 read,
478 folders,
479 taskFolder,
480 turn,
481 rewind,
482 recorded,
483 records,
484 apply,
485 };
486});
487
488const withThread = <A, E>(
489 options: Options,
490 test: (
491 thread: Effect.Success<ReturnType<typeof taskFolderThread>>,
492 ) => Effect.Effect<A, E, Layer.Success<ReturnType<typeof layerFor>>>,
493) => {
494 const state: State = { workspaceRoot: "/unset", trackedFolders: [], thread: null, committed: [] };
495 return taskFolderThread(state, options).pipe(
496 Effect.flatMap(test),
497 Effect.provide(layerFor(state, options)),
498 Effect.scoped,
499 );
500};
501
502it.live.each([{ symlinkedWorktrees: false }, { symlinkedWorktrees: true }])(
503 "rewinds the project folder and every repository a discarded turn changed, symlinked worktrees directory=$symlinkedWorktrees",
504 ({ symlinkedWorktrees }) =>
505 withThread({ projectIsRepository: true, symlinkedWorktrees }, (thread) =>
506 Effect.gen(function* () {
507 const { path, folders, write, read } = thread;
508 const file = (folder: keyof typeof folders, name = "a.txt") =>
509 path.join(folders[folder], name);
510 yield* thread.turn(
511 1,
512 Effect.all([write(file("shop"), "1"), write(file("api"), "1"), write(file("web"), "1")]),
513 );
514 yield* thread.turn(2, Effect.all([write(file("shop"), "2"), write(file("api"), "2")]));
515 yield* thread.turn(
516 3,
517 Effect.all([
518 write(file("shop", "new.txt"), "3"),
519 write(file("api", "new.txt"), "3"),
520 write(file("web"), "3"),
521 ]),
522 );
523
524 yield* thread.rewind(1);
525
526 assert.deepEqual(
527 yield* Effect.all([
528 read(file("shop")),
529 read(file("shop", "new.txt")),
530 read(file("api")),
531 read(file("api", "new.txt")),
532 read(file("web")),
533 ]),
534 ["1", null, "1", null, "1"],
535 );
536 // The project folder's restore left the worktree inside it checked out.
537 assert.equal(yield* thread.run(folders.api, "rev-parse", "--abbrev-ref", "HEAD"), branch);
538 const recorded = yield* thread.recorded;
539 assert.deepEqual(recorded.runs, ["completed", "rolled_back", "rolled_back"]);
540 assert.deepEqual(recorded.checkpoints, {
541 shop: { 0: "ready", 1: "ready", 2: "stale", 3: "stale" },
542 api: { 0: "ready", 1: "ready", 2: "stale", 3: "stale" },
543 web: { 0: "ready", 1: "ready", 2: "stale", 3: "stale" },
544 });
545
546 // The next turn starts from what the rewind restored, in every folder.
547 assert.deepEqual(yield* thread.turn(4, write(file("api"), "again")), {
548 shop: [],
549 api: ["a.txt"],
550 });
551 }),
552 ),
553);
554
555it.live("rewinds a linked project folder's repositories to how each was before the turn", () =>
556 withThread({ projectIsRepository: false }, (thread) =>
557 Effect.gen(function* () {
558 const { path, folders, write, read } = thread;
559 yield* thread.turn(1, write(path.join(folders.api, "a.txt"), "1"));
560 yield* thread.turn(2, write(path.join(folders.api, "a.txt"), "2"));
561 // The first turn to change web: it has no checkpoint at the turn the rewind goes back to.
562 yield* thread.turn(3, write(path.join(folders.web, "a.txt"), "3"));
563 assert.deepEqual((yield* thread.recorded).checkpoints, {
564 shop: { 0: "missing", 1: "missing", 2: "missing", 3: "missing" },
565 api: { 0: "ready", 1: "ready", 2: "ready" },
566 web: { 2: "ready", 3: "ready" },
567 });
568
569 yield* thread.rewind(1);
570
571 assert.deepEqual(
572 yield* Effect.all([
573 read(path.join(folders.api, "a.txt")),
574 read(path.join(folders.web, "a.txt")),
575 read(path.join(folders.web, "README.md")),
576 read(path.join(folders.shop, "AGENTS.md")),
577 ]),
578 ["1", null, "start\n", "rules\n"],
579 );
580 assert.deepEqual((yield* thread.recorded).runs, ["completed", "rolled_back", "rolled_back"]);
581 // A turn that changes only web lists web's file alone, against what the rewind left.
582 assert.deepEqual(yield* thread.turn(4, write(path.join(folders.web, "b.txt"), "again")), {
583 shop: [],
584 web: ["b.txt"],
585 });
586 }),
587 ),
588);
589
590it.live.each([
591 { label: "whose baseline is lost", runSnapshot: "ready" },
592 { label: "whose baseline is lost and whose run snapshot failed", runSnapshot: "error" },
593] as const)("names the repositories a rewind could not restore: one $label", ({ runSnapshot }) =>
594 withThread({ projectIsRepository: false }, (thread) =>
595 Effect.gen(function* () {
596 const { path, folders, write, read } = thread;
597 const store = yield* ProjectionStore.ProjectionStoreV2;
598 yield* thread.turn(1, write(path.join(folders.api, "a.txt"), "1"));
599 yield* thread.turn(2, write(path.join(folders.api, "a.txt"), "2"));
600 yield* thread.turn(3, write(path.join(folders.web, "a.txt"), "3"));
601 // web's only record of how it was before turn 3 is lost.
602 const { checkpoints, checkpointScopes } = yield* thread.records;
603 const web = checkpointScopes.find((scope) => scope.label === "web")!;
604 const baseline = checkpoints.find(
605 (checkpoint) => checkpoint.scopeId === web.id && checkpoint.runId === null,
606 )!;
607 yield* thread.apply({
608 type: "checkpoint.captured",
609 nodeId: baseline.nodeId,
610 payload: { ...baseline, status: "missing" },
611 });
612 const ran = checkpoints.find(
613 (checkpoint) => checkpoint.scopeId === web.id && checkpoint.runId !== null,
614 )!;
615 yield* thread.apply({
616 type: "checkpoint.captured",
617 nodeId: ran.nodeId,
618 payload: { ...ran, status: runSnapshot },
619 });
620 const requestId = CommandId.make("command:rewind:unrestored");
621
622 yield* thread.rewind(1, requestId);
623
624 assert.deepEqual(
625 yield* Effect.all([
626 read(path.join(folders.api, "a.txt")),
627 read(path.join(folders.web, "a.txt")),
628 ]),
629 ["1", "3"],
630 );
631 assert.deepEqual((yield* store.getThread(threadId)).rollbackUnrestored, {
632 requestId,
633 repositories: ["web"],
634 });
635 }),
636 ),
637);
638
639it.live("refuses to restore files when a linked project folder has no repository to restore", () =>
640 withThread({ projectIsRepository: false }, (thread) =>
641 Effect.gen(function* () {
642 yield* thread.turn(1, Effect.void);
643 yield* thread.turn(2, Effect.void);
644
645 const refused = yield* thread.rewind(1).pipe(Effect.flip);
646
647 assert.equal(refused.reason, "rollback-target-invalid");
648 assert.deepEqual((yield* thread.recorded).runs, ["completed", "completed"]);
649 }),
650 ),
651);
652
653it.live("refuses a project folder whose own snapshot is missing, before any folder changes", () =>
654 withThread({ projectIsRepository: true }, (thread) =>
655 Effect.gen(function* () {
656 const { path, folders, write, read } = thread;
657 yield* thread.turn(1, write(path.join(folders.api, "a.txt"), "1"));
658 yield* thread.turn(2, write(path.join(folders.api, "a.txt"), "2"));
659 const target = (yield* thread.records).checkpoints.find(
660 (checkpoint) => checkpoint.appRunOrdinal === 1,
661 )!;
662 const untouched = Effect.gen(function* () {
663 assert.equal(yield* read(path.join(folders.api, "a.txt")), "2");
664 assert.deepEqual((yield* thread.recorded).runs, ["completed", "completed"]);
665 });
666
667 // Recorded as present, but the snapshot itself is gone.
668 yield* thread.run(folders.shop, "update-ref", "-d", target.ref);
669 assert.equal((yield* thread.rewind(1).pipe(Effect.flip)).reason, "unexpected-failure");
670 yield* untouched;
671
672 yield* thread.apply({
673 type: "checkpoint.captured",
674 nodeId: target.nodeId,
675 payload: { ...target, status: "missing" },
676 });
677 assert.equal((yield* thread.rewind(1).pipe(Effect.flip)).reason, "rollback-target-invalid");
678 yield* untouched;
679 }),
680 ),
681);
682
683it.live("puts restored folders back when a later folder's restore fails", () =>
684 withThread({ projectIsRepository: true }, (thread) =>
685 Effect.gen(function* () {
686 const { path, folders, write, read, taskFolder } = thread;
687 const edit = (contents: string) =>
688 Effect.all([
689 write(path.join(folders.shop, "a.txt"), contents),
690 write(path.join(folders.api, "a.txt"), contents),
691 write(path.join(folders.web, "a.txt"), contents),
692 ]);
693 yield* thread.turn(1, edit("1"));
694 yield* thread.turn(2, edit("2"));
695 // Repositories restore in the order the task folder lists them: the last one's fails.
696 const last = taskFolder.repositories.at(-1)!.worktreePath;
697 const lock = path.resolve(
698 last,
699 yield* thread.run(last, "rev-parse", "--git-path", "index.lock"),
700 );
701 yield* write(lock, "");
702
703 const failed = yield* thread.rewind(1).pipe(Effect.flip);
704
705 assert.equal(failed.reason, "unexpected-failure");
706 assert.deepEqual(
707 yield* Effect.all([
708 read(path.join(folders.shop, "a.txt")),
709 read(path.join(folders.api, "a.txt")),
710 read(path.join(folders.web, "a.txt")),
711 ]),
712 ["2", "2", "2"],
713 );
714 const recorded = yield* thread.recorded;
715 assert.deepEqual(recorded.runs, ["completed", "completed"]);
716 assert.deepEqual(recorded.checkpoints.api, { 0: "ready", 1: "ready", 2: "ready" });
717 }),
718 ),
719);
720
721it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])(
722 "restores a task folder storage cleanup removed before rewinding it, project is a repository=$projectIsRepository",
723 (options) =>
724 withThread(options, (thread) =>
725 Effect.gen(function* () {
726 const { path, folders, write, read, taskFolder, fileSystem } = thread;
727 const taskFolders = yield* TaskFolders.TaskFolders;
728 const edit = (contents: string) =>
729 Effect.all([
730 write(path.join(folders.api, "a.txt"), contents),
731 write(path.join(folders.web, "a.txt"), contents),
732 ]);
733 yield* thread.turn(1, edit("1"));
734 yield* thread.turn(2, edit("2"));
735 const removal = yield* taskFolders.remove({
736 root: taskFolder.root,
737 force: true,
738 forget: false,
739 projectCommands: "permitted",
740 });
741 assert.deepEqual(removal.kept, []);
742 assert.isFalse(yield* fileSystem.exists(taskFolder.root));
743
744 yield* thread.rewind(1);
745
746 assert.deepEqual(
747 yield* Effect.all([
748 read(path.join(folders.shop, "AGENTS.md")),
749 read(path.join(folders.api, "a.txt")),
750 read(path.join(folders.web, "a.txt")),
751 ]),
752 ["rules\n", "1", "1"],
753 );
754 assert.equal(yield* thread.run(folders.web, "rev-parse", "--abbrev-ref", "HEAD"), branch);
755 }),
756 ),
757);