mandrel 2.102.0 → 2.104.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 (34) hide show
  1. package/.agents/agents/acceptance-critic.md +2 -0
  2. package/.agents/agents/auditor.md +2 -0
  3. package/.agents/agents/plan-critic.md +2 -0
  4. package/.agents/agents/story-worker.md +2 -0
  5. package/.agents/audit-checklists/quality.md +8 -0
  6. package/.agents/docs/configuration.md +1 -1
  7. package/.agents/docs/execution-reference.md +35 -0
  8. package/.agents/instructions.md +4 -2
  9. package/.agents/rules/testing-standards.md +7 -1
  10. package/.agents/schemas/agentrc.schema.json +1 -1
  11. package/.agents/scripts/lib/close-validation/test-delta.js +8 -2
  12. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  13. package/.agents/scripts/lib/coverage-capture-affected.js +3 -2
  14. package/.agents/scripts/lib/coverage-capture-delta.js +101 -34
  15. package/.agents/scripts/lib/coverage-capture.js +14 -7
  16. package/.agents/scripts/lib/orchestration/code-review.js +24 -10
  17. package/.agents/scripts/lib/orchestration/evidence-stream.js +16 -7
  18. package/.agents/scripts/lib/orchestration/review-deposit.js +24 -7
  19. package/.agents/scripts/lib/orchestration/review-providers/claim-grounding.js +183 -0
  20. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +2 -0
  21. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +6 -1
  22. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +11 -1
  23. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +4 -1
  24. package/.agents/scripts/lib/orchestration/review-providers/generated-diff.js +7 -3
  25. package/.agents/scripts/lib/orchestration/review-providers/parse-findings.js +7 -0
  26. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +7 -20
  27. package/.agents/scripts/lib/orchestration/review-providers/types.js +9 -0
  28. package/.agents/scripts/lib/orchestration/story-handoff.js +77 -18
  29. package/.agents/workflows/audit-quality.md +73 -1
  30. package/.agents/workflows/helpers/code-review.md +8 -0
  31. package/.agents/workflows/helpers/deliver-digest.md +8 -8
  32. package/.agents/workflows/helpers/deliver-reference.md +21 -14
  33. package/docs/CHANGELOG.md +21 -0
  34. package/package.json +1 -1
@@ -0,0 +1,183 @@
1
+ /**
2
+ * review-providers/claim-grounding.js — checks a critical finding's
3
+ * structured `claim` against the reviewed head before it can halt. A
4
+ * refuted claim downgrades the finding to a suggestion; a confirmed claim,
5
+ * a git error or no claim leaves it unchanged. Prose is never parsed.
6
+ *
7
+ * @typedef {import('./types.js').Finding} Finding
8
+ * @typedef {import('./types.js').FindingClaim} FindingClaim
9
+ */
10
+
11
+ import { gitSpawn } from '../../git-utils.js';
12
+ import { isObject } from '../../json-utils.js';
13
+
14
+ const TRUNCATED_CONTEXT = 'reviewed-with-truncated-context';
15
+ const CLAIM_KINDS = ['path-absent', 'symbol-referenced'];
16
+
17
+ /** The optional `claim` property of the Claude findings schema. */
18
+ export const CLAIM_SCHEMA = {
19
+ type: 'object',
20
+ properties: {
21
+ kind: { enum: CLAIM_KINDS },
22
+ path: { type: 'string' },
23
+ symbol: { type: 'string' },
24
+ },
25
+ required: ['kind'],
26
+ };
27
+
28
+ /** Codex strict output: every property required, absence as `null`. */
29
+ export const STRICT_CLAIM_SCHEMA = {
30
+ type: ['object', 'null'],
31
+ additionalProperties: false,
32
+ required: ['kind', 'path', 'symbol'],
33
+ properties: {
34
+ kind: { type: 'string', enum: CLAIM_KINDS },
35
+ path: { type: ['string', 'null'] },
36
+ symbol: { type: ['string', 'null'] },
37
+ },
38
+ };
39
+
40
+ const nonBlank = (value) =>
41
+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
42
+
43
+ /**
44
+ * A claim is kept only when its `kind` is known and carries the field that
45
+ * kind is checked by; anything else is dropped, never grounded.
46
+ *
47
+ * @param {unknown} raw
48
+ * @returns {FindingClaim | null}
49
+ */
50
+ export function buildClaim(raw) {
51
+ if (!isObject(raw)) return null;
52
+ const path = nonBlank(raw.path);
53
+ const symbol = nonBlank(raw.symbol);
54
+ if (raw.kind === 'path-absent' && path) return { kind: raw.kind, path };
55
+ if (raw.kind !== 'symbol-referenced' || !symbol) return null;
56
+ return path ? { kind: raw.kind, symbol, path } : { kind: raw.kind, symbol };
57
+ }
58
+
59
+ /**
60
+ * Report lines saying why a finding did not block, or was reviewed blind.
61
+ *
62
+ * @param {Finding} finding
63
+ * @returns {string[]}
64
+ */
65
+ export function groundingNotes(finding) {
66
+ const notes = [];
67
+ if (finding.ungrounded) {
68
+ notes.push(`_Not blocking: ungrounded — ${finding.ungrounded}._`);
69
+ }
70
+ if (finding.context) notes.push(`_Context: ${finding.context}._`);
71
+ return notes;
72
+ }
73
+
74
+ /** @returns {string|null} evidence when the path exists at `headRef`. */
75
+ function refutePathAbsent(claim, headRef, git) {
76
+ const result = git('cat-file', '-e', `${headRef}:${claim.path}`);
77
+ return result?.status === 0 ? `git cat-file found ${claim.path}` : null;
78
+ }
79
+
80
+ /** `{ file, text }` of one `git grep <ref>` hit (`<ref>:<file>:<n>:<text>`). */
81
+ function parseHit(line, headRef) {
82
+ const rest = line.startsWith(`${headRef}:`)
83
+ ? line.slice(headRef.length + 1)
84
+ : line;
85
+ const match = /^(.*?):\d+:(.*)$/.exec(rest);
86
+ return match ? { file: match[1], text: match[2] } : { file: rest, text: '' };
87
+ }
88
+
89
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
90
+
91
+ /**
92
+ * Only the symbol's own declaration line in `claim.path` is discounted; any
93
+ * other hit there (a stale caller) still counts, so the check fails safe.
94
+ */
95
+ function isDeclaration(hit, claim) {
96
+ if (!claim.path || hit.file !== claim.path) return false;
97
+ const declares = new RegExp(
98
+ `\\b(?:function\\*?|class|const|let|var|def|type|interface|enum)\\s+${escapeRegExp(claim.symbol)}\\b`,
99
+ );
100
+ return declares.test(hit.text);
101
+ }
102
+
103
+ /** @returns {string|null} evidence when every hit is the declaration. */
104
+ function refuteSymbolReferenced(claim, headRef, git) {
105
+ const result = git(
106
+ 'grep',
107
+ '-n',
108
+ '-w',
109
+ '-F',
110
+ '-e',
111
+ claim.symbol,
112
+ headRef,
113
+ '--',
114
+ );
115
+ if (result?.status !== 0 && result?.status !== 1) return null;
116
+ const referenced = String(result.stdout ?? '')
117
+ .split('\n')
118
+ .filter((line) => line.length > 0)
119
+ .some((line) => !isDeclaration(parseHit(line, headRef), claim));
120
+ if (referenced) return null;
121
+ return claim.path
122
+ ? `git grep found no references outside ${claim.path}`
123
+ : 'git grep found no references';
124
+ }
125
+
126
+ const REFUTERS = {
127
+ 'path-absent': refutePathAbsent,
128
+ 'symbol-referenced': refuteSymbolReferenced,
129
+ };
130
+
131
+ /** @returns {Finding} */
132
+ function groundFinding(finding, headRef, git) {
133
+ const refute = REFUTERS[finding?.claim?.kind];
134
+ if (finding?.severity !== 'critical' || !refute) return finding;
135
+ let evidence = null;
136
+ try {
137
+ evidence = refute(finding.claim, headRef, git);
138
+ } catch {
139
+ evidence = null;
140
+ }
141
+ if (!evidence) return finding;
142
+ return { ...finding, severity: 'suggestion', ungrounded: evidence };
143
+ }
144
+
145
+ /** Names a degradation reason carries, split on its list punctuation. */
146
+ function reasonTokens(degradations) {
147
+ return new Set(
148
+ degradations.flatMap((d) => String(d.reason).split(/[\s,()]+/)),
149
+ );
150
+ }
151
+
152
+ function annotateContext(finding, tokens) {
153
+ const names = [finding.file, finding.claim?.path, finding.claim?.symbol];
154
+ if (!names.some((name) => name && tokens.has(name))) return finding;
155
+ return { ...finding, context: TRUNCATED_CONTEXT };
156
+ }
157
+
158
+ /**
159
+ * @param {{
160
+ * findings: Finding[],
161
+ * headRef: string,
162
+ * degradations?: ReadonlyArray<{ reason: string }>,
163
+ * cwd?: string,
164
+ * gitSpawnFn?: typeof gitSpawn,
165
+ * }} args
166
+ * @returns {Finding[]}
167
+ */
168
+ export function groundFindings({
169
+ findings,
170
+ headRef,
171
+ degradations = [],
172
+ cwd = process.cwd(),
173
+ gitSpawnFn = gitSpawn,
174
+ }) {
175
+ const git = (...args) => gitSpawnFn(cwd, ...args);
176
+ const tokens = reasonTokens(degradations);
177
+ return findings.map((finding) => {
178
+ const grounded = groundFinding(finding, headRef, git);
179
+ return grounded && tokens.size > 0
180
+ ? annotateContext(grounded, tokens)
181
+ : grounded;
182
+ });
183
+ }
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { isObject } from '../../json-utils.js';
9
+ import { CLAIM_SCHEMA } from './claim-grounding.js';
9
10
  import { buildFinding, unwrapEnvelope } from './parse-findings.js';
10
11
 
11
12
  export const FINDINGS_SCHEMA_JSON = JSON.stringify({
@@ -21,6 +22,7 @@ export const FINDINGS_SCHEMA_JSON = JSON.stringify({
21
22
  file: { type: 'string' },
22
23
  line: { type: 'integer' },
23
24
  category: { type: 'string' },
25
+ claim: CLAIM_SCHEMA,
24
26
  },
25
27
  required: ['title', 'body'],
26
28
  },
@@ -80,7 +80,12 @@ const PROMPT_HEAD =
80
80
  'The diff below is authoritative — files on disk may not reflect it. ' +
81
81
  'Answer with a JSON object of this exact shape, no prose around it:\n\n' +
82
82
  '{"findings":[{"title":"...","body":"Why it is wrong: ... How to show it ' +
83
- 'fails: ...","file":"...","line":1,"category":"bug"}]}\n\n' +
83
+ 'fails: ...","file":"...","line":1,"category":"bug","claim":null}]}\n\n' +
84
+ 'Set `claim` when the problem rests on a checkable fact: ' +
85
+ '{"kind":"path-absent","path":"<file>"} when a file the change needs is ' +
86
+ 'missing, or {"kind":"symbol-referenced","symbol":"<name>","path":"<its ' +
87
+ 'definition file>"} when a removed or renamed symbol still has callers. ' +
88
+ 'Otherwise leave it null.\n\n' +
84
89
  'Emit {"findings":[]} if there is nothing you would block the merge for.\n\n';
85
90
 
86
91
  /**
@@ -17,6 +17,7 @@ import { spawnCaptureAsync, spawnChild } from '../../child-exec.js';
17
17
  import { resolveAgentrcRoot } from '../../config/git-roots.js';
18
18
  import { resolvedTempRoot } from '../../config/temp-paths.js';
19
19
  import { resolveConfig } from '../../config-resolver.js';
20
+ import { STRICT_CLAIM_SCHEMA } from './claim-grounding.js';
20
21
  import { PROVIDER_SEVERITY_MAP } from './provider-severity.js';
21
22
  import { renderDepthDirective } from './review-depth.js';
22
23
 
@@ -47,7 +48,15 @@ const FINDINGS_SCHEMA = Object.freeze({
47
48
  items: {
48
49
  type: 'object',
49
50
  additionalProperties: false,
50
- required: ['severity', 'title', 'body', 'file', 'line', 'category'],
51
+ required: [
52
+ 'severity',
53
+ 'title',
54
+ 'body',
55
+ 'file',
56
+ 'line',
57
+ 'category',
58
+ 'claim',
59
+ ],
51
60
  properties: {
52
61
  severity: { type: 'string', enum: Object.keys(CODEX_SEVERITY_MAP) },
53
62
  title: { type: 'string' },
@@ -55,6 +64,7 @@ const FINDINGS_SCHEMA = Object.freeze({
55
64
  file: { type: ['string', 'null'] },
56
65
  line: { type: ['integer', 'null'] },
57
66
  category: { type: 'string' },
67
+ claim: STRICT_CLAIM_SCHEMA,
58
68
  },
59
69
  },
60
70
  },
@@ -7,6 +7,7 @@
7
7
  * @typedef {import('./types.js').Severity} Severity
8
8
  */
9
9
 
10
+ import { groundingNotes } from './claim-grounding.js';
10
11
  import {
11
12
  normalizeDegradations,
12
13
  renderDegradedGatesSection,
@@ -63,7 +64,9 @@ export function renderFinding(finding) {
63
64
  const attribution = buildAttribution(finding);
64
65
  const category = finding.category ? ` _[${finding.category}]_` : '';
65
66
  const header = `#### ${emoji} ${finding.title}${attribution}${category}`;
66
- return `${header}\n\n${finding.body}`;
67
+ return [`${header}\n\n${finding.body}`, ...groundingNotes(finding)].join(
68
+ '\n\n',
69
+ );
67
70
  }
68
71
 
69
72
  /**
@@ -2,11 +2,15 @@
2
2
 
3
3
  import { clip } from './claude-verdict.js';
4
4
 
5
- function sectionPath(section) {
5
+ export function diffSections(diff) {
6
+ return diff.split(/(?=^diff --git )/m);
7
+ }
8
+
9
+ export function sectionPath(section) {
6
10
  return /^diff --git a\/.+? b\/(.+)$/m.exec(section)?.[1] ?? null;
7
11
  }
8
12
 
9
- function generatedPaths(paths, { cwd, gitSpawnFn }) {
13
+ export function generatedPaths(paths, { cwd, gitSpawnFn }) {
10
14
  const generated = new Set();
11
15
  if (paths.length === 0) return generated;
12
16
  const result = gitSpawnFn(
@@ -29,7 +33,7 @@ function generatedPaths(paths, { cwd, gitSpawnFn }) {
29
33
 
30
34
  /** A failed attribute lookup leaves the diff whole. */
31
35
  function omitGeneratedFiles(diff, deps) {
32
- const sections = diff.split(/(?=^diff --git )/m);
36
+ const sections = diffSections(diff);
33
37
  const generated = generatedPaths(
34
38
  sections.map(sectionPath).filter(Boolean),
35
39
  deps,
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { isObject } from '../../json-utils.js';
11
+ import { buildClaim } from './claim-grounding.js';
11
12
 
12
13
  /**
13
14
  * Unwrap a bare array, `{ findings }`, or either under `result`/`data`.
@@ -69,13 +70,19 @@ export function buildFinding(entry, { mapSeverity, defaultCategory }) {
69
70
  ? entry.category
70
71
  : defaultCategory;
71
72
  if (category !== undefined) finding.category = category;
73
+ return attachLocation(finding, entry);
74
+ }
72
75
 
76
+ /** Well-formed `file`, `line` and `claim` only. */
77
+ function attachLocation(finding, entry) {
73
78
  if (typeof entry.file === 'string' && entry.file.length > 0) {
74
79
  finding.file = entry.file;
75
80
  }
76
81
  if (Number.isInteger(entry.line) && entry.line > 0) {
77
82
  finding.line = entry.line;
78
83
  }
84
+ const claim = buildClaim(entry.claim);
85
+ if (claim) finding.claim = claim;
79
86
  return finding;
80
87
  }
81
88
 
@@ -198,31 +198,28 @@ export function buildProviderChain(entries, ctx) {
198
198
  }
199
199
 
200
200
  /**
201
- * @param {Record<string, number>} tally
202
- * @param {string} name
203
201
  * @param {Finding[]} findings
202
+ * @param {string} name
203
+ * @returns {Finding[]}
204
204
  */
205
- function recordCritical(tally, name, findings) {
206
- const critical = findings.filter((f) => f?.severity === 'critical').length;
207
- if (critical > 0) tally[name] = critical;
205
+ function stampProvider(findings, name) {
206
+ return findings.map((f) => ({ ...f, provider: name }));
208
207
  }
209
208
 
210
209
  /**
211
- * Inline findings merge in declaration order; prompt entries render via
210
+ * Inline findings merge in declaration order, each stamped with its entry's
211
+ * `provider` name for attribution; prompt entries render via
212
212
  * `getPromptMessages`.
213
213
  *
214
214
  * @param {ProviderChain} chain
215
215
  * @param {{ logger?: { info?: Function, warn?: Function } }} [opts]
216
216
  * @returns {ReviewProvider & {
217
217
  * getPromptMessages: (input: ReviewInput) => Promise<string[]>,
218
- * getCriticalByProvider: () => Record<string, number>,
219
218
  * chain: ProviderChain,
220
219
  * }}
221
220
  */
222
221
  export function createChainProvider(chain, opts = {}) {
223
222
  const logger = opts.logger;
224
- /** Critical findings per entry from the last `runReview`, for attribution. */
225
- let criticalByProvider = {};
226
223
 
227
224
  return {
228
225
  chain,
@@ -233,7 +230,6 @@ export function createChainProvider(chain, opts = {}) {
233
230
  async runReview(input) {
234
231
  /** @type {Finding[]} */
235
232
  const merged = [];
236
- criticalByProvider = {};
237
233
  const ctx = {
238
234
  scope: input?.scope,
239
235
  labels: /** @type {ReadonlyArray<string>} */ (
@@ -253,19 +249,10 @@ export function createChainProvider(chain, opts = {}) {
253
249
  `[code-review] Inline provider "${entry.name}" returned a non-array; expected Finding[].`,
254
250
  );
255
251
  }
256
- for (const f of findings) merged.push(f);
257
- recordCritical(criticalByProvider, entry.name, findings);
252
+ merged.push(...stampProvider(findings, entry.name));
258
253
  }
259
254
  return merged;
260
255
  },
261
- /**
262
- * Which entries raised the last run's critical findings, and how many.
263
- *
264
- * @returns {Record<string, number>}
265
- */
266
- getCriticalByProvider() {
267
- return { ...criticalByProvider };
268
- },
269
256
  /**
270
257
  * Called after `runReview`.
271
258
  *
@@ -11,6 +11,15 @@
11
11
  * @property {string=} file - Relative path, when attributable.
12
12
  * @property {number=} line - 1-based, when attributable.
13
13
  * @property {string=} category - e.g. 'security', 'lint'.
14
+ * @property {FindingClaim=} claim - Structured, checkable claim.
15
+ * @property {string=} ungrounded - Why a refuted critical was downgraded.
16
+ * @property {string=} context - 'reviewed-with-truncated-context'.
17
+ * @property {string=} provider - Chain entry that raised it.
18
+ *
19
+ * @typedef {object} FindingClaim
20
+ * @property {'path-absent'|'symbol-referenced'} kind
21
+ * @property {string=} path - Absent path, or the symbol's definition file.
22
+ * @property {string=} symbol
14
23
  *
15
24
  * @typedef {'story'} ReviewScope
16
25
  *
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * story-handoff.js — the story-worker's whole post-implementation tail as one
3
3
  * deterministic sequence: blocking preflight (lint, quality-preview, baselined
4
- * ratchets) → base merge → the one credited run → baseline seating → push +
5
- * remote-ref check → held review. It runs
4
+ * ratchets) → base merge → the one credited run with the held review beside
5
+ * it → baseline seating → push + remote-ref check → review awaited. It runs
6
6
  * exactly what deliver-digest § 5 and deliver-reference § Held review define,
7
7
  * changing nothing close credits or adopts, and settles one envelope:
8
8
  *
@@ -131,7 +131,7 @@ const SEAT_SCRIPTS = Object.freeze({
131
131
  /**
132
132
  * A settled step. `stop` carries the envelope status that ends the run.
133
133
  *
134
- * @typedef {{ name: string, outcome: 'ran'|'skipped'|'failed'|'error',
134
+ * @typedef {{ name: string, outcome: 'ran'|'skipped'|'failed'|'error'|'aborted',
135
135
  * detail: string, evidencePath?: string|null, conflictFiles?: string[],
136
136
  * stop?: 'fix-required'|'blocked', reason?: string }} StepResult
137
137
  */
@@ -203,9 +203,10 @@ function worktreeEnv(ctx, env) {
203
203
  * @param {string} cmd
204
204
  * @param {string[]} args
205
205
  * @param {Record<string, string|undefined>} [env] the child's whole env.
206
+ * @param {AbortSignal} [signal]
206
207
  * @returns {Promise<{ status: number, output: string, evidencePath: string }>}
207
208
  */
208
- async function runLogged(ctx, logName, cmd, args, env) {
209
+ async function runLogged(ctx, logName, cmd, args, env, signal) {
209
210
  ctx.progress(logName, `${cmd} ${args.join(' ')}`);
210
211
  const file = ctx.evidencePathFor(logName);
211
212
  ctx.storyProgress.evidence(file);
@@ -218,6 +219,7 @@ async function runLogged(ctx, logName, cmd, args, env) {
218
219
  opts: { cwd: ctx.cwd, env: worktreeEnv(ctx, env) },
219
220
  file,
220
221
  tag: logName,
222
+ signal,
221
223
  });
222
224
  }
223
225
 
@@ -462,8 +464,8 @@ function testGateArgv(config) {
462
464
  return [cmd, ...args];
463
465
  }
464
466
 
465
- /** @param {object} ctx @returns {Promise<StepResult>} */
466
- async function stepCreditedRun(ctx) {
467
+ /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
468
+ async function creditedRun(ctx, signal) {
467
469
  const name = 'credited-run';
468
470
  if (ctx.state.creditHead === ctx.head) {
469
471
  return skipped(
@@ -489,7 +491,7 @@ async function stepCreditedRun(ctx) {
489
491
  ...testGateArgv(ctx.config),
490
492
  ];
491
493
  const { result: run, timings } = await withLockProgress(ctx, (env) =>
492
- runLogged(ctx, 'credited-run', 'node', args, env),
494
+ runLogged(ctx, 'credited-run', 'node', args, env, signal),
493
495
  );
494
496
  const { lockWait, suiteTimings, spawns } = timings;
495
497
  const extra = {
@@ -498,6 +500,14 @@ async function stepCreditedRun(ctx) {
498
500
  lockWait,
499
501
  suiteTimings,
500
502
  };
503
+ if (signal.aborted) {
504
+ return {
505
+ name,
506
+ outcome: 'aborted',
507
+ detail: 'aborted: the held review found a CRITICAL mid-run; no credit',
508
+ ...extra,
509
+ };
510
+ }
501
511
  if (run.status !== 0) {
502
512
  return fixRequired(name, describeSuiteFailure(run.status), extra);
503
513
  }
@@ -747,7 +757,7 @@ function reviewVerdict(deposit, depositPath, settled) {
747
757
  }
748
758
 
749
759
  /** @param {object} ctx @returns {Promise<StepResult>} */
750
- async function stepReview(ctx) {
760
+ async function computeHeldReview(ctx) {
751
761
  const name = 'review';
752
762
  const held = ctx.probeReview({
753
763
  cwd: ctx.cwd,
@@ -796,6 +806,38 @@ async function stepReview(ctx) {
796
806
  );
797
807
  }
798
808
 
809
+ /** Pinned to the head it resolves now; never rejects. */
810
+ function startReview(ctx) {
811
+ const startedAt = ctx.now();
812
+ ctx.reviewPending = computeHeldReview(ctx)
813
+ .catch((err) => ({
814
+ name: 'review',
815
+ outcome: 'error',
816
+ detail: `held review failed (${err?.message ?? err}); close computes the review itself`,
817
+ }))
818
+ .finally(() => {
819
+ ctx.reviewMs = ctx.now() - startedAt;
820
+ });
821
+ return ctx.reviewPending;
822
+ }
823
+
824
+ /** A review that halts mid-run aborts the run. */
825
+ async function stepCreditedRun(ctx) {
826
+ const abort = new AbortController();
827
+ let halted = null;
828
+ startReview(ctx).then((result) => {
829
+ if (!result.stop) return;
830
+ halted = result;
831
+ abort.abort();
832
+ });
833
+ const run = await creditedRun(ctx, abort.signal);
834
+ return run.outcome === 'aborted' ? [run, halted] : run;
835
+ }
836
+
837
+ function stepReview(ctx) {
838
+ return ctx.reviewPending;
839
+ }
840
+
799
841
  /**
800
842
  * The run's step order. On the evidence-gate path the `test` credit is keyed
801
843
  * on the tree, so seating (static MI) goes first and cannot void it; the
@@ -813,6 +855,25 @@ function stepOrder(depositor) {
813
855
  return [stepPreflight, stepBaseMerge, ...middle, stepPush, stepReview];
814
856
  }
815
857
 
858
+ /**
859
+ * Run the steps in order into `steps`; a step may settle several results.
860
+ *
861
+ * @returns {Promise<StepResult|null>} the result that stopped the run.
862
+ */
863
+ async function runSteps(ctx, steps) {
864
+ for (const step of stepOrder(ctx.depositor)) {
865
+ ctx.storyProgress.phase(handoffStepName(step));
866
+ const results = [await step(ctx)].flat();
867
+ for (const result of results) {
868
+ steps.push(result);
869
+ ctx.progress(result.name, `${result.outcome} — ${result.detail}`);
870
+ }
871
+ const stop = results.find((r) => r.stop);
872
+ if (stop) return stop;
873
+ }
874
+ return null;
875
+ }
876
+
816
877
  /**
817
878
  * Refusals before any step: the handoff runs on the Story branch with the
818
879
  * implementation committed.
@@ -922,6 +983,7 @@ async function defaultBlock({
922
983
  * signalTarget?: import('node:events').EventEmitter,
923
984
  * reraise?: (signal: string) => void,
924
985
  * evidenceFs?: typeof fs,
986
+ * now?: () => number,
925
987
  * }} deps `runCommand` receives `onChunk`, `signal` and (when set)
926
988
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
927
989
  * still gets its whole output written at settle.
@@ -948,6 +1010,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
948
1010
  signalTarget,
949
1011
  reraise,
950
1012
  evidenceFs,
1013
+ now = Date.now,
951
1014
  } = deps;
952
1015
  const block =
953
1016
  deps.block ??
@@ -983,8 +1046,11 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
983
1046
  sleep,
984
1047
  lockPollMs,
985
1048
  env,
1049
+ now,
986
1050
  state: readState(statePath, progress),
987
1051
  review: null,
1052
+ reviewPending: null,
1053
+ reviewMs: null,
988
1054
  reviewPath: storyReviewDepositPath(storyId, config),
989
1055
  depositor: selectCreditedDepositor({
990
1056
  config,
@@ -1013,16 +1079,8 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1013
1079
  const steps = [];
1014
1080
  let stop = precheck(ctx);
1015
1081
  if (stop) steps.push(stop);
1016
- for (const step of stop ? [] : stepOrder(ctx.depositor)) {
1017
- storyProgress.phase(handoffStepName(step));
1018
- const result = await step(ctx);
1019
- steps.push(result);
1020
- progress(result.name, `${result.outcome} — ${result.detail}`);
1021
- if (result.stop) {
1022
- stop = result;
1023
- break;
1024
- }
1025
- }
1082
+ else stop = await runSteps(ctx, steps);
1083
+ await ctx.reviewPending;
1026
1084
 
1027
1085
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1028
1086
  const credited = steps.find((s) => s.name === 'credited-run');
@@ -1040,6 +1098,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1040
1098
  review: ctx.review,
1041
1099
  lockWait: credited?.lockWait ?? null,
1042
1100
  suiteTimings: credited?.suiteTimings ?? null,
1101
+ reviewMs: ctx.reviewMs,
1043
1102
  ...(stop
1044
1103
  ? {
1045
1104
  failedStep: stop.name,