Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/autoplan-guard-runs-on-haiku-5-5.md
Original file line number Diff line number Diff line change
@@ -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 (`<agent-message from=...>`), 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.
64 changes: 64 additions & 0 deletions test/autoplan-guard-pty-fixture.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: `<task-notification>\n<tool-use-id>${id}</tool-use-id>\n<status>completed</status>\n</task-notification>` }] });
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<agent-message from="${agent}">\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<agent-message from="a1">\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: '<task-notification>\n<tool-use-id>toolu_ceo</tool-use-id>\n</task-notification>' }, '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-'));
Expand Down
73 changes: 66 additions & 7 deletions test/helpers/autoplan-guard-pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,63 @@ 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
* `<agent-message from="<agentId>">` (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('<task-notification>') && t.includes(`<tool-use-id>${call.id}</tool-use-id>`)) || (agent !== undefined && t.includes(`<agent-message from="${agent}">`));
});
}

/** 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<string, unknown>) => `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
* never logged; only an Agent tool call carrying a dispatch token, and that call in later requests' history, is rewritten.
*/
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) {
Expand All @@ -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);
Expand All @@ -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 {
Expand Down Expand Up @@ -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: () => {
Expand All @@ -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 (`<agent-message from=...>`, 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' && /<agent-message from="[^"]+">\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 => {
Expand Down
Loading
Loading