mandrel 2.87.0 → 2.89.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 (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -9,7 +9,7 @@ import path from 'node:path';
9
9
  import { getBaselines, getQuality, resolveConfig } from '../config-resolver.js';
10
10
  import {
11
11
  isCoverageFresh,
12
- missingCoverageArtifactMessage,
12
+ MissingCoverageArtifactError,
13
13
  } from '../coverage-capture.js';
14
14
  import { loadCoverage as loadCoverageDefault } from '../coverage-utils.js';
15
15
  import { checkResolutionFloor, scanAndScore } from '../crap-utils.js';
@@ -91,6 +91,7 @@ export function resolveCrapUpdaterOptions(
91
91
  minMethodResolutionRate:
92
92
  crap.minMethodResolutionRate ?? DEFAULT_MIN_RESOLUTION_RATE,
93
93
  coveragePath,
94
+ captureScript: crap.captureScript ?? 'test:coverage',
94
95
  baselinePath,
95
96
  absBaselinePath: path.isAbsolute(baselinePath)
96
97
  ? baselinePath
@@ -136,40 +137,51 @@ function reportScanSummary(summary, logger = Logger) {
136
137
  }
137
138
  }
138
139
 
140
+ /** @param {string} coverageAbs */
141
+ function refuseMissingCoverage(coverageAbs) {
142
+ throw new MissingCoverageArtifactError(coverageAbs, { prefix: '[CRAP] ' });
143
+ }
144
+
139
145
  /**
140
- * No artifact under `requireCoverage`: a full-scope refresh throws naming the
141
- * capture contract (zero rows would write an empty baseline); a scoped one
142
- * warns and yields no rows.
146
+ * `refreshBaseline` options for the CRAP updater. With no scope flag the
147
+ * service derives the diff via `origin/main..HEAD` (its default refs). The
148
+ * transpiler stamp resolves from the anchors the scorer resolves compilers
149
+ * from: the target dirs and the project root.
143
150
  *
144
- * @param {string} coverageAbs
145
- * @param {{ coveragePath: string }} options
146
- * @param {{ fullScope?: boolean } | undefined} opts
147
- * @param {{ warn: Function }} logger
148
- * @returns {object[]}
151
+ * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
152
+ * @param {{loadCoverage: Function, epsilon?: number, cwd?: string,
153
+ * scan?: Function, logger?: object}} deps
154
+ * @returns {object}
149
155
  */
150
- function noCoverageRows(coverageAbs, options, opts, logger) {
151
- if (opts?.fullScope) {
152
- throw new Error(`[CRAP] ${missingCoverageArtifactMessage(coverageAbs)}`);
153
- }
154
- logger.warn(
155
- `[CRAP] ⚠ No coverage artifact at ${options.coveragePath}. All files will be skipped under requireCoverage=true.`,
156
- );
157
- logger.warn(
158
- "[CRAP] ⚠ Run 'npm run test:coverage' before 'npm run crap:update'.",
159
- );
160
- return [];
156
+ export function buildCrapRefreshOptions(
157
+ options,
158
+ { epsilon, cwd = process.cwd(), ...scorerDeps },
159
+ ) {
160
+ return {
161
+ kind: 'crap',
162
+ writePath: options.absBaselinePath,
163
+ epsilon,
164
+ scorer: buildCrapUpdaterScorer(options, scorerDeps),
165
+ extrasContext: { cwd, targetDirs: options.targetDirs },
166
+ ...scopeFields(options),
167
+ };
168
+ }
169
+
170
+ function scopeFields({ fullScope, diffScopeRef }) {
171
+ if (fullScope) return { fullScope: true };
172
+ return diffScopeRef ? { baseRef: diffScopeRef } : {};
161
173
  }
162
174
 
163
175
  /**
164
176
  * Fails closed on a missing coverage artifact under `requireCoverage` (throws
165
- * on a full-scope refresh; warns with no rows on a scoped one) and on a resolution rate below the floor (throws before anything is
166
- * written: a broken join is wrong, not sparse).
177
+ * on every scope) and on a resolution rate below the floor (throws before
178
+ * anything is written: a broken join is wrong, not sparse).
167
179
  *
168
180
  * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
169
181
  * @param {{loadCoverage: Function, scan?: Function, logger?: object}} deps
170
182
  * @returns {(files: string[], opts: object) => Promise<object[]>}
171
183
  */
172
- export function buildCrapUpdaterScorer(
184
+ function buildCrapUpdaterScorer(
173
185
  options,
174
186
  { loadCoverage, scan = scanAndScore, logger = Logger } = {},
175
187
  ) {
@@ -179,9 +191,8 @@ export function buildCrapUpdaterScorer(
179
191
  ? options.coveragePath
180
192
  : path.resolve(effectiveCwd, options.coveragePath);
181
193
  const coverage = loadCoverage(coverageAbs);
182
- if (!coverage && options.requireCoverage) {
183
- return noCoverageRows(coverageAbs, options, opts, logger);
184
- }
194
+ if (!coverage && options.requireCoverage)
195
+ refuseMissingCoverage(coverageAbs);
185
196
 
186
197
  const summary = await scan({
187
198
  targetDirs: options.targetDirs,
@@ -198,6 +209,7 @@ export function buildCrapUpdaterScorer(
198
209
  const refusal = checkResolutionFloor(
199
210
  summary.resolution,
200
211
  options.minMethodResolutionRate,
212
+ options.captureScript,
201
213
  );
202
214
  if (refusal) throw new Error(refusal);
203
215
 
@@ -105,11 +105,13 @@ function cloneLineNumbers(dup, maxLine) {
105
105
  /**
106
106
  * Pure. Both sides of each clone pair accrue lines; overlapping clones are
107
107
  * unioned per file so a line counts once. Every counted file gets a row.
108
+ * `partners` names the other files sharing a clone with this one; the
109
+ * refresh service widens a diff scope with it, and `projectRow` drops it.
108
110
  *
109
111
  * @param {Array<{duplicationA?: object, duplicationB?: object}>} clones
110
112
  * @param {Map<string, number>|Record<string, number>} fileLineCounts
111
113
  * @param {string} [cwd]
112
- * @returns {Array<{path: string, duplicatedLines: number, totalLines: number, percentage: number}>}
114
+ * @returns {Array<{path: string, duplicatedLines: number, totalLines: number, percentage: number, partners: string[]}>}
113
115
  */
114
116
  export function buildDuplicationRows(
115
117
  clones,
@@ -118,19 +120,23 @@ export function buildDuplicationRows(
118
120
  ) {
119
121
  const counts = toLineCountMap(fileLineCounts);
120
122
  const dupLinesByFile = new Map();
123
+ const partnersByFile = new Map();
121
124
  // Seed every visited file with an empty set so clean files get a 0-row.
122
125
  for (const file of counts.keys()) {
123
126
  dupLinesByFile.set(file, new Set());
124
127
  }
125
128
  for (const clone of clones ?? []) {
129
+ const files = [];
126
130
  for (const side of [clone?.duplicationA, clone?.duplicationB]) {
127
131
  if (!side) continue;
128
132
  const file = relativisePath(side.sourceId, cwd);
129
133
  if (!file) continue;
134
+ files.push(file);
130
135
  const set = dupLinesByFile.get(file) ?? new Set();
131
136
  for (const n of cloneLineNumbers(side, counts.get(file))) set.add(n);
132
137
  dupLinesByFile.set(file, set);
133
138
  }
139
+ addClonePartners(partnersByFile, files);
134
140
  }
135
141
  const rows = [];
136
142
  for (const [file, lineSet] of dupLinesByFile) {
@@ -143,11 +149,24 @@ export function buildDuplicationRows(
143
149
  duplicatedLines,
144
150
  totalLines,
145
151
  percentage: Number(percentage.toFixed(2)),
152
+ partners: [...(partnersByFile.get(file) ?? [])].sort(),
146
153
  });
147
154
  }
148
155
  return rows;
149
156
  }
150
157
 
158
+ /**
159
+ * @param {Map<string, Set<string>>} partnersByFile
160
+ * @param {string[]} files both sides of one clone
161
+ */
162
+ function addClonePartners(partnersByFile, files) {
163
+ for (const file of files) {
164
+ const partners = partnersByFile.get(file) ?? new Set();
165
+ for (const other of files) if (other !== file) partners.add(other);
166
+ partnersByFile.set(file, partners);
167
+ }
168
+ }
169
+
151
170
  function toLineCountMap(fileLineCounts) {
152
171
  if (fileLineCounts instanceof Map) return fileLineCounts;
153
172
  const map = new Map();
@@ -9,6 +9,30 @@ import { Logger } from '../Logger.js';
9
9
  // the pre-push hook from ratcheting on noise.
10
10
  const MI_DEFAULT_TOLERANCE = 0.5;
11
11
 
12
+ /**
13
+ * A non-negative numeric env override of `key`, or `current` (with a warning)
14
+ * when the value is malformed. An unset or empty var keeps `current` silently.
15
+ *
16
+ * @param {{ env: NodeJS.ProcessEnv, varName: string, key: string, current: number, overrides: string[] }} opts
17
+ * @returns {number}
18
+ */
19
+ function readNonNegativeEnv({ env, varName, key, current, overrides }) {
20
+ const raw = env?.[varName];
21
+ if (raw === undefined || raw === '') return current;
22
+ const parsed = Number(raw);
23
+ if (Number.isFinite(parsed) && parsed >= 0) {
24
+ overrides.push(`${key}=${parsed} (${varName})`);
25
+ return parsed;
26
+ }
27
+ Logger.warn(
28
+ `[CRAP] ⚠ ignoring malformed ${varName}=${raw}; keeping config value ${current}`,
29
+ );
30
+ return current;
31
+ }
32
+
33
+ const finiteOr = (value, fallback) =>
34
+ Number.isFinite(value) ? value : fallback;
35
+
12
36
  /**
13
37
  * @param {{ newMethodCeiling?: unknown, tolerance?: unknown, refreshTag?: unknown }} crapConfig
14
38
  * @param {NodeJS.ProcessEnv} env
@@ -16,46 +40,27 @@ const MI_DEFAULT_TOLERANCE = 0.5;
16
40
  */
17
41
  export function resolveCrapEnvOverrides(crapConfig, env) {
18
42
  const overrides = [];
19
- let newMethodCeiling = Number.isFinite(crapConfig?.newMethodCeiling)
20
- ? crapConfig.newMethodCeiling
21
- : 30;
43
+ const newMethodCeiling = readNonNegativeEnv({
44
+ env,
45
+ varName: 'CRAP_NEW_METHOD_CEILING',
46
+ key: 'newMethodCeiling',
47
+ current: finiteOr(crapConfig?.newMethodCeiling, 30),
48
+ overrides,
49
+ });
22
50
  // Coverage rounding across CI environments shifts a CRAP score by ~0.01;
23
51
  // real regressions cross whole integers and clear 0.05 trivially.
24
- let tolerance = Number.isFinite(crapConfig?.tolerance)
25
- ? crapConfig.tolerance
26
- : 0.05;
52
+ const tolerance = readNonNegativeEnv({
53
+ env,
54
+ varName: 'CRAP_TOLERANCE',
55
+ key: 'tolerance',
56
+ current: finiteOr(crapConfig?.tolerance, 0.05),
57
+ overrides,
58
+ });
59
+ const rawRefreshTag = env?.CRAP_REFRESH_TAG;
27
60
  let refreshTag =
28
61
  typeof crapConfig?.refreshTag === 'string' && crapConfig.refreshTag.length
29
62
  ? crapConfig.refreshTag
30
63
  : 'baseline-refresh:';
31
-
32
- const rawCeiling = env?.CRAP_NEW_METHOD_CEILING;
33
- if (rawCeiling !== undefined && rawCeiling !== '') {
34
- const parsed = Number(rawCeiling);
35
- if (Number.isFinite(parsed) && parsed >= 0) {
36
- newMethodCeiling = parsed;
37
- overrides.push(`newMethodCeiling=${parsed} (CRAP_NEW_METHOD_CEILING)`);
38
- } else {
39
- Logger.warn(
40
- `[CRAP] ⚠ ignoring malformed CRAP_NEW_METHOD_CEILING=${rawCeiling}; keeping config value ${newMethodCeiling}`,
41
- );
42
- }
43
- }
44
-
45
- const rawTolerance = env?.CRAP_TOLERANCE;
46
- if (rawTolerance !== undefined && rawTolerance !== '') {
47
- const parsed = Number(rawTolerance);
48
- if (Number.isFinite(parsed) && parsed >= 0) {
49
- tolerance = parsed;
50
- overrides.push(`tolerance=${parsed} (CRAP_TOLERANCE)`);
51
- } else {
52
- Logger.warn(
53
- `[CRAP] ⚠ ignoring malformed CRAP_TOLERANCE=${rawTolerance}; keeping config value ${tolerance}`,
54
- );
55
- }
56
- }
57
-
58
- const rawRefreshTag = env?.CRAP_REFRESH_TAG;
59
64
  if (typeof rawRefreshTag === 'string' && rawRefreshTag.length > 0) {
60
65
  refreshTag = rawRefreshTag;
61
66
  overrides.push(`refreshTag=${rawRefreshTag} (CRAP_REFRESH_TAG)`);
@@ -233,12 +233,13 @@ function tryGetKindModule(kind) {
233
233
  *
234
234
  * @param {string} kind
235
235
  * @param {object|null} baseline
236
+ * @param {object} [ctx] Passed through to the kind's hook (e.g. scan anchors).
236
237
  * @returns {string|null} Operator-facing message, or null when compatible.
237
238
  */
238
- export function checkBaselineSemantics(kind, baseline) {
239
+ export function checkBaselineSemantics(kind, baseline, ctx = {}) {
239
240
  const mod = tryGetKindModule(kind);
240
241
  if (typeof mod?.assertBaselineCompatible !== 'function') return null;
241
- return mod.assertBaselineCompatible(baseline);
242
+ return mod.assertBaselineCompatible(baseline, ctx);
242
243
  }
243
244
 
244
245
  /**
@@ -3,7 +3,6 @@
3
3
  * `{ path, method, startLine, crap }`.
4
4
  */
5
5
 
6
- import fs from 'node:fs';
7
6
  import path from 'node:path';
8
7
  import { fileURLToPath } from 'node:url';
9
8
  import {
@@ -12,6 +11,7 @@ import {
12
11
  deriveFixGuidance,
13
12
  } from '../../crap-engine.js';
14
13
  import { isAnonymousMethodLabel } from '../../crap-method-identity.js';
14
+ import { resolveEscomplexVersion } from '../../crap-utils.js';
15
15
  import { Logger } from '../../Logger.js';
16
16
  import { resolveTsTranspilerVersion } from '../../transpile.js';
17
17
  import {
@@ -42,43 +42,16 @@ export { loadCrapBaseline } from './_crap-read.js';
42
42
 
43
43
  const __filename = fileURLToPath(import.meta.url);
44
44
 
45
- /** The package that computes the metrics; its version stamps the scorer identity. */
46
- const SCORER_PACKAGE = 'escomplex-plugin-metrics-module';
47
-
48
45
  /**
49
- * Resolve the scorer version from the nearest `node_modules/<SCORER_PACKAGE>`,
50
- * walking up. Returns the `'0.0.0'` "unknown environment" sentinel when not
51
- * found, which makes the writer refuse to persist. The walk-up can escape a
52
- * worktree into the parent checkout, so a local pass does not prove CI's.
46
+ * Scorer version, walked up from this module's directory; the `'0.0.0'`
47
+ * sentinel (unknown environment) makes the writer refuse to persist. The
48
+ * walk-up can escape a worktree into the parent checkout, so a local pass
49
+ * does not prove CI's.
53
50
  *
54
51
  * @returns {string}
55
52
  */
56
53
  export function kernelVersion() {
57
- let dir = path.dirname(__filename);
58
- const { root } = path.parse(dir);
59
- while (true) {
60
- const pkgPath = path.join(
61
- dir,
62
- 'node_modules',
63
- SCORER_PACKAGE,
64
- 'package.json',
65
- );
66
- if (fs.existsSync(pkgPath)) {
67
- try {
68
- const parsed = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
69
- if (parsed && typeof parsed.version === 'string') {
70
- return parsed.version;
71
- }
72
- } catch {
73
- // fall through to parent lookup
74
- }
75
- }
76
- if (dir === root) break;
77
- const parent = path.dirname(dir);
78
- if (parent === dir) break;
79
- dir = parent;
80
- }
81
- return '0.0.0';
54
+ return resolveEscomplexVersion(path.dirname(__filename));
82
55
  }
83
56
 
84
57
  /**
@@ -96,15 +69,17 @@ const SCORING_SEMANTICS = 'method-identity-v3';
96
69
  * change can move every TS row's `startLine` (half the row identity key), so
97
70
  * `tsTranspilerVersion` is stamped for the `ts-transpiler-drift` axis.
98
71
  * `provenanceStamped` is a positive marker that per-row provenance was
99
- * recorded; no other stamp can detect its absence.
72
+ * recorded; no other stamp can detect its absence. `ctx` carries the scan's
73
+ * `cwd` / `targetDirs` so the stamp names the compiler the scorer resolved.
100
74
  *
75
+ * @param {{ cwd?: string, targetDirs?: string[] }} [ctx]
101
76
  * @returns {{scoringSemantics: string, tsTranspilerVersion: string,
102
77
  * provenanceStamped: boolean}}
103
78
  */
104
- export function envelopeExtras() {
79
+ export function envelopeExtras(ctx = {}) {
105
80
  return {
106
81
  scoringSemantics: SCORING_SEMANTICS,
107
- tsTranspilerVersion: resolveTsTranspilerVersion(),
82
+ tsTranspilerVersion: resolveTsTranspilerVersion(ctx),
108
83
  provenanceStamped: true,
109
84
  };
110
85
  }
@@ -445,7 +420,7 @@ export const INCOMPATIBLE_BASELINE_DIAGNOSTIC = 'crap-baseline-incompatible';
445
420
  *
446
421
  * @param {{total?: number, comparable?: number, provenanceMismatched?: number,
447
422
  * incomparable?: number}} compareResult
448
- * @param {{ratio?: number, minSample?: number}} [opts]
423
+ * @param {{ratio?: number, minSample?: number, captureScript?: string}} [opts]
449
424
  */
450
425
  export function assessComparisonBasis(compareResult, opts = {}) {
451
426
  const ratio = Number.isFinite(opts.ratio)
@@ -476,7 +451,7 @@ export function assessComparisonBasis(compareResult, opts = {}) {
476
451
  'the same line coordinates, so every per-method verdict below would ' +
477
452
  'be derived from a mis-keyed join rather than from your change. ' +
478
453
  'They are suppressed.\n' +
479
- " Re-seed the baseline: run 'npm run test:coverage' then " +
454
+ ` Re-seed the baseline: run 'npm run ${captureScriptOf(opts)}' then ` +
480
455
  "'npm run crap:update -- --full-scope' and commit the result with a " +
481
456
  "'baseline-refresh:' subject. The authoritative check-baselines gate " +
482
457
  'still gates the merge.',
@@ -484,10 +459,27 @@ export function assessComparisonBasis(compareResult, opts = {}) {
484
459
  };
485
460
  }
486
461
 
487
- const RESEED_REMEDY =
488
- "Re-derive the baseline: run 'npm run test:coverage' then " +
489
- "'npm run crap:update -- --full-scope' and commit the result with a " +
490
- "'baseline-refresh:' subject.";
462
+ /**
463
+ * The CRAP capture script an operator hint names — the resolved
464
+ * `gates.crap.captureScript` when the caller passes it, else the default.
465
+ *
466
+ * @param {{ captureScript?: string } | undefined} ctx
467
+ * @returns {string}
468
+ */
469
+ function captureScriptOf(ctx) {
470
+ return typeof ctx?.captureScript === 'string' && ctx.captureScript.length > 0
471
+ ? ctx.captureScript
472
+ : 'test:coverage';
473
+ }
474
+
475
+ /** @param {{ captureScript?: string } | undefined} ctx */
476
+ function reseedRemedy(ctx) {
477
+ return (
478
+ `Re-derive the baseline: run 'npm run ${captureScriptOf(ctx)}' then ` +
479
+ "'npm run crap:update -- --full-scope' and commit the result with a " +
480
+ "'baseline-refresh:' subject."
481
+ );
482
+ }
491
483
 
492
484
  /**
493
485
  * Compat axes for `evaluateBaselineCompatibility`: `{ name, severity, check }`,
@@ -502,7 +494,7 @@ export const CRAP_COMPAT_AXES = [
502
494
  {
503
495
  name: 'scoring-semantics-drift',
504
496
  severity: 'fatal',
505
- check: ({ baseline }) => {
497
+ check: ({ baseline, captureScript }) => {
506
498
  if (!baseline) return null;
507
499
  const stamped = baseline.scoringSemantics ?? null;
508
500
  if (stamped === SCORING_SEMANTICS) return null;
@@ -510,14 +502,14 @@ export const CRAP_COMPAT_AXES = [
510
502
  `[CRAP] scoring semantics changed: baseline=${stamped ?? '<unstamped>'} ` +
511
503
  `running=${SCORING_SEMANTICS}. Rows scored by the previous per-method ` +
512
504
  'coverage join are not comparable to rows scored by the current one, ' +
513
- `so this baseline cannot be compared. ${RESEED_REMEDY}`
505
+ `so this baseline cannot be compared. ${reseedRemedy({ captureScript })}`
514
506
  );
515
507
  },
516
508
  },
517
509
  {
518
510
  name: 'ts-transpiler-drift',
519
511
  severity: 'fatal',
520
- check: ({ baseline, runningTsTranspilerVersion }) => {
512
+ check: ({ baseline, runningTsTranspilerVersion, captureScript }) => {
521
513
  if (!baseline) return null;
522
514
  if (!isKnownVersion(runningTsTranspilerVersion)) return null;
523
515
  const baselineTs = baseline.tsTranspilerVersion;
@@ -530,7 +522,7 @@ export const CRAP_COMPAT_AXES = [
530
522
  `[CRAP] tsTranspilerVersion changed: baseline=${baselineTs} running=${runningTsTranspilerVersion}. ` +
531
523
  "A TS row's startLine is an original-source coordinate only because the transpiler's " +
532
524
  'sourcemap said so, and that coordinate is half the row identity key — so rows scored ' +
533
- `under the previous transpiler are not comparable to rows scored under this one. ${RESEED_REMEDY}`
525
+ `under the previous transpiler are not comparable to rows scored under this one. ${reseedRemedy({ captureScript })}`
534
526
  );
535
527
  },
536
528
  },
@@ -540,7 +532,7 @@ export const CRAP_COMPAT_AXES = [
540
532
  // scoped to transpiled rows because pure-JS coordinates coincide.
541
533
  name: 'provenance-unstamped',
542
534
  severity: 'fatal',
543
- check: ({ baseline }) =>
535
+ check: ({ baseline, captureScript }) =>
544
536
  baseline &&
545
537
  baseline.provenanceStamped !== true &&
546
538
  hasTranspiledRows(baseline)
@@ -549,7 +541,7 @@ export const CRAP_COMPAT_AXES = [
549
541
  'asserts by omission that every row is an original-source coordinate. ' +
550
542
  '`startLine` is half the row identity key, so the comparator would ' +
551
543
  'key those rows against a coordinate space they are not in and ' +
552
- `report regressions no edit can satisfy. ${RESEED_REMEDY}`
544
+ `report regressions no edit can satisfy. ${reseedRemedy({ captureScript })}`
553
545
  : null,
554
546
  },
555
547
  {
@@ -559,7 +551,7 @@ export const CRAP_COMPAT_AXES = [
559
551
  // `anonymous` marker.
560
552
  name: 'anon-identity-unstamped',
561
553
  severity: 'fatal',
562
- check: ({ baseline }) => {
554
+ check: ({ baseline, captureScript }) => {
563
555
  if (!baseline) return null;
564
556
  const stale = (baseline.rows ?? []).filter(
565
557
  (row) => isAnonymousMethodLabel(row?.method) && row?.anonymous !== true,
@@ -572,7 +564,7 @@ export const CRAP_COMPAT_AXES = [
572
564
  'envelope claims the current scoring semantics. Those ordinals ' +
573
565
  'renumber whenever any anonymous function is added or removed, so the ' +
574
566
  'comparator would score the live methods against the new-method ' +
575
- `ceiling instead of their own baseline. ${RESEED_REMEDY}`
567
+ `ceiling instead of their own baseline. ${reseedRemedy({ captureScript })}`
576
568
  );
577
569
  },
578
570
  },
@@ -621,16 +613,21 @@ const LOADED_ENVELOPE_AXES = [
621
613
  * closed on a message, so an incompatible baseline is never silently compared.
622
614
  *
623
615
  * @param {object|null} baseline A loaded v2 baseline envelope.
624
- * @param {{runningTsTranspilerVersion?: string}} [ctx]
616
+ * @param {{runningTsTranspilerVersion?: string, cwd?: string,
617
+ * targetDirs?: string[], captureScript?: string}} [ctx]
625
618
  * @returns {string|null} Operator-facing message, or null when compatible.
626
619
  */
627
620
  export function assertBaselineCompatible(baseline, ctx = {}) {
628
621
  if (!baseline) return null;
629
622
  const runningTsTranspilerVersion =
630
- ctx.runningTsTranspilerVersion ?? resolveTsTranspilerVersion();
623
+ ctx.runningTsTranspilerVersion ?? resolveTsTranspilerVersion(ctx);
631
624
  for (const name of LOADED_ENVELOPE_AXES) {
632
625
  const axis = CRAP_COMPAT_AXES.find((a) => a.name === name);
633
- const message = axis?.check({ baseline, runningTsTranspilerVersion });
626
+ const message = axis?.check({
627
+ baseline,
628
+ runningTsTranspilerVersion,
629
+ captureScript: ctx.captureScript,
630
+ });
634
631
  if (message) return message;
635
632
  }
636
633
  return null;
@@ -215,7 +215,11 @@ export async function runCrapPreview({
215
215
 
216
216
  // An incompatible baseline yields no meaningful verdict. Fail open:
217
217
  // `check-baselines` still gates the merge.
218
- const incompatible = assertBaselineCompatible(baseline);
218
+ const incompatible = assertBaselineCompatible(baseline, {
219
+ cwd,
220
+ targetDirs: crap.targetDirs,
221
+ captureScript: crap.captureScript,
222
+ });
219
223
  if (incompatible) {
220
224
  return {
221
225
  exitCode: 0,