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

CheckpointStore.test.ts

446 lines17.0 KB

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