mandrel 2.87.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 (156) 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 +12 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +11 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/deliver-run.js +11 -0
  17. package/.agents/scripts/diagnose-friction.js +3 -3
  18. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  19. package/.agents/scripts/lib/baselines/crap-updater-cli.js +36 -26
  20. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  21. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  22. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  23. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  24. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  25. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  26. package/.agents/scripts/lib/baselines/writer.js +5 -1
  27. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  28. package/.agents/scripts/lib/child-exec.js +14 -1
  29. package/.agents/scripts/lib/child-stream.js +122 -0
  30. package/.agents/scripts/lib/clean-temp.js +19 -13
  31. package/.agents/scripts/lib/cli-args.js +49 -0
  32. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  33. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  34. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  35. package/.agents/scripts/lib/config/github.js +2 -0
  36. package/.agents/scripts/lib/config/paths.js +14 -3
  37. package/.agents/scripts/lib/config-resolver.js +78 -64
  38. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  39. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  40. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  41. package/.agents/scripts/lib/coverage-capture.js +16 -1
  42. package/.agents/scripts/lib/crap-utils.js +59 -47
  43. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  44. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  45. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  46. package/.agents/scripts/lib/gh-exec.js +45 -2
  47. package/.agents/scripts/lib/gh-transport.js +27 -0
  48. package/.agents/scripts/lib/git-utils.js +16 -9
  49. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  50. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  51. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  52. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  53. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  54. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  55. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  56. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  57. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  58. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  59. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  60. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  61. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  64. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  65. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  66. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  67. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  68. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  69. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  71. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  72. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  73. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  74. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  75. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  76. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  77. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  78. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  79. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  80. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  81. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  82. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  83. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  84. package/.agents/scripts/lib/suite-admission.js +3 -11
  85. package/.agents/scripts/lib/temp-retention.js +25 -11
  86. package/.agents/scripts/lib/test-run-credit.js +2 -5
  87. package/.agents/scripts/lib/transpile.js +193 -31
  88. package/.agents/scripts/lib/util/paths.js +31 -0
  89. package/.agents/scripts/lib/util/sleep.js +15 -0
  90. package/.agents/scripts/lib/validation-evidence.js +29 -3
  91. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  92. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  93. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  94. package/.agents/scripts/lib/workflow-closure.js +1 -8
  95. package/.agents/scripts/notify.js +83 -90
  96. package/.agents/scripts/plan-context.js +8 -4
  97. package/.agents/scripts/providers/github/auth.js +14 -30
  98. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  99. package/.agents/scripts/providers/github/compose.js +1 -0
  100. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  101. package/.agents/scripts/providers/github/identity.js +158 -0
  102. package/.agents/scripts/providers/github/issues.js +2 -2
  103. package/.agents/scripts/providers/github/mappers.js +16 -19
  104. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  105. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  106. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  107. package/.agents/scripts/providers/github.js +10 -2
  108. package/.agents/scripts/quality-preview.js +6 -19
  109. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  110. package/.agents/scripts/single-story-init.js +0 -1
  111. package/.agents/scripts/stories-wave-tick.js +60 -46
  112. package/.agents/scripts/story-handoff.js +2 -23
  113. package/.agents/scripts/story-review-compute.js +3 -22
  114. package/.agents/scripts/sync-claude-agents.js +1 -12
  115. package/.agents/scripts/sync-claude-commands.js +1 -12
  116. package/.agents/scripts/update-crap-baseline.js +10 -19
  117. package/.agents/scripts/update-ticket-state.js +44 -45
  118. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  119. package/.agents/workflows/audit-accessibility.md +1 -1
  120. package/.agents/workflows/audit-adrs.md +1 -1
  121. package/.agents/workflows/audit-architecture.md +1 -1
  122. package/.agents/workflows/audit-baselines.md +2 -2
  123. package/.agents/workflows/audit-clean-code.md +1 -1
  124. package/.agents/workflows/audit-data-model.md +1 -1
  125. package/.agents/workflows/audit-dependencies.md +1 -1
  126. package/.agents/workflows/audit-devops.md +1 -1
  127. package/.agents/workflows/audit-documentation.md +1 -1
  128. package/.agents/workflows/audit-exceptions.md +2 -2
  129. package/.agents/workflows/audit-mobile.md +1 -1
  130. package/.agents/workflows/audit-navigability.md +1 -1
  131. package/.agents/workflows/audit-performance.md +1 -1
  132. package/.agents/workflows/audit-privacy.md +1 -1
  133. package/.agents/workflows/audit-quality.md +1 -1
  134. package/.agents/workflows/audit-security.md +1 -1
  135. package/.agents/workflows/audit-seo.md +1 -1
  136. package/.agents/workflows/audit-sre.md +1 -1
  137. package/.agents/workflows/audit-to-stories.md +9 -7
  138. package/.agents/workflows/audit-ux-ui.md +1 -1
  139. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  140. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  141. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  142. package/.agents/workflows/mandrel-deliver.md +3 -1
  143. package/README.md +6 -3
  144. package/docs/CHANGELOG.md +29 -0
  145. package/lib/cli/doctor-checks/codex.js +240 -0
  146. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  147. package/lib/cli/doctor-checks/payload.js +201 -0
  148. package/lib/cli/doctor-checks/read-json.js +16 -0
  149. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  150. package/lib/cli/doctor-checks/spawn.js +18 -0
  151. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  152. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  153. package/lib/cli/doctor-checks/toolchain.js +137 -0
  154. package/lib/cli/doctor-checks/version-current.js +82 -0
  155. package/lib/cli/registry.js +40 -1330
  156. package/package.json +1 -1
@@ -12,6 +12,7 @@ import {
12
12
  } from './config/agentrc-overlay.js';
13
13
  import { getCiDelivery } from './config/ci.js';
14
14
  import { getCommands } from './config/commands.js';
15
+ import { applyGhConfigDir } from './config/gh-config-dir.js';
15
16
  import { getGitHub } from './config/github.js';
16
17
  import { resolvePaths } from './config/paths.js';
17
18
  import { validateOrchestrationConfig } from './config/validate-orchestration.js';
@@ -52,9 +53,9 @@ export {
52
53
  } from './config/worktree-isolation.js';
53
54
  export { PROJECT_ROOT } from './project-root.js';
54
55
 
55
- // Cache keyed by absolute root path so callers passing different cwds
56
- // (e.g. per-worktree) each get their own resolved config.
57
- const _cacheByRoot = new Map();
56
+ // Keyed by absolute root + validate mode, so per-worktree cwds and a
57
+ // `validate: false` read never answer a validating caller.
58
+ const _cacheByKey = new Map();
58
59
  const _envLoadedRoots = new Set();
59
60
 
60
61
  /**
@@ -137,79 +138,92 @@ function applyDefaults(raw) {
137
138
  }
138
139
 
139
140
  /**
140
- * Returns `{ project, github, planning, delivery, qa?, raw, source }`. A
141
- * missing file falls back to defaults; malformed JSON or a schema failure
142
- * throws.
141
+ * The merged raw config and a human description of where it came from;
142
+ * `raw: null` when neither file exists (zero-config).
143
143
  *
144
- * @param {{ bustCache?: boolean, cwd?: string, validate?: boolean, ctx?: object }} [opts]
144
+ * @param {import('node:fs')} fsImpl
145
+ * @param {string} root
146
+ * @returns {{ raw: object|null, source: string }}
145
147
  */
146
- export function resolveConfig(opts) {
147
- const envCwd = process.env.AP_AGENTRC_CWD;
148
- const root = path.resolve(opts?.cwd ?? envCwd ?? PROJECT_ROOT);
149
- const validate = opts?.validate !== false;
150
- const fsImpl = opts?.ctx?.fs ?? fs;
151
-
152
- if (!opts?.bustCache && _cacheByRoot.has(root)) {
153
- return _cacheByRoot.get(root);
154
- }
155
-
156
- if (!_envLoadedRoots.has(root)) {
157
- loadEnv(root);
158
- _envLoadedRoots.add(root);
159
- }
160
-
148
+ function readRawConfig(fsImpl, root) {
161
149
  const agentrcPath = path.join(root, '.agentrc.json');
162
150
  const localPath = path.join(root, '.agentrc.local.json');
163
151
  const hasAgentrc = fsImpl.existsSync(agentrcPath);
164
152
  const hasLocal = fsImpl.existsSync(localPath);
165
-
166
- if (!hasAgentrc && !hasLocal) {
167
- const blocks = applyDefaults({ ...ZERO_CONFIG_RAW });
168
- const resolved = {
169
- ...blocks,
170
- raw: null,
171
- source: 'built-in defaults',
153
+ if (!hasAgentrc) {
154
+ if (!hasLocal) return { raw: null, source: 'built-in defaults' };
155
+ return {
156
+ raw: deepMergeObjects(
157
+ { ...ZERO_CONFIG_RAW },
158
+ readJsonConfigFile(fsImpl, localPath, '.agentrc.local.json'),
159
+ ),
160
+ source: `${localPath} (overrides built-in defaults)`,
172
161
  };
173
- _cacheByRoot.set(root, resolved);
174
- return resolved;
175
- }
176
-
177
- let raw = hasAgentrc
178
- ? readJsonConfigFile(fsImpl, agentrcPath, '.agentrc.json')
179
- : { ...ZERO_CONFIG_RAW };
180
-
181
- let source = hasAgentrc ? agentrcPath : 'built-in defaults';
182
-
183
- if (hasLocal) {
184
- const localRaw = readJsonConfigFile(
185
- fsImpl,
186
- localPath,
187
- '.agentrc.local.json',
188
- );
189
- raw = deepMergeObjects(raw, localRaw);
190
- source =
191
- source === 'built-in defaults'
192
- ? `${localPath} (overrides built-in defaults)`
193
- : `${localPath} (overrides ${agentrcPath})`;
194
162
  }
163
+ const raw = readJsonConfigFile(fsImpl, agentrcPath, '.agentrc.json');
164
+ if (!hasLocal) return { raw, source: agentrcPath };
165
+ return {
166
+ raw: deepMergeObjects(
167
+ raw,
168
+ readJsonConfigFile(fsImpl, localPath, '.agentrc.local.json'),
169
+ ),
170
+ source: `${localPath} (overrides ${agentrcPath})`,
171
+ };
172
+ }
195
173
 
196
- if (validate) {
197
- const validateAgentrc = getAgentrcValidator();
198
- if (!validateAgentrc(raw)) {
199
- const details = formatAgentrcErrors(validateAgentrc.errors).join(', ');
200
- throw new Error(`[config] Invalid .agentrc.json: ${details}`);
201
- }
174
+ /** @param {object} raw */
175
+ function assertSchemaValid(raw) {
176
+ const validateAgentrc = getAgentrcValidator();
177
+ if (!validateAgentrc(raw)) {
178
+ const details = formatAgentrcErrors(validateAgentrc.errors).join(', ');
179
+ throw new Error(`[config] Invalid .agentrc.json: ${details}`);
202
180
  }
181
+ }
203
182
 
204
- const blocks = applyDefaults(raw);
183
+ /**
184
+ * Defaults applied over `raw`; a zero-config read is never validated.
185
+ *
186
+ * @param {{ raw: object|null, source: string }} read
187
+ * @param {boolean} validate
188
+ */
189
+ function finalizeConfig({ raw, source }, validate) {
190
+ const checked = validate && raw !== null;
191
+ if (checked) assertSchemaValid(raw);
192
+ const blocks = applyDefaults(raw ?? { ...ZERO_CONFIG_RAW });
193
+ if (checked) validateOrchestrationConfig(blocks);
194
+ return { ...blocks, raw, source };
195
+ }
205
196
 
206
- if (validate) validateOrchestrationConfig(blocks);
197
+ function ensureEnvLoaded(root) {
198
+ if (_envLoadedRoots.has(root)) return;
199
+ loadEnv(root);
200
+ _envLoadedRoots.add(root);
201
+ }
207
202
 
208
- const resolved = {
209
- ...blocks,
210
- raw,
211
- source,
212
- };
213
- _cacheByRoot.set(root, resolved);
203
+ /**
204
+ * Returns `{ project, github, planning, delivery, qa?, raw, source }`. A
205
+ * missing file falls back to defaults; malformed JSON or a schema failure
206
+ * throws. A set `github.cliConfigDir` is applied to `GH_CONFIG_DIR`. A call with an injected `ctx.fs` neither reads nor fills the
207
+ * shared cache.
208
+ *
209
+ * @param {{ bustCache?: boolean, cwd?: string, validate?: boolean, ctx?: object }} [opts]
210
+ */
211
+ export function resolveConfig(opts) {
212
+ const root = path.resolve(
213
+ opts?.cwd ?? process.env.AP_AGENTRC_CWD ?? PROJECT_ROOT,
214
+ );
215
+ const validate = opts?.validate !== false;
216
+ const injectedFs = opts?.ctx?.fs;
217
+ const key = `${root}\0${validate}`;
218
+ if (!injectedFs && !opts?.bustCache && _cacheByKey.has(key)) {
219
+ return _cacheByKey.get(key);
220
+ }
221
+ ensureEnvLoaded(root);
222
+ const resolved = finalizeConfig(
223
+ readRawConfig(injectedFs ?? fs, root),
224
+ validate,
225
+ );
226
+ applyGhConfigDir(resolved.github, root, { fsImpl: injectedFs ?? fs });
227
+ if (!injectedFs) _cacheByKey.set(key, resolved);
214
228
  return resolved;
215
229
  }
@@ -183,7 +183,7 @@ const WORKTREE_ISOLATION_SCHEMA = {
183
183
  const MERGE_WATCH_SCHEMA = {
184
184
  type: 'object',
185
185
  description:
186
- "Knobs consumed by the close-and-land merge wait (Story #4543). `mode` (Story #4698) selects the close-time merge posture. `maxWaitSeconds` bounds ONE invocation of the merge wait and its expiry returns a resumable `pending` terminal with no label mutation; `maxBudgetSeconds` bounds the CUMULATIVE wait across resumes (anchored at the PR's createdAt, so a resume does not restart the clock) and exhausting it is the genuine give-up that classifies and blocks. The poll cadence is internal (at most 30s while checks run, at most 10s once they are green and the PR is unmerged); it and the cap of 3 behind-the-base updates are not configurable.",
186
+ "Knobs consumed by the close-and-land merge wait (Story #4543). `mode` (Story #4698) selects the close-time merge posture. `maxWaitSeconds` bounds ONE invocation of the merge wait and its expiry returns a resumable `pending` terminal with no label mutation; `maxBudgetSeconds` bounds the CUMULATIVE wait across resumes (anchored at the later of the PR's createdAt and its latest auto-merge arm, so a `--wait` resume does not restart the clock while a re-close that re-arms gets a fresh budget) and exhausting it is the genuine give-up that classifies and blocks. The poll cadence is internal (at most 30s while checks run, at most 10s once they are green and the PR is unmerged); it and the cap of 3 behind-the-base updates are not configurable.",
187
187
  properties: {
188
188
  mode: {
189
189
  type: 'string',
@@ -201,7 +201,7 @@ const MERGE_WATCH_SCHEMA = {
201
201
  type: 'integer',
202
202
  minimum: 1,
203
203
  description:
204
- "Cumulative wall-clock budget (seconds) across merge-wait resumes, anchored at the PR's createdAt. Default 3600 (60 minutes). Exhausting this classifies the block and transitions the Story to agent::blocked.",
204
+ "Cumulative wall-clock budget (seconds) across merge-wait resumes, anchored at the later of the PR's createdAt and its latest auto-merge arm (`autoMergeRequest.enabledAt`), so a re-close that re-arms starts a fresh budget; without an arm time it falls back to createdAt, then to the invocation start. Default 3600 (60 minutes). Exhausting this classifies the block and transitions the Story to agent::blocked.",
205
205
  default: 3600,
206
206
  },
207
207
  },
@@ -368,7 +368,8 @@ const TEMP_RETENTION_SCHEMA = {
368
368
  },
369
369
  auditResults: {
370
370
  type: 'boolean',
371
- description: '<tempRoot>/audits/ — audit lens reports.',
371
+ description:
372
+ '<tempRoot>/audits/ — audit lens reports (audit-results/) and audit working artifacts.',
372
373
  default: true,
373
374
  },
374
375
  planDirs: {
@@ -351,6 +351,13 @@ const GITHUB_SCHEMA = {
351
351
  'The human the framework escalates to, `@`-prefixed. Used for HITL @-mentions on `agent::blocked`.',
352
352
  default: '@[USERNAME]',
353
353
  },
354
+ cliConfigDir: {
355
+ type: ['string', 'null'],
356
+ minLength: 1,
357
+ description:
358
+ "Dedicated `gh` credential store (`GH_CONFIG_DIR`) for this project, set in the gitignored `.agentrc.local.json`. Relative paths resolve against the project root and a leading `~` expands to the home directory; the directory must exist. When set, every `gh` call Mandrel makes runs with `GH_CONFIG_DIR` pointed at it. `null` keeps `gh`'s default store.",
359
+ default: null,
360
+ },
354
361
  followUpRepos: FOLLOW_UP_REPOS_SCHEMA,
355
362
  branchProtection: BRANCH_PROTECTION_SCHEMA,
356
363
  mergeMethods: MERGE_METHODS_SCHEMA,
@@ -9,7 +9,7 @@ import picomatch from 'picomatch';
9
9
  import { write, writeFile } from './baselines/writer.js';
10
10
  import {
11
11
  captureStampPath,
12
- missingCoverageArtifactMessage,
12
+ MissingCoverageArtifactError,
13
13
  } from './coverage-capture.js';
14
14
 
15
15
  const COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';
@@ -98,7 +98,7 @@ export function readCoverageFinal(cwd, opts = {}, fsImpl) {
98
98
  ? coveragePath
99
99
  : path.resolve(cwd, coveragePath);
100
100
  if (!resolvedFs.existsSync(abs)) {
101
- throw new Error(missingCoverageArtifactMessage(abs));
101
+ throw new MissingCoverageArtifactError(abs);
102
102
  }
103
103
  return JSON.parse(resolvedFs.readFileSync(abs, 'utf8'));
104
104
  }
@@ -486,7 +486,7 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
486
486
  * @param {string} abs Absolute artifact path that was looked for.
487
487
  * @returns {string}
488
488
  */
489
- export function missingCoverageArtifactMessage(abs) {
489
+ function missingCoverageArtifactMessage(abs) {
490
490
  return (
491
491
  `coverage artifact not found at ${abs}. \`npm run test:coverage\` must ` +
492
492
  'write Istanbul per-file JSON (the `json` reporter → coverage-final.json) ' +
@@ -495,6 +495,21 @@ export function missingCoverageArtifactMessage(abs) {
495
495
  );
496
496
  }
497
497
 
498
+ /**
499
+ * Fatal on every scope: zero scored rows would let the scope merge delete the
500
+ * in-scope rows.
501
+ */
502
+ export class MissingCoverageArtifactError extends Error {
503
+ constructor(abs, { prefix = '', cause } = {}) {
504
+ super(
505
+ `${prefix}${missingCoverageArtifactMessage(abs)}`,
506
+ cause === undefined ? undefined : { cause },
507
+ );
508
+ this.name = 'MissingCoverageArtifactError';
509
+ this.artifactPath = abs;
510
+ }
511
+ }
512
+
498
513
  /**
499
514
  * Wrap a capture runner so a green run that left no artifact at
500
515
  * `coveragePath` exits 1: a broken capture contract, not a capture. Every
@@ -14,6 +14,8 @@ import { analyzeModule } from './escomplex-kernel.js';
14
14
  import { Logger } from './Logger.js';
15
15
  import { scanDirectory } from './maintainability-utils.js';
16
16
  import {
17
+ CompilerMissingError,
18
+ preparedFailureFields,
17
19
  prepareSourceForScoring,
18
20
  resolveTsTranspilerVersion,
19
21
  } from './transpile.js';
@@ -272,12 +274,58 @@ function projectScanRow(relPath, mr) {
272
274
  };
273
275
  }
274
276
 
277
+ /** Fold per-file results; missing compilers throw one CompilerMissingError. */
278
+ function tallyScanResults(perFile, cwd) {
279
+ const rows = [];
280
+ let skippedFilesNoCoverage = 0;
281
+ let skippedMethodsNoCoverage = 0;
282
+ let unscorableFiles = 0;
283
+ const missingCompilerDirs = [];
284
+ const resolution = newResolutionAccumulator();
285
+ for (const { item, result } of perFile) {
286
+ if (result?.compilerMissing) {
287
+ missingCompilerDirs.push(result.packageDir);
288
+ continue;
289
+ }
290
+ if (result?.skippedFileNoCoverage) {
291
+ skippedFilesNoCoverage += 1;
292
+ continue;
293
+ }
294
+ // `!result` is a pool-level error the worker never answered.
295
+ if (!result || result.rows === null) {
296
+ unscorableFiles += 1;
297
+ if (result?.error) {
298
+ Logger.warn(
299
+ `[crap-utils] failed to score ${item.relPath}: ${result.error}`,
300
+ );
301
+ }
302
+ continue;
303
+ }
304
+ skippedMethodsNoCoverage += result.skippedMethodsNoCoverage ?? 0;
305
+ accumulateResolution(resolution, item.relPath, result);
306
+ for (const mr of result.rows) {
307
+ rows.push(projectScanRow(item.relPath, mr));
308
+ }
309
+ }
310
+ if (missingCompilerDirs.length > 0) {
311
+ throw new CompilerMissingError(missingCompilerDirs, { cwd });
312
+ }
313
+ return {
314
+ rows,
315
+ skippedFilesNoCoverage,
316
+ skippedMethodsNoCoverage,
317
+ unscorableFiles,
318
+ resolution: summarizeResolution(resolution),
319
+ };
320
+ }
321
+
275
322
  /**
276
323
  * Score every method under `targetDirs` (no disk writes). Files without
277
324
  * coverage are skipped under `requireCoverage`; methods without resolvable
278
325
  * coverage are always dropped, so baselines never hold partial rows. A file
279
326
  * that cannot be read, transpiled or parsed is counted in `unscorableFiles`
280
- * so no drop is silent. `scopeFiles` filters before any I/O;
327
+ * so no drop is silent; a TypeScript file with no resolvable compiler throws
328
+ * `CompilerMissingError` instead. `scopeFiles` filters before any I/O;
281
329
  * `preScannedFiles` skips the walk; `incremental` resolves untouched files
282
330
  * from the baseline instead of fresh coverage.
283
331
  *
@@ -351,52 +399,16 @@ export async function scanAndScore({
351
399
  ? queue.map((item) => ({ item, result: scoreFileSerial(item, coverage) }))
352
400
  : await scoreFilesViaPool(queue, coverage);
353
401
 
354
- const rows = [];
355
- let skippedFilesNoCoverage = 0;
356
- let skippedMethodsNoCoverage = 0;
357
- let unscorableFiles = 0;
358
- const resolution = newResolutionAccumulator();
359
- for (const { item, result } of perFile) {
360
- if (!result) {
361
- // Pool-level error the worker never answered.
362
- unscorableFiles += 1;
363
- continue;
364
- }
365
- if (result.skippedFileNoCoverage) {
366
- skippedFilesNoCoverage += 1;
367
- continue;
368
- }
369
- if (result.rows === null) {
370
- unscorableFiles += 1;
371
- if (result.error) {
372
- Logger.warn(
373
- `[crap-utils] failed to score ${item.relPath}: ${result.error}`,
374
- );
375
- }
376
- continue;
377
- }
378
- skippedMethodsNoCoverage += result.skippedMethodsNoCoverage ?? 0;
379
- accumulateResolution(resolution, item.relPath, result);
380
- for (const mr of result.rows) {
381
- rows.push(projectScanRow(item.relPath, mr));
382
- }
383
- }
384
-
385
- rows.sort((a, b) => {
386
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
387
- if (a.startLine !== b.startLine) return a.startLine - b.startLine;
388
- if (a.method !== b.method) return a.method < b.method ? -1 : 1;
389
- return 0;
390
- });
402
+ const tally = tallyScanResults(perFile, cwd);
403
+ tally.rows.sort(compareScanRows);
404
+ return { ...tally, scannedFiles };
405
+ }
391
406
 
392
- return {
393
- rows,
394
- scannedFiles,
395
- skippedFilesNoCoverage,
396
- skippedMethodsNoCoverage,
397
- unscorableFiles,
398
- resolution: summarizeResolution(resolution),
399
- };
407
+ function compareScanRows(a, b) {
408
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
409
+ if (a.startLine !== b.startLine) return a.startLine - b.startLine;
410
+ if (a.method !== b.method) return a.method < b.method ? -1 : 1;
411
+ return 0;
400
412
  }
401
413
 
402
414
  /** In-process scorer; the reference the worker output must match exactly. */
@@ -433,7 +445,7 @@ function scoreFileSerial(
433
445
  totalMethods: 0,
434
446
  };
435
447
  const prepared = prepareSourceForScoring(abs);
436
- if (prepared.error) return dropped;
448
+ if (prepared.error) return { ...dropped, ...preparedFailureFields(prepared) };
437
449
  const { crapRows, parseError } = analyzeOnce(
438
450
  prepared.code,
439
451
  entry,
@@ -26,6 +26,7 @@ import {
26
26
  resolveAdmission,
27
27
  resolveSuiteCapacity,
28
28
  } from './suite-admission.js';
29
+ import { defaultSleep } from './util/sleep.js';
29
30
 
30
31
  export { ADMISSION_REFUSED_EXIT_CODE };
31
32
 
@@ -281,16 +282,6 @@ function reportCompleted(opts, wait, ranMs) {
281
282
  } catch {}
282
283
  }
283
284
 
284
- /**
285
- * @param {number} ms
286
- * @returns {Promise<void>}
287
- */
288
- function defaultSleep(ms) {
289
- return new Promise((resolve) => {
290
- setTimeout(resolve, ms);
291
- });
292
- }
293
-
294
285
  /**
295
286
  * The one admission policy every caller resolves: enablement, budget,
296
287
  * capacity, and the workload `argv` classifies to.
@@ -48,6 +48,16 @@ function defaultReadFromTree({ baselinePath, projectRoot } = {}) {
48
48
  return JSON.parse(fs.readFileSync(abs, 'utf8'));
49
49
  }
50
50
 
51
+ /** Ratchet-gate read: `null` when missing, unparseable or not an object. */
52
+ export function readJsonBaseline(baselinePath) {
53
+ try {
54
+ const parsed = defaultReadFromTree({ baselinePath });
55
+ return parsed && typeof parsed === 'object' ? parsed : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
51
61
  /**
52
62
  * A gate may supply `readFromTree` for a "missing → empty" bootstrap (MI
53
63
  * returns `{}`); the default throws `BaselineNotFoundError`.