mandrel 2.90.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +31 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/check-arch-cycles.js +1 -5
  14. package/.agents/scripts/check-context-budget.js +1 -5
  15. package/.agents/scripts/check-cyclomatic.js +1 -5
  16. package/.agents/scripts/check-dead-exports.js +23 -14
  17. package/.agents/scripts/check-doc-links.js +4 -4
  18. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  19. package/.agents/scripts/coverage-capture.js +14 -6
  20. package/.agents/scripts/diagnose-friction.js +8 -10
  21. package/.agents/scripts/generate-workflows-doc.js +5 -0
  22. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  24. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  25. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  26. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  27. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  28. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  29. package/.agents/scripts/lib/baselines/components.js +5 -5
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  32. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  33. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  34. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  36. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  37. package/.agents/scripts/lib/baselines/writer.js +4 -4
  38. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  39. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  40. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  41. package/.agents/scripts/lib/child-exec.js +4 -4
  42. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  43. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  44. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  45. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  46. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  47. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  48. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  49. package/.agents/scripts/lib/config/commands.js +82 -7
  50. package/.agents/scripts/lib/config/explain.js +2 -1
  51. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  52. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  53. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  54. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  55. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  56. package/.agents/scripts/lib/config/git-roots.js +120 -0
  57. package/.agents/scripts/lib/config/quality.js +46 -50
  58. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  59. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  60. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  61. package/.agents/scripts/lib/config-resolver.js +5 -9
  62. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  63. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  64. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  65. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  67. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  68. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  69. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  70. package/.agents/scripts/lib/coverage-capture.js +31 -20
  71. package/.agents/scripts/lib/coverage-utils.js +34 -16
  72. package/.agents/scripts/lib/cpu-pool.js +2 -4
  73. package/.agents/scripts/lib/crap-engine.js +19 -1
  74. package/.agents/scripts/lib/crap-utils.js +2 -1
  75. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  76. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  77. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  78. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  79. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  80. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  81. package/.agents/scripts/lib/gh-env.js +72 -0
  82. package/.agents/scripts/lib/gh-exec.js +26 -1
  83. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  84. package/.agents/scripts/lib/npm-scripts.js +1 -1
  85. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  86. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  87. package/.agents/scripts/lib/orchestration/board-access-latch.js +19 -8
  88. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  89. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  90. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  91. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  92. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  93. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  94. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  95. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  96. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  97. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  98. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  99. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  100. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  101. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  102. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  103. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  104. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  105. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  106. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  107. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  108. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  109. package/.agents/scripts/lib/orchestration/story-handoff.js +13 -5
  110. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  111. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  112. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  113. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  114. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  115. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  116. package/.agents/scripts/lib/source-extensions.js +30 -15
  117. package/.agents/scripts/lib/test-run-credit.js +1 -9
  118. package/.agents/scripts/lib/test-temp.js +22 -21
  119. package/.agents/scripts/lib/util/ajv.js +111 -0
  120. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  121. package/.agents/scripts/lib/util/paths.js +51 -0
  122. package/.agents/scripts/lib/util/sleep.js +6 -0
  123. package/.agents/scripts/lib/util/slug.js +12 -0
  124. package/.agents/scripts/lib/validation-evidence.js +19 -40
  125. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  126. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  127. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  128. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  129. package/.agents/scripts/lint-issue-body.js +2 -2
  130. package/.agents/scripts/plan-context.js +2 -7
  131. package/.agents/scripts/providers/github/auth.js +3 -3
  132. package/.agents/scripts/providers/github/errors.js +3 -1
  133. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  134. package/.agents/scripts/providers/github/issues.js +6 -2
  135. package/.agents/scripts/providers/github/mappers.js +1 -5
  136. package/.agents/scripts/providers/github/projects-v2-graphql.js +11 -3
  137. package/.agents/scripts/providers/github/search-budget.js +3 -1
  138. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  139. package/.agents/scripts/sync-agentrc.js +5 -14
  140. package/.agents/scripts/sync-claude-agents.js +38 -150
  141. package/.agents/scripts/sync-claude-commands.js +35 -218
  142. package/.agents/scripts/update-coverage-baseline.js +1 -1
  143. package/.agents/scripts/update-crap-baseline.js +1 -1
  144. package/.agents/scripts/update-duplication-baseline.js +2 -16
  145. package/.agents/scripts/validate-skills.js +6 -10
  146. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  147. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  148. package/.agents/workflows/audit-exceptions.md +9 -0
  149. package/.agents/workflows/audit-lean.md +129 -0
  150. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  151. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  152. package/.agents/workflows/helpers/code-review.md +15 -1
  153. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  154. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  155. package/.agents/workflows/mandrel-plan.md +2 -2
  156. package/docs/CHANGELOG.md +35 -0
  157. package/lib/cli/doctor-checks/codex.js +6 -5
  158. package/lib/cli/doctor-checks/llm-review.js +102 -0
  159. package/lib/cli/doctor-checks/project-access.js +20 -10
  160. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  161. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  162. package/lib/cli/doctor-checks/toolchain.js +5 -3
  163. package/lib/cli/registry.js +5 -0
  164. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  165. package/lib/migrations/index.js +6 -0
  166. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  167. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  168. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  169. package/package.json +1 -3
@@ -2,6 +2,7 @@
2
2
  * Per-kind module for the duplication baseline (jscpd). Row shape:
3
3
  * `{ path, duplicatedLines, totalLines, percentage }`; lower is better. Bump
4
4
  * the static kernel version when the row shape or rollup math changes.
5
+ * Regressions compare `duplicatedLines`; a ratio moves with the file's size.
5
6
  */
6
7
 
7
8
  import { canonicalise } from '../path-canon.js';
@@ -72,12 +73,13 @@ export const {
72
73
  } = makeBaselineKind({
73
74
  keyField,
74
75
  kernelVersion: '1.0.0',
75
- axes: ['percentage'],
76
+ axes: ['duplicatedLines'],
77
+ epsilonAxes: ['percentage'],
76
78
  betterWhen: 'lower',
77
79
  aggregate,
78
80
  missingBasePolicy: 'addition',
79
81
  removedRowPolicy: {
80
82
  kind: 'improvement-when',
81
- when: (b) => (b.percentage ?? 0) > 0,
83
+ when: (b) => (b.duplicatedLines ?? 0) > 0,
82
84
  },
83
85
  });
@@ -8,11 +8,14 @@ import { mergeRowsByScope } from '../scope.js';
8
8
  * (default; never a regression) or is classified against a `'perfect'` base.
9
9
  * `removedRowPolicy`: a base row with no head row is classified against a
10
10
  * perfect head, or is an improvement when `when(baseRow)` holds.
11
+ * `epsilonAxes`: the axes `applyEpsilon` measures (default `axes`); a prior
12
+ * row is kept only when every compared axis outside them is unchanged.
11
13
  *
12
14
  * @param {{
13
15
  * keyField: string,
14
16
  * kernelVersion: string | (() => string),
15
17
  * axes: string[],
18
+ * epsilonAxes?: string[],
16
19
  * betterWhen: 'higher' | 'lower',
17
20
  * aggregate: (rows: object[]) => Record<string, number>,
18
21
  * missingBasePolicy?: 'addition' | 'perfect',
@@ -35,6 +38,7 @@ export function makeBaselineKind({
35
38
  keyField,
36
39
  kernelVersion,
37
40
  axes,
41
+ epsilonAxes = axes,
38
42
  betterWhen,
39
43
  aggregate,
40
44
  missingBasePolicy = 'addition',
@@ -141,12 +145,7 @@ export function makeBaselineKind({
141
145
  return regenRows.map((row) => {
142
146
  const p = priorByKey.get(keyOf(row));
143
147
  if (!p) return row;
144
- let maxAxisDelta = 0;
145
- for (const axis of axes) {
146
- const d = Math.abs((row[axis] ?? 0) - (p[axis] ?? 0));
147
- if (d > maxAxisDelta) maxAxisDelta = d;
148
- }
149
- return maxAxisDelta <= eps ? p : row;
148
+ return priorStillHolds(row, p, { axes, epsilonAxes, eps }) ? p : row;
150
149
  });
151
150
  }
152
151
 
@@ -169,3 +168,11 @@ export function makeBaselineKind({
169
168
  mergeRows,
170
169
  };
171
170
  }
171
+
172
+ function priorStillHolds(row, prior, { axes, epsilonAxes, eps }) {
173
+ const drift = (axis) => Math.abs((row[axis] ?? 0) - (prior[axis] ?? 0));
174
+ if (epsilonAxes.some((axis) => drift(axis) > eps)) return false;
175
+ return axes.every(
176
+ (axis) => epsilonAxes.includes(axis) || row[axis] === prior[axis],
177
+ );
178
+ }
@@ -11,6 +11,7 @@ import nodeFs from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import path from 'node:path';
13
13
  import { execFileCaptureAsync } from '../child-exec.js';
14
+ import { COVERAGE_CAPTURE_DEFAULTS } from '../config/gates/coverage.schema.js';
14
15
  import { COVERAGE_GATE_DEFAULTS } from '../config/quality.js';
15
16
  import { getQuality, resolveConfig } from '../config-resolver.js';
16
17
  import {
@@ -29,6 +30,7 @@ import {
29
30
  isIgnoredByGlobs as isIgnoredByGlobsMi,
30
31
  scanDirectory as scanDirectoryMi,
31
32
  } from '../maintainability-utils.js';
33
+ import { isScorableSourceFile } from '../source-extensions.js';
32
34
  import { buildBundleSizeScorer } from './bundle-size-scorer.js';
33
35
  import { resolveDetectClones, scanDuplication } from './duplication-scanner.js';
34
36
  import { getKindModule } from './kernel.js';
@@ -55,12 +57,13 @@ const SUPPORTED_KINDS = Object.freeze([
55
57
  * @type {Record<string, (p: string) => boolean>}
56
58
  */
57
59
  const KIND_FILE_PREDICATES = Object.freeze({
58
- maintainability: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
59
- crap: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
60
- coverage: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
61
- // Over-inclusive is inert for JS-only jscpd; under-inclusive would pin a
62
- // changed file's prior row.
63
- duplication: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
60
+ // The scanner walks exactly this set, so a scoped file it never scores
61
+ // cannot trip the "produced no baseline rows" refusal.
62
+ maintainability: isScorableSourceFile,
63
+ crap: isScorableSourceFile,
64
+ coverage: isScorableSourceFile,
65
+ // jscpd's formats derive from the same set, so the scope matches the scan.
66
+ duplication: isScorableSourceFile,
64
67
  // Bundle names are not paths: no changed file scopes a bundle row.
65
68
  'bundle-size': () => false,
66
69
  });
@@ -97,7 +100,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
97
100
  : [];
98
101
  const requireCoverage = crapCfg.requireCoverage !== false;
99
102
  const coverageRelPath =
100
- crapCfg.coveragePath ?? 'coverage/coverage-final.json';
103
+ crapCfg.coveragePath ?? COVERAGE_CAPTURE_DEFAULTS.coveragePath;
101
104
  return async (files, opts) => {
102
105
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
103
106
  const coverageAbs = path.isAbsolute(coverageRelPath)
@@ -648,17 +651,11 @@ function buildDefaultDuplicationScorer({ cwd, config, quality, detect } = {}) {
648
651
  const ignoreGlobs = Array.isArray(dupCfg.ignoreGlobs)
649
652
  ? dupCfg.ignoreGlobs
650
653
  : [];
651
- // Absent or empty falls through to the scanner's own default.
652
- const formats =
653
- Array.isArray(dupCfg.formats) && dupCfg.formats.length > 0
654
- ? dupCfg.formats
655
- : undefined;
656
654
  return async (_files, opts) => {
657
655
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
658
656
  return scanDuplication({
659
657
  targetDirs,
660
658
  cwd: effectiveCwd,
661
- formats,
662
659
  ignoreGlobs,
663
660
  detect: detect ?? resolveDetectClones(),
664
661
  });
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { deepEqual } from '../json-utils.js';
11
+ import { writeFileAtomic } from '../util/atomic-write.js';
11
12
  import { assertEnvelope, buildEnvelope } from './envelope.js';
12
13
  import { currentKernelVersion, getKindModule } from './kernel.js';
13
14
  import { assertCanonical } from './path-canon.js';
@@ -144,10 +145,9 @@ export function writeFile(absPath, envelope, opts = {}) {
144
145
  rows: envelope.rows,
145
146
  };
146
147
 
147
- const tmpPath = `${absPath}.tmp`;
148
- fsImpl.mkdirSync(path.dirname(absPath), { recursive: true });
149
- fsImpl.writeFileSync(tmpPath, `${JSON.stringify(canonical, null, 2)}\n`);
150
- fsImpl.renameSync(tmpPath, absPath);
148
+ writeFileAtomic(absPath, `${JSON.stringify(canonical, null, 2)}\n`, {
149
+ fsImpl,
150
+ });
151
151
  return absPath;
152
152
  }
153
153
 
@@ -4,13 +4,14 @@
4
4
  * keyword-based (not embeddings) so re-planning is deterministic.
5
5
  */
6
6
 
7
- import { readdirSync, readFileSync, statSync } from 'node:fs';
8
- import path from 'node:path';
7
+ import { readFileSync, statSync } from 'node:fs';
9
8
 
10
9
  import { Logger } from './Logger.js';
10
+ import { walkFiles } from './util/paths.js';
11
11
 
12
12
  /**
13
- * Unreadable directories are skipped, never thrown.
13
+ * An unreadable or missing directory is logged at debug and skipped, never
14
+ * thrown; its readable siblings are still listed.
14
15
  *
15
16
  * @param {string[]} roots
16
17
  * @param {{ logger?: { debug: Function } }} [opts]
@@ -18,41 +19,35 @@ import { Logger } from './Logger.js';
18
19
  */
19
20
  export function listFeatureFiles(roots, opts = {}) {
20
21
  const logger = opts.logger ?? Logger;
21
- const out = [];
22
- for (const root of roots ?? []) {
23
- walk(root, out, logger);
22
+ const onError = (err, dir) =>
23
+ logger.debug(
24
+ `[bdd-scenario-scanner] readdir failed for ${dir}: ${err?.message ?? err}`,
25
+ );
26
+ const filter = (abs, d) => isFeatureFile(abs, d, logger);
27
+ return (roots ?? [])
28
+ .filter((root) => rootReadable(root, onError))
29
+ .flatMap((root) => walkFiles(root, { filter, onError }));
30
+ }
31
+
32
+ function rootReadable(root, onError) {
33
+ try {
34
+ statSync(root);
35
+ return true;
36
+ } catch (err) {
37
+ onError(err, root);
38
+ return false;
24
39
  }
25
- return out;
26
40
  }
27
41
 
28
- function walk(dir, acc, logger) {
29
- let entries;
42
+ function isFeatureFile(abs, dirent, logger) {
43
+ if (!dirent.isFile() || !abs.toLowerCase().endsWith('.feature')) return false;
30
44
  try {
31
- entries = readdirSync(dir, { withFileTypes: true });
45
+ return statSync(abs).size <= 256 * 1024; // skip obviously bogus inputs
32
46
  } catch (err) {
33
47
  logger.debug(
34
- `[bdd-scenario-scanner] readdir failed for ${dir}: ${err?.message ?? err}`,
48
+ `[bdd-scenario-scanner] stat failed for ${abs}: ${err?.message ?? err}`,
35
49
  );
36
- return;
37
- }
38
- for (const entry of entries) {
39
- const abs = path.join(dir, entry.name);
40
- if (entry.isDirectory()) {
41
- walk(abs, acc, logger);
42
- continue;
43
- }
44
- if (!entry.isFile()) continue;
45
- if (!abs.toLowerCase().endsWith('.feature')) continue;
46
- try {
47
- const stat = statSync(abs);
48
- if (stat.size > 256 * 1024) continue; // skip obviously bogus inputs
49
- } catch (err) {
50
- logger.debug(
51
- `[bdd-scenario-scanner] stat failed for ${abs}: ${err?.message ?? err}`,
52
- );
53
- continue;
54
- }
55
- acc.push(abs);
50
+ return false;
56
51
  }
57
52
  }
58
53
 
@@ -2,8 +2,7 @@
2
2
  * bootstrap/gh-list — `gh`-backed list providers for live pickers.
3
3
  *
4
4
  * Provides the selection substrate for interactive pickers: thin wrappers
5
- * over `gh repo list` / `gh project list` that shell out via the same
6
- * `spawnSync('gh', …)` convention used elsewhere in the bootstrap libs
5
+ * over `gh repo list` / `gh project list` that shell out via `runGh`
7
6
  * (see `gh-preflight.js`). Both providers return a plain array of string
8
7
  * values and degrade to an **empty array on any non-zero exit** (or spawn
9
8
  * error), so a missing scope, an unauthenticated host, or a `gh` that is
@@ -12,11 +11,11 @@
12
11
  * through to manual entry.
13
12
  *
14
13
  * The `runner` seam mirrors `gh-preflight.js`: it defaults to a real
15
- * `spawnSync('gh', …)` but lets tests inject a stub returning the canonical
14
+ * `runGh` spawn but lets tests inject a stub returning the canonical
16
15
  * `{ status, stdout, stderr, error }` shape without spawning a child.
17
16
  */
18
17
 
19
- import { spawnSync } from 'node:child_process';
18
+ import { runGh } from '../gh-exec.js';
20
19
 
21
20
  /**
22
21
  * Default runner: synchronously execs `gh <args>` and returns the canonical
@@ -28,7 +27,7 @@ import { spawnSync } from 'node:child_process';
28
27
  * error?: NodeJS.ErrnoException }}
29
28
  */
30
29
  function defaultGhRunner(args) {
31
- const result = spawnSync('gh', args, { encoding: 'utf8' });
30
+ const result = runGh(args, { encoding: 'utf8' });
32
31
  return {
33
32
  status: result.status,
34
33
  stdout: typeof result.stdout === 'string' ? result.stdout : '',
@@ -1,12 +1,12 @@
1
1
  /** Provider-agnostic `gh` CLI and runtime-dependency preflight. */
2
2
 
3
- import { spawnSync } from 'node:child_process';
4
3
  import {
5
4
  GhAuthError,
6
5
  GhNotInstalledError,
7
6
  GhVersionError,
8
7
  MissingRuntimeDepsError,
9
8
  } from '../errors/index.js';
9
+ import { runGh } from '../gh-exec.js';
10
10
 
11
11
  /** Older releases miss flags the `gh` shim relies on; bumping is operator-visible. */
12
12
  export const MIN_GH_VERSION = '2.40.0';
@@ -27,15 +27,16 @@ const RUNTIME_DEPS_HINT =
27
27
  'Run `mandrel init` (for a fresh project) or `npm install mandrel` (for an existing one) to install the framework runtime dependencies, then re-run this command.';
28
28
 
29
29
  /**
30
- * Raw `spawnSync`, not the `gh-exec` facade: these probes decide whether the
30
+ * Raw `runGh`, not the `exec()` facade: these probes decide whether the
31
31
  * facade (which assumes an authenticated `gh`) is usable at all.
32
32
  *
33
33
  * @param {string[]} args
34
+ * @param {Function} [spawnImpl]
34
35
  * @returns {{ status: number|null, stdout: string, stderr: string,
35
36
  * error?: NodeJS.ErrnoException }}
36
37
  */
37
- function defaultGhRunner(args) {
38
- const result = spawnSync('gh', args, { encoding: 'utf8' });
38
+ function defaultGhRunner(args, spawnImpl) {
39
+ const result = runGh(args, { encoding: 'utf8' }, spawnImpl);
39
40
  return {
40
41
  status: result.status,
41
42
  stdout: typeof result.stdout === 'string' ? result.stdout : '',
@@ -44,6 +45,10 @@ function defaultGhRunner(args) {
44
45
  };
45
46
  }
46
47
 
48
+ function resolveRunner(opts) {
49
+ return opts.runner ?? ((args) => defaultGhRunner(args, opts.spawnImpl));
50
+ }
51
+
47
52
  /**
48
53
  * @param {string} stdout
49
54
  * @returns {string|null}
@@ -80,11 +85,11 @@ export function compareSemver(a, b) {
80
85
  * @param {{ runner?: (args: string[]) => {
81
86
  * status: number|null, stdout: string, stderr: string,
82
87
  * error?: NodeJS.ErrnoException
83
- * } }} [opts]
88
+ * }, spawnImpl?: Function }} [opts]
84
89
  * @returns {Promise<{ version: string }>}
85
90
  */
86
91
  export async function preflightGh(opts = {}) {
87
- const runner = opts.runner ?? defaultGhRunner;
92
+ const runner = resolveRunner(opts);
88
93
  const version = resolveGhVersion(runner);
89
94
  assertGhVersionFloor(version);
90
95
  assertGhAuth(runner);
@@ -157,12 +162,12 @@ function assertGhAuth(runner) {
157
162
  * @param {{ runner?: (args: string[]) => {
158
163
  * status: number|null, stdout: string, stderr: string,
159
164
  * error?: NodeJS.ErrnoException
160
- * } }} [opts]
165
+ * }, spawnImpl?: Function }} [opts]
161
166
  * @returns {Promise<{ name: string, ok: boolean, remedy?: string,
162
167
  * detail?: string }>}
163
168
  */
164
169
  export async function checkProjectScopes(opts = {}) {
165
- const runner = opts.runner ?? defaultGhRunner;
170
+ const runner = resolveRunner(opts);
166
171
  const result = runner(['auth', 'status']);
167
172
  const text = `${result.stdout || ''}\n${result.stderr || ''}`;
168
173
  return classifyProjectScopes(/Token scopes:([^\n]*)/i.exec(text));
@@ -25,13 +25,13 @@ const MIB = 1024 * 1024;
25
25
  const MAX_BUFFER_BYTES = 64 * MIB;
26
26
 
27
27
  /**
28
- * Deliberately lower bound for `diagnose-friction.js`: a reported policy
29
- * limit (it records `executionMaxBuffer` on the friction row), not an
30
- * overflow guard.
28
+ * The ceiling, readable for *reporting* only: `diagnose-friction.js` names
29
+ * the bound that killed an overflowed child on its friction row. Passing it
30
+ * as a `maxBuffer` is redundant — omitting the option applies it.
31
31
  *
32
32
  * @type {number}
33
33
  */
34
- export const INTERCEPTOR_MAX_BUFFER_BYTES = 10 * MIB;
34
+ export const REPORTED_MAX_BUFFER_BYTES = MAX_BUFFER_BYTES;
35
35
 
36
36
  /**
37
37
  * `maxBuffer` goes last so a caller's spread cannot reset it to 1 MB.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Claude role-agent projection: `.agents/agents/` and `.agents/local/agents/`
3
+ * become `.claude/agents/`, payload winning a collision, with each
4
+ * `delivery.routing.agentModels` entry overriding a role's `model:`. Node
5
+ * built-ins only, so the doctor can import it.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import { applyHeader } from '../command-header.js';
12
+ import { applyAgentModel, getAgentModels } from '../config/agent-models.js';
13
+ import { dirExists } from '../util/paths.js';
14
+
15
+ export const CLAUDE_AGENTS_DIR = '.claude/agents';
16
+
17
+ const HEADER =
18
+ '<!-- AUTO-GENERATED — do not edit. Source of truth: .agents/agents/ -->\n<!-- Re-run: npm run sync:agents -->\n\n';
19
+
20
+ const LOCAL_HEADER =
21
+ '<!-- AUTO-GENERATED from .agents/local/ — do not edit. Source of truth: .agents/local/agents/ -->\n<!-- Re-run: npm run sync:agents -->\n\n';
22
+
23
+ /**
24
+ * @param {string} dir
25
+ * @returns {string[]}
26
+ */
27
+ function agentFilesIn(dir) {
28
+ if (!dirExists(dir)) return [];
29
+ return fs
30
+ .readdirSync(dir, { withFileTypes: true })
31
+ .filter((e) => e.isFile() && e.name.endsWith('.md'))
32
+ .map((e) => e.name);
33
+ }
34
+
35
+ /**
36
+ * @param {string} file
37
+ * @returns {object | null}
38
+ */
39
+ function readJsonOrNull(file) {
40
+ try {
41
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * `agentModels` with local merged over base per role, as `resolveConfig()`
49
+ * would, minus AJV; invalid entries are dropped.
50
+ *
51
+ * @param {string} projectRoot
52
+ * @returns {Record<string, string>}
53
+ */
54
+ function readAgentModels(projectRoot) {
55
+ const modelsIn = (file) =>
56
+ readJsonOrNull(path.join(projectRoot, file))?.delivery?.routing
57
+ ?.agentModels;
58
+ const merged = {
59
+ ...(modelsIn('.agentrc.json') ?? {}),
60
+ ...(modelsIn('.agentrc.local.json') ?? {}),
61
+ };
62
+ return getAgentModels({ delivery: { routing: { agentModels: merged } } });
63
+ }
64
+
65
+ /**
66
+ * Projected bytes keyed by file name.
67
+ *
68
+ * @param {{
69
+ * projectRoot: string,
70
+ * payloadSrc?: string,
71
+ * localSrc?: string,
72
+ * agentModels?: Record<string, string>,
73
+ * warn?: (line: string) => void,
74
+ * }} opts
75
+ * @returns {Map<string, string>}
76
+ */
77
+ export function expectedClaudeAgents({
78
+ projectRoot,
79
+ payloadSrc = path.join(projectRoot, '.agents', 'agents'),
80
+ localSrc = path.join(projectRoot, '.agents', 'local', 'agents'),
81
+ agentModels = readAgentModels(projectRoot),
82
+ warn = () => {},
83
+ }) {
84
+ const expected = new Map();
85
+ for (const [dir, header] of [
86
+ [payloadSrc, HEADER],
87
+ [localSrc, LOCAL_HEADER],
88
+ ]) {
89
+ for (const name of agentFilesIn(dir)) {
90
+ if (expected.has(name)) {
91
+ warn(` shadowed ${name} (local copy ignored; payload wins)`);
92
+ continue;
93
+ }
94
+ const content = fs.readFileSync(path.join(dir, name), 'utf8');
95
+ const model = agentModels[name.replace(/\.md$/, '')];
96
+ expected.set(
97
+ name,
98
+ applyHeader(model ? applyAgentModel(content, model) : content, header),
99
+ );
100
+ }
101
+ }
102
+ return expected;
103
+ }
104
+
105
+ /**
106
+ * @param {string} destDir
107
+ * @returns {string[]}
108
+ */
109
+ export function listGeneratedClaudeAgents(destDir) {
110
+ return agentFilesIn(destDir)
111
+ .filter((f) => !f.startsWith('.'))
112
+ .sort();
113
+ }
114
+
115
+ /**
116
+ * Write the projection, reap orphans, skip unchanged files.
117
+ *
118
+ * @param {{
119
+ * projectRoot: string,
120
+ * payloadSrc?: string,
121
+ * localSrc?: string,
122
+ * destDir?: string,
123
+ * agentModels?: Record<string, string>,
124
+ * log?: (line: string) => void,
125
+ * warn?: (line: string) => void,
126
+ * }} opts
127
+ * @returns {{ written: string[], removed: string[], total: number }}
128
+ */
129
+ export function syncClaudeAgents({
130
+ projectRoot,
131
+ payloadSrc,
132
+ localSrc,
133
+ destDir = path.join(projectRoot, ...CLAUDE_AGENTS_DIR.split('/')),
134
+ agentModels,
135
+ log = () => {},
136
+ warn = log,
137
+ }) {
138
+ fs.mkdirSync(destDir, { recursive: true });
139
+ const expected = expectedClaudeAgents({
140
+ projectRoot,
141
+ payloadSrc,
142
+ localSrc,
143
+ agentModels,
144
+ warn,
145
+ });
146
+
147
+ const removed = [];
148
+ for (const name of agentFilesIn(destDir)) {
149
+ if (expected.has(name)) continue;
150
+ fs.unlinkSync(path.join(destDir, name));
151
+ removed.push(name);
152
+ log(` removed ${name} (no longer in .agents/agents)`);
153
+ }
154
+
155
+ const written = [];
156
+ for (const [name, body] of expected) {
157
+ const dest = path.join(destDir, name);
158
+ let current = null;
159
+ try {
160
+ current = fs.readFileSync(dest, 'utf8');
161
+ } catch (err) {
162
+ if (err.code !== 'ENOENT') throw err;
163
+ }
164
+ if (current === body) continue;
165
+ fs.writeFileSync(dest, body, 'utf8');
166
+ written.push(name);
167
+ log(` synced ${name}`);
168
+ }
169
+ return { written, removed, total: expected.size };
170
+ }