mandrel 2.84.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.
- package/.agents/schemas/story-deliver-terminal.schema.json +2 -2
- package/.agents/scripts/coverage-capture.js +1 -0
- package/.agents/scripts/evidence-gate.js +1 -0
- package/.agents/scripts/lib/close-lock-events.js +29 -9
- package/.agents/scripts/lib/full-suite-lock.js +2 -0
- package/.agents/scripts/lib/full-suite-queue.js +66 -26
- package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +242 -0
- package/.agents/scripts/lib/orchestration/review-providers/code-review.js +151 -111
- package/.agents/scripts/lib/orchestration/single-story-close/runner.js +30 -4
- package/.agents/scripts/lib/orchestration/story-handoff.js +84 -10
- package/.agents/workflows/helpers/deliver-story-reference.md +6 -0
- package/docs/CHANGELOG.md +8 -0
- package/package.json +1 -1
|
@@ -77,10 +77,10 @@
|
|
|
77
77
|
},
|
|
78
78
|
"gates": {
|
|
79
79
|
"type": "object",
|
|
80
|
-
"description": "Outcome of each close gate this invocation was responsible for. A gate the run skipped (--skip-validation, or a phase it never reached) reports \"skipped\" rather than being omitted, so a missing gate is never mistaken for a passing one. \"overridden\" is distinct from both: the gate ran, it FAILED, and an operator authorized delivery anyway via --override-review-block with a recorded reason. Reporting that as \"passed\" would erase the one fact a reader of this envelope most needs, and reporting it as \"skipped\" would claim the gate never ran.",
|
|
80
|
+
"description": "Outcome of each close gate this invocation was responsible for. A gate the run skipped (--skip-validation, or a phase it never reached) reports \"skipped\" rather than being omitted, so a missing gate is never mistaken for a passing one. \"overridden\" is distinct from both: the gate ran, it FAILED, and an operator authorized delivery anyway via --override-review-block with a recorded reason. Reporting that as \"passed\" would erase the one fact a reader of this envelope most needs, and reporting it as \"skipped\" would claim the gate never ran. \"degraded\" (codeReview only, Story #5663) means a review surface ran but produced no verdict (CLI not logged in, out of quota, unparseable output); it is reported, not blocking, and ranks below \"overridden\".",
|
|
81
81
|
"additionalProperties": {
|
|
82
82
|
"type": "string",
|
|
83
|
-
"enum": ["passed", "failed", "skipped", "overridden"]
|
|
83
|
+
"enum": ["passed", "failed", "skipped", "overridden", "degraded"]
|
|
84
84
|
}
|
|
85
85
|
},
|
|
86
86
|
"tail": {
|
|
@@ -107,6 +107,7 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
|
|
|
107
107
|
const locked = lockedCapture(runCaptureImpl, config, env, {
|
|
108
108
|
rerunCommand: rerunCommandFor(argv),
|
|
109
109
|
onLockOutcome: lockHooks.onLockOutcome,
|
|
110
|
+
onLockProgress: lockHooks.onLockProgress,
|
|
110
111
|
...lockOptions,
|
|
111
112
|
});
|
|
112
113
|
const credited = creditedCapture(locked, {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* (never gate output, which tests can forge). A child claims
|
|
4
|
-
* before spawning, so no suite process can write to it.
|
|
2
|
+
* Lock-wait, suite-timing and live lock-progress events, as NDJSON in a
|
|
3
|
+
* per-run file (never gate output, which tests can forge). A child claims
|
|
4
|
+
* the env var before spawning, so no suite process can write to it.
|
|
5
5
|
*/
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import fs from 'node:fs';
|
|
@@ -10,7 +10,7 @@ import path from 'node:path';
|
|
|
10
10
|
|
|
11
11
|
const CLOSE_LOCK_EVENTS_FILE_ENV = 'MANDREL_CLOSE_LOCK_EVENTS_FILE';
|
|
12
12
|
|
|
13
|
-
const EVENT_KINDS = new Set(['lock-wait', 'suite-timings']);
|
|
13
|
+
const EVENT_KINDS = new Set(['lock-wait', 'suite-timings', 'lock-progress']);
|
|
14
14
|
|
|
15
15
|
function appendEvent(file, event, fsImpl) {
|
|
16
16
|
try {
|
|
@@ -39,6 +39,7 @@ export function createLockEventChannel({
|
|
|
39
39
|
env: { [CLOSE_LOCK_EVENTS_FILE_ENV]: file },
|
|
40
40
|
emit: (event) => appendEvent(file, event, fsImpl),
|
|
41
41
|
read: () => readEvents(file, fsImpl),
|
|
42
|
+
drain: createDrain(file, fsImpl),
|
|
42
43
|
dispose() {
|
|
43
44
|
try {
|
|
44
45
|
fsImpl.rmSync(file, { force: true });
|
|
@@ -47,16 +48,34 @@ export function createLockEventChannel({
|
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
50
|
|
|
50
|
-
function
|
|
51
|
-
let text;
|
|
51
|
+
function readText(file, fsImpl) {
|
|
52
52
|
try {
|
|
53
|
-
|
|
53
|
+
return fsImpl.readFileSync(file, 'utf8');
|
|
54
54
|
} catch {
|
|
55
|
-
return
|
|
55
|
+
return '';
|
|
56
56
|
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseEvents(text) {
|
|
57
60
|
return text.split('\n').filter(Boolean).map(parseEventLine).filter(Boolean);
|
|
58
61
|
}
|
|
59
62
|
|
|
63
|
+
function readEvents(file, fsImpl) {
|
|
64
|
+
return parseEvents(readText(file, fsImpl));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Each call returns only complete lines appended since the last one. */
|
|
68
|
+
function createDrain(file, fsImpl) {
|
|
69
|
+
let consumed = 0;
|
|
70
|
+
return () => {
|
|
71
|
+
const text = readText(file, fsImpl);
|
|
72
|
+
const end = Math.max(consumed, text.lastIndexOf('\n') + 1);
|
|
73
|
+
const fresh = text.slice(consumed, end);
|
|
74
|
+
consumed = end;
|
|
75
|
+
return parseEvents(fresh);
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
60
79
|
/**
|
|
61
80
|
* Remove the channel from `env` and return its emitter (a no-op without one).
|
|
62
81
|
*
|
|
@@ -80,7 +99,7 @@ export function claimLockEventSink(env = process.env, { fsImpl = fs } = {}) {
|
|
|
80
99
|
export function summarizeLockEvents(events) {
|
|
81
100
|
let lockWait = null;
|
|
82
101
|
let suiteTimings = null;
|
|
83
|
-
for (const event of events) {
|
|
102
|
+
for (const event of events.filter((e) => e.kind !== 'lock-progress')) {
|
|
84
103
|
if (event.kind === 'lock-wait') lockWait = mergeLockWait(lockWait, event);
|
|
85
104
|
else suiteTimings = timingsOf(event);
|
|
86
105
|
}
|
|
@@ -104,6 +123,7 @@ function timingsOf({ lockWaitMs, hostWaitMs, testRunMs }) {
|
|
|
104
123
|
export function lockEventHooks(emit) {
|
|
105
124
|
return {
|
|
106
125
|
onLockOutcome: (outcome) => emit({ kind: 'lock-wait', ...outcome }),
|
|
126
|
+
onLockProgress: (progress) => emit({ kind: 'lock-progress', ...progress }),
|
|
107
127
|
onTimings: (timings) => emit({ kind: 'suite-timings', ...timings }),
|
|
108
128
|
};
|
|
109
129
|
}
|
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
*
|
|
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(
|
|
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(
|
|
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
|
}
|
|
@@ -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
|
+
}
|
|
@@ -6,26 +6,58 @@
|
|
|
6
6
|
* id and the diff text — never `acceptance[]` or the self-eval verdict: this
|
|
7
7
|
* is a bug review, not a second acceptance scoring.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* Cost is bounded by stripping context, not by pinning a model: an empty
|
|
10
|
+
* OS temp cwd (no CLAUDE.md discovery), user-only settings, no MCP, no tools.
|
|
11
|
+
*
|
|
12
|
+
* A missing CLI throws at construction (the chain entry is optional). A
|
|
13
|
+
* review with no verdict records one degraded gate via `getDegradations()`
|
|
14
|
+
* and returns no findings, so "never ran" cannot read as "found nothing".
|
|
12
15
|
*
|
|
13
16
|
* @typedef {import('./types.js').Finding} Finding
|
|
14
17
|
* @typedef {import('./types.js').ReviewInput} ReviewInput
|
|
15
18
|
* @typedef {import('./types.js').ReviewProvider} ReviewProvider
|
|
19
|
+
* @typedef {import('./degraded-gates.js').GateDegradation} GateDegradation
|
|
16
20
|
*/
|
|
17
21
|
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import os from 'node:os';
|
|
24
|
+
import path from 'node:path';
|
|
18
25
|
import { spawnCaptureAsync } from '../../child-exec.js';
|
|
19
26
|
import { gitSpawn } from '../../git-utils.js';
|
|
20
27
|
import { PROJECT_ROOT } from '../../project-root.js';
|
|
21
|
-
import {
|
|
28
|
+
import {
|
|
29
|
+
clip,
|
|
30
|
+
FINDINGS_SCHEMA_JSON,
|
|
31
|
+
readAuthStatus,
|
|
32
|
+
resolveVerdict,
|
|
33
|
+
} from './claude-verdict.js';
|
|
22
34
|
import { renderDepthDirective } from './review-depth.js';
|
|
23
35
|
import { probeClaudeCli } from './security-review.js';
|
|
24
36
|
|
|
25
|
-
const CLAUDE_ARGS = Object.freeze([
|
|
37
|
+
const CLAUDE_ARGS = Object.freeze([
|
|
38
|
+
'--print',
|
|
39
|
+
'--effort',
|
|
40
|
+
'low',
|
|
41
|
+
'--output-format',
|
|
42
|
+
'json',
|
|
43
|
+
'--json-schema',
|
|
44
|
+
FINDINGS_SCHEMA_JSON,
|
|
45
|
+
'--setting-sources',
|
|
46
|
+
'user',
|
|
47
|
+
'--strict-mcp-config',
|
|
48
|
+
'--tools',
|
|
49
|
+
'',
|
|
50
|
+
]);
|
|
51
|
+
const AUTH_ARGS = Object.freeze(['auth', 'status', '--json']);
|
|
26
52
|
const INVOKE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
53
|
+
const AUTH_TIMEOUT_MS = 15 * 1000;
|
|
27
54
|
/** Larger diffs are truncated; the reviewer is told so. */
|
|
28
55
|
const MAX_DIFF_CHARS = 200_000;
|
|
56
|
+
const DEGRADATION_BASE = Object.freeze({
|
|
57
|
+
tool: 'code-review',
|
|
58
|
+
gate: 'codeReview',
|
|
59
|
+
surface: 'model-bug-review',
|
|
60
|
+
});
|
|
29
61
|
|
|
30
62
|
const PROMPT_HEAD =
|
|
31
63
|
'You are reviewing the diff `{baseRef}...{headRef}` for Story #{ticketId} ' +
|
|
@@ -37,11 +69,10 @@ const PROMPT_HEAD =
|
|
|
37
69
|
'line in the new version, why it is wrong, and how to show it fails (an ' +
|
|
38
70
|
'input, command or test that exposes it).\n\n' +
|
|
39
71
|
'The diff below is authoritative — files on disk may not reflect it. ' +
|
|
40
|
-
'
|
|
41
|
-
'it
|
|
42
|
-
'
|
|
43
|
-
'"
|
|
44
|
-
'Emit [] if there is nothing you would block the merge for.\n\n';
|
|
72
|
+
'Answer with a JSON object of this exact shape, no prose around it:\n\n' +
|
|
73
|
+
'{"findings":[{"title":"...","body":"Why it is wrong: ... How to show it ' +
|
|
74
|
+
'fails: ...","file":"...","line":1,"category":"bug"}]}\n\n' +
|
|
75
|
+
'Emit {"findings":[]} if there is nothing you would block the merge for.\n\n';
|
|
45
76
|
|
|
46
77
|
/**
|
|
47
78
|
* @param {ReviewInput} input
|
|
@@ -62,64 +93,37 @@ function buildPrompt(input, diff) {
|
|
|
62
93
|
}
|
|
63
94
|
|
|
64
95
|
/**
|
|
65
|
-
*
|
|
66
|
-
*
|
|
96
|
+
* A Windows shell joins argv unquoted, which would drop `--tools ""` and
|
|
97
|
+
* split the schema; quote each arg for the MSVCRT argv parser.
|
|
67
98
|
*
|
|
68
|
-
* @param {string}
|
|
69
|
-
* @
|
|
70
|
-
* @returns {Promise<{ status: number, stdout: string, stderr: string }>}
|
|
71
|
-
*/
|
|
72
|
-
function invokeClaude(prompt, run) {
|
|
73
|
-
return spawnCaptureAsync('claude', [...CLAUDE_ARGS], {
|
|
74
|
-
cwd: PROJECT_ROOT,
|
|
75
|
-
input: prompt,
|
|
76
|
-
shell: process.platform === 'win32',
|
|
77
|
-
timeout: INVOKE_TIMEOUT_MS,
|
|
78
|
-
...(run ? { run } : {}),
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** A model often fences its JSON; strip one surrounding fence. */
|
|
83
|
-
function stripFence(text) {
|
|
84
|
-
const match = /^\s*```[a-z]*\s*\n([\s\S]*?)\n\s*```\s*$/i.exec(text ?? '');
|
|
85
|
-
return match ? match[1] : (text ?? '');
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* @param {string} title
|
|
90
|
-
* @param {string} detail
|
|
91
|
-
* @returns {Finding}
|
|
99
|
+
* @param {string} arg
|
|
100
|
+
* @returns {string}
|
|
92
101
|
*/
|
|
93
|
-
function
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
title,
|
|
97
|
-
body:
|
|
98
|
-
`${detail} The model bug review did not produce a verdict — inspect ` +
|
|
99
|
-
'the diff manually before merging. Advisory only; the chain did not halt.',
|
|
100
|
-
category: 'bug',
|
|
101
|
-
};
|
|
102
|
+
function quoteWindowsArg(arg) {
|
|
103
|
+
const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1');
|
|
104
|
+
return `"${escaped}"`;
|
|
102
105
|
}
|
|
103
106
|
|
|
104
107
|
/**
|
|
105
|
-
*
|
|
106
|
-
*
|
|
108
|
+
* Async, so close's concurrent gate children keep draining.
|
|
109
|
+
*
|
|
110
|
+
* @param {ReadonlyArray<string>} args
|
|
111
|
+
* @param {{ cwd: string, input?: string, timeout: number, run?: Function, platform: string }} opts
|
|
112
|
+
* @returns {Promise<{ status: number, stdout: string, stderr: string }>}
|
|
107
113
|
*/
|
|
108
|
-
function
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
];
|
|
122
|
-
}
|
|
114
|
+
function runClaude(args, { cwd, input, timeout, run, platform }) {
|
|
115
|
+
const shell = platform === 'win32';
|
|
116
|
+
return spawnCaptureAsync(
|
|
117
|
+
'claude',
|
|
118
|
+
shell ? args.map(quoteWindowsArg) : [...args],
|
|
119
|
+
{
|
|
120
|
+
cwd,
|
|
121
|
+
input: input ?? '',
|
|
122
|
+
shell,
|
|
123
|
+
timeout,
|
|
124
|
+
...(run ? { run } : {}),
|
|
125
|
+
},
|
|
126
|
+
);
|
|
123
127
|
}
|
|
124
128
|
|
|
125
129
|
/**
|
|
@@ -139,69 +143,105 @@ function assertInput(input) {
|
|
|
139
143
|
}
|
|
140
144
|
}
|
|
141
145
|
|
|
146
|
+
function runAuthStatus(runDir, deps) {
|
|
147
|
+
return runClaude(AUTH_ARGS, {
|
|
148
|
+
cwd: runDir,
|
|
149
|
+
timeout: AUTH_TIMEOUT_MS,
|
|
150
|
+
run: deps.authSpawnFn,
|
|
151
|
+
platform: deps.platform,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function runReviewer(runDir, prompt, deps) {
|
|
156
|
+
return runClaude(CLAUDE_ARGS, {
|
|
157
|
+
cwd: runDir,
|
|
158
|
+
input: prompt,
|
|
159
|
+
timeout: INVOKE_TIMEOUT_MS,
|
|
160
|
+
run: deps.spawnFn,
|
|
161
|
+
platform: deps.platform,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Preflight, then the review, both from a fresh OS temp dir removed after.
|
|
167
|
+
*
|
|
168
|
+
* @returns {Promise<{ findings: Finding[] } | { reason: string }>}
|
|
169
|
+
*/
|
|
170
|
+
async function reviewInTempDir(prompt, deps) {
|
|
171
|
+
const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mandrel-code-review-'));
|
|
172
|
+
try {
|
|
173
|
+
const auth = readAuthStatus(await runAuthStatus(runDir, deps));
|
|
174
|
+
if (!auth.ok) return auth;
|
|
175
|
+
deps.logger?.info?.(
|
|
176
|
+
`[code-review] Invoking claude --print --effort low (${auth.detail})...`,
|
|
177
|
+
);
|
|
178
|
+
return resolveVerdict(await runReviewer(runDir, prompt, deps));
|
|
179
|
+
} finally {
|
|
180
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* @returns {{ reason: string } | { text: string }}
|
|
186
|
+
*/
|
|
187
|
+
function readDiff(gitSpawnFn, { baseRef, headRef }) {
|
|
188
|
+
const range = `${baseRef}...${headRef}`;
|
|
189
|
+
const diff = gitSpawnFn(PROJECT_ROOT, 'diff', '--no-color', range);
|
|
190
|
+
if (diff.status === 0) return { text: diff.stdout };
|
|
191
|
+
return {
|
|
192
|
+
reason: `git diff ${range} failed: ${clip(diff.stderr) || '<no output>'}`,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function assertCliPresent(probeFn) {
|
|
197
|
+
if (probeFn()) return;
|
|
198
|
+
throw new Error(
|
|
199
|
+
'[ReviewProviderFactory] codeReview provider "code-review" requires ' +
|
|
200
|
+
'the `claude` CLI on PATH but it was not detected. Install the ' +
|
|
201
|
+
'Claude Code CLI, or keep the entry `optional: true` so hosts ' +
|
|
202
|
+
'without it skip the model bug review.',
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
142
206
|
/**
|
|
143
207
|
* @param {{
|
|
144
208
|
* probeFn?: () => boolean,
|
|
145
209
|
* gitSpawnFn?: typeof gitSpawn,
|
|
146
210
|
* spawnFn?: Function,
|
|
211
|
+
* authSpawnFn?: Function,
|
|
212
|
+
* platform?: string,
|
|
147
213
|
* logger?: { info?: Function, warn?: Function },
|
|
148
|
-
* }} [deps] - `spawnFn`
|
|
149
|
-
*
|
|
214
|
+
* }} [deps] - `spawnFn` / `authSpawnFn` replace the async runner for the
|
|
215
|
+
* review and the `claude auth status` preflight.
|
|
216
|
+
* @returns {ReviewProvider & { getDegradations: () => GateDegradation[] }}
|
|
150
217
|
*/
|
|
151
218
|
export function createCodeReviewProviderForRegistry(deps = {}) {
|
|
152
|
-
|
|
153
|
-
if (!probeFn()) {
|
|
154
|
-
throw new Error(
|
|
155
|
-
'[ReviewProviderFactory] codeReview provider "code-review" requires ' +
|
|
156
|
-
'the `claude` CLI on PATH but it was not detected. Install the ' +
|
|
157
|
-
'Claude Code CLI, or keep the entry `optional: true` so hosts ' +
|
|
158
|
-
'without it skip the model bug review.',
|
|
159
|
-
);
|
|
160
|
-
}
|
|
219
|
+
assertCliPresent(deps.probeFn ?? probeClaudeCli);
|
|
161
220
|
const gitSpawnFn = deps.gitSpawnFn ?? gitSpawn;
|
|
162
|
-
const {
|
|
221
|
+
const runDeps = { ...deps, platform: deps.platform ?? process.platform };
|
|
222
|
+
/** @type {GateDegradation[]} */
|
|
223
|
+
let degradations = [];
|
|
224
|
+
|
|
225
|
+
function settle(verdict) {
|
|
226
|
+
if (!('reason' in verdict)) return verdict.findings;
|
|
227
|
+
degradations.push({ ...DEGRADATION_BASE, reason: verdict.reason });
|
|
228
|
+
deps.logger?.warn?.(`[code-review] No verdict: ${verdict.reason}.`);
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
163
231
|
|
|
164
232
|
return {
|
|
165
233
|
async runReview(input) {
|
|
234
|
+
degradations = [];
|
|
166
235
|
assertInput(input);
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`${baseRef}...${headRef}`,
|
|
173
|
-
);
|
|
174
|
-
if (diff.status !== 0) {
|
|
175
|
-
return [
|
|
176
|
-
advisory(
|
|
177
|
-
'Code review could not read the diff',
|
|
178
|
-
`\`git diff ${baseRef}...${headRef}\` failed: ${diff.stderr || '<no output>'}.`,
|
|
179
|
-
),
|
|
180
|
-
];
|
|
181
|
-
}
|
|
182
|
-
if (diff.stdout.trim().length === 0) return [];
|
|
183
|
-
|
|
184
|
-
logger?.info?.(
|
|
185
|
-
`[code-review] Invoking claude --print --effort low for Story #${ticketId} (${baseRef}...${headRef})...`,
|
|
186
|
-
);
|
|
187
|
-
const result = await invokeClaude(
|
|
188
|
-
buildPrompt(input, diff.stdout),
|
|
189
|
-
spawnFn,
|
|
236
|
+
const diff = readDiff(gitSpawnFn, input);
|
|
237
|
+
if ('reason' in diff) return settle(diff);
|
|
238
|
+
if (diff.text.trim().length === 0) return [];
|
|
239
|
+
return settle(
|
|
240
|
+
await reviewInTempDir(buildPrompt(input, diff.text), runDeps),
|
|
190
241
|
);
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
);
|
|
195
|
-
return [
|
|
196
|
-
advisory(
|
|
197
|
-
'Code review did not complete',
|
|
198
|
-
`\`claude --print\` exited with status ${result.status}: ${
|
|
199
|
-
result.stderr || result.stdout || '<no output>'
|
|
200
|
-
}.`,
|
|
201
|
-
),
|
|
202
|
-
];
|
|
203
|
-
}
|
|
204
|
-
return parseFindings(result.stdout);
|
|
242
|
+
},
|
|
243
|
+
getDegradations() {
|
|
244
|
+
return degradations.map((d) => ({ ...d }));
|
|
205
245
|
},
|
|
206
246
|
};
|
|
207
247
|
}
|
|
@@ -257,19 +257,38 @@ function baselinesEnvelopeGates(validationGates) {
|
|
|
257
257
|
return out;
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
+
/**
|
|
261
|
+
* `overridden` > `degraded` > `passed`: an override records the human
|
|
262
|
+
* decision on a failed review; `degraded` says a review surface produced no
|
|
263
|
+
* verdict (reported, not blocking — a secondary review does not gate merge).
|
|
264
|
+
*
|
|
265
|
+
* @param {object|null} reviewOverride
|
|
266
|
+
* @param {boolean} [reviewDegraded]
|
|
267
|
+
* @returns {'overridden'|'degraded'|'passed'}
|
|
268
|
+
*/
|
|
269
|
+
function codeReviewGate(reviewOverride, reviewDegraded) {
|
|
270
|
+
if (reviewOverride) return 'overridden';
|
|
271
|
+
return reviewDegraded ? 'degraded' : 'passed';
|
|
272
|
+
}
|
|
273
|
+
|
|
260
274
|
/**
|
|
261
275
|
* @param {{ skipValidation?: boolean, skipSync?: boolean }} options
|
|
262
276
|
* @param {Record<string, string>|null} validationGates
|
|
263
277
|
* @param {object|null} reviewOverride
|
|
278
|
+
* @param {boolean} [reviewDegraded]
|
|
264
279
|
* @returns {Record<string, string>}
|
|
265
280
|
*/
|
|
266
|
-
function closeEnvelopeGates(
|
|
281
|
+
function closeEnvelopeGates(
|
|
282
|
+
options,
|
|
283
|
+
validationGates,
|
|
284
|
+
reviewOverride,
|
|
285
|
+
reviewDegraded,
|
|
286
|
+
) {
|
|
267
287
|
return {
|
|
268
288
|
validation: options.skipValidation ? 'skipped' : 'passed',
|
|
269
289
|
...baselinesEnvelopeGates(validationGates),
|
|
270
290
|
baseSync: options.skipSync ? 'skipped' : 'passed',
|
|
271
|
-
|
|
272
|
-
codeReview: reviewOverride ? 'overridden' : 'passed',
|
|
291
|
+
codeReview: codeReviewGate(reviewOverride, reviewDegraded),
|
|
273
292
|
};
|
|
274
293
|
}
|
|
275
294
|
|
|
@@ -466,7 +485,13 @@ async function openAndReviewPr(ctx, deps) {
|
|
|
466
485
|
const reviewOverride = reviewOutcome.halted
|
|
467
486
|
? await resolveReviewHalt(ctx, deps, { prUrl, prNumber, reviewOutcome })
|
|
468
487
|
: null;
|
|
469
|
-
return {
|
|
488
|
+
return {
|
|
489
|
+
prUrl,
|
|
490
|
+
prNumber,
|
|
491
|
+
alreadyMerged: false,
|
|
492
|
+
reviewOverride,
|
|
493
|
+
reviewDegraded: reviewOutcome.degraded === true,
|
|
494
|
+
};
|
|
470
495
|
}
|
|
471
496
|
|
|
472
497
|
async function releaseLease({ storyId }, deps) {
|
|
@@ -1181,6 +1206,7 @@ async function finishPhase(ctx, deps) {
|
|
|
1181
1206
|
options,
|
|
1182
1207
|
ctx.prePush.validationGates,
|
|
1183
1208
|
ctx.pr.reviewOverride,
|
|
1209
|
+
ctx.pr.reviewDegraded,
|
|
1184
1210
|
),
|
|
1185
1211
|
};
|
|
1186
1212
|
if (!waitForMerge) {
|
|
@@ -23,6 +23,7 @@ import path from 'node:path';
|
|
|
23
23
|
import { fileURLToPath } from 'node:url';
|
|
24
24
|
|
|
25
25
|
import { spawnCaptureAsync } from '../child-exec.js';
|
|
26
|
+
import { createLockEventChannel } from '../close-lock-events.js';
|
|
26
27
|
import {
|
|
27
28
|
resolveLintCommand,
|
|
28
29
|
resolveTestGateArgv,
|
|
@@ -109,6 +110,14 @@ const RATCHETS = Object.freeze([
|
|
|
109
110
|
|
|
110
111
|
const MAX_OFFENDING_LINES = 10;
|
|
111
112
|
|
|
113
|
+
const LOCK_POLL_MS = 1_000;
|
|
114
|
+
|
|
115
|
+
function defaultSleep(ms) {
|
|
116
|
+
return new Promise((resolve) => {
|
|
117
|
+
setTimeout(resolve, ms).unref?.();
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
112
121
|
const SEAT_SCRIPTS = Object.freeze({
|
|
113
122
|
crap: 'update-crap-baseline.js',
|
|
114
123
|
maintainability: 'update-maintainability-baseline.js',
|
|
@@ -174,16 +183,70 @@ function headSha(ctx) {
|
|
|
174
183
|
* @param {string} logName
|
|
175
184
|
* @param {string} cmd
|
|
176
185
|
* @param {string[]} args
|
|
186
|
+
* @param {Record<string, string|undefined>} [env] the child's whole env.
|
|
177
187
|
* @returns {Promise<{ status: number, output: string, evidencePath: string }>}
|
|
178
188
|
*/
|
|
179
|
-
async function runLogged(ctx, logName, cmd, args) {
|
|
189
|
+
async function runLogged(ctx, logName, cmd, args, env) {
|
|
180
190
|
ctx.progress(logName, `${cmd} ${args.join(' ')}`);
|
|
181
|
-
const res = await ctx.runCommand(cmd, args, { cwd: ctx.cwd });
|
|
191
|
+
const res = await ctx.runCommand(cmd, args, { cwd: ctx.cwd, env });
|
|
182
192
|
const output = [res.stdout, res.stderr].filter(Boolean).join('\n');
|
|
183
193
|
const evidencePath = ctx.writeEvidence(logName, output);
|
|
184
194
|
return { status: res.status, output, evidencePath };
|
|
185
195
|
}
|
|
186
196
|
|
|
197
|
+
const LOCK_PHASE_TEXT = Object.freeze({
|
|
198
|
+
waiting: 'waiting for the full-suite lock',
|
|
199
|
+
'still-waiting': 'still waiting for the full-suite lock',
|
|
200
|
+
acquired: 'acquired the full-suite lock',
|
|
201
|
+
expired: 'gave up waiting for the full-suite lock',
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
/** @param {import('../full-suite-queue.js').LockProgress} event */
|
|
205
|
+
function describeLockProgress(event) {
|
|
206
|
+
const head = LOCK_PHASE_TEXT[event.phase] ?? `lock ${event.phase}`;
|
|
207
|
+
const parts = [
|
|
208
|
+
`waited ${event.waitedSeconds}s of a ${event.waitBudgetSeconds}s budget`,
|
|
209
|
+
];
|
|
210
|
+
const { holder, queueAhead } = event;
|
|
211
|
+
if (holder) {
|
|
212
|
+
parts.push(
|
|
213
|
+
`holder ${holder.ownerId ?? 'unknown'}, pid ${holder.pid ?? 'unknown'}, lock age ${holder.ageSeconds ?? 'unknown'}s`,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
if (Number.isInteger(queueAhead)) parts.push(`${queueAhead} ahead in queue`);
|
|
217
|
+
return `${head} (${parts.join('; ')})`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Tail a fresh lock-event channel while `run(env)` runs, forwarding each
|
|
222
|
+
* `lock-progress` event once; never the child's output, which can be forged.
|
|
223
|
+
*/
|
|
224
|
+
async function withLockProgress(ctx, run) {
|
|
225
|
+
const channel = ctx.createLockChannel();
|
|
226
|
+
const forward = () => {
|
|
227
|
+
for (const event of channel.drain()) {
|
|
228
|
+
if (event.kind === 'lock-progress') {
|
|
229
|
+
ctx.progress('LOCK', describeLockProgress(event));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
let running = true;
|
|
234
|
+
// Not awaited: the final drain below forwards anything it would have.
|
|
235
|
+
(async () => {
|
|
236
|
+
while (running) {
|
|
237
|
+
await ctx.sleep(ctx.lockPollMs);
|
|
238
|
+
if (running) forward();
|
|
239
|
+
}
|
|
240
|
+
})().catch(() => {});
|
|
241
|
+
try {
|
|
242
|
+
return await run({ ...ctx.env, ...channel.env });
|
|
243
|
+
} finally {
|
|
244
|
+
running = false;
|
|
245
|
+
forward();
|
|
246
|
+
channel.dispose();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
187
250
|
/**
|
|
188
251
|
* The suite exit codes § 5 distinguishes from a red run.
|
|
189
252
|
*
|
|
@@ -354,13 +417,9 @@ async function stepCreditedRun(ctx) {
|
|
|
354
417
|
);
|
|
355
418
|
}
|
|
356
419
|
const capture = ctx.depositor === 'coverage-capture';
|
|
357
|
-
const
|
|
358
|
-
?
|
|
359
|
-
|
|
360
|
-
'--cwd',
|
|
361
|
-
ctx.cwd,
|
|
362
|
-
])
|
|
363
|
-
: await runLogged(ctx, 'credited-run', 'node', [
|
|
420
|
+
const args = capture
|
|
421
|
+
? [path.join(SCRIPTS_DIR, 'coverage-capture.js'), '--cwd', ctx.cwd]
|
|
422
|
+
: [
|
|
364
423
|
path.join(SCRIPTS_DIR, 'evidence-gate.js'),
|
|
365
424
|
'--standalone',
|
|
366
425
|
'--scope-id',
|
|
@@ -372,7 +431,10 @@ async function stepCreditedRun(ctx) {
|
|
|
372
431
|
'--',
|
|
373
432
|
// Close's `test` gate argv, so the deposit keys on its credit identity.
|
|
374
433
|
...testGateArgv(ctx.config),
|
|
375
|
-
]
|
|
434
|
+
];
|
|
435
|
+
const run = await withLockProgress(ctx, (env) =>
|
|
436
|
+
runLogged(ctx, 'credited-run', 'node', args, env),
|
|
437
|
+
);
|
|
376
438
|
const extra = { evidencePath: run.evidencePath, depositor: ctx.depositor };
|
|
377
439
|
if (run.status !== 0) {
|
|
378
440
|
return fixRequired(name, describeSuiteFailure(run.status), extra);
|
|
@@ -769,6 +831,10 @@ async function defaultBlock({
|
|
|
769
831
|
* createProviderFn?: Function,
|
|
770
832
|
* progress?: (tag: string, msg: string) => void,
|
|
771
833
|
* logDir?: string,
|
|
834
|
+
* createLockChannel?: typeof createLockEventChannel,
|
|
835
|
+
* sleep?: (ms: number) => Promise<void>,
|
|
836
|
+
* lockPollMs?: number,
|
|
837
|
+
* env?: Record<string, string|undefined>,
|
|
772
838
|
* }} deps
|
|
773
839
|
* @returns {Promise<{ envelope: object, exitCode: number }>}
|
|
774
840
|
*/
|
|
@@ -784,6 +850,10 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
|
|
|
784
850
|
createProviderFn,
|
|
785
851
|
progress = () => {},
|
|
786
852
|
logDir = orchestrationLogDir(config),
|
|
853
|
+
createLockChannel = createLockEventChannel,
|
|
854
|
+
sleep = defaultSleep,
|
|
855
|
+
lockPollMs = LOCK_POLL_MS,
|
|
856
|
+
env = process.env,
|
|
787
857
|
} = deps;
|
|
788
858
|
const block =
|
|
789
859
|
deps.block ??
|
|
@@ -808,6 +878,10 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
|
|
|
808
878
|
probeReview,
|
|
809
879
|
computeReview,
|
|
810
880
|
progress,
|
|
881
|
+
createLockChannel,
|
|
882
|
+
sleep,
|
|
883
|
+
lockPollMs,
|
|
884
|
+
env,
|
|
811
885
|
state: readState(statePath),
|
|
812
886
|
review: null,
|
|
813
887
|
reviewPath: storyReviewDepositPath(storyId, config),
|
|
@@ -276,6 +276,12 @@ judgment that help text cannot carry.
|
|
|
276
276
|
`gates.codeReview: "overridden"` rather than `"passed"`. If you find yourself
|
|
277
277
|
reaching for it twice for the same shape of finding, the gate is
|
|
278
278
|
miscalibrated — fix the gate, not the run.
|
|
279
|
+
- `gates.codeReview: "degraded"` — not a flag but an envelope value: a
|
|
280
|
+
review surface ran yet produced no verdict (the `claude` CLI is not logged
|
|
281
|
+
in or out of quota, or its output did not parse). The PR comment lists it
|
|
282
|
+
under Degraded Gates. It is reported, not blocking — close still lands —
|
|
283
|
+
so read the diff yourself before trusting the merge. Precedence:
|
|
284
|
+
`overridden` > `degraded` > `passed`.
|
|
279
285
|
- `--max-wait-seconds <n>` — from a headless caller with no host
|
|
280
286
|
tool-invocation ceiling, to keep single-block semantics
|
|
281
287
|
without editing the consumer's config.
|
package/docs/CHANGELOG.md
CHANGED
|
@@ -15,6 +15,14 @@ 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.85.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.84.0...mandrel-v2.85.0) (2026-10-13)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
* code-review held review: structured output, bounded context, and a degraded gate when no verdict is produced ([#5663](https://github.com/dsj1984/mandrel/issues/5663)) ([#5665](https://github.com/dsj1984/mandrel/issues/5665)) ([0927d4d](https://github.com/dsj1984/mandrel/commit/0927d4d3099e9cdb7e8f8491663f72f10f2042ac))
|
|
24
|
+
* stream full-suite lock wait progress live during story handoffs ([#5662](https://github.com/dsj1984/mandrel/issues/5662)) ([#5664](https://github.com/dsj1984/mandrel/issues/5664)) ([8a679cf](https://github.com/dsj1984/mandrel/commit/8a679cf248491642aa58990c8ae24532a49f286c))
|
|
25
|
+
|
|
18
26
|
## [2.84.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.83.0...mandrel-v2.84.0) (2026-10-13)
|
|
19
27
|
|
|
20
28
|
|
package/package.json
CHANGED