mandrel 2.114.0 → 2.116.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 (44) hide show
  1. package/.agents/docs/agentrc-reference.json +1 -0
  2. package/.agents/docs/configuration.md +18 -4
  3. package/.agents/docs/workflows.md +2 -1
  4. package/.agents/schemas/agentrc.schema.json +54 -1
  5. package/.agents/scripts/acceptance-eval.js +2 -2
  6. package/.agents/scripts/ceremony-derive.js +15 -2
  7. package/.agents/scripts/closeout-audit.js +132 -0
  8. package/.agents/scripts/lib/baselines/crap-preview-scan.js +15 -8
  9. package/.agents/scripts/lib/baselines/crap-preview-touched.js +140 -0
  10. package/.agents/scripts/lib/baselines/crap-prune.js +86 -0
  11. package/.agents/scripts/lib/baselines/kinds/crap.js +12 -4
  12. package/.agents/scripts/lib/baselines/seat-missing.js +1 -1
  13. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  14. package/.agents/scripts/lib/config/gates/crap.schema.js +7 -0
  15. package/.agents/scripts/lib/config/quality.js +3 -0
  16. package/.agents/scripts/lib/config/temp-paths.js +12 -0
  17. package/.agents/scripts/lib/config-settings-schema-delivery.js +34 -0
  18. package/.agents/scripts/lib/coverage-capture-delta.js +26 -3
  19. package/.agents/scripts/lib/coverage-capture-own-fix.js +35 -19
  20. package/.agents/scripts/lib/coverage-capture.js +62 -14
  21. package/.agents/scripts/lib/crap-engine.js +3 -5
  22. package/.agents/scripts/lib/crap-utils.js +12 -2
  23. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  24. package/.agents/scripts/lib/git-branch-lifecycle.js +2 -1
  25. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  26. package/.agents/scripts/lib/orchestrate/classify.js +238 -0
  27. package/.agents/scripts/lib/orchestrate/conflicts.js +119 -0
  28. package/.agents/scripts/lib/orchestrate/inherited-failure.js +66 -0
  29. package/.agents/scripts/lib/orchestrate/inventory.js +388 -0
  30. package/.agents/scripts/lib/orchestrate/ledger.js +223 -0
  31. package/.agents/scripts/lib/orchestration/closeout-audit.js +511 -0
  32. package/.agents/scripts/lib/orchestration/handoff-gates.js +25 -8
  33. package/.agents/scripts/lib/orchestration/merge-queue.js +1 -1
  34. package/.agents/scripts/lib/orchestration/required-checks.js +12 -2
  35. package/.agents/scripts/lib/orchestration/story-handoff.js +131 -41
  36. package/.agents/scripts/orchestrate-inventory.js +70 -0
  37. package/.agents/scripts/orchestrate-ledger.js +141 -0
  38. package/.agents/scripts/single-story-init.js +43 -5
  39. package/.agents/scripts/story-handoff.js +6 -2
  40. package/.agents/workflows/helpers/deliver-digest.md +3 -3
  41. package/.agents/workflows/helpers/deliver-reference.md +31 -4
  42. package/.agents/workflows/mandrel-orchestrate.md +140 -0
  43. package/docs/CHANGELOG.md +21 -0
  44. package/package.json +1 -1
@@ -0,0 +1,511 @@
1
+ /**
2
+ * closeout-audit — report every landed Story whose close-out did not finish,
3
+ * and (on `execute`) repair each drifted check through the seam that already
4
+ * owns it. Probes, repairs and the lock are injected; the evaluation is pure.
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import { spawnChild } from '../child-exec.js';
9
+ import { readDeferralMarker } from '../coverage-deferral.js';
10
+ import { gh as defaultGh } from '../gh-exec.js';
11
+ import { deleteBranchRemote } from '../git-branch-cleanup.js';
12
+ import {
13
+ gitSpawn as defaultGitSpawn,
14
+ getStoryBranch,
15
+ parseStoryBranch,
16
+ } from '../git-utils.js';
17
+ import { AGENT_LABELS } from '../label-constants.js';
18
+ import { buildProtectionCtx } from '../single-story-sweep/protection-ctx.js';
19
+ import {
20
+ acquireSweepLock,
21
+ resolveSweepLockPath,
22
+ } from '../single-story-sweep/sweep-lock.js';
23
+ import { sweepMergedBranches } from '../single-story-sweep.js';
24
+ import { purgeStoryTempArtifacts } from '../temp-retention.js';
25
+ import { ColumnSync, columnForLabels } from './column-sync.js';
26
+ import { probeBranch, probePr, probeTicket } from './deliver-recover.js';
27
+ import { isPrMerged } from './merge-poll.js';
28
+ import { sweepStaleStoryWorktrees } from './plan-runner/worktree-sweep.js';
29
+ import { NEXT_COMMANDS } from './story-deliver-terminal.js';
30
+
31
+ /** Repair order: `story-state` first, its land tail clears most of the rest. */
32
+ const CHECKS = Object.freeze([
33
+ 'story-state',
34
+ 'board-status',
35
+ 'remote-branch',
36
+ 'local-branch',
37
+ 'worktree',
38
+ 'scratch',
39
+ ]);
40
+
41
+ export const DEFAULT_SINCE_HOURS = 24;
42
+
43
+ // shortcut: one page of 100 recent merged PRs, raise it if a window holds more.
44
+ const MERGED_PR_PAGE = 100;
45
+
46
+ const auditCommand = (id) =>
47
+ `node .agents/scripts/closeout-audit.js --story ${id} --execute`;
48
+
49
+ function repairCommandFor(check, storyId) {
50
+ if (check === 'story-state') return NEXT_COMMANDS.confirmMerge(storyId);
51
+ if (check === 'board-status') return NEXT_COMMANDS.resync(storyId);
52
+ return auditCommand(storyId);
53
+ }
54
+
55
+ function row(check, storyId, status, evidence) {
56
+ return {
57
+ check,
58
+ status,
59
+ evidence,
60
+ repair: status === 'drift' ? repairCommandFor(check, storyId) : null,
61
+ repaired: false,
62
+ };
63
+ }
64
+
65
+ function storyStateRow(storyId, { ticket, pr }) {
66
+ if (!ticket?.ok) {
67
+ return row(
68
+ 'story-state',
69
+ storyId,
70
+ 'unknown',
71
+ `ticket unreadable: ${ticket?.error}`,
72
+ );
73
+ }
74
+ const issue = String(ticket.issueState ?? 'unknown').toLowerCase();
75
+ const label = ticket.stateLabel ?? 'none';
76
+ const marker = readDeferralMarker(pr?.body);
77
+ const evidence =
78
+ `issue=${issue} label=${label} pr=#${pr.number} merged` +
79
+ (marker ? `; Coverage-deferred: ${marker}` : '');
80
+ const ok = issue === 'closed' && label === AGENT_LABELS.DONE;
81
+ return row('story-state', storyId, ok ? 'ok' : 'drift', evidence);
82
+ }
83
+
84
+ function boardRow(storyId, { ticket, board }) {
85
+ const expected = ticket?.ok ? columnForLabels(ticket.labels) : null;
86
+ if (!board?.ok || !expected || !board.column) {
87
+ const why = board?.ok === false ? board.error : 'no Status to compare';
88
+ return row('board-status', storyId, 'unknown', `board unreadable: ${why}`);
89
+ }
90
+ const ok = board.column === expected;
91
+ return row(
92
+ 'board-status',
93
+ storyId,
94
+ ok ? 'ok' : 'drift',
95
+ `Status=${board.column} expected=${expected}`,
96
+ );
97
+ }
98
+
99
+ function presenceRow(check, storyId, present, evidence) {
100
+ return row(check, storyId, present ? 'drift' : 'ok', evidence);
101
+ }
102
+
103
+ /**
104
+ * Pure: one row per check from a Story's probe readings.
105
+ *
106
+ * @param {number} storyId
107
+ * @param {object} r `{ ticket, pr, board, branch, remote, scratch }`
108
+ * @returns {object[]}
109
+ */
110
+ function evaluateStory(storyId, r) {
111
+ const branchName = getStoryBranch(storyId);
112
+ if (!isPrMerged(r.pr)) {
113
+ const why = r.pr?.error
114
+ ? `PR probe failed: ${r.pr.error}`
115
+ : `no merged ${branchName} PR — not landed`;
116
+ return CHECKS.map((c) => row(c, storyId, 'unknown', why));
117
+ }
118
+ const remote = r.remote?.ok
119
+ ? presenceRow(
120
+ 'remote-branch',
121
+ storyId,
122
+ Boolean(r.remote.sha),
123
+ r.remote.sha
124
+ ? `origin/${branchName} at ${r.remote.sha}`
125
+ : `origin/${branchName} absent`,
126
+ )
127
+ : row(
128
+ 'remote-branch',
129
+ storyId,
130
+ 'unknown',
131
+ `ls-remote failed: ${r.remote?.error}`,
132
+ );
133
+ const scratch = r.scratch?.error
134
+ ? row('scratch', storyId, 'unknown', `temp scan failed: ${r.scratch.error}`)
135
+ : presenceRow(
136
+ 'scratch',
137
+ storyId,
138
+ r.scratch.paths.length > 0,
139
+ r.scratch.paths.length
140
+ ? r.scratch.paths.join(', ')
141
+ : 'no per-Story temp artifacts',
142
+ );
143
+ return [
144
+ storyStateRow(storyId, r),
145
+ boardRow(storyId, r),
146
+ remote,
147
+ presenceRow(
148
+ 'local-branch',
149
+ storyId,
150
+ r.branch.local,
151
+ r.branch.local ? `refs/heads/${branchName}` : 'no local ref',
152
+ ),
153
+ presenceRow(
154
+ 'worktree',
155
+ storyId,
156
+ Boolean(r.branch.worktreePath),
157
+ r.branch.worktreePath ?? 'no worktree',
158
+ ),
159
+ scratch,
160
+ ];
161
+ }
162
+
163
+ async function auditStory(storyId, probes) {
164
+ const pr = await probes.pr(storyId);
165
+ const ticket = await probes.ticket(storyId);
166
+ const readings = {
167
+ ticket,
168
+ pr,
169
+ board: await probes.board(storyId),
170
+ branch: await probes.branch(storyId),
171
+ remote: await probes.remote(storyId),
172
+ scratch: await probes.scratch(storyId),
173
+ };
174
+ return {
175
+ storyId,
176
+ pr: pr?.number ?? null,
177
+ readings,
178
+ checks: evaluateStory(storyId, readings),
179
+ };
180
+ }
181
+
182
+ async function safeRepair(fn, entry) {
183
+ try {
184
+ return (await fn(entry)) ?? { ok: true };
185
+ } catch (err) {
186
+ return { ok: false, reason: String(err?.message ?? err) };
187
+ }
188
+ }
189
+
190
+ async function repairStory(before, { probes, repairs }) {
191
+ const reasons = new Map();
192
+ let current = before;
193
+ for (const check of CHECKS) {
194
+ if (current.checks.find((c) => c.check === check)?.status !== 'drift')
195
+ continue;
196
+ const res = await safeRepair(repairs[check], current);
197
+ if (!res.ok) reasons.set(check, res.reason ?? 'refused');
198
+ if (check === 'story-state')
199
+ current = await auditStory(before.storyId, probes);
200
+ }
201
+ const after = await auditStory(before.storyId, probes);
202
+ return markOutcome(before, after, (check) =>
203
+ reasons.has(check)
204
+ ? `repair refused: ${reasons.get(check)}`
205
+ : 'still drifted after repair',
206
+ );
207
+ }
208
+
209
+ function markOutcome(before, after, reasonFor) {
210
+ const checks = after.checks.map((c) => {
211
+ const was = before.checks.find((b) => b.check === c.check)?.status;
212
+ if (c.status === 'drift' && was === 'drift') {
213
+ return { ...c, evidence: `${c.evidence}; ${reasonFor(c.check)}` };
214
+ }
215
+ return { ...c, repaired: was === 'drift' && c.status === 'ok' };
216
+ });
217
+ return { ...after, checks };
218
+ }
219
+
220
+ function summarize(stories) {
221
+ const all = stories.flatMap((s) => s.checks);
222
+ const count = (pred) => all.filter(pred).length;
223
+ return {
224
+ stories: stories.length,
225
+ ok: count((c) => c.status === 'ok'),
226
+ drift: count((c) => c.status === 'drift'),
227
+ unknown: count((c) => c.status === 'unknown'),
228
+ repaired: count((c) => c.repaired),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Audit each Story; on `execute`, repair drift under one lock and re-audit.
234
+ *
235
+ * @param {{ storyIds: number[], scope: object, probes: object, repairs?: object,
236
+ * execute?: boolean, withLock?: Function }} args
237
+ * @returns {Promise<object>} the `closeout-audit` envelope.
238
+ */
239
+ export async function runCloseoutAudit({
240
+ storyIds,
241
+ scope,
242
+ probes,
243
+ repairs,
244
+ execute = false,
245
+ withLock,
246
+ }) {
247
+ let stories = [];
248
+ for (const id of storyIds) stories.push(await auditStory(id, probes));
249
+ const drifted = stories.some((s) =>
250
+ s.checks.some((c) => c.status === 'drift'),
251
+ );
252
+ if (execute && drifted) {
253
+ const locked = await withLock(async () => {
254
+ const out = [];
255
+ for (const s of stories)
256
+ out.push(await repairStory(s, { probes, repairs }));
257
+ return out;
258
+ });
259
+ stories = locked.locked
260
+ ? locked.value
261
+ : stories.map((s) =>
262
+ markOutcome(
263
+ s,
264
+ s,
265
+ () => `repair skipped: sweep lock ${locked.reason}`,
266
+ ),
267
+ );
268
+ }
269
+ const clean = stories.map(({ readings, ...s }) => s);
270
+ return {
271
+ kind: 'closeout-audit',
272
+ scope,
273
+ stories: clean,
274
+ summary: summarize(clean),
275
+ };
276
+ }
277
+
278
+ /** 0 nothing drifted (or all repaired), 2 drift remains. */
279
+ export function exitCodeFor(envelope) {
280
+ return envelope.summary.drift > 0 ? 2 : 0;
281
+ }
282
+
283
+ export function renderAudit(envelope) {
284
+ const lines = [];
285
+ for (const s of envelope.stories) {
286
+ lines.push(`Story #${s.storyId} (PR ${s.pr ? `#${s.pr}` : 'none'})`);
287
+ for (const c of s.checks) {
288
+ const mark = c.repaired ? 'repaired' : c.status;
289
+ lines.push(` ${c.check.padEnd(14)} ${mark.padEnd(8)} ${c.evidence}`);
290
+ if (c.status === 'drift')
291
+ lines.push(` ${''.padEnd(14)} fix: ${c.repair}`);
292
+ }
293
+ }
294
+ const t = envelope.summary;
295
+ lines.push(
296
+ `${t.stories} Story(ies): ${t.drift} drift, ${t.unknown} unknown, ${t.repaired} repaired.`,
297
+ );
298
+ return `${lines.join('\n')}\n`;
299
+ }
300
+
301
+ /**
302
+ * Pure scope filter: exact `story-<id>` heads merged at or after the cutoff.
303
+ *
304
+ * @param {Array<{ headRefName?: string, mergedAt?: string }>} rows
305
+ * @param {{ sinceHours: number, nowMs: number }} window
306
+ * @returns {number[]}
307
+ */
308
+ function selectMergedStoryIds(rows, { sinceHours, nowMs }) {
309
+ const cutoff = nowMs - sinceHours * 3_600_000;
310
+ const ids = new Set();
311
+ for (const r of Array.isArray(rows) ? rows : []) {
312
+ const id = parseStoryBranch(r?.headRefName);
313
+ const merged = Date.parse(r?.mergedAt ?? '');
314
+ if (id !== null && Number.isFinite(merged) && merged >= cutoff) ids.add(id);
315
+ }
316
+ return [...ids];
317
+ }
318
+
319
+ export async function listMergedStoryIds({
320
+ gh = defaultGh,
321
+ baseBranch,
322
+ sinceHours,
323
+ nowMs = Date.now(),
324
+ }) {
325
+ const rows = await gh.pr.list(
326
+ [
327
+ '--state',
328
+ 'merged',
329
+ '--base',
330
+ baseBranch,
331
+ '--limit',
332
+ String(MERGED_PR_PAGE),
333
+ ],
334
+ ['number', 'headRefName', 'mergedAt'],
335
+ );
336
+ return selectMergedStoryIds(rows, { sinceHours, nowMs });
337
+ }
338
+
339
+ /** Live probes over the main checkout; every one settles, none throws. */
340
+ export function buildProbes({
341
+ cwd,
342
+ config,
343
+ provider,
344
+ gh = defaultGh,
345
+ gitSpawnFn = defaultGitSpawn,
346
+ purgeFn = purgeStoryTempArtifacts,
347
+ logger,
348
+ }) {
349
+ const branchOf = (id) => getStoryBranch(id);
350
+ return {
351
+ ticket: (id) => probeTicket({ provider, storyId: id }),
352
+ pr: async (id) => {
353
+ const pr = await probePr({ storyBranch: branchOf(id), gh });
354
+ if (!isPrMerged(pr)) return pr;
355
+ const view = await gh.pr.view(pr.number, ['body']).catch(() => null);
356
+ return { ...pr, body: view?.body ?? null };
357
+ },
358
+ board: async (id) => {
359
+ if (typeof provider?.graphql !== 'function')
360
+ return { ok: false, error: 'no GraphQL transport' };
361
+ try {
362
+ const column = await new ColumnSync({
363
+ provider,
364
+ logger,
365
+ config,
366
+ }).readCurrentColumn(id);
367
+ return { ok: true, column };
368
+ } catch (err) {
369
+ return { ok: false, error: String(err?.message ?? err) };
370
+ }
371
+ },
372
+ branch: (id) =>
373
+ probeBranch({ cwd, storyBranch: branchOf(id), config, gitSpawnFn }),
374
+ // ls-remote, not the tracking ref: a stale tracking ref would read as drift forever.
375
+ remote: (id) => {
376
+ const res = gitSpawnFn(
377
+ cwd,
378
+ 'ls-remote',
379
+ '--heads',
380
+ 'origin',
381
+ `refs/heads/${branchOf(id)}`,
382
+ );
383
+ if (res.status !== 0)
384
+ return {
385
+ ok: false,
386
+ error: (res.stderr || `exit ${res.status}`).trim(),
387
+ };
388
+ return {
389
+ ok: true,
390
+ sha:
391
+ String(res.stdout ?? '')
392
+ .trim()
393
+ .split(/\s+/)[0] || null,
394
+ };
395
+ },
396
+ scratch: async (id) => {
397
+ const res = await purgeFn({ storyId: id, config, dryRun: true, logger });
398
+ if (res.errors?.length) return { error: res.errors[0] };
399
+ return { paths: res.purged.map((p) => p.path) };
400
+ },
401
+ };
402
+ }
403
+
404
+ function runScript({ cwd, spawnFn }, script, storyId) {
405
+ const res = spawnFn(
406
+ process.execPath,
407
+ [path.join(cwd, '.agents', 'scripts', script), '--story', String(storyId)],
408
+ {
409
+ cwd,
410
+ stdio: ['ignore', process.stderr, process.stderr],
411
+ },
412
+ );
413
+ return res.status === 0
414
+ ? { ok: true }
415
+ : { ok: false, reason: `${script} exited ${res.status}` };
416
+ }
417
+
418
+ function refusalFromSweep(result, branch) {
419
+ if (result?.reaped?.includes(branch)) return { ok: true };
420
+ const prot = result?.protected?.find((p) => p.branch === branch);
421
+ if (prot) return { ok: false, reason: prot.reason };
422
+ if (result?.contentMerged?.some((p) => p.branch === branch))
423
+ return { ok: false, reason: 'content-merged, left for /clean-git' };
424
+ const fail = result?.failures?.find((f) => f.branch === branch);
425
+ return {
426
+ ok: false,
427
+ reason:
428
+ fail?.stderr ||
429
+ result?.error ||
430
+ result?.reason ||
431
+ 'not a merged sweep candidate',
432
+ };
433
+ }
434
+
435
+ /** Each check's existing repair seam, wrapped to `{ ok, reason? }`. */
436
+ export function buildRepairs({
437
+ cwd,
438
+ config,
439
+ provider,
440
+ logger,
441
+ spawnFn = spawnChild,
442
+ deleteRemoteFn = deleteBranchRemote,
443
+ sweepBranchesFn = sweepMergedBranches,
444
+ sweepWorktreesFn = sweepStaleStoryWorktrees,
445
+ purgeFn = purgeStoryTempArtifacts,
446
+ }) {
447
+ const ctx = { cwd, spawnFn };
448
+ return {
449
+ 'story-state': (e) =>
450
+ runScript(ctx, 'single-story-confirm-merge.js', e.storyId),
451
+ 'board-status': (e) => runScript(ctx, 'resync-status-column.js', e.storyId),
452
+ 'remote-branch': (e) => {
453
+ const { sha } = e.readings.remote;
454
+ const merged = e.readings.pr.headSha;
455
+ if (merged && sha !== merged)
456
+ return {
457
+ ok: false,
458
+ reason: `origin head ${sha} is not the merged head ${merged}`,
459
+ };
460
+ const res = deleteRemoteFn(getStoryBranch(e.storyId), { cwd });
461
+ return res.deleted
462
+ ? { ok: true }
463
+ : { ok: false, reason: res.stderr || res.reason };
464
+ },
465
+ 'local-branch': async (e) => {
466
+ const branch = getStoryBranch(e.storyId);
467
+ const result = await sweepBranchesFn({
468
+ cwd,
469
+ baseBranch: config?.project?.baseBranch ?? 'main',
470
+ include: [branch],
471
+ logger,
472
+ protectionCtx: buildProtectionCtx({ cwd, provider }),
473
+ });
474
+ return refusalFromSweep(result, branch);
475
+ },
476
+ worktree: async (e) => {
477
+ const result = await sweepWorktreesFn({
478
+ provider,
479
+ repoRoot: cwd,
480
+ logger,
481
+ });
482
+ const skip = result?.skipped?.find((s) => s.storyId === e.storyId);
483
+ return skip ? { ok: false, reason: skip.reason } : { ok: true };
484
+ },
485
+ scratch: async (e) => {
486
+ const res = await purgeFn({ storyId: e.storyId, config, logger });
487
+ return res.errors?.length
488
+ ? { ok: false, reason: res.errors[0] }
489
+ : { ok: true };
490
+ },
491
+ };
492
+ }
493
+
494
+ /** The sweep lock boot-sweep and init share, held across every repair. */
495
+ export function buildWithLock({ cwd, config, acquireFn = acquireSweepLock }) {
496
+ return async (fn) => {
497
+ const lock = acquireFn({
498
+ lockPath: resolveSweepLockPath({
499
+ cwd,
500
+ tempRoot: config?.project?.paths?.tempRoot ?? 'temp',
501
+ }),
502
+ timeoutMs: config?.delivery?.worktreeIsolation?.sweepLockMs ?? 60_000,
503
+ });
504
+ if (!lock.acquired) return { locked: false, reason: lock.reason };
505
+ try {
506
+ return { locked: true, value: await fn() };
507
+ } finally {
508
+ lock.release();
509
+ }
510
+ };
511
+ }
@@ -66,7 +66,7 @@ function holdsLint(ctx, gate) {
66
66
 
67
67
  /** The argv a preflight check runs: bare when held, else deposited. */
68
68
  function preflightArgv(ctx, gate, run) {
69
- if (holdsLint(ctx, gate)) {
69
+ if (ctx.reportAll || holdsLint(ctx, gate)) {
70
70
  return { cmd: run.cmd, args: run.args, held: true };
71
71
  }
72
72
  return {
@@ -100,6 +100,21 @@ function isWholeTreeLint(gate, run) {
100
100
  );
101
101
  }
102
102
 
103
+ /** Close's artifact-free baseline compare, as a preflight check. */
104
+ export function baselineComparePreflight(ctx) {
105
+ return closeGates(ctx)
106
+ .filter((g) => g.name === BASELINES_GATE_NAMES.independent && !g.skip)
107
+ .map((gate) => ({
108
+ key: gate.name,
109
+ label: describeGate(gate),
110
+ cmd: gate.cmd,
111
+ args: gate.args,
112
+ env: gate.env,
113
+ scoresDuplication: scoresDuplication(gate),
114
+ baselineRef: gate.env?.BASELINE_REF,
115
+ }));
116
+ }
117
+
103
118
  /**
104
119
  * Close's preflight entries wrapped in `evidence-gate.js` with the argv close
105
120
  * executes; a disabled or scoped-out gate deposits nothing.
@@ -259,8 +274,9 @@ export function seatableKinds(ctx, kinds) {
259
274
  }
260
275
 
261
276
  /**
262
- * `quality-preview-crap` (capture depositor only) and every baselines entry;
263
- * after a deferral, none that reads the coverage artifact.
277
+ * The coverage-reading half of close's list: `quality-preview-crap` (capture
278
+ * depositor only) and the baselines entries that read the artifact, none
279
+ * after a deferral. The artifact-free compare runs at preflight.
264
280
  */
265
281
  function postCaptureGates(ctx) {
266
282
  const names = new Set(Object.values(BASELINES_GATE_NAMES));
@@ -271,10 +287,10 @@ function postCaptureGates(ctx) {
271
287
  return closeGates(ctx).filter(keep);
272
288
  }
273
289
 
274
- /** A registered, unskipped post-capture gate, minus artifact readers after a deferral. */
290
+ /** A registered, unskipped artifact reader; none after a deferral. */
275
291
  function postCaptureFilter(names, deferred) {
276
292
  return (g) =>
277
- names.has(g.name) && !g.skip && !(deferred && g.readsCoverageArtifact);
293
+ names.has(g.name) && !g.skip && !deferred && g.readsCoverageArtifact;
278
294
  }
279
295
 
280
296
  /** The kinds a baselines entry scores; `null` without `--gate` (every kind). */
@@ -306,9 +322,10 @@ function failure(gate, res) {
306
322
  };
307
323
  }
308
324
 
309
- /** Run each post-capture gate through `run`; the first non-zero exit is the finding. */
325
+ /** Run every post-capture gate through `run`; each non-zero exit is a finding. */
310
326
  export async function scorePostCapture(ctx, run) {
311
327
  const gates = postCaptureGates(ctx);
328
+ const failures = [];
312
329
  for (const gate of gates) {
313
330
  const env = gate.env ? { ...ctx.env, ...gate.env } : undefined;
314
331
  const res = await run(
@@ -317,7 +334,7 @@ export async function scorePostCapture(ctx, run) {
317
334
  gate.args,
318
335
  env,
319
336
  );
320
- if (res.status !== 0) return { gates, failed: failure(gate, res) };
337
+ if (res.status !== 0) failures.push(failure(gate, res));
321
338
  }
322
- return { gates, failed: null };
339
+ return { gates, failures };
323
340
  }
@@ -59,7 +59,7 @@ async function readMergeQueueStateRest({ prRef, prNodeId, facade, timeoutMs }) {
59
59
  * @param {{ stdout?: string }|string|undefined} result
60
60
  * @returns {object|null}
61
61
  */
62
- function parseGraphqlData(result) {
62
+ export function parseGraphqlData(result) {
63
63
  const text = typeof result === 'string' ? result : result?.stdout;
64
64
  const parsed = JSON.parse(String(text ?? ''));
65
65
  if (Array.isArray(parsed?.errors) && parsed.errors.length > 0) {
@@ -108,9 +108,19 @@ async function readRequiredNamesRest({ prNumber, gh, timeoutMs }) {
108
108
  const view = await gh.pr.view(String(prNumber), ['baseRefName']);
109
109
  const base = view?.baseRefName;
110
110
  if (!base) throw new Error('PR base branch unreadable');
111
+ return readBaseRequiredNames({ api: gh.api, base, timeoutMs });
112
+ }
113
+
114
+ /**
115
+ * The base branch's required check names, over REST on either transport.
116
+ *
117
+ * @param {{ api: Function, base: string, timeoutMs?: number }} args
118
+ * @returns {Promise<Set<string>>}
119
+ */
120
+ export async function readBaseRequiredNames({ api, base, timeoutMs }) {
111
121
  const [rules, contexts] = await Promise.all([
112
- readBranchRules({ api: gh.api, base, timeoutMs }),
113
- readProtectionContexts({ api: gh.api, base, timeoutMs }),
122
+ readBranchRules({ api, base, timeoutMs }),
123
+ readProtectionContexts({ api, base, timeoutMs }),
114
124
  ]);
115
125
  const names = new Set(contexts.filter(Boolean));
116
126
  for (const rule of rules) {