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

GitVcsDriver.test.ts

980 lines43.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as Cause from "effect/Cause";
3import * as Exit from "effect/Exit";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as TestClock from "effect/testing/TestClock";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import { ChildProcessSpawner } from "effect/unstable/process";
13import { assert, it } from "@effect/vitest";
14​
15import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts";
16import * as ServerConfig from "../config.ts";
17import * as GitVcsDriver from "./GitVcsDriver.ts";
18import * as VcsProcess from "./VcsProcess.ts";
19import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
20​
21const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
22 prefix: "t3-git-vcs-contract-",
23});
24const GitContractLayer = Layer.mergeAll(GitVcsDriver.vcsLayer, GitVcsDriver.layer).pipe(
25 Layer.provide(ServerConfigLayer),
26 Layer.provideMerge(VcsProcess.layer),
27 Layer.provideMerge(NodeServices.layer),
28);
29​
30const runGit = (cwd: string, args: ReadonlyArray<string>) =>
31 Effect.gen(function* () {
32 const driver = yield* GitVcsDriver.GitVcsDriver;
33 yield* driver.execute({
34 operation: "GitVcsDriver.contract.git",
35 cwd,
36 args,
37 timeoutMs: 10_000,
38 });
39 });
40​
41type GitContractError = GitCommandError | PlatformError.PlatformError;
42​
43runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
44 name: "Git",
45 kind: "git",
46 layer: GitContractLayer,
47 fixture: {
48 createRepo: (cwd) =>
49 Effect.gen(function* () {
50 yield* runGit(cwd, ["init"]);
51 yield* runGit(cwd, ["config", "user.email", "test@test.com"]);
52 yield* runGit(cwd, ["config", "user.name", "Test"]);
53 }),
54 writeFile: (cwd, relativePath, contents) =>
55 Effect.gen(function* () {
56 const fileSystem = yield* FileSystem.FileSystem;
57 const path = yield* Path.Path;
58 const absolutePath = path.join(cwd, relativePath);
59 yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
60 yield* fileSystem.writeFileString(absolutePath, contents);
61 }),
62 trackFile: (cwd, relativePath) => runGit(cwd, ["add", relativePath]),
63 commit: (cwd, message) => runGit(cwd, ["commit", "-m", message]),
64 ignorePath: (cwd, pattern) =>
65 Effect.gen(function* () {
66 const fileSystem = yield* FileSystem.FileSystem;
67 const path = yield* Path.Path;
68 yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
69 }),
70 },
71});
72​
73const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* (
74 driver: Effect.Success<ReturnType<typeof GitVcsDriver.makeVcsDriverShape>>,
75 cwd: string,
76) {
77 const fileSystem = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const git = (args: ReadonlyArray<string>) =>
80 driver.execute({ operation: "checkpoint-test", cwd, args });
81 yield* git(["init"]);
82 yield* git(["config", "user.name", "Test"]);
83 yield* git(["config", "user.email", "test@test.com"]);
84 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "initial\n");
85 yield* git(["add", "."]);
86 yield* git(["commit", "-m", "initial"]);
87 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/test");
88 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
89 yield* git(["add", "."]);
90 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "unstaged\n");
91 return { git, checkpointRef };
92});
93​
94it.effect("checkpoint capture skips untracked nested repositories without a commit", () =>
95 Effect.gen(function* () {
96 const fileSystem = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const driver = yield* GitVcsDriver.makeVcsDriverShape();
99 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-unborn-" });
100 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
101 const nested = "scratch/empty [repo]";
102 yield* git(["init", nested]);
103 yield* git(["init", "another empty"]);
104 yield* fileSystem.writeFileString(path.join(cwd, nested, "private.txt"), "nested\n");
105 yield* git(["init", "committed"]);
106 yield* git([
107 "-C",
108 "committed",
109 "-c",
110 "user.name=Test",
111 "-c",
112 "user.email=test@test.com",
113 "commit",
114 "--allow-empty",
115 "-m",
116 "initial",
117 ]);
118 const nestedHead = (yield* git(["-C", "committed", "rev-parse", "HEAD"])).stdout.trim();
119 yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n");
120 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
121​
122 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
123​
124 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
125 assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n");
126 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", nested])).stdout, "");
127 assert.strictEqual((yield* git(["ls-tree", checkpointRef, "--", "another empty"])).stdout, "");
128 assert.strictEqual(
129 (yield* git(["ls-tree", checkpointRef, "--", "committed"])).stdout,
130 `160000 commit ${nestedHead}\tcommitted\n`,
131 );
132 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
133 assert.strictEqual(
134 yield* fileSystem.readFileString(path.join(cwd, nested, "private.txt")),
135 "nested\n",
136 );
137 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
138);
139​
140it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () =>
141 Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const driver = yield* GitVcsDriver.makeVcsDriverShape();
145 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-git-dir-" });
146 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
147 yield* git(["init", "empty"]);
148 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
149 yield* Effect.acquireUseRelease(
150 Effect.sync(() => {
151 const previous = process.env.GIT_DIR;
152 process.env.GIT_DIR = path.join(cwd, ".git");
153 return previous;
154 }),
155 () => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
156 (previous) =>
157 Effect.sync(() => {
158 if (previous === undefined) delete process.env.GIT_DIR;
159 else process.env.GIT_DIR = previous;
160 }),
161 );
162 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
163 assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, "");
164 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
165 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
166);
167​
168it.effect("checkpoint capture still fails when a clean filter rejects a file", () =>
169 Effect.gen(function* () {
170 const fileSystem = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 const driver = yield* GitVcsDriver.makeVcsDriverShape();
173 const cwd = yield* fileSystem.makeTempDirectoryScoped({
174 prefix: "t3-checkpoint-filter-failure-",
175 });
176 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
177 yield* fileSystem.writeFileString(path.join(cwd, ".gitattributes"), "file.txt filter=reject\n");
178 yield* git(["config", "filter.reject.clean", "false"]);
179 yield* git(["config", "filter.reject.required", "true"]);
180 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
181​
182 const result = yield* Effect.result(
183 driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
184 );
185​
186 assert.strictEqual(result._tag, "Failure");
187 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
188 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
189 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
190);
191​
192it.effect("checkpoint capture refuses a truncated nested repository listing", () =>
193 Effect.gen(function* () {
194 const fs = yield* FileSystem.FileSystem;
195 const liveProcess = yield* VcsProcess.VcsProcess;
196 const driver = yield* GitVcsDriver.makeVcsDriverShape();
197 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-truncated-" });
198 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
199 yield* git(["init", "empty"]);
200 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
201 Effect.provideService(VcsProcess.VcsProcess, {
202 run: (input) =>
203 liveProcess
204 .run(input)
205 .pipe(
206 Effect.map((result) =>
207 input.args.includes("--others") ? { ...result, stdoutTruncated: true } : result,
208 ),
209 ),
210 }),
211 );
212​
213 const result = yield* Effect.result(
214 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
215 );
216​
217 assert.strictEqual(result._tag, "Failure");
218 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
219 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
220);
221​
222it.effect("checkpoint recovery refuses excessive candidates before probing", () =>
223 Effect.gen(function* () {
224 const fs = yield* FileSystem.FileSystem;
225 const path = yield* Path.Path;
226 const liveProcess = yield* VcsProcess.VcsProcess;
227 const driver = yield* GitVcsDriver.makeVcsDriverShape();
228 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-cap-" });
229 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
230 yield* git(["init", "empty0"]);
231 for (let i = 1; i < 65; i++)
232 yield* fs.copy(path.join(cwd, "empty0"), path.join(cwd, `empty${i}`));
233 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
234 let stageError: VcsProcessExitError | undefined;
235 let nestedProbes = 0;
236 let stageAttempts = 0;
237 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
238 Effect.provideService(VcsProcess.VcsProcess, {
239 run: (input) => {
240 if (input.cwd !== cwd && input.args.includes("rev-parse")) nestedProbes++;
241 if (input.args.includes("add") && input.args.includes("-A")) stageAttempts++;
242 return liveProcess.run(input).pipe(
243 Effect.tapError((error) => {
244 if (error._tag === "VcsProcessExitError") stageError = error;
245 return Effect.void;
246 }),
247 );
248 },
249 }),
250 );
251 const result = yield* Effect.result(
252 captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
253 );
254 assert.strictEqual(nestedProbes, 0);
255 assert.strictEqual(stageAttempts, 1);
256 assert.strictEqual(result._tag, "Failure");
257 if (result._tag === "Failure") assert.strictEqual(result.failure, stageError);
258 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
259 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
260 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
261);
262​
263for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
264 it.effect(`checkpoint recovery has one deadline including ${blockedPhase}`, () =>
265 Effect.gen(function* () {
266 const fs = yield* FileSystem.FileSystem;
267 const path = yield* Path.Path;
268 const liveProcess = yield* VcsProcess.VcsProcess;
269 const driver = yield* GitVcsDriver.makeVcsDriverShape();
270 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-timeout-" });
271 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
272 yield* git(["init", "empty"]);
273 const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
274 const entered = yield* Deferred.make<void>();
275 const discovered = yield* Deferred.make<void>();
276 let stageError: VcsProcessExitError | undefined;
277 let privateIndex: string | undefined;
278 let interrupted = false;
279 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
280 Effect.provideService(VcsProcess.VcsProcess, {
281 run: (input) => {
282 const staging = input.args.includes("add") && input.args.includes("-A");
283 if (staging) privateIndex = input.env?.GIT_INDEX_FILE;
284 const block =
285 (blockedPhase === "discovery" && input.args.includes("--others")) ||
286 (blockedPhase === "probe" && input.cwd !== cwd && input.args.includes("rev-parse")) ||
287 (blockedPhase === "retry" &&
288 staging &&
289 input.args.some((arg) => arg.startsWith(":(exclude,literal)")));
290 if (block)
291 return (
292 blockedPhase === "retry"
293 ? fs
294 .writeFileString(
295 `${input.env!.GIT_INDEX_FILE!}.lock`,
296 "interrupted index write",
297 )
298 .pipe(Effect.orDie)
299 : Effect.void
300 ).pipe(
301 Effect.andThen(Deferred.succeed(entered, undefined)),
302 Effect.andThen(Effect.never),
303 Effect.onInterrupt(() =>
304 Effect.sync(() => {
305 interrupted = true;
306 }),
307 ),
308 );
309 return liveProcess.run(input).pipe(
310 Effect.tap(() =>
311 blockedPhase === "probe" && input.args.includes("--others")
312 ? Deferred.succeed(discovered, undefined).pipe(
313 Effect.andThen(Effect.sleep("3 seconds")),
314 )
315 : Effect.void,
316 ),
317 Effect.tapError((error) => {
318 if (staging && error._tag === "VcsProcessExitError") stageError = error;
319 return Effect.void;
320 }),
321 );
322 },
323 }),
324 );
325 const fiber = yield* captureDriver.checkpoints
326 .captureCheckpoint({ cwd, checkpointRef })
327 .pipe(Effect.flip, Effect.forkScoped);
328 if (blockedPhase === "probe") {
329 yield* Deferred.await(discovered);
330 yield* TestClock.adjust("3 seconds");
331 }
332 yield* Deferred.await(entered);
333 yield* TestClock.adjust(blockedPhase === "probe" ? "2 seconds" : "5 seconds");
334 const error = yield* Fiber.join(fiber);
335 assert.strictEqual(error, stageError);
336 assert.isTrue(interrupted);
337 assert.isDefined(privateIndex);
338 assert.isFalse(yield* fs.exists(privateIndex!));
339 assert.isFalse(yield* fs.exists(`${privateIndex!}.lock`));
340 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
341 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
342 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
343 );
345​
346it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
347 Effect.gen(function* () {
348 const fs = yield* FileSystem.FileSystem;
349 const liveProcess = yield* VcsProcess.VcsProcess;
350 const driver = yield* GitVcsDriver.makeVcsDriverShape();
351 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-interrupt-" });
352 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
353 yield* git(["init", "empty"]);
354 const entered = yield* Deferred.make<void>();
355 let privateIndex: string | undefined;
356 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
357 Effect.provideService(VcsProcess.VcsProcess, {
358 run: (input) => {
359 if (input.args.includes("add") && input.args.includes("-A"))
360 privateIndex = input.env?.GIT_INDEX_FILE;
361 return input.args.includes("--others")
362 ? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
363 : liveProcess.run(input);
364 },
365 }),
366 );
367 const fiber = yield* captureDriver.checkpoints
368 .captureCheckpoint({ cwd, checkpointRef })
369 .pipe(Effect.forkScoped);
370 yield* Deferred.await(entered);
371 yield* Fiber.interrupt(fiber);
372 const exit = yield* Fiber.await(fiber);
373 assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
374 assert.isDefined(privateIndex);
375 assert.isFalse(yield* fs.exists(privateIndex!));
376 assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
377 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
378);
379​
380it.effect("checkpoint capture does not rerun clean filters for unchanged indexed files", () =>
381 Effect.gen(function* () {
382 const fileSystem = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const driver = yield* GitVcsDriver.makeVcsDriverShape();
385 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-cache-" });
386 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
387 yield* fileSystem.writeFileString(
388 path.join(cwd, ".gitattributes"),
389 "stable.txt filter=probe\n",
390 );
391 yield* fileSystem.writeFileString(path.join(cwd, "stable.txt"), "unchanged\n");
392 yield* fileSystem.writeFileString(
393 path.join(cwd, ".git", "filter.cjs"),
394 'require("node:fs").appendFileSync(".git/filter-runs", "read\\n"); process.stdin.pipe(process.stdout);',
395 );
396 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
397 yield* fileSystem.utimes(path.join(cwd, "stable.txt"), 1_700_000_000, 1_700_000_000);
398 yield* git(["add", "."]);
399 yield* git(["commit", "-m", "record stable file"]);
400 yield* fileSystem.writeFileString(path.join(cwd, ".git", "filter-runs"), "");
401 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "changed\n");
402 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
403​
404 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
405​
406 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, ".git", "filter-runs")), "");
407 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "changed\n");
408 assert.strictEqual((yield* git(["show", `${checkpointRef}:stable.txt`])).stdout, "unchanged\n");
409 assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
410 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
411);
412​
413for (const nested of [false, true]) {
414 for (const indexState of [
415 "sparse",
416 "flags",
417 "manual-skip",
418 "missing",
419 "non-cone-missing",
420 ] as const) {
421 it.effect(
422 `sparse checkpoint preserves two captures (nested=${nested}, index=${indexState})`,
423 () =>
424 Effect.gen(function* () {
425 const fs = yield* FileSystem.FileSystem;
426 const path = yield* Path.Path;
427 const driver = yield* GitVcsDriver.makeVcsDriverShape();
428 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
429 const { git } = yield* makeCheckpointFixture(driver, cwd);
430 const write = Effect.fn(function* (name: string, contents: string) {
431 yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
432 yield* fs.writeFileString(path.join(cwd, name), contents);
433 });
434 for (const name of [
435 "scope/in/edit",
436 "scope/in/delete",
437 "scope/out/deep/absent",
438 "scope/out/present",
439 "elsewhere/file",
440 ]) {
441 yield* write(name, "original\n");
442 }
443 yield* git(["add", "."]);
444 yield* git(["commit", "-m", "sparse fixture"]);
445 yield* git([
446 "sparse-checkout",
447 "set",
448 "--cone",
449 "--sparse-index",
450 "scope/in",
451 "elsewhere",
452 ]);
453 if (indexState === "non-cone-missing")
454 yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
455 yield* write("scope/in/edit", "staged\n");
456 yield* write("elsewhere/file", "staged outside\n");
457 yield* git(["add", "."]);
458 if (indexState === "flags")
459 yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
460 if (indexState === "manual-skip")
461 yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
462 yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
463 yield* write("scope/in/edit", "working\n");
464 yield* write("scope/out/present", "modified skipped\n");
465 yield* write("scope/out/new file", "new outside cone\n");
466 yield* write("elsewhere/file", "working outside\n");
467 yield* fs.remove(path.join(cwd, "scope/in/delete"));
468 const indexPath = path.join(cwd, ".git/index");
469 if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
470 const originalIndex = yield* fs
471 .readFile(indexPath)
472 .pipe(Effect.orElseSucceed(() => null));
473 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
474 for (const turn of [1, 2]) {
475 const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
476 if (turn === 2) {
477 yield* write("scope/in/edit", "second\n");
478 yield* fs.remove(path.join(cwd, "scope/out/new file"));
479 yield* write("scope/out/second", "second addition\n");
480 }
481 const capture = driver.checkpoints.captureCheckpoint({
482 cwd: captureCwd,
483 checkpointRef: ref,
484 });
485 if (indexState === "non-cone-missing") {
486 assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
487 assert.isFalse(
488 yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
489 );
490 assert.isFalse(yield* fs.exists(indexPath));
491 break;
492 }
493 yield* capture;
494 for (const [name, content] of [
495 ["scope/out/deep/absent", "original\n"],
496 ["scope/out/present", "modified skipped\n"],
497 ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
498 ["elsewhere/file", nested ? "original\n" : "working outside\n"],
499 [
500 turn === 1 ? "scope/out/new file" : "scope/out/second",
501 turn === 1 ? "new outside cone\n" : "second addition\n",
502 ],
503 ]) {
504 assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
505 }
506 const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
507 assert.notInclude(files, "scope/in/delete");
508 if (turn === 2) assert.notInclude(files, "scope/out/new file");
509 assert.deepEqual(
510 yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
511 originalIndex,
512 );
513 assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
514 assert.strictEqual(
515 yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
516 "working outside\n",
517 );
518 }
519 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
520 );
521 }
523​
524it.effect("checkpoint capture keeps the legacy path when Git lacks add --sparse", () =>
525 Effect.gen(function* () {
526 const fs = yield* FileSystem.FileSystem;
527 const path = yield* Path.Path;
528 const liveProcess = yield* VcsProcess.VcsProcess;
529 const driver = yield* GitVcsDriver.makeVcsDriverShape();
530 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-legacy-" });
531 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
532 yield* git(["sparse-checkout", "set", "--cone", "included"]);
533 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
534 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
535 Effect.provideService(VcsProcess.VcsProcess, {
536 run: (input) => {
537 if (input.args.includes("-h"))
538 return Effect.succeed({
539 exitCode: ChildProcessSpawner.ExitCode(129),
540 stdout: "usage: git add",
541 stderr: "",
542 stdoutTruncated: false,
543 stderrTruncated: false,
544 });
545 return liveProcess.run(
546 input.args.includes("--sparse")
547 ? {
548 ...input,
549 args: input.args.map((arg) =>
550 arg === "--sparse" ? "--unsupported-sparse" : arg,
551 ),
552 }
553 : input,
554 );
555 },
556 }),
557 );
558 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
559 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
560 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
561 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
562);
563​
564for (const indexMode of ["normal", "flags", "sparse"] as const) {
565 it.effect(
566 `checkpoint index inspection handles entries beyond the output cap (index=${indexMode})`,
567 () =>
568 Effect.gen(function* () {
569 const fs = yield* FileSystem.FileSystem;
570 const path = yield* Path.Path;
571 const liveProcess = yield* VcsProcess.VcsProcess;
572 const driver = yield* GitVcsDriver.makeVcsDriverShape();
573 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
574 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
575 yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
576 yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
577 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
578 yield* fs.makeDirectory(path.join(cwd, "excluded"));
579 yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
580 yield* fs.writeFileString(
581 path.join(cwd, ".git/filter.cjs"),
582 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
583 );
584 yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
585 yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
586 yield* git(["add", "."]);
587 yield* git(["commit", "-m", "inspection fixture"]);
588 if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
589 if (indexMode === "sparse")
590 yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
591 yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
592 yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
593 const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
594 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
595 Effect.provideService(VcsProcess.VcsProcess, {
596 run: (input) =>
597 liveProcess.run(
598 input.args.includes("ls-files")
599 ? {
600 ...input,
601 maxOutputBytes: 8,
602 onStdoutChunk: (chunk) => {
603 for (let i = 0; i < chunk.length; i++)
604 input.onStdoutChunk?.(chunk.subarray(i, i + 1));
605 },
606 }
607 : input,
608 ),
609 }),
610 );
611 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
612 assert.strictEqual(
613 (yield* git(["show", `${checkpointRef}:z-skipped`])).stdout,
614 "modified\n",
615 );
616 if (indexMode !== "flags")
617 assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
618 assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
619 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
620 );
622​
623for (const timestamp of [1_700_000_000, 1_700_000_000.9999]) {
624 it.effect(
625 `checkpoint capture preserves same-size edits with racy index timestamps (${timestamp})`,
626 () =>
627 Effect.gen(function* () {
628 const fileSystem = yield* FileSystem.FileSystem;
629 const path = yield* Path.Path;
630 const driver = yield* GitVcsDriver.makeVcsDriverShape();
631 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
632 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
633 const filePath = path.join(cwd, "file.txt");
634 const indexPath = path.join(cwd, ".git", "index");
635 yield* git(["config", "core.trustctime", "false"]);
636 yield* fileSystem.writeFileString(filePath, "before\n");
637 yield* fileSystem.utimes(filePath, timestamp, timestamp);
638 yield* git(["add", "file.txt"]);
639 yield* git(["commit", "-m", "record racy file"]);
640 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
641 const originalIndex = yield* fileSystem.readFile(indexPath);
642 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
643 yield* fileSystem.writeFileString(filePath, "after!\n");
644 yield* fileSystem.utimes(filePath, timestamp, timestamp);
645​
646 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
647​
648 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
649 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
650 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
651 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
652 );
654​
655it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
656 Effect.gen(function* () {
657 const fileSystem = yield* FileSystem.FileSystem;
658 const path = yield* Path.Path;
659 const liveProcess = yield* VcsProcess.VcsProcess;
660 const driver = yield* GitVcsDriver.makeVcsDriverShape();
661 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-reset-" });
662 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
663 const racyPath = path.join(cwd, "racy.txt");
664 const indexPath = path.join(cwd, ".git", "index");
665 const timestamp = 1_700_000_000;
666 yield* git(["config", "core.trustctime", "false"]);
667 yield* fileSystem.writeFileString(racyPath, "before\n");
668 yield* fileSystem.utimes(racyPath, timestamp, timestamp);
669 yield* git(["add", "."]);
670 yield* git(["commit", "-m", "record racy file"]);
671 yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "staged\n");
672 yield* git(["add", "file.txt"]);
673 yield* fileSystem.utimes(indexPath, timestamp, timestamp);
674 const originalIndex = yield* fileSystem.readFile(indexPath);
675 const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
676 const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
677 Effect.provideService(VcsProcess.VcsProcess, {
678 run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) {
679 const result = yield* liveProcess.run(input);
680 if (input.args.includes("read-tree") && input.args.includes("--reset")) {
681 yield* fileSystem.writeFileString(racyPath, "after!\n").pipe(Effect.orDie);
682 yield* fileSystem.utimes(racyPath, timestamp, timestamp).pipe(Effect.orDie);
683 }
684 return result;
685 }),
686 }),
687 );
688​
689 yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
690​
691 assert.strictEqual((yield* git(["show", `${checkpointRef}:racy.txt`])).stdout, "after!\n");
692 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "staged\n");
693 assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
694 assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
695 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
696);
697​
698for (const nested of [false, true]) {
699 for (const indexMode of ["normal", "flags", "split"] as const) {
700 it.effect(
701 `checkpoint index reuse preserves two turns (nested=${nested}, index=${indexMode})`,
702 () =>
703 Effect.gen(function* () {
704 const fileSystem = yield* FileSystem.FileSystem;
705 const path = yield* Path.Path;
706 const driver = yield* GitVcsDriver.makeVcsDriverShape();
707 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
708 const { git } = yield* makeCheckpointFixture(driver, cwd);
709 const write = (name: string, contents: string) =>
710 fileSystem.writeFileString(path.join(cwd, name), contents);
711 yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
712 for (const name of [
713 "scope/staged",
714 "scope/deleted",
715 "scope/assumed",
716 "scope/skipped",
717 "outside",
718 ]) {
719 yield* write(name, "original\n");
720 }
721 yield* git(["add", "."]);
722 yield* git(["commit", "-m", "initial scoped files"]);
723 yield* write("scope/staged", "staged\n");
724 yield* write("scope/new-deleted", "staged then deleted\n");
725 yield* write("outside", "staged outside\n");
726 yield* git(["add", "."]);
727 if (indexMode === "flags") {
728 yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
729 yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
730 }
731 if (indexMode === "split") {
732 yield* git(["update-index", "--split-index"]);
733 }
734 const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
735 for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
736 yield* write(name, "working\n");
737 }
738 yield* write("scope/new", "first\n");
739 yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
740 yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
741 const captureCwd = nested ? path.join(cwd, "scope") : cwd;
742 const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
743 const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
744 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
745 for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
746 assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
747 }
748 assert.strictEqual(
749 (yield* git(["show", `${first}:outside`])).stdout,
750 nested ? "original\n" : "working\n",
751 );
752 const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
753 assert.notInclude(files, "scope/deleted");
754 assert.notInclude(files, "scope/new-deleted");
755 assert.include(files, "scope/new");
756​
757 yield* write("scope/staged", "second\n");
758 yield* fileSystem.remove(path.join(cwd, "scope/new"));
759 yield* write("scope/second", "added in second turn\n");
760 yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
761 assert.strictEqual(
762 (yield* git(["diff", "--name-only", first, second])).stdout,
763 "scope/new\nscope/second\nscope/staged\n",
764 );
765 assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
766 assert.strictEqual(
767 (yield* git(["show", `${second}:scope/second`])).stdout,
768 "added in second turn\n",
769 );
770 assert.deepEqual(
771 yield* fileSystem.readFile(path.join(cwd, ".git", "index")),
772 originalIndex,
773 );
774 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
775 );
776 }
778​
779for (const indexState of ["missing", "invalid"] as const) {
780 it.effect(`checkpoint capture falls back when the user index is ${indexState}`, () =>
781 Effect.gen(function* () {
782 const fileSystem = yield* FileSystem.FileSystem;
783 const path = yield* Path.Path;
784 const driver = yield* GitVcsDriver.makeVcsDriverShape();
785 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-index-" });
786 const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
787 const indexPath = path.join(cwd, ".git", "index");
788 if (indexState === "missing") {
789 yield* fileSystem.remove(indexPath);
790 } else {
791 yield* fileSystem.writeFileString(indexPath, "invalid index");
792 }
793​
794 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
795​
796 assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
797 if (indexState === "missing") {
798 assert.isFalse(yield* fileSystem.exists(indexPath));
799 } else {
800 assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
801 }
802 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
803 );
805​
806it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
807 Effect.gen(function* () {
808 const fileSystem = yield* FileSystem.FileSystem;
809 const path = yield* Path.Path;
810 const driver = yield* GitVcsDriver.makeVcsDriverShape();
811 for (const nested of [false, true]) {
812 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-empty-checkpoint-" });
813 yield* runGit(root, ["init"]);
814 yield* runGit(root, ["config", "user.email", "test@test.com"]);
815 yield* runGit(root, ["config", "user.name", "Test"]);
816 if (nested) {
817 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "original\n");
818 yield* runGit(root, ["add", "."]);
819 }
820 yield* runGit(root, ["commit", "--allow-empty", "-m", "initial"]);
821 const cwd = nested ? path.join(root, "nested") : root;
822 yield* fileSystem.makeDirectory(cwd, { recursive: true });
823 const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/empty");
824 yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
825 if (nested) {
826 yield* fileSystem.writeFileString(path.join(root, "outside.txt"), "changed\n");
827 yield* runGit(root, ["add", "outside.txt"]);
828 }
829 for (const staged of [false, true]) {
830 const addedPath = path.join(cwd, "added.txt");
831 yield* fileSystem.writeFileString(addedPath, "new\n");
832 if (staged) yield* runGit(cwd, ["add", "added.txt"]);
833 assert.isTrue(
834 yield* driver.checkpoints.restoreCheckpoint({
835 cwd,
836 checkpointRef,
837 fallbackToHead: false,
838 }),
839 );
840 assert.isFalse(yield* fileSystem.exists(addedPath));
841 }
842 yield* fileSystem.writeFileString(
843 path.join(root, ".git", "info", "exclude"),
844 "ignored.txt\n",
845 );
846 yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "keep\n");
847 yield* fileSystem.makeDirectory(path.join(cwd, "untracked"));
848 yield* fileSystem.writeFileString(path.join(cwd, "untracked", "file.txt"), "remove\n");
849 assert.isTrue(
850 yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }),
851 );
852 assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, "ignored.txt")), "keep\n");
853 assert.isFalse(yield* fileSystem.exists(path.join(cwd, "untracked")));
854 if (nested) {
855 assert.strictEqual(
856 yield* fileSystem.readFileString(path.join(root, "outside.txt")),
857 "changed\n",
858 );
859 const staged = yield* driver.execute({
860 operation: "test",
861 cwd: root,
862 args: ["diff", "--cached", "--name-only"],
863 });
864 assert.strictEqual(staged.stdout.trim(), "outside.txt");
865 }
866 }
867 }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
868);
869​
870it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
871 let observedEnv: NodeJS.ProcessEnv | undefined;
872 let observedAppendTruncationMarker: boolean | undefined;
873 let observedOutputMode: VcsProcess.VcsProcessInput["outputMode"];
874​
875 return Effect.gen(function* () {
876 const driver = yield* GitVcsDriver.makeVcsDriverShape();
877​
878 yield* driver.execute({
879 operation: "GitVcsDriver.test.env",
880 cwd: "/repo",
881 args: ["status"],
882 env: {
883 GIT_INDEX_FILE: "/tmp/t3-index",
884 },
885 appendTruncationMarker: true,
886 outputMode: "error",
887 });
888​
889 assert.deepStrictEqual(observedEnv, {
890 GIT_INDEX_FILE: "/tmp/t3-index",
891 });
892 assert.strictEqual(observedAppendTruncationMarker, true);
893 assert.strictEqual(observedOutputMode, "error");
894 }).pipe(
895 Effect.provide(
896 Layer.mergeAll(
897 NodeServices.layer,
898 Layer.mock(VcsProcess.VcsProcess)({
899 run: (input) =>
900 Effect.sync(() => {
901 observedEnv = input.env;
902 observedAppendTruncationMarker = input.appendTruncationMarker;
903 observedOutputMode = input.outputMode;
904 return {
905 exitCode: ChildProcessSpawner.ExitCode(0),
906 stdout: "",
907 stderr: "",
908 stdoutTruncated: false,
909 stderrTruncated: false,
910 };
911 }),
912 }),
913 ),
914 ),
915 );
916});
917​
918it.effect("GitVcsDriver flushes checkpoint objects and refs to disk before publishing them", () => {
919 const observedArgs: ReadonlyArray<string>[] = [];
920​
921 return Effect.gen(function* () {
922 const driver = yield* GitVcsDriver.makeVcsDriverShape();
923​
924 yield* driver.checkpoints.captureCheckpoint({
925 cwd: "/repo",
926 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread/turn/1"),
927 });
928​
929 const writeCommands = ["add", "write-tree", "commit-tree", "update-ref"];
930 const writes = observedArgs.filter((args) =>
931 writeCommands.some((command) => args.includes(command)),
932 );
933 assert.strictEqual(writes.length, 4);
934 for (const args of writes) {
935 const command = args.findIndex((arg) => writeCommands.includes(arg));
936 for (const setting of ["core.fsync=objects,reference", "core.fsyncMethod=fsync"]) {
937 const index = args.indexOf(setting);
938 assert.strictEqual(args[index - 1], "-c", args.join(" "));
939 assert.isBelow(index, command);
940 }
941 }
942 assert.deepStrictEqual(observedArgs.at(-1), [
943 "-C",
944 "/repo",
945 "-c",
946 "core.fsync=objects,reference",
947 "-c",
948 "core.fsyncMethod=fsync",
949 "update-ref",
950 "refs/t3/checkpoints/thread/turn/1",
951 "commit0000",
952 ]);
953 }).pipe(
954 Effect.provide(
955 Layer.mergeAll(
956 NodeServices.layer,
957 Layer.mock(VcsProcess.VcsProcess)({
958 run: (input) =>
959 Effect.sync(() => {
960 observedArgs.push(input.args);
961 const stdout = input.args.includes("write-tree")
962 ? "tree0000\n"
963 : input.args.includes("commit-tree")
964 ? "commit0000\n"
965 : input.args.includes("--git-common-dir")
966 ? ".git\n"
967 : "";
968 return {
969 exitCode: ChildProcessSpawner.ExitCode(0),
970 stdout,
971 stderr: "",
972 stdoutTruncated: false,
973 stderrTruncated: false,
974 };
975 }),
976 }),
977 ),
978 ),
979 );
980});