mandrel 2.87.0 → 2.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +12 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +11 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/deliver-run.js +11 -0
  17. package/.agents/scripts/diagnose-friction.js +3 -3
  18. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  19. package/.agents/scripts/lib/baselines/crap-updater-cli.js +36 -26
  20. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  21. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  22. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  23. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  24. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  25. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  26. package/.agents/scripts/lib/baselines/writer.js +5 -1
  27. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  28. package/.agents/scripts/lib/child-exec.js +14 -1
  29. package/.agents/scripts/lib/child-stream.js +122 -0
  30. package/.agents/scripts/lib/clean-temp.js +19 -13
  31. package/.agents/scripts/lib/cli-args.js +49 -0
  32. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  33. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  34. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  35. package/.agents/scripts/lib/config/github.js +2 -0
  36. package/.agents/scripts/lib/config/paths.js +14 -3
  37. package/.agents/scripts/lib/config-resolver.js +78 -64
  38. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  39. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  40. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  41. package/.agents/scripts/lib/coverage-capture.js +16 -1
  42. package/.agents/scripts/lib/crap-utils.js +59 -47
  43. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  44. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  45. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  46. package/.agents/scripts/lib/gh-exec.js +45 -2
  47. package/.agents/scripts/lib/gh-transport.js +27 -0
  48. package/.agents/scripts/lib/git-utils.js +16 -9
  49. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  50. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  51. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  52. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  53. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  54. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  55. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  56. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  57. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  58. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  59. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  60. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  61. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  64. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  65. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  66. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  67. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  68. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  69. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  71. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  72. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  73. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  74. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  75. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  76. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  77. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  78. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  79. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  80. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  81. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  82. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  83. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  84. package/.agents/scripts/lib/suite-admission.js +3 -11
  85. package/.agents/scripts/lib/temp-retention.js +25 -11
  86. package/.agents/scripts/lib/test-run-credit.js +2 -5
  87. package/.agents/scripts/lib/transpile.js +193 -31
  88. package/.agents/scripts/lib/util/paths.js +31 -0
  89. package/.agents/scripts/lib/util/sleep.js +15 -0
  90. package/.agents/scripts/lib/validation-evidence.js +29 -3
  91. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  92. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  93. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  94. package/.agents/scripts/lib/workflow-closure.js +1 -8
  95. package/.agents/scripts/notify.js +83 -90
  96. package/.agents/scripts/plan-context.js +8 -4
  97. package/.agents/scripts/providers/github/auth.js +14 -30
  98. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  99. package/.agents/scripts/providers/github/compose.js +1 -0
  100. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  101. package/.agents/scripts/providers/github/identity.js +158 -0
  102. package/.agents/scripts/providers/github/issues.js +2 -2
  103. package/.agents/scripts/providers/github/mappers.js +16 -19
  104. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  105. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  106. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  107. package/.agents/scripts/providers/github.js +10 -2
  108. package/.agents/scripts/quality-preview.js +6 -19
  109. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  110. package/.agents/scripts/single-story-init.js +0 -1
  111. package/.agents/scripts/stories-wave-tick.js +60 -46
  112. package/.agents/scripts/story-handoff.js +2 -23
  113. package/.agents/scripts/story-review-compute.js +3 -22
  114. package/.agents/scripts/sync-claude-agents.js +1 -12
  115. package/.agents/scripts/sync-claude-commands.js +1 -12
  116. package/.agents/scripts/update-crap-baseline.js +10 -19
  117. package/.agents/scripts/update-ticket-state.js +44 -45
  118. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  119. package/.agents/workflows/audit-accessibility.md +1 -1
  120. package/.agents/workflows/audit-adrs.md +1 -1
  121. package/.agents/workflows/audit-architecture.md +1 -1
  122. package/.agents/workflows/audit-baselines.md +2 -2
  123. package/.agents/workflows/audit-clean-code.md +1 -1
  124. package/.agents/workflows/audit-data-model.md +1 -1
  125. package/.agents/workflows/audit-dependencies.md +1 -1
  126. package/.agents/workflows/audit-devops.md +1 -1
  127. package/.agents/workflows/audit-documentation.md +1 -1
  128. package/.agents/workflows/audit-exceptions.md +2 -2
  129. package/.agents/workflows/audit-mobile.md +1 -1
  130. package/.agents/workflows/audit-navigability.md +1 -1
  131. package/.agents/workflows/audit-performance.md +1 -1
  132. package/.agents/workflows/audit-privacy.md +1 -1
  133. package/.agents/workflows/audit-quality.md +1 -1
  134. package/.agents/workflows/audit-security.md +1 -1
  135. package/.agents/workflows/audit-seo.md +1 -1
  136. package/.agents/workflows/audit-sre.md +1 -1
  137. package/.agents/workflows/audit-to-stories.md +9 -7
  138. package/.agents/workflows/audit-ux-ui.md +1 -1
  139. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  140. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  141. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  142. package/.agents/workflows/mandrel-deliver.md +3 -1
  143. package/README.md +6 -3
  144. package/docs/CHANGELOG.md +29 -0
  145. package/lib/cli/doctor-checks/codex.js +240 -0
  146. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  147. package/lib/cli/doctor-checks/payload.js +201 -0
  148. package/lib/cli/doctor-checks/read-json.js +16 -0
  149. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  150. package/lib/cli/doctor-checks/spawn.js +18 -0
  151. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  152. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  153. package/lib/cli/doctor-checks/toolchain.js +137 -0
  154. package/lib/cli/doctor-checks/version-current.js +82 -0
  155. package/lib/cli/registry.js +40 -1330
  156. package/package.json +1 -1
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,35 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.88.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.87.0...mandrel-v2.88.0) (2026-10-15)
19
+
20
+
21
+ ### Added
22
+
23
+ * finalize a merged Story's labels and lease from the beat and the boot sweep ([#5705](https://github.com/dsj1984/mandrel/issues/5705)) ([#5710](https://github.com/dsj1984/mandrel/issues/5710)) ([516f675](https://github.com/dsj1984/mandrel/commit/516f6755be4ca16845d47b0ba346a9b3fa7a5a98))
24
+ * persist a project-local GitHub CLI config dir, verify the operator identity, and stop reading transport failures as expired auth ([#5693](https://github.com/dsj1984/mandrel/issues/5693)) ([#5712](https://github.com/dsj1984/mandrel/issues/5712)) ([2668ff4](https://github.com/dsj1984/mandrel/commit/2668ff4cce7231ac612d4d98e02794d2fb7fb941))
25
+ * resolve TypeScript from the scanned file's own package in the CRAP and maintainability scorers ([#5692](https://github.com/dsj1984/mandrel/issues/5692)) ([#5701](https://github.com/dsj1984/mandrel/issues/5701)) ([c7ac7eb](https://github.com/dsj1984/mandrel/commit/c7ac7eb5b03ab6a36b1e0c3fb62915ab803f9c04))
26
+ * stream the handoff credited-run evidence log while the suite runs ([#5694](https://github.com/dsj1984/mandrel/issues/5694)) ([#5699](https://github.com/dsj1984/mandrel/issues/5699)) ([8931932](https://github.com/dsj1984/mandrel/commit/89319325ebeb67babcf845c29bef98807eb163f8))
27
+ * write audit lens reports to a dedicated temp/audits/audit-results/ folder ([#5679](https://github.com/dsj1984/mandrel/issues/5679)) ([#5680](https://github.com/dsj1984/mandrel/issues/5680)) ([9f20249](https://github.com/dsj1984/mandrel/commit/9f202494a51e69b83accbdfba8c0f44ec95369cb))
28
+
29
+
30
+ ### Fixed
31
+
32
+ * clear the duplication drift and make the scoped refresh rewrite clone-partner rows ([#5702](https://github.com/dsj1984/mandrel/issues/5702)) ([#5711](https://github.com/dsj1984/mandrel/issues/5711)) ([76cff34](https://github.com/dsj1984/mandrel/commit/76cff34be2729c57d2e40ec8d291355a9137c906))
33
+ * close the suite-admission and sweep-lock interleaving races and prove the admission invariant ([#5684](https://github.com/dsj1984/mandrel/issues/5684)) ([#5700](https://github.com/dsj1984/mandrel/issues/5700)) ([2bf193d](https://github.com/dsj1984/mandrel/commit/2bf193d4f8358f3d24310a924fc34c0d416f0a2c))
34
+ * drive the untested destructive and state-mutation seams: worktree ops, flip-failed emitter, init, ticket-state CLI ([#5685](https://github.com/dsj1984/mandrel/issues/5685)) ([#5698](https://github.com/dsj1984/mandrel/issues/5698)) ([297ed1c](https://github.com/dsj1984/mandrel/commit/297ed1c8205de307e8acdb4dd8a66fcb99fe8db4))
35
+ * fail the comment-ratio gate only on a change whose own diff is comment-heavy, so an unrelated merge cannot tip it ([#5713](https://github.com/dsj1984/mandrel/issues/5713)) ([#5714](https://github.com/dsj1984/mandrel/issues/5714)) ([5bc18a3](https://github.com/dsj1984/mandrel/commit/5bc18a34d26a446ff0f0f1a5aff3663aea51a3c1))
36
+ * give a re-close after a block a fresh merge budget and re-take its lease ([#5706](https://github.com/dsj1984/mandrel/issues/5706)) ([#5708](https://github.com/dsj1984/mandrel/issues/5708)) ([8c3be8b](https://github.com/dsj1984/mandrel/commit/8c3be8b0bc7c9db55ebebe8455f5a3ff7925a43a))
37
+ * make baseline and gate-credit writes fail closed: scoped refresh, writeback restore, atomic evidence, honest mutation default ([#5683](https://github.com/dsj1984/mandrel/issues/5683)) ([#5697](https://github.com/dsj1984/mandrel/issues/5697)) ([6a65a02](https://github.com/dsj1984/mandrel/commit/6a65a0226e474d3fe9e96bca6b0648895360ef94))
38
+ * make the story-body parser skip whole-line HTML comment markers (audit-… ([#5690](https://github.com/dsj1984/mandrel/issues/5690)) ([#5691](https://github.com/dsj1984/mandrel/issues/5691)) ([1419e05](https://github.com/dsj1984/mandrel/commit/1419e05fef8a289f207e7bf9cbbe902e600e6688))
39
+ * split the close runner and the doctor registry along their seams, and fix the doctor's comment-matching hook detector ([#5688](https://github.com/dsj1984/mandrel/issues/5688)) ([#5703](https://github.com/dsj1984/mandrel/issues/5703)) ([cbca841](https://github.com/dsj1984/mandrel/commit/cbca841a5a8f62e35597bf78b13675161f2cd22f))
40
+ * stop CLIs truncating piped output at 64 KiB and move hand-rolled argv parsing onto parseArgs ([#5686](https://github.com/dsj1984/mandrel/issues/5686)) ([#5696](https://github.com/dsj1984/mandrel/issues/5696)) ([02d7684](https://github.com/dsj1984/mandrel/commit/02d76845f3f4fe65698ca2e9549b5e8fbfc3a1ab))
41
+
42
+
43
+ ### Changed
44
+
45
+ * collapse drifting duplicate helpers onto one owner each and fix the config-resolver cache key ([#5687](https://github.com/dsj1984/mandrel/issues/5687)) ([#5704](https://github.com/dsj1984/mandrel/issues/5704)) ([18bdfcc](https://github.com/dsj1984/mandrel/commit/18bdfccf8c31b064b0e25db28fb97fff6a4fd5a0))
46
+
18
47
  ## [2.87.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.86.0...mandrel-v2.87.0) (2026-10-14)
19
48
 
20
49
 
@@ -0,0 +1,240 @@
1
+ // lib/cli/doctor-checks/codex.js — Doctor checks: codex-skills-in-sync, codex-agents-in-sync, codex-instructions.
2
+
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {
7
+ SYSTEM_PROMPT_IMPORT,
8
+ SYSTEM_PROMPT_READ_DIRECTIVE,
9
+ } from '../../../.agents/scripts/lib/bootstrap/agents-md-fold.js';
10
+ import {
11
+ CODEX_AGENTS_DIR,
12
+ expectedCodexAgents,
13
+ listGeneratedCodexAgents,
14
+ } from '../../../.agents/scripts/lib/codex/agents-projection.js';
15
+ import {
16
+ CODEX_SKILLS_DIR,
17
+ expectedCodexSkills,
18
+ listGeneratedCodexSkills,
19
+ } from '../../../.agents/scripts/lib/codex/skills-projection.js';
20
+
21
+ // check: codex-skills-in-sync / codex-agents-in-sync
22
+
23
+ /**
24
+ * Compare a generated tree against what its projector would write now.
25
+ * `readEntry(name)` returns the on-disk text or null.
26
+ *
27
+ * @param {{
28
+ * expected: () => Map<string, string>,
29
+ * onDisk: string[],
30
+ * readEntry: (name: string) => string | null,
31
+ * noun: string,
32
+ * where: string,
33
+ * remedy: string,
34
+ * }} spec
35
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
36
+ */
37
+ function projectionParity({
38
+ expected,
39
+ onDisk,
40
+ readEntry,
41
+ noun,
42
+ where,
43
+ remedy,
44
+ }) {
45
+ let want;
46
+ try {
47
+ want = expected();
48
+ } catch (err) {
49
+ return { ok: false, detail: err.message, remedy };
50
+ }
51
+ const have = new Set(onDisk);
52
+ const missing = [...want.keys()].filter((n) => !have.has(n));
53
+ const stale = [...want.entries()].filter(
54
+ ([n, body]) => have.has(n) && readEntry(n) !== body,
55
+ );
56
+ const extra = onDisk.filter((n) => !want.has(n));
57
+ if (missing.length + stale.length + extra.length === 0) {
58
+ return { ok: true, detail: `${want.size} ${noun} up to date in ${where}` };
59
+ }
60
+ const parts = [];
61
+ if (missing.length > 0) parts.push(`${missing.length} not synced`);
62
+ if (stale.length + extra.length > 0) {
63
+ parts.push(`${stale.length + extra.length} stale`);
64
+ }
65
+ return { ok: false, detail: `${parts.join(', ')} in ${where}`, remedy };
66
+ }
67
+
68
+ /**
69
+ * @param {string} file
70
+ * @returns {string | null}
71
+ */
72
+ function readTextOrNull(file) {
73
+ try {
74
+ return fs.readFileSync(file, 'utf8');
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Parity of `.agents/skills/workflows/` against the workflow set — the Codex
82
+ * twin of `commands-in-sync`, byte-for-byte rather than by name.
83
+ *
84
+ * @param {{ projectRoot?: string, cwd?: () => string }} [opts]
85
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
86
+ */
87
+ export function runCodexSkillsInSync({ projectRoot, cwd } = {}) {
88
+ const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
89
+ const destDir = path.join(root, ...CODEX_SKILLS_DIR.split('/'));
90
+ return projectionParity({
91
+ expected: () => expectedCodexSkills({ projectRoot: root }),
92
+ onDisk: listGeneratedCodexSkills(destDir),
93
+ readEntry: (name) => readTextOrNull(path.join(destDir, name, 'SKILL.md')),
94
+ noun: 'Codex skills',
95
+ where: `${CODEX_SKILLS_DIR}/`,
96
+ remedy: `Run \`mandrel sync-commands\` to regenerate the Codex skills under \`${CODEX_SKILLS_DIR}/\`.`,
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Parity of `.codex/agents/mandrel-*.toml` against `.agents/agents/` — the
102
+ * Codex twin of `agents-in-sync`.
103
+ *
104
+ * @param {{ projectRoot?: string, cwd?: () => string }} [opts]
105
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
106
+ */
107
+ export function runCodexAgentsInSync({ projectRoot, cwd } = {}) {
108
+ const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
109
+ const destDir = path.join(root, ...CODEX_AGENTS_DIR.split('/'));
110
+ return projectionParity({
111
+ expected: () => expectedCodexAgents({ projectRoot: root }),
112
+ onDisk: listGeneratedCodexAgents(destDir),
113
+ readEntry: (name) => readTextOrNull(path.join(destDir, name)),
114
+ noun: 'Codex agents',
115
+ where: `${CODEX_AGENTS_DIR}/`,
116
+ remedy: `Run \`mandrel sync-agents\` to regenerate \`${CODEX_AGENTS_DIR}/mandrel-<role>.toml\`.`,
117
+ });
118
+ }
119
+
120
+ // check: codex-instructions
121
+
122
+ /** Codex's default `project_doc_max_bytes`. */
123
+ export const CODEX_PROJECT_DOC_MAX_BYTES = 32768;
124
+
125
+ /**
126
+ * A top-level `project_doc_max_bytes = <int>` line before any `[table]`
127
+ * header; anything else (absent file, nested key, non-integer) is null. No
128
+ * TOML dependency — this one key is all the check needs.
129
+ *
130
+ * @param {string | null} text
131
+ * @returns {number | null}
132
+ */
133
+ export function readProjectDocMaxBytes(text) {
134
+ if (typeof text !== 'string') return null;
135
+ for (const line of text.split(/\r?\n/)) {
136
+ if (/^\s*\[/.test(line)) return null;
137
+ const match = /^\s*project_doc_max_bytes\s*=\s*(\d+)\s*(?:#.*)?$/.exec(
138
+ line,
139
+ );
140
+ if (match) return Number(match[1]);
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * Effective limit and where it came from: project `.codex/config.toml`, then
147
+ * `$CODEX_HOME/config.toml` (default `~/.codex`), else the default.
148
+ *
149
+ * @param {string} root
150
+ * @param {NodeJS.ProcessEnv} env
151
+ * @param {string} homeDir
152
+ * @param {(file: string) => string | null} readText
153
+ * @returns {{ limit: number, source: string }}
154
+ */
155
+ function resolveProjectDocLimit(root, env, homeDir, readText) {
156
+ const codexHome = env.CODEX_HOME || path.join(homeDir, '.codex');
157
+ for (const [file, source] of [
158
+ [path.join(root, '.codex', 'config.toml'), '.codex/config.toml'],
159
+ [path.join(codexHome, 'config.toml'), '$CODEX_HOME/config.toml'],
160
+ ]) {
161
+ const limit = readProjectDocMaxBytes(readText(file));
162
+ if (limit !== null) return { limit, source };
163
+ }
164
+ return { limit: CODEX_PROJECT_DOC_MAX_BYTES, source: 'the Codex default' };
165
+ }
166
+
167
+ const HOIST_REMEDY =
168
+ 'Move the `## System Prompt` block to the top of the file, or run `mandrel update` (its 2.84.0 migration moves it).';
169
+
170
+ /**
171
+ * Does Codex load the Mandrel block? Sizes the root `AGENTS.override.md`, else
172
+ * `AGENTS.md`, against the effective `project_doc_max_bytes`. Fails when the
173
+ * block (import through read directive) does not end inside the limit, or
174
+ * carries no directive Codex can follow; an oversized file whose block still
175
+ * loads passes with an advisory. No entry doc at all skips, as
176
+ * `claude-code-version` does.
177
+ *
178
+ * @param {{
179
+ * projectRoot?: string,
180
+ * cwd?: () => string,
181
+ * env?: NodeJS.ProcessEnv,
182
+ * homeDir?: string,
183
+ * readText?: (file: string) => string | null,
184
+ * }} [opts]
185
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
186
+ */
187
+ export function runCodexInstructions({
188
+ projectRoot,
189
+ cwd,
190
+ env = process.env,
191
+ homeDir = os.homedir(),
192
+ readText = readTextOrNull,
193
+ } = {}) {
194
+ const root = projectRoot ?? (cwd ?? (() => process.cwd()))();
195
+ const { limit, source } = resolveProjectDocLimit(
196
+ root,
197
+ env,
198
+ homeDir,
199
+ readText,
200
+ );
201
+ const override = readText(path.join(root, 'AGENTS.override.md'));
202
+ const docName = override === null ? 'AGENTS.md' : 'AGENTS.override.md';
203
+ const text = override ?? readText(path.join(root, 'AGENTS.md'));
204
+ if (text === null) {
205
+ return { ok: true, detail: 'skipped: no AGENTS.md' };
206
+ }
207
+ const importAt = text.indexOf(SYSTEM_PROMPT_IMPORT);
208
+ const directiveAt = text.indexOf(SYSTEM_PROMPT_READ_DIRECTIVE);
209
+ if (importAt === -1 || directiveAt === -1) {
210
+ return {
211
+ ok: false,
212
+ detail: `${docName} carries no Mandrel read directive for hosts without @-imports — Codex would not load .agents/instructions.md`,
213
+ remedy: HOIST_REMEDY,
214
+ };
215
+ }
216
+ const bytes = (s) => Buffer.byteLength(s, 'utf8');
217
+ const start = bytes(text.slice(0, Math.min(importAt, directiveAt)));
218
+ const end = bytes(
219
+ text.slice(0, directiveAt + SYSTEM_PROMPT_READ_DIRECTIVE.length),
220
+ );
221
+ const total = bytes(text);
222
+ const limitLabel = `project_doc_max_bytes ${limit} (${source})`;
223
+ if (end > limit) {
224
+ return {
225
+ ok: false,
226
+ detail: `the Mandrel block in ${docName} spans bytes ${start}–${end}, beyond ${limitLabel} — Codex never reads it`,
227
+ remedy: HOIST_REMEDY,
228
+ };
229
+ }
230
+ if (total > limit) {
231
+ return {
232
+ ok: true,
233
+ 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`,
234
+ };
235
+ }
236
+ return {
237
+ ok: true,
238
+ detail: `${docName} is ${total} bytes, within ${limitLabel}; the Mandrel block loads`,
239
+ };
240
+ }
@@ -0,0 +1,79 @@
1
+ // lib/cli/doctor-checks/merge-driver.js — Doctor check: merge-driver.
2
+
3
+ import fs from 'node:fs';
4
+ import {
5
+ BASELINE_MERGE_DRIVER_CONFIG_KEY,
6
+ BASELINE_MERGE_DRIVER_REMEDY,
7
+ parseBaselineMergeDriverCommand,
8
+ probeBaselineMergeDriver,
9
+ } from '../../../.agents/scripts/lib/bootstrap/baseline-merge-driver.js';
10
+ import { spawn } from './spawn.js';
11
+
12
+ // check: merge-driver
13
+
14
+ /**
15
+ * Is this clone's `baselines/*.json` merge driver registered? `.gitattributes`
16
+ * ships with the repo but the driver command is per-clone `git config`, and a
17
+ * missing one silently falls back to a text merge. Skipped when
18
+ * `.gitattributes` does not declare the driver.
19
+ *
20
+ * @param {{cwd?: () => string, fsImpl?: typeof fs, runner?: typeof spawn}} [opts]
21
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
22
+ */
23
+ export function runMergeDriver({ cwd, fsImpl = fs, runner = spawn } = {}) {
24
+ const projectRoot = (cwd ?? (() => process.cwd()))();
25
+ // Git runs from projectRoot: the config key is per-clone.
26
+ const { declared, command } = probeBaselineMergeDriver({
27
+ projectRoot,
28
+ fsImpl,
29
+ runGit: (args) => runner('git', args, { cwd: projectRoot }),
30
+ });
31
+ if (!declared) {
32
+ return {
33
+ ok: true,
34
+ detail:
35
+ 'skipped — .gitattributes does not route baselines/*.json through the mandrel merge driver',
36
+ };
37
+ }
38
+ if (command === '') {
39
+ return {
40
+ ok: false,
41
+ 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`,
42
+ remedy: BASELINE_MERGE_DRIVER_REMEDY,
43
+ };
44
+ }
45
+ return probeConfiguredDriver(command, runner, projectRoot);
46
+ }
47
+
48
+ /**
49
+ * Execute the configured driver with `--help` (the real invocation mutates
50
+ * `%A`): a set-but-broken command — typically an absolute node path moved by
51
+ * an nvm/volta bump — fails as silently as an unset key. The command is
52
+ * tokenised, never shell-run, since a config value must not become arbitrary
53
+ * command execution. Runs from projectRoot, where git invokes drivers.
54
+ *
55
+ * @param {string} command
56
+ * @param {typeof spawn} runner
57
+ * @param {string} projectRoot
58
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
59
+ */
60
+ function probeConfiguredDriver(command, runner, projectRoot) {
61
+ const parsed = parseBaselineMergeDriverCommand(command);
62
+ if (!parsed) {
63
+ return {
64
+ ok: false,
65
+ detail: `${BASELINE_MERGE_DRIVER_CONFIG_KEY} is set to ${JSON.stringify(command)}, which has no runnable command in it`,
66
+ remedy: BASELINE_MERGE_DRIVER_REMEDY,
67
+ };
68
+ }
69
+ const probe = runner(parsed.file, [...parsed.args, '--help'], {
70
+ cwd: projectRoot,
71
+ });
72
+ if (probe.status === 0) return { ok: true, detail: command };
73
+ const why = probe.error?.message ?? `exit ${probe.status}`;
74
+ return {
75
+ ok: false,
76
+ 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`,
77
+ remedy: BASELINE_MERGE_DRIVER_REMEDY,
78
+ };
79
+ }
@@ -0,0 +1,201 @@
1
+ // lib/cli/doctor-checks/payload.js — Doctor checks: agents-drift, pin-current.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {
6
+ defaultResolvePackageRoot,
7
+ listFiles as listPayloadFiles,
8
+ } from '../sync.js';
9
+ import {
10
+ compareVersions as compareSemver,
11
+ resolveConsumerPinSpec,
12
+ satisfiesPinSpec,
13
+ } from '../version-helpers.js';
14
+
15
+ // check: agents-drift
16
+
17
+ /**
18
+ * A size mismatch proves drift without reading contents; equal sizes fall
19
+ * through to a byte compare. `statSync` is optional on the seam.
20
+ *
21
+ * @param {string} src - absolute path to the package-payload file
22
+ * @param {string} dest - absolute path to the materialized file
23
+ * @param {{ readFileSync: Function, statSync?: Function }} fsImpl
24
+ * @returns {boolean} `true` when the files differ
25
+ */
26
+ function payloadFileDrifted(src, dest, fsImpl) {
27
+ if (
28
+ typeof fsImpl.statSync === 'function' &&
29
+ fsImpl.statSync(src).size !== fsImpl.statSync(dest).size
30
+ ) {
31
+ return true;
32
+ }
33
+ return !fsImpl.readFileSync(src).equals(fsImpl.readFileSync(dest));
34
+ }
35
+
36
+ /**
37
+ * Compare materialized `./.agents/` bytes to the installed package payload
38
+ * (excluding `.agents/local/`) and report the first missing or drifted file.
39
+ * Only paths and counts are reported, never contents.
40
+ *
41
+ * @param {{
42
+ * cwd?: () => string,
43
+ * fsImpl?: { existsSync: (p: string) => boolean, readdirSync: Function, readFileSync: Function, statSync?: Function },
44
+ * resolvePackageRoot?: (fromDir: string) => string,
45
+ * }} [opts]
46
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
47
+ */
48
+ export function runAgentsDrift({ cwd, fsImpl = fs, resolvePackageRoot } = {}) {
49
+ const getCwd = cwd ?? (() => process.cwd());
50
+ const resolveRoot = resolvePackageRoot ?? defaultResolvePackageRoot;
51
+ const projectRoot = getCwd();
52
+
53
+ let packageRoot;
54
+ try {
55
+ packageRoot = resolveRoot(projectRoot);
56
+ } catch {
57
+ // agents-materialized owns the "not installed" remedy.
58
+ return {
59
+ ok: true,
60
+ detail: 'mandrel not installed — drift skipped',
61
+ };
62
+ }
63
+
64
+ const sourceRoot = path.join(packageRoot, '.agents');
65
+ if (!fsImpl.existsSync(sourceRoot)) {
66
+ return {
67
+ ok: true,
68
+ detail: 'mandrel ships no .agents/ payload — drift skipped',
69
+ };
70
+ }
71
+
72
+ const destRoot = path.join(projectRoot, '.agents');
73
+ if (!fsImpl.existsSync(destRoot)) {
74
+ return { ok: true, detail: './.agents/ not materialized — drift skipped' };
75
+ }
76
+
77
+ const files = listPayloadFiles(sourceRoot, fsImpl);
78
+ let comparedCount = 0;
79
+ let missingCount = 0;
80
+
81
+ for (const rel of files) {
82
+ const src = path.join(sourceRoot, rel);
83
+ const dest = path.join(destRoot, rel);
84
+ const relLabel = path.join('.agents', rel);
85
+
86
+ if (!fsImpl.existsSync(dest)) {
87
+ missingCount += 1;
88
+ return {
89
+ ok: false,
90
+ detail: `${relLabel} is missing from ./.agents/ (${missingCount} of ${files.length} payload files checked so far)`,
91
+ remedy:
92
+ 'Run `mandrel sync` to restore the materialized .agents/ payload.',
93
+ };
94
+ }
95
+
96
+ comparedCount += 1;
97
+ if (payloadFileDrifted(src, dest, fsImpl)) {
98
+ return {
99
+ ok: false,
100
+ detail: `${relLabel} differs from the installed package payload`,
101
+ remedy:
102
+ 'Run `mandrel sync` to overwrite local edits, or move intentional changes into the `.agents/local/` zone.',
103
+ };
104
+ }
105
+ }
106
+
107
+ return {
108
+ ok: true,
109
+ detail: `${comparedCount} materialized file(s) match the package payload`,
110
+ };
111
+ }
112
+
113
+ // check: pin-current
114
+
115
+ /**
116
+ * Fatal: does the installed `mandrel` satisfy the consumer's declared range?
117
+ * Distinct from `agents-drift` (file contents) and `version-current` (newer
118
+ * published). Graded by range satisfaction, not identity, because `^2.1.0` +
119
+ * 2.4.0 after `npm update` is the normal steady state:
120
+ * - satisfies and equals the base → pass;
121
+ * - satisfies but newer than the base → pass, advisory in `detail`;
122
+ * - behind the base → fail (distinct message);
123
+ * - otherwise outside the range → fail.
124
+ * No resolvable semver pin (absent, `workspace:`, `git+`, `latest`, …) skips.
125
+ *
126
+ * @param {{
127
+ * cwd?: () => string,
128
+ * fsImpl?: typeof fs,
129
+ * resolvePackageRoot?: (fromDir: string) => string,
130
+ * }} [opts]
131
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
132
+ */
133
+ export function runPinCurrent({ cwd, fsImpl = fs, resolvePackageRoot } = {}) {
134
+ const getCwd = cwd ?? (() => process.cwd());
135
+ const resolveRoot = resolvePackageRoot ?? defaultResolvePackageRoot;
136
+ const projectRoot = getCwd();
137
+
138
+ const spec = resolveConsumerPinSpec(projectRoot, fsImpl);
139
+ if (!spec) {
140
+ return {
141
+ ok: true,
142
+ detail: 'no resolvable mandrel dependency pin — skipped',
143
+ };
144
+ }
145
+
146
+ let installedRoot;
147
+ try {
148
+ installedRoot = resolveRoot(projectRoot);
149
+ } catch {
150
+ return {
151
+ ok: true,
152
+ detail: 'mandrel not installed — pin check skipped',
153
+ };
154
+ }
155
+
156
+ let installed;
157
+ try {
158
+ const parsed = JSON.parse(
159
+ fsImpl.readFileSync(path.join(installedRoot, 'package.json'), 'utf8'),
160
+ );
161
+ installed = String(parsed.version);
162
+ } catch {
163
+ return {
164
+ ok: true,
165
+ detail: 'installed version unreadable — pin check skipped',
166
+ };
167
+ }
168
+
169
+ const declared = `${spec.operator}${spec.version}`;
170
+
171
+ if (compareSemver(installed, spec.version) < 0) {
172
+ return {
173
+ ok: false,
174
+ detail: `package.json pins ${declared} but an older v${installed} is installed`,
175
+ remedy:
176
+ 'Run `npm install` to install a version satisfying the package.json pin.',
177
+ };
178
+ }
179
+
180
+ if (!satisfiesPinSpec(installed, spec)) {
181
+ return {
182
+ ok: false,
183
+ detail: `package.json pins ${declared} but v${installed} is installed — outside the declared range`,
184
+ remedy:
185
+ 'Run `mandrel update` to reconcile the package.json pin with the installed version.',
186
+ };
187
+ }
188
+
189
+ if (compareSemver(installed, spec.version) > 0) {
190
+ // The doctor prints only `detail` for a pass, so the advisory rides there.
191
+ return {
192
+ ok: true,
193
+ detail: `v${installed} satisfies the ${declared} pin but is newer than it — run \`mandrel update\` to re-pin (advisory)`,
194
+ };
195
+ }
196
+
197
+ return {
198
+ ok: true,
199
+ detail: `pin ${declared} matches the installed version`,
200
+ };
201
+ }
@@ -0,0 +1,16 @@
1
+ // lib/cli/doctor-checks/read-json.js — shared JSON read for the doctor checks.
2
+
3
+ /**
4
+ * Raw JSON read; any failure degrades to `null`.
5
+ *
6
+ * @param {string} absPath
7
+ * @param {{ readFileSync: Function }} fsImpl
8
+ * @returns {object | null}
9
+ */
10
+ export function readJsonSafe(absPath, fsImpl) {
11
+ try {
12
+ return JSON.parse(fsImpl.readFileSync(absPath, 'utf8'));
13
+ } catch {
14
+ return null;
15
+ }
16
+ }