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