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