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("writes stdin before waiting for exit", () =>
345 Effect.gen(function* () {
346 const result = yield* run({
347 operation: "test.stdin",
348 command: "node",
349 args: [
350 "-e",
351 [
352 "process.stdin.setEncoding('utf8');",
353 "let data='';",
354 "process.stdin.on('data', chunk => { data += chunk; });",
355 "process.stdin.on('end', () => { process.stdout.write(data); });",
356 ].join(""),
357 ],
358 cwd: process.cwd(),
359 stdin: "stdin payload",
360 });
361
362 expect(result.stdout).toBe("stdin payload");
363 }).pipe(provideLive),
364 );
365
366 it.effect("classifies authentication failures without retaining stderr", () =>
367 Effect.gen(function* () {
368 const secretStderr = "authentication failed for token super-secret-token";
369 const error = yield* run({
370 operation: "test.authentication",
371 command: "node",
372 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
373 cwd: process.cwd(),
374 }).pipe(Effect.flip);
375
376 expect(error).toBeInstanceOf(VcsProcessExitError);
377 expect(error).toMatchObject({
378 operation: "test.authentication",
379 command: "node",
380 exitCode: 1,
381 detail: "Authentication failed.",
382 failureKind: "authentication",
383 stderrLength: secretStderr.length,
384 stderrTruncated: false,
385 });
386 expect(error.message).not.toContain(secretStderr);
387 expect(error.message).not.toContain("super-secret-token");
388 }).pipe(provideLive),
389 );
390
391 it.effect("classifies API rate limits without retaining provider stderr", () =>
392 Effect.gen(function* () {
393 const providerStderr =
394 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
395 const error = yield* run({
396 operation: "test.rate-limit",
397 command: "node",
398 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
399 cwd: process.cwd(),
400 }).pipe(Effect.flip);
401
402 expect(error).toBeInstanceOf(VcsProcessExitError);
403 expect(error).toMatchObject({
404 command: "node",
405 exitCode: 1,
406 detail: "API rate limit exceeded.",
407 failureKind: "rate-limited",
408 stderrLength: providerStderr.length,
409 stderrTruncated: false,
410 });
411 expect(error.message).not.toContain(providerStderr);
412 expect(error.message).not.toContain("secret-value");
413 }).pipe(provideLive),
414 );
415
416 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
417 Effect.gen(function* () {
418 const secretArgument = "--token=super-secret-token";
419 const error = yield* run({
420 operation: "test.spawn",
421 command: "definitely-not-a-t3code-executable",
422 args: [secretArgument],
423 cwd: process.cwd(),
424 }).pipe(Effect.flip);
425
426 expect(error).toBeInstanceOf(VcsProcessSpawnError);
427 expect(error).toMatchObject({
428 operation: "test.spawn",
429 command: "definitely-not-a-t3code-executable",
430 argumentCount: 1,
431 });
432 expect(error).toHaveProperty("cause");
433 expect(error.message).not.toContain(secretArgument);
434 }).pipe(provideLive),
435 );
436
437 it.effect("truncates output and appends the marker when requested", () =>
438 Effect.gen(function* () {
439 const result = yield* run({
440 operation: "test.truncate-marker",
441 command: "node",
442 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
443 cwd: process.cwd(),
444 maxOutputBytes: 128,
445 appendTruncationMarker: true,
446 });
447
448 expect(result.stdoutTruncated).toBe(true);
449 expect(result.stdout).toContain("[truncated]");
450 expect(result.stderrTruncated).toBe(false);
451 }).pipe(provideLive),
452 );
453
454 it.effect("fails with measured byte counts when output must not be truncated", () =>
455 Effect.gen(function* () {
456 const error = yield* run({
457 operation: "test.output-limit",
458 command: "node",
459 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
460 cwd: yield* HostProcess.WorkingDirectory,
461 maxOutputBytes: 128,
462 outputMode: "error",
463 }).pipe(Effect.flip);
464
465 assert(error._tag === "VcsProcessOutputLimitError");
466 expect(error.stream).toBe("stdout");
467 expect(error.maxBytes).toBe(128);
468 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
469 }).pipe(provideLive),
470 );
471
472 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
473 Effect.gen(function* () {
474 const chunks: Uint8Array[] = [];
475 const result = yield* run({
476 operation: "test.stream-output",
477 command: "node",
478 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
479 cwd: process.cwd(),
480 maxOutputBytes: 8,
481 onStdoutChunk: (chunk) => chunks.push(chunk),
482 });
483
484 expect(result.stdout).toBe("xxxxxxxx");
485 expect(result.stdoutTruncated).toBe(true);
486 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
487 }).pipe(provideLive),
488 );
489});