Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitVcsDriver.test.ts

1,479 lines65.1 KB

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