mandrel 2.118.0 → 2.120.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 (44) hide show
  1. package/.agents/docs/agentrc-reference.json +2 -1
  2. package/.agents/docs/configuration.md +31 -8
  3. package/.agents/schemas/agentrc.schema.json +27 -4
  4. package/.agents/schemas/lifecycle/merge.unlanded.schema.json +2 -1
  5. package/.agents/schemas/story-deliver-terminal.schema.json +16 -1
  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 +21 -6
  10. package/.agents/scripts/lib/close-validation/base-sync-revalidation.js +152 -0
  11. package/.agents/scripts/lib/close-validation/ci-deferral.js +23 -5
  12. package/.agents/scripts/lib/close-validation/gates.js +8 -2
  13. package/.agents/scripts/lib/close-validation/runner.js +8 -10
  14. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  15. package/.agents/scripts/lib/config-settings-schema-delivery.js +22 -2
  16. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  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/handoff-telemetry.js +1 -0
  20. package/.agents/scripts/lib/observability/story-outcome.js +5 -4
  21. package/.agents/scripts/lib/orchestrate/inventory.js +15 -0
  22. package/.agents/scripts/lib/orchestration/handoff-changed-tests.js +67 -0
  23. package/.agents/scripts/lib/orchestration/handoff-rescore.js +95 -25
  24. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +25 -10
  25. package/.agents/scripts/lib/orchestration/merge-block-class.js +13 -1
  26. package/.agents/scripts/lib/orchestration/merge-poll.js +9 -0
  27. package/.agents/scripts/lib/orchestration/merge-queue.js +169 -21
  28. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +2 -25
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +8 -1
  30. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +26 -7
  31. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +181 -26
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +3 -2
  33. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +9 -3
  34. package/.agents/scripts/lib/orchestration/single-story-close/result.js +9 -6
  35. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +1 -0
  36. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +158 -71
  37. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +4 -0
  38. package/.agents/scripts/lib/orchestration/story-handoff.js +124 -26
  39. package/.agents/scripts/quality-preview.js +57 -8
  40. package/.agents/workflows/helpers/deliver-reference.md +27 -1
  41. package/docs/CHANGELOG.md +18 -0
  42. package/lib/cli/doctor-checks/suite-ownership.js +42 -0
  43. package/lib/cli/registry.js +6 -10
  44. 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
 
@@ -38,6 +38,7 @@ import {
38
38
  import { isBiomeNoFilesProcessed } from '../close-validation/process.js';
39
39
  import { applyChangedFileScope } from '../close-validation/runner.js';
40
40
  import { skipBranchDeposit } from '../close-validation/skip-branch-test.js';
41
+ import { substituteChangedSince } from '../close-validation/test-delta.js';
41
42
  import { getBaselines } from '../config/baselines.js';
42
43
  import { getPostSeatChecks } from '../config/handoff.js';
43
44
  import { getQuality } from '../config/quality.js';
@@ -91,14 +92,20 @@ import {
91
92
  settleOverBudget,
92
93
  } from './handoff-gates.js';
93
94
  import {
95
+ joinDuplicationScan,
94
96
  raisedDuplicationSuffix,
95
97
  rescoreDuplication,
98
+ startDuplicationScan,
96
99
  } from './handoff-rescore.js';
97
100
  import { handoffStatePath } from './handoff-state.js';
98
101
  import { settleSuiteOfRecord } from './handoff-suite-of-record.js';
99
102
  import { requestedLanes, runPreflightLanes } from './preflight-lanes.js';
100
103
  import { probeHeldReviewDiff } from './review-deposit.js';
101
- import { runDuplicationCloseRescore } from './story-close/duplication-close-rescore.js';
104
+ import {
105
+ applyDuplicationRescore,
106
+ runDuplicationCloseRescore,
107
+ scanDuplicationRescore,
108
+ } from './story-close/duplication-close-rescore.js';
102
109
  import { createStoryProgress, handoffStepName } from './story-progress.js';
103
110
  import {
104
111
  STATE_LABELS,
@@ -412,13 +419,15 @@ function preflightFinding(check, run) {
412
419
  * Runs every check — serially, or over admitted lanes when
413
420
  * `preflightConcurrency` asks (preflight-lanes.js) — then settles one
414
421
  * `fix-required` listing each finding in check order; a passed carryable
415
- * check keeps its credit either way.
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.
416
425
  *
417
- * @param {object} ctx @returns {Promise<StepResult>}
426
+ * @param {object} ctx @returns {Promise<StepResult|StepResult[]>}
418
427
  */
419
428
  async function stepPreflight(ctx) {
420
429
  const name = 'preflight';
421
- if (ctx.state.preflightHead === ctx.head) {
430
+ if (preflightCredited(ctx)) {
422
431
  return creditSkip(
423
432
  name,
424
433
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
@@ -436,22 +445,52 @@ async function stepPreflight(ctx) {
436
445
  { cause: 'preflight-unresolved' },
437
446
  );
438
447
  }
439
- let findings = [];
440
448
  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 {
449
+ if (!ctx.overlapRescore) {
450
+ return settlePreflight(ctx, await runChecks(ctx, checks, pass));
451
+ }
452
+ const scan = startDuplicationScan(ctx);
453
+ const isCompare = (c) => c.key === BASELINES_GATE_NAMES.independent;
454
+ const run = await runChecks(
455
+ ctx,
456
+ checks.filter((c) => !isCompare(c)),
457
+ pass,
458
+ );
459
+ const rescore = await joinRescore(ctx, scan);
460
+ for (const check of checks.filter(isCompare)) {
461
+ const finding = await runPreflightCheck(ctx, check, pass);
462
+ if (finding) run.findings.push(finding);
463
+ }
464
+ return [rescore, settlePreflight(ctx, run)];
465
+ }
466
+
467
+ /** Preflight passed at HEAD and, when overlapped, the re-score ran there. */
468
+ function preflightCredited(ctx) {
469
+ const { preflightHead, duplicationRescore } = ctx.state;
470
+ if (preflightHead !== ctx.head) return false;
471
+ return !ctx.overlapRescore || duplicationRescore?.head === ctx.head;
472
+ }
473
+
474
+ /** Run `checks` over the admitted lanes, or serially. */
475
+ async function runChecks(ctx, checks, pass) {
476
+ if (!ctx.lanes) {
477
+ const findings = [];
450
478
  for (const check of checks) {
451
479
  const finding = await runPreflightCheck(ctx, check, pass);
452
480
  if (finding) findings.push(finding);
453
481
  }
482
+ return { findings, pass, extra: {} };
454
483
  }
484
+ const run = await runPreflightLanes(ctx, checks, ctx.lanes, (check, env) =>
485
+ runPreflightCheck(ctx, check, pass, env),
486
+ );
487
+ const concurrency = { requested: ctx.lanes, admitted: run.admitted };
488
+ return { findings: run.findings, pass, extra: { concurrency } };
489
+ }
490
+
491
+ /** One `fix-required` naming every finding, or the clean pass at HEAD. */
492
+ function settlePreflight(ctx, { findings, pass, extra }) {
493
+ const name = 'preflight';
455
494
  if (findings.length > 0) {
456
495
  const { check, evidencePath } = findings[0];
457
496
  return fixRequired(name, findings.map((f) => f.detail).join('\n'), {
@@ -466,6 +505,22 @@ async function stepPreflight(ctx) {
466
505
  return ran(name, preflightSummary(pass), extra);
467
506
  }
468
507
 
508
+ /**
509
+ * Join the overlapped scan; a re-score commit touches only the duplication
510
+ * baseline, so the credits minted at the prior HEAD carry onto it.
511
+ */
512
+ async function joinRescore(ctx, scan) {
513
+ const priorHead = ctx.head;
514
+ const result = await joinDuplicationScan(ctx, scan, () => headSha(ctx));
515
+ if (ctx.head !== priorHead) {
516
+ carryBaselineCredits(ctx, priorHead);
517
+ if (ctx.state.staticSeatHead === priorHead) {
518
+ ctx.state.staticSeatHead = ctx.head;
519
+ }
520
+ }
521
+ return result;
522
+ }
523
+
469
524
  /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
470
525
  function preflightCause(key) {
471
526
  return key === BASELINES_GATE_NAMES.independent ||
@@ -563,9 +618,11 @@ function creditCheck(ctx, check) {
563
618
  };
564
619
  }
565
620
 
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;
621
+ /** A baselines-only commit re-keys the preflight credits and a held `lint`. */
622
+ function carryBaselineCredits(ctx, priorHead) {
623
+ carryPreflightCredits(ctx, priorHead);
624
+ const held = ctx.state.heldLint;
625
+ if (held?.head === priorHead) held.head = ctx.head;
569
626
  }
570
627
 
571
628
  /** Record a held `lint` once every post-seat check passed at HEAD. */
@@ -682,6 +739,27 @@ function depositorArgv(ctx) {
682
739
  return { args, label: deposit.label };
683
740
  }
684
741
 
742
+ /**
743
+ * The `ci` posture's changed-tests guard: `testChanged` keyed on the
744
+ * `origin/<base>` merge-base, outside the full-suite lock, bounded by
745
+ * `coverage.timeoutMs`.
746
+ */
747
+ function runChangedTests(ctx, testChanged, signal) {
748
+ const base = `origin/${ctx.baseBranch}`;
749
+ const since = gitLine(ctx.git, ctx.cwd, ['merge-base', 'HEAD', base]) || base;
750
+ const { cmd, args, env } = substituteChangedSince(testChanged, since);
751
+ const timeoutMs = getQuality(ctx.config).coverage.timeoutMs;
752
+ const bounded = { ...ctx, stream: { ...ctx.stream, timeoutMs } };
753
+ return runLogged(
754
+ bounded,
755
+ 'changed-tests',
756
+ cmd,
757
+ args,
758
+ { ...ctx.env, ...env },
759
+ signal,
760
+ );
761
+ }
762
+
685
763
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
686
764
  async function creditedRun(ctx, signal) {
687
765
  const name = 'credited-run';
@@ -692,7 +770,8 @@ async function creditedRun(ctx, signal) {
692
770
  { depositor: ctx.depositor },
693
771
  );
694
772
  }
695
- const ciOwned = settleSuiteOfRecord(ctx, name);
773
+ const guard = { run: (cmd) => runChangedTests(ctx, cmd, signal), signal };
774
+ const ciOwned = await settleSuiteOfRecord(ctx, name, guard);
696
775
  if (ciOwned) return ciOwned;
697
776
  const capture = ctx.depositor === 'coverage-capture';
698
777
  const { args, label } = depositorArgv(ctx);
@@ -919,8 +998,7 @@ async function commitSeatedRows(
919
998
  recordCredit(ctx, { ...ctx.state.creditTimings, head: ctx.head });
920
999
  }
921
1000
  if (paths.every((p) => p.startsWith('baselines/'))) {
922
- carryPreflightCredits(ctx, priorHead);
923
- carryHeldLint(ctx.state, priorHead, ctx.head);
1001
+ carryBaselineCredits(ctx, priorHead);
924
1002
  }
925
1003
  return ran(name, `seated ${total} row(s) and committed them`, {
926
1004
  evidencePath,
@@ -1474,17 +1552,19 @@ function appendReview(steps, review) {
1474
1552
  * it; the capture stamp's digests leave `baselines/` out, so the CRAP and
1475
1553
  * coverage seat after the capture keeps the stamp fresh.
1476
1554
  *
1477
- * @param {'coverage-capture'|'test'} depositor
1555
+ * Under admitted preflight lanes the re-score runs inside preflight instead.
1556
+ *
1557
+ * @param {{ depositor: 'coverage-capture'|'test', overlapRescore?: boolean }} ctx
1478
1558
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
1479
1559
  */
1480
- function stepOrder(depositor) {
1560
+ function stepOrder({ depositor, overlapRescore }) {
1481
1561
  const middle =
1482
1562
  depositor === 'test'
1483
1563
  ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1484
1564
  : [beforeRun(stepCreditedRun), stepSeat];
1485
1565
  return [
1486
1566
  stepBaseMerge,
1487
- stepDuplicationRescore,
1567
+ ...serialRescore(overlapRescore),
1488
1568
  stepSeatStatic,
1489
1569
  stepPreflight,
1490
1570
  ...middle,
@@ -1494,15 +1574,26 @@ function stepOrder(depositor) {
1494
1574
  ];
1495
1575
  }
1496
1576
 
1577
+ /** The standalone re-score step, absent when it overlaps preflight. */
1578
+ function serialRescore(overlapRescore) {
1579
+ return overlapRescore ? [] : [stepDuplicationRescore];
1580
+ }
1581
+
1582
+ /** Admit preflight lanes once per run; the re-score overlaps them unless `--report-all`. */
1583
+ function resolveLanes(ctx) {
1584
+ ctx.lanes = requestedLanes(ctx);
1585
+ ctx.overlapRescore = Boolean(ctx.lanes) && !ctx.reportAll;
1586
+ }
1587
+
1497
1588
  /** `--report-all`: the steps that spawn no suite and write nothing. */
1498
1589
  const REPORT_ALL_STEPS = Object.freeze([stepPreflight, stepPostCapture]);
1499
1590
 
1500
- /** `run`'s results, each carrying the call's wall time as `durationMs`. */
1591
+ /** `run`'s results, each carrying the call's wall time unless it set its own. */
1501
1592
  async function timed(ctx, run) {
1502
1593
  const startedAt = ctx.now();
1503
1594
  const results = await run();
1504
1595
  const durationMs = ctx.now() - startedAt;
1505
- return results.map((r) => ({ ...r, durationMs }));
1596
+ return results.map((r) => ({ ...r, durationMs: r.durationMs ?? durationMs }));
1506
1597
  }
1507
1598
 
1508
1599
  /**
@@ -1521,7 +1612,8 @@ function envelopeStep(ctx, { stop: _stop, ...rest }) {
1521
1612
  * @returns {Promise<StepResult|null>} the result that stopped the run.
1522
1613
  */
1523
1614
  async function runSteps(ctx, steps) {
1524
- const order = ctx.reportAll ? REPORT_ALL_STEPS : stepOrder(ctx.depositor);
1615
+ resolveLanes(ctx);
1616
+ const order = ctx.reportAll ? REPORT_ALL_STEPS : stepOrder(ctx);
1525
1617
  let first = null;
1526
1618
  for (const step of order) {
1527
1619
  ctx.stepName = handoffStepName(step);
@@ -1682,6 +1774,8 @@ async function defaultBlock({
1682
1774
  * scopeGate?: typeof applyChangedFileScope,
1683
1775
  * presentBaselines?: string[],
1684
1776
  * runDuplicationRescore?: typeof runDuplicationCloseRescore,
1777
+ * scanDuplicationRescore?: typeof scanDuplicationRescore,
1778
+ * applyDuplicationRescore?: typeof applyDuplicationRescore,
1685
1779
  * emitFriction?: typeof emitRuntimeFriction,
1686
1780
  * writeSignal?: typeof import('../signals/write.js').appendSignal,
1687
1781
  * readSignals?: typeof import('../signals/write.js').forEachLine,
@@ -1720,6 +1814,8 @@ export async function runStoryHandoff(
1720
1814
  scopeGate = applyChangedFileScope,
1721
1815
  presentBaselines,
1722
1816
  runDuplicationRescore = runDuplicationCloseRescore,
1817
+ scanDuplicationRescore: scanRescore = scanDuplicationRescore,
1818
+ applyDuplicationRescore: applyRescore = applyDuplicationRescore,
1723
1819
  emitFriction = emitRuntimeFriction,
1724
1820
  admitSuite = withSuiteAdmission,
1725
1821
  pruneStaleCrap = pruneStaleCrapRows,
@@ -1768,6 +1864,8 @@ export async function runStoryHandoff(
1768
1864
  presentBaselines,
1769
1865
  getChangedFilesFn,
1770
1866
  runDuplicationRescore,
1867
+ scanDuplicationRescore: scanRescore,
1868
+ applyDuplicationRescore: applyRescore,
1771
1869
  emitFriction,
1772
1870
  admitSuite,
1773
1871
  pruneStaleCrap,