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

GitVcsDriver.test.ts

1,242 lines55.1 KB

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