mandrel 2.87.0 → 2.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -0,0 +1,146 @@
1
+ // lib/cli/doctor-checks/runtime-deps.js — Doctor checks: runtime-deps, agents-materialized.
2
+
3
+ import fs from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { isResolvable } from '../../../.agents/scripts/lib/runtime-deps/dep-resolution.js';
7
+ import { describeParserMajorError } from '../../../.agents/scripts/lib/runtime-deps/parser-major.js';
8
+
9
+ // check: runtime-deps
10
+
11
+ /**
12
+ * Presence is not enough: a declared range cannot pin which `@babel/parser`
13
+ * major the consumer's node_modules supplies, and the wrong one fails
14
+ * scoring mid-scan with an opaque error — so report it here.
15
+ *
16
+ * @param {() => string|null} parserMajorError
17
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
18
+ */
19
+ function allPresentVerdict(parserMajorError) {
20
+ const parserProblem = parserMajorError();
21
+ if (parserProblem === null) {
22
+ return { ok: true, detail: 'all dependencies found' };
23
+ }
24
+ return {
25
+ ok: false,
26
+ detail: 'dependency version unsupported',
27
+ remedy: parserProblem,
28
+ };
29
+ }
30
+
31
+ /**
32
+ * Are the runtime deps resolvable from the consumer root? Anchored at
33
+ * `process.cwd()`, not the package root: under pnpm isolated mode the
34
+ * consumer's node_modules are invisible from `node_modules/mandrel/`.
35
+ *
36
+ * @param {{ projectRoot?: string, resolve?: (dep: string) => string, manifestRequired?: string[] }} [opts]
37
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
38
+ */
39
+ export function runRuntimeDeps({
40
+ projectRoot,
41
+ resolve: resolveSeam,
42
+ manifestRequired,
43
+ parserMajorError = describeParserMajorError,
44
+ } = {}) {
45
+ const root = projectRoot ?? process.cwd();
46
+
47
+ let required = manifestRequired;
48
+ if (!required) {
49
+ try {
50
+ const manifestPath = path.join(root, '.agents', 'runtime-deps.json');
51
+ const raw = fs.readFileSync(manifestPath, 'utf8');
52
+ const parsed = JSON.parse(raw);
53
+ required = Object.keys(parsed.dependencies ?? {});
54
+ } catch {
55
+ required = [];
56
+ }
57
+ }
58
+
59
+ if (required.length === 0) {
60
+ return { ok: true, detail: 'all dependencies found' };
61
+ }
62
+
63
+ const missing = [];
64
+
65
+ // `isResolvable` also probes `<name>/package.json`: a dep with no `main`
66
+ // and no `exports` cannot be resolved by bare name yet is installed.
67
+ const resolve =
68
+ resolveSeam ?? createRequire(path.join(root, 'package.json')).resolve;
69
+ for (const dep of required) {
70
+ if (!isResolvable(dep, resolve)) missing.push(dep);
71
+ }
72
+
73
+ if (missing.length === 0) return allPresentVerdict(parserMajorError);
74
+ return {
75
+ ok: false,
76
+ detail: `missing: ${missing.join(', ')}`,
77
+ remedy:
78
+ 'The framework runtime deps are not resolvable from the consumer root, ' +
79
+ 'where the materialized .agents/scripts/*.js run. npm and yarn hoist ' +
80
+ "them automatically — run the installer if you haven't. pnpm's default " +
81
+ 'isolated layout does NOT hoist transitive deps to the top level: add ' +
82
+ '`shamefully-hoist=true` (or a scoped `public-hoist-pattern[]` for ' +
83
+ 'each dep) to your `.npmrc` and reinstall. ' +
84
+ `Missing: ${missing.join(', ')}`,
85
+ };
86
+ }
87
+
88
+ // check: agents-materialized
89
+
90
+ /**
91
+ * Is `./.agents/instructions.md` present? Absent with the package installed
92
+ * means postinstall was skipped (`--ignore-scripts`, sandboxed CI). Both
93
+ * lookups anchor at the consumer's cwd.
94
+ *
95
+ * @param {{
96
+ * cwd?: () => string,
97
+ * existsSync?: (p: string) => boolean,
98
+ * resolvePackage?: (fromDir: string) => string,
99
+ * }} [opts]
100
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
101
+ */
102
+ export function runAgentsMaterialized({
103
+ cwd,
104
+ existsSync,
105
+ resolvePackage,
106
+ } = {}) {
107
+ const getCwd = cwd ?? (() => process.cwd());
108
+ const exists = existsSync ?? ((p) => fs.existsSync(p));
109
+ const root = getCwd();
110
+ const instructionsPath = path.join(root, '.agents', 'instructions.md');
111
+
112
+ if (exists(instructionsPath)) {
113
+ return { ok: true, detail: '.agents/ materialized' };
114
+ }
115
+
116
+ const resolvePkg =
117
+ resolvePackage ??
118
+ ((fromDir) => {
119
+ const requireFrom = createRequire(path.join(fromDir, 'noop.js'));
120
+ return requireFrom.resolve('mandrel/package.json');
121
+ });
122
+
123
+ let packageInstalled = false;
124
+ try {
125
+ resolvePkg(root);
126
+ packageInstalled = true;
127
+ } catch {
128
+ packageInstalled = false;
129
+ }
130
+
131
+ if (packageInstalled) {
132
+ return {
133
+ ok: false,
134
+ detail: 'mandrel installed but ./.agents/ not materialized',
135
+ remedy:
136
+ 'Run `mandrel sync` to materialize the .agents/ payload (postinstall was skipped).',
137
+ };
138
+ }
139
+
140
+ return {
141
+ ok: false,
142
+ detail: 'mandrel not installed and ./.agents/ absent',
143
+ remedy:
144
+ 'Install the framework (`npm install mandrel`), then run `mandrel sync`.',
145
+ };
146
+ }
@@ -0,0 +1,18 @@
1
+ // lib/cli/doctor-checks/spawn.js — Shared `spawnSync` wrapper for the doctor checks.
2
+
3
+ import { spawnSync } from 'node:child_process';
4
+
5
+ /**
6
+ * @param {string} cmd
7
+ * @param {string[]} args
8
+ * @returns {{ status: number|null, stdout: string, stderr: string, error?: NodeJS.ErrnoException }}
9
+ */
10
+ export function spawn(cmd, args, opts = {}) {
11
+ const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
12
+ return {
13
+ status: r.status,
14
+ stdout: typeof r.stdout === 'string' ? r.stdout : '',
15
+ stderr: typeof r.stderr === 'string' ? r.stderr : '',
16
+ error: r.error,
17
+ };
18
+ }
@@ -0,0 +1,205 @@
1
+ // lib/cli/doctor-checks/sync-parity.js — Doctor checks: commands-in-sync, agents-in-sync.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { isCommandExcluded } from '../../../.agents/scripts/lib/command-header.js';
6
+ import { getDeliveryRouting } from '../../../.agents/scripts/lib/config/delivery-routing.js';
7
+ import { readJsonSafe } from './read-json.js';
8
+
9
+ // check: commands-in-sync
10
+
11
+ /**
12
+ * Parity of `.claude/commands/*.md` against the union of `.agents/workflows/`
13
+ * and `.agents/local/workflows/`. A basename is expected iff at least one
14
+ * source copy is not `command: false`, mirroring the sync script's
15
+ * payload-wins shadowing; an unreadable source counts as projected.
16
+ *
17
+ * The root defaults to `process.cwd()`, never `resolveProjectRoot()` — that
18
+ * lands on `node_modules/mandrel/` in an installed consumer, where the
19
+ * command tree never exists, producing a permanent false "not synced".
20
+ *
21
+ * @param {{ projectRoot?: string, cwd?: () => string, readDir?: (dir: string) => string[], readFile?: (file: string) => string | null }} [opts]
22
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
23
+ */
24
+ export function runCommandsInSync({
25
+ projectRoot,
26
+ cwd,
27
+ readDir,
28
+ readFile,
29
+ } = {}) {
30
+ const getCwd = cwd ?? (() => process.cwd());
31
+ const root = projectRoot ?? getCwd();
32
+ const listDir =
33
+ readDir ??
34
+ ((dir) => {
35
+ try {
36
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
37
+ } catch {
38
+ return [];
39
+ }
40
+ });
41
+ const readSource =
42
+ readFile ??
43
+ ((file) => {
44
+ try {
45
+ return fs.readFileSync(file, 'utf8');
46
+ } catch {
47
+ return null;
48
+ }
49
+ });
50
+
51
+ const srcDirs = [
52
+ path.join(root, '.agents', 'workflows'),
53
+ path.join(root, '.agents', 'local', 'workflows'),
54
+ ];
55
+ const destDir = path.join(root, '.claude', 'commands');
56
+
57
+ // Top-level .md only (helpers/ are included modules, not commands).
58
+ const expected = new Set();
59
+ for (const srcDir of srcDirs) {
60
+ for (const f of listDir(srcDir)) {
61
+ if (f.startsWith('.')) continue;
62
+ const content = readSource(path.join(srcDir, f));
63
+ if (content != null && isCommandExcluded(content)) continue;
64
+ expected.add(f);
65
+ }
66
+ }
67
+ const sources = [...expected].sort();
68
+ const dests = listDir(destDir)
69
+ .filter((f) => !f.startsWith('.'))
70
+ .sort();
71
+
72
+ const dstSet = new Set(dests);
73
+ const missing = sources.filter((f) => !dstSet.has(f));
74
+ const extra = dests.filter((f) => !expected.has(f));
75
+
76
+ if (missing.length === 0 && extra.length === 0) {
77
+ return { ok: true, detail: `${sources.length} commands up to date` };
78
+ }
79
+
80
+ const parts = [];
81
+ if (missing.length > 0) parts.push(`${missing.length} not synced`);
82
+ if (extra.length > 0) parts.push(`${extra.length} stale`);
83
+ return {
84
+ ok: false,
85
+ detail: parts.join(', '),
86
+ remedy:
87
+ 'Run `npm run sync:commands` to regenerate the `.claude/commands/` tree.',
88
+ };
89
+ }
90
+
91
+ // check: agents-in-sync
92
+
93
+ /**
94
+ * Resolve `delivery.routing.roleScopedAgents` without `resolveConfig()`,
95
+ * which pulls in AJV and would break the built-ins-only contract. Shallow-
96
+ * merges only `delivery.routing` from `.agentrc.json` and
97
+ * `.agentrc.local.json` (local wins).
98
+ *
99
+ * @param {string} projectRoot
100
+ * @param {typeof fs} fsImpl
101
+ * @returns {boolean}
102
+ */
103
+ function resolveRoleScopedAgentsFlag(projectRoot, fsImpl) {
104
+ const base = readJsonSafe(path.join(projectRoot, '.agentrc.json'), fsImpl);
105
+ const local = readJsonSafe(
106
+ path.join(projectRoot, '.agentrc.local.json'),
107
+ fsImpl,
108
+ );
109
+ const merged = {
110
+ delivery: {
111
+ routing: {
112
+ ...(base?.delivery?.routing ?? {}),
113
+ ...(local?.delivery?.routing ?? {}),
114
+ },
115
+ },
116
+ };
117
+ return getDeliveryRouting(merged).roleScopedAgents;
118
+ }
119
+
120
+ /**
121
+ * Parity of `.claude/agents/*.md` against `.agents/agents/*.md` (root anchored
122
+ * at `process.cwd()` as in `commands-in-sync`). A never-materialized tree is
123
+ * fatal while `roleScopedAgents` is on — the acceptance critic would silently
124
+ * fail to spawn and fall back to a weaker inline critic — and advisory when it
125
+ * is off. Drift in a materialized tree always fails.
126
+ *
127
+ * @param {{
128
+ * projectRoot?: string,
129
+ * cwd?: () => string,
130
+ * readDir?: (dir: string) => string[],
131
+ * fsImpl?: typeof fs,
132
+ * roleScopedAgents?: boolean,
133
+ * }} [opts]
134
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
135
+ */
136
+ export function runAgentsInSync({
137
+ projectRoot,
138
+ cwd,
139
+ readDir,
140
+ fsImpl = fs,
141
+ roleScopedAgents,
142
+ } = {}) {
143
+ const getCwd = cwd ?? (() => process.cwd());
144
+ const root = projectRoot ?? getCwd();
145
+ const listDir =
146
+ readDir ??
147
+ ((dir) => {
148
+ try {
149
+ return fsImpl.readdirSync(dir).filter((f) => f.endsWith('.md'));
150
+ } catch {
151
+ return [];
152
+ }
153
+ });
154
+
155
+ const srcDir = path.join(root, '.agents', 'agents');
156
+ const destDir = path.join(root, '.claude', 'agents');
157
+
158
+ const sources = listDir(srcDir)
159
+ .filter((f) => !f.startsWith('.'))
160
+ .sort();
161
+ const dests = listDir(destDir)
162
+ .filter((f) => !f.startsWith('.'))
163
+ .sort();
164
+
165
+ if (dests.length === 0) {
166
+ if (sources.length === 0) {
167
+ return { ok: true, detail: '0 agents up to date' };
168
+ }
169
+ const resolvedFlag =
170
+ typeof roleScopedAgents === 'boolean'
171
+ ? roleScopedAgents
172
+ : resolveRoleScopedAgentsFlag(root, fsImpl);
173
+ if (!resolvedFlag) {
174
+ return {
175
+ ok: true,
176
+ detail: `${sources.length} agent def(s) not materialized (roleScopedAgents is disabled)`,
177
+ };
178
+ }
179
+ return {
180
+ ok: false,
181
+ detail: `${sources.length} agent def(s) not yet materialized in .claude/agents/`,
182
+ remedy:
183
+ 'Run `mandrel sync-agents` to regenerate the `.claude/agents/` tree.',
184
+ };
185
+ }
186
+
187
+ const srcSet = new Set(sources);
188
+ const dstSet = new Set(dests);
189
+ const missing = sources.filter((f) => !dstSet.has(f));
190
+ const extra = dests.filter((f) => !srcSet.has(f));
191
+
192
+ if (missing.length === 0 && extra.length === 0) {
193
+ return { ok: true, detail: `${sources.length} agents up to date` };
194
+ }
195
+
196
+ const parts = [];
197
+ if (missing.length > 0) parts.push(`${missing.length} not synced`);
198
+ if (extra.length > 0) parts.push(`${extra.length} stale`);
199
+ return {
200
+ ok: false,
201
+ detail: parts.join(', '),
202
+ remedy:
203
+ 'Run `mandrel sync-agents` to regenerate the `.claude/agents/` tree.',
204
+ };
205
+ }
@@ -0,0 +1,270 @@
1
+ // lib/cli/doctor-checks/test-credit-path.js — Doctor check: test-credit-path.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { readJsonSafe } from './read-json.js';
6
+
7
+ // check: test-credit-path
8
+
9
+ /** The runner whose green full run deposits the close `test` credit itself. */
10
+ const MANDREL_TEST_RUNNER = 'run-tests.js';
11
+
12
+ /** The close `test` gate's command when `project.commands.test` is unset. */
13
+ const DEFAULT_TEST_COMMAND = 'npm test';
14
+
15
+ /**
16
+ * The deposit command that works on any runner, wrapping `command`.
17
+ *
18
+ * @param {string} command
19
+ * @returns {string}
20
+ */
21
+ function testCreditDepositCommand(command) {
22
+ return `node .agents/scripts/evidence-gate.js --standalone --scope-id <storyId> --gate test --worktree <workCwd> -- ${command}`;
23
+ }
24
+
25
+ /** The capture close's `coverage-capture` gate finds fresh, per digest § 5. */
26
+ const COVERAGE_CAPTURE_COMMAND =
27
+ 'node .agents/scripts/coverage-capture.js --cwd <workCwd>';
28
+
29
+ /** The worker's one tail command; it runs whichever depositor applies. */
30
+ const STORY_HANDOFF_COMMAND =
31
+ 'node .agents/scripts/story-handoff.js --story <storyId> --cwd <workCwd>';
32
+
33
+ /**
34
+ * @param {string} command
35
+ * @returns {string}
36
+ */
37
+ function testCreditRemedy(command) {
38
+ return `run the suite through the depositor instead of bare \`${command}\`: ${testCreditDepositCommand(command)}`;
39
+ }
40
+
41
+ const PRE_PUSH_REMEDY =
42
+ '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';
43
+
44
+ /** A hook line that runs a typecheck or lint gate. */
45
+ const HOOK_GATE_RE = /\b(typecheck|tsc|lint|eslint|biome)\b/;
46
+
47
+ /**
48
+ * The hook minus its comment lines: a comment that mentions lint runs nothing.
49
+ *
50
+ * @param {string} hook
51
+ * @returns {string}
52
+ */
53
+ function hookCommandLines(hook) {
54
+ return hook
55
+ .split('\n')
56
+ .filter((line) => !line.trimStart().startsWith('#'))
57
+ .join('\n');
58
+ }
59
+
60
+ /**
61
+ * Consulted only while `project.commands.test` is unset — then the close
62
+ * gate's argv is `npm test`, which runs `scripts.test`.
63
+ *
64
+ * @param {string} projectRoot
65
+ * @param {typeof fs.readFileSync} readFileImpl
66
+ * @returns {Record<string, string>} The `scripts` map, empty when unreadable.
67
+ */
68
+ function readProjectScripts(projectRoot, readFileImpl) {
69
+ try {
70
+ const raw = readFileImpl(path.join(projectRoot, 'package.json'), 'utf8');
71
+ const scripts = JSON.parse(raw)?.scripts;
72
+ return scripts && typeof scripts === 'object' ? scripts : {};
73
+ } catch {
74
+ return {};
75
+ }
76
+ }
77
+
78
+ /**
79
+ * @param {Record<string, string>} scripts
80
+ * @param {string} name
81
+ * @returns {string|null} The trimmed script, or null when there is none.
82
+ */
83
+ function scriptNamed(scripts, name) {
84
+ const script = scripts[name];
85
+ return typeof script === 'string' && script.trim().length > 0
86
+ ? script.trim()
87
+ : null;
88
+ }
89
+
90
+ /**
91
+ * `delivery.quality.gates.crap.enabled` from `.agentrc.json` overlaid by
92
+ * `.agentrc.local.json`, defaulting on — the predicate close registers
93
+ * `coverage-capture` on. Read without `resolveConfig()` (built-ins only).
94
+ *
95
+ * @param {string} projectRoot
96
+ * @param {typeof fs.readFileSync} readFileImpl
97
+ * @returns {boolean}
98
+ */
99
+ function isCrapEnabled(projectRoot, readFileImpl) {
100
+ let enabled = true;
101
+ for (const file of ['.agentrc.json', '.agentrc.local.json']) {
102
+ const value = readJsonSafe(path.join(projectRoot, file), {
103
+ readFileSync: readFileImpl,
104
+ })?.delivery?.quality?.gates?.crap?.enabled;
105
+ if (typeof value === 'boolean') enabled = value;
106
+ }
107
+ return enabled;
108
+ }
109
+
110
+ /**
111
+ * `project.commands.test` from `.agentrc.json` overlaid by
112
+ * `.agentrc.local.json` — the command close's `test` gate spawns. Read without
113
+ * `resolveConfig()` (built-ins only), like {@link isCrapEnabled}.
114
+ *
115
+ * @param {string} projectRoot
116
+ * @param {typeof fs.readFileSync} readFileImpl
117
+ * @returns {string|null} The configured command, or null when unset/default.
118
+ */
119
+ function configuredTestCommand(projectRoot, readFileImpl) {
120
+ let command = null;
121
+ for (const file of ['.agentrc.json', '.agentrc.local.json']) {
122
+ const value = readJsonSafe(path.join(projectRoot, file), {
123
+ readFileSync: readFileImpl,
124
+ })?.project?.commands?.test;
125
+ if (typeof value === 'string' && value.trim().length > 0) {
126
+ command = value.trim();
127
+ }
128
+ }
129
+ return command === DEFAULT_TEST_COMMAND ? null : command;
130
+ }
131
+
132
+ /**
133
+ * A configured `project.commands.test` is what close spawns, so the analysis
134
+ * is of that command, never of `scripts.test`.
135
+ *
136
+ * @param {string} command
137
+ * @returns {{ detail: string, remedy?: string }}
138
+ */
139
+ function describeConfiguredTestCommand(command) {
140
+ const lead = `\`project.commands.test\` sets close's \`test\` gate to \`${command}\``;
141
+ if (command.includes(MANDREL_TEST_RUNNER)) {
142
+ return {
143
+ detail: `${lead}, which reaches mandrel's runner — a green full run on a story branch deposits the close \`test\` credit itself`,
144
+ };
145
+ }
146
+ const remedy = testCreditRemedy(command);
147
+ return {
148
+ detail: `${lead}, which deposits no close \`test\` credit by itself — ${remedy}`,
149
+ remedy,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Which depositor digest § 5 selects, stated with its exact command.
155
+ *
156
+ * @param {{ scripts: Record<string, string>, crapEnabled: boolean, testCommand: string|null }} probe
157
+ * @returns {{ detail: string, remedy?: string }}
158
+ */
159
+ function describeCreditedRun({ scripts, crapEnabled, testCommand }) {
160
+ if (crapEnabled && scriptNamed(scripts, 'test:coverage') !== null) {
161
+ return {
162
+ 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`,
163
+ };
164
+ }
165
+ return testCommand !== null
166
+ ? describeConfiguredTestCommand(testCommand)
167
+ : describeNpmTestScript(scripts);
168
+ }
169
+
170
+ /**
171
+ * With `project.commands.test` unset close spawns `npm test`, so the analysis
172
+ * is of `scripts.test`.
173
+ *
174
+ * @param {Record<string, string>} scripts
175
+ * @returns {{ detail: string, remedy?: string }}
176
+ */
177
+ function describeNpmTestScript(scripts) {
178
+ const remedy = testCreditRemedy(DEFAULT_TEST_COMMAND);
179
+ const script = scriptNamed(scripts, 'test');
180
+ if (script === null) {
181
+ return {
182
+ detail: `no \`test\` script in package.json — close still spawns \`npm test\`, so ${remedy}`,
183
+ remedy,
184
+ };
185
+ }
186
+ if (script.includes(MANDREL_TEST_RUNNER)) {
187
+ return {
188
+ detail: `\`npm test\` → \`${script}\` reaches mandrel's runner — a green full run on a story branch deposits the close \`test\` credit itself`,
189
+ };
190
+ }
191
+ return {
192
+ 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}`,
193
+ remedy,
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Does the pre-push hook deposit gate evidence? Read, never executed.
199
+ *
200
+ * @param {string} projectRoot
201
+ * @param {typeof fs.readFileSync} readFileImpl
202
+ * @returns {{ detail: string, remedy?: string }}
203
+ */
204
+ function describePrePushHook(projectRoot, readFileImpl) {
205
+ let hook = null;
206
+ let hookPath = null;
207
+ for (const rel of [
208
+ path.join('.husky', 'pre-push'),
209
+ path.join('.git', 'hooks', 'pre-push'),
210
+ ]) {
211
+ try {
212
+ hook = readFileImpl(path.join(projectRoot, rel), 'utf8');
213
+ hookPath = rel.split(path.sep).join('/');
214
+ break;
215
+ } catch {
216
+ // Absent here — try the next hooks location.
217
+ }
218
+ }
219
+ if (hook === null) {
220
+ return { detail: 'no pre-push hook found, so nothing runs a gate there' };
221
+ }
222
+ if (hook.includes('evidence-gate.js')) {
223
+ return {
224
+ detail: `\`${hookPath}\` routes its gates through \`evidence-gate.js\`, so the push deposits evidence close can credit`,
225
+ };
226
+ }
227
+ if (HOOK_GATE_RE.test(hookCommandLines(hook))) {
228
+ return {
229
+ detail: `\`${hookPath}\` runs typecheck or lint without \`evidence-gate.js\`, so it deposits nothing and close re-runs them — ${PRE_PUSH_REMEDY}`,
230
+ remedy: PRE_PUSH_REMEDY,
231
+ };
232
+ }
233
+ return {
234
+ detail: `\`${hookPath}\` runs no typecheck or lint gate, so close has nothing of it to re-run`,
235
+ };
236
+ }
237
+
238
+ /**
239
+ * Which credited run does digest § 5 select for this project, and does its
240
+ * pre-push hook deposit the gate evidence close reads? Always `ok: true` —
241
+ * every shape is supported, some just cost close a re-run — so any remedy
242
+ * rides a passing verdict and is repeated in `detail`. Detected from files
243
+ * only; nothing is executed.
244
+ *
245
+ * @param {{ projectRoot?: string, readFile?: typeof fs.readFileSync }} [opts]
246
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
247
+ */
248
+ export function runTestCreditPath({
249
+ projectRoot,
250
+ readFile = fs.readFileSync,
251
+ } = {}) {
252
+ const root = projectRoot ?? process.cwd();
253
+ const parts = [
254
+ {
255
+ detail: `the worker's \`${STORY_HANDOFF_COMMAND}\` runs the credited run close reads`,
256
+ },
257
+ describeCreditedRun({
258
+ scripts: readProjectScripts(root, readFile),
259
+ crapEnabled: isCrapEnabled(root, readFile),
260
+ testCommand: configuredTestCommand(root, readFile),
261
+ }),
262
+ describePrePushHook(root, readFile),
263
+ ];
264
+ const remedies = parts.map((p) => p.remedy).filter(Boolean);
265
+ return {
266
+ ok: true,
267
+ detail: parts.map((p) => p.detail).join('; '),
268
+ ...(remedies.length > 0 ? { remedy: remedies.join('; ') } : {}),
269
+ };
270
+ }