mandrel 2.89.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 (175) 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 +38 -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/board-backfill.js +253 -0
  14. package/.agents/scripts/check-arch-cycles.js +1 -5
  15. package/.agents/scripts/check-context-budget.js +1 -5
  16. package/.agents/scripts/check-cyclomatic.js +1 -5
  17. package/.agents/scripts/check-dead-exports.js +23 -14
  18. package/.agents/scripts/check-doc-links.js +4 -4
  19. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  20. package/.agents/scripts/coverage-capture.js +14 -6
  21. package/.agents/scripts/diagnose-friction.js +8 -10
  22. package/.agents/scripts/generate-workflows-doc.js +5 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  24. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  25. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  26. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  27. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  28. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  29. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  30. package/.agents/scripts/lib/baselines/components.js +5 -5
  31. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  32. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  33. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  34. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  36. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  37. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  38. package/.agents/scripts/lib/baselines/writer.js +4 -4
  39. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  40. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  41. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  42. package/.agents/scripts/lib/child-exec.js +4 -4
  43. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  44. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  45. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  46. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  47. package/.agents/scripts/lib/close-validation/process.js +5 -1
  48. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  49. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  50. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  51. package/.agents/scripts/lib/config/commands.js +82 -7
  52. package/.agents/scripts/lib/config/explain.js +2 -1
  53. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  54. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  55. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  56. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  57. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  58. package/.agents/scripts/lib/config/git-roots.js +120 -0
  59. package/.agents/scripts/lib/config/quality.js +46 -50
  60. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  61. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  62. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  63. package/.agents/scripts/lib/config-resolver.js +5 -9
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  66. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  67. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  68. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  69. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  70. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  71. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture.js +80 -43
  73. package/.agents/scripts/lib/coverage-utils.js +34 -16
  74. package/.agents/scripts/lib/cpu-pool.js +2 -4
  75. package/.agents/scripts/lib/crap-engine.js +19 -1
  76. package/.agents/scripts/lib/crap-utils.js +2 -1
  77. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  78. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  79. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  80. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  81. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  82. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  83. package/.agents/scripts/lib/gh-env.js +72 -0
  84. package/.agents/scripts/lib/gh-exec.js +26 -1
  85. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  86. package/.agents/scripts/lib/npm-scripts.js +1 -1
  87. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  88. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  89. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  90. package/.agents/scripts/lib/orchestration/board-access-latch.js +112 -0
  91. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  92. package/.agents/scripts/lib/orchestration/column-sync.js +107 -52
  93. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  94. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  95. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  96. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  97. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  98. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  99. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +44 -17
  100. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  101. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  102. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  103. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  104. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  105. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  106. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  107. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  108. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  109. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  110. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  111. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  112. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  113. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  114. package/.agents/scripts/lib/orchestration/story-handoff.js +27 -6
  115. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  116. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  117. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  118. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  119. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  120. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  121. package/.agents/scripts/lib/source-extensions.js +30 -15
  122. package/.agents/scripts/lib/test-run-credit.js +1 -9
  123. package/.agents/scripts/lib/test-temp.js +22 -21
  124. package/.agents/scripts/lib/util/ajv.js +111 -0
  125. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  126. package/.agents/scripts/lib/util/paths.js +51 -0
  127. package/.agents/scripts/lib/util/sleep.js +6 -0
  128. package/.agents/scripts/lib/util/slug.js +12 -0
  129. package/.agents/scripts/lib/validation-evidence.js +19 -40
  130. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  131. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  132. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  133. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  134. package/.agents/scripts/lint-issue-body.js +2 -2
  135. package/.agents/scripts/plan-context.js +2 -7
  136. package/.agents/scripts/providers/github/auth.js +3 -3
  137. package/.agents/scripts/providers/github/board-add.js +18 -9
  138. package/.agents/scripts/providers/github/errors.js +3 -1
  139. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  140. package/.agents/scripts/providers/github/issues.js +6 -2
  141. package/.agents/scripts/providers/github/mappers.js +1 -5
  142. package/.agents/scripts/providers/github/projects-v2-graphql.js +26 -6
  143. package/.agents/scripts/providers/github/search-budget.js +3 -1
  144. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  145. package/.agents/scripts/sync-agentrc.js +5 -14
  146. package/.agents/scripts/sync-claude-agents.js +38 -150
  147. package/.agents/scripts/sync-claude-commands.js +35 -218
  148. package/.agents/scripts/update-coverage-baseline.js +1 -1
  149. package/.agents/scripts/update-crap-baseline.js +1 -1
  150. package/.agents/scripts/update-duplication-baseline.js +2 -16
  151. package/.agents/scripts/validate-skills.js +6 -10
  152. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  153. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  154. package/.agents/workflows/audit-exceptions.md +9 -0
  155. package/.agents/workflows/audit-lean.md +129 -0
  156. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  157. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  158. package/.agents/workflows/helpers/code-review.md +15 -1
  159. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  160. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  161. package/.agents/workflows/mandrel-plan.md +2 -2
  162. package/docs/CHANGELOG.md +48 -0
  163. package/lib/cli/doctor-checks/codex.js +6 -5
  164. package/lib/cli/doctor-checks/llm-review.js +102 -0
  165. package/lib/cli/doctor-checks/project-access.js +124 -0
  166. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  167. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  168. package/lib/cli/doctor-checks/toolchain.js +5 -3
  169. package/lib/cli/registry.js +11 -0
  170. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  171. package/lib/migrations/index.js +6 -0
  172. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  173. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  174. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  175. package/package.json +1 -3
@@ -1,13 +1,16 @@
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
- import { spawnSync } from 'node:child_process';
7
6
  import crypto from 'node:crypto';
8
7
  import fs from 'node:fs';
9
8
  import path from 'node:path';
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';
13
+ import { Logger } from './Logger.js';
11
14
  import { TIMEOUT_EXIT_CODE } from './process-group.js';
12
15
  import {
13
16
  isScorableSourceFile,
@@ -63,16 +66,18 @@ export function newestSourceMtime(cwd, targetDirs, io = {}) {
63
66
 
64
67
  /**
65
68
  * The stamp records the sources' content digest at capture time, so freshness
66
- * 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.
67
71
  *
68
72
  * @param {string} cwd Absolute repo root.
69
73
  * @param {string} coveragePath Repo-relative coverage artifact path.
70
- * @returns {string} Absolute stamp path (`<coverage-dir>/.capture-stamp.json`).
74
+ * @returns {string} Absolute stamp path (`<dir>/.capture-stamp.<basename>.json`).
71
75
  */
72
76
  export function captureStampPath(cwd, coveragePath) {
77
+ const abs = path.resolve(cwd, coveragePath);
73
78
  return path.join(
74
- path.dirname(path.resolve(cwd, coveragePath)),
75
- '.capture-stamp.json',
79
+ path.dirname(abs),
80
+ `.capture-stamp.${path.basename(abs)}.json`,
76
81
  );
77
82
  }
78
83
 
@@ -114,6 +119,45 @@ function foldDirtySources({
114
119
  return count;
115
120
  }
116
121
 
122
+ /**
123
+ * A digest's git runner, through `spawnChild` so a repo whose index listing
124
+ * outgrows Node's 1 MiB default buffer still digests (no ENOBUFS). A failure
125
+ * throws an error tagged with the subcommand, for the warning.
126
+ *
127
+ * @param {string} cwd
128
+ * @param {{ spawnSync?: Function }} io `io.spawnSync` is the test seam.
129
+ * @returns {(...args: string[]) => string}
130
+ */
131
+ function digestGit(cwd, io) {
132
+ return (...args) => {
133
+ const res = spawnChild('git', args, { cwd, run: io.spawnSync });
134
+ if (res?.error || res?.status !== 0) {
135
+ const err =
136
+ res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
137
+ err.gitSubcommand = args[0];
138
+ if (err.code === undefined) err.code = `exit ${res?.status}`;
139
+ throw err;
140
+ }
141
+ return res.stdout ?? '';
142
+ };
143
+ }
144
+
145
+ /**
146
+ * No digest never matches, so an unfreshable stamp is announced, not silent.
147
+ *
148
+ * @param {Error & { gitSubcommand?: string, code?: string }} err
149
+ * @param {{ logger?: { warn: Function } }} io
150
+ * @returns {null}
151
+ */
152
+ function warnDigestUnavailable(err, io) {
153
+ const logger = io.logger ?? Logger;
154
+ const subcommand = err?.gitSubcommand ?? 'digest';
155
+ logger.warn(
156
+ `[coverage-capture] ⚠ git ${subcommand} failed (${err?.code ?? 'unknown'}); digest unavailable, stamp cannot read fresh.`,
157
+ );
158
+ return null;
159
+ }
160
+
117
161
  /**
118
162
  * Digest of the scorable sources under `targetDirs`: `git ls-files -s` of
119
163
  * tracked content plus dirty files' bytes, so it moves only on content change.
@@ -122,24 +166,17 @@ function foldDirtySources({
122
166
  *
123
167
  * @param {string} cwd Absolute repo root.
124
168
  * @param {string[]} targetDirs Repo-relative directories to digest.
125
- * @param {{ spawnSync?: typeof spawnSync, readFileSync?: typeof fs.readFileSync }} [io]
169
+ * @param {{ spawnSync?: Function, readFileSync?: typeof fs.readFileSync, logger?: { warn: Function } }} [io]
126
170
  * @returns {string | null} Hex SHA-256 digest, or null when unavailable.
127
171
  */
128
172
  export function computeContentDigest(cwd, targetDirs, io = {}) {
129
- const spawn = io.spawnSync ?? spawnSync;
130
173
  const readFileSync = io.readFileSync ?? fs.readFileSync;
131
174
  const dirs = (targetDirs ?? []).filter(
132
175
  (d) => typeof d === 'string' && d.length > 0,
133
176
  );
134
177
  if (dirs.length === 0) return null;
135
178
 
136
- const git = (...args) => {
137
- const res = spawn('git', args, { cwd, encoding: 'utf8' });
138
- if (res?.error || res?.status !== 0) {
139
- throw res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
140
- }
141
- return res.stdout ?? '';
142
- };
179
+ const git = digestGit(cwd, io);
143
180
 
144
181
  try {
145
182
  const hash = crypto.createHash('sha256');
@@ -156,8 +193,8 @@ export function computeContentDigest(cwd, targetDirs, io = {}) {
156
193
  });
157
194
  if (tracked.length + scorableDirty === 0) return null;
158
195
  return hash.digest('hex');
159
- } catch {
160
- return null;
196
+ } catch (err) {
197
+ return warnDigestUnavailable(err, io);
161
198
  }
162
199
  }
163
200
 
@@ -197,24 +234,17 @@ export function filterSuiteInputPaths(files, coveragePath = null) {
197
234
  *
198
235
  * @param {string} cwd
199
236
  * @param {string} coveragePath
200
- * @param {{ spawnSync?: typeof spawnSync, readFileSync?: typeof fs.readFileSync }} [io]
237
+ * @param {{ spawnSync?: Function, readFileSync?: typeof fs.readFileSync, logger?: { warn: Function } }} [io]
201
238
  * @returns {string | null}
202
239
  */
203
240
  export function computeTreeDigest(cwd, coveragePath, io = {}) {
204
- const spawn = io.spawnSync ?? spawnSync;
205
241
  const readFileSync = io.readFileSync ?? fs.readFileSync;
206
242
  const pathspec = [
207
243
  '--',
208
244
  '.',
209
245
  ...suiteDigestExcludedDirs(coveragePath).map((dir) => `:(exclude)${dir}`),
210
246
  ];
211
- const git = (...args) => {
212
- const res = spawn('git', args, { cwd, encoding: 'utf8' });
213
- if (res?.error || res?.status !== 0) {
214
- throw res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
215
- }
216
- return res.stdout ?? '';
217
- };
247
+ const git = digestGit(cwd, io);
218
248
  try {
219
249
  const hash = crypto.createHash('sha256');
220
250
  hash.update(git('ls-files', '-s', ...pathspec));
@@ -231,8 +261,8 @@ export function computeTreeDigest(cwd, coveragePath, io = {}) {
231
261
  select: () => true,
232
262
  });
233
263
  return hash.digest('hex');
234
- } catch {
235
- return null;
264
+ } catch (err) {
265
+ return warnDigestUnavailable(err, io);
236
266
  }
237
267
  }
238
268
 
@@ -479,7 +509,7 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
479
509
  }
480
510
 
481
511
  /**
482
- * The capture contract every coverage consumer leans on: `test:coverage`
512
+ * The capture contract every coverage consumer leans on: the capture script
483
513
  * writes Istanbul per-file JSON at `coveragePath`. A summary-only reporter
484
514
  * cannot feed the coverage or CRAP baselines (CRAP joins per-function maps).
485
515
  *
@@ -488,11 +518,11 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
488
518
  */
489
519
  function missingCoverageArtifactMessage(
490
520
  abs,
491
- script = 'test:coverage',
521
+ script = COVERAGE_CAPTURE_DEFAULTS.captureScript,
492
522
  configKey = 'delivery.quality.gates.coverage.coveragePath',
493
523
  ) {
494
524
  return (
495
- `coverage artifact not found at ${abs}. \`npm run ${script}\` must ` +
525
+ `coverage artifact not found at ${abs}. The \`${script}\` script must ` +
496
526
  'write Istanbul per-file JSON (the `json` reporter → coverage-final.json) ' +
497
527
  `at ${configKey}; a \`json-summary\` ` +
498
528
  '(coverage-summary.json) alone cannot feed the coverage or CRAP baselines.'
@@ -538,7 +568,7 @@ export function requireCaptureArtifact(
538
568
  const abs = path.resolve(cwd, coveragePath);
539
569
  if (existsSync(abs)) return 0;
540
570
  logger.error(
541
- `[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)}`,
542
572
  );
543
573
  return 1;
544
574
  };
@@ -651,7 +681,8 @@ function dropCaptureStamp({ cwd, coveragePath }) {
651
681
  export const COVERAGE_TIMEOUT_EXIT_CODE = TIMEOUT_EXIT_CODE;
652
682
 
653
683
  /**
654
- * 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
655
686
  * the lock heartbeat keeps running and a timeout or signal kills every
656
687
  * worker. Takes no positional file args: node's runner would execute a
657
688
  * forwarded source file as a test instead of filtering the suite. Scope a
@@ -674,17 +705,19 @@ export const COVERAGE_TIMEOUT_EXIT_CODE = TIMEOUT_EXIT_CODE;
674
705
  * @returns {Promise<number>}
675
706
  */
676
707
  export function runCapture(opts = {}) {
677
- const { script = 'test:coverage', log = () => {} } = opts;
708
+ const { script = COVERAGE_CAPTURE_DEFAULTS.captureScript, log = () => {} } =
709
+ opts;
678
710
  dropCaptureStamp(opts);
679
- const args = ['run', script];
680
- 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}`);
681
714
  return runSupervisedSuite({
682
715
  ...opts,
683
- cmd: 'npm',
716
+ cmd,
684
717
  args,
685
718
  onTimeout: () =>
686
719
  log(
687
- `[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}.`,
688
721
  ),
689
722
  });
690
723
  }
@@ -699,7 +732,7 @@ function lockWaitExpiredMessage(code) {
699
732
  * @param {string} script
700
733
  */
701
734
  function timeoutMessage(code, script) {
702
- 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.`;
703
736
  }
704
737
 
705
738
  /**
@@ -707,7 +740,7 @@ function timeoutMessage(code, script) {
707
740
  * @param {string} script
708
741
  */
709
742
  function failingSuiteMessage(code, script) {
710
- 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.`;
711
744
  }
712
745
 
713
746
  /**
@@ -733,7 +766,11 @@ const FAILING_SUITE_REPORT = Object.freeze(['error', failingSuiteMessage]);
733
766
  * @param {string} [script]
734
767
  * @returns {number}
735
768
  */
736
- export function reportCaptureFailure(code, logger, script = 'test:coverage') {
769
+ export function reportCaptureFailure(
770
+ code,
771
+ logger,
772
+ script = COVERAGE_CAPTURE_DEFAULTS.captureScript,
773
+ ) {
737
774
  const [level, message] =
738
775
  NON_FAILURE_CAPTURE_EXITS[code] ?? FAILING_SUITE_REPORT;
739
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,
@@ -15,6 +15,7 @@ import path from 'node:path';
15
15
 
16
16
  import { getQuality } from './config/quality.js';
17
17
  import { mainCheckoutRoot } from './config/temp-paths.js';
18
+ import { packageScriptArgv } from './detect-package-manager.js';
18
19
  import { isFirstInLine, waitInLine } from './full-suite-queue.js';
19
20
  import { acquireSweepLock } from './single-story-sweep/sweep-lock.js';
20
21
  import {
@@ -51,9 +52,6 @@ const FALSEY = /^(0|false|off|no)$/i;
51
52
 
52
53
  const LOCK_TAG = '[full-suite-lock]';
53
54
 
54
- /** The argv coverage capture spawns — its workload identity. */
55
- const COVERAGE_CAPTURE_ARGV = Object.freeze(['npm', 'run', 'test:coverage']);
56
-
57
55
  const LOCK_DEFAULTS = Object.freeze({
58
56
  enabled: true,
59
57
  log: () => {},
@@ -299,9 +297,26 @@ export function fullSuiteLockPolicy(config, env = process.env, argv) {
299
297
  };
300
298
  }
301
299
 
300
+ /**
301
+ * The argv a capture spawns — its workload identity: `<pm> run <script>`,
302
+ * where `script` is the pass's own (an own CRAP source) or the coverage
303
+ * gate's `captureScript`.
304
+ *
305
+ * @param {object} [config]
306
+ * @param {{ cwd?: string, script?: string }} [captureOpts]
307
+ * @returns {string[]}
308
+ */
309
+ function coverageCaptureArgv(config, { cwd, script } = {}) {
310
+ return packageScriptArgv(
311
+ cwd ?? process.cwd(),
312
+ script ?? getQuality(config).coverage.captureScript,
313
+ );
314
+ }
315
+
302
316
  /**
303
317
  * Serialize a capture runner's spawn. Wrapped at the one call site below
304
- * every skip/freshness decision, so a credited capture never waits.
318
+ * every skip/freshness decision, so a credited capture never waits. The
319
+ * admission policy is resolved per spawn, from that spawn's argv.
305
320
  *
306
321
  * @param {Function} runCaptureFn
307
322
  * @param {object} [config]
@@ -315,14 +330,15 @@ export function lockedCapture(
315
330
  env = process.env,
316
331
  lockOptions = {},
317
332
  ) {
318
- const policy = {
319
- ...fullSuiteLockPolicy(config, env, COVERAGE_CAPTURE_ARGV),
320
- ...lockOptions,
321
- };
322
333
  return (captureOpts = {}) =>
323
334
  withFullSuiteLockAsync(
324
335
  {
325
- ...policy,
336
+ ...fullSuiteLockPolicy(
337
+ config,
338
+ env,
339
+ coverageCaptureArgv(config, captureOpts),
340
+ ),
341
+ ...lockOptions,
326
342
  cwd: captureOpts.cwd,
327
343
  log: captureOpts.log,
328
344
  skipIfSatisfied: freshnessProbe(captureOpts),
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { readBaselineAtRef as defaultReadAtRef } from '../baseline-loader.js';
12
12
  import { Logger } from '../Logger.js';
13
+ import { writeFileAtomic } from '../util/atomic-write.js';
13
14
 
14
15
  export class BaselineNotFoundError extends Error {
15
16
  constructor(message, details = {}) {
@@ -92,18 +93,9 @@ export function writeBaseline({
92
93
  indent = 2,
93
94
  } = {}) {
94
95
  const abs = absPath(baselinePath, projectRoot);
95
- const tmp = `${abs}.tmp`;
96
96
  try {
97
- const serialised = `${JSON.stringify(data, null, indent)}\n`;
98
- fs.mkdirSync(path.dirname(abs), { recursive: true });
99
- fs.writeFileSync(tmp, serialised, 'utf8');
100
- fs.renameSync(tmp, abs);
97
+ writeFileAtomic(abs, `${JSON.stringify(data, null, indent)}\n`);
101
98
  } catch (err) {
102
- try {
103
- fs.rmSync(tmp, { force: true });
104
- } catch {
105
- /* best-effort cleanup */
106
- }
107
99
  throw new BaselineWriteError(
108
100
  `[baseline-store] failed to write baseline at ${baselinePath}: ${err?.message ?? err}`,
109
101
  { path: abs, cause: err },