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
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The gh environment, owned by the gh boundary (`gh-exec.js`): Node builtins
3
+ * only, so doctor and the bootstrap preflight can import it.
4
+ */
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { applyLocalOverlay } from './config/agentrc-overlay.js';
9
+ import { applyGhConfigDir } from './config/gh-config-dir.js';
10
+ import {
11
+ overlayRoot,
12
+ resolveAgentrcRoot,
13
+ storeRoot,
14
+ } from './config/git-roots.js';
15
+
16
+ /** Applied dir (or null) per anchor root. */
17
+ const _ensuredByRoot = new Map();
18
+
19
+ function readCommittedAgentrc(fsImpl, root) {
20
+ try {
21
+ return JSON.parse(
22
+ fsImpl.readFileSync(path.join(root, '.agentrc.json'), 'utf8'),
23
+ );
24
+ } catch {
25
+ return {};
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Export `GH_CONFIG_DIR` from `github.cliConfigDir` before any `gh` spawn. A
31
+ * relative dir resolves against the main checkout, where the gitignored
32
+ * store lives. Memoised per anchor root unless deps are injected.
33
+ *
34
+ * @returns {string|null} the applied dir.
35
+ */
36
+ export function ensureGhEnv(deps = {}) {
37
+ const { cwd, env = process.env, fsImpl = fs, exec } = deps;
38
+ const memoize = env === process.env && fsImpl === fs && !exec;
39
+ const root = resolveAgentrcRoot({ cwd, env, exec });
40
+ if (memoize && _ensuredByRoot.has(root)) return _ensuredByRoot.get(root);
41
+ const { effective } = applyLocalOverlay({
42
+ fsImpl,
43
+ projectRoot: overlayRoot(root, exec),
44
+ committed: readCommittedAgentrc(fsImpl, root),
45
+ });
46
+ const dir = applyGhConfigDir(effective?.github, storeRoot(root, exec), {
47
+ env,
48
+ fsImpl,
49
+ });
50
+ if (memoize) _ensuredByRoot.set(root, dir);
51
+ return dir;
52
+ }
53
+
54
+ /** `base` with the ensured `GH_CONFIG_DIR` layered on; throws a config error. */
55
+ export function ghEnv(base = process.env) {
56
+ const dir = ensureGhEnv();
57
+ return dir ? { ...base, GH_CONFIG_DIR: dir } : base;
58
+ }
59
+
60
+ /**
61
+ * `{ env }` — `base` with the ensured `GH_CONFIG_DIR` — or, on a config
62
+ * error, `{ failure }`: a failed `spawnSync`-shaped result carrying it.
63
+ */
64
+ export function tryGhEnv(base = process.env) {
65
+ try {
66
+ return { env: ghEnv(base) };
67
+ } catch (error) {
68
+ return {
69
+ failure: { status: null, stdout: '', stderr: error.message, error },
70
+ };
71
+ }
72
+ }
@@ -4,6 +4,8 @@
4
4
  */
5
5
 
6
6
  import { spawn as defaultSpawn } from 'node:child_process';
7
+ import { spawnChild } from './child-exec.js';
8
+ import { ghEnv, tryGhEnv } from './gh-env.js';
7
9
  import {
8
10
  isTransportFailure,
9
11
  sandboxDenialCode,
@@ -13,6 +15,23 @@ import {
13
15
 
14
16
  let _spawnCount = 0;
15
17
 
18
+ /**
19
+ * `gh` through `spawnChild` (an injected runner is its `run` seam), with the
20
+ * gh env ensured. A gh-env config error never throws: it returns a failed
21
+ * `spawnSync`-shaped result carrying it as `error`.
22
+ */
23
+ export function runGh(args, opts = {}, runner) {
24
+ const { env, failure } = tryGhEnv(opts.env);
25
+ return failure ?? spawnChild('gh', args, { ...opts, env, run: runner });
26
+ }
27
+
28
+ /** `runGh` for a throwing runner (`execFileSync`): a config error throws too. */
29
+ export function runGhOrThrow(args, opts, runner) {
30
+ const out = runGh(args, opts, runner);
31
+ if (out?.error) throw out.error;
32
+ return out;
33
+ }
34
+
16
35
  /**
17
36
  * @returns {number}
18
37
  */
@@ -243,10 +262,16 @@ export function exec({
243
262
  );
244
263
  }
245
264
 
265
+ let env;
266
+ try {
267
+ env = ghEnv();
268
+ } catch (err) {
269
+ return Promise.reject(err);
270
+ }
246
271
  const spawnOpts = {
247
272
  stdio: ['pipe', 'pipe', 'pipe'],
248
273
  shell: false,
249
- env: process.env,
274
+ env,
250
275
  };
251
276
  if (typeof timeoutMs === 'number' && timeoutMs > 0) {
252
277
  spawnOpts.timeout = timeoutMs;
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { Minimatch } from 'minimatch';
3
+ import picomatch from 'picomatch';
4
4
  import { canonicalise as canonicalisePath } from './baselines/path-canon.js';
5
5
  import { POOL_SERIAL_THRESHOLD, runOnPool } from './cpu-pool.js';
6
6
  import { Logger } from './Logger.js';
@@ -33,12 +33,12 @@ export const IGNORED_DIRS = new Set([
33
33
 
34
34
  /**
35
35
  * Compiled matchers plus a per-path verdict memo, keyed on the pattern list:
36
- * functional `minimatch()` recompiles per call, and the gates ask about the
36
+ * `picomatch.isMatch()` recompiles per call, and the gates ask about the
37
37
  * same path once per CRAP row. Inputs are immutable config, so it is bounded.
38
38
  * `\u0000` is the join separator because it cannot occur in a glob, so two
39
39
  * different lists cannot collide onto one key.
40
40
  *
41
- * @type {Map<string, {matchers: import('minimatch').Minimatch[], verdicts: Map<string, boolean>}>}
41
+ * @type {Map<string, {matchers: ((path: string) => boolean)[], verdicts: Map<string, boolean>}>}
42
42
  */
43
43
  const IGNORE_MATCHER_CACHE = new Map();
44
44
 
@@ -46,7 +46,7 @@ const IGNORE_MATCHER_CACHE = new Map();
46
46
  * Non-string patterns are dropped rather than compiled.
47
47
  *
48
48
  * @param {string[]} ignoreGlobs
49
- * @returns {{matchers: import('minimatch').Minimatch[], verdicts: Map<string, boolean>}}
49
+ * @returns {{matchers: ((path: string) => boolean)[], verdicts: Map<string, boolean>}}
50
50
  */
51
51
  function ignoreMatcherEntry(ignoreGlobs) {
52
52
  const key = ignoreGlobs.join('\u0000');
@@ -55,7 +55,7 @@ function ignoreMatcherEntry(ignoreGlobs) {
55
55
  entry = {
56
56
  matchers: ignoreGlobs
57
57
  .filter((g) => typeof g === 'string')
58
- .map((g) => new Minimatch(g, { dot: true })),
58
+ .map((g) => picomatch(g, { dot: true })),
59
59
  verdicts: new Map(),
60
60
  };
61
61
  IGNORE_MATCHER_CACHE.set(key, entry);
@@ -69,7 +69,7 @@ function ignoreMatcherEntry(ignoreGlobs) {
69
69
  * match.
70
70
  *
71
71
  * @param {string} filePath absolute or relative path to the source file
72
- * @param {string[]} ignoreGlobs minimatch patterns; empty/absent is a no-op
72
+ * @param {string[]} ignoreGlobs picomatch patterns; empty/absent is a no-op
73
73
  * @param {string} [cwd] root for repo-relative resolution; defaults to cwd
74
74
  * @returns {boolean} true when the file matches at least one ignore glob
75
75
  */
@@ -89,14 +89,14 @@ function canonicalRelPath(filePath, matchCwd) {
89
89
  /**
90
90
  * Split out to keep `isIgnoredByGlobs` under the per-method CRAP contract.
91
91
  *
92
- * @param {{matchers: import('minimatch').Minimatch[], verdicts: Map<string, boolean>}} entry
92
+ * @param {{matchers: ((path: string) => boolean)[], verdicts: Map<string, boolean>}} entry
93
93
  * @param {string} relPath Canonicalised, POSIX, repo-relative path.
94
94
  * @returns {boolean}
95
95
  */
96
96
  function memoisedIgnoreVerdict(entry, relPath) {
97
97
  const memoised = entry.verdicts.get(relPath);
98
98
  if (memoised !== undefined) return memoised;
99
- const verdict = entry.matchers.some((m) => m.match(relPath));
99
+ const verdict = entry.matchers.some((isMatch) => isMatch(relPath));
100
100
  entry.verdicts.set(relPath, verdict);
101
101
  return verdict;
102
102
  }
@@ -27,7 +27,7 @@ export function readPackageScripts(cwd) {
27
27
  * Runnable means a present, non-empty string.
28
28
  *
29
29
  * @param {Record<string, string>} scripts - A scripts map.
30
- * @param {string} name - The script name to check (e.g. `test:coverage`).
30
+ * @param {string} name - The script name to check (e.g. the coverage gate's `captureScript`).
31
31
  * @returns {boolean}
32
32
  */
33
33
  export function hasNpmScript(scripts, name) {
@@ -11,11 +11,8 @@
11
11
  import { readFileSync } from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
-
15
- import Ajv from 'ajv';
16
- import addFormats from 'ajv-formats';
17
-
18
14
  import { Logger } from '../Logger.js';
15
+ import { createAjv } from '../util/ajv.js';
19
16
 
20
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
18
  const SCHEMA_PATH = path.resolve(
@@ -36,8 +33,7 @@ const SCHEMA_PATH = path.resolve(
36
33
  function buildValidator() {
37
34
  try {
38
35
  const schema = JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'));
39
- const ajv = new Ajv({ allErrors: true, strict: false });
40
- addFormats(ajv);
36
+ const ajv = createAjv({ allErrors: true, strict: false });
41
37
  return ajv.compile(schema);
42
38
  } catch (err) {
43
39
  Logger.warn(
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
 
4
4
  import { orchestrationLogDir } from '../config/temp-paths.js';
5
5
  import { Logger } from '../Logger.js';
6
+ import { slugifyLabel } from '../util/slug.js';
6
7
 
7
8
  /**
8
9
  * Hot-path CLIs log their full result and print one summary line, keeping a
@@ -17,12 +18,7 @@ const RESULT_DETAIL_ENV = 'MANDREL_RESULT_DETAIL';
17
18
  * @returns {string}
18
19
  */
19
20
  function slugify(label) {
20
- return (
21
- String(label)
22
- .toLowerCase()
23
- .replace(/[^a-z0-9]+/g, '-')
24
- .replace(/^-+|-+$/g, '') || 'result'
25
- );
21
+ return slugifyLabel(String(label), { fallback: 'result' });
26
22
  }
27
23
 
28
24
  /**
@@ -4,7 +4,11 @@
4
4
  * here aborts a run.
5
5
  */
6
6
 
7
- import { isInsufficientScopes } from '../../providers/github/projects-v2-graphql.js';
7
+ import {
8
+ errorTextMatches,
9
+ isInsufficientScopes,
10
+ } from '../../providers/github/projects-v2-graphql.js';
11
+ import { describeGhFailure, GhScopeError } from '../gh-exec.js';
8
12
  import { Logger } from '../Logger.js';
9
13
 
10
14
  const PROJECT_SCOPE = 'project';
@@ -20,6 +24,8 @@ export const SCOPE_FAILURE = Object.freeze({
20
24
  const AUTH_FAILURE_RE =
21
25
  /\bFORBIDDEN\b|Bad credentials|\b(?:HTTP|GraphQL) 40[13]\b/;
22
26
 
27
+ const ACCESS_ERROR_NAMES = new Set(['ProjectAccessError', 'GhScopeError']);
28
+
23
29
  /**
24
30
  * The board is unreachable with this token — a missing `project` scope or an
25
31
  * auth refusal, never an owner-type miss.
@@ -39,17 +45,17 @@ export class ProjectAccessError extends Error {
39
45
 
40
46
  /**
41
47
  * Is `err` a token-scope / auth refusal (as opposed to a NOT_FOUND miss or a
42
- * transient failure)? A `ProjectAccessError` always is.
48
+ * transient failure)? A `ProjectAccessError` or `GhScopeError` always is.
43
49
  *
44
50
  * @param {unknown} err
45
51
  * @returns {boolean}
46
52
  */
47
53
  export function isProjectAccessFailure(err) {
48
54
  if (!err) return false;
49
- if (err instanceof ProjectAccessError) return true;
50
- if (isInsufficientScopes(err)) return true;
51
- const message = typeof err.message === 'string' ? err.message : String(err);
52
- return AUTH_FAILURE_RE.test(message);
55
+ if (err instanceof GhScopeError || ACCESS_ERROR_NAMES.has(err.name)) {
56
+ return true;
57
+ }
58
+ return isInsufficientScopes(err) || errorTextMatches(err, AUTH_FAILURE_RE);
53
59
  }
54
60
 
55
61
  /**
@@ -60,7 +66,7 @@ export function isProjectAccessFailure(err) {
60
66
  */
61
67
  export function toProjectAccessError(err) {
62
68
  if (err instanceof ProjectAccessError) return err;
63
- const detail = err?.message ?? String(err);
69
+ const detail = describeGhFailure(err);
64
70
  return new ProjectAccessError(
65
71
  `GitHub Projects v2 board is not accessible with this token (missing the "${PROJECT_SCOPE}" scope?): ${detail}`,
66
72
  { cause: err },
@@ -68,7 +74,12 @@ export function toProjectAccessError(err) {
68
74
  }
69
75
 
70
76
  // Sinks already warned; production shares one `Logger`, so once per process.
71
- const warnedSinks = new WeakSet();
77
+ let warnedSinks = new WeakSet();
78
+
79
+ /** Test isolation: forget every warned sink. */
80
+ export function resetBoardAccessLatch() {
81
+ warnedSinks = new WeakSet();
82
+ }
72
83
 
73
84
  /**
74
85
  * Record a board scope failure; the first call per process (per sink) emits
@@ -21,8 +21,8 @@ import {
21
21
  writeFileSync,
22
22
  } from 'node:fs';
23
23
  import path from 'node:path';
24
- import { spawnChild } from '../child-exec.js';
25
24
  import { resolveConfig } from '../config-resolver.js';
25
+ import { runGh } from '../gh-exec.js';
26
26
  import { Logger } from '../Logger.js';
27
27
  import { createProvider } from '../provider-factory.js';
28
28
  import { isRerunPermitted } from './check-state.js';
@@ -97,10 +97,10 @@ function ciDigestPaths({ storyId = null, tempRoot, cwd }) {
97
97
  */
98
98
  function ghRunLogTail({ runId, cwd, spawnFn, maxLines = 40 }) {
99
99
  if (!runId) return '';
100
- const result = spawnChild(
101
- 'gh',
100
+ const result = runGh(
102
101
  ['run', 'view', String(runId), '--log-failed'],
103
- { run: spawnFn, cwd },
102
+ { cwd },
103
+ spawnFn,
104
104
  );
105
105
  const out = (result.stdout ?? '').trim();
106
106
  if (out.length === 0) return '';
@@ -115,10 +115,10 @@ function ghRunLogTail({ runId, cwd, spawnFn, maxLines = 40 }) {
115
115
  * @returns {{ runId: string|null, url: string|null }}
116
116
  */
117
117
  function resolveFailingCheckRun({ prRef, checkName, cwd, spawnFn }) {
118
- const result = spawnChild(
119
- 'gh',
118
+ const result = runGh(
120
119
  ['pr', 'checks', prRef, '--json', 'name,link'],
121
- { run: spawnFn, cwd },
120
+ { cwd },
121
+ spawnFn,
122
122
  );
123
123
  try {
124
124
  const parsed = JSON.parse((result.stdout ?? '').trim() || '[]');
@@ -141,13 +141,10 @@ function resolveFailingCheckRun({ prRef, checkName, cwd, spawnFn }) {
141
141
  * @returns {string|null}
142
142
  */
143
143
  export function resolvePrHeadSha({ prRef, cwd, spawnFn }) {
144
- const result = spawnChild(
145
- 'gh',
144
+ const result = runGh(
146
145
  ['pr', 'view', prRef, '--json', 'headRefOid'],
147
- {
148
- run: spawnFn,
149
- cwd,
150
- },
146
+ { cwd },
147
+ spawnFn,
151
148
  );
152
149
  if ((result?.status ?? 1) !== 0) return null;
153
150
  try {
@@ -13,6 +13,7 @@ import {
13
13
  } from '../config/temp-paths.js';
14
14
  import { gh as defaultGh } from '../gh-exec.js';
15
15
  import { gitSpawn as defaultGitSpawn, getStoryBranch } from '../git-utils.js';
16
+ import { defaultSleep } from '../util/sleep.js';
16
17
  import {
17
18
  CHECKS_FAILED_CLASS,
18
19
  deriveChecksStatus,
@@ -709,7 +710,7 @@ export async function recoverStory({
709
710
  fsImpl,
710
711
  reprobe = true,
711
712
  stabilityDelayMs = STABILITY_DELAY_MS,
712
- sleepFn = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
713
+ sleepFn = defaultSleep,
713
714
  }) {
714
715
  const storyBranch = getStoryBranch(storyId);
715
716
  const probeArgs = {
@@ -5,8 +5,8 @@
5
5
  * @module lib/orchestration/git-cleanup/phases/git-probes
6
6
  */
7
7
 
8
- import { execFileSync } from 'node:child_process';
9
-
8
+ import { execFileCapture } from '../../../child-exec.js';
9
+ import { runGhOrThrow } from '../../../gh-exec.js';
10
10
  import { gitSpawn } from '../../../git-utils.js';
11
11
  import { parseWorktreePorcelain } from '../../../worktree-manager.js';
12
12
  import { makeWorktreeOps } from './git-probes-ff.js';
@@ -168,7 +168,7 @@ export function worktreesByBranch(cwd) {
168
168
  /* node:coverage ignore next */
169
169
  // Synchronous on purpose: `planCleanup` is a sync planner.
170
170
  export function defaultGhRunner(args, { cwd }) {
171
- return execFileSync('gh', args, { cwd, encoding: 'utf8' });
171
+ return runGhOrThrow(args, { cwd, encoding: 'utf8' }, execFileCapture);
172
172
  }
173
173
 
174
174
  /**
@@ -6,11 +6,8 @@
6
6
  import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
-
10
- import Ajv2020 from 'ajv/dist/2020.js';
11
- import addFormats from 'ajv-formats';
12
-
13
9
  import { storyLedgerPath } from '../../config/temp-paths.js';
10
+ import { createAjv2020 } from '../../util/ajv.js';
14
11
 
15
12
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
13
  const SCHEMA_DIR = path.resolve(
@@ -42,8 +39,7 @@ function getValidator(schemaFile) {
42
39
  const schema = JSON.parse(
43
40
  readFileSync(path.resolve(SCHEMA_DIR, schemaFile), 'utf8'),
44
41
  );
45
- const ajv = new Ajv2020({ allErrors: true, strict: false });
46
- addFormats(ajv);
42
+ const ajv = createAjv2020({ allErrors: true, strict: false });
47
43
  const validator = ajv.compile(schema);
48
44
  _validators.set(schemaFile, validator);
49
45
  return validator;
@@ -7,6 +7,7 @@
7
7
  * @module lib/orchestration/light-suitability
8
8
  */
9
9
 
10
+ import { slugifyLabel } from '../util/slug.js';
10
11
  import { deriveStoryShape, SHAPE_CODES } from './complexity-gate.js';
11
12
  import { deriveChangeLevel } from './review-depth.js';
12
13
 
@@ -387,13 +388,10 @@ const RECEIPT_SLUG_MAX = 48;
387
388
  * @returns {string}
388
389
  */
389
390
  function slugifyPrompt(text) {
390
- const slug = text
391
- .toLowerCase()
392
- .replace(/[^a-z0-9]+/g, '-')
393
- .replace(/^-+|-+$/g, '')
394
- .slice(0, RECEIPT_SLUG_MAX)
395
- .replace(/-+$/g, '');
396
- return slug === '' ? 'light-change' : slug;
391
+ return slugifyLabel(text, {
392
+ max: RECEIPT_SLUG_MAX,
393
+ fallback: 'light-change',
394
+ });
397
395
  }
398
396
 
399
397
  const RECEIPT_TITLE_MAX = 72;
@@ -5,7 +5,7 @@
5
5
  * skip or wait forever on a check. Returns a verdict; no side effects.
6
6
  */
7
7
 
8
- import { spawnSync } from 'node:child_process';
8
+ import { runGh as spawnGh } from '../gh-exec.js';
9
9
  import { defaultSleep } from '../util/sleep.js';
10
10
  import { applyBehindUpdate } from './behind-recovery.js';
11
11
  import { createCancelledRunDiscount } from './cancelled-run-discount.js';
@@ -31,12 +31,12 @@ function ghRepoFlag(repo) {
31
31
  return trimmed.length > 0 ? ['--repo', trimmed] : [];
32
32
  }
33
33
 
34
- function runGh(args, { cwd, repo, spawnFn = spawnSync }) {
35
- const result = spawnFn('gh', [...args, ...ghRepoFlag(repo)], {
36
- cwd,
37
- encoding: 'utf-8',
38
- shell: false,
39
- });
34
+ function runGh(args, { cwd, repo, spawnFn }) {
35
+ const result = spawnGh(
36
+ [...args, ...ghRepoFlag(repo)],
37
+ { cwd, encoding: 'utf-8', shell: false },
38
+ spawnFn,
39
+ );
40
40
  return {
41
41
  status: result.status ?? 1,
42
42
  stdout: result.stdout ?? '',
@@ -10,6 +10,7 @@
10
10
  import fs from 'node:fs';
11
11
  import path from 'node:path';
12
12
  import { anchorTempRoot, tempRootFrom } from '../config/temp-paths.js';
13
+ import { writeFileAtomic } from '../util/atomic-write.js';
13
14
 
14
15
  /** One hour spans a delivery run's cold flips yet forces periodic refresh. */
15
16
  const DEFAULT_META_TTL_MS = 60 * 60 * 1000;
@@ -58,17 +59,7 @@ function readCacheFile(filePath) {
58
59
 
59
60
  /** Tmp + rename: a reader never sees a partial write. Throws; reaps the tmp. */
60
61
  function writeStoreAtomic(filePath, store) {
61
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
62
- const tmp = `${filePath}.${process.pid}.tmp`;
63
- try {
64
- fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
65
- fs.renameSync(tmp, filePath);
66
- } catch (err) {
67
- try {
68
- fs.unlinkSync(tmp);
69
- } catch {}
70
- throw err;
71
- }
62
+ writeFileAtomic(filePath, `${JSON.stringify(store, null, 2)}\n`);
72
63
  }
73
64
 
74
65
  /**
@@ -14,9 +14,9 @@
14
14
 
15
15
  import { createHash } from 'node:crypto';
16
16
  import nodeFs from 'node:fs';
17
- import path from 'node:path';
18
17
 
19
18
  import { storyReviewDepositPath } from '../config/temp-paths.js';
19
+ import { writeFileAtomic } from '../util/atomic-write.js';
20
20
  import { resolveSharedBaseRef } from './review-base-ref.js';
21
21
 
22
22
  const DEPOSIT_KIND = 'story-review-deposit';
@@ -137,14 +137,7 @@ export function depositAsComputedReview(deposit) {
137
137
  */
138
138
  export function writeReviewDeposit(deposit, { config, fsImpl = nodeFs } = {}) {
139
139
  const target = storyReviewDepositPath(deposit.storyId, config);
140
- fsImpl.mkdirSync(path.dirname(target), { recursive: true });
141
- const tmpPath = `${target}.${process.pid}.tmp`;
142
- fsImpl.writeFileSync(
143
- tmpPath,
144
- `${JSON.stringify(deposit, null, 2)}\n`,
145
- 'utf8',
146
- );
147
- fsImpl.renameSync(tmpPath, target);
140
+ writeFileAtomic(target, `${JSON.stringify(deposit, null, 2)}\n`, { fsImpl });
148
141
  return target;
149
142
  }
150
143