mandrel 2.90.0 → 2.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +31 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/check-arch-cycles.js +1 -5
  14. package/.agents/scripts/check-context-budget.js +1 -5
  15. package/.agents/scripts/check-cyclomatic.js +1 -5
  16. package/.agents/scripts/check-dead-exports.js +23 -14
  17. package/.agents/scripts/check-doc-links.js +4 -4
  18. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  19. package/.agents/scripts/coverage-capture.js +14 -6
  20. package/.agents/scripts/diagnose-friction.js +8 -10
  21. package/.agents/scripts/generate-workflows-doc.js +5 -0
  22. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  24. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  25. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  26. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  27. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  28. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  29. package/.agents/scripts/lib/baselines/components.js +5 -5
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  32. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  33. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  34. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  36. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  37. package/.agents/scripts/lib/baselines/writer.js +4 -4
  38. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  39. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  40. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  41. package/.agents/scripts/lib/child-exec.js +4 -4
  42. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  43. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  44. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  45. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  46. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  47. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  48. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  49. package/.agents/scripts/lib/config/commands.js +82 -7
  50. package/.agents/scripts/lib/config/explain.js +2 -1
  51. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  52. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  53. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  54. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  55. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  56. package/.agents/scripts/lib/config/git-roots.js +120 -0
  57. package/.agents/scripts/lib/config/quality.js +46 -50
  58. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  59. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  60. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  61. package/.agents/scripts/lib/config-resolver.js +5 -9
  62. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  63. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  64. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  65. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  67. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  68. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  69. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  70. package/.agents/scripts/lib/coverage-capture.js +31 -20
  71. package/.agents/scripts/lib/coverage-utils.js +34 -16
  72. package/.agents/scripts/lib/cpu-pool.js +2 -4
  73. package/.agents/scripts/lib/crap-engine.js +19 -1
  74. package/.agents/scripts/lib/crap-utils.js +2 -1
  75. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  76. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  77. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  78. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  79. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  80. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  81. package/.agents/scripts/lib/gh-env.js +72 -0
  82. package/.agents/scripts/lib/gh-exec.js +26 -1
  83. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  84. package/.agents/scripts/lib/npm-scripts.js +1 -1
  85. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  86. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  87. package/.agents/scripts/lib/orchestration/board-access-latch.js +19 -8
  88. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  89. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  90. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  91. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  92. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  93. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  94. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  95. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  96. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  97. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  98. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  99. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  100. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  101. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  102. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  103. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  104. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  105. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +4 -1
  106. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +49 -83
  107. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  108. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  109. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  110. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  111. package/.agents/scripts/lib/orchestration/story-handoff.js +13 -5
  112. package/.agents/scripts/lib/orchestration/story-init-result.js +11 -0
  113. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  114. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  115. package/.agents/scripts/lib/orchestration/ticketing/transition.js +47 -21
  116. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  117. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  118. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  119. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  120. package/.agents/scripts/lib/source-extensions.js +30 -15
  121. package/.agents/scripts/lib/test-run-credit.js +1 -9
  122. package/.agents/scripts/lib/test-temp.js +22 -21
  123. package/.agents/scripts/lib/util/ajv.js +111 -0
  124. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  125. package/.agents/scripts/lib/util/paths.js +51 -0
  126. package/.agents/scripts/lib/util/sleep.js +6 -0
  127. package/.agents/scripts/lib/util/slug.js +12 -0
  128. package/.agents/scripts/lib/validation-evidence.js +19 -40
  129. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  130. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  131. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  132. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  133. package/.agents/scripts/lint-issue-body.js +2 -2
  134. package/.agents/scripts/plan-context.js +2 -7
  135. package/.agents/scripts/providers/github/auth.js +3 -3
  136. package/.agents/scripts/providers/github/errors.js +3 -1
  137. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  138. package/.agents/scripts/providers/github/issues.js +6 -2
  139. package/.agents/scripts/providers/github/mappers.js +1 -5
  140. package/.agents/scripts/providers/github/projects-v2-graphql.js +11 -3
  141. package/.agents/scripts/providers/github/search-budget.js +3 -1
  142. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  143. package/.agents/scripts/single-story-init.js +18 -14
  144. package/.agents/scripts/sync-agentrc.js +5 -14
  145. package/.agents/scripts/sync-claude-agents.js +38 -150
  146. package/.agents/scripts/sync-claude-commands.js +35 -218
  147. package/.agents/scripts/update-coverage-baseline.js +1 -1
  148. package/.agents/scripts/update-crap-baseline.js +1 -1
  149. package/.agents/scripts/update-duplication-baseline.js +2 -16
  150. package/.agents/scripts/validate-skills.js +6 -10
  151. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  152. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  153. package/.agents/workflows/audit-exceptions.md +9 -0
  154. package/.agents/workflows/audit-lean.md +129 -0
  155. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  156. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  157. package/.agents/workflows/helpers/code-review.md +15 -1
  158. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  159. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  160. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  161. package/.agents/workflows/mandrel-plan.md +2 -2
  162. package/docs/CHANGELOG.md +42 -0
  163. package/lib/cli/doctor-checks/codex.js +6 -5
  164. package/lib/cli/doctor-checks/llm-review.js +102 -0
  165. package/lib/cli/doctor-checks/project-access.js +20 -10
  166. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  167. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  168. package/lib/cli/doctor-checks/toolchain.js +5 -3
  169. package/lib/cli/registry.js +5 -0
  170. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  171. package/lib/migrations/index.js +6 -0
  172. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  173. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  174. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  175. package/package.json +1 -3
@@ -4,16 +4,37 @@
4
4
  * per-file baseline so a `baseline-refresh:` commit can ship with the PR.
5
5
  */
6
6
 
7
+ import path from 'node:path';
7
8
  import { getBaseline } from '../../baselines/maintainability-baseline-io.js';
8
9
  import { diffNameOnly } from '../../changed-files.js';
9
10
  import { cachedGitFetchSync } from '../../git/cached-fetch.js';
10
11
  import { gitSpawn as defaultGitSpawn } from '../../git-utils.js';
11
12
  import { calculateForSource } from '../../maintainability-engine.js';
13
+ import { reportUnscorable } from '../../maintainability-unscorable.js';
14
+ import { isScorableSourceFile } from '../../source-extensions.js';
15
+ import { transpileForReport } from '../../transpile.js';
12
16
  import { MISSING_ARG_REASONS, validateProjectionInputs } from './inputs.js';
13
17
 
14
18
  /** Absorbs floating-point noise. */
15
19
  export const DEFAULT_MI_TOLERANCE = 0.001;
16
20
 
21
+ const UNSCORABLE_TRANSPILE_REASON =
22
+ 'transpile failed; no projected MI (lint and typecheck own the syntax error)';
23
+
24
+ /**
25
+ * TS is transpiled first, as the baseline scanner does, so a `.tsx` projects
26
+ * the score its baseline row holds. `null` when the transpile fails: no
27
+ * projection beats a phantom 0-score regression.
28
+ *
29
+ * @param {string} source
30
+ * @param {string} absPath Used only to pick the transpile mode and compiler.
31
+ * @returns {number | null}
32
+ */
33
+ function scoreHeadSource(source, absPath) {
34
+ const prepared = transpileForReport(absPath, source);
35
+ return prepared === null ? null : calculateForSource(prepared);
36
+ }
37
+
17
38
  /**
18
39
  * Collapse `missing-*` to the public `missing-args` reason.
19
40
  *
@@ -73,9 +94,9 @@ function diffChangedFiles({ cwd, baseBranch, storyBranch, git }) {
73
94
  * baselineScore: number,
74
95
  * tolerance: number,
75
96
  * git: { gitSpawn: typeof defaultGitSpawn },
76
- * scoreSource: (source: string) => number,
97
+ * scoreSource: (source: string, absPath: string) => number | null,
77
98
  * }} opts
78
- * @returns {{ file: string, projected: number, baseline: number, drop: number } | null}
99
+ * @returns {{ file: string, projected?: number, reason?: string } | null}
79
100
  */
80
101
  function scoreFile({
81
102
  cwd,
@@ -88,7 +109,8 @@ function scoreFile({
88
109
  }) {
89
110
  const show = git.gitSpawn(cwd, 'show', `${storyBranch}:${file}`);
90
111
  if (show.status !== 0) return null; // deleted/renamed on the story branch
91
- const projected = scoreSource(show.stdout || '');
112
+ const projected = scoreSource(show.stdout || '', path.join(cwd, file));
113
+ if (projected === null) return { file, reason: UNSCORABLE_TRANSPILE_REASON };
92
114
  if (projected >= baselineScore - tolerance) return null;
93
115
  return {
94
116
  file,
@@ -98,6 +120,10 @@ function scoreFile({
98
120
  };
99
121
  }
100
122
 
123
+ function bucketOf(outcome) {
124
+ return outcome.reason ? 'unscorable' : 'regressions';
125
+ }
126
+
101
127
  /**
102
128
  * @param {{
103
129
  * cwd: string,
@@ -106,9 +132,9 @@ function scoreFile({
106
132
  * baseline: Record<string, number>,
107
133
  * tolerance: number,
108
134
  * git: { gitSpawn: typeof defaultGitSpawn },
109
- * scoreSource: (source: string) => number,
135
+ * scoreSource: (source: string, absPath: string) => number | null,
110
136
  * }} opts
111
- * @returns {Array<{ file: string, projected: number, baseline: number, drop: number }>}
137
+ * @returns {{ regressions: object[], unscorable: object[] }}
112
138
  */
113
139
  function collectRegressions({
114
140
  cwd,
@@ -119,12 +145,12 @@ function collectRegressions({
119
145
  git,
120
146
  scoreSource,
121
147
  }) {
122
- const regressions = [];
148
+ const found = { regressions: [], unscorable: [] };
123
149
  for (const file of files) {
124
- if (!file.endsWith('.js') && !file.endsWith('.mjs')) continue;
150
+ if (!isScorableSourceFile(file)) continue;
125
151
  const baselineScore = baseline[file];
126
152
  if (typeof baselineScore !== 'number') continue;
127
- const reg = scoreFile({
153
+ const outcome = scoreFile({
128
154
  cwd,
129
155
  storyBranch,
130
156
  file,
@@ -133,15 +159,20 @@ function collectRegressions({
133
159
  git,
134
160
  scoreSource,
135
161
  });
136
- if (reg) regressions.push(reg);
162
+ if (outcome) found[bucketOf(outcome)].push(outcome);
137
163
  }
138
- return regressions;
164
+ return found;
165
+ }
166
+
167
+ function toUnscorableEntry({ file, reason }) {
168
+ return { relPath: file, unscorable: true, reason };
139
169
  }
140
170
 
141
171
  /**
142
172
  * Scores each changed file's content at the Story branch tip (exact for a
143
173
  * clean merge). Never throws; failures resolve to
144
- * `{ ok: true, regressions: [], skipped }`.
174
+ * `{ ok: true, regressions: [], skipped }`. An unscorable file is reported,
175
+ * never a regression.
145
176
  *
146
177
  * @param {{
147
178
  * cwd: string,
@@ -150,12 +181,14 @@ function collectRegressions({
150
181
  * baselinePath: string,
151
182
  * tolerance?: number,
152
183
  * git?: { gitSpawn: typeof defaultGitSpawn },
153
- * scoreSource?: (source: string) => number,
184
+ * scoreSource?: (source: string, absPath: string) => number | null,
154
185
  * loadBaseline?: (path: string) => Record<string, number>,
186
+ * report?: typeof reportUnscorable,
155
187
  * }} opts
156
188
  * @returns {{
157
189
  * ok: boolean,
158
190
  * regressions: Array<{ file: string, projected: number, baseline: number, drop: number }>,
191
+ * unscorable?: object[],
159
192
  * skipped?: string,
160
193
  * detail?: string,
161
194
  * }}
@@ -167,8 +200,9 @@ export function projectMaintainabilityRegressions({
167
200
  baselinePath,
168
201
  tolerance = DEFAULT_MI_TOLERANCE,
169
202
  git = { gitSpawn: defaultGitSpawn },
170
- scoreSource = calculateForSource,
203
+ scoreSource = scoreHeadSource,
171
204
  loadBaseline = getBaseline,
205
+ report = reportUnscorable,
172
206
  } = {}) {
173
207
  const validation = validateProjectionInputs(
174
208
  { cwd, baseBranch, storyBranch, baselinePath },
@@ -202,7 +236,7 @@ export function projectMaintainabilityRegressions({
202
236
  };
203
237
  }
204
238
 
205
- const regressions = collectRegressions({
239
+ const { regressions, unscorable } = collectRegressions({
206
240
  cwd,
207
241
  storyBranch,
208
242
  files: diffOutcome.files,
@@ -212,7 +246,8 @@ export function projectMaintainabilityRegressions({
212
246
  scoreSource,
213
247
  });
214
248
 
215
- return { ok: regressions.length === 0, regressions };
249
+ report(unscorable.map(toUnscorableEntry));
250
+ return { ok: regressions.length === 0, regressions, unscorable };
216
251
  }
217
252
 
218
253
  /**
@@ -4,13 +4,10 @@
4
4
  */
5
5
 
6
6
  import path from 'node:path';
7
+ import { isObject } from '../json-utils.js';
7
8
 
8
9
  const LOCAL_AGENTRC = '.agentrc.local.json';
9
10
 
10
- function isPlainObject(value) {
11
- return value !== null && typeof value === 'object' && !Array.isArray(value);
12
- }
13
-
14
11
  /**
15
12
  * Deep-merge plain objects for the overlay. Arrays and scalars from
16
13
  * `override` replace the base value at that key.
@@ -20,8 +17,8 @@ function isPlainObject(value) {
20
17
  * @returns {unknown}
21
18
  */
22
19
  export function deepMergeObjects(base, override) {
23
- if (!isPlainObject(override)) return override;
24
- if (!isPlainObject(base)) return { ...override };
20
+ if (!isObject(override)) return override;
21
+ if (!isObject(base)) return { ...override };
25
22
  const out = { ...base };
26
23
  for (const key of Object.keys(override)) {
27
24
  out[key] = mergeValue(base[key], override[key]);
@@ -30,7 +27,7 @@ export function deepMergeObjects(base, override) {
30
27
  }
31
28
 
32
29
  function mergeValue(baseVal, overrideVal) {
33
- if (isPlainObject(overrideVal) && isPlainObject(baseVal)) {
30
+ if (isObject(overrideVal) && isObject(baseVal)) {
34
31
  return deepMergeObjects(baseVal, overrideVal);
35
32
  }
36
33
  return overrideVal;
@@ -1,22 +1,97 @@
1
+ /**
2
+ * `project.commands.*` tri-state: absent → default; own-present `null` →
3
+ * disabled (optional gates only); string → that command. Anything else throws.
4
+ */
5
+
6
+ import { isObject } from '../json-utils.js';
7
+
8
+ /** `test` must stay byte-identical: every recorded `test` credit hashes it. */
1
9
  export const COMMANDS_DEFAULTS = Object.freeze({
2
10
  test: 'npm test',
3
- typecheck: null,
4
- lint: null,
11
+ typecheck: 'npm run typecheck',
12
+ lint: 'npm run lint',
5
13
  formatCheck: 'npx biome format .',
6
14
  formatWrite: 'npx biome format --write .',
7
15
  });
8
16
 
17
+ /** The gates an explicit `null` disables. */
18
+ const OPTIONAL_COMMAND_KEYS = Object.freeze([
19
+ 'typecheck',
20
+ 'lint',
21
+ 'formatCheck',
22
+ ]);
23
+
24
+ /** @param {string} raw */
25
+ function splitArgv(raw) {
26
+ return raw.split(/\s+/).filter(Boolean);
27
+ }
28
+
29
+ /** @param {string} detail */
30
+ function configError(detail) {
31
+ return new Error(`[config] project.commands${detail}.`);
32
+ }
33
+
34
+ /** @param {object|null|undefined} config */
35
+ function commandsBlock(config) {
36
+ const commands = config?.project?.commands;
37
+ if (commands === undefined) return {};
38
+ if (!isObject(commands)) {
39
+ throw configError(' must be an object of command strings');
40
+ }
41
+ return commands;
42
+ }
43
+
44
+ /** @param {string} raw @param {'default'|'config'} source */
45
+ function enabled(raw, source) {
46
+ return { argv: splitArgv(raw), raw, disabled: false, source };
47
+ }
48
+
49
+ /** @param {string} key */
50
+ function disabledCommand(key) {
51
+ if (!OPTIONAL_COMMAND_KEYS.includes(key)) {
52
+ throw configError(`.${key} cannot be null — that gate is mandatory`);
53
+ }
54
+ return { argv: [], raw: null, disabled: true, source: 'disabled' };
55
+ }
56
+
57
+ /** @param {string} key @param {unknown} value */
58
+ function configuredCommand(key, value) {
59
+ const raw = typeof value === 'string' ? value.trim() : '';
60
+ if (raw.length === 0) {
61
+ throw configError(`.${key} must be a non-empty command string`);
62
+ }
63
+ return enabled(raw, 'config');
64
+ }
65
+
66
+ /** @param {string} key */
67
+ function assertKnownKey(key) {
68
+ if (!Object.hasOwn(COMMANDS_DEFAULTS, key)) {
69
+ throw configError(`.${key} is not a known command`);
70
+ }
71
+ }
72
+
9
73
  /**
10
- * @param {object | null | undefined} config
11
- * @returns {{ test: string, typecheck: string|null, lint: string|null, formatCheck: string, formatWrite: string }}
74
+ * @param {object|null|undefined} config
75
+ * @param {keyof typeof COMMANDS_DEFAULTS} key
76
+ * @returns {{ argv: string[], raw: string|null, disabled: boolean, source: 'default'|'disabled'|'config' }}
12
77
  */
78
+ export function resolveProjectCommand(config, key) {
79
+ assertKnownKey(key);
80
+ const commands = commandsBlock(config);
81
+ if (!Object.hasOwn(commands, key) || commands[key] === undefined) {
82
+ return enabled(COMMANDS_DEFAULTS[key], 'default');
83
+ }
84
+ return commands[key] === null
85
+ ? disabledCommand(key)
86
+ : configuredCommand(key, commands[key]);
87
+ }
88
+
89
+ /** Projection over {@link resolveProjectCommand}; a disabled gate keeps `null`. */
13
90
  export function getCommands(config) {
14
- const commands = config?.project?.commands ?? {};
15
- // `??` is safe for the nullable keys: their default is `null` too.
16
91
  return Object.fromEntries(
17
92
  Object.keys(COMMANDS_DEFAULTS).map((key) => [
18
93
  key,
19
- commands[key] ?? COMMANDS_DEFAULTS[key],
94
+ resolveProjectCommand(config, key).raw,
20
95
  ]),
21
96
  );
22
97
  }
@@ -49,8 +49,9 @@ const KEY_MEANINGS = Object.freeze({
49
49
  "Test command close's `test` gate runs and its credit identity hashes.",
50
50
  'project.commands.typecheck':
51
51
  'Typecheck command (null disables the typecheck gate).',
52
+ 'project.commands.lint': 'Lint command (null disables the lint gate).',
52
53
  'project.commands.formatCheck':
53
- 'Format-verify command run without modifying files.',
54
+ 'Format-verify command run without modifying files (null disables the format gate).',
54
55
  'project.commands.formatWrite':
55
56
  'Format-write command that applies formatting in place.',
56
57
 
@@ -1,8 +1,36 @@
1
1
  /* node:coverage ignore file -- AJV schema declaration (data-as-code) */
2
2
 
3
- import { COVERAGE_GATE_DEFAULTS } from '../quality.js';
4
3
  import { gateBase, SAFE_STRING } from './shared.js';
5
4
 
5
+ /**
6
+ * The single home of the coverage capture literals: the script the coverage
7
+ * gate's capture runs, the consumer-owned `affected` variant, and the
8
+ * artifact path. Every other site imports these, never re-types them.
9
+ */
10
+ export const COVERAGE_CAPTURE_DEFAULTS = Object.freeze({
11
+ captureScript: 'test:coverage',
12
+ affectedCaptureScript: 'test:coverage:affected',
13
+ coveragePath: 'coverage/coverage-final.json',
14
+ });
15
+
16
+ /** Injected when a declared gate omits a workspace key (usually `'*'`). */
17
+ const DEFAULT_COVERAGE_FLOORS = Object.freeze({
18
+ '*': Object.freeze({ lines: 90, branches: 85, functions: 90 }),
19
+ });
20
+
21
+ export const COVERAGE_GATE_DEFAULTS = Object.freeze({
22
+ enabled: true,
23
+ baselinePath: 'baselines/coverage.json',
24
+ tolerance: Object.freeze({ kind: 'absolute', value: 0 }),
25
+ floors: DEFAULT_COVERAGE_FLOORS,
26
+ coveragePath: COVERAGE_CAPTURE_DEFAULTS.coveragePath,
27
+ captureScript: COVERAGE_CAPTURE_DEFAULTS.captureScript,
28
+ // `affected` runs the consumer's affected capture script instead.
29
+ captureScope: 'full',
30
+ // On expiry `runCapture` exits 124 so callers can tell a hang from a failure.
31
+ timeoutMs: 600_000,
32
+ });
33
+
6
34
  /** Schema bounds on `coverage.timeoutMs`: one minute to two hours. */
7
35
  export const COVERAGE_TIMEOUT_BOUNDS = Object.freeze({
8
36
  min: 60_000,
@@ -24,14 +52,22 @@ export const COVERAGE_GATE = {
24
52
  ...SAFE_STRING,
25
53
  minLength: 1,
26
54
  description:
27
- 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads. The capture contract: `npm run test:coverage` MUST write Istanbul per-file JSON (the `json` reporter) here — the coverage and CRAP refreshes both read it. A `json-summary` (`coverage-summary.json`) alone cannot feed them, so a green capture that leaves no file here fails and a full-scope refresh refuses to run.',
55
+ 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads. The capture contract: `captureScript` MUST write Istanbul per-file JSON (the `json` reporter) here — the coverage and CRAP refreshes both read it. A `json-summary` (`coverage-summary.json`) alone cannot feed them, so a green capture that leaves no file here fails and a full-scope refresh refuses to run. Its capture stamp sits beside it (`.capture-stamp.<file>.json`), so another artifact may share its directory.',
28
56
  default: COVERAGE_GATE_DEFAULTS.coveragePath,
29
57
  },
58
+ captureScript: {
59
+ type: 'string',
60
+ minLength: 1,
61
+ pattern: '^[A-Za-z0-9@:._/-]+$',
62
+ description: `\`package.json\` script (never a shell command) the coverage gate's capture runs, spawned as \`<pm> run <script>\` under the detected package manager (npm, pnpm, yarn or bun). Close registers the coverage-capture gate when the coverage or CRAP gate is enabled and this script exists; the full-suite lock's workload identity and \`mandrel doctor\`'s \`test-credit-path\` check follow it. Default \`${COVERAGE_CAPTURE_DEFAULTS.captureScript}\`.`,
63
+ default: COVERAGE_GATE_DEFAULTS.captureScript,
64
+ },
30
65
  captureScope: {
31
66
  type: 'string',
32
67
  enum: ['full', 'affected'],
33
68
  description:
34
- 'What coverage-capture runs. `full` (default) runs `npm run test:coverage`. `affected` runs the consumer-owned `npm run test:coverage:affected` with the base ref in `MANDREL_COVERAGE_BASE_REF`, merges its rows over the prior artifact and stamps it `affected`; baseline rows the scoped run did not measure are treated as unmeasured, never removed. Falls back to `full` with a warning when the script is absent. Meant for consumers whose CI already enforces coverage on the full suite.',
69
+ `What coverage-capture runs. \`full\` (default) runs \`captureScript\`. \`affected\` runs the consumer-owned \`${COVERAGE_CAPTURE_DEFAULTS.affectedCaptureScript}\` script` +
70
+ ' with the base ref in `MANDREL_COVERAGE_BASE_REF`, merges its rows over the prior artifact and stamps it `affected`; baseline rows the scoped run did not measure are treated as unmeasured, never removed. Falls back to `full` with a warning when the script is absent. Meant for consumers whose CI already enforces coverage on the full suite.',
35
71
  default: COVERAGE_GATE_DEFAULTS.captureScope,
36
72
  },
37
73
  timeoutMs: {
@@ -7,7 +7,7 @@
7
7
  export const INCREMENTAL_COVERAGE_SCHEMA = {
8
8
  type: 'object',
9
9
  description:
10
- 'The two independent full-suite economies (Story #4981, split by Story #5173). `skipWhenUnchanged` (default true) decides WHETHER to capture — no changed file under `crap.targetDirs` versus `baseRef` means no capture at all — and is a pure saving. `baselineJoin` (default false) loosens gate semantics: the CRAP join resolves a method in an untouched file from its committed baseline row instead of requiring fresh coverage for it. Neither narrows the capture run itself: a capture that does happen is the ordinary full `npm run test:coverage` (Story #5065).',
10
+ "The two independent full-suite economies (Story #4981, split by Story #5173). `skipWhenUnchanged` (default true) decides WHETHER to capture — no changed file under `crap.targetDirs` versus `baseRef` means no capture at all — and is a pure saving. `baselineJoin` (default false) loosens gate semantics: the CRAP join resolves a method in an untouched file from its committed baseline row instead of requiring fresh coverage for it. Neither narrows the capture run itself: a capture that does happen is the ordinary full run of the coverage gate's `captureScript` (Story #5065).",
11
11
  properties: {
12
12
  skipWhenUnchanged: {
13
13
  type: 'boolean',
@@ -53,7 +53,7 @@ export const CRAP_GATE = {
53
53
  type: ['string', 'null'],
54
54
  minLength: 1,
55
55
  description:
56
- "Repo-relative Istanbul `coverage-final.json` the CRAP gate joins against (Story #5717). `null` or unset falls back to `delivery.quality.gates.coverage.coveragePath`. When it differs from that path the CRAP gate has its OWN coverage source: `coverage-capture.js` refreshes it full-scope via `captureScript`, and the handoff seat, close preview and `update-crap-baseline.js` read it. It must live in a different directory from the coverage gate's artifact (the capture stamp is per directory); a same-directory path is refused at config resolution.",
56
+ "Repo-relative Istanbul `coverage-final.json` the CRAP gate joins against (Story #5717). `null` or unset falls back to `delivery.quality.gates.coverage.coveragePath`. When it differs from that path the CRAP gate has its OWN coverage source: `coverage-capture.js` refreshes it full-scope via `captureScript`, and the handoff seat, close preview and `update-crap-baseline.js` read it. Its capture stamp sits beside it, so it may share a directory with the coverage gate's artifact.",
57
57
  default: null,
58
58
  },
59
59
  captureScript: {
@@ -61,9 +61,11 @@ export const CRAP_GATE = {
61
61
  minLength: 1,
62
62
  pattern: '^[A-Za-z0-9@:._/-]+$',
63
63
  description:
64
- 'npm script name (run as `npm run <script>`, never a shell command) that writes the CRAP coverage artifact. Close registers the coverage-capture gate, and the capture refusal and credited-run probe key, on this script.',
65
- default: CRAP_GATE_DEFAULTS.captureScript,
64
+ "`package.json` script (never a shell command) that writes the CRAP gate's OWN coverage artifact, spawned as `<pm> run <script>`. Valid only beside an own `coveragePath`: without one the CRAP gate reads the coverage gate's artifact, so this key is refused and `delivery.quality.gates.coverage.captureScript` runs. Unset beside an own `coveragePath`, it is the coverage gate's `captureScript`.",
66
65
  },
67
66
  },
67
+ // Draft-07 `dependencies` (array form) — the `dependentRequired` contract:
68
+ // a CRAP capture script needs the own artifact it writes.
69
+ dependencies: { captureScript: ['coveragePath'] },
68
70
  additionalProperties: false,
69
71
  };
@@ -5,7 +5,7 @@ import { gateBase, LIST_OR_EXTENDER_OF_STRINGS } from './shared.js';
5
5
  export const DUPLICATION_GATE = {
6
6
  type: 'object',
7
7
  description:
8
- 'Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks, the jscpd `formats` it reads there, and `ignoreGlobs` to exclude files from the scan.',
8
+ 'Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks and `ignoreGlobs` to exclude files from the scan. The jscpd formats it reads are derived from the scorable-extension list every other gate scores (JavaScript, JSX, TypeScript, TSX), so they are not configurable (Story #5738).',
9
9
  properties: {
10
10
  ...gateBase({
11
11
  enabled: false,
@@ -16,22 +16,17 @@ export const DUPLICATION_GATE = {
16
16
  targetDirs: {
17
17
  ...LIST_OR_EXTENDER_OF_STRINGS,
18
18
  description:
19
- "Directories whose sources — the languages `formats` selects — the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664).",
19
+ "Directories whose scorable sources (`.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts`, `.cts`) the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664).",
20
20
  default: ['src'],
21
21
  },
22
- formats: {
23
- type: 'array',
24
- items: { type: 'string', minLength: 1 },
25
- minItems: 1,
26
- description:
27
- "jscpd format names the duplication (DRY) gate scans under `targetDirs`. The default covers JavaScript, JSX, TypeScript and TSX; jscpd's `javascript` format alone reads only `.js`/`.es`/`.es6`/`.mjs`/`.cjs`. Names are jscpd's own vocabulary and are not restricted here. Widening the set adds rows, so re-seat the baseline with `npm run duplication:reanchor` after changing it.",
28
- default: ['javascript', 'jsx', 'typescript', 'tsx'],
29
- },
22
+ // No `formats`: jscpd formats derive from `jscpdFormatsFor()`, and the
23
+ // 2.91.0 migration `retire-duplication-formats` strips the old key from
24
+ // `.agentrc.json` / `.agentrc.local.json` before this strict block sees it.
30
25
  ignoreGlobs: {
31
26
  type: 'array',
32
27
  items: { type: 'string', minLength: 1 },
33
28
  description:
34
- 'Minimatch glob patterns matched against the canonicalised repo-relative path of each discovered file. Files matching any pattern are excluded from duplication discovery before scanning. Orthogonal to `components` (grouping). Absent or empty preserves the existing behaviour (Story #3664).',
29
+ 'Minimatch glob patterns matched against the canonicalised repo-relative path of each discovered file. Files matching any pattern are excluded from duplication discovery before scanning. Orthogonal to `components` (grouping). Absent or empty preserves the existing behaviour (Story #3664). This is the lever for scanning fewer files.',
35
30
  default: [],
36
31
  },
37
32
  },
@@ -50,7 +50,7 @@ const TOLERANCE_SCHEMA = {
50
50
  const FLOORS_SCHEMA = {
51
51
  type: 'object',
52
52
  description:
53
- 'Workspace-keyed absolute floors: `{ "<workspace>": { "<metric>": number } }`. `"*"` is the project-wide catch-all; the metric keyset is open so per-rollup keys flow through without each gate enumerating them. Floors are absolute — unlike `tolerance`, they are enforced regardless of the baseline.',
53
+ 'Component-keyed absolute floors: `{ "<component>": { "<metric>": number } }` — the threshold half of the component mapping whose membership half is `components`. `"*"` is the project-wide catch-all component; the metric keyset is open so per-rollup keys flow through without each gate enumerating them. Floors are absolute — unlike `tolerance`, they are enforced regardless of the baseline.',
54
54
  additionalProperties: {
55
55
  type: 'object',
56
56
  additionalProperties: { type: 'number' },
@@ -60,7 +60,7 @@ const FLOORS_SCHEMA = {
60
60
  const COMPONENTS_SCHEMA = {
61
61
  type: 'object',
62
62
  description:
63
- 'Per-gate component map — component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer.',
63
+ 'Component-keyed membership map — the membership half of the component mapping whose threshold half is `floors`: component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer.',
64
64
  additionalProperties: {
65
65
  type: 'array',
66
66
  items: { type: 'string', minLength: 1 },
@@ -0,0 +1,120 @@
1
+ /** Git-derived roots; Node builtins only, since doctor imports it. */
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { execFileCapture } from '../child-exec.js';
7
+ import { PROJECT_ROOT } from '../project-root.js';
8
+
9
+ const GIT_QUIET = { stdio: ['ignore', 'pipe', 'ignore'] };
10
+
11
+ const _cache = new Map();
12
+
13
+ /** Memoized per flag and cwd for the real runner; `null` outside a repo. */
14
+ function revParse(flag, cwd, exec) {
15
+ const key = `${flag}\0${cwd}`;
16
+ if (!exec && _cache.has(key)) return _cache.get(key);
17
+ let out = null;
18
+ try {
19
+ const opts = { cwd, ...GIT_QUIET, ...(exec ? { run: exec } : {}) };
20
+ out = execFileCapture('git', ['rev-parse', flag], opts).trim() || null;
21
+ } catch {
22
+ out = null;
23
+ }
24
+ if (!exec) _cache.set(key, out);
25
+ return out;
26
+ }
27
+
28
+ /** Parent of `--git-common-dir`: the main checkout, from any worktree. */
29
+ export function mainCheckoutRoot(cwd = process.cwd(), deps = {}) {
30
+ const out = revParse('--git-common-dir', cwd, deps.exec);
31
+ if (!out) return null;
32
+ return path.dirname(path.isAbsolute(out) ? out : path.resolve(cwd, out));
33
+ }
34
+
35
+ /** This work tree's own root — a linked worktree's, not the main one's. */
36
+ function gitToplevel(cwd, exec) {
37
+ return revParse('--show-toplevel', cwd, exec);
38
+ }
39
+
40
+ /**
41
+ * Where `.agentrc.json` is read: `cwd` → `AP_AGENTRC_CWD` → the nearest
42
+ * config dir within the process cwd's work tree (else its toplevel) →
43
+ * `PROJECT_ROOT`.
44
+ */
45
+ export function resolveAgentrcRoot({
46
+ cwd,
47
+ env = process.env,
48
+ processCwd = process.cwd,
49
+ exec,
50
+ } = {}) {
51
+ if (cwd) return path.resolve(cwd);
52
+ if (env.AP_AGENTRC_CWD) return path.resolve(env.AP_AGENTRC_CWD);
53
+ return path.resolve(cwdRoot(processCwd(), exec));
54
+ }
55
+
56
+ /** The config dir of the work tree `here` is in, or `PROJECT_ROOT`. */
57
+ function cwdRoot(here, exec) {
58
+ const top = gitToplevel(here, exec);
59
+ return top === null ? PROJECT_ROOT : nearestConfig(here, top);
60
+ }
61
+
62
+ /**
63
+ * The nearest dir from `start` up to the work tree root `top` holding an
64
+ * `.agentrc.json` — a project nested in a larger repo — else `top`.
65
+ */
66
+ function nearestConfig(start, top) {
67
+ const stop = canonical(top, process.platform);
68
+ for (let dir = start; ; dir = path.dirname(dir)) {
69
+ if (fs.existsSync(path.join(dir, '.agentrc.json'))) return dir;
70
+ const atTop = canonical(dir, process.platform) === stop;
71
+ if (atTop || path.dirname(dir) === dir) return top;
72
+ }
73
+ }
74
+
75
+ function nativeReal(p) {
76
+ try {
77
+ return fs.realpathSync.native(p);
78
+ } catch {
79
+ return p;
80
+ }
81
+ }
82
+
83
+ /** Native realpath (8.3 names, symlinks); win32 compares case-insensitively. */
84
+ function canonical(p, platform) {
85
+ const win = platform === 'win32';
86
+ const resolved = (win ? path.win32 : path).resolve(nativeReal(p));
87
+ return win ? resolved.toLowerCase() : resolved;
88
+ }
89
+
90
+ /** The main checkout when `root` is a work tree root over a checkout's `.git`. */
91
+ function checkoutOf(root, exec, platform) {
92
+ const top = gitToplevel(root, exec);
93
+ const same =
94
+ top !== null && canonical(top, platform) === canonical(root, platform);
95
+ if (!same) return null;
96
+ const common = revParse('--git-common-dir', root, exec) ?? '';
97
+ return path.basename(common) === '.git'
98
+ ? mainCheckoutRoot(root, { exec })
99
+ : null;
100
+ }
101
+
102
+ /**
103
+ * The project root a gitignored file under `root` lives in: the main
104
+ * checkout for a checkout or linked worktree root, else `root` (a nested
105
+ * project, a submodule, a separate git dir).
106
+ */
107
+ export function storeRoot(root, exec, platform = process.platform) {
108
+ return checkoutOf(root, exec, platform) ?? root;
109
+ }
110
+
111
+ /** Where `root`'s `.agentrc.local.json` is read: its own, else `storeRoot`'s. */
112
+ export function overlayRoot(root, exec) {
113
+ if (fs.existsSync(path.join(root, '.agentrc.local.json'))) return root;
114
+ return storeRoot(root, exec);
115
+ }
116
+
117
+ /** Test-only. */
118
+ export function _clearGitRootCaches() {
119
+ _cache.clear();
120
+ }