mandrel 2.89.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 (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 +38 -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/board-backfill.js +253 -0
  14. package/.agents/scripts/check-arch-cycles.js +1 -5
  15. package/.agents/scripts/check-context-budget.js +1 -5
  16. package/.agents/scripts/check-cyclomatic.js +1 -5
  17. package/.agents/scripts/check-dead-exports.js +23 -14
  18. package/.agents/scripts/check-doc-links.js +4 -4
  19. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  20. package/.agents/scripts/coverage-capture.js +14 -6
  21. package/.agents/scripts/diagnose-friction.js +8 -10
  22. package/.agents/scripts/generate-workflows-doc.js +5 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  24. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  25. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  26. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  27. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  28. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  29. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  30. package/.agents/scripts/lib/baselines/components.js +5 -5
  31. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  32. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  33. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  34. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  36. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  37. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  38. package/.agents/scripts/lib/baselines/writer.js +4 -4
  39. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  40. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  41. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  42. package/.agents/scripts/lib/child-exec.js +4 -4
  43. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  44. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  45. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  46. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  47. package/.agents/scripts/lib/close-validation/process.js +5 -1
  48. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  49. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  50. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  51. package/.agents/scripts/lib/config/commands.js +82 -7
  52. package/.agents/scripts/lib/config/explain.js +2 -1
  53. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  54. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  55. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  56. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  57. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  58. package/.agents/scripts/lib/config/git-roots.js +120 -0
  59. package/.agents/scripts/lib/config/quality.js +46 -50
  60. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  61. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  62. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  63. package/.agents/scripts/lib/config-resolver.js +5 -9
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  66. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  67. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  68. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  69. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  70. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  71. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture.js +80 -43
  73. package/.agents/scripts/lib/coverage-utils.js +34 -16
  74. package/.agents/scripts/lib/cpu-pool.js +2 -4
  75. package/.agents/scripts/lib/crap-engine.js +19 -1
  76. package/.agents/scripts/lib/crap-utils.js +2 -1
  77. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  78. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  79. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  80. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  81. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  82. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  83. package/.agents/scripts/lib/gh-env.js +72 -0
  84. package/.agents/scripts/lib/gh-exec.js +26 -1
  85. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  86. package/.agents/scripts/lib/npm-scripts.js +1 -1
  87. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  88. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  89. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  90. package/.agents/scripts/lib/orchestration/board-access-latch.js +112 -0
  91. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  92. package/.agents/scripts/lib/orchestration/column-sync.js +107 -52
  93. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  94. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  95. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  96. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  97. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  98. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  99. package/.agents/scripts/lib/orchestration/project-meta-resolver.js +44 -17
  100. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  101. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  102. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  103. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  104. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  105. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  106. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  107. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  108. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  109. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  110. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  111. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  112. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  113. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  114. package/.agents/scripts/lib/orchestration/story-handoff.js +27 -6
  115. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  116. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  117. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  118. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  119. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  120. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  121. package/.agents/scripts/lib/source-extensions.js +30 -15
  122. package/.agents/scripts/lib/test-run-credit.js +1 -9
  123. package/.agents/scripts/lib/test-temp.js +22 -21
  124. package/.agents/scripts/lib/util/ajv.js +111 -0
  125. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  126. package/.agents/scripts/lib/util/paths.js +51 -0
  127. package/.agents/scripts/lib/util/sleep.js +6 -0
  128. package/.agents/scripts/lib/util/slug.js +12 -0
  129. package/.agents/scripts/lib/validation-evidence.js +19 -40
  130. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  131. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  132. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  133. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  134. package/.agents/scripts/lint-issue-body.js +2 -2
  135. package/.agents/scripts/plan-context.js +2 -7
  136. package/.agents/scripts/providers/github/auth.js +3 -3
  137. package/.agents/scripts/providers/github/board-add.js +18 -9
  138. package/.agents/scripts/providers/github/errors.js +3 -1
  139. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  140. package/.agents/scripts/providers/github/issues.js +6 -2
  141. package/.agents/scripts/providers/github/mappers.js +1 -5
  142. package/.agents/scripts/providers/github/projects-v2-graphql.js +26 -6
  143. package/.agents/scripts/providers/github/search-budget.js +3 -1
  144. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  145. package/.agents/scripts/sync-agentrc.js +5 -14
  146. package/.agents/scripts/sync-claude-agents.js +38 -150
  147. package/.agents/scripts/sync-claude-commands.js +35 -218
  148. package/.agents/scripts/update-coverage-baseline.js +1 -1
  149. package/.agents/scripts/update-crap-baseline.js +1 -1
  150. package/.agents/scripts/update-duplication-baseline.js +2 -16
  151. package/.agents/scripts/validate-skills.js +6 -10
  152. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  153. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  154. package/.agents/workflows/audit-exceptions.md +9 -0
  155. package/.agents/workflows/audit-lean.md +129 -0
  156. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  157. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  158. package/.agents/workflows/helpers/code-review.md +15 -1
  159. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  160. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  161. package/.agents/workflows/mandrel-plan.md +2 -2
  162. package/docs/CHANGELOG.md +48 -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 +124 -0
  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 +11 -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(
@@ -26,6 +26,7 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
26
26
  'audit-exceptions.js',
27
27
  'audit-labels-bootstrap.js',
28
28
  'audit-to-stories.js',
29
+ 'board-backfill.js',
29
30
  'boot-sweep.js',
30
31
  'bootstrap.js',
31
32
  'check-arch-cycles.js',
@@ -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
  /**
@@ -0,0 +1,112 @@
1
+ /**
2
+ * board-access-latch — the typed Projects v2 access failure and a
3
+ * warn-once-per-process latch for it. Labels stay authoritative: nothing
4
+ * here aborts a run.
5
+ */
6
+
7
+ import {
8
+ errorTextMatches,
9
+ isInsufficientScopes,
10
+ } from '../../providers/github/projects-v2-graphql.js';
11
+ import { describeGhFailure, GhScopeError } from '../gh-exec.js';
12
+ import { Logger } from '../Logger.js';
13
+
14
+ const PROJECT_SCOPE = 'project';
15
+ const PROJECT_SCOPE_REMEDY = 'gh auth refresh -h github.com -s project';
16
+
17
+ /** The outcome shape a board seam reports for a scope failure. */
18
+ export const SCOPE_FAILURE = Object.freeze({
19
+ reason: 'insufficient-scope',
20
+ scope: PROJECT_SCOPE,
21
+ });
22
+
23
+ // GraphQL `FORBIDDEN`, or an explicit HTTP 401/403 from the GraphQL endpoint.
24
+ const AUTH_FAILURE_RE =
25
+ /\bFORBIDDEN\b|Bad credentials|\b(?:HTTP|GraphQL) 40[13]\b/;
26
+
27
+ const ACCESS_ERROR_NAMES = new Set(['ProjectAccessError', 'GhScopeError']);
28
+
29
+ /**
30
+ * The board is unreachable with this token — a missing `project` scope or an
31
+ * auth refusal, never an owner-type miss.
32
+ */
33
+ export class ProjectAccessError extends Error {
34
+ /**
35
+ * @param {string} message
36
+ * @param {{ cause?: unknown }} [opts]
37
+ */
38
+ constructor(message, { cause } = {}) {
39
+ super(message, { cause });
40
+ this.name = 'ProjectAccessError';
41
+ this.scope = PROJECT_SCOPE;
42
+ this.remedy = PROJECT_SCOPE_REMEDY;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Is `err` a token-scope / auth refusal (as opposed to a NOT_FOUND miss or a
48
+ * transient failure)? A `ProjectAccessError` or `GhScopeError` always is.
49
+ *
50
+ * @param {unknown} err
51
+ * @returns {boolean}
52
+ */
53
+ export function isProjectAccessFailure(err) {
54
+ if (!err) return false;
55
+ if (err instanceof GhScopeError || ACCESS_ERROR_NAMES.has(err.name)) {
56
+ return true;
57
+ }
58
+ return isInsufficientScopes(err) || errorTextMatches(err, AUTH_FAILURE_RE);
59
+ }
60
+
61
+ /**
62
+ * Wrap a raw scope/auth error in a `ProjectAccessError` (idempotent).
63
+ *
64
+ * @param {unknown} err
65
+ * @returns {ProjectAccessError}
66
+ */
67
+ export function toProjectAccessError(err) {
68
+ if (err instanceof ProjectAccessError) return err;
69
+ const detail = describeGhFailure(err);
70
+ return new ProjectAccessError(
71
+ `GitHub Projects v2 board is not accessible with this token (missing the "${PROJECT_SCOPE}" scope?): ${detail}`,
72
+ { cause: err },
73
+ );
74
+ }
75
+
76
+ // Sinks already warned; production shares one `Logger`, so once per process.
77
+ let warnedSinks = new WeakSet();
78
+
79
+ /** Test isolation: forget every warned sink. */
80
+ export function resetBoardAccessLatch() {
81
+ warnedSinks = new WeakSet();
82
+ }
83
+
84
+ /**
85
+ * Record a board scope failure; the first call per process (per sink) emits
86
+ * the one warning (stderr), later calls are silent.
87
+ *
88
+ * @param {{ logger?: { warn?: Function } }} [opts]
89
+ * @returns {boolean} true when this call emitted the warning.
90
+ */
91
+ export function reportBoardScopeFailure({ logger = Logger } = {}) {
92
+ if (warnedSinks.has(logger)) return false;
93
+ warnedSinks.add(logger);
94
+ logger.warn?.(
95
+ `GitHub Projects v2 board updates are failing: the token lacks the "${PROJECT_SCOPE}" scope, so board adds and Status flips are skipped (labels still move). Run \`${PROJECT_SCOPE_REMEDY}\`, then \`node .agents/scripts/board-backfill.js\` to catch the board up.`,
96
+ );
97
+ return true;
98
+ }
99
+
100
+ /**
101
+ * Classify a board-call failure: a scope/auth refusal trips the latch and
102
+ * yields the outcome fields to report; anything else yields null.
103
+ *
104
+ * @param {unknown} err
105
+ * @param {{ logger?: { warn?: Function } }} [opts]
106
+ * @returns {{ reason: 'insufficient-scope', scope: 'project' } | null}
107
+ */
108
+ export function boardScopeFailure(err, { logger } = {}) {
109
+ if (!isProjectAccessFailure(err)) return null;
110
+ reportBoardScopeFailure({ logger });
111
+ return SCOPE_FAILURE;
112
+ }
@@ -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 {
@@ -2,10 +2,17 @@
2
2
  * ColumnSync — collapse an issue's `agent::*` labels onto the stock Projects
3
3
  * v2 Status options (`Todo` / `In Progress` / `Done`) and push it via
4
4
  * GraphQL. Soft no-op when no project is configured, the Status field or
5
- * option is missing, or the issue is not on the board.
5
+ * option is missing, or the issue is not on the board. A token that cannot
6
+ * reach the board (missing `project` scope) reports `{ status: 'failed',
7
+ * reason: 'insufficient-scope' }` and trips the warn-once latch instead.
6
8
  */
7
9
 
8
10
  import { AGENT_LABELS } from '../label-constants.js';
11
+ import {
12
+ isProjectAccessFailure,
13
+ reportBoardScopeFailure,
14
+ SCOPE_FAILURE,
15
+ } from './board-access-latch.js';
9
16
  import {
10
17
  invalidateProjectMetaCache,
11
18
  readProjectMetaCache,
@@ -40,6 +47,59 @@ export function columnForLabels(labels) {
40
47
  return null;
41
48
  }
42
49
 
50
+ /**
51
+ * The issue's item id on board `projectId`, or null. Walks issue →
52
+ * projectItems, not board → items: scanning board items hits a pagination
53
+ * cliff on large boards; an issue is on few boards.
54
+ */
55
+ async function getProjectItemId(provider, issueId, projectId) {
56
+ const owner = provider.owner;
57
+ const repo = provider.repo;
58
+ if (!owner || !repo) return null;
59
+ const data = await provider.graphql(
60
+ `
61
+ query($owner: String!, $repo: String!, $number: Int!) {
62
+ repository(owner: $owner, name: $repo) {
63
+ issue(number: $number) {
64
+ projectItems(first: 20) {
65
+ nodes {
66
+ id
67
+ project { id }
68
+ }
69
+ }
70
+ }
71
+ }
72
+ }`,
73
+ { owner, repo, number: issueId },
74
+ );
75
+ const nodes = data?.repository?.issue?.projectItems?.nodes ?? [];
76
+ const match = nodes.find((n) => n?.project?.id === projectId);
77
+ return match?.id ?? null;
78
+ }
79
+
80
+ /** Push one Status option onto a board item. */
81
+ async function updateStatusField(provider, meta, itemId, optionId) {
82
+ await provider.graphql(
83
+ `
84
+ mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
85
+ updateProjectV2ItemFieldValue(
86
+ input: {
87
+ projectId: $projectId,
88
+ itemId: $itemId,
89
+ fieldId: $fieldId,
90
+ value: { singleSelectOptionId: $optionId }
91
+ }
92
+ ) { projectV2Item { id } }
93
+ }`,
94
+ {
95
+ projectId: meta.projectId,
96
+ itemId,
97
+ fieldId: meta.fieldId,
98
+ optionId,
99
+ },
100
+ );
101
+ }
102
+
43
103
  export class ColumnSync {
44
104
  /**
45
105
  * @param {{
@@ -68,6 +128,8 @@ export class ColumnSync {
68
128
  this._meta = null; // lazy-cached { projectId, fieldId, options: Map<name, id> }
69
129
  // Disk-hydrated meta may be stale; a failed mutation then invalidates it.
70
130
  this._metaFromDiskCache = false;
131
+ // A scope/auth refusal seen this process; memory only, never on disk.
132
+ this._accessFailed = false;
71
133
  }
72
134
 
73
135
  /**
@@ -92,47 +154,58 @@ export class ColumnSync {
92
154
  if (!this.projectNumber) {
93
155
  return { status: 'skipped', reason: 'no-project' };
94
156
  }
157
+ try {
158
+ return await this.#setColumnOnBoard(issueId, column);
159
+ } catch (err) {
160
+ if (!isProjectAccessFailure(err)) throw err;
161
+ return this.#scopeFailure();
162
+ }
163
+ }
95
164
 
165
+ async #setColumnOnBoard(issueId, column) {
96
166
  const meta = await this.#loadMeta();
97
- if (!meta) return { status: 'skipped', reason: 'no-meta' };
167
+ if (!meta) return this.#metaMiss();
98
168
 
99
169
  const optionId = meta.options.get(column);
100
170
  if (!optionId) {
101
171
  return { status: 'skipped', reason: `no-option-${column}` };
102
172
  }
103
173
 
104
- const itemId = await this.#getProjectItemId(issueId, meta.projectId);
174
+ const itemId = await getProjectItemId(
175
+ this.provider,
176
+ issueId,
177
+ meta.projectId,
178
+ );
105
179
  if (!itemId) return { status: 'skipped', reason: 'not-on-project' };
106
180
 
107
181
  try {
108
- await this.provider.graphql(
109
- `
110
- mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
111
- updateProjectV2ItemFieldValue(
112
- input: {
113
- projectId: $projectId,
114
- itemId: $itemId,
115
- fieldId: $fieldId,
116
- value: { singleSelectOptionId: $optionId }
117
- }
118
- ) { projectV2Item { id } }
119
- }`,
120
- {
121
- projectId: meta.projectId,
122
- itemId,
123
- fieldId: meta.fieldId,
124
- optionId,
125
- },
126
- );
182
+ await updateStatusField(this.provider, meta, itemId, optionId);
127
183
  } catch (err) {
128
184
  // Likely a reconfigured board: drop cached meta so the next flip
129
- // self-heals, and re-throw for the caller's handling.
130
- this.#invalidateMetaCache();
185
+ // self-heals, and re-throw for the caller's handling. A scope refusal
186
+ // is not staleness, so the cache stays.
187
+ if (!isProjectAccessFailure(err)) this.#invalidateMetaCache();
131
188
  throw err;
132
189
  }
133
190
  return { status: 'synced', column };
134
191
  }
135
192
 
193
+ /** No meta: a latched scope refusal, or a board without a Status field. */
194
+ #metaMiss() {
195
+ if (this._accessFailed) return this.#scopeFailure();
196
+ return { status: 'skipped', reason: 'no-meta' };
197
+ }
198
+
199
+ /**
200
+ * Latch the scope failure (one warning per process) and report it to the
201
+ * caller; never throws, so the label transition still completes.
202
+ */
203
+ #scopeFailure() {
204
+ this._accessFailed = true;
205
+ reportBoardScopeFailure({ logger: this.logger });
206
+ return { status: 'failed', ...SCOPE_FAILURE };
207
+ }
208
+
136
209
  /**
137
210
  * Cache key; same owner `#loadMeta` resolves against.
138
211
  *
@@ -158,6 +231,7 @@ export class ColumnSync {
158
231
  }
159
232
 
160
233
  async #loadMeta() {
234
+ if (this._accessFailed) return null;
161
235
  if (this._meta !== null) return this._meta || null;
162
236
  // Board meta is repo-invariant; the disk cache spares each cold CLI
163
237
  // process the resolve round-trips.
@@ -208,6 +282,10 @@ export class ColumnSync {
208
282
  this._metaFromDiskCache = false;
209
283
  return this._meta;
210
284
  } catch (err) {
285
+ if (isProjectAccessFailure(err)) {
286
+ this._accessFailed = true;
287
+ return null;
288
+ }
211
289
  this.logger.warn?.(
212
290
  `[ColumnSync] could not resolve project metadata: ${err?.message ?? err}`,
213
291
  );
@@ -227,7 +305,11 @@ export class ColumnSync {
227
305
  if (!this.projectNumber) return null;
228
306
  const meta = await this.#loadMeta();
229
307
  if (!meta) return null;
230
- const itemId = await this.#getProjectItemId(issueId, meta.projectId);
308
+ const itemId = await getProjectItemId(
309
+ this.provider,
310
+ issueId,
311
+ meta.projectId,
312
+ );
231
313
  if (!itemId) return null;
232
314
  try {
233
315
  const data = await this.provider.graphql(
@@ -252,31 +334,4 @@ export class ColumnSync {
252
334
  return null;
253
335
  }
254
336
  }
255
-
256
- async #getProjectItemId(issueId, projectId) {
257
- // Walk issue → projectItems, not board → items: scanning board items
258
- // hits a pagination cliff on large boards; an issue is on few boards.
259
- const owner = this.provider.owner;
260
- const repo = this.provider.repo;
261
- if (!owner || !repo) return null;
262
- const data = await this.provider.graphql(
263
- `
264
- query($owner: String!, $repo: String!, $number: Int!) {
265
- repository(owner: $owner, name: $repo) {
266
- issue(number: $number) {
267
- projectItems(first: 20) {
268
- nodes {
269
- id
270
- project { id }
271
- }
272
- }
273
- }
274
- }
275
- }`,
276
- { owner, repo, number: issueId },
277
- );
278
- const nodes = data?.repository?.issue?.projectItems?.nodes ?? [];
279
- const match = nodes.find((n) => n?.project?.id === projectId);
280
- return match?.id ?? null;
281
- }
282
337
  }
@@ -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
  /**