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 burst of processes that share a concurrency key", () =>
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.cli.${index}`,
298 command: "host-cli",
299 args: ["api", "user"],
300 cwd: "/workspace",
301 concurrency: { key: "host-cli", limit: 4 },
302 }),
303 ),
304 { concurrency: "unbounded" },
305 ).pipe(Effect.forkChild);
306
307 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
308 yield* Effect.yieldNow;
309 expect(yield* Queue.size(starts)).toBe(0);
310 expect(yield* Ref.get(peak)).toBe(4);
311
312 yield* Deferred.succeed(gate, undefined);
313 yield* Fiber.join(burst);
314 expect(yield* Ref.get(total)).toBe(32);
315 expect(yield* Ref.get(peak)).toBe(4);
316 }),
317 );
318
319 it.effect("keeps git from opening a folder laid out as a bare repository", () =>
320 Effect.gen(function* () {
321 const fileSystem = yield* FileSystem.FileSystem;
322 const path = yield* Path.Path;
323 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
324 yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
325 yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
326 yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
327 yield* fileSystem.writeFileString(
328 path.join(cwd, "config"),
329 '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
330 );
331
332 const result = yield* run({
333 operation: "test.bare-repository",
334 command: "git",
335 args: ["status"],
336 cwd,
337 allowNonZeroExit: true,
338 });
339
340 expect(result.exitCode).not.toBe(0);
341 expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
342 }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
343 );
344
345 it.effect("classifies authentication failures without retaining stderr", () =>
346 Effect.gen(function* () {
347 const secretStderr = "authentication failed for token super-secret-token";
348 const error = yield* run({
349 operation: "test.authentication",
350 command: "node",
351 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
352 cwd: process.cwd(),
353 }).pipe(Effect.flip);
354
355 expect(error).toBeInstanceOf(VcsProcessExitError);
356 expect(error).toMatchObject({
357 operation: "test.authentication",
358 command: "node",
359 exitCode: 1,
360 detail: "Authentication failed.",
361 failureKind: "authentication",
362 stderrLength: secretStderr.length,
363 stderrTruncated: false,
364 });
365 expect(error.message).not.toContain(secretStderr);
366 expect(error.message).not.toContain("super-secret-token");
367 }).pipe(provideLive),
368 );
369
370 it.effect("classifies API rate limits without retaining provider stderr", () =>
371 Effect.gen(function* () {
372 const providerStderr =
373 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
374 const error = yield* run({
375 operation: "test.rate-limit",
376 command: "node",
377 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
378 cwd: process.cwd(),
379 }).pipe(Effect.flip);
380
381 expect(error).toBeInstanceOf(VcsProcessExitError);
382 expect(error).toMatchObject({
383 command: "node",
384 exitCode: 1,
385 detail: "API rate limit exceeded.",
386 failureKind: "rate-limited",
387 stderrLength: providerStderr.length,
388 stderrTruncated: false,
389 });
390 expect(error.message).not.toContain(providerStderr);
391 expect(error.message).not.toContain("secret-value");
392 }).pipe(provideLive),
393 );
394
395 it.effect("reads a failure with the command's own classifier and names it in its terms", () =>
396 Effect.gen(function* () {
397 const fail = (input: Partial<VcsProcess.VcsProcessInput>) =>
398 run({
399 operation: "test.classify",
400 command: "node",
401 args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"],
402 cwd: process.cwd(),
403 ...input,
404 }).pipe(Effect.flip);
405
406 expect(yield* fail({})).toMatchObject({
407 failureKind: "command-failed",
408 detail: "Process exited with a non-zero status.",
409 });
410 expect(
411 yield* fail({
412 classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null),
413 notFoundDetail: "Merge request not found.",
414 }),
415 ).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." });
416 }).pipe(provideLive),
417 );
418
419 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
420 Effect.gen(function* () {
421 const secretArgument = "--token=super-secret-token";
422 const error = yield* run({
423 operation: "test.spawn",
424 command: "definitely-not-a-t3code-executable",
425 args: [secretArgument],
426 cwd: process.cwd(),
427 }).pipe(Effect.flip);
428
429 expect(error).toBeInstanceOf(VcsProcessSpawnError);
430 expect(error).toMatchObject({
431 operation: "test.spawn",
432 command: "definitely-not-a-t3code-executable",
433 argumentCount: 1,
434 });
435 expect(error).toHaveProperty("cause");
436 expect(error.message).not.toContain(secretArgument);
437 }).pipe(provideLive),
438 );
439
440 it.effect("truncates output and appends the marker when requested", () =>
441 Effect.gen(function* () {
442 const result = yield* run({
443 operation: "test.truncate-marker",
444 command: "node",
445 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
446 cwd: process.cwd(),
447 maxOutputBytes: 128,
448 appendTruncationMarker: true,
449 });
450
451 expect(result.stdoutTruncated).toBe(true);
452 expect(result.stdout).toContain("[truncated]");
453 expect(result.stderrTruncated).toBe(false);
454 }).pipe(provideLive),
455 );
456
457 it.effect("fails with measured byte counts when output must not be truncated", () =>
458 Effect.gen(function* () {
459 const error = yield* run({
460 operation: "test.output-limit",
461 command: "node",
462 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
463 cwd: yield* HostProcess.WorkingDirectory,
464 maxOutputBytes: 128,
465 outputMode: "error",
466 }).pipe(Effect.flip);
467
468 assert(error._tag === "VcsProcessOutputLimitError");
469 expect(error.stream).toBe("stdout");
470 expect(error.maxBytes).toBe(128);
471 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
472 }).pipe(provideLive),
473 );
474
475 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
476 Effect.gen(function* () {
477 const chunks: Uint8Array[] = [];
478 const result = yield* run({
479 operation: "test.stream-output",
480 command: "node",
481 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
482 cwd: process.cwd(),
483 maxOutputBytes: 8,
484 onStdoutChunk: (chunk) => chunks.push(chunk),
485 });
486
487 expect(result.stdout).toBe("xxxxxxxx");
488 expect(result.stdoutTruncated).toBe(true);
489 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
490 }).pipe(provideLive),
491 );
492});