@patronage/software-factory 1.0.0-alpha.48 → 1.0.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1026 +0,0 @@
1
- #!/usr/bin/env node
2
- // A `gh` for Claude Code cloud sessions (#1567).
3
- //
4
- // The session's egress proxy answers every GitHub GraphQL request with 403,
5
- // and `gh pr view`, `gh pr list`, `gh pr create`, `gh pr ready`,
6
- // `gh pr merge --auto`, `gh repo view` and `gh api graphql` are all GraphQL
7
- // underneath. The SessionStart hook puts this shim first on PATH once HQ is
8
- // reachable. It runs the reads through HQ's read relay
9
- // (`POST /api/ingest/github-graphql`), which answers with GitHub's own JSON,
10
- // and turns the three writes into the REST and proxy routes the proxy allows.
11
- // Output keeps `gh --json`'s shape, so the factory CLI and an operator see the
12
- // same `gh`. Anything else goes to the real `gh` untouched.
13
-
14
- import { spawnSync } from "node:child_process";
15
- import { realpathSync } from "node:fs";
16
- import path from "node:path";
17
-
18
- export const READ_RELAY_PATH = "/api/ingest/github-graphql";
19
- const RELAY_UPSTREAM_HEADER = "x-factory-relay-upstream";
20
- const PROXY_INJECTED = "proxy-injected";
21
- const RELAY_TIMEOUT_MS = 30_000;
22
-
23
- // REST `mergeable_state` values for which `gh pr merge --auto` merges now
24
- // rather than arming (gh's isImmediatelyMergeable: CLEAN, HAS_HOOKS, UNSTABLE).
25
- const IMMEDIATELY_MERGEABLE = new Set(["clean", "has_hooks", "unstable"]);
26
- const ALREADY_MERGEABLE_REFUSAL =
27
- /Pull request is in (?:clean|has_hooks|unstable) status/iu;
28
-
29
- export class GhShimError extends Error {
30
- name = "GhShimError";
31
- }
32
-
33
- // ---------------------------------------------------------------- arguments
34
-
35
- const VALUE_FLAGS = new Set([
36
- "--base",
37
- "--body",
38
- "--head",
39
- "--jq",
40
- "--json",
41
- "--limit",
42
- "--match-head-commit",
43
- "--repo",
44
- "--state",
45
- "--title",
46
- "-B",
47
- "-H",
48
- "-L",
49
- "-R",
50
- "-b",
51
- "-q",
52
- "-s",
53
- "-t",
54
- ]);
55
-
56
- const FLAG_ALIASES = {
57
- "-B": "--base",
58
- "-H": "--head",
59
- "-L": "--limit",
60
- "-R": "--repo",
61
- "-b": "--body",
62
- "-q": "--jq",
63
- "-s": "--state",
64
- "-t": "--title",
65
- };
66
-
67
- /** Positional arguments and flags of one `gh <group> <command>` call. */
68
- export const parseFlags = (args) => {
69
- const flags = {};
70
- const positional = [];
71
- for (let index = 0; index < args.length; index += 1) {
72
- const raw = args[index];
73
- const equals = raw.startsWith("--") ? raw.indexOf("=") : -1;
74
- const name = equals > 0 ? raw.slice(0, equals) : raw;
75
- const flag = FLAG_ALIASES[name] ?? name;
76
- if (equals > 0) {
77
- flags[flag] = raw.slice(equals + 1);
78
- } else if (VALUE_FLAGS.has(raw)) {
79
- index += 1;
80
- flags[flag] = args[index];
81
- } else if (raw.startsWith("-")) {
82
- flags[flag] = true;
83
- } else {
84
- positional.push(raw);
85
- }
86
- }
87
- return { flags, positional };
88
- };
89
-
90
- /** `gh api graphql`'s `-f`/`-F` fields: the query and its variables. */
91
- export const parseGraphqlFields = (args) => {
92
- const variables = {};
93
- let query;
94
- for (let index = 0; index < args.length; index += 1) {
95
- const flag = args[index];
96
- const typed = flag === "-F" || flag === "--field";
97
- if (!typed && flag !== "-f" && flag !== "--raw-field") {
98
- throw new GhShimError(`gh api graphql: unsupported argument ${flag}`);
99
- }
100
- index += 1;
101
- const field = args[index] ?? "";
102
- const equals = field.indexOf("=");
103
- const key = field.slice(0, equals);
104
- const raw = field.slice(equals + 1);
105
- if (key === "query") {
106
- query = raw;
107
- } else if (typed && /^-?\d+$/u.test(raw)) {
108
- variables[key] = Number(raw);
109
- } else if (typed && (raw === "true" || raw === "false")) {
110
- variables[key] = raw === "true";
111
- } else if (typed && raw === "null") {
112
- variables[key] = null;
113
- } else {
114
- variables[key] = raw;
115
- }
116
- }
117
- if (query === undefined) {
118
- throw new GhShimError("gh api graphql: no query field");
119
- }
120
- return { query, variables };
121
- };
122
-
123
- // ------------------------------------------------------------- `--json` map
124
-
125
- const STATUS_CHECK_ROLLUP = `commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes {
126
- __typename
127
- ... on CheckRun { name status conclusion startedAt completedAt detailsUrl checkSuite { workflowRun { workflow { name } } } }
128
- ... on StatusContext { context state targetUrl createdAt description }
129
- } } } } } }`;
130
-
131
- /**
132
- * Each `--json` field the factory reads: its GraphQL selection, and how gh
133
- * exports the selected value. A field missing here is refused rather than
134
- * guessed.
135
- */
136
- const PR_FIELDS = {
137
- autoMergeRequest: {
138
- select:
139
- "autoMergeRequest { enabledAt mergeMethod authorEmail commitBody commitHeadline enabledBy { login } }",
140
- },
141
- baseRefName: {},
142
- body: {},
143
- comments: {
144
- export: (node) => node.comments.nodes,
145
- select:
146
- "comments(first: 100) { nodes { id author { login } authorAssociation body createdAt url } }",
147
- },
148
- headRefName: {},
149
- headRefOid: {},
150
- isCrossRepository: {},
151
- isDraft: {},
152
- mergeCommit: { select: "mergeCommit { oid }" },
153
- mergeStateStatus: {},
154
- mergeable: {},
155
- mergedAt: {},
156
- number: {},
157
- reviewDecision: {
158
- export: (node) => node.reviewDecision ?? "",
159
- },
160
- state: {},
161
- statusCheckRollup: {
162
- export: (node) =>
163
- (
164
- node.commits.nodes[0]?.commit.statusCheckRollup?.contexts.nodes ?? []
165
- ).map((context) =>
166
- context.__typename === "CheckRun"
167
- ? {
168
- __typename: "CheckRun",
169
- completedAt: context.completedAt ?? "0001-01-01T00:00:00Z",
170
- conclusion: context.conclusion ?? "",
171
- detailsUrl: context.detailsUrl ?? "",
172
- name: context.name,
173
- startedAt: context.startedAt ?? "0001-01-01T00:00:00Z",
174
- status: context.status,
175
- workflowName:
176
- context.checkSuite?.workflowRun?.workflow?.name ?? "",
177
- }
178
- : {
179
- __typename: "StatusContext",
180
- context: context.context,
181
- startedAt: context.createdAt,
182
- state: context.state,
183
- targetUrl: context.targetUrl ?? "",
184
- }
185
- ),
186
- select: STATUS_CHECK_ROLLUP,
187
- },
188
- title: {},
189
- url: {},
190
- };
191
-
192
- export const pullRequestSelection = (fields) =>
193
- fields
194
- .map((field) => {
195
- const spec = PR_FIELDS[field];
196
- if (spec === undefined) {
197
- throw new GhShimError(
198
- `the cloud gh shim cannot read pull request field ${field}`
199
- );
200
- }
201
- return spec.select ?? field;
202
- })
203
- .join("\n");
204
-
205
- export const exportPullRequest = (node, fields) =>
206
- Object.fromEntries(
207
- fields.map((field) => [
208
- field,
209
- PR_FIELDS[field].export?.(node) ?? node[field] ?? null,
210
- ])
211
- );
212
-
213
- // ----------------------------------------------------------------- `--jq`
214
-
215
- /** The `--jq` the factory passes: a plain `.a.b` path. */
216
- export const applyJq = (value, expression) => {
217
- if (expression === undefined) {
218
- return `${JSON.stringify(value)}\n`;
219
- }
220
- if (!/^(?:\.[A-Za-z_]\w*)+$/u.test(expression)) {
221
- throw new GhShimError(
222
- `the cloud gh shim supports only path --jq expressions, not ${expression}`
223
- );
224
- }
225
- let result = value;
226
- for (const key of expression.slice(1).split(".")) {
227
- result = result?.[key];
228
- }
229
- if (result === undefined || result === null) {
230
- return "\n";
231
- }
232
- return typeof result === "string"
233
- ? `${result}\n`
234
- : `${JSON.stringify(result)}\n`;
235
- };
236
-
237
- // --------------------------------------------------------------- planning
238
-
239
- const STATES = {
240
- all: ["OPEN", "CLOSED", "MERGED"],
241
- closed: ["CLOSED"],
242
- merged: ["MERGED"],
243
- open: ["OPEN"],
244
- };
245
-
246
- const splitRepo = (slug) => {
247
- const match = /^(?<owner>[\w.-]+)\/(?<repo>[\w.-]+)$/u.exec(slug ?? "");
248
- if (match === null) {
249
- throw new GhShimError(`not an OWNER/REPO: ${slug}`);
250
- }
251
- return { owner: match.groups.owner, repo: match.groups.repo };
252
- };
253
-
254
- const NUMBER = /^\d+$/u;
255
-
256
- const planPrView = ({ context, flags, positional, repository }) => {
257
- if (typeof flags["--json"] !== "string") {
258
- return { kind: "passthrough" };
259
- }
260
- const [target] = positional;
261
- const byNumber = target !== undefined && NUMBER.test(target);
262
- return {
263
- ...repository,
264
- branch: byNumber ? undefined : (target ?? context.branch()),
265
- fields: flags["--json"].split(","),
266
- jq: flags["--jq"],
267
- kind: "pr-view",
268
- number: byNumber ? Number(target) : undefined,
269
- };
270
- };
271
-
272
- const planPrList = ({ flags, repository }) => {
273
- if (typeof flags["--json"] !== "string") {
274
- return { kind: "passthrough" };
275
- }
276
- const state = flags["--state"] ?? "open";
277
- if (STATES[state] === undefined) {
278
- throw new GhShimError(`gh pr list: unsupported --state ${state}`);
279
- }
280
- return {
281
- ...repository,
282
- base: flags["--base"],
283
- fields: flags["--json"].split(","),
284
- head: flags["--head"],
285
- jq: flags["--jq"],
286
- kind: "pr-list",
287
- limit: Number(flags["--limit"] ?? 30),
288
- states: STATES[state],
289
- };
290
- };
291
-
292
- const planPrCreate = ({ context, flags, repository }) => {
293
- if (
294
- typeof flags["--title"] !== "string" ||
295
- typeof flags["--body"] !== "string"
296
- ) {
297
- throw new GhShimError(
298
- "gh pr create in a Claude cloud session needs --title and --body (pass a --base so pr:publish fills them)"
299
- );
300
- }
301
- return {
302
- ...repository,
303
- base: flags["--base"],
304
- body: flags["--body"],
305
- draft: flags["--draft"] === true,
306
- head: flags["--head"] ?? context.branch(),
307
- kind: "pr-create",
308
- title: flags["--title"],
309
- };
310
- };
311
-
312
- const planPrReady = ({ flags, positional, repository }) => {
313
- if (flags["--undo"] === true || !NUMBER.test(positional[0] ?? "")) {
314
- return { kind: "passthrough" };
315
- }
316
- return { ...repository, kind: "pr-ready", number: Number(positional[0]) };
317
- };
318
-
319
- const planPrMerge = ({ flags, positional, repository }) => {
320
- if (flags["--auto"] !== true || !NUMBER.test(positional[0] ?? "")) {
321
- return { kind: "passthrough" };
322
- }
323
- const method = ["merge", "rebase", "squash"].find(
324
- (name) => flags[`--${name}`] === true
325
- );
326
- if (method === undefined) {
327
- throw new GhShimError(
328
- "gh pr merge --auto needs --merge, --rebase or --squash"
329
- );
330
- }
331
- return {
332
- ...repository,
333
- headSha: flags["--match-head-commit"],
334
- kind: "pr-merge-auto",
335
- method,
336
- number: Number(positional[0]),
337
- };
338
- };
339
-
340
- const ISSUE_FIELDS = new Set(["body", "number", "state", "title", "url"]);
341
-
342
- const planIssueView = ({ flags, positional, repository }) => {
343
- if (
344
- typeof flags["--json"] !== "string" ||
345
- !NUMBER.test(positional[0] ?? "")
346
- ) {
347
- return { kind: "passthrough" };
348
- }
349
- const fields = flags["--json"].split(",");
350
- const unknown = fields.filter((field) => !ISSUE_FIELDS.has(field));
351
- if (unknown.length > 0) {
352
- throw new GhShimError(
353
- `gh issue view --json ${unknown.join(",")} is not supported in a Claude cloud session`
354
- );
355
- }
356
- return {
357
- ...repository,
358
- fields,
359
- jq: flags["--jq"],
360
- kind: "issue-view",
361
- number: Number(positional[0]),
362
- };
363
- };
364
-
365
- /** What `repo view --json` exports from the REST repository, per field. */
366
- const REPO_FIELDS = {
367
- defaultBranchRef: (repository) =>
368
- repository.default_branch === undefined
369
- ? null
370
- : { name: repository.default_branch },
371
- name: (repository) => repository.name,
372
- nameWithOwner: (repository) => repository.full_name,
373
- owner: (repository) =>
374
- repository.owner?.login === undefined
375
- ? null
376
- : { login: repository.owner.login },
377
- url: (repository) => repository.html_url,
378
- };
379
-
380
- const planRepoView = ({ context, flags, positional }) => {
381
- if (typeof flags["--json"] !== "string") {
382
- throw new GhShimError(
383
- "gh repo view without --json is not supported in a Claude cloud session"
384
- );
385
- }
386
- const fields = flags["--json"].split(",");
387
- const unknown = fields.filter((field) => !Object.hasOwn(REPO_FIELDS, field));
388
- if (unknown.length > 0) {
389
- throw new GhShimError(
390
- `gh repo view --json ${unknown.join(",")} is not supported in a Claude cloud session`
391
- );
392
- }
393
- const repository =
394
- positional[0] === undefined
395
- ? context.repository()
396
- : splitRepo(positional[0]);
397
- return { ...repository, fields, jq: flags["--jq"], kind: "repo-view" };
398
- };
399
-
400
- /**
401
- * The commands the shim answers itself, with the flags each one honours. A
402
- * flag outside that list is refused rather than dropped: `pr list --search`
403
- * answered unfiltered, or `pr merge --delete-branch` that deletes nothing,
404
- * would be a wrong answer that looks right.
405
- */
406
- const PLANS = {
407
- "issue view": {
408
- flags: ["--jq", "--json", "--repo"],
409
- plan: planIssueView,
410
- },
411
- "pr create": {
412
- flags: [
413
- "--base",
414
- "--body",
415
- "--draft",
416
- "--fill-verbose",
417
- "--head",
418
- "--repo",
419
- "--title",
420
- ],
421
- plan: planPrCreate,
422
- },
423
- "pr list": {
424
- flags: [
425
- "--base",
426
- "--head",
427
- "--jq",
428
- "--json",
429
- "--limit",
430
- "--repo",
431
- "--state",
432
- ],
433
- plan: planPrList,
434
- },
435
- "pr merge": {
436
- flags: [
437
- "--auto",
438
- "--match-head-commit",
439
- "--merge",
440
- "--rebase",
441
- "--repo",
442
- "--squash",
443
- ],
444
- plan: planPrMerge,
445
- },
446
- "pr ready": { flags: ["--repo", "--undo"], plan: planPrReady },
447
- "pr view": { flags: ["--jq", "--json", "--repo"], plan: planPrView },
448
- "repo view": { flags: ["--jq", "--json"], plan: planRepoView },
449
- };
450
-
451
- /**
452
- * What one `gh` call becomes. Pure: `context` supplies the repository and the
453
- * current branch, so tests need no git.
454
- */
455
- export const planGhCall = (argv, context) => {
456
- const [group, command, ...rest] = argv;
457
- if (group === "api" && command === "graphql") {
458
- const { query, variables } = parseGraphqlFields(rest);
459
- const owner = variables.owner ?? context.repository().owner;
460
- const repo = variables.name ?? variables.repo ?? context.repository().repo;
461
- return { kind: "graphql", owner, query, repo, variables };
462
- }
463
- const name = `${group} ${command}`;
464
- if (!Object.hasOwn(PLANS, name)) {
465
- return { kind: "passthrough" };
466
- }
467
- const { flags, positional } = parseFlags(rest);
468
- const unknown = Object.keys(flags).filter(
469
- (flag) => !PLANS[name].flags.includes(flag)
470
- );
471
- if (unknown.length > 0) {
472
- throw new GhShimError(
473
- `gh ${name} ${unknown.join(" ")} is not supported in a Claude cloud session`
474
- );
475
- }
476
- return PLANS[name].plan({
477
- context,
478
- flags,
479
- positional,
480
- // A getter, so `repo view OWNER/REPO` reads no git remote.
481
- get repository() {
482
- return flags["--repo"] === undefined
483
- ? context.repository()
484
- : splitRepo(flags["--repo"]);
485
- },
486
- });
487
- };
488
-
489
- // ---------------------------------------------------------------- queries
490
-
491
- export const pullRequestByNumberQuery = (
492
- fields
493
- ) => `query($owner: String!, $name: String!, $number: Int!) {
494
- repository(owner: $owner, name: $name) {
495
- pullRequest(number: $number) {
496
- ${pullRequestSelection(fields)}
497
- }
498
- }
499
- }`;
500
-
501
- export const issueByNumberQuery = (
502
- fields
503
- ) => `query($owner: String!, $name: String!, $number: Int!) {
504
- repository(owner: $owner, name: $name) {
505
- issue(number: $number) {
506
- ${fields.join("\n ")}
507
- }
508
- }
509
- }`;
510
-
511
- export const pullRequestListQuery = (
512
- fields
513
- ) => `query($owner: String!, $name: String!, $first: Int!, $after: String, $head: String, $base: String, $states: [PullRequestState!]) {
514
- repository(owner: $owner, name: $name) {
515
- pullRequests(first: $first, after: $after, headRefName: $head, baseRefName: $base, states: $states, orderBy: { field: CREATED_AT, direction: DESC }) {
516
- nodes {
517
- ${pullRequestSelection(fields)}
518
- }
519
- pageInfo { hasNextPage endCursor }
520
- }
521
- }
522
- }`;
523
-
524
- // ---------------------------------------------------------------- running
525
-
526
- /** Why HQ refused, for the statuses that are a setup fault, not a request. */
527
- const relayRefusalHint = (status, origin) => {
528
- if (status === 404) {
529
- return `: ${origin} serves no ${READ_RELAY_PATH}, so either HQ's deploy with the read relay (#1583) has not finished or FACTORY_CHECK_RUN_RELAY_ORIGIN names another host`;
530
- }
531
- if (status === 401 || status === 403) {
532
- return ": HQ did not accept this session, so check that hq.patronage.com's Access token is injected and that this machine is in FACTORY_CHECK_RUN_RELAY_MACHINES";
533
- }
534
- return "";
535
- };
536
-
537
- /**
538
- * The relay origin as a URL, or a refusal. `https:` with no embedded
539
- * credentials is the CLI's own protocol rule (`validatedHqOrigin` in
540
- * software-factory/src/hq-origin-policy.ts); the shim is a standalone script
541
- * and cannot import it, so the rule is restated here and the tests pin the
542
- * same cases. The refusal names the scheme and host only: a value that embeds
543
- * a password must not reach a log through this message.
544
- */
545
- const relayOrigin = (value) => {
546
- let endpoint;
547
- try {
548
- endpoint = new URL(value);
549
- } catch {
550
- throw new GhShimError(
551
- "FACTORY_CHECK_RUN_RELAY_ORIGIN is not an https origin: it does not parse as a URL"
552
- );
553
- }
554
- if (
555
- endpoint.protocol !== "https:" ||
556
- endpoint.username !== "" ||
557
- endpoint.password !== ""
558
- ) {
559
- throw new GhShimError(
560
- `FACTORY_CHECK_RUN_RELAY_ORIGIN (${endpoint.protocol}//${endpoint.host}) is not an https origin without embedded credentials`
561
- );
562
- }
563
- return endpoint;
564
- };
565
-
566
- /**
567
- * The operator's `FACTORY_HQ_ALLOWED_ORIGINS`, parsed as the CLI parses it
568
- * (`hqAllowedOriginsFromEnv`): comma-separated, trimmed, and an entry counts
569
- * only when it is exactly its own https origin, with no path, no trailing
570
- * slash and no credentials. The CLI also unions `hqAllowedOrigins` from the
571
- * operator user config; the shim reads the environment alone. A cloud session
572
- * has no user config, and both cloud paths export the variable
573
- * (`hq_access_exports` in session-start.sh, `resolveCloudEnvironment`).
574
- */
575
- const allowedHqOrigins = (env) => {
576
- const raw = env.FACTORY_HQ_ALLOWED_ORIGINS;
577
- if (typeof raw !== "string") {
578
- return [];
579
- }
580
- const origins = [];
581
- for (const segment of raw.split(",")) {
582
- const candidate = segment.trim();
583
- let endpoint;
584
- try {
585
- endpoint = new URL(candidate);
586
- } catch {
587
- continue;
588
- }
589
- if (
590
- endpoint.protocol === "https:" &&
591
- endpoint.username === "" &&
592
- endpoint.password === "" &&
593
- candidate === endpoint.origin
594
- ) {
595
- origins.push(endpoint.origin);
596
- }
597
- }
598
- return origins;
599
- };
600
-
601
- /**
602
- * The relay request's headers. The session holds the Access token itself only
603
- * when both values are real (not proxy-injected), and then the shim applies
604
- * the matching rule every other HQ client applies (check-run-relay.ts): the
605
- * token goes only to an origin the operator listed, matched exactly. The
606
- * refusal comes before any request. With a proxy-injected token there is
607
- * nothing to send: the egress proxy adds it, and only for HQ's own host.
608
- */
609
- const relayHeaders = (env, origin) => {
610
- const headers = { "Content-Type": "application/json" };
611
- const id = env.CF_ACCESS_CLIENT_ID;
612
- const secret = env.CF_ACCESS_CLIENT_SECRET;
613
- if (id && secret && id !== PROXY_INJECTED && secret !== PROXY_INJECTED) {
614
- if (!allowedHqOrigins(env).includes(origin)) {
615
- throw new GhShimError(
616
- `the HQ read relay at ${origin} was not used: it is not listed in FACTORY_HQ_ALLOWED_ORIGINS`
617
- );
618
- }
619
- headers["CF-Access-Client-Id"] = id;
620
- headers["CF-Access-Client-Secret"] = secret;
621
- }
622
- return headers;
623
- };
624
-
625
- /** Run one read through HQ's relay; GitHub's `data`, or a thrown error. */
626
- export const relayGraphql = async (
627
- { owner, query, repo, variables },
628
- { env: given, fetch: request = fetch, resolveEnv = (env) => env }
629
- ) => {
630
- // A repository that holds its own HQ credentials (a 1Password service
631
- // account, say) resolves them here, in memory, per call. The packaged entry
632
- // resolves nothing: proxy-injected Access, or values already in the env.
633
- const env = resolveEnv(given);
634
- const named = env.FACTORY_CHECK_RUN_RELAY_ORIGIN;
635
- if (named === undefined || named.length === 0) {
636
- throw new GhShimError(
637
- "GitHub GraphQL is blocked here and FACTORY_CHECK_RUN_RELAY_ORIGIN names no HQ to read through"
638
- );
639
- }
640
- const { origin } = relayOrigin(named);
641
- const headers = relayHeaders(env, origin);
642
- let response;
643
- try {
644
- response = await request(new URL(READ_RELAY_PATH, origin), {
645
- body: JSON.stringify({ owner, query, repo, variables }),
646
- headers,
647
- method: "POST",
648
- redirect: "error",
649
- signal: AbortSignal.timeout(RELAY_TIMEOUT_MS),
650
- });
651
- } catch (error) {
652
- if (error.name === "TimeoutError") {
653
- throw new GhShimError(
654
- `HQ read relay at ${origin} did not answer within ${RELAY_TIMEOUT_MS / 1000}s`
655
- );
656
- }
657
- const cause = error.cause?.code ?? error.cause?.message ?? error.message;
658
- throw new GhShimError(
659
- `HQ read relay at ${origin} is unreachable (${cause}): check that the environment allows the host and that NODE_USE_ENV_PROXY=1 is set`
660
- );
661
- }
662
- const text = await response.text();
663
- if (response.headers.get(RELAY_UPSTREAM_HEADER) !== "github") {
664
- let code = "no error code";
665
- try {
666
- code = JSON.parse(text).error ?? code;
667
- } catch {
668
- // Not the relay's JSON: the status says enough.
669
- }
670
- throw new GhShimError(
671
- `HQ read relay refused with ${response.status} (${code})${relayRefusalHint(response.status, origin)}`
672
- );
673
- }
674
- if (!response.ok) {
675
- throw new GhShimError(`GitHub GraphQL answered HTTP ${response.status}`);
676
- }
677
- const body = JSON.parse(text);
678
- if (Array.isArray(body.errors) && body.errors.length > 0) {
679
- throw new GhShimError(
680
- `GraphQL: ${body.errors.map((error) => error.message).join(", ")}`
681
- );
682
- }
683
- return body;
684
- };
685
-
686
- const listPullRequests = async (plan, run) => {
687
- const nodes = [];
688
- let after = null;
689
- while (nodes.length < plan.limit) {
690
- // Each page depends on the previous page's cursor.
691
- // oxlint-disable-next-line no-await-in-loop
692
- const { data } = await run({
693
- owner: plan.owner,
694
- query: pullRequestListQuery(plan.fields),
695
- repo: plan.repo,
696
- variables: {
697
- after,
698
- base: plan.base ?? null,
699
- first: Math.min(100, plan.limit - nodes.length),
700
- head: plan.head ?? null,
701
- name: plan.repo,
702
- owner: plan.owner,
703
- states: plan.states ?? null,
704
- },
705
- });
706
- const page = data.repository.pullRequests;
707
- nodes.push(...page.nodes);
708
- if (!page.pageInfo.hasNextPage) {
709
- break;
710
- }
711
- after = page.pageInfo.endCursor;
712
- }
713
- return nodes;
714
- };
715
-
716
- const viewIssue = async (plan, graphql) => {
717
- const { data } = await graphql({
718
- owner: plan.owner,
719
- query: issueByNumberQuery(plan.fields),
720
- repo: plan.repo,
721
- variables: { name: plan.repo, number: plan.number, owner: plan.owner },
722
- });
723
- const node = data.repository.issue;
724
- if (node === null) {
725
- throw new GhShimError(`no issue #${plan.number}`);
726
- }
727
- return applyJq(
728
- Object.fromEntries(plan.fields.map((field) => [field, node[field]])),
729
- plan.jq
730
- );
731
- };
732
-
733
- const viewPullRequest = async (plan, { graphql }) => {
734
- if (plan.number !== undefined) {
735
- const { data } = await graphql({
736
- owner: plan.owner,
737
- query: pullRequestByNumberQuery(plan.fields),
738
- repo: plan.repo,
739
- variables: {
740
- name: plan.repo,
741
- number: plan.number,
742
- owner: plan.owner,
743
- },
744
- });
745
- const node = data.repository.pullRequest;
746
- if (node === null) {
747
- throw new GhShimError(`no pull request #${plan.number}`);
748
- }
749
- return applyJq(exportPullRequest(node, plan.fields), plan.jq);
750
- }
751
- // gh's own rule for a branch: its open pull request, else its newest.
752
- const nodes = await listPullRequests(
753
- {
754
- ...plan,
755
- fields: [...new Set([...plan.fields, "state"])],
756
- head: plan.branch,
757
- limit: 30,
758
- },
759
- graphql
760
- );
761
- const node =
762
- nodes.find((candidate) => candidate.state === "OPEN") ?? nodes[0];
763
- if (node === undefined) {
764
- throw new GhShimError(`no pull requests found for branch "${plan.branch}"`);
765
- }
766
- return applyJq(exportPullRequest(node, plan.fields), plan.jq);
767
- };
768
-
769
- const mergeAuto = async (plan, { api }) => {
770
- const pull = JSON.parse(
771
- api(["api", `repos/${plan.owner}/${plan.repo}/pulls/${plan.number}`])
772
- );
773
- if (plan.headSha !== undefined) {
774
- const head = pull.head?.sha;
775
- if (head !== plan.headSha) {
776
- throw new GhShimError(
777
- `head ${head ?? "unknown"} does not match --match-head-commit ${plan.headSha}`
778
- );
779
- }
780
- }
781
- // Real gh merges at once instead of arming when the pull request is
782
- // already mergeable, and GitHub refuses to arm it then ("Pull request
783
- // is in clean status", or "unstable" while non-required checks run).
784
- const mergeNow = () => {
785
- api([
786
- "api",
787
- "-X",
788
- "PUT",
789
- `repos/${plan.owner}/${plan.repo}/pulls/${plan.number}/merge`,
790
- "-f",
791
- `merge_method=${plan.method}`,
792
- ...(plan.headSha === undefined ? [] : ["-f", `sha=${plan.headSha}`]),
793
- ]);
794
- return "";
795
- };
796
- if (IMMEDIATELY_MERGEABLE.has(pull.mergeable_state)) {
797
- return mergeNow();
798
- }
799
- try {
800
- api([
801
- "api",
802
- "-X",
803
- "PUT",
804
- `repos/${plan.owner}/${plan.repo}/pulls/${plan.number}/ccr/auto_merge`,
805
- "-f",
806
- `merge_method=${plan.method}`,
807
- ]);
808
- } catch (error) {
809
- // The read said "unknown" or "blocked", but GitHub found the pull
810
- // request mergeable by the time it was asked to arm.
811
- if (ALREADY_MERGEABLE_REFUSAL.test(String(error?.message))) {
812
- return mergeNow();
813
- }
814
- throw error;
815
- }
816
- return "";
817
- };
818
-
819
- /** Execute a plan; returns stdout. Writes go through `api` (the real gh). */
820
- export const executePlan = async (plan, { api, graphql }) => {
821
- switch (plan.kind) {
822
- case "graphql": {
823
- return `${JSON.stringify(await graphql(plan))}\n`;
824
- }
825
- case "pr-view": {
826
- return viewPullRequest(plan, { graphql });
827
- }
828
- case "pr-list": {
829
- const nodes = await listPullRequests(plan, graphql);
830
- return applyJq(
831
- nodes.map((node) => exportPullRequest(node, plan.fields)),
832
- plan.jq
833
- );
834
- }
835
- case "issue-view": {
836
- return viewIssue(plan, graphql);
837
- }
838
- case "repo-view": {
839
- const repository = JSON.parse(
840
- api(["api", `repos/${plan.owner}/${plan.repo}`])
841
- );
842
- return applyJq(
843
- Object.fromEntries(
844
- plan.fields.map((field) => [
845
- field,
846
- REPO_FIELDS[field](repository) ?? null,
847
- ])
848
- ),
849
- plan.jq
850
- );
851
- }
852
- case "pr-create": {
853
- const base =
854
- plan.base ??
855
- JSON.parse(api(["api", `repos/${plan.owner}/${plan.repo}`]))
856
- .default_branch;
857
- const created = JSON.parse(
858
- api([
859
- "api",
860
- "-X",
861
- "POST",
862
- `repos/${plan.owner}/${plan.repo}/pulls`,
863
- "-f",
864
- `title=${plan.title}`,
865
- "-f",
866
- `body=${plan.body}`,
867
- "-f",
868
- `head=${plan.head}`,
869
- "-f",
870
- `base=${base}`,
871
- "-F",
872
- `draft=${plan.draft}`,
873
- ])
874
- );
875
- return `${created.html_url}\n`;
876
- }
877
- case "pr-ready": {
878
- api([
879
- "api",
880
- "-X",
881
- "POST",
882
- `repos/${plan.owner}/${plan.repo}/pulls/${plan.number}/ccr/ready_for_review`,
883
- ]);
884
- return "";
885
- }
886
- case "pr-merge-auto": {
887
- return mergeAuto(plan, { api });
888
- }
889
- default: {
890
- throw new GhShimError(`unplanned ${plan.kind}`);
891
- }
892
- }
893
- };
894
-
895
- // ------------------------------------------------------------------- main
896
-
897
- /**
898
- * The real `gh`: the first one on PATH outside every shim wrapper directory.
899
- * `shimDirectories` is one directory or a list of them (see `runGhShim`).
900
- */
901
- export const findRealGh = (env, shimDirectories, exists) => {
902
- if (env.FACTORY_REAL_GH) {
903
- return env.FACTORY_REAL_GH;
904
- }
905
- const skipped = new Set(
906
- [shimDirectories].flat().map((directory) => path.resolve(directory))
907
- );
908
- for (const directory of (env.PATH ?? "").split(path.delimiter)) {
909
- if (directory.length > 0 && !skipped.has(path.resolve(directory))) {
910
- const candidate = path.join(directory, "gh");
911
- if (exists(candidate)) {
912
- return candidate;
913
- }
914
- }
915
- }
916
- throw new GhShimError("no real gh found on PATH");
917
- };
918
-
919
- /** The env variable that carries every shim directory seen so far to children. */
920
- export const SHIM_DIRECTORIES_ENV = "FACTORY_GH_SHIM_DIRS";
921
-
922
- const originRepository = () => {
923
- const remote = spawnSync("git", ["remote", "get-url", "origin"], {
924
- encoding: "utf-8",
925
- }).stdout.trim();
926
- const match =
927
- /github\.com[/:](?<owner>[\w.-]+)\/(?<repo>[\w.-]+?)(?:\.git)?$/u.exec(
928
- remote
929
- );
930
- if (match === null) {
931
- throw new GhShimError(
932
- `cannot tell the GitHub repository from origin ${remote}`
933
- );
934
- }
935
- return { owner: match.groups.owner, repo: match.groups.repo };
936
- };
937
-
938
- const currentBranch = () =>
939
- spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
940
- encoding: "utf-8",
941
- }).stdout.trim();
942
-
943
- /**
944
- * The shim's process entry. `shimDirectory` is the directory holding the `gh`
945
- * wrapper that runs this file, so the real `gh` lookup can skip it;
946
- * `resolveEnv` is passed to every relay read (see `relayGraphql`).
947
- */
948
- export const runGhShim = async ({
949
- resolveEnv = (env) => env,
950
- shimDirectory: given = process.env.FACTORY_GH_SHIM_DIR,
951
- } = {}) => {
952
- const argv = process.argv.slice(2);
953
- if (given === undefined || given.length === 0) {
954
- process.stderr.write(
955
- "gh shim: FACTORY_GH_SHIM_DIR names no wrapper directory\n"
956
- );
957
- process.exit(1);
958
- }
959
- // Two shim wrappers can be on PATH at once (this repository's hook-installed
960
- // one and the packaged launcher's). Each would take the other for the real
961
- // gh, so every directory a shim has run from in this chain is skipped, and
962
- // handed on to the gh it spawns.
963
- const shimDirectories = [
964
- path.resolve(given),
965
- ...(process.env[SHIM_DIRECTORIES_ENV] ?? "")
966
- .split(path.delimiter)
967
- .filter((directory) => directory.length > 0)
968
- .map((directory) => path.resolve(directory)),
969
- ];
970
- process.env[SHIM_DIRECTORIES_ENV] = [...new Set(shimDirectories)].join(
971
- path.delimiter
972
- );
973
- const { existsSync } = await import("node:fs");
974
- const realGh = findRealGh(process.env, shimDirectories, (candidate) => {
975
- try {
976
- return (
977
- existsSync(candidate) &&
978
- !shimDirectories.includes(path.dirname(realpathSync(candidate)))
979
- );
980
- } catch {
981
- return false;
982
- }
983
- });
984
- let plan;
985
- try {
986
- plan = planGhCall(argv, {
987
- branch: currentBranch,
988
- repository: originRepository,
989
- });
990
- } catch (error) {
991
- process.stderr.write(`${error.message}\n`);
992
- process.exit(1);
993
- }
994
- if (plan.kind === "passthrough") {
995
- const result = spawnSync(realGh, argv, { stdio: "inherit" });
996
- process.exit(result.status ?? 1);
997
- }
998
- const api = (args) => {
999
- const result = spawnSync(realGh, args, { encoding: "utf-8" });
1000
- if (result.status !== 0) {
1001
- throw new GhShimError(
1002
- result.stderr.trim() || `gh ${args.join(" ")} failed`
1003
- );
1004
- }
1005
- return result.stdout;
1006
- };
1007
- try {
1008
- process.stdout.write(
1009
- await executePlan(plan, {
1010
- api,
1011
- graphql: (request) =>
1012
- relayGraphql(request, { env: process.env, resolveEnv }),
1013
- })
1014
- );
1015
- } catch (error) {
1016
- process.stderr.write(`${error.message}\n`);
1017
- process.exit(1);
1018
- }
1019
- };
1020
-
1021
- if (
1022
- process.argv[1] !== undefined &&
1023
- realpathSync(process.argv[1]) === import.meta.filename
1024
- ) {
1025
- await runGhShim();
1026
- }