mandrel 2.93.0 → 2.95.0

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.
Files changed (130) hide show
  1. package/.agents/docs/configuration.md +8 -3
  2. package/.agents/runtime-deps.json +6 -6
  3. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  4. package/.agents/schemas/story-deliver-terminal.schema.json +1 -0
  5. package/.agents/scripts/agents-bootstrap-github.js +1 -1
  6. package/.agents/scripts/board-backfill.js +1 -1
  7. package/.agents/scripts/boot-sweep.js +1 -1
  8. package/.agents/scripts/check-arch-cycles.js +69 -41
  9. package/.agents/scripts/check-doc-links.js +5 -7
  10. package/.agents/scripts/check-gherkin-corpus.js +2 -11
  11. package/.agents/scripts/clean-temp.js +1 -1
  12. package/.agents/scripts/cleanup-repo-test-temp.js +1 -1
  13. package/.agents/scripts/diagnose-friction.js +1 -1
  14. package/.agents/scripts/generate-lens-checklists.js +4 -4
  15. package/.agents/scripts/generate-skills-index.js +3 -2
  16. package/.agents/scripts/generate-workflows-doc.js +2 -1
  17. package/.agents/scripts/lib/audit-baselines/read.js +2 -1
  18. package/.agents/scripts/lib/audit-exceptions/adapters/tool-config.js +13 -3
  19. package/.agents/scripts/lib/audit-exceptions/globs.js +12 -1
  20. package/.agents/scripts/lib/audit-exceptions/probe.js +24 -2
  21. package/.agents/scripts/lib/audit-exceptions/read.js +2 -2
  22. package/.agents/scripts/lib/audit-to-stories/group-findings.js +77 -67
  23. package/.agents/scripts/lib/baselines/components.js +21 -19
  24. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -8
  25. package/.agents/scripts/lib/baselines/kinds/maintainability.js +2 -3
  26. package/.agents/scripts/lib/baselines/preview-gates.js +2 -2
  27. package/.agents/scripts/lib/baselines/refresh-service.js +4 -7
  28. package/.agents/scripts/lib/baselines/writer.js +2 -7
  29. package/.agents/scripts/lib/bdd-runner-detect.js +2 -2
  30. package/.agents/scripts/lib/bdd-step-index.js +3 -7
  31. package/.agents/scripts/lib/bootstrap/baseline-merge-driver.js +11 -7
  32. package/.agents/scripts/lib/bootstrap/install-ledger.js +19 -4
  33. package/.agents/scripts/lib/bootstrap/json-io.js +14 -0
  34. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +20 -44
  35. package/.agents/scripts/lib/bootstrap/quality-bootstrap.js +38 -54
  36. package/.agents/scripts/lib/branch-name-guard.js +2 -3
  37. package/.agents/scripts/lib/claude/agents-projection.js +1 -12
  38. package/.agents/scripts/lib/codex/agents-projection.js +2 -5
  39. package/.agents/scripts/lib/codex/skills-projection.js +4 -12
  40. package/.agents/scripts/lib/config/defaults.js +2 -1
  41. package/.agents/scripts/lib/config/qa.js +4 -5
  42. package/.agents/scripts/lib/config-schema.js +1 -8
  43. package/.agents/scripts/lib/config-settings-schema.js +0 -3
  44. package/.agents/scripts/lib/coverage-baseline.js +2 -3
  45. package/.agents/scripts/lib/coverage-utils.js +2 -1
  46. package/.agents/scripts/lib/cpu-pool.js +0 -1
  47. package/.agents/scripts/lib/cyclomatic-scope.js +2 -1
  48. package/.agents/scripts/lib/doc-tiers.js +2 -1
  49. package/.agents/scripts/lib/duplicate-search.js +52 -18
  50. package/.agents/scripts/lib/feedback-loop/prior-feedback-fetcher.js +47 -20
  51. package/.agents/scripts/lib/gh-exec.js +115 -25
  52. package/.agents/scripts/lib/gh-pr-rest.js +371 -0
  53. package/.agents/scripts/lib/git/sync-from-base.js +1 -1
  54. package/.agents/scripts/lib/import-graph.js +13 -28
  55. package/.agents/scripts/lib/json-utils.js +11 -0
  56. package/.agents/scripts/lib/label-constants.js +7 -1
  57. package/.agents/scripts/lib/maintainability-utils.js +14 -22
  58. package/.agents/scripts/lib/observability/runtime-friction.js +37 -1
  59. package/.agents/scripts/lib/orchestration/board-graphql-latch.js +75 -0
  60. package/.agents/scripts/lib/orchestration/check-baselines/phases/parse-args.js +25 -1
  61. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +82 -41
  62. package/.agents/scripts/lib/orchestration/code-review.js +1 -6
  63. package/.agents/scripts/lib/orchestration/column-sync.js +23 -21
  64. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  65. package/.agents/scripts/lib/orchestration/git-cleanup/phases/fast-forward.js +7 -14
  66. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +2 -21
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +11 -20
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/phase-drivers.js +65 -86
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/prompts.js +2 -2
  70. package/.agents/scripts/lib/orchestration/git-cleanup/phases/stashes.js +15 -6
  71. package/.agents/scripts/lib/orchestration/lifecycle/emit-merge-unlanded.js +5 -2
  72. package/.agents/scripts/lib/orchestration/merge-block-class.js +48 -47
  73. package/.agents/scripts/lib/orchestration/merge-queue.js +49 -4
  74. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +20 -1
  75. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +2 -2
  76. package/.agents/scripts/lib/orchestration/required-checks.js +72 -12
  77. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +2 -3
  78. package/.agents/scripts/lib/orchestration/review-providers/parse-findings.js +4 -2
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +132 -58
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +92 -9
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/graphql-preflight.js +41 -18
  82. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -2
  83. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +3 -3
  84. package/.agents/scripts/lib/orchestration/story-handoff.js +18 -5
  85. package/.agents/scripts/lib/orchestration/ticketing/transition.js +18 -22
  86. package/.agents/scripts/lib/runtime-deps/dep-resolution.js +19 -5
  87. package/.agents/scripts/lib/runtime-deps/scan-imports.js +4 -10
  88. package/.agents/scripts/lib/skills/parse-skill.js +2 -2
  89. package/.agents/scripts/lib/skills/walk-skill-files.js +7 -23
  90. package/.agents/scripts/lib/story-body/story-body.js +4 -14
  91. package/.agents/scripts/lib/util/atomic-write.js +14 -3
  92. package/.agents/scripts/lib/util/regex.js +4 -0
  93. package/.agents/scripts/notify.js +1 -1
  94. package/.agents/scripts/plan-context.js +1 -1
  95. package/.agents/scripts/plan-critics.js +3 -11
  96. package/.agents/scripts/providers/github/auth.js +0 -4
  97. package/.agents/scripts/providers/github/board-add.js +3 -3
  98. package/.agents/scripts/providers/github/compose.js +2 -0
  99. package/.agents/scripts/providers/github/errors.js +41 -0
  100. package/.agents/scripts/providers/github/project-board.js +0 -1
  101. package/.agents/scripts/providers/github/sub-issues-rest.js +55 -0
  102. package/.agents/scripts/providers/github/sub-issues.js +9 -1
  103. package/.agents/scripts/providers/github/tickets.js +0 -2
  104. package/.agents/scripts/resync-status-column.js +1 -1
  105. package/.agents/scripts/run-tests.js +1 -1
  106. package/.agents/scripts/single-story-confirm-merge.js +2 -0
  107. package/.agents/scripts/test-wrapper.js +1 -1
  108. package/.agents/scripts/update-ticket-state.js +4 -3
  109. package/.agents/scripts/validate-skills.js +2 -1
  110. package/.agents/skills/core/gates-and-baselines/reference.md +1 -0
  111. package/.agents/workflows/audit-baselines.md +21 -9
  112. package/.agents/workflows/clean-git.md +1 -1
  113. package/.agents/workflows/helpers/audit-lens-core.md +1 -1
  114. package/.agents/workflows/helpers/code-quality-guardrails.md +3 -3
  115. package/README.md +1 -1
  116. package/docs/CHANGELOG.md +46 -0
  117. package/lib/cli/claude-code-version.js +13 -7
  118. package/lib/cli/doctor-checks/llm-review.js +12 -5
  119. package/lib/cli/doctor-checks/merge-driver.js +10 -6
  120. package/lib/cli/doctor-checks/project-access.js +21 -8
  121. package/lib/cli/doctor-checks/read-json.js +2 -15
  122. package/lib/cli/doctor-checks/spawn.js +29 -9
  123. package/lib/cli/doctor-checks/test-credit-path.js +2 -1
  124. package/lib/cli/doctor-checks/toolchain.js +16 -12
  125. package/lib/cli/doctor.js +31 -8
  126. package/lib/cli/registry.js +7 -10
  127. package/lib/cli/sync.js +46 -10
  128. package/lib/cli/uninstall.js +259 -175
  129. package/lib/cli/update.js +3 -3
  130. package/package.json +23 -20
@@ -96,10 +96,24 @@ function normalizeIssue(raw) {
96
96
  const number = typeof raw.number === 'number' ? raw.number : null;
97
97
  if (number === null) return null;
98
98
  const title = typeof raw.title === 'string' ? raw.title : '';
99
- const url = typeof raw.url === 'string' ? raw.url : '';
100
99
  const intake =
101
100
  typeof raw.body === 'string' && raw.body.includes(CI_GAP_INTAKE_MARKER);
102
- return { number, title, url, labels: normalizeLabels(raw.labels), intake };
101
+ return {
102
+ number,
103
+ title,
104
+ url: issueUrl(raw),
105
+ labels: normalizeLabels(raw.labels),
106
+ intake,
107
+ };
108
+ }
109
+
110
+ /**
111
+ * @param {{ html_url?: unknown, url?: unknown }} raw
112
+ * @returns {string}
113
+ */
114
+ function issueUrl(raw) {
115
+ if (typeof raw.html_url === 'string') return raw.html_url;
116
+ return typeof raw.url === 'string' ? raw.url : '';
103
117
  }
104
118
 
105
119
  /**
@@ -115,6 +129,30 @@ function normalizeLabels(raw) {
115
129
  .filter((name) => typeof name === 'string');
116
130
  }
117
131
 
132
+ const REST_PER_PAGE_MAX = 100;
133
+
134
+ /**
135
+ * REST, not `gh issue list` (GraphQL, refused in cloud sessions).
136
+ *
137
+ * @param {{ owner: string, repo: string, label: string, limit: number }} opts
138
+ * @returns {string[]}
139
+ */
140
+ function restIssuesArgs({ owner, repo, label, limit }) {
141
+ const perPage = Math.min(Math.max(1, limit), REST_PER_PAGE_MAX);
142
+ return [
143
+ 'api',
144
+ '-X',
145
+ 'GET',
146
+ `repos/${owner}/${repo}/issues`,
147
+ '-f',
148
+ 'state=open',
149
+ '-f',
150
+ `labels=${label}`,
151
+ '-f',
152
+ `per_page=${perPage}`,
153
+ ];
154
+ }
155
+
118
156
  /**
119
157
  * @param {object} opts
120
158
  * @param {string} opts.owner
@@ -126,21 +164,7 @@ function normalizeLabels(raw) {
126
164
  * @returns {Promise<{ issues: object[], error: string|null }>}
127
165
  */
128
166
  async function fetchByLabel({ owner, repo, label, ghPath, limit, spawnImpl }) {
129
- const args = [
130
- 'issue',
131
- 'list',
132
- '--repo',
133
- `${owner}/${repo}`,
134
- '--state',
135
- 'open',
136
- '--label',
137
- label,
138
- '--json',
139
- 'number,title,labels,url,body',
140
- '--limit',
141
- String(limit),
142
- ];
143
-
167
+ const args = restIssuesArgs({ owner, repo, label, limit });
144
168
  const result = await runGh({ ghPath, args, spawnImpl });
145
169
 
146
170
  if (
@@ -155,15 +179,18 @@ async function fetchByLabel({ owner, repo, label, ghPath, limit, spawnImpl }) {
155
179
  if (!Array.isArray(parsed)) {
156
180
  return {
157
181
  issues: [],
158
- error: `gh issue list returned non-array JSON for label "${label}"`,
182
+ error: `gh api issues returned non-array JSON for label "${label}"`,
159
183
  };
160
184
  }
161
- const issues = parsed.map(normalizeIssue).filter((issue) => issue !== null);
185
+ const issues = parsed
186
+ .filter((row) => !row?.pull_request)
187
+ .map(normalizeIssue)
188
+ .filter((issue) => issue !== null);
162
189
  return { issues, error: null };
163
190
  } catch (err) {
164
191
  return {
165
192
  issues: [],
166
- error: `Failed to parse gh issue list JSON for label "${label}": ${err.message}`,
193
+ error: `Failed to parse gh api issues JSON for label "${label}": ${err.message}`,
167
194
  };
168
195
  }
169
196
  }
@@ -6,6 +6,7 @@
6
6
  import { spawn as defaultSpawn } from 'node:child_process';
7
7
  import { spawnChild } from './child-exec.js';
8
8
  import { ghEnv, tryGhEnv } from './gh-env.js';
9
+ import { createRestPr } from './gh-pr-rest.js';
9
10
  import {
10
11
  isTransportFailure,
11
12
  sandboxDenialCode,
@@ -241,6 +242,9 @@ export function classify({
241
242
  return new GhExecError(`gh-exec: gh exited with code ${code}`, details);
242
243
  }
243
244
 
245
+ /** Windows (libuv) reports a broken pipe on a pending write as `EOF`. */
246
+ const BROKEN_PIPE_CODES = new Set(['EPIPE', 'EOF']);
247
+
244
248
  /**
245
249
  * @param {object} opts
246
250
  * @param {string[]} opts.args
@@ -293,6 +297,7 @@ export function exec({
293
297
  let stdout = '';
294
298
  let stderr = '';
295
299
  let settled = false;
300
+ let stdinError = null;
296
301
 
297
302
  child.stdout?.on('data', (chunk) => {
298
303
  stdout += chunk.toString('utf8');
@@ -315,7 +320,7 @@ export function exec({
315
320
  const timedOut =
316
321
  spawnOpts.timeout !== undefined &&
317
322
  (signal === 'SIGTERM' || code === null);
318
- if (timedOut && spawnOpts.timeout !== undefined) {
323
+ if (timedOut) {
319
324
  reject(
320
325
  new GhExecTimeoutError(
321
326
  `gh-exec: gh ${args.join(' ')} exceeded ${spawnOpts.timeout}ms`,
@@ -330,6 +335,17 @@ export function exec({
330
335
  return;
331
336
  }
332
337
 
338
+ // A clean exit after a failed stdin write may have run on truncated input.
339
+ if (stdinError) {
340
+ reject(
341
+ new GhExecError(
342
+ `gh-exec: writing gh stdin failed: ${stdinError.message}`,
343
+ { args, stdout, stderr, code },
344
+ ),
345
+ );
346
+ return;
347
+ }
348
+
333
349
  if (wantsJson) {
334
350
  try {
335
351
  resolve(JSON.parse(stdout));
@@ -347,6 +363,11 @@ export function exec({
347
363
  resolve({ stdout, stderr, code });
348
364
  });
349
365
 
366
+ // A gh that exits before reading stdin breaks the pipe; its exit still
367
+ // settles the call. Any other write error rejects at 'close', never throws.
368
+ child.stdin?.on?.('error', (err) => {
369
+ if (!BROKEN_PIPE_CODES.has(err.code)) stdinError = err;
370
+ });
350
371
  if (typeof input === 'string' && child.stdin) {
351
372
  child.stdin.end(input);
352
373
  } else if (child.stdin) {
@@ -355,13 +376,66 @@ export function exec({
355
376
  });
356
377
  }
357
378
 
379
+ /**
380
+ * The process-wide GraphQL-availability verdict, produced once — by close's
381
+ * preflight (`setGraphqlAvailability`) or the facade's first PR-surface use —
382
+ * and read by every facade. Only `unavailable` (the proxy 403) selects REST:
383
+ * `auth-failed` would fail REST the same way, and an inconclusive probe keeps
384
+ * the GraphQL path it was already on.
385
+ */
386
+ let graphqlLatch = null;
387
+ let graphqlLatchPending = null;
388
+
389
+ function transportForVerdict(verdict) {
390
+ return verdict?.verdict === 'unavailable' ? 'rest' : 'graphql';
391
+ }
392
+
393
+ /**
394
+ * Seed (or, with `null`, clear) the latch.
395
+ *
396
+ * @param {{ verdict: string }|null} verdict A `probeGraphqlAvailability` result.
397
+ */
398
+ export function setGraphqlAvailability(verdict) {
399
+ graphqlLatch = verdict ?? null;
400
+ graphqlLatchPending = null;
401
+ }
402
+
403
+ /**
404
+ * Synchronous read for callers that cannot await: true only once the latch
405
+ * has settled on `unavailable`.
406
+ *
407
+ * @returns {boolean}
408
+ */
409
+ export function prSurfaceUsesRest() {
410
+ return transportForVerdict(graphqlLatch) === 'rest';
411
+ }
412
+
413
+ /**
414
+ * The PR transport a facade will use; a facade without one (a test double)
415
+ * is on GraphQL.
416
+ *
417
+ * @param {{ prTransport?: () => Promise<string> }|null|undefined} facade
418
+ * @returns {Promise<'rest'|'graphql'>}
419
+ */
420
+ export async function prTransportOf(facade) {
421
+ if (typeof facade?.prTransport !== 'function') return 'graphql';
422
+ return (await facade.prTransport()) === 'rest' ? 'rest' : 'graphql';
423
+ }
424
+
358
425
  /**
359
426
  * Typed `gh` facade over an `exec` implementation (tests inject a fake).
360
427
  *
361
428
  * @param {Function} execImpl
362
429
  * @param {object} [defaultExecOpts] — per-call options win.
430
+ * @param {{ lazyProbe?: boolean }} [transportOpts] `lazyProbe`: probe GraphQL
431
+ * on first PR-surface use when nothing seeded the latch. Defaults on for the
432
+ * real spawner only, so an injected exec's call log stays its own.
363
433
  */
364
- export function createGh(execImpl = exec, defaultExecOpts = {}) {
434
+ export function createGh(
435
+ execImpl = exec,
436
+ defaultExecOpts = {},
437
+ { lazyProbe = execImpl === exec } = {},
438
+ ) {
365
439
  const execWithDefaults = (opts) => execImpl({ ...defaultExecOpts, ...opts });
366
440
  /**
367
441
  * @param {object} opts
@@ -425,7 +499,7 @@ export function createGh(execImpl = exec, defaultExecOpts = {}) {
425
499
  }),
426
500
  };
427
501
 
428
- const pr = {
502
+ const graphqlPr = {
429
503
  view: (id, fields) =>
430
504
  execWithDefaults({
431
505
  args: ['pr', 'view', idStr(id), ...jsonFlag(fields)],
@@ -444,6 +518,42 @@ export function createGh(execImpl = exec, defaultExecOpts = {}) {
444
518
  args: ['pr', 'list', ...flags, ...jsonFlag(fields)],
445
519
  }),
446
520
  };
521
+ const restPr = createRestPr({ api, GhExecError });
522
+
523
+ /** @returns {'rest'|'graphql'|null} null until a lazy probe settles it. */
524
+ function settledPrTransport() {
525
+ if (graphqlLatch) return transportForVerdict(graphqlLatch);
526
+ return lazyProbe ? null : 'graphql';
527
+ }
528
+
529
+ /** @returns {Promise<'rest'|'graphql'>} */
530
+ async function prTransport() {
531
+ const settled = settledPrTransport();
532
+ if (settled) return settled;
533
+ graphqlLatchPending ??= probeGraphqlAvailability({
534
+ ghFacade: { api },
535
+ }).then((verdict) => {
536
+ graphqlLatch ??= verdict;
537
+ return graphqlLatch;
538
+ });
539
+ return transportForVerdict(await graphqlLatchPending);
540
+ }
541
+
542
+ /** Synchronous when the transport is already known, so argv order is unchanged. */
543
+ function routed(name) {
544
+ return (...args) => {
545
+ const settled = settledPrTransport();
546
+ if (settled)
547
+ return (settled === 'rest' ? restPr : graphqlPr)[name](...args);
548
+ return prTransport().then((transport) =>
549
+ (transport === 'rest' ? restPr : graphqlPr)[name](...args),
550
+ );
551
+ };
552
+ }
553
+
554
+ const pr = Object.fromEntries(
555
+ Object.keys(graphqlPr).map((name) => [name, routed(name)]),
556
+ );
447
557
 
448
558
  const label = {
449
559
  create: (name, flags = []) =>
@@ -472,24 +582,11 @@ export function createGh(execImpl = exec, defaultExecOpts = {}) {
472
582
  };
473
583
 
474
584
  const defaults = Object.freeze({ ...defaultExecOpts });
475
- return { api, issue, pr, label, repo, defaults };
585
+ return { api, issue, pr, label, repo, defaults, prTransport };
476
586
  }
477
587
 
478
588
  export const gh = createGh();
479
589
 
480
- /**
481
- * `gh` routes every one of these through GraphQL, so a GraphQL 403 gates the
482
- * whole PR surface. Kept beside `pr` so the refusal text cannot drift.
483
- */
484
- const GH_PR_SUBCOMMANDS = Object.freeze([
485
- 'view',
486
- 'create',
487
- 'edit',
488
- 'merge',
489
- 'update-branch',
490
- 'list',
491
- ]);
492
-
493
590
  /** Cheapest authenticated GraphQL read: no repo, no extra scope. */
494
591
  const GRAPHQL_PROBE_QUERY = 'query{viewer{login}}';
495
592
 
@@ -577,14 +674,7 @@ export function describeGraphqlPreflight({ verdict, detail } = {}) {
577
674
  suffix
578
675
  );
579
676
  }
580
- const subcommands = GH_PR_SUBCOMMANDS.map((s) => `\`gh pr ${s}\``).join(', ');
581
- return (
582
- 'GitHub GraphQL is unavailable in this session (HTTP 403). `gh` routes the entire pull-request ' +
583
- `surface through GraphQL — ${subcommands} — so this close can neither open, inspect, nor merge ` +
584
- 'a pull request, and every later phase would fail the same way. Retrying here will not help: ' +
585
- 're-run the close from a local session, where GraphQL is reachable.' +
586
- suffix
587
- );
677
+ return `GitHub GraphQL preflight did not refuse this session (verdict=${verdict ?? 'unknown'}).${suffix}`;
588
678
  }
589
679
 
590
680
  export default exec;
@@ -0,0 +1,371 @@
1
+ /**
2
+ * gh-pr-rest.js — the `gh pr` facade over repo-scoped REST, for a session
3
+ * whose GitHub proxy refuses GraphQL (which every `gh pr` subcommand needs).
4
+ *
5
+ * Same signatures as `createGh().pr`, and rows in `gh`'s camelCase `--json`
6
+ * shape for exactly the fields current callers request. Only the flags those
7
+ * callers pass are parsed: any other flag or field throws, so a new caller
8
+ * cannot silently lose one. Every request is `repos/{owner}/{repo}/…` — `gh
9
+ * api` fills the placeholders from the current checkout — so the REST path
10
+ * never touches `graphql`, `search/*`, or a user/org endpoint.
11
+ *
12
+ * Takes its `api` and error class by injection so `gh-exec.js` can build it
13
+ * without an import cycle.
14
+ */
15
+
16
+ /** Arm outcome when the CCR auto-merge route refuses: the merge wait merges on green. */
17
+ export const REST_MERGE_ON_GREEN = 'rest-merge-on-green';
18
+
19
+ const REPO = 'repos/{owner}/{repo}';
20
+
21
+ /** Flag grammar per subcommand: `value` takes the next argv entry, `bool` does not. */
22
+ const FLAG_SPECS = Object.freeze({
23
+ list: {
24
+ '--head': 'value',
25
+ '--state': 'value',
26
+ '--base': 'value',
27
+ '--limit': 'value',
28
+ },
29
+ create: {
30
+ '--base': 'value',
31
+ '--head': 'value',
32
+ '--title': 'value',
33
+ '--body': 'value',
34
+ '--draft': 'bool',
35
+ },
36
+ edit: { '--title': 'value', '--body': 'value' },
37
+ merge: {
38
+ '--auto': 'bool',
39
+ '--squash': 'bool',
40
+ '--delete-branch': 'bool',
41
+ '--disable-auto': 'bool',
42
+ '--match-head-commit': 'value',
43
+ },
44
+ 'update-branch': {},
45
+ });
46
+
47
+ function upper(value, fallback = '') {
48
+ return typeof value === 'string' && value ? value.toUpperCase() : fallback;
49
+ }
50
+
51
+ function mapAutoMerge(autoMerge) {
52
+ if (!autoMerge) return null;
53
+ return {
54
+ enabledAt: null,
55
+ mergeMethod: upper(autoMerge.merge_method),
56
+ enabledBy: { login: autoMerge.enabled_by?.login ?? null },
57
+ };
58
+ }
59
+
60
+ /** Field → reader over a REST pull object; `statusCheckRollup` is read separately. */
61
+ const PULL_FIELDS = Object.freeze({
62
+ number: (p) => p.number,
63
+ url: (p) => p.html_url,
64
+ title: (p) => p.title,
65
+ state: (p) => (p.merged === true || p.merged_at ? 'MERGED' : upper(p.state)),
66
+ mergedAt: (p) => p.merged_at ?? null,
67
+ createdAt: (p) => p.created_at ?? null,
68
+ id: (p) => p.node_id,
69
+ headRefOid: (p) => p.head?.sha ?? null,
70
+ headRefName: (p) => p.head?.ref ?? null,
71
+ baseRefName: (p) => p.base?.ref ?? null,
72
+ isDraft: (p) => p.draft === true,
73
+ mergeStateStatus: (p) => upper(p.mergeable_state, 'UNKNOWN'),
74
+ autoMergeRequest: (p) => mapAutoMerge(p.auto_merge),
75
+ // REST has no review rollup, and nothing on the close path gates on it.
76
+ reviewDecision: () => null,
77
+ });
78
+
79
+ /** Fields a list row lacks (the list endpoint omits `mergeable_state`). */
80
+ const DETAIL_ONLY_FIELDS = new Set(['mergeStateStatus']);
81
+
82
+ const ROLLUP_FIELD = 'statusCheckRollup';
83
+
84
+ /**
85
+ * @param {{ api: Function, GhExecError: typeof Error }} deps
86
+ */
87
+ export function createRestPr({ api, GhExecError }) {
88
+ function refuse(message, args) {
89
+ return new GhExecError(`gh-pr-rest: ${message}`, { args });
90
+ }
91
+
92
+ async function call(method, endpoint, body) {
93
+ const result = await api({ method, endpoint, body });
94
+ return parseApiJson(result);
95
+ }
96
+
97
+ function parseFlags(sub, flags) {
98
+ const spec = FLAG_SPECS[sub];
99
+ const out = {};
100
+ const list = Array.isArray(flags) ? flags : [];
101
+ for (let i = 0; i < list.length; i += 1) {
102
+ const flag = list[i];
103
+ const kind = Object.hasOwn(spec, flag) ? spec[flag] : null;
104
+ if (!kind) {
105
+ throw refuse(`\`gh pr ${sub}\` flag ${flag} has no REST mapping`, [
106
+ 'pr',
107
+ sub,
108
+ ...list,
109
+ ]);
110
+ }
111
+ if (kind === 'bool') {
112
+ out[flag] = true;
113
+ } else {
114
+ i += 1;
115
+ out[flag] = list[i];
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ function prNumberOf(id, sub) {
122
+ const text = String(id ?? '');
123
+ const match = /^(\d+)$/.exec(text) ?? /\/pull\/(\d+)/.exec(text);
124
+ if (!match) {
125
+ throw refuse(`\`gh pr ${sub}\` needs a PR number or URL, got "${text}"`, [
126
+ 'pr',
127
+ sub,
128
+ text,
129
+ ]);
130
+ }
131
+ return Number(match[1]);
132
+ }
133
+
134
+ function assertFields(sub, fields) {
135
+ if (!Array.isArray(fields) || fields.length === 0) {
136
+ throw refuse(`\`gh pr ${sub}\` needs --json fields over REST`, [
137
+ 'pr',
138
+ sub,
139
+ ]);
140
+ }
141
+ for (const field of fields) {
142
+ if (field !== ROLLUP_FIELD && !Object.hasOwn(PULL_FIELDS, field)) {
143
+ throw refuse(
144
+ `\`gh pr ${sub}\` --json field ${field} has no REST mapping`,
145
+ ['pr', sub, '--json', fields.join(',')],
146
+ );
147
+ }
148
+ }
149
+ }
150
+
151
+ const getPull = (n) => call('GET', `${REPO}/pulls/${n}`);
152
+
153
+ async function readRollup(sha) {
154
+ if (!sha) return [];
155
+ const [runs, status] = await Promise.all([
156
+ call('GET', `${REPO}/commits/${sha}/check-runs?per_page=100`),
157
+ call('GET', `${REPO}/commits/${sha}/status`),
158
+ ]);
159
+ return [
160
+ ...(runs?.check_runs ?? []).map(toCheckRunNode),
161
+ ...(status?.statuses ?? []).map(toStatusContextNode),
162
+ ];
163
+ }
164
+
165
+ async function project(pull, fields) {
166
+ const row = {};
167
+ for (const field of fields) {
168
+ if (field === ROLLUP_FIELD) {
169
+ row[field] = await readRollup(pull.head?.sha);
170
+ } else {
171
+ row[field] = PULL_FIELDS[field](pull);
172
+ }
173
+ }
174
+ return row;
175
+ }
176
+
177
+ async function view(id, fields) {
178
+ const n = prNumberOf(id, 'view');
179
+ assertFields('view', fields);
180
+ return project(await getPull(n), fields);
181
+ }
182
+
183
+ async function list(flags = [], fields) {
184
+ const opts = parseFlags('list', flags);
185
+ assertFields('list', fields);
186
+ const rows = await call('GET', listEndpoint(opts));
187
+ const wanted = (Array.isArray(rows) ? rows : []).filter(
188
+ (p) => opts['--state'] !== 'merged' || p.merged_at,
189
+ );
190
+ const needsDetail = fields.some((f) => DETAIL_ONLY_FIELDS.has(f));
191
+ const out = [];
192
+ for (const row of wanted) {
193
+ out.push(
194
+ await project(needsDetail ? await getPull(row.number) : row, fields),
195
+ );
196
+ }
197
+ return out;
198
+ }
199
+
200
+ async function create(flags = []) {
201
+ const opts = parseFlags('create', flags);
202
+ const pull = await call('POST', `${REPO}/pulls`, {
203
+ title: opts['--title'],
204
+ head: opts['--head'],
205
+ base: opts['--base'],
206
+ body: opts['--body'] ?? '',
207
+ ...(opts['--draft'] ? { draft: true } : {}),
208
+ });
209
+ return envelope(`${pull?.html_url ?? ''}\n`);
210
+ }
211
+
212
+ async function edit(id, flags = []) {
213
+ const n = prNumberOf(id, 'edit');
214
+ const opts = parseFlags('edit', flags);
215
+ const patch = {};
216
+ if (opts['--title'] !== undefined) patch.title = opts['--title'];
217
+ if (opts['--body'] !== undefined) patch.body = opts['--body'];
218
+ const pull = await call('PATCH', `${REPO}/pulls/${n}`, patch);
219
+ return envelope(`${pull?.html_url ?? ''}\n`);
220
+ }
221
+
222
+ /**
223
+ * `--auto` arms through the CCR route; its refusal resolves (not throws)
224
+ * with `mergeOnGreen`, since the wait then owns the merge.
225
+ */
226
+ async function armAuto(n) {
227
+ try {
228
+ await call('PUT', `${REPO}/pulls/${n}/ccr/auto_merge`, {
229
+ merge_method: 'squash',
230
+ });
231
+ return envelope('');
232
+ } catch (err) {
233
+ return { ...envelope(''), mergeOnGreen: true, detail: describe(err) };
234
+ }
235
+ }
236
+
237
+ /** Squash-merge pinned to the head SHA, then reap the head ref (best-effort). */
238
+ async function squashMerge(n, opts) {
239
+ const pull = await getPull(n);
240
+ const sha = opts['--match-head-commit'] ?? pull.head?.sha;
241
+ const merged = await call('PUT', `${REPO}/pulls/${n}/merge`, {
242
+ merge_method: 'squash',
243
+ ...(sha ? { sha } : {}),
244
+ });
245
+ if (opts['--delete-branch'] && sameRepo(pull)) {
246
+ await call(
247
+ 'DELETE',
248
+ `${REPO}/git/refs/heads/${encodeRef(pull.head.ref)}`,
249
+ ).catch(() => null);
250
+ }
251
+ return {
252
+ ...envelope(''),
253
+ merged: merged?.merged === true,
254
+ sha: merged?.sha ?? null,
255
+ };
256
+ }
257
+
258
+ async function merge(id, flags = []) {
259
+ const n = prNumberOf(id, 'merge');
260
+ const opts = parseFlags('merge', flags);
261
+ if (opts['--disable-auto']) {
262
+ await call('DELETE', `${REPO}/pulls/${n}/ccr/auto_merge`);
263
+ return envelope('');
264
+ }
265
+ if (opts['--auto']) return armAuto(n);
266
+ if (!opts['--squash']) {
267
+ throw refuse('a REST merge supports --squash only', [
268
+ 'pr',
269
+ 'merge',
270
+ ...flags,
271
+ ]);
272
+ }
273
+ return squashMerge(n, opts);
274
+ }
275
+
276
+ async function updateBranch(id, flags = []) {
277
+ const n = prNumberOf(id, 'update-branch');
278
+ parseFlags('update-branch', flags);
279
+ await call('PUT', `${REPO}/pulls/${n}/update-branch`, {});
280
+ return envelope('');
281
+ }
282
+
283
+ return { view, list, create, edit, merge, updateBranch };
284
+ }
285
+
286
+ function envelope(stdout) {
287
+ return { stdout, stderr: '', code: 0 };
288
+ }
289
+
290
+ function describe(err) {
291
+ const stderr = String(err?.stderr ?? '').trim();
292
+ const message = String(err?.message ?? err);
293
+ return stderr ? `${message}: ${stderr.split('\n').at(-1)}` : message;
294
+ }
295
+
296
+ function sameRepo(pull) {
297
+ const head = pull?.head?.repo?.full_name;
298
+ const base = pull?.base?.repo?.full_name;
299
+ return Boolean(pull?.head?.ref) && (!head || !base || head === base);
300
+ }
301
+
302
+ function encodeRef(ref) {
303
+ return String(ref).split('/').map(encodeURIComponent).join('/');
304
+ }
305
+
306
+ function listEndpoint(opts) {
307
+ const params = [];
308
+ if (opts['--head'])
309
+ params.push(`head={owner}:${encodeURIComponent(opts['--head'])}`);
310
+ if (opts['--base']) params.push(`base=${encodeURIComponent(opts['--base'])}`);
311
+ const state = opts['--state'] ?? 'open';
312
+ params.push(`state=${state === 'merged' ? 'closed' : state}`);
313
+ if (opts['--limit']) params.push(`per_page=${Number(opts['--limit']) || 30}`);
314
+ return `${REPO}/pulls?${params.join('&')}`;
315
+ }
316
+
317
+ /** A REST check run as the `CheckRun` node `gh`'s rollup carries. */
318
+ function toCheckRunNode(run) {
319
+ return {
320
+ __typename: 'CheckRun',
321
+ name: run?.name ?? '',
322
+ status: upper(run?.status),
323
+ conclusion: upper(run?.conclusion),
324
+ startedAt: run?.started_at ?? '',
325
+ completedAt: run?.completed_at ?? '',
326
+ detailsUrl: run?.details_url ?? run?.html_url ?? '',
327
+ };
328
+ }
329
+
330
+ /** A REST commit status as the `StatusContext` node `gh`'s rollup carries. */
331
+ function toStatusContextNode(status) {
332
+ return {
333
+ __typename: 'StatusContext',
334
+ context: status?.context ?? '',
335
+ state: upper(status?.state),
336
+ targetUrl: status?.target_url ?? '',
337
+ startedAt: status?.created_at ?? '',
338
+ };
339
+ }
340
+
341
+ /**
342
+ * `gh api` output (`{ stdout }`, a string, or an already-parsed value) as JSON.
343
+ * An empty body (a 204) reads as `null`.
344
+ *
345
+ * @param {unknown} result
346
+ * @returns {unknown}
347
+ */
348
+ export function parseApiJson(result) {
349
+ if (result && typeof result === 'object' && !('stdout' in result))
350
+ return result;
351
+ const text = typeof result === 'string' ? result : result?.stdout;
352
+ const trimmed = String(text ?? '').trim();
353
+ return trimmed ? JSON.parse(trimmed) : null;
354
+ }
355
+
356
+ /**
357
+ * The active rulesets on `base` (`GET …/rules/branches/{base}`).
358
+ *
359
+ * @param {{ api: Function, base: string, timeoutMs?: number }} args
360
+ * @returns {Promise<Array<{ type?: string, parameters?: object }>>}
361
+ */
362
+ export async function readBranchRules({ api, base, timeoutMs }) {
363
+ const rules = parseApiJson(
364
+ await api({
365
+ method: 'GET',
366
+ endpoint: `${REPO}/rules/branches/${encodeRef(base)}`,
367
+ ...(timeoutMs ? { execOpts: { timeoutMs } } : {}),
368
+ }),
369
+ );
370
+ return Array.isArray(rules) ? rules : [];
371
+ }
@@ -139,7 +139,7 @@ export async function syncBranchFromBase({
139
139
  );
140
140
  }
141
141
 
142
- const driver = probeBaselineMergeDriver({
142
+ const driver = await probeBaselineMergeDriver({
143
143
  projectRoot: cwd,
144
144
  runGit: (args) => gitSpawn(cwd, ...args),
145
145
  });