mandrel 2.117.0 → 2.119.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 (38) hide show
  1. package/.agents/docs/agentrc-reference.json +2 -1
  2. package/.agents/docs/configuration.md +14 -5
  3. package/.agents/schemas/agentrc.schema.json +25 -2
  4. package/.agents/schemas/story-deliver-terminal.schema.json +15 -1
  5. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +2 -6
  6. package/.agents/scripts/lib/baselines/crap-preview-coverage.js +17 -0
  7. package/.agents/scripts/lib/baselines/crap-preview-scan.js +11 -6
  8. package/.agents/scripts/lib/baselines/preview-gates.js +2 -0
  9. package/.agents/scripts/lib/baselines/refresh-service.js +23 -12
  10. package/.agents/scripts/lib/baselines/seat-missing.js +2 -9
  11. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +152 -0
  12. package/.agents/scripts/lib/close-validation/ci-deferral.js +23 -5
  13. package/.agents/scripts/lib/close-validation/gates.js +8 -2
  14. package/.agents/scripts/lib/close-validation/runner.js +8 -10
  15. package/.agents/scripts/lib/config-settings-schema-delivery.js +22 -2
  16. package/.agents/scripts/lib/coverage-baseline.js +20 -9
  17. package/.agents/scripts/lib/coverage-deferral.js +17 -0
  18. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  19. package/.agents/scripts/lib/observability/story-outcome.js +5 -4
  20. package/.agents/scripts/lib/orchestration/handoff-rescore.js +95 -25
  21. package/.agents/scripts/lib/orchestration/merge-block-class.js +12 -1
  22. package/.agents/scripts/lib/orchestration/merge-poll.js +9 -0
  23. package/.agents/scripts/lib/orchestration/merge-queue.js +14 -7
  24. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +2 -25
  25. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +8 -1
  26. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +26 -7
  27. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +50 -8
  28. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +3 -2
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +9 -3
  30. package/.agents/scripts/lib/orchestration/single-story-close/result.js +9 -6
  31. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +1 -0
  32. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +158 -71
  33. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +4 -0
  34. package/.agents/scripts/lib/orchestration/story-handoff.js +100 -25
  35. package/.agents/scripts/quality-preview.js +57 -8
  36. package/.agents/workflows/helpers/deliver-reference.md +10 -1
  37. package/docs/CHANGELOG.md +17 -0
  38. package/package.json +1 -1
@@ -21,6 +21,7 @@ import {
21
21
  fileFilterFor,
22
22
  readPriorEnvelope,
23
23
  } from '../../baselines/refresh-service.js';
24
+ import { writeFile as writeEnvelopeFile } from '../../baselines/writer.js';
24
25
  import { getBaselineEpsilon } from '../../config/quality.js';
25
26
  import { getQuality } from '../../config-resolver.js';
26
27
  import { Logger as DefaultLogger } from '../../Logger.js';
@@ -135,27 +136,24 @@ function resolveScopeRefs({ workTree, git, baseBranch, baselineRef }) {
135
136
  }
136
137
 
137
138
  /**
138
- * Guards plus the scoped file list and the paths whose rows stay untouched. A
139
- * dirty baseline file would otherwise be swept into the commit.
139
+ * The scanned HEAD, the scoped file list and the paths whose rows stay
140
+ * untouched. Read-only ref queries only: never `git status`.
140
141
  *
141
- * @param {{ workTree: string, baseBranch: string, storyBranch: string, git: Function, relPath: string, additionalFormats?: string[], baselineRef?: string }} ctx
142
- * @returns {{ reason: string } | { files: string[], exclude: string[] }}
142
+ * @param {{ workTree: string, baseBranch: string, storyBranch: string, git: Function, additionalFormats?: string[], baselineRef?: string }} ctx
143
+ * @returns {{ reason: string } | { head: string, files: string[], exclude: string[] }}
143
144
  */
144
145
  function resolveScope({
145
146
  workTree,
146
147
  baseBranch,
147
148
  storyBranch,
148
149
  git,
149
- relPath,
150
150
  additionalFormats,
151
151
  baselineRef,
152
152
  }) {
153
153
  if (currentBranch(workTree, git) !== storyBranch) {
154
154
  return { reason: 'wrong-branch' };
155
155
  }
156
- if (listDirtyPaths(workTree, git).includes(relPath)) {
157
- return { reason: 'dirty-tree' };
158
- }
156
+ const head = readHead(workTree, git);
159
157
  const { diffBase, exclude } = resolveScopeRefs({
160
158
  workTree,
161
159
  git,
@@ -171,7 +169,31 @@ function resolveScope({
171
169
  }).filter((f) => isScorable(f));
172
170
  return files.length === 0
173
171
  ? { reason: 'no-changed-files' }
174
- : { files, exclude };
172
+ : { head, files, exclude };
173
+ }
174
+
175
+ function readHead(workTree, git) {
176
+ return String(git(['rev-parse', 'HEAD'], { cwd: workTree }) ?? '').trim();
177
+ }
178
+
179
+ /**
180
+ * Why the scanned rows may not be committed now: HEAD moved since the scan,
181
+ * the branch changed, or a dirty baseline would be swept into the commit.
182
+ *
183
+ * @returns {Promise<string|null>}
184
+ */
185
+ async function applyRefusal({ relPath, head }, opts) {
186
+ const { workTree, git } = gitFor(opts);
187
+ const refusal = await attempt(() => {
188
+ if (readHead(workTree, git) !== head) return 'head-moved';
189
+ if (currentBranch(workTree, git) !== opts.storyBranch) {
190
+ return 'wrong-branch';
191
+ }
192
+ return listDirtyPaths(workTree, git).includes(relPath)
193
+ ? 'dirty-tree'
194
+ : null;
195
+ }, 'git-failed');
196
+ return refusal.reason ?? refusal.value;
175
197
  }
176
198
 
177
199
  /**
@@ -230,7 +252,7 @@ async function attempt(fn, label) {
230
252
  }
231
253
 
232
254
  /**
233
- * @param {{
255
+ * @typedef {{
234
256
  * cwd: string,
235
257
  * worktreePath?: string|null,
236
258
  * storyId: number|string,
@@ -242,84 +264,137 @@ async function attempt(fn, label) {
242
264
  * gitSync?: (cwd: string, ...args: string[]) => string,
243
265
  * refreshBaseline?: typeof defaultRefreshBaseline,
244
266
  * scorer?: (files: string[], opts: object) => Promise<object[]>|object[],
245
- * }} opts
246
- * @returns {Promise<{ ran: boolean, committed: boolean, sha?: string, movedPaths?: string[], reason?: string, moved?: Array<{ path: string, before: number|null, after: number|null }>, partners?: Record<string, string[]> }>}
247
- * `moved` and `partners` (write-scope clone partners) whenever a scan completed.
267
+ * }} RescoreOptions
248
268
  */
249
- export async function runDuplicationCloseRescore({
250
- cwd,
251
- worktreePath,
252
- storyId,
253
- baseBranch,
254
- storyBranch,
255
- baselineRef,
256
- config,
257
- logger = DefaultLogger,
258
- gitSync = defaultGitSync,
259
- refreshBaseline = defaultRefreshBaseline,
260
- scorer,
261
- } = {}) {
262
- if (!cwd || !baseBranch || !storyBranch) {
263
- return skip(logger, 'missing-context');
264
- }
269
+
270
+ /** @param {RescoreOptions} opts */
271
+ function gitFor({ cwd, worktreePath, gitSync = defaultGitSync }) {
265
272
  const workTree = worktreePath || cwd;
266
- const git = (args, opts = {}) => gitSync(opts.cwd ?? workTree, ...args);
273
+ return {
274
+ workTree,
275
+ git: (args, opts = {}) => gitSync(opts.cwd ?? workTree, ...args),
276
+ };
277
+ }
267
278
 
268
- // The DECLARED `gates.duplication` block — `quality.duplication` is undefined.
269
- const gate = await attempt(
270
- () => getQuality(config)?.gates?.[KIND] ?? {},
271
- 'config-failed',
272
- );
279
+ /**
280
+ * Score the tree and diff the scoped rows at the recorded HEAD, writing
281
+ * nothing and committing nothing.
282
+ *
283
+ * @param {RescoreOptions} opts
284
+ * @returns {Promise<object>} a named skip (`reason`), or the scan:
285
+ * `{ head, relPath, writePath, envelope, wrote, changed, moved, partners }`.
286
+ */
287
+ export async function scanDuplicationRescore(opts = {}) {
288
+ const { logger = DefaultLogger } = opts;
289
+ if (!opts.cwd || !opts.baseBranch || !opts.storyBranch) {
290
+ return skip(logger, 'missing-context');
291
+ }
292
+ const { workTree, git } = gitFor(opts);
293
+ const gate = await resolveGate(opts.config);
273
294
  if (gate.reason) return skip(logger, gate.reason);
274
- if (gate.value.enabled === false) return skip(logger, 'gate-disabled');
275
-
276
- const relPath = gate.value.baselinePath ?? DEFAULT_BASELINE_REL_PATH;
277
- const writePath = path.resolve(workTree, relPath);
295
+ const { additionalFormats, baselinePath } = gate.value;
278
296
  const scope = await attempt(
279
- () =>
280
- resolveScope({
281
- workTree,
282
- baseBranch,
283
- storyBranch,
284
- git,
285
- relPath,
286
- additionalFormats: gate.value.additionalFormats,
287
- baselineRef,
288
- }),
297
+ () => resolveScope({ ...opts, workTree, git, additionalFormats }),
289
298
  'git-failed',
290
299
  );
291
- if (scope.reason) return skip(logger, scope.reason);
292
- if (scope.value.reason) return skip(logger, scope.value.reason);
293
- const { files, exclude } = scope.value;
294
-
300
+ const reason = scope.reason ?? scope.value.reason;
301
+ if (reason) return skip(logger, reason);
302
+ const relPath = baselinePath ?? DEFAULT_BASELINE_REL_PATH;
303
+ const writePath = path.resolve(workTree, relPath);
295
304
  const priorRows = readPriorEnvelope(writePath, fs)?.rows ?? [];
296
305
  const refreshed = await attempt(
297
- () =>
298
- refreshBaseline({
299
- kind: KIND,
300
- cwd: workTree,
301
- writePath,
302
- scopeFiles: files,
303
- excludeWriteFiles: exclude,
304
- epsilon: getBaselineEpsilon(KIND),
305
- ...(scorer ? { scorer } : {}),
306
- }),
306
+ () => refreshScope({ ...opts, ...scope.value, workTree, writePath }),
307
307
  'scorer-failed',
308
308
  );
309
309
  if (refreshed.reason) return skip(logger, refreshed.reason);
310
- const { partners = {} } = refreshed.value;
311
- if (!refreshed.value.wrote) return unchanged(logger, partners);
312
-
313
- const moved = diffScopedRows({
314
- files: refreshed.value.scope?.files ?? files,
310
+ const { head, files } = scope.value;
311
+ return scanResult(refreshed.value, {
312
+ head,
313
+ files,
315
314
  priorRows,
316
- nextRows: refreshed.value.envelope?.rows,
315
+ relPath,
316
+ writePath,
317
+ });
318
+ }
319
+
320
+ /** The DECLARED `gates.duplication` block — `quality.duplication` is undefined. */
321
+ async function resolveGate(config) {
322
+ const gate = await attempt(
323
+ () => getQuality(config)?.gates?.[KIND] ?? {},
324
+ 'config-failed',
325
+ );
326
+ if (gate.value?.enabled === false) return { reason: 'gate-disabled' };
327
+ return gate;
328
+ }
329
+
330
+ /** Score the scoped files without writing the baseline. */
331
+ function refreshScope({
332
+ refreshBaseline = defaultRefreshBaseline,
333
+ scorer,
334
+ workTree,
335
+ writePath,
336
+ files,
337
+ exclude,
338
+ }) {
339
+ return refreshBaseline({
340
+ kind: KIND,
341
+ cwd: workTree,
342
+ writePath,
343
+ scopeFiles: files,
344
+ excludeWriteFiles: exclude,
345
+ epsilon: getBaselineEpsilon(KIND),
346
+ write: false,
347
+ ...(scorer ? { scorer } : {}),
317
348
  });
349
+ }
350
+
351
+ /** A completed scan: the envelope to write and the scoped rows that moved. */
352
+ function scanResult(refreshed, { files, priorRows, ...rest }) {
353
+ const { partners = {}, envelope, wrote = false } = refreshed;
354
+ const changed = refreshed.changed ?? wrote;
355
+ const moved = changed
356
+ ? diffScopedRows({
357
+ files: refreshed.scope?.files ?? files,
358
+ priorRows,
359
+ nextRows: envelope?.rows,
360
+ })
361
+ : [];
362
+ return { ...rest, envelope, wrote, changed, moved, partners };
363
+ }
364
+
365
+ /**
366
+ * Write a scan's envelope and commit it untagged; a scan skip passes through.
367
+ * Refused (named skip, nothing written) once HEAD, the branch or the
368
+ * baseline file moved since the scan.
369
+ *
370
+ * @param {object} scan {@link scanDuplicationRescore}'s result.
371
+ * @param {RescoreOptions} opts
372
+ * @returns {Promise<{ ran: boolean, committed: boolean, sha?: string, movedPaths?: string[], reason?: string, moved?: Array<{ path: string, before: number|null, after: number|null }>, partners?: Record<string, string[]> }>}
373
+ */
374
+ export async function applyDuplicationRescore(scan, opts = {}) {
375
+ if (scan?.reason) return scan;
376
+ const { logger = DefaultLogger } = opts;
377
+ const refused = await applyRefusal(scan, opts);
378
+ if (refused) return skip(logger, refused);
379
+ if (!scan.changed) return unchanged(logger, scan.partners);
380
+ // A refresh that ignored `write: false` already wrote the file.
381
+ const written = scan.wrote
382
+ ? {}
383
+ : await attempt(
384
+ () => writeEnvelopeFile(scan.writePath, scan.envelope),
385
+ 'write-failed',
386
+ );
387
+ if (written.reason) return skip(logger, written.reason);
388
+ return commitScan(scan, opts);
389
+ }
390
+
391
+ /** Commit a written scan untagged; a refused commit is a named skip. */
392
+ async function commitScan({ relPath, moved, partners }, opts) {
393
+ const { storyId, logger = DefaultLogger } = opts;
318
394
  const committed = await attempt(
319
395
  () =>
320
396
  commitBaseline({
321
- workTree,
322
- git,
397
+ ...gitFor(opts),
323
398
  relPath,
324
399
  subject: buildCommitSubject(storyId),
325
400
  body: buildCommitBody(moved),
@@ -332,3 +407,15 @@ export async function runDuplicationCloseRescore({
332
407
  );
333
408
  return committedResult(committed.value, moved, partners);
334
409
  }
410
+
411
+ /**
412
+ * Close's re-score: {@link scanDuplicationRescore} then
413
+ * {@link applyDuplicationRescore}.
414
+ *
415
+ * @param {RescoreOptions} opts
416
+ * @returns {Promise<object>} `moved` and `partners` (write-scope clone
417
+ * partners) whenever a scan completed.
418
+ */
419
+ export async function runDuplicationCloseRescore(opts = {}) {
420
+ return applyDuplicationRescore(await scanDuplicationRescore(opts), opts);
421
+ }
@@ -121,6 +121,8 @@ function compact(obj) {
121
121
  * @param {{ mode: string, outcome: string, reason: string, incoming: number }|null} [args.baseSync]
122
122
  * Close's base-sync decision; `null` when no sync ran, absent when not passed.
123
123
  * @param {'pushed'|'skipped-already-at-head'|null} [args.pushOutcome]
124
+ * @param {{ mode: 'ci', applied: 'full'|'deferred-to-ci', reason: string, detail?: string, deferredGates: string[], ciChecks: string[] }} [args.revalidation]
125
+ * Close's post-merge revalidation; absent unless `revalidateAfterBaseSync` is `ci`.
124
126
  * @param {string} [args.timestamp]
125
127
  * @param {{ schema: object|null, error: string|null }} [args.schemaSource]
126
128
  * Test seam.
@@ -146,6 +148,7 @@ export function buildTerminalEnvelope({
146
148
  phaseDurations,
147
149
  baseSync,
148
150
  pushOutcome,
151
+ revalidation,
149
152
  timestamp = new Date().toISOString(),
150
153
  schemaSource,
151
154
  }) {
@@ -171,6 +174,7 @@ export function buildTerminalEnvelope({
171
174
  phaseDurations,
172
175
  baseSync,
173
176
  pushOutcome,
177
+ revalidation,
174
178
  timestamp,
175
179
  });
176
180
 
@@ -91,14 +91,20 @@ import {
91
91
  settleOverBudget,
92
92
  } from './handoff-gates.js';
93
93
  import {
94
+ joinDuplicationScan,
94
95
  raisedDuplicationSuffix,
95
96
  rescoreDuplication,
97
+ startDuplicationScan,
96
98
  } from './handoff-rescore.js';
97
99
  import { handoffStatePath } from './handoff-state.js';
98
100
  import { settleSuiteOfRecord } from './handoff-suite-of-record.js';
99
101
  import { requestedLanes, runPreflightLanes } from './preflight-lanes.js';
100
102
  import { probeHeldReviewDiff } from './review-deposit.js';
101
- import { runDuplicationCloseRescore } from './story-close/duplication-close-rescore.js';
103
+ import {
104
+ applyDuplicationRescore,
105
+ runDuplicationCloseRescore,
106
+ scanDuplicationRescore,
107
+ } from './story-close/duplication-close-rescore.js';
102
108
  import { createStoryProgress, handoffStepName } from './story-progress.js';
103
109
  import {
104
110
  STATE_LABELS,
@@ -412,13 +418,15 @@ function preflightFinding(check, run) {
412
418
  * Runs every check — serially, or over admitted lanes when
413
419
  * `preflightConcurrency` asks (preflight-lanes.js) — then settles one
414
420
  * `fix-required` listing each finding in check order; a passed carryable
415
- * check keeps its credit either way.
421
+ * check keeps its credit either way. With the re-score overlapped, the scan
422
+ * runs beside the checks and the independent baseline compare waits for its
423
+ * join, so it scores the committed rows.
416
424
  *
417
- * @param {object} ctx @returns {Promise<StepResult>}
425
+ * @param {object} ctx @returns {Promise<StepResult|StepResult[]>}
418
426
  */
419
427
  async function stepPreflight(ctx) {
420
428
  const name = 'preflight';
421
- if (ctx.state.preflightHead === ctx.head) {
429
+ if (preflightCredited(ctx)) {
422
430
  return creditSkip(
423
431
  name,
424
432
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
@@ -436,22 +444,52 @@ async function stepPreflight(ctx) {
436
444
  { cause: 'preflight-unresolved' },
437
445
  );
438
446
  }
439
- let findings = [];
440
447
  const pass = { checks, lint: null, covered: [] };
441
- const lanes = requestedLanes(ctx);
442
- let extra = {};
443
- if (lanes) {
444
- const run = await runPreflightLanes(ctx, checks, lanes, (check, env) =>
445
- runPreflightCheck(ctx, check, pass, env),
446
- );
447
- findings = run.findings;
448
- extra = { concurrency: { requested: lanes, admitted: run.admitted } };
449
- } else {
448
+ if (!ctx.overlapRescore) {
449
+ return settlePreflight(ctx, await runChecks(ctx, checks, pass));
450
+ }
451
+ const scan = startDuplicationScan(ctx);
452
+ const isCompare = (c) => c.key === BASELINES_GATE_NAMES.independent;
453
+ const run = await runChecks(
454
+ ctx,
455
+ checks.filter((c) => !isCompare(c)),
456
+ pass,
457
+ );
458
+ const rescore = await joinRescore(ctx, scan);
459
+ for (const check of checks.filter(isCompare)) {
460
+ const finding = await runPreflightCheck(ctx, check, pass);
461
+ if (finding) run.findings.push(finding);
462
+ }
463
+ return [rescore, settlePreflight(ctx, run)];
464
+ }
465
+
466
+ /** Preflight passed at HEAD and, when overlapped, the re-score ran there. */
467
+ function preflightCredited(ctx) {
468
+ const { preflightHead, duplicationRescore } = ctx.state;
469
+ if (preflightHead !== ctx.head) return false;
470
+ return !ctx.overlapRescore || duplicationRescore?.head === ctx.head;
471
+ }
472
+
473
+ /** Run `checks` over the admitted lanes, or serially. */
474
+ async function runChecks(ctx, checks, pass) {
475
+ if (!ctx.lanes) {
476
+ const findings = [];
450
477
  for (const check of checks) {
451
478
  const finding = await runPreflightCheck(ctx, check, pass);
452
479
  if (finding) findings.push(finding);
453
480
  }
481
+ return { findings, pass, extra: {} };
454
482
  }
483
+ const run = await runPreflightLanes(ctx, checks, ctx.lanes, (check, env) =>
484
+ runPreflightCheck(ctx, check, pass, env),
485
+ );
486
+ const concurrency = { requested: ctx.lanes, admitted: run.admitted };
487
+ return { findings: run.findings, pass, extra: { concurrency } };
488
+ }
489
+
490
+ /** One `fix-required` naming every finding, or the clean pass at HEAD. */
491
+ function settlePreflight(ctx, { findings, pass, extra }) {
492
+ const name = 'preflight';
455
493
  if (findings.length > 0) {
456
494
  const { check, evidencePath } = findings[0];
457
495
  return fixRequired(name, findings.map((f) => f.detail).join('\n'), {
@@ -466,6 +504,22 @@ async function stepPreflight(ctx) {
466
504
  return ran(name, preflightSummary(pass), extra);
467
505
  }
468
506
 
507
+ /**
508
+ * Join the overlapped scan; a re-score commit touches only the duplication
509
+ * baseline, so the credits minted at the prior HEAD carry onto it.
510
+ */
511
+ async function joinRescore(ctx, scan) {
512
+ const priorHead = ctx.head;
513
+ const result = await joinDuplicationScan(ctx, scan, () => headSha(ctx));
514
+ if (ctx.head !== priorHead) {
515
+ carryBaselineCredits(ctx, priorHead);
516
+ if (ctx.state.staticSeatHead === priorHead) {
517
+ ctx.state.staticSeatHead = ctx.head;
518
+ }
519
+ }
520
+ return result;
521
+ }
522
+
469
523
  /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
470
524
  function preflightCause(key) {
471
525
  return key === BASELINES_GATE_NAMES.independent ||
@@ -563,9 +617,11 @@ function creditCheck(ctx, check) {
563
617
  };
564
618
  }
565
619
 
566
- /** A baselines-only seat commit re-keys a held `lint`; any other commit drops it. */
567
- function carryHeldLint(state, priorHead, head) {
568
- if (state.heldLint?.head === priorHead) state.heldLint.head = head;
620
+ /** A baselines-only commit re-keys the preflight credits and a held `lint`. */
621
+ function carryBaselineCredits(ctx, priorHead) {
622
+ carryPreflightCredits(ctx, priorHead);
623
+ const held = ctx.state.heldLint;
624
+ if (held?.head === priorHead) held.head = ctx.head;
569
625
  }
570
626
 
571
627
  /** Record a held `lint` once every post-seat check passed at HEAD. */
@@ -919,8 +975,7 @@ async function commitSeatedRows(
919
975
  recordCredit(ctx, { ...ctx.state.creditTimings, head: ctx.head });
920
976
  }
921
977
  if (paths.every((p) => p.startsWith('baselines/'))) {
922
- carryPreflightCredits(ctx, priorHead);
923
- carryHeldLint(ctx.state, priorHead, ctx.head);
978
+ carryBaselineCredits(ctx, priorHead);
924
979
  }
925
980
  return ran(name, `seated ${total} row(s) and committed them`, {
926
981
  evidencePath,
@@ -1474,17 +1529,19 @@ function appendReview(steps, review) {
1474
1529
  * it; the capture stamp's digests leave `baselines/` out, so the CRAP and
1475
1530
  * coverage seat after the capture keeps the stamp fresh.
1476
1531
  *
1477
- * @param {'coverage-capture'|'test'} depositor
1532
+ * Under admitted preflight lanes the re-score runs inside preflight instead.
1533
+ *
1534
+ * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean }} ctx
1478
1535
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
1479
1536
  */
1480
- function stepOrder(depositor) {
1537
+ function stepOrder({ depositor, overlapRescore }) {
1481
1538
  const middle =
1482
1539
  depositor === 'test'
1483
1540
  ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1484
1541
  : [beforeRun(stepCreditedRun), stepSeat];
1485
1542
  return [
1486
1543
  stepBaseMerge,
1487
- stepDuplicationRescore,
1544
+ ...serialRescore(overlapRescore),
1488
1545
  stepSeatStatic,
1489
1546
  stepPreflight,
1490
1547
  ...middle,
@@ -1494,15 +1551,26 @@ function stepOrder(depositor) {
1494
1551
  ];
1495
1552
  }
1496
1553
 
1554
+ /** The standalone re-score step, absent when it overlaps preflight. */
1555
+ function serialRescore(overlapRescore) {
1556
+ return overlapRescore ? [] : [stepDuplicationRescore];
1557
+ }
1558
+
1559
+ /** Admit preflight lanes once per run; the re-score overlaps them unless `--report-all`. */
1560
+ function resolveLanes(ctx) {
1561
+ ctx.lanes = requestedLanes(ctx);
1562
+ ctx.overlapRescore = Boolean(ctx.lanes) && !ctx.reportAll;
1563
+ }
1564
+
1497
1565
  /** `--report-all`: the steps that spawn no suite and write nothing. */
1498
1566
  const REPORT_ALL_STEPS = Object.freeze([stepPreflight, stepPostCapture]);
1499
1567
 
1500
- /** `run`'s results, each carrying the call's wall time as `durationMs`. */
1568
+ /** `run`'s results, each carrying the call's wall time unless it set its own. */
1501
1569
  async function timed(ctx, run) {
1502
1570
  const startedAt = ctx.now();
1503
1571
  const results = await run();
1504
1572
  const durationMs = ctx.now() - startedAt;
1505
- return results.map((r) => ({ ...r, durationMs }));
1573
+ return results.map((r) => ({ ...r, durationMs: r.durationMs ?? durationMs }));
1506
1574
  }
1507
1575
 
1508
1576
  /**
@@ -1521,7 +1589,8 @@ function envelopeStep(ctx, { stop: _stop, ...rest }) {
1521
1589
  * @returns {Promise<StepResult|null>} the result that stopped the run.
1522
1590
  */
1523
1591
  async function runSteps(ctx, steps) {
1524
- const order = ctx.reportAll ? REPORT_ALL_STEPS : stepOrder(ctx.depositor);
1592
+ resolveLanes(ctx);
1593
+ const order = ctx.reportAll ? REPORT_ALL_STEPS : stepOrder(ctx);
1525
1594
  let first = null;
1526
1595
  for (const step of order) {
1527
1596
  ctx.stepName = handoffStepName(step);
@@ -1682,6 +1751,8 @@ async function defaultBlock({
1682
1751
  * scopeGate?: typeof applyChangedFileScope,
1683
1752
  * presentBaselines?: string[],
1684
1753
  * runDuplicationRescore?: typeof runDuplicationCloseRescore,
1754
+ * scanDuplicationRescore?: typeof scanDuplicationRescore,
1755
+ * applyDuplicationRescore?: typeof applyDuplicationRescore,
1685
1756
  * emitFriction?: typeof emitRuntimeFriction,
1686
1757
  * writeSignal?: typeof import('../signals/write.js').appendSignal,
1687
1758
  * readSignals?: typeof import('../signals/write.js').forEachLine,
@@ -1720,6 +1791,8 @@ export async function runStoryHandoff(
1720
1791
  scopeGate = applyChangedFileScope,
1721
1792
  presentBaselines,
1722
1793
  runDuplicationRescore = runDuplicationCloseRescore,
1794
+ scanDuplicationRescore: scanRescore = scanDuplicationRescore,
1795
+ applyDuplicationRescore: applyRescore = applyDuplicationRescore,
1723
1796
  emitFriction = emitRuntimeFriction,
1724
1797
  admitSuite = withSuiteAdmission,
1725
1798
  pruneStaleCrap = pruneStaleCrapRows,
@@ -1768,6 +1841,8 @@ export async function runStoryHandoff(
1768
1841
  presentBaselines,
1769
1842
  getChangedFilesFn,
1770
1843
  runDuplicationRescore,
1844
+ scanDuplicationRescore: scanRescore,
1845
+ applyDuplicationRescore: applyRescore,
1771
1846
  emitFriction,
1772
1847
  admitSuite,
1773
1848
  pruneStaleCrap,