mandrel 2.90.0 → 2.91.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 (169) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +31 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/check-arch-cycles.js +1 -5
  14. package/.agents/scripts/check-context-budget.js +1 -5
  15. package/.agents/scripts/check-cyclomatic.js +1 -5
  16. package/.agents/scripts/check-dead-exports.js +23 -14
  17. package/.agents/scripts/check-doc-links.js +4 -4
  18. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  19. package/.agents/scripts/coverage-capture.js +14 -6
  20. package/.agents/scripts/diagnose-friction.js +8 -10
  21. package/.agents/scripts/generate-workflows-doc.js +5 -0
  22. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  24. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  25. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  26. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  27. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  28. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  29. package/.agents/scripts/lib/baselines/components.js +5 -5
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  32. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  33. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  34. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  36. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  37. package/.agents/scripts/lib/baselines/writer.js +4 -4
  38. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  39. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  40. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  41. package/.agents/scripts/lib/child-exec.js +4 -4
  42. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  43. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  44. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  45. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  46. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  47. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  48. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  49. package/.agents/scripts/lib/config/commands.js +82 -7
  50. package/.agents/scripts/lib/config/explain.js +2 -1
  51. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  52. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  53. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  54. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  55. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  56. package/.agents/scripts/lib/config/git-roots.js +120 -0
  57. package/.agents/scripts/lib/config/quality.js +46 -50
  58. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  59. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  60. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  61. package/.agents/scripts/lib/config-resolver.js +5 -9
  62. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  63. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  64. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  65. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  67. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  68. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  69. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  70. package/.agents/scripts/lib/coverage-capture.js +31 -20
  71. package/.agents/scripts/lib/coverage-utils.js +34 -16
  72. package/.agents/scripts/lib/cpu-pool.js +2 -4
  73. package/.agents/scripts/lib/crap-engine.js +19 -1
  74. package/.agents/scripts/lib/crap-utils.js +2 -1
  75. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  76. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  77. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  78. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  79. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  80. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  81. package/.agents/scripts/lib/gh-env.js +72 -0
  82. package/.agents/scripts/lib/gh-exec.js +26 -1
  83. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  84. package/.agents/scripts/lib/npm-scripts.js +1 -1
  85. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  86. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  87. package/.agents/scripts/lib/orchestration/board-access-latch.js +19 -8
  88. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  89. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  90. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  91. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  92. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  93. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  94. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  95. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  96. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  97. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  98. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  99. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  100. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  101. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  102. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  103. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  104. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  105. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  106. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  107. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  108. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  109. package/.agents/scripts/lib/orchestration/story-handoff.js +13 -5
  110. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  111. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  112. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  113. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  114. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  115. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  116. package/.agents/scripts/lib/source-extensions.js +30 -15
  117. package/.agents/scripts/lib/test-run-credit.js +1 -9
  118. package/.agents/scripts/lib/test-temp.js +22 -21
  119. package/.agents/scripts/lib/util/ajv.js +111 -0
  120. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  121. package/.agents/scripts/lib/util/paths.js +51 -0
  122. package/.agents/scripts/lib/util/sleep.js +6 -0
  123. package/.agents/scripts/lib/util/slug.js +12 -0
  124. package/.agents/scripts/lib/validation-evidence.js +19 -40
  125. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  126. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  127. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  128. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  129. package/.agents/scripts/lint-issue-body.js +2 -2
  130. package/.agents/scripts/plan-context.js +2 -7
  131. package/.agents/scripts/providers/github/auth.js +3 -3
  132. package/.agents/scripts/providers/github/errors.js +3 -1
  133. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  134. package/.agents/scripts/providers/github/issues.js +6 -2
  135. package/.agents/scripts/providers/github/mappers.js +1 -5
  136. package/.agents/scripts/providers/github/projects-v2-graphql.js +11 -3
  137. package/.agents/scripts/providers/github/search-budget.js +3 -1
  138. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  139. package/.agents/scripts/sync-agentrc.js +5 -14
  140. package/.agents/scripts/sync-claude-agents.js +38 -150
  141. package/.agents/scripts/sync-claude-commands.js +35 -218
  142. package/.agents/scripts/update-coverage-baseline.js +1 -1
  143. package/.agents/scripts/update-crap-baseline.js +1 -1
  144. package/.agents/scripts/update-duplication-baseline.js +2 -16
  145. package/.agents/scripts/validate-skills.js +6 -10
  146. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  147. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  148. package/.agents/workflows/audit-exceptions.md +9 -0
  149. package/.agents/workflows/audit-lean.md +129 -0
  150. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  151. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  152. package/.agents/workflows/helpers/code-review.md +15 -1
  153. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  154. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  155. package/.agents/workflows/mandrel-plan.md +2 -2
  156. package/docs/CHANGELOG.md +35 -0
  157. package/lib/cli/doctor-checks/codex.js +6 -5
  158. package/lib/cli/doctor-checks/llm-review.js +102 -0
  159. package/lib/cli/doctor-checks/project-access.js +20 -10
  160. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  161. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  162. package/lib/cli/doctor-checks/toolchain.js +5 -3
  163. package/lib/cli/registry.js +5 -0
  164. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  165. package/lib/migrations/index.js +6 -0
  166. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  167. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  168. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  169. package/package.json +1 -3
@@ -1,38 +1,127 @@
1
1
  /**
2
- * The ordered capture passes for `coverage-capture.js` and the capture-script
3
- * refusal. A shared source is one pass: the existing pipeline, scoped modes
4
- * included. An own CRAP source (`crap.ownCoverageSource`) first refreshes the
5
- * coverage gate's artifact exactly as before, then gives the CRAP artifact
6
- * its own full-scope pass via `crap.captureScript`, stamped in its own
7
- * directory. Scoped capture modes never apply to the own source.
2
+ * Capture passes, the refusal, and the registration predicate close, the
3
+ * handoff and `verify[]` credit share. An own CRAP source gets a second,
4
+ * full-scope pass after the coverage gate's.
8
5
  */
6
+ import { COVERAGE_CAPTURE_DEFAULTS } from './config/gates/coverage.schema.js';
9
7
  import { runFullScopeCapture } from './coverage-capture-fullscope.js';
8
+ import { hasNpmScript } from './npm-scripts.js';
10
9
 
11
- const COVERAGE_GATE_SCRIPT = 'test:coverage';
12
10
  const COVERAGE_PATH_KEY = 'delivery.quality.gates.coverage.coveragePath';
11
+ const COVERAGE_SCRIPT_KEY = 'delivery.quality.gates.coverage.captureScript';
13
12
  const CRAP_PATH_KEY = 'delivery.quality.gates.crap.coveragePath';
14
13
  const CRAP_SCRIPT_KEY = 'delivery.quality.gates.crap.captureScript';
15
14
 
16
15
  /**
17
- * The exit code when no capture may run: the CRAP gate is off (0), or its
18
- * capture script is missing from `package.json` (1, naming the fix).
16
+ * The resolved `{ crap, coverage }` pair a `getQuality` seam returns, with the
17
+ * coverage gate's capture fields always present: a shared source's artifact
18
+ * is the CRAP one, and the script defaults to the coverage gate default.
19
19
  *
20
- * @param {{ crap: object, scripts: object, hasNpmScriptImpl: Function, logger: object }} opts
21
- * @returns {number|null}
20
+ * @param {{ crap: object, coverage?: object }} quality
21
+ * @returns {{ crap: object, coverage: object }}
22
22
  */
23
- export function captureRefusal({ crap, scripts, hasNpmScriptImpl, logger }) {
24
- if (crap.enabled === false) {
25
- logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
23
+ export function captureGates({ crap, coverage }) {
24
+ const sharedPath = crap.ownCoverageSource ? undefined : crap.coveragePath;
25
+ return {
26
+ crap,
27
+ coverage: {
28
+ ...coverage,
29
+ coveragePath:
30
+ coverage?.coveragePath ??
31
+ sharedPath ??
32
+ COVERAGE_CAPTURE_DEFAULTS.coveragePath,
33
+ captureScript:
34
+ coverage?.captureScript ?? COVERAGE_CAPTURE_DEFAULTS.captureScript,
35
+ },
36
+ };
37
+ }
38
+
39
+ /** @param {{ crap: object, coverage: object }} gates */
40
+ function isCaptureGateEnabled({ crap, coverage }) {
41
+ return crap.enabled !== false || coverage.enabled !== false;
42
+ }
43
+
44
+ /** @param {object} crap */
45
+ function crapOwnsSource(crap) {
46
+ return crap.enabled !== false && crap.ownCoverageSource === true;
47
+ }
48
+
49
+ /** An enabled CRAP gate's own source, else the coverage gate's. @param {{ crap: object, coverage: object }} gates */
50
+ export function primaryCaptureSource({ crap, coverage }) {
51
+ return crapOwnsSource(crap)
52
+ ? {
53
+ coveragePath: crap.coveragePath,
54
+ captureScript: crap.captureScript,
55
+ scriptKey: CRAP_SCRIPT_KEY,
56
+ }
57
+ : {
58
+ coveragePath: coverage.coveragePath,
59
+ captureScript: coverage.captureScript,
60
+ scriptKey: COVERAGE_SCRIPT_KEY,
61
+ };
62
+ }
63
+
64
+ /** @param {{ crap: object, coverage: object, scripts: object|null|undefined, hasNpmScriptImpl?: Function }} opts */
65
+ export function isCaptureActive({
66
+ crap,
67
+ coverage,
68
+ scripts,
69
+ hasNpmScriptImpl = hasNpmScript,
70
+ }) {
71
+ return (
72
+ isCaptureGateEnabled({ crap, coverage }) &&
73
+ hasNpmScriptImpl(
74
+ scripts,
75
+ primaryCaptureSource({ crap, coverage }).captureScript,
76
+ )
77
+ );
78
+ }
79
+
80
+ /**
81
+ * 0 when both gates are off, 1 (naming the fix) when the script is missing.
82
+ *
83
+ * @param {{ crap: object, coverage: object, scripts: object, hasNpmScriptImpl: Function, logger: object }} opts
84
+ */
85
+ export function captureRefusal({
86
+ crap,
87
+ coverage,
88
+ scripts,
89
+ hasNpmScriptImpl,
90
+ logger,
91
+ }) {
92
+ if (!isCaptureGateEnabled({ crap, coverage })) {
93
+ logger.info(
94
+ '[coverage-capture] CRAP and coverage gates disabled — skipping capture.',
95
+ );
26
96
  return 0;
27
97
  }
28
- const script = crap.captureScript ?? COVERAGE_GATE_SCRIPT;
98
+ const { captureScript: script, scriptKey } = primaryCaptureSource({
99
+ crap,
100
+ coverage,
101
+ });
29
102
  if (hasNpmScriptImpl(scripts, script)) return null;
30
- // Name the fix rather than propagate npm's opaque "Missing script" exit.
103
+ return missingScriptExit({ crap, script, scriptKey, logger });
104
+ }
105
+
106
+ /**
107
+ * With the CRAP gate off nothing fails closed on a missing artifact, and close
108
+ * registers no capture without the script, so its absence is a skip (0).
109
+ * Otherwise name the fix rather than propagate the manager's opaque exit (1).
110
+ *
111
+ * @param {{ crap: object, script: string, scriptKey: string, logger: object }} opts
112
+ */
113
+ function missingScriptExit({ crap, script, scriptKey, logger }) {
114
+ if (crap.enabled === false) {
115
+ logger.info(
116
+ `[coverage-capture] CRAP gate disabled and no "${script}" script — skipping capture.`,
117
+ );
118
+ return 0;
119
+ }
31
120
  logger.error(
32
- `[coverage-capture] ✖ No "${script}" script in package.json (the CRAP capture script, set by ${CRAP_SCRIPT_KEY}). ` +
121
+ `[coverage-capture] ✖ No "${script}" script in package.json (the capture script, set by ${scriptKey}). ` +
33
122
  `Add one (e.g. "${script}": "node --test --experimental-test-coverage"), ` +
34
- `point ${CRAP_SCRIPT_KEY} at an existing script, ` +
35
- 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
123
+ `point ${scriptKey} at an existing script, ` +
124
+ 'or disable the coverage and CRAP gates via delivery.quality.gates.{coverage,crap}.enabled=false.',
36
125
  );
37
126
  return 1;
38
127
  }
@@ -42,25 +131,21 @@ export function captureRefusal({ crap, scripts, hasNpmScriptImpl, logger }) {
42
131
  * @returns {Array<{ crap: object, configKey: string, own: boolean }>}
43
132
  */
44
133
  function planPasses({ crap, coverage, scripts, hasNpmScriptImpl, logger }) {
45
- if (crap.ownCoverageSource !== true) {
46
- return [{ crap, configKey: COVERAGE_PATH_KEY, own: false }];
47
- }
134
+ const gateCrap = {
135
+ ...crap,
136
+ coveragePath: coverage.coveragePath,
137
+ captureScript: coverage.captureScript,
138
+ };
139
+ const gatePass = { crap: gateCrap, configKey: COVERAGE_PATH_KEY, own: false };
140
+ if (!crapOwnsSource(crap)) return [gatePass];
48
141
  const ownPass = { crap, configKey: CRAP_PATH_KEY, own: true };
49
- if (!hasNpmScriptImpl(scripts, COVERAGE_GATE_SCRIPT)) {
142
+ if (!hasNpmScriptImpl(scripts, coverage.captureScript)) {
50
143
  logger.info(
51
- `[coverage-capture] No "${COVERAGE_GATE_SCRIPT}" script — skipping the coverage gate's capture; only the CRAP source at ${crap.coveragePath} is refreshed.`,
144
+ `[coverage-capture] No "${coverage.captureScript}" script — skipping the coverage gate's capture; only the CRAP source at ${crap.coveragePath} is refreshed.`,
52
145
  );
53
146
  return [ownPass];
54
147
  }
55
- const gateCrap = {
56
- ...crap,
57
- coveragePath: coverage.coveragePath,
58
- captureScript: COVERAGE_GATE_SCRIPT,
59
- };
60
- return [
61
- { crap: gateCrap, configKey: COVERAGE_PATH_KEY, own: false },
62
- ownPass,
63
- ];
148
+ return [gatePass, ownPass];
64
149
  }
65
150
 
66
151
  /**
@@ -131,7 +216,7 @@ export async function runCapturePasses({
131
216
  */
132
217
  function runOwnSource({ crap, coverage, args, capture, deps }) {
133
218
  deps.logger.info(
134
- `[coverage-capture] CRAP gate has its own coverage source (${CRAP_PATH_KEY}=${crap.coveragePath}, npm run ${crap.captureScript}).`,
219
+ `[coverage-capture] CRAP gate has its own coverage source (${CRAP_PATH_KEY}=${crap.coveragePath}, capture script ${crap.captureScript}).`,
135
220
  );
136
221
  return runFullScopeCapture({
137
222
  ...deps,
@@ -14,7 +14,7 @@ const COVERAGE_CAPTURE_USAGE = {
14
14
  invocation:
15
15
  'node .agents/scripts/coverage-capture.js [--skip-when-no-crap-files] [--require-credited] [--ref <git-ref>] [--cwd <path>]',
16
16
  summary:
17
- 'Ensure coverage/coverage-final.json is present and fresh before the CRAP gate fires, spawning `npm run test:coverage` only when it is stale (`npm run test:coverage:affected`, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp that close-validation reads to skip a redundant re-run. When delivery.quality.gates.crap.coveragePath names its own artifact, that artifact is then refreshed full-scope with `npm run <delivery.quality.gates.crap.captureScript>` and stamped in its own directory.',
17
+ 'Ensure the coverage artifact (delivery.quality.gates.coverage.coveragePath) is present and fresh before the coverage and CRAP gates fire, spawning `<pm> run <delivery.quality.gates.coverage.captureScript>` under the detected package manager only when it is stale (the affected capture script, with the base ref in MANDREL_COVERAGE_BASE_REF, under delivery.quality.gates.coverage.captureScope="affected"). Writes a content-digest capture stamp beside the artifact that close-validation reads to skip a redundant re-run. When delivery.quality.gates.crap.coveragePath names its own artifact, that artifact is then refreshed full-scope with `<pm> run <delivery.quality.gates.crap.captureScript>` and stamped beside itself.',
18
18
  flags: [
19
19
  [
20
20
  '--skip-when-no-crap-files',
@@ -1,12 +1,14 @@
1
1
  /**
2
- * Keep `coverage/coverage-final.json` present and fresh before a CRAP gate
3
- * reads it: the scorer skips uncovered methods, so a stale artifact silently
4
- * weakens the gate.
2
+ * Keep the coverage artifact (`coverage.coveragePath`) present and fresh
3
+ * before a CRAP or coverage gate reads it: the scorer skips uncovered
4
+ * methods, so a stale artifact silently weakens the gate.
5
5
  */
6
6
  import crypto from 'node:crypto';
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { spawnChild } from './child-exec.js';
10
+ import { COVERAGE_CAPTURE_DEFAULTS } from './config/gates/coverage.schema.js';
11
+ import { packageScriptArgv } from './detect-package-manager.js';
10
12
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from './full-suite-lock.js';
11
13
  import { Logger } from './Logger.js';
12
14
  import { TIMEOUT_EXIT_CODE } from './process-group.js';
@@ -64,16 +66,18 @@ export function newestSourceMtime(cwd, targetDirs, io = {}) {
64
66
 
65
67
  /**
66
68
  * The stamp records the sources' content digest at capture time, so freshness
67
- * survives mtime churn from checkouts.
69
+ * survives mtime churn from checkouts. It is keyed per artifact, beside it, so
70
+ * two artifacts may share a directory without cross-crediting freshness.
68
71
  *
69
72
  * @param {string} cwd Absolute repo root.
70
73
  * @param {string} coveragePath Repo-relative coverage artifact path.
71
- * @returns {string} Absolute stamp path (`<coverage-dir>/.capture-stamp.json`).
74
+ * @returns {string} Absolute stamp path (`<dir>/.capture-stamp.<basename>.json`).
72
75
  */
73
76
  export function captureStampPath(cwd, coveragePath) {
77
+ const abs = path.resolve(cwd, coveragePath);
74
78
  return path.join(
75
- path.dirname(path.resolve(cwd, coveragePath)),
76
- '.capture-stamp.json',
79
+ path.dirname(abs),
80
+ `.capture-stamp.${path.basename(abs)}.json`,
77
81
  );
78
82
  }
79
83
 
@@ -505,7 +509,7 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
505
509
  }
506
510
 
507
511
  /**
508
- * The capture contract every coverage consumer leans on: `test:coverage`
512
+ * The capture contract every coverage consumer leans on: the capture script
509
513
  * writes Istanbul per-file JSON at `coveragePath`. A summary-only reporter
510
514
  * cannot feed the coverage or CRAP baselines (CRAP joins per-function maps).
511
515
  *
@@ -514,11 +518,11 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
514
518
  */
515
519
  function missingCoverageArtifactMessage(
516
520
  abs,
517
- script = 'test:coverage',
521
+ script = COVERAGE_CAPTURE_DEFAULTS.captureScript,
518
522
  configKey = 'delivery.quality.gates.coverage.coveragePath',
519
523
  ) {
520
524
  return (
521
- `coverage artifact not found at ${abs}. \`npm run ${script}\` must ` +
525
+ `coverage artifact not found at ${abs}. The \`${script}\` script must ` +
522
526
  'write Istanbul per-file JSON (the `json` reporter → coverage-final.json) ' +
523
527
  `at ${configKey}; a \`json-summary\` ` +
524
528
  '(coverage-summary.json) alone cannot feed the coverage or CRAP baselines.'
@@ -564,7 +568,7 @@ export function requireCaptureArtifact(
564
568
  const abs = path.resolve(cwd, coveragePath);
565
569
  if (existsSync(abs)) return 0;
566
570
  logger.error(
567
- `[coverage-capture] ✖ ${script ?? 'test:coverage'} passed but ${missingCoverageArtifactMessage(abs, script, configKey)}`,
571
+ `[coverage-capture] ✖ ${script ?? COVERAGE_CAPTURE_DEFAULTS.captureScript} passed but ${missingCoverageArtifactMessage(abs, script, configKey)}`,
568
572
  );
569
573
  return 1;
570
574
  };
@@ -677,7 +681,8 @@ function dropCaptureStamp({ cwd, coveragePath }) {
677
681
  export const COVERAGE_TIMEOUT_EXIT_CODE = TIMEOUT_EXIT_CODE;
678
682
 
679
683
  /**
680
- * Spawn `npm run <script>` asynchronously as its own process group, so
684
+ * Spawn `<pm> run <script>` (the detected package manager, see
685
+ * `packageScriptArgv`) asynchronously as its own process group, so
681
686
  * the lock heartbeat keeps running and a timeout or signal kills every
682
687
  * worker. Takes no positional file args: node's runner would execute a
683
688
  * forwarded source file as a test instead of filtering the suite. Scope a
@@ -700,17 +705,19 @@ export const COVERAGE_TIMEOUT_EXIT_CODE = TIMEOUT_EXIT_CODE;
700
705
  * @returns {Promise<number>}
701
706
  */
702
707
  export function runCapture(opts = {}) {
703
- const { script = 'test:coverage', log = () => {} } = opts;
708
+ const { script = COVERAGE_CAPTURE_DEFAULTS.captureScript, log = () => {} } =
709
+ opts;
704
710
  dropCaptureStamp(opts);
705
- const args = ['run', script];
706
- log(`[coverage-capture] ▶ npm ${args.join(' ')}`);
711
+ const [cmd, ...args] = packageScriptArgv(opts.cwd ?? process.cwd(), script);
712
+ const command = [cmd, ...args].join(' ');
713
+ log(`[coverage-capture] ▶ ${command}`);
707
714
  return runSupervisedSuite({
708
715
  ...opts,
709
- cmd: 'npm',
716
+ cmd,
710
717
  args,
711
718
  onTimeout: () =>
712
719
  log(
713
- `[coverage-capture] ⏱ npm run ${script} exceeded ${opts.timeoutMs}ms — killed its process group. Returning exit ${COVERAGE_TIMEOUT_EXIT_CODE}.`,
720
+ `[coverage-capture] ⏱ ${command} exceeded ${opts.timeoutMs}ms — killed its process group. Returning exit ${COVERAGE_TIMEOUT_EXIT_CODE}.`,
714
721
  ),
715
722
  });
716
723
  }
@@ -725,7 +732,7 @@ function lockWaitExpiredMessage(code) {
725
732
  * @param {string} script
726
733
  */
727
734
  function timeoutMessage(code, script) {
728
- return `[coverage-capture] ⏱ npm run ${script} timed out and was killed (exit ${code}) — no test verdict exists. This is usually host contention, not a failing test; re-run once the host is quieter.`;
735
+ return `[coverage-capture] ⏱ the ${script} capture script timed out and was killed (exit ${code}) — no test verdict exists. This is usually host contention, not a failing test; re-run once the host is quieter.`;
729
736
  }
730
737
 
731
738
  /**
@@ -733,7 +740,7 @@ function timeoutMessage(code, script) {
733
740
  * @param {string} script
734
741
  */
735
742
  function failingSuiteMessage(code, script) {
736
- return `[coverage-capture] ✖ npm run ${script} exited ${code}. Fix failing tests or coverage-threshold breaches before re-running the CRAP gate.`;
743
+ return `[coverage-capture] ✖ the ${script} capture script exited ${code}. Fix failing tests or coverage-threshold breaches before re-running the CRAP gate.`;
737
744
  }
738
745
 
739
746
  /**
@@ -759,7 +766,11 @@ const FAILING_SUITE_REPORT = Object.freeze(['error', failingSuiteMessage]);
759
766
  * @param {string} [script]
760
767
  * @returns {number}
761
768
  */
762
- export function reportCaptureFailure(code, logger, script = 'test:coverage') {
769
+ export function reportCaptureFailure(
770
+ code,
771
+ logger,
772
+ script = COVERAGE_CAPTURE_DEFAULTS.captureScript,
773
+ ) {
763
774
  const [level, message] =
764
775
  NON_FAILURE_CAPTURE_EXITS[code] ?? FAILING_SUITE_REPORT;
765
776
  logger[level](message(code, script));
@@ -214,44 +214,62 @@ function getEntryIndex(entry) {
214
214
  return idx;
215
215
  }
216
216
 
217
+ function statementCoverageOverLines(idx, fromLine, toLine) {
218
+ let total = 0;
219
+ let covered = 0;
220
+ for (let line = fromLine; line <= toLine; line += 1) {
221
+ const bucket = idx.statementsByLine.get(line);
222
+ if (!bucket) continue;
223
+ total += bucket.total;
224
+ covered += bucket.covered;
225
+ }
226
+ return { total, covered };
227
+ }
228
+
217
229
  /**
218
230
  * Executed fraction of statements in the method's range (0 for an empty
219
231
  * range, `null` for no data). `startLine` MUST be in original-source
220
232
  * coordinates. The entry index is cached on the entry.
221
233
  *
234
+ * No `fnMap` range (V8 folds a callback into its parent) falls back to the
235
+ * statements on `[startLine, endLine]`; an empty span is `null`.
236
+ *
222
237
  * @param {object|null} entry One inner value from a `coverage-final.json` map.
223
238
  * @param {number} startLine The method's start line, in entry coordinates.
239
+ * @param {number} [endLine]
224
240
  * @returns {number|null}
225
241
  */
226
- export function coverageForMethodInEntry(entry, startLine) {
242
+ export function coverageForMethodInEntry(entry, startLine, endLine) {
227
243
  if (!entry || typeof entry !== 'object') return null;
228
244
  const idx = getEntryIndex(entry);
229
245
  const range = resolveFnRangeForLine(idx, startLine);
230
- if (!range) return null;
231
- const { fnStart, fnEnd } = range;
232
-
233
- let total = 0;
234
- let covered = 0;
235
- for (let line = fnStart; line <= fnEnd; line += 1) {
236
- const bucket = idx.statementsByLine.get(line);
237
- if (!bucket) continue;
238
- total += bucket.total;
239
- covered += bucket.covered;
246
+ if (range) {
247
+ const { total, covered } = statementCoverageOverLines(
248
+ idx,
249
+ range.fnStart,
250
+ range.fnEnd,
251
+ );
252
+ return total === 0 ? 0 : covered / total;
240
253
  }
241
-
242
- if (total === 0) return 0;
243
- return covered / total;
254
+ if (typeof endLine !== 'number') return null;
255
+ const { total, covered } = statementCoverageOverLines(
256
+ idx,
257
+ startLine,
258
+ endLine,
259
+ );
260
+ return total === 0 ? null : covered / total;
244
261
  }
245
262
 
246
263
  /**
247
264
  * @param {object|null} map Parsed `coverage-final.json`.
248
265
  * @param {string} relPath Repo-relative path of the source file.
249
266
  * @param {number} startLine The method's start line, in entry coordinates.
267
+ * @param {number} [endLine]
250
268
  * @returns {number|null} Coverage in [0, 1], or null when the file or method
251
269
  * is absent.
252
270
  */
253
- export function coverageByMethod(map, relPath, startLine) {
271
+ export function coverageByMethod(map, relPath, startLine, endLine) {
254
272
  const entry = findFileEntry(map, relPath);
255
273
  if (!entry) return null;
256
- return coverageForMethodInEntry(entry, startLine);
274
+ return coverageForMethodInEntry(entry, startLine, endLine);
257
275
  }
@@ -10,6 +10,7 @@
10
10
 
11
11
  import os from 'node:os';
12
12
  import { Worker } from 'node:worker_threads';
13
+ import { defaultSleep } from './util/sleep.js';
13
14
 
14
15
  const defaultWorkerFactory = (script, options) => new Worker(script, options);
15
16
 
@@ -136,10 +137,7 @@ export async function runOnPool(workerScript, items, opts = {}) {
136
137
  else worker.once('exit', resolve);
137
138
  });
138
139
  // Never unref: an idle-looking loop trips test-runner cancellation.
139
- await Promise.race([
140
- exited,
141
- new Promise((resolve) => setTimeout(resolve, 1000)),
142
- ]);
140
+ await Promise.race([exited, defaultSleep(1000)]);
143
141
  }
144
142
  }
145
143
  try {
@@ -40,6 +40,20 @@ function resolveCoordinate(rawStartLine, mapLine) {
40
40
  : { startLine: rawStartLine, coordinateSystem: COORDINATE_TRANSPILED };
41
41
  }
42
42
 
43
+ /**
44
+ * `undefined` when unmapped, which keeps the statement-span fallback off.
45
+ *
46
+ * @param {unknown} rawEndLine
47
+ * @param {((line: number) => number|null)|null} mapLine
48
+ * @returns {number|undefined}
49
+ */
50
+ function resolveEndLine(rawEndLine, mapLine) {
51
+ if (typeof rawEndLine !== 'number') return undefined;
52
+ if (typeof mapLine !== 'function') return rawEndLine;
53
+ const mapped = mapLine(rawEndLine);
54
+ return typeof mapped === 'number' ? mapped : undefined;
55
+ }
56
+
43
57
  /**
44
58
  * Raw per-method CRAP rows, shared by the CRAP-only and combined MI paths.
45
59
  * A row still in transpiled coordinates joins no coverage: a transpiled line
@@ -74,7 +88,11 @@ export function methodRowsFromReport(report, coverageForFile, mapLine = null) {
74
88
  const cyclomatic = m?.cyclomatic ?? 0;
75
89
  const coverage =
76
90
  coverageForFile && coordinateSystem === COORDINATE_ORIGINAL
77
- ? coverageForMethodInEntry(coverageForFile, startLine)
91
+ ? coverageForMethodInEntry(
92
+ coverageForFile,
93
+ startLine,
94
+ resolveEndLine(m?.lineEnd, mapLine),
95
+ )
78
96
  : null;
79
97
  const crap = coverage === null ? null : crapFormula(cyclomatic, coverage);
80
98
  rows.push({
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { canonicalise as canonicalisePath } from './baselines/path-canon.js';
4
+ import { COVERAGE_CAPTURE_DEFAULTS } from './config/gates/coverage.schema.js';
4
5
  import { findCoverageEntry } from './coverage-utils.js';
5
6
  import { POOL_SERIAL_THRESHOLD, runOnPool } from './cpu-pool.js';
6
7
  import {
@@ -167,7 +168,7 @@ const MIN_RESOLUTION_SAMPLE = 25;
167
168
  export function checkResolutionFloor(
168
169
  resolution,
169
170
  floor,
170
- captureScript = 'test:coverage',
171
+ captureScript = COVERAGE_CAPTURE_DEFAULTS.captureScript,
171
172
  ) {
172
173
  if (!resolution) return null;
173
174
  const { joinableMethods = 0, resolvedMethods = 0, rate = 1 } = resolution;
@@ -5,43 +5,61 @@
5
5
  * @module lib/dead-exports-knip
6
6
  */
7
7
 
8
- import { spawnSync } from 'node:child_process';
9
8
  import fs from 'node:fs';
10
9
  import process from 'node:process';
10
+ import { spawnChild } from './child-exec.js';
11
+
12
+ const KNIP_MAX_ISSUE_STATUS = 1;
11
13
 
12
14
  /**
13
- * Never throws; on error the caller treats current rows as empty, which
14
- * surfaces every baseline row as removed — loud but safe.
15
+ * Never throws; the caller fails closed on `{ ok: false }`. `spawn` is the
16
+ * run seam inside `spawnChild`, so a fake still gets the buffer ceiling.
15
17
  *
16
18
  * `production` requires the `!`-suffixed entry patterns in `knip.json`
17
19
  * (test globs deliberately lack it, so test-only exports read as dead);
18
20
  * without them production mode silently reports nothing.
19
21
  *
20
- * @param {{ cwd?: string, spawn?: typeof spawnSync, production?: boolean }} [opts]
22
+ * @param {{ cwd?: string, spawn?: Function, production?: boolean }} [opts]
21
23
  * @returns {{ ok: true, envelope: unknown } | { ok: false, error: string }}
22
24
  */
23
25
  export function runKnip({
24
26
  cwd = process.cwd(),
25
- spawn = spawnSync,
27
+ spawn,
26
28
  production = false,
27
29
  } = {}) {
28
30
  const args = ['knip', '--reporter', 'json', '--no-progress'];
29
31
  if (production) args.push('--production');
30
- const result = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
32
+ const isWindows = process.platform === 'win32';
33
+ const result = spawnChild(isWindows ? 'npx.cmd' : 'npx', args, {
31
34
  cwd,
32
35
  stdio: ['ignore', 'pipe', 'pipe'],
33
- encoding: 'utf-8',
34
- shell: process.platform === 'win32',
36
+ shell: isWindows,
37
+ run: spawn,
35
38
  });
39
+ return interpretKnipResult(result);
40
+ }
41
+
42
+ /** Knip exits 1 when it reports issues, so only a status above 1 fails. */
43
+ function interpretKnipResult(result) {
36
44
  if (result.error) {
37
45
  return { ok: false, error: `spawn failed: ${result.error.message}` };
38
46
  }
39
- const stdout = typeof result.stdout === 'string' ? result.stdout : '';
40
- if (stdout.trim().length === 0) {
47
+ if (result.status > KNIP_MAX_ISSUE_STATUS) {
48
+ return {
49
+ ok: false,
50
+ error: `knip exited ${result.status}: ${String(result.stderr ?? '').trim()}`,
51
+ };
52
+ }
53
+ return parseKnipStdout(result.stdout);
54
+ }
55
+
56
+ function parseKnipStdout(stdout) {
57
+ const text = typeof stdout === 'string' ? stdout : '';
58
+ if (text.trim().length === 0) {
41
59
  return { ok: false, error: 'knip produced empty stdout' };
42
60
  }
43
61
  try {
44
- return { ok: true, envelope: JSON.parse(stdout) };
62
+ return { ok: true, envelope: JSON.parse(text) };
45
63
  } catch (err) {
46
64
  return {
47
65
  ok: false,
@@ -40,3 +40,16 @@ export function detectPackageManagerWithWorkspace(
40
40
  pm === 'pnpm' && exists(path.join(root, 'pnpm-workspace.yaml'));
41
41
  return { packageManager: pm, workspaceRoot };
42
42
  }
43
+
44
+ /**
45
+ * The argv that runs `package.json` script `script` under `root`'s package
46
+ * manager — `npm` when none is detected. All four managers honour `run`.
47
+ *
48
+ * @param {string} root - Absolute directory to probe.
49
+ * @param {string} script - The `package.json` script name.
50
+ * @param {(p: string) => boolean} [exists=fs.existsSync] - Path existence probe.
51
+ * @returns {string[]} `[<pm>, 'run', script]`.
52
+ */
53
+ export function packageScriptArgv(root, script, exists = fs.existsSync) {
54
+ return [detectPackageManager(root, exists) ?? 'npm', 'run', script];
55
+ }
@@ -5,13 +5,14 @@
5
5
 
6
6
  import { spawn as defaultSpawn } from 'node:child_process';
7
7
 
8
+ import { ensureGhEnv } from '../gh-env.js';
8
9
  import { LABEL_COLORS } from '../label-constants.js';
9
10
 
10
11
  export const DEFAULT_RUN_CHILD_TIMEOUT_MS = 30000;
11
12
 
12
13
  /**
13
- * The feedback loop's single spawn helper. Never throws: spawn errors land in
14
- * `spawnError`; an overrun is SIGKILL'd and resolves `timedOut: true`.
14
+ * The feedback loop's single spawn helper (gh env ensured first). Never
15
+ * throws: spawn and config errors land in `spawnError`; an overrun is SIGKILL'd and resolves `timedOut: true`.
15
16
  * `timeoutMs` of `0`/`Infinity` disables the watchdog.
16
17
  *
17
18
  * @param {object} opts
@@ -32,6 +33,7 @@ export function runChild({
32
33
  return new Promise((resolve) => {
33
34
  let child;
34
35
  try {
36
+ ensureGhEnv();
35
37
  child = spawnImpl(cmd, args, {
36
38
  stdio: ['ignore', 'pipe', 'pipe'],
37
39
  cwd,