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
@@ -0,0 +1,63 @@
1
+ /** `github.cliConfigDir` → `process.env.GH_CONFIG_DIR`, inherited by every `gh` child. */
2
+
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { Logger } from '../Logger.js';
7
+
8
+ function resolveGhConfigDir(value, root, { homedir = os.homedir } = {}) {
9
+ if (value === '~') return homedir();
10
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
11
+ return path.join(homedir(), value.slice(2));
12
+ }
13
+ return path.resolve(root, value);
14
+ }
15
+
16
+ function isDirectory(fsImpl, dir) {
17
+ try {
18
+ return fsImpl.statSync(dir).isDirectory();
19
+ } catch {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Sets `env.GH_CONFIG_DIR` from `github.cliConfigDir`, idempotently. Absent
26
+ * key = no-op. A missing directory is a config error, never a silent
27
+ * fallback to the default store; a differing inherited value is overridden
28
+ * with one warning naming both paths.
29
+ *
30
+ * @param {{ cliConfigDir?: string|null }|null|undefined} github
31
+ * @param {string} root
32
+ * @param {{ env?: NodeJS.ProcessEnv, fsImpl?: import('node:fs'),
33
+ * warn?: (msg: string) => void, homedir?: () => string }} [deps]
34
+ * @returns {string|null} the applied absolute path, or null when unset.
35
+ */
36
+ export function applyGhConfigDir(
37
+ github,
38
+ root,
39
+ {
40
+ env = process.env,
41
+ fsImpl = fs,
42
+ warn = (msg) => Logger.warn(msg),
43
+ homedir,
44
+ } = {},
45
+ ) {
46
+ const configured = github?.cliConfigDir;
47
+ if (typeof configured !== 'string' || configured.length === 0) return null;
48
+ const dir = resolveGhConfigDir(configured, root, { homedir });
49
+ if (!isDirectory(fsImpl, dir)) {
50
+ throw new Error(
51
+ `[config] github.cliConfigDir points at ${dir}, which is not an existing directory. ` +
52
+ 'Create it (e.g. `GH_CONFIG_DIR=<dir> gh auth login`) or remove the key to use the default gh store.',
53
+ );
54
+ }
55
+ const inherited = env.GH_CONFIG_DIR;
56
+ if (inherited && path.resolve(inherited) !== dir) {
57
+ warn(
58
+ `[config] github.cliConfigDir (${dir}) overrides the inherited GH_CONFIG_DIR (${inherited}).`,
59
+ );
60
+ }
61
+ env.GH_CONFIG_DIR = dir;
62
+ return dir;
63
+ }
@@ -59,6 +59,7 @@ export const NOTIFICATIONS_DEFAULTS = Object.freeze({
59
59
  * projectNumber: number|null,
60
60
  * projectOwner: string|null,
61
61
  * operatorHandle: string|null,
62
+ * cliConfigDir: string|null,
62
63
  * branchProtection: { enforce: boolean, requiredChecks: Array<{name:string,cmd:readonly string[]}> },
63
64
  * mergeMethods: typeof MERGE_METHODS_DEFAULTS,
64
65
  * notifications: typeof NOTIFICATIONS_DEFAULTS,
@@ -81,6 +82,7 @@ export function getGitHub(config) {
81
82
  projectNumber: gh.projectNumber ?? null,
82
83
  projectOwner: gh.projectOwner ?? null,
83
84
  operatorHandle: gh.operatorHandle ?? null,
85
+ cliConfigDir: gh.cliConfigDir ?? null,
84
86
  branchProtection: {
85
87
  enforce:
86
88
  typeof userBranchProtection.enforce === 'boolean'
@@ -1,6 +1,6 @@
1
1
  /**
2
- * `project.paths` accessor; every `*Root` subdirectory and `auditOutputDir`
3
- * is derived from `agentRoot` / `tempRoot`.
2
+ * `project.paths` accessor; every `*Root` subdirectory, `auditOutputDir` and
3
+ * `auditResultsDir` is derived from `agentRoot` / `tempRoot`.
4
4
  */
5
5
 
6
6
  export const PATHS_DEFAULTS = Object.freeze({
@@ -9,6 +9,16 @@ export const PATHS_DEFAULTS = Object.freeze({
9
9
  tempRoot: 'temp',
10
10
  });
11
11
 
12
+ /**
13
+ * Audit working area and its reports-only subfolder.
14
+ *
15
+ * @param {string} tempRoot
16
+ */
17
+ function auditDirs(tempRoot) {
18
+ const auditOutputDir = `${tempRoot}/audits`;
19
+ return { auditOutputDir, auditResultsDir: `${auditOutputDir}/audit-results` };
20
+ }
21
+
12
22
  /**
13
23
  * @param {object|undefined} userPaths
14
24
  * @returns {{
@@ -16,6 +26,7 @@ export const PATHS_DEFAULTS = Object.freeze({
16
26
  * docsRoot: string,
17
27
  * tempRoot: string,
18
28
  * auditOutputDir: string,
29
+ * auditResultsDir: string,
19
30
  * scriptsRoot: string,
20
31
  * workflowsRoot: string,
21
32
  * schemasRoot: string,
@@ -33,7 +44,7 @@ export function resolvePaths(userPaths) {
33
44
  agentRoot,
34
45
  docsRoot,
35
46
  tempRoot,
36
- auditOutputDir: `${tempRoot}/audits`,
47
+ ...auditDirs(tempRoot),
37
48
  scriptsRoot: `${agentRoot}/scripts`,
38
49
  workflowsRoot: `${agentRoot}/workflows`,
39
50
  schemasRoot: `${agentRoot}/schemas`,
@@ -89,6 +89,7 @@ const CRAP_GATE_KEYS = new Set([
89
89
  'baselinePath',
90
90
  'tolerance',
91
91
  'floors',
92
+ 'components',
92
93
  'targetDirs',
93
94
  'newMethodCeiling',
94
95
  'requireCoverage',
@@ -102,6 +103,7 @@ const COVERAGE_GATE_KEYS = new Set([
102
103
  'baselinePath',
103
104
  'tolerance',
104
105
  'floors',
106
+ 'components',
105
107
  'coveragePath',
106
108
  'captureScope',
107
109
  'timeoutMs',
@@ -112,6 +114,7 @@ const MI_GATE_KEYS = new Set([
112
114
  'baselinePath',
113
115
  'tolerance',
114
116
  'floors',
117
+ 'components',
115
118
  'targetDirs',
116
119
  'ignoreGlobs',
117
120
  ]);
@@ -400,14 +403,15 @@ export function resolveQuality(userQuality) {
400
403
 
401
404
  /**
402
405
  * The writer folds sub-epsilon row deltas back to the prior bytes so env
403
- * variance never rewrites a baseline. bundle-size is bytes.
406
+ * variance never rewrites a baseline. Each value is in its kind's row unit:
407
+ * bundle-size rows are KB, so 1 means "ignore sub-KB jitter".
404
408
  */
405
409
  const BASELINE_EPSILON = Object.freeze({
406
410
  maintainability: 0.5,
407
411
  crap: 0.5,
408
412
  coverage: 0.1,
409
413
  mutation: 0.5,
410
- 'bundle-size': 1024,
414
+ 'bundle-size': 1,
411
415
  duplication: 0.5,
412
416
  });
413
417
 
@@ -12,6 +12,7 @@ import {
12
12
  } from './config/agentrc-overlay.js';
13
13
  import { getCiDelivery } from './config/ci.js';
14
14
  import { getCommands } from './config/commands.js';
15
+ import { applyGhConfigDir } from './config/gh-config-dir.js';
15
16
  import { getGitHub } from './config/github.js';
16
17
  import { resolvePaths } from './config/paths.js';
17
18
  import { validateOrchestrationConfig } from './config/validate-orchestration.js';
@@ -52,9 +53,9 @@ export {
52
53
  } from './config/worktree-isolation.js';
53
54
  export { PROJECT_ROOT } from './project-root.js';
54
55
 
55
- // Cache keyed by absolute root path so callers passing different cwds
56
- // (e.g. per-worktree) each get their own resolved config.
57
- const _cacheByRoot = new Map();
56
+ // Keyed by absolute root + validate mode, so per-worktree cwds and a
57
+ // `validate: false` read never answer a validating caller.
58
+ const _cacheByKey = new Map();
58
59
  const _envLoadedRoots = new Set();
59
60
 
60
61
  /**
@@ -137,79 +138,92 @@ function applyDefaults(raw) {
137
138
  }
138
139
 
139
140
  /**
140
- * Returns `{ project, github, planning, delivery, qa?, raw, source }`. A
141
- * missing file falls back to defaults; malformed JSON or a schema failure
142
- * throws.
141
+ * The merged raw config and a human description of where it came from;
142
+ * `raw: null` when neither file exists (zero-config).
143
143
  *
144
- * @param {{ bustCache?: boolean, cwd?: string, validate?: boolean, ctx?: object }} [opts]
144
+ * @param {import('node:fs')} fsImpl
145
+ * @param {string} root
146
+ * @returns {{ raw: object|null, source: string }}
145
147
  */
146
- export function resolveConfig(opts) {
147
- const envCwd = process.env.AP_AGENTRC_CWD;
148
- const root = path.resolve(opts?.cwd ?? envCwd ?? PROJECT_ROOT);
149
- const validate = opts?.validate !== false;
150
- const fsImpl = opts?.ctx?.fs ?? fs;
151
-
152
- if (!opts?.bustCache && _cacheByRoot.has(root)) {
153
- return _cacheByRoot.get(root);
154
- }
155
-
156
- if (!_envLoadedRoots.has(root)) {
157
- loadEnv(root);
158
- _envLoadedRoots.add(root);
159
- }
160
-
148
+ function readRawConfig(fsImpl, root) {
161
149
  const agentrcPath = path.join(root, '.agentrc.json');
162
150
  const localPath = path.join(root, '.agentrc.local.json');
163
151
  const hasAgentrc = fsImpl.existsSync(agentrcPath);
164
152
  const hasLocal = fsImpl.existsSync(localPath);
165
-
166
- if (!hasAgentrc && !hasLocal) {
167
- const blocks = applyDefaults({ ...ZERO_CONFIG_RAW });
168
- const resolved = {
169
- ...blocks,
170
- raw: null,
171
- source: 'built-in defaults',
153
+ if (!hasAgentrc) {
154
+ if (!hasLocal) return { raw: null, source: 'built-in defaults' };
155
+ return {
156
+ raw: deepMergeObjects(
157
+ { ...ZERO_CONFIG_RAW },
158
+ readJsonConfigFile(fsImpl, localPath, '.agentrc.local.json'),
159
+ ),
160
+ source: `${localPath} (overrides built-in defaults)`,
172
161
  };
173
- _cacheByRoot.set(root, resolved);
174
- return resolved;
175
- }
176
-
177
- let raw = hasAgentrc
178
- ? readJsonConfigFile(fsImpl, agentrcPath, '.agentrc.json')
179
- : { ...ZERO_CONFIG_RAW };
180
-
181
- let source = hasAgentrc ? agentrcPath : 'built-in defaults';
182
-
183
- if (hasLocal) {
184
- const localRaw = readJsonConfigFile(
185
- fsImpl,
186
- localPath,
187
- '.agentrc.local.json',
188
- );
189
- raw = deepMergeObjects(raw, localRaw);
190
- source =
191
- source === 'built-in defaults'
192
- ? `${localPath} (overrides built-in defaults)`
193
- : `${localPath} (overrides ${agentrcPath})`;
194
162
  }
163
+ const raw = readJsonConfigFile(fsImpl, agentrcPath, '.agentrc.json');
164
+ if (!hasLocal) return { raw, source: agentrcPath };
165
+ return {
166
+ raw: deepMergeObjects(
167
+ raw,
168
+ readJsonConfigFile(fsImpl, localPath, '.agentrc.local.json'),
169
+ ),
170
+ source: `${localPath} (overrides ${agentrcPath})`,
171
+ };
172
+ }
195
173
 
196
- if (validate) {
197
- const validateAgentrc = getAgentrcValidator();
198
- if (!validateAgentrc(raw)) {
199
- const details = formatAgentrcErrors(validateAgentrc.errors).join(', ');
200
- throw new Error(`[config] Invalid .agentrc.json: ${details}`);
201
- }
174
+ /** @param {object} raw */
175
+ function assertSchemaValid(raw) {
176
+ const validateAgentrc = getAgentrcValidator();
177
+ if (!validateAgentrc(raw)) {
178
+ const details = formatAgentrcErrors(validateAgentrc.errors).join(', ');
179
+ throw new Error(`[config] Invalid .agentrc.json: ${details}`);
202
180
  }
181
+ }
203
182
 
204
- const blocks = applyDefaults(raw);
183
+ /**
184
+ * Defaults applied over `raw`; a zero-config read is never validated.
185
+ *
186
+ * @param {{ raw: object|null, source: string }} read
187
+ * @param {boolean} validate
188
+ */
189
+ function finalizeConfig({ raw, source }, validate) {
190
+ const checked = validate && raw !== null;
191
+ if (checked) assertSchemaValid(raw);
192
+ const blocks = applyDefaults(raw ?? { ...ZERO_CONFIG_RAW });
193
+ if (checked) validateOrchestrationConfig(blocks);
194
+ return { ...blocks, raw, source };
195
+ }
205
196
 
206
- if (validate) validateOrchestrationConfig(blocks);
197
+ function ensureEnvLoaded(root) {
198
+ if (_envLoadedRoots.has(root)) return;
199
+ loadEnv(root);
200
+ _envLoadedRoots.add(root);
201
+ }
207
202
 
208
- const resolved = {
209
- ...blocks,
210
- raw,
211
- source,
212
- };
213
- _cacheByRoot.set(root, resolved);
203
+ /**
204
+ * Returns `{ project, github, planning, delivery, qa?, raw, source }`. A
205
+ * missing file falls back to defaults; malformed JSON or a schema failure
206
+ * throws. A set `github.cliConfigDir` is applied to `GH_CONFIG_DIR`. A call with an injected `ctx.fs` neither reads nor fills the
207
+ * shared cache.
208
+ *
209
+ * @param {{ bustCache?: boolean, cwd?: string, validate?: boolean, ctx?: object }} [opts]
210
+ */
211
+ export function resolveConfig(opts) {
212
+ const root = path.resolve(
213
+ opts?.cwd ?? process.env.AP_AGENTRC_CWD ?? PROJECT_ROOT,
214
+ );
215
+ const validate = opts?.validate !== false;
216
+ const injectedFs = opts?.ctx?.fs;
217
+ const key = `${root}\0${validate}`;
218
+ if (!injectedFs && !opts?.bustCache && _cacheByKey.has(key)) {
219
+ return _cacheByKey.get(key);
220
+ }
221
+ ensureEnvLoaded(root);
222
+ const resolved = finalizeConfig(
223
+ readRawConfig(injectedFs ?? fs, root),
224
+ validate,
225
+ );
226
+ applyGhConfigDir(resolved.github, root, { fsImpl: injectedFs ?? fs });
227
+ if (!injectedFs) _cacheByKey.set(key, resolved);
214
228
  return resolved;
215
229
  }
@@ -183,7 +183,7 @@ const WORKTREE_ISOLATION_SCHEMA = {
183
183
  const MERGE_WATCH_SCHEMA = {
184
184
  type: 'object',
185
185
  description:
186
- "Knobs consumed by the close-and-land merge wait (Story #4543). `mode` (Story #4698) selects the close-time merge posture. `maxWaitSeconds` bounds ONE invocation of the merge wait and its expiry returns a resumable `pending` terminal with no label mutation; `maxBudgetSeconds` bounds the CUMULATIVE wait across resumes (anchored at the PR's createdAt, so a resume does not restart the clock) and exhausting it is the genuine give-up that classifies and blocks. The poll cadence is internal (at most 30s while checks run, at most 10s once they are green and the PR is unmerged); it and the cap of 3 behind-the-base updates are not configurable.",
186
+ "Knobs consumed by the close-and-land merge wait (Story #4543). `mode` (Story #4698) selects the close-time merge posture. `maxWaitSeconds` bounds ONE invocation of the merge wait and its expiry returns a resumable `pending` terminal with no label mutation; `maxBudgetSeconds` bounds the CUMULATIVE wait across resumes (anchored at the later of the PR's createdAt and its latest auto-merge arm, so a `--wait` resume does not restart the clock while a re-close that re-arms gets a fresh budget) and exhausting it is the genuine give-up that classifies and blocks. The poll cadence is internal (at most 30s while checks run, at most 10s once they are green and the PR is unmerged); it and the cap of 3 behind-the-base updates are not configurable.",
187
187
  properties: {
188
188
  mode: {
189
189
  type: 'string',
@@ -201,7 +201,7 @@ const MERGE_WATCH_SCHEMA = {
201
201
  type: 'integer',
202
202
  minimum: 1,
203
203
  description:
204
- "Cumulative wall-clock budget (seconds) across merge-wait resumes, anchored at the PR's createdAt. Default 3600 (60 minutes). Exhausting this classifies the block and transitions the Story to agent::blocked.",
204
+ "Cumulative wall-clock budget (seconds) across merge-wait resumes, anchored at the later of the PR's createdAt and its latest auto-merge arm (`autoMergeRequest.enabledAt`), so a re-close that re-arms starts a fresh budget; without an arm time it falls back to createdAt, then to the invocation start. Default 3600 (60 minutes). Exhausting this classifies the block and transitions the Story to agent::blocked.",
205
205
  default: 3600,
206
206
  },
207
207
  },
@@ -368,7 +368,8 @@ const TEMP_RETENTION_SCHEMA = {
368
368
  },
369
369
  auditResults: {
370
370
  type: 'boolean',
371
- description: '<tempRoot>/audits/ — audit lens reports.',
371
+ description:
372
+ '<tempRoot>/audits/ — audit lens reports (audit-results/) and audit working artifacts.',
372
373
  default: true,
373
374
  },
374
375
  planDirs: {
@@ -351,6 +351,13 @@ const GITHUB_SCHEMA = {
351
351
  'The human the framework escalates to, `@`-prefixed. Used for HITL @-mentions on `agent::blocked`.',
352
352
  default: '@[USERNAME]',
353
353
  },
354
+ cliConfigDir: {
355
+ type: ['string', 'null'],
356
+ minLength: 1,
357
+ description:
358
+ "Dedicated `gh` credential store (`GH_CONFIG_DIR`) for this project, set in the gitignored `.agentrc.local.json`. Relative paths resolve against the project root and a leading `~` expands to the home directory; the directory must exist. When set, every `gh` call Mandrel makes runs with `GH_CONFIG_DIR` pointed at it. `null` keeps `gh`'s default store.",
359
+ default: null,
360
+ },
354
361
  followUpRepos: FOLLOW_UP_REPOS_SCHEMA,
355
362
  branchProtection: BRANCH_PROTECTION_SCHEMA,
356
363
  mergeMethods: MERGE_METHODS_SCHEMA,
@@ -7,10 +7,13 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import picomatch from 'picomatch';
9
9
  import { write, writeFile } from './baselines/writer.js';
10
- import { captureStampPath } from './coverage-capture.js';
10
+ import {
11
+ captureStampPath,
12
+ MissingCoverageArtifactError,
13
+ } from './coverage-capture.js';
11
14
 
12
15
  const COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';
13
- export const COVERAGE_BASELINE_PATH = 'baselines/coverage.json';
16
+ const COVERAGE_BASELINE_PATH = 'baselines/coverage.json';
14
17
  // Percentage points; baselines store two decimals.
15
18
  export const COVERAGE_TOLERANCE = 0.01;
16
19
  // One instrumentation event of slack per axis: V8 coverage flaps by a single
@@ -84,7 +87,7 @@ export function scoreCoverageFinal({ raw, cwd, scope }) {
84
87
  return out;
85
88
  }
86
89
 
87
- /** Throws, naming the capture command, when the artifact is missing. */
90
+ /** Throws, naming the capture contract, when the artifact is missing. */
88
91
  export function readCoverageFinal(cwd, opts = {}, fsImpl) {
89
92
  const resolvedFs = fsImpl ?? fs;
90
93
  const coveragePath =
@@ -95,9 +98,7 @@ export function readCoverageFinal(cwd, opts = {}, fsImpl) {
95
98
  ? coveragePath
96
99
  : path.resolve(cwd, coveragePath);
97
100
  if (!resolvedFs.existsSync(abs)) {
98
- throw new Error(
99
- `coverage-final.json not found at ${abs}. Run \`npm run test:coverage\` first.`,
100
- );
101
+ throw new MissingCoverageArtifactError(abs);
101
102
  }
102
103
  return JSON.parse(resolvedFs.readFileSync(abs, 'utf8'));
103
104
  }
@@ -478,6 +478,65 @@ export function creditedCapture(runCaptureFn, { requireCredited, logger }) {
478
478
  };
479
479
  }
480
480
 
481
+ /**
482
+ * The capture contract every coverage consumer leans on: `test:coverage`
483
+ * writes Istanbul per-file JSON at `coveragePath`. A summary-only reporter
484
+ * cannot feed the coverage or CRAP baselines (CRAP joins per-function maps).
485
+ *
486
+ * @param {string} abs Absolute artifact path that was looked for.
487
+ * @returns {string}
488
+ */
489
+ function missingCoverageArtifactMessage(abs) {
490
+ return (
491
+ `coverage artifact not found at ${abs}. \`npm run test:coverage\` must ` +
492
+ 'write Istanbul per-file JSON (the `json` reporter → coverage-final.json) ' +
493
+ 'at delivery.quality.gates.coverage.coveragePath; a `json-summary` ' +
494
+ '(coverage-summary.json) alone cannot feed the coverage or CRAP baselines.'
495
+ );
496
+ }
497
+
498
+ /**
499
+ * Fatal on every scope: zero scored rows would let the scope merge delete the
500
+ * in-scope rows.
501
+ */
502
+ export class MissingCoverageArtifactError extends Error {
503
+ constructor(abs, { prefix = '', cause } = {}) {
504
+ super(
505
+ `${prefix}${missingCoverageArtifactMessage(abs)}`,
506
+ cause === undefined ? undefined : { cause },
507
+ );
508
+ this.name = 'MissingCoverageArtifactError';
509
+ this.artifactPath = abs;
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Wrap a capture runner so a green run that left no artifact at
515
+ * `coveragePath` exits 1: a broken capture contract, not a capture. Every
516
+ * capture path already returns before stamping on a non-zero code.
517
+ *
518
+ * @param {(opts: object) => Promise<number>} run
519
+ * @param {{ cwd: string, coveragePath: string,
520
+ * existsSync?: (p: string) => boolean,
521
+ * logger: { error: Function } }} opts
522
+ * @returns {(opts: object) => Promise<number>}
523
+ */
524
+ export function requireCaptureArtifact(
525
+ run,
526
+ { cwd, coveragePath, existsSync = fs.existsSync, logger },
527
+ ) {
528
+ return async (captureOpts) => {
529
+ const code = await run(captureOpts);
530
+ if (code !== 0) return code;
531
+ const abs = path.resolve(cwd, coveragePath);
532
+ if (existsSync(abs)) return 0;
533
+ logger.error(
534
+ `[coverage-capture] ✖ test:coverage passed but ${missingCoverageArtifactMessage(abs)}`,
535
+ );
536
+ return 1;
537
+ };
538
+ }
539
+
481
540
  /**
482
541
  * Stamp the pre-spawn digest (the tree the run measured), and write nothing
483
542
  * when the post-run digest differs — the artifact then describes a tree no
@@ -14,6 +14,8 @@ import { analyzeModule } from './escomplex-kernel.js';
14
14
  import { Logger } from './Logger.js';
15
15
  import { scanDirectory } from './maintainability-utils.js';
16
16
  import {
17
+ CompilerMissingError,
18
+ preparedFailureFields,
17
19
  prepareSourceForScoring,
18
20
  resolveTsTranspilerVersion,
19
21
  } from './transpile.js';
@@ -272,12 +274,58 @@ function projectScanRow(relPath, mr) {
272
274
  };
273
275
  }
274
276
 
277
+ /** Fold per-file results; missing compilers throw one CompilerMissingError. */
278
+ function tallyScanResults(perFile, cwd) {
279
+ const rows = [];
280
+ let skippedFilesNoCoverage = 0;
281
+ let skippedMethodsNoCoverage = 0;
282
+ let unscorableFiles = 0;
283
+ const missingCompilerDirs = [];
284
+ const resolution = newResolutionAccumulator();
285
+ for (const { item, result } of perFile) {
286
+ if (result?.compilerMissing) {
287
+ missingCompilerDirs.push(result.packageDir);
288
+ continue;
289
+ }
290
+ if (result?.skippedFileNoCoverage) {
291
+ skippedFilesNoCoverage += 1;
292
+ continue;
293
+ }
294
+ // `!result` is a pool-level error the worker never answered.
295
+ if (!result || result.rows === null) {
296
+ unscorableFiles += 1;
297
+ if (result?.error) {
298
+ Logger.warn(
299
+ `[crap-utils] failed to score ${item.relPath}: ${result.error}`,
300
+ );
301
+ }
302
+ continue;
303
+ }
304
+ skippedMethodsNoCoverage += result.skippedMethodsNoCoverage ?? 0;
305
+ accumulateResolution(resolution, item.relPath, result);
306
+ for (const mr of result.rows) {
307
+ rows.push(projectScanRow(item.relPath, mr));
308
+ }
309
+ }
310
+ if (missingCompilerDirs.length > 0) {
311
+ throw new CompilerMissingError(missingCompilerDirs, { cwd });
312
+ }
313
+ return {
314
+ rows,
315
+ skippedFilesNoCoverage,
316
+ skippedMethodsNoCoverage,
317
+ unscorableFiles,
318
+ resolution: summarizeResolution(resolution),
319
+ };
320
+ }
321
+
275
322
  /**
276
323
  * Score every method under `targetDirs` (no disk writes). Files without
277
324
  * coverage are skipped under `requireCoverage`; methods without resolvable
278
325
  * coverage are always dropped, so baselines never hold partial rows. A file
279
326
  * that cannot be read, transpiled or parsed is counted in `unscorableFiles`
280
- * so no drop is silent. `scopeFiles` filters before any I/O;
327
+ * so no drop is silent; a TypeScript file with no resolvable compiler throws
328
+ * `CompilerMissingError` instead. `scopeFiles` filters before any I/O;
281
329
  * `preScannedFiles` skips the walk; `incremental` resolves untouched files
282
330
  * from the baseline instead of fresh coverage.
283
331
  *
@@ -351,52 +399,16 @@ export async function scanAndScore({
351
399
  ? queue.map((item) => ({ item, result: scoreFileSerial(item, coverage) }))
352
400
  : await scoreFilesViaPool(queue, coverage);
353
401
 
354
- const rows = [];
355
- let skippedFilesNoCoverage = 0;
356
- let skippedMethodsNoCoverage = 0;
357
- let unscorableFiles = 0;
358
- const resolution = newResolutionAccumulator();
359
- for (const { item, result } of perFile) {
360
- if (!result) {
361
- // Pool-level error the worker never answered.
362
- unscorableFiles += 1;
363
- continue;
364
- }
365
- if (result.skippedFileNoCoverage) {
366
- skippedFilesNoCoverage += 1;
367
- continue;
368
- }
369
- if (result.rows === null) {
370
- unscorableFiles += 1;
371
- if (result.error) {
372
- Logger.warn(
373
- `[crap-utils] failed to score ${item.relPath}: ${result.error}`,
374
- );
375
- }
376
- continue;
377
- }
378
- skippedMethodsNoCoverage += result.skippedMethodsNoCoverage ?? 0;
379
- accumulateResolution(resolution, item.relPath, result);
380
- for (const mr of result.rows) {
381
- rows.push(projectScanRow(item.relPath, mr));
382
- }
383
- }
384
-
385
- rows.sort((a, b) => {
386
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
387
- if (a.startLine !== b.startLine) return a.startLine - b.startLine;
388
- if (a.method !== b.method) return a.method < b.method ? -1 : 1;
389
- return 0;
390
- });
402
+ const tally = tallyScanResults(perFile, cwd);
403
+ tally.rows.sort(compareScanRows);
404
+ return { ...tally, scannedFiles };
405
+ }
391
406
 
392
- return {
393
- rows,
394
- scannedFiles,
395
- skippedFilesNoCoverage,
396
- skippedMethodsNoCoverage,
397
- unscorableFiles,
398
- resolution: summarizeResolution(resolution),
399
- };
407
+ function compareScanRows(a, b) {
408
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
409
+ if (a.startLine !== b.startLine) return a.startLine - b.startLine;
410
+ if (a.method !== b.method) return a.method < b.method ? -1 : 1;
411
+ return 0;
400
412
  }
401
413
 
402
414
  /** In-process scorer; the reference the worker output must match exactly. */
@@ -433,7 +445,7 @@ function scoreFileSerial(
433
445
  totalMethods: 0,
434
446
  };
435
447
  const prepared = prepareSourceForScoring(abs);
436
- if (prepared.error) return dropped;
448
+ if (prepared.error) return { ...dropped, ...preparedFailureFields(prepared) };
437
449
  const { crapRows, parseError } = analyzeOnce(
438
450
  prepared.code,
439
451
  entry,
@@ -26,6 +26,7 @@ import {
26
26
  resolveAdmission,
27
27
  resolveSuiteCapacity,
28
28
  } from './suite-admission.js';
29
+ import { defaultSleep } from './util/sleep.js';
29
30
 
30
31
  export { ADMISSION_REFUSED_EXIT_CODE };
31
32
 
@@ -281,16 +282,6 @@ function reportCompleted(opts, wait, ranMs) {
281
282
  } catch {}
282
283
  }
283
284
 
284
- /**
285
- * @param {number} ms
286
- * @returns {Promise<void>}
287
- */
288
- function defaultSleep(ms) {
289
- return new Promise((resolve) => {
290
- setTimeout(resolve, ms);
291
- });
292
- }
293
-
294
285
  /**
295
286
  * The one admission policy every caller resolves: enablement, budget,
296
287
  * capacity, and the workload `argv` classifies to.
@@ -48,6 +48,16 @@ function defaultReadFromTree({ baselinePath, projectRoot } = {}) {
48
48
  return JSON.parse(fs.readFileSync(abs, 'utf8'));
49
49
  }
50
50
 
51
+ /** Ratchet-gate read: `null` when missing, unparseable or not an object. */
52
+ export function readJsonBaseline(baselinePath) {
53
+ try {
54
+ const parsed = defaultReadFromTree({ baselinePath });
55
+ return parsed && typeof parsed === 'object' ? parsed : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
51
61
  /**
52
62
  * A gate may supply `readFromTree` for a "missing → empty" bootstrap (MI
53
63
  * returns `{}`); the default throws `BaselineNotFoundError`.