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