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
@@ -7,9 +7,9 @@
7
7
  import fs from 'node:fs';
8
8
  import { rm as fsPromisesRm } from 'node:fs/promises';
9
9
  import { fileURLToPath } from 'node:url';
10
+ import { defaultSleep, sleepSync } from '../../util/sleep.js';
10
11
  import { canonicalPath } from '../canonical-path.js';
11
12
  import { isInsideWorktree, samePath } from '../inspector.js';
12
- import { sleepSync } from '../node-modules-strategy.js';
13
13
  import { checkMergeReachability } from './merge-reachability.js';
14
14
  import { recordPendingCleanup } from './pending-cleanup.js';
15
15
  import { checkLocalSafety } from './precheck.js';
@@ -108,7 +108,7 @@ async function fsRmWithRetry(
108
108
  } catch (err) {
109
109
  lastErr = err;
110
110
  if (attempt < maxRetries && retryDelay > 0) {
111
- await new Promise((r) => setTimeout(r, retryDelay));
111
+ await defaultSleep(retryDelay);
112
112
  }
113
113
  }
114
114
  }
@@ -6,16 +6,26 @@
6
6
  * install), `symlink` (to a donor; opt-in on Windows) and `pnpm-store`.
7
7
  */
8
8
 
9
- import { spawnSync } from 'node:child_process';
10
9
  import crypto from 'node:crypto';
11
10
  import fs from 'node:fs';
12
11
  import path from 'node:path';
12
+ import { spawnChild } from '../child-exec.js';
13
13
  import { detectPackageManager } from '../detect-package-manager.js';
14
+ import { sleepSync } from '../util/sleep.js';
14
15
 
15
- function sleepSync(ms) {
16
- if (!Number.isFinite(ms) || ms <= 0) return;
17
- const signal = new Int32Array(new SharedArrayBuffer(4));
18
- Atomics.wait(signal, 0, 0, ms);
16
+ /**
17
+ * Every spawn here goes through `spawnChild` so the wrapper's stdout ceiling
18
+ * applies: a chatty install overflowing Node's 1 MiB default would be killed
19
+ * mid-write and leave a half-populated `node_modules`. An injected `spawnFn`
20
+ * becomes the wrapper's `run` seam, so tests still see every call.
21
+ *
22
+ * @param {Function|undefined} spawnFn - `spawnSync`-shaped seam; omitted → real.
23
+ * @param {string} cmd
24
+ * @param {string[]} args
25
+ * @param {object} opts
26
+ */
27
+ function runChild(spawnFn, cmd, args, opts) {
28
+ return spawnChild(cmd, args, spawnFn ? { ...opts, run: spawnFn } : opts);
19
29
  }
20
30
 
21
31
  /**
@@ -106,11 +116,11 @@ export function applyNodeModulesStrategy(ctx, wtPath) {
106
116
  *
107
117
  * @param {{ config: object, platform: NodeJS.Platform, logger: object, repoRoot: string }} ctx
108
118
  * @param {string} wtPath
109
- * @param {{ spawnFn?: typeof spawnSync, fsLike?: typeof fs }} [io]
119
+ * @param {{ spawnFn?: Function, fsLike?: typeof fs }} [io]
110
120
  * @returns {{ cloned: boolean, reason?: string }}
111
121
  */
112
122
  export function cloneNodeModules(ctx, wtPath, io = {}) {
113
- const spawnFn = io.spawnFn ?? spawnSync;
123
+ const spawnFn = io.spawnFn;
114
124
  const fsLike = io.fsLike ?? fs;
115
125
  // Real host OS, not `ctx.platform`: Windows has no clone `cp` here.
116
126
  if (process.platform === 'win32') {
@@ -144,7 +154,7 @@ export function cloneNodeModules(ctx, wtPath, io = {}) {
144
154
  process.platform === 'darwin'
145
155
  ? ['-c', '-R', donorNodeModules, target]
146
156
  : ['--reflink=always', '-R', donorNodeModules, target];
147
- const result = spawnFn('cp', cloneArgs, {
157
+ const result = runChild(spawnFn, 'cp', cloneArgs, {
148
158
  cwd: wtPath,
149
159
  stdio: 'pipe',
150
160
  encoding: 'utf-8',
@@ -319,7 +329,7 @@ function primePnpmStore({
319
329
  strategy,
320
330
  repoRoot,
321
331
  logger,
322
- spawnFn = spawnSync,
332
+ spawnFn,
323
333
  fsLike = fs,
324
334
  shell = process.platform === 'win32',
325
335
  }) {
@@ -334,7 +344,7 @@ function primePnpmStore({
334
344
  logger.info(
335
345
  `worktree.install priming pnpm content-addressable store at ${repoRoot} (sentinel missing)`,
336
346
  );
337
- const result = spawnFn('pnpm', ['install', '--frozen-lockfile'], {
347
+ const result = runChild(spawnFn, 'pnpm', ['install', '--frozen-lockfile'], {
338
348
  cwd: repoRoot,
339
349
  stdio: 'pipe',
340
350
  encoding: 'utf-8',
@@ -391,7 +401,7 @@ export function runInstallWithRetry({
391
401
  logger.info(
392
402
  `worktree.install strategy=${strategy} cmd=${cmd} attempt=${attempt}/${policy.maxAttempts} path=${cwd}`,
393
403
  );
394
- lastResult = spawnFn(cmd, args, {
404
+ lastResult = runChild(spawnFn, cmd, args, {
395
405
  cwd,
396
406
  stdio: 'pipe',
397
407
  encoding: 'utf-8',
@@ -480,7 +490,6 @@ export function installDependencies(ctx, wtPath) {
480
490
  cwd: wtPath,
481
491
  shell: ctx.platform === 'win32',
482
492
  policy,
483
- spawnFn: spawnSync,
484
493
  sleepFn: sleepSync,
485
494
  logger: ctx.logger,
486
495
  strategy,
@@ -493,5 +502,3 @@ export function installDependencies(ctx, wtPath) {
493
502
  }
494
503
  return { status: 'installed' };
495
504
  }
496
-
497
- export { sleepSync };
@@ -8,8 +8,8 @@
8
8
  * @module lint-issue-body
9
9
  */
10
10
 
11
- import { spawnSync } from 'node:child_process';
12
11
  import { runAsCli } from './lib/cli-utils.js';
12
+ import { runGh } from './lib/gh-exec.js';
13
13
  import { parse, StoryBodyParseError } from './lib/story-body/story-body.js';
14
14
 
15
15
  export const LINT_COMMENT_MARKER = '<!-- mandrel:issue-body-conformance -->';
@@ -142,7 +142,7 @@ export function renderConformanceComment(verdict) {
142
142
  * @returns {string}
143
143
  */
144
144
  function gh(args) {
145
- const res = spawnSync('gh', args, { encoding: 'utf8' });
145
+ const res = runGh(args, { encoding: 'utf8' });
146
146
  if (res.status !== 0) {
147
147
  throw new Error(
148
148
  `gh ${args.join(' ')} failed (exit ${res.status}): ${res.stderr?.trim() ?? ''}`,
@@ -31,6 +31,7 @@ import {
31
31
  } from './lib/orchestration/plan-context.js';
32
32
  import { recordPlanInvocation } from './lib/orchestration/plan-metrics.js';
33
33
  import { createProvider } from './lib/provider-factory.js';
34
+ import { slugifyLabel } from './lib/util/slug.js';
34
35
 
35
36
  const PLAN_SLUG_MAX_LENGTH = 48;
36
37
 
@@ -42,13 +43,7 @@ const PLAN_SLUG_MAX_LENGTH = 48;
42
43
  * @returns {string} `plan` when nothing survives.
43
44
  */
44
45
  export function slugifyPlanLabel(raw) {
45
- const slug = String(raw ?? '')
46
- .toLowerCase()
47
- .replace(/[^a-z0-9]+/g, '-')
48
- .replace(/^-+|-+$/g, '')
49
- .slice(0, PLAN_SLUG_MAX_LENGTH)
50
- .replace(/-+$/, '');
51
- return slug === '' ? 'plan' : slug;
46
+ return slugifyLabel(raw, { max: PLAN_SLUG_MAX_LENGTH, fallback: 'plan' });
52
47
  }
53
48
 
54
49
  /**
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * GitHub Provider — token resolution: GITHUB_TOKEN / GH_TOKEN env →
3
- * `gh auth token` → classified throw (`gh-token-diagnostics.js`). `execSync`
4
- * sits behind a holder so tests can swap it.
3
+ * `gh auth token` → classified throw (`gh-token-diagnostics.js`). The
4
+ * `execFileSync`-shaped runner sits behind a holder so tests can swap it.
5
5
  */
6
6
 
7
- import { execSync as defaultExecSync } from 'node:child_process';
7
+ import { execFileSync as defaultExecSync } from 'node:child_process';
8
8
  import {
9
9
  describeTokenFailure,
10
10
  runGhAuthToken,
@@ -2,10 +2,13 @@
2
2
  * GitHub Provider — post-create "add issue to the Projects V2 board" step.
3
3
  * Needed because GitHub's auto-add workflow is off on fresh boards and can't
4
4
  * be enabled via API. Never throws (issue creation survives a board failure)
5
- * and is idempotent (the mutation returns an existing item).
5
+ * and is idempotent (the mutation returns an existing item). A token without
6
+ * the `project` scope reports `reason: 'insufficient-scope'` and trips the
7
+ * warn-once latch rather than warning per issue.
6
8
  */
7
9
 
8
10
  import { Logger } from '../../lib/Logger.js';
11
+ import { boardScopeFailure } from '../../lib/orchestration/board-access-latch.js';
9
12
 
10
13
  /**
11
14
  * No project number → no-op without network.
@@ -16,7 +19,7 @@ import { Logger } from '../../lib/Logger.js';
16
19
  * getProjectNumber?: () => number|null,
17
20
  * addItemToProject?: (nodeId: string) => Promise<unknown>,
18
21
  * }} opts
19
- * @returns {Promise<{ added: boolean, reason?: string }>}
22
+ * @returns {Promise<{ added: boolean, reason?: string, scope?: string }>}
20
23
  */
21
24
  export async function addIssueToBoard({
22
25
  nodeId,
@@ -35,13 +38,19 @@ export async function addIssueToBoard({
35
38
  await addItemToProject(nodeId);
36
39
  return { added: true };
37
40
  } catch (err) {
38
- const label =
39
- issueNumber !== null && issueNumber !== undefined
40
- ? `Issue #${issueNumber}`
41
- : `issue ${nodeId}`;
42
- Logger.warn(
43
- `[GitHubProvider] Failed to add ${label} to project: ${err.message}`,
44
- );
41
+ const scopeFailure = boardScopeFailure(err);
42
+ if (scopeFailure) return { added: false, ...scopeFailure };
43
+ warnAddFailure(err, issueNumber, nodeId);
45
44
  return { added: false, reason: 'error' };
46
45
  }
47
46
  }
47
+
48
+ function warnAddFailure(err, issueNumber, nodeId) {
49
+ const label =
50
+ issueNumber !== null && issueNumber !== undefined
51
+ ? `Issue #${issueNumber}`
52
+ : `issue ${nodeId}`;
53
+ Logger.warn(
54
+ `[GitHubProvider] Failed to add ${label} to project: ${err.message}`,
55
+ );
56
+ }
@@ -7,6 +7,8 @@
7
7
  * permission rule because a secondary rate limit arrives as HTTP 403.
8
8
  */
9
9
 
10
+ import { defaultSleep } from '../../lib/util/sleep.js';
11
+
10
12
  /**
11
13
  * Schema facts (absent field, disabled feature) no retry can change. Never
12
14
  * add a bare `sub-issues` needle: it matches the endpoint name, so a rate
@@ -186,7 +188,7 @@ export async function withTransientRetry(fn, opts = {}) {
186
188
  classify = classifyGithubError,
187
189
  label = 'gh-api',
188
190
  onRetry,
189
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
191
+ sleep = defaultSleep,
190
192
  random = Math.random,
191
193
  } = opts;
192
194
 
@@ -1,5 +1,6 @@
1
1
  /** Classified `gh auth token` results; only a confirmed not-logged-in result says `gh auth login`. */
2
2
 
3
+ import { runGhOrThrow } from '../../lib/gh-exec.js';
3
4
  import {
4
5
  isTransportFailure,
5
6
  sandboxDenialCode,
@@ -60,15 +61,17 @@ function classifyGhTokenFailure(err) {
60
61
  * detail: string|null }} GhTokenResult
61
62
  */
62
63
 
63
- /** @returns {GhTokenResult} */
64
+ /**
65
+ * @param {Function} execImpl - an `execFileSync`-shaped `(file, args, opts)` runner.
66
+ * @returns {GhTokenResult}
67
+ */
64
68
  export function runGhAuthToken(execImpl) {
65
69
  try {
66
- const out = execImpl('gh auth token', {
67
- encoding: 'utf8',
68
- timeout: 5000,
69
- stdio: ['pipe', 'pipe', 'pipe'],
70
- env: process.env,
71
- });
70
+ const out = runGhOrThrow(
71
+ ['auth', 'token'],
72
+ { encoding: 'utf8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'] },
73
+ execImpl,
74
+ );
72
75
  const token = String(out ?? '').trim();
73
76
  if (token) return { token, verdict: 'ok', detail: null };
74
77
  return {
@@ -8,7 +8,11 @@ import { Logger } from '../../lib/Logger.js';
8
8
  import { concurrentMap } from '../../lib/util/concurrent-map.js';
9
9
  import { isNotFoundError } from './branch-protection.js';
10
10
  import { classifyGithubError, withTransientRetry } from './errors.js';
11
- import { issueToEpic, issueToTicket, subIssueNodeToTicket } from './mappers.js';
11
+ import {
12
+ baseIssueFields,
13
+ issueToTicket,
14
+ subIssueNodeToTicket,
15
+ } from './mappers.js';
12
16
  import {
13
17
  defaultRetryWarn,
14
18
  paginateRest,
@@ -229,7 +233,7 @@ export class IssuesGateway {
229
233
  }),
230
234
  { label: `getEpic #${epicId}`, onRetry: defaultRetryWarn },
231
235
  );
232
- return issueToEpic(parseApiJson(result));
236
+ return baseIssueFields(parseApiJson(result));
233
237
  }
234
238
 
235
239
  /**
@@ -21,7 +21,7 @@ function normalizeLabels(issue) {
21
21
  * @param {object} issue
22
22
  * @returns {object}
23
23
  */
24
- function baseIssueFields(issue) {
24
+ export function baseIssueFields(issue) {
25
25
  const labels = normalizeLabels(issue);
26
26
  return {
27
27
  id: issue.number,
@@ -45,10 +45,6 @@ export function issueToTicket(issue) {
45
45
  };
46
46
  }
47
47
 
48
- export function issueToEpic(issue) {
49
- return baseIssueFields(issue);
50
- }
51
-
52
48
  export function subIssueNodeToTicket(node) {
53
49
  // Absent nodes are legitimate (childless Story, empty page entry).
54
50
  if (node == null) return null;
@@ -31,9 +31,17 @@ const opt = (name, id) => ({
31
31
  description: '',
32
32
  });
33
33
 
34
- export const isInsufficientScopes = (err) =>
35
- Boolean(err) &&
36
- SCOPES_RE.test(err.message ?? err.toString?.() ?? String(err));
34
+ // gh-exec keeps the refusal text in stderr behind a generic message.
35
+ export const errorTextMatches = (err, re) => {
36
+ if (!err) return false;
37
+ const texts = [err.message, err.stderr, err.stdout].filter(
38
+ (text) => typeof text === 'string',
39
+ );
40
+ if (texts.length === 0) texts.push(err.toString?.() ?? String(err));
41
+ return texts.some((text) => re.test(text));
42
+ };
43
+
44
+ export const isInsufficientScopes = (err) => errorTextMatches(err, SCOPES_RE);
37
45
  export const isScopesMissingEnvelope = (value) =>
38
46
  Boolean(value) && typeof value === 'object' && value.scopesMissing === true;
39
47
 
@@ -65,7 +73,16 @@ async function gql(ctx, query, variables, { retry = false } = {}) {
65
73
  return retry ? withTransientRetry(run) : run();
66
74
  }
67
75
 
68
- async function lookupProject(ctx, fragment, strict = false) {
76
+ /**
77
+ * `strict` rethrows every failure; `scopeStrict` rethrows only a scope
78
+ * refusal (identical on both rungs), leaving an owner miss a soft null.
79
+ */
80
+ async function lookupProject(
81
+ ctx,
82
+ fragment,
83
+ strict = false,
84
+ { scopeStrict = false } = {},
85
+ ) {
69
86
  if (!ctx.projectNumber) return null;
70
87
  let lastError = null;
71
88
  for (const scope of ['user', 'organization']) {
@@ -78,7 +95,7 @@ async function lookupProject(ctx, fragment, strict = false) {
78
95
  );
79
96
  if (data?.[scope]?.projectV2) return data[scope].projectV2;
80
97
  } catch (err) {
81
- if (strict && isInsufficientScopes(err)) throw err;
98
+ if ((strict || scopeStrict) && isInsufficientScopes(err)) throw err;
82
99
  lastError = err;
83
100
  }
84
101
  }
@@ -260,7 +277,10 @@ export async function ensureProjectFields(ctx, fieldDefs) {
260
277
 
261
278
  export async function addItemToProject(ctx, contentNodeId) {
262
279
  if (!ctx.state.projectId) {
263
- const project = await lookupProject(ctx, 'id');
280
+ // A scope refusal must reach the caller, not read as "no board".
281
+ const project = await lookupProject(ctx, 'id', false, {
282
+ scopeStrict: true,
283
+ });
264
284
  if (!project) return;
265
285
  ctx.state.projectId = project.id;
266
286
  }
@@ -4,6 +4,8 @@
4
4
  * it before every call so all callers share one budget.
5
5
  */
6
6
 
7
+ import { defaultSleep } from '../../lib/util/sleep.js';
8
+
7
9
  /** GitHub's authenticated Search cap; cooldown applies when no reset is readable. */
8
10
  const SEARCH_BUDGET_DEFAULTS = Object.freeze({
9
11
  capacity: 30,
@@ -30,7 +32,7 @@ export function createSearchBudget({
30
32
  windowMs = SEARCH_BUDGET_DEFAULTS.windowMs,
31
33
  cooldownMs = SEARCH_BUDGET_DEFAULTS.cooldownMs,
32
34
  now = () => Date.now(),
33
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
35
+ sleep = defaultSleep,
34
36
  } = {}) {
35
37
  const refillPerMs = capacity / windowMs;
36
38
  let tokens = capacity;
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import process from 'node:process';
8
+ import { parseGateArgv } from './lib/cli-args.js';
8
9
  import { runAsCli } from './lib/cli-utils.js';
9
10
  import { PROJECT_ROOT, resolveConfig } from './lib/config-resolver.js';
10
11
  import { resolveDocTiers } from './lib/doc-tiers.js';
@@ -14,21 +15,11 @@ import { resolveDocTiers } from './lib/doc-tiers.js';
14
15
  * @returns {{ rootPath: string | null, json: boolean }}
15
16
  */
16
17
  export function parseArgv(argv = []) {
17
- let rootPath = null;
18
- let json = false;
19
- for (let i = 0; i < argv.length; i += 1) {
20
- const a = argv[i];
21
- if (a === '--root') {
22
- const next = argv[i + 1];
23
- if (next && !next.startsWith('--')) {
24
- rootPath = next;
25
- i += 1;
26
- }
27
- } else if (a === '--json') {
28
- json = true;
29
- }
30
- }
31
- return { rootPath, json };
18
+ const { root, json } = parseGateArgv(argv, {
19
+ strings: ['root'],
20
+ booleans: ['json'],
21
+ });
22
+ return { rootPath: root, json };
32
23
  }
33
24
 
34
25
  /**
@@ -59,11 +50,7 @@ export async function runCli(
59
50
  return 0;
60
51
  }
61
52
 
62
- async function main() {
63
- return runCli();
64
- }
65
-
66
- runAsCli(import.meta.url, main, {
53
+ runAsCli(import.meta.url, runCli, {
67
54
  source: 'resolve-doc-tiers',
68
55
  propagateExitCode: true,
69
56
  errorPrefix: '[resolve-doc-tiers] ❌ Fatal error',
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { fileURLToPath } from 'node:url';
12
+ import { parseGateArgv } from './lib/cli-args.js';
12
13
  import { respondToHelp } from './lib/cli-usage.js';
13
14
  import { formatSyncReport, syncAgentrc } from './lib/config/sync-agentrc.js';
14
15
  import { Logger } from './lib/Logger.js';
@@ -26,21 +27,11 @@ const USAGE = {
26
27
  ],
27
28
  };
28
29
 
29
- function parseArgs(argv) {
30
- const out = { cwd: null, quiet: false };
31
- for (let i = 0; i < argv.length; i += 1) {
32
- const a = argv[i];
33
- if (a === '--cwd' && i + 1 < argv.length) {
34
- out.cwd = argv[++i];
35
- } else if (a === '--quiet') {
36
- out.quiet = true;
37
- }
38
- }
39
- return out;
40
- }
41
-
42
30
  export function main(argv = process.argv.slice(2)) {
43
- const { cwd, quiet } = parseArgs(argv);
31
+ const { cwd, quiet } = parseGateArgv(argv, {
32
+ strings: ['cwd'],
33
+ booleans: ['quiet'],
34
+ });
44
35
  const projectRoot = cwd || process.cwd();
45
36
  const result = syncAgentrc({ projectRoot });
46
37
  const report = quiet
@@ -1,159 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- /**
4
- * Project `.agents/agents/` and `.agents/local/agents/` into a flat
5
- * `.claude/agents/` tree — the sibling of `sync-claude-commands.js`, with the
6
- * same payload-wins shadowing and orphan-reap. A role agent runs on its own
7
- * system prompt (no entry-doc `@`-import closure), which is the point of routing to it.
8
- * A `delivery.routing.agentModels` entry overrides the role's `model:` default.
9
- */
10
-
11
- // cli-opt-out: top-level-await script with no main() function — runAsCli wraps an async main, which doesn't apply here.
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
-
15
- import { syncCodexAgents } from './lib/codex/agents-projection.js';
16
- import { applyHeader } from './lib/command-header.js';
17
- import { applyAgentModel, getAgentModels } from './lib/config/agent-models.js';
3
+ /** Project the role agents for Claude, then Codex, from `process.cwd()`. */
4
+
5
+ import {
6
+ CLAUDE_AGENTS_DIR,
7
+ syncClaudeAgents,
8
+ } from './lib/claude/agents-projection.js';
9
+ import { runAsCli } from './lib/cli-utils.js';
10
+ import {
11
+ CODEX_AGENTS_DIR,
12
+ syncCodexAgents,
13
+ } from './lib/codex/agents-projection.js';
14
+ import { getAgentModels } from './lib/config/agent-models.js';
18
15
  import { resolveConfig } from './lib/config-resolver.js';
19
16
  import { Logger } from './lib/Logger.js';
20
- import { dirExists } from './lib/util/paths.js';
21
-
22
- // cwd, never `__dirname/../..`, which lands inside node_modules when installed.
23
- const PROJECT_ROOT = process.cwd();
24
-
25
- // Test overrides; SYNC_CLAUDE_AGENTS_SRC replaces the payload source only.
26
- const PAYLOAD_SRC =
27
- process.env.SYNC_CLAUDE_AGENTS_SRC ??
28
- path.join(PROJECT_ROOT, '.agents', 'agents');
29
- const LOCAL_SRC = path.join(PROJECT_ROOT, '.agents', 'local', 'agents');
30
-
31
- const DEST_DIR =
32
- process.env.SYNC_CLAUDE_AGENTS_DEST ??
33
- path.join(PROJECT_ROOT, '.claude', 'agents');
34
-
35
- export const HEADER =
36
- '<!-- AUTO-GENERATED — do not edit. Source of truth: .agents/agents/ -->\n<!-- Re-run: npm run sync:agents -->\n\n';
37
-
38
- export const LOCAL_HEADER =
39
- '<!-- AUTO-GENERATED from .agents/local/ — do not edit. Source of truth: .agents/local/agents/ -->\n<!-- Re-run: npm run sync:agents -->\n\n';
40
-
41
- fs.mkdirSync(DEST_DIR, { recursive: true });
42
-
43
- const isTopLevelAgent = (entry) => entry.isFile() && entry.name.endsWith('.md');
44
17
 
45
- // Payload first, so it wins a collision.
46
- const SRC_DIRS = [PAYLOAD_SRC, LOCAL_SRC].filter(dirExists);
47
-
48
- /**
49
- * Named, not inline: an anonymous callback in this spawned-only script has no
50
- * coverage coordinates for the CRAP seat to resolve.
51
- *
52
- * @param {string} dir
53
- * @returns {Array<{dir: string, name: string}>}
54
- */
55
- function agentEntriesIn(dir) {
56
- return fs
57
- .readdirSync(dir, { withFileTypes: true })
58
- .filter(isTopLevelAgent)
59
- .map(function toAgentEntry(e) {
60
- return { dir, name: e.name };
61
- });
62
- }
63
-
64
- const entries = SRC_DIRS.flatMap(agentEntriesIn);
65
-
66
- const byName = new Map();
67
- for (const e of entries) {
68
- if (byName.has(e.name)) {
69
- Logger.warn(` shadowed ${e.name} (local copy ignored; payload wins)`);
70
- continue;
71
- }
72
- byName.set(e.name, e);
73
- }
74
-
75
- // Any existing agent def not in this set is reaped.
76
- const sourceSet = new Set(byName.keys());
77
-
78
- /**
79
- * @returns {string[]}
80
- */
81
- function listExistingAgents() {
82
- try {
83
- return fs.readdirSync(DEST_DIR).filter((f) => f.endsWith('.md'));
84
- } catch {
85
- return [];
86
- }
87
- }
88
-
89
- for (const name of listExistingAgents()) {
90
- if (!sourceSet.has(name)) {
91
- fs.unlinkSync(path.join(DEST_DIR, name));
92
- Logger.info(` removed ${name} (no longer in .agents/agents)`);
93
- }
94
- }
95
-
96
- // Resolved once: an invalid override (an unknown role) fails the sync here.
97
- const agentModels = getAgentModels(resolveConfig({ cwd: PROJECT_ROOT }));
98
-
99
- /**
100
- * @param {string} name
101
- * @param {string} content
102
- * @returns {string}
103
- */
104
- function withModelOverride(name, content) {
105
- const model = agentModels[name.replace(/\.md$/, '')];
106
- return model ? applyAgentModel(content, model) : content;
107
- }
108
-
109
- let synced = 0;
110
-
111
- /**
112
- * The header goes after any frontmatter, so `---` stays on line 1.
113
- *
114
- * @param {{ dir: string, name: string }} entry
115
- * @returns {Promise<void>}
116
- */
117
- async function syncEntry({ dir, name }) {
118
- const isLocal = dir === LOCAL_SRC;
119
- const header = isLocal ? LOCAL_HEADER : HEADER;
120
- const content = await fs.promises.readFile(path.join(dir, name), 'utf8');
121
- const dest = path.join(DEST_DIR, name);
122
- const target = applyHeader(withModelOverride(name, content), header);
123
-
124
- try {
125
- const existingContent = await fs.promises.readFile(dest, 'utf8');
126
- if (existingContent === target) return;
127
- } catch (err) {
128
- if (err.code !== 'ENOENT') throw err;
129
- }
130
-
131
- await fs.promises.writeFile(dest, target, 'utf8');
132
- synced++;
133
- Logger.info(` synced ${name}`);
134
- }
135
-
136
- await Promise.all(Array.from(byName.values()).map(syncEntry));
137
-
138
- Logger.info(
139
- `\n✔ ${synced} file(s) synced, ${sourceSet.size} total agents in .claude/agents/`,
140
- );
141
-
142
- // The Codex half: the same roles as `.codex/agents/mandrel-<role>.toml`. A
143
- // fixture run (a DEST override) skips it unless SYNC_CODEX_AGENTS_DEST names
144
- // its own target.
145
- const codexAgentsDest =
146
- process.env.SYNC_CODEX_AGENTS_DEST ??
147
- (process.env.SYNC_CLAUDE_AGENTS_DEST ? null : undefined);
148
- if (codexAgentsDest !== null) {
149
- const codex = syncCodexAgents({
150
- projectRoot: PROJECT_ROOT,
151
- payloadSrc: PAYLOAD_SRC,
152
- localSrc: LOCAL_SRC,
153
- destDir: codexAgentsDest,
154
- log: (line) => Logger.info(line),
18
+ /** @returns {Promise<void>} */
19
+ async function main() {
20
+ // cwd, never `__dirname/../..`, which lands inside node_modules.
21
+ const projectRoot = process.cwd();
22
+ const log = (line) => Logger.info(line);
23
+ const claude = syncClaudeAgents({
24
+ projectRoot,
25
+ // Validated: an unknown role fails the sync.
26
+ agentModels: getAgentModels(resolveConfig({ cwd: projectRoot })),
27
+ log,
28
+ warn: (line) => Logger.warn(line),
155
29
  });
156
30
  Logger.info(
157
- `✔ ${codex.written.length} file(s) synced, ${codex.total} total Codex agents in .codex/agents/`,
31
+ `\n✔ ${claude.written.length} file(s) synced, ${claude.total} total agents in ${CLAUDE_AGENTS_DIR}/`,
32
+ );
33
+ const codex = syncCodexAgents({ projectRoot, log });
34
+ Logger.info(
35
+ `✔ ${codex.written.length} file(s) synced, ${codex.total} total Codex agents in ${CODEX_AGENTS_DIR}/`,
158
36
  );
159
37
  }
38
+
39
+ runAsCli(import.meta.url, main, {
40
+ source: 'sync-claude-agents',
41
+ usage: {
42
+ invocation: 'node .agents/scripts/sync-claude-agents.js',
43
+ summary:
44
+ 'Regenerate the .claude/agents/ projection of .agents/agents/ (and .agents/local/agents/), then the Codex agents under .codex/agents/.',
45
+ flags: [],
46
+ },
47
+ });