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

CheckpointStore.test.ts

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