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

CheckpointRollbackService.taskFolder.test.ts

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