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 Duration from "effect/Duration";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Cause from "effect/Cause";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Queue from "effect/Queue";
14import * as Ref from "effect/Ref";
15import * as Schema from "effect/Schema";
16import { TestClock } from "effect/testing";
17import { ChildProcessSpawner } from "effect/process";
18
19import {
20 VcsProcessExitError,
21 VcsProcessSpawnError,
22 VcsProcessTimeoutError,
23} from "@t3tools/contracts";
24import * as ProcessRunner from "../processRunner.ts";
25import * as VcsProcess from "./VcsProcess.ts";
26
27const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
28
29const run = (input: VcsProcess.VcsProcessInput) =>
30 Effect.gen(function* () {
31 const process = yield* VcsProcess.VcsProcess;
32 return yield* process.run(input);
33 });
34
35const layerLive = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
36
37const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
38 effect.pipe(Effect.provide(layerLive));
39
40const baseInput = {
41 operation: "test.process-boundary",
42 command: "git",
43 args: ["status", "--short"],
44 cwd: "/workspace",
45} satisfies VcsProcess.VcsProcessInput;
46
47const captureProcessResult = (
48 result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
49) =>
50 VcsProcess.make.pipe(
51 Effect.provideService(
52 ProcessRunner.ProcessRunner,
53 ProcessRunner.ProcessRunner.of({ run: () => result }),
54 ),
55 Effect.flatMap((service) => service.run(baseInput)),
56 Effect.flip,
57 );
58
59describe("VcsProcess.run", () => {
60 it.effect("explains a locked Git index and allows restore after the lock is released", () =>
61 Effect.gen(function* () {
62 const fs = yield* FileSystem.FileSystem;
63 const path = yield* Path.Path;
64 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" });
65 const git = (args: readonly string[]) =>
66 run({ operation: "test.checkpoint.restore", command: "git", cwd, args });
67 yield* git(["init"]);
68 const file = path.join(cwd, "README.md");
69 yield* fs.writeFileString(file, "before\n");
70 yield* git(["add", "README.md"]);
71 yield* git([
72 "-c",
73 "user.name=Test",
74 "-c",
75 "user.email=test@example.com",
76 "commit",
77 "-m",
78 "initial",
79 ]);
80 yield* fs.writeFileString(file, "after\n");
81 const lock = path.join(cwd, ".git", "index.lock");
82 yield* fs.writeFileString(lock, "held by another process\n");
83 const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"];
84
85 const error = yield* Effect.flip(git(restore));
86 expect(error).toBeInstanceOf(VcsProcessExitError);
87 expect(error).toMatchObject({
88 exitCode: 128,
89 failureKind: "command-failed",
90 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
91 });
92 expect(error.message).not.toContain("index.lock");
93 expect(yield* fs.readFileString(file)).toBe("after\n");
94 expect(yield* fs.readFileString(lock)).toBe("held by another process\n");
95
96 yield* fs.remove(lock);
97 yield* git(restore);
98 expect(yield* fs.readFileString(file)).toBe("before\n");
99 }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),
100 );
101
102 it.effect.each([
103 {
104 stderr: "fatal: Unable to create '/private/repo/index.lock': File exists",
105 retryable: true,
106 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
107 },
108 {
109 stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.",
110 retryable: true,
111 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
112 },
113 {
114 stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.",
115 retryable: true,
116 },
117 {
118 stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
119 retryable: false,
120 },
121 { stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
122 {
123 stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
124 retryable: true,
125 },
126 { stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
127 {
128 stderr: "error: '/private/repo/child/' does not have a commit checked out",
129 retryable: false,
130 },
131 { stderr: "fatal: index file corrupt", retryable: false },
132 ])(
133 "classifies Git exit retryability and safe detail without retaining stderr: $stderr",
134 ({ stderr, retryable, detail = "Process exited with a non-zero status." }) =>
135 Effect.gen(function* () {
136 const error = yield* captureProcessResult(
137 Effect.succeed({
138 stdout: "",
139 stderr,
140 code: ChildProcessSpawner.ExitCode(128),
141 timedOut: false,
142 stdoutTruncated: false,
143 stderrTruncated: false,
144 stdoutInvalidUtf8: false,
145 stderrInvalidUtf8: false,
146 }),
147 );
148 assert.instanceOf(error, VcsProcessExitError);
149 expect(error.retryable === true).toBe(retryable);
150 expect(error.detail).toBe(detail);
151 const encoded = yield* encodeExitError(error);
152 expect(encoded).not.toContain("private");
153 }),
154 );
155
156 it.effect.each([
157 {
158 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
159 fsyncMethods: ["fsync", "writeout-only"],
160 },
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'",
164 fsyncMethods: ["fsync", "writeout-only"],
165 },
166 { stderr: "fatal: Operation not supported", fsyncMethods: ["fsync"] },
167 {
168 stderr:
169 "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",
170 fsyncMethods: ["fsync"],
171 },
172 {
173 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
174 fsyncMethods: ["fsync", "writeout-only"],
175 fallbackFails: true,
176 },
177 {
178 platform: "linux",
179 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
180 fsyncMethods: ["fsync"],
181 },
182 {
183 operation: baseInput.operation,
184 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
185 fsyncMethods: ["fsync"],
186 },
187 {
188 stderr: "fatal: fsync error on '.git/objects/bulk_fsync_Pseg66': Operation not supported",
189 fsyncMethods: ["batch", "writeout-only"],
190 },
191 {
192 stderr:
193 "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'",
194 fsyncMethods: ["batch", "writeout-only"],
195 },
196 ] as const)(
197 "falls back to writeout-only only for unsupported flushes on macOS ($fsyncMethods): $stderr",
198 ({ stderr, fsyncMethods, ...scenario }) =>
199 Effect.gen(function* () {
200 const seen: Array<ReadonlyArray<string>> = [];
201 const service = yield* VcsProcess.make.pipe(
202 Effect.provideService(
203 HostProcess.Platform,
204 "platform" in scenario ? scenario.platform : "darwin",
205 ),
206 Effect.provideService(ProcessRunner.ProcessRunner, {
207 run: (input) =>
208 Effect.sync(() => {
209 seen.push(input.args);
210 const failed =
211 input.args.includes(`core.fsyncMethod=${fsyncMethods[0]}`) ||
212 ("fallbackFails" in scenario && scenario.fallbackFails);
213 return {
214 stdout: "",
215 stderr: failed ? stderr : "",
216 code: ChildProcessSpawner.ExitCode(failed ? 128 : 0),
217 timedOut: false,
218 stdoutTruncated: false,
219 stderrTruncated: false,
220 stdoutInvalidUtf8: false,
221 stderrInvalidUtf8: false,
222 };
223 }),
224 }),
225 );
226 const exit = yield* service
227 .run({
228 ...baseInput,
229 operation:
230 "operation" in scenario
231 ? scenario.operation
232 : VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
233 args: [
234 "-c",
235 "core.fsync=objects,reference",
236 "-c",
237 ...(fsyncMethods[0] === "batch" ? ["core.fsyncMethod=fsync", "-c"] : []),
238 `core.fsyncMethod=${fsyncMethods[0]}`,
239 "add",
240 ],
241 })
242 .pipe(Effect.exit);
243 expect(seen).toEqual(
244 fsyncMethods.map((method) => [
245 "-c",
246 "core.fsync=objects,reference",
247 "-c",
248 ...(fsyncMethods[0] === "batch"
249 ? [`core.fsyncMethod=${method === "batch" ? "fsync" : method}`, "-c"]
250 : []),
251 `core.fsyncMethod=${method}`,
252 "add",
253 ]),
254 );
255 expect(Exit.isSuccess(exit)).toBe(
256 fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails),
257 );
258 if (Exit.isFailure(exit)) {
259 expect(Cause.findErrorOption(exit.cause)).toMatchObject({
260 _tag: "Some",
261 value: { _tag: "VcsProcessExitError", exitCode: 128 },
262 });
263 }
264 }),
265 );
266
267 it.effect.each(["timeout", "spawn"] as const)(
268 "checkpoint commands do not retry %s failures",
269 (kind) =>
270 Effect.gen(function* () {
271 let attempts = 0;
272 const fields = { command: "git", argumentCount: 2, cwd: "/workspace" };
273 const failure =
274 kind === "timeout"
275 ? new ProcessRunner.ProcessTimeoutError({ ...fields, timeoutMs: 30_000 })
276 : new ProcessRunner.ProcessSpawnError({ ...fields, cause: new Error("spawn failed") });
277 const service = yield* VcsProcess.make.pipe(
278 Effect.provideService(ProcessRunner.ProcessRunner, {
279 run: () =>
280 Effect.sync(() => {
281 attempts += 1;
282 }).pipe(Effect.andThen(Effect.fail(failure))),
283 }),
284 );
285 const error = yield* service
286 .run({
287 ...baseInput,
288 operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
289 })
290 .pipe(Effect.flip);
291 expect(attempts).toBe(1);
292 expect(error._tag).toBe(
293 kind === "timeout" ? "VcsProcessTimeoutError" : "VcsProcessSpawnError",
294 );
295 }),
296 );
297
298 it.effect.each([
299 {
300 name: "recovers after two lock failures",
301 failures: 2,
302 attempts: 3,
303 transient: true,
304 capture: true,
305 streaming: false,
306 },
307 {
308 name: "bounds persistent lock failures",
309 failures: Infinity,
310 attempts: 3,
311 transient: true,
312 capture: true,
313 streaming: false,
314 },
315 {
316 name: "does not retry unknown exits",
317 failures: Infinity,
318 attempts: 1,
319 transient: false,
320 capture: true,
321 streaming: false,
322 },
323 {
324 name: "leaves other operations unchanged",
325 failures: Infinity,
326 attempts: 1,
327 transient: true,
328 capture: false,
329 streaming: false,
330 },
331 {
332 name: "does not replay stdout callbacks",
333 failures: Infinity,
334 attempts: 1,
335 transient: true,
336 capture: true,
337 streaming: true,
338 },
339 ])(
340 "checkpoint command retry $name",
341 ({ failures, attempts: expectedAttempts, transient, capture, streaming }) =>
342 Effect.gen(function* () {
343 let attempts = 0;
344 const service = yield* VcsProcess.make.pipe(
345 Effect.provideService(ProcessRunner.ProcessRunner, {
346 run: () =>
347 Effect.sync(() => {
348 attempts += 1;
349 return {
350 stdout: "",
351 stderr:
352 attempts > failures
353 ? ""
354 : transient
355 ? "fatal: Unable to create '/repo/index.lock': File exists"
356 : "fatal: index file corrupt",
357 code: ChildProcessSpawner.ExitCode(attempts > failures ? 0 : attempts),
358 timedOut: false,
359 stdoutTruncated: false,
360 stderrTruncated: false,
361 stdoutInvalidUtf8: false,
362 stderrInvalidUtf8: false,
363 };
364 }),
365 }),
366 );
367 const fiber = yield* service
368 .run({
369 ...baseInput,
370 operation: capture ? VcsProcess.CHECKPOINT_CAPTURE_OPERATION : baseInput.operation,
371 ...(streaming ? { onStdoutChunk: () => {} } : {}),
372 })
373 .pipe(Effect.exit, Effect.forkScoped);
374 yield* TestClock.adjust("150 millis");
375 const result = yield* Fiber.join(fiber);
376 expect(attempts).toBe(expectedAttempts);
377 if (failures === Infinity) {
378 if (Exit.isSuccess(result))
379 return yield* Effect.die("Expected a capture command failure");
380 const error = Cause.findErrorOption(result.cause);
381 if (error._tag === "None" || error.value._tag !== "VcsProcessExitError") {
382 return yield* Effect.die("Expected a Git exit error");
383 }
384 expect(error.value.exitCode).toBe(expectedAttempts);
385 } else {
386 expect(Exit.isSuccess(result)).toBe(true);
387 }
388 }),
389 );
390
391 it.effect("bounds a synthetic burst of GitHub API processes", () =>
392 Effect.gen(function* () {
393 const gate = yield* Deferred.make<void>();
394 const starts = yield* Queue.unbounded<number>();
395 const active = yield* Ref.make(0);
396 const peak = yield* Ref.make(0);
397 const total = yield* Ref.make(0);
398 const service = yield* VcsProcess.make.pipe(
399 Effect.provideService(
400 ProcessRunner.ProcessRunner,
401 ProcessRunner.ProcessRunner.of({
402 run: () =>
403 Effect.gen(function* () {
404 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
405 yield* Ref.update(peak, (held) => Math.max(held, count));
406 yield* Ref.update(total, (held) => held + 1);
407 yield* Queue.offer(starts, count);
408 yield* Deferred.await(gate);
409 return {
410 stdout: "",
411 stderr: "",
412 code: ChildProcessSpawner.ExitCode(0),
413 timedOut: false,
414 stdoutTruncated: false,
415 stderrTruncated: false,
416 stdoutInvalidUtf8: false,
417 stderrInvalidUtf8: false,
418 };
419 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
420 }),
421 ),
422 );
423
424 const burst = yield* Effect.all(
425 Array.from({ length: 32 }, (_, index) =>
426 service.run({
427 operation: `synthetic.github.${index}`,
428 command: "gh",
429 args: ["api", "user"],
430 cwd: "/workspace",
431 }),
432 ),
433 { concurrency: "unbounded" },
434 ).pipe(Effect.forkChild);
435
436 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
437 yield* Effect.yieldNow;
438 expect(yield* Queue.size(starts)).toBe(0);
439 expect(yield* Ref.get(peak)).toBe(4);
440
441 yield* Deferred.succeed(gate, undefined);
442 yield* Fiber.join(burst);
443 expect(yield* Ref.get(total)).toBe(32);
444 expect(yield* Ref.get(peak)).toBe(4);
445 }),
446 );
447
448 it.effect("collects stdout", () =>
449 Effect.gen(function* () {
450 const result = yield* run({
451 operation: "test.stdout",
452 command: "node",
453 args: ["-e", "process.stdout.write('hello')"],
454 cwd: process.cwd(),
455 });
456
457 expect(result.stdout).toBe("hello");
458 expect(result.stderr).toBe("");
459 expect(result.stdoutTruncated).toBe(false);
460 expect(result.stderrTruncated).toBe(false);
461 }).pipe(provideLive),
462 );
463
464 it.effect("keeps git from opening a folder laid out as a bare repository", () =>
465 Effect.gen(function* () {
466 const fileSystem = yield* FileSystem.FileSystem;
467 const path = yield* Path.Path;
468 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
469 yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
470 yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
471 yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
472 yield* fileSystem.writeFileString(
473 path.join(cwd, "config"),
474 '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
475 );
476
477 const result = yield* run({
478 operation: "test.bare-repository",
479 command: "git",
480 args: ["status"],
481 cwd,
482 allowNonZeroExit: true,
483 });
484
485 expect(result.exitCode).not.toBe(0);
486 expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
487 }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
488 );
489
490 it.effect("writes stdin before waiting for exit", () =>
491 Effect.gen(function* () {
492 const result = yield* run({
493 operation: "test.stdin",
494 command: "node",
495 args: [
496 "-e",
497 [
498 "process.stdin.setEncoding('utf8');",
499 "let data='';",
500 "process.stdin.on('data', chunk => { data += chunk; });",
501 "process.stdin.on('end', () => { process.stdout.write(data); });",
502 ].join(""),
503 ],
504 cwd: process.cwd(),
505 stdin: "stdin payload",
506 });
507
508 expect(result.stdout).toBe("stdin payload");
509 }).pipe(provideLive),
510 );
511
512 it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
513 Effect.gen(function* () {
514 const secretArgument = "--token=super-secret-token";
515 const secretStderr = "remote rejected super-secret-token";
516 const error = yield* run({
517 operation: "test.exit",
518 command: "node",
519 args: [
520 "-e",
521 "process.stderr.write(process.argv[1]); process.exit(2)",
522 secretStderr,
523 secretArgument,
524 ],
525 cwd: process.cwd(),
526 }).pipe(Effect.flip);
527
528 expect(error).toBeInstanceOf(VcsProcessExitError);
529 expect(error).toMatchObject({
530 operation: "test.exit",
531 command: "node",
532 argumentCount: 4,
533 exitCode: 2,
534 detail: "Process exited with a non-zero status.",
535 failureKind: "command-failed",
536 stderrLength: secretStderr.length,
537 stderrTruncated: false,
538 });
539 expect(error.message).not.toContain(secretArgument);
540 expect(error.message).not.toContain(secretStderr);
541 }).pipe(provideLive),
542 );
543
544 it.effect("classifies authentication failures without retaining stderr", () =>
545 Effect.gen(function* () {
546 const secretStderr = "authentication failed for token super-secret-token";
547 const error = yield* run({
548 operation: "test.authentication",
549 command: "node",
550 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
551 cwd: process.cwd(),
552 }).pipe(Effect.flip);
553
554 expect(error).toBeInstanceOf(VcsProcessExitError);
555 expect(error).toMatchObject({
556 operation: "test.authentication",
557 command: "node",
558 exitCode: 1,
559 detail: "Authentication failed.",
560 failureKind: "authentication",
561 stderrLength: secretStderr.length,
562 stderrTruncated: false,
563 });
564 expect(error.message).not.toContain(secretStderr);
565 expect(error.message).not.toContain("super-secret-token");
566 }).pipe(provideLive),
567 );
568
569 it.effect("classifies API rate limits without retaining provider stderr", () =>
570 Effect.gen(function* () {
571 const providerStderr =
572 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
573 const error = yield* run({
574 operation: "test.rate-limit",
575 command: "node",
576 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
577 cwd: process.cwd(),
578 }).pipe(Effect.flip);
579
580 expect(error).toBeInstanceOf(VcsProcessExitError);
581 expect(error).toMatchObject({
582 command: "node",
583 exitCode: 1,
584 detail: "API rate limit exceeded.",
585 failureKind: "rate-limited",
586 stderrLength: providerStderr.length,
587 stderrTruncated: false,
588 });
589 expect(error.message).not.toContain(providerStderr);
590 expect(error.message).not.toContain("secret-value");
591 }).pipe(provideLive),
592 );
593
594 it.effect("classifies HTTP 429 responses as rate limits", () =>
595 Effect.gen(function* () {
596 const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value";
597 const error = yield* run({
598 operation: "test.rate-limit",
599 command: "node",
600 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
601 cwd: process.cwd(),
602 }).pipe(Effect.flip);
603
604 expect(error).toMatchObject({
605 detail: "API rate limit exceeded.",
606 failureKind: "rate-limited",
607 });
608 expect(error.message).not.toContain(providerStderr);
609 }).pipe(provideLive),
610 );
611
612 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
613 Effect.gen(function* () {
614 const secretArgument = "--token=super-secret-token";
615 const error = yield* run({
616 operation: "test.spawn",
617 command: "definitely-not-a-t3code-executable",
618 args: [secretArgument],
619 cwd: process.cwd(),
620 }).pipe(Effect.flip);
621
622 expect(error).toBeInstanceOf(VcsProcessSpawnError);
623 expect(error).toMatchObject({
624 operation: "test.spawn",
625 command: "definitely-not-a-t3code-executable",
626 argumentCount: 1,
627 });
628 expect(error).toHaveProperty("cause");
629 expect(error.message).not.toContain(secretArgument);
630 }).pipe(provideLive),
631 );
632
633 it.effect("preserves real boundary causes without manufacturing structural ones", () =>
634 Effect.gen(function* () {
635 const cause = new Error("secret stdin failure");
636 const error = yield* captureProcessResult(
637 Effect.fail(
638 new ProcessRunner.ProcessStdinError({
639 command: baseInput.command,
640 argumentCount: baseInput.args.length,
641 cwd: baseInput.cwd,
642 stdinBytes: 47,
643 cause,
644 }),
645 ),
646 );
647
648 expect(error).toMatchObject({
649 _tag: "VcsProcessStdinWriteError",
650 operation: baseInput.operation,
651 stdinBytes: 47,
652 cause,
653 });
654 expect(error.message).not.toContain(cause.message);
655
656 const missingExitCodeError = yield* captureProcessResult(
657 Effect.succeed({
658 stdout: "",
659 stderr: "",
660 code: null,
661 timedOut: false,
662 stdoutTruncated: false,
663 stderrTruncated: false,
664 stdoutInvalidUtf8: false,
665 stderrInvalidUtf8: false,
666 }),
667 );
668
669 expect(missingExitCodeError).toMatchObject({
670 _tag: "VcsProcessMissingExitCodeError",
671 operation: baseInput.operation,
672 command: baseInput.command,
673 cwd: baseInput.cwd,
674 argumentCount: baseInput.args.length,
675 });
676 expect(missingExitCodeError).not.toHaveProperty("cause");
677 }),
678 );
679
680 it.effect("returns output when non-zero exits are allowed", () =>
681 Effect.gen(function* () {
682 const result = yield* run({
683 operation: "test.allowed-exit",
684 command: "node",
685 args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
686 cwd: process.cwd(),
687 allowNonZeroExit: true,
688 });
689
690 expect(result.exitCode).toBe(2);
691 expect(result.stderr).toBe("boom");
692 }).pipe(provideLive),
693 );
694
695 it.effect("truncates output and appends the marker when requested", () =>
696 Effect.gen(function* () {
697 const result = yield* run({
698 operation: "test.truncate-marker",
699 command: "node",
700 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
701 cwd: process.cwd(),
702 maxOutputBytes: 128,
703 appendTruncationMarker: true,
704 });
705
706 expect(result.stdoutTruncated).toBe(true);
707 expect(result.stdout).toContain("[truncated]");
708 expect(result.stderrTruncated).toBe(false);
709 }).pipe(provideLive),
710 );
711
712 it.effect("truncates without the marker when truncation markers are disabled", () =>
713 Effect.gen(function* () {
714 const result = yield* run({
715 operation: "test.truncate-silent",
716 command: "node",
717 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
718 cwd: process.cwd(),
719 maxOutputBytes: 128,
720 });
721
722 expect(result.stdoutTruncated).toBe(true);
723 expect(result.stdout).not.toContain("[truncated]");
724 }).pipe(provideLive),
725 );
726
727 it.effect("fails with measured byte counts when output must not be truncated", () =>
728 Effect.gen(function* () {
729 const error = yield* run({
730 operation: "test.output-limit",
731 command: "node",
732 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
733 cwd: yield* HostProcess.WorkingDirectory,
734 maxOutputBytes: 128,
735 outputMode: "error",
736 }).pipe(Effect.flip);
737
738 assert(error._tag === "VcsProcessOutputLimitError");
739 expect(error.stream).toBe("stdout");
740 expect(error.maxBytes).toBe(128);
741 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
742 }).pipe(provideLive),
743 );
744
745 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
746 Effect.gen(function* () {
747 const chunks: Uint8Array[] = [];
748 const result = yield* run({
749 operation: "test.stream-output",
750 command: "node",
751 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
752 cwd: process.cwd(),
753 maxOutputBytes: 8,
754 onStdoutChunk: (chunk) => chunks.push(chunk),
755 });
756
757 expect(result.stdout).toBe("xxxxxxxx");
758 expect(result.stdoutTruncated).toBe(true);
759 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
760 }).pipe(provideLive),
761 );
762
763 it.effect("fails with VcsProcessTimeoutError on timeout", () =>
764 Effect.gen(function* () {
765 const errorFiber = yield* run({
766 operation: "test.timeout",
767 command: "node",
768 args: ["-e", "setTimeout(() => {}, 5000)"],
769 cwd: process.cwd(),
770 timeoutMs: 50,
771 }).pipe(Effect.flip, Effect.forkScoped);
772 yield* Effect.yieldNow;
773 yield* TestClock.adjust(Duration.millis(50));
774 const error = yield* Fiber.join(errorFiber);
775
776 expect(error).toBeInstanceOf(VcsProcessTimeoutError);
777 }).pipe(provideLive),
778 );
779});