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