mandrel 2.89.0 → 2.90.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.
@@ -324,6 +324,13 @@ names or defaults.
324
324
  - **`branchProtection.requiredChecks`.** Each `{ name, cmd[] }` entry is used
325
325
  **both** as a required-status-check expectation on the PR and as a local
326
326
  close-validation gate invocation.
327
+ - **`projectNumber`.** Board sync needs a token with the `project` scope. A
328
+ token without it never aborts a run (labels stay authoritative): the first
329
+ board add or Status flip that fails on scope emits one warning per process
330
+ naming the remedy, `gh auth refresh -h github.com -s project`, and
331
+ `mandrel doctor` fails its `github-project-access` check. After refreshing
332
+ the token, `node .agents/scripts/board-backfill.js` (`--dry-run` to preview)
333
+ adds the open Stories and Epics the board missed and syncs their Status.
327
334
  - **`notifications`.** Both event allowlists filter their channel
328
335
  independently; their enums are pinned in the schema. Set an array to `[]` to
329
336
  suppress a channel. The severity vocabulary and shipped default allowlists
@@ -0,0 +1,253 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * board-backfill.js — add open Stories/Epics missing from the Projects v2
5
+ * board and sync each Story's Status from its `agent::*` label. Idempotent.
6
+ */
7
+
8
+ import { parseArgs } from 'node:util';
9
+
10
+ import { runAsCli } from './lib/cli-utils.js';
11
+ import { resolveConfig } from './lib/config-resolver.js';
12
+ import { Logger, routeAllOutputToStderr } from './lib/Logger.js';
13
+ import {
14
+ isProjectAccessFailure,
15
+ toProjectAccessError,
16
+ } from './lib/orchestration/board-access-latch.js';
17
+ import {
18
+ ColumnSync,
19
+ columnForLabels,
20
+ } from './lib/orchestration/column-sync.js';
21
+ import {
22
+ ProjectAccessError,
23
+ resolveProjectMeta,
24
+ } from './lib/orchestration/project-meta-resolver.js';
25
+ import { createProvider } from './lib/provider-factory.js';
26
+
27
+ const BOARD_TYPE_LABELS = Object.freeze(['type::story', 'type::epic']);
28
+
29
+ const OPEN_ISSUES_QUERY = `
30
+ query($owner: String!, $repo: String!, $label: String!, $after: String) {
31
+ repository(owner: $owner, name: $repo) {
32
+ issues(states: OPEN, labels: [$label], first: 100, after: $after) {
33
+ pageInfo { hasNextPage endCursor }
34
+ nodes {
35
+ number
36
+ id
37
+ labels(first: 50) { nodes { name } }
38
+ projectItems(first: 20) {
39
+ nodes {
40
+ id
41
+ project { id }
42
+ fieldValueByName(name: "Status") {
43
+ ... on ProjectV2ItemFieldSingleSelectValue { name }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }`;
51
+
52
+ const ADD_ITEM_MUTATION = `
53
+ mutation($projectId: ID!, $contentId: ID!) {
54
+ addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
55
+ item { id }
56
+ }
57
+ }`;
58
+
59
+ /**
60
+ * Raise a scope/auth refusal as the typed error; return anything else.
61
+ *
62
+ * @param {unknown} err
63
+ * @returns {unknown}
64
+ */
65
+ function classify(err) {
66
+ if (isProjectAccessFailure(err)) throw toProjectAccessError(err);
67
+ return err;
68
+ }
69
+
70
+ /**
71
+ * Open issues carrying any board type label, deduped by number.
72
+ *
73
+ * @param {{ graphql: Function, owner: string, repo: string }} provider
74
+ * @returns {Promise<Array<{ number: number, nodeId: string, labels: string[], items: object[] }>>}
75
+ */
76
+ export async function listBoardCandidates(provider) {
77
+ const byNumber = new Map();
78
+ for (const label of BOARD_TYPE_LABELS) {
79
+ let after = null;
80
+ do {
81
+ let data;
82
+ try {
83
+ data = await provider.graphql(OPEN_ISSUES_QUERY, {
84
+ owner: provider.owner,
85
+ repo: provider.repo,
86
+ label,
87
+ after,
88
+ });
89
+ } catch (err) {
90
+ throw classify(err);
91
+ }
92
+ const page = data?.repository?.issues;
93
+ for (const node of page?.nodes ?? []) {
94
+ if (!node || byNumber.has(node.number)) continue;
95
+ byNumber.set(node.number, {
96
+ number: node.number,
97
+ nodeId: node.id,
98
+ labels: (node.labels?.nodes ?? []).map((l) => l.name),
99
+ items: node.projectItems?.nodes ?? [],
100
+ });
101
+ }
102
+ after = page?.pageInfo?.hasNextPage ? page.pageInfo.endCursor : null;
103
+ } while (after);
104
+ }
105
+ return [...byNumber.values()].sort((a, b) => a.number - b.number);
106
+ }
107
+
108
+ /**
109
+ * What the board needs for one issue: an add, a Status sync, both, or
110
+ * nothing. Epics never get a Status target here.
111
+ *
112
+ * @param {{ labels: string[], items: object[] }} issue
113
+ * @param {string} projectId
114
+ */
115
+ export function planIssue(issue, projectId) {
116
+ const isEpic = issue.labels.includes('type::epic');
117
+ const target = isEpic ? null : columnForLabels(issue.labels);
118
+ const item = issue.items.find((n) => n?.project?.id === projectId);
119
+ const current = item?.fieldValueByName?.name ?? null;
120
+ return {
121
+ number: issue.number,
122
+ type: isEpic ? 'epic' : 'story',
123
+ add: !item,
124
+ status: target && target !== current ? target : null,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * @param {{
130
+ * provider: { graphql: Function, owner: string, repo: string, projectNumber?: number|null, projectOwner?: string|null },
131
+ * config?: object,
132
+ * dryRun?: boolean,
133
+ * columnSync?: { sync: Function },
134
+ * }} args
135
+ * @returns {Promise<{ dryRun: boolean, added: number, synced: number, skipped: number, failed: number, planned: object[] }>}
136
+ * @throws {ProjectAccessError} when the token cannot read or write the board.
137
+ */
138
+ export async function runBackfill({
139
+ provider,
140
+ config,
141
+ dryRun = false,
142
+ columnSync,
143
+ }) {
144
+ const projectNumber =
145
+ config?.github?.projectNumber ?? provider.projectNumber ?? null;
146
+ if (!projectNumber) {
147
+ throw new Error(
148
+ 'No github.projectNumber configured — nothing to backfill.',
149
+ );
150
+ }
151
+ const project = await resolveProjectMeta({
152
+ provider,
153
+ owner: provider.projectOwner ?? provider.owner ?? null,
154
+ projectNumber,
155
+ projectFields: 'id',
156
+ });
157
+ if (!project) {
158
+ throw new Error(`Project #${projectNumber} not found.`);
159
+ }
160
+ const sync =
161
+ columnSync ??
162
+ new ColumnSync({ provider, projectNumber, logger: Logger, config });
163
+ const summary = { dryRun, added: 0, synced: 0, skipped: 0, failed: 0 };
164
+ const planned = [];
165
+ for (const issue of await listBoardCandidates(provider)) {
166
+ const plan = planIssue(issue, project.id);
167
+ if (!plan.add && !plan.status) {
168
+ summary.skipped += 1;
169
+ continue;
170
+ }
171
+ planned.push(plan);
172
+ if (dryRun) continue;
173
+ await applyPlan({
174
+ plan,
175
+ issue,
176
+ provider,
177
+ projectId: project.id,
178
+ sync,
179
+ summary,
180
+ });
181
+ }
182
+ return { ...summary, planned };
183
+ }
184
+
185
+ async function applyPlan({ plan, issue, provider, projectId, sync, summary }) {
186
+ if (plan.add) {
187
+ try {
188
+ await provider.graphql(ADD_ITEM_MUTATION, {
189
+ projectId,
190
+ contentId: issue.nodeId,
191
+ });
192
+ summary.added += 1;
193
+ } catch (err) {
194
+ classify(err);
195
+ Logger.warn(
196
+ `[board-backfill] could not add #${issue.number}: ${err?.message ?? err}`,
197
+ );
198
+ summary.failed += 1;
199
+ return;
200
+ }
201
+ }
202
+ if (!plan.status) return;
203
+ const result = await sync
204
+ .sync(issue.number, issue.labels)
205
+ .catch((err) => ({ status: 'failed', error: classify(err) }));
206
+ if (result?.reason === 'insufficient-scope') {
207
+ throw toProjectAccessError(new Error('Status update refused'));
208
+ }
209
+ if (result?.status === 'synced') summary.synced += 1;
210
+ else summary.failed += 1;
211
+ }
212
+
213
+ /* node:coverage ignore next */
214
+ export async function main(argv = process.argv.slice(2)) {
215
+ const { values } = parseArgs({
216
+ args: argv,
217
+ options: { 'dry-run': { type: 'boolean', default: false } },
218
+ strict: true,
219
+ });
220
+ routeAllOutputToStderr();
221
+ const config = resolveConfig();
222
+ const provider = createProvider(config);
223
+ try {
224
+ const result = await runBackfill({
225
+ provider,
226
+ config,
227
+ dryRun: values['dry-run'],
228
+ });
229
+ process.stdout.write(`${JSON.stringify(result)}\n`);
230
+ } catch (err) {
231
+ if (err instanceof ProjectAccessError) {
232
+ process.stderr.write(
233
+ `[board-backfill] ${err.message}\nRemedy: ${err.remedy}\n`,
234
+ );
235
+ process.exitCode = 1;
236
+ return;
237
+ }
238
+ throw err;
239
+ }
240
+ }
241
+
242
+ runAsCli(import.meta.url, main, {
243
+ source: 'board-backfill',
244
+ usage: {
245
+ invocation: 'node .agents/scripts/board-backfill.js [--dry-run]',
246
+ summary:
247
+ "Add open type::story / type::epic issues missing from the configured Projects v2 board and sync each Story's Status from its agent::* label. Idempotent; prints a JSON summary { added, synced, skipped, failed } on stdout.",
248
+ flags: [
249
+ ['--dry-run', 'List what would be added or synced; change nothing.'],
250
+ ['--help', 'Show this message.'],
251
+ ],
252
+ },
253
+ });
@@ -153,6 +153,10 @@ function spawnGate(cmd, args, opts, lock) {
153
153
  }
154
154
 
155
155
  /**
156
+ * The child always gets an env: `AP_AGENTRC_CWD` is pinned to `cwd` (layered
157
+ * last) so every gate and its `npm run` grandchildren resolve the worktree's
158
+ * `.agentrc.json`, not the config of the checkout holding the scripts.
159
+ *
156
160
  * @param {string} cmd
157
161
  * @param {string[]} args
158
162
  * @param {string} cwd
@@ -164,7 +168,7 @@ function spawnGateChild(cmd, args, cwd, env) {
164
168
  shell: process.platform === 'win32',
165
169
  stdio: ['ignore', 'pipe', 'pipe'],
166
170
  ...groupSpawnOptions(),
167
- ...(env ? { env: { ...process.env, ...env } } : {}),
171
+ env: { ...process.env, ...env, AP_AGENTRC_CWD: cwd },
168
172
  });
169
173
  }
170
174
 
@@ -3,11 +3,12 @@
3
3
  * reads it: the scorer skips uncovered methods, so a stale artifact silently
4
4
  * weakens the gate.
5
5
  */
6
- import { spawnSync } from 'node:child_process';
7
6
  import crypto from 'node:crypto';
8
7
  import fs from 'node:fs';
9
8
  import path from 'node:path';
9
+ import { spawnChild } from './child-exec.js';
10
10
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from './full-suite-lock.js';
11
+ import { Logger } from './Logger.js';
11
12
  import { TIMEOUT_EXIT_CODE } from './process-group.js';
12
13
  import {
13
14
  isScorableSourceFile,
@@ -114,6 +115,45 @@ function foldDirtySources({
114
115
  return count;
115
116
  }
116
117
 
118
+ /**
119
+ * A digest's git runner, through `spawnChild` so a repo whose index listing
120
+ * outgrows Node's 1 MiB default buffer still digests (no ENOBUFS). A failure
121
+ * throws an error tagged with the subcommand, for the warning.
122
+ *
123
+ * @param {string} cwd
124
+ * @param {{ spawnSync?: Function }} io `io.spawnSync` is the test seam.
125
+ * @returns {(...args: string[]) => string}
126
+ */
127
+ function digestGit(cwd, io) {
128
+ return (...args) => {
129
+ const res = spawnChild('git', args, { cwd, run: io.spawnSync });
130
+ if (res?.error || res?.status !== 0) {
131
+ const err =
132
+ res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
133
+ err.gitSubcommand = args[0];
134
+ if (err.code === undefined) err.code = `exit ${res?.status}`;
135
+ throw err;
136
+ }
137
+ return res.stdout ?? '';
138
+ };
139
+ }
140
+
141
+ /**
142
+ * No digest never matches, so an unfreshable stamp is announced, not silent.
143
+ *
144
+ * @param {Error & { gitSubcommand?: string, code?: string }} err
145
+ * @param {{ logger?: { warn: Function } }} io
146
+ * @returns {null}
147
+ */
148
+ function warnDigestUnavailable(err, io) {
149
+ const logger = io.logger ?? Logger;
150
+ const subcommand = err?.gitSubcommand ?? 'digest';
151
+ logger.warn(
152
+ `[coverage-capture] ⚠ git ${subcommand} failed (${err?.code ?? 'unknown'}); digest unavailable, stamp cannot read fresh.`,
153
+ );
154
+ return null;
155
+ }
156
+
117
157
  /**
118
158
  * Digest of the scorable sources under `targetDirs`: `git ls-files -s` of
119
159
  * tracked content plus dirty files' bytes, so it moves only on content change.
@@ -122,24 +162,17 @@ function foldDirtySources({
122
162
  *
123
163
  * @param {string} cwd Absolute repo root.
124
164
  * @param {string[]} targetDirs Repo-relative directories to digest.
125
- * @param {{ spawnSync?: typeof spawnSync, readFileSync?: typeof fs.readFileSync }} [io]
165
+ * @param {{ spawnSync?: Function, readFileSync?: typeof fs.readFileSync, logger?: { warn: Function } }} [io]
126
166
  * @returns {string | null} Hex SHA-256 digest, or null when unavailable.
127
167
  */
128
168
  export function computeContentDigest(cwd, targetDirs, io = {}) {
129
- const spawn = io.spawnSync ?? spawnSync;
130
169
  const readFileSync = io.readFileSync ?? fs.readFileSync;
131
170
  const dirs = (targetDirs ?? []).filter(
132
171
  (d) => typeof d === 'string' && d.length > 0,
133
172
  );
134
173
  if (dirs.length === 0) return null;
135
174
 
136
- const git = (...args) => {
137
- const res = spawn('git', args, { cwd, encoding: 'utf8' });
138
- if (res?.error || res?.status !== 0) {
139
- throw res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
140
- }
141
- return res.stdout ?? '';
142
- };
175
+ const git = digestGit(cwd, io);
143
176
 
144
177
  try {
145
178
  const hash = crypto.createHash('sha256');
@@ -156,8 +189,8 @@ export function computeContentDigest(cwd, targetDirs, io = {}) {
156
189
  });
157
190
  if (tracked.length + scorableDirty === 0) return null;
158
191
  return hash.digest('hex');
159
- } catch {
160
- return null;
192
+ } catch (err) {
193
+ return warnDigestUnavailable(err, io);
161
194
  }
162
195
  }
163
196
 
@@ -197,24 +230,17 @@ export function filterSuiteInputPaths(files, coveragePath = null) {
197
230
  *
198
231
  * @param {string} cwd
199
232
  * @param {string} coveragePath
200
- * @param {{ spawnSync?: typeof spawnSync, readFileSync?: typeof fs.readFileSync }} [io]
233
+ * @param {{ spawnSync?: Function, readFileSync?: typeof fs.readFileSync, logger?: { warn: Function } }} [io]
201
234
  * @returns {string | null}
202
235
  */
203
236
  export function computeTreeDigest(cwd, coveragePath, io = {}) {
204
- const spawn = io.spawnSync ?? spawnSync;
205
237
  const readFileSync = io.readFileSync ?? fs.readFileSync;
206
238
  const pathspec = [
207
239
  '--',
208
240
  '.',
209
241
  ...suiteDigestExcludedDirs(coveragePath).map((dir) => `:(exclude)${dir}`),
210
242
  ];
211
- const git = (...args) => {
212
- const res = spawn('git', args, { cwd, encoding: 'utf8' });
213
- if (res?.error || res?.status !== 0) {
214
- throw res?.error ?? new Error(res?.stderr || `git ${args[0]} failed`);
215
- }
216
- return res.stdout ?? '';
217
- };
243
+ const git = digestGit(cwd, io);
218
244
  try {
219
245
  const hash = crypto.createHash('sha256');
220
246
  hash.update(git('ls-files', '-s', ...pathspec));
@@ -231,8 +257,8 @@ export function computeTreeDigest(cwd, coveragePath, io = {}) {
231
257
  select: () => true,
232
258
  });
233
259
  return hash.digest('hex');
234
- } catch {
235
- return null;
260
+ } catch (err) {
261
+ return warnDigestUnavailable(err, io);
236
262
  }
237
263
  }
238
264
 
@@ -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',
@@ -0,0 +1,101 @@
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 { isInsufficientScopes } from '../../providers/github/projects-v2-graphql.js';
8
+ import { Logger } from '../Logger.js';
9
+
10
+ const PROJECT_SCOPE = 'project';
11
+ const PROJECT_SCOPE_REMEDY = 'gh auth refresh -h github.com -s project';
12
+
13
+ /** The outcome shape a board seam reports for a scope failure. */
14
+ export const SCOPE_FAILURE = Object.freeze({
15
+ reason: 'insufficient-scope',
16
+ scope: PROJECT_SCOPE,
17
+ });
18
+
19
+ // GraphQL `FORBIDDEN`, or an explicit HTTP 401/403 from the GraphQL endpoint.
20
+ const AUTH_FAILURE_RE =
21
+ /\bFORBIDDEN\b|Bad credentials|\b(?:HTTP|GraphQL) 40[13]\b/;
22
+
23
+ /**
24
+ * The board is unreachable with this token — a missing `project` scope or an
25
+ * auth refusal, never an owner-type miss.
26
+ */
27
+ export class ProjectAccessError extends Error {
28
+ /**
29
+ * @param {string} message
30
+ * @param {{ cause?: unknown }} [opts]
31
+ */
32
+ constructor(message, { cause } = {}) {
33
+ super(message, { cause });
34
+ this.name = 'ProjectAccessError';
35
+ this.scope = PROJECT_SCOPE;
36
+ this.remedy = PROJECT_SCOPE_REMEDY;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Is `err` a token-scope / auth refusal (as opposed to a NOT_FOUND miss or a
42
+ * transient failure)? A `ProjectAccessError` always is.
43
+ *
44
+ * @param {unknown} err
45
+ * @returns {boolean}
46
+ */
47
+ export function isProjectAccessFailure(err) {
48
+ 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);
53
+ }
54
+
55
+ /**
56
+ * Wrap a raw scope/auth error in a `ProjectAccessError` (idempotent).
57
+ *
58
+ * @param {unknown} err
59
+ * @returns {ProjectAccessError}
60
+ */
61
+ export function toProjectAccessError(err) {
62
+ if (err instanceof ProjectAccessError) return err;
63
+ const detail = err?.message ?? String(err);
64
+ return new ProjectAccessError(
65
+ `GitHub Projects v2 board is not accessible with this token (missing the "${PROJECT_SCOPE}" scope?): ${detail}`,
66
+ { cause: err },
67
+ );
68
+ }
69
+
70
+ // Sinks already warned; production shares one `Logger`, so once per process.
71
+ const warnedSinks = new WeakSet();
72
+
73
+ /**
74
+ * Record a board scope failure; the first call per process (per sink) emits
75
+ * the one warning (stderr), later calls are silent.
76
+ *
77
+ * @param {{ logger?: { warn?: Function } }} [opts]
78
+ * @returns {boolean} true when this call emitted the warning.
79
+ */
80
+ export function reportBoardScopeFailure({ logger = Logger } = {}) {
81
+ if (warnedSinks.has(logger)) return false;
82
+ warnedSinks.add(logger);
83
+ logger.warn?.(
84
+ `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.`,
85
+ );
86
+ return true;
87
+ }
88
+
89
+ /**
90
+ * Classify a board-call failure: a scope/auth refusal trips the latch and
91
+ * yields the outcome fields to report; anything else yields null.
92
+ *
93
+ * @param {unknown} err
94
+ * @param {{ logger?: { warn?: Function } }} [opts]
95
+ * @returns {{ reason: 'insufficient-scope', scope: 'project' } | null}
96
+ */
97
+ export function boardScopeFailure(err, { logger } = {}) {
98
+ if (!isProjectAccessFailure(err)) return null;
99
+ reportBoardScopeFailure({ logger });
100
+ return SCOPE_FAILURE;
101
+ }
@@ -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
  }
@@ -5,6 +5,14 @@
5
5
  * `projectV2 { … }` selection body as `projectFields`.
6
6
  */
7
7
 
8
+ import {
9
+ isProjectAccessFailure,
10
+ ProjectAccessError,
11
+ toProjectAccessError,
12
+ } from './board-access-latch.js';
13
+
14
+ export { ProjectAccessError };
15
+
8
16
  /**
9
17
  * Priority order. `viewer` (the ambient identity) is last so a configured
10
18
  * owner always wins.
@@ -42,8 +50,36 @@ function buildScopedQuery(scope, projectFields) {
42
50
  }
43
51
 
44
52
  /**
45
- * The first non-null `projectV2` node down the ladder; a throwing or null
46
- * rung is a miss. With no `owner`, only `viewer` is tried.
53
+ * One rung's `projectV2` node, or null for a miss. An owner miss (NOT_FOUND)
54
+ * and any other non-access error advance the ladder; a scope or auth refusal
55
+ * is raised as a `ProjectAccessError`.
56
+ */
57
+ async function queryRung(
58
+ provider,
59
+ scope,
60
+ { owner, projectNumber, projectFields },
61
+ ) {
62
+ const vars = scope.needsOwner
63
+ ? { owner, number: projectNumber }
64
+ : { number: projectNumber };
65
+ try {
66
+ const data = await provider.graphql(
67
+ buildScopedQuery(scope, projectFields),
68
+ vars,
69
+ );
70
+ return data?.[scope.root]?.projectV2 ?? null;
71
+ } catch (err) {
72
+ if (isProjectAccessFailure(err)) throw toProjectAccessError(err);
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * The first non-null `projectV2` node down the ladder. A null rung or an
79
+ * owner miss (NOT_FOUND — expected on two of three rungs) advances; a scope
80
+ * or auth refusal is identical on every rung, so it fails fast as a
81
+ * `ProjectAccessError` instead of being hidden by the ladder. With no
82
+ * `owner`, only `viewer` is tried.
47
83
  *
48
84
  * @param {{
49
85
  * provider: { graphql: Function },
@@ -52,6 +88,7 @@ function buildScopedQuery(scope, projectFields) {
52
88
  * projectFields: string,
53
89
  * }} args
54
90
  * @returns {Promise<object|null>} the resolved `projectV2` node, or null.
91
+ * @throws {ProjectAccessError} when the token cannot read the board.
55
92
  */
56
93
  export async function resolveProjectMeta(args) {
57
94
  const { provider, owner, projectNumber, projectFields } = args ?? {};
@@ -66,21 +103,11 @@ export async function resolveProjectMeta(args) {
66
103
 
67
104
  for (const scope of OWNER_SCOPES) {
68
105
  if (scope.needsOwner && !owner) continue;
69
-
70
- const query = buildScopedQuery(scope, projectFields);
71
- const vars = scope.needsOwner
72
- ? { owner, number: projectNumber }
73
- : { number: projectNumber };
74
-
75
- let data;
76
- try {
77
- data = await provider.graphql(query, vars);
78
- } catch {
79
- // Wrong owner type (NOT_FOUND) etc. — advance the ladder.
80
- continue;
81
- }
82
-
83
- const node = data?.[scope.root]?.projectV2;
106
+ const node = await queryRung(provider, scope, {
107
+ owner,
108
+ projectNumber,
109
+ projectFields,
110
+ });
84
111
  if (node) return node;
85
112
  }
86
113
 
@@ -176,6 +176,19 @@ function headSha(ctx) {
176
176
  return gitLine(ctx.git, ctx.cwd, ['rev-parse', 'HEAD']);
177
177
  }
178
178
 
179
+ /**
180
+ * A child's env with `AP_AGENTRC_CWD` pinned to the Story worktree, layered
181
+ * last so a stale inherited value cannot win: a gate judges the branch by
182
+ * the branch's own `.agentrc.json`.
183
+ *
184
+ * @param {object} ctx
185
+ * @param {Record<string, string|undefined>} [env] defaults to `ctx.env`.
186
+ * @returns {Record<string, string|undefined>}
187
+ */
188
+ function worktreeEnv(ctx, env) {
189
+ return { ...(env ?? ctx.env), AP_AGENTRC_CWD: ctx.cwd };
190
+ }
191
+
179
192
  /**
180
193
  * Run one child with its combined output streamed live into the step's
181
194
  * evidence log (announced, and recorded in story-progress, before it spawns).
@@ -197,7 +210,7 @@ async function runLogged(ctx, logName, cmd, args, env) {
197
210
  progress: ctx.progress,
198
211
  cmd,
199
212
  args,
200
- opts: { cwd: ctx.cwd, env },
213
+ opts: { cwd: ctx.cwd, env: worktreeEnv(ctx, env) },
201
214
  file,
202
215
  tag: logName,
203
216
  });
@@ -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
+ }
@@ -65,7 +65,16 @@ async function gql(ctx, query, variables, { retry = false } = {}) {
65
65
  return retry ? withTransientRetry(run) : run();
66
66
  }
67
67
 
68
- async function lookupProject(ctx, fragment, strict = false) {
68
+ /**
69
+ * `strict` rethrows every failure; `scopeStrict` rethrows only a scope
70
+ * refusal (identical on both rungs), leaving an owner miss a soft null.
71
+ */
72
+ async function lookupProject(
73
+ ctx,
74
+ fragment,
75
+ strict = false,
76
+ { scopeStrict = false } = {},
77
+ ) {
69
78
  if (!ctx.projectNumber) return null;
70
79
  let lastError = null;
71
80
  for (const scope of ['user', 'organization']) {
@@ -78,7 +87,7 @@ async function lookupProject(ctx, fragment, strict = false) {
78
87
  );
79
88
  if (data?.[scope]?.projectV2) return data[scope].projectV2;
80
89
  } catch (err) {
81
- if (strict && isInsufficientScopes(err)) throw err;
90
+ if ((strict || scopeStrict) && isInsufficientScopes(err)) throw err;
82
91
  lastError = err;
83
92
  }
84
93
  }
@@ -260,7 +269,10 @@ export async function ensureProjectFields(ctx, fieldDefs) {
260
269
 
261
270
  export async function addItemToProject(ctx, contentNodeId) {
262
271
  if (!ctx.state.projectId) {
263
- const project = await lookupProject(ctx, 'id');
272
+ // A scope refusal must reach the caller, not read as "no board".
273
+ const project = await lookupProject(ctx, 'id', false, {
274
+ scopeStrict: true,
275
+ });
264
276
  if (!project) return;
265
277
  ctx.state.projectId = project.id;
266
278
  }
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,19 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.90.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.89.0...mandrel-v2.90.0) (2026-10-16)
19
+
20
+
21
+ ### Added
22
+
23
+ * surface Projects v2 scope failures instead of swallowing them, and backfill the board ([#5727](https://github.com/dsj1984/mandrel/issues/5727)) ([#5733](https://github.com/dsj1984/mandrel/issues/5733)) ([41bf87a](https://github.com/dsj1984/mandrel/commit/41bf87a94e2930d04ce4a8f374fb204bfca94e77))
24
+
25
+
26
+ ### Fixed
27
+
28
+ * coverage-capture: route the tree/content digest git calls through child-exec so large repos get a freshable stamp ([#5728](https://github.com/dsj1984/mandrel/issues/5728)) ([#5730](https://github.com/dsj1984/mandrel/issues/5730)) ([8919d41](https://github.com/dsj1984/mandrel/commit/8919d414e715afa9dd352a8c18cd41a72fbb2118))
29
+ * handoff and close gate children resolve .agentrc.json from the Story worktree, not the main checkout ([#5729](https://github.com/dsj1984/mandrel/issues/5729)) ([#5731](https://github.com/dsj1984/mandrel/issues/5731)) ([af4f4cf](https://github.com/dsj1984/mandrel/commit/af4f4cf05e7f7b05e75ab0418a366733206b84ad))
30
+
18
31
  ## [2.89.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.88.0...mandrel-v2.89.0) (2026-10-16)
19
32
 
20
33
 
@@ -0,0 +1,114 @@
1
+ // lib/cli/doctor-checks/project-access.js — Doctor check: github-project-access.
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { isInsufficientScopes } from '../../../.agents/scripts/providers/github/projects-v2-graphql.js';
7
+ import { readJsonSafe } from './read-json.js';
8
+ import { spawn } from './spawn.js';
9
+
10
+ const REMEDY = 'Run `gh auth refresh -h github.com -s project`, then re-run.';
11
+
12
+ // A gh that cannot authenticate at all is gh-auth's failure, not this one's.
13
+ const GH_AUTH_RE = /gh auth login|not logged in|Bad credentials|HTTP 401/i;
14
+
15
+ /**
16
+ * `github.projectNumber` / `github.owner` from `.agentrc.json`, with
17
+ * `.agentrc.local.json` winning per key.
18
+ *
19
+ * @param {string} projectRoot
20
+ * @param {{ readFileSync: Function }} fsImpl
21
+ * @returns {{ projectNumber: number|null, owner: string|null }}
22
+ */
23
+ function readBoardConfig(projectRoot, fsImpl) {
24
+ const base = readJsonSafe(path.join(projectRoot, '.agentrc.json'), fsImpl);
25
+ const local = readJsonSafe(
26
+ path.join(projectRoot, '.agentrc.local.json'),
27
+ fsImpl,
28
+ );
29
+ const github = { ...(base?.github ?? {}), ...(local?.github ?? {}) };
30
+ const n = Number(github.projectNumber);
31
+ return {
32
+ projectNumber: Number.isInteger(n) && n > 0 ? n : null,
33
+ owner:
34
+ typeof github.owner === 'string' && github.owner ? github.owner : null,
35
+ };
36
+ }
37
+
38
+ /** One rung's query: `organization` / `user` by login, else `viewer`. */
39
+ function rungArgs(root, owner, projectNumber) {
40
+ const query = owner
41
+ ? `query($owner:String!,$number:Int!){${root}(login:$owner){projectV2(number:$number){id}}}`
42
+ : `query($number:Int!){viewer{projectV2(number:$number){id}}}`;
43
+ const args = ['api', 'graphql', '-f', `query=${query}`];
44
+ if (owner) args.push('-f', `owner=${owner}`);
45
+ args.push('-F', `number=${projectNumber}`);
46
+ return args;
47
+ }
48
+
49
+ /**
50
+ * Probe one rung.
51
+ *
52
+ * @returns {'found'|'miss'|'scope'|'defer'}
53
+ */
54
+ function probeRung(runner, root, owner, projectNumber) {
55
+ const r = runner('gh', rungArgs(root, owner, projectNumber), {
56
+ timeout: 20_000,
57
+ });
58
+ if (r.error) return 'defer';
59
+ const output = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
60
+ if (isInsufficientScopes({ message: output })) return 'scope';
61
+ if (r.status !== 0 && GH_AUTH_RE.test(output)) return 'defer';
62
+ try {
63
+ const json = JSON.parse(r.stdout || '{}');
64
+ if (json?.data?.[root]?.projectV2?.id) return 'found';
65
+ } catch {
66
+ // Non-JSON output is a miss for this rung.
67
+ }
68
+ return 'miss';
69
+ }
70
+
71
+ // check: github-project-access
72
+
73
+ /**
74
+ * Can the active token read the configured Projects v2 board? No board →
75
+ * skipped; a gh that cannot run defers to `gh-auth`.
76
+ *
77
+ * @param {{ cwd?: () => string, fsImpl?: typeof fs, runner?: typeof spawn }} [opts]
78
+ * @returns {{ ok: boolean, detail: string, remedy?: string }}
79
+ */
80
+ export function runProjectAccess({ cwd, fsImpl = fs, runner = spawn } = {}) {
81
+ const projectRoot = (cwd ?? (() => process.cwd()))();
82
+ const { projectNumber, owner } = readBoardConfig(projectRoot, fsImpl);
83
+ if (!projectNumber) {
84
+ return {
85
+ ok: true,
86
+ detail: 'skipped — no github.projectNumber configured',
87
+ };
88
+ }
89
+ const roots = owner ? ['organization', 'user'] : ['viewer'];
90
+ const target = `project #${projectNumber}${owner ? ` for ${owner}` : ''}`;
91
+ for (const root of roots) {
92
+ const outcome = probeRung(runner, root, owner, projectNumber);
93
+ if (outcome === 'found') return { ok: true, detail: `${target} readable` };
94
+ if (outcome === 'defer') {
95
+ return {
96
+ ok: true,
97
+ detail: 'skipped — gh cannot run or authenticate (see gh-auth)',
98
+ };
99
+ }
100
+ if (outcome === 'scope') {
101
+ return {
102
+ ok: false,
103
+ detail: `token lacks the "project" scope — cannot read ${target}; board adds and Status flips are being skipped`,
104
+ remedy: REMEDY,
105
+ };
106
+ }
107
+ }
108
+ return {
109
+ ok: false,
110
+ detail: `${target} not found`,
111
+ remedy:
112
+ 'Check github.projectNumber and github.owner in .agentrc.json (or `gh auth refresh -h github.com -s project` if the board is private).',
113
+ };
114
+ }
@@ -19,6 +19,7 @@ import {
19
19
  } from './doctor-checks/codex.js';
20
20
  import { runMergeDriver } from './doctor-checks/merge-driver.js';
21
21
  import { runAgentsDrift, runPinCurrent } from './doctor-checks/payload.js';
22
+ import { runProjectAccess } from './doctor-checks/project-access.js';
22
23
  import {
23
24
  runAgentsMaterialized,
24
25
  runRuntimeDeps,
@@ -72,6 +73,11 @@ export const registry = [
72
73
  name: 'gh-auth',
73
74
  run: (opts) => runGhAuth(opts),
74
75
  },
76
+ // Presupposes gh-auth: an unauthenticated gh defers there.
77
+ {
78
+ name: 'github-project-access',
79
+ run: (opts) => runProjectAccess(opts),
80
+ },
75
81
  {
76
82
  name: 'commands-in-sync',
77
83
  run: (opts) => runCommandsInSync(opts),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.89.0",
3
+ "version": "2.90.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",