mandrel 2.83.0 → 2.85.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 (54) hide show
  1. package/.agents/README.md +65 -20
  2. package/.agents/docs/configuration.md +36 -0
  3. package/.agents/docs/runbooks/mods.md +98 -54
  4. package/.agents/docs/workflows.md +14 -0
  5. package/.agents/instructions.md +4 -1
  6. package/.agents/mods/mandrel-status/hooks/register.tsx +579 -204
  7. package/.agents/mods/mandrel-status/types/index.d.ts +58 -13
  8. package/.agents/schemas/story-deliver-terminal.schema.json +2 -2
  9. package/.agents/scripts/boot-sweep.js +42 -13
  10. package/.agents/scripts/coverage-capture.js +1 -0
  11. package/.agents/scripts/evidence-gate.js +1 -0
  12. package/.agents/scripts/generate-workflows-doc.js +14 -0
  13. package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
  14. package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
  15. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
  16. package/.agents/scripts/lib/close-lock-events.js +29 -9
  17. package/.agents/scripts/lib/codex/agents-projection.js +284 -0
  18. package/.agents/scripts/lib/codex/skills-projection.js +291 -0
  19. package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
  20. package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
  21. package/.agents/scripts/lib/config-resolver.js +5 -42
  22. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  23. package/.agents/scripts/lib/full-suite-lock.js +2 -0
  24. package/.agents/scripts/lib/full-suite-queue.js +66 -26
  25. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  26. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +242 -0
  27. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +151 -111
  28. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
  29. package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
  30. package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
  31. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +12 -5
  33. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +30 -4
  34. package/.agents/scripts/lib/orchestration/story-handoff.js +84 -10
  35. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
  36. package/.agents/scripts/single-story-init.js +20 -5
  37. package/.agents/scripts/sync-agentrc.js +5 -3
  38. package/.agents/scripts/sync-claude-agents.js +20 -0
  39. package/.agents/scripts/sync-claude-commands.js +64 -27
  40. package/.agents/scripts/sync-codex-agents.js +36 -0
  41. package/.agents/scripts/sync-codex-skills.js +36 -0
  42. package/.agents/workflows/helpers/deliver-story-reference.md +6 -0
  43. package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
  44. package/.agents/workflows/mandrel-update.md +2 -1
  45. package/docs/CHANGELOG.md +23 -0
  46. package/lib/cli/guarded-sync.js +3 -2
  47. package/lib/cli/registry.js +248 -0
  48. package/lib/cli/sync-agents.js +5 -2
  49. package/lib/cli/sync-commands.js +5 -2
  50. package/lib/cli/sync.js +45 -14
  51. package/lib/cli/uninstall.js +8 -1
  52. package/lib/migrations/index.js +2 -0
  53. package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
  54. package/package.json +3 -2
@@ -1,13 +1,16 @@
1
1
  /**
2
- * Read-only `.agentrc.json` reconciliation: validate against the schema
3
- * (never silently strip), never auto-fill defaults (the runtime layers them
4
- * at read time), and flag leaves equal to their default as `[REDUNDANT]`.
2
+ * Read-only `.agentrc.json` reconciliation: validate the effective config —
3
+ * `.agentrc.local.json` deep-merged over `.agentrc.json`, as the runtime
4
+ * resolver does — against the schema (never silently strip), never auto-fill
5
+ * defaults (the runtime layers them at read time), and flag committed leaves
6
+ * equal to their default as `[REDUNDANT]`.
5
7
  */
6
8
 
7
9
  import fs from 'node:fs';
8
10
  import path from 'node:path';
9
11
  import { AGENTRC_SCHEMA, getAgentrcValidator } from '../config-schema.js';
10
12
  import { deepEqual } from '../json-utils.js';
13
+ import { applyLocalOverlay, formatAgentrcErrors } from './agentrc-overlay.js';
11
14
  import {
12
15
  getAgentrcDefaults,
13
16
  IDENTITY_PLACEHOLDER_PATHS,
@@ -29,6 +32,7 @@ import {
29
32
  * @property {SyncChange[]} changes
30
33
  * @property {string[]} errors
31
34
  * @property {string} configPath
35
+ * @property {string|null} [localPath] the merged `.agentrc.local.json`, if any
32
36
  * @property {boolean} wrote whether `.agentrc.json` was rewritten
33
37
  */
34
38
 
@@ -69,20 +73,23 @@ export function syncAgentrc(opts) {
69
73
  };
70
74
  }
71
75
 
76
+ let overlay;
77
+ try {
78
+ overlay = applyLocalOverlay({ fsImpl, projectRoot, committed: raw });
79
+ } catch (err) {
80
+ return invalidResult(configPath, err.localPath, [err.message]);
81
+ }
82
+
72
83
  const validate = getAgentrcValidator();
73
- if (!validate(raw)) {
74
- const errors = (validate.errors || []).map(
75
- (e) => `${e.instancePath || '(root)'} ${e.message}`,
76
- );
77
- return {
78
- status: 'invalid',
79
- changes: [],
80
- errors,
84
+ if (!validate(overlay.effective)) {
85
+ return invalidResult(
81
86
  configPath,
82
- wrote: false,
83
- };
87
+ overlay.localPath,
88
+ formatAgentrcErrors(validate.errors),
89
+ );
84
90
  }
85
91
 
92
+ // Advisories target the committed file only: the overlay is per-machine.
86
93
  const changes = collectRedundantAdvisories(raw, defaults);
87
94
 
88
95
  return {
@@ -90,6 +97,18 @@ export function syncAgentrc(opts) {
90
97
  changes,
91
98
  errors: [],
92
99
  configPath,
100
+ localPath: overlay.localPath,
101
+ wrote: false,
102
+ };
103
+ }
104
+
105
+ function invalidResult(configPath, localPath, errors) {
106
+ return {
107
+ status: 'invalid',
108
+ changes: [],
109
+ errors,
110
+ configPath,
111
+ localPath,
93
112
  wrote: false,
94
113
  };
95
114
  }
@@ -168,16 +187,13 @@ export function formatSyncReport(result) {
168
187
  return lines.join('\n');
169
188
  }
170
189
  if (result.status === 'invalid') {
171
- lines.push('[sync-agentrc] ❌ Validation failed:');
190
+ lines.push(`[sync-agentrc] ❌ Validation failed${overlayNote(result)}:`);
172
191
  for (const err of result.errors) lines.push(` - ${err}`);
173
192
  return lines.join('\n');
174
193
  }
175
194
  const redundant = result.changes.filter((c) => c.op === 'REDUNDANT');
176
- if (redundant.length === 0) {
177
- lines.push('[sync-agentrc] ✅ No changes required.');
178
- return lines.join('\n');
179
- }
180
- lines.push('[sync-agentrc] ✅ No changes required.');
195
+ lines.push(`[sync-agentrc] ✅ No changes required${overlayNote(result)}.`);
196
+ if (redundant.length === 0) return lines.join('\n');
181
197
  lines.push(
182
198
  `[sync-agentrc] Advisories: ${redundant.length} project key(s) match framework defaults — informational only.`,
183
199
  );
@@ -190,6 +206,10 @@ export function formatSyncReport(result) {
190
206
  return lines.join('\n');
191
207
  }
192
208
 
209
+ function overlayNote(result) {
210
+ return result.localPath ? ` (with overlay ${result.localPath})` : '';
211
+ }
212
+
193
213
  function previewValue(value) {
194
214
  let s;
195
215
  try {
@@ -6,6 +6,10 @@
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
+ import {
10
+ deepMergeObjects,
11
+ formatAgentrcErrors,
12
+ } from './config/agentrc-overlay.js';
9
13
  import { getCiDelivery } from './config/ci.js';
10
14
  import { getCommands } from './config/commands.js';
11
15
  import { getGitHub } from './config/github.js';
@@ -90,45 +94,6 @@ function applyDeliveryDefaults(rawDelivery) {
90
94
  return delivery;
91
95
  }
92
96
 
93
- /**
94
- * Deep-merge plain objects for the `.agentrc.local.json` overlay. Arrays and
95
- * scalars from `override` replace the base value at that key.
96
- *
97
- * @param {unknown} base
98
- * @param {unknown} override
99
- * @returns {unknown}
100
- */
101
- function deepMergeObjects(base, override) {
102
- if (
103
- override === null ||
104
- typeof override !== 'object' ||
105
- Array.isArray(override)
106
- ) {
107
- return override;
108
- }
109
- if (base === null || typeof base !== 'object' || Array.isArray(base)) {
110
- return { ...override };
111
- }
112
- const out = { ...base };
113
- for (const key of Object.keys(override)) {
114
- const baseVal = base[key];
115
- const overrideVal = override[key];
116
- if (
117
- overrideVal !== null &&
118
- typeof overrideVal === 'object' &&
119
- !Array.isArray(overrideVal) &&
120
- baseVal !== null &&
121
- typeof baseVal === 'object' &&
122
- !Array.isArray(baseVal)
123
- ) {
124
- out[key] = deepMergeObjects(baseVal, overrideVal);
125
- } else {
126
- out[key] = overrideVal;
127
- }
128
- }
129
- return out;
130
- }
131
-
132
97
  /** @param {import('node:fs')} fsImpl */
133
98
  function readJsonConfigFile(fsImpl, filePath, label) {
134
99
  try {
@@ -231,9 +196,7 @@ export function resolveConfig(opts) {
231
196
  if (validate) {
232
197
  const validateAgentrc = getAgentrcValidator();
233
198
  if (!validateAgentrc(raw)) {
234
- const details = (validateAgentrc.errors || [])
235
- .map((e) => `${e.instancePath || '(root)'} ${e.message}`)
236
- .join(', ');
199
+ const details = formatAgentrcErrors(validateAgentrc.errors).join(', ');
237
200
  throw new Error(`[config] Invalid .agentrc.json: ${details}`);
238
201
  }
239
202
  }
@@ -71,7 +71,7 @@ export const CODE_REVIEW_SCHEMA = {
71
71
  description:
72
72
  'Review-provider chain and on-branch remediation threshold for the /mandrel-deliver code-review ceremony.',
73
73
  properties: {
74
- // An adapter whose probe fails (e.g. codex without `/codex:review`)
74
+ // An adapter whose probe fails (e.g. codex without the Codex CLI)
75
75
  // hard-fails at construction — no silent fallback to native.
76
76
  providers: {
77
77
  type: 'array',
@@ -50,6 +50,7 @@ const LOCK_DEFAULTS = Object.freeze({
50
50
  acquireOnceFn: (opts) => acquireSweepLock(opts),
51
51
  onWaitExpired: () => LOCK_WAIT_EXPIRED_EXIT_CODE,
52
52
  onLockOutcome: () => {},
53
+ onLockProgress: () => {},
53
54
  rerunCommand: 'the same command',
54
55
  });
55
56
 
@@ -170,6 +171,7 @@ function consult(probe, applies) {
170
171
  * skipIfSatisfied?: () => T|undefined,
171
172
  * onWaitExpired?: (holder: import('./full-suite-queue.js').LockHolder) => T,
172
173
  * onLockOutcome?: (outcome: object) => void,
174
+ * onLockProgress?: (progress: import('./full-suite-queue.js').LockProgress) => void,
173
175
  * rerunCommand?: string,
174
176
  * }} opts A non-`undefined` `skipIfSatisfied` return stands in for the spawn.
175
177
  * @param {(timing: { lockWaitMs: number }) => Promise<T>} spawn
@@ -94,20 +94,8 @@ function isLiveEntry({ dir, name, staleMs, nowFn, fsImpl, killFn }) {
94
94
  }
95
95
  }
96
96
 
97
- /**
98
- * With no ticket, true only when nobody is queued.
99
- *
100
- * @param {{
101
- * lockPath: string,
102
- * ticket: Ticket|null,
103
- * staleMs: number,
104
- * nowFn?: () => number,
105
- * fsImpl?: object,
106
- * killFn?: Function,
107
- * }} opts
108
- * @returns {boolean}
109
- */
110
- export function isFirstInLine({
97
+ /** Live waiters ahead of `ticket`; `null` when the queue is unreadable. */
98
+ function countAhead({
111
99
  lockPath,
112
100
  ticket,
113
101
  staleMs,
@@ -120,15 +108,31 @@ export function isFirstInLine({
120
108
  try {
121
109
  names = fsImpl.readdirSync(dir).map(String).sort();
122
110
  } catch {
123
- return true;
124
- }
125
- for (const name of names) {
126
- if (name === ticket?.name) return true;
127
- if (isLiveEntry({ dir, name, staleMs, nowFn, fsImpl, killFn })) {
128
- return false;
129
- }
111
+ return null;
130
112
  }
131
- return true;
113
+ const own = ticket ? names.indexOf(ticket.name) : -1;
114
+ return names
115
+ .slice(0, own === -1 ? names.length : own)
116
+ .filter((name) =>
117
+ isLiveEntry({ dir, name, staleMs, nowFn, fsImpl, killFn }),
118
+ ).length;
119
+ }
120
+
121
+ /**
122
+ * With no ticket, true only when nobody is queued.
123
+ *
124
+ * @param {{
125
+ * lockPath: string,
126
+ * ticket: Ticket|null,
127
+ * staleMs: number,
128
+ * nowFn?: () => number,
129
+ * fsImpl?: object,
130
+ * killFn?: Function,
131
+ * }} opts
132
+ * @returns {boolean}
133
+ */
134
+ export function isFirstInLine(opts) {
135
+ return (countAhead(opts) ?? 0) === 0;
132
136
  }
133
137
 
134
138
  /**
@@ -171,19 +175,29 @@ function holderLabel(lockPath, fsImpl) {
171
175
  return `holding pid ${readLockHolderPid(lockPath, fsImpl) ?? 'unknown'}`;
172
176
  }
173
177
 
178
+ /**
179
+ * @typedef {{
180
+ * phase: 'waiting'|'still-waiting'|'acquired'|'expired',
181
+ * waitedSeconds: number, waitBudgetSeconds: number,
182
+ * holder?: LockHolder, queueAhead?: number,
183
+ * }} LockProgress
184
+ */
185
+
174
186
  /**
175
187
  * @param {{
176
188
  * lockPath: string, waitMs: number, pollMs: number, staleMs: number,
177
189
  * reportMs: number, fsImpl: object, nowFn: () => number,
178
190
  * sleepFn: (ms: number) => Promise<void>, acquireOnceFn: Function,
179
191
  * log: (m: string) => void, rerunCommand: string,
180
- * }} opts
192
+ * onLockProgress?: (progress: LockProgress) => void,
193
+ * }} opts A throwing `onLockProgress` is swallowed.
181
194
  * @returns {Promise<{ held: object|null, expired: boolean, waited: true, waitedMs: number, holder?: LockHolder }>}
182
195
  */
183
196
  export async function waitInLine(opts) {
184
197
  const { lockPath, fsImpl, nowFn } = opts;
185
198
  const clock = waitClock(opts);
186
199
  announceWait(opts);
200
+ reportProgress(opts, clock, 'waiting', null);
187
201
  const ticket = enqueueWaiter({ lockPath, nowFn, fsImpl });
188
202
  try {
189
203
  const outcome = await pollForTurn(opts, ticket, clock);
@@ -205,17 +219,40 @@ function waitClock({ waitMs, reportMs, nowFn }) {
205
219
  };
206
220
  }
207
221
 
222
+ function reportProgress(opts, clock, phase, ticket, knownHolder) {
223
+ try {
224
+ opts.onLockProgress?.({
225
+ phase,
226
+ waitedSeconds: clock.waited(),
227
+ waitBudgetSeconds: Math.round(Math.max(0, opts.waitMs) / 1000),
228
+ ...(phase === 'acquired' ? {} : waitContext(opts, ticket, knownHolder)),
229
+ });
230
+ } catch {}
231
+ }
232
+
233
+ /** Holder and queue position, each only when readable. */
234
+ function waitContext({ lockPath, staleMs, fsImpl, nowFn }, ticket, known) {
235
+ const holder = known ?? readLockHolder(lockPath, { fsImpl, nowFn });
236
+ const queueAhead = countAhead({ lockPath, ticket, staleMs, nowFn, fsImpl });
237
+ return {
238
+ ...(holder.ownerId === null && holder.pid === null ? {} : { holder }),
239
+ ...(queueAhead === null ? {} : { queueAhead }),
240
+ };
241
+ }
242
+
208
243
  function announceWait({ lockPath, waitMs, fsImpl, log }) {
209
244
  log(
210
245
  `${LOCK_TAG} ⏳ another full suite is already running on this host (${holderLabel(lockPath, fsImpl)}) — waiting up to ${Math.round(waitMs / 1000)}s for it to finish before spawning.`,
211
246
  );
212
247
  }
213
248
 
214
- function giveUp({ lockPath, fsImpl, nowFn, log, rerunCommand }, clock) {
249
+ function giveUp(opts, clock) {
250
+ const { lockPath, fsImpl, nowFn, log, rerunCommand } = opts;
215
251
  const holder = readLockHolder(lockPath, { fsImpl, nowFn });
216
252
  log(
217
253
  `${LOCK_TAG} ⌛ gave up waiting for the full-suite lock (waited ${clock.waited()}s, ${describeHolder(holder)}) — not spawning, so two full suites never overlap. Re-run once it finishes: ${rerunCommand}`,
218
254
  );
255
+ reportProgress(opts, clock, 'expired', null, holder);
219
256
  return {
220
257
  held: null,
221
258
  expired: true,
@@ -238,19 +275,22 @@ async function pollForTurn(opts, ticket, clock) {
238
275
  log(
239
276
  `${LOCK_TAG} ✅ acquired the full-suite lock (waited ${clock.waited()}s).`,
240
277
  );
278
+ reportProgress(opts, clock, 'acquired', ticket);
241
279
  return { held: attempt, expired: false };
242
280
  }
243
281
  // A hard I/O error will not resolve by waiting; it is not an expiry.
244
282
  if (attempt.reason === 'error') return { held: null, expired: false };
245
- reportStillWaiting(opts, clock);
283
+ reportStillWaiting(opts, clock, ticket);
246
284
  }
247
285
  return null;
248
286
  }
249
287
 
250
- function reportStillWaiting({ lockPath, fsImpl, nowFn, log, reportMs }, clock) {
288
+ function reportStillWaiting(opts, clock, ticket) {
289
+ const { lockPath, fsImpl, nowFn, log, reportMs } = opts;
251
290
  if (nowFn() < clock.nextReport) return;
252
291
  log(
253
292
  `${LOCK_TAG} ⏳ still waiting for the full-suite lock (${holderLabel(lockPath, fsImpl)}, waited ${clock.waited()}s).`,
254
293
  );
294
+ reportProgress(opts, clock, 'still-waiting', ticket);
255
295
  clock.nextReport += reportMs;
256
296
  }
@@ -81,6 +81,8 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
81
81
  'sync-agentrc.js',
82
82
  'sync-claude-agents.js',
83
83
  'sync-claude-commands.js',
84
+ 'sync-codex-agents.js',
85
+ 'sync-codex-skills.js',
84
86
  'test-wrapper.js',
85
87
  'update-coverage-baseline.js',
86
88
  'update-crap-baseline.js',
@@ -0,0 +1,242 @@
1
+ /**
2
+ * review-providers/claude-verdict.js — reads `code-review`'s claude result
3
+ * envelope and auth-status payload into findings or a no-verdict reason.
4
+ *
5
+ * @typedef {import('./types.js').Finding} Finding
6
+ */
7
+
8
+ import { buildFinding, unwrapEnvelope } from './parse-findings.js';
9
+
10
+ export const FINDINGS_SCHEMA_JSON = JSON.stringify({
11
+ type: 'object',
12
+ properties: {
13
+ findings: {
14
+ type: 'array',
15
+ items: {
16
+ type: 'object',
17
+ properties: {
18
+ title: { type: 'string' },
19
+ body: { type: 'string' },
20
+ file: { type: 'string' },
21
+ line: { type: 'integer' },
22
+ category: { type: 'string' },
23
+ },
24
+ required: ['title', 'body'],
25
+ },
26
+ },
27
+ },
28
+ required: ['findings'],
29
+ });
30
+
31
+ const MAX_DETAIL_CHARS = 300;
32
+ const USAGE_LIMIT_RE = /hit your .*limit|usage limit|rate limit/i;
33
+
34
+ export function clip(text) {
35
+ const flat = String(text ?? '')
36
+ .replace(/\s+/g, ' ')
37
+ .trim();
38
+ return flat.length > MAX_DETAIL_CHARS
39
+ ? `${flat.slice(0, MAX_DETAIL_CHARS)}…`
40
+ : flat;
41
+ }
42
+
43
+ function tryParseJson(text) {
44
+ try {
45
+ return JSON.parse(text);
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * `claude auth status --json`. Only `authMethod` and `subscriptionType`
53
+ * are ever named: the payload also carries the account email, org name
54
+ * and ids, which no reason or log line may repeat.
55
+ *
56
+ * @param {{ status: number, stdout: string }} result
57
+ * @returns {{ ok: true, detail: string } | { ok: false, reason: string }}
58
+ */
59
+ export function readAuthStatus(result) {
60
+ if (result.status !== 0) {
61
+ return {
62
+ ok: false,
63
+ reason: `claude auth status exited ${result.status}: the CLI is not logged in or unusable`,
64
+ };
65
+ }
66
+ const parsed = tryParseJson(result.stdout);
67
+ if (!parsed || typeof parsed !== 'object') {
68
+ return {
69
+ ok: false,
70
+ reason: 'claude auth status returned unparseable output',
71
+ };
72
+ }
73
+ const method =
74
+ typeof parsed.authMethod === 'string' ? parsed.authMethod : null;
75
+ if (parsed.loggedIn !== true) {
76
+ return {
77
+ ok: false,
78
+ reason: `claude CLI is not logged in${method ? ` (authMethod: ${method})` : ''}`,
79
+ };
80
+ }
81
+ const plan =
82
+ typeof parsed.subscriptionType === 'string'
83
+ ? `, subscriptionType: ${parsed.subscriptionType}`
84
+ : '';
85
+ return { ok: true, detail: `authMethod: ${method ?? 'unknown'}${plan}` };
86
+ }
87
+
88
+ /**
89
+ * The end index of the balanced JSON array opening at `start`, string-aware.
90
+ *
91
+ * @param {string} text
92
+ * @param {number} start - index of a `[`.
93
+ * @returns {number} index of the closing `]`, or -1.
94
+ */
95
+ function matchArrayEnd(text, start) {
96
+ let depth = 0;
97
+ let inString = false;
98
+ for (let i = start; i < text.length; i += 1) {
99
+ const ch = text[i];
100
+ if (inString) {
101
+ if (ch === '\\') i += 1;
102
+ else if (ch === '"') inString = false;
103
+ } else if (ch === '"') inString = true;
104
+ else if (ch === '[') depth += 1;
105
+ else if (ch === ']') {
106
+ depth -= 1;
107
+ if (depth === 0) return i;
108
+ }
109
+ }
110
+ return -1;
111
+ }
112
+
113
+ /**
114
+ * The last top-level JSON array in free text.
115
+ *
116
+ * @param {string} text
117
+ * @returns {unknown[] | undefined}
118
+ */
119
+ function lastBareArray(text) {
120
+ let found;
121
+ let i = text.indexOf('[');
122
+ while (i !== -1) {
123
+ const end = matchArrayEnd(text, i);
124
+ const parsed =
125
+ end === -1 ? undefined : tryParseJson(text.slice(i, end + 1));
126
+ if (Array.isArray(parsed)) {
127
+ found = parsed;
128
+ i = text.indexOf('[', end + 1);
129
+ } else {
130
+ i = text.indexOf('[', i + 1);
131
+ }
132
+ }
133
+ return found;
134
+ }
135
+
136
+ /**
137
+ * The findings list from a JSON value: a bare array or `{ findings }`.
138
+ *
139
+ * @param {unknown} value
140
+ * @returns {unknown[] | undefined}
141
+ */
142
+ function asFindingList(value) {
143
+ if (value === undefined) return undefined;
144
+ const unwrapped = unwrapEnvelope(value);
145
+ return Array.isArray(unwrapped) ? unwrapped : undefined;
146
+ }
147
+
148
+ /**
149
+ * Fallback over the envelope's `result` text: the last fenced block, else
150
+ * the last top-level JSON array — so a prose preamble is still a verdict.
151
+ *
152
+ * @param {string} text
153
+ * @returns {unknown[] | undefined}
154
+ */
155
+ function parseVerdictText(text) {
156
+ const fences = [...text.matchAll(/```[a-z]*[^\S\n]*\n([\s\S]*?)```/gi)];
157
+ const lastFence = fences.at(-1);
158
+ const fenced = lastFence
159
+ ? asFindingList(tryParseJson(lastFence[1].trim()))
160
+ : undefined;
161
+ return fenced ?? lastBareArray(text);
162
+ }
163
+
164
+ function toFindings(entries) {
165
+ return entries
166
+ .map((entry) =>
167
+ buildFinding(entry, {
168
+ mapSeverity: () => 'critical',
169
+ defaultCategory: 'bug',
170
+ }),
171
+ )
172
+ .filter(Boolean);
173
+ }
174
+
175
+ function failureReason(result, envelope) {
176
+ const resultText =
177
+ typeof envelope?.result === 'string' ? envelope.result : '';
178
+ const text = [result.stderr, resultText, result.stdout].join('\n');
179
+ if (USAGE_LIMIT_RE.test(text)) {
180
+ return 'the claude CLI account is out of quota (usage limit reached)';
181
+ }
182
+ if (result.status !== 0) {
183
+ return `claude --print exited with status ${result.status}: ${
184
+ clip(result.stderr || resultText || result.stdout) || '<no output>'
185
+ }`;
186
+ }
187
+ if (envelope?.is_error === true) {
188
+ return `the reviewer returned an error result: ${clip(resultText) || '<no output>'}`;
189
+ }
190
+ return `the reviewer run ended with subtype ${clip(envelope?.subtype)}`;
191
+ }
192
+
193
+ function parseEnvelope(stdout) {
194
+ const parsed = tryParseJson(stdout);
195
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
196
+ ? parsed
197
+ : null;
198
+ }
199
+
200
+ function isSuccess(result, envelope) {
201
+ return (
202
+ result.status === 0 &&
203
+ envelope !== null &&
204
+ envelope.is_error !== true &&
205
+ envelope.subtype === 'success'
206
+ );
207
+ }
208
+
209
+ function noVerdictReason(result, envelope) {
210
+ if (result.status === 0 && envelope === null) {
211
+ return 'the reviewer output was not a JSON result envelope';
212
+ }
213
+ return failureReason(result, envelope);
214
+ }
215
+
216
+ function structuredFindings(structured) {
217
+ return Array.isArray(structured?.findings) ? structured.findings : undefined;
218
+ }
219
+
220
+ function resultTextFindings(text) {
221
+ return typeof text === 'string' ? parseVerdictText(text) : undefined;
222
+ }
223
+
224
+ /**
225
+ * Verdict resolution: (a) a successful envelope's `structured_output`,
226
+ * (b) the fallback parser over its `result` text, (c) no verdict.
227
+ *
228
+ * @param {{ status: number, stdout: string, stderr: string }} result
229
+ * @returns {{ findings: Finding[] } | { reason: string }}
230
+ */
231
+ export function resolveVerdict(result) {
232
+ const envelope = parseEnvelope(result.stdout);
233
+ if (!isSuccess(result, envelope)) {
234
+ return { reason: noVerdictReason(result, envelope) };
235
+ }
236
+ const entries =
237
+ structuredFindings(envelope.structured_output) ??
238
+ resultTextFindings(envelope.result);
239
+ return entries
240
+ ? { findings: toFindings(entries) }
241
+ : { reason: 'the reviewer output did not parse as a findings verdict' };
242
+ }