mandrel 2.111.0 → 2.113.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 (183) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +367 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/merge-envelopes.js +46 -1
  38. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  39. package/.agents/scripts/lib/baselines/reader.js +36 -9
  40. package/.agents/scripts/lib/baselines/refresh-service.js +93 -21
  41. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  42. package/.agents/scripts/lib/baselines/writer.js +36 -21
  43. package/.agents/scripts/lib/changed-files.js +70 -6
  44. package/.agents/scripts/lib/child-exec.js +10 -0
  45. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  46. package/.agents/scripts/lib/close-lock-events.js +8 -3
  47. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  48. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  49. package/.agents/scripts/lib/close-validation/process.js +16 -7
  50. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  51. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  52. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  53. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  54. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  55. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  56. package/.agents/scripts/lib/config/explain.js +5 -2
  57. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  58. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  59. package/.agents/scripts/lib/config/git-roots.js +38 -4
  60. package/.agents/scripts/lib/config/handoff.js +24 -0
  61. package/.agents/scripts/lib/config/quality.js +26 -13
  62. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  63. package/.agents/scripts/lib/config-resolver.js +22 -2
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  66. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  67. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  68. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  69. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  70. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  71. package/.agents/scripts/lib/coverage-capture.js +15 -0
  72. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  73. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  74. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  75. package/.agents/scripts/lib/crap-engine.js +3 -3
  76. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  77. package/.agents/scripts/lib/error-redactor.js +20 -0
  78. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  79. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  80. package/.agents/scripts/lib/failure-rows.js +121 -0
  81. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  82. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  83. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  84. package/.agents/scripts/lib/gh-env.js +3 -6
  85. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  86. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  87. package/.agents/scripts/lib/git/baseline-conflict-rows.js +60 -0
  88. package/.agents/scripts/lib/git/sync-from-base.js +18 -9
  89. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  90. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  91. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  92. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  93. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  94. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  95. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  102. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  103. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  104. package/.agents/scripts/lib/orchestration/handoff-rescore.js +170 -0
  105. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  106. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  107. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  108. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  109. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  110. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  111. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +41 -12
  112. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +90 -39
  113. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  114. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +102 -3
  115. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  116. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  117. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  118. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  119. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  120. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  121. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +16 -3
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +2 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  140. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  141. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  142. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  143. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  144. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +77 -15
  145. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  146. package/.agents/scripts/lib/orchestration/story-handoff.js +796 -196
  147. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  148. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  149. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  150. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  151. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  152. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  153. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  154. package/.agents/scripts/lib/suite-admission.js +20 -8
  155. package/.agents/scripts/lib/suite-sizing.js +146 -0
  156. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  157. package/.agents/scripts/merge-baseline.js +14 -3
  158. package/.agents/scripts/providers/github/comments.js +19 -3
  159. package/.agents/scripts/providers/github.js +1 -0
  160. package/.agents/scripts/review-dispositions-report.js +1 -1
  161. package/.agents/scripts/role-scope-guard.js +267 -0
  162. package/.agents/scripts/single-story-close.js +4 -4
  163. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  164. package/.agents/scripts/single-story-init.js +24 -4
  165. package/.agents/scripts/story-handoff.js +3 -3
  166. package/.agents/scripts/story-outcomes-report.js +231 -0
  167. package/.agents/scripts/story-review-compute.js +9 -5
  168. package/.agents/scripts/update-coverage-baseline.js +12 -2
  169. package/.agents/scripts/update-crap-baseline.js +9 -1
  170. package/.agents/workflows/helpers/code-review.md +63 -9
  171. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  172. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  173. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  174. package/.agents/workflows/helpers/deliver-story.md +7 -2
  175. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  176. package/docs/CHANGELOG.md +55 -0
  177. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  178. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  179. package/lib/cli/doctor-checks/llm-review.js +2 -11
  180. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  181. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  182. package/lib/cli/registry.js +5 -0
  183. package/package.json +1 -1
@@ -10,7 +10,7 @@
10
10
  * @module lib/baselines/merge-envelopes
11
11
  */
12
12
 
13
- import { deepEqual } from '../json-utils.js';
13
+ import { deepEqual, isObject } from '../json-utils.js';
14
14
  import { KNOWN_KINDS } from './envelope.js';
15
15
  import { getKindModule } from './kernel.js';
16
16
 
@@ -310,6 +310,51 @@ export function mergePlainBaseline({ base, ours, theirs, kind } = {}) {
310
310
  };
311
311
  }
312
312
 
313
+ /**
314
+ * Three-way merge where every row and stamp conflict takes theirs, so a row
315
+ * only ours carries survives a conflicted file. `null` for an unknown kind or
316
+ * a missing side.
317
+ *
318
+ * @param {{ base: object|null, ours: object, theirs: object }} params
319
+ * @returns {{ kind: string, envelopeKind: boolean, envelope: object, storyOnlyRows: number }|null}
320
+ */
321
+ export function mergeBaselineTheirsWins({ base, ours, theirs } = {}) {
322
+ const envelopeKind = kindFromEnvelope(ours) ?? kindFromEnvelope(theirs);
323
+ const kind =
324
+ envelopeKind ??
325
+ plainKindFromEnvelope(ours) ??
326
+ plainKindFromEnvelope(theirs);
327
+ if (!kind || !isObject(ours) || !isObject(theirs)) return null;
328
+ const merge = envelopeKind ? mergeEnvelopes : mergePlainBaseline;
329
+ const { conflicts } = merge({ base, ours, theirs, kind });
330
+ const rowConflicts = conflicts.filter((c) => c.scope === 'row');
331
+ const replaced = new Set(rowConflicts.map((c) => c.ours));
332
+ const resolved = {
333
+ ...ours,
334
+ rows: [
335
+ ...(ours.rows ?? []).filter((row) => !replaced.has(row)),
336
+ ...rowConflicts.flatMap((c) =>
337
+ c.theirs === undefined ? [] : [c.theirs],
338
+ ),
339
+ ],
340
+ };
341
+ for (const c of conflicts.filter((c) => c.scope === 'envelope')) {
342
+ if (c.theirs === undefined) delete resolved[c.identity];
343
+ else resolved[c.identity] = c.theirs;
344
+ }
345
+ const { envelope } = merge({ base, ours: resolved, theirs, kind });
346
+ const rowIdentity = envelopeKind
347
+ ? getKindModule(kind).rowIdentity
348
+ : plainSpec(kind).rowIdentity;
349
+ const elsewhere = new Set(
350
+ [...(base?.rows ?? []), ...(theirs.rows ?? [])].map(rowIdentity),
351
+ );
352
+ const storyOnlyRows = (ours.rows ?? []).filter(
353
+ (row) => !elsewhere.has(rowIdentity(row)),
354
+ ).length;
355
+ return { kind, envelopeKind: Boolean(envelopeKind), envelope, storyOnlyRows };
356
+ }
357
+
313
358
  const REGENERATE_COMMANDS = Object.freeze({
314
359
  'dead-exports': 'npm run dead-exports:update',
315
360
  'dead-exports-production': 'npm run dead-exports:update',
@@ -12,6 +12,8 @@ import { calculateAll, scanDirectory } from '../maintainability-utils.js';
12
12
  import { toPosix } from '../util/paths.js';
13
13
  import { computeCrapPreviewScan } from './crap-preview-scan.js';
14
14
  import {
15
+ AHEAD_BASELINE_DIAGNOSTIC,
16
+ aheadStampOf,
15
17
  assertBaselineCompatible,
16
18
  INCOMPATIBLE_BASELINE_DIAGNOSTIC,
17
19
  loadCrapBaseline,
@@ -22,6 +24,7 @@ import {
22
24
  loadMaintainabilityBaseline,
23
25
  MAINTAINABILITY_EXCLUSIONS,
24
26
  } from './kinds/maintainability.js';
27
+ import { peekFile } from './reader.js';
25
28
 
26
29
  export const MI_PREVIEW_DEFAULT_TOLERANCE = 0.5;
27
30
 
@@ -186,6 +189,25 @@ export async function runMaintainabilityPreview({
186
189
  return { exitCode, envelope };
187
190
  }
188
191
 
192
+ /**
193
+ * The skips decided before the schema-validated load: a disabled gate, or a
194
+ * baseline stamped ahead of this code (whose layout may be newer too).
195
+ */
196
+ function crapPreviewSkip({ crap, baselinePath, scope, diffRef }) {
197
+ const empty = emptyCrapEnvelope({ scope, diffRef });
198
+ if (crap.enabled === false) return { exitCode: 0, envelope: empty };
199
+ return aheadSkip(aheadStampOf(peekFile(baselinePath)), empty);
200
+ }
201
+
202
+ function aheadSkip(ahead, empty) {
203
+ if (!ahead) return null;
204
+ const diagnostic = {
205
+ name: AHEAD_BASELINE_DIAGNOSTIC,
206
+ message: ahead.message,
207
+ };
208
+ return { exitCode: 0, envelope: suppressVerdicts(empty, diagnostic) };
209
+ }
210
+
189
211
  /**
190
212
  * Run the CRAP gate in preview mode.
191
213
  */
@@ -200,16 +222,12 @@ export async function runCrapPreview({
200
222
  cwd,
201
223
  });
202
224
  const config = resolveConfig({ cwd });
203
- const baselinePath = getBaselines(config).crap.path;
204
- const baseline = loadCrapBaseline({
205
- baselinePath: path.isAbsolute(baselinePath)
206
- ? baselinePath
207
- : path.resolve(cwd, baselinePath),
208
- epicRef: null,
209
- });
210
- const quality = getQuality(config);
211
- const crap = quality.crap;
212
- if (!baseline || crap.enabled === false) {
225
+ const baselinePath = path.resolve(cwd, getBaselines(config).crap.path);
226
+ const crap = getQuality(config).crap;
227
+ const skipped = crapPreviewSkip({ crap, baselinePath, scope, diffRef });
228
+ if (skipped) return skipped;
229
+ const baseline = loadCrapBaseline({ baselinePath, epicRef: null });
230
+ if (!baseline) {
213
231
  return { exitCode: 0, envelope: emptyCrapEnvelope({ scope, diffRef }) };
214
232
  }
215
233
 
@@ -237,5 +255,6 @@ export async function runCrapPreview({
237
255
  scope,
238
256
  diffRef,
239
257
  baseline,
258
+ baseBranch: config?.project?.baseBranch,
240
259
  });
241
260
  }
@@ -10,6 +10,7 @@ import {
10
10
  } from '../baseline-schema-registry.js';
11
11
  import { getBaselines } from '../config/baselines.js';
12
12
  import { resolveConfig } from '../config-resolver.js';
13
+ import { decodeEnvelope } from './codec.js';
13
14
 
14
15
  // Overridden by `delivery.quality.gates.<kind>.baselinePath`.
15
16
  const DEFAULT_PATHS = Object.freeze({
@@ -130,24 +131,24 @@ function validate(kind, parsed, sourceHint) {
130
131
  /**
131
132
  * The one narrowing projection for every loaded envelope. It is an
132
133
  * allow-list: compat axes read stamps off the loaded object and fail closed
133
- * on `undefined`, so every envelope stamp must be carried through here. The
134
- * committed file carries no rollup; a consumer that needs one derives it from
135
- * `rows` through the kind module.
134
+ * on `undefined`, so every envelope stamp must be carried through here. Rows
135
+ * come out of the layout codec. The committed file carries no rollup; a
136
+ * consumer that needs one derives it from `rows` through the kind module.
136
137
  *
137
138
  * @param {string} kind
138
139
  * @param {object} parsed A validated baseline envelope.
139
140
  * @returns {{ rows: Array<object>, kernelVersion: string }}
140
141
  */
141
142
  function shapeEnvelope(kind, parsed) {
142
- const rows = Array.isArray(parsed.rows)
143
- ? parsed.rows.map((row) => canonicaliseRow(kind, row))
143
+ const decoded = decodeEnvelope(parsed);
144
+ const rows = Array.isArray(decoded.rows)
145
+ ? decoded.rows.map((row) => canonicaliseRow(kind, row))
144
146
  : [];
145
147
  return {
146
148
  rows,
147
- kernelVersion: parsed.kernelVersion,
148
- scoringSemantics: parsed.scoringSemantics,
149
- tsTranspilerVersion: parsed.tsTranspilerVersion,
150
- provenanceStamped: parsed.provenanceStamped,
149
+ kernelVersion: decoded.kernelVersion,
150
+ scoringSemantics: decoded.scoringSemantics,
151
+ tsTranspilerVersion: decoded.tsTranspilerVersion,
151
152
  };
152
153
  }
153
154
 
@@ -248,6 +249,32 @@ export function loadFile(absolutePath, opts = {}) {
248
249
  return shapeEnvelope(kind, parsed);
249
250
  }
250
251
 
252
+ /**
253
+ * Parsed JSON with no schema check, or null on any read/parse failure: lets a
254
+ * caller read a stamp off an envelope whose layout this code predates.
255
+ *
256
+ * @param {string} absolutePath
257
+ * @returns {unknown}
258
+ */
259
+ export function peekFile(absolutePath) {
260
+ try {
261
+ return JSON.parse(readFileSync(absolutePath, 'utf8'));
262
+ } catch {
263
+ return null;
264
+ }
265
+ }
266
+
267
+ /**
268
+ * {@link peekFile} at the path `load(kind, opts)` would read.
269
+ *
270
+ * @param {string} kind
271
+ * @param {{ configPath?: string, cwd?: string }} [opts]
272
+ * @returns {unknown}
273
+ */
274
+ export function peek(kind, opts = {}) {
275
+ return peekFile(resolveBaselinePath(kind, opts));
276
+ }
277
+
251
278
  export const _internals = Object.freeze({
252
279
  DEFAULT_PATHS,
253
280
  KIND_TO_SCHEMA_FILE,
@@ -34,12 +34,13 @@ import {
34
34
  import { isScorableSourceFile } from '../source-extensions.js';
35
35
  import { toPosix } from '../util/paths.js';
36
36
  import { buildBundleSizeScorer } from './bundle-size-scorer.js';
37
+ import { decodeEnvelope } from './codec.js';
37
38
  import {
38
39
  resolveDetectClones,
39
40
  resolveFormatExtensions,
40
41
  scanDuplication,
41
42
  } from './duplication-scanner.js';
42
- import { getKindModule } from './kernel.js';
43
+ import { checkBaselineAhead, getKindModule } from './kernel.js';
43
44
  import { filterExcludedRows } from './kinds/maintainability.js';
44
45
  import { canonicalizeBaselinePath } from './path-canon.js';
45
46
  import {
@@ -287,11 +288,38 @@ function defaultExtrasContext(kind, cwd) {
287
288
  return { cwd, targetDirs };
288
289
  }
289
290
 
291
+ /**
292
+ * A full scope is the operator's explicit re-seed: it overwrites even an
293
+ * ahead baseline. Any narrower scope hands off before scoring.
294
+ */
295
+ function aheadHandOff({ prior, fullScope, kind, writePath, scopeFiles }) {
296
+ if (!prior.ahead || fullScope) return null;
297
+ return {
298
+ kind,
299
+ writePath,
300
+ scope: { mode: scopeFiles ? 'explicit' : 'diff', files: [] },
301
+ envelope: null,
302
+ wrote: false,
303
+ ahead: prior.ahead,
304
+ };
305
+ }
306
+
307
+ function requireScorer(kind, scorer, cwd) {
308
+ const resolved = scorer ?? resolveDefaultScorer(kind, { cwd });
309
+ if (typeof resolved !== 'function') {
310
+ throw new Error(
311
+ `refreshBaseline: no scorer registered for kind "${kind}" (inject one via opts.scorer)`,
312
+ );
313
+ }
314
+ return resolved;
315
+ }
316
+
290
317
  /**
291
318
  * Refresh the on-disk baseline for `kind`. `scopeFiles: null` without
292
319
  * `fullScope` derives scope from `git diff baseRef..headRef`; `fullScope`
293
320
  * requires `scopeFiles: null`. `requireRowsForScopeFiles` fails loud when a
294
- * scoped file produced no row.
321
+ * scoped file produced no row. A scoped refresh never rewrites an
322
+ * `excludeWriteFiles` row.
295
323
  *
296
324
  * @param {{
297
325
  * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication' | 'bundle-size',
@@ -308,14 +336,18 @@ function defaultExtrasContext(kind, cwd) {
308
336
  * requireRowsForScopeFiles?: boolean,
309
337
  * requiredScopeFilePredicate?: (file: string) => boolean,
310
338
  * extrasContext?: { cwd?: string, targetDirs?: string[] },
339
+ * excludeWriteFiles?: string[],
311
340
  * }} opts
312
341
  * @returns {Promise<{
313
342
  * kind: string,
314
343
  * writePath: string,
315
344
  * scope: { mode: 'full' | 'diff' | 'explicit', ref?: string, files: string[] },
316
- * envelope: object,
345
+ * envelope: object | null,
317
346
  * wrote: boolean,
318
- * }>}
347
+ * partners?: Record<string, string[]>,
348
+ * ahead?: object,
349
+ * }>} `partners`: each write-scope file's scored clone partners. `ahead` (with a null `envelope`): a narrower-than-full refresh left a
350
+ * baseline stamped newer than this code untouched.
319
351
  */
320
352
  export async function refreshBaseline(opts = {}) {
321
353
  const {
@@ -333,16 +365,22 @@ export async function refreshBaseline(opts = {}) {
333
365
  requireRowsForScopeFiles = false,
334
366
  requiredScopeFilePredicate,
335
367
  extrasContext,
368
+ excludeWriteFiles = [],
336
369
  } = opts;
337
370
 
338
371
  validateOptions({ kind, scopeFiles, fullScope, writePath });
339
372
 
340
- const resolvedScorer = scorer ?? resolveDefaultScorer(kind, { cwd });
341
- if (typeof resolvedScorer !== 'function') {
342
- throw new Error(
343
- `refreshBaseline: no scorer registered for kind "${kind}" (inject one via opts.scorer)`,
344
- );
345
- }
373
+ const prior = readPriorState(writePath, fs, kind);
374
+ const handedOff = aheadHandOff({
375
+ prior,
376
+ fullScope,
377
+ kind,
378
+ writePath,
379
+ scopeFiles,
380
+ });
381
+ if (handedOff) return handedOff;
382
+
383
+ const resolvedScorer = requireScorer(kind, scorer, cwd);
346
384
 
347
385
  const scope = await resolveScope({
348
386
  kind,
@@ -378,12 +416,13 @@ export async function refreshBaseline(opts = {}) {
378
416
  requiredScopeFilePredicate,
379
417
  });
380
418
 
381
- const priorEnvelope = readPriorEnvelope(writePath, fs);
419
+ const priorEnvelope = prior.envelope;
382
420
  const writeFiles = resolveWriteScopeFiles({
383
421
  kind,
384
422
  scope,
385
423
  rows: canonicalRows,
386
424
  priorRows: priorEnvelope?.rows,
425
+ exclude: excludeWriteFiles,
387
426
  });
388
427
 
389
428
  const envelope = writeEnvelope({
@@ -417,9 +456,21 @@ export async function refreshBaseline(opts = {}) {
417
456
  },
418
457
  envelope,
419
458
  wrote,
459
+ partners: partnersOf(canonicalRows, writeFiles),
420
460
  };
421
461
  }
422
462
 
463
+ /** Each listed file's scored clone partners; the envelope never stores them. */
464
+ function partnersOf(rows, files) {
465
+ const byPath = new Map(rows.map((row) => [row.path, row.partners]));
466
+ const out = {};
467
+ for (const file of files) {
468
+ const partners = byPath.get(file);
469
+ if (partners?.length) out[file] = partners.map(canonicalizeBaselinePath);
470
+ }
471
+ return out;
472
+ }
473
+
423
474
  /**
424
475
  * The files whose rows a scoped refresh rewrites. Duplication is pairwise, so
425
476
  * a changed file also moves the rows of files it shares (or shared) a clone
@@ -428,10 +479,17 @@ export async function refreshBaseline(opts = {}) {
428
479
  * removed clone's partner appears in no head pair). A rise in an unrelated
429
480
  * file stays out of scope, so a branch never owns drift it did not cause.
430
481
  *
431
- * @param {{ kind: string, scope: { mode: string, files: string[] }, rows: object[], priorRows?: object[] }} args
482
+ * `exclude` is subtracted last.
483
+ *
484
+ * @param {{ kind: string, scope: { mode: string, files: string[] }, rows: object[], priorRows?: object[], exclude?: string[] }} args
432
485
  * @returns {string[]}
433
486
  */
434
- function resolveWriteScopeFiles({ kind, scope, rows, priorRows }) {
487
+ function resolveWriteScopeFiles({ exclude = [], ...args }) {
488
+ const excluded = new Set(exclude.map(canonicalizeBaselinePath));
489
+ return widenWriteScope(args).filter((file) => !excluded.has(file));
490
+ }
491
+
492
+ function widenWriteScope({ kind, scope, rows, priorRows }) {
435
493
  if (kind !== 'duplication' || scope.mode === 'full') return [...scope.files];
436
494
  const headByPath = new Map(rows.map((row) => [row.path, row]));
437
495
  const partners = scope.files.flatMap(
@@ -631,20 +689,34 @@ async function resolveScope({
631
689
  * @returns {object | null}
632
690
  */
633
691
  export function readPriorEnvelope(writePath, fs) {
692
+ return readPriorState(writePath, fs).envelope;
693
+ }
694
+
695
+ /**
696
+ * The prior envelope (as {@link readPriorEnvelope}), or `ahead` when its stamp
697
+ * is newer than this code: then `envelope` is null and nothing may write it
698
+ * short of a full-scope re-seed.
699
+ *
700
+ * @param {string} writePath
701
+ * @param {typeof nodeFs} fs
702
+ * @param {string} [kind]
703
+ * @returns {{envelope: object|null, ahead: object|null}}
704
+ */
705
+ export function readPriorState(writePath, fs, kind) {
634
706
  let raw;
635
707
  try {
636
- raw = fs.readFileSync(writePath, 'utf8');
708
+ raw = JSON.parse(fs.readFileSync(writePath, 'utf8'));
637
709
  } catch {
638
- return null;
710
+ return { envelope: null, ahead: null };
639
711
  }
712
+ const ahead = kind ? checkBaselineAhead(kind, raw) : null;
713
+ if (ahead) return { envelope: null, ahead };
640
714
  try {
641
- const parsed = JSON.parse(raw);
642
- if (isObject(parsed) && Array.isArray(parsed.rows)) {
643
- return parsed;
644
- }
645
- return null;
715
+ const parsed = decodeEnvelope(raw);
716
+ const valid = isObject(parsed) && Array.isArray(parsed.rows);
717
+ return { envelope: valid ? parsed : null, ahead: null };
646
718
  } catch {
647
- return null;
719
+ return { envelope: null, ahead: null };
648
720
  }
649
721
  }
650
722
 
@@ -3,22 +3,35 @@
3
3
  * key is absent from the committed baseline; prior rows keep their parsed
4
4
  * objects, so they serialise byte-identically. The CRAP key is
5
5
  * `path::method` — the gate matches a moved method by name, so it is not
6
- * missing.
6
+ * missing; MI and coverage key on `path`.
7
7
  */
8
8
 
9
9
  import nodeFs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { execFileCaptureAsync } from '../child-exec.js';
12
- import { getBaselines, resolveConfig } from '../config-resolver.js';
12
+ import { getBaselines, getQuality, resolveConfig } from '../config-resolver.js';
13
+ import {
14
+ buildScopePredicate,
15
+ scoreCoverageFinal,
16
+ } from '../coverage-baseline.js';
17
+ import { isCoverageFresh } from '../coverage-capture.js';
13
18
  import { Logger } from '../Logger.js';
19
+ import {
20
+ coverageUpdaterTargets,
21
+ loadC8ScopeConfig,
22
+ } from './coverage-updater-cli.js';
14
23
  import { parseDiffScopeFlag } from './diff-scope-cli.js';
15
24
  import { assertEnvelope } from './envelope.js';
16
25
  import { getKindModule } from './kernel.js';
26
+ import {
27
+ classifyScoringSemantics,
28
+ SCORING_SEMANTICS,
29
+ } from './kinds/_crap-read.js';
17
30
  import { canonicalizeBaselinePath } from './path-canon.js';
18
31
  import {
19
32
  deriveScopeFromDiff,
20
33
  fileFilterFor,
21
- readPriorEnvelope,
34
+ readPriorState,
22
35
  resolveDefaultScorer,
23
36
  } from './refresh-service.js';
24
37
  import {
@@ -37,8 +50,30 @@ export class SeatRefusal extends Error {
37
50
  const SEAT_KEYS = Object.freeze({
38
51
  crap: (row) => `${row.path}::${row.method}`,
39
52
  maintainability: (row) => row.path,
53
+ coverage: (row) => row.path,
40
54
  });
41
55
 
56
+ /** Stamp scopes a capture may have written; any one fresh stamp suffices. */
57
+ const CAPTURE_SCOPES = ['full', 'incremental', 'affected'];
58
+
59
+ /**
60
+ * Whether any capture stamp marks the coverage artifact fresh for the
61
+ * current tree. `targetDirs` is the stamp's digest scope.
62
+ *
63
+ * @param {{coveragePath: string, targetDirs: string[]}} options
64
+ * @param {{isFresh?: Function, cwd: string}} deps
65
+ * @returns {boolean}
66
+ */
67
+ export function isCaptureFresh(
68
+ { coveragePath, targetDirs },
69
+ { isFresh = isCoverageFresh, cwd },
70
+ ) {
71
+ return CAPTURE_SCOPES.some(
72
+ (requireScope) =>
73
+ isFresh({ coveragePath, targetDirs, cwd, requireScope }).fresh,
74
+ );
75
+ }
76
+
42
77
  /**
43
78
  * @param {string} kind
44
79
  * @returns {(row: object) => string}
@@ -117,13 +152,37 @@ function buildSeatedEnvelope({ kind, priorEnvelope, seated }) {
117
152
  return envelope;
118
153
  }
119
154
 
155
+ /** A behind CRAP baseline needs a full re-seed; seating would mix semantics. */
156
+ function assertCrapPriorCurrent(kind, envelope) {
157
+ if (kind !== 'crap' || !envelope) return;
158
+ const stamp = envelope.scoringSemantics;
159
+ if (classifyScoringSemantics(stamp) !== 'behind') return;
160
+ throw new SeatRefusal(
161
+ `[CRAP] --seat-missing refused: baseline scoringSemantics=${stamp ?? '<unstamped>'} ` +
162
+ `is behind running=${SCORING_SEMANTICS}; re-seed with a --full-scope crap:update`,
163
+ );
164
+ }
165
+
166
+ /** An ahead baseline is left untouched: nothing seated, nothing scored. */
167
+ function handOff(ahead) {
168
+ return { seated: 0, wrote: false, files: [], ahead };
169
+ }
170
+
171
+ /** `seated: N`, preceded by the hand-off line when the baseline was ahead. */
172
+ function logSeated(logger, label, { seated, ahead }) {
173
+ if (ahead) logger.info(ahead.message);
174
+ logger.info(`[${label}] seated: ${seated}`);
175
+ }
176
+
120
177
  /**
121
178
  * Seat the missing rows of `kind` for the files changed in `baseRef...HEAD`.
122
179
  * `score(files)` may throw a {@link SeatRefusal}. No missing row, no write.
123
180
  *
124
181
  * @param {{kind: string, writePath: string, score: Function, baseRef: string,
125
182
  * headRef?: string, cwd?: string, gitDiff?: Function, fs?: typeof nodeFs}} opts
126
- * @returns {Promise<{seated: number, wrote: boolean, files: string[]}>}
183
+ * @returns {Promise<{seated: number, wrote: boolean, files: string[],
184
+ * ahead?: object}>} `ahead`: a baseline stamped newer than this code is
185
+ * left untouched.
127
186
  */
128
187
  export async function seatMissingBaseline({
129
188
  kind,
@@ -134,6 +193,33 @@ export async function seatMissingBaseline({
134
193
  cwd = process.cwd(),
135
194
  gitDiff = mergeBaseGitDiff,
136
195
  fs = nodeFs,
196
+ }) {
197
+ const prior = readPriorState(writePath, fs, kind);
198
+ if (prior.ahead) return handOff(prior.ahead);
199
+ assertCrapPriorCurrent(kind, prior.envelope);
200
+ return seatScoped({
201
+ kind,
202
+ writePath,
203
+ score,
204
+ baseRef,
205
+ headRef,
206
+ cwd,
207
+ gitDiff,
208
+ fs,
209
+ prior,
210
+ });
211
+ }
212
+
213
+ async function seatScoped({
214
+ kind,
215
+ writePath,
216
+ score,
217
+ baseRef,
218
+ headRef,
219
+ cwd,
220
+ gitDiff,
221
+ fs,
222
+ prior,
137
223
  }) {
138
224
  const files = await deriveScopeFromDiff({
139
225
  baseRef,
@@ -148,7 +234,7 @@ export async function seatMissingBaseline({
148
234
  ...row,
149
235
  path: canonicalizeBaselinePath(row.path ?? row.file),
150
236
  }));
151
- const priorEnvelope = readPriorEnvelope(writePath, fs);
237
+ const priorEnvelope = prior.envelope;
152
238
  const seated = selectMissingRows({
153
239
  kind,
154
240
  priorRows: priorEnvelope?.rows,
@@ -188,14 +274,14 @@ export async function runSeatMissing({
188
274
  );
189
275
  }
190
276
  try {
191
- const { seated } = await seat({
277
+ const result = await seat({
192
278
  kind,
193
279
  writePath,
194
280
  baseRef: diffScopeRef ?? `origin/${baseBranch}`,
195
281
  score: score ?? ((files) => resolveDefaultScorer(kind, { cwd })(files)),
196
282
  cwd,
197
283
  });
198
- logger.info(`[${label}] seated: ${seated}`);
284
+ logSeated(logger, label, result);
199
285
  return 0;
200
286
  } catch (err) {
201
287
  if (!(err instanceof SeatRefusal)) throw err;
@@ -226,3 +312,83 @@ export function seatMaintainabilityBaseline(
226
312
  cwd,
227
313
  });
228
314
  }
315
+
316
+ /** One coverage baseline row from a file's scores. */
317
+ const coverageRow = (relPath, s) => ({
318
+ path: relPath,
319
+ lines: s?.lines ?? 0,
320
+ branches: s?.branches ?? 0,
321
+ functions: s?.functions ?? 0,
322
+ });
323
+
324
+ /** @param {string} coveragePath @param {string[]} inScope @param {string} cwd */
325
+ function staleRefusal(coveragePath, inScope, cwd) {
326
+ return new SeatRefusal(
327
+ `[Coverage] --seat-missing refused: no coverage artifact at ${coveragePath} is fresh for the current tree ` +
328
+ `(in-scope files: ${inScope.join(', ')}).\n` +
329
+ `Fix: re-capture coverage for the current tree — node .agents/scripts/coverage-capture.js --cwd ${cwd}`,
330
+ );
331
+ }
332
+
333
+ /** Rows for the measured files; an unmeasured one is named, never seated. */
334
+ function measuredRows(scores, inScope, logger) {
335
+ const measured = inScope.filter((file) => Object.hasOwn(scores, file));
336
+ const unmeasured = inScope.filter((file) => !measured.includes(file));
337
+ if (unmeasured.length > 0) {
338
+ logger.info(
339
+ `[Coverage] not seated — the fresh artifact did not measure: ${unmeasured.join(', ')}`,
340
+ );
341
+ }
342
+ return measured.map((file) => coverageRow(file, scores[file]));
343
+ }
344
+
345
+ /**
346
+ * The coverage `--seat-missing` scorer: refuses unless a capture stamp is
347
+ * fresh (`targetDirs` is its digest scope); never seats an unmeasured file.
348
+ */
349
+ function buildCoverageSeatScorer(
350
+ { coveragePath, readCoverage },
351
+ { targetDirs, cwd, logger },
352
+ ) {
353
+ return (files) => {
354
+ const scope = buildScopePredicate(loadC8ScopeConfig(cwd));
355
+ const inScope = files.filter((file) => scope(file));
356
+ if (inScope.length === 0) return [];
357
+ if (!isCaptureFresh({ coveragePath, targetDirs }, { cwd })) {
358
+ throw staleRefusal(coveragePath, inScope, cwd);
359
+ }
360
+ const scores = scoreCoverageFinal({ raw: readCoverage(cwd), cwd, scope });
361
+ return measuredRows(scores, inScope, logger);
362
+ };
363
+ }
364
+
365
+ /**
366
+ * `update-coverage-baseline.js --seat-missing`: seat rows for the diff's
367
+ * files that have none. Resolves to the exit code.
368
+ *
369
+ * @param {string[]} argv
370
+ * @param {{ config?: object, cwd?: string, logger?: object }} [deps]
371
+ * @returns {Promise<number>}
372
+ */
373
+ export function seatCoverageBaseline(
374
+ argv,
375
+ { config = resolveConfig(), cwd = process.cwd(), logger = Logger } = {},
376
+ ) {
377
+ const quality = getQuality(config);
378
+ const targets = coverageUpdaterTargets(quality.coverage, cwd);
379
+ return runSeatMissing({
380
+ kind: 'coverage',
381
+ label: 'Coverage',
382
+ writePath: targets.absBaselinePath,
383
+ diffScopeRef: parseDiffScopeFlag(argv),
384
+ fullScope: argv.includes('--full-scope'),
385
+ baseBranch: config.project.baseBranch,
386
+ score: buildCoverageSeatScorer(targets, {
387
+ targetDirs: quality.crap.targetDirs,
388
+ cwd,
389
+ logger,
390
+ }),
391
+ cwd,
392
+ logger,
393
+ });
394
+ }