diff --git a/changelog.d/autoplan-guard-runs-on-haiku-5-5.md b/changelog.d/autoplan-guard-runs-on-haiku-5-5.md new file mode 100644 index 00000000000..6490aa8ca54 --- /dev/null +++ b/changelog.d/autoplan-guard-runs-on-haiku-5-5.md @@ -0,0 +1 @@ +**The release gate's live /autoplan guard test runs its scripted actor on Claude Haiku 5.5.** The test's relay now ends the actor's turn after the background reviewer dispatch until that reviewer hands its report back, so the test reaches the path it checks however fast the model is; on Haiku 5.5 without this the actor ran ahead and the case failed the release gate 8 times out of 8. The relay and the test's evidence both recognise the hand-back form Claude Code 2.1.326 sends (``), and the test sets `CLAUDE_CODE_AUTO_MODE_SERVER=0` so Claude Code's auto-mode billing notice can't hold the reviewer behind the local relay. diff --git a/test/autoplan-guard-pty-fixture.test.ts b/test/autoplan-guard-pty-fixture.test.ts index 69a3cc9a731..879b4fe625f 100644 --- a/test/autoplan-guard-pty-fixture.test.ts +++ b/test/autoplan-guard-pty-fixture.test.ts @@ -171,6 +171,70 @@ test('the dispatch relay hands the guard the exact dispatch for the declared tok } }); +// GST-3441: on Haiku 5.5 the actor read the close packet in its dispatch turn, before the CEO reviewer's notice (8 of 8 release +// gate attempts, GSTA-766). The relay now ends that turn itself, so the notice starts the next one at any model speed. +test('the relay ends the actor\'s turn after the background CEO dispatch until that call\'s notice arrives, at any model speed', async () => { + const artifacts = fs.mkdtempSync(path.join(os.tmpdir(), 'ap-guard-wait-')); + const exact = 'the exact CEO dispatch'; + fs.writeFileSync(path.join(artifacts, 'dispatch-ceo.txt'), exact); + const seen: string[] = []; + const upstream = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(req) { + seen.push(await req.text()); + return Response.json({ id: 'msg_up', type: 'message', role: 'assistant', content: [{ type: 'text', text: 'upstream' }], stop_reason: 'end_turn' }); + } }); + const relay = startDispatchRelay(artifacts, `http://127.0.0.1:${upstream.port}`); + const call = { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_ceo', name: 'Agent', input: { description: 'CEO review', prompt: exact } }] }; + const launched = { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_ceo', content: [{ type: 'text', text: 'Async agent launched successfully.\nagentId: a1 The agent is working in the background.' }] }] }; + const notice = (id: string) => ({ role: 'user', content: [{ type: 'text', text: `\n${id}\ncompleted\n` }] }); + const send = (messages: unknown[], stream = false) => fetch(`${relay.url}/v1/messages`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model: 'claude-haiku-5-5', stream, messages }) }); + try { + const held = await (await send([{ role: 'user', content: '/autoplan-guard-transition' }, call, launched])).json() as any; + expect(held).toMatchObject({ role: 'assistant', stop_reason: 'end_turn', content: [{ type: 'text' }] }); + const events = (await (await send([call, launched], true)).text()).split('\n\n').filter(Boolean).map(e => JSON.parse(/^data: (.*)$/m.exec(e)![1]!)); + expect(events.map(e => e.type)).toEqual(['message_start', 'content_block_start', 'content_block_delta', 'content_block_stop', 'message_delta', 'message_stop']); + expect(events[4].delta.stop_reason).toBe('end_turn'); + expect(relay.noticeWaits).toBe(2); + expect(seen).toEqual([]); + // Another call's notice does not release it; this call's notice does, and so does a result that finished in the foreground. + expect((await (await send([call, launched, notice('toolu_other')])).json() as any).id).toBe('msg_relay_notice_wait'); + expect((await (await send([call, launched, { role: 'assistant', content: [{ type: 'text', text: 'Waiting.' }] }, notice('toolu_ceo')])).json() as any).content[0].text).toBe('upstream'); + expect((await (await send([call, { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_ceo', content: 'Review done.' }] }])).json() as any).content[0].text).toBe('upstream'); + // The Messages API carries the notice as the reviewer's hand-back (seen on Claude Code 2.1.326, run gsta796-guard-3); + // another agent's hand-back does not release the wait, this agent's does. + const handBack = (agent: string) => ({ role: 'user', content: [{ type: 'text', text: `Another Claude session sent a message:\n\n[Subagent hand-back] The report follows:\n Findings` }] }); + const waiting = { role: 'assistant', content: [{ type: 'text', text: 'Waiting.' }] }; + expect((await (await send([call, launched, waiting, handBack('a2')])).json() as any).id).toBe('msg_relay_notice_wait'); + expect((await (await send([call, launched, waiting, handBack('a1')])).json() as any).content[0].text).toBe('upstream'); + // A hand-back batched into the launch result's own request releases at once and is counted, not held. + expect(relay.noticeWithLaunch).toBe(0); + const batched = { role: 'user', content: [...launched.content, ...handBack('a1').content] }; + expect((await (await send([call, batched])).json() as any).content[0].text).toBe('upstream'); + expect(relay.noticeWithLaunch).toBe(1); + // The reviewer's own requests, whose dispatch is user text, and the Design dispatch's turn always go upstream. + expect((await (await send([{ role: 'user', content: exact }])).json() as any).content[0].text).toBe('upstream'); + const design = { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_design', name: 'Agent', input: { prompt: dispatchToken('design') } }] }; + expect((await (await send([design, { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_design', content: 'Async agent launched successfully.' }] }])).json() as any).content[0].text).toBe('upstream'); + expect(seen).toHaveLength(6); + expect(relay.noticeWaits).toBe(4); + } finally { relay.stop(); upstream.stop(true); fs.rmSync(artifacts, { recursive: true, force: true }); } +}); + +// /ship second-model review on PR #4846: the journal stores the hand-back as text blocks, so the reader must not regex the JSON. +test('the journal reader starts the notice turn at a hand-back stored as text blocks, ahead of a later task-notification record', () => { + const s = prepareGuardSession(undefined); + try { + const dir = path.join(s.home, '.claude', 'projects', 'p'); + fs.mkdirSync(dir, { recursive: true }); + const row = (message: unknown, origin?: string) => JSON.stringify({ message, ...(origin ? { origin: { kind: origin } } : {}) }); + fs.writeFileSync(path.join(dir, 's.jsonl'), [ + row({ role: 'user', content: [{ type: 'text', text: 'Another Claude session sent a message:\n\n[Subagent hand-back] The report follows:' }] }), + row({ role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Read', input: { file_path: '/x/close-packet.md' } }] }), + row({ role: 'user', content: '\ntoolu_ceo\n' }, 'task-notification'), + ].join('\n') + '\n'); + expect(s.noticeEvidence().afterNotice).toEqual(['Read /x/close-packet.md']); + } finally { s.cleanup(); } +}); + // /ship outside voice on PR #3953: a CRLF stream whose \r and \n land in separate chunks kept the token unsubstituted. test('the event rewriter substitutes the token however LF or CRLF delimiters are split across chunks', () => { const artifacts = fs.mkdtempSync(path.join(os.tmpdir(), 'ap-guard-crlf-')); diff --git a/test/helpers/autoplan-guard-pty.ts b/test/helpers/autoplan-guard-pty.ts index 341dfe242a9..99e29acbac4 100644 --- a/test/helpers/autoplan-guard-pty.ts +++ b/test/helpers/autoplan-guard-pty.ts @@ -152,7 +152,55 @@ export function dispatchEventRewriter(artifacts: string, substituted: (phase: Di }; } -export interface DispatchRelay { url: string; substituted: DispatchPhase[]; stop(): void } +/** + * GST-3441: the actor's wait for the CEO reviewer's completion notice is the relay's job, not the model's. A request whose + * history holds the actor's CEO-token Agent call, that call's "Async agent launched" result and no notice for that agent + * is the actor about to act before the event step 5 waits on (Haiku 5.5 read the close packet there, 8 of 8 release + * gate attempts, GSTA-766). The relay answers it with an end_turn message itself, so the notice starts the next turn at any + * model speed. Claude Code journals the notice as a task-notification, but the Messages API request carries it as + * `` (seen on 2.1.326, run gsta796-guard-3); either form releases the wait. Every other + * request, the reviewer's own included, goes upstream. + */ +export function waitingForNotice(request: any): boolean { + const messages: any[] = Array.isArray(request?.messages) ? request.messages : []; + const blocks = (m: any): any[] => (Array.isArray(m?.content) ? m.content : typeof m?.content === 'string' ? [{ type: 'text', text: m.content }] : []); + const text = (b: any): string => (typeof b?.content === 'string' ? b.content : Array.isArray(b?.content) ? b.content.map((c: any) => text(c)).join('') : typeof b?.text === 'string' ? b.text : ''); + const call = messages.filter(m => m?.role === 'assistant').flatMap(blocks).find(b => b?.type === 'tool_use' && b.name === 'Agent' && b.input?.prompt === dispatchToken('ceo')); + if (!call) return false; + const user = messages.filter(m => m?.role === 'user').flatMap(blocks); + const launched = user.find(b => b?.type === 'tool_result' && b.tool_use_id === call.id && /^Async agent launched/.test(text(b).trimStart())); + if (!launched) return false; + const agent = /agentId: ([A-Za-z0-9_-]+)/.exec(text(launched))?.[1]; + return !user.some(b => { + const t = text(b); + return (t.includes('') && t.includes(`${call.id}`)) || (agent !== undefined && t.includes(``)); + }); +} + +/** The relay's own end_turn reply to a waitingForNotice request, as a Messages API stream or JSON body. */ +export function noticeWaitResponse(request: any): Response { + const text = 'Waiting for the CEO review agent\'s completion notification.'; + const message = { id: 'msg_relay_notice_wait', type: 'message', role: 'assistant', model: request?.model ?? 'relay', content: [{ type: 'text', text }], stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } }; + if (!request?.stream) return Response.json(message); + const frame = (data: Record) => `event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`; + return new Response([ + frame({ type: 'message_start', message: { ...message, content: [], stop_reason: null } }), + frame({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }), + frame({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }), + frame({ type: 'content_block_stop', index: 0 }), + frame({ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 0 } }), + frame({ type: 'message_stop' }), + ].join(''), { headers: { 'content-type': 'text/event-stream' } }); +} + +/** The CEO reviewer's hand-back reached the actor in the same request as its launch result, so there was nothing to hold. */ +export function noticeWithLaunch(request: any): boolean { + const last = Array.isArray(request?.messages) ? request.messages.at(-1) : undefined; + return last?.role === 'user' && !waitingForNotice(request) && !waitingForNotice({ ...request, messages: request.messages.slice(0, -1) }) && waitingForNotice({ ...request, messages: [...request.messages.slice(0, -1), + { ...last, content: (Array.isArray(last.content) ? last.content : []).filter((b: any) => b?.type === 'tool_result') }] }); +} + +export interface DispatchRelay { url: string; substituted: DispatchPhase[]; noticeWaits: number; noticeWithLaunch: number; stop(): void } /** * A loopback relay to the Messages API for the live case (point ANTHROPIC_BASE_URL at url). Headers pass through and are @@ -160,6 +208,7 @@ export interface DispatchRelay { url: string; substituted: DispatchPhase[]; stop */ export function startDispatchRelay(artifacts: string, upstream = process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com'): DispatchRelay { const substituted: DispatchPhase[] = []; + const relay: DispatchRelay = { url: '', substituted, noticeWaits: 0, noticeWithLaunch: 0, stop: () => {} }; const server = Bun.serve({ hostname: '127.0.0.1', port: 0, idleTimeout: 0, async fetch(req) { @@ -168,7 +217,10 @@ export function startDispatchRelay(artifacts: string, upstream = process.env.ANT headers.set('accept-encoding', 'identity'); let body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await req.text(); if (body && url.pathname.endsWith('/messages')) { - try { const request = JSON.parse(body); restoreDispatchTokens(request, artifacts); body = JSON.stringify(request); } catch { /* not JSON: forward as sent */ } + let request: any; + try { request = JSON.parse(body); restoreDispatchTokens(request, artifacts); body = JSON.stringify(request); } catch { /* not JSON: forward as sent */ } + if (waitingForNotice(request)) { relay.noticeWaits++; return noticeWaitResponse(request); } + if (noticeWithLaunch(request)) relay.noticeWithLaunch++; } const res = await fetch(upstream.replace(/\/+$/, '') + url.pathname + url.search, { method: req.method, headers, body }); const out = new Headers(res.headers); @@ -190,7 +242,9 @@ export function startDispatchRelay(artifacts: string, upstream = process.env.ANT })), { status: res.status, headers: out }); }, }); - return { url: `http://127.0.0.1:${server.port}`, substituted, stop: () => { server.stop(true); } }; + relay.url = `http://127.0.0.1:${server.port}`; + relay.stop = () => { server.stop(true); }; + return relay; } export function prepareGuardSession(apiKey: string | undefined): GuardSession { @@ -262,11 +316,12 @@ console.log(close); if (!fs.existsSync(projects)) return ['(no journal)']; return fs.readdirSync(projects).flatMap(dir => fs.readdirSync(path.join(projects, dir)).filter(f => f.endsWith('.jsonl')) .flatMap(f => fs.readFileSync(path.join(projects, dir, f), 'utf8').split('\n').filter(Boolean).flatMap(line => { - const r = JSON.parse(line); - return (Array.isArray(r.message?.content) ? r.message.content : []).map((b: any) => b.type === 'tool_use' + const r = JSON.parse(line), origin = r.origin?.kind ? `[${r.origin.kind}] ` : ''; + if (typeof r.message?.content === 'string') return [`${origin}${r.message.role} ${r.message.content.slice(0, 80)}`]; + return (Array.isArray(r.message?.content) ? r.message.content : []).map((b: any) => origin + (b.type === 'tool_use' ? `use ${b.name} ${JSON.stringify(b.input).slice(0, 160)}` : b.type === 'tool_result' ? `result${b.is_error ? ' ERROR' : ''} ${JSON.stringify(b.content).slice(0, 240)}` - : b.type === 'text' ? `text ${String(b.text).slice(0, 80)}` : b.type); + : b.type === 'text' ? `text ${String(b.text).slice(0, 80)}` : b.type)); }))); }, dispatchPromptDeltas: () => { @@ -290,7 +345,11 @@ console.log(close); const rows = (file: string): any[] => fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line)); const blocks = (rs: any[], type: string): any[] => rs.flatMap(r => Array.isArray(r.message?.content) ? r.message.content.filter((b: any) => b.type === type) : []); const parent = files.filter(f => !f.includes(sub)).flatMap(rows); - const notice = parent.findIndex(r => r.origin?.kind === 'task-notification'); + // Claude Code 2.1.326 starts the actor's next turn on the reviewer's hand-back (``, run + // gsta796-guard-3); its task-notification record may come later, so the earlier of the two marks the notice. + const text = (c: any): string => typeof c === 'string' ? c : Array.isArray(c) ? c.map(b => text(b?.text ?? b?.content ?? '')).join('\n') : ''; + const handBack = (r: any): boolean => r.message?.role === 'user' && /\s*\[Subagent hand-back\]/.test(text(r.message.content)); + const notice = parent.findIndex(r => r.origin?.kind === 'task-notification' || handBack(r)); const afterNotice = notice < 0 ? [] : blocks(parent.slice(notice), 'tool_use') .map(b => `${b.name} ${b.input?.file_path ?? b.input?.command ?? b.input?.description ?? ''}`); const reviewerReads = files.filter(f => f.includes(sub)).flatMap(f => { diff --git a/test/skill-e2e-autoplan-guard-pty.test.ts b/test/skill-e2e-autoplan-guard-pty.test.ts index c105dbe50ea..2c1c4d21968 100644 --- a/test/skill-e2e-autoplan-guard-pty.test.ts +++ b/test/skill-e2e-autoplan-guard-pty.test.ts @@ -18,12 +18,19 @@ * input in the project's .gstack/tmp/autoplan/, the installed Phase 2 section) * must still raise no permission card. * - * The actor stays on Claude Haiku 4.5. It acts out a scripted turn shape the - * guard depends on and is not a model under test. On Haiku 5.5 (#4630) the actor - * read the close packet and dispatched Phase 2 before the CEO reviewer's notice - * arrived, so the notice-turn path never ran: 8 of 8 attempts failed in release - * gate runs 44952328945, 44955253712 and 44956497475, against 11 of 11 passes on - * Haiku 4.5 at bisect prefixes up to 79eea6d5 in runs 44954167348 and 44956497475. + * The actor is Claude Haiku 5.5. It acts out a scripted turn shape the guard + * depends on and is not a model under test, so the wait for the CEO reviewer's + * notice is the relay's, not the model's (GST-3441): the relay ends the actor's + * turn after the background dispatch until that notice arrives. Without it, Haiku + * 5.5 read the close packet and dispatched Phase 2 before the notice, so the + * notice-turn path never ran: 8 of 8 attempts failed in release gate runs + * 44952328945, 44955253712 and 44956497475 (#4639 pinned Haiku 4.5 meanwhile). + * + * The relay is a gateway to Claude Code, so auto mode's server-side checks cannot reach the session and the first + * reviewer action the local classifier checks waits on the "auto mode classifier billing" notice for Enter. The + * reviewer then never finishes and its notice never comes (run gsta796-guard-1). CLAUDE_CODE_AUTO_MODE_SERVER=0 is + * the documented setting for a gateway that cannot carry those checks: the same local classifier, with no notice. + * https://code.claude.com/docs/en/auto-mode-classifier-billing */ import { expect } from 'bun:test'; import * as path from 'node:path'; @@ -31,14 +38,14 @@ import { describeIfSelected, testIfSelected } from './helpers/e2e-helpers'; import { launchClaudePty, selectPtyNumberedOption } from './helpers/claude-pty-runner'; import { closePacketReadAfterNotice, guardRunNeedsJournal, prepareGuardSession, startDispatchRelay, stoppedAtPhaseBoundary } from './helpers/autoplan-guard-pty'; -const MODEL = 'claude-haiku-4-5-20251001'; +const MODEL = 'claude-haiku-5-5'; describeIfSelected('autoplan publication guard live PTY', ['autoplan-guard-pty'], () => { testIfSelected('autoplan-guard-pty', async () => { if (!process.env.ANTHROPIC_API_KEY) throw new Error('autoplan-guard-pty requires ANTHROPIC_API_KEY; refusing to skip'); const s = prepareGuardSession(process.env.ANTHROPIC_API_KEY); const relay = startDispatchRelay(path.join(s.project, '.gstack', 'tmp', 'autoplan')); - const session = await launchClaudePty({ permissionMode: null, model: MODEL, cwd: s.project, env: { ...s.env, ANTHROPIC_BASE_URL: relay.url }, + const session = await launchClaudePty({ permissionMode: null, model: MODEL, cwd: s.project, env: { ...s.env, ANTHROPIC_BASE_URL: relay.url, CLAUDE_CODE_AUTO_MODE_SERVER: '0' }, timeoutMs: 540_000, observeScreen: true }).catch(error => { relay.stop(); throw error; }); const started = performance.now(); const prompts: string[] = []; @@ -65,15 +72,19 @@ describeIfSelected('autoplan publication guard live PTY', ['autoplan-guard-pty'] } await Bun.sleep(3_000); const log = s.readLog(), evidence = s.noticeEvidence(); - const summary = { prompts: prompts.length, substituted: relay.substituted, phase1Ms, totalMs: Math.round(performance.now() - started), evidence, + const summary = { prompts: prompts.length, substituted: relay.substituted, noticeWaits: relay.noticeWaits, noticeWithLaunch: relay.noticeWithLaunch, phase1Ms, totalMs: Math.round(performance.now() - started), evidence, decisions: log.map(e => ({ decision: e.decision, code: e.code, path: e.path, version: e.claude_code_version, ts: e.ts })) }; console.log(`[autoplan-guard-pty] ${JSON.stringify(summary)}`); if (log.length < 4 && stoppedAtPhaseBoundary(session.visibleText())) console.log('[autoplan-guard-pty] PHASE_BOUNDARY_STOP: the actor ended its turn after "Phase 1 complete." instead of going on to step 7'); + if (!guardRunNeedsJournal(log, prompts.length) && !closePacketReadAfterNotice(evidence.afterNotice)) + console.log(`[autoplan-guard-pty] journal (no close packet read after the notice):\n${s.journalSummary().join('\n')}`); if (guardRunNeedsJournal(log, prompts.length)) console.log(`[autoplan-guard-pty] journal:\n${s.journalSummary().join('\n')}\n[autoplan-guard-pty] screen:\n${session.visibleText().slice(-2_000)}\n[autoplan-guard-pty] last non-blank screen:\n${session.lastScreen?.() ?? ''}`); if (log.some(e => e.code === 'dispatch_prompt')) console.log(`[autoplan-guard-pty] dispatch prompt deltas:\n${s.dispatchPromptDeltas().join('\n')}`); for (const prompt of prompts) console.log(`[autoplan-guard-pty] permission card approved:\n${prompt}`); expect(log.filter(e => e.decision === 'deny')).toEqual([]); + // The relay held the actor until the hand-back, or the hand-back came with the launch result and there was nothing to hold. + expect(relay.noticeWaits + relay.noticeWithLaunch).toBeGreaterThan(0); // Phase 1 entry, the CEO reviewer dispatch (Cause A: run_in_background sent, stripped from the payload), // the Phase 2 transition and the Phase 2 reviewer dispatch: four guarded allows, each verified. expect(log.map(e => [e.decision, e.disposition])).toEqual(Array(4).fill(['allow', 'allow']));