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
@@ -1,10 +1,16 @@
1
1
  /**
2
- * merge-queue.js — the one GraphQL seam for a merge-queue-protected base:
3
- * whether the PR's base requires a queue, whether the PR sits in it, and the
4
- * dequeue. Keyed on the PR node, so no owner/repo is needed.
2
+ * merge-queue.js — the one seam for a merge-queue-protected base: whether the
3
+ * PR's base requires a queue, whether the PR sits in it, and the dequeue.
4
+ * GraphQL keys on the PR node, so no owner/repo is needed; the REST transport
5
+ * reads the base's rulesets and cannot see queue membership.
5
6
  */
6
7
 
7
- import { gh as defaultGh, describeGhFailure } from '../gh-exec.js';
8
+ import {
9
+ gh as defaultGh,
10
+ describeGhFailure,
11
+ prTransportOf,
12
+ } from '../gh-exec.js';
13
+ import { readBranchRules } from '../gh-pr-rest.js';
8
14
 
9
15
  /** Bound on each merge-queue GraphQL call, so a wedged `gh` cannot stall close. */
10
16
  const MERGE_QUEUE_GH_TIMEOUT_MS = 30_000;
@@ -18,6 +24,37 @@ const DEQUEUE_MUTATION =
18
24
  /** `gh` stderr when the base requires a merge queue and the arm spelling is wrong. */
19
25
  export const MERGE_QUEUE_REFUSAL = /when merge queue enabled/i;
20
26
 
27
+ /** Block class: a merge-queue base reached over the REST transport. */
28
+ export const MERGE_QUEUE_REST_BLOCK_CLASS = 'merge-queue-rest-unsupported';
29
+
30
+ /** The remedy that block carries: enqueueing is GraphQL-only. */
31
+ export const MERGE_QUEUE_REST_REMEDY =
32
+ "The PR's base branch requires a merge queue, and this session reaches GitHub over " +
33
+ 'repo-scoped REST only (GraphQL answers 403). Enqueueing is GraphQL-only, and a direct ' +
34
+ 'merge would bypass the queue, so close did not merge. Enqueue the PR from a session ' +
35
+ 'that can reach GraphQL (arm auto-merge there) or from the GitHub UI, then confirm with ' +
36
+ '`node .agents/scripts/single-story-confirm-merge.js --story <id>`.';
37
+
38
+ /**
39
+ * REST reading: the base's active rulesets name a `merge_queue` rule.
40
+ * Whether the PR sits in the queue is unreadable, so `inQueue` is null.
41
+ */
42
+ async function readMergeQueueStateRest({ prRef, prNodeId, facade, timeoutMs }) {
43
+ if (!prRef)
44
+ throw new Error('PR number unavailable for the REST merge-queue read');
45
+ const view = await facade.pr.view(String(prRef), ['id', 'baseRefName']);
46
+ const rules = await readBranchRules({
47
+ api: facade.api,
48
+ base: view?.baseRefName,
49
+ timeoutMs,
50
+ });
51
+ return {
52
+ queueRequired: rules.some((rule) => rule?.type === 'merge_queue'),
53
+ inQueue: null,
54
+ prNodeId: prNodeId ?? view?.id ?? null,
55
+ };
56
+ }
57
+
21
58
  /**
22
59
  * @param {{ stdout?: string }|string|undefined} result
23
60
  * @returns {object|null}
@@ -54,6 +91,14 @@ export async function readMergeQueueState({
54
91
  const facade = gh ?? defaultGh;
55
92
  let id = prNodeId ?? null;
56
93
  try {
94
+ if ((await prTransportOf(facade)) === 'rest') {
95
+ return await readMergeQueueStateRest({
96
+ prRef: prRef ?? prNumber,
97
+ prNodeId: id,
98
+ facade,
99
+ timeoutMs,
100
+ });
101
+ }
57
102
  if (!id) {
58
103
  const view = await facade.pr.view(String(prRef ?? prNumber), ['id']);
59
104
  id = typeof view?.id === 'string' && view.id ? view.id : null;
@@ -403,6 +403,24 @@ function logPersistEpilogue({
403
403
  }
404
404
  }
405
405
 
406
+ /**
407
+ * A dry run wrote nothing, so it claims no ready flip and offers no deliver
408
+ * command; the per-ticket `dry-run: would …` lines already said what it would do.
409
+ *
410
+ * @param {Parameters<typeof logPersistEpilogue>[0] & { dryRun: boolean }} args
411
+ * @returns {void}
412
+ */
413
+ function logRunEpilogue({ dryRun, ...epilogue }) {
414
+ if (!dryRun) {
415
+ logPersistEpilogue(epilogue);
416
+ return;
417
+ }
418
+ Logger.info(
419
+ `[plan-persist] dry-run: validated ${epilogue.created.length} Story(ies); ` +
420
+ 'nothing was written to GitHub.',
421
+ );
422
+ }
423
+
406
424
  /**
407
425
  * @param {{
408
426
  * provider: object,
@@ -597,11 +615,12 @@ export async function runPlanPersist({
597
615
  supersede.sourceTicketOrigin = sourceTicketOrigin;
598
616
 
599
617
  await cleanupPlanDirs({ config, planDir, skipCleanup });
600
- logPersistEpilogue({
618
+ logRunEpilogue({
601
619
  created,
602
620
  primary,
603
621
  planRunLabel,
604
622
  planRunLabelApplied,
623
+ dryRun,
605
624
  });
606
625
 
607
626
  return {
@@ -6,10 +6,10 @@
6
6
  */
7
7
 
8
8
  import {
9
- isProjectAccessFailure,
10
9
  ProjectAccessError,
11
10
  toProjectAccessError,
12
11
  } from './board-access-latch.js';
12
+ import { isBoardAccessFailure } from './board-graphql-latch.js';
13
13
 
14
14
  export { ProjectAccessError };
15
15
 
@@ -69,7 +69,7 @@ async function queryRung(
69
69
  );
70
70
  return data?.[scope.root]?.projectV2 ?? null;
71
71
  } catch (err) {
72
- if (isProjectAccessFailure(err)) throw toProjectAccessError(err);
72
+ if (isBoardAccessFailure(err)) throw toProjectAccessError(err);
73
73
  return null;
74
74
  }
75
75
  }
@@ -1,8 +1,11 @@
1
1
  /**
2
- * GitHub's per-PR required-check attribution (GraphQL `isRequired`), not
2
+ * GitHub's per-PR required-check attribution (GraphQL `isRequired`, or over
3
+ * the REST transport the base's rulesets plus classic protection), not
3
4
  * `.agentrc` requiredChecks, which are local command names.
4
5
  */
5
6
 
7
+ import { GhNotFoundError, prTransportOf } from '../gh-exec.js';
8
+ import { parseApiJson, readBranchRules } from '../gh-pr-rest.js';
6
9
  import {
7
10
  deriveRequiredRunEvidence,
8
11
  failingChecksBlockMerge,
@@ -71,6 +74,69 @@ function parseRequiredNames(result) {
71
74
  return names;
72
75
  }
73
76
 
77
+ /**
78
+ * Classic branch protection's required contexts; no protection (404) is none.
79
+ *
80
+ * @returns {Promise<string[]>}
81
+ */
82
+ async function readProtectionContexts({ api, base, timeoutMs }) {
83
+ try {
84
+ const body = parseApiJson(
85
+ await api({
86
+ method: 'GET',
87
+ endpoint: `repos/{owner}/{repo}/branches/${encodeURIComponent(base)}/protection/required_status_checks`,
88
+ execOpts: { timeoutMs },
89
+ }),
90
+ );
91
+ return [
92
+ ...(body?.contexts ?? []),
93
+ ...(body?.checks ?? []).map((check) => check?.context),
94
+ ];
95
+ } catch (err) {
96
+ if (err instanceof GhNotFoundError) return [];
97
+ throw err;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * REST required names: `required_status_checks` rules on the base, unioned
103
+ * with classic protection.
104
+ *
105
+ * @returns {Promise<Set<string>>}
106
+ */
107
+ async function readRequiredNamesRest({ prNumber, gh, timeoutMs }) {
108
+ const view = await gh.pr.view(String(prNumber), ['baseRefName']);
109
+ const base = view?.baseRefName;
110
+ if (!base) throw new Error('PR base branch unreadable');
111
+ const [rules, contexts] = await Promise.all([
112
+ readBranchRules({ api: gh.api, base, timeoutMs }),
113
+ readProtectionContexts({ api: gh.api, base, timeoutMs }),
114
+ ]);
115
+ const names = new Set(contexts.filter(Boolean));
116
+ for (const rule of rules) {
117
+ if (rule?.type !== 'required_status_checks') continue;
118
+ for (const check of rule.parameters?.required_status_checks ?? []) {
119
+ if (check?.context) names.add(check.context);
120
+ }
121
+ }
122
+ return names;
123
+ }
124
+
125
+ /** @returns {Promise<Set<string>>} */
126
+ async function readRequiredNamesGraphql({ prNodeId, prNumber, gh, timeoutMs }) {
127
+ return parseRequiredNames(
128
+ await gh.api({
129
+ method: 'POST',
130
+ endpoint: 'graphql',
131
+ body: {
132
+ query: REQUIRED_CHECKS_QUERY,
133
+ variables: { id: prNodeId, n: Number(prNumber) },
134
+ },
135
+ execOpts: { timeoutMs },
136
+ }),
137
+ );
138
+ }
139
+
74
140
  /** Per-head cache: required attribution is read at most once per PR head. */
75
141
  const requiredNamesCache = new Map();
76
142
 
@@ -92,17 +158,11 @@ async function readRequiredCheckNames({
92
158
  const key = `${prNodeId}@${headSha}`;
93
159
  if (requiredNamesCache.has(key)) return requiredNamesCache.get(key);
94
160
  try {
95
- const names = parseRequiredNames(
96
- await gh.api({
97
- method: 'POST',
98
- endpoint: 'graphql',
99
- body: {
100
- query: REQUIRED_CHECKS_QUERY,
101
- variables: { id: prNodeId, n: Number(prNumber) },
102
- },
103
- execOpts: { timeoutMs },
104
- }),
105
- );
161
+ const read =
162
+ (await prTransportOf(gh)) === 'rest'
163
+ ? readRequiredNamesRest
164
+ : readRequiredNamesGraphql;
165
+ const names = await read({ prNodeId, prNumber, gh, timeoutMs });
106
166
  requiredNamesCache.set(key, names);
107
167
  return names;
108
168
  } catch {
@@ -5,6 +5,7 @@
5
5
  * @typedef {import('./types.js').Finding} Finding
6
6
  */
7
7
 
8
+ import { isObject } from '../../json-utils.js';
8
9
  import { buildFinding, unwrapEnvelope } from './parse-findings.js';
9
10
 
10
11
  export const FINDINGS_SCHEMA_JSON = JSON.stringify({
@@ -192,9 +193,7 @@ function failureReason(result, envelope) {
192
193
 
193
194
  function parseEnvelope(stdout) {
194
195
  const parsed = tryParseJson(stdout);
195
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
196
- ? parsed
197
- : null;
196
+ return isObject(parsed) ? parsed : null;
198
197
  }
199
198
 
200
199
  function isSuccess(result, envelope) {
@@ -7,6 +7,8 @@
7
7
  * @typedef {import('./types.js').Severity} Severity
8
8
  */
9
9
 
10
+ import { isObject } from '../../json-utils.js';
11
+
10
12
  /**
11
13
  * Unwrap a bare array, `{ findings }`, or either under `result`/`data`.
12
14
  * A non-array result is returned for the caller to reject.
@@ -16,12 +18,12 @@
16
18
  */
17
19
  export function unwrapEnvelope(parsed) {
18
20
  let value = parsed;
19
- if (value && typeof value === 'object' && !Array.isArray(value)) {
21
+ if (isObject(value)) {
20
22
  if (Array.isArray(value.findings)) value = value.findings;
21
23
  else if (value.result !== undefined) value = value.result;
22
24
  else if (value.data !== undefined) value = value.data;
23
25
  }
24
- if (value && typeof value === 'object' && !Array.isArray(value)) {
26
+ if (isObject(value)) {
25
27
  if (Array.isArray(value.findings)) value = value.findings;
26
28
  }
27
29
  return value;
@@ -9,7 +9,12 @@
9
9
  * repo's `delete_branch_on_merge` owns the remote branch reap.
10
10
  */
11
11
 
12
- import { gh as defaultGh, describeGhFailure } from '../../../gh-exec.js';
12
+ import {
13
+ gh as defaultGh,
14
+ describeGhFailure,
15
+ prTransportOf,
16
+ } from '../../../gh-exec.js';
17
+ import { REST_MERGE_ON_GREEN } from '../../../gh-pr-rest.js';
13
18
  import { resolveAutoMergeArmCwd } from '../../auto-merge-cwd.js';
14
19
  import {
15
20
  decideAdvisoryGateBlock,
@@ -19,6 +24,7 @@ import {
19
24
  armForMergeQueue,
20
25
  disarmByDequeue,
21
26
  MERGE_QUEUE_REFUSAL,
27
+ MERGE_QUEUE_REST_BLOCK_CLASS,
22
28
  readMergeQueueState,
23
29
  } from '../../merge-queue.js';
24
30
 
@@ -139,12 +145,30 @@ export async function enableAutoMergeWith({
139
145
  resolveArmCwd = resolveAutoMergeArmCwd,
140
146
  queueRequired = false,
141
147
  }) {
142
- const exec = runner ?? makeDefaultGhAutoMergeRunner(gh ?? defaultGh);
148
+ const facade = gh ?? defaultGh;
149
+ const refused = await refuseQueueOverRest(facade, queueRequired);
150
+ if (refused) return refused;
151
+ const exec = runner ?? makeDefaultGhAutoMergeRunner(facade);
143
152
  const armCwd = resolveArmCwd(cwd);
144
153
  const arm = queueRequired ? armForMergeQueue : armNativeAutoMerge;
145
154
  return arm({ exec, prNumber, armCwd });
146
155
  }
147
156
 
157
+ /**
158
+ * A merge-queue base over the REST transport: enqueueing is GraphQL-only, and
159
+ * a direct merge would bypass the queue, so the arm refuses.
160
+ *
161
+ * @returns {Promise<{ enabled: false, mergeQueue: true, reason: string }|null>}
162
+ */
163
+ async function refuseQueueOverRest(facade, queueRequired) {
164
+ if (!queueRequired || (await prTransportOf(facade)) !== 'rest') return null;
165
+ return {
166
+ enabled: false,
167
+ mergeQueue: true,
168
+ reason: MERGE_QUEUE_REST_BLOCK_CLASS,
169
+ };
170
+ }
171
+
148
172
  /** The hand-run equivalent of the arm, for an operator-facing remedy. */
149
173
  export function manualArmCommand({ prNumber, queueRequired = false }) {
150
174
  return queueRequired
@@ -177,6 +201,37 @@ export async function rearmAutoMerge({
177
201
  });
178
202
  }
179
203
 
204
+ /**
205
+ * The merge wait's own squash-merge for a PR the CCR route would not arm,
206
+ * pinned to the head SHA it saw green (a moved head is refused), with the
207
+ * head ref reaped. Lives here because `lifecycle-lint` confines `gh pr merge`
208
+ * to this module. Never throws.
209
+ *
210
+ * @param {{ prNumber: number, headSha: string, gh?: object }} args
211
+ * @returns {Promise<{ merged: boolean, detail: string }>}
212
+ */
213
+ export async function mergeOnGreen({ prNumber, headSha, gh }) {
214
+ try {
215
+ const result = await (gh ?? defaultGh).pr.merge(String(prNumber), [
216
+ '--squash',
217
+ '--delete-branch',
218
+ '--match-head-commit',
219
+ headSha,
220
+ ]);
221
+ const merged = result?.merged !== false;
222
+ return { merged, detail: merged ? 'merged' : 'merge not performed' };
223
+ } catch (err) {
224
+ return { merged: false, detail: describeGhFailure(err) };
225
+ }
226
+ }
227
+
228
+ /** A zero-exit arm; the REST transport's CCR refusal hands the merge to the wait. */
229
+ function armedOutcome(result) {
230
+ return result.mergeOnGreen
231
+ ? { enabled: true, mergeOnGreen: true, reason: result.stderr }
232
+ : { enabled: true };
233
+ }
234
+
180
235
  /**
181
236
  * `--auto --squash --delete-branch`, falling back to a direct squash-merge
182
237
  * only when native auto-merge is unavailable.
@@ -194,7 +249,7 @@ async function armNativeAutoMerge({ exec, prNumber, armCwd }) {
194
249
  ],
195
250
  { cwd: armCwd },
196
251
  );
197
- if (result.status === 0) return { enabled: true };
252
+ if (result.status === 0) return armedOutcome(result);
198
253
  const detail = `gh-exit-${result.status}: ${(result.stderr ?? '').trim().slice(0, 200)}`;
199
254
  if (isLocalCleanupOnlyFailure(result.stderr)) {
200
255
  // The remote side stands; the land tail finishes the local ref reap.
@@ -218,6 +273,21 @@ async function armNativeAutoMerge({ exec, prNumber, armCwd }) {
218
273
  }
219
274
  }
220
275
 
276
+ /**
277
+ * A resolved `gh.pr.merge` as the runner envelope. The REST transport's CCR
278
+ * refusal resolves too, carrying `mergeOnGreen` and its detail as `stderr`.
279
+ */
280
+ function successEnvelope(result) {
281
+ if (result?.mergeOnGreen) {
282
+ return { status: 0, stdout: '', stderr: result.detail, mergeOnGreen: true };
283
+ }
284
+ return {
285
+ status: 0,
286
+ stdout: result?.stdout ?? '',
287
+ stderr: result?.stderr ?? '',
288
+ };
289
+ }
290
+
221
291
  /**
222
292
  * Adapt `gh.pr.merge` into the `{ status, stdout, stderr }` envelope,
223
293
  * mapping non-zero exits back to that envelope rather than throwing.
@@ -226,12 +296,7 @@ function makeDefaultGhAutoMergeRunner(gh) {
226
296
  return async function defaultGhAutoMergeRunner(args, _opts) {
227
297
  const [, , prIdStr, ...flags] = args;
228
298
  try {
229
- const result = await gh.pr.merge(prIdStr, flags);
230
- return {
231
- status: 0,
232
- stdout: result?.stdout ?? '',
233
- stderr: result?.stderr ?? '',
234
- };
299
+ return successEnvelope(await gh.pr.merge(prIdStr, flags));
235
300
  } catch (err) {
236
301
  // Any error with a numeric `.code`/`.status` maps to the envelope;
237
302
  // a codeless Error falls through to the caller's spawn-error reason.
@@ -392,60 +457,69 @@ async function evaluateAdvisoryGate({
392
457
  };
393
458
  }
394
459
 
460
+ /** The fields every standing arm reports. */
461
+ const ARMED = Object.freeze({ autoMergeEnabled: true, autoMergeReason: null });
462
+
463
+ /** How each kind of standing arm reports, and the outcome it returns. */
464
+ const ARMED_REPORTS = Object.freeze({
465
+ mergeOnGreen: ({ result, prNumber }) => [
466
+ `↪ The CCR auto-merge route refused PR #${prNumber} (${result.reason || 'no detail'}) — ` +
467
+ 'the merge wait squash-merges it, pinned to the head SHA, once it is CLEAN with green checks.',
468
+ {
469
+ ...ARMED,
470
+ autoMergeReason: REST_MERGE_ON_GREEN,
471
+ localCleanupDeferred: false,
472
+ },
473
+ ],
474
+ mergeQueue: ({ prNumber }) => [
475
+ `✅ Auto-merge enabled on PR #${prNumber} (merge queue — the queue rule picks the strategy).`,
476
+ { ...ARMED, localCleanupDeferred: false, mergeQueue: true },
477
+ ],
478
+ directMerged: ({ result, prNumber }) => [
479
+ `✅ Native auto-merge unavailable on PR #${prNumber} — direct squash-merge landed it` +
480
+ (result.localCleanupDeferred
481
+ ? " (gh's LOCAL branch cleanup deferred to the land tail; the merge stands)."
482
+ : '.'),
483
+ {
484
+ ...ARMED,
485
+ directMerged: true,
486
+ localCleanupDeferred: Boolean(result.localCleanupDeferred),
487
+ },
488
+ ],
489
+ localCleanupDeferred: ({ result, prNumber }) => [
490
+ `⚠️ Auto-merge armed on PR #${prNumber}, but gh's LOCAL branch cleanup failed ` +
491
+ `(${result.reason}) — deferring the local ref reap to the land tail; the merge stands.`,
492
+ { ...ARMED, localCleanupDeferred: true },
493
+ ],
494
+ plain: ({ prNumber }) => [
495
+ `✅ Auto-merge enabled on PR #${prNumber} (squash, delete-branch).`,
496
+ { ...ARMED, localCleanupDeferred: false },
497
+ ],
498
+ });
499
+
500
+ /** The first flag a standing arm carries, in precedence order. */
501
+ function armedKind(result) {
502
+ const kinds = [
503
+ 'mergeOnGreen',
504
+ 'mergeQueue',
505
+ 'directMerged',
506
+ 'localCleanupDeferred',
507
+ ];
508
+ return kinds.find((kind) => result[kind]) ?? 'plain';
509
+ }
510
+
395
511
  /**
396
512
  * Report an arm that stood, naming how it will land.
397
513
  *
398
- * @returns {{ autoMergeEnabled: true, autoMergeReason: null, localCleanupDeferred: boolean, directMerged?: boolean, mergeQueue?: boolean }}
514
+ * @returns {{ autoMergeEnabled: true, autoMergeReason: string|null, localCleanupDeferred: boolean, directMerged?: boolean, mergeQueue?: boolean }}
399
515
  */
400
516
  function reportArmed({ result, prNumber, progress }) {
401
- if (result.mergeQueue) {
402
- progress(
403
- 'PR',
404
- `✅ Auto-merge enabled on PR #${prNumber} (merge queue — the queue rule picks the strategy).`,
405
- );
406
- return {
407
- autoMergeEnabled: true,
408
- autoMergeReason: null,
409
- localCleanupDeferred: false,
410
- mergeQueue: true,
411
- };
412
- }
413
- if (result.directMerged) {
414
- progress(
415
- 'PR',
416
- `✅ Native auto-merge unavailable on PR #${prNumber} — direct squash-merge landed it` +
417
- (result.localCleanupDeferred
418
- ? " (gh's LOCAL branch cleanup deferred to the land tail; the merge stands)."
419
- : '.'),
420
- );
421
- return {
422
- autoMergeEnabled: true,
423
- autoMergeReason: null,
424
- directMerged: true,
425
- localCleanupDeferred: Boolean(result.localCleanupDeferred),
426
- };
427
- }
428
- if (result.localCleanupDeferred) {
429
- progress(
430
- 'PR',
431
- `⚠️ Auto-merge armed on PR #${prNumber}, but gh's LOCAL branch cleanup failed ` +
432
- `(${result.reason}) — deferring the local ref reap to the land tail; the merge stands.`,
433
- );
434
- return {
435
- autoMergeEnabled: true,
436
- autoMergeReason: null,
437
- localCleanupDeferred: true,
438
- };
439
- }
440
- progress(
441
- 'PR',
442
- `✅ Auto-merge enabled on PR #${prNumber} (squash, delete-branch).`,
443
- );
444
- return {
445
- autoMergeEnabled: true,
446
- autoMergeReason: null,
447
- localCleanupDeferred: false,
448
- };
517
+ const [line, outcome] = ARMED_REPORTS[armedKind(result)]({
518
+ result,
519
+ prNumber,
520
+ });
521
+ progress('PR', line);
522
+ return outcome;
449
523
  }
450
524
 
451
525
  /**