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
@@ -106,15 +106,49 @@ async function loadTicketSnapshot(provider, opts, ticketId, needFromState) {
106
106
  }
107
107
  }
108
108
 
109
+ const BOARD_SYNC_REMEDIES = Object.freeze({
110
+ 'insufficient-scope': 'gh auth refresh -h github.com -s project',
111
+ 'not-on-project': 'node .agents/scripts/board-backfill.js',
112
+ });
113
+
114
+ const SILENT_BOARD_SKIPS = new Set(['no-project']);
115
+
116
+ /** Warns on every flip, never latched: agents read the flip's own output. */
117
+ function reportBoardSync(ticketId, newState, boardSync) {
118
+ if (boardSync.status === 'synced') return;
119
+ if (SILENT_BOARD_SKIPS.has(boardSync.reason)) return;
120
+ Logger.warn(boardSyncMessage(ticketId, newState, boardSync));
121
+ }
122
+
123
+ function boardSyncMessage(ticketId, newState, { status, reason, detail }) {
124
+ const why = detail ? `${reason}: ${detail}` : reason;
125
+ const remedy = BOARD_SYNC_REMEDIES[reason];
126
+ const fix = remedy ? ` — fix: \`${remedy}\`` : '';
127
+ return `[Ticketing] board Status not synced for #${ticketId} → ${newState} (${status}, ${why})${fix}`;
128
+ }
129
+
130
+ /** First instance per provider wins, so a later `config` is ignored. */
131
+ function columnSyncFor(provider, _makeColumnSync, config) {
132
+ if (_makeColumnSync) return _makeColumnSync({ provider, logger: Logger });
133
+ if (!_columnSyncRegistry.has(provider)) {
134
+ _columnSyncRegistry.set(
135
+ provider,
136
+ new ColumnSync({ provider, logger: Logger, config }),
137
+ );
138
+ }
139
+ return _columnSyncRegistry.get(provider);
140
+ }
141
+
109
142
  /**
110
143
  * Mirror the new state onto the Projects v2 Status column. Best-effort: a
111
- * board failure is logged and never blocks the label transition. An injected
112
- * `_makeColumnSync` bypasses the registry so test stubs are never cached.
144
+ * board failure never blocks the label transition; the outcome is returned.
145
+ * An injected `_makeColumnSync` bypasses the registry.
113
146
  *
114
147
  * @param {object} provider
115
148
  * @param {number} ticketId
116
149
  * @param {string} newState
117
150
  * @param {(opts: object) => { sync: (id: number, labels: string[]) => Promise<object> }} [_makeColumnSync]
151
+ * @returns {Promise<{ status: string, reason?: string, column?: string, detail?: string }>}
118
152
  */
119
153
  async function syncProjectStatusColumn(
120
154
  provider,
@@ -124,25 +158,14 @@ async function syncProjectStatusColumn(
124
158
  config,
125
159
  ) {
126
160
  try {
127
- let sync;
128
- if (_makeColumnSync) {
129
- sync = _makeColumnSync({ provider, logger: Logger });
130
- } else {
131
- // `config` is read at construction only; the first instance per
132
- // provider wins, so a later transition's config is ignored.
133
- if (!_columnSyncRegistry.has(provider)) {
134
- _columnSyncRegistry.set(
135
- provider,
136
- new ColumnSync({ provider, logger: Logger, config }),
137
- );
138
- }
139
- sync = _columnSyncRegistry.get(provider);
140
- }
141
- await sync.sync(ticketId, [newState]);
161
+ const sync = columnSyncFor(provider, _makeColumnSync, config);
162
+ return await sync.sync(ticketId, [newState]);
142
163
  } catch (err) {
143
- Logger.warn(
144
- `[Ticketing] column sync failed for #${ticketId} → ${newState}: ${err?.message ?? err}`,
145
- );
164
+ return {
165
+ status: 'failed',
166
+ reason: 'error',
167
+ detail: String(err?.message ?? err),
168
+ };
146
169
  }
147
170
  }
148
171
 
@@ -250,6 +273,7 @@ async function emitBlockedFriction(ticketId, fromState, newState, opts) {
250
273
  * `cascade: false` suppresses the upward parent cascade.
251
274
  * `ticketSnapshot` is a pre-fetched ticket that saves the `fromState` read
252
275
  * and the provider's label-merge read. `_makeColumnSync` is a test seam.
276
+ * @returns {Promise<{ boardSync: { status: string, reason?: string, column?: string, detail?: string } }>}
253
277
  */
254
278
  export async function transitionTicketState(
255
279
  provider,
@@ -285,13 +309,14 @@ export async function transitionTicketState(
285
309
 
286
310
  await emitBlockedFriction(ticketId, fromState, newState, opts);
287
311
 
288
- await syncProjectStatusColumn(
312
+ const boardSync = await syncProjectStatusColumn(
289
313
  provider,
290
314
  ticketId,
291
315
  newState,
292
316
  opts._makeColumnSync,
293
317
  opts.config,
294
318
  );
319
+ reportBoardSync(ticketId, newState, boardSync);
295
320
 
296
321
  // Every transition re-derives parent state from children (not just `done`),
297
322
  // keeping the board accurate when work starts or a child blocks.
@@ -310,6 +335,7 @@ export async function transitionTicketState(
310
335
  newState,
311
336
  });
312
337
  }
338
+ return { boardSync };
313
339
  }
314
340
 
315
341
  /**
@@ -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
  }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The one Ajv factory for validators that need string formats. Mandrel's
3
+ * schemas declare only `date-time` and `date`, so those two are registered by
4
+ * hand (a port of the Ajv formats plugin's full-mode RFC 3339 checks) instead
5
+ * of loading that whole plugin.
6
+ */
7
+
8
+ import AjvDraft07 from 'ajv';
9
+ import AjvDraft2020 from 'ajv/dist/2020.js';
10
+
11
+ const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
12
+ const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
13
+ const DATE_TIME_SEPARATOR = /t|\s/i;
14
+ const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
15
+
16
+ /**
17
+ * @param {number} year
18
+ * @returns {boolean}
19
+ */
20
+ function isLeapYear(year) {
21
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
22
+ }
23
+
24
+ /**
25
+ * RFC 3339 full-date on a real calendar day.
26
+ *
27
+ * @param {string} str
28
+ * @returns {boolean}
29
+ */
30
+ function isDate(str) {
31
+ const m = DATE.exec(str);
32
+ if (!m) return false;
33
+ const year = +m[1];
34
+ const month = +m[2];
35
+ const day = +m[3];
36
+ if (month < 1 || month > 12 || day < 1) return false;
37
+ return day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
38
+ }
39
+
40
+ /**
41
+ * A `:60` second is valid only at 23:59 UTC once the offset is applied.
42
+ *
43
+ * @param {RegExpExecArray} m
44
+ * @returns {boolean}
45
+ */
46
+ function isLeapSecond(m) {
47
+ const sign = m[5] === '-' ? -1 : 1;
48
+ const utcMin = +m[2] - +(m[7] || 0) * sign;
49
+ const utcHr = +m[1] - +(m[6] || 0) * sign - (utcMin < 0 ? 1 : 0);
50
+ const atLastHour = utcHr === 23 || utcHr === -1;
51
+ return atLastHour && (utcMin === 59 || utcMin === -1) && +m[3] < 61;
52
+ }
53
+
54
+ /**
55
+ * RFC 3339 full-time with a required `Z` or `±hh:mm` offset.
56
+ *
57
+ * @param {string} str
58
+ * @returns {boolean}
59
+ */
60
+ function isTime(str) {
61
+ const m = TIME.exec(str);
62
+ if (!m || !m[4]) return false;
63
+ if (+(m[6] || 0) > 23 || +(m[7] || 0) > 59) return false;
64
+ if (+m[1] <= 23 && +m[2] <= 59 && +m[3] < 60) return true;
65
+ return isLeapSecond(m);
66
+ }
67
+
68
+ /**
69
+ * RFC 3339 date-time: full-date, a `T`/`t`/space separator, full-time.
70
+ *
71
+ * @param {string} str
72
+ * @returns {boolean}
73
+ */
74
+ function isDateTime(str) {
75
+ const parts = str.split(DATE_TIME_SEPARATOR);
76
+ return parts.length === 2 && isDate(parts[0]) && isTime(parts[1]);
77
+ }
78
+
79
+ /**
80
+ * @template {import('ajv').default} T
81
+ * @param {T} ajv
82
+ * @returns {T}
83
+ */
84
+ function withFormats(ajv) {
85
+ ajv.addFormat('date-time', isDateTime);
86
+ ajv.addFormat('date', isDate);
87
+ return ajv;
88
+ }
89
+
90
+ const Draft07 = AjvDraft07.default ?? AjvDraft07;
91
+ const Draft2020 = AjvDraft2020.default ?? AjvDraft2020;
92
+
93
+ /**
94
+ * Draft-07 Ajv with the `date-time` and `date` formats registered.
95
+ *
96
+ * @param {import('ajv').Options} [options]
97
+ * @returns {import('ajv').default}
98
+ */
99
+ export function createAjv(options = {}) {
100
+ return withFormats(new Draft07(options));
101
+ }
102
+
103
+ /**
104
+ * Draft 2020-12 Ajv with the `date-time` and `date` formats registered.
105
+ *
106
+ * @param {import('ajv').Options} [options]
107
+ * @returns {import('ajv/dist/2020.js').default}
108
+ */
109
+ export function createAjv2020(options = {}) {
110
+ return withFormats(new Draft2020(options));
111
+ }
@@ -0,0 +1,30 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Tmp-then-rename via a pid-scoped sibling; reaps the tmp and rethrows on
6
+ * failure.
7
+ *
8
+ * @param {string} target
9
+ * @param {string} contents
10
+ * @param {{ fsImpl?: typeof fs }} [opts]
11
+ */
12
+ export function writeFileAtomic(target, contents, { fsImpl = fs } = {}) {
13
+ const tmp = `${target}.${process.pid}.tmp`;
14
+ try {
15
+ fsImpl.mkdirSync(path.dirname(target), { recursive: true });
16
+ fsImpl.writeFileSync(tmp, contents, 'utf8');
17
+ fsImpl.renameSync(tmp, target);
18
+ } catch (err) {
19
+ reapTmp(fsImpl, tmp);
20
+ throw err;
21
+ }
22
+ }
23
+
24
+ function reapTmp(fsImpl, tmp) {
25
+ try {
26
+ if (typeof fsImpl.rmSync === 'function')
27
+ fsImpl.rmSync(tmp, { force: true });
28
+ else fsImpl.unlinkSync(tmp);
29
+ } catch {}
30
+ }
@@ -29,3 +29,54 @@ export function dirExists(dir) {
29
29
  return false;
30
30
  }
31
31
  }
32
+
33
+ /**
34
+ * Non-directory entries under `dir` passing `filter`, pruning `skipDirs`
35
+ * before descent. A missing root is `[]`; any other readdir error throws,
36
+ * or, given `onError(err, dir)`, is reported and that directory skipped.
37
+ *
38
+ * @param {string} dir
39
+ * @param {{ skipDirs?: Iterable<string> | ((name: string) => boolean), filter?: (absPath: string, dirent: fs.Dirent) => boolean, onError?: (err: Error, dir: string) => void, fsImpl?: typeof fs }} [opts]
40
+ * @returns {string[]}
41
+ */
42
+ export function walkFiles(
43
+ dir,
44
+ { skipDirs = [], filter, onError, fsImpl = fs } = {},
45
+ ) {
46
+ const skip = toSkipPredicate(skipDirs);
47
+ const out = [];
48
+ const visit = (current) => {
49
+ for (const dirent of readEntries(
50
+ fsImpl,
51
+ current,
52
+ current === dir,
53
+ onError,
54
+ )) {
55
+ const abs = path.join(current, dirent.name);
56
+ if (dirent.isDirectory()) {
57
+ if (!skip(dirent.name)) visit(abs);
58
+ } else if (!filter || filter(abs, dirent)) {
59
+ out.push(abs);
60
+ }
61
+ }
62
+ };
63
+ visit(dir);
64
+ return out;
65
+ }
66
+
67
+ function toSkipPredicate(skipDirs) {
68
+ if (typeof skipDirs === 'function') return skipDirs;
69
+ const names = new Set(skipDirs);
70
+ return (name) => names.has(name);
71
+ }
72
+
73
+ function readEntries(fsImpl, dir, isRoot, onError) {
74
+ try {
75
+ return fsImpl.readdirSync(dir, { withFileTypes: true });
76
+ } catch (err) {
77
+ if (isRoot && err?.code === 'ENOENT') return [];
78
+ if (!onError) throw err;
79
+ onError(err, dir);
80
+ return [];
81
+ }
82
+ }
@@ -13,3 +13,9 @@ export function defaultSleep(ms) {
13
13
  setTimeout(resolve, ms);
14
14
  });
15
15
  }
16
+
17
+ /** Blocks without spinning; a no-op for a non-finite or non-positive `ms`. */
18
+ export function sleepSync(ms) {
19
+ if (!Number.isFinite(ms) || ms <= 0) return;
20
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
21
+ }