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

CheckpointRollbackService.taskFolder.test.ts

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