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