mandrel 2.119.0 → 2.121.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 (47) hide show
  1. package/.agents/agents/acceptance-critic.md +4 -0
  2. package/.agents/agents/story-worker.md +1 -1
  3. package/.agents/docs/agentrc-reference.json +1 -0
  4. package/.agents/docs/configuration.md +18 -3
  5. package/.agents/schemas/acceptance-eval-verdict.schema.json +6 -1
  6. package/.agents/schemas/agentrc.schema.json +11 -2
  7. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  8. package/.agents/schemas/story-deliver-terminal.schema.json +1 -0
  9. package/.agents/scripts/acceptance-eval.js +125 -13
  10. package/.agents/scripts/evidence-gate.js +15 -2
  11. package/.agents/scripts/lib/baselines/crap-preview-scan.js +1 -0
  12. package/.agents/scripts/lib/baselines/git-base.js +43 -0
  13. package/.agents/scripts/lib/baselines/kinds/_crap-new-method-gate.js +29 -5
  14. package/.agents/scripts/lib/baselines/kinds/crap.js +7 -1
  15. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +81 -52
  16. package/.agents/scripts/lib/close-validation/projections/advisories.js +1 -0
  17. package/.agents/scripts/lib/close-validation/projections/crap.js +3 -0
  18. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  19. package/.agents/scripts/lib/config/gates/crap.schema.js +7 -0
  20. package/.agents/scripts/lib/config/quality.js +13 -6
  21. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  23. package/.agents/scripts/lib/observability/handoff-telemetry.js +1 -0
  24. package/.agents/scripts/lib/orchestrate/inventory.js +15 -0
  25. package/.agents/scripts/lib/orchestration/acceptance-eval-decision.js +65 -6
  26. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +34 -2
  27. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +7 -2
  28. package/.agents/scripts/lib/orchestration/handoff-changed-tests.js +67 -0
  29. package/.agents/scripts/lib/orchestration/handoff-gates.js +2 -0
  30. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +25 -10
  31. package/.agents/scripts/lib/orchestration/merge-block-class.js +1 -0
  32. package/.agents/scripts/lib/orchestration/merge-queue.js +155 -14
  33. package/.agents/scripts/lib/orchestration/preflight-lanes.js +2 -0
  34. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +131 -18
  35. package/.agents/scripts/lib/orchestration/story-handoff.js +24 -1
  36. package/.agents/scripts/lib/orchestration/ticket-validator.js +35 -0
  37. package/.agents/scripts/lib/orchestration/verify-credit.js +144 -0
  38. package/.agents/scripts/lib/validation-evidence.js +27 -0
  39. package/.agents/workflows/helpers/acceptance-self-eval.md +9 -1
  40. package/.agents/workflows/helpers/deliver-digest.md +7 -8
  41. package/.agents/workflows/helpers/deliver-reference.md +17 -0
  42. package/.agents/workflows/helpers/deliver-story-reference.md +1 -1
  43. package/.agents/workflows/helpers/plan-reference.md +3 -1
  44. package/docs/CHANGELOG.md +23 -0
  45. package/lib/cli/doctor-checks/suite-ownership.js +42 -0
  46. package/lib/cli/registry.js +6 -10
  47. package/package.json +1 -1
@@ -38,6 +38,7 @@ import {
38
38
  isRerunPermitted,
39
39
  } from '../../check-state.js';
40
40
  import { recordRequiredRed as defaultRecordRequiredRed } from '../../ci-red-handling.js';
41
+ import { writeCiDigest } from '../../ci-rerun-guard.js';
41
42
  import {
42
43
  emitMergeFlipFailed as defaultEmitMergeFlipFailed,
43
44
  MERGED_FLIP_FAILED_BLOCK_CLASS,
@@ -67,7 +68,9 @@ import {
67
68
  import {
68
69
  MERGE_QUEUE_REST_BLOCK_CLASS,
69
70
  MERGE_QUEUE_REST_REMEDY,
71
+ QUEUE_EJECTED_BLOCK_CLASS,
70
72
  readMergeQueueState,
73
+ readQueueEjection,
71
74
  } from '../../merge-queue.js';
72
75
  import { readProbeRunEvidence } from '../../required-checks.js';
73
76
  import { NEXT_COMMANDS } from '../../story-deliver-terminal.js';
@@ -275,6 +278,7 @@ export async function readPrWaitProbe({
275
278
  redHeadRuns: deriveRedHeadRuns(view?.statusCheckRollup),
276
279
  checkStates: deriveCheckStates(view?.statusCheckRollup),
277
280
  headSha: readString(view?.headRefOid),
281
+ prNodeId: readString(view?.id),
278
282
  autoMergeArmed: readAutoMergeArmed(view),
279
283
  };
280
284
  } catch (err) {
@@ -406,16 +410,10 @@ function disarmedOn(redRecord) {
406
410
  * @param {{ storyId: number, prNumber: number|null, blockClass: string }} args
407
411
  * @returns {string}
408
412
  */
409
- function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
410
- if (blockClass === CHECKS_FAILED_CLASS) {
411
- return checksFailedRemedy({ storyId, prNumber, redRecord });
412
- }
413
- if (
414
- blockClass === ADVISORY_GATE_INCONCLUSIVE_CLASS ||
415
- blockClass === ADVISORY_GATE_RED_CLASS
416
- ) {
417
- return advisoryGateRemedy({ storyId, blockClass, redRecord });
418
- }
413
+ function unlandedRemedy(args) {
414
+ const remedy = REMEDY_OF_CLASS[args.blockClass];
415
+ if (remedy) return remedy(args);
416
+ const { storyId } = args;
419
417
  return (
420
418
  `Resolve the underlying condition (branch protection, required checks, ` +
421
419
  `or a manual merge), then resume the land:\n\n` +
@@ -423,6 +421,13 @@ function unlandedRemedy({ storyId, prNumber, blockClass, redRecord }) {
423
421
  );
424
422
  }
425
423
 
424
+ const REMEDY_OF_CLASS = Object.freeze({
425
+ [CHECKS_FAILED_CLASS]: checksFailedRemedy,
426
+ [QUEUE_EJECTED_BLOCK_CLASS]: queueEjectedRemedy,
427
+ [ADVISORY_GATE_INCONCLUSIVE_CLASS]: advisoryGateRemedy,
428
+ [ADVISORY_GATE_RED_CLASS]: advisoryGateRemedy,
429
+ });
430
+
426
431
  /**
427
432
  * States what the red handling actually did — never claims a disarm or a
428
433
  * digest that did not happen — then names both ci-remediation routes.
@@ -438,11 +443,8 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
438
443
  : 'Auto-merge was **disarmed**; only a green on a new head SHA, or the one rerun a filed `capacity` / `unreproducible-tier` verdict admits, re-arms it.'
439
444
  : `⚠️ Auto-merge could **not** be disarmed (${disarm?.detail ?? 'the red handling did not run'}) — GitHub may still land the PR when the checks read green. Disarm it by hand.`;
440
445
  const watch = NEXT_COMMANDS.watchCi(storyId, prNumber);
441
- const digestLine = redRecord?.digestPaths
442
- ? `CI digest (run link + failure signature): \`${redRecord.digestPaths.jsonPath}\`.`
443
- : `⚠️ No CI digest was written (${redRecord?.digestError ?? 'no Story scope'}); \`${watch}\` rewrites it.`;
444
446
  return (
445
- `A required check is **red**. ${armLine}\n\n${digestLine}\n\n` +
447
+ `A required check is **red**. ${armLine}\n\n${digestLineOf(redRecord, watch)}\n\n` +
446
448
  `Per \`.agents/rules/ci-remediation.md\`, either fix the failure and push a new commit on ` +
447
449
  `\`story-${storyId}\` (re-running the failed job is forbidden), or — when the root cause is ` +
448
450
  `outside this delivery — file it:\n\n` +
@@ -452,6 +454,27 @@ function checksFailedRemedy({ storyId, prNumber, redRecord }) {
452
454
  );
453
455
  }
454
456
 
457
+ function digestLineOf(redRecord, rewrite) {
458
+ return redRecord?.digestPaths
459
+ ? `CI digest (run link + failure signature): \`${redRecord.digestPaths.jsonPath}\`.`
460
+ : `⚠️ No CI digest was written (${redRecord?.digestError ?? 'no Story scope'}); \`${rewrite}\` rewrites it.`;
461
+ }
462
+
463
+ /** The queue run's own failure: fix on the Story branch, hand off again. */
464
+ function queueEjectedRemedy({ storyId, prNumber, redRecord }) {
465
+ const run = redRecord?.queueRun ?? {};
466
+ return (
467
+ `The merge queue **ejected** PR #${prNumber}: queue run ${run.url ?? `#${run.id}`} ` +
468
+ `concluded \`${run.conclusion}\` and the entry it was built on did not fail, so the ` +
469
+ `failure is this change's own. Auto-merge was not re-armed.\n\n` +
470
+ `${digestLineOf(redRecord, NEXT_COMMANDS.watchCi(storyId, prNumber))}\n\n` +
471
+ `Fix it on \`story-${storyId}\` in the Story worktree, commit, and re-run the hand-off, ` +
472
+ `which pushes the new head:\n\n` +
473
+ `\`\`\`bash\nnode .agents/scripts/story-handoff.js --story ${storyId} --cwd <worktree>\n\`\`\`\n\n` +
474
+ `Then resume the land:\n\n\`\`\`bash\n${NEXT_COMMANDS.resumeLand(storyId)}\n\`\`\``
475
+ );
476
+ }
477
+
455
478
  function formatUnlandedFriction({
456
479
  storyId,
457
480
  prNumber,
@@ -852,7 +875,7 @@ function queuedExhaustionVerdict(probe, cumulativeMs) {
852
875
  *
853
876
  * @returns {Promise<object>} the `recordRequiredRed` outcome.
854
877
  */
855
- async function recordRed(ctx, probe, failures) {
878
+ async function recordRed(ctx, probe, failures, run = null) {
856
879
  const {
857
880
  storyId,
858
881
  prNumber,
@@ -873,6 +896,7 @@ async function recordRed(ctx, probe, failures) {
873
896
  cwd,
874
897
  headSha: probe?.headSha ?? null,
875
898
  disarmFn: () => disarmAutoMergeFn({ prNumber, gh, progress }),
899
+ ...pinnedRun(run),
876
900
  });
877
901
  if (record.digestPaths) {
878
902
  progress?.(
@@ -896,6 +920,13 @@ async function recordRed(ctx, probe, failures) {
896
920
  }
897
921
  }
898
922
 
923
+ /** A queue run is not on the PR head, so the digest is pinned to it. */
924
+ function pinnedRun(run) {
925
+ if (!run) return {};
926
+ const checkRunFn = () => ({ runId: String(run.id), url: run.url });
927
+ return { writeDigestFn: (args) => writeCiDigest({ ...args, checkRunFn }) };
928
+ }
929
+
899
930
  /** Classify, emit `merge.unlanded`, post friction, block — all best-effort. */
900
931
  async function blockOnUnlanded({
901
932
  storyId,
@@ -1290,6 +1321,31 @@ async function settleChecksFailed(ctx, decision, probe) {
1290
1321
  });
1291
1322
  }
1292
1323
 
1324
+ /** An own queue failure settles at once, its digest written from the queue run. */
1325
+ async function settleQueueEjected(ctx, decision, probe, ejection) {
1326
+ const { run } = ejection;
1327
+ const names = ejection.failedJobs?.length
1328
+ ? ejection.failedJobs
1329
+ : [run.name ?? 'merge queue'];
1330
+ const failures = names.map((name) => ({
1331
+ name,
1332
+ outcome: run.conclusion,
1333
+ runId: run.id,
1334
+ }));
1335
+ ctx.progress?.(
1336
+ 'CONFIRM',
1337
+ `🛑 PR #${ctx.prNumber}: the merge queue ejected it on its own failure (${run.url ?? run.id}) — handing back.`,
1338
+ );
1339
+ const redRecord = await recordRed(ctx, probe, failures, run);
1340
+ return blockWith(ctx, {
1341
+ prProbe: probe,
1342
+ budget: { exhausted: false, elapsedSeconds: decision.elapsedSeconds },
1343
+ blockClassOverride: QUEUE_EJECTED_BLOCK_CLASS,
1344
+ reasonOverride: `merge queue run ${run.url ?? run.id} concluded ${run.conclusion}: ${describeFailures(failures)}`,
1345
+ redRecord: { ...redRecord, queueRun: run },
1346
+ });
1347
+ }
1348
+
1293
1349
  function settleUnrecognisedChecks(ctx, decision, probe) {
1294
1350
  return blockWith(ctx, {
1295
1351
  prProbe: probe,
@@ -1367,9 +1423,8 @@ async function recoverOpenPr(ctx, decision, probe) {
1367
1423
  if (advisory) {
1368
1424
  return { state: decision.state, outcome: await blockWith(ctx, advisory) };
1369
1425
  }
1370
- const landed = await maybeMergeOnGreen(ctx, decision, probe);
1371
- if (landed) return { state: decision.state, outcome: landed };
1372
- await maybeRearmPr(ctx, probe);
1426
+ const settled = await settleOpenPr(ctx, decision, probe);
1427
+ if (settled) return { state: decision.state, outcome: settled };
1373
1428
  const updated = await maybeUpdateBehindPr({
1374
1429
  probe,
1375
1430
  prNumber: ctx.prNumber,
@@ -1385,6 +1440,57 @@ async function recoverOpenPr(ctx, decision, probe) {
1385
1440
  return { state, outcome: null };
1386
1441
  }
1387
1442
 
1443
+ /** Merge-on-green lands; an own ejection blocks; otherwise the re-arm rule runs. */
1444
+ async function settleOpenPr(ctx, decision, probe) {
1445
+ const landed = await maybeMergeOnGreen(ctx, decision, probe);
1446
+ if (landed) return landed;
1447
+ const ejection = await readEjection(ctx, probe);
1448
+ if (ejection?.verdict === 'own') {
1449
+ return settleQueueEjected(ctx, decision, probe, ejection);
1450
+ }
1451
+ if (await admitsRearm(ctx, ejection)) await maybeRearmPr(ctx, probe);
1452
+ return null;
1453
+ }
1454
+
1455
+ /**
1456
+ * A queue ejection, read only for a close-armed, un-armed PR that GraphQL
1457
+ * reads out of the queue (`inMergeQueue` is only read on a green open PR).
1458
+ */
1459
+ async function readEjection(ctx, probe) {
1460
+ const unarmed = ctx.closeArmed === true && probe.autoMergeArmed === false;
1461
+ if (probe.inMergeQueue !== false || !unarmed || !probe.headSha) return null;
1462
+ return ctx.readQueueEjectionFn({
1463
+ prNodeId: probe.prNodeId,
1464
+ prNumber: ctx.prNumber,
1465
+ headSha: probe.headSha,
1466
+ gh: ctx.waitGh,
1467
+ timeoutMs: ctx.ghTimeoutMs,
1468
+ });
1469
+ }
1470
+
1471
+ /**
1472
+ * Each distinct inherited ejecting run frees one more re-arm on the head
1473
+ * (the once-per-head record is reset); a held release veto admits none.
1474
+ */
1475
+ async function admitsRearm(ctx, ejection) {
1476
+ if (ejection?.verdict !== 'inherited') return true;
1477
+ const labels = ejection.labels ?? [];
1478
+ if (await ctx.releaseVetoFn({ config: ctx.config, labels, cwd: ctx.cwd })) {
1479
+ return false;
1480
+ }
1481
+ if (!ctx.ejectionRuns.has(ejection.run?.id)) {
1482
+ ctx.ejectionRuns.add(ejection.run?.id);
1483
+ ctx.rearmedHeads.clear();
1484
+ }
1485
+ return true;
1486
+ }
1487
+
1488
+ /** Loaded on use: the inventory's import graph is not close's to carry. */
1489
+ async function releaseVetoHolds(args) {
1490
+ const inventory = await import('../../../orchestrate/inventory.js');
1491
+ return inventory.releaseVetoHolds(args);
1492
+ }
1493
+
1388
1494
  /**
1389
1495
  * Close owns the merge when the CCR route would not arm it: the arm said so,
1390
1496
  * or (a `--wait` resume, which has no arm outcome) the PR transport is REST
@@ -1597,6 +1703,8 @@ function neverArmedOverride(autoMergeReason, advisoryGate) {
1597
1703
  * @param {Function} [args.recordRequiredRedFn] The shared first-red handling (disarm + CI digest).
1598
1704
  * @param {Function} [args.mergeOnGreenFn] The merge-on-green squash-merge (`auto-merge.js#mergeOnGreen`).
1599
1705
  * @param {Function} [args.readMergeQueueStateFn] Whether the base requires a merge queue.
1706
+ * @param {Function} [args.readQueueEjectionFn] Why the merge queue ejected the PR.
1707
+ * @param {Function} [args.releaseVetoFn] Whether `orchestrate.releaseVeto` holds the PR.
1600
1708
  * @param {object} [args.recoverySeams] DIRTY-sync / re-arm seams (`mergeWaitRecoverySeams`).
1601
1709
  * @param {(ms: number) => Promise<void>} [args.sleepFn]
1602
1710
  * @param {() => number} [args.nowMsFn]
@@ -1618,6 +1726,8 @@ export async function runConfirmMergePhase({
1618
1726
  recordRequiredRedFn = defaultRecordRequiredRed,
1619
1727
  mergeOnGreenFn = mergeOnGreen,
1620
1728
  readMergeQueueStateFn = readMergeQueueState,
1729
+ readQueueEjectionFn = readQueueEjection,
1730
+ releaseVetoFn = releaseVetoHolds,
1621
1731
  sleepFn = defaultSleep,
1622
1732
  nowMsFn = Date.now,
1623
1733
  ghTimeoutMs = MERGE_WAIT_GH_TIMEOUT_MS,
@@ -1667,6 +1777,9 @@ export async function runConfirmMergePhase({
1667
1777
  recordRequiredRedFn,
1668
1778
  mergeOnGreenFn,
1669
1779
  readMergeQueueStateFn,
1780
+ readQueueEjectionFn,
1781
+ releaseVetoFn,
1782
+ ejectionRuns: new Set(),
1670
1783
  nowMsFn,
1671
1784
  ghTimeoutMs,
1672
1785
  waitGh: args.injectedGh ?? defaultGh,
@@ -38,6 +38,7 @@ import {
38
38
  import { isBiomeNoFilesProcessed } from '../close-validation/process.js';
39
39
  import { applyChangedFileScope } from '../close-validation/runner.js';
40
40
  import { skipBranchDeposit } from '../close-validation/skip-branch-test.js';
41
+ import { substituteChangedSince } from '../close-validation/test-delta.js';
41
42
  import { getBaselines } from '../config/baselines.js';
42
43
  import { getPostSeatChecks } from '../config/handoff.js';
43
44
  import { getQuality } from '../config/quality.js';
@@ -738,6 +739,27 @@ function depositorArgv(ctx) {
738
739
  return { args, label: deposit.label };
739
740
  }
740
741
 
742
+ /**
743
+ * The `ci` posture's changed-tests guard: `testChanged` keyed on the
744
+ * `origin/<base>` merge-base, outside the full-suite lock, bounded by
745
+ * `coverage.timeoutMs`.
746
+ */
747
+ function runChangedTests(ctx, testChanged, signal) {
748
+ const base = `origin/${ctx.baseBranch}`;
749
+ const since = gitLine(ctx.git, ctx.cwd, ['merge-base', 'HEAD', base]) || base;
750
+ const { cmd, args, env } = substituteChangedSince(testChanged, since);
751
+ const timeoutMs = getQuality(ctx.config).coverage.timeoutMs;
752
+ const bounded = { ...ctx, stream: { ...ctx.stream, timeoutMs } };
753
+ return runLogged(
754
+ bounded,
755
+ 'changed-tests',
756
+ cmd,
757
+ args,
758
+ { ...ctx.env, ...env },
759
+ signal,
760
+ );
761
+ }
762
+
741
763
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
742
764
  async function creditedRun(ctx, signal) {
743
765
  const name = 'credited-run';
@@ -748,7 +770,8 @@ async function creditedRun(ctx, signal) {
748
770
  { depositor: ctx.depositor },
749
771
  );
750
772
  }
751
- const ciOwned = settleSuiteOfRecord(ctx, name);
773
+ const guard = { run: (cmd) => runChangedTests(ctx, cmd, signal), signal };
774
+ const ciOwned = await settleSuiteOfRecord(ctx, name, guard);
752
775
  if (ciOwned) return ciOwned;
753
776
  const capture = ctx.depositor === 'coverage-capture';
754
777
  const { args, label } = depositorArgv(ctx);
@@ -253,6 +253,38 @@ function assertEveryStoryHasInlineContract({ stories }) {
253
253
  );
254
254
  }
255
255
 
256
+ const QUOTED_RE = /'[^']*'|"(?:\\.|[^"\\])*"/g;
257
+ const DISCARD_RE = /\|\|\s*(?:true|:|break|continue)(?=\s*(?:$|;|done\b|\)))/m;
258
+ const LOOP_RE = /(?:^|[;&|(]|\bdo|\bthen)\s*(?:for|while|until)\s/m;
259
+ const FAILING_EXIT_RE = /\bexit\s+(?:[1-9]\d*|\$\?)/;
260
+
261
+ /**
262
+ * True when a verify command can exit 0 after its check failed: a failure
263
+ * branch that discards status, or a loop (status = last iteration's) with no
264
+ * failing `exit`. Quoted strings are ignored. `|| echo …` passes on purpose.
265
+ *
266
+ * @param {string} entry
267
+ * @returns {boolean}
268
+ */
269
+ function discardsExitStatus(entry) {
270
+ const code = String(entry ?? '').replace(QUOTED_RE, "''");
271
+ if (DISCARD_RE.test(code)) return true;
272
+ return LOOP_RE.test(code) && !FAILING_EXIT_RE.test(code);
273
+ }
274
+
275
+ function assertVerifyKeepsExitStatus({ stories }) {
276
+ const offenders = stories.flatMap((s) =>
277
+ (Array.isArray(s.verify) ? s.verify : [])
278
+ .filter((entry) => typeof entry === 'string' && discardsExitStatus(entry))
279
+ .map((entry) => ` - ${s.slug}: ${entry}`),
280
+ );
281
+ if (offenders.length === 0) return;
282
+ throw new Error(
283
+ `Cross-Validation Failed: ${offenders.length} verify[] entry/entries can exit 0 after a failure:\n${offenders.join('\n')}\n\n` +
284
+ 'Fail the entry with `|| exit 1` instead of discarding the status.',
285
+ );
286
+ }
287
+
256
288
  /**
257
289
  * @param {object[]} stories
258
290
  * @returns {string[]}
@@ -347,6 +379,7 @@ export function validateAndNormalizeTickets(tickets, opts = {}) {
347
379
 
348
380
  assertAllTicketsAreStories({ tickets, stories });
349
381
  assertEveryStoryHasInlineContract({ stories });
382
+ assertVerifyKeepsExitStatus({ stories });
350
383
  assertStoryProvenanceShape({ stories });
351
384
  assertNoUnknownDeps({ tickets, ticketBySlug });
352
385
 
@@ -407,6 +440,8 @@ export const _internal = {
407
440
  indexTicketsBySlug,
408
441
  assertAllTicketsAreStories,
409
442
  assertEveryStoryHasInlineContract,
443
+ assertVerifyKeepsExitStatus,
444
+ discardsExitStatus,
410
445
  assertStoryProvenanceShape,
411
446
  assertNoUnknownDeps,
412
447
  assertAcyclic,
@@ -5,6 +5,9 @@
5
5
  * manufactures a pass.
6
6
  */
7
7
 
8
+ import { globSync } from 'node:fs';
9
+
10
+ import { spawnChild } from '../child-exec.js';
8
11
  import { resolveTestGateArgv } from '../close-validation/commands.js';
9
12
  import { COVERAGE_CAPTURE_DEFAULTS } from '../config/gates/coverage.schema.js';
10
13
  import { getQuality, resolveConfig } from '../config-resolver.js';
@@ -258,3 +261,144 @@ export function planVerifyExecution(entries, context, deps = {}) {
258
261
  return { ...resolveVerifyCredit({ ...context, command }, deps), tier };
259
262
  });
260
263
  }
264
+
265
+ const MANUAL_ENTRY = /^manual:/i;
266
+
267
+ const VERIFY_RUN_TIMEOUT_MS = 10 * 60 * 1000;
268
+
269
+ /** Any of these makes an entry compound, so its paths are not probed. */
270
+ const COMPOUND_SHELL = /[;|&<>()`]|\$\(/;
271
+
272
+ /** Flags whose next token is a value, not a test path. */
273
+ const VALUE_FLAGS = new Set([
274
+ '--test-name-pattern',
275
+ '--test-skip-pattern',
276
+ '--test-reporter',
277
+ '--test-reporter-destination',
278
+ '--test-concurrency',
279
+ '--test-timeout',
280
+ '--test-shard',
281
+ '--test-isolation',
282
+ '--test-global-setup',
283
+ '--test-coverage-include',
284
+ '--test-coverage-exclude',
285
+ '--import',
286
+ '--require',
287
+ '-r',
288
+ '--loader',
289
+ '--experimental-loader',
290
+ '--env-file',
291
+ '--conditions',
292
+ '-C',
293
+ '--config',
294
+ '-c',
295
+ '--project',
296
+ '--reporter',
297
+ '--root',
298
+ '--dir',
299
+ '-t',
300
+ '--testNamePattern',
301
+ '--environment',
302
+ '--pool',
303
+ '--shard',
304
+ '--outputFile',
305
+ '--exclude',
306
+ '--maxWorkers',
307
+ '--minWorkers',
308
+ '--testTimeout',
309
+ '--mode',
310
+ '--workspace',
311
+ '--retry',
312
+ ]);
313
+
314
+ /** `parseVerifyEntry` plus collapsed whitespace: the evidence match key. */
315
+ export function normalizeVerifyCommand(entry) {
316
+ return parseVerifyEntry(entry).command.replace(/\s+/g, ' ');
317
+ }
318
+
319
+ /** `required` must be evidenced; `scoped` (not full-suite) is also run. */
320
+ export function classifyVerifyEntries(entries) {
321
+ const required = [
322
+ ...new Set((entries ?? []).map(normalizeVerifyCommand).filter(Boolean)),
323
+ ].filter((command) => !MANUAL_ENTRY.test(command));
324
+ return {
325
+ required,
326
+ scoped: required.filter((command) => !isFullSuiteCommand(command)),
327
+ };
328
+ }
329
+
330
+ const unquote = (token) => token.replace(/^(['"])(.*)\1$/, '$2');
331
+
332
+ /** Runner and test paths of a simple `vitest run` / `node --test`, else null. */
333
+ function extractTestPaths(command) {
334
+ if (COMPOUND_SHELL.test(command)) return null;
335
+ const tokens = command.split(' ').map(unquote);
336
+ let runner = 'node';
337
+ let start = 2;
338
+ if (tokens[0] !== 'node' || tokens[1] !== '--test') {
339
+ const lead = { npx: 1, pnpm: 1, npm: tokens[1] === 'exec' ? 2 : -1 };
340
+ const at = lead[tokens[0]] ?? 0;
341
+ if (at < 0 || tokens[at] !== 'vitest' || tokens[at + 1] !== 'run') {
342
+ return null;
343
+ }
344
+ runner = 'vitest';
345
+ start = at + 2;
346
+ }
347
+ const paths = [];
348
+ for (let i = start; i < tokens.length; i += 1) {
349
+ if (!tokens[i].startsWith('-')) paths.push(tokens[i]);
350
+ else if (VALUE_FLAGS.has(tokens[i])) i += 1;
351
+ }
352
+ return { runner, paths };
353
+ }
354
+
355
+ /** @param {string} pattern @param {string} cwd @returns {number} */
356
+ function countGlobFiles(pattern, cwd) {
357
+ try {
358
+ return globSync(pattern, { cwd }).length;
359
+ } catch {
360
+ return 0;
361
+ }
362
+ }
363
+
364
+ /** Listed lines count: `vitest list` exits 0 on an empty selection. */
365
+ function countVitestFiles(testPath, cwd) {
366
+ const res = spawnChild('npx', ['vitest', 'list', testPath, '--filesOnly'], {
367
+ cwd,
368
+ shell: process.platform === 'win32',
369
+ timeout: VERIFY_RUN_TIMEOUT_MS,
370
+ });
371
+ return String(res.stdout ?? '')
372
+ .split('\n')
373
+ .filter((line) => line.trim().length > 0).length;
374
+ }
375
+
376
+ /** Output goes to stderr so stdout stays one envelope; null on timeout. */
377
+ function spawnVerifyCommand(command, cwd) {
378
+ const res = spawnChild(command, [], {
379
+ cwd,
380
+ shell: true,
381
+ stdio: ['ignore', 2, 2],
382
+ timeout: VERIFY_RUN_TIMEOUT_MS,
383
+ });
384
+ return Number.isInteger(res.status) ? res.status : null;
385
+ }
386
+
387
+ /** Run one scoped entry in `cwd`; a dead test path fails it unspawned. */
388
+ export function runScopedVerifyEntry(command, { cwd }, deps = {}) {
389
+ const {
390
+ spawnImpl = spawnVerifyCommand,
391
+ listVitestImpl = countVitestFiles,
392
+ globImpl = countGlobFiles,
393
+ } = deps;
394
+ const selection = extractTestPaths(command);
395
+ const count = selection?.runner === 'vitest' ? listVitestImpl : globImpl;
396
+ const deadPaths = (selection?.paths ?? []).filter((p) => count(p, cwd) < 1);
397
+ const exitCode = deadPaths.length > 0 ? null : spawnImpl(command, cwd);
398
+ return {
399
+ command,
400
+ exitCode,
401
+ outcome: exitCode === 0 ? 'pass' : 'fail',
402
+ deadPaths,
403
+ };
404
+ }
@@ -254,6 +254,33 @@ export function treeFingerprint(cwd, gitSpawnFn) {
254
254
  }
255
255
  }
256
256
 
257
+ /**
258
+ * Why evidence must be bypassed — the tree differs from HEAD, or the probe
259
+ * failed — or `null` on a clean tree. Gitignored files are not counted.
260
+ */
261
+ export function dirtyTreeReason(cwd, gitSpawnFn) {
262
+ let res;
263
+ try {
264
+ res = gitSpawnFn(cwd, 'status', '--porcelain', '--untracked-files=normal');
265
+ } catch {
266
+ res = null;
267
+ }
268
+ if (res?.status !== 0) return 'git status probe failed';
269
+ // The runner trims stdout: strip the status code by shape, not width.
270
+ const paths = (res.stdout || '')
271
+ .split(/\r?\n/)
272
+ .map((line) => line.replace(/^\s*[ MADRCUT?!]{1,2}\s/, '').trim())
273
+ .filter(Boolean);
274
+ if (paths.length === 0) return null;
275
+ return `tree differs from HEAD: ${paths[0]}, ${paths.length} changed path(s)`;
276
+ }
277
+
278
+ /** Throws the {@link dirtyTreeReason} when evidence must not be recorded. */
279
+ export function assertCleanTree(cwd, gitSpawnFn) {
280
+ const reason = dirtyTreeReason(cwd, gitSpawnFn);
281
+ if (reason) throw new Error(reason);
282
+ }
283
+
257
284
  /**
258
285
  * Skip only when gate and config hash match and either the SHA or a non-empty
259
286
  * input fingerprint matches; otherwise `reason` says why not.
@@ -112,9 +112,17 @@ per-criterion, mid-delivery, and evaluates the actual work product.
112
112
 
113
113
  ```bash
114
114
  node <main-repo>/.agents/scripts/acceptance-eval.js \
115
- --story <storyId> --verdict <verdict-path>
115
+ --story <storyId> --verdict <verdict-path> --cwd <workCwd>
116
116
  ```
117
117
 
118
+ The gate runs each scoped Story `verify[]` entry itself in `--cwd`
119
+ (full-suite and `manual:` entries are not spawned). Every required entry
120
+ must be cited in some criterion's `verifyEvidence[]`, and a `met`
121
+ criterion over a non-`pass` item needs a `waiver` — both are refused
122
+ before scoring, consuming no round. A criterion citing an entry whose
123
+ gate run fails (non-zero exit, or a test path selecting no file) is
124
+ scored `unmet`.
125
+
118
126
  The gate reads the Story's `acceptance[]` count itself (Story #5313): a
119
127
  verdict whose `criteria[]` length differs — one covering only part of the
120
128
  Story — is rejected **before scoring**, with an error naming the count and
@@ -76,18 +76,17 @@ skeleton — it derives § 3's `files` and `verdictOwner` with the same function
76
76
  `node <main-repo>/.agents/scripts/acceptance-eval.js --story <storyId> --init
77
77
  --cwd <workCwd>`
78
78
 
79
- It writes one empty record per `acceptance[]` item and prints its
80
- path. The owner fills **every** record,
81
- scored against that change set with `verify[]` output as evidence, and scores
82
- it in **one** gate call. Bounded by `delivery.acceptanceEval.maxRounds`
79
+ It writes one empty record per `acceptance[]` item and prints its path. The
80
+ owner fills **every** record against that change set, `verify[]` output as
81
+ evidence, and scores it in **one** gate call. Bounded by `delivery.acceptanceEval.maxRounds`
83
82
  (default 2; `0` scores once with no redraft).
84
83
 
85
84
  `node <main-repo>/.agents/scripts/acceptance-eval.js --story <storyId>
86
- --verdict <verdict-path>`
85
+ --verdict <verdict-path> --cwd <workCwd>`
87
86
 
88
- The gate reads the Story's `acceptance[]` count itself and rejects, **before**
89
- scoring and consuming no round, a verdict whose `criteria[]` length differs
90
- or with an unfilled record (naming its indices).
87
+ Refused before scoring (no round): a `criteria[]` length off the
88
+ `acceptance[]` count, an unfilled record, an uncited `verify[]` entry. The
89
+ gate runs scoped entries in `--cwd`.
91
90
 
92
91
  `proceed` → § 5. `redraft` → one more round inside the cap. `block` → **do
93
92
  not close**: post a `friction` comment and flip `agent::blocked`.
@@ -374,6 +374,23 @@ in the foreground, now bounded to the gates plus the ~60s probe, and the long
374
374
  merge wait moves into the background confirm that carries the explicit
375
375
  timeout. A local session need not pass the flag.
376
376
 
377
+ **A merge-queue ejection is settled from one probe.** When a close-armed PR
378
+ reads out of the queue with no auto-merge request (GraphQL only — over REST
379
+ queue membership is unreadable and the wait is unchanged), the wait reads
380
+ the `merge_group` run that ejected it, on the
381
+ `gh-readonly-queue/<base>/pr-<n>-<parentSha>` ref, and the run of the entry
382
+ it was built on. An **inherited** ejection (the run was cancelled, or the
383
+ entry ahead failed or was cancelled) re-arms once per ejecting run, at most
384
+ three times per head; the fourth counts as the PR's own. An **own** ejection
385
+ blocks at once with block class `queue-ejected`: the CI digest is written
386
+ from the queue run (run link, failed jobs, failure signature) and nothing is
387
+ re-armed. To resume, fix the failure on `story-<id>` in the Story worktree,
388
+ commit, re-run `story-handoff.js` to push the new head, then run the
389
+ friction comment's resume command. An unreadable ejecting run keeps today's
390
+ one blind re-arm per head. The ejection path never re-arms a PR close did
391
+ not arm, under `ci.autoMerge: strict`, or one `orchestrate.releaseVeto`
392
+ holds.
393
+
377
394
  ## Close-out audit {#closeout-audit}
378
395
 
379
396
  `deliver-recover.js` names the next command for one stranded Story;
@@ -184,7 +184,7 @@ criteria, then transition the Story to `agent::blocked`:
184
184
 
185
185
  ```bash
186
186
  node .agents/scripts/diagnose-friction.js --story <storyId> \
187
- --cmd node .agents/scripts/acceptance-eval.js --story <storyId> --verdict <verdict-path>
187
+ --cmd node .agents/scripts/acceptance-eval.js --story <storyId> --verdict <verdict-path> --cwd <workCwd>
188
188
  node .agents/scripts/update-ticket-state.js --ticket <storyId> --state agent::blocked
189
189
  ```
190
190
 
@@ -381,7 +381,9 @@ half with the second suppressed. Either way every gate runs before the first
381
381
  where the second half is read:
382
382
 
383
383
  **Hard — the run refuses:** a body that does not parse, a ticket that is not
384
- a Story, an empty `acceptance[]`, an unknown or cyclic `depends_on`, the
384
+ a Story, an empty `acceptance[]`, a `verify[]` entry that can exit 0 after a
385
+ failure (`|| true`, `|| :`, `|| break`, `|| continue`, or a loop with no
386
+ failing `exit`; use `|| exit 1`), an unknown or cyclic `depends_on`, the
385
387
  same-wave collision refusal at N>1, a supersede claim on a non-source id or
386
388
  one claimed twice, and a `deletes` entry naming a path absent at base.
387
389
  Commit subjects are not scanned — the `commit-msg` hook and
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,29 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.121.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.120.0...mandrel-v2.121.0) (2026-11-12)
19
+
20
+
21
+ ### Added
22
+
23
+ * new and renamed files are judged by the coverage gate, and untested new files get the full CRAP check ([#6068](https://github.com/dsj1984/mandrel/issues/6068)) ([#6076](https://github.com/dsj1984/mandrel/issues/6076)) ([b28ce16](https://github.com/dsj1984/mandrel/commit/b28ce16a6d739f94782df6748632cf3952aae989))
24
+ * plan-persist refuses verify entries that discard their exit status ([#6071](https://github.com/dsj1984/mandrel/issues/6071)) ([#6073](https://github.com/dsj1984/mandrel/issues/6073)) ([9fb3ace](https://github.com/dsj1984/mandrel/commit/9fb3ace0e1ca567034050e6485a57d837742e4a9))
25
+ * the acceptance gate runs the Story's scoped verify[] entries itself and refuses a met verdict without passing evidence ([#6067](https://github.com/dsj1984/mandrel/issues/6067)) ([#6077](https://github.com/dsj1984/mandrel/issues/6077)) ([fbe68cd](https://github.com/dsj1984/mandrel/commit/fbe68cd21a7646db46e3efc72200a8c8a3fc4d95))
26
+
27
+
28
+ ### Fixed
29
+
30
+ * evidence-gate neither spends nor records credit when the working tree differs from HEAD ([#6070](https://github.com/dsj1984/mandrel/issues/6070)) ([#6074](https://github.com/dsj1984/mandrel/issues/6074)) ([c0bf74e](https://github.com/dsj1984/mandrel/commit/c0bf74e78e517e859570c37ad9b88e6dfd7ab1e6))
31
+ * handoff's credit re-recorders skip a dirty tree, sharing evidence-gate's probe ([#6078](https://github.com/dsj1984/mandrel/issues/6078)) ([#6079](https://github.com/dsj1984/mandrel/issues/6079)) ([012f305](https://github.com/dsj1984/mandrel/commit/012f305a0a62c1e569f475f7ef17ead9bf8ab08c))
32
+
33
+ ## [2.120.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.119.0...mandrel-v2.120.0) (2026-11-12)
34
+
35
+
36
+ ### Added
37
+
38
+ * merge wait settles a merge-queue ejection: re-queue an inherited failure, hand back an own failure with the queue run's digest ([#6060](https://github.com/dsj1984/mandrel/issues/6060)) ([#6064](https://github.com/dsj1984/mandrel/issues/6064)) ([d6efd90](https://github.com/dsj1984/mandrel/commit/d6efd90a332636761bed253dfe726e9342562c43))
39
+ * under suiteOfRecord ci the handoff runs the changed-tests command as a guard, and doctor reports a suite run in both places ([#6061](https://github.com/dsj1984/mandrel/issues/6061)) ([#6062](https://github.com/dsj1984/mandrel/issues/6062)) ([1ecbfb9](https://github.com/dsj1984/mandrel/commit/1ecbfb9d377523335a8ae4d6d4ebcea0f7da383e))
40
+
18
41
  ## [2.119.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.118.0...mandrel-v2.119.0) (2026-11-11)
19
42
 
20
43