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