mandrel 2.87.0 → 2.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -4,28 +4,142 @@ import path from 'node:path';
4
4
  import { resolveDependencyVersion } from './dependency-version.js';
5
5
  import { Logger } from './Logger.js';
6
6
 
7
- const require = createRequire(import.meta.url);
7
+ const moduleRequire = createRequire(import.meta.url);
8
8
 
9
9
  const TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts']);
10
10
 
11
11
  /** TS 7 moved `transpileModule` under `unstable/*`; mirrors the peer range. */
12
12
  const SUPPORTED_TS_RANGE = '>=5.0.0 <7';
13
13
 
14
- let _ts = null;
15
- let _tsLoadFailed = false;
14
+ /** No compiler resolved — distinct from `null`, a transpile failure. */
15
+ const COMPILER_MISSING = Object.freeze({ compilerMissing: true });
16
16
 
17
- function loadTypeScript() {
18
- if (_ts) return _ts;
19
- if (_tsLoadFailed) return null;
17
+ const DIAGNOSTIC_DIR_CAP = 10;
18
+
19
+ const MODULE_ANCHOR = '\0module-location';
20
+
21
+ // Misses are cached per anchor, never process-wide.
22
+ const _entryByAnchor = new Map();
23
+ const _compilerByEntry = new Map();
24
+ const _packageDirByDir = new Map();
25
+
26
+ /** Node's upward `node_modules` walk starts at `dir`. */
27
+ function requireFromDir(dir) {
28
+ return createRequire(path.join(dir, 'noop.cjs'));
29
+ }
30
+
31
+ function requireForAnchor(anchor) {
32
+ return anchor === MODULE_ANCHOR ? moduleRequire : requireFromDir(anchor);
33
+ }
34
+
35
+ function resolveEntry(anchor) {
36
+ if (_entryByAnchor.has(anchor)) return _entryByAnchor.get(anchor);
37
+ let entry = null;
20
38
  try {
21
- _ts = require('typescript');
22
- return _ts;
39
+ entry = requireForAnchor(anchor).resolve('typescript');
23
40
  } catch {
24
- _tsLoadFailed = true;
25
- return null;
41
+ entry = null;
42
+ }
43
+ _entryByAnchor.set(anchor, entry);
44
+ return entry;
45
+ }
46
+
47
+ /** One load per installation. */
48
+ function loadCompiler(entry) {
49
+ if (_compilerByEntry.has(entry)) return _compilerByEntry.get(entry);
50
+ let ts = null;
51
+ try {
52
+ ts = moduleRequire(entry);
53
+ } catch {
54
+ ts = null;
55
+ }
56
+ _compilerByEntry.set(entry, ts);
57
+ return ts;
58
+ }
59
+
60
+ /**
61
+ * The file's own directory first: the walk finds its package's compiler and
62
+ * passes the project root on the way. Then this module's location.
63
+ */
64
+ function loadTypeScriptFor(filePath) {
65
+ const anchors = [path.dirname(path.resolve(String(filePath))), MODULE_ANCHOR];
66
+ for (const anchor of anchors) {
67
+ const entry = resolveEntry(anchor);
68
+ const ts = entry ? loadCompiler(entry) : null;
69
+ if (ts) return ts;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * Nearest ancestor holding a `package.json` (else the file's directory).
76
+ *
77
+ * @param {string} filePath
78
+ * @returns {string}
79
+ */
80
+ export function owningPackageDir(filePath) {
81
+ const start = path.dirname(path.resolve(String(filePath)));
82
+ if (_packageDirByDir.has(start)) return _packageDirByDir.get(start);
83
+ let dir = start;
84
+ let found = start;
85
+ while (true) {
86
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
87
+ found = dir;
88
+ break;
89
+ }
90
+ const parent = path.dirname(dir);
91
+ if (parent === dir) break;
92
+ dir = parent;
93
+ }
94
+ _packageDirByDir.set(start, found);
95
+ return found;
96
+ }
97
+
98
+ function compilerMissingMessage(packageDirs, opts = {}) {
99
+ const dirs = [...new Set(packageDirs)].sort();
100
+ const render = (dir) =>
101
+ opts.cwd ? path.relative(opts.cwd, dir).replace(/\\/g, '/') || '.' : dir;
102
+ const shown = dirs.slice(0, DIAGNOSTIC_DIR_CAP).map(render);
103
+ const more =
104
+ dirs.length > shown.length ? ` (+${dirs.length - shown.length} more)` : '';
105
+ return (
106
+ `typescript is not resolvable for TypeScript sources in ${dirs.length} ` +
107
+ `package(s): ${shown.join(', ')}${more}. Install it as a devDependency of ` +
108
+ `each package ('npm install --save-dev typescript' there; supported ` +
109
+ `range ${SUPPORTED_TS_RANGE}). No baseline was written.`
110
+ );
111
+ }
112
+
113
+ /** The scorers throw this so update/check fail loud and write nothing. */
114
+ export class CompilerMissingError extends Error {
115
+ constructor(packageDirs, opts = {}) {
116
+ super(compilerMissingMessage(packageDirs, opts));
117
+ this.name = 'CompilerMissingError';
118
+ this.packageDirs = [...new Set(packageDirs)].sort();
119
+ // An install step, not a crash: no trace.
120
+ this.stack = `${this.name}: ${this.message}`;
26
121
  }
27
122
  }
28
123
 
124
+ /**
125
+ * @param {unknown} value
126
+ * @returns {boolean}
127
+ */
128
+ export function isCompilerMissing(value) {
129
+ return value === COMPILER_MISSING;
130
+ }
131
+
132
+ /**
133
+ * Scan-result fields for a failed prepare; only a missing compiler has any.
134
+ *
135
+ * @param {{error?: string, packageDir?: string}} prepared
136
+ * @returns {{compilerMissing?: true, packageDir?: string}}
137
+ */
138
+ export function preparedFailureFields(prepared) {
139
+ if (prepared?.error !== 'compiler-missing') return {};
140
+ return { compilerMissing: true, packageDir: prepared.packageDir };
141
+ }
142
+
29
143
  /** Compiler modules already diagnosed as API-less — one warning per module. */
30
144
  const _unsupportedDiagnosed = new WeakSet();
31
145
 
@@ -47,19 +161,42 @@ function isUsableCompiler(ts) {
47
161
  return false;
48
162
  }
49
163
 
50
- let _tsVersion = null;
164
+ const _tsVersionByAnchors = new Map();
51
165
 
52
166
  /**
53
- * `typescript` version for baseline stamps, read from the manifest (never by
54
- * loading the compiler). `'0.0.0'` means unknown environment.
167
+ * `typescript` version stamp from manifests (never loading the compiler):
168
+ * target dirs and project root, else this module's location. Distinct
169
+ * versions are `+`-joined; `'0.0.0'` means unknown.
55
170
  *
171
+ * @param {{ cwd?: string, targetDirs?: string[] }} [ctx]
56
172
  * @returns {string}
57
173
  */
58
- export function resolveTsTranspilerVersion() {
59
- if (_tsVersion === null) {
60
- _tsVersion = resolveDependencyVersion('typescript', require) ?? '0.0.0';
174
+ export function resolveTsTranspilerVersion(ctx = {}) {
175
+ const anchors = stampAnchors(ctx ?? {});
176
+ const key = anchors.join('\n');
177
+ if (!_tsVersionByAnchors.has(key)) {
178
+ _tsVersionByAnchors.set(key, stampFrom(anchors));
179
+ }
180
+ return _tsVersionByAnchors.get(key);
181
+ }
182
+
183
+ function stampAnchors({ cwd, targetDirs }) {
184
+ const dirs = Array.isArray(targetDirs) ? targetDirs.filter(Boolean) : [];
185
+ if (!cwd) return dirs.filter((dir) => path.isAbsolute(dir));
186
+ return [...dirs.map((dir) => path.resolve(cwd, dir)), path.resolve(cwd)];
187
+ }
188
+
189
+ function stampFrom(anchors) {
190
+ const manifestVersion = (requireFn) =>
191
+ resolveDependencyVersion('typescript', requireFn);
192
+ let versions = anchors
193
+ .map((anchor) => manifestVersion(requireFromDir(anchor)))
194
+ .filter(Boolean);
195
+ if (versions.length === 0) {
196
+ versions = [manifestVersion(moduleRequire)].filter(Boolean);
61
197
  }
62
- return _tsVersion;
198
+ if (versions.length === 0) return '0.0.0';
199
+ return [...new Set(versions)].sort().join('+');
63
200
  }
64
201
 
65
202
  function isTypeScriptPath(filePath) {
@@ -119,27 +256,22 @@ function buildLineMapper(sourceMapText, code) {
119
256
 
120
257
  /**
121
258
  * TS/TSX → JS escomplex can parse (types add no control flow); JS passes
122
- * through; `null` means skip. Transpiling shifts lines, so a coverage join
123
- * opts into `{ withLineMap: true }` → `{ code, mapLine }` (`null` for JS).
259
+ * through; `null` means skip, `COMPILER_MISSING` no compiler. Transpiling
260
+ * shifts lines, so a coverage join opts into `{ withLineMap: true }` →
261
+ * `{ code, mapLine }` (`null` for JS).
124
262
  *
125
263
  * @param {string} filePath
126
264
  * @param {string} source
127
265
  * @param {{withLineMap?: boolean, typescript?: object}} [opts]
128
- * @returns {string|null|{code: string, mapLine: ((line: number) => number|null)|null}}
266
+ * @returns {string|null|typeof COMPILER_MISSING|{code: string, mapLine: ((line: number) => number|null)|null}}
129
267
  */
130
268
  export function transpileIfNeeded(filePath, source, opts = {}) {
131
269
  const withLineMap = opts?.withLineMap === true;
132
270
  if (!isTypeScriptPath(filePath)) {
133
271
  return withLineMap ? { code: source, mapLine: null } : source;
134
272
  }
135
- const ts = opts?.typescript ?? loadTypeScript();
136
- if (!ts) {
137
- Logger.warn(
138
- `[Maintainability] ⚠ typescript package not resolvable; cannot score ${filePath}. ` +
139
- `Install with 'npm install --save-dev typescript' (peer dep, ${SUPPORTED_TS_RANGE}).`,
140
- );
141
- return null;
142
- }
273
+ const ts = opts?.typescript ?? loadTypeScriptFor(filePath);
274
+ if (!ts) return COMPILER_MISSING;
143
275
  if (!isUsableCompiler(ts)) return null;
144
276
  try {
145
277
  const result = ts.transpileModule(source, {
@@ -171,14 +303,41 @@ export function transpileIfNeeded(filePath, source, opts = {}) {
171
303
  }
172
304
  }
173
305
 
306
+ const _reportDiagnosed = new Set();
307
+
174
308
  /**
175
- * Read + transpile with a line map. Read and transpile failures stay
176
- * distinct: the MI path drops the score on `read` but scores 0 on `transpile`.
309
+ * For report-only callers (review, report worker): a string, or `null` to
310
+ * report a parse error. A missing compiler is diagnosed once per package,
311
+ * never handed back as a sentinel.
312
+ *
313
+ * @param {string} filePath
314
+ * @param {string} source
315
+ * @returns {string|null}
316
+ */
317
+ export function transpileForReport(filePath, source) {
318
+ const prepared = transpileIfNeeded(filePath, source);
319
+ if (!isCompilerMissing(prepared)) return prepared;
320
+ const dir = owningPackageDir(filePath);
321
+ if (!_reportDiagnosed.has(dir)) {
322
+ _reportDiagnosed.add(dir);
323
+ Logger.warn(
324
+ `[Maintainability] ⚠ typescript is not resolvable for ${dir}; its TypeScript is ` +
325
+ `reported as a parse error. Install it there: 'npm install --save-dev typescript' ` +
326
+ `(${SUPPORTED_TS_RANGE}).`,
327
+ );
328
+ }
329
+ return null;
330
+ }
331
+
332
+ /**
333
+ * Read + transpile with a line map. Read, transpile and missing-compiler
334
+ * failures stay distinct.
177
335
  *
178
336
  * @param {string} abs
179
337
  * @param {{readFile?: (p: string) => string, transpile?: Function}} [deps]
180
338
  * @returns {{code: string, mapLine: ((line: number) => number|null)|null}
181
- * | {error: 'read'|'transpile'}}
339
+ * | {error: 'read'|'transpile'}
340
+ * | {error: 'compiler-missing', packageDir: string}}
182
341
  */
183
342
  export function prepareSourceForScoring(abs, deps = {}) {
184
343
  const readFile = deps.readFile ?? ((p) => fs.readFileSync(p, 'utf-8'));
@@ -190,6 +349,9 @@ export function prepareSourceForScoring(abs, deps = {}) {
190
349
  return { error: 'read' };
191
350
  }
192
351
  const prepared = transpile(abs, source, { withLineMap: true });
352
+ if (isCompilerMissing(prepared)) {
353
+ return { error: 'compiler-missing', packageDir: owningPackageDir(abs) };
354
+ }
193
355
  if (prepared === null || prepared === undefined)
194
356
  return { error: 'transpile' };
195
357
  // Tolerate a `deps.transpile` stub that still returns a bare string.
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Shared filesystem-path helpers.
3
+ *
4
+ * @module lib/util/paths
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ /**
11
+ * Native separators to `/`. Splits on `path.sep` only, so a literal `\` in a
12
+ * POSIX filename survives while every win32 separator is converted.
13
+ *
14
+ * @param {string} p
15
+ * @returns {string}
16
+ */
17
+ export function toPosix(p) {
18
+ return p.split(path.sep).join('/');
19
+ }
20
+
21
+ /**
22
+ * @param {string} dir
23
+ * @returns {boolean}
24
+ */
25
+ export function dirExists(dir) {
26
+ try {
27
+ return fs.statSync(dir).isDirectory();
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The one default `sleep` seam modules inject-and-override in tests.
3
+ *
4
+ * @module lib/util/sleep
5
+ */
6
+
7
+ /**
8
+ * @param {number} ms
9
+ * @returns {Promise<void>}
10
+ */
11
+ export function defaultSleep(ms) {
12
+ return new Promise((resolve) => {
13
+ setTimeout(resolve, ms);
14
+ });
15
+ }
@@ -11,6 +11,7 @@ import {
11
11
  existsSync as defaultExistsSync,
12
12
  mkdirSync as defaultMkdirSync,
13
13
  readFileSync as defaultReadFileSync,
14
+ renameSync as defaultRenameSync,
14
15
  unlinkSync as defaultUnlinkSync,
15
16
  writeFileSync as defaultWriteFileSync,
16
17
  } from 'node:fs';
@@ -54,6 +55,7 @@ const defaultFsAdapter = {
54
55
  existsSync: defaultExistsSync,
55
56
  mkdirSync: defaultMkdirSync,
56
57
  readFileSync: defaultReadFileSync,
58
+ renameSync: defaultRenameSync,
57
59
  unlinkSync: defaultUnlinkSync,
58
60
  writeFileSync: defaultWriteFileSync,
59
61
  };
@@ -213,12 +215,36 @@ export function recordPass(
213
215
  throw new Error(`Evidence document failed schema validation: ${detail}`);
214
216
  }
215
217
 
216
- const file = evidencePath(storyId, evidenceOpts);
217
- resolved.fs.mkdirSync(path.dirname(file), { recursive: true });
218
- resolved.fs.writeFileSync(file, JSON.stringify(doc, null, 2), 'utf8');
218
+ writeEvidenceAtomically(
219
+ resolved.fs,
220
+ evidencePath(storyId, evidenceOpts),
221
+ JSON.stringify(doc, null, 2),
222
+ );
219
223
  return record;
220
224
  }
221
225
 
226
+ /** Atomic write (pid-scoped tmp + rename): a torn file drops all credit. */
227
+ function writeEvidenceAtomically(fsImpl, file, body) {
228
+ fsImpl.mkdirSync(path.dirname(file), { recursive: true });
229
+ const tmpPath = `${file}.${process.pid}.tmp`;
230
+ try {
231
+ fsImpl.writeFileSync(tmpPath, body, 'utf8');
232
+ fsImpl.renameSync(tmpPath, file);
233
+ } catch (err) {
234
+ reapTmp(fsImpl, tmpPath);
235
+ throw err;
236
+ }
237
+ }
238
+
239
+ /** Best-effort removal of a tmp sibling. */
240
+ function reapTmp(fsImpl, tmpPath) {
241
+ try {
242
+ if (fsImpl.existsSync(tmpPath)) fsImpl.unlinkSync(tmpPath);
243
+ } catch {
244
+ // A leftover tmp is never read as evidence.
245
+ }
246
+ }
247
+
222
248
  /**
223
249
  * `HEAD^{tree}` as `inputFingerprint`: survives close's base-sync moving HEAD
224
250
  * without changing content, so gates are not re-paid. `null` when unreadable
@@ -68,6 +68,28 @@ function deriveBlockedIds(storyRecords) {
68
68
  .sort((a, b) => a - b);
69
69
  }
70
70
 
71
+ /** Close reasons meaning nothing merged — no `agent::done` is owed. */
72
+ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
73
+
74
+ /**
75
+ * Closed, not `agent::done`, not superseded; ascending.
76
+ *
77
+ * @param {Array<{id?: number, number?: number, labels?: string[], state?: string, stateReason?: string|null}>} storyRecords
78
+ * @returns {number[]}
79
+ */
80
+ function deriveConfirmIds(storyRecords) {
81
+ return storyRecords
82
+ .filter(
83
+ (rec) =>
84
+ rec.state === 'closed' &&
85
+ !rec.labels.includes(AGENT_LABELS.DONE) &&
86
+ !UNLANDED_CLOSE_REASONS.has(rec.stateReason),
87
+ )
88
+ .map((rec) => storyIdOf(rec))
89
+ .filter((id) => id !== null)
90
+ .sort((a, b) => a - b);
91
+ }
92
+
71
93
  /**
72
94
  * `ready` Stories whose assignee lease belongs to another operator: they can
73
95
  * read `ready` while that operator's init is still running, and dispatching
@@ -143,6 +165,7 @@ export function createProbeContext({
143
165
  * doneIds: Set<number>,
144
166
  * inFlight: number,
145
167
  * blockedIds: number[],
168
+ * confirmIds: number[],
146
169
  * stalledDispatch: number[],
147
170
  * foreignHeld: Array<{id: number, holder: string}>,
148
171
  * crossRunOverlaps?: object[]
@@ -204,6 +227,7 @@ export async function probeLiveState({
204
227
  doneIds: new Set(envelope.done),
205
228
  inFlight: inFlightIds.size,
206
229
  blockedIds: deriveBlockedIds(stories),
230
+ confirmIds: deriveConfirmIds(stories),
207
231
  // Reported, never released. A foreign lease outranks the claim, so one
208
232
  // Story never carries two recoveries.
209
233
  stalledDispatch: [...unlabelled]
@@ -2,7 +2,8 @@
2
2
  * CPU-pool worker for `scanAndScore`: one file in, its per-method CRAP rows
3
3
  * out. The host pre-resolves each file's coverage entry (`item.coverageEntry`)
4
4
  * so the coverage map is never cloned per worker. An unrecoverable per-file
5
- * failure replies `rows: null`, which the host drops and counts.
5
+ * failure replies `rows: null`, which the host drops and counts; a missing
6
+ * TypeScript compiler replies `compilerMissing` so the host fails loud.
6
7
  */
7
8
 
8
9
  import { parentPort } from 'node:worker_threads';
@@ -11,7 +12,10 @@ import {
11
12
  finalizeMethodRows,
12
13
  UNSCORABLE,
13
14
  } from '../crap-engine.js';
14
- import { prepareSourceForScoring } from '../transpile.js';
15
+ import {
16
+ preparedFailureFields,
17
+ prepareSourceForScoring,
18
+ } from '../transpile.js';
15
19
  import { serveWorkerMessages } from './serve-worker-messages.js';
16
20
 
17
21
  /**
@@ -31,11 +35,7 @@ export function handleCrapWorkerMessage(msg, _coverage, deps = {}) {
31
35
  if (msg && msg.exit === true) return { kind: 'exit' };
32
36
 
33
37
  const item = msg?.item;
34
- if (
35
- !item ||
36
- typeof item.abs !== 'string' ||
37
- typeof item.relPath !== 'string'
38
- ) {
38
+ if (!isWorkItem(item)) {
39
39
  return {
40
40
  kind: 'reply',
41
41
  message: {
@@ -77,7 +77,8 @@ export function handleCrapWorkerMessage(msg, _coverage, deps = {}) {
77
77
  // escomplex's transpiled coordinates to them.
78
78
  const prepare = deps.prepare ?? prepareSourceForScoring;
79
79
  const prepared = prepare(abs, deps);
80
- if (prepared.error) return dropped(null);
80
+ // `reply` defaults `rows: null`, so every prepare error is a drop.
81
+ if (prepared.error) return reply(preparedFailureFields(prepared));
81
82
 
82
83
  let methodRows;
83
84
  try {
@@ -87,9 +88,7 @@ export function handleCrapWorkerMessage(msg, _coverage, deps = {}) {
87
88
  prepared.mapLine,
88
89
  );
89
90
  } catch (err) {
90
- return dropped(
91
- err && typeof err.message === 'string' ? err.message : String(err),
92
- );
91
+ return dropped(errorText(err));
93
92
  }
94
93
  // Unparseable must drop (`rows: null`), not read as a file with no methods,
95
94
  // or its baseline rows vanish uncounted.
@@ -100,4 +99,16 @@ export function handleCrapWorkerMessage(msg, _coverage, deps = {}) {
100
99
  );
101
100
  }
102
101
 
103
- serveWorkerMessages(parentPort, (msg) => handleCrapWorkerMessage(msg, null));
102
+ function isWorkItem(item) {
103
+ return (
104
+ Boolean(item) &&
105
+ typeof item.abs === 'string' &&
106
+ typeof item.relPath === 'string'
107
+ );
108
+ }
109
+
110
+ function errorText(err) {
111
+ return err && typeof err.message === 'string' ? err.message : String(err);
112
+ }
113
+
114
+ serveWorkerMessages(parentPort, handleCrapWorkerMessage);
@@ -11,7 +11,7 @@ import {
11
11
  calculateReport,
12
12
  calculateReportForFile,
13
13
  } from '../maintainability-engine.js';
14
- import { transpileIfNeeded } from '../transpile.js';
14
+ import { transpileForReport } from '../transpile.js';
15
15
  import { serveWorkerMessages } from './serve-worker-messages.js';
16
16
 
17
17
  /**
@@ -22,7 +22,7 @@ import { serveWorkerMessages } from './serve-worker-messages.js';
22
22
  * @returns {object}
23
23
  */
24
24
  function reportFromSource(source, label) {
25
- const prepared = transpileIfNeeded(label, source);
25
+ const prepared = transpileForReport(label, source);
26
26
  if (prepared === null) {
27
27
  return {
28
28
  moduleScore: 0,
@@ -47,11 +47,7 @@ export function handleMaintainabilityReportWorkerMessage(msg, deps = {}) {
47
47
 
48
48
  const item = msg?.item;
49
49
  const isPathItem = typeof item === 'string';
50
- const isSourceItem =
51
- item &&
52
- typeof item === 'object' &&
53
- typeof item.source === 'string' &&
54
- typeof item.label === 'string';
50
+ const isSourceItem = isSourceShaped(item);
55
51
  if (!isPathItem && !isSourceItem) {
56
52
  return {
57
53
  kind: 'reply',
@@ -81,14 +77,24 @@ export function handleMaintainabilityReportWorkerMessage(msg, deps = {}) {
81
77
  result: {
82
78
  filePath,
83
79
  report: null,
84
- error:
85
- err && typeof err.message === 'string' ? err.message : String(err),
80
+ error: errorText(err),
86
81
  },
87
82
  },
88
83
  };
89
84
  }
90
85
  }
91
86
 
92
- serveWorkerMessages(parentPort, (msg) =>
93
- handleMaintainabilityReportWorkerMessage(msg),
94
- );
87
+ function isSourceShaped(item) {
88
+ return (
89
+ Boolean(item) &&
90
+ typeof item === 'object' &&
91
+ typeof item.source === 'string' &&
92
+ typeof item.label === 'string'
93
+ );
94
+ }
95
+
96
+ function errorText(err) {
97
+ return err && typeof err.message === 'string' ? err.message : String(err);
98
+ }
99
+
100
+ serveWorkerMessages(parentPort, handleMaintainabilityReportWorkerMessage);
@@ -10,6 +10,7 @@
10
10
 
11
11
  import nodeFs from 'node:fs';
12
12
  import path from 'node:path';
13
+ import { toPosix } from './util/paths.js';
13
14
 
14
15
  /**
15
16
  * @type {string}
@@ -55,14 +56,6 @@ function unquote(value) {
55
56
  return quoted ? t.slice(1, -1).trim() : t;
56
57
  }
57
58
 
58
- /**
59
- * @param {string} p
60
- * @returns {string}
61
- */
62
- function toPosix(p) {
63
- return p.split(path.sep).join('/');
64
- }
65
-
66
59
  /**
67
60
  * @param {string} source
68
61
  * @returns {string}