Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it } from "@effect/vitest";
6import { ThreadId, type VcsError } from "@t3tools/contracts";
7import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as PlatformError from "effect/PlatformError";
12import * as Scope from "effect/Scope";
13import { describe, expect } from "vite-plus/test";
14
15import { checkpointRefForThreadTurn } from "./Utils.ts";
16import { parseTurnDiffFilesFromNumstat } from "./Diffs.ts";
17import * as CheckpointStore from "./CheckpointStore.ts";
18import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
19import * as VcsProcess from "../vcs/VcsProcess.ts";
20import * as ServerConfig from "../config.ts";
21
22const ServerConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
23 prefix: "t3-checkpoint-store-test-",
24});
25const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
26const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
27const CheckpointStoreTestLayer = CheckpointStore.layer.pipe(
28 Layer.provideMerge(VcsDriverTestLayer),
29 Layer.provideMerge(NodeServices.layer),
30);
31const TestLayer = CheckpointStoreTestLayer.pipe(
32 Layer.provideMerge(VcsProcessTestLayer),
33 Layer.provideMerge(VcsDriverTestLayer),
34 Layer.provideMerge(ServerConfigLayer),
35 Layer.provideMerge(NodeServices.layer),
36);
37
38function makeTmpDir(
39 prefix = "checkpoint-store-test-",
40): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
41 return Effect.gen(function* () {
42 const fileSystem = yield* FileSystem.FileSystem;
43 return yield* fileSystem.makeTempDirectoryScoped({ prefix });
44 });
45}
46
47function writeTextFile(
48 filePath: string,
49 contents: string,
50): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
51 return Effect.gen(function* () {
52 const fileSystem = yield* FileSystem.FileSystem;
53 yield* fileSystem.writeFileString(filePath, contents);
54 });
55}
56
57function git(
58 cwd: string,
59 args: ReadonlyArray<string>,
60): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
61 return Effect.gen(function* () {
62 const process = yield* VcsProcess.VcsProcess;
63 const result = yield* process.run({
64 operation: "CheckpointStore.test.git",
65 command: "git",
66 cwd,
67 args,
68 timeoutMs: 10_000,
69 });
70 return result.stdout.trim();
71 });
72}
73
74function initRepoWithCommit(
75 cwd: string,
76): Effect.Effect<
77 void,
78 VcsError | PlatformError.PlatformError,
79 VcsProcess.VcsProcess | FileSystem.FileSystem
80> {
81 return Effect.gen(function* () {
82 yield* git(cwd, ["init"]);
83 yield* git(cwd, ["config", "user.email", "test@test.com"]);
84 yield* git(cwd, ["config", "user.name", "Test"]);
85 yield* writeTextFile(NodePath.join(cwd, "README.md"), "# test\n");
86 yield* git(cwd, ["add", "."]);
87 yield* git(cwd, ["commit", "-m", "initial commit"]);
88 });
89}
90
91function buildLargeText(lineCount = 5_000): string {
92 return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
93 .join("\n")
94 .concat("\n");
95}
96
97it.layer(TestLayer)("CheckpointStore.layer", (it) => {
98 describe("isGitRepository", () => {
99 it.effect("returns false when no Git repository is detected", () =>
100 Effect.gen(function* () {
101 const tmp = yield* makeTmpDir();
102 const checkpointStore = yield* CheckpointStore.CheckpointStore;
103
104 expect(yield* checkpointStore.isGitRepository(tmp)).toBe(false);
105 }),
106 );
107
108 it.effect("returns true when a Git repository is detected", () =>
109 Effect.gen(function* () {
110 const tmp = yield* makeTmpDir();
111 yield* initRepoWithCommit(tmp);
112 const checkpointStore = yield* CheckpointStore.CheckpointStore;
113
114 expect(yield* checkpointStore.isGitRepository(tmp)).toBe(true);
115 }),
116 );
117 });
118
119 it.effect("preserves unrelated files created after the checkpoint", () =>
120 Effect.gen(function* () {
121 const tmp = yield* makeTmpDir();
122 yield* initRepoWithCommit(tmp);
123 const store = yield* CheckpointStore.CheckpointStore;
124 const fs = yield* FileSystem.FileSystem;
125 const checkpointRef = checkpointRefForThreadTurn(ThreadId.make("unrelated-file"), 0);
126 yield* store.captureCheckpoint({ cwd: tmp, checkpointRef });
127 yield* writeTextFile(NodePath.join(tmp, "unrelated.txt"), "Human bytes\n");
128 expect(yield* store.restoreCheckpoint({ cwd: tmp, checkpointRef })).toBe(true);
129 expect(yield* fs.readFileString(NodePath.join(tmp, "unrelated.txt"))).toBe("Human bytes\n");
130 }),
131 );
132
133 it.effect("removes checkpoint additions without cleaning later unrelated files", () =>
134 Effect.gen(function* () {
135 const tmp = yield* makeTmpDir();
136 yield* initRepoWithCommit(tmp);
137 const store = yield* CheckpointStore.CheckpointStore;
138 const fs = yield* FileSystem.FileSystem;
139 const thread = ThreadId.make("checkpoint-additions");
140 const checkpointRef = checkpointRefForThreadTurn(thread, 0);
141 const fromCheckpointRef = checkpointRefForThreadTurn(thread, 1);
142 yield* store.captureCheckpoint({ cwd: tmp, checkpointRef });
143 yield* fs.makeDirectory(NodePath.join(tmp, "new directory"));
144 yield* writeTextFile(NodePath.join(tmp, "new directory/agent.txt"), "Agent bytes\n");
145 yield* writeTextFile(NodePath.join(tmp, "README.md"), "Agent edit\n");
146 yield* store.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
147 yield* writeTextFile(NodePath.join(tmp, "new directory/human.txt"), "Human bytes\n");
148 expect(yield* store.restoreCheckpoint({ cwd: tmp, checkpointRef, fromCheckpointRef })).toBe(
149 true,
150 );
151 expect(yield* fs.exists(NodePath.join(tmp, "new directory/agent.txt"))).toBe(false);
152 expect(yield* fs.readFileString(NodePath.join(tmp, "new directory/human.txt"))).toBe(
153 "Human bytes\n",
154 );
155 expect(yield* fs.readFileString(NodePath.join(tmp, "README.md"))).toBe("# test\n");
156 }),
157 );
158
159 it.effect("preserves post-checkpoint tracked edits outside the reverted turn diff", () =>
160 Effect.gen(function* () {
161 const tmp = yield* makeTmpDir();
162 yield* initRepoWithCommit(tmp);
163 const store = yield* CheckpointStore.CheckpointStore;
164 const fs = yield* FileSystem.FileSystem;
165 const thread = ThreadId.make("post-checkpoint-tracked-edits");
166 const checkpointRef = checkpointRefForThreadTurn(thread, 0);
167 const fromCheckpointRef = checkpointRefForThreadTurn(thread, 1);
168 const humanFile = NodePath.join(tmp, "human.txt");
169
170 yield* writeTextFile(humanFile, "Human baseline\n");
171 yield* git(tmp, ["add", "human.txt"]);
172 yield* git(tmp, ["commit", "-m", "add human file"]);
173 yield* store.captureCheckpoint({ cwd: tmp, checkpointRef });
174
175 yield* writeTextFile(NodePath.join(tmp, "README.md"), "Agent edit\n");
176 yield* store.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
177
178 yield* writeTextFile(humanFile, "Human staged\n");
179 yield* git(tmp, ["add", "human.txt"]);
180 yield* writeTextFile(humanFile, "Human unstaged\n");
181
182 expect(yield* store.restoreCheckpoint({ cwd: tmp, checkpointRef, fromCheckpointRef })).toBe(
183 true,
184 );
185 expect(yield* fs.readFileString(NodePath.join(tmp, "README.md"))).toBe("# test\n");
186 expect(yield* git(tmp, ["show", ":human.txt"])).toBe("Human staged");
187 expect(yield* fs.readFileString(humanFile)).toBe("Human unstaged\n");
188 }),
189 );
190
191 it.effect("preserves staged changes outside a nested project during restore", () =>
192 Effect.gen(function* () {
193 const tmp = yield* makeTmpDir();
194 yield* initRepoWithCommit(tmp);
195 const project = NodePath.join(tmp, "project");
196 const projectFile = NodePath.join(project, "app.ts");
197 const outsideFile = NodePath.join(tmp, "outside.txt");
198 const store = yield* CheckpointStore.CheckpointStore;
199 const fs = yield* FileSystem.FileSystem;
200 const thread = ThreadId.make("nested-project-index");
201 const checkpointRef = checkpointRefForThreadTurn(thread, 0);
202 const fromCheckpointRef = checkpointRefForThreadTurn(thread, 1);
203
204 yield* fs.makeDirectory(project);
205 yield* writeTextFile(projectFile, "baseline\n");
206 yield* writeTextFile(outsideFile, "outside baseline\n");
207 yield* git(tmp, ["add", "."]);
208 yield* git(tmp, ["commit", "-m", "add project"]);
209 yield* store.captureCheckpoint({ cwd: project, checkpointRef });
210
211 yield* writeTextFile(projectFile, "agent edit\n");
212 yield* writeTextFile(NodePath.join(project, "agent.txt"), "agent addition\n");
213 yield* store.captureCheckpoint({ cwd: project, checkpointRef: fromCheckpointRef });
214
215 yield* writeTextFile(outsideFile, "outside staged\n");
216 yield* git(tmp, ["add", "outside.txt"]);
217 yield* writeTextFile(outsideFile, "outside unstaged\n");
218
219 expect(
220 yield* store.restoreCheckpoint({ cwd: project, checkpointRef, fromCheckpointRef }),
221 ).toBe(true);
222 expect(yield* git(tmp, ["show", ":outside.txt"])).toBe("outside staged");
223 expect(yield* fs.readFileString(outsideFile)).toBe("outside unstaged\n");
224 expect(yield* fs.readFileString(projectFile)).toBe("baseline\n");
225 expect(yield* fs.exists(NodePath.join(project, "agent.txt"))).toBe(false);
226 }),
227 );
228
229 describe("diffCheckpoints", () => {
230 it.effect("returns full oversized checkpoint diffs without truncation", () =>
231 Effect.gen(function* () {
232 const tmp = yield* makeTmpDir();
233 yield* initRepoWithCommit(tmp);
234 const checkpointStore = yield* CheckpointStore.CheckpointStore;
235 const threadId = ThreadId.make("thread-checkpoint-store");
236 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
237 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
238
239 yield* checkpointStore.captureCheckpoint({
240 cwd: tmp,
241 checkpointRef: fromCheckpointRef,
242 });
243 yield* writeTextFile(NodePath.join(tmp, "README.md"), buildLargeText());
244 yield* checkpointStore.captureCheckpoint({
245 cwd: tmp,
246 checkpointRef: toCheckpointRef,
247 });
248
249 const diff = yield* checkpointStore.diffCheckpoints({
250 cwd: tmp,
251 fromCheckpointRef,
252 toCheckpointRef,
253 ignoreWhitespace: true,
254 });
255
256 expect(diff).toContain("diff --git");
257 expect(diff).not.toContain("[truncated]");
258 expect(diff).toContain("+line 04999");
259 }),
260 );
261
262 it.effect("keeps a/ and b/ patch prefixes when the repository disables them", () =>
263 Effect.gen(function* () {
264 const tmp = yield* makeTmpDir();
265 yield* initRepoWithCommit(tmp);
266 yield* git(tmp, ["config", "diff.noprefix", "true"]);
267 const checkpointStore = yield* CheckpointStore.CheckpointStore;
268 const threadId = ThreadId.make("thread-checkpoint-store-noprefix");
269 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
270 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
271
272 yield* checkpointStore.captureCheckpoint({
273 cwd: tmp,
274 checkpointRef: fromCheckpointRef,
275 });
276 yield* writeTextFile(NodePath.join(tmp, "README.md"), "# changed\n");
277 yield* checkpointStore.captureCheckpoint({
278 cwd: tmp,
279 checkpointRef: toCheckpointRef,
280 });
281
282 const diff = yield* checkpointStore.diffCheckpoints({
283 cwd: tmp,
284 fromCheckpointRef,
285 toCheckpointRef,
286 ignoreWhitespace: false,
287 });
288
289 expect(diff).toContain("diff --git a/README.md b/README.md");
290 }),
291 );
292
293 it.effect("can hide indentation churn when changes wrap existing lines", () =>
294 Effect.gen(function* () {
295 const tmp = yield* makeTmpDir();
296 yield* initRepoWithCommit(tmp);
297 const checkpointStore = yield* CheckpointStore.CheckpointStore;
298 const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
299 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
300 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
301
302 const componentPath = NodePath.join(tmp, "Component.tsx");
303 yield* writeTextFile(
304 componentPath,
305 [
306 "export function View() {",
307 " return (",
308 " <section>",
309 " <h1>Title</h1>",
310 " <p>Body</p>",
311 " </section>",
312 " );",
313 "}",
314 "",
315 ].join("\n"),
316 );
317 yield* checkpointStore.captureCheckpoint({
318 cwd: tmp,
319 checkpointRef: fromCheckpointRef,
320 });
321 yield* writeTextFile(
322 componentPath,
323 [
324 "export function View() {",
325 " return (",
326 " <section>",
327 " {isReady ? (",
328 " <div>",
329 " <h1>Title</h1>",
330 " <p>Body</p>",
331 " </div>",
332 " ) : null}",
333 " </section>",
334 " );",
335 "}",
336 "",
337 ].join("\n"),
338 );
339 yield* checkpointStore.captureCheckpoint({
340 cwd: tmp,
341 checkpointRef: toCheckpointRef,
342 });
343
344 const normalDiff = yield* checkpointStore.diffCheckpoints({
345 cwd: tmp,
346 fromCheckpointRef,
347 toCheckpointRef,
348 ignoreWhitespace: false,
349 });
350 const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
351 cwd: tmp,
352 fromCheckpointRef,
353 toCheckpointRef,
354 ignoreWhitespace: true,
355 });
356
357 expect(normalDiff).toContain("diff --git");
358 expect(normalDiff).toContain("- <h1>Title</h1>");
359 expect(normalDiff).toContain("+ <h1>Title</h1>");
360 expect(whitespaceIgnoredDiff).toContain("diff --git");
361 expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
362 expect(whitespaceIgnoredDiff).toContain("+ <div>");
363 expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
364 expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
365
366 for (const ignoreWhitespace of [false, true]) {
367 const numstat = yield* checkpointStore.diffCheckpoints({
368 cwd: tmp,
369 fromCheckpointRef,
370 toCheckpointRef,
371 ignoreWhitespace,
372 format: "numstat",
373 });
374 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
375 {
376 path: "Component.tsx",
377 additions: ignoreWhitespace ? 4 : 6,
378 deletions: ignoreWhitespace ? 0 : 2,
379 },
380 ]);
381 }
382 }),
383 );
384 });
385
386 describe("checkpoint file summaries", () => {
387 it.effect("counts changes whose full patch exceeds the output limit", () =>
388 Effect.gen(function* () {
389 const tmp = yield* makeTmpDir();
390 yield* initRepoWithCommit(tmp);
391 const checkpointStore = yield* CheckpointStore.CheckpointStore;
392 const threadId = ThreadId.make("large-checkpoint-summary");
393 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
394 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
395 const filePath = NodePath.join(tmp, "README.md");
396 const lineCount = 20_000;
397 yield* writeTextFile(filePath, `${"before".repeat(50)}\n`.repeat(lineCount));
398 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
399 yield* writeTextFile(filePath, `${"after".repeat(60)}\n`.repeat(lineCount));
400 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
401
402 const numstat = yield* checkpointStore.diffCheckpoints({
403 cwd: tmp,
404 fromCheckpointRef,
405 toCheckpointRef,
406 ignoreWhitespace: false,
407 format: "numstat",
408 });
409
410 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
411 { path: "README.md", additions: lineCount, deletions: lineCount },
412 ]);
413 expect(numstat.length).toBeLessThan(100);
414 }),
415 );
416
417 it.effect("preserves file paths and turn ranges without changing the user index", () =>
418 Effect.gen(function* () {
419 const tmp = yield* makeTmpDir();
420 yield* initRepoWithCommit(tmp);
421 yield* git(tmp, ["config", "diff.renames", "copies"]);
422 const fileSystem = yield* FileSystem.FileSystem;
423 const checkpointStore = yield* CheckpointStore.CheckpointStore;
424 const threadId = ThreadId.make("checkpoint-summary-paths");
425 const baseline = checkpointRefForThreadTurn(threadId, 0);
426 const firstTurn = checkpointRefForThreadTurn(threadId, 1);
427 const secondTurn = checkpointRefForThreadTurn(threadId, 2);
428 const copiedText = Array.from({ length: 20 }, (_, index) => `copy line ${index}\n`).join(
429 "",
430 );
431 const platform = yield* HostProcessPlatform;
432 const renamedPath = platform === "win32" ? "renamed café.txt" : "renamed\tcafé\nname.txt";
433 const addedPath = platform === "win32" ? "new café.txt" : "new\tfile\n名.txt";
434 for (const [path, contents] of Object.entries({
435 "copy-source.txt": copiedText,
436 "deleted.txt": "delete me\n",
437 "rename-old.txt": "before\nkeep one\nkeep two\nkeep three\n",
438 "binary.bin": "\0before",
439 })) {
440 yield* writeTextFile(NodePath.join(tmp, path), contents);
441 }
442 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baseline });
443
444 yield* fileSystem.rename(
445 NodePath.join(tmp, "rename-old.txt"),
446 NodePath.join(tmp, renamedPath),
447 );
448 yield* fileSystem.remove(NodePath.join(tmp, "deleted.txt"));
449 for (const [path, contents] of Object.entries({
450 "copy-source.txt": `${copiedText}one more\n`,
451 "copied.txt": copiedText,
452 [renamedPath]: "after\nkeep one\nkeep two\nkeep three\n",
453 "binary.bin": "\0after",
454 "empty.txt": "",
455 [addedPath]: "first\nsecond\n",
456 })) {
457 yield* writeTextFile(NodePath.join(tmp, path), contents);
458 }
459 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: firstTurn });
460 const userIndex = yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"));
461 const input = {
462 cwd: tmp,
463 fromCheckpointRef: baseline,
464 toCheckpointRef: firstTurn,
465 ignoreWhitespace: false,
466 format: "numstat" as const,
467 };
468 const firstSummary = parseTurnDiffFilesFromNumstat(
469 yield* checkpointStore.diffCheckpoints(input),
470 );
471 const expectedFiles = [
472 { path: "binary.bin", additions: 0, deletions: 0 },
473 { path: "copied.txt", additions: 0, deletions: 0 },
474 { path: "copy-source.txt", additions: 1, deletions: 0 },
475 { path: "deleted.txt", additions: 0, deletions: 1 },
476 { path: "empty.txt", additions: 0, deletions: 0 },
477 { path: addedPath, additions: 2, deletions: 0 },
478 { path: renamedPath, additions: 1, deletions: 1 },
479 ].toSorted((left, right) => left.path.localeCompare(right.path));
480 expect(firstSummary).toEqual(expectedFiles);
481
482 yield* fileSystem.remove(NodePath.join(tmp, "empty.txt"));
483 yield* writeTextFile(NodePath.join(tmp, "copy-source.txt"), "replacement\n");
484 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: secondTurn });
485 const secondSummary = parseTurnDiffFilesFromNumstat(
486 yield* checkpointStore.diffCheckpoints({
487 ...input,
488 fromCheckpointRef: firstTurn,
489 toCheckpointRef: secondTurn,
490 }),
491 );
492 expect(secondSummary).toEqual([
493 { path: "copy-source.txt", additions: 1, deletions: 21 },
494 { path: "empty.txt", additions: 0, deletions: 0 },
495 ]);
496
497 const inclusiveSummary = parseTurnDiffFilesFromNumstat(
498 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: secondTurn }),
499 );
500 expect(inclusiveSummary).toEqual(
501 expectedFiles
502 .filter((file) => file.path !== "empty.txt")
503 .map((file) =>
504 file.path === "copy-source.txt" ? { ...file, additions: 1, deletions: 20 } : file,
505 ),
506 );
507 expect(
508 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: baseline }),
509 ).toBe("");
510 expect(yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"))).toEqual(userIndex);
511 }),
512 );
513
514 it.effect("uses HEAD for a missing baseline only when requested", () =>
515 Effect.gen(function* () {
516 const tmp = yield* makeTmpDir();
517 yield* initRepoWithCommit(tmp);
518 const checkpointStore = yield* CheckpointStore.CheckpointStore;
519 const threadId = ThreadId.make("checkpoint-summary-fallback");
520 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
521 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
522 yield* writeTextFile(NodePath.join(tmp, "README.md"), "changed\n");
523 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
524 const input = {
525 cwd: tmp,
526 fromCheckpointRef,
527 toCheckpointRef,
528 ignoreWhitespace: false,
529 format: "numstat" as const,
530 };
531
532 const error = yield* Effect.flip(checkpointStore.diffCheckpoints(input));
533 expect(error._tag).toBe("VcsProcessExitError");
534 const numstat = yield* checkpointStore.diffCheckpoints({
535 ...input,
536 fallbackFromToHead: true,
537 });
538 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
539 { path: "README.md", additions: 1, deletions: 1 },
540 ]);
541 }),
542 );
543 });
544});