mandrel 2.123.0 → 2.125.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 (105) hide show
  1. package/.agents/README.md +1 -1
  2. package/.agents/docs/agentrc-reference.json +2 -0
  3. package/.agents/docs/configuration.md +6 -3
  4. package/.agents/docs/runbooks/dispatch-board.md +174 -0
  5. package/.agents/docs/runbooks/dispatch.md +219 -0
  6. package/.agents/docs/runbooks/session-titles.md +52 -0
  7. package/.agents/runtime-deps.json +2 -2
  8. package/.agents/schemas/agentrc.schema.json +85 -3
  9. package/.agents/schemas/audit-rules.schema.json +1 -1
  10. package/.agents/schemas/story-deliver-terminal.schema.json +7 -2
  11. package/.agents/scripts/acceptance-eval.js +11 -2
  12. package/.agents/scripts/check-doc-links.js +4 -4
  13. package/.agents/scripts/dispatch.js +400 -0
  14. package/.agents/scripts/lib/audit-baselines/surface-entry.js +2 -2
  15. package/.agents/scripts/lib/audit-exceptions/globs.js +2 -2
  16. package/.agents/scripts/lib/audit-exceptions/scope.js +2 -2
  17. package/.agents/scripts/lib/audit-suite/selector.js +3 -3
  18. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +3 -3
  19. package/.agents/scripts/lib/baselines/components.js +2 -2
  20. package/.agents/scripts/lib/baselines/kinds/_crap-new-method-gate.js +2 -2
  21. package/.agents/scripts/lib/bdd-runner-detect.js +3 -4
  22. package/.agents/scripts/lib/child-detached.js +48 -0
  23. package/.agents/scripts/lib/child-exec.js +11 -0
  24. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +2 -2
  25. package/.agents/scripts/lib/config/delivery-routing.js +15 -12
  26. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  27. package/.agents/scripts/lib/config/handoff.js +21 -6
  28. package/.agents/scripts/lib/config/temp-paths.js +26 -0
  29. package/.agents/scripts/lib/config-settings-schema-delivery.js +64 -10
  30. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  31. package/.agents/scripts/lib/coverage-baseline.js +3 -3
  32. package/.agents/scripts/lib/coverage-capture-delta.js +2 -2
  33. package/.agents/scripts/lib/coverage-capture-own-fix.js +2 -2
  34. package/.agents/scripts/lib/dispatch/environments.js +135 -0
  35. package/.agents/scripts/lib/dispatch/launch-cloud.js +164 -0
  36. package/.agents/scripts/lib/dispatch/launch-local.js +77 -0
  37. package/.agents/scripts/lib/dispatch/liveness.js +21 -0
  38. package/.agents/scripts/lib/dispatch/record.js +54 -0
  39. package/.agents/scripts/lib/dispatch/status.js +285 -0
  40. package/.agents/scripts/lib/dispatch/targets.js +101 -0
  41. package/.agents/scripts/lib/dispatch/verdict.js +207 -0
  42. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  43. package/.agents/scripts/lib/git-test-guard.js +119 -0
  44. package/.agents/scripts/lib/git-utils.js +3 -0
  45. package/.agents/scripts/lib/maintainability-utils.js +4 -4
  46. package/.agents/scripts/lib/observability/handoff-telemetry.js +2 -0
  47. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  48. package/.agents/scripts/lib/orchestration/acceptance-eval-decision.js +3 -2
  49. package/.agents/scripts/lib/orchestration/block-class-recovery.js +44 -0
  50. package/.agents/scripts/lib/orchestration/code-review.js +35 -19
  51. package/.agents/scripts/lib/orchestration/diff-magnitude.js +1 -1
  52. package/.agents/scripts/lib/orchestration/git-cleanup/phases/filters.js +3 -3
  53. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +3 -4
  54. package/.agents/scripts/lib/orchestration/review-history.js +9 -10
  55. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +9 -2
  56. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +8 -5
  57. package/.agents/scripts/lib/orchestration/review-providers/codex.js +3 -11
  58. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  59. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +22 -0
  60. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +10 -2
  61. package/.agents/scripts/lib/orchestration/review-providers/types.js +2 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/ultrareview.js +13 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +40 -15
  64. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +2 -0
  65. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +8 -1
  66. package/.agents/scripts/lib/orchestration/story-handoff.js +222 -54
  67. package/.agents/scripts/lib/orchestration/story-stage-publish.js +147 -0
  68. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  69. package/.agents/scripts/lib/test-temp.js +5 -5
  70. package/.agents/scripts/lib/test-tiers.js +3 -3
  71. package/.agents/scripts/lib/util/glob-match.js +64 -0
  72. package/.agents/scripts/lib/wave-runner/footprint.js +3 -3
  73. package/.agents/scripts/run-tests.js +2 -1
  74. package/.agents/scripts/session-title.js +187 -0
  75. package/.agents/scripts/single-story-confirm-merge.js +7 -0
  76. package/.agents/scripts/single-story-init.js +6 -3
  77. package/.agents/workflows/helpers/audit-lens-core.md +4 -0
  78. package/.agents/workflows/helpers/code-review.md +8 -1
  79. package/.agents/workflows/helpers/deliver-digest.md +22 -23
  80. package/.agents/workflows/helpers/deliver-light.md +4 -1
  81. package/.agents/workflows/helpers/deliver-reference.md +55 -24
  82. package/.agents/workflows/helpers/deliver-story-reference.md +10 -3
  83. package/.agents/workflows/helpers/deliver-story.md +27 -7
  84. package/.agents/workflows/helpers/qa-core.md +2 -0
  85. package/.agents/workflows/mandrel-deliver.md +14 -4
  86. package/.agents/workflows/mandrel-orchestrate.md +2 -0
  87. package/.agents/workflows/mandrel-plan.md +4 -0
  88. package/README.md +8 -0
  89. package/bin/mandrel.js +35 -13
  90. package/docs/CHANGELOG.md +29 -0
  91. package/lib/cli/dispatch.js +27 -0
  92. package/lib/cli/ui/accounts.js +81 -0
  93. package/lib/cli/ui/board-model.js +372 -0
  94. package/lib/cli/ui/board.css +525 -0
  95. package/lib/cli/ui/board.html +80 -0
  96. package/lib/cli/ui/board.js +676 -0
  97. package/lib/cli/ui/log-tail.js +89 -0
  98. package/lib/cli/ui/panel-model.js +100 -0
  99. package/lib/cli/ui/preferences.js +136 -0
  100. package/lib/cli/ui/request-guard.js +108 -0
  101. package/lib/cli/ui/server.js +211 -0
  102. package/lib/cli/ui/sources.js +202 -0
  103. package/lib/cli/ui/story-detail.js +92 -0
  104. package/lib/cli/ui.js +114 -0
  105. 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,12 +103,14 @@ 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,
107
110
  scanDuplicationRescore,
108
111
  } from './story-close/duplication-close-rescore.js';
109
112
  import { createStoryProgress, handoffStepName } from './story-progress.js';
113
+ import { publishDeliveryStage } from './story-stage-publish.js';
110
114
  import {
111
115
  STATE_LABELS,
112
116
  transitionTicketState,
@@ -357,8 +361,8 @@ function describeSuiteFailure(status) {
357
361
  }
358
362
 
359
363
  /**
360
- * Typecheck, lint and format (deposited), quality-preview, each ratchet whose
361
- * baseline is committed, then close's artifact-free baseline compare.
364
+ * Typecheck, lint and format (deposited), quality-preview, then each ratchet
365
+ * whose baseline is committed.
362
366
  *
363
367
  * @param {object} ctx
364
368
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean, deposit?: object }>}
@@ -386,10 +390,23 @@ function preflightChecks(ctx) {
386
390
  ],
387
391
  },
388
392
  ...ratchets,
389
- ...baselineComparePreflight(ctx),
390
393
  ];
391
394
  }
392
395
 
396
+ /**
397
+ * The fast lane: each `delivery.handoff.firstChecks` entry, then close's
398
+ * artifact-free baseline compare.
399
+ */
400
+ function fastLaneChecks(ctx) {
401
+ const first = getFirstChecks(ctx.config).map(({ cmd, args }, i) => ({
402
+ key: `first-check-${i + 1}`,
403
+ label: `first check \`${[cmd, ...args].join(' ')}\``,
404
+ cmd,
405
+ args,
406
+ }));
407
+ return [...first, ...baselineComparePreflight(ctx)];
408
+ }
409
+
393
410
  /**
394
411
  * A ratchet also fails on `(gate fail)`; its finding names the `+`/`!` rows.
395
412
  * Any other check quotes the failure rows its output carries.
@@ -416,18 +433,19 @@ function preflightFinding(check, run) {
416
433
  }
417
434
 
418
435
  /**
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.
436
+ * The fast lane runs first; a finding there settles before any other check
437
+ * or the held review starts (`--report-all` runs on). The rest run serially
438
+ * or over admitted lanes (preflight-lanes.js); one `fix-required` lists every
439
+ * finding in check order. With the re-score overlapped, the scan runs beside
440
+ * the first checks and the compare waits for its join, so it scores the
441
+ * committed rows.
425
442
  *
426
443
  * @param {object} ctx @returns {Promise<StepResult|StepResult[]>}
427
444
  */
428
445
  async function stepPreflight(ctx) {
429
446
  const name = 'preflight';
430
447
  if (preflightCredited(ctx)) {
448
+ ensureReview(ctx);
431
449
  return creditSkip(
432
450
  name,
433
451
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
@@ -435,9 +453,11 @@ async function stepPreflight(ctx) {
435
453
  }
436
454
  ctx.state.preflightCredits = {};
437
455
  delete ctx.state.heldLint;
438
- let checks;
456
+ let fast;
457
+ let rest;
439
458
  try {
440
- checks = preflightChecks(ctx);
459
+ fast = fastLaneChecks(ctx);
460
+ rest = preflightChecks(ctx);
441
461
  } catch (err) {
442
462
  return fixRequired(
443
463
  name,
@@ -445,23 +465,40 @@ async function stepPreflight(ctx) {
445
465
  { cause: 'preflight-unresolved' },
446
466
  );
447
467
  }
448
- const pass = { checks, lint: null, covered: [] };
449
- if (!ctx.overlapRescore) {
450
- return settlePreflight(ctx, await runChecks(ctx, checks, pass));
468
+ const pass = { checks: [...fast, ...rest], lint: null, covered: [] };
469
+ const lane = await runFastLane(ctx, fast, pass);
470
+ const rescore = lane.rescore ? [lane.rescore] : [];
471
+ if (lane.findings.length > 0 && !ctx.reportAll) {
472
+ return [...rescore, settlePreflight(ctx, { ...lane, pass, extra: {} })];
451
473
  }
452
- const scan = startDuplicationScan(ctx);
474
+ ensureReview(ctx);
475
+ const run = await runChecks(ctx, rest, pass);
476
+ run.findings.unshift(...lane.findings);
477
+ return [...rescore, settlePreflight(ctx, run)];
478
+ }
479
+
480
+ /** The first checks (beside an overlapped scan), then the compare. */
481
+ async function runFastLane(ctx, checks, pass) {
482
+ const scan = ctx.overlapRescore ? startDuplicationScan(ctx) : null;
453
483
  const isCompare = (c) => c.key === BASELINES_GATE_NAMES.independent;
454
- const run = await runChecks(
484
+ const findings = await runSerial(
455
485
  ctx,
456
486
  checks.filter((c) => !isCompare(c)),
457
487
  pass,
458
488
  );
459
- const rescore = await joinRescore(ctx, scan);
460
- for (const check of checks.filter(isCompare)) {
489
+ const rescore = scan ? await joinRescore(ctx, scan) : null;
490
+ findings.push(...(await runSerial(ctx, checks.filter(isCompare), pass)));
491
+ return { findings, rescore };
492
+ }
493
+
494
+ /** Each check in order; the findings it settled. */
495
+ async function runSerial(ctx, checks, pass) {
496
+ const findings = [];
497
+ for (const check of checks) {
461
498
  const finding = await runPreflightCheck(ctx, check, pass);
462
- if (finding) run.findings.push(finding);
499
+ if (finding) findings.push(finding);
463
500
  }
464
- return [rescore, settlePreflight(ctx, run)];
501
+ return findings;
465
502
  }
466
503
 
467
504
  /** Preflight passed at HEAD and, when overlapped, the re-score ran there. */
@@ -474,12 +511,7 @@ function preflightCredited(ctx) {
474
511
  /** Run `checks` over the admitted lanes, or serially. */
475
512
  async function runChecks(ctx, checks, pass) {
476
513
  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: {} };
514
+ return { findings: await runSerial(ctx, checks, pass), pass, extra: {} };
483
515
  }
484
516
  const run = await runPreflightLanes(ctx, checks, ctx.lanes, (check, env) =>
485
517
  runPreflightCheck(ctx, check, pass, env),
@@ -523,12 +555,15 @@ async function joinRescore(ctx, scan) {
523
555
 
524
556
  /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
525
557
  function preflightCause(key) {
526
- return key === BASELINES_GATE_NAMES.independent ||
527
- STANDALONE_RATCHETS.some((r) => r.key === key)
528
- ? 'ratchet'
529
- : key;
558
+ const cause = key.replace(/^first-check-\d+$/, 'first-check');
559
+ return RATCHET_KEYS.has(cause) ? 'ratchet' : cause;
530
560
  }
531
561
 
562
+ const RATCHET_KEYS = new Set([
563
+ BASELINES_GATE_NAMES.independent,
564
+ ...STANDALONE_RATCHETS.map((r) => r.key),
565
+ ]);
566
+
532
567
  /**
533
568
  * Runs one check unless this pass's lint covers it; records the lint result
534
569
  * and credits a passed check.
@@ -648,7 +683,7 @@ async function stepBaseMerge(ctx) {
648
683
  const name = 'base-merge';
649
684
  const skip = await handoffRerunSkip(ctx);
650
685
  if (skip) {
651
- startReview(ctx);
686
+ reviewAtMerge(ctx);
652
687
  return skipped(name, skip);
653
688
  }
654
689
  const sync = await ctx.syncFromBase({
@@ -659,7 +694,7 @@ async function stepBaseMerge(ctx) {
659
694
  if (sync.synced) {
660
695
  ctx.state.baseMergeSettled = true;
661
696
  ctx.head = headSha(ctx) ?? ctx.head;
662
- startReview(ctx);
697
+ reviewAtMerge(ctx);
663
698
  return sync.kind === 'noop-already-current'
664
699
  ? skipped(name, `origin/${ctx.baseBranch} already merged`)
665
700
  : ran(name, mergedDetail(sync, ctx.baseBranch));
@@ -898,6 +933,18 @@ async function settleHostResources(ctx, name, output, extra) {
898
933
  };
899
934
  }
900
935
 
936
+ /** The envelope's `reviewRound`, present only once a CRITICAL settled. */
937
+ function reviewRoundEnvelope(ctx) {
938
+ return ctx.reviewRound ? { reviewRound: ctx.reviewRound } : {};
939
+ }
940
+
941
+ /** A worker cannot fix a blocked review, so it outranks a fixable stop. */
942
+ function outrankingStop(stop, review) {
943
+ const outranks =
944
+ review?.stop === HANDOFF_STATUS.BLOCKED && stop?.stop !== review.stop;
945
+ return outranks ? review : stop;
946
+ }
947
+
901
948
  /** The envelope's `hostResources` field, present only when the consumer reported counts. */
902
949
  function hostResourcesEnvelope(ctx) {
903
950
  return ctx.hostResources ? { hostResources: ctx.hostResources } : {};
@@ -1317,30 +1364,81 @@ async function stepPush(ctx) {
1317
1364
  }
1318
1365
 
1319
1366
  /**
1367
+ * @param {object} ctx
1320
1368
  * @param {object} deposit
1321
1369
  * @param {string|null} depositPath
1322
1370
  * @param {StepResult} settled
1323
1371
  * @returns {StepResult}
1324
1372
  */
1325
- function reviewVerdict(deposit, depositPath, settled) {
1326
- if (deposit?.halted) return haltedReview(deposit, depositPath);
1373
+ function reviewVerdict(ctx, deposit, depositPath, settled) {
1374
+ if (deposit?.halted) return haltedReview(ctx, deposit, depositPath);
1327
1375
  return settled;
1328
1376
  }
1329
1377
 
1330
- /** No code change resolves a missing verdict, so that halt is blocked. */
1331
- function haltedReview(deposit, depositPath) {
1378
+ /**
1379
+ * No code change resolves a missing verdict, so that halt is blocked; a
1380
+ * CRITICAL is the worker's to fix until its round reaches the cap.
1381
+ */
1382
+ function haltedReview(ctx, deposit, depositPath) {
1383
+ const evidence = { evidencePath: depositPath };
1332
1384
  if (deposit.haltCause === 'no-verdict') {
1333
- return blocked('review', 'review-no-verdict', deposit.blockerReason, {
1334
- evidencePath: depositPath,
1335
- });
1385
+ return blocked(
1386
+ 'review',
1387
+ 'review-no-verdict',
1388
+ deposit.blockerReason,
1389
+ evidence,
1390
+ );
1391
+ }
1392
+ return criticalStop(ctx, evidence);
1393
+ }
1394
+
1395
+ /** The CRITICAL halt, `blocked` once its round reaches the cap. */
1396
+ function criticalStop(ctx, evidence) {
1397
+ const history = ctx.readReviewHistory(ctx.storyId, { config: ctx.config });
1398
+ const round = Math.max(1, criticalRounds(history));
1399
+ const cap = effectiveCap(getAcceptanceEval(ctx.config).maxRounds);
1400
+ ctx.reviewRound = { round, cap };
1401
+ if (round >= cap) {
1402
+ return blocked(
1403
+ 'review',
1404
+ 'review-cap',
1405
+ capDetail(history, round, cap),
1406
+ evidence,
1407
+ );
1336
1408
  }
1337
1409
  return fixRequired(
1338
1410
  'review',
1339
1411
  'held review found a CRITICAL — fix, commit, re-run the handoff',
1340
- { evidencePath: depositPath, cause: 'review-critical' },
1412
+ { ...evidence, cause: 'review-critical' },
1341
1413
  );
1342
1414
  }
1343
1415
 
1416
+ /** Runs holding a CRITICAL that survived grounding, verification and override. */
1417
+ function criticalRounds({ runs, overridden }) {
1418
+ const cleared = new Set(overridden);
1419
+ const surviving = (f) =>
1420
+ f?.severity === 'critical' &&
1421
+ !f.unverified &&
1422
+ !f.ungrounded &&
1423
+ !cleared.has(f.id);
1424
+ return runs.filter(
1425
+ (run) => Array.isArray(run?.findings) && run.findings.some(surviving),
1426
+ ).length;
1427
+ }
1428
+
1429
+ /** The cap stop's friction text, naming each open CRITICAL. */
1430
+ function capDetail(history, round, cap) {
1431
+ const titles = earlierCriticals(history)
1432
+ .filter((e) => e.status === 'open')
1433
+ .map((e) => `- ${e.finding.title ?? e.id}`);
1434
+ return [
1435
+ `held review still CRITICAL at round ${round} of ${cap} (delivery.acceptanceEval.maxRounds) — open CRITICALs:`,
1436
+ ...(titles.length > 0
1437
+ ? titles
1438
+ : ['- (none recorded in the review history)']),
1439
+ ].join('\n');
1440
+ }
1441
+
1344
1442
  /** @param {object} ctx @returns {Promise<StepResult>} */
1345
1443
  async function computeHeldReview(ctx) {
1346
1444
  const name = 'review';
@@ -1355,6 +1453,7 @@ async function computeHeldReview(ctx) {
1355
1453
  if (held?.deposit) {
1356
1454
  ctx.review = held.deposit.severity ?? null;
1357
1455
  return reviewVerdict(
1456
+ ctx,
1358
1457
  held.deposit,
1359
1458
  ctx.reviewPath,
1360
1459
  creditSkip(name, 'held review already matches this diff'),
@@ -1383,6 +1482,7 @@ async function computeHeldReview(ctx) {
1383
1482
  }
1384
1483
  ctx.review = outcome.deposit?.severity ?? null;
1385
1484
  return reviewVerdict(
1485
+ ctx,
1386
1486
  outcome.deposit,
1387
1487
  outcome.path ?? null,
1388
1488
  ran(name, 'held review computed and deposited', {
@@ -1425,6 +1525,51 @@ function stepReview(ctx) {
1425
1525
  return ctx.reviewPending;
1426
1526
  }
1427
1527
 
1528
+ /** Start the held review once per run, never under `--report-all`. */
1529
+ function ensureReview(ctx) {
1530
+ if (!ctx.reviewPending && !ctx.reportAll) startReview(ctx);
1531
+ }
1532
+
1533
+ /** A review-first retry starts the held review at the base merge. */
1534
+ function reviewAtMerge(ctx) {
1535
+ if (ctx.reviewFirst) ensureReview(ctx);
1536
+ }
1537
+
1538
+ /** The retry's held review, settled before any other step; clean adds nothing. */
1539
+ async function stepReviewFirst(ctx) {
1540
+ const review = await ctx.reviewPending;
1541
+ return review?.stop
1542
+ ? [review, ...skippedAfterReviewFirst(stepOrder(ctx))]
1543
+ : [];
1544
+ }
1545
+
1546
+ const REVIEW_FIRST_SKIP = 'review-first retry: held review still CRITICAL';
1547
+
1548
+ /** Every step after the review-first stop, listed `skipped`. */
1549
+ function skippedAfterReviewFirst(order) {
1550
+ return order
1551
+ .slice(order.indexOf(stepReviewFirst) + 1)
1552
+ .filter((step) => step !== stepReview)
1553
+ .map((step) => skipped(handoffStepName(step), REVIEW_FIRST_SKIP));
1554
+ }
1555
+
1556
+ /** `--report-all` never retries review-first. */
1557
+ function reviewFirstFor(prior, reportAll) {
1558
+ return !reportAll && isReviewFirstRetry(prior);
1559
+ }
1560
+
1561
+ /**
1562
+ * The previous run stopped on a CRITICAL after its preflight passed at its
1563
+ * head: this run settles the review before paying for any check again.
1564
+ */
1565
+ function isReviewFirstRetry({ state, envelope }) {
1566
+ return (
1567
+ envelope?.cause === 'review-critical' &&
1568
+ Boolean(envelope.headSha) &&
1569
+ state.preflightHead === envelope.headSha
1570
+ );
1571
+ }
1572
+
1428
1573
  /**
1429
1574
  * Close's own duplication re-score, before any credit is minted, so close's
1430
1575
  * re-score no-ops on the handed-off tree. Best-effort: never stops the run.
@@ -1553,17 +1698,19 @@ function appendReview(steps, review) {
1553
1698
  * coverage seat after the capture keeps the stamp fresh.
1554
1699
  *
1555
1700
  * Under admitted preflight lanes the re-score runs inside preflight instead.
1701
+ * A review-first retry awaits the held review right after the base merge.
1556
1702
  *
1557
- * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean }} ctx
1703
+ * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean, reviewFirst?: boolean }} ctx
1558
1704
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
1559
1705
  */
1560
- function stepOrder({ depositor, overlapRescore }) {
1706
+ function stepOrder({ depositor, overlapRescore, reviewFirst }) {
1561
1707
  const middle =
1562
1708
  depositor === 'test'
1563
1709
  ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1564
1710
  : [beforeRun(stepCreditedRun), stepSeat];
1565
1711
  return [
1566
1712
  stepBaseMerge,
1713
+ ...reviewFirstStep(reviewFirst),
1567
1714
  ...serialRescore(overlapRescore),
1568
1715
  stepSeatStatic,
1569
1716
  stepPreflight,
@@ -1574,6 +1721,11 @@ function stepOrder({ depositor, overlapRescore }) {
1574
1721
  ];
1575
1722
  }
1576
1723
 
1724
+ /** The review-first await, present only on that retry. */
1725
+ function reviewFirstStep(reviewFirst) {
1726
+ return reviewFirst ? [stepReviewFirst] : [];
1727
+ }
1728
+
1577
1729
  /** The standalone re-score step, absent when it overlaps preflight. */
1578
1730
  function serialRescore(overlapRescore) {
1579
1731
  return overlapRescore ? [] : [stepDuplicationRescore];
@@ -1682,27 +1834,29 @@ function precheck(ctx) {
1682
1834
  }
1683
1835
 
1684
1836
  /**
1685
- * `{}` when absent or corrupt; a corrupt file is reported.
1837
+ * The previous run's state and envelope; `{ state: {} }` when absent or
1838
+ * corrupt, and a corrupt file is reported.
1686
1839
  *
1687
1840
  * @param {string} statePath
1688
1841
  * @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[]> } }}
1842
+ * @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
1843
  */
1691
1844
  function readState(statePath, progress) {
1692
1845
  let raw;
1693
1846
  try {
1694
1847
  raw = fs.readFileSync(statePath, 'utf8');
1695
1848
  } catch {
1696
- return {};
1849
+ return { state: {} };
1697
1850
  }
1698
1851
  try {
1699
- return JSON.parse(raw)?.state ?? {};
1852
+ const parsed = JSON.parse(raw);
1853
+ return { state: parsed?.state ?? {}, envelope: parsed?.envelope };
1700
1854
  } catch (err) {
1701
1855
  progress(
1702
1856
  'STATE',
1703
1857
  `⚠️ ignoring corrupt ${statePath} (${err.message}) — every step re-runs`,
1704
1858
  );
1705
- return {};
1859
+ return { state: {} };
1706
1860
  }
1707
1861
  }
1708
1862
 
@@ -1779,6 +1933,7 @@ async function defaultBlock({
1779
1933
  * emitFriction?: typeof emitRuntimeFriction,
1780
1934
  * writeSignal?: typeof import('../signals/write.js').appendSignal,
1781
1935
  * readSignals?: typeof import('../signals/write.js').forEachLine,
1936
+ * readReviewHistoryFn?: typeof readReviewHistory,
1782
1937
  * }} deps `evidenceCwd` anchors close's evidence store (the main checkout);
1783
1938
  * `runCommand` receives `onChunk`, `signal` and (when set)
1784
1939
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
@@ -1820,6 +1975,7 @@ export async function runStoryHandoff(
1820
1975
  admitSuite = withSuiteAdmission,
1821
1976
  pruneStaleCrap = pruneStaleCrapRows,
1822
1977
  isCaptureFreshFn = isCaptureFresh,
1978
+ readReviewHistoryFn = readReviewHistory,
1823
1979
  writeSignal,
1824
1980
  readSignals,
1825
1981
  } = deps;
@@ -1836,11 +1992,17 @@ export async function runStoryHandoff(
1836
1992
  const branch = getStoryBranch(storyId);
1837
1993
  const evidencePathFor = (name) =>
1838
1994
  path.join(logDir, `story-handoff-${storyId}-${name}.log`);
1995
+ const prior = readState(statePath, progress);
1839
1996
  const storyProgress = createStoryProgress({
1840
1997
  storyId,
1841
1998
  stage: 'handoff',
1842
1999
  config,
1843
2000
  });
2001
+ await publishDeliveryStage({
2002
+ provider: () => createProviderFn(config),
2003
+ storyId,
2004
+ stage: 'handoff',
2005
+ });
1844
2006
  const ctx = {
1845
2007
  storyId,
1846
2008
  cwd,
@@ -1871,7 +2033,10 @@ export async function runStoryHandoff(
1871
2033
  pruneStaleCrap,
1872
2034
  isCaptureFresh: isCaptureFreshFn,
1873
2035
  reportAll,
1874
- state: readState(statePath, progress),
2036
+ state: prior.state,
2037
+ reviewFirst: reviewFirstFor(prior, reportAll),
2038
+ readReviewHistory: readReviewHistoryFn,
2039
+ reviewRound: null,
1875
2040
  review: null,
1876
2041
  reviewPending: null,
1877
2042
  reviewSettled: null,
@@ -1922,7 +2087,9 @@ export async function runStoryHandoff(
1922
2087
  steps.push(stop);
1923
2088
  progress(stop.name, `${stop.outcome} — ${stop.detail}`);
1924
2089
  }
1925
- appendReview(steps, await ctx.reviewPending);
2090
+ const review = await ctx.reviewPending;
2091
+ appendReview(steps, review);
2092
+ stop = outrankingStop(stop, review);
1926
2093
 
1927
2094
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1928
2095
  const credited = steps.find((s) => s.name === 'credited-run');
@@ -1950,6 +2117,7 @@ export async function runStoryHandoff(
1950
2117
  lockWait: credited?.lockWait ?? null,
1951
2118
  suiteTimings: credited?.suiteTimings ?? null,
1952
2119
  reviewMs: ctx.reviewMs,
2120
+ ...reviewRoundEnvelope(ctx),
1953
2121
  ...coverageEnvelope(ctx),
1954
2122
  ...hostResourcesEnvelope(ctx),
1955
2123
  ...ctx.baseMergeEnvelope,
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The delivery stage a Story has reached, published as one `delivery-stage`
3
+ * structured comment on the Story issue so a tool on another machine can show
4
+ * progress for a run it cannot see locally.
5
+ *
6
+ * Advisory only, like the local story-progress record: nothing decides on
7
+ * it, one attempt with no retry, and any failure is logged at debug and
8
+ * swallowed, so no delivery result changes because of it.
9
+ */
10
+
11
+ import { Logger } from '../Logger.js';
12
+ import { findStructuredComment } from './ticketing/reads.js';
13
+ import { upsertStructuredComment } from './ticketing/state.js';
14
+
15
+ const DELIVERY_STAGE_TYPE = 'delivery-stage';
16
+ const DELIVERY_STAGES = Object.freeze([
17
+ 'build',
18
+ 'check',
19
+ 'handoff',
20
+ 'close',
21
+ 'merge',
22
+ ]);
23
+
24
+ const RECORD_RE = /```json\n(\{[^\n]*"kind":"delivery-stage"[^\n]*\})\n```/;
25
+
26
+ const HISTORY_LIMIT = 10;
27
+
28
+ /** The comment body: a one-line summary, then the machine block. */
29
+ function formatDeliveryStageBody(fields) {
30
+ const record = { kind: DELIVERY_STAGE_TYPE, ...fields };
31
+ return `Delivery stage: **${fields.stage}** (Story #${fields.storyId}).\n\n\`\`\`json\n${JSON.stringify(record)}\n\`\`\``;
32
+ }
33
+
34
+ const isEntry = (e) =>
35
+ DELIVERY_STAGES.includes(e?.stage) && typeof e?.at === 'string';
36
+
37
+ const historyOf = (raw) =>
38
+ (Array.isArray(raw) ? raw : [])
39
+ .filter(isEntry)
40
+ .map((e) => ({ stage: e.stage, at: e.at }));
41
+
42
+ /** The entries before `stage`, seeded from a pre-history record's own stage. */
43
+ function priorHistory(previous) {
44
+ if (!previous) return [];
45
+ if (previous.history.length > 0) return previous.history;
46
+ return [{ stage: previous.stage, at: previous.updatedAt }];
47
+ }
48
+
49
+ /**
50
+ * The stage record a comment body carries, or `null` for any other comment.
51
+ * Exported for readers that list an issue's comments.
52
+ *
53
+ * @public
54
+ * @param {unknown} body
55
+ * @returns {object|null} The record; `history` is `[]` on an older one.
56
+ */
57
+ export function parseDeliveryStage(body) {
58
+ const match = typeof body === 'string' ? RECORD_RE.exec(body) : null;
59
+ if (!match) return null;
60
+ let record;
61
+ try {
62
+ record = JSON.parse(match[1]);
63
+ } catch {
64
+ return null;
65
+ }
66
+ const { storyId, stage, prNumber, updatedAt } = record;
67
+ const valid =
68
+ Number.isInteger(storyId) &&
69
+ DELIVERY_STAGES.includes(stage) &&
70
+ (prNumber === null || Number.isInteger(prNumber)) &&
71
+ typeof updatedAt === 'string';
72
+ return valid
73
+ ? {
74
+ kind: DELIVERY_STAGE_TYPE,
75
+ storyId,
76
+ stage,
77
+ prNumber,
78
+ updatedAt,
79
+ history: historyOf(record.history),
80
+ }
81
+ : null;
82
+ }
83
+
84
+ /**
85
+ * Publish `stage` for `storyId`, skipping the write when the comment already
86
+ * names it. Never throws.
87
+ *
88
+ * @param {{ storyId: number, stage: string, prNumber?: number|null,
89
+ * provider: object|(() => object)|null|undefined, now?: () => Date,
90
+ * debug?: (msg: string) => void }} args `provider` may be a thunk so a
91
+ * provider that fails to build is swallowed too; a missing one skips.
92
+ * @returns {Promise<'published'|'unchanged'|'skipped'>}
93
+ */
94
+ export async function publishDeliveryStage({
95
+ storyId,
96
+ stage,
97
+ prNumber = null,
98
+ provider,
99
+ now = () => new Date(),
100
+ debug = (msg) => Logger.debug(msg),
101
+ }) {
102
+ try {
103
+ const resolved = typeof provider === 'function' ? provider() : provider;
104
+ if (!resolved) return 'skipped';
105
+ const existing = await findStructuredComment(
106
+ resolved,
107
+ storyId,
108
+ DELIVERY_STAGE_TYPE,
109
+ );
110
+ const previous = parseDeliveryStage(existing?.body);
111
+ if (previous?.stage === stage) return 'unchanged';
112
+ const updatedAt = now().toISOString();
113
+ const body = formatDeliveryStageBody({
114
+ storyId,
115
+ stage,
116
+ prNumber: Number.isInteger(prNumber) && prNumber > 0 ? prNumber : null,
117
+ updatedAt,
118
+ history: [...priorHistory(previous), { stage, at: updatedAt }].slice(
119
+ -HISTORY_LIMIT,
120
+ ),
121
+ });
122
+ await upsertStructuredComment(resolved, storyId, DELIVERY_STAGE_TYPE, body);
123
+ return 'published';
124
+ } catch (err) {
125
+ debug(
126
+ `[story-stage] ${stage} not published for Story #${storyId}: ${err?.message ?? err}`,
127
+ );
128
+ return 'skipped';
129
+ }
130
+ }
131
+
132
+ /**
133
+ * A pipeline phase `(ctx, deps)` that publishes `stage` and never ends the run.
134
+ *
135
+ * @param {string} stage
136
+ * @returns {(ctx: { storyId: number }, deps: { provider: object }) => Promise<null>}
137
+ */
138
+ export function publishStagePhase(stage) {
139
+ return async (ctx, deps) => {
140
+ await publishDeliveryStage({
141
+ provider: deps.provider,
142
+ storyId: ctx.storyId,
143
+ stage,
144
+ });
145
+ return null;
146
+ };
147
+ }
@@ -65,6 +65,8 @@ export const STRUCTURED_COMMENT_TYPES = Object.freeze([
65
65
  'plan-rewrite',
66
66
  // Opt-in per-Story close outcome record, upserted on every close attempt.
67
67
  'story-outcome',
68
+ // The delivery stage a Story has reached, upserted on each stage entry.
69
+ 'delivery-stage',
68
70
  ]);
69
71
 
70
72
  export const WAVE_TYPE_PATTERN = WAVE_MARKER_RE;