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 ] as const)(
188 "falls back to writeout-only only for unsupported fsync on macOS: $stderr",
189 ({ stderr, fsyncMethods, ...scenario }) =>
190 Effect.gen(function* () {
191 const seen: Array<ReadonlyArray<string>> = [];
192 const service = yield* VcsProcess.make.pipe(
193 Effect.provideService(
194 HostProcess.Platform,
195 "platform" in scenario ? scenario.platform : "darwin",
196 ),
197 Effect.provideService(ProcessRunner.ProcessRunner, {
198 run: (input) =>
199 Effect.sync(() => {
200 seen.push(input.args);
201 const failed =
202 input.args.includes("core.fsyncMethod=fsync") ||
203 ("fallbackFails" in scenario && scenario.fallbackFails);
204 return {
205 stdout: "",
206 stderr: failed ? stderr : "",
207 code: ChildProcessSpawner.ExitCode(failed ? 128 : 0),
208 timedOut: false,
209 stdoutTruncated: false,
210 stderrTruncated: false,
211 stdoutInvalidUtf8: false,
212 stderrInvalidUtf8: false,
213 };
214 }),
215 }),
216 );
217 const exit = yield* service
218 .run({
219 ...baseInput,
220 operation:
221 "operation" in scenario
222 ? scenario.operation
223 : VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
224 args: ["-c", "core.fsync=objects,reference", "-c", "core.fsyncMethod=fsync", "add"],
225 })
226 .pipe(Effect.exit);
227 expect(seen).toEqual(
228 fsyncMethods.map((method) => [
229 "-c",
230 "core.fsync=objects,reference",
231 "-c",
232 `core.fsyncMethod=${method}`,
233 "add",
234 ]),
235 );
236 expect(Exit.isSuccess(exit)).toBe(
237 fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails),
238 );
239 if (Exit.isFailure(exit)) {
240 expect(Cause.findErrorOption(exit.cause)).toMatchObject({
241 _tag: "Some",
242 value: { _tag: "VcsProcessExitError", exitCode: 128 },
243 });
244 }
245 }),
246 );
247
248 it.effect.each(["timeout", "spawn"] as const)(
249 "checkpoint commands do not retry %s failures",
250 (kind) =>
251 Effect.gen(function* () {
252 let attempts = 0;
253 const fields = { command: "git", argumentCount: 2, cwd: "/workspace" };
254 const failure =
255 kind === "timeout"
256 ? new ProcessRunner.ProcessTimeoutError({ ...fields, timeoutMs: 30_000 })
257 : new ProcessRunner.ProcessSpawnError({ ...fields, cause: new Error("spawn failed") });
258 const service = yield* VcsProcess.make.pipe(
259 Effect.provideService(ProcessRunner.ProcessRunner, {
260 run: () =>
261 Effect.sync(() => {
262 attempts += 1;
263 }).pipe(Effect.andThen(Effect.fail(failure))),
264 }),
265 );
266 const error = yield* service
267 .run({
268 ...baseInput,
269 operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
270 })
271 .pipe(Effect.flip);
272 expect(attempts).toBe(1);
273 expect(error._tag).toBe(
274 kind === "timeout" ? "VcsProcessTimeoutError" : "VcsProcessSpawnError",
275 );
276 }),
277 );
278
279 it.effect.each([
280 {
281 name: "recovers after two lock failures",
282 failures: 2,
283 attempts: 3,
284 transient: true,
285 capture: true,
286 streaming: false,
287 },
288 {
289 name: "bounds persistent lock failures",
290 failures: Infinity,
291 attempts: 3,
292 transient: true,
293 capture: true,
294 streaming: false,
295 },
296 {
297 name: "does not retry unknown exits",
298 failures: Infinity,
299 attempts: 1,
300 transient: false,
301 capture: true,
302 streaming: false,
303 },
304 {
305 name: "leaves other operations unchanged",
306 failures: Infinity,
307 attempts: 1,
308 transient: true,
309 capture: false,
310 streaming: false,
311 },
312 {
313 name: "does not replay stdout callbacks",
314 failures: Infinity,
315 attempts: 1,
316 transient: true,
317 capture: true,
318 streaming: true,
319 },
320 ])(
321 "checkpoint command retry $name",
322 ({ failures, attempts: expectedAttempts, transient, capture, streaming }) =>
323 Effect.gen(function* () {
324 let attempts = 0;
325 const service = yield* VcsProcess.make.pipe(
326 Effect.provideService(ProcessRunner.ProcessRunner, {
327 run: () =>
328 Effect.sync(() => {
329 attempts += 1;
330 return {
331 stdout: "",
332 stderr:
333 attempts > failures
334 ? ""
335 : transient
336 ? "fatal: Unable to create '/repo/index.lock': File exists"
337 : "fatal: index file corrupt",
338 code: ChildProcessSpawner.ExitCode(attempts > failures ? 0 : attempts),
339 timedOut: false,
340 stdoutTruncated: false,
341 stderrTruncated: false,
342 stdoutInvalidUtf8: false,
343 stderrInvalidUtf8: false,
344 };
345 }),
346 }),
347 );
348 const fiber = yield* service
349 .run({
350 ...baseInput,
351 operation: capture ? VcsProcess.CHECKPOINT_CAPTURE_OPERATION : baseInput.operation,
352 ...(streaming ? { onStdoutChunk: () => {} } : {}),
353 })
354 .pipe(Effect.exit, Effect.forkScoped);
355 yield* TestClock.adjust("150 millis");
356 const result = yield* Fiber.join(fiber);
357 expect(attempts).toBe(expectedAttempts);
358 if (failures === Infinity) {
359 if (Exit.isSuccess(result))
360 return yield* Effect.die("Expected a capture command failure");
361 const error = Cause.findErrorOption(result.cause);
362 if (error._tag === "None" || error.value._tag !== "VcsProcessExitError") {
363 return yield* Effect.die("Expected a Git exit error");
364 }
365 expect(error.value.exitCode).toBe(expectedAttempts);
366 } else {
367 expect(Exit.isSuccess(result)).toBe(true);
368 }
369 }),
370 );
371
372 it.effect("bounds a synthetic burst of GitHub API processes", () =>
373 Effect.gen(function* () {
374 const gate = yield* Deferred.make<void>();
375 const starts = yield* Queue.unbounded<number>();
376 const active = yield* Ref.make(0);
377 const peak = yield* Ref.make(0);
378 const total = yield* Ref.make(0);
379 const service = yield* VcsProcess.make.pipe(
380 Effect.provideService(
381 ProcessRunner.ProcessRunner,
382 ProcessRunner.ProcessRunner.of({
383 run: () =>
384 Effect.gen(function* () {
385 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
386 yield* Ref.update(peak, (held) => Math.max(held, count));
387 yield* Ref.update(total, (held) => held + 1);
388 yield* Queue.offer(starts, count);
389 yield* Deferred.await(gate);
390 return {
391 stdout: "",
392 stderr: "",
393 code: ChildProcessSpawner.ExitCode(0),
394 timedOut: false,
395 stdoutTruncated: false,
396 stderrTruncated: false,
397 stdoutInvalidUtf8: false,
398 stderrInvalidUtf8: false,
399 };
400 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
401 }),
402 ),
403 );
404
405 const burst = yield* Effect.all(
406 Array.from({ length: 32 }, (_, index) =>
407 service.run({
408 operation: `synthetic.github.${index}`,
409 command: "gh",
410 args: ["api", "user"],
411 cwd: "/workspace",
412 }),
413 ),
414 { concurrency: "unbounded" },
415 ).pipe(Effect.forkChild);
416
417 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
418 yield* Effect.yieldNow;
419 expect(yield* Queue.size(starts)).toBe(0);
420 expect(yield* Ref.get(peak)).toBe(4);
421
422 yield* Deferred.succeed(gate, undefined);
423 yield* Fiber.join(burst);
424 expect(yield* Ref.get(total)).toBe(32);
425 expect(yield* Ref.get(peak)).toBe(4);
426 }),
427 );
428
429 it.effect("collects stdout", () =>
430 Effect.gen(function* () {
431 const result = yield* run({
432 operation: "test.stdout",
433 command: "node",
434 args: ["-e", "process.stdout.write('hello')"],
435 cwd: process.cwd(),
436 });
437
438 expect(result.stdout).toBe("hello");
439 expect(result.stderr).toBe("");
440 expect(result.stdoutTruncated).toBe(false);
441 expect(result.stderrTruncated).toBe(false);
442 }).pipe(provideLive),
443 );
444
445 it.effect("keeps git from opening a folder laid out as a bare repository", () =>
446 Effect.gen(function* () {
447 const fileSystem = yield* FileSystem.FileSystem;
448 const path = yield* Path.Path;
449 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
450 yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
451 yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
452 yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
453 yield* fileSystem.writeFileString(
454 path.join(cwd, "config"),
455 '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
456 );
457
458 const result = yield* run({
459 operation: "test.bare-repository",
460 command: "git",
461 args: ["status"],
462 cwd,
463 allowNonZeroExit: true,
464 });
465
466 expect(result.exitCode).not.toBe(0);
467 expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
468 }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
469 );
470
471 it.effect("writes stdin before waiting for exit", () =>
472 Effect.gen(function* () {
473 const result = yield* run({
474 operation: "test.stdin",
475 command: "node",
476 args: [
477 "-e",
478 [
479 "process.stdin.setEncoding('utf8');",
480 "let data='';",
481 "process.stdin.on('data', chunk => { data += chunk; });",
482 "process.stdin.on('end', () => { process.stdout.write(data); });",
483 ].join(""),
484 ],
485 cwd: process.cwd(),
486 stdin: "stdin payload",
487 });
488
489 expect(result.stdout).toBe("stdin payload");
490 }).pipe(provideLive),
491 );
492
493 it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
494 Effect.gen(function* () {
495 const secretArgument = "--token=super-secret-token";
496 const secretStderr = "remote rejected super-secret-token";
497 const error = yield* run({
498 operation: "test.exit",
499 command: "node",
500 args: [
501 "-e",
502 "process.stderr.write(process.argv[1]); process.exit(2)",
503 secretStderr,
504 secretArgument,
505 ],
506 cwd: process.cwd(),
507 }).pipe(Effect.flip);
508
509 expect(error).toBeInstanceOf(VcsProcessExitError);
510 expect(error).toMatchObject({
511 operation: "test.exit",
512 command: "node",
513 argumentCount: 4,
514 exitCode: 2,
515 detail: "Process exited with a non-zero status.",
516 failureKind: "command-failed",
517 stderrLength: secretStderr.length,
518 stderrTruncated: false,
519 });
520 expect(error.message).not.toContain(secretArgument);
521 expect(error.message).not.toContain(secretStderr);
522 }).pipe(provideLive),
523 );
524
525 it.effect("classifies authentication failures without retaining stderr", () =>
526 Effect.gen(function* () {
527 const secretStderr = "authentication failed for token super-secret-token";
528 const error = yield* run({
529 operation: "test.authentication",
530 command: "node",
531 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
532 cwd: process.cwd(),
533 }).pipe(Effect.flip);
534
535 expect(error).toBeInstanceOf(VcsProcessExitError);
536 expect(error).toMatchObject({
537 operation: "test.authentication",
538 command: "node",
539 exitCode: 1,
540 detail: "Authentication failed.",
541 failureKind: "authentication",
542 stderrLength: secretStderr.length,
543 stderrTruncated: false,
544 });
545 expect(error.message).not.toContain(secretStderr);
546 expect(error.message).not.toContain("super-secret-token");
547 }).pipe(provideLive),
548 );
549
550 it.effect("classifies API rate limits without retaining provider stderr", () =>
551 Effect.gen(function* () {
552 const providerStderr =
553 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
554 const error = yield* run({
555 operation: "test.rate-limit",
556 command: "node",
557 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
558 cwd: process.cwd(),
559 }).pipe(Effect.flip);
560
561 expect(error).toBeInstanceOf(VcsProcessExitError);
562 expect(error).toMatchObject({
563 command: "node",
564 exitCode: 1,
565 detail: "API rate limit exceeded.",
566 failureKind: "rate-limited",
567 stderrLength: providerStderr.length,
568 stderrTruncated: false,
569 });
570 expect(error.message).not.toContain(providerStderr);
571 expect(error.message).not.toContain("secret-value");
572 }).pipe(provideLive),
573 );
574
575 it.effect("classifies HTTP 429 responses as rate limits", () =>
576 Effect.gen(function* () {
577 const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value";
578 const error = yield* run({
579 operation: "test.rate-limit",
580 command: "node",
581 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
582 cwd: process.cwd(),
583 }).pipe(Effect.flip);
584
585 expect(error).toMatchObject({
586 detail: "API rate limit exceeded.",
587 failureKind: "rate-limited",
588 });
589 expect(error.message).not.toContain(providerStderr);
590 }).pipe(provideLive),
591 );
592
593 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
594 Effect.gen(function* () {
595 const secretArgument = "--token=super-secret-token";
596 const error = yield* run({
597 operation: "test.spawn",
598 command: "definitely-not-a-t3code-executable",
599 args: [secretArgument],
600 cwd: process.cwd(),
601 }).pipe(Effect.flip);
602
603 expect(error).toBeInstanceOf(VcsProcessSpawnError);
604 expect(error).toMatchObject({
605 operation: "test.spawn",
606 command: "definitely-not-a-t3code-executable",
607 argumentCount: 1,
608 });
609 expect(error).toHaveProperty("cause");
610 expect(error.message).not.toContain(secretArgument);
611 }).pipe(provideLive),
612 );
613
614 it.effect("preserves real boundary causes without manufacturing structural ones", () =>
615 Effect.gen(function* () {
616 const cause = new Error("secret stdin failure");
617 const error = yield* captureProcessResult(
618 Effect.fail(
619 new ProcessRunner.ProcessStdinError({
620 command: baseInput.command,
621 argumentCount: baseInput.args.length,
622 cwd: baseInput.cwd,
623 stdinBytes: 47,
624 cause,
625 }),
626 ),
627 );
628
629 expect(error).toMatchObject({
630 _tag: "VcsProcessStdinWriteError",
631 operation: baseInput.operation,
632 stdinBytes: 47,
633 cause,
634 });
635 expect(error.message).not.toContain(cause.message);
636
637 const missingExitCodeError = yield* captureProcessResult(
638 Effect.succeed({
639 stdout: "",
640 stderr: "",
641 code: null,
642 timedOut: false,
643 stdoutTruncated: false,
644 stderrTruncated: false,
645 stdoutInvalidUtf8: false,
646 stderrInvalidUtf8: false,
647 }),
648 );
649
650 expect(missingExitCodeError).toMatchObject({
651 _tag: "VcsProcessMissingExitCodeError",
652 operation: baseInput.operation,
653 command: baseInput.command,
654 cwd: baseInput.cwd,
655 argumentCount: baseInput.args.length,
656 });
657 expect(missingExitCodeError).not.toHaveProperty("cause");
658 }),
659 );
660
661 it.effect("returns output when non-zero exits are allowed", () =>
662 Effect.gen(function* () {
663 const result = yield* run({
664 operation: "test.allowed-exit",
665 command: "node",
666 args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
667 cwd: process.cwd(),
668 allowNonZeroExit: true,
669 });
670
671 expect(result.exitCode).toBe(2);
672 expect(result.stderr).toBe("boom");
673 }).pipe(provideLive),
674 );
675
676 it.effect("truncates output and appends the marker when requested", () =>
677 Effect.gen(function* () {
678 const result = yield* run({
679 operation: "test.truncate-marker",
680 command: "node",
681 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
682 cwd: process.cwd(),
683 maxOutputBytes: 128,
684 appendTruncationMarker: true,
685 });
686
687 expect(result.stdoutTruncated).toBe(true);
688 expect(result.stdout).toContain("[truncated]");
689 expect(result.stderrTruncated).toBe(false);
690 }).pipe(provideLive),
691 );
692
693 it.effect("truncates without the marker when truncation markers are disabled", () =>
694 Effect.gen(function* () {
695 const result = yield* run({
696 operation: "test.truncate-silent",
697 command: "node",
698 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
699 cwd: process.cwd(),
700 maxOutputBytes: 128,
701 });
702
703 expect(result.stdoutTruncated).toBe(true);
704 expect(result.stdout).not.toContain("[truncated]");
705 }).pipe(provideLive),
706 );
707
708 it.effect("fails with measured byte counts when output must not be truncated", () =>
709 Effect.gen(function* () {
710 const error = yield* run({
711 operation: "test.output-limit",
712 command: "node",
713 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
714 cwd: yield* HostProcess.WorkingDirectory,
715 maxOutputBytes: 128,
716 outputMode: "error",
717 }).pipe(Effect.flip);
718
719 assert(error._tag === "VcsProcessOutputLimitError");
720 expect(error.stream).toBe("stdout");
721 expect(error.maxBytes).toBe(128);
722 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
723 }).pipe(provideLive),
724 );
725
726 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
727 Effect.gen(function* () {
728 const chunks: Uint8Array[] = [];
729 const result = yield* run({
730 operation: "test.stream-output",
731 command: "node",
732 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
733 cwd: process.cwd(),
734 maxOutputBytes: 8,
735 onStdoutChunk: (chunk) => chunks.push(chunk),
736 });
737
738 expect(result.stdout).toBe("xxxxxxxx");
739 expect(result.stdoutTruncated).toBe(true);
740 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
741 }).pipe(provideLive),
742 );
743
744 it.effect("fails with VcsProcessTimeoutError on timeout", () =>
745 Effect.gen(function* () {
746 const errorFiber = yield* run({
747 operation: "test.timeout",
748 command: "node",
749 args: ["-e", "setTimeout(() => {}, 5000)"],
750 cwd: process.cwd(),
751 timeoutMs: 50,
752 }).pipe(Effect.flip, Effect.forkScoped);
753 yield* Effect.yieldNow;
754 yield* TestClock.adjust(Duration.millis(50));
755 const error = yield* Fiber.join(errorFiber);
756
757 expect(error).toBeInstanceOf(VcsProcessTimeoutError);
758 }).pipe(provideLive),
759 );
760});