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("detects a nested workspace without its own .git entry", () =>
120 Effect.gen(function* () {
121 const tmp = yield* makeTmpDir();
122 yield* initRepoWithCommit(tmp);
123 const fileSystem = yield* FileSystem.FileSystem;
124 const nested = NodePath.join(tmp, "packages", "nested");
125 yield* fileSystem.makeDirectory(nested, { recursive: true });
126 const checkpointStore = yield* CheckpointStore.CheckpointStore;
127 expect(yield* checkpointStore.isGitRepository(nested)).toBe(true);
128 }),
129 );
130 describe("warmCheckpoint", () => {
131 it.effect("hashes the worktree without touching the real index or leaving temp files", () =>
132 Effect.gen(function* () {
133 const store = yield* CheckpointStore.CheckpointStore;
134 const fileSystem = yield* FileSystem.FileSystem;
135 const cwd = yield* makeTmpDir();
136 yield* initRepoWithCommit(cwd);
137 yield* writeTextFile(NodePath.join(cwd, "untracked.txt"), "warm me\n");
138
139 yield* store.warmCheckpoint({ cwd });
140
141 // The real index is untouched: the untracked file stays untracked.
142 const status = yield* git(cwd, ["status", "--porcelain"]);
143 expect(status).toContain("?? untracked.txt");
144 // No throwaway index files remain.
145 const gitEntries = yield* fileSystem.readDirectory(NodePath.join(cwd, ".git"));
146 expect(gitEntries.filter((entry) => entry.startsWith("t3-checkpoint-warm-"))).toEqual([]);
147 // The blob was hashed into the object store, so a capture reuses it.
148 const blobOid = yield* git(cwd, ["hash-object", "untracked.txt"]);
149 yield* git(cwd, ["cat-file", "-e", blobOid]);
150
151 yield* store.captureCheckpoint({
152 cwd,
153 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-warm"), 1),
154 });
155 }).pipe(Effect.provide(TestLayer), Effect.scoped),
156 );
157 });
158
159 describe("diffCheckpoints", () => {
160 it.effect("returns full oversized checkpoint diffs without truncation", () =>
161 Effect.gen(function* () {
162 const tmp = yield* makeTmpDir();
163 yield* initRepoWithCommit(tmp);
164 const checkpointStore = yield* CheckpointStore.CheckpointStore;
165 const threadId = ThreadId.make("thread-checkpoint-store");
166 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
167 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
168
169 yield* checkpointStore.captureCheckpoint({
170 cwd: tmp,
171 checkpointRef: fromCheckpointRef,
172 });
173 yield* writeTextFile(NodePath.join(tmp, "README.md"), buildLargeText());
174 yield* checkpointStore.captureCheckpoint({
175 cwd: tmp,
176 checkpointRef: toCheckpointRef,
177 });
178
179 const diff = yield* checkpointStore.diffCheckpoints({
180 cwd: tmp,
181 fromCheckpointRef,
182 toCheckpointRef,
183 ignoreWhitespace: true,
184 });
185
186 expect(diff).toContain("diff --git");
187 expect(diff).not.toContain("[truncated]");
188 expect(diff).toContain("+line 04999");
189 }),
190 );
191
192 it.effect("keeps a/ and b/ patch prefixes when the repository disables them", () =>
193 Effect.gen(function* () {
194 const tmp = yield* makeTmpDir();
195 yield* initRepoWithCommit(tmp);
196 yield* git(tmp, ["config", "diff.noprefix", "true"]);
197 const checkpointStore = yield* CheckpointStore.CheckpointStore;
198 const threadId = ThreadId.make("thread-checkpoint-store-noprefix");
199 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
200 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
201
202 yield* checkpointStore.captureCheckpoint({
203 cwd: tmp,
204 checkpointRef: fromCheckpointRef,
205 });
206 yield* writeTextFile(NodePath.join(tmp, "README.md"), "# changed\n");
207 yield* checkpointStore.captureCheckpoint({
208 cwd: tmp,
209 checkpointRef: toCheckpointRef,
210 });
211
212 const diff = yield* checkpointStore.diffCheckpoints({
213 cwd: tmp,
214 fromCheckpointRef,
215 toCheckpointRef,
216 ignoreWhitespace: false,
217 });
218
219 expect(diff).toContain("diff --git a/README.md b/README.md");
220 }),
221 );
222
223 it.effect("can hide indentation churn when changes wrap existing lines", () =>
224 Effect.gen(function* () {
225 const tmp = yield* makeTmpDir();
226 yield* initRepoWithCommit(tmp);
227 const checkpointStore = yield* CheckpointStore.CheckpointStore;
228 const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
229 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
230 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
231
232 const componentPath = NodePath.join(tmp, "Component.tsx");
233 yield* writeTextFile(
234 componentPath,
235 [
236 "export function View() {",
237 " return (",
238 " <section>",
239 " <h1>Title</h1>",
240 " <p>Body</p>",
241 " </section>",
242 " );",
243 "}",
244 "",
245 ].join("\n"),
246 );
247 yield* checkpointStore.captureCheckpoint({
248 cwd: tmp,
249 checkpointRef: fromCheckpointRef,
250 });
251 yield* writeTextFile(
252 componentPath,
253 [
254 "export function View() {",
255 " return (",
256 " <section>",
257 " {isReady ? (",
258 " <div>",
259 " <h1>Title</h1>",
260 " <p>Body</p>",
261 " </div>",
262 " ) : null}",
263 " </section>",
264 " );",
265 "}",
266 "",
267 ].join("\n"),
268 );
269 yield* checkpointStore.captureCheckpoint({
270 cwd: tmp,
271 checkpointRef: toCheckpointRef,
272 });
273
274 const normalDiff = yield* checkpointStore.diffCheckpoints({
275 cwd: tmp,
276 fromCheckpointRef,
277 toCheckpointRef,
278 ignoreWhitespace: false,
279 });
280 const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
281 cwd: tmp,
282 fromCheckpointRef,
283 toCheckpointRef,
284 ignoreWhitespace: true,
285 });
286
287 expect(normalDiff).toContain("diff --git");
288 expect(normalDiff).toContain("- <h1>Title</h1>");
289 expect(normalDiff).toContain("+ <h1>Title</h1>");
290 expect(whitespaceIgnoredDiff).toContain("diff --git");
291 expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
292 expect(whitespaceIgnoredDiff).toContain("+ <div>");
293 expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
294 expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
295
296 for (const ignoreWhitespace of [false, true]) {
297 const numstat = yield* checkpointStore.diffCheckpoints({
298 cwd: tmp,
299 fromCheckpointRef,
300 toCheckpointRef,
301 ignoreWhitespace,
302 format: "numstat",
303 });
304 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
305 {
306 path: "Component.tsx",
307 additions: ignoreWhitespace ? 4 : 6,
308 deletions: ignoreWhitespace ? 0 : 2,
309 },
310 ]);
311 }
312 }),
313 );
314 });
315
316 describe("checkpoint file summaries", () => {
317 it.effect("counts changes whose full patch exceeds the output limit", () =>
318 Effect.gen(function* () {
319 const tmp = yield* makeTmpDir();
320 yield* initRepoWithCommit(tmp);
321 const checkpointStore = yield* CheckpointStore.CheckpointStore;
322 const threadId = ThreadId.make("large-checkpoint-summary");
323 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
324 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
325 const filePath = NodePath.join(tmp, "README.md");
326 const lineCount = 20_000;
327 yield* writeTextFile(filePath, `${"before".repeat(50)}\n`.repeat(lineCount));
328 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: fromCheckpointRef });
329 yield* writeTextFile(filePath, `${"after".repeat(60)}\n`.repeat(lineCount));
330 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
331
332 const numstat = yield* checkpointStore.diffCheckpoints({
333 cwd: tmp,
334 fromCheckpointRef,
335 toCheckpointRef,
336 ignoreWhitespace: false,
337 format: "numstat",
338 });
339
340 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
341 { path: "README.md", additions: lineCount, deletions: lineCount },
342 ]);
343 expect(numstat.length).toBeLessThan(100);
344 }),
345 );
346
347 it.effect("preserves file paths and turn ranges without changing the user index", () =>
348 Effect.gen(function* () {
349 const tmp = yield* makeTmpDir();
350 yield* initRepoWithCommit(tmp);
351 yield* git(tmp, ["config", "diff.renames", "copies"]);
352 const fileSystem = yield* FileSystem.FileSystem;
353 const checkpointStore = yield* CheckpointStore.CheckpointStore;
354 const threadId = ThreadId.make("checkpoint-summary-paths");
355 const baseline = checkpointRefForThreadTurn(threadId, 0);
356 const firstTurn = checkpointRefForThreadTurn(threadId, 1);
357 const secondTurn = checkpointRefForThreadTurn(threadId, 2);
358 const copiedText = Array.from({ length: 20 }, (_, index) => `copy line ${index}\n`).join(
359 "",
360 );
361 const platform = yield* HostProcessPlatform;
362 const renamedPath = platform === "win32" ? "renamed café.txt" : "renamed\tcafé\nname.txt";
363 const addedPath = platform === "win32" ? "new café.txt" : "new\tfile\n名.txt";
364 for (const [path, contents] of Object.entries({
365 "copy-source.txt": copiedText,
366 "deleted.txt": "delete me\n",
367 "rename-old.txt": "before\nkeep one\nkeep two\nkeep three\n",
368 "binary.bin": "\0before",
369 })) {
370 yield* writeTextFile(NodePath.join(tmp, path), contents);
371 }
372 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baseline });
373
374 yield* fileSystem.rename(
375 NodePath.join(tmp, "rename-old.txt"),
376 NodePath.join(tmp, renamedPath),
377 );
378 yield* fileSystem.remove(NodePath.join(tmp, "deleted.txt"));
379 for (const [path, contents] of Object.entries({
380 "copy-source.txt": `${copiedText}one more\n`,
381 "copied.txt": copiedText,
382 [renamedPath]: "after\nkeep one\nkeep two\nkeep three\n",
383 "binary.bin": "\0after",
384 "empty.txt": "",
385 [addedPath]: "first\nsecond\n",
386 })) {
387 yield* writeTextFile(NodePath.join(tmp, path), contents);
388 }
389 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: firstTurn });
390 const userIndex = yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"));
391 const input = {
392 cwd: tmp,
393 fromCheckpointRef: baseline,
394 toCheckpointRef: firstTurn,
395 ignoreWhitespace: false,
396 format: "numstat" as const,
397 };
398 const firstSummary = parseTurnDiffFilesFromNumstat(
399 yield* checkpointStore.diffCheckpoints(input),
400 );
401 const expectedFiles = [
402 { path: "binary.bin", additions: 0, deletions: 0 },
403 { path: "copied.txt", additions: 0, deletions: 0 },
404 { path: "copy-source.txt", additions: 1, deletions: 0 },
405 { path: "deleted.txt", additions: 0, deletions: 1 },
406 { path: "empty.txt", additions: 0, deletions: 0 },
407 { path: addedPath, additions: 2, deletions: 0 },
408 { path: renamedPath, additions: 1, deletions: 1 },
409 ].toSorted((left, right) => left.path.localeCompare(right.path));
410 expect(firstSummary).toEqual(expectedFiles);
411
412 yield* fileSystem.remove(NodePath.join(tmp, "empty.txt"));
413 yield* writeTextFile(NodePath.join(tmp, "copy-source.txt"), "replacement\n");
414 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: secondTurn });
415 const secondSummary = parseTurnDiffFilesFromNumstat(
416 yield* checkpointStore.diffCheckpoints({
417 ...input,
418 fromCheckpointRef: firstTurn,
419 toCheckpointRef: secondTurn,
420 }),
421 );
422 expect(secondSummary).toEqual([
423 { path: "copy-source.txt", additions: 1, deletions: 21 },
424 { path: "empty.txt", additions: 0, deletions: 0 },
425 ]);
426
427 const inclusiveSummary = parseTurnDiffFilesFromNumstat(
428 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: secondTurn }),
429 );
430 expect(inclusiveSummary).toEqual(
431 expectedFiles
432 .filter((file) => file.path !== "empty.txt")
433 .map((file) =>
434 file.path === "copy-source.txt" ? { ...file, additions: 1, deletions: 20 } : file,
435 ),
436 );
437 expect(
438 yield* checkpointStore.diffCheckpoints({ ...input, toCheckpointRef: baseline }),
439 ).toBe("");
440 expect(yield* fileSystem.readFile(NodePath.join(tmp, ".git/index"))).toEqual(userIndex);
441 }),
442 );
443
444 it.effect("uses HEAD for a missing baseline only when requested", () =>
445 Effect.gen(function* () {
446 const tmp = yield* makeTmpDir();
447 yield* initRepoWithCommit(tmp);
448 const checkpointStore = yield* CheckpointStore.CheckpointStore;
449 const threadId = ThreadId.make("checkpoint-summary-fallback");
450 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
451 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
452 yield* writeTextFile(NodePath.join(tmp, "README.md"), "changed\n");
453 yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: toCheckpointRef });
454 const input = {
455 cwd: tmp,
456 fromCheckpointRef,
457 toCheckpointRef,
458 ignoreWhitespace: false,
459 format: "numstat" as const,
460 };
461
462 const error = yield* Effect.flip(checkpointStore.diffCheckpoints(input));
463 expect(error._tag).toBe("VcsProcessExitError");
464 const numstat = yield* checkpointStore.diffCheckpoints({
465 ...input,
466 fallbackFromToHead: true,
467 });
468 expect(parseTurnDiffFilesFromNumstat(numstat)).toEqual([
469 { path: "README.md", additions: 1, deletions: 1 },
470 ]);
471 }),
472 );
473 });
474});