mandrel 2.89.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +38 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/board-backfill.js +253 -0
  14. package/.agents/scripts/check-arch-cycles.js +1 -5
  15. package/.agents/scripts/check-context-budget.js +1 -5
  16. package/.agents/scripts/check-cyclomatic.js +1 -5
  17. package/.agents/scripts/check-dead-exports.js +23 -14
  18. package/.agents/scripts/check-doc-links.js +4 -4
  19. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  20. package/.agents/scripts/coverage-capture.js +14 -6
  21. package/.agents/scripts/diagnose-friction.js +8 -10
  22. package/.agents/scripts/generate-workflows-doc.js +5 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  24. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  25. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  26. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  27. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  28. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  29. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  30. package/.agents/scripts/lib/baselines/components.js +5 -5
  31. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  32. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  33. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  34. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  36. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  37. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  38. package/.agents/scripts/lib/baselines/writer.js +4 -4
  39. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  40. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  41. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  42. package/.agents/scripts/lib/child-exec.js +4 -4
  43. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  44. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  45. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  46. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  47. package/.agents/scripts/lib/close-validation/process.js +5 -1
  48. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  49. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  50. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  51. package/.agents/scripts/lib/config/commands.js +82 -7
  52. package/.agents/scripts/lib/config/explain.js +2 -1
  53. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  54. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  55. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  56. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  57. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  58. package/.agents/scripts/lib/config/git-roots.js +120 -0
  59. package/.agents/scripts/lib/config/quality.js +46 -50
  60. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  61. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  62. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  63. package/.agents/scripts/lib/config-resolver.js +5 -9
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  66. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  67. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  68. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  69. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  70. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  71. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture.js +80 -43
  73. package/.agents/scripts/lib/coverage-utils.js +34 -16
  74. package/.agents/scripts/lib/cpu-pool.js +2 -4
  75. package/.agents/scripts/lib/crap-engine.js +19 -1
  76. package/.agents/scripts/lib/crap-utils.js +2 -1
  77. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  78. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  79. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  80. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  81. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  82. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  83. package/.agents/scripts/lib/gh-env.js +72 -0
  84. package/.agents/scripts/lib/gh-exec.js +26 -1
  85. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  86. package/.agents/scripts/lib/npm-scripts.js +1 -1
  87. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  88. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  89. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  90. package/.agents/scripts/lib/orchestration/board-access-latch.js +112 -0
  91. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  92. package/.agents/scripts/lib/orchestration/column-sync.js +107 -52
  93. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  94. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  95. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  96. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  97. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  98. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  99. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +44 -17
  100. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  101. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  102. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  103. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  104. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  105. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  106. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  107. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  108. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  109. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  110. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  111. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  112. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  113. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  114. package/.agents/scripts/lib/orchestration/story-handoff.js +27 -6
  115. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  116. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  117. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  118. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  119. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  120. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  121. package/.agents/scripts/lib/source-extensions.js +30 -15
  122. package/.agents/scripts/lib/test-run-credit.js +1 -9
  123. package/.agents/scripts/lib/test-temp.js +22 -21
  124. package/.agents/scripts/lib/util/ajv.js +111 -0
  125. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  126. package/.agents/scripts/lib/util/paths.js +51 -0
  127. package/.agents/scripts/lib/util/sleep.js +6 -0
  128. package/.agents/scripts/lib/util/slug.js +12 -0
  129. package/.agents/scripts/lib/validation-evidence.js +19 -40
  130. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  131. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  132. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  133. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  134. package/.agents/scripts/lint-issue-body.js +2 -2
  135. package/.agents/scripts/plan-context.js +2 -7
  136. package/.agents/scripts/providers/github/auth.js +3 -3
  137. package/.agents/scripts/providers/github/board-add.js +18 -9
  138. package/.agents/scripts/providers/github/errors.js +3 -1
  139. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  140. package/.agents/scripts/providers/github/issues.js +6 -2
  141. package/.agents/scripts/providers/github/mappers.js +1 -5
  142. package/.agents/scripts/providers/github/projects-v2-graphql.js +26 -6
  143. package/.agents/scripts/providers/github/search-budget.js +3 -1
  144. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  145. package/.agents/scripts/sync-agentrc.js +5 -14
  146. package/.agents/scripts/sync-claude-agents.js +38 -150
  147. package/.agents/scripts/sync-claude-commands.js +35 -218
  148. package/.agents/scripts/update-coverage-baseline.js +1 -1
  149. package/.agents/scripts/update-crap-baseline.js +1 -1
  150. package/.agents/scripts/update-duplication-baseline.js +2 -16
  151. package/.agents/scripts/validate-skills.js +6 -10
  152. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  153. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  154. package/.agents/workflows/audit-exceptions.md +9 -0
  155. package/.agents/workflows/audit-lean.md +129 -0
  156. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  157. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  158. package/.agents/workflows/helpers/code-review.md +15 -1
  159. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  160. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  161. package/.agents/workflows/mandrel-plan.md +2 -2
  162. package/docs/CHANGELOG.md +48 -0
  163. package/lib/cli/doctor-checks/codex.js +6 -5
  164. package/lib/cli/doctor-checks/llm-review.js +102 -0
  165. package/lib/cli/doctor-checks/project-access.js +124 -0
  166. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  167. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  168. package/lib/cli/doctor-checks/toolchain.js +5 -3
  169. package/lib/cli/registry.js +11 -0
  170. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  171. package/lib/migrations/index.js +6 -0
  172. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  173. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  174. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  175. package/package.json +1 -3
@@ -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
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Claude command projection: `.agents/workflows/` and `.agents/local/workflows/`
3
+ * become a flat `.claude/commands/` tree (flat, not a plugin tree, which some
4
+ * hosts lack). Payload wins a collision; `loops/` is the one recursed
5
+ * subdirectory. Node 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, isCommandExcluded } from '../command-header.js';
12
+ import { dirExists } from '../util/paths.js';
13
+
14
+ export const CLAUDE_COMMANDS_DIR = '.claude/commands';
15
+
16
+ const HEADER =
17
+ '<!-- AUTO-GENERATED — do not edit. Source of truth: .agents/workflows/ -->\n<!-- Re-run: npm run sync:commands -->\n\n';
18
+
19
+ const LOCAL_HEADER =
20
+ '<!-- AUTO-GENERATED from .agents/local/ — do not edit. Source of truth: .agents/local/workflows/ -->\n<!-- Re-run: npm run sync:commands -->\n\n';
21
+
22
+ const LOOPS_NS = 'loops';
23
+
24
+ /**
25
+ * @param {string} dir
26
+ * @param {boolean} skipReadme
27
+ * @returns {string[]}
28
+ */
29
+ function mdFilesIn(dir, skipReadme) {
30
+ if (!dirExists(dir)) return [];
31
+ return fs
32
+ .readdirSync(dir, { withFileTypes: true })
33
+ .filter(
34
+ (e) =>
35
+ e.isFile() &&
36
+ e.name.endsWith('.md') &&
37
+ !(skipReadme && e.name.toLowerCase() === 'readme.md'),
38
+ )
39
+ .map((e) => e.name);
40
+ }
41
+
42
+ /**
43
+ * Flat commands, then `loops/<name>.md`.
44
+ *
45
+ * @param {string} dir
46
+ * @returns {string[]}
47
+ */
48
+ function commandRelsIn(dir) {
49
+ return [
50
+ ...mdFilesIn(dir, false),
51
+ ...mdFilesIn(path.join(dir, LOOPS_NS), true).map((f) => `${LOOPS_NS}/${f}`),
52
+ ];
53
+ }
54
+
55
+ /**
56
+ * Projected bytes keyed by destination-relative path. A `command: false` copy
57
+ * never claims its name.
58
+ *
59
+ * @param {{
60
+ * projectRoot: string,
61
+ * payloadSrc?: string,
62
+ * localSrc?: string,
63
+ * warn?: (line: string) => void,
64
+ * }} opts
65
+ * @returns {Map<string, string>}
66
+ */
67
+ export function expectedClaudeCommands({
68
+ projectRoot,
69
+ payloadSrc = path.join(projectRoot, '.agents', 'workflows'),
70
+ localSrc = path.join(projectRoot, '.agents', 'local', 'workflows'),
71
+ warn = () => {},
72
+ }) {
73
+ const expected = new Map();
74
+ for (const [dir, header] of [
75
+ [payloadSrc, HEADER],
76
+ [localSrc, LOCAL_HEADER],
77
+ ]) {
78
+ for (const rel of commandRelsIn(dir)) {
79
+ if (expected.has(rel)) {
80
+ warn(` shadowed ${rel} (local copy ignored; payload wins)`);
81
+ continue;
82
+ }
83
+ const content = fs.readFileSync(path.join(dir, rel), 'utf8');
84
+ if (isCommandExcluded(content)) {
85
+ warn(` excluded ${rel} (frontmatter command: false)`);
86
+ continue;
87
+ }
88
+ expected.set(rel, applyHeader(content, header));
89
+ }
90
+ }
91
+ return expected;
92
+ }
93
+
94
+ /**
95
+ * @param {string} destDir
96
+ * @returns {string[]}
97
+ */
98
+ export function listGeneratedClaudeCommands(destDir) {
99
+ return commandRelsIn(destDir)
100
+ .filter((rel) => !path.basename(rel).startsWith('.'))
101
+ .sort();
102
+ }
103
+
104
+ /**
105
+ * Remove a plugin projection, which would shadow the flat commands.
106
+ *
107
+ * @param {string} projectRoot
108
+ * @param {(line: string) => void} warn
109
+ * @returns {void}
110
+ */
111
+ function reapPluginTree(projectRoot, warn) {
112
+ const claudeDir = path.join(projectRoot, '.claude');
113
+ for (const target of [
114
+ path.join(claudeDir, 'plugins', 'mandrel'),
115
+ path.join(claudeDir, '.claude-plugin', 'marketplace.json'),
116
+ ]) {
117
+ try {
118
+ fs.rmSync(target, { recursive: true, force: true });
119
+ } catch (err) {
120
+ warn(` skip reap ${target}: ${err.message}`);
121
+ }
122
+ }
123
+ try {
124
+ fs.rmdirSync(path.join(claudeDir, '.claude-plugin'));
125
+ } catch {
126
+ /* not empty or absent — leave it */
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Write the projection, reap orphans, skip unchanged files.
132
+ *
133
+ * @param {{
134
+ * projectRoot: string,
135
+ * payloadSrc?: string,
136
+ * localSrc?: string,
137
+ * destDir?: string,
138
+ * log?: (line: string) => void,
139
+ * warn?: (line: string) => void,
140
+ * }} opts
141
+ * @returns {{ written: string[], removed: string[], total: number }}
142
+ */
143
+ export function syncClaudeCommands({
144
+ projectRoot,
145
+ payloadSrc,
146
+ localSrc,
147
+ destDir = path.join(projectRoot, ...CLAUDE_COMMANDS_DIR.split('/')),
148
+ log = () => {},
149
+ warn = log,
150
+ }) {
151
+ reapPluginTree(projectRoot, warn);
152
+ fs.mkdirSync(destDir, { recursive: true });
153
+ const expected = expectedClaudeCommands({
154
+ projectRoot,
155
+ payloadSrc,
156
+ localSrc,
157
+ warn,
158
+ });
159
+
160
+ const removed = [];
161
+ for (const rel of commandRelsIn(destDir)) {
162
+ if (expected.has(rel)) continue;
163
+ fs.unlinkSync(path.join(destDir, rel));
164
+ removed.push(rel);
165
+ log(` removed ${rel} (no longer in workflows)`);
166
+ }
167
+
168
+ const written = [];
169
+ for (const [rel, body] of expected) {
170
+ const dest = path.join(destDir, rel);
171
+ let current = null;
172
+ try {
173
+ current = fs.readFileSync(dest, 'utf8');
174
+ } catch (err) {
175
+ if (err.code !== 'ENOENT') throw err;
176
+ }
177
+ if (current === body) continue;
178
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
179
+ fs.writeFileSync(dest, body, 'utf8');
180
+ written.push(rel);
181
+ log(` synced ${rel}`);
182
+ }
183
+ return { written, removed, total: expected.size };
184
+ }