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

CheckpointRollbackService.taskFolder.test.ts

755 lines26.9 KB

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