mandrel 2.86.0 → 2.88.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 (165) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  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 +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -1,13 +1,40 @@
1
1
  /**
2
2
  * The `update-coverage-baseline` CLI's testable logic. The scorer stays
3
- * bespoke (not the refresh-service default) because it logs when the coverage
4
- * artifact is missing: `refreshBaseline` has no empty-rows guard, so that line
5
- * is the only signal a full-scope refresh just wrote an empty baseline.
3
+ * bespoke (not the refresh-service default) because it logs an unreadable
4
+ * coverage artifact before refusing it.
6
5
  */
7
6
 
7
+ import fs from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import path from 'node:path';
10
+ import { getBaselineEpsilon } from '../config/quality.js';
11
+ import {
12
+ buildScopePredicate,
13
+ readCoverageFinal,
14
+ scoreCoverageFinal,
15
+ } from '../coverage-baseline.js';
8
16
  import { Logger } from '../Logger.js';
9
17
  import { parseDiffScopeFlag } from './diff-scope-cli.js';
10
18
 
19
+ /** CommonJS `require`, for the `.c8rc.cjs` scope config. */
20
+ const require = createRequire(import.meta.url);
21
+
22
+ /**
23
+ * The c8 include/exclude scope from `<cwd>/.c8rc.cjs` — the one
24
+ * environment-bound step, which the scorer takes as a seam so a test never
25
+ * touches a real config. A consumer measuring with another runner has no
26
+ * `.c8rc.cjs`: that is an unscoped artifact, mirroring the refresh-service
27
+ * default scorer.
28
+ *
29
+ * @param {string} cwd
30
+ * @returns {{ include?: string[], exclude?: string[] }}
31
+ */
32
+ export function loadC8ScopeConfig(cwd) {
33
+ const c8rcPath = path.resolve(cwd, '.c8rc.cjs');
34
+ if (!fs.existsSync(c8rcPath)) return {};
35
+ return require(c8rcPath);
36
+ }
37
+
11
38
  /**
12
39
  * Throws when both scope flags are present.
13
40
  *
@@ -25,6 +52,16 @@ export function resolveCoverageUpdaterScope(argv = []) {
25
52
  return { fullScope, diffScopeRef };
26
53
  }
27
54
 
55
+ /** Logs a read failure and rethrows it: an empty row set would erase rows. */
56
+ function readOrRefuse(readCoverage, cwd, logger) {
57
+ try {
58
+ return readCoverage(cwd);
59
+ } catch (err) {
60
+ logger.error(`[Coverage] ❌ ${err.message}`);
61
+ throw err;
62
+ }
63
+ }
64
+
28
65
  /**
29
66
  * Narrows to the c8 include/exclude scope, and in diff mode to the in-scope
30
67
  * files so untouched rows are preserved rather than re-scored.
@@ -34,20 +71,13 @@ export function resolveCoverageUpdaterScope(argv = []) {
34
71
  * score: Function, logger?: object}} deps
35
72
  * @returns {(files: string[], opts: object) => object[]}
36
73
  */
37
- export function buildCoverageUpdaterScorer(
74
+ function buildCoverageUpdaterScorer(
38
75
  cwd,
39
76
  { readCoverage, loadScope, buildScope, score, logger = Logger } = {},
40
77
  ) {
41
78
  return (files, opts) => {
42
79
  const effectiveCwd = opts?.cwd ?? cwd;
43
- let raw;
44
- try {
45
- raw = readCoverage(effectiveCwd);
46
- } catch (err) {
47
- logger.error(`[Coverage] ❌ ${err.message}`);
48
- return [];
49
- }
50
-
80
+ const raw = readOrRefuse(readCoverage, effectiveCwd, logger);
51
81
  const c8Config = loadScope(effectiveCwd);
52
82
  const scores = score({
53
83
  raw,
@@ -57,25 +87,88 @@ export function buildCoverageUpdaterScorer(
57
87
  exclude: c8Config.exclude ?? [],
58
88
  }),
59
89
  });
90
+ return projectScoredRows(scores, files, opts, logger);
91
+ };
92
+ }
60
93
 
61
- const inScope =
62
- !opts?.fullScope && Array.isArray(files) && files.length > 0
63
- ? new Set(files)
64
- : null;
94
+ /**
95
+ * Baseline rows from per-file scores; in diff mode only the in-scope files,
96
+ * so untouched rows are preserved rather than re-scored.
97
+ *
98
+ * @param {Record<string, object>} scores
99
+ * @param {string[]} files
100
+ * @param {{ fullScope?: boolean } | undefined} opts
101
+ * @param {{ info: Function }} logger
102
+ * @returns {object[]}
103
+ */
104
+ function projectScoredRows(scores, files, opts, logger) {
105
+ const inScope =
106
+ !opts?.fullScope && Array.isArray(files) && files.length > 0
107
+ ? new Set(files)
108
+ : null;
109
+ const rows = Object.entries(scores)
110
+ .filter(([relPath]) => inScope === null || inScope.has(relPath))
111
+ .map(([relPath, s]) => ({
112
+ path: relPath,
113
+ lines: s?.lines ?? 0,
114
+ branches: s?.branches ?? 0,
115
+ functions: s?.functions ?? 0,
116
+ }));
117
+ logger.info(
118
+ `[Coverage] Scored ${Object.keys(scores).length} file(s)${inScope ? ` (${rows.length} in scope)` : ''}.`,
119
+ );
120
+ return rows;
121
+ }
65
122
 
66
- const rows = Object.entries(scores)
67
- .filter(([relPath]) => inScope === null || inScope.has(relPath))
68
- .map(([relPath, s]) => ({
69
- path: relPath,
70
- lines: s?.lines ?? 0,
71
- branches: s?.branches ?? 0,
72
- functions: s?.functions ?? 0,
73
- }));
123
+ /**
124
+ * The configured artifact the refresh reads and the baseline it writes —
125
+ * `coveragePath` / `baselinePath` from the resolved coverage gate, never a
126
+ * hardcoded default.
127
+ *
128
+ * @param {{ coveragePath: string, baselinePath: string }} coverageGate
129
+ * @param {string} cwd
130
+ * @returns {{ coveragePath: string, baselinePath: string,
131
+ * absBaselinePath: string, readCoverage: (dir: string) => object }}
132
+ */
133
+ export function coverageUpdaterTargets({ coveragePath, baselinePath }, cwd) {
134
+ return {
135
+ coveragePath,
136
+ baselinePath,
137
+ absBaselinePath: path.resolve(cwd, baselinePath),
138
+ readCoverage: (dir) => readCoverageFinal(dir, { coveragePath }),
139
+ };
140
+ }
74
141
 
75
- const fileCount = Object.keys(scores).length;
76
- logger.info(
77
- `[Coverage] Scored ${fileCount} file(s)${inScope ? ` (${rows.length} in scope)` : ''}.`,
78
- );
79
- return rows;
142
+ /**
143
+ * `refreshBaseline` options for the coverage updater. `deps` substitutes the
144
+ * scorer's scope and scoring seams so a test never touches a real artifact.
145
+ *
146
+ * @param {string} cwd
147
+ * @param {{ absBaselinePath: string, readCoverage: Function }} targets
148
+ * @param {{ loadScope?: Function, buildScope?: Function, score?: Function,
149
+ * logger?: object }} [deps]
150
+ * @returns {object}
151
+ */
152
+ export function buildCoverageRefreshOpts(
153
+ cwd,
154
+ { absBaselinePath, readCoverage },
155
+ {
156
+ loadScope = loadC8ScopeConfig,
157
+ buildScope = buildScopePredicate,
158
+ score = scoreCoverageFinal,
159
+ logger,
160
+ } = {},
161
+ ) {
162
+ return {
163
+ kind: 'coverage',
164
+ writePath: absBaselinePath,
165
+ epsilon: getBaselineEpsilon('coverage'),
166
+ scorer: buildCoverageUpdaterScorer(cwd, {
167
+ readCoverage,
168
+ loadScope,
169
+ buildScope,
170
+ score,
171
+ logger,
172
+ }),
80
173
  };
81
174
  }
@@ -7,7 +7,10 @@
7
7
 
8
8
  import path from 'node:path';
9
9
  import { getBaselines, getQuality, resolveConfig } from '../config-resolver.js';
10
- import { isCoverageFresh } from '../coverage-capture.js';
10
+ import {
11
+ isCoverageFresh,
12
+ MissingCoverageArtifactError,
13
+ } from '../coverage-capture.js';
11
14
  import { loadCoverage as loadCoverageDefault } from '../coverage-utils.js';
12
15
  import { checkResolutionFloor, scanAndScore } from '../crap-utils.js';
13
16
  import { Logger } from '../Logger.js';
@@ -133,16 +136,51 @@ function reportScanSummary(summary, logger = Logger) {
133
136
  }
134
137
  }
135
138
 
139
+ /** @param {string} coverageAbs */
140
+ function refuseMissingCoverage(coverageAbs) {
141
+ throw new MissingCoverageArtifactError(coverageAbs, { prefix: '[CRAP] ' });
142
+ }
143
+
144
+ /**
145
+ * `refreshBaseline` options for the CRAP updater. With no scope flag the
146
+ * service derives the diff via `origin/main..HEAD` (its default refs). The
147
+ * transpiler stamp resolves from the anchors the scorer resolves compilers
148
+ * from: the target dirs and the project root.
149
+ *
150
+ * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
151
+ * @param {{loadCoverage: Function, epsilon?: number, cwd?: string,
152
+ * scan?: Function, logger?: object}} deps
153
+ * @returns {object}
154
+ */
155
+ export function buildCrapRefreshOptions(
156
+ options,
157
+ { epsilon, cwd = process.cwd(), ...scorerDeps },
158
+ ) {
159
+ return {
160
+ kind: 'crap',
161
+ writePath: options.absBaselinePath,
162
+ epsilon,
163
+ scorer: buildCrapUpdaterScorer(options, scorerDeps),
164
+ extrasContext: { cwd, targetDirs: options.targetDirs },
165
+ ...scopeFields(options),
166
+ };
167
+ }
168
+
169
+ function scopeFields({ fullScope, diffScopeRef }) {
170
+ if (fullScope) return { fullScope: true };
171
+ return diffScopeRef ? { baseRef: diffScopeRef } : {};
172
+ }
173
+
136
174
  /**
137
- * Fails closed on a missing coverage artifact under `requireCoverage` (warn,
138
- * no rows) and on a resolution rate below the floor (throws before anything is
139
- * written: a broken join is wrong, not sparse).
175
+ * Fails closed on a missing coverage artifact under `requireCoverage` (throws
176
+ * on every scope) and on a resolution rate below the floor (throws before
177
+ * anything is written: a broken join is wrong, not sparse).
140
178
  *
141
179
  * @param {ReturnType<typeof resolveCrapUpdaterOptions>} options
142
180
  * @param {{loadCoverage: Function, scan?: Function, logger?: object}} deps
143
181
  * @returns {(files: string[], opts: object) => Promise<object[]>}
144
182
  */
145
- export function buildCrapUpdaterScorer(
183
+ function buildCrapUpdaterScorer(
146
184
  options,
147
185
  { loadCoverage, scan = scanAndScore, logger = Logger } = {},
148
186
  ) {
@@ -152,15 +190,8 @@ export function buildCrapUpdaterScorer(
152
190
  ? options.coveragePath
153
191
  : path.resolve(effectiveCwd, options.coveragePath);
154
192
  const coverage = loadCoverage(coverageAbs);
155
- if (!coverage && options.requireCoverage) {
156
- logger.warn(
157
- `[CRAP] ⚠ No coverage artifact at ${options.coveragePath}. All files will be skipped under requireCoverage=true.`,
158
- );
159
- logger.warn(
160
- "[CRAP] ⚠ Run 'npm run test:coverage' before 'npm run crap:update'.",
161
- );
162
- return [];
163
- }
193
+ if (!coverage && options.requireCoverage)
194
+ refuseMissingCoverage(coverageAbs);
164
195
 
165
196
  const summary = await scan({
166
197
  targetDirs: options.targetDirs,
@@ -21,6 +21,30 @@ const require = createRequire(import.meta.url);
21
21
  /** jscpd 5 is a Rust rewrite with no Node API; only major 4 exposes one. */
22
22
  const SUPPORTED_JSCPD_MAJOR = '^4';
23
23
 
24
+ /** `err.code` of the missing-install refusal, so a CLI prints it stackless. */
25
+ export const JSCPD_MISSING = 'JSCPD_MISSING';
26
+
27
+ /**
28
+ * jscpd is an optional peer dependency: only a consumer that enables the
29
+ * duplication gate installs it. A missing install names the fix rather than
30
+ * surfacing `MODULE_NOT_FOUND`; any other load failure propagates as-is.
31
+ *
32
+ * @param {NodeJS.Require} requireFn
33
+ * @returns {object}
34
+ */
35
+ function loadJscpd(requireFn) {
36
+ try {
37
+ return requireFn('jscpd');
38
+ } catch (err) {
39
+ if (err?.code !== 'MODULE_NOT_FOUND') throw err;
40
+ const missing = new Error(
41
+ `[Duplication] jscpd is not installed. The duplication gate scans with jscpd ${SUPPORTED_JSCPD_MAJOR}, an optional peer dependency of mandrel — install it in this project: npm i -D jscpd@${SUPPORTED_JSCPD_MAJOR}`,
42
+ );
43
+ missing.code = JSCPD_MISSING;
44
+ throw missing;
45
+ }
46
+ }
47
+
24
48
  /**
25
49
  * Lazy CJS load: jscpd's ESM entry has a broken transitive `colors/safe`
26
50
  * specifier under strict ESM resolution, and importers that never scan should
@@ -32,7 +56,7 @@ const SUPPORTED_JSCPD_MAJOR = '^4';
32
56
  * @returns {(opts: object) => Promise<Array<object>>}
33
57
  */
34
58
  export function resolveDetectClones(requireFn = require) {
35
- const jscpd = requireFn('jscpd');
59
+ const jscpd = loadJscpd(requireFn);
36
60
  if (typeof jscpd?.detectClones !== 'function') {
37
61
  const version = resolveDependencyVersion('jscpd', requireFn) ?? 'unknown';
38
62
  throw new Error(
@@ -81,11 +105,13 @@ function cloneLineNumbers(dup, maxLine) {
81
105
  /**
82
106
  * Pure. Both sides of each clone pair accrue lines; overlapping clones are
83
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.
84
110
  *
85
111
  * @param {Array<{duplicationA?: object, duplicationB?: object}>} clones
86
112
  * @param {Map<string, number>|Record<string, number>} fileLineCounts
87
113
  * @param {string} [cwd]
88
- * @returns {Array<{path: string, duplicatedLines: number, totalLines: number, percentage: number}>}
114
+ * @returns {Array<{path: string, duplicatedLines: number, totalLines: number, percentage: number, partners: string[]}>}
89
115
  */
90
116
  export function buildDuplicationRows(
91
117
  clones,
@@ -94,19 +120,23 @@ export function buildDuplicationRows(
94
120
  ) {
95
121
  const counts = toLineCountMap(fileLineCounts);
96
122
  const dupLinesByFile = new Map();
123
+ const partnersByFile = new Map();
97
124
  // Seed every visited file with an empty set so clean files get a 0-row.
98
125
  for (const file of counts.keys()) {
99
126
  dupLinesByFile.set(file, new Set());
100
127
  }
101
128
  for (const clone of clones ?? []) {
129
+ const files = [];
102
130
  for (const side of [clone?.duplicationA, clone?.duplicationB]) {
103
131
  if (!side) continue;
104
132
  const file = relativisePath(side.sourceId, cwd);
105
133
  if (!file) continue;
134
+ files.push(file);
106
135
  const set = dupLinesByFile.get(file) ?? new Set();
107
136
  for (const n of cloneLineNumbers(side, counts.get(file))) set.add(n);
108
137
  dupLinesByFile.set(file, set);
109
138
  }
139
+ addClonePartners(partnersByFile, files);
110
140
  }
111
141
  const rows = [];
112
142
  for (const [file, lineSet] of dupLinesByFile) {
@@ -119,11 +149,24 @@ export function buildDuplicationRows(
119
149
  duplicatedLines,
120
150
  totalLines,
121
151
  percentage: Number(percentage.toFixed(2)),
152
+ partners: [...(partnersByFile.get(file) ?? [])].sort(),
122
153
  });
123
154
  }
124
155
  return rows;
125
156
  }
126
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
+
127
170
  function toLineCountMap(fileLineCounts) {
128
171
  if (fileLineCounts instanceof Map) return fileLineCounts;
129
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
  }
@@ -621,13 +596,14 @@ const LOADED_ENVELOPE_AXES = [
621
596
  * closed on a message, so an incompatible baseline is never silently compared.
622
597
  *
623
598
  * @param {object|null} baseline A loaded v2 baseline envelope.
624
- * @param {{runningTsTranspilerVersion?: string}} [ctx]
599
+ * @param {{runningTsTranspilerVersion?: string, cwd?: string,
600
+ * targetDirs?: string[]}} [ctx]
625
601
  * @returns {string|null} Operator-facing message, or null when compatible.
626
602
  */
627
603
  export function assertBaselineCompatible(baseline, ctx = {}) {
628
604
  if (!baseline) return null;
629
605
  const runningTsTranspilerVersion =
630
- ctx.runningTsTranspilerVersion ?? resolveTsTranspilerVersion();
606
+ ctx.runningTsTranspilerVersion ?? resolveTsTranspilerVersion(ctx);
631
607
  for (const name of LOADED_ENVELOPE_AXES) {
632
608
  const axis = CRAP_COMPAT_AXES.find((a) => a.name === name);
633
609
  const message = axis?.check({ baseline, runningTsTranspilerVersion });
@@ -215,7 +215,10 @@ 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
+ });
219
222
  if (incompatible) {
220
223
  return {
221
224
  exitCode: 0,