mandrel 2.86.0 → 2.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  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 +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -3,1342 +3,51 @@
3
3
  * Ordered `mandrel doctor` check registry: each entry is `{ name, run() }`,
4
4
  * `run()` returning `{ ok, detail, remedy? }` (`remedy` present whenever
5
5
  * `ok` is false). Checks run sequentially because some presuppose an earlier
6
- * one (`gh-auth` needs `gh-available`). Node built-ins only, so the module
7
- * loads inside the preflight guard before third-party packages exist; no
8
- * check ever echoes a token value.
6
+ * one (`gh-auth` needs `gh-available`). Each check lives under
7
+ * `doctor-checks/`; this array is the order. Node built-ins only (here and in
8
+ * every check module), so it loads inside the preflight guard before
9
+ * third-party packages exist; no check ever echoes a token value.
9
10
  */
10
11
 
11
- import { spawnSync } from 'node:child_process';
12
- import fs from 'node:fs';
13
- import { createRequire } from 'node:module';
14
- import os from 'node:os';
15
- import path from 'node:path';
16
- import { fileURLToPath } from 'node:url';
17
- import {
18
- SYSTEM_PROMPT_IMPORT,
19
- SYSTEM_PROMPT_READ_DIRECTIVE,
20
- } from '../../.agents/scripts/lib/bootstrap/agents-md-fold.js';
21
- import {
22
- BASELINE_MERGE_DRIVER_CONFIG_KEY,
23
- BASELINE_MERGE_DRIVER_REMEDY,
24
- parseBaselineMergeDriverCommand,
25
- probeBaselineMergeDriver,
26
- } from '../../.agents/scripts/lib/bootstrap/baseline-merge-driver.js';
27
- import {
28
- REQUIRED_NODE_CEILING_MAJOR,
29
- REQUIRED_NODE_FLOOR,
30
- satisfiesNodeEngine,
31
- } from '../../.agents/scripts/lib/bootstrap/project-bootstrap.js';
12
+ import { runClaudeCodeVersion } from './claude-code-version.js';
32
13
  import {
33
- CODEX_AGENTS_DIR,
34
- expectedCodexAgents,
35
- listGeneratedCodexAgents,
36
- } from '../../.agents/scripts/lib/codex/agents-projection.js';
14
+ CODEX_PROJECT_DOC_MAX_BYTES,
15
+ readProjectDocMaxBytes,
16
+ runCodexAgentsInSync,
17
+ runCodexInstructions,
18
+ runCodexSkillsInSync,
19
+ } from './doctor-checks/codex.js';
20
+ import { runMergeDriver } from './doctor-checks/merge-driver.js';
21
+ import { runAgentsDrift, runPinCurrent } from './doctor-checks/payload.js';
37
22
  import {
38
- CODEX_SKILLS_DIR,
39
- expectedCodexSkills,
40
- listGeneratedCodexSkills,
41
- } from '../../.agents/scripts/lib/codex/skills-projection.js';
42
- import { isCommandExcluded } from '../../.agents/scripts/lib/command-header.js';
43
- import { getDeliveryRouting } from '../../.agents/scripts/lib/config/delivery-routing.js';
44
- import { isResolvable } from '../../.agents/scripts/lib/runtime-deps/dep-resolution.js';
45
- import { describeParserMajorError } from '../../.agents/scripts/lib/runtime-deps/parser-major.js';
46
- import { runClaudeCodeVersion } from './claude-code-version.js';
23
+ runAgentsMaterialized,
24
+ runRuntimeDeps,
25
+ } from './doctor-checks/runtime-deps.js';
26
+ import { spawn } from './doctor-checks/spawn.js';
47
27
  import {
48
- defaultResolvePackageRoot,
49
- listFiles as listPayloadFiles,
50
- } from './sync.js';
51
- import { readCache } from './version-check.js';
28
+ runAgentsInSync,
29
+ runCommandsInSync,
30
+ } from './doctor-checks/sync-parity.js';
31
+ import { runTestCreditPath } from './doctor-checks/test-credit-path.js';
52
32
  import {
53
- compareVersions as compareSemver,
54
- resolveConsumerPinSpec,
55
- satisfiesPinSpec,
56
- } from './version-helpers.js';
57
-
58
- /**
59
- * @param {string} cmd
60
- * @param {string[]} args
61
- * @returns {{ status: number|null, stdout: string, stderr: string, error?: NodeJS.ErrnoException }}
62
- */
63
- function spawn(cmd, args, opts = {}) {
64
- const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
65
- return {
66
- status: r.status,
67
- stdout: typeof r.stdout === 'string' ? r.stdout : '',
68
- stderr: typeof r.stderr === 'string' ? r.stderr : '',
69
- error: r.error,
70
- };
71
- }
72
-
73
- // check: node-version
74
-
75
- /**
76
- * @param {{ nodeVersion?: string }} [opts]
77
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
78
- */
79
- function runNodeVersion({ nodeVersion = process.versions.node } = {}) {
80
- const ok = satisfiesNodeEngine(nodeVersion);
81
- const detail = `v${nodeVersion} (required >=${REQUIRED_NODE_FLOOR} <${REQUIRED_NODE_CEILING_MAJOR})`;
82
- if (ok) return { ok: true, detail };
83
- return {
84
- ok: false,
85
- detail,
86
- remedy: `Upgrade Node to >=${REQUIRED_NODE_FLOOR} <${REQUIRED_NODE_CEILING_MAJOR}: https://nodejs.org/`,
87
- };
88
- }
89
-
90
- // check: git-available
91
-
92
- /**
93
- * @param {{ runner?: (cmd: string, args: string[]) => { status: number|null, stdout: string, stderr: string, error?: NodeJS.ErrnoException } }} [opts]
94
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
95
- */
96
- function runGitAvailable({ runner = spawn } = {}) {
97
- const r = runner('git', ['--version']);
98
- if (r.error?.code === 'ENOENT' || r.status !== 0) {
99
- const snippet = (r.stderr || r.stdout || '').trim().slice(0, 120);
100
- return {
101
- ok: false,
102
- detail: snippet || 'git not found on PATH',
103
- remedy: 'Install git: https://git-scm.com/downloads — then re-run.',
104
- };
105
- }
106
- return { ok: true, detail: r.stdout.trim().split('\n')[0] };
107
- }
108
-
109
- // check: gh-available
110
-
111
- /**
112
- * @param {{ runner?: (cmd: string, args: string[]) => { status: number|null, stdout: string, stderr: string, error?: NodeJS.ErrnoException } }} [opts]
113
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
114
- */
115
- function runGhAvailable({ runner = spawn } = {}) {
116
- const r = runner('gh', ['--version']);
117
- if (r.error?.code === 'ENOENT' || r.status !== 0) {
118
- const snippet = (r.stderr || r.stdout || '').trim().slice(0, 120);
119
- return {
120
- ok: false,
121
- detail: snippet || 'gh not found on PATH',
122
- remedy: 'Install gh CLI: https://cli.github.com/ — then re-run.',
123
- };
124
- }
125
- return { ok: true, detail: r.stdout.trim().split('\n')[0] };
126
- }
127
-
128
- // check: github-token
129
-
130
- /**
131
- * Resolve a token the way `providers/github/auth.js#resolveToken` does: env
132
- * `GITHUB_TOKEN`/`GH_TOKEN`, else `gh auth token`. The CLI does not load
133
- * `.env`, so an env-only check would false-block `gh auth login` users.
134
- *
135
- * @param {{ env?: Record<string,string|undefined>,
136
- * runner?: (cmd: string, args: string[]) => {
137
- * status: number|null, stdout: string, stderr: string,
138
- * error?: NodeJS.ErrnoException } }} [opts]
139
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
140
- */
141
- function runGithubToken({ env = process.env, runner = spawn } = {}) {
142
- const envToken = env.GITHUB_TOKEN || env.GH_TOKEN;
143
- if (envToken && envToken.length > 0) {
144
- return { ok: true, detail: 'GITHUB_TOKEN set' };
145
- }
146
- const r = runner('gh', ['auth', 'token']);
147
- const ghToken = !r.error && r.status === 0 ? (r.stdout || '').trim() : '';
148
- if (ghToken.length > 0) {
149
- return { ok: true, detail: 'token resolved via `gh auth token`' };
150
- }
151
- return {
152
- ok: false,
153
- detail: 'no GitHub token (env unset, `gh auth token` returned nothing)',
154
- remedy:
155
- 'Run `gh auth login` (the CLI resolves the token via `gh auth token`), or export GITHUB_TOKEN=<your-token>.',
156
- };
157
- }
158
-
159
- // check: gh-auth
160
-
161
- /**
162
- * `gh auth status` live-validates the token, which an Actions installation
163
- * token (and some fine-grained tokens) cannot pass even though they work for
164
- * everything mandrel does. The runtime never consults it, so a failing status
165
- * with an env token present is warn-and-skip (ok); only "no token and not
166
- * logged in" fails.
167
- *
168
- * @param {{ runner?: (cmd: string, args: string[]) => { status: number|null, stdout: string, stderr: string, error?: NodeJS.ErrnoException }, env?: Record<string,string|undefined> }} [opts]
169
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
170
- */
171
- function runGhAuth({ runner = spawn, env = process.env } = {}) {
172
- const r = runner('gh', ['auth', 'status']);
173
- if (r.error?.code === 'ENOENT') {
174
- return {
175
- ok: false,
176
- detail: 'gh not found — auth check skipped',
177
- remedy: 'Install the GitHub CLI: https://cli.github.com',
178
- };
179
- }
180
- if (r.status !== 0) {
181
- const envToken = env.GITHUB_TOKEN || env.GH_TOKEN;
182
- if (envToken && envToken.length > 0) {
183
- return {
184
- ok: true,
185
- detail:
186
- '`gh auth status` could not validate the active token, but GITHUB_TOKEN/GH_TOKEN is set (the runtime authenticates non-interactively with it)',
187
- };
188
- }
189
- return {
190
- ok: false,
191
- detail: 'not logged in',
192
- remedy:
193
- 'Run `gh auth login` (choose GitHub.com → HTTPS → login with a web browser), then re-run.',
194
- };
195
- }
196
- const output = (r.stdout + r.stderr).trim();
197
- const match = /Logged in to \S+ as (\S+)/i.exec(output);
198
- const detail = match ? `logged in as ${match[1]}` : 'logged in';
199
- return { ok: true, detail };
200
- }
201
-
202
- // check: commands-in-sync
203
-
204
- /**
205
- * Parity of `.claude/commands/*.md` against the union of `.agents/workflows/`
206
- * and `.agents/local/workflows/`. A basename is expected iff at least one
207
- * source copy is not `command: false`, mirroring the sync script's
208
- * payload-wins shadowing; an unreadable source counts as projected.
209
- *
210
- * The root defaults to `process.cwd()`, never `resolveProjectRoot()` — that
211
- * lands on `node_modules/mandrel/` in an installed consumer, where the
212
- * command tree never exists, producing a permanent false "not synced".
213
- *
214
- * @param {{ projectRoot?: string, cwd?: () => string, readDir?: (dir: string) => string[], readFile?: (file: string) => string | null }} [opts]
215
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
216
- */
217
- function runCommandsInSync({ projectRoot, cwd, readDir, readFile } = {}) {
218
- const getCwd = cwd ?? (() => process.cwd());
219
- const root = projectRoot ?? getCwd();
220
- const listDir =
221
- readDir ??
222
- ((dir) => {
223
- try {
224
- return fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
225
- } catch {
226
- return [];
227
- }
228
- });
229
- const readSource =
230
- readFile ??
231
- ((file) => {
232
- try {
233
- return fs.readFileSync(file, 'utf8');
234
- } catch {
235
- return null;
236
- }
237
- });
238
-
239
- const srcDirs = [
240
- path.join(root, '.agents', 'workflows'),
241
- path.join(root, '.agents', 'local', 'workflows'),
242
- ];
243
- const destDir = path.join(root, '.claude', 'commands');
244
-
245
- // Top-level .md only (helpers/ are included modules, not commands).
246
- const expected = new Set();
247
- for (const srcDir of srcDirs) {
248
- for (const f of listDir(srcDir)) {
249
- if (f.startsWith('.')) continue;
250
- const content = readSource(path.join(srcDir, f));
251
- if (content != null && isCommandExcluded(content)) continue;
252
- expected.add(f);
253
- }
254
- }
255
- const sources = [...expected].sort();
256
- const dests = listDir(destDir)
257
- .filter((f) => !f.startsWith('.'))
258
- .sort();
259
-
260
- const dstSet = new Set(dests);
261
- const missing = sources.filter((f) => !dstSet.has(f));
262
- const extra = dests.filter((f) => !expected.has(f));
263
-
264
- if (missing.length === 0 && extra.length === 0) {
265
- return { ok: true, detail: `${sources.length} commands up to date` };
266
- }
267
-
268
- const parts = [];
269
- if (missing.length > 0) parts.push(`${missing.length} not synced`);
270
- if (extra.length > 0) parts.push(`${extra.length} stale`);
271
- return {
272
- ok: false,
273
- detail: parts.join(', '),
274
- remedy:
275
- 'Run `npm run sync:commands` to regenerate the `.claude/commands/` tree.',
276
- };
277
- }
278
-
279
- // check: agents-in-sync
280
-
281
- /**
282
- * Raw JSON read; any failure degrades to `null`.
283
- *
284
- * @param {string} absPath
285
- * @param {typeof fs} fsImpl
286
- * @returns {object | null}
287
- */
288
- function readJsonSafe(absPath, fsImpl) {
289
- try {
290
- return JSON.parse(fsImpl.readFileSync(absPath, 'utf8'));
291
- } catch {
292
- return null;
293
- }
294
- }
295
-
296
- /**
297
- * Resolve `delivery.routing.roleScopedAgents` without `resolveConfig()`,
298
- * which pulls in AJV and would break the built-ins-only contract. Shallow-
299
- * merges only `delivery.routing` from `.agentrc.json` and
300
- * `.agentrc.local.json` (local wins).
301
- *
302
- * @param {string} projectRoot
303
- * @param {typeof fs} fsImpl
304
- * @returns {boolean}
305
- */
306
- function resolveRoleScopedAgentsFlag(projectRoot, fsImpl) {
307
- const base = readJsonSafe(path.join(projectRoot, '.agentrc.json'), fsImpl);
308
- const local = readJsonSafe(
309
- path.join(projectRoot, '.agentrc.local.json'),
310
- fsImpl,
311
- );
312
- const merged = {
313
- delivery: {
314
- routing: {
315
- ...(base?.delivery?.routing ?? {}),
316
- ...(local?.delivery?.routing ?? {}),
317
- },
318
- },
319
- };
320
- return getDeliveryRouting(merged).roleScopedAgents;
321
- }
322
-
323
- /**
324
- * Parity of `.claude/agents/*.md` against `.agents/agents/*.md` (root anchored
325
- * at `process.cwd()` as in `commands-in-sync`). A never-materialized tree is
326
- * fatal while `roleScopedAgents` is on — the acceptance critic would silently
327
- * fail to spawn and fall back to a weaker inline critic — and advisory when it
328
- * is off. Drift in a materialized tree always fails.
329
- *
330
- * @param {{
331
- * projectRoot?: string,
332
- * cwd?: () => string,
333
- * readDir?: (dir: string) => string[],
334
- * fsImpl?: typeof fs,
335
- * roleScopedAgents?: boolean,
336
- * }} [opts]
337
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
338
- */
339
- function runAgentsInSync({
340
- projectRoot,
341
- cwd,
342
- readDir,
343
- fsImpl = fs,
344
- roleScopedAgents,
345
- } = {}) {
346
- const getCwd = cwd ?? (() => process.cwd());
347
- const root = projectRoot ?? getCwd();
348
- const listDir =
349
- readDir ??
350
- ((dir) => {
351
- try {
352
- return fsImpl.readdirSync(dir).filter((f) => f.endsWith('.md'));
353
- } catch {
354
- return [];
355
- }
356
- });
357
-
358
- const srcDir = path.join(root, '.agents', 'agents');
359
- const destDir = path.join(root, '.claude', 'agents');
360
-
361
- const sources = listDir(srcDir)
362
- .filter((f) => !f.startsWith('.'))
363
- .sort();
364
- const dests = listDir(destDir)
365
- .filter((f) => !f.startsWith('.'))
366
- .sort();
367
-
368
- if (dests.length === 0) {
369
- if (sources.length === 0) {
370
- return { ok: true, detail: '0 agents up to date' };
371
- }
372
- const resolvedFlag =
373
- typeof roleScopedAgents === 'boolean'
374
- ? roleScopedAgents
375
- : resolveRoleScopedAgentsFlag(root, fsImpl);
376
- if (!resolvedFlag) {
377
- return {
378
- ok: true,
379
- detail: `${sources.length} agent def(s) not materialized (roleScopedAgents is disabled)`,
380
- };
381
- }
382
- return {
383
- ok: false,
384
- detail: `${sources.length} agent def(s) not yet materialized in .claude/agents/`,
385
- remedy:
386
- 'Run `mandrel sync-agents` to regenerate the `.claude/agents/` tree.',
387
- };
388
- }
389
-
390
- const srcSet = new Set(sources);
391
- const dstSet = new Set(dests);
392
- const missing = sources.filter((f) => !dstSet.has(f));
393
- const extra = dests.filter((f) => !srcSet.has(f));
394
-
395
- if (missing.length === 0 && extra.length === 0) {
396
- return { ok: true, detail: `${sources.length} agents up to date` };
397
- }
398
-
399
- const parts = [];
400
- if (missing.length > 0) parts.push(`${missing.length} not synced`);
401
- if (extra.length > 0) parts.push(`${extra.length} stale`);
402
- return {
403
- ok: false,
404
- detail: parts.join(', '),
405
- remedy:
406
- 'Run `mandrel sync-agents` to regenerate the `.claude/agents/` tree.',
407
- };
408
- }
409
-
410
- // check: codex-skills-in-sync / codex-agents-in-sync
411
-
412
- /**
413
- * Compare a generated tree against what its projector would write now.
414
- * `readEntry(name)` returns the on-disk text or null.
415
- *
416
- * @param {{
417
- * expected: () => Map<string, string>,
418
- * onDisk: string[],
419
- * readEntry: (name: string) => string | null,
420
- * noun: string,
421
- * where: string,
422
- * remedy: string,
423
- * }} spec
424
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
425
- */
426
- function projectionParity({
427
- expected,
428
- onDisk,
429
- readEntry,
430
- noun,
431
- where,
432
- remedy,
433
- }) {
434
- let want;
435
- try {
436
- want = expected();
437
- } catch (err) {
438
- return { ok: false, detail: err.message, remedy };
439
- }
440
- const have = new Set(onDisk);
441
- const missing = [...want.keys()].filter((n) => !have.has(n));
442
- const stale = [...want.entries()].filter(
443
- ([n, body]) => have.has(n) && readEntry(n) !== body,
444
- );
445
- const extra = onDisk.filter((n) => !want.has(n));
446
- if (missing.length + stale.length + extra.length === 0) {
447
- return { ok: true, detail: `${want.size} ${noun} up to date in ${where}` };
448
- }
449
- const parts = [];
450
- if (missing.length > 0) parts.push(`${missing.length} not synced`);
451
- if (stale.length + extra.length > 0) {
452
- parts.push(`${stale.length + extra.length} stale`);
453
- }
454
- return { ok: false, detail: `${parts.join(', ')} in ${where}`, remedy };
455
- }
456
-
457
- /**
458
- * @param {string} file
459
- * @returns {string | null}
460
- */
461
- function readTextOrNull(file) {
462
- try {
463
- return fs.readFileSync(file, 'utf8');
464
- } catch {
465
- return null;
466
- }
467
- }
468
-
469
- /**
470
- * Parity of `.agents/skills/workflows/` against the workflow set — the Codex
471
- * twin of `commands-in-sync`, byte-for-byte rather than by name.
472
- *
473
- * @param {{ projectRoot?: string, cwd?: () => string }} [opts]
474
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
475
- */
476
- export function runCodexSkillsInSync({ projectRoot, cwd } = {}) {
477
- const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
478
- const destDir = path.join(root, ...CODEX_SKILLS_DIR.split('/'));
479
- return projectionParity({
480
- expected: () => expectedCodexSkills({ projectRoot: root }),
481
- onDisk: listGeneratedCodexSkills(destDir),
482
- readEntry: (name) => readTextOrNull(path.join(destDir, name, 'SKILL.md')),
483
- noun: 'Codex skills',
484
- where: `${CODEX_SKILLS_DIR}/`,
485
- remedy: `Run \`mandrel sync-commands\` to regenerate the Codex skills under \`${CODEX_SKILLS_DIR}/\`.`,
486
- });
487
- }
488
-
489
- /**
490
- * Parity of `.codex/agents/mandrel-*.toml` against `.agents/agents/` — the
491
- * Codex twin of `agents-in-sync`.
492
- *
493
- * @param {{ projectRoot?: string, cwd?: () => string }} [opts]
494
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
495
- */
496
- export function runCodexAgentsInSync({ projectRoot, cwd } = {}) {
497
- const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
498
- const destDir = path.join(root, ...CODEX_AGENTS_DIR.split('/'));
499
- return projectionParity({
500
- expected: () => expectedCodexAgents({ projectRoot: root }),
501
- onDisk: listGeneratedCodexAgents(destDir),
502
- readEntry: (name) => readTextOrNull(path.join(destDir, name)),
503
- noun: 'Codex agents',
504
- where: `${CODEX_AGENTS_DIR}/`,
505
- remedy: `Run \`mandrel sync-agents\` to regenerate \`${CODEX_AGENTS_DIR}/mandrel-<role>.toml\`.`,
506
- });
507
- }
508
-
509
- // check: codex-instructions
510
-
511
- /** Codex's default `project_doc_max_bytes`. */
512
- export const CODEX_PROJECT_DOC_MAX_BYTES = 32768;
513
-
514
- /**
515
- * A top-level `project_doc_max_bytes = <int>` line before any `[table]`
516
- * header; anything else (absent file, nested key, non-integer) is null. No
517
- * TOML dependency — this one key is all the check needs.
518
- *
519
- * @param {string | null} text
520
- * @returns {number | null}
521
- */
522
- export function readProjectDocMaxBytes(text) {
523
- if (typeof text !== 'string') return null;
524
- for (const line of text.split(/\r?\n/)) {
525
- if (/^\s*\[/.test(line)) return null;
526
- const match = /^\s*project_doc_max_bytes\s*=\s*(\d+)\s*(?:#.*)?$/.exec(
527
- line,
528
- );
529
- if (match) return Number(match[1]);
530
- }
531
- return null;
532
- }
533
-
534
- /**
535
- * Effective limit and where it came from: project `.codex/config.toml`, then
536
- * `$CODEX_HOME/config.toml` (default `~/.codex`), else the default.
537
- *
538
- * @param {string} root
539
- * @param {NodeJS.ProcessEnv} env
540
- * @param {string} homeDir
541
- * @param {(file: string) => string | null} readText
542
- * @returns {{ limit: number, source: string }}
543
- */
544
- function resolveProjectDocLimit(root, env, homeDir, readText) {
545
- const codexHome = env.CODEX_HOME || path.join(homeDir, '.codex');
546
- for (const [file, source] of [
547
- [path.join(root, '.codex', 'config.toml'), '.codex/config.toml'],
548
- [path.join(codexHome, 'config.toml'), '$CODEX_HOME/config.toml'],
549
- ]) {
550
- const limit = readProjectDocMaxBytes(readText(file));
551
- if (limit !== null) return { limit, source };
552
- }
553
- return { limit: CODEX_PROJECT_DOC_MAX_BYTES, source: 'the Codex default' };
554
- }
555
-
556
- const HOIST_REMEDY =
557
- 'Move the `## System Prompt` block to the top of the file, or run `mandrel update` (its 2.84.0 migration moves it).';
558
-
559
- /**
560
- * Does Codex load the Mandrel block? Sizes the root `AGENTS.override.md`, else
561
- * `AGENTS.md`, against the effective `project_doc_max_bytes`. Fails when the
562
- * block (import through read directive) does not end inside the limit, or
563
- * carries no directive Codex can follow; an oversized file whose block still
564
- * loads passes with an advisory. No entry doc at all skips, as
565
- * `claude-code-version` does.
566
- *
567
- * @param {{
568
- * projectRoot?: string,
569
- * cwd?: () => string,
570
- * env?: NodeJS.ProcessEnv,
571
- * homeDir?: string,
572
- * readText?: (file: string) => string | null,
573
- * }} [opts]
574
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
575
- */
576
- export function runCodexInstructions({
577
- projectRoot,
578
- cwd,
579
- env = process.env,
580
- homeDir = os.homedir(),
581
- readText = readTextOrNull,
582
- } = {}) {
583
- const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
584
- const { limit, source } = resolveProjectDocLimit(
585
- root,
586
- env,
587
- homeDir,
588
- readText,
589
- );
590
- const override = readText(path.join(root, 'AGENTS.override.md'));
591
- const docName = override === null ? 'AGENTS.md' : 'AGENTS.override.md';
592
- const text = override ?? readText(path.join(root, 'AGENTS.md'));
593
- if (text === null) {
594
- return { ok: true, detail: 'skipped: no AGENTS.md' };
595
- }
596
- const importAt = text.indexOf(SYSTEM_PROMPT_IMPORT);
597
- const directiveAt = text.indexOf(SYSTEM_PROMPT_READ_DIRECTIVE);
598
- if (importAt === -1 || directiveAt === -1) {
599
- return {
600
- ok: false,
601
- detail: `${docName} carries no Mandrel read directive for hosts without @-imports — Codex would not load .agents/instructions.md`,
602
- remedy: HOIST_REMEDY,
603
- };
604
- }
605
- const bytes = (s) => Buffer.byteLength(s, 'utf8');
606
- const start = bytes(text.slice(0, Math.min(importAt, directiveAt)));
607
- const end = bytes(
608
- text.slice(0, directiveAt + SYSTEM_PROMPT_READ_DIRECTIVE.length),
609
- );
610
- const total = bytes(text);
611
- const limitLabel = `project_doc_max_bytes ${limit} (${source})`;
612
- if (end > limit) {
613
- return {
614
- ok: false,
615
- detail: `the Mandrel block in ${docName} spans bytes ${start}–${end}, beyond ${limitLabel} — Codex never reads it`,
616
- remedy: HOIST_REMEDY,
617
- };
618
- }
619
- if (total > limit) {
620
- return {
621
- ok: true,
622
- detail: `${docName} is ${total} bytes, over ${limitLabel}: the Mandrel block (bytes ${start}–${end}) loads, the last ${total - limit} bytes do not — raise project_doc_max_bytes in .codex/config.toml to load them`,
623
- };
624
- }
625
- return {
626
- ok: true,
627
- detail: `${docName} is ${total} bytes, within ${limitLabel}; the Mandrel block loads`,
628
- };
629
- }
630
-
631
- // check: runtime-deps
632
-
633
- /**
634
- * Presence is not enough: a declared range cannot pin which `@babel/parser`
635
- * major the consumer's node_modules supplies, and the wrong one fails
636
- * scoring mid-scan with an opaque error — so report it here.
637
- *
638
- * @param {() => string|null} parserMajorError
639
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
640
- */
641
- function allPresentVerdict(parserMajorError) {
642
- const parserProblem = parserMajorError();
643
- if (parserProblem === null) {
644
- return { ok: true, detail: 'all dependencies found' };
645
- }
646
- return {
647
- ok: false,
648
- detail: 'dependency version unsupported',
649
- remedy: parserProblem,
650
- };
651
- }
652
-
653
- /**
654
- * Are the runtime deps resolvable from the consumer root? Anchored at
655
- * `process.cwd()`, not the package root: under pnpm isolated mode the
656
- * consumer's node_modules are invisible from `node_modules/mandrel/`.
657
- *
658
- * @param {{ projectRoot?: string, resolve?: (dep: string) => string, manifestRequired?: string[] }} [opts]
659
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
660
- */
661
- function runRuntimeDeps({
662
- projectRoot,
663
- resolve: resolveSeam,
664
- manifestRequired,
665
- parserMajorError = describeParserMajorError,
666
- } = {}) {
667
- const root = projectRoot ?? process.cwd();
668
-
669
- let required = manifestRequired;
670
- if (!required) {
671
- try {
672
- const manifestPath = path.join(root, '.agents', 'runtime-deps.json');
673
- const raw = fs.readFileSync(manifestPath, 'utf8');
674
- const parsed = JSON.parse(raw);
675
- required = Object.keys(parsed.dependencies ?? {});
676
- } catch {
677
- required = [];
678
- }
679
- }
680
-
681
- if (required.length === 0) {
682
- return { ok: true, detail: 'all dependencies found' };
683
- }
684
-
685
- const missing = [];
686
-
687
- // `isResolvable` also probes `<name>/package.json`: a dep with no `main`
688
- // and no `exports` cannot be resolved by bare name yet is installed.
689
- const resolve =
690
- resolveSeam ?? createRequire(path.join(root, 'package.json')).resolve;
691
- for (const dep of required) {
692
- if (!isResolvable(dep, resolve)) missing.push(dep);
693
- }
694
-
695
- if (missing.length === 0) return allPresentVerdict(parserMajorError);
696
- return {
697
- ok: false,
698
- detail: `missing: ${missing.join(', ')}`,
699
- remedy:
700
- 'The framework runtime deps are not resolvable from the consumer root, ' +
701
- 'where the materialized .agents/scripts/*.js run. npm and yarn hoist ' +
702
- "them automatically — run the installer if you haven't. pnpm's default " +
703
- 'isolated layout does NOT hoist transitive deps to the top level: add ' +
704
- '`shamefully-hoist=true` (or a scoped `public-hoist-pattern[]` for ' +
705
- 'each dep) to your `.npmrc` and reinstall. ' +
706
- `Missing: ${missing.join(', ')}`,
707
- };
708
- }
709
-
710
- // check: agents-materialized
711
-
712
- /**
713
- * Is `./.agents/instructions.md` present? Absent with the package installed
714
- * means postinstall was skipped (`--ignore-scripts`, sandboxed CI). Both
715
- * lookups anchor at the consumer's cwd.
716
- *
717
- * @param {{
718
- * cwd?: () => string,
719
- * existsSync?: (p: string) => boolean,
720
- * resolvePackage?: (fromDir: string) => string,
721
- * }} [opts]
722
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
723
- */
724
- function runAgentsMaterialized({ cwd, existsSync, resolvePackage } = {}) {
725
- const getCwd = cwd ?? (() => process.cwd());
726
- const exists = existsSync ?? ((p) => fs.existsSync(p));
727
- const root = getCwd();
728
- const instructionsPath = path.join(root, '.agents', 'instructions.md');
729
-
730
- if (exists(instructionsPath)) {
731
- return { ok: true, detail: '.agents/ materialized' };
732
- }
733
-
734
- const resolvePkg =
735
- resolvePackage ??
736
- ((fromDir) => {
737
- const requireFrom = createRequire(path.join(fromDir, 'noop.js'));
738
- return requireFrom.resolve('mandrel/package.json');
739
- });
740
-
741
- let packageInstalled = false;
742
- try {
743
- resolvePkg(root);
744
- packageInstalled = true;
745
- } catch {
746
- packageInstalled = false;
747
- }
748
-
749
- if (packageInstalled) {
750
- return {
751
- ok: false,
752
- detail: 'mandrel installed but ./.agents/ not materialized',
753
- remedy:
754
- 'Run `mandrel sync` to materialize the .agents/ payload (postinstall was skipped).',
755
- };
756
- }
757
-
758
- return {
759
- ok: false,
760
- detail: 'mandrel not installed and ./.agents/ absent',
761
- remedy:
762
- 'Install the framework (`npm install mandrel`), then run `mandrel sync`.',
763
- };
764
- }
765
-
766
- // check: agents-drift
767
-
768
- /**
769
- * A size mismatch proves drift without reading contents; equal sizes fall
770
- * through to a byte compare. `statSync` is optional on the seam.
771
- *
772
- * @param {string} src - absolute path to the package-payload file
773
- * @param {string} dest - absolute path to the materialized file
774
- * @param {{ readFileSync: Function, statSync?: Function }} fsImpl
775
- * @returns {boolean} `true` when the files differ
776
- */
777
- function payloadFileDrifted(src, dest, fsImpl) {
778
- if (
779
- typeof fsImpl.statSync === 'function' &&
780
- fsImpl.statSync(src).size !== fsImpl.statSync(dest).size
781
- ) {
782
- return true;
783
- }
784
- return !fsImpl.readFileSync(src).equals(fsImpl.readFileSync(dest));
785
- }
786
-
787
- /**
788
- * Compare materialized `./.agents/` bytes to the installed package payload
789
- * (excluding `.agents/local/`) and report the first missing or drifted file.
790
- * Only paths and counts are reported, never contents.
791
- *
792
- * @param {{
793
- * cwd?: () => string,
794
- * fsImpl?: { existsSync: (p: string) => boolean, readdirSync: Function, readFileSync: Function, statSync?: Function },
795
- * resolvePackageRoot?: (fromDir: string) => string,
796
- * }} [opts]
797
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
798
- */
799
- export function runAgentsDrift({ cwd, fsImpl = fs, resolvePackageRoot } = {}) {
800
- const getCwd = cwd ?? (() => process.cwd());
801
- const resolveRoot = resolvePackageRoot ?? defaultResolvePackageRoot;
802
- const projectRoot = getCwd();
803
-
804
- let packageRoot;
805
- try {
806
- packageRoot = resolveRoot(projectRoot);
807
- } catch {
808
- // agents-materialized owns the "not installed" remedy.
809
- return {
810
- ok: true,
811
- detail: 'mandrel not installed — drift skipped',
812
- };
813
- }
814
-
815
- const sourceRoot = path.join(packageRoot, '.agents');
816
- if (!fsImpl.existsSync(sourceRoot)) {
817
- return {
818
- ok: true,
819
- detail: 'mandrel ships no .agents/ payload — drift skipped',
820
- };
821
- }
822
-
823
- const destRoot = path.join(projectRoot, '.agents');
824
- if (!fsImpl.existsSync(destRoot)) {
825
- return { ok: true, detail: './.agents/ not materialized — drift skipped' };
826
- }
827
-
828
- const files = listPayloadFiles(sourceRoot, fsImpl);
829
- let comparedCount = 0;
830
- let missingCount = 0;
831
-
832
- for (const rel of files) {
833
- const src = path.join(sourceRoot, rel);
834
- const dest = path.join(destRoot, rel);
835
- const relLabel = path.join('.agents', rel);
836
-
837
- if (!fsImpl.existsSync(dest)) {
838
- missingCount += 1;
839
- return {
840
- ok: false,
841
- detail: `${relLabel} is missing from ./.agents/ (${missingCount} of ${files.length} payload files checked so far)`,
842
- remedy:
843
- 'Run `mandrel sync` to restore the materialized .agents/ payload.',
844
- };
845
- }
846
-
847
- comparedCount += 1;
848
- if (payloadFileDrifted(src, dest, fsImpl)) {
849
- return {
850
- ok: false,
851
- detail: `${relLabel} differs from the installed package payload`,
852
- remedy:
853
- 'Run `mandrel sync` to overwrite local edits, or move intentional changes into the `.agents/local/` zone.',
854
- };
855
- }
856
- }
857
-
858
- return {
859
- ok: true,
860
- detail: `${comparedCount} materialized file(s) match the package payload`,
861
- };
862
- }
863
-
864
- // check: pin-current
865
-
866
- /**
867
- * Fatal: does the installed `mandrel` satisfy the consumer's declared range?
868
- * Distinct from `agents-drift` (file contents) and `version-current` (newer
869
- * published). Graded by range satisfaction, not identity, because `^2.1.0` +
870
- * 2.4.0 after `npm update` is the normal steady state:
871
- * - satisfies and equals the base → pass;
872
- * - satisfies but newer than the base → pass, advisory in `detail`;
873
- * - behind the base → fail (distinct message);
874
- * - otherwise outside the range → fail.
875
- * No resolvable semver pin (absent, `workspace:`, `git+`, `latest`, …) skips.
876
- *
877
- * @param {{
878
- * cwd?: () => string,
879
- * fsImpl?: typeof fs,
880
- * resolvePackageRoot?: (fromDir: string) => string,
881
- * }} [opts]
882
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
883
- */
884
- export function runPinCurrent({ cwd, fsImpl = fs, resolvePackageRoot } = {}) {
885
- const getCwd = cwd ?? (() => process.cwd());
886
- const resolveRoot = resolvePackageRoot ?? defaultResolvePackageRoot;
887
- const projectRoot = getCwd();
888
-
889
- const spec = resolveConsumerPinSpec(projectRoot, fsImpl);
890
- if (!spec) {
891
- return {
892
- ok: true,
893
- detail: 'no resolvable mandrel dependency pin — skipped',
894
- };
895
- }
896
-
897
- let installedRoot;
898
- try {
899
- installedRoot = resolveRoot(projectRoot);
900
- } catch {
901
- return {
902
- ok: true,
903
- detail: 'mandrel not installed — pin check skipped',
904
- };
905
- }
906
-
907
- let installed;
908
- try {
909
- const parsed = JSON.parse(
910
- fsImpl.readFileSync(path.join(installedRoot, 'package.json'), 'utf8'),
911
- );
912
- installed = String(parsed.version);
913
- } catch {
914
- return {
915
- ok: true,
916
- detail: 'installed version unreadable — pin check skipped',
917
- };
918
- }
919
-
920
- const declared = `${spec.operator}${spec.version}`;
921
-
922
- if (compareSemver(installed, spec.version) < 0) {
923
- return {
924
- ok: false,
925
- detail: `package.json pins ${declared} but an older v${installed} is installed`,
926
- remedy:
927
- 'Run `npm install` to install a version satisfying the package.json pin.',
928
- };
929
- }
930
-
931
- if (!satisfiesPinSpec(installed, spec)) {
932
- return {
933
- ok: false,
934
- detail: `package.json pins ${declared} but v${installed} is installed — outside the declared range`,
935
- remedy:
936
- 'Run `mandrel update` to reconcile the package.json pin with the installed version.',
937
- };
938
- }
939
-
940
- if (compareSemver(installed, spec.version) > 0) {
941
- // The doctor prints only `detail` for a pass, so the advisory rides there.
942
- return {
943
- ok: true,
944
- detail: `v${installed} satisfies the ${declared} pin but is newer than it — run \`mandrel update\` to re-pin (advisory)`,
945
- };
946
- }
947
-
948
- return {
949
- ok: true,
950
- detail: `pin ${declared} matches the installed version`,
951
- };
952
- }
953
-
954
- // check: version-current
955
-
956
- /**
957
- * @param {typeof fs} fsImpl
958
- * @returns {string}
959
- */
960
- function defaultInstalledVersion(fsImpl) {
961
- const here = path.dirname(fileURLToPath(import.meta.url));
962
- const manifestPath = path.resolve(here, '..', '..', 'package.json');
963
- const parsed = JSON.parse(fsImpl.readFileSync(manifestPath, 'utf8'));
964
- return String(parsed.version);
965
- }
966
-
967
- /** Mirrors `version-check.js#DEFAULT_CACHE_FILENAME`. */
968
- const DEFAULT_VERSION_CACHE_FILENAME = 'version-check.json';
969
-
970
- /**
971
- * Anchored at the consumer root so the cache survives reinstalls that
972
- * replace `node_modules/`.
973
- *
974
- * @returns {string}
975
- */
976
- function defaultVersionCachePath() {
977
- return path.join(process.cwd(), 'temp', DEFAULT_VERSION_CACHE_FILENAME);
978
- }
979
-
980
- /**
981
- * Cache-only stale-version advisory: reads the freshness cache and never hits
982
- * the network. Always `ok: true`, so it can never fail doctor or CI.
983
- *
984
- * @param {{
985
- * cachePath?: string,
986
- * installedVersion?: string,
987
- * fsImpl?: typeof fs,
988
- * }} [opts]
989
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
990
- */
991
- function runVersionCurrent({ cachePath, installedVersion, fsImpl = fs } = {}) {
992
- const resolvedPath = cachePath ?? defaultVersionCachePath();
993
-
994
- let current = installedVersion;
995
- if (!current) {
996
- try {
997
- current = defaultInstalledVersion(fsImpl);
998
- } catch {
999
- return {
1000
- ok: true,
1001
- detail: 'installed version unknown — advisory skipped',
1002
- };
1003
- }
1004
- }
1005
-
1006
- const cached = readCache({ cachePath: resolvedPath, fs: fsImpl });
1007
- if (!cached) {
1008
- return {
1009
- ok: true,
1010
- detail: `v${current} (no cached freshness check yet)`,
1011
- };
1012
- }
1013
-
1014
- if (compareSemver(cached.latestVersion, current) > 0) {
1015
- return {
1016
- ok: true,
1017
- detail: `a newer version is available: v${current} → v${cached.latestVersion} (advisory)`,
1018
- remedy: 'Run `mandrel update` to upgrade to the latest version.',
1019
- };
1020
- }
1021
-
1022
- return { ok: true, detail: `v${current} is up to date` };
1023
- }
1024
-
1025
- // check: merge-driver
1026
-
1027
- /**
1028
- * Is this clone's `baselines/*.json` merge driver registered? `.gitattributes`
1029
- * ships with the repo but the driver command is per-clone `git config`, and a
1030
- * missing one silently falls back to a text merge. Skipped when
1031
- * `.gitattributes` does not declare the driver.
1032
- *
1033
- * @param {{cwd?: () => string, fsImpl?: typeof fs, runner?: typeof spawn}} [opts]
1034
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
1035
- */
1036
- export function runMergeDriver({ cwd, fsImpl = fs, runner = spawn } = {}) {
1037
- const projectRoot = (cwd ?? (() => process.cwd()))();
1038
- // Git runs from projectRoot: the config key is per-clone.
1039
- const { declared, command } = probeBaselineMergeDriver({
1040
- projectRoot,
1041
- fsImpl,
1042
- runGit: (args) => runner('git', args, { cwd: projectRoot }),
1043
- });
1044
- if (!declared) {
1045
- return {
1046
- ok: true,
1047
- detail:
1048
- 'skipped — .gitattributes does not route baselines/*.json through the mandrel merge driver',
1049
- };
1050
- }
1051
- if (command === '') {
1052
- return {
1053
- ok: false,
1054
- detail: `${BASELINE_MERGE_DRIVER_CONFIG_KEY} is unset — baselines/*.json will fall back to git's text merge, which conflicts on adjacent rows and can splice rows neither branch scored`,
1055
- remedy: BASELINE_MERGE_DRIVER_REMEDY,
1056
- };
1057
- }
1058
- return probeConfiguredDriver(command, runner, projectRoot);
1059
- }
1060
-
1061
- /**
1062
- * Execute the configured driver with `--help` (the real invocation mutates
1063
- * `%A`): a set-but-broken command — typically an absolute node path moved by
1064
- * an nvm/volta bump — fails as silently as an unset key. The command is
1065
- * tokenised, never shell-run, since a config value must not become arbitrary
1066
- * command execution. Runs from projectRoot, where git invokes drivers.
1067
- *
1068
- * @param {string} command
1069
- * @param {typeof spawn} runner
1070
- * @param {string} projectRoot
1071
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
1072
- */
1073
- function probeConfiguredDriver(command, runner, projectRoot) {
1074
- const parsed = parseBaselineMergeDriverCommand(command);
1075
- if (!parsed) {
1076
- return {
1077
- ok: false,
1078
- detail: `${BASELINE_MERGE_DRIVER_CONFIG_KEY} is set to ${JSON.stringify(command)}, which has no runnable command in it`,
1079
- remedy: BASELINE_MERGE_DRIVER_REMEDY,
1080
- };
1081
- }
1082
- const probe = runner(parsed.file, [...parsed.args, '--help'], {
1083
- cwd: projectRoot,
1084
- });
1085
- if (probe.status === 0) return { ok: true, detail: command };
1086
- const why = probe.error?.message ?? `exit ${probe.status}`;
1087
- return {
1088
- ok: false,
1089
- detail: `${BASELINE_MERGE_DRIVER_CONFIG_KEY} is set to ${JSON.stringify(command)} but running it failed (${why}) — git would fall back to text-merging baselines/*.json exactly as if the key were unset`,
1090
- remedy: BASELINE_MERGE_DRIVER_REMEDY,
1091
- };
1092
- }
1093
-
1094
- // check: test-credit-path
1095
-
1096
- /** The runner whose green full run deposits the close `test` credit itself. */
1097
- const MANDREL_TEST_RUNNER = 'run-tests.js';
1098
-
1099
- /** The close `test` gate's command when `project.commands.test` is unset. */
1100
- const DEFAULT_TEST_COMMAND = 'npm test';
1101
-
1102
- /**
1103
- * The deposit command that works on any runner, wrapping `command`.
1104
- *
1105
- * @param {string} command
1106
- * @returns {string}
1107
- */
1108
- function testCreditDepositCommand(command) {
1109
- return `node .agents/scripts/evidence-gate.js --standalone --scope-id <storyId> --gate test --worktree <workCwd> -- ${command}`;
1110
- }
1111
-
1112
- /** The capture close's `coverage-capture` gate finds fresh, per digest § 5. */
1113
- const COVERAGE_CAPTURE_COMMAND =
1114
- 'node .agents/scripts/coverage-capture.js --cwd <workCwd>';
1115
-
1116
- /** The worker's one tail command; it runs whichever depositor applies. */
1117
- const STORY_HANDOFF_COMMAND =
1118
- 'node .agents/scripts/story-handoff.js --story <storyId> --cwd <workCwd>';
1119
-
1120
- /**
1121
- * @param {string} command
1122
- * @returns {string}
1123
- */
1124
- function testCreditRemedy(command) {
1125
- return `run the suite through the depositor instead of bare \`${command}\`: ${testCreditDepositCommand(command)}`;
1126
- }
1127
-
1128
- const PRE_PUSH_REMEDY =
1129
- 'wrap each hook gate in `node .agents/scripts/evidence-gate.js --standalone --scope-id <storyId> --gate <typecheck|lint> -- <command>` so the push deposits the credit close reads';
1130
-
1131
- /** A hook line that runs a typecheck or lint gate. */
1132
- const HOOK_GATE_RE = /\b(typecheck|tsc|lint|eslint|biome)\b/;
1133
-
1134
- /**
1135
- * Consulted only while `project.commands.test` is unset — then the close
1136
- * gate's argv is `npm test`, which runs `scripts.test`.
1137
- *
1138
- * @param {string} projectRoot
1139
- * @param {typeof fs.readFileSync} readFileImpl
1140
- * @returns {Record<string, string>} The `scripts` map, empty when unreadable.
1141
- */
1142
- function readProjectScripts(projectRoot, readFileImpl) {
1143
- try {
1144
- const raw = readFileImpl(path.join(projectRoot, 'package.json'), 'utf8');
1145
- const scripts = JSON.parse(raw)?.scripts;
1146
- return scripts && typeof scripts === 'object' ? scripts : {};
1147
- } catch {
1148
- return {};
1149
- }
1150
- }
1151
-
1152
- /**
1153
- * @param {Record<string, string>} scripts
1154
- * @param {string} name
1155
- * @returns {string|null} The trimmed script, or null when there is none.
1156
- */
1157
- function scriptNamed(scripts, name) {
1158
- const script = scripts[name];
1159
- return typeof script === 'string' && script.trim().length > 0
1160
- ? script.trim()
1161
- : null;
1162
- }
1163
-
1164
- /**
1165
- * `delivery.quality.gates.crap.enabled` from `.agentrc.json` overlaid by
1166
- * `.agentrc.local.json`, defaulting on — the predicate close registers
1167
- * `coverage-capture` on. Read without `resolveConfig()` (built-ins only).
1168
- *
1169
- * @param {string} projectRoot
1170
- * @param {typeof fs.readFileSync} readFileImpl
1171
- * @returns {boolean}
1172
- */
1173
- function isCrapEnabled(projectRoot, readFileImpl) {
1174
- let enabled = true;
1175
- for (const file of ['.agentrc.json', '.agentrc.local.json']) {
1176
- const value = readJsonSafe(path.join(projectRoot, file), {
1177
- readFileSync: readFileImpl,
1178
- })?.delivery?.quality?.gates?.crap?.enabled;
1179
- if (typeof value === 'boolean') enabled = value;
1180
- }
1181
- return enabled;
1182
- }
1183
-
1184
- /**
1185
- * `project.commands.test` from `.agentrc.json` overlaid by
1186
- * `.agentrc.local.json` — the command close's `test` gate spawns. Read without
1187
- * `resolveConfig()` (built-ins only), like {@link isCrapEnabled}.
1188
- *
1189
- * @param {string} projectRoot
1190
- * @param {typeof fs.readFileSync} readFileImpl
1191
- * @returns {string|null} The configured command, or null when unset/default.
1192
- */
1193
- function configuredTestCommand(projectRoot, readFileImpl) {
1194
- let command = null;
1195
- for (const file of ['.agentrc.json', '.agentrc.local.json']) {
1196
- const value = readJsonSafe(path.join(projectRoot, file), {
1197
- readFileSync: readFileImpl,
1198
- })?.project?.commands?.test;
1199
- if (typeof value === 'string' && value.trim().length > 0) {
1200
- command = value.trim();
1201
- }
1202
- }
1203
- return command === DEFAULT_TEST_COMMAND ? null : command;
1204
- }
1205
-
1206
- /**
1207
- * A configured `project.commands.test` is what close spawns, so the analysis
1208
- * is of that command, never of `scripts.test`.
1209
- *
1210
- * @param {string} command
1211
- * @returns {{ detail: string, remedy?: string }}
1212
- */
1213
- function describeConfiguredTestCommand(command) {
1214
- const lead = `\`project.commands.test\` sets close's \`test\` gate to \`${command}\``;
1215
- if (command.includes(MANDREL_TEST_RUNNER)) {
1216
- return {
1217
- detail: `${lead}, which reaches mandrel's runner — a green full run on a story branch deposits the close \`test\` credit itself`,
1218
- };
1219
- }
1220
- const remedy = testCreditRemedy(command);
1221
- return {
1222
- detail: `${lead}, which deposits no close \`test\` credit by itself — ${remedy}`,
1223
- remedy,
1224
- };
1225
- }
1226
-
1227
- /**
1228
- * Which depositor digest § 5 selects, stated with its exact command.
1229
- *
1230
- * @param {{ scripts: Record<string, string>, crapEnabled: boolean, testCommand: string|null }} probe
1231
- * @returns {{ detail: string, remedy?: string }}
1232
- */
1233
- function describeCreditedRun({ scripts, crapEnabled, testCommand }) {
1234
- if (crapEnabled && scriptNamed(scripts, 'test:coverage') !== null) {
1235
- return {
1236
- detail: `the CRAP gate is enabled and \`test:coverage\` exists, so close registers \`coverage-capture\` and the credited run is the coverage capture: \`${COVERAGE_CAPTURE_COMMAND}\` — its fresh stamp lets close's capture skip the suite`,
1237
- };
1238
- }
1239
- return testCommand !== null
1240
- ? describeConfiguredTestCommand(testCommand)
1241
- : describeNpmTestScript(scripts);
1242
- }
1243
-
1244
- /**
1245
- * With `project.commands.test` unset close spawns `npm test`, so the analysis
1246
- * is of `scripts.test`.
1247
- *
1248
- * @param {Record<string, string>} scripts
1249
- * @returns {{ detail: string, remedy?: string }}
1250
- */
1251
- function describeNpmTestScript(scripts) {
1252
- const remedy = testCreditRemedy(DEFAULT_TEST_COMMAND);
1253
- const script = scriptNamed(scripts, 'test');
1254
- if (script === null) {
1255
- return {
1256
- detail: `no \`test\` script in package.json — close still spawns \`npm test\`, so ${remedy}`,
1257
- remedy,
1258
- };
1259
- }
1260
- if (script.includes(MANDREL_TEST_RUNNER)) {
1261
- return {
1262
- detail: `\`npm test\` → \`${script}\` reaches mandrel's runner — a green full run on a story branch deposits the close \`test\` credit itself`,
1263
- };
1264
- }
1265
- return {
1266
- detail: `\`npm test\` → \`${script}\` is this project's own runner and never reaches \`${MANDREL_TEST_RUNNER}\`, so it deposits no close \`test\` credit and prints nothing — ${remedy}`,
1267
- remedy,
1268
- };
1269
- }
1270
-
1271
- /**
1272
- * Does the pre-push hook deposit gate evidence? Read, never executed.
1273
- *
1274
- * @param {string} projectRoot
1275
- * @param {typeof fs.readFileSync} readFileImpl
1276
- * @returns {{ detail: string, remedy?: string }}
1277
- */
1278
- function describePrePushHook(projectRoot, readFileImpl) {
1279
- let hook = null;
1280
- let hookPath = null;
1281
- for (const rel of [
1282
- path.join('.husky', 'pre-push'),
1283
- path.join('.git', 'hooks', 'pre-push'),
1284
- ]) {
1285
- try {
1286
- hook = readFileImpl(path.join(projectRoot, rel), 'utf8');
1287
- hookPath = rel.split(path.sep).join('/');
1288
- break;
1289
- } catch {
1290
- // Absent here — try the next hooks location.
1291
- }
1292
- }
1293
- if (hook === null) {
1294
- return { detail: 'no pre-push hook found, so nothing runs a gate there' };
1295
- }
1296
- if (hook.includes('evidence-gate.js')) {
1297
- return {
1298
- detail: `\`${hookPath}\` routes its gates through \`evidence-gate.js\`, so the push deposits evidence close can credit`,
1299
- };
1300
- }
1301
- if (HOOK_GATE_RE.test(hook)) {
1302
- return {
1303
- detail: `\`${hookPath}\` runs typecheck or lint without \`evidence-gate.js\`, so it deposits nothing and close re-runs them — ${PRE_PUSH_REMEDY}`,
1304
- remedy: PRE_PUSH_REMEDY,
1305
- };
1306
- }
1307
- return {
1308
- detail: `\`${hookPath}\` runs no typecheck or lint gate, so close has nothing of it to re-run`,
1309
- };
1310
- }
1311
-
1312
- /**
1313
- * Which credited run does digest § 5 select for this project, and does its
1314
- * pre-push hook deposit the gate evidence close reads? Always `ok: true` —
1315
- * every shape is supported, some just cost close a re-run — so any remedy
1316
- * rides a passing verdict and is repeated in `detail`. Detected from files
1317
- * only; nothing is executed.
1318
- *
1319
- * @param {{ projectRoot?: string, readFile?: typeof fs.readFileSync }} [opts]
1320
- * @returns {{ ok: boolean, detail: string, remedy?: string }}
1321
- */
1322
- function runTestCreditPath({ projectRoot, readFile = fs.readFileSync } = {}) {
1323
- const root = projectRoot ?? process.cwd();
1324
- const parts = [
1325
- {
1326
- detail: `the worker's \`${STORY_HANDOFF_COMMAND}\` runs the credited run close reads`,
1327
- },
1328
- describeCreditedRun({
1329
- scripts: readProjectScripts(root, readFile),
1330
- crapEnabled: isCrapEnabled(root, readFile),
1331
- testCommand: configuredTestCommand(root, readFile),
1332
- }),
1333
- describePrePushHook(root, readFile),
1334
- ];
1335
- const remedies = parts.map((p) => p.remedy).filter(Boolean);
1336
- return {
1337
- ok: true,
1338
- detail: parts.map((p) => p.detail).join('; '),
1339
- ...(remedies.length > 0 ? { remedy: remedies.join('; ') } : {}),
1340
- };
1341
- }
33
+ runGhAuth,
34
+ runGhAvailable,
35
+ runGitAvailable,
36
+ runGithubToken,
37
+ runNodeVersion,
38
+ } from './doctor-checks/toolchain.js';
39
+ import { runVersionCurrent } from './doctor-checks/version-current.js';
40
+
41
+ export {
42
+ CODEX_PROJECT_DOC_MAX_BYTES,
43
+ readProjectDocMaxBytes,
44
+ runAgentsDrift,
45
+ runCodexAgentsInSync,
46
+ runCodexInstructions,
47
+ runCodexSkillsInSync,
48
+ runMergeDriver,
49
+ runPinCurrent,
50
+ };
1342
51
 
1343
52
  /** `advisory: true` marks a check whose `run()` never fails. */
1344
53
  export const registry = [
@@ -1358,6 +67,7 @@ export const registry = [
1358
67
  name: 'github-token',
1359
68
  run: (opts) => runGithubToken(opts),
1360
69
  },
70
+ // Presupposes gh-available: an absent gh binary reports there, not here.
1361
71
  {
1362
72
  name: 'gh-auth',
1363
73
  run: (opts) => runGhAuth(opts),