mandrel 2.122.0 → 2.124.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 (65) hide show
  1. package/.agents/README.md +1 -1
  2. package/.agents/docs/agentrc-reference.json +1 -0
  3. package/.agents/docs/configuration.md +10 -7
  4. package/.agents/runtime-deps.json +2 -2
  5. package/.agents/schemas/agentrc.schema.json +26 -4
  6. package/.agents/schemas/audit-rules.schema.json +1 -1
  7. package/.agents/schemas/story-deliver-terminal.schema.json +7 -2
  8. package/.agents/scripts/check-doc-links.js +4 -4
  9. package/.agents/scripts/lib/audit-baselines/surface-entry.js +2 -2
  10. package/.agents/scripts/lib/audit-exceptions/globs.js +2 -2
  11. package/.agents/scripts/lib/audit-exceptions/scope.js +2 -2
  12. package/.agents/scripts/lib/audit-suite/selector.js +3 -3
  13. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +3 -3
  14. package/.agents/scripts/lib/baselines/components.js +2 -2
  15. package/.agents/scripts/lib/baselines/kinds/_crap-new-method-gate.js +2 -2
  16. package/.agents/scripts/lib/bdd-runner-detect.js +3 -4
  17. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +2 -2
  18. package/.agents/scripts/lib/close-validation/gates.js +16 -3
  19. package/.agents/scripts/lib/close-validation/test-delta.js +9 -4
  20. package/.agents/scripts/lib/config/gates/coverage.schema.js +2 -2
  21. package/.agents/scripts/lib/config/handoff.js +21 -6
  22. package/.agents/scripts/lib/config-settings-schema-delivery.js +19 -10
  23. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  24. package/.agents/scripts/lib/coverage-baseline.js +8 -4
  25. package/.agents/scripts/lib/coverage-capture-delta.js +2 -2
  26. package/.agents/scripts/lib/coverage-capture-own-fix.js +2 -2
  27. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  28. package/.agents/scripts/lib/git-test-guard.js +119 -0
  29. package/.agents/scripts/lib/git-utils.js +3 -0
  30. package/.agents/scripts/lib/maintainability-utils.js +4 -4
  31. package/.agents/scripts/lib/observability/handoff-telemetry.js +2 -0
  32. package/.agents/scripts/lib/orchestration/acceptance-eval-decision.js +3 -2
  33. package/.agents/scripts/lib/orchestration/block-class-recovery.js +44 -0
  34. package/.agents/scripts/lib/orchestration/code-review.js +35 -19
  35. package/.agents/scripts/lib/orchestration/diff-magnitude.js +1 -1
  36. package/.agents/scripts/lib/orchestration/git-cleanup/phases/filters.js +3 -3
  37. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +15 -7
  38. package/.agents/scripts/lib/orchestration/merge-queue.js +36 -10
  39. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +3 -4
  40. package/.agents/scripts/lib/orchestration/review-history.js +9 -10
  41. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +9 -2
  42. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +8 -5
  43. package/.agents/scripts/lib/orchestration/review-providers/codex.js +3 -11
  44. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  45. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +22 -0
  46. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +10 -2
  47. package/.agents/scripts/lib/orchestration/review-providers/types.js +2 -0
  48. package/.agents/scripts/lib/orchestration/review-providers/ultrareview.js +13 -2
  49. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +40 -15
  50. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +8 -1
  51. package/.agents/scripts/lib/orchestration/story-handoff.js +216 -54
  52. package/.agents/scripts/lib/test-temp.js +5 -5
  53. package/.agents/scripts/lib/test-tiers.js +3 -3
  54. package/.agents/scripts/lib/util/glob-match.js +64 -0
  55. package/.agents/scripts/lib/wave-runner/footprint.js +3 -3
  56. package/.agents/scripts/run-tests.js +2 -1
  57. package/.agents/scripts/single-story-init.js +3 -3
  58. package/.agents/workflows/helpers/code-review.md +8 -1
  59. package/.agents/workflows/helpers/deliver-digest.md +23 -24
  60. package/.agents/workflows/helpers/deliver-reference.md +62 -26
  61. package/.agents/workflows/helpers/deliver-story-reference.md +10 -3
  62. package/.agents/workflows/helpers/deliver-story.md +27 -7
  63. package/.agents/workflows/mandrel-deliver.md +8 -2
  64. package/docs/CHANGELOG.md +23 -0
  65. package/package.json +2 -2
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * story-handoff.js — the story-worker's whole post-implementation tail as one
3
- * deterministic sequence: base merge (starting the held review) → duplication
4
- * re-score → blocking preflight (lint and format deposited as close's credit,
5
- * quality-preview, baselined ratchets) → the one credited run, which a halted
3
+ * deterministic sequence: base merge → duplication re-score → blocking
4
+ * preflight (a fast lane, then the held review starts; lint and format
5
+ * deposited as close's credit, quality-preview, baselined ratchets) → the one credited run, which a halted
6
6
  * review skips or aborts → baseline seating → close's post-capture CRAP and
7
7
  * baselines scoring → push + remote-ref check → review awaited. It runs exactly what deliver-digest § 5 and deliver-reference
8
8
  * define, with close's own gate identities, and settles one envelope:
@@ -12,7 +12,7 @@
12
12
  * labels untouched.
13
13
  * - `blocked` (exit 1) — the worker cannot: a rejected push, an unreachable
14
14
  * remote, an unconfirmed base branch, an unregistered baseline merge
15
- * driver or a suite that lost workers to host memory (exit 77). Flips `agent::blocked` and posts a `friction` comment.
15
+ * driver, a CRITICAL at the review round cap or a suite that lost workers to host memory (exit 77). Flips `agent::blocked` and posts a `friction` comment.
16
16
  *
17
17
  * Idempotent: a re-run skips every step whose result is still valid for the
18
18
  * current HEAD, judged by the step's output signal, never its exit code alone.
@@ -39,8 +39,9 @@ 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
41
  import { substituteChangedSince } from '../close-validation/test-delta.js';
42
+ import { getAcceptanceEval } from '../config/acceptance-eval.js';
42
43
  import { getBaselines } from '../config/baselines.js';
43
- import { getPostSeatChecks } from '../config/handoff.js';
44
+ import { getFirstChecks, getPostSeatChecks } from '../config/handoff.js';
44
45
  import { getQuality } from '../config/quality.js';
45
46
  import {
46
47
  orchestrationLogDir,
@@ -74,6 +75,7 @@ import { describeBlocking } from '../suite-admission.js';
74
75
  import { writeFileAtomic } from '../util/atomic-write.js';
75
76
  import { defaultSleep } from '../util/sleep.js';
76
77
  import { hashCommandConfig } from '../validation-evidence.js';
78
+ import { effectiveCap } from './acceptance-eval-decision.js';
77
79
  import { runStreamed } from './evidence-stream.js';
78
80
  import {
79
81
  baselineComparePreflight,
@@ -101,6 +103,7 @@ import { handoffStatePath } from './handoff-state.js';
101
103
  import { settleSuiteOfRecord } from './handoff-suite-of-record.js';
102
104
  import { requestedLanes, runPreflightLanes } from './preflight-lanes.js';
103
105
  import { probeHeldReviewDiff } from './review-deposit.js';
106
+ import { earlierCriticals, readReviewHistory } from './review-history.js';
104
107
  import {
105
108
  applyDuplicationRescore,
106
109
  runDuplicationCloseRescore,
@@ -357,8 +360,8 @@ function describeSuiteFailure(status) {
357
360
  }
358
361
 
359
362
  /**
360
- * Typecheck, lint and format (deposited), quality-preview, each ratchet whose
361
- * baseline is committed, then close's artifact-free baseline compare.
363
+ * Typecheck, lint and format (deposited), quality-preview, then each ratchet
364
+ * whose baseline is committed.
362
365
  *
363
366
  * @param {object} ctx
364
367
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean, deposit?: object }>}
@@ -386,10 +389,23 @@ function preflightChecks(ctx) {
386
389
  ],
387
390
  },
388
391
  ...ratchets,
389
- ...baselineComparePreflight(ctx),
390
392
  ];
391
393
  }
392
394
 
395
+ /**
396
+ * The fast lane: each `delivery.handoff.firstChecks` entry, then close's
397
+ * artifact-free baseline compare.
398
+ */
399
+ function fastLaneChecks(ctx) {
400
+ const first = getFirstChecks(ctx.config).map(({ cmd, args }, i) => ({
401
+ key: `first-check-${i + 1}`,
402
+ label: `first check \`${[cmd, ...args].join(' ')}\``,
403
+ cmd,
404
+ args,
405
+ }));
406
+ return [...first, ...baselineComparePreflight(ctx)];
407
+ }
408
+
393
409
  /**
394
410
  * A ratchet also fails on `(gate fail)`; its finding names the `+`/`!` rows.
395
411
  * Any other check quotes the failure rows its output carries.
@@ -416,18 +432,19 @@ function preflightFinding(check, run) {
416
432
  }
417
433
 
418
434
  /**
419
- * Runs every check — serially, or over admitted lanes when
420
- * `preflightConcurrency` asks (preflight-lanes.js) — then settles one
421
- * `fix-required` listing each finding in check order; a passed carryable
422
- * check keeps its credit either way. With the re-score overlapped, the scan
423
- * runs beside the checks and the independent baseline compare waits for its
424
- * join, so it scores the committed rows.
435
+ * The fast lane runs first; a finding there settles before any other check
436
+ * or the held review starts (`--report-all` runs on). The rest run serially
437
+ * or over admitted lanes (preflight-lanes.js); one `fix-required` lists every
438
+ * finding in check order. With the re-score overlapped, the scan runs beside
439
+ * the first checks and the compare waits for its join, so it scores the
440
+ * committed rows.
425
441
  *
426
442
  * @param {object} ctx @returns {Promise<StepResult|StepResult[]>}
427
443
  */
428
444
  async function stepPreflight(ctx) {
429
445
  const name = 'preflight';
430
446
  if (preflightCredited(ctx)) {
447
+ ensureReview(ctx);
431
448
  return creditSkip(
432
449
  name,
433
450
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
@@ -435,9 +452,11 @@ async function stepPreflight(ctx) {
435
452
  }
436
453
  ctx.state.preflightCredits = {};
437
454
  delete ctx.state.heldLint;
438
- let checks;
455
+ let fast;
456
+ let rest;
439
457
  try {
440
- checks = preflightChecks(ctx);
458
+ fast = fastLaneChecks(ctx);
459
+ rest = preflightChecks(ctx);
441
460
  } catch (err) {
442
461
  return fixRequired(
443
462
  name,
@@ -445,23 +464,40 @@ async function stepPreflight(ctx) {
445
464
  { cause: 'preflight-unresolved' },
446
465
  );
447
466
  }
448
- const pass = { checks, lint: null, covered: [] };
449
- if (!ctx.overlapRescore) {
450
- return settlePreflight(ctx, await runChecks(ctx, checks, pass));
467
+ const pass = { checks: [...fast, ...rest], lint: null, covered: [] };
468
+ const lane = await runFastLane(ctx, fast, pass);
469
+ const rescore = lane.rescore ? [lane.rescore] : [];
470
+ if (lane.findings.length > 0 && !ctx.reportAll) {
471
+ return [...rescore, settlePreflight(ctx, { ...lane, pass, extra: {} })];
451
472
  }
452
- const scan = startDuplicationScan(ctx);
473
+ ensureReview(ctx);
474
+ const run = await runChecks(ctx, rest, pass);
475
+ run.findings.unshift(...lane.findings);
476
+ return [...rescore, settlePreflight(ctx, run)];
477
+ }
478
+
479
+ /** The first checks (beside an overlapped scan), then the compare. */
480
+ async function runFastLane(ctx, checks, pass) {
481
+ const scan = ctx.overlapRescore ? startDuplicationScan(ctx) : null;
453
482
  const isCompare = (c) => c.key === BASELINES_GATE_NAMES.independent;
454
- const run = await runChecks(
483
+ const findings = await runSerial(
455
484
  ctx,
456
485
  checks.filter((c) => !isCompare(c)),
457
486
  pass,
458
487
  );
459
- const rescore = await joinRescore(ctx, scan);
460
- for (const check of checks.filter(isCompare)) {
488
+ const rescore = scan ? await joinRescore(ctx, scan) : null;
489
+ findings.push(...(await runSerial(ctx, checks.filter(isCompare), pass)));
490
+ return { findings, rescore };
491
+ }
492
+
493
+ /** Each check in order; the findings it settled. */
494
+ async function runSerial(ctx, checks, pass) {
495
+ const findings = [];
496
+ for (const check of checks) {
461
497
  const finding = await runPreflightCheck(ctx, check, pass);
462
- if (finding) run.findings.push(finding);
498
+ if (finding) findings.push(finding);
463
499
  }
464
- return [rescore, settlePreflight(ctx, run)];
500
+ return findings;
465
501
  }
466
502
 
467
503
  /** Preflight passed at HEAD and, when overlapped, the re-score ran there. */
@@ -474,12 +510,7 @@ function preflightCredited(ctx) {
474
510
  /** Run `checks` over the admitted lanes, or serially. */
475
511
  async function runChecks(ctx, checks, pass) {
476
512
  if (!ctx.lanes) {
477
- const findings = [];
478
- for (const check of checks) {
479
- const finding = await runPreflightCheck(ctx, check, pass);
480
- if (finding) findings.push(finding);
481
- }
482
- return { findings, pass, extra: {} };
513
+ return { findings: await runSerial(ctx, checks, pass), pass, extra: {} };
483
514
  }
484
515
  const run = await runPreflightLanes(ctx, checks, ctx.lanes, (check, env) =>
485
516
  runPreflightCheck(ctx, check, pass, env),
@@ -523,12 +554,15 @@ async function joinRescore(ctx, scan) {
523
554
 
524
555
  /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
525
556
  function preflightCause(key) {
526
- return key === BASELINES_GATE_NAMES.independent ||
527
- STANDALONE_RATCHETS.some((r) => r.key === key)
528
- ? 'ratchet'
529
- : key;
557
+ const cause = key.replace(/^first-check-\d+$/, 'first-check');
558
+ return RATCHET_KEYS.has(cause) ? 'ratchet' : cause;
530
559
  }
531
560
 
561
+ const RATCHET_KEYS = new Set([
562
+ BASELINES_GATE_NAMES.independent,
563
+ ...STANDALONE_RATCHETS.map((r) => r.key),
564
+ ]);
565
+
532
566
  /**
533
567
  * Runs one check unless this pass's lint covers it; records the lint result
534
568
  * and credits a passed check.
@@ -648,7 +682,7 @@ async function stepBaseMerge(ctx) {
648
682
  const name = 'base-merge';
649
683
  const skip = await handoffRerunSkip(ctx);
650
684
  if (skip) {
651
- startReview(ctx);
685
+ reviewAtMerge(ctx);
652
686
  return skipped(name, skip);
653
687
  }
654
688
  const sync = await ctx.syncFromBase({
@@ -659,7 +693,7 @@ async function stepBaseMerge(ctx) {
659
693
  if (sync.synced) {
660
694
  ctx.state.baseMergeSettled = true;
661
695
  ctx.head = headSha(ctx) ?? ctx.head;
662
- startReview(ctx);
696
+ reviewAtMerge(ctx);
663
697
  return sync.kind === 'noop-already-current'
664
698
  ? skipped(name, `origin/${ctx.baseBranch} already merged`)
665
699
  : ran(name, mergedDetail(sync, ctx.baseBranch));
@@ -898,6 +932,18 @@ async function settleHostResources(ctx, name, output, extra) {
898
932
  };
899
933
  }
900
934
 
935
+ /** The envelope's `reviewRound`, present only once a CRITICAL settled. */
936
+ function reviewRoundEnvelope(ctx) {
937
+ return ctx.reviewRound ? { reviewRound: ctx.reviewRound } : {};
938
+ }
939
+
940
+ /** A worker cannot fix a blocked review, so it outranks a fixable stop. */
941
+ function outrankingStop(stop, review) {
942
+ const outranks =
943
+ review?.stop === HANDOFF_STATUS.BLOCKED && stop?.stop !== review.stop;
944
+ return outranks ? review : stop;
945
+ }
946
+
901
947
  /** The envelope's `hostResources` field, present only when the consumer reported counts. */
902
948
  function hostResourcesEnvelope(ctx) {
903
949
  return ctx.hostResources ? { hostResources: ctx.hostResources } : {};
@@ -1317,30 +1363,81 @@ async function stepPush(ctx) {
1317
1363
  }
1318
1364
 
1319
1365
  /**
1366
+ * @param {object} ctx
1320
1367
  * @param {object} deposit
1321
1368
  * @param {string|null} depositPath
1322
1369
  * @param {StepResult} settled
1323
1370
  * @returns {StepResult}
1324
1371
  */
1325
- function reviewVerdict(deposit, depositPath, settled) {
1326
- if (deposit?.halted) return haltedReview(deposit, depositPath);
1372
+ function reviewVerdict(ctx, deposit, depositPath, settled) {
1373
+ if (deposit?.halted) return haltedReview(ctx, deposit, depositPath);
1327
1374
  return settled;
1328
1375
  }
1329
1376
 
1330
- /** No code change resolves a missing verdict, so that halt is blocked. */
1331
- function haltedReview(deposit, depositPath) {
1377
+ /**
1378
+ * No code change resolves a missing verdict, so that halt is blocked; a
1379
+ * CRITICAL is the worker's to fix until its round reaches the cap.
1380
+ */
1381
+ function haltedReview(ctx, deposit, depositPath) {
1382
+ const evidence = { evidencePath: depositPath };
1332
1383
  if (deposit.haltCause === 'no-verdict') {
1333
- return blocked('review', 'review-no-verdict', deposit.blockerReason, {
1334
- evidencePath: depositPath,
1335
- });
1384
+ return blocked(
1385
+ 'review',
1386
+ 'review-no-verdict',
1387
+ deposit.blockerReason,
1388
+ evidence,
1389
+ );
1390
+ }
1391
+ return criticalStop(ctx, evidence);
1392
+ }
1393
+
1394
+ /** The CRITICAL halt, `blocked` once its round reaches the cap. */
1395
+ function criticalStop(ctx, evidence) {
1396
+ const history = ctx.readReviewHistory(ctx.storyId, { config: ctx.config });
1397
+ const round = Math.max(1, criticalRounds(history));
1398
+ const cap = effectiveCap(getAcceptanceEval(ctx.config).maxRounds);
1399
+ ctx.reviewRound = { round, cap };
1400
+ if (round >= cap) {
1401
+ return blocked(
1402
+ 'review',
1403
+ 'review-cap',
1404
+ capDetail(history, round, cap),
1405
+ evidence,
1406
+ );
1336
1407
  }
1337
1408
  return fixRequired(
1338
1409
  'review',
1339
1410
  'held review found a CRITICAL — fix, commit, re-run the handoff',
1340
- { evidencePath: depositPath, cause: 'review-critical' },
1411
+ { ...evidence, cause: 'review-critical' },
1341
1412
  );
1342
1413
  }
1343
1414
 
1415
+ /** Runs holding a CRITICAL that survived grounding, verification and override. */
1416
+ function criticalRounds({ runs, overridden }) {
1417
+ const cleared = new Set(overridden);
1418
+ const surviving = (f) =>
1419
+ f?.severity === 'critical' &&
1420
+ !f.unverified &&
1421
+ !f.ungrounded &&
1422
+ !cleared.has(f.id);
1423
+ return runs.filter(
1424
+ (run) => Array.isArray(run?.findings) && run.findings.some(surviving),
1425
+ ).length;
1426
+ }
1427
+
1428
+ /** The cap stop's friction text, naming each open CRITICAL. */
1429
+ function capDetail(history, round, cap) {
1430
+ const titles = earlierCriticals(history)
1431
+ .filter((e) => e.status === 'open')
1432
+ .map((e) => `- ${e.finding.title ?? e.id}`);
1433
+ return [
1434
+ `held review still CRITICAL at round ${round} of ${cap} (delivery.acceptanceEval.maxRounds) — open CRITICALs:`,
1435
+ ...(titles.length > 0
1436
+ ? titles
1437
+ : ['- (none recorded in the review history)']),
1438
+ ].join('\n');
1439
+ }
1440
+
1344
1441
  /** @param {object} ctx @returns {Promise<StepResult>} */
1345
1442
  async function computeHeldReview(ctx) {
1346
1443
  const name = 'review';
@@ -1355,6 +1452,7 @@ async function computeHeldReview(ctx) {
1355
1452
  if (held?.deposit) {
1356
1453
  ctx.review = held.deposit.severity ?? null;
1357
1454
  return reviewVerdict(
1455
+ ctx,
1358
1456
  held.deposit,
1359
1457
  ctx.reviewPath,
1360
1458
  creditSkip(name, 'held review already matches this diff'),
@@ -1383,6 +1481,7 @@ async function computeHeldReview(ctx) {
1383
1481
  }
1384
1482
  ctx.review = outcome.deposit?.severity ?? null;
1385
1483
  return reviewVerdict(
1484
+ ctx,
1386
1485
  outcome.deposit,
1387
1486
  outcome.path ?? null,
1388
1487
  ran(name, 'held review computed and deposited', {
@@ -1425,6 +1524,51 @@ function stepReview(ctx) {
1425
1524
  return ctx.reviewPending;
1426
1525
  }
1427
1526
 
1527
+ /** Start the held review once per run, never under `--report-all`. */
1528
+ function ensureReview(ctx) {
1529
+ if (!ctx.reviewPending && !ctx.reportAll) startReview(ctx);
1530
+ }
1531
+
1532
+ /** A review-first retry starts the held review at the base merge. */
1533
+ function reviewAtMerge(ctx) {
1534
+ if (ctx.reviewFirst) ensureReview(ctx);
1535
+ }
1536
+
1537
+ /** The retry's held review, settled before any other step; clean adds nothing. */
1538
+ async function stepReviewFirst(ctx) {
1539
+ const review = await ctx.reviewPending;
1540
+ return review?.stop
1541
+ ? [review, ...skippedAfterReviewFirst(stepOrder(ctx))]
1542
+ : [];
1543
+ }
1544
+
1545
+ const REVIEW_FIRST_SKIP = 'review-first retry: held review still CRITICAL';
1546
+
1547
+ /** Every step after the review-first stop, listed `skipped`. */
1548
+ function skippedAfterReviewFirst(order) {
1549
+ return order
1550
+ .slice(order.indexOf(stepReviewFirst) + 1)
1551
+ .filter((step) => step !== stepReview)
1552
+ .map((step) => skipped(handoffStepName(step), REVIEW_FIRST_SKIP));
1553
+ }
1554
+
1555
+ /** `--report-all` never retries review-first. */
1556
+ function reviewFirstFor(prior, reportAll) {
1557
+ return !reportAll && isReviewFirstRetry(prior);
1558
+ }
1559
+
1560
+ /**
1561
+ * The previous run stopped on a CRITICAL after its preflight passed at its
1562
+ * head: this run settles the review before paying for any check again.
1563
+ */
1564
+ function isReviewFirstRetry({ state, envelope }) {
1565
+ return (
1566
+ envelope?.cause === 'review-critical' &&
1567
+ Boolean(envelope.headSha) &&
1568
+ state.preflightHead === envelope.headSha
1569
+ );
1570
+ }
1571
+
1428
1572
  /**
1429
1573
  * Close's own duplication re-score, before any credit is minted, so close's
1430
1574
  * re-score no-ops on the handed-off tree. Best-effort: never stops the run.
@@ -1553,17 +1697,19 @@ function appendReview(steps, review) {
1553
1697
  * coverage seat after the capture keeps the stamp fresh.
1554
1698
  *
1555
1699
  * Under admitted preflight lanes the re-score runs inside preflight instead.
1700
+ * A review-first retry awaits the held review right after the base merge.
1556
1701
  *
1557
- * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean }} ctx
1702
+ * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean, reviewFirst?: boolean }} ctx
1558
1703
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
1559
1704
  */
1560
- function stepOrder({ depositor, overlapRescore }) {
1705
+ function stepOrder({ depositor, overlapRescore, reviewFirst }) {
1561
1706
  const middle =
1562
1707
  depositor === 'test'
1563
1708
  ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1564
1709
  : [beforeRun(stepCreditedRun), stepSeat];
1565
1710
  return [
1566
1711
  stepBaseMerge,
1712
+ ...reviewFirstStep(reviewFirst),
1567
1713
  ...serialRescore(overlapRescore),
1568
1714
  stepSeatStatic,
1569
1715
  stepPreflight,
@@ -1574,6 +1720,11 @@ function stepOrder({ depositor, overlapRescore }) {
1574
1720
  ];
1575
1721
  }
1576
1722
 
1723
+ /** The review-first await, present only on that retry. */
1724
+ function reviewFirstStep(reviewFirst) {
1725
+ return reviewFirst ? [stepReviewFirst] : [];
1726
+ }
1727
+
1577
1728
  /** The standalone re-score step, absent when it overlaps preflight. */
1578
1729
  function serialRescore(overlapRescore) {
1579
1730
  return overlapRescore ? [] : [stepDuplicationRescore];
@@ -1682,27 +1833,29 @@ function precheck(ctx) {
1682
1833
  }
1683
1834
 
1684
1835
  /**
1685
- * `{}` when absent or corrupt; a corrupt file is reported.
1836
+ * The previous run's state and envelope; `{ state: {} }` when absent or
1837
+ * corrupt, and a corrupt file is reported.
1686
1838
  *
1687
1839
  * @param {string} statePath
1688
1840
  * @param {(tag: string, msg: string) => void} progress
1689
- * @returns {{ baseMergeSettled?: boolean, preflightHead?: string, preflightCredits?: Record<string, { head: string, configHash: string }>, creditHead?: string, creditTimings?: object, seatHead?: string, staticSeatHead?: string, postCaptureHead?: string, duplicationRescore?: { head: string, partners: Record<string, string[]> } }}
1841
+ * @returns {{ envelope?: object, state: { baseMergeSettled?: boolean, preflightHead?: string, preflightCredits?: Record<string, { head: string, configHash: string }>, creditHead?: string, creditTimings?: object, seatHead?: string, staticSeatHead?: string, postCaptureHead?: string, duplicationRescore?: { head: string, partners: Record<string, string[]> } } }}
1690
1842
  */
1691
1843
  function readState(statePath, progress) {
1692
1844
  let raw;
1693
1845
  try {
1694
1846
  raw = fs.readFileSync(statePath, 'utf8');
1695
1847
  } catch {
1696
- return {};
1848
+ return { state: {} };
1697
1849
  }
1698
1850
  try {
1699
- return JSON.parse(raw)?.state ?? {};
1851
+ const parsed = JSON.parse(raw);
1852
+ return { state: parsed?.state ?? {}, envelope: parsed?.envelope };
1700
1853
  } catch (err) {
1701
1854
  progress(
1702
1855
  'STATE',
1703
1856
  `⚠️ ignoring corrupt ${statePath} (${err.message}) — every step re-runs`,
1704
1857
  );
1705
- return {};
1858
+ return { state: {} };
1706
1859
  }
1707
1860
  }
1708
1861
 
@@ -1779,6 +1932,7 @@ async function defaultBlock({
1779
1932
  * emitFriction?: typeof emitRuntimeFriction,
1780
1933
  * writeSignal?: typeof import('../signals/write.js').appendSignal,
1781
1934
  * readSignals?: typeof import('../signals/write.js').forEachLine,
1935
+ * readReviewHistoryFn?: typeof readReviewHistory,
1782
1936
  * }} deps `evidenceCwd` anchors close's evidence store (the main checkout);
1783
1937
  * `runCommand` receives `onChunk`, `signal` and (when set)
1784
1938
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
@@ -1820,6 +1974,7 @@ export async function runStoryHandoff(
1820
1974
  admitSuite = withSuiteAdmission,
1821
1975
  pruneStaleCrap = pruneStaleCrapRows,
1822
1976
  isCaptureFreshFn = isCaptureFresh,
1977
+ readReviewHistoryFn = readReviewHistory,
1823
1978
  writeSignal,
1824
1979
  readSignals,
1825
1980
  } = deps;
@@ -1836,6 +1991,7 @@ export async function runStoryHandoff(
1836
1991
  const branch = getStoryBranch(storyId);
1837
1992
  const evidencePathFor = (name) =>
1838
1993
  path.join(logDir, `story-handoff-${storyId}-${name}.log`);
1994
+ const prior = readState(statePath, progress);
1839
1995
  const storyProgress = createStoryProgress({
1840
1996
  storyId,
1841
1997
  stage: 'handoff',
@@ -1871,7 +2027,10 @@ export async function runStoryHandoff(
1871
2027
  pruneStaleCrap,
1872
2028
  isCaptureFresh: isCaptureFreshFn,
1873
2029
  reportAll,
1874
- state: readState(statePath, progress),
2030
+ state: prior.state,
2031
+ reviewFirst: reviewFirstFor(prior, reportAll),
2032
+ readReviewHistory: readReviewHistoryFn,
2033
+ reviewRound: null,
1875
2034
  review: null,
1876
2035
  reviewPending: null,
1877
2036
  reviewSettled: null,
@@ -1922,7 +2081,9 @@ export async function runStoryHandoff(
1922
2081
  steps.push(stop);
1923
2082
  progress(stop.name, `${stop.outcome} — ${stop.detail}`);
1924
2083
  }
1925
- appendReview(steps, await ctx.reviewPending);
2084
+ const review = await ctx.reviewPending;
2085
+ appendReview(steps, review);
2086
+ stop = outrankingStop(stop, review);
1926
2087
 
1927
2088
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1928
2089
  const credited = steps.find((s) => s.name === 'credited-run');
@@ -1950,6 +2111,7 @@ export async function runStoryHandoff(
1950
2111
  lockWait: credited?.lockWait ?? null,
1951
2112
  suiteTimings: credited?.suiteTimings ?? null,
1952
2113
  reviewMs: ctx.reviewMs,
2114
+ ...reviewRoundEnvelope(ctx),
1953
2115
  ...coverageEnvelope(ctx),
1954
2116
  ...hostResourcesEnvelope(ctx),
1955
2117
  ...ctx.baseMergeEnvelope,
@@ -7,7 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
- import picomatch from 'picomatch';
10
+ import { globMatcher } from './util/glob-match.js';
11
11
  import { toPosix, walkFiles } from './util/paths.js';
12
12
 
13
13
  /** Suite-root name prefix; the guard matches on it. */
@@ -253,21 +253,21 @@ const LINT_ESCAPE = 'test-temp-allow';
253
253
  * Raw OS-temp mints outside {@link makeTempDir}, in explicit globs only.
254
254
  *
255
255
  * @param {string} repoRoot
256
- * @param {string[]} globs repo-relative picomatch patterns
256
+ * @param {string[]} globs repo-relative glob patterns
257
257
  * @param {{ fsImpl?: typeof fs }} [deps]
258
258
  * @returns {{ file: string, line: number, text: string }[]}
259
259
  */
260
260
  export function findRawTmpdirMkdtemp(repoRoot, globs, { fsImpl = fs } = {}) {
261
261
  const patterns = (globs ?? []).filter(Boolean);
262
- // Split negations out: in a mixed picomatch array a `!` entry is its own
262
+ // Split negations out: in a mixed glob array a `!` entry is its own
263
263
  // positive matcher, which widens the scan instead of narrowing it.
264
264
  const include = patterns.filter((p) => !p.startsWith('!'));
265
265
  const exclude = patterns
266
266
  .filter((p) => p.startsWith('!'))
267
267
  .map((p) => p.slice(1));
268
268
  if (include.length === 0) return [];
269
- const isIncluded = picomatch(include);
270
- const isExcluded = exclude.length > 0 ? picomatch(exclude) : () => false;
269
+ const isIncluded = globMatcher(include);
270
+ const isExcluded = exclude.length > 0 ? globMatcher(exclude) : () => false;
271
271
  const findings = [];
272
272
  for (const rel of listJsSources(repoRoot, fsImpl)) {
273
273
  if (!isIncluded(rel) || isExcluded(rel)) continue;
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import picomatch from 'picomatch';
3
+ import { globMatcher } from './util/glob-match.js';
4
4
 
5
5
  /** Slow suites (real git, binary spawns) excluded from `test:quick`. */
6
6
  export const INTEGRATION_INCLUDE = [
@@ -14,7 +14,7 @@ export const INTEGRATION_INCLUDE = [
14
14
  'tests/single-story-close-sync.test.js',
15
15
  ];
16
16
 
17
- const matchesIntegration = picomatch(INTEGRATION_INCLUDE, { dot: true });
17
+ const matchesIntegration = globMatcher(INTEGRATION_INCLUDE, { dot: true });
18
18
 
19
19
  /**
20
20
  * Pack-and-install suites driving the shipped binary — too expensive for
@@ -23,7 +23,7 @@ const matchesIntegration = picomatch(INTEGRATION_INCLUDE, { dot: true });
23
23
  */
24
24
  const E2E_INCLUDE = ['tests/e2e/**/*.test.js'];
25
25
 
26
- const matchesE2E = picomatch(E2E_INCLUDE, { dot: true });
26
+ const matchesE2E = globMatcher(E2E_INCLUDE, { dot: true });
27
27
 
28
28
  const TIERS = ['full', 'quick', 'integration', 'e2e'];
29
29
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * glob-match.js — the one glob matcher for shipped scripts.
3
+ *
4
+ * Every repo-relative glob (config, audit rules, footprints) is matched here,
5
+ * on POSIX semantics on every platform, so a pattern means the same thing on
6
+ * a Windows runner as on Linux. Built on minimatch; picomatch was dropped
7
+ * because no release fixes GHSA-fc5q-39xc-vjpf.
8
+ */
9
+
10
+ import { Minimatch } from 'minimatch';
11
+
12
+ const BASE_OPTIONS = Object.freeze({ platform: 'linux', nocomment: true });
13
+
14
+ // `dir/**` also matches `dir` itself, as picomatch did; `!dir/**` excludes it.
15
+ function compile(pattern, opts) {
16
+ const options = { ...BASE_OPTIONS, ...opts };
17
+ const mm = new Minimatch(pattern, options);
18
+ if (!pattern.endsWith('/**')) return (file) => mm.match(file);
19
+ const dir = new Minimatch(pattern.slice(0, -3), options);
20
+ return mm.negate
21
+ ? (file) => mm.match(file) && dir.match(file)
22
+ : (file) => mm.match(file) || dir.match(file);
23
+ }
24
+
25
+ /**
26
+ * @param {string|string[]} patterns A path matches when ANY pattern does.
27
+ * @param {{ dot?: boolean }} [opts]
28
+ * @returns {(file: string) => boolean}
29
+ */
30
+ export function globMatcher(patterns, opts = {}) {
31
+ const matchers = [patterns].flat().map((p) => compile(p, opts));
32
+ return (file) => matchers.some((match) => match(file));
33
+ }
34
+
35
+ /**
36
+ * @param {string} file
37
+ * @param {string|string[]} patterns
38
+ * @param {{ dot?: boolean }} [opts]
39
+ * @returns {boolean}
40
+ */
41
+ export function isGlobMatch(file, patterns, opts = {}) {
42
+ return globMatcher(patterns, opts)(file);
43
+ }
44
+
45
+ const hasMagic = (segment) => new Minimatch(segment, BASE_OPTIONS).hasMagic();
46
+
47
+ /**
48
+ * Split a glob into its static directory prefix and whether it has magic. A
49
+ * literal path is its own base; a leading `!` is not part of the base.
50
+ *
51
+ * @param {string} glob
52
+ * @returns {{ base: string, isGlob: boolean }}
53
+ */
54
+ export function scanGlob(glob) {
55
+ const text = String(glob).replace(/^!/, '');
56
+ const segments = text.split('/');
57
+ const firstMagic = segments.findIndex(hasMagic);
58
+ if (firstMagic === -1) return { base: text, isGlob: false };
59
+ const base = segments.slice(0, firstMagic).join('/');
60
+ return {
61
+ base: base === '' && text.startsWith('/') ? '/' : base,
62
+ isGlob: true,
63
+ };
64
+ }
@@ -9,7 +9,7 @@
9
9
  * @module lib/wave-runner/footprint
10
10
  */
11
11
 
12
- import picomatch from 'picomatch';
12
+ import { globMatcher, scanGlob } from '../util/glob-match.js';
13
13
 
14
14
  /**
15
15
  * One class today; kept on the envelope so consumers keyed on `source` stay
@@ -62,7 +62,7 @@ const GLOB_OPTIONS = Object.freeze({ dot: true });
62
62
  * @returns {string}
63
63
  */
64
64
  function globBase(glob) {
65
- return picomatch.scan(glob).base;
65
+ return scanGlob(glob).base;
66
66
  }
67
67
 
68
68
  /**
@@ -117,7 +117,7 @@ function addHit(hits, path, side) {
117
117
  */
118
118
  function collectGlobHits(hits, mine, theirs, side) {
119
119
  for (const glob of mine.globs) {
120
- const matches = picomatch(glob, GLOB_OPTIONS);
120
+ const matches = globMatcher(glob, GLOB_OPTIONS);
121
121
  const covers =
122
122
  theirs.concrete.some((path) => matches(path)) ||
123
123
  theirs.globs.some((other) => globsOverlap(glob, other));