mandrel 2.111.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 (178) 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 +351 -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/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -10,6 +10,7 @@ import { getChangedFiles, resolveChangedFilesRef } from '../changed-files.js';
10
10
  * @param {{
11
11
  * crap: { incrementalCoverage?: { baselineJoin?: boolean, baseRef?: string } },
12
12
  * diffRef: string | null,
13
+ * baseBranch?: string,
13
14
  * cwd: string,
14
15
  * baselineRows: Array<object>,
15
16
  * getChangedFilesImpl?: typeof getChangedFiles,
@@ -19,15 +20,19 @@ import { getChangedFiles, resolveChangedFilesRef } from '../changed-files.js';
19
20
  export function resolveCrapPreviewIncremental({
20
21
  crap,
21
22
  diffRef,
23
+ baseBranch,
22
24
  cwd,
23
25
  baselineRows,
24
26
  getChangedFilesImpl = getChangedFiles,
25
27
  }) {
26
28
  if (crap.incrementalCoverage?.baselineJoin !== true) return null;
27
- const baseRef = resolveChangedFilesRef({ crap, ref: diffRef });
29
+ const ref = resolveChangedFilesRef({ crap, ref: diffRef, baseBranch });
30
+ return readTouched(getChangedFilesImpl, { ref, cwd }, baselineRows);
31
+ }
32
+
33
+ function readTouched(getChangedFilesImpl, query, baselineRows) {
28
34
  try {
29
- const touchedFiles = new Set(getChangedFilesImpl({ ref: baseRef, cwd }));
30
- return { touchedFiles, baselineRows };
35
+ return { touchedFiles: new Set(getChangedFilesImpl(query)), baselineRows };
31
36
  } catch {
32
37
  return null;
33
38
  }
@@ -15,11 +15,9 @@ import { CYCLOMATIC_CEILING } from '../cyclomatic-ceiling.js';
15
15
  import { resolveCrapPreviewIncremental } from './crap-preview-incremental.js';
16
16
  import { resolveCrapEnvOverrides } from './env-overrides.js';
17
17
  import {
18
- assessComparisonBasis,
19
18
  buildCrapReport,
20
19
  compareCrap,
21
20
  filterRowsByFileScope,
22
- suppressVerdicts,
23
21
  } from './kinds/crap.js';
24
22
 
25
23
  /**
@@ -59,6 +57,12 @@ export function listCyclomaticAdvisories(rows) {
59
57
  }));
60
58
  }
61
59
 
60
+ function loadPreviewCoverage(crap, cwd) {
61
+ const coveragePath =
62
+ crap.coveragePath ?? COVERAGE_CAPTURE_DEFAULTS.coveragePath;
63
+ return loadCoverage(path.resolve(cwd, coveragePath));
64
+ }
65
+
62
66
  /**
63
67
  * @param {{
64
68
  * crap: object,
@@ -67,6 +71,7 @@ export function listCyclomaticAdvisories(rows) {
67
71
  * scope: string,
68
72
  * diffRef: string|null,
69
73
  * baseline: { rows: object[] },
74
+ * baseBranch?: string,
70
75
  * }} opts
71
76
  * @returns {Promise<{ exitCode: number, envelope: object }>}
72
77
  */
@@ -77,15 +82,14 @@ export async function computeCrapPreviewScan({
77
82
  scope,
78
83
  diffRef,
79
84
  baseline,
85
+ baseBranch,
80
86
  }) {
81
87
  const targetDirs = Array.isArray(crap.targetDirs) ? crap.targetDirs : [];
82
88
  const crapIgnoreGlobs = Array.isArray(crap.ignoreGlobs)
83
89
  ? crap.ignoreGlobs
84
90
  : [];
85
91
  const requireCoverage = crap.requireCoverage !== false;
86
- const coveragePath =
87
- crap.coveragePath ?? COVERAGE_CAPTURE_DEFAULTS.coveragePath;
88
- const coverage = loadCoverage(path.resolve(cwd, coveragePath));
92
+ const coverage = loadPreviewCoverage(crap, cwd);
89
93
  // The configured tolerance keeps the preview aligned with the authoritative
90
94
  // gate: deltas at or under it are demoted, not failed.
91
95
  const { newMethodCeiling, tolerance } = resolveCrapEnvOverrides(
@@ -95,6 +99,7 @@ export async function computeCrapPreviewScan({
95
99
  const incremental = resolveCrapPreviewIncremental({
96
100
  crap,
97
101
  diffRef,
102
+ baseBranch,
98
103
  cwd,
99
104
  baselineRows: baseline.rows,
100
105
  });
@@ -123,17 +128,6 @@ export async function computeCrapPreviewScan({
123
128
  scopeInfo: { scope, diffRef },
124
129
  });
125
130
  envelope.cyclomaticAdvisories = listCyclomaticAdvisories(scan.rows);
126
- // Above the drifted-row ratio every verdict is an artefact of a mis-keyed
127
- // join: say so once and fail open.
128
- const basis = assessComparisonBasis(result, {
129
- captureScript: crap.captureScript,
130
- });
131
- if (!basis.sound) {
132
- return {
133
- exitCode: 0,
134
- envelope: suppressVerdicts(envelope, basis.diagnostic),
135
- };
136
- }
137
131
  const exitCode = hasCrapRegressions(result) ? 1 : 0;
138
132
  return { exitCode, envelope };
139
133
  }
@@ -20,6 +20,7 @@ import { isScorableSourceFile } from '../source-extensions.js';
20
20
  import { parseDiffScopeFlag } from './diff-scope-cli.js';
21
21
  import {
22
22
  checkSeatResolution,
23
+ isCaptureFresh,
23
24
  runSeatMissing,
24
25
  SeatRefusal,
25
26
  } from './seat-missing.js';
@@ -221,9 +222,6 @@ function buildCrapUpdaterScorer(
221
222
  };
222
223
  }
223
224
 
224
- /** Stamp scopes a capture may have written; any one fresh stamp suffices. */
225
- const CAPTURE_SCOPES = ['full', 'incremental', 'affected'];
226
-
227
225
  /**
228
226
  * The coverage artifact when any capture stamp marks it fresh for the
229
227
  * current tree; otherwise `null`.
@@ -233,16 +231,9 @@ const CAPTURE_SCOPES = ['full', 'incremental', 'affected'];
233
231
  * @returns {object|null}
234
232
  */
235
233
  function loadFreshCoverage(options, { isFresh, loadCoverage, cwd }) {
236
- const fresh = CAPTURE_SCOPES.some(
237
- (requireScope) =>
238
- isFresh({
239
- coveragePath: options.coveragePath,
240
- targetDirs: options.targetDirs,
241
- cwd,
242
- requireScope,
243
- }).fresh,
244
- );
245
- return fresh ? loadCoverage(path.resolve(cwd, options.coveragePath)) : null;
234
+ return isCaptureFresh(options, { isFresh, cwd })
235
+ ? loadCoverage(path.resolve(cwd, options.coveragePath))
236
+ : null;
246
237
  }
247
238
 
248
239
  /**
@@ -31,6 +31,7 @@ import {
31
31
  sortRows as coverageSortRows,
32
32
  } from './kinds/coverage.js';
33
33
  import {
34
+ aheadStampOf as crapAheadStampOf,
34
35
  applyEpsilon as crapApplyEpsilon,
35
36
  assertBaselineCompatible as crapAssertBaselineCompatible,
36
37
  compare as crapCompare,
@@ -102,9 +103,11 @@ function bindKindModule(members) {
102
103
  compare: members.compare,
103
104
  applyEpsilon: members.applyEpsilon,
104
105
  mergeRows: members.mergeRows,
105
- // Optional hooks: extra envelope stamps; refusal of an incompatible baseline.
106
+ // Optional hooks: extra envelope stamps; refusal of an incompatible
107
+ // baseline; a stamp newer than this code (hands off, never compared).
106
108
  envelopeExtras: members.envelopeExtras,
107
109
  assertBaselineCompatible: members.assertBaselineCompatible,
110
+ aheadStampOf: members.aheadStampOf,
108
111
  });
109
112
  }
110
113
 
@@ -135,6 +138,7 @@ const KIND_MODULES = Object.freeze({
135
138
  mergeRows: crapMergeRows,
136
139
  envelopeExtras: crapEnvelopeExtras,
137
140
  assertBaselineCompatible: crapAssertBaselineCompatible,
141
+ aheadStampOf: crapAheadStampOf,
138
142
  }),
139
143
  maintainability: bindKindModule({
140
144
  name: maintainabilityName,
@@ -242,6 +246,20 @@ export function checkBaselineSemantics(kind, baseline, ctx = {}) {
242
246
  return mod.assertBaselineCompatible(baseline, ctx);
243
247
  }
244
248
 
249
+ /**
250
+ * The kind's `aheadStampOf` hook over a raw (unvalidated) envelope; kinds
251
+ * without it are never ahead.
252
+ *
253
+ * @param {string} kind
254
+ * @param {unknown} envelope
255
+ * @returns {{baseline: string, running: string, message: string}|null}
256
+ */
257
+ export function checkBaselineAhead(kind, envelope) {
258
+ const mod = tryGetKindModule(kind);
259
+ if (typeof mod?.aheadStampOf !== 'function') return null;
260
+ return mod.aheadStampOf(envelope);
261
+ }
262
+
245
263
  /**
246
264
  * @param {string} kind
247
265
  * @param {string} baselineVersion
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The CRAP baseline's on-disk layout: `files` maps each canonical path, once,
3
+ * to its `{ "<method key>": <crap> }` entries, so each method sits on its own
4
+ * line and disjoint methods merge textually. A leaf: `codec.js` and the merge
5
+ * driver import it.
6
+ */
7
+
8
+ /**
9
+ * Path, then method key: the persisted order of both layouts.
10
+ *
11
+ * @param {{path: string, method: string}} a
12
+ * @param {{path: string, method: string}} b
13
+ * @returns {number}
14
+ */
15
+ export function compareCrapRows(a, b) {
16
+ if (a.path !== b.path) return a.path.localeCompare(b.path);
17
+ return a.method.localeCompare(b.method);
18
+ }
19
+
20
+ /**
21
+ * Null-prototype objects: a method named `__proto__` stays a plain key.
22
+ *
23
+ * @param {Array<{path: string, method: string, crap: number}>} rows
24
+ * @returns {Record<string, Record<string, number>>}
25
+ */
26
+ export function encodeCrapFiles(rows) {
27
+ const files = Object.create(null);
28
+ for (const { path, method, crap } of [...(rows ?? [])].sort(
29
+ compareCrapRows,
30
+ )) {
31
+ files[path] ??= Object.create(null);
32
+ files[path][method] = crap;
33
+ }
34
+ return files;
35
+ }
36
+
37
+ /**
38
+ * @param {Record<string, Record<string, number>>} files
39
+ * @returns {Array<{path: string, method: string, crap: number}>}
40
+ */
41
+ export function decodeCrapFiles(files) {
42
+ const rows = [];
43
+ for (const [path, methods] of Object.entries(files ?? {})) {
44
+ if (!methods || typeof methods !== 'object') continue;
45
+ for (const [method, crap] of Object.entries(methods)) {
46
+ rows.push({ path, method, crap });
47
+ }
48
+ }
49
+ return rows;
50
+ }
51
+
52
+ const OURS = '<<<<<<< ours';
53
+ const SPLIT = '=======';
54
+ const THEIRS = '>>>>>>> theirs';
55
+
56
+ /** A method's line in the grouped layout: `"<method key>": <crap>`. */
57
+ function crapLine(row) {
58
+ return ` ${JSON.stringify(row.method)}: ${JSON.stringify(row.crap)}`;
59
+ }
60
+
61
+ /**
62
+ * Git conflict markers around one method's line inside its path's block;
63
+ * every other line stays byte-identical.
64
+ *
65
+ * @param {string[]} lines The serialised envelope, split on `\n`.
66
+ * @param {{ours?: object, theirs?: object}} conflict
67
+ */
68
+ function markCrapConflict(lines, conflict) {
69
+ const placed = conflict.ours ?? conflict.theirs;
70
+ if (placed === undefined) return;
71
+ const header = lines.indexOf(` ${JSON.stringify(placed.path)}: {`);
72
+ if (header < 0) return;
73
+ const needle = crapLine(placed);
74
+ let i = header + 1;
75
+ // Scan to the block's closing brace: an earlier conflict's markers sit
76
+ // unindented inside the block and must not end the search.
77
+ while (i < lines.length && !lines[i].startsWith(' }')) {
78
+ if (lines[i] === needle || lines[i] === `${needle},`) break;
79
+ i += 1;
80
+ }
81
+ if (!lines[i]?.startsWith(needle)) return;
82
+ const suffix = lines[i].endsWith(',') ? ',' : '';
83
+ const side = (row) =>
84
+ row === undefined ? [] : [`${crapLine(row)}${suffix}`];
85
+ lines.splice(
86
+ i,
87
+ 1,
88
+ OURS,
89
+ ...side(conflict.ours),
90
+ SPLIT,
91
+ ...side(conflict.theirs),
92
+ THEIRS,
93
+ );
94
+ }
95
+
96
+ /** A block's lines as units: a shared line, or one hunk's two sides. */
97
+ function blockUnits(lines, start) {
98
+ const units = [];
99
+ let i = start;
100
+ while (i < lines.length && !lines[i].startsWith(' }')) {
101
+ const unit = lines[i] === OURS ? hunkUnit(lines, i) : sharedUnit(lines, i);
102
+ units.push(unit);
103
+ i = unit.next;
104
+ }
105
+ return { units, end: i };
106
+ }
107
+
108
+ /** A line both sides share. */
109
+ function sharedUnit(lines, i) {
110
+ return { at: i, next: i + 1, ours: [lines[i]], theirs: [lines[i]] };
111
+ }
112
+
113
+ /** One conflict hunk opening at `i`, split into its two sides. */
114
+ function hunkUnit(lines, i) {
115
+ const split = lines.indexOf(SPLIT, i);
116
+ const close = lines.indexOf(THEIRS, split);
117
+ return {
118
+ at: i,
119
+ next: close + 1,
120
+ ours: lines.slice(i + 1, split),
121
+ theirs: lines.slice(split + 1, close),
122
+ };
123
+ }
124
+
125
+ /** Every line but the side's last carries the separating comma. */
126
+ function terminate(side) {
127
+ return side.map(
128
+ (line, n) => `${line.replace(/,$/, '')}${n < side.length - 1 ? ',' : ''}`,
129
+ );
130
+ }
131
+
132
+ /**
133
+ * When a side deletes a block's trailing methods, the line before them keeps
134
+ * its comma; fold that tail into one hunk so either side parses as JSON.
135
+ */
136
+ function settleBlockTail(lines, filePath) {
137
+ const header = lines.indexOf(` ${JSON.stringify(filePath)}: {`);
138
+ if (header < 0) return;
139
+ const { units, end } = blockUnits(lines, header + 1);
140
+ const from = tailStart(units);
141
+ if (from >= units.length - 1) return;
142
+ const span = units.slice(from);
143
+ lines.splice(span[0].at, end - span[0].at, ...hunkOf(span));
144
+ }
145
+
146
+ /** The first unit after which some side carries no more lines. */
147
+ function tailStart(units) {
148
+ const lastWith = (side) => units.findLastIndex((u) => u[side].length > 0);
149
+ return Math.max(Math.min(lastWith('ours'), lastWith('theirs')), 0);
150
+ }
151
+
152
+ /** One conflict hunk joining the units' sides, each comma-terminated. */
153
+ function hunkOf(span) {
154
+ const side = (key) => terminate(span.flatMap((u) => u[key]));
155
+ return [OURS, ...side('ours'), SPLIT, ...side('theirs'), THEIRS];
156
+ }
157
+
158
+ /**
159
+ * Render every row conflict of a merged grouped-layout CRAP file.
160
+ *
161
+ * @param {string} text
162
+ * @param {Array<{ours?: object, theirs?: object}>} conflicts
163
+ * @returns {string}
164
+ */
165
+ export function renderCrapConflicts(text, conflicts) {
166
+ const lines = text.split('\n');
167
+ for (const conflict of conflicts) markCrapConflict(lines, conflict);
168
+ const paths = conflicts.map((c) => (c.ours ?? c.theirs)?.path);
169
+ for (const filePath of new Set(paths)) settleBlockTail(lines, filePath);
170
+ return lines.join('\n');
171
+ }
@@ -11,6 +11,52 @@ import {
11
11
  load as loadBaselineKind,
12
12
  } from '../reader.js';
13
13
 
14
+ /**
15
+ * Scoring-semantics stamp. The scorer version does not move when this repo's
16
+ * coverage join changes, yet rows scored under different joins are not
17
+ * comparable (phantom regressions and phantom passes), so the stamp fails
18
+ * closed across that boundary. Bump it whenever the coverage join, the line
19
+ * coordinate system, the unresolved-method policy, or the method identity
20
+ * rule changes. Read it via `envelopeExtras().scoringSemantics`.
21
+ */
22
+ export const SCORING_SEMANTICS = 'method-identity-v5';
23
+
24
+ const STAMP_RE = /^method-identity-v(\d+)$/;
25
+
26
+ /**
27
+ * Order a baseline's `scoringSemantics` against the running stamp: `ahead`
28
+ * only for a higher `method-identity-v<N>`; any other mismatch is `behind`.
29
+ *
30
+ * @param {unknown} stamp
31
+ * @returns {'current'|'ahead'|'behind'}
32
+ */
33
+ export function classifyScoringSemantics(stamp) {
34
+ if (stamp === SCORING_SEMANTICS) return 'current';
35
+ const theirs = STAMP_RE.exec(typeof stamp === 'string' ? stamp : '');
36
+ const ours = STAMP_RE.exec(SCORING_SEMANTICS);
37
+ return theirs && Number(theirs[1]) > Number(ours[1]) ? 'ahead' : 'behind';
38
+ }
39
+
40
+ /**
41
+ * A raw envelope stamped ahead of this code: no CRAP path writes or compares
42
+ * it, whatever its layout. `null` when not ahead.
43
+ *
44
+ * @param {unknown} envelope Parsed JSON, unvalidated.
45
+ * @returns {{baseline: string, running: string, message: string}|null}
46
+ */
47
+ export function aheadStampOf(envelope) {
48
+ const stamp = envelope?.scoringSemantics;
49
+ if (classifyScoringSemantics(stamp) !== 'ahead') return null;
50
+ return {
51
+ baseline: stamp,
52
+ running: SCORING_SEMANTICS,
53
+ message:
54
+ `[CRAP] gate skipped: baseline scoringSemantics=${stamp} is ahead of ` +
55
+ `running=${SCORING_SEMANTICS}, so this code leaves the baseline untouched ` +
56
+ "and compares nothing; CI, running the branch's own code, is the check of record.",
57
+ };
58
+ }
59
+
14
60
  /**
15
61
  * Read the working-tree baseline, projected onto the `file`-keyed comparator
16
62
  * shape. `null` on any failure; the preview gate then fails open.
@@ -40,30 +86,18 @@ function readCrapBaselineFromTree({ baselinePath, projectRoot } = {}) {
40
86
  typeof envelope.tsTranspilerVersion === 'string'
41
87
  ? envelope.tsTranspilerVersion
42
88
  : null,
43
- provenanceStamped: envelope.provenanceStamped,
44
89
  rows: (envelope.rows ?? []).map(projectBaselineRow),
45
90
  };
46
91
  }
47
92
 
48
93
  /**
49
- * Re-key `path` to `file`, carrying `coordinateSystem` and `anonymous`
50
- * verbatim: dropping either breaks a compat axis or the comparator.
94
+ * Re-key `path` to `file`, the field the comparator matches on.
51
95
  *
52
- * @param {{path: string, method: string, startLine: number, crap: number,
53
- * coordinateSystem?: string, anonymous?: boolean}} row
54
- * @returns {object}
96
+ * @param {{path: string, method: string, crap: number}} row
97
+ * @returns {{file: string, method: string, crap: number}}
55
98
  */
56
99
  function projectBaselineRow(row) {
57
- return {
58
- crap: row.crap,
59
- file: row.path,
60
- method: row.method,
61
- startLine: row.startLine,
62
- ...(row.coordinateSystem === undefined
63
- ? {}
64
- : { coordinateSystem: row.coordinateSystem }),
65
- ...(row.anonymous === undefined ? {} : { anonymous: row.anonymous }),
66
- };
100
+ return { crap: row.crap, file: row.path, method: row.method };
67
101
  }
68
102
 
69
103
  /**
@@ -89,6 +123,12 @@ export function loadCrapBaseline({
89
123
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
90
124
  return null;
91
125
  }
126
+ // A newer layout is the caller's to skip, not a shape failure.
127
+ return aheadStampOf(parsed) ? parsed : shapeCheckedAtRef(parsed);
128
+ }
129
+
130
+ /** The ref read's shape-check and `tsTranspilerVersion` back-fill. */
131
+ function shapeCheckedAtRef(parsed) {
92
132
  if (typeof parsed.kernelVersion !== 'string') return null;
93
133
  if (typeof parsed.escomplexVersion !== 'string') return null;
94
134
  if (!Array.isArray(parsed.rows)) return null;
@@ -79,65 +79,6 @@ export function makeRollup({ aggregate }) {
79
79
  };
80
80
  }
81
81
 
82
- /**
83
- * A removed base row is an improvement only when `removedIsImprovement` says
84
- * so; otherwise it is unchanged.
85
- *
86
- * @param {{
87
- * identity: (row: object) => string,
88
- * betterIsHigher: boolean,
89
- * metricField: string,
90
- * removedIsImprovement?: (row: object) => boolean
91
- * }} opts
92
- * @returns {(head: object, base: object) => {
93
- * regressions: object[], improvements: object[],
94
- * unchanged: object[], additions: object[]
95
- * }}
96
- */
97
- export function makeCompare({
98
- identity,
99
- betterIsHigher,
100
- metricField,
101
- removedIsImprovement = () => false,
102
- }) {
103
- return function compare(head, base) {
104
- const headRows = Array.isArray(head?.rows) ? head.rows : [];
105
- const baseRows = Array.isArray(base?.rows) ? base.rows : [];
106
- const baseByKey = new Map();
107
- for (const r of baseRows) baseByKey.set(identity(r), r);
108
- const seen = new Set();
109
- const regressions = [];
110
- const improvements = [];
111
- const unchanged = [];
112
- const additions = [];
113
- for (const h of headRows) {
114
- const key = identity(h);
115
- seen.add(key);
116
- const b = baseByKey.get(key);
117
- if (!b) {
118
- additions.push({ key, head: h, base: null });
119
- continue;
120
- }
121
- const delta = (h[metricField] ?? 0) - (b[metricField] ?? 0);
122
- const regressed = betterIsHigher ? delta < 0 : delta > 0;
123
- const improved = betterIsHigher ? delta > 0 : delta < 0;
124
- if (regressed) regressions.push({ key, head: h, base: b });
125
- else if (improved) improvements.push({ key, head: h, base: b });
126
- else unchanged.push({ key, head: h, base: b });
127
- }
128
- for (const b of baseRows) {
129
- const key = identity(b);
130
- if (seen.has(key)) continue;
131
- if (removedIsImprovement(b)) {
132
- improvements.push({ key, head: null, base: b });
133
- } else {
134
- unchanged.push({ key, head: null, base: b });
135
- }
136
- }
137
- return { regressions, improvements, unchanged, additions };
138
- };
139
- }
140
-
141
82
  /**
142
83
  * Within epsilon, the prior row object is returned so its bytes are kept.
143
84
  *