mandrel 2.90.0 → 2.91.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 (169) 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/story-close/baseline-upward-writeback.js +2 -3
  106. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  107. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  108. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  109. package/.agents/scripts/lib/orchestration/story-handoff.js +13 -5
  110. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  111. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  112. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  113. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  114. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  115. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  116. package/.agents/scripts/lib/source-extensions.js +30 -15
  117. package/.agents/scripts/lib/test-run-credit.js +1 -9
  118. package/.agents/scripts/lib/test-temp.js +22 -21
  119. package/.agents/scripts/lib/util/ajv.js +111 -0
  120. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  121. package/.agents/scripts/lib/util/paths.js +51 -0
  122. package/.agents/scripts/lib/util/sleep.js +6 -0
  123. package/.agents/scripts/lib/util/slug.js +12 -0
  124. package/.agents/scripts/lib/validation-evidence.js +19 -40
  125. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  126. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  127. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  128. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  129. package/.agents/scripts/lint-issue-body.js +2 -2
  130. package/.agents/scripts/plan-context.js +2 -7
  131. package/.agents/scripts/providers/github/auth.js +3 -3
  132. package/.agents/scripts/providers/github/errors.js +3 -1
  133. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  134. package/.agents/scripts/providers/github/issues.js +6 -2
  135. package/.agents/scripts/providers/github/mappers.js +1 -5
  136. package/.agents/scripts/providers/github/projects-v2-graphql.js +11 -3
  137. package/.agents/scripts/providers/github/search-budget.js +3 -1
  138. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  139. package/.agents/scripts/sync-agentrc.js +5 -14
  140. package/.agents/scripts/sync-claude-agents.js +38 -150
  141. package/.agents/scripts/sync-claude-commands.js +35 -218
  142. package/.agents/scripts/update-coverage-baseline.js +1 -1
  143. package/.agents/scripts/update-crap-baseline.js +1 -1
  144. package/.agents/scripts/update-duplication-baseline.js +2 -16
  145. package/.agents/scripts/validate-skills.js +6 -10
  146. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  147. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  148. package/.agents/workflows/audit-exceptions.md +9 -0
  149. package/.agents/workflows/audit-lean.md +129 -0
  150. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  151. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  152. package/.agents/workflows/helpers/code-review.md +15 -1
  153. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  154. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  155. package/.agents/workflows/mandrel-plan.md +2 -2
  156. package/docs/CHANGELOG.md +35 -0
  157. package/lib/cli/doctor-checks/codex.js +6 -5
  158. package/lib/cli/doctor-checks/llm-review.js +102 -0
  159. package/lib/cli/doctor-checks/project-access.js +20 -10
  160. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  161. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  162. package/lib/cli/doctor-checks/toolchain.js +5 -3
  163. package/lib/cli/registry.js +5 -0
  164. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  165. package/lib/migrations/index.js +6 -0
  166. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  167. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  168. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  169. package/package.json +1 -3
@@ -7,24 +7,34 @@
7
7
  * formats the changed files and commits the result instead.
8
8
  */
9
9
 
10
- import { execFileSync } from 'node:child_process';
11
-
12
10
  import { diffNameOnly } from '../../changed-files.js';
11
+ import { execFileCapture } from '../../child-exec.js';
13
12
  import { resolveFormatWriteCommand } from '../../close-validation/commands.js';
14
13
  import { Logger as DefaultLogger } from '../../Logger.js';
15
14
 
16
15
  const SCOPED_TAG = '[format-autofix-scoped]';
17
16
 
17
+ /**
18
+ * `-- <paths…>` when pathspecs are given, else nothing (whole tree).
19
+ *
20
+ * @param {string[]} [paths]
21
+ * @returns {string[]}
22
+ */
23
+ const pathspecArgs = (paths = []) => (paths.length ? ['--', ...paths] : []);
24
+
18
25
  /**
19
26
  * Paths from `git status --porcelain`. Lines are `XY <path>` and the status
20
27
  * pair's leading space is significant, so slice 3 chars rather than trim.
28
+ * With `paths`, the status walk is limited to those pathspecs.
21
29
  *
22
30
  * @param {string} cwd
23
31
  * @param {(args: string[], opts: object) => string} git
32
+ * @param {string[]} [paths] - Pathspecs to scope the status to.
24
33
  * @returns {string[]}
25
34
  */
26
- export function listDirtyPaths(cwd, git) {
27
- const out = git(['status', '--porcelain'], {
35
+ export function listDirtyPaths(cwd, git, paths) {
36
+ const scope = pathspecArgs(paths);
37
+ const out = git(['status', '--porcelain', ...scope], {
28
38
  cwd,
29
39
  encoding: 'utf8',
30
40
  stdio: ['ignore', 'pipe', 'ignore'],
@@ -74,18 +84,22 @@ export function currentBranch(cwd, git) {
74
84
  }
75
85
 
76
86
  /**
77
- * `git add -u` + commit with hooks enabled (never `--no-verify`).
87
+ * `git add -u` + commit with hooks enabled (never `--no-verify`). With
88
+ * `paths`, both the staging and the commit are limited to those pathspecs, so
89
+ * a change outside them is never swept in.
78
90
  *
79
91
  * @param {{
80
92
  * cwd: string,
81
93
  * git: (args: string[], opts: object) => string,
82
94
  * subject: string,
95
+ * paths?: string[],
83
96
  * }} opts
84
97
  * @returns {string} short HEAD SHA of the new commit
85
98
  */
86
- export function commitDirtyPaths({ cwd, git, subject }) {
87
- git(['add', '-u'], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
88
- git(['commit', '-m', subject], {
99
+ export function commitDirtyPaths({ cwd, git, subject, paths }) {
100
+ const scope = pathspecArgs(paths);
101
+ git(['add', '-u', ...scope], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
102
+ git(['commit', '-m', subject, ...scope], {
89
103
  cwd,
90
104
  stdio: ['ignore', 'pipe', 'pipe'],
91
105
  });
@@ -142,7 +156,7 @@ export function listChangedFiles({ cwd, baseBranch, storyBranch, git }) {
142
156
  * storyBranch: string,
143
157
  * config?: object,
144
158
  * logger?: object,
145
- * spawnSync?: typeof execFileSync,
159
+ * spawnSync?: Function,
146
160
  * gitSync?: (args: string[], opts: object) => string,
147
161
  * }} opts
148
162
  * @returns {{
@@ -161,7 +175,7 @@ export function runScopedFormatAutofix({
161
175
  storyBranch,
162
176
  config,
163
177
  logger = DefaultLogger,
164
- spawnSync = execFileSync,
178
+ spawnSync,
165
179
  gitSync,
166
180
  } = {}) {
167
181
  if (!cwd) throw new Error('runScopedFormatAutofix: cwd is required');
@@ -172,7 +186,12 @@ export function runScopedFormatAutofix({
172
186
 
173
187
  const workTree = worktreePath || cwd;
174
188
 
175
- const git = gitSync ?? ((args, opts) => spawnSync('git', args, opts));
189
+ // `spawnSync` is an `execFileSync`-shaped seam: it becomes the wrapper's
190
+ // `run`, so the wrapper's stdout ceiling covers the diff, status and
191
+ // formatter captures whether or not a test injects it.
192
+ const exec = (file, args, opts) =>
193
+ execFileCapture(file, args, spawnSync ? { ...opts, run: spawnSync } : opts);
194
+ const git = gitSync ?? ((args, opts) => exec('git', args, opts));
176
195
 
177
196
  const { writeCmdString, writeCmd, writeArgs } = resolveFormatterCmd({
178
197
  commands: config?.project?.commands,
@@ -191,7 +210,7 @@ export function runScopedFormatAutofix({
191
210
  return { ran: false, committed: false, reason: 'no-changed-files' };
192
211
  }
193
212
 
194
- const dirtyBefore = listDirtyPaths(workTree, git);
213
+ const dirtyBefore = listDirtyPaths(workTree, git, changed);
195
214
  if (dirtyBefore.length) {
196
215
  logger.info?.(
197
216
  `${SCOPED_TAG} skipped — working tree dirty before scoped autofix (${dirtyBefore.length} paths).`,
@@ -201,7 +220,7 @@ export function runScopedFormatAutofix({
201
220
 
202
221
  // A non-zero exit is tolerated: the downstream check gate is authoritative.
203
222
  try {
204
- spawnSync(writeCmd, [...writeArgs, ...changed], {
223
+ exec(writeCmd, [...writeArgs, ...changed], {
205
224
  cwd: workTree,
206
225
  stdio: ['ignore', 'pipe', 'pipe'],
207
226
  encoding: 'utf8',
@@ -212,7 +231,7 @@ export function runScopedFormatAutofix({
212
231
  );
213
232
  }
214
233
 
215
- const dirtyAfter = listDirtyPaths(workTree, git);
234
+ const dirtyAfter = listDirtyPaths(workTree, git, changed);
216
235
  if (!dirtyAfter.length) {
217
236
  logger.info?.(
218
237
  `${SCOPED_TAG} no format drift on ${changed.length} changed file(s).`,
@@ -230,7 +249,14 @@ export function runScopedFormatAutofix({
230
249
  }
231
250
 
232
251
  const subject = `fix(story-close): auto-apply biome format in scoped lint (story #${storyId})`;
233
- const sha = commitDirtyPaths({ cwd: workTree, git, subject });
252
+ const sha = commitDirtyPaths({
253
+ cwd: workTree,
254
+ git,
255
+ subject,
256
+ // The dirty set, not `changed`: a path the branch deleted is no pathspec
257
+ // `git add` / `git commit` can match.
258
+ paths: dirtyAfter,
259
+ });
234
260
 
235
261
  logger.warn?.(
236
262
  `${SCOPED_TAG} auto-applied biome format to ${dirtyAfter.length} path(s) on story #${storyId}: ${dirtyAfter.join(', ')}; committed as ${sha}.`,
@@ -9,8 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
11
 
12
- import Ajv2020 from 'ajv/dist/2020.js';
13
- import addFormats from 'ajv-formats';
12
+ import { createAjv2020 } from '../util/ajv.js';
14
13
 
15
14
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
15
 
@@ -57,8 +56,7 @@ function getValidator(source) {
57
56
  if (!source?.schema) return null;
58
57
  const cached = VALIDATORS.get(source);
59
58
  if (cached) return cached;
60
- const ajv = new Ajv2020({ allErrors: true, strict: false });
61
- addFormats(ajv);
59
+ const ajv = createAjv2020({ allErrors: true, strict: false });
62
60
  const validate = ajv.compile(source.schema);
63
61
  VALIDATORS.set(source, validate);
64
62
  return validate;
@@ -5,9 +5,9 @@
5
5
  */
6
6
 
7
7
  import nodeFs from 'node:fs';
8
- import path from 'node:path';
9
8
  import { storyTerminalEnvelopePath } from '../config/temp-paths.js';
10
9
  import { resolveConfig } from '../config-resolver.js';
10
+ import { writeFileAtomic } from '../util/atomic-write.js';
11
11
  import { validateTerminalEnvelope } from './story-deliver-terminal-schema.js';
12
12
 
13
13
  export { validateTerminalEnvelope };
@@ -273,23 +273,12 @@ export function persistTerminalEnvelope(
273
273
  ) {
274
274
  const storyId = envelope?.storyId;
275
275
  if (!Number.isInteger(storyId) || storyId <= 0) return null;
276
- let tmpPath = null;
277
276
  try {
278
277
  const resolved = config ?? tolerantConfig(resolveConfigImpl);
279
278
  const target = storyTerminalEnvelopePath(storyId, resolved);
280
- fsImpl.mkdirSync(path.dirname(target), { recursive: true });
281
- tmpPath = `${target}.${process.pid}.tmp`;
282
- fsImpl.writeFileSync(tmpPath, `${JSON.stringify(envelope)}\n`, 'utf8');
283
- fsImpl.renameSync(tmpPath, target);
279
+ writeFileAtomic(target, `${JSON.stringify(envelope)}\n`, { fsImpl });
284
280
  return target;
285
281
  } catch {
286
- if (tmpPath) {
287
- try {
288
- fsImpl.rmSync(tmpPath, { force: true });
289
- } catch {
290
- // Best-effort.
291
- }
292
- }
293
282
  return null;
294
283
  }
295
284
  }
@@ -25,7 +25,7 @@ import { fileURLToPath } from 'node:url';
25
25
  import { spawnStreamAsync } from '../child-exec.js';
26
26
  import { createLockEventChannel } from '../close-lock-events.js';
27
27
  import {
28
- resolveLintCommand,
28
+ resolveGateCommand,
29
29
  resolveTestGateArgv,
30
30
  } from '../close-validation/commands.js';
31
31
  import {
@@ -299,6 +299,17 @@ function describeSuiteFailure(status) {
299
299
  return `red suite (exit ${status}) — fix the failing tests, commit, re-run`;
300
300
  }
301
301
 
302
+ /**
303
+ * The lint preflight, absent when `project.commands.lint` is `null`.
304
+ *
305
+ * @param {object} config
306
+ * @returns {Array<{ key: string, cmd: string, args: string[] }>}
307
+ */
308
+ function lintPreflight(config) {
309
+ const lint = resolveGateCommand(config, 'lint');
310
+ return lint.disabled ? [] : [{ key: 'lint', cmd: lint.cmd, args: lint.args }];
311
+ }
312
+
302
313
  /**
303
314
  * Lint, quality-preview, then each ratchet whose baseline is committed.
304
315
  *
@@ -306,9 +317,6 @@ function describeSuiteFailure(status) {
306
317
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean }>}
307
318
  */
308
319
  function preflightChecks(ctx) {
309
- const [lintCmd, ...lintArgs] = resolveLintCommand(ctx.config)
310
- .split(/\s+/)
311
- .filter(Boolean);
312
320
  const ratchets = RATCHETS.filter((r) =>
313
321
  fs.existsSync(path.join(ctx.cwd, r.baseline)),
314
322
  ).map((r) => ({
@@ -318,7 +326,7 @@ function preflightChecks(ctx) {
318
326
  gated: true,
319
327
  }));
320
328
  return [
321
- { key: 'lint', cmd: lintCmd, args: lintArgs },
329
+ ...lintPreflight(ctx.config),
322
330
  {
323
331
  key: 'quality-preview',
324
332
  cmd: 'node',
@@ -6,15 +6,15 @@
6
6
  *
7
7
  * Advisory only — nothing in Mandrel decides on it. Every write is best
8
8
  * effort (an fs error is swallowed and logged at debug) and atomic (a
9
- * `<file>.tmp` sibling renamed over the target), so a poller never parses
9
+ * pid-scoped tmp sibling renamed over the target), so a poller never parses
10
10
  * half a file and an unwritable temp folder changes no delivery outcome.
11
11
  */
12
12
 
13
13
  import fs from 'node:fs';
14
- import path from 'node:path';
15
14
 
16
15
  import { storyProgressPath } from '../config/temp-paths.js';
17
16
  import { Logger } from '../Logger.js';
17
+ import { writeFileAtomic } from '../util/atomic-write.js';
18
18
 
19
19
  const STORY_PROGRESS_KIND = 'story-progress';
20
20
 
@@ -43,18 +43,10 @@ export function handoffStepName(step) {
43
43
  function writeStoryProgress(file, record, deps = {}) {
44
44
  const fsImpl = deps.fsImpl ?? fs;
45
45
  const debug = deps.debug ?? ((msg) => Logger.debug(msg));
46
- const tmp = `${file}.tmp`;
47
46
  try {
48
- fsImpl.mkdirSync(path.dirname(file), { recursive: true });
49
- fsImpl.writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
50
- fsImpl.renameSync(tmp, file);
47
+ writeFileAtomic(file, `${JSON.stringify(record, null, 2)}\n`, { fsImpl });
51
48
  return true;
52
49
  } catch (err) {
53
- try {
54
- fsImpl.rmSync(tmp, { force: true });
55
- } catch {
56
- // The stray tmp is harmless; the next write overwrites it.
57
- }
58
50
  debug(`[story-progress] write skipped for ${file}: ${err?.message ?? err}`);
59
51
  return false;
60
52
  }
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { Logger } from '../../Logger.js';
9
+ import { defaultSleep } from '../../util/sleep.js';
9
10
  import { ALL_STATES, STATE_LABELS } from './reads.js';
10
11
  import {
11
12
  postStructuredComment,
@@ -15,10 +16,8 @@ import {
15
16
 
16
17
  /** Backoff for transient `gh` failures inside the cascade transition. */
17
18
  const CASCADE_RETRY_BACKOFF_MS = [250, 500, 1000];
18
- const defaultCascadeSleep = (ms) =>
19
- new Promise((resolve) => setTimeout(resolve, ms));
20
19
  let _cascadeRetryDelays = CASCADE_RETRY_BACKOFF_MS;
21
- let _cascadeSleep = defaultCascadeSleep;
20
+ let _cascadeSleep = defaultSleep;
22
21
 
23
22
  /**
24
23
  * Test seam; call with no arguments to restore defaults.
@@ -29,8 +28,7 @@ export function __setCascadeRetryDelays(opts = {}) {
29
28
  _cascadeRetryDelays = Array.isArray(opts.delays)
30
29
  ? opts.delays
31
30
  : CASCADE_RETRY_BACKOFF_MS;
32
- _cascadeSleep =
33
- typeof opts.sleep === 'function' ? opts.sleep : defaultCascadeSleep;
31
+ _cascadeSleep = typeof opts.sleep === 'function' ? opts.sleep : defaultSleep;
34
32
  }
35
33
 
36
34
  /**
@@ -6,8 +6,14 @@
6
6
  */
7
7
 
8
8
  import { resolveTestGateArgv } from '../close-validation/commands.js';
9
+ import { COVERAGE_CAPTURE_DEFAULTS } from '../config/gates/coverage.schema.js';
9
10
  import { getQuality, resolveConfig } from '../config-resolver.js';
10
11
  import { isCoverageFresh } from '../coverage-capture.js';
12
+ import {
13
+ captureGates,
14
+ isCaptureActive,
15
+ primaryCaptureSource,
16
+ } from '../coverage-capture-passes.js';
11
17
  import { gitSpawn } from '../git-utils.js';
12
18
  import { hasNpmScript, readPackageScripts } from '../npm-scripts.js';
13
19
  import {
@@ -24,7 +30,10 @@ export const FULL_SUITE_SHAPE_WARNING =
24
30
 
25
31
  const PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
26
32
 
27
- const FULL_SUITE_SCRIPTS = new Set(['test', 'test:coverage']);
33
+ const FULL_SUITE_SCRIPTS = new Set([
34
+ 'test',
35
+ COVERAGE_CAPTURE_DEFAULTS.captureScript,
36
+ ]);
28
37
 
29
38
  /** Filter flags that scope a bare-looking `node --test`; `=value` form too. */
30
39
  const NARROWING_FLAGS = Object.freeze([
@@ -45,6 +54,30 @@ function hasNarrowingFlag(tokens) {
45
54
  );
46
55
  }
47
56
 
57
+ /**
58
+ * The credit mode, and — in capture mode — the primary artifact's freshness.
59
+ *
60
+ * @param {{ quality: object, scripts: object, worktree: string, hasNpmScriptImpl: Function, isCoverageFreshImpl: Function }} opts
61
+ */
62
+ function probeCaptureStamp({
63
+ quality,
64
+ scripts,
65
+ worktree,
66
+ hasNpmScriptImpl,
67
+ isCoverageFreshImpl,
68
+ }) {
69
+ const gates = captureGates(quality);
70
+ if (!isCaptureActive({ ...gates, scripts, hasNpmScriptImpl })) {
71
+ return { mode: 'evidence', freshness: null };
72
+ }
73
+ const freshness = isCoverageFreshImpl({
74
+ coveragePath: primaryCaptureSource(gates).coveragePath,
75
+ targetDirs: gates.crap.targetDirs,
76
+ cwd: worktree,
77
+ });
78
+ return { mode: 'capture', freshness };
79
+ }
80
+
48
81
  /**
49
82
  * Strip a trailing `(<tier>)` tag, which would otherwise make every entry
50
83
  * look scoped.
@@ -136,34 +169,25 @@ export function resolveVerifyCredit(
136
169
  warning: FULL_SUITE_SHAPE_WARNING,
137
170
  };
138
171
  const config = resolveConfigImpl({ cwd: worktree });
139
- const { crap } = getQualityImpl(config);
140
- const mode =
141
- crap?.enabled !== false &&
142
- hasNpmScriptImpl(
143
- readPackageScriptsImpl(worktree),
144
- crap?.captureScript ?? 'test:coverage',
145
- )
146
- ? 'capture'
147
- : 'evidence';
148
-
149
- let stampReason = null;
150
- if (mode === 'capture') {
151
- const freshness = isCoverageFreshImpl({
152
- coveragePath: crap.coveragePath,
153
- targetDirs: crap.targetDirs,
154
- cwd: worktree,
155
- });
156
- if (freshness?.fresh === true) {
157
- return {
158
- ...scoped,
159
- mode,
160
- credited: true,
161
- spawn: false,
162
- reason: 'capture-stamp-fresh',
163
- };
164
- }
165
- stampReason = freshness?.reason ?? 'unknown';
172
+ const { mode, freshness } = probeCaptureStamp({
173
+ quality: getQualityImpl(config),
174
+ scripts: readPackageScriptsImpl(worktree),
175
+ worktree,
176
+ hasNpmScriptImpl,
177
+ isCoverageFreshImpl,
178
+ });
179
+
180
+ if (freshness?.fresh === true) {
181
+ return {
182
+ ...scoped,
183
+ mode,
184
+ credited: true,
185
+ spawn: false,
186
+ reason: 'capture-stamp-fresh',
187
+ };
166
188
  }
189
+ const stampReason =
190
+ mode === 'capture' ? (freshness?.reason ?? 'unknown') : null;
167
191
 
168
192
  // A stale stamp is not the last word: a green `npm test` deposits `test`
169
193
  // evidence, consulted in both modes before spawning.
@@ -2,25 +2,25 @@
2
2
  * single-story-sweep/protection-ctx.js
3
3
  *
4
4
  * The one builder of the `evaluateProtection` ctx for every sweep caller.
5
- * `ghRunner` stays on synchronous `spawnSync` (not the async gh-exec facade)
6
- * because the checks run inside a synchronous candidate-filter loop.
5
+ * `ghRunner` stays synchronous (gh-exec's `runGh`, not the async `exec()`
6
+ * facade) because the checks run inside a synchronous candidate-filter loop.
7
7
  */
8
8
 
9
- import { spawnSync as defaultSpawnSync } from 'node:child_process';
9
+ import { runGh } from '../gh-exec.js';
10
10
  import { gitSpawn } from '../git-utils.js';
11
11
 
12
12
  /**
13
13
  * @param {string} cwd Repo root used as the default spawn cwd.
14
- * @param {typeof defaultSpawnSync} [spawnImpl]
14
+ * @param {Function} [spawnImpl] - `spawnSync`-shaped; defaults to `spawnSync`.
15
15
  * @returns {(args: string[], opts?: { cwd?: string }) => string}
16
16
  */
17
- export function makeGhRunner(cwd, spawnImpl = defaultSpawnSync) {
17
+ export function makeGhRunner(cwd, spawnImpl) {
18
18
  return (args, opts) => {
19
- const result = spawnImpl('gh', args, {
20
- cwd: opts?.cwd ?? cwd,
21
- encoding: 'utf-8',
22
- shell: false,
23
- });
19
+ const result = runGh(
20
+ args,
21
+ { cwd: opts?.cwd ?? cwd, encoding: 'utf-8', shell: false },
22
+ spawnImpl,
23
+ );
24
24
  if (result.status !== 0) {
25
25
  throw new Error(
26
26
  `gh ${args.join(' ')} exit ${result.status}: ${result.stderr ?? ''}`,
@@ -34,7 +34,7 @@ export function makeGhRunner(cwd, spawnImpl = defaultSpawnSync) {
34
34
  * @param {{
35
35
  * cwd: string,
36
36
  * provider: { getTicket: (id: number) => Promise<object> },
37
- * spawnImpl?: typeof defaultSpawnSync,
37
+ * spawnImpl?: Function,
38
38
  * }} args
39
39
  * @returns {{
40
40
  * repoRoot: string,
@@ -12,14 +12,6 @@ import { parseStoryBranch } from '../git-utils.js';
12
12
 
13
13
  const DONE_LABEL = 'agent::done';
14
14
 
15
- /**
16
- * @param {string} branch
17
- * @returns {number|null}
18
- */
19
- export function storyIdFromBranch(branch) {
20
- return parseStoryBranch(branch);
21
- }
22
-
23
15
  /**
24
16
  * Closed, or carrying `agent::done`.
25
17
  *
@@ -135,7 +127,7 @@ export function checkDirtyTree({ candidate, ctx }) {
135
127
 
136
128
  /** Non-`story-<n>` branches have no parent ticket and bypass this guard. */
137
129
  export async function checkTicketNotDone({ candidate, ctx }) {
138
- const storyId = storyIdFromBranch(candidate.branch);
130
+ const storyId = parseStoryBranch(candidate.branch);
139
131
  if (storyId === null) return { protected: false };
140
132
  if (typeof ctx.getTicket !== 'function') {
141
133
  return { protected: true, reason: 'provider-unavailable' };
@@ -10,7 +10,7 @@
10
10
 
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
- import { defaultSleep } from '../util/sleep.js';
13
+ import { defaultSleep, sleepSync } from '../util/sleep.js';
14
14
 
15
15
  const DEFAULT_TIMEOUT_MS = 60_000;
16
16
 
@@ -458,10 +458,6 @@ function guardedRelease(lockPath, fsImpl, removeOwn) {
458
458
  }
459
459
  }
460
460
 
461
- function sleepSync(ms) {
462
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
463
- }
464
-
465
461
  function buildAcquired(holder) {
466
462
  const { lockPath, ownerId, fsImpl, processImpl = process } = holder;
467
463
  const stopHeartbeat = startHeartbeat(holder);
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * SSOT for the extensions the CRAP/MI scanners score. The scanner walk, the
3
- * coverage-freshness check and the CRAP projection filter must all agree: a
4
- * narrower selector makes a gate green while measuring nothing. Not
5
- * configurable, for the same reason.
3
+ * coverage-freshness check, the refresh scope predicates, the close-time
4
+ * CRAP/MI projections, native review and the duplication scanner's jscpd
5
+ * formats must all agree: a narrower selector makes a gate green while
6
+ * measuring nothing. Not configurable, for the same reason.
6
7
  *
7
8
  * MUST import only `node:` builtins — it runs on the pre-push path and must
8
9
  * not drag the scoring engines in.
@@ -10,20 +11,24 @@
10
11
  import path from 'node:path';
11
12
 
12
13
  /**
13
- * What the engines can parse (not `.vue`/`.svelte`/`.astro`). Private: select
14
- * via the exported regex or predicate.
14
+ * What the engines can parse (not `.vue`/`.svelte`/`.astro`), each mapped to
15
+ * the jscpd format that reads it — jscpd's `javascript` alone reads only
16
+ * `.js`/`.mjs`/`.cjs`. Private: select via the exported regex or predicate.
15
17
  *
16
- * @type {readonly string[]}
18
+ * @type {Readonly<Record<string, string>>}
17
19
  */
18
- const SCORABLE_SOURCE_EXTENSIONS = Object.freeze([
19
- '.js',
20
- '.mjs',
21
- '.cjs',
22
- '.ts',
23
- '.tsx',
24
- '.mts',
25
- '.cts',
26
- ]);
20
+ const SCORABLE_SOURCES = Object.freeze({
21
+ '.js': 'javascript',
22
+ '.mjs': 'javascript',
23
+ '.cjs': 'javascript',
24
+ '.jsx': 'jsx',
25
+ '.ts': 'typescript',
26
+ '.tsx': 'tsx',
27
+ '.mts': 'typescript',
28
+ '.cts': 'typescript',
29
+ });
30
+
31
+ const SCORABLE_SOURCE_EXTENSIONS = Object.keys(SCORABLE_SOURCES);
27
32
 
28
33
  /**
29
34
  * For paths arriving as raw text (git output lines).
@@ -43,3 +48,13 @@ export function isScorableSourceFile(filePath) {
43
48
  path.extname(String(filePath)).toLowerCase(),
44
49
  );
45
50
  }
51
+
52
+ /**
53
+ * The jscpd formats covering the scorable list. Derived, never declared: the
54
+ * duplication gate scans exactly the files the other gates score.
55
+ *
56
+ * @returns {string[]}
57
+ */
58
+ export function jscpdFormatsFor() {
59
+ return [...new Set(Object.values(SCORABLE_SOURCES))];
60
+ }
@@ -72,14 +72,6 @@ function gitLine(gitSpawnFn, cwd, args) {
72
72
  }
73
73
  }
74
74
 
75
- /**
76
- * @param {string|null} branch
77
- * @returns {number|null}
78
- */
79
- export function storyIdFromBranch(branch) {
80
- return parseStoryBranch(branch);
81
- }
82
-
83
75
  /**
84
76
  * The main checkout (where close reads evidence), via `--git-common-dir`.
85
77
  *
@@ -118,7 +110,7 @@ export function depositTestRunCredit({
118
110
  } = {}) {
119
111
  if (status !== 0) return { deposited: false, reason: 'run-not-green' };
120
112
  if (tier !== 'full') return { deposited: false, reason: 'not-full-tier' };
121
- const storyId = storyIdFromBranch(
113
+ const storyId = parseStoryBranch(
122
114
  gitLine(gitSpawnFn, cwd, ['rev-parse', '--abbrev-ref', 'HEAD']),
123
115
  );
124
116
  if (storyId === null)
@@ -8,6 +8,7 @@ import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
10
  import picomatch from 'picomatch';
11
+ import { toPosix, walkFiles } from './util/paths.js';
11
12
 
12
13
  /** Suite-root name prefix; the guard matches on it. */
13
14
  export const SUITE_ROOT_PREFIX = 'mandrel-suite-';
@@ -207,14 +208,23 @@ export function reapOnExit(
207
208
  export function listSuiteTempRoots(tmpDir, { fsImpl = fs } = {}) {
208
209
  if (!fsImpl.existsSync(tmpDir)) return [];
209
210
  return fsImpl
210
- .readdirSync(tmpDir, { withFileTypes: true })
211
+ .readdirSync(tmpDir)
211
212
  .filter(
212
- (ent) => ent.isDirectory() && ent.name.startsWith(SUITE_ROOT_PREFIX),
213
+ (name) =>
214
+ name.startsWith(SUITE_ROOT_PREFIX) &&
215
+ isDirectory(path.join(tmpDir, name), fsImpl),
213
216
  )
214
- .map((ent) => ent.name)
215
217
  .sort();
216
218
  }
217
219
 
220
+ function isDirectory(p, fsImpl) {
221
+ try {
222
+ return fsImpl.statSync(p).isDirectory();
223
+ } catch {
224
+ return false;
225
+ }
226
+ }
227
+
218
228
  /**
219
229
  * Suite roots created since the snapshot and still on disk. Diffing against
220
230
  * the snapshot keeps a concurrent suite from failing this one.
@@ -259,7 +269,7 @@ export function findRawTmpdirMkdtemp(repoRoot, globs, { fsImpl = fs } = {}) {
259
269
  const isIncluded = picomatch(include);
260
270
  const isExcluded = exclude.length > 0 ? picomatch(exclude) : () => false;
261
271
  const findings = [];
262
- for (const rel of walkFiles(repoRoot, fsImpl)) {
272
+ for (const rel of listJsSources(repoRoot, fsImpl)) {
263
273
  if (!isIncluded(rel) || isExcluded(rel)) continue;
264
274
  const lines = fsImpl
265
275
  .readFileSync(path.join(repoRoot, rel), 'utf8')
@@ -282,21 +292,12 @@ export function findRawTmpdirMkdtemp(repoRoot, globs, { fsImpl = fs } = {}) {
282
292
  * @param {typeof fs} fsImpl
283
293
  * @returns {string[]}
284
294
  */
285
- function walkFiles(root, fsImpl) {
286
- const out = [];
287
- const skip = new Set(['node_modules', '.worktrees', '.git', 'temp']);
288
- const walk = (dir, prefix) => {
289
- if (!fsImpl.existsSync(dir)) return;
290
- for (const ent of fsImpl.readdirSync(dir, { withFileTypes: true })) {
291
- if (skip.has(ent.name)) continue;
292
- const rel = prefix ? `${prefix}/${ent.name}` : ent.name;
293
- if (ent.isDirectory()) {
294
- walk(path.join(dir, ent.name), rel);
295
- } else if (/\.(?:js|mjs|cjs)$/.test(ent.name)) {
296
- out.push(rel);
297
- }
298
- }
299
- };
300
- walk(root, '');
301
- return out.sort();
295
+ function listJsSources(root, fsImpl) {
296
+ return walkFiles(root, {
297
+ skipDirs: ['node_modules', '.worktrees', '.git', 'temp'],
298
+ filter: (_abs, dirent) => /\.(?:js|mjs|cjs)$/.test(dirent.name),
299
+ fsImpl,
300
+ })
301
+ .map((abs) => toPosix(path.relative(root, abs)))
302
+ .sort();
302
303
  }