mandrel 2.86.0 → 2.88.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 (165) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { createHmac } from 'node:crypto';
13
+ import { parseArgs } from 'node:util';
13
14
  import { runAsCli } from './lib/cli-utils.js';
14
15
  import { resolveConfig } from './lib/config-resolver.js';
15
16
  import { Logger } from './lib/Logger.js';
@@ -123,111 +124,103 @@ export async function notify(ticketId, payload, opts = {}) {
123
124
  const commentEvents = resolveEventAllowlist(notifications, 'commentEvents');
124
125
  const webhookEvents = resolveEventAllowlist(notifications, 'webhookEvents');
125
126
 
126
- const numericId = Number.parseInt(ticketId, 10);
127
- const noTicket = Number.isNaN(numericId) || numericId <= 0;
128
- const callerSuppressed = opts.skipComment === true;
129
- const eventAllowedOnComments = Boolean(event) && commentEvents.has(event);
130
- const fireComment = !noTicket && !callerSuppressed && eventAllowedOnComments;
131
-
132
- if (fireComment) {
133
- const mention =
134
- severity === 'high' ||
135
- (severity === 'medium' && notifications?.mentionOperator);
136
- const commentBody = mention ? `${operator} ${message}` : message;
137
-
138
- await provider.postComment(numericId, {
139
- body: commentBody,
140
- type: SEVERITY_TO_COMMENT_TYPE[severity],
141
- });
127
+ const ctx = { config, operator, notifications, severity, message, event };
128
+ if (event && commentEvents.has(event) && opts.skipComment !== true) {
129
+ await postOperatorComment(provider, ticketId, ctx);
142
130
  }
143
-
144
131
  if (event && webhookEvents.has(event)) {
145
- // Only `undefined` resolves from env; an explicit `null` means none.
146
- const webhookUrl =
147
- opts.webhookUrl === undefined ? resolveWebhookUrl() : opts.webhookUrl;
148
- if (webhookUrl) {
149
- Logger.info(`[Notify] Firing webhook (${event}) to ${webhookUrl}...`);
150
- const payloadBody = buildWebhookPayload({
151
- config,
152
- ticketId,
153
- severity,
154
- message,
155
- operator,
156
- event,
157
- level,
158
- epicId,
159
- phase,
160
- });
161
- await sendWebhook(webhookUrl, payloadBody, opts.fetchImpl);
162
- } else {
163
- // Allowlisted but no URL: warn rather than drop silently.
164
- Logger.warn(
165
- `[Notify] Webhook event (${event}) suppressed — no webhook URL resolved (NOTIFICATION_WEBHOOK_URL unset or empty).`,
166
- );
167
- }
132
+ await fireWebhook(opts, { ...ctx, ticketId, level, epicId, phase });
168
133
  }
169
134
  }
170
135
 
171
- export function parseNotifyArgs(args) {
172
- if (args.length < 1) {
173
- throw new Error(
174
- 'Usage: node notify.js [TicketId] <Message> [--severity low|medium|high]',
136
+ async function postOperatorComment(provider, ticketId, ctx) {
137
+ const numericId = Number.parseInt(ticketId, 10);
138
+ if (Number.isNaN(numericId) || numericId <= 0) return;
139
+ const { severity, message, operator, notifications } = ctx;
140
+ const mention =
141
+ severity === 'high' ||
142
+ (severity === 'medium' && notifications?.mentionOperator);
143
+ await provider.postComment(numericId, {
144
+ body: mention ? `${operator} ${message}` : message,
145
+ type: SEVERITY_TO_COMMENT_TYPE[severity],
146
+ });
147
+ }
148
+
149
+ async function fireWebhook(opts, payload) {
150
+ // Only `undefined` resolves from env; an explicit `null` means none.
151
+ const webhookUrl =
152
+ opts.webhookUrl === undefined ? resolveWebhookUrl() : opts.webhookUrl;
153
+ if (!webhookUrl) {
154
+ // Allowlisted but no URL: warn rather than drop silently.
155
+ Logger.warn(
156
+ `[Notify] Webhook event (${payload.event}) suppressed — no webhook URL resolved (NOTIFICATION_WEBHOOK_URL unset or empty).`,
175
157
  );
158
+ return;
176
159
  }
160
+ Logger.info(`[Notify] Firing webhook (${payload.event}) to ${webhookUrl}...`);
161
+ await sendWebhook(webhookUrl, buildWebhookPayload(payload), opts.fetchImpl);
162
+ }
177
163
 
178
- let severity = 'medium';
179
- const sevIdx = args.indexOf('--severity');
180
- let working = args;
181
- if (sevIdx !== -1) {
182
- const raw = args[sevIdx + 1];
183
- if (!raw || !Object.hasOwn(SEVERITY_RANK, raw)) {
184
- throw new Error(
185
- '[Notify] --severity requires one of: low | medium | high.',
186
- );
187
- }
188
- severity = raw;
189
- working = args.filter((_a, i) => i !== sevIdx && i !== sevIdx + 1);
190
- }
164
+ const NOTIFY_USAGE_ERROR =
165
+ 'Usage: node notify.js [TicketId] <Message> [--severity low|medium|high]';
166
+ const MESSAGE_REQUIRED_ERROR = '[Notify] Error: Message is required.';
167
+ const NUMERIC_ID = /^\d+$/;
191
168
 
192
- if (working.length === 0) {
193
- throw new Error('[Notify] Error: Message is required.');
194
- }
169
+ const NOTIFY_OPTIONS = {
170
+ severity: { type: 'string' },
171
+ ticket: { type: 'string' },
172
+ issue: { type: 'string' },
173
+ };
195
174
 
196
- let ticketId = 0;
197
- let message = '';
198
- const explicitTicketFlag = working.findIndex(
199
- (arg) => arg === '--ticket' || arg === '--issue',
200
- );
175
+ function requireSeverity(raw) {
176
+ if (raw === undefined) return 'medium';
177
+ if (typeof raw === 'string' && Object.hasOwn(SEVERITY_RANK, raw)) return raw;
178
+ throw new Error('[Notify] --severity requires one of: low | medium | high.');
179
+ }
201
180
 
202
- if (explicitTicketFlag !== -1) {
203
- const rawTicketId = working[explicitTicketFlag + 1] ?? '';
204
- if (!/^\d+$/.test(rawTicketId)) {
205
- throw new Error(
206
- '[Notify] Error: --ticket/--issue requires a numeric ID.',
207
- );
208
- }
209
- ticketId = Number.parseInt(rawTicketId, 10);
210
- const positional = working.filter(
211
- (_arg, idx) =>
212
- idx !== explicitTicketFlag && idx !== explicitTicketFlag + 1,
213
- );
214
- message = positional.join(' ').trim();
215
- } else {
216
- const firstArg = working[0];
217
- const isNumeric = /^\d+$/.test(firstArg);
218
-
219
- if (isNumeric) {
220
- ticketId = Number.parseInt(firstArg, 10);
221
- message = working.slice(1).join(' ').trim();
222
- } else {
223
- message = firstArg;
224
- }
181
+ function requireTicketId(raw) {
182
+ if (typeof raw === 'string' && NUMERIC_ID.test(raw)) {
183
+ return Number.parseInt(raw, 10);
225
184
  }
185
+ throw new Error('[Notify] Error: --ticket/--issue requires a numeric ID.');
186
+ }
226
187
 
227
- if (!message) {
228
- throw new Error('[Notify] Error: Message is required.');
188
+ /** Without `--ticket`, a leading numeric positional is the legacy ticket id. */
189
+ function splitTicketAndMessage(explicitTicket, positionals) {
190
+ if (explicitTicket !== undefined) {
191
+ return {
192
+ ticketId: requireTicketId(explicitTicket),
193
+ message: positionals.join(' ').trim(),
194
+ };
195
+ }
196
+ const [first = '', ...rest] = positionals;
197
+ if (NUMERIC_ID.test(first)) {
198
+ return {
199
+ ticketId: Number.parseInt(first, 10),
200
+ message: rest.join(' ').trim(),
201
+ };
229
202
  }
203
+ return { ticketId: 0, message: first };
204
+ }
230
205
 
206
+ export function parseNotifyArgs(args) {
207
+ if (args.length < 1) throw new Error(NOTIFY_USAGE_ERROR);
208
+ const { values, positionals } = parseArgs({
209
+ args,
210
+ options: NOTIFY_OPTIONS,
211
+ allowPositionals: true,
212
+ strict: false,
213
+ });
214
+ const severity = requireSeverity(values.severity);
215
+ const explicitTicket = values.ticket ?? values.issue;
216
+ if (positionals.length === 0 && explicitTicket === undefined) {
217
+ throw new Error(MESSAGE_REQUIRED_ERROR);
218
+ }
219
+ const { ticketId, message } = splitTicketAndMessage(
220
+ explicitTicket,
221
+ positionals,
222
+ );
223
+ if (!message) throw new Error(MESSAGE_REQUIRED_ERROR);
231
224
  return { ticketId, message, severity };
232
225
  }
233
226
 
@@ -88,19 +88,23 @@ export function resolveDefaultOutPath({
88
88
  );
89
89
  }
90
90
 
91
+ /** @param {string} token a `#` prefix is stripped */
92
+ function parseIdToken(token) {
93
+ return Number(token.trim().replace(/^#/, ''));
94
+ }
95
+
91
96
  /**
92
97
  * @param {string} raw
93
98
  * @returns {number[]}
94
99
  */
95
100
  export function parseTicketIds(raw) {
96
- if (typeof raw !== 'string' || raw.trim().length === 0) {
101
+ if (typeof raw !== 'string' || raw.replace(/[,\s]/g, '').length === 0) {
97
102
  throw new Error('--tickets requires one or more positive issue ids.');
98
103
  }
99
104
  const ids = raw
100
105
  .split(/[,\s]+/)
101
- .map((s) => s.trim())
102
106
  .filter(Boolean)
103
- .map((s) => Number(s));
107
+ .map(parseIdToken);
104
108
  if (ids.some((n) => !Number.isInteger(n) || n <= 0)) {
105
109
  throw new Error(
106
110
  `--tickets expects positive integer ids; got ${JSON.stringify(raw)}`,
@@ -117,7 +121,7 @@ export function parseAmendsId(raw) {
117
121
  if (typeof raw !== 'string' || raw.trim().length === 0) {
118
122
  throw new Error('--amends requires a single prior Story id.');
119
123
  }
120
- const id = Number(raw.trim().replace(/^#/, ''));
124
+ const id = parseIdToken(raw);
121
125
  if (!Number.isInteger(id) || id <= 0) {
122
126
  throw new Error(
123
127
  `--amends expects a positive integer Story id; got ${JSON.stringify(raw)}`,
@@ -1,10 +1,15 @@
1
1
  /**
2
2
  * GitHub Provider — token resolution: GITHUB_TOKEN / GH_TOKEN env →
3
- * `gh auth token` → instructive throw. `execSync` sits behind a holder so
4
- * tests can swap it.
3
+ * `gh auth token` → classified throw (`gh-token-diagnostics.js`). `execSync`
4
+ * sits behind a holder so tests can swap it.
5
5
  */
6
6
 
7
7
  import { execSync as defaultExecSync } from 'node:child_process';
8
+ import {
9
+ describeTokenFailure,
10
+ runGhAuthToken,
11
+ TOKEN_SOURCE_ENV,
12
+ } from './gh-token-diagnostics.js';
8
13
 
9
14
  export const execSyncHolder = { impl: defaultExecSync };
10
15
 
@@ -14,31 +19,9 @@ export function __setExecSyncForTests(fn) {
14
19
 
15
20
  /* node:coverage ignore next */
16
21
  export function readGhCliToken() {
17
- try {
18
- const t = execSyncHolder
19
- .impl('gh auth token', {
20
- encoding: 'utf8',
21
- timeout: 5000,
22
- stdio: ['pipe', 'pipe', 'pipe'],
23
- })
24
- .trim();
25
- return t || null;
26
- } catch {
27
- // gh CLI not installed or not authenticated.
28
- return null;
29
- }
22
+ return runGhAuthToken(execSyncHolder.impl);
30
23
  }
31
24
 
32
- const TOKEN_MISSING_ERROR = [
33
- '[GitHubProvider] Authentication Failed: No GitHub token found.',
34
- '',
35
- 'To resolve this, choose one of the following:',
36
- ' A. (CI/CD / Agent Script) Set the GITHUB_TOKEN or GH_TOKEN environment variable.',
37
- ' B. (Local) Run `gh auth login` to authenticate the GitHub CLI.',
38
- '',
39
- 'See .agents/README.md#github-authentication for details.',
40
- ].join('\n');
41
-
42
25
  /* node:coverage ignore next */
43
26
  function readEnvToken() {
44
27
  return process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null;
@@ -46,15 +29,16 @@ function readEnvToken() {
46
29
 
47
30
  /* node:coverage ignore next */
48
31
  function memoizeEnvToken(token) {
49
- if (!process.env.GITHUB_TOKEN) process.env.GITHUB_TOKEN = token;
32
+ process.env.GITHUB_TOKEN = token;
33
+ process.env[TOKEN_SOURCE_ENV] = 'gh-cli';
50
34
  }
51
35
 
52
36
  /* node:coverage ignore next */
53
37
  export function resolveToken() {
54
38
  const envToken = readEnvToken();
55
39
  if (envToken) return envToken;
56
- const ghToken = readGhCliToken();
57
- if (!ghToken) throw new Error(TOKEN_MISSING_ERROR);
58
- memoizeEnvToken(ghToken);
59
- return ghToken;
40
+ const result = readGhCliToken();
41
+ if (!result.token) throw new Error(describeTokenFailure(result));
42
+ memoizeEnvToken(result.token);
43
+ return result.token;
60
44
  }
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { Logger } from '../../lib/Logger.js';
9
9
  import { concurrentMap } from '../../lib/util/concurrent-map.js';
10
- import { paginateRest } from './request-helpers.js';
10
+ import { paginateRest, postEdges } from './request-helpers.js';
11
11
 
12
12
  /** Modest, to stay clear of GitHub's secondary rate limits. */
13
13
  const EDGE_CONCURRENCY = 5;
@@ -79,32 +79,16 @@ async function addBlockedByEdges({
79
79
  const missing = blockerInternalIds.filter((id) => !existingSet.has(id));
80
80
  const skipped = blockerInternalIds.length - missing.length;
81
81
 
82
- const perEdge = await concurrentMap(
83
- missing,
84
- async (blockerId) => {
85
- try {
86
- await gh.api({
87
- method: 'POST',
88
- endpoint: `/repos/${owner}/${repo}/issues/${issueNumber}/dependencies/blocked_by`,
89
- body: { issue_id: blockerId },
90
- });
91
- return { added: 1, failed: 0 };
92
- } catch (err) {
93
- Logger.warn(
94
- `[blocked-by-add] Failed to add blocked-by edge #${issueNumber} ← blocker(id=${blockerId}): ${err.message}`,
95
- );
96
- return { added: 0, failed: 1 };
97
- }
98
- },
99
- { concurrency: EDGE_CONCURRENCY },
100
- );
101
-
102
- let added = 0;
103
- let failed = 0;
104
- for (const r of perEdge) {
105
- added += r.added;
106
- failed += r.failed;
107
- }
82
+ const { added, failed } = await postEdges({
83
+ edges: missing,
84
+ endpointFor: () =>
85
+ `/repos/${owner}/${repo}/issues/${issueNumber}/dependencies/blocked_by`,
86
+ bodyFor: (blockerId) => ({ issue_id: blockerId }),
87
+ describe: (blockerId) =>
88
+ `[blocked-by-add] Failed to add blocked-by edge #${issueNumber} ← blocker(id=${blockerId})`,
89
+ gh,
90
+ concurrency: EDGE_CONCURRENCY,
91
+ });
108
92
 
109
93
  return { added, skipped, failed };
110
94
  }
@@ -69,6 +69,7 @@ export function composeGateways(provider) {
69
69
  get token() {
70
70
  return p._memoizedToken;
71
71
  },
72
+ ensureIdentity: () => p._ensureIdentity(),
72
73
  state: { projectId: null },
73
74
  hooks: {
74
75
  getTicket: (id, o) => p.getTicket(id, o),
@@ -0,0 +1,130 @@
1
+ /** Classified `gh auth token` results; only a confirmed not-logged-in result says `gh auth login`. */
2
+
3
+ import {
4
+ isTransportFailure,
5
+ sandboxDenialCode,
6
+ TRANSPORT_REMEDY,
7
+ } from '../../lib/gh-transport.js';
8
+
9
+ /** Marks a memoised `GITHUB_TOKEN` as copied out of the `gh` store. */
10
+ export const TOKEN_SOURCE_ENV = 'MANDREL_GH_TOKEN_SOURCE';
11
+
12
+ const TOKEN_SHAPE =
13
+ /\b(?:gh[pousr]_[A-Za-z0-9]{8,}|github_pat_[A-Za-z0-9_]{8,})\b/g;
14
+
15
+ function redactTokens(text) {
16
+ return String(text ?? '').replace(TOKEN_SHAPE, '[redacted]');
17
+ }
18
+
19
+ /** Last stderr line (or the message), redacted. */
20
+ export function failureDetail(err) {
21
+ const lines = String(err?.stderr ?? '')
22
+ .split('\n')
23
+ .map((l) => l.trim())
24
+ .filter(Boolean);
25
+ return redactTokens(lines.at(-1) ?? err?.message ?? 'unknown error');
26
+ }
27
+
28
+ const NOT_INSTALLED_RE = /command not found|: not found|is not recognized/i;
29
+ const NOT_LOGGED_IN_RE =
30
+ /not logged in|no oauth token|gh auth login|http 401|bad credentials|authentication required/i;
31
+
32
+ function isNotInstalled(err) {
33
+ return (
34
+ err?.code === 'ENOENT' ||
35
+ err?.status === 127 ||
36
+ NOT_INSTALLED_RE.test(`${err?.stderr ?? ''}\n${err?.message ?? ''}`)
37
+ );
38
+ }
39
+
40
+ function isTimeoutOrDenied(err) {
41
+ return (
42
+ err?.code === 'ETIMEDOUT' ||
43
+ err?.signal === 'SIGTERM' ||
44
+ sandboxDenialCode(err) !== null
45
+ );
46
+ }
47
+
48
+ function classifyGhTokenFailure(err) {
49
+ if (isNotInstalled(err)) return 'not-installed';
50
+ if (isTimeoutOrDenied(err) || isTransportFailure(err)) return 'transport';
51
+ if (NOT_LOGGED_IN_RE.test(`${err?.stderr ?? ''}\n${err?.message ?? ''}`)) {
52
+ return 'auth-rejected';
53
+ }
54
+ return 'unknown';
55
+ }
56
+
57
+ /**
58
+ * @typedef {{ token: string|null,
59
+ * verdict: 'ok'|'not-installed'|'transport'|'auth-rejected'|'unknown',
60
+ * detail: string|null }} GhTokenResult
61
+ */
62
+
63
+ /** @returns {GhTokenResult} */
64
+ export function runGhAuthToken(execImpl) {
65
+ try {
66
+ const out = execImpl('gh auth token', {
67
+ encoding: 'utf8',
68
+ timeout: 5000,
69
+ stdio: ['pipe', 'pipe', 'pipe'],
70
+ env: process.env,
71
+ });
72
+ const token = String(out ?? '').trim();
73
+ if (token) return { token, verdict: 'ok', detail: null };
74
+ return {
75
+ token: null,
76
+ verdict: 'auth-rejected',
77
+ detail: 'gh auth token printed no token',
78
+ };
79
+ } catch (err) {
80
+ return {
81
+ token: null,
82
+ verdict: classifyGhTokenFailure(err),
83
+ detail: failureDetail(err),
84
+ };
85
+ }
86
+ }
87
+
88
+ function configDirNote() {
89
+ const dir = process.env.GH_CONFIG_DIR;
90
+ return dir ? ` (GH_CONFIG_DIR=${dir})` : '';
91
+ }
92
+
93
+ const FAILURE_LINES = {
94
+ 'not-installed': () => [
95
+ '[GitHubProvider] Authentication Failed: the GitHub CLI (`gh`) is not installed or not on PATH.',
96
+ '',
97
+ 'Install `gh`, or set the GITHUB_TOKEN or GH_TOKEN environment variable.',
98
+ ],
99
+ transport: () => [
100
+ `[GitHubProvider] GitHub CLI unreachable: \`gh auth token\` could not run${configDirNote()} — a sandbox or network fault, not an authentication failure.`,
101
+ '',
102
+ `Remedy: ${TRANSPORT_REMEDY}.`,
103
+ ],
104
+ unknown: () => [
105
+ `[GitHubProvider] \`gh auth token\` failed for an unrecognised reason${configDirNote()}; credentials were not confirmed missing.`,
106
+ '',
107
+ 'Run `gh auth status` to see what gh reports, or set GITHUB_TOKEN / GH_TOKEN.',
108
+ ],
109
+ 'auth-rejected': () => [
110
+ `[GitHubProvider] Authentication Failed: No GitHub token found${configDirNote()}.`,
111
+ '',
112
+ 'To resolve this, choose one of the following:',
113
+ ' A. (CI/CD / Agent Script) Set the GITHUB_TOKEN or GH_TOKEN environment variable.',
114
+ ' B. (Local) Run `gh auth login` to authenticate the GitHub CLI.',
115
+ ],
116
+ };
117
+
118
+ export function describeTokenFailure({ verdict, detail }) {
119
+ const lines = (FAILURE_LINES[verdict] ?? FAILURE_LINES['auth-rejected'])();
120
+ if (detail) lines.push(`gh said: ${detail}`);
121
+ lines.push('', 'See .agents/README.md#github-authentication for details.');
122
+ return lines.join('\n');
123
+ }
124
+
125
+ /** `env` for an exported token, `gh-cli` for the gh store (or a token memoised from it). */
126
+ export function resolveTokenSource(env = process.env) {
127
+ if (!env.GITHUB_TOKEN && !env.GH_TOKEN) return 'gh-cli';
128
+ if (env[TOKEN_SOURCE_ENV] === 'gh-cli' && !env.GH_TOKEN) return 'gh-cli';
129
+ return 'env';
130
+ }
@@ -0,0 +1,158 @@
1
+ /** Operator identity preflight: the gh-store login must equal `github.operatorHandle` before any write. */
2
+
3
+ import { GhAuthError, GhNotInstalledError } from '../../lib/gh-exec.js';
4
+ import {
5
+ isTransportFailure,
6
+ TRANSPORT_REMEDY,
7
+ } from '../../lib/gh-transport.js';
8
+ import { failureDetail, resolveTokenSource } from './gh-token-diagnostics.js';
9
+
10
+ class GitHubIdentityError extends Error {
11
+ constructor(message, code) {
12
+ super(message);
13
+ this.name = 'GitHubIdentityError';
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ /** `@Name` → `name`; null for unset or placeholder. */
19
+ function normalizeHandle(handle) {
20
+ if (typeof handle !== 'string') return null;
21
+ const bare = handle.trim().replace(/^@/, '').toLowerCase();
22
+ if (bare.length === 0 || /^\[.*\]$/.test(bare)) return null;
23
+ return bare;
24
+ }
25
+
26
+ function isMutatingApiCall({ method = 'GET', endpoint, body } = {}) {
27
+ if (endpoint === 'graphql') return isGraphqlMutation(body?.query);
28
+ return String(method).toUpperCase() !== 'GET';
29
+ }
30
+
31
+ function isGraphqlMutation(query) {
32
+ return /^\s*mutation\b/.test(String(query ?? ''));
33
+ }
34
+
35
+ const MUTATING_METHODS = Object.freeze({
36
+ issue: ['edit', 'comment'],
37
+ pr: ['create', 'edit', 'merge', 'updateBranch'],
38
+ label: ['create', 'edit'],
39
+ repo: ['edit'],
40
+ });
41
+
42
+ /** A `createGh` facade whose writes await `ensure()` first. */
43
+ function guardMutations(gh, ensure) {
44
+ const before =
45
+ (fn) =>
46
+ async (...args) => {
47
+ await ensure();
48
+ return fn(...args);
49
+ };
50
+ const guarded = {
51
+ ...gh,
52
+ api: async (opts) => {
53
+ if (isMutatingApiCall(opts)) await ensure();
54
+ return gh.api(opts);
55
+ },
56
+ };
57
+ for (const [group, methods] of Object.entries(MUTATING_METHODS)) {
58
+ if (!gh[group]) continue;
59
+ guarded[group] = { ...gh[group] };
60
+ for (const m of methods) {
61
+ if (typeof gh[group][m] === 'function') {
62
+ guarded[group][m] = before(gh[group][m].bind(gh[group]));
63
+ }
64
+ }
65
+ }
66
+ return guarded;
67
+ }
68
+
69
+ function configDirInEffect(env) {
70
+ return env.GH_CONFIG_DIR || "gh's default config dir";
71
+ }
72
+
73
+ function classifyProbeFailure(err, configDir) {
74
+ const said = `gh said: ${failureDetail(err)}`;
75
+ if (isTransportFailure(err)) {
76
+ return new GitHubIdentityError(
77
+ `[GitHubProvider] Identity check could not reach GitHub (GH_CONFIG_DIR: ${configDir}) — a sandbox or network fault, not an authentication failure; ${TRANSPORT_REMEDY}. ${said}`,
78
+ 'identity-transport',
79
+ );
80
+ }
81
+ if (err instanceof GhNotInstalledError) {
82
+ return new GitHubIdentityError(
83
+ `[GitHubProvider] Identity check needs the GitHub CLI (\`gh\`), which is not installed or not on PATH. ${said}`,
84
+ 'identity-not-installed',
85
+ );
86
+ }
87
+ if (err instanceof GhAuthError) {
88
+ return new GitHubIdentityError(
89
+ `[GitHubProvider] Identity check was rejected by GitHub (GH_CONFIG_DIR: ${configDir}): the gh store holds no valid login — run \`gh auth login\` against that config dir. ${said}`,
90
+ 'identity-auth',
91
+ );
92
+ }
93
+ return new GitHubIdentityError(
94
+ `[GitHubProvider] Identity check failed for an unrecognised reason (GH_CONFIG_DIR: ${configDir}); no mutation was sent. ${said}`,
95
+ 'identity-unknown',
96
+ );
97
+ }
98
+
99
+ /** One `/user` probe per process per GH_CONFIG_DIR. */
100
+ const _loginByConfigDir = new Map();
101
+
102
+ async function probeLogin(gh) {
103
+ const res = await gh.api({
104
+ method: 'GET',
105
+ endpoint: 'user',
106
+ fields: ['login'],
107
+ });
108
+ const login = String(res?.stdout ?? '').trim();
109
+ if (!login) throw new Error('GET /user returned no login');
110
+ return login;
111
+ }
112
+
113
+ function cachedLogin(gh, env) {
114
+ const key = env.GH_CONFIG_DIR ?? '';
115
+ if (!_loginByConfigDir.has(key)) {
116
+ const pending = probeLogin(gh);
117
+ _loginByConfigDir.set(key, pending);
118
+ // A failed probe is not memoised; the next mutation retries it.
119
+ pending.catch(() => _loginByConfigDir.delete(key));
120
+ }
121
+ return _loginByConfigDir.get(key);
122
+ }
123
+
124
+ /** `gh` is the UNGUARDED facade the probe runs through. */
125
+ function createIdentityGate({ gh, expectedHandle, env = process.env }) {
126
+ const expected = normalizeHandle(expectedHandle);
127
+ return async function ensureIdentity() {
128
+ if (!expected || resolveTokenSource(env) !== 'gh-cli') return;
129
+ const configDir = configDirInEffect(env);
130
+ let login;
131
+ try {
132
+ login = await cachedLogin(gh, env);
133
+ } catch (err) {
134
+ throw classifyProbeFailure(err, configDir);
135
+ }
136
+ if (normalizeHandle(login) === expected) return;
137
+ throw new GitHubIdentityError(
138
+ `[GitHubProvider] Refusing to write as the wrong GitHub account: github.operatorHandle expects @${expected}, ` +
139
+ `but the gh store (GH_CONFIG_DIR: ${configDir}) is logged in as @${login}. ` +
140
+ 'Fix: point github.cliConfigDir (in .agentrc.local.json) at the store that holds the expected account, ' +
141
+ `or log that store in as @${expected}. No mutation was sent.`,
142
+ 'identity-mismatch',
143
+ );
144
+ };
145
+ }
146
+
147
+ /** Provider `_gh`/`_ensureIdentity`; an injected `opts.gh` opts in via `verifyIdentity`, an explicit token never gates. */
148
+ export function gateProviderGh(gh, operatorHandle, opts) {
149
+ const verify = (opts.verifyIdentity ?? !opts.gh) && !opts.token;
150
+ if (!verify) return { _gh: gh, _ensureIdentity: async () => {} };
151
+ const ensure = createIdentityGate({ gh, expectedHandle: operatorHandle });
152
+ return { _gh: guardMutations(gh, ensure), _ensureIdentity: ensure };
153
+ }
154
+
155
+ /** Runs `ctx.ensureIdentity` before a GraphQL mutation; queries pass. */
156
+ export async function ensureIdentityForQuery(ctx, query) {
157
+ if (isGraphqlMutation(query)) await ctx.ensureIdentity?.();
158
+ }
@@ -125,8 +125,8 @@ export class IssuesGateway {
125
125
  * @param {{ state?: 'open'|'closed'|'all', labels?: string }} [opts]
126
126
  * @returns {Promise<Array<object>>} Mapped tickets (`id` is the issue number).
127
127
  * @field-manifest /repos/{owner}/{repo}/issues: number, id, node_id, title,
128
- * body, labels, state, state_reason, assignees, html_url,
129
- * pull_request
128
+ * body, labels, state, state_reason, closed_at, assignees,
129
+ * html_url, pull_request
130
130
  */
131
131
  async listTicketsByLabel(opts = {}) {
132
132
  const issues = await this.listIssuesByLabel(opts);