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