Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Cause from "effect/Cause";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Schema from "effect/Schema";
15import { ChildProcessSpawner } from "effect/process";
16
17import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
18import * as ProcessRunner from "../processRunner.ts";
19import * as VcsProcess from "./VcsProcess.ts";
20
21const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
22
23const run = (input: VcsProcess.VcsProcessInput) =>
24 Effect.gen(function* () {
25 const process = yield* VcsProcess.VcsProcess;
26 return yield* process.run(input);
27 });
28
29const layerLive = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
30
31const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
32 effect.pipe(Effect.provide(layerLive));
33
34const baseInput = {
35 operation: "test.process-boundary",
36 command: "git",
37 args: ["status", "--short"],
38 cwd: "/workspace",
39} satisfies VcsProcess.VcsProcessInput;
40
41const captureProcessResult = (
42 result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
43) =>
44 VcsProcess.make.pipe(
45 Effect.provideService(
46 ProcessRunner.ProcessRunner,
47 ProcessRunner.ProcessRunner.of({ run: () => result }),
48 ),
49 Effect.flatMap((service) => service.run(baseInput)),
50 Effect.flip,
51 );
52
53describe("VcsProcess.run", () => {
54 it.effect("explains a locked Git index and allows restore after the lock is released", () =>
55 Effect.gen(function* () {
56 const fs = yield* FileSystem.FileSystem;
57 const path = yield* Path.Path;
58 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" });
59 const git = (args: readonly string[]) =>
60 run({ operation: "test.checkpoint.restore", command: "git", cwd, args });
61 yield* git(["init"]);
62 const file = path.join(cwd, "README.md");
63 yield* fs.writeFileString(file, "before\n");
64 yield* git(["add", "README.md"]);
65 yield* git([
66 "-c",
67 "user.name=Test",
68 "-c",
69 "user.email=test@example.com",
70 "commit",
71 "-m",
72 "initial",
73 ]);
74 yield* fs.writeFileString(file, "after\n");
75 const lock = path.join(cwd, ".git", "index.lock");
76 yield* fs.writeFileString(lock, "held by another process\n");
77 const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"];
78
79 const error = yield* Effect.flip(git(restore));
80 expect(error).toBeInstanceOf(VcsProcessExitError);
81 expect(error).toMatchObject({
82 exitCode: 128,
83 failureKind: "command-failed",
84 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
85 });
86 expect(error.message).not.toContain("index.lock");
87 expect(yield* fs.readFileString(file)).toBe("after\n");
88 expect(yield* fs.readFileString(lock)).toBe("held by another process\n");
89
90 yield* fs.remove(lock);
91 yield* git(restore);
92 expect(yield* fs.readFileString(file)).toBe("before\n");
93 }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),
94 );
95
96 it.effect.each([
97 {
98 stderr: "fatal: Unable to create '/private/repo/index.lock': File exists",
99 retryable: true,
100 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
101 },
102 {
103 stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.",
104 retryable: true,
105 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
106 },
107 {
108 stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.",
109 retryable: true,
110 },
111 {
112 stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
113 retryable: false,
114 },
115 { stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
116 {
117 stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
118 retryable: true,
119 },
120 { stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
121 {
122 stderr: "error: '/private/repo/child/' does not have a commit checked out",
123 retryable: false,
124 },
125 { stderr: "fatal: index file corrupt", retryable: false },
126 ])(
127 "classifies Git exit retryability and safe detail without retaining stderr: $stderr",
128 ({ stderr, retryable, detail = "Process exited with a non-zero status." }) =>
129 Effect.gen(function* () {
130 const error = yield* captureProcessResult(
131 Effect.succeed({
132 stdout: "",
133 stderr,
134 code: ChildProcessSpawner.ExitCode(128),
135 timedOut: false,
136 stdoutTruncated: false,
137 stderrTruncated: false,
138 stdoutInvalidUtf8: false,
139 stderrInvalidUtf8: false,
140 }),
141 );
142 assert.instanceOf(error, VcsProcessExitError);
143 expect(error.retryable === true).toBe(retryable);
144 expect(error.detail).toBe(detail);
145 const encoded = yield* encodeExitError(error);
146 expect(encoded).not.toContain("private");
147 }),
148 );
149
150 it.effect.each([
151 {
152 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
153 fsyncMethods: ["fsync", "writeout-only"],
154 },
155 {
156 stderr:
157 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
158 fsyncMethods: ["fsync", "writeout-only"],
159 },
160 { stderr: "fatal: Operation not supported", fsyncMethods: ["fsync"] },
161 {
162 stderr:
163 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock': Input/output error",
164 fsyncMethods: ["fsync"],
165 },
166 {
167 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
168 fsyncMethods: ["fsync", "writeout-only"],
169 fallbackFails: true,
170 },
171 {
172 platform: "linux",
173 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
174 fsyncMethods: ["fsync"],
175 },
176 {
177 operation: baseInput.operation,
178 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
179 fsyncMethods: ["fsync"],
180 },
181 {
182 stderr: "fatal: fsync error on '.git/objects/bulk_fsync_Pseg66': Operation not supported",
183 fsyncMethods: ["batch", "writeout-only"],
184 },
185 {
186 stderr:
187 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
188 fsyncMethods: ["batch", "writeout-only"],
189 },
190 ] as const)(
191 "falls back to writeout-only only for unsupported flushes on macOS ($fsyncMethods): $stderr",
192 ({ stderr, fsyncMethods, ...scenario }) =>
193 Effect.gen(function* () {
194 const seen: Array<ReadonlyArray<string>> = [];
195 const service = yield* VcsProcess.make.pipe(
196 Effect.provideService(
197 HostProcess.Platform,
198 "platform" in scenario ? scenario.platform : "darwin",
199 ),
200 Effect.provideService(ProcessRunner.ProcessRunner, {
201 run: (input) =>
202 Effect.sync(() => {
203 seen.push(input.args);
204 const failed =
205 input.args.includes(`core.fsyncMethod=${fsyncMethods[0]}`) ||
206 ("fallbackFails" in scenario && scenario.fallbackFails);
207 return {
208 stdout: "",
209 stderr: failed ? stderr : "",
210 code: ChildProcessSpawner.ExitCode(failed ? 128 : 0),
211 timedOut: false,
212 stdoutTruncated: false,
213 stderrTruncated: false,
214 stdoutInvalidUtf8: false,
215 stderrInvalidUtf8: false,
216 };
217 }),
218 }),
219 );
220 const exit = yield* service
221 .run({
222 ...baseInput,
223 operation:
224 "operation" in scenario
225 ? scenario.operation
226 : VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
227 args: [
228 "-c",
229 "core.fsync=objects,reference",
230 "-c",
231 ...(fsyncMethods[0] === "batch" ? ["core.fsyncMethod=fsync", "-c"] : []),
232 `core.fsyncMethod=${fsyncMethods[0]}`,
233 "add",
234 ],
235 })
236 .pipe(Effect.exit);
237 expect(seen).toEqual(
238 fsyncMethods.map((method) => [
239 "-c",
240 "core.fsync=objects,reference",
241 "-c",
242 ...(fsyncMethods[0] === "batch"
243 ? [`core.fsyncMethod=${method === "batch" ? "fsync" : method}`, "-c"]
244 : []),
245 `core.fsyncMethod=${method}`,
246 "add",
247 ]),
248 );
249 expect(Exit.isSuccess(exit)).toBe(
250 fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails),
251 );
252 if (Exit.isFailure(exit)) {
253 expect(Cause.findErrorOption(exit.cause)).toMatchObject({
254 _tag: "Some",
255 value: { _tag: "VcsProcessExitError", exitCode: 128 },
256 });
257 }
258 }),
259 );
260
261 it.effect("bounds a synthetic burst of GitHub API processes", () =>
262 Effect.gen(function* () {
263 const gate = yield* Deferred.make<void>();
264 const starts = yield* Queue.unbounded<number>();
265 const active = yield* Ref.make(0);
266 const peak = yield* Ref.make(0);
267 const total = yield* Ref.make(0);
268 const service = yield* VcsProcess.make.pipe(
269 Effect.provideService(
270 ProcessRunner.ProcessRunner,
271 ProcessRunner.ProcessRunner.of({
272 run: () =>
273 Effect.gen(function* () {
274 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
275 yield* Ref.update(peak, (held) => Math.max(held, count));
276 yield* Ref.update(total, (held) => held + 1);
277 yield* Queue.offer(starts, count);
278 yield* Deferred.await(gate);
279 return {
280 stdout: "",
281 stderr: "",
282 code: ChildProcessSpawner.ExitCode(0),
283 timedOut: false,
284 stdoutTruncated: false,
285 stderrTruncated: false,
286 stdoutInvalidUtf8: false,
287 stderrInvalidUtf8: false,
288 };
289 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
290 }),
291 ),
292 );
293
294 const burst = yield* Effect.all(
295 Array.from({ length: 32 }, (_, index) =>
296 service.run({
297 operation: `synthetic.github.${index}`,
298 command: "gh",
299 args: ["api", "user"],
300 cwd: "/workspace",
301 }),
302 ),
303 { concurrency: "unbounded" },
304 ).pipe(Effect.forkChild);
305
306 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
307 yield* Effect.yieldNow;
308 expect(yield* Queue.size(starts)).toBe(0);
309 expect(yield* Ref.get(peak)).toBe(4);
310
311 yield* Deferred.succeed(gate, undefined);
312 yield* Fiber.join(burst);
313 expect(yield* Ref.get(total)).toBe(32);
314 expect(yield* Ref.get(peak)).toBe(4);
315 }),
316 );
317
318 it.effect("keeps git from opening a folder laid out as a bare repository", () =>
319 Effect.gen(function* () {
320 const fileSystem = yield* FileSystem.FileSystem;
321 const path = yield* Path.Path;
322 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
323 yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
324 yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
325 yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
326 yield* fileSystem.writeFileString(
327 path.join(cwd, "config"),
328 '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
329 );
330
331 const result = yield* run({
332 operation: "test.bare-repository",
333 command: "git",
334 args: ["status"],
335 cwd,
336 allowNonZeroExit: true,
337 });
338
339 expect(result.exitCode).not.toBe(0);
340 expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
341 }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
342 );
343
344 it.effect("classifies authentication failures without retaining stderr", () =>
345 Effect.gen(function* () {
346 const secretStderr = "authentication failed for token super-secret-token";
347 const error = yield* run({
348 operation: "test.authentication",
349 command: "node",
350 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
351 cwd: process.cwd(),
352 }).pipe(Effect.flip);
353
354 expect(error).toBeInstanceOf(VcsProcessExitError);
355 expect(error).toMatchObject({
356 operation: "test.authentication",
357 command: "node",
358 exitCode: 1,
359 detail: "Authentication failed.",
360 failureKind: "authentication",
361 stderrLength: secretStderr.length,
362 stderrTruncated: false,
363 });
364 expect(error.message).not.toContain(secretStderr);
365 expect(error.message).not.toContain("super-secret-token");
366 }).pipe(provideLive),
367 );
368
369 it.effect("classifies API rate limits without retaining provider stderr", () =>
370 Effect.gen(function* () {
371 const providerStderr =
372 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
373 const error = yield* run({
374 operation: "test.rate-limit",
375 command: "node",
376 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
377 cwd: process.cwd(),
378 }).pipe(Effect.flip);
379
380 expect(error).toBeInstanceOf(VcsProcessExitError);
381 expect(error).toMatchObject({
382 command: "node",
383 exitCode: 1,
384 detail: "API rate limit exceeded.",
385 failureKind: "rate-limited",
386 stderrLength: providerStderr.length,
387 stderrTruncated: false,
388 });
389 expect(error.message).not.toContain(providerStderr);
390 expect(error.message).not.toContain("secret-value");
391 }).pipe(provideLive),
392 );
393
394 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
395 Effect.gen(function* () {
396 const secretArgument = "--token=super-secret-token";
397 const error = yield* run({
398 operation: "test.spawn",
399 command: "definitely-not-a-t3code-executable",
400 args: [secretArgument],
401 cwd: process.cwd(),
402 }).pipe(Effect.flip);
403
404 expect(error).toBeInstanceOf(VcsProcessSpawnError);
405 expect(error).toMatchObject({
406 operation: "test.spawn",
407 command: "definitely-not-a-t3code-executable",
408 argumentCount: 1,
409 });
410 expect(error).toHaveProperty("cause");
411 expect(error.message).not.toContain(secretArgument);
412 }).pipe(provideLive),
413 );
414
415 it.effect("truncates output and appends the marker when requested", () =>
416 Effect.gen(function* () {
417 const result = yield* run({
418 operation: "test.truncate-marker",
419 command: "node",
420 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
421 cwd: process.cwd(),
422 maxOutputBytes: 128,
423 appendTruncationMarker: true,
424 });
425
426 expect(result.stdoutTruncated).toBe(true);
427 expect(result.stdout).toContain("[truncated]");
428 expect(result.stderrTruncated).toBe(false);
429 }).pipe(provideLive),
430 );
431
432 it.effect("fails with measured byte counts when output must not be truncated", () =>
433 Effect.gen(function* () {
434 const error = yield* run({
435 operation: "test.output-limit",
436 command: "node",
437 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
438 cwd: yield* HostProcess.WorkingDirectory,
439 maxOutputBytes: 128,
440 outputMode: "error",
441 }).pipe(Effect.flip);
442
443 assert(error._tag === "VcsProcessOutputLimitError");
444 expect(error.stream).toBe("stdout");
445 expect(error.maxBytes).toBe(128);
446 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
447 }).pipe(provideLive),
448 );
449
450 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
451 Effect.gen(function* () {
452 const chunks: Uint8Array[] = [];
453 const result = yield* run({
454 operation: "test.stream-output",
455 command: "node",
456 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
457 cwd: process.cwd(),
458 maxOutputBytes: 8,
459 onStdoutChunk: (chunk) => chunks.push(chunk),
460 });
461
462 expect(result.stdout).toBe("xxxxxxxx");
463 expect(result.stdoutTruncated).toBe(true);
464 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
465 }).pipe(provideLive),
466 );
467});