Second-model review keeps the reviewer's result and reports budget stops (GST-3181) (#4515)

When Codex reviews a change, gstack now keeps the review file the
reviewer wrote instead of replacing it with Codex's one-line closing
message, and a provider that refuses with HTTP 402 is reported as a
used-up budget instead of "exit 1" or a login failure.

Why: gstack-evals lost 22 review attempts to the overwrite and 5 of 45
sessions to a 402 from a metering proxy whose cause gstack threw away.

Nothing to do: a 401 or 403 is still a login problem. Open notes, one of
them a known gap, are listed below.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-19 10:27:37 +00:00
1 parent f13dbb0d4a
commit 957fab79c5
14 files changed
+311 -10

No files matched your search

+25
View File
@@ -82,6 +82,12 @@ if (mode === 'overflow') {
for(let i=0;i<18;i++) { process.stdout.write(block); process.stderr.write(block); }
await new Promise(() => {});
}
if (mode === 'payment' || mode === 'http401' || mode === 'http401-402-fields' || mode === 'usage-limit') {
const reply = mode === 'payment' ? 'API Error: 402 Payment Required {"error":{"message":"API key allowance exhausted"}}' : mode === 'usage-limit' ? 'Claude AI usage limit reached|1763600000' : 'API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}';
const fields = mode === 'http401-402-fields' ? { session_id: '5c1e-402a-9b7f', duration_ms: 402, total_cost_usd: 0.402 } : { session_id: 'session-123' };
process.stdout.write(JSON.stringify({ type: 'result', is_error: true, result: reply, ...fields }));
process.exit(1);
}
if (mode === 'malformed') { process.stdout.write('broken JSON'); process.exit(0); }
if (mode === 'array') { process.stdout.write('[]'); process.exit(0); }
if (mode === 'null') { process.stdout.write('null'); process.exit(0); }
@@ -276,6 +282,25 @@ describe('Claude Code restricted execution', () => {
});
}
test('a 402 from the provider is a budget stop, not a login; a 401 stays an authentication failure', async () => {
const budget = await run('payment');
expect([budget.status, budget.error?.code]).toEqual(['unavailable', 'budget']);
expect(budget.error?.message).toContain('API Error: 402 Payment Required');
expect(budget.error?.message).toContain('allowance');
expect(budget.error?.message).not.toMatch(/log ?in|authenticat/i);
const auth = await run('http401');
expect([auth.status, auth.error?.code]).toEqual(['unavailable', 'authentication']);
});
test('a 401 whose result JSON carries 402 in other fields stays authentication; a usage limit is not called a 402', async () => {
const auth = await run('http401-402-fields');
expect([auth.status, auth.error?.code]).toEqual(['unavailable', 'authentication']);
const quota = await run('usage-limit');
expect([quota.status, quota.error?.code]).toEqual(['unavailable', 'budget']);
expect(quota.error?.message).toContain('Claude AI usage limit reached');
expect(quota.error?.message).not.toMatch(/402|payment required/i);
});
test('the combined stdout/stderr limit terminates a noisy CLI', async () => {
const result = await run('overflow');
expect(result.status).toBe('error');
+1
View File
@@ -11,6 +11,7 @@ test('replacing the shipped catalog changes role choices, not eval rulers, overl
const files = [
'lib/model-catalog.ts', 'lib/model-policy.ts', 'lib/model-policy-notice.ts', 'lib/state-root.ts',
'lib/eval-model.ts', 'lib/claude-code.ts', 'lib/claude-bin.ts', 'lib/claude-code-windows-job.ts',
'lib/outside-review-result.ts', 'lib/autoplan-reconcile.ts', 'lib/gate-outcomes.ts',
'lib/design-catalog.ts', 'scripts/resolve-codex-generation-model.ts', 'scripts/models.ts',
'scripts/resolvers/constants.ts', 'scripts/resolvers/model-overlay.ts',
...fs.readdirSync(path.join(source, 'hosts')).filter(file => file.endsWith('.ts')).map(file => `hosts/${file}`),
+78
View File
@@ -599,3 +599,81 @@ describe('a mid-run Codex usage limit is unavailable (quota_exhausted); a mid-ru
} finally { fs.rmSync(home, { recursive: true, force: true }); }
});
});
describe('an HTTP 402 or payment-required refusal is unavailable (budget_exhausted), never an auth failure', () => {
const PAYMENT_402 = 'ERROR: unexpected status 402 Payment Required: {"error":{"message":"API key allowance exhausted for this billing period","type":"payment_required"}}';
const STREAM_402 = 'stream error: exceeded retry limit, last status: 402 Payment Required';
const BODY_ONLY = 'ERROR: {"type":"error","error":{"type":"payment_required","message":"Proxy allowance used up for this API key"}}';
const AUTH_401 = 'ERROR: unexpected status 401 Unauthorized: {"error":{"message":"Incorrect API key provided","code":"invalid_api_key"}}';
const AUTH_403 = 'ERROR: unexpected status 403 Forbidden: {"error":{"message":"This API key is not allowed to use this project","type":"permission_error"}}';
const ECHOED = 'user\nHandle the 402 Payment Required answer from the billing proxy in this diff\n';
test('a failed call with a 402 line -> unavailable, reason budget_exhausted, detail is the line', () => {
for (const line of [PAYMENT_402, STREAM_402, BODY_ONLY]) {
const result = classifyOutsideReview({ text: '', stderr: `Reading prompt from stdin...\n${line}\n`, exit: 1, gate: 'review' });
expect({ line, verdict: result.verdict, reason: result.reason, detail: result.detail }).toEqual({ line, verdict: 'unavailable', reason: 'budget_exhausted', detail: line });
}
});
test('the printed line names the budget, says what to check and never says to log in', () => {
const line = gateOutcomeLine('Codex outside review', 'budget_exhausted', PAYMENT_402);
expect(line).toContain('HTTP 402');
expect(line).toContain('allowance');
expect(line).toContain('quota');
expect(line).toContain('https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#outside-review-budget-exhausted');
expect(line).not.toMatch(/codex login|claude auth login|authentication failed/i);
});
test('401 and 403 controls are not a budget stop: they stay execution_failed with the status in the detail', () => {
for (const [line, status] of [[AUTH_401, '401'], [AUTH_403, '403']] as const) {
const result = classifyOutsideReview({ text: '', stderr: `${line}\n`, exit: 1, gate: 'review' });
expect({ status, reason: result.reason }).toEqual({ status, reason: 'execution_failed' });
expect(result.detail).toContain(status);
}
});
test('an echoed prompt that names a 402 stays execution_failed, and a timeout keeps its reason', () => {
expect(classifyOutsideReview({ text: '', stderr: `${ECHOED}ERROR: unexpected status 500 Internal Server Error\n`, exit: 1, gate: 'review' }).reason).toBe('execution_failed');
expect(classifyOutsideReview({ text: '', stderr: `${PAYMENT_402}\n`, exit: 124, gate: 'review' }).reason).toBe('timeout');
});
test('a host error for a dispatched reviewer (a Capy subagent) that names a 402 or a quota is the budget or quota stop', () => {
const budget = classifyOutsideReview({ text: '', gate: 'review', exit: 1, providerError: 'OpenAI key declined the request: 402 Payment Required: allowance exhausted' });
expect([budget.verdict, budget.reason]).toEqual(['unavailable', 'budget_exhausted']);
const quota = classifyOutsideReview({ text: '', gate: 'review', exit: 1, providerError: 'OpenAI key declined the request: insufficient_quota: You exceeded your current quota' });
expect(quota.reason).toBe('quota_exhausted');
const auth = classifyOutsideReview({ text: '', gate: 'review', exit: 1, providerError: 'OpenAI key declined the request: 401 Unauthorized: invalid_api_key' });
expect(auth.reason).toBe('execution_failed');
});
test('the readiness probe does not stop on a 402: the review still runs once and its own result names the cause', () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-budget-probe-'));
try {
const stubDir = path.join(home, 'bin');
const codexHome = path.join(home, '.codex');
fs.mkdirSync(stubDir);
fs.mkdirSync(codexHome);
fs.writeFileSync(path.join(codexHome, 'auth.json'), '{}');
fs.writeFileSync(path.join(stubDir, 'codex'), '#!/usr/bin/env bash\nprintf \'%s\\n\' "$STUB_STDERR" >&2\nexit 1\n', { mode: 0o755 });
const probe = spawnSync('bash', ['-c', `source "${path.join(ROOT, 'bin', 'gstack-codex-probe')}" && _gstack_codex_model_probe`], {
encoding: 'utf8', timeout: 20_000,
env: { PATH: `${stubDir}:${process.env.PATH ?? ''}`, HOME: home, CODEX_HOME: codexHome, GSTACK_HOME: path.join(home, '.gstack'), STUB_STDERR: PAYMENT_402, _TEL: 'off' },
});
expect(probe.status).toBe(0);
expect(probe.stdout).toContain('MODEL_PROBE_INCONCLUSIVE');
} finally { fs.rmSync(home, { recursive: true, force: true }); }
});
});
describe('the execution_failed detail names the terminal Codex failure', () => {
test('a transient reconnect error before turn.failed does not become the detail', () => {
const fatal = 'unexpected status 500 Internal Server Error, url: http://127.0.0.1:41000/v1/responses';
const events = [
JSON.stringify({ type: 'error', message: 'Reconnecting... 1/5 (stream disconnected before completion)' }),
JSON.stringify({ type: 'turn.failed', error: { message: fatal } }),
].join('\n');
const result = classifyOutsideReview({ text: '', gate: 'review', exit: 1, stderr: 'Reading additional input from stdin...', events });
expect([result.verdict, result.reason]).toEqual(['unavailable', 'execution_failed']);
expect(result.detail).toBe(`exit 1: ${fatal}`);
});
});
+62 -2
View File
@@ -12,6 +12,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { createRunner, familyConflict, modelFamily, runnerTable, selectRunner, usageFromEvents } from '../lib/outside-voice-runner';
import { RESULT_FORMAT } from '../lib/autoplan-prompts';
const ROOT = path.resolve(import.meta.dir, '..');
const BIN = path.join(ROOT, 'bin', 'gstack-outside-voice');
@@ -19,6 +20,8 @@ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'outside-runner-'));
afterAll(() => fs.rmSync(TMP, { recursive: true, force: true }));
const REVIEW = `INPUT: ceo abc\n\n[P2] The install check lies by omission.\n\nRecommendation: revise because the premise is unmeasured.\nVERDICT: FINDINGS\n`;
const SHA = 'a'.repeat(64);
const AUTOPLAN_REVIEW = `INPUT: ceo ${SHA}\n\nThe premise is unmeasured, so the plan may solve the wrong problem.\n\n\`\`\`gstack-findings\n{"id":"F1","severity":"High","title":"premise unmeasured","fix":"measure the install check first"}\n\`\`\`\n`;
const promptFile = path.join(TMP, 'prompt.md');
fs.writeFileSync(promptFile, 'You are the outside CEO reviewer.\n');
@@ -143,7 +146,12 @@ out=""; while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift;; esac; shift; d
printf '%s\\n' "$FAKE_ARGV_SINK" >/dev/null
cat >"$out.prompt"
if [ -n "\${FAKE_CODEX_SLEEP:-}" ]; then sleep "$FAKE_CODEX_SLEEP"; fi
cat "$FAKE_CODEX_REVIEW" >"$out"
if [ -n "\${FAKE_CODEX_EVENTS:-}" ]; then cat "$FAKE_CODEX_EVENTS"; printf '%s\\n' "\${FAKE_CODEX_STDERR:-}" >&2; : >"$out"; exit 1; fi
if [ -n "\${FAKE_CODEX_OWN:-}" ]; then
own=$(sed -n 's/^3\\. Write the whole result to this file: //p' "$out.prompt")
cat "$FAKE_CODEX_REVIEW" >"$own"
printf '%s\\n' "\${FAKE_CODEX_LAST:-Wrote the review to the result file.}" >"$out"
else cat "$FAKE_CODEX_REVIEW" >"$out"; fi
echo '{"type":"item.completed","item":{"type":"command_execution","status":"completed","exit_code":0}}'
echo '{"type":"turn.completed","usage":{"input_tokens":1200,"output_tokens":340}}'
`, { mode: 0o755 });
@@ -158,11 +166,63 @@ echo '{"type":"turn.completed","usage":{"input_tokens":1200,"output_tokens":340}
const result = await runner.run({ promptFile, outFile: out, model: 'gpt-5.5', timeoutMs: 30_000, cwd: ROOT, gate: 'review', env, binDir: gstackBin });
expect(result).toMatchObject({ runner: 'codex-cli', status: 'completed', model: 'gpt-5.5', family: 'openai', exit: 0, usage: { input_tokens: 1200, output_tokens: 340, usd: 'unknown' } });
expect(result.verdict!.verdict).toBe('clean');
expect(fs.readFileSync(`${out}.prompt`, 'utf8')).toBe(fs.readFileSync(promptFile, 'utf8'));
expect(fs.readFileSync(`${out}.last-message.prompt`, 'utf8')).toBe(fs.readFileSync(promptFile, 'utf8'));
expect(fs.readFileSync(out, 'utf8')).toBe(REVIEW);
expect(usageFromEvents('{"usage":{"input_tokens":5}}\nnot json\n')).toEqual({ input_tokens: 5, usd: 'unknown' });
});
test('the reviewer\'s own result file survives Codex\'s closing message (-o goes to a separate file)', async () => {
const review = path.join(TMP, 'own-review.md');
fs.writeFileSync(review, AUTOPLAN_REVIEW);
const out = path.join(TMP, 'own', 'ceo-outside.md');
const prompt = path.join(TMP, 'own-prompt.md');
fs.writeFileSync(prompt, `You are the outside CEO reviewer.\n${RESULT_FORMAT('ceo', SHA, out)}`);
const result = await createRunner('codex-cli').run({ promptFile: prompt, outFile: out, timeoutMs: 30_000, cwd: ROOT, gate: 'autoplan', env: { ...cleanEnv(fakeBin), FAKE_CODEX_REVIEW: review, FAKE_CODEX_OWN: '1' }, binDir: gstackBin });
expect(fs.readFileSync(out, 'utf8')).toBe(AUTOPLAN_REVIEW);
expect(fs.readFileSync(`${out}.last-message`, 'utf8')).toBe('Wrote the review to the result file.\n');
expect(result.reason).toBeUndefined();
expect(result.status).toBe('completed');
});
test('when the reviewer\'s own file lacks the gate\'s markers and the closing message has them, the closing message is the result', async () => {
const review = path.join(TMP, 'own-junk.md');
fs.writeFileSync(review, 'draft notes, not the result\n');
const out = path.join(TMP, 'own-junk', 'ceo-outside.md');
const prompt = path.join(TMP, 'own-junk-prompt.md');
fs.writeFileSync(prompt, `You are the outside CEO reviewer.\n${RESULT_FORMAT('ceo', SHA, out)}`);
const result = await createRunner('codex-cli').run({ promptFile: prompt, outFile: out, timeoutMs: 30_000, cwd: ROOT, gate: 'autoplan', env: { ...cleanEnv(fakeBin), FAKE_CODEX_REVIEW: review, FAKE_CODEX_OWN: '1', FAKE_CODEX_LAST: AUTOPLAN_REVIEW.trimEnd() }, binDir: gstackBin });
expect(fs.readFileSync(out, 'utf8')).toBe(AUTOPLAN_REVIEW);
expect(result.status).toBe('completed');
});
// Captured from codex-cli 0.170.0 against a local stub answering 402 (application/problem+json, a metering proxy's allowance) and 401.
const REFUSAL_EVENTS = (status: string) => [
'{"type":"thread.started","thread_id":"01a1f2ae-a04c-7583-8012-638cc20a388d"}',
'{"type":"turn.started"}',
JSON.stringify({ type: 'error', message: status }),
JSON.stringify({ type: 'turn.failed', error: { message: status } }),
].join('\n') + '\n';
const STATUS_402 = 'unexpected status 402 Payment Required: {"type":"https://meter.example/problems/allowance","title":"E_ALLOWANCE","status":402,"code":"E_ALLOWANCE","detail":"E_ALLOWANCE: metering proxy: the slot\'s allowance of $15 cannot hold this call\'s worst case"}, url: http://127.0.0.1:33037/v1/responses';
const STATUS_401 = 'unexpected status 401 Unauthorized: Incorrect API key provided, url: http://127.0.0.1:45349/v1/responses';
const STDERR = 'Reading additional input from stdin...';
test('a 402 in Codex\'s JSON failure events is recorded as budget_exhausted with the cause, not "exit 1"', async () => {
const events = path.join(TMP, 'refusal-402.jsonl');
fs.writeFileSync(events, REFUSAL_EVENTS(STATUS_402));
const result = await createRunner('codex-cli').run({ promptFile, outFile: path.join(TMP, 'r402', 'o.md'), timeoutMs: 30_000, cwd: ROOT, gate: 'review', env: { ...cleanEnv(fakeBin), FAKE_CODEX_EVENTS: events, FAKE_CODEX_STDERR: STDERR }, binDir: gstackBin });
expect([result.status, result.exit, result.reason]).toEqual(['unavailable', 1, 'budget_exhausted']);
expect(result.detail).toStartWith('unexpected status 402 Payment Required');
expect(result.detail).toContain('E_ALLOWANCE');
});
test('a 401 in the same events stays execution_failed and keeps the 401 cause in its detail', async () => {
const events = path.join(TMP, 'refusal-401.jsonl');
fs.writeFileSync(events, REFUSAL_EVENTS(STATUS_401));
const result = await createRunner('codex-cli').run({ promptFile, outFile: path.join(TMP, 'r401', 'o.md'), timeoutMs: 30_000, cwd: ROOT, gate: 'review', env: { ...cleanEnv(fakeBin), FAKE_CODEX_EVENTS: events, FAKE_CODEX_STDERR: STDERR }, binDir: gstackBin });
expect([result.status, result.reason]).toEqual(['unavailable', 'execution_failed']);
expect(result.detail).toBe(`exit 1: ${STATUS_401}`);
});
test('cancel() terminates the child and reports cancelled', async () => {
const review = path.join(TMP, 'codex-review-2.md');
fs.writeFileSync(review, REVIEW);
+16
View File
@@ -13,6 +13,7 @@ import * as path from 'node:path';
import { ALL_HOST_CONFIGS } from '../hosts/index';
import { outsideVoiceFailurePolicy, outsideVoiceFor, type OutsideVoiceFailurePolicyOptions } from '../scripts/resolvers/outside-voice';
import { generateAdversarialStep } from '../scripts/resolvers/outside-voice-steps';
import { gateOutcomeLine } from '../lib/gate-outcomes';
import { HOST_PATHS, type TemplateContext } from '../scripts/resolvers/types';
const ROOT = path.resolve(import.meta.dir, '..');
@@ -195,3 +196,18 @@ describe('ratchet (d): outside-voice failure prose has one owner', () => {
expect(problems).toEqual([`${ALLOWLIST} entry for codex/SKILL.md.tmpl has no reason: ${allowlist[0].text}`]);
});
});
describe('a 402 or quota stop is never reported as an auth failure', () => {
test('the validator\'s budget line does not itself trip the auth rule\'s keywords', () => {
const line = gateOutcomeLine('Codex outside review', 'budget_exhausted');
expect(line).not.toMatch(/auth|login|unauthorized|API key/i);
expect(line).toContain('HTTP 402');
});
test('the /codex skill\'s own error handling names the budget stop before its auth error', () => {
const text = fs.readFileSync(path.join(ROOT, 'codex/SKILL.md'), 'utf8');
const budget = text.indexOf('- **Budget or quota stop (HTTP 402, payment required, quota):**');
expect(budget).toBeGreaterThan(0);
expect(budget).toBeLessThan(text.indexOf('- **Auth error:**'));
});
});
+46
View File
@@ -478,3 +478,49 @@ echo 'Recommendation: approve because the late answer arrived.'
}
});
});
describe('a 402 budget stop reads as a budget stop on both outside voices; 401 and 403 do not', () => {
const stderrFile = (name: string, text: string) => { const p = path.join(TMP, name); fs.writeFileSync(p, `${text}\n`); return p; };
const BUDGET = 'outside review unavailable: the provider refused the review with HTTP 402';
test('Codex voice: a metering proxy\'s 402 is unavailable with the budget line and no login advice', () => {
const result = invoke('claude', {}, { FAKE_MODE: 'nonzero', FAKE_STDERR_FILE: stderrFile('codex-402.stderr', 'ERROR: unexpected status 402 Payment Required: {"error":{"message":"API key allowance exhausted"}}') });
expect(result.status).not.toBe(0);
expect(result.stderr).toContain(`Codex ${BUDGET}`);
expect(result.stderr).toContain('#outside-review-budget-exhausted');
expect(result.stderr).not.toContain('codex login');
expect(result.stdout).not.toContain('OUTSIDE_STATUS: completed');
});
test('Codex voice: a 402 that appears only in Codex\'s JSON failure events (its stderr names no cause) is the budget line', () => {
const message = 'unexpected status 402 Payment Required: {"title":"E_ALLOWANCE","status":402,"code":"E_ALLOWANCE","detail":"E_ALLOWANCE: metering proxy: the slot\'s allowance of $15 cannot hold this call\'s worst case"}';
const events = stderrFile('codex-402.events.jsonl', [JSON.stringify({ type: 'turn.started' }), JSON.stringify({ type: 'error', message }), JSON.stringify({ type: 'turn.failed', error: { message } })].join('\n'));
const result = invoke('claude', {}, { FAKE_MODE: 'nonzero', FAKE_EVENTS_FILE: events, FAKE_STDERR_FILE: stderrFile('codex-402-plain.stderr', 'Reading additional input from stdin...') });
expect(result.status).not.toBe(0);
expect(result.stderr).toContain(`Codex ${BUDGET}`);
expect(result.stderr).toContain('E_ALLOWANCE');
});
for (const [status, line] of [
['401', 'ERROR: unexpected status 401 Unauthorized: {"error":{"message":"Incorrect API key provided","code":"invalid_api_key"}}'],
['403', 'ERROR: unexpected status 403 Forbidden: {"error":{"message":"This API key is not allowed to use this project"}}'],
] as const) {
test(`Codex voice: a ${status} is missing coverage with its status shown, never a budget stop`, () => {
const result = invoke('claude', {}, { FAKE_MODE: 'nonzero', FAKE_STDERR_FILE: stderrFile(`codex-${status}.stderr`, line) });
expect(result.status).not.toBe(0);
expect(result.stderr).toContain(`Codex outside review unavailable: the reviewer process failed (exit 4: ${line.slice(0, 60)}`);
expect(result.stderr).not.toContain('HTTP 402');
});
}
test('Claude Code voice: a 402 is unavailable with the budget line; a 401 stays an authentication failure', () => {
const budget = invoke('codex', {}, { FAKE_MODE: 'nonzero', FAKE_RESPONSE: 'API Error: 402 Payment Required {"error":{"message":"API key allowance exhausted"}}' });
expect(budget.status).not.toBe(0);
expect(budget.stderr).toContain(`Claude Code ${BUDGET}`);
expect(budget.stdout).toContain('"code":"budget"');
const auth = invoke('codex', {}, { FAKE_MODE: 'nonzero', FAKE_RESPONSE: 'API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' });
expect(auth.status).not.toBe(0);
expect(auth.stdout).toContain('"code":"authentication"');
expect(auth.stderr).not.toContain('HTTP 402');
});
});