mandrel 2.110.0 → 2.112.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 (190) 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/audit-checklists/state-machines.md +21 -0
  6. package/.agents/docs/agentrc-reference.json +23 -10
  7. package/.agents/docs/configuration.md +362 -15
  8. package/.agents/docs/execution-reference.md +11 -0
  9. package/.agents/docs/workflows.md +2 -1
  10. package/.agents/rules/ci-remediation.md +28 -4
  11. package/.agents/rules/git-conventions-reference.md +7 -0
  12. package/.agents/schemas/agentrc.schema.json +179 -13
  13. package/.agents/schemas/audit-rules.json +28 -0
  14. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  15. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  16. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  17. package/.agents/schemas/baselines/crap.schema.json +37 -10
  18. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  19. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  20. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  21. package/.agents/schemas/crap-report.schema.json +6 -5
  22. package/.agents/schemas/story-deliver-terminal.schema.json +49 -3
  23. package/.agents/schemas/story-progress.schema.json +1 -1
  24. package/.agents/schemas/validation-evidence.schema.json +2 -2
  25. package/.agents/scripts/boot-sweep.js +41 -3
  26. package/.agents/scripts/coverage-capture.js +39 -3
  27. package/.agents/scripts/coverage-ratchet.js +106 -0
  28. package/.agents/scripts/evidence-gate.js +84 -21
  29. package/.agents/scripts/file-ci-gap.js +220 -10
  30. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  31. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  32. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  33. package/.agents/scripts/lib/baseline-loader.js +4 -2
  34. package/.agents/scripts/lib/baselines/codec.js +57 -0
  35. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  36. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  37. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  38. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  39. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  40. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  41. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  42. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  43. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  44. package/.agents/scripts/lib/baselines/reader.js +36 -9
  45. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  46. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  47. package/.agents/scripts/lib/baselines/writer.js +36 -21
  48. package/.agents/scripts/lib/changed-files.js +70 -6
  49. package/.agents/scripts/lib/child-exec.js +10 -0
  50. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  51. package/.agents/scripts/lib/close-lock-events.js +8 -3
  52. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  53. package/.agents/scripts/lib/close-validation/gates.js +156 -32
  54. package/.agents/scripts/lib/close-validation/process.js +16 -7
  55. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  56. package/.agents/scripts/lib/close-validation/runner.js +160 -41
  57. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  58. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  59. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  60. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  61. package/.agents/scripts/lib/config/explain.js +5 -2
  62. package/.agents/scripts/lib/config/gates/coverage.schema.js +53 -0
  63. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  64. package/.agents/scripts/lib/config/git-roots.js +38 -4
  65. package/.agents/scripts/lib/config/handoff.js +24 -0
  66. package/.agents/scripts/lib/config/quality.js +28 -12
  67. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  68. package/.agents/scripts/lib/config-resolver.js +22 -2
  69. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  70. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  71. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  73. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  74. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  75. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  76. package/.agents/scripts/lib/coverage-capture.js +31 -0
  77. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  78. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  79. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  80. package/.agents/scripts/lib/crap-engine.js +3 -3
  81. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  82. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  83. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  84. package/.agents/scripts/lib/failure-rows.js +121 -0
  85. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  86. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  87. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  88. package/.agents/scripts/lib/gh-env.js +3 -6
  89. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  90. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  91. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  92. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  93. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  94. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  95. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  96. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  97. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  102. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  103. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  104. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +124 -23
  105. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  106. package/.agents/scripts/lib/orchestration/handoff-gates.js +217 -44
  107. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  108. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  109. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -1
  110. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +76 -4
  111. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +2 -2
  112. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  113. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  114. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  115. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  116. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  117. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  118. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  119. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  120. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  121. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  122. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  123. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  124. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  125. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  127. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +17 -2
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +13 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +17 -2
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +42 -20
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -1
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +51 -15
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  140. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  141. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  142. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  143. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  144. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  145. package/.agents/scripts/lib/orchestration/single-story-close/result.js +43 -13
  146. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  147. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -2
  148. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  149. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  150. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  151. package/.agents/scripts/lib/orchestration/story-handoff.js +789 -196
  152. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  153. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  154. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  155. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  156. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  157. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  158. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  159. package/.agents/scripts/lib/suite-admission.js +20 -8
  160. package/.agents/scripts/lib/suite-sizing.js +146 -0
  161. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  162. package/.agents/scripts/merge-baseline.js +14 -3
  163. package/.agents/scripts/providers/github/comments.js +19 -3
  164. package/.agents/scripts/providers/github.js +1 -0
  165. package/.agents/scripts/review-dispositions-report.js +1 -1
  166. package/.agents/scripts/role-scope-guard.js +267 -0
  167. package/.agents/scripts/single-story-close.js +4 -4
  168. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  169. package/.agents/scripts/single-story-init.js +24 -4
  170. package/.agents/scripts/story-handoff.js +3 -3
  171. package/.agents/scripts/story-outcomes-report.js +231 -0
  172. package/.agents/scripts/story-review-compute.js +9 -5
  173. package/.agents/scripts/update-coverage-baseline.js +12 -2
  174. package/.agents/scripts/update-crap-baseline.js +9 -1
  175. package/.agents/workflows/audit-state-machines.md +213 -0
  176. package/.agents/workflows/helpers/code-review.md +63 -9
  177. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  178. package/.agents/workflows/helpers/deliver-reference.md +236 -63
  179. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  180. package/.agents/workflows/helpers/deliver-story.md +7 -2
  181. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  182. package/.agents/workflows/helpers/plan-reference.md +10 -2
  183. package/docs/CHANGELOG.md +56 -0
  184. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  185. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  186. package/lib/cli/doctor-checks/llm-review.js +2 -11
  187. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  188. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  189. package/lib/cli/registry.js +5 -0
  190. package/package.json +1 -1
@@ -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,6 +288,32 @@ 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`
@@ -313,9 +340,12 @@ function defaultExtrasContext(kind, cwd) {
313
340
  * kind: string,
314
341
  * writePath: string,
315
342
  * scope: { mode: 'full' | 'diff' | 'explicit', ref?: string, files: string[] },
316
- * envelope: object,
343
+ * envelope: object | null,
317
344
  * wrote: boolean,
318
- * }>}
345
+ * partners?: Record<string, string[]>,
346
+ * ahead?: object,
347
+ * }>} `partners`: each write-scope file's scored clone partners. `ahead` (with a null `envelope`): a narrower-than-full refresh left a
348
+ * baseline stamped newer than this code untouched.
319
349
  */
320
350
  export async function refreshBaseline(opts = {}) {
321
351
  const {
@@ -337,12 +367,17 @@ export async function refreshBaseline(opts = {}) {
337
367
 
338
368
  validateOptions({ kind, scopeFiles, fullScope, writePath });
339
369
 
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
- }
370
+ const prior = readPriorState(writePath, fs, kind);
371
+ const handedOff = aheadHandOff({
372
+ prior,
373
+ fullScope,
374
+ kind,
375
+ writePath,
376
+ scopeFiles,
377
+ });
378
+ if (handedOff) return handedOff;
379
+
380
+ const resolvedScorer = requireScorer(kind, scorer, cwd);
346
381
 
347
382
  const scope = await resolveScope({
348
383
  kind,
@@ -378,7 +413,7 @@ export async function refreshBaseline(opts = {}) {
378
413
  requiredScopeFilePredicate,
379
414
  });
380
415
 
381
- const priorEnvelope = readPriorEnvelope(writePath, fs);
416
+ const priorEnvelope = prior.envelope;
382
417
  const writeFiles = resolveWriteScopeFiles({
383
418
  kind,
384
419
  scope,
@@ -417,9 +452,21 @@ export async function refreshBaseline(opts = {}) {
417
452
  },
418
453
  envelope,
419
454
  wrote,
455
+ partners: partnersOf(canonicalRows, writeFiles),
420
456
  };
421
457
  }
422
458
 
459
+ /** Each listed file's scored clone partners; the envelope never stores them. */
460
+ function partnersOf(rows, files) {
461
+ const byPath = new Map(rows.map((row) => [row.path, row.partners]));
462
+ const out = {};
463
+ for (const file of files) {
464
+ const partners = byPath.get(file);
465
+ if (partners?.length) out[file] = partners.map(canonicalizeBaselinePath);
466
+ }
467
+ return out;
468
+ }
469
+
423
470
  /**
424
471
  * The files whose rows a scoped refresh rewrites. Duplication is pairwise, so
425
472
  * a changed file also moves the rows of files it shares (or shared) a clone
@@ -631,20 +678,34 @@ async function resolveScope({
631
678
  * @returns {object | null}
632
679
  */
633
680
  export function readPriorEnvelope(writePath, fs) {
681
+ return readPriorState(writePath, fs).envelope;
682
+ }
683
+
684
+ /**
685
+ * The prior envelope (as {@link readPriorEnvelope}), or `ahead` when its stamp
686
+ * is newer than this code: then `envelope` is null and nothing may write it
687
+ * short of a full-scope re-seed.
688
+ *
689
+ * @param {string} writePath
690
+ * @param {typeof nodeFs} fs
691
+ * @param {string} [kind]
692
+ * @returns {{envelope: object|null, ahead: object|null}}
693
+ */
694
+ export function readPriorState(writePath, fs, kind) {
634
695
  let raw;
635
696
  try {
636
- raw = fs.readFileSync(writePath, 'utf8');
697
+ raw = JSON.parse(fs.readFileSync(writePath, 'utf8'));
637
698
  } catch {
638
- return null;
699
+ return { envelope: null, ahead: null };
639
700
  }
701
+ const ahead = kind ? checkBaselineAhead(kind, raw) : null;
702
+ if (ahead) return { envelope: null, ahead };
640
703
  try {
641
- const parsed = JSON.parse(raw);
642
- if (isObject(parsed) && Array.isArray(parsed.rows)) {
643
- return parsed;
644
- }
645
- return null;
704
+ const parsed = decodeEnvelope(raw);
705
+ const valid = isObject(parsed) && Array.isArray(parsed.rows);
706
+ return { envelope: valid ? parsed : null, ahead: null };
646
707
  } catch {
647
- return null;
708
+ return { envelope: null, ahead: null };
648
709
  }
649
710
  }
650
711
 
@@ -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
+ }
@@ -9,6 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { deepEqual, isObject } from '../json-utils.js';
11
11
  import { writeFileAtomic } from '../util/atomic-write.js';
12
+ import { encodeEnvelope } from './codec.js';
12
13
  import { assertEnvelope, buildEnvelope } from './envelope.js';
13
14
  import { currentKernelVersion, getKindModule } from './kernel.js';
14
15
  import { assertCanonical } from './path-canon.js';
@@ -73,12 +74,18 @@ export function write({
73
74
  });
74
75
  }
75
76
 
77
+ const priorEnv = resolvePriorEnvelope(priorEnvelope, prior);
78
+ const extras =
79
+ typeof mod.envelopeExtras === 'function'
80
+ ? mod.envelopeExtras(extrasContext)
81
+ : null;
82
+ assertScopedSemantics(kind, scope, priorEnv, extras);
83
+
76
84
  const merged = scopeMergeRows(mod, projected, prior, scope);
77
85
  const stabilised = stabiliseRows(mod, merged, prior, epsilon);
78
86
 
79
87
  const sortedRows = mod.sortRows(stabilised);
80
88
 
81
- const priorEnv = resolvePriorEnvelope(priorEnvelope, prior);
82
89
  if (priorEnv && deepEqual(sortedRows, priorEnv.rows)) {
83
90
  // No smuggling an invalid envelope through the short-circuit.
84
91
  assertEnvelope(priorEnv);
@@ -89,15 +96,30 @@ export function write({
89
96
  kind,
90
97
  rows: sortedRows,
91
98
  kernelVersion: kernelVersion ?? currentKernelVersion(kind),
92
- extras:
93
- typeof mod.envelopeExtras === 'function'
94
- ? mod.envelopeExtras(extrasContext)
95
- : null,
99
+ extras,
96
100
  });
97
101
  assertEnvelope(envelope);
98
102
  return envelope;
99
103
  }
100
104
 
105
+ /**
106
+ * A scoped write keeps out-of-scope prior rows verbatim but stamps the
107
+ * running semantics, so across a semantics boundary it would hide a
108
+ * half-migrated baseline behind a current stamp. Refuse it.
109
+ */
110
+ function assertScopedSemantics(kind, scope, priorEnv, extras) {
111
+ const running = extras?.scoringSemantics;
112
+ if (!scope || scope.mode === 'full' || !priorEnv || !running) return;
113
+ const stamped = priorEnv.scoringSemantics ?? null;
114
+ if (stamped === running) return;
115
+ throw new Error(
116
+ `writer.write: refusing a scoped ${kind} refresh across a scoring-semantics ` +
117
+ `change (baseline=${stamped ?? '<unstamped>'} running=${running}): ` +
118
+ 'out-of-scope rows would keep the old semantics under the new stamp. ' +
119
+ 'Re-seed the whole baseline with a --full-scope refresh.',
120
+ );
121
+ }
122
+
101
123
  /** `priorEnvelope`, else `prior` when it is a whole envelope, else null. */
102
124
  function resolvePriorEnvelope(priorEnvelope, prior) {
103
125
  if (isEnvelopeObject(priorEnvelope)) return priorEnvelope;
@@ -110,8 +132,8 @@ function isEnvelopeObject(value) {
110
132
  }
111
133
 
112
134
  /**
113
- * Serialise deterministically (fixed top-level key order, two-space indent,
114
- * trailing newline) and atomically (tmp + rename).
135
+ * Serialise through the layout codec deterministically (fixed top-level key
136
+ * order, two-space indent, trailing newline) and atomically (tmp + rename).
115
137
  *
116
138
  * @param {string} absPath
117
139
  * @param {object} envelope
@@ -129,20 +151,13 @@ export function writeFile(absPath, envelope, opts = {}) {
129
151
 
130
152
  const fsImpl = opts?.fsImpl ? opts.fsImpl : fs;
131
153
 
132
- // A kind's envelope stamp reaches disk only if named here — add every new
133
- // `envelopeExtras()` key. Unset stamps are undefined and JSON omits them.
134
- const canonical = {
135
- $schema: envelope.$schema,
136
- kernelVersion: envelope.kernelVersion,
137
- scoringSemantics: envelope.scoringSemantics,
138
- tsTranspilerVersion: envelope.tsTranspilerVersion,
139
- provenanceStamped: envelope.provenanceStamped,
140
- rows: envelope.rows,
141
- };
142
-
143
- writeFileAtomic(absPath, `${JSON.stringify(canonical, null, 2)}\n`, {
144
- fsImpl,
145
- });
154
+ writeFileAtomic(
155
+ absPath,
156
+ `${JSON.stringify(encodeEnvelope(envelope), null, 2)}\n`,
157
+ {
158
+ fsImpl,
159
+ },
160
+ );
146
161
  return absPath;
147
162
  }
148
163