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