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