Open History to see the last commit
1import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
2import * as Cache from "effect/Cache";
3import * as TestClock from "effect/testing/TestClock";
4import * as Clock from "effect/Clock";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as PlatformError from "effect/PlatformError";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import { ChildProcessSpawner } from "effect/unstable/process";
12import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
13
14import * as VcsProcess from "../vcs/VcsProcess.ts";
15import * as GitHubCli from "./GitHubCli.ts";
16import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
17import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
18
19const encodeGitHubCliError = Schema.encodeEffect(Schema.fromJsonString(GitHubCli.GitHubCliError));
20
21const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
22 exitCode: ChildProcessSpawner.ExitCode(0),
23 stdout,
24 stderr: "",
25 stdoutTruncated: false,
26 stderrTruncated: false,
27});
28
29const quotaOutput = (remaining = 5000, resetAt = "2099-01-01T00:00:00Z") =>
30 processOutput(
31 JSON.stringify({ data: { rateLimit: { cost: 1, limit: 5000, remaining, resetAt } } }),
32 );
33
34const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
35
36const layer = GitHubCli.layer.pipe(
37 Layer.provide(
38 Layer.mock(VcsProcess.VcsProcess)({
39 run: (input) =>
40 input.args[1] === "rate_limit" ? Effect.succeed(quotaOutput()) : mockRun(input),
41 }),
42 ),
43);
44
45afterEach(() => {
46 mockRun.mockReset();
47});
48
49it.effect("shares quota checks, preserves the reserve, and resumes after reset", () =>
50 Effect.gen(function* () {
51 let probes = 0;
52 const commands: string[] = [];
53 let remaining = 501;
54 let resetAt = DateTime.formatIso(
55 DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000),
56 );
57 const gh = yield* GitHubCli.make.pipe(
58 Effect.provideService(VcsProcess.VcsProcess, {
59 run: (input) =>
60 Effect.sync(() => {
61 if (input.args[1] === "rate_limit") {
62 probes++;
63 assert.strictEqual(input.args[3], "enterprise.test");
64 return quotaOutput(remaining, resetAt);
65 }
66 commands.push(input.args.slice(0, 2).join(" "));
67 return processOutput("[]");
68 }),
69 }),
70 );
71 const read = (command: string) =>
72 gh.execute({
73 cwd: "/repo",
74 args:
75 command === "repo"
76 ? ["repo", "view", "enterprise.test/acme/web", "--json", "name"]
77 : ["pr", command, "--repo=enterprise.test/acme/web", "--json", "number"],
78 });
79 yield* read("list");
80 const failure = yield* read("view").pipe(Effect.flip);
81 assert.strictEqual(failure._tag, "GitHubCliRateLimitError");
82 assert.strictEqual(probes, 1);
83 assert.deepStrictEqual(commands, ["pr list"]);
84 yield* read("view").pipe(Effect.provideService(GitHubCli.AllowGitHubReserve, true));
85 yield* gh.execute({ cwd: "/repo", args: ["pr", "merge", "1"] });
86 assert.deepStrictEqual(commands, ["pr list", "pr view", "pr merge"]);
87 remaining = 0;
88 yield* TestClock.adjust("30 seconds");
89 yield* read("repo").pipe(Effect.flip);
90 assert.strictEqual(probes, 2);
91 yield* TestClock.adjust("30 seconds");
92 remaining = 5000;
93 resetAt = DateTime.formatIso(DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000));
94 yield* Effect.all([read("list"), read("repo")], { concurrency: 2 });
95 assert.strictEqual(probes, 3);
96 assert.deepStrictEqual(commands.slice(3).toSorted(), ["pr list", "repo view"]);
97 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
98);
99
100describe("GitHubCli.layer", () => {
101 it.effect("shares the registry budget with CLI reads through nested layer providers", () =>
102 Effect.gen(function* () {
103 const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
104 const gh = yield* GitHubCli.GitHubCli;
105 yield* budget.observe("github.com", quotaOutput(0).stdout);
106 const error = yield* gh.execute({ cwd: "/repo", args: ["pr", "list"] }).pipe(Effect.flip);
107 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
108 expect(mockRun).not.toHaveBeenCalled();
109 }).pipe(Effect.provide(layer.pipe(Layer.provide(GitHubGraphQlBudget.layer)))),
110 );
111
112 it.effect("keeps quota snapshots separate for verified credentials on the same host", () =>
113 Effect.gen(function* () {
114 let reads = 0;
115 const gh = yield* GitHubCli.make.pipe(
116 Effect.provideService(VcsProcess.VcsProcess, {
117 run: (input) =>
118 Effect.sync(() => {
119 if (input.args[1] === "rate_limit")
120 return quotaOutput(input.env?.GH_TOKEN === "empty" ? 0 : 5000);
121 reads++;
122 return processOutput("[]");
123 }),
124 }),
125 );
126 const read = (token: string) =>
127 gh.execute({ cwd: "/repo", args: ["pr", "list", "--repo", "github.com/acme/web"] }).pipe(
128 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
129 host: "github.com",
130 token: Redacted.make(token),
131 credentialFingerprint: token,
132 }),
133 );
134 yield* read("empty").pipe(Effect.flip);
135 yield* read("healthy");
136 yield* read("empty").pipe(Effect.flip);
137 assert.strictEqual(reads, 1);
138 }).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
139 );
140
141 it.effect("pins concurrent cached commands to their own verified credentials", () =>
142 Effect.gen(function* () {
143 mockRun.mockImplementation((input) =>
144 Effect.succeed(processOutput(input.env?.GH_TOKEN ?? "ambient")),
145 );
146 const gh = yield* GitHubCli.GitHubCli;
147 // Constructed outside either request, like the PR service's read caches.
148 const cache = yield* Cache.make({
149 lookup: (host: string) =>
150 gh.execute({
151 cwd: "/repo",
152 args: ["api", "user", "--hostname", host],
153 env: { GH_DEBUG: "api", GH_TOKEN: "changed-after-verification" },
154 }),
155 capacity: 2,
156 timeToLive: "1 minute",
157 });
158 const results = yield* Effect.forEach(
159 ["github.com", "github.example.test"],
160 (host, index) =>
161 Cache.get(cache, host).pipe(
162 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
163 host,
164 token: Redacted.make(`credential-${index}`),
165 credentialFingerprint: `fingerprint-${index}`,
166 }),
167 ),
168 { concurrency: 2 },
169 );
170 expect(results.map((result) => result.stdout)).toEqual(["credential-0", "credential-1"]);
171 for (const [input] of mockRun.mock.calls) {
172 expect(input.env).toMatchObject({
173 GH_HOST: input.args[3],
174 GH_DEBUG: "",
175 GH_TOKEN: input.env?.GITHUB_TOKEN,
176 GH_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
177 GITHUB_ENTERPRISE_TOKEN: input.env?.GH_TOKEN,
178 });
179 }
180 expect((yield* gh.execute({ cwd: "/repo", args: ["api", "user"] })).stdout).toBe("ambient");
181 }).pipe(Effect.provide(layer)),
182 );
183
184 it.effect("refuses other or implicit hosts before exposing a scoped credential to gh", () =>
185 Effect.gen(function* () {
186 const gh = yield* GitHubCli.GitHubCli;
187 for (const args of [
188 ["api", "user", "--hostname", "other.example.test"],
189 ["api", "user", "--hostname=other.example.test"],
190 ["pr", "view", "1", "--repo", "other.example.test/owner/repo"],
191 ["repo", "view", "other.example.test/owner/repo", "--json", "name"],
192 ["api", "https://other.example.test/user", "--hostname", "github.com"],
193 ["api", "user"],
194 ]) {
195 const failure = yield* gh.execute({ cwd: "/repo", args }).pipe(
196 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
197 host: "github.com",
198 token: Redacted.make("secret-credential"),
199 credentialFingerprint: "fingerprint",
200 }),
201 Effect.flip,
202 );
203 expect(failure._tag).toBe("GitHubCliCommandError");
204 expect(yield* encodeGitHubCliError(failure)).not.toContain("secret-credential");
205 }
206 expect(mockRun).not.toHaveBeenCalled();
207 }).pipe(Effect.provide(layer)),
208 );
209
210 it.effect("pins repository-targeted writes on enterprise hosts", () =>
211 Effect.gen(function* () {
212 mockRun.mockReturnValue(Effect.succeed(processOutput("")));
213 const gh = yield* GitHubCli.GitHubCli;
214 yield* gh
215 .execute({
216 cwd: "/repo",
217 args: ["pr", "merge", "1", "--repo", "github.example.test/owner/repo"],
218 })
219 .pipe(
220 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
221 host: "github.example.test",
222 token: Redacted.make("enterprise-credential"),
223 credentialFingerprint: "fingerprint",
224 }),
225 );
226 yield* gh
227 .execute({
228 cwd: "/repo",
229 args: ["repo", "view", "github.example.test/owner/repo", "--json", "name"],
230 })
231 .pipe(
232 Effect.provideService(GitHubCli.PinnedGitHubCredential, {
233 host: "github.example.test",
234 token: Redacted.make("enterprise-credential"),
235 credentialFingerprint: "fingerprint",
236 }),
237 );
238 expect(mockRun.mock.calls[0]?.[0].env).toMatchObject({
239 GH_HOST: "github.example.test",
240 GH_ENTERPRISE_TOKEN: "enterprise-credential",
241 GH_DEBUG: "",
242 });
243 }).pipe(Effect.provide(layer)),
244 );
245
246 it("does not classify a missing cwd as an unavailable gh executable", () => {
247 const context = { command: "gh", cwd: "/repo" } as const;
248 const missingCwd = new VcsProcessSpawnError({
249 operation: "GitHubCli.execute",
250 command: "gh",
251 cwd: context.cwd,
252 cause: PlatformError.systemError({
253 _tag: "NotFound",
254 module: "FileSystem",
255 method: "access",
256 pathOrDescriptor: context.cwd,
257 }),
258 });
259
260 const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
261
262 assert.equal(commandFailure._tag, "GitHubCliCommandError");
263 assert.strictEqual(commandFailure.cause, missingCwd);
264 assert.notProperty(commandFailure, "operation");
265 });
266
267 it.effect("parses pull request view output", () =>
268 Effect.gen(function* () {
269 mockRun.mockReturnValueOnce(
270 Effect.succeed(
271 processOutput(
272 // @effect-diagnostics-next-line preferSchemaOverJson:off
273 JSON.stringify({
274 number: 42,
275 title: "Add PR thread creation",
276 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
277 baseRefName: "main",
278 headRefName: "feature/pr-threads",
279 state: "OPEN",
280 isDraft: true,
281 mergedAt: null,
282 updatedAt: "2026-08-24T12:34:56Z",
283 isCrossRepository: true,
284 headRepository: {
285 nameWithOwner: "octocat/codething-mvp",
286 },
287 headRepositoryOwner: {
288 login: "octocat",
289 },
290 }),
291 ),
292 ),
293 );
294
295 const gh = yield* GitHubCli.GitHubCli;
296 const result = yield* gh.getPullRequest({
297 cwd: "/repo",
298 reference: "#42",
299 });
300
301 assert.deepStrictEqual(result, {
302 number: 42,
303 title: "Add PR thread creation",
304 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
305 baseRefName: "main",
306 headRefName: "feature/pr-threads",
307 state: "open",
308 closedAt: null,
309 mergedAt: null,
310 isDraft: true,
311 updatedAt: "2026-08-24T12:34:56.000Z",
312 isCrossRepository: true,
313 headRepositoryNameWithOwner: "octocat/codething-mvp",
314 headRepositoryOwnerLogin: "octocat",
315 });
316 expect(mockRun).toHaveBeenCalledWith({
317 operation: "GitHubCli.execute",
318 command: "gh",
319 args: [
320 "pr",
321 "view",
322 "#42",
323 "--json",
324 "number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
325 ],
326 cwd: "/repo",
327 timeoutMs: 30_000,
328 });
329 }).pipe(Effect.provide(layer)),
330 );
331
332 it.effect("trims pull request fields decoded from gh json", () =>
333 Effect.gen(function* () {
334 mockRun.mockReturnValueOnce(
335 Effect.succeed(
336 processOutput(
337 // @effect-diagnostics-next-line preferSchemaOverJson:off
338 JSON.stringify({
339 number: 42,
340 title: " Add PR thread creation \n",
341 url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
342 baseRefName: " main ",
343 headRefName: "\tfeature/pr-threads\t",
344 state: "OPEN",
345 mergedAt: null,
346 isCrossRepository: true,
347 headRepository: {
348 nameWithOwner: " octocat/codething-mvp ",
349 },
350 headRepositoryOwner: {
351 login: " octocat ",
352 },
353 }),
354 ),
355 ),
356 );
357
358 const gh = yield* GitHubCli.GitHubCli;
359 const result = yield* gh.getPullRequest({
360 cwd: "/repo",
361 reference: "#42",
362 });
363
364 assert.deepStrictEqual(result, {
365 number: 42,
366 title: "Add PR thread creation",
367 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
368 baseRefName: "main",
369 headRefName: "feature/pr-threads",
370 state: "open",
371 closedAt: null,
372 mergedAt: null,
373 isCrossRepository: true,
374 headRepositoryNameWithOwner: "octocat/codething-mvp",
375 headRepositoryOwnerLogin: "octocat",
376 });
377 }).pipe(Effect.provide(layer)),
378 );
379
380 it.effect("skips invalid entries when parsing pr lists", () =>
381 Effect.gen(function* () {
382 mockRun.mockReturnValueOnce(
383 Effect.succeed(
384 processOutput(
385 // @effect-diagnostics-next-line preferSchemaOverJson:off
386 JSON.stringify([
387 {
388 number: 0,
389 title: "invalid",
390 url: "https://github.com/pingdotgg/codething-mvp/pull/0",
391 baseRefName: "main",
392 headRefName: "feature/invalid",
393 },
394 {
395 number: 43,
396 title: " Valid PR ",
397 url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
398 baseRefName: " main ",
399 headRefName: " feature/pr-list ",
400 headRepository: {
401 nameWithOwner: " ",
402 },
403 headRepositoryOwner: {
404 login: " ",
405 },
406 },
407 ]),
408 ),
409 ),
410 );
411
412 const gh = yield* GitHubCli.GitHubCli;
413 const result = yield* gh.listOpenPullRequests({
414 cwd: "/repo",
415 headSelector: "feature/pr-list",
416 });
417
418 assert.deepStrictEqual(result, [
419 {
420 number: 43,
421 title: "Valid PR",
422 url: "https://github.com/pingdotgg/codething-mvp/pull/43",
423 baseRefName: "main",
424 headRefName: "feature/pr-list",
425 state: "open",
426 closedAt: null,
427 mergedAt: null,
428 },
429 ]);
430 }).pipe(Effect.provide(layer)),
431 );
432
433 it.effect("keeps pull requests from gh versions without headRepository.nameWithOwner", () =>
434 // gh < 2.47 (e.g. Ubuntu-packaged 2.46) exports headRepository as
435 // {id, name} only. These entries must decode instead of being dropped,
436 // with nameWithOwner rebuilt from the owner login.
437 Effect.gen(function* () {
438 mockRun.mockReturnValueOnce(
439 Effect.succeed(
440 processOutput(
441 // @effect-diagnostics-next-line preferSchemaOverJson:off
442 JSON.stringify([
443 {
444 number: 2829,
445 title: "Codex turn mapping",
446 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
447 baseRefName: "main",
448 headRefName: "t3code/codex-turn-mapping",
449 state: "OPEN",
450 mergedAt: null,
451 isCrossRepository: false,
452 headRepository: {
453 id: "R_kgDORLtfbQ",
454 name: "codething-mvp",
455 },
456 headRepositoryOwner: {
457 id: "MDEyOk9yZ2FuaXphdGlvbjg5MTkxNzI3",
458 login: "pingdotgg",
459 },
460 },
461 ]),
462 ),
463 ),
464 );
465
466 const gh = yield* GitHubCli.GitHubCli;
467 const result = yield* gh.listOpenPullRequests({
468 cwd: "/repo",
469 headSelector: "t3code/codex-turn-mapping",
470 });
471
472 assert.deepStrictEqual(result, [
473 {
474 number: 2829,
475 title: "Codex turn mapping",
476 url: "https://github.com/pingdotgg/codething-mvp/pull/2829",
477 baseRefName: "main",
478 headRefName: "t3code/codex-turn-mapping",
479 state: "open",
480 closedAt: null,
481 mergedAt: null,
482 isCrossRepository: false,
483 headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
484 headRepositoryOwnerLogin: "pingdotgg",
485 },
486 ]);
487 }).pipe(Effect.provide(layer)),
488 );
489
490 it.effect("reads repository clone URLs", () =>
491 Effect.gen(function* () {
492 mockRun.mockReturnValueOnce(
493 Effect.succeed(
494 processOutput(
495 // @effect-diagnostics-next-line preferSchemaOverJson:off
496 JSON.stringify({
497 nameWithOwner: "octocat/codething-mvp",
498 url: "https://github.com/octocat/codething-mvp",
499 sshUrl: "git@github.com:octocat/codething-mvp.git",
500 }),
501 ),
502 ),
503 );
504
505 const gh = yield* GitHubCli.GitHubCli;
506 const result = yield* gh.getRepositoryCloneUrls({
507 cwd: "/repo",
508 repository: "octocat/codething-mvp",
509 });
510
511 assert.deepStrictEqual(result, {
512 nameWithOwner: "octocat/codething-mvp",
513 url: "https://github.com/octocat/codething-mvp",
514 sshUrl: "git@github.com:octocat/codething-mvp.git",
515 });
516 }).pipe(Effect.provide(layer)),
517 );
518
519 it.effect("creates repositories and parses clone URLs from create output", () =>
520 Effect.gen(function* () {
521 mockRun.mockReturnValueOnce(
522 Effect.succeed(
523 processOutput(
524 "✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
525 ),
526 ),
527 );
528
529 const gh = yield* GitHubCli.GitHubCli;
530 const result = yield* gh.createRepository({
531 cwd: "/repo",
532 repository: "octocat/codething-mvp",
533 visibility: "private",
534 });
535
536 assert.deepStrictEqual(result, {
537 nameWithOwner: "octocat/codething-mvp",
538 url: "https://github.com/octocat/codething-mvp",
539 sshUrl: "git@github.com:octocat/codething-mvp.git",
540 });
541 expect(mockRun).toHaveBeenCalledTimes(1);
542 expect(mockRun).toHaveBeenNthCalledWith(1, {
543 operation: "GitHubCli.execute",
544 command: "gh",
545 args: ["repo", "create", "octocat/codething-mvp", "--private"],
546 cwd: "/repo",
547 timeoutMs: 30_000,
548 });
549 }).pipe(Effect.provide(layer)),
550 );
551
552 it.effect("falls back to constructed URLs when create output omits a URL", () =>
553 Effect.gen(function* () {
554 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
555
556 const gh = yield* GitHubCli.GitHubCli;
557 const result = yield* gh.createRepository({
558 cwd: "/repo",
559 repository: "octocat/codething-mvp",
560 visibility: "private",
561 });
562
563 assert.deepStrictEqual(result, {
564 nameWithOwner: "octocat/codething-mvp",
565 url: "https://github.com/octocat/codething-mvp",
566 sshUrl: "git@github.com:octocat/codething-mvp.git",
567 });
568 }).pipe(Effect.provide(layer)),
569 );
570
571 it.effect("surfaces a friendly error when the pull request is not found", () =>
572 Effect.gen(function* () {
573 const cause = new VcsProcessExitError({
574 operation: "GitHubCli.execute",
575 command: "gh pr view",
576 cwd: "/repo",
577 exitCode: 1,
578 failureKind: "not-found",
579 detail:
580 "GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
581 });
582 mockRun.mockReturnValueOnce(Effect.fail(cause));
583
584 const gh = yield* GitHubCli.GitHubCli;
585 const error = yield* gh
586 .getPullRequest({
587 cwd: "/repo",
588 reference: "4888",
589 })
590 .pipe(Effect.flip);
591
592 assert.equal(error.message.includes("Pull request not found"), true);
593 assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
594 assert.strictEqual(error.command, "gh");
595 assert.strictEqual(error.cwd, "/repo");
596 assert.strictEqual(error.cause, cause);
597 assert.equal(error.message.includes(cause.detail), false);
598 }).pipe(Effect.provide(layer)),
599 );
600
601 it.effect("surfaces an actionable rate-limit error without exposing provider stderr", () =>
602 Effect.gen(function* () {
603 const cause = new VcsProcessExitError({
604 operation: "GitHubCli.execute",
605 command: "gh",
606 cwd: "/repo",
607 exitCode: 1,
608 failureKind: "rate-limited",
609 detail: "API rate limit exceeded.",
610 stderrLength: 82,
611 stderrTruncated: false,
612 });
613 mockRun.mockReturnValueOnce(Effect.fail(cause));
614
615 const gh = yield* GitHubCli.GitHubCli;
616 const error = yield* gh
617 .listOpenPullRequests({
618 cwd: "/repo",
619 headSelector: "feature/rate-limited",
620 })
621 .pipe(Effect.flip);
622
623 assert.strictEqual(error._tag, "GitHubCliRateLimitError");
624 assert.include(error.detail, "GitHub API rate limit exceeded");
625 assert.include(error.detail, "gh api rate_limit");
626 assert.strictEqual(error.cause, cause);
627 assert.notInclude(error.message, "user ID");
628 const paused = yield* gh
629 .execute({ cwd: "/other-repo", args: ["pr", "list"] })
630 .pipe(Effect.flip);
631 assert.strictEqual(paused._tag, "GitHubCliRateLimitError");
632 expect(mockRun).toHaveBeenCalledTimes(1);
633 yield* TestClock.adjust("30 seconds");
634 mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
635 yield* gh.execute({ cwd: "/other-repo", args: ["pr", "list"] });
636 expect(mockRun).toHaveBeenCalledTimes(2);
637 }).pipe(Effect.provide(layer)),
638 );
639});