graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Retry mid-stream provider errors, keep ACP at parity with REPL and TUI, and add GPT-5.6 guidance.
justrach68a0f8f09d22
diff --git a/README.md b/README.mdindex 45899090..0e12c8cf 100644--- a/README.md+++ b/README.md@@ -242,6 +242,14 @@ Vercel, OpenRouter, MiniMax, Xiaomi, Groq, Cerebras, Mistral, plus oneworkspace router in `.graff/.config.router`. `graff models refresh` pullscatalogs. Claude-subscription OAuth is deliberately not supported.+OpenAI's GPT-5.6 family is `gpt-5.6` (the API alias for `gpt-5.6-sol`),+`gpt-5.6-terra`, and `gpt-5.6-luna`, on the Responses wire via `openai`,+`codex`, or the Codegraff gateway. `/effort` takes `low|medium|high|xhigh`+plus the family's `max` (shown as Ultra; `medium` is the default). Reasoning+replays from local history, so `reasoning.context` is never sent+([ADR 0145](docs/adr/0145-gpt-5-6-reasoning-replays-from-local-history.md));+`reasoning.mode: "pro"` is not exposed yet.+</details>## Evaluation resultsdiff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsxindex f246dd6d..fc88a87d 100644--- a/apps/native/components/site/ChatBubbles.tsx+++ b/apps/native/components/site/ChatBubbles.tsx@@ -58,12 +58,16 @@ function PastedImage({ name }: { name: string }) {{/* Local staged pixels: no remote image optimizer or expiring object URL. */}{/* eslint-disable-next-line @next/next/no-img-element */}<img src={src} alt="Pasted image" loading="lazy" onError={() => setFailed(true)}- className="block h-32 max-w-full rounded-lg object-contain" />+ className="block h-32 max-w-full rounded-chip object-contain" /></a>);}-export const UserBubble = memo(function UserBubble({ text, onEdit }: { text: string; onEdit?: (next: string) => void }) {+export const UserBubble = memo(function UserBubble({ text, promptIndex, onEdit }: {+ text: string;+ /** 1-based index of this prompt in the chat; handed back to `onEdit` so the handler can stay identical across renders. */+ promptIndex?: number; onEdit?: (promptIndex: number, next: string) => void;+}) {const parts = splitImageMarkers(text);const images = parts.filter((_, index) => index % 2 === 1);const words = parts.filter((_, index) => index % 2 === 0).join("");@@ -87,8 +91,8 @@ export const UserBubble = memo(function UserBubble({ text, onEdit }: { text: strconst save = () => {const next = draft.trim();setEditing(false);- if (!next || next === words.trim() || !onEdit) return;- onEdit(next);+ if (!next || next === words.trim() || !onEdit || promptIndex === undefined) return;+ onEdit(promptIndex, next);};return (<div data-user-bubble className="group flex justify-end pl-10 sm:pl-24" style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>@@ -138,11 +142,18 @@ export const AssistantBody = memo(function AssistantBody({reasoningLabel,snapshot,usage = false,+ onRetry,+ retryDisabled,+ promptIndex,}: {turn: AssistantTurn;onOpenPath?: (path: string) => void;onReview?: () => void;onAnswer?: (text: string, cancelled?: boolean) => void | Promise<void>;+ /** Re-send prompt `promptIndex` (1-based), the one that produced this turn; rendered only when it errored. */+ onRetry?: (promptIndex: number) => void;+ retryDisabled?: boolean;+ promptIndex?: number;scroller?: RefObject<HTMLDivElement | null>;following: boolean;reasoningLabel?: string;@@ -212,10 +223,7 @@ export const AssistantBody = memo(function AssistantBody({/></div>)}- {!snapshot && <TurnActivity turn={turn} />}- {turn.error && (- <p role="alert" className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>- )}+ {!snapshot && <TurnActivity turn={turn} onRetry={turn.status === "error" ? onRetry : undefined} promptIndex={promptIndex} retryDisabled={retryDisabled} />}{turn.recap && turn.status === "done" && (<p className="mt-3 text-[12px] text-ink-3">{turn.recap}</p>)}@@ -226,7 +234,7 @@ export const AssistantBody = memo(function AssistantBody({<buttontype="button"onClick={onReview}- className="mt-4 flex h-9 w-full max-w-[630px] items-center gap-2 rounded-[10px] bg-surface px-3 text-left shadow-btn transition-colors duration-100 hover:bg-hover"+ className="mt-4 flex h-9 w-full max-w-[630px] items-center gap-2 rounded-control bg-surface px-3 text-left shadow-btn transition-colors duration-100 hover:bg-hover"style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-ink-3" aria-hidden>diff --git a/apps/native/components/site/ChatColumn.tsx b/apps/native/components/site/ChatColumn.tsxindex 36ea1feb..dc288e21 100644--- a/apps/native/components/site/ChatColumn.tsx+++ b/apps/native/components/site/ChatColumn.tsx@@ -46,17 +46,17 @@ export default function ChatColumn({ thread, compact, following, register, onOpe</div>;return <div ref={hostRef} className="relative flex min-h-0 flex-1 flex-col"><ChatTranscript messages={thread.messages} register={register} following={following}- onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer} snapshot={thread.snapshot} onEditPrompt={onEditPrompt} />+ onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer} snapshot={thread.snapshot} onEditPrompt={onEditPrompt} busy={prompt.busy} /><div ref={composerRef} data-chat-composer className={`pointer-events-none absolute inset-x-0 bottom-0 z-10 px-4 ${composer.dock} ${compact ? "py-2" : "pt-16 pb-6 sm:px-8"}`}><div className="pointer-events-auto mx-auto max-w-[720px]">{thread.snapshot && thread.session ? <SavedSnapshot name={thread.session} cwd={thread.cwd} model={prompt.modelKey}onRefresh={onRefresh} onContinue={onContinue} /> : <><ComposerAgents root={prompt.root} session={thread.session} />- {pins > 0 && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">+ {pins > 0 && <div className="mb-2 flex items-center gap-2 rounded-chip bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline"><span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span><span className="min-w-0 flex-1 truncate text-ink">{pins} element{pins === 1 ? "" : "s"} in the browser go with your next message</span>- <button type="button" onClick={onShowPins} className="shrink-0 rounded px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink">Show</button>- <button type="button" aria-label="Clear pins" onClick={onClearPins} className="flex size-5 shrink-0 items-center justify-center rounded-[5px] text-ink-3 hover:bg-hover hover:text-ink">+ <button type="button" onClick={onShowPins} className="shrink-0 rounded-full px-1.5 text-[11.5px] font-medium text-ink-2 hover:bg-hover hover:text-ink">Show</button>+ <button type="button" aria-label="Clear pins" onClick={onClearPins} className="flex size-5 shrink-0 items-center justify-center rounded-full text-ink-3 hover:bg-hover hover:text-ink"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" aria-hidden><path d="M18 6L6 18M6 6l12 12" /></svg></button></div>}diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsxindex c8da7ce1..30808628 100644--- a/apps/native/components/site/ChatTranscript.tsx+++ b/apps/native/components/site/ChatTranscript.tsx@@ -1,16 +1,25 @@"use client";-import { memo, useCallback, useLayoutEffect, useRef, useState } from "react";+import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";import { AssistantBody, UserBubble } from "./ChatBubbles";import SessionNotice from "./SessionNotice";import type { Msg } from "./harness-types";import { pinScrollerTail } from "@/lib/follow-scroll";import { transcriptPageStart } from "@/lib/transcript-window";-export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview, onAnswer, snapshot, onEditPrompt }: {+const isPrompt = (message: Msg): message is Extract<Msg, { role: "user" }> => message.role === "user" && message.origin !== "notification";++/** 1-based index of the user prompt each message belongs to: the prompt itself, or the prompt that produced an assistant turn. */+export function promptIndexes(messages: Msg[]): number[] {+ let n = 0;+ return messages.map(message => isPrompt(message) ? ++n : n);+}++export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview, onAnswer, snapshot, onEditPrompt, busy }: {messages: Msg[]; register: (element: HTMLDivElement | null) => void; following: boolean;onOpenPath: (path: string) => void; onReview: () => void;onAnswer?: (text: string, cancelled?: boolean) => void | Promise<void>; snapshot?: boolean;onEditPrompt?: (n: number, text: string) => void; // n is 1-based user prompt index; text is the replacement+ busy?: boolean; // a turn is live in this chat: Retry on an errored turn waits}) {const scroller = useRef<HTMLDivElement>(null);const registerScroller = useCallback((element: HTMLDivElement | null) => {@@ -18,6 +27,16 @@ export default memo(function ChatTranscript({ messages, register, following, onO}, [register]);const followingRef = useRef(following);followingRef.current = following;+ const messagesRef = useRef(messages);+ messagesRef.current = messages;+ const prompts = useMemo(() => promptIndexes(messages), [messages]);+ // Retry is the edit path with the same words: the engine rewinds to that+ // prompt and re-sends it, so the errored turn is replaced in place. Stable+ // across token paints so memoized turns stay memoized (the ref holds the text).+ const retryPrompt = useCallback((n: number) => {+ const last = messagesRef.current.filter(isPrompt)[n - 1];+ if (last) onEditPrompt?.(n, last.text);+ }, [onEditPrompt]);const [shown, setShown] = useState(0);const expanded = useRef(false);const anchor = useRef<{ height: number; top: number } | null>(null);@@ -63,11 +82,9 @@ export default memo(function ChatTranscript({ messages, register, following, onO{messages.slice(start).map((message, index) => message.role === "user"? message.origin === "notification"? <SessionNotice key={message.id} text={message.text} />- : <UserBubble key={message.id} text={message.text} onEdit={snapshot || !onEditPrompt ? undefined : (next) => {- const n = messages.slice(0, start + index + 1).filter(m => m.role === "user" && m.origin !== "notification").length;- onEditPrompt(n, next);- }} />+ : <UserBubble key={message.id} text={message.text} promptIndex={prompts[start + index]} onEdit={snapshot || !onEditPrompt ? undefined : onEditPrompt} />: <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer}+ retryDisabled={busy} promptIndex={prompts[start + index]} onRetry={snapshot || !onEditPrompt || message.turn.status !== "error" ? undefined : retryPrompt}usage={(() => { const previous = messages[start + index - 1]; return previous?.role === "user" && /^\/(usage|cost)$/.test(previous.text.trim()); })()}scroller={scroller} following={following && start + index === messages.length - 1} snapshot={snapshot} />)}</div>diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 57d250ea..28365d0e 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -21,6 +21,7 @@ import { modelDisplayName, paneComposerKey } from "@/lib/composer-model";import { createModelSwitcher } from "./harness-model";import { useBrowserVisibility } from "./useBrowserVisibility";import { useReferenceNavigation } from "./useReferenceNavigation";+import { useThreadCallbacks } from "./useThreadCallbacks";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { type PromptModel } from "@/components/primitives/PromptBar";import SidebarNav from "@/components/primitives/SidebarNav";@@ -187,6 +188,10 @@ export default function GraffHarness() {sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal,pendingPick: () => pendingPickRef.current ?? pendingModel,});+ useOpenWorkspace({+ chats, chatsRef, sessionNamesRef, chatIdRef, msgIdRef, groups, activeId,+ filesOpen, fileRequest, zoomedPane, setChats, setActiveId, setFilesOpen, setFileRequest, setZoomedPane,+ });const { openPath, openReference } = useReferenceNavigation({context: (id = activeIdRef.current) => ({ root: chatsRef.current.find(c => c.id === id)?.cwd ?? activePathRef.current ?? health?.cwd, chat: handleOf(id), focus: () => focusChat(id) }),@@ -386,16 +391,24 @@ export default function GraffHarness() {return session ? cancel(handleOf(chat), session) : Promise.reject(new Error("Session unavailable"));});+ // Stable per-column callbacks: the harness renders on every token, and a+ // fresh closure here would re-render every markdown block in every column.+ const threadCallbacks = useThreadCallbacks({+ onOpenPath: (path, chatId) => openReference(path, chatId),+ onAnswer: (chatId, text, cancelled) => { const live = sessionsRef.current.get(chatId); const ask = chats.find(c => c.id === chatId)?.messages.findLast(m => m.role === "assistant")?.turn.ask; if (live && ask) void answer(handleOf(chatId), live, { callId: ask.callId, text, cancelled }); },+ onEditPrompt: (chatId, n, text) => {+ const live = sessionsRef.current.get(chatId);+ if (live) void cancel(handleOf(chatId), live).catch(() => undefined);+ runningRef.current.delete(chatId);+ void runPrompt(chatId, text, { edit: n });+ },+ }, chats.map(c => c.id));+const columnBody = (thread: Chat) => <ChatColumn key={thread.id} thread={thread}compact={columnIds.length > 1 || navigation.focusedMode || filesOpen || browserOpen || agentsOpen || reviewsOpen || !!(fileRequest?.changes)} following={tailing[thread.id] ?? true} register={paneRef(thread.id)}- onOpenPath={path => openReference(path, thread.id)} onReview={openChanges}- onAnswer={(text, cancelled) => { const live = sessionsRef.current.get(thread.id); const ask = thread.messages.findLast(m => m.role === "assistant")?.turn.ask; if (!live || !ask) return Promise.reject(new Error("This question is no longer waiting")); return answer(handleOf(thread.id), live, { callId: ask.callId, text, cancelled }); }}- onEditPrompt={(n, text) => {- const live = sessionsRef.current.get(thread.id);- if (live) void cancel(handleOf(thread.id), live).catch(() => undefined);- runningRef.current.delete(thread.id);- void runPrompt(thread.id, text, { edit: n });- }}+ onOpenPath={threadCallbacks(thread.id).onOpenPath} onReview={openChanges}+ onAnswer={threadCallbacks(thread.id).onAnswer}+ onEditPrompt={threadCallbacks(thread.id).onEditPrompt}onRefresh={loaded => {const messages: Msg[] = loaded.messages.map(m => ({ id: ++msgIdRef.current, ...m }));setChats(current => current.map(c => c.id === thread.id && c.snapshot ? { ...c, messages } : c));diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxindex 2dbd70a1..22ad1652 100644--- a/apps/native/components/site/HarnessChrome.tsx+++ b/apps/native/components/site/HarnessChrome.tsx@@ -3,6 +3,7 @@ import SessionTabs from "./SessionTabs";import type {SplitTree} from "@/lib/split-tree";import ActionMenu from "@/components/primitives/ActionMenu";import AppSettings from "./AppSettings";+import { IconSidebarLeftOpen } from "@/lib/icons";import type { PointerEvent, MouseEvent, ReactNode } from "react";import type { Chat } from "./harness-types";import reviewStyles from "./ChangesPane.module.css";@@ -39,7 +40,7 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,agentsOpen={agentsOpen} focusChat={focusChat} closeChat={closeChat}onTabPointerDown={onTabPointerDown} onTabClickCapture={onTabClickCapture} /><button type="button" aria-label="New chat" title="New chat (⌘T)" onClick={newChat}- className="ml-0.5 flex size-7 shrink-0 items-center justify-center rounded-[7px] text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink">+ className="ml-0.5 flex size-7 shrink-0 items-center justify-center rounded-full text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden><path d="M12 5v14M5 12h14" /></svg>@@ -65,6 +66,11 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,<button type="button" aria-label="Conversations" aria-pressed={conversationsOpen} onClick={openConversations}>All conversations</button><button type="button" onClick={onFolder}>Open a folder…</button></ActionMenu>+ {!sidebarVisible && <button type="button" aria-label="Expand sidebar" title="Expand sidebar (⌘B)"+ onClick={() => window.dispatchEvent(new CustomEvent("graff-toggle-sidebar"))}+ className="hidden size-7 shrink-0 items-center justify-center rounded-full text-ink-3 hover:bg-hover hover:text-ink lg:flex">+ <IconSidebarLeftOpen size={16} />+ </button>}{!sidebarVisible && <AppSettings />}<div data-desktop-update-slot className="shrink-0" /></div>diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsxindex 3a9d92c2..3dea8dda 100644--- a/apps/native/components/site/TurnActivity.tsx+++ b/apps/native/components/site/TurnActivity.tsx@@ -2,8 +2,12 @@import { useEffect, useState } from "react";import LoadingState from "@/components/primitives/LoadingState";import type { AssistantTurn } from "@/lib/acp";-import { turnActivity } from "@/lib/turn-activity";-export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn; snapshot?: boolean }) {+import { describeTurnError, turnActivity } from "@/lib/turn-activity";+export default function TurnActivity({ turn, snapshot, onRetry, promptIndex = 0, retryDisabled }: {+ turn: AssistantTurn; snapshot?: boolean;+ /** Re-send prompt `promptIndex` (1-based; 0 when unknown); only shown on an errored turn. */+ onRetry?: (promptIndex: number) => void; promptIndex?: number; retryDisabled?: boolean;+}) {const [now, setNow] = useState(Date.now);const active = turn.status === "thinking" || turn.status === "streaming";useEffect(() => {@@ -23,6 +27,28 @@ export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn;<LoadingState label={activity.label} elapsed={activity.detail ?? ""} variant="Drive" /></div>;}+ if (activity.state === "error") {+ // One failure, told once: the human label and timing in red, the+ // provider's own words as a muted single line (hover for the full text).+ const failure = turn.error ? describeTurnError(turn.error, turn.provider) : null;+ return <div data-turn-activity="error" className="mt-4 flex flex-col gap-1.5 text-[12px]">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-red">+ <span aria-hidden="true">!</span>+ <span role="status" aria-live="polite">{activity.label}</span>+ {activity.detail && <><span aria-hidden="true">·</span><span data-activity-detail className="tabular-nums">{activity.detail}</span></>}+ </div>+ {failure && <p role="alert" data-turn-error title={turn.error} className="max-w-[630px] truncate text-ink-3">+ <span className="text-ink-2">{failure.framing}:</span> {failure.message}+ </p>}+ {onRetry && <div>+ <button type="button" data-retry-turn onClick={() => onRetry(promptIndex)} disabled={retryDisabled}+ title={retryDisabled ? "Wait for the current response to finish" : "Send the same prompt again"}+ className="h-7 rounded-full bg-surface px-3 text-[12px] font-medium text-ink shadow-btn transition-[background-color,opacity] duration-150 hover:bg-hover focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-50">+ Retry+ </button>+ </div>}+ </div>;+ }return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : "text-ink-3"}`}><span aria-hidden="true">{activity.state === "snapshot" ? "○" : activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span><span role="status" aria-live="polite">{activity.label}</span>{activity.detail && <><span aria-hidden="true">·</span><span data-activity-detail data-tok-rate={activity.detail.includes("tok/s") ? activity.detail : undefined} className="tabular-nums">{activity.detail}</span></>}diff --git a/apps/native/components/site/useThreadCallbacks.ts b/apps/native/components/site/useThreadCallbacks.tsnew file mode 100644index 00000000..26e55390--- /dev/null+++ b/apps/native/components/site/useThreadCallbacks.ts@@ -0,0 +1,58 @@+import { useEffect, useRef } from "react";++/** The harness-level handlers; each takes the chat id it is acting for. */+export type ThreadHandlers = {+ onOpenPath: (path: string, chatId: number) => void;+ onAnswer: (chatId: number, text: string, cancelled?: boolean) => void;+ onEditPrompt: (chatId: number, n: number, text: string) => void;+};++/** What one chat column receives: the same three functions on every render. */+export type ThreadCallbacks = {+ onOpenPath: (path: string) => void;+ onAnswer: (text: string, cancelled?: boolean) => void;+ onEditPrompt: (n: number, text: string) => void;+};++/** Lazily builds one `ThreadCallbacks` per chat id and keeps handing out the+ * same object. Every function reads the current handlers through `latest`, so+ * identity is fixed while behavior follows the newest render. */+export function createThreadCallbackRegistry(latest: () => ThreadHandlers) {+ const byChat = new Map<number, ThreadCallbacks>();+ return {+ forThread(chatId: number): ThreadCallbacks {+ let callbacks = byChat.get(chatId);+ if (!callbacks) {+ callbacks = {+ onOpenPath: path => latest().onOpenPath(path, chatId),+ onAnswer: (text, cancelled) => latest().onAnswer(chatId, text, cancelled),+ onEditPrompt: (n, text) => latest().onEditPrompt(chatId, n, text),+ };+ byChat.set(chatId, callbacks);+ }+ return callbacks;+ },+ /** Drop entries for chats that no longer exist. */+ prune(liveIds: Iterable<number>) {+ const live = new Set(liveIds);+ for (const id of byChat.keys()) if (!live.has(id)) byChat.delete(id);+ },+ get size() { return byChat.size; },+ };+}++/** Per-thread callbacks whose identity survives every harness render.+ *+ * The harness re-renders on every painted token; fresh `(path) => ...` closures+ * per column would break the memo chain from `ChatTranscript` down to each+ * markdown block. The latest handlers live in a ref; the returned functions+ * are created once per chat id and forgotten when that chat closes. */+export function useThreadCallbacks(handlers: ThreadHandlers, chatIds: number[]): (chatId: number) => ThreadCallbacks {+ const latest = useRef(handlers);+ latest.current = handlers;+ const registry = useRef<ReturnType<typeof createThreadCallbackRegistry> | null>(null);+ registry.current ??= createThreadCallbackRegistry(() => latest.current);+ const key = chatIds.join(",");+ useEffect(() => { registry.current?.prune(key ? key.split(",").map(Number) : []); }, [key]);+ return registry.current.forThread;+}diff --git a/apps/native/lib/acp-prompt-stream.test.ts b/apps/native/lib/acp-prompt-stream.test.tsindex 65930a83..4ec829ba 100644--- a/apps/native/lib/acp-prompt-stream.test.ts+++ b/apps/native/lib/acp-prompt-stream.test.ts@@ -126,6 +126,37 @@ test("the capped timeout reaches the transport", async () => {}});+test("mid-stream retry announcement resets streamed text and records a notice", () => {+ let turn = emptyTurn();+ turn = applyAcpUpdate(turn, { sessionUpdate: "tool_call", toolCallId: "write", title: "Update layout", status: "in_progress" });+ turn = applyAcpUpdate(turn, { sessionUpdate: "tool_call_update", toolCallId: "write", status: "completed" });+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "The plan has three" } });+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "[provider error mid-response — retrying in 1s (1/3)]" } });+ assert.equal(turn.text, "");+ assert.equal(turn.retryNotice, "provider error mid-response — retrying in 1s (1/3)");+ assert.deepEqual(turn.tools.map(tool => tool.status), ["ok"]);+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "recovered after the retry" } });+ assert.equal(turn.text, "recovered after the retry");+ assert.equal(turn.retryNotice, "provider error mid-response — retrying in 1s (1/3)");+ const activity = turnActivity({ ...turn, connected: true, startedAt: 1000, lastUpdateAt: 2000 }, 2000);+ assert.equal(activity.live, true);+ assert.equal(activity.detail, "provider error mid-response — retrying in 1s (1/3)");+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "[server overloaded — retrying in 2s (2/3)]" } });+ assert.equal(turn.text, "");+ assert.equal(turn.retryNotice, "server overloaded — retrying in 2s (2/3)");+ assert.deepEqual(turn.tools.map(tool => tool.status), ["ok"]);+});++test("a non-matching message chunk still appends", () => {+ let turn = applyAcpUpdate(emptyTurn(), { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Hello" } });+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: " [not a retry]" } });+ assert.equal(turn.text, "Hello [not a retry]");+ assert.equal(turn.retryNotice, undefined);+ turn = applyAcpUpdate(turn, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "[gateway flake — retrying in 1s (1/3)]" } });+ assert.equal(turn.text, "Hello [not a retry][gateway flake — retrying in 1s (1/3)]");+ assert.equal(turn.retryNotice, undefined);+});+test("closing a live HTTP reader cancels once, and later failure cannot write into it", async () => {const child = Object.assign(new EventEmitter(), { stdout: new PassThrough(), stdin: new PassThrough() });const transport = new AcpTransport(child as never);diff --git a/apps/native/lib/acp-retry-notice.ts b/apps/native/lib/acp-retry-notice.tsnew file mode 100644index 00000000..68d8d19d--- /dev/null+++ b/apps/native/lib/acp-retry-notice.ts@@ -0,0 +1,10 @@+/** ACP paints `announceTransientRetry` as one `agent_message_chunk`.+ * Match the whole chunk (trimmed), not a substring, so quoted prose still appends. */+const TRANSIENT_RETRY =+ /^\[(?:provider error mid-response|server overloaded) — retrying in \d+s \(\d+\/3\)\]$/;++/** Inner notice for TurnActivity, or null when the chunk is ordinary prose. */+export function transientRetryNotice(text: string): string | null {+ const line = text.trim();+ return TRANSIENT_RETRY.test(line) ? line.slice(1, -1) : null;+}diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.tsindex e5914f69..913adddd 100644--- a/apps/native/lib/acp.ts+++ b/apps/native/lib/acp.ts@@ -2,6 +2,7 @@ import { htmlArtifactId } from "./html-artifacts";import { parseContextMeter } from "./context-meter";import { boundToolDetail } from "./tool-detail";import { stripCiteMarkup } from "./cite-markup";+import { transientRetryNotice } from "./acp-retry-notice";import { mcpAppId, viewSnapshotId } from "./mcp-apps";/** ACP v1 session/update shapes the native harness renders. */@@ -284,6 +285,10 @@ export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): Assistan}case "agent_message_chunk": {const text = stripCiteMarkup((update as { content?: AcpContent }).content?.text ?? "");+ const retry = transientRetryNotice(text);+ if (retry) {+ return { ...turn, text: "", pendingBreak: false, status: "streaming", retryNotice: retry };+ }const needsBreak = turn.pendingBreak && turn.text.length > 0 && !/\s$/.test(turn.text) && !/^\s/.test(text);return {...turn,diff --git a/apps/native/lib/assistant-body.test.tsx b/apps/native/lib/assistant-body.test.tsxindex 1cfb7d57..ad8cde27 100644--- a/apps/native/lib/assistant-body.test.tsx+++ b/apps/native/lib/assistant-body.test.tsx@@ -29,3 +29,28 @@ test("actual reasoning is retained when a turn completes", () => {expect(html).toContain("Inspect the relevant file.");expect(html).toContain("Thought for 8s");});++const count = (html: string, needle: string) => html.split(needle).length - 1;++test("an errored turn tells the failure once, with the provider's words as muted detail", () => {+ const turn = { ...emptyTurn(), status: "error" as const, startedAt: 1000, endedAt: 13000, error: "xai api error: Internal error during token parsing" };+ const html = renderToStaticMarkup(<AssistantBody turn={turn} following={false} onRetry={() => {}} />);+ expect(count(html, "Response interrupted")).toBe(1);+ expect(count(html, "data-turn-error")).toBe(1);+ expect(count(html, "role=\"alert\"")).toBe(1);+ expect(html).toContain("xai failed mid-response");+ expect(html).toContain("Internal error during token parsing");+ expect(html).toContain("After 12s.");+ expect(html).toContain("data-retry-turn");+ expect(html).not.toMatch(/data-retry-turn[^>]*\sdisabled=/);+});++test("Retry only exists on an errored turn, and waits while another turn is live", () => {+ const done = { ...emptyTurn(), status: "done" as const, text: "Fine." };+ expect(renderToStaticMarkup(<AssistantBody turn={done} following={false} onRetry={() => {}} />)).not.toContain("data-retry-turn");+ const failed = { ...emptyTurn(), status: "error" as const, error: "Disconnected" };+ expect(renderToStaticMarkup(<AssistantBody turn={failed} following={false} />)).not.toContain("data-retry-turn");+ const busy = renderToStaticMarkup(<AssistantBody turn={failed} following={false} onRetry={() => {}} retryDisabled />);+ expect(busy).toContain("data-retry-turn");+ expect(busy).toMatch(/data-retry-turn[^>]*\sdisabled=/);+});diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.tsindex 71ac4cd9..8bdebab7 100644--- a/apps/native/lib/graff-events.ts+++ b/apps/native/lib/graff-events.ts@@ -118,6 +118,8 @@ export type AssistantTurn = {/** A tool bracket landed after streamed text — the next text chunk starts a* new paragraph instead of fusing onto the previous sentence. */pendingBreak?: boolean;+ /** Mid-stream engine retry. Activity only — never assistant prose. */+ retryNotice?: string;status: TurnStatus;};diff --git a/apps/native/lib/thread-callbacks.test.tsx b/apps/native/lib/thread-callbacks.test.tsxnew file mode 100644index 00000000..a54037de--- /dev/null+++ b/apps/native/lib/thread-callbacks.test.tsx@@ -0,0 +1,65 @@+import { expect, test } from "bun:test";+import { useState } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createThreadCallbackRegistry, useThreadCallbacks, type ThreadCallbacks, type ThreadHandlers } from "../components/site/useThreadCallbacks";+import { promptIndexes } from "../components/site/ChatTranscript";+import type { Msg } from "../components/site/harness-types";+import { emptyTurn } from "./graff-events";++const handlers = (log: string[], tag: string): ThreadHandlers => ({+ onOpenPath: (path, chatId) => log.push(`${tag} open ${chatId} ${path}`),+ onAnswer: (chatId, text, cancelled) => log.push(`${tag} answer ${chatId} ${text} ${cancelled ?? false}`),+ onEditPrompt: (chatId, n, text) => log.push(`${tag} edit ${chatId} ${n} ${text}`),+});++test("per-thread callbacks keep their identity across re-renders while running the latest handlers", () => {+ const seen: ThreadCallbacks[] = [];+ const log: string[] = [];+ function Probe() {+ const [pass, setPass] = useState(0);+ const callbacksOf = useThreadCallbacks(handlers(log, `pass${pass}`), [1, 2]);+ seen.push(callbacksOf(1));+ // A render-phase update re-runs this component with its hooks intact:+ // the same test double the harness re-render on every painted token.+ if (pass < 2) setPass(pass + 1);+ return <span>{pass}</span>;+ }+ expect(renderToStaticMarkup(<Probe />)).toBe("<span>2</span>");+ expect(seen).toHaveLength(3);+ expect(seen[1]).toBe(seen[0]);+ expect(seen[2].onOpenPath).toBe(seen[0].onOpenPath);+ expect(seen[2].onAnswer).toBe(seen[0].onAnswer);+ expect(seen[2].onEditPrompt).toBe(seen[0].onEditPrompt);+ // The function handed out on the first render reaches the handlers of the last one.+ seen[0].onOpenPath("src/a.ts");+ seen[0].onAnswer("yes");+ seen[0].onEditPrompt(3, "again");+ expect(log).toEqual(["pass2 open 1 src/a.ts", "pass2 answer 1 yes false", "pass2 edit 1 3 again"]);+});++test("the registry hands out one object per chat and forgets closed chats", () => {+ const log: string[] = [];+ const registry = createThreadCallbackRegistry(() => handlers(log, "now"));+ const first = registry.forThread(1), second = registry.forThread(2);+ expect(registry.forThread(1)).toBe(first);+ expect(first).not.toBe(second);+ second.onOpenPath("b.ts");+ expect(log).toEqual(["now open 2 b.ts"]);+ expect(registry.size).toBe(2);+ registry.prune([1]);+ expect(registry.size).toBe(1);+ expect(registry.forThread(1)).toBe(first);+ expect(registry.forThread(2)).not.toBe(second);+});++test("promptIndexes numbers prompts 1-based and attributes turns and notices to the prompt before them", () => {+ const messages: Msg[] = [+ { id: 1, role: "user", text: "first" },+ { id: 2, role: "assistant", turn: emptyTurn() },+ { id: 3, role: "user", origin: "notification", text: "peer mail" },+ { id: 4, role: "user", text: "second" },+ { id: 5, role: "assistant", turn: { ...emptyTurn(), status: "error" } },+ ];+ expect(promptIndexes(messages)).toEqual([1, 1, 1, 2, 2]);+ expect(promptIndexes([])).toEqual([]);+});diff --git a/apps/native/lib/turn-activity.test.ts b/apps/native/lib/turn-activity.test.tsindex 86b76766..b91029d0 100644--- a/apps/native/lib/turn-activity.test.ts+++ b/apps/native/lib/turn-activity.test.ts@@ -1,6 +1,6 @@import { test, expect } from "bun:test";import { emptyTurn, applyAcpUpdate, finishAcpTurn } from "./acp";-import { turnActivity, workDuration } from "./turn-activity";+import { describeTurnError, turnActivity, workDuration } from "./turn-activity";import { createTurnPainter } from "./turn-painter";test("a saved snapshot does not claim the turn finished here (#839)", () => {const turn = { ...emptyTurn(), status: "done" as const, startedAt: 1000 };@@ -69,7 +69,6 @@ test("elapsed work freezes at completion across remounts and repeated finalizatiexpect(workDuration(60)).toBe("1m 0s");expect(workDuration(3601)).toBe("1h 0m");});-test("streaming text reports tok/s; tools and MCP Apps wait instead", () => {const writing = {...emptyTurn(), status: "streaming" as const, text: "x".repeat(80), connected: true,@@ -84,3 +83,32 @@ test("streaming text reports tok/s; tools and MCP Apps wait instead", () => {const done = finishAcpTurn({ ...writing, startedAt: 0 }, 1000);expect(turnActivity(done, 1000).detail).toMatch(/tok\/s/);});++test("a mid-stream retry notice is live activity, not a failed turn", () => {+ const turn = {+ ...emptyTurn(),+ status: "streaming" as const,+ text: "",+ retryNotice: "provider error mid-response — retrying in 1s (1/3)",+ connected: true,+ startedAt: 1000,+ lastUpdateAt: 2000,+ activityKind: "agent_message_chunk",+ };+ expect(turnActivity(turn, 2000)).toMatchObject({+ live: true,+ state: "working",+ detail: "provider error mid-response — retrying in 1s (1/3)",+ });+});++test("a failed turn names the provider from the harness error and keeps its words as detail", () => {+ expect(describeTurnError("xai api error: Internal error during token parsing")).toEqual({ framing: "xai failed mid-response", message: "Internal error during token parsing" });+ expect(describeTurnError("api error (rate_limit_error): Too many requests", "anthropic")).toEqual({ framing: "anthropic failed mid-response", message: "Too many requests" });+ expect(describeTurnError("api error: quota").framing).toBe("The model provider failed mid-response");+ expect(describeTurnError("graff acp exited with code 1")).toEqual({ framing: "The agent stopped before finishing", message: "graff acp exited with code 1" });+ expect(describeTurnError("Preview inspection failed")).toEqual({ framing: "The request failed", message: "Preview inspection failed" });+ const failed = finishAcpTurn({ ...emptyTurn(), status: "error", error: "xai api error: boom", startedAt: 1000 }, 13000);+ expect(turnActivity(failed, 13000).detail).toMatch(/^After 12s\./);+});+});diff --git a/apps/native/lib/turn-activity.ts b/apps/native/lib/turn-activity.tsindex 92207bcf..879a67f3 100644--- a/apps/native/lib/turn-activity.ts+++ b/apps/native/lib/turn-activity.ts@@ -35,14 +35,28 @@ export function turnActivity(turn: AssistantTurn, now: number, opts?: { snapshotconst mcpApps = turn.tools.filter(tool => tool.status === "running" && tool.mcpAppId).length;const missing = turn.tools.filter(tool => tool.status === "interrupted").length;const rate = running ? null : tokPerSec(estimateTokens(turn.text), elapsedMs);- if (turn.status === "error") return { state: "error", label: "Response interrupted", detail: `After ${duration}. ${turn.tools.some(tool => tool.status === "ok") ? "Completed tool results are kept. " : ""}Send a follow-up to continue.`, live: false };+ if (turn.status === "error") return { state: "error", label: "Response interrupted", detail: `After ${duration}. ${turn.tools.some(tool => tool.status === "ok") ? "Completed tool results are kept. " : ""}Retry or send a follow-up to continue.`, live: false };if (turn.status === "ask") return { state: "input", label: "Waiting for your answer", detail: "", live: false };if (!live) {const wait = missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : rate;return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : `Worked for ${duration}`, detail: turn.stopReason === "cancelled" ? `After ${duration}` : wait ?? "", live: false };}- const waitingOn = mcpApps ? `Waiting on ${mcpApps === 1 ? "MCP App" : "MCP Apps"}…` : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : "";+ const waitingOn = mcpApps ? `Waiting on ${mcpApps === 1 ? "MCP App" : "MCP Apps"}…` : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : turn.retryNotice ? turn.retryNotice : "";const writing = !turn.connected ? "Starting…" : waitingOn || (turn.activityKind === "agent_thought_chunk" ? "Thinking…" : turn.activityKind === "agent_message_chunk" && idle < 2 ? "Writing…" : "");const detail = idle >= 15 ? joinDetail(writing, `No update for ${workDuration(idle)}`) : joinDetail(writing, waitingOn ? null : rate);return { state: idle >= 15 ? "waiting" : "working", label: `Working for ${duration}`, detail, live: true };}++/** Human framing for a failed turn: who failed, then the provider's own words.+ * The provider id is whatever prefixes the harness's `<provider> api error:`+ * text (or the turn's spawn provider); nothing vendor-specific is hardcoded. */+export function describeTurnError(error: string, provider?: string): { framing: string; message: string } {+ const text = error.trim();+ const api = /^(?:([a-z0-9][\w.-]*)\s+)?api error(?:\s*\([^)]*\))?\s*:\s*([\s\S]*)$/i.exec(text);+ if (api) {+ const who = api[1] ?? provider;+ return { framing: who ? `${who} failed mid-response` : "The model provider failed mid-response", message: api[2].trim() || text };+ }+ if (/\b(exited|disconnected|closed|not running)\b/i.test(text)) return { framing: "The agent stopped before finishing", message: text };+ return { framing: provider ? `${provider} failed mid-response` : "The request failed", message: text };+}diff --git a/docs/adr/0145-gpt-5-6-reasoning-replays-from-local-history.md b/docs/adr/0145-gpt-5-6-reasoning-replays-from-local-history.mdnew file mode 100644index 00000000..e0bb42bb--- /dev/null+++ b/docs/adr/0145-gpt-5-6-reasoning-replays-from-local-history.md@@ -0,0 +1,51 @@+# 0145. GPT-5.6 reasoning replays from local history; `reasoning.context` and pro mode are not sent++Status: accepted 2026-09-21++## Context++GPT-5.6 (`gpt-5.6` → `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`) adds+`reasoning.context` (`auto | all_turns | current_turn`, default `all_turns` on+5.6, `current_turn` on earlier models) and `reasoning.mode: "pro"` on the same+model slug. With `all_turns` the API wants prior reasoning carried forward:+either continue with `previous_response_id`, or resend every output item —+including encrypted reasoning items when `store:false`. It also accepts+`reasoning.effort` up to `max`, and may pause a stream for several seconds+mid-generation for classifier review.++Graff already sends `store:false`, includes `reasoning.encrypted_content`, and+appends every Responses output item to history verbatim; a full rebuild+re-sends that history, and the Codex/xAI held-socket path chains on+`previous_response_id` with only the delta. Reasoning items therefore reach+the model on every turn without any new field. Effort is part of the cached+prefix and only moves on an explicit `/effort` or worker pin (see the header+of `effort_route.zig`); OpenAI's maximum is shown as Ultra and wired as `max`.++## Decision++- Do not send `reasoning.context`. The default (`all_turns` on 5.6) matches+ what graff replays, and pinning `current_turn` would drop reasoning the+ history already carries. The field is understood as an echo on+ `response.completed` and nothing else. Revisit only with a measured win+ from `current_turn` on a stale-reasoning workload.+- Do not send `reasoning.mode`. Pro mode is a session-wide, billed opt-in that+ must land on the REPL, TUI, and GUI together (a live control, persisted+ setting, and SDK/ACP surface); a wire-only flag is a half feature.+- Keep `max` as the ceiling of the effort ladder for the family (picker tag+ Ultra), default `medium`, `xhigh` between. `none` is not exposed.+- Unknown Responses output items (`program`, `program_output`, program-issued+ `function_call`s) are kept as opaque history so `call_id`/`caller` pairing+ survives; Programmatic Tool Calling itself is not implemented.+- Stall budgets stay as they are: a several-second safety pause sits well+ inside the 30s between-lines budget (15s floor) and the 45s head ceiling.+- The model note in `prompt_guidance.zig` states the autonomy/approval+ boundary once and carries no brevity rule; the model is already concise.++## Consequences++Every rebuild replays encrypted reasoning bytes, which is the cost of+`all_turns` without server-side storage; the held-socket delta avoids it+where a chain exists. A future pro-mode toggle is one field on the request+builder plus the three-surface control; the capability gate is+`prompt_guidance.isGpt56`. If OpenAI changes the `all_turns` default, graff's+behavior is unchanged because it never relied on the server default.diff --git a/docs/adr/0148-midstream-provider-error-is-a-transient-500.md b/docs/adr/0148-midstream-provider-error-is-a-transient-500.mdnew file mode 100644index 00000000..cccec7c6--- /dev/null+++ b/docs/adr/0148-midstream-provider-error-is-a-transient-500.md@@ -0,0 +1,64 @@+# 0148. A mid-stream provider "internal error" is a transient 500, not overflow++Status: accepted 2026-09-21. Reverses the `#1019` classification.++## Context++xAI (grok-4.6 on the Responses wire) sometimes ends a streamed response with a+`type:error` frame whose message is `Internal error during token parsing`.+`#1019` read that as the tokenizer rejecting an over-window prompt and put+`"during token parsing"` in the overflow table, with a matching carve-out so+the gateway-flake ladder would never retry it. The remedy was emergency-trim+and resend.++The frame does not behave like an input-size rejection:++- It arrives after the model has already streamed output text, on requests+ well under the advertised window. A rejection for size arrives before any+ output, with no partial answer.+- Trim-and-resend hit the same error again; resending the same body sometimes+ succeeded. Both are the signature of a server-side fault, not a size limit.+- The provider's own reference harness classifies a streamed `error` /+ `response.failed` as a retryable HTTP 500 with bounded backoff, discarding+ the partial output; "token parsing" is not in its context-length list.++Treating it as overflow had a second cost. `applyOverflowRecovery` pins the+context meter to the window before it decides whether it can trim (`#174`), so+the between-turn compaction still engages after a genuine rejection that+returned no usage. On a misclassified frame in a small conversation there was+nothing to trim, the pin stayed, and the next turn force-compacted a+conversation that was nowhere near the window.++## Decision++- A streamed provider "internal error" that lands after output began is a+ transient server error. It rides the bounded transient ladder in+ `agent_gateway_retry.zig` (3 attempts, 1·2·4 s backoff), with partial text+ cleared and, on the WS arm, the socket already retired so the rebuild+ reconnects with full input. The user sees+ `[provider error mid-response — retrying in Ns (i/3)]`; the overloaded+ wording is kept for overloaded cases.+- Overflow classification requires a size or length phrasing, or a structured+ overflow code. An "internal error" with neither is never overflow, whatever+ else the message says.+- The context meter is pinned only on a real overflow rejection. The pin-first+ order in `applyOverflowRecovery` is unchanged: for a genuine overflow that+ cannot trim in-turn (a compaction summary request, a second overflow after+ one trim, nothing left to drop) the pin is what lets the outer+ `compactOrRecover` path recover, and existing tests hold it there. Removing+ the misclassification removes the stale pin.++## Consequences++A transient mid-stream fault costs one to three resends of the same body+instead of a destructive trim, and a repeat surfaces as the provider's own+error text after the ladder is spent. A real xAI over-window rejection still+classifies through `"maximum prompt length"`. Tier 2+`midstream-provider-error-retries-not-trims` scripts the frame after text+deltas and asserts a retry, a `text` event with the retry line (ACP renders it+as `agent_message_chunk`; a bound TUI sink gets `session_notice`), no error+event, no partial text in history, and no extra compaction call on the following+turn. ACP has no replace/reset update, so a client that already painted the+first stream will append the retry. If xAI ever returns this message+for an oversized prompt before any output, add a size-bearing phrasing to the+overflow table rather than reinstating this needle.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6df2bdcf..13f8ae48 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -168,6 +168,8 @@ record only when you need the evidence or the edge cases.| [0146](0146-concurrent-sessions-auto-isolate.md) | A second live session in the same Git checkout gets its own worktree; concurrent agents never share `index.lock`. || [0147](0147-finish-is-not-cleanup-fanout.md) | Finish is not archive: park peer wakes until idle, paint the tally at the step boundary, refuse cleanup/fix-it children, cap live fan-out. || [0148](0148-read-file-miss-storm-stops.md) | After N same-prefix or incrementing `read_file` misses, refuse further guesses this turn and point at `codedb list_dir`. |+| [0145](0145-gpt-5-6-reasoning-replays-from-local-history.md) | GPT-5.6 reasoning replays from local history: never send `reasoning.context` or `reasoning.mode`; `max` effort is the ladder ceiling (shown as Ultra); PTC items stay opaque history. |+| [0148](0148-midstream-provider-error-is-a-transient-500.md) | A streamed provider "internal error" after output began is a transient 500: bounded backoff retry, never overflow. Overflow needs a size/length phrasing or code; the meter pins only on a real rejection. Reverses `#1019`. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex cc6fd39d..26e9f6d7 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -42,6 +42,7 @@{"id": "budget-exhausted-past-the-landing-dies-fatal", "why": "#368 exhaustedFatal, the harness's own last words - and the FIRST case that can exist at all, since the runner auto-failed every nonzero exit until expected_exit landed. The #390 landing reserve buys the run ONE tools-free final call; it cannot stop a model that answers that call with a tool call anyway, and executing that tool demands a call the pool cannot admit. A one-shot (-p) run must then die LOUDLY: exit 1 with the harness naming what ran out, that the work is PARTIAL and was NOT rolled back, and where the trace is - never the bare 'turn failed: RunBudgetExhausted' that #368 replaced, and never a silent exit 0. The asserts pin the whole ordering: request 1 carries the full toolset, request 2 IS the landing call (note present, tools gone), and only PAST it does the run die. NOTE (-p): one-shot sets root.out = null, so the --json event stream is empty and no event/final_text assert is expressible here; the same exhaustion inside the stdin/mainloop shape is non-fatal by design (an error event, exit 0), which is why this case must be one-shot. GRAFF_FLEET=on plus the workflow call makes the run carry a real orchestration decision, so exhaustedFatal's other half fires too - it files the score-0 exhausted:true orch_outcome row before dying (verified by hand in the workspace: kind:\"orch_outcome\" ... \"exhausted\":true,\"landed\":false). That row is NOT asserted: it is written as the process dies, after every scripted bash step could run, and the runner keeps no post-mortem surface - it becomes assertable when the trajectory_row extension lands.", "args": ["--max-model-calls", "2", "-p", "fix the failing checks in parser.py"], "env": {"GRAFF_FLEET": "on"}, "expected_exit": 1, "timeout_s": 90, "prompt": "fix the failing checks in parser.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read parser.py and locate the failing check"}]}]}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "never reached: the pool was dry two calls ago"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"stderr_contains": "model-call budget exhausted"}, {"stderr_contains": "(--max-model-calls 2)"}, {"stderr_contains": "Work done so far is PARTIAL and was NOT rolled back"}, {"stderr_contains": "raise --max-model-calls or re-run to continue"}]}{"id": "new-ask-retires-finished-checklist", "why": "#394: completed items from PRIOR asks piled up. The omitted-completed preserve rule (2896b32) is per-ASK, but the parking never expired: five unrelated goals in one session came back from todo_read as one 13-item [x] pile, and every new prompt inherited it. A checklist that is FULLY completed retires at the next user ask, so the second ask's list holds the second ask's work only - while an unfinished list still crosses the turn untouched (compaction-keeps-completed) and an omission inside one ask still preserves (todo-preserves-completed).", "args": [], "prompt": "rename the config flag", "second_prompt": "unrelated: draft the release notes", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "rename the flag in config.zig", "status": "completed"}]}}, {"text": "the flag is renamed"}, {"tool": "todo_write", "arguments": {"todos": [{"content": "draft the release notes", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "the release notes are drafted"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 1}}, {"request_contains": {"index": -1, "text": "[~] draft the release notes"}}, {"request_lacks": {"index": -1, "text": "[x] rename the flag in config.zig\\n[~] draft the release notes"}}, {"final_text_contains": "the release notes are drafted"}]}{"id": "btw-side-question-leaves-no-trace", "why": "#415: /btw must be answered from the LIVE context with NO tools and then vanish. The next turn's request is where the regression would show: a side question that reaches it has reached root.messages, which is the only way it could also reach the session file OR the append-only transcript (#441) - both are written from that same array.", "prompt": "build it", "controls_after_turn": [{"type": "btw", "text": "what did that linker error actually mean?"}], "second_prompt": "ok, carry on", "script": [{"text": "the link step failed with an undefined symbol"}, {"text": "SIDE-ONLY it means the entry point was renamed"}, {"text": "moving on"}], "assert": [{"event": {"type": "btw", "ok": true, "persisted": false}}, {"request_contains": {"index": 1, "text": "what did that linker error actually mean?"}}, {"request_contains": {"index": 1, "text": "the link step failed with an undefined symbol"}}, {"request_lacks": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "what did that linker error actually mean?"}}, {"request_lacks": {"index": -1, "text": "SIDE-ONLY"}}, {"request_contains": {"index": -1, "text": "the link step failed with an undefined symbol"}}]}+{"id": "midstream-provider-error-retries-not-trims", "why": "ADR 0148 (reverses #1019): a streamed {\"type\":\"error\"} that lands after output began - xAI's 'Internal error during token parsing' - is a transient server 500. The harness must resend the same request on the bounded transient ladder (a second model call, then a clean answer) and never classify it as context overflow: no emergency trim, no error event, no partial text leaking into history, and no pinned meter forcing a compaction summary call on the next turn.", "prompt": "summarize the plan", "second_prompt": "and the next step?", "script": [{"text": "The plan has three", "stream_error": {"type": "api_error", "message": "Internal error during token parsing"}}, {"text": "recovered after the retry"}, {"text": "ship it"}], "assert": [{"events_at_least": {"match": {"type": "model_call_started"}, "count": 2}}, {"events_at_most": {"match": {"type": "model_call_started"}, "count": 3}}, {"event": {"type": "model_call_finished", "ok": true}}, {"event": {"type": "text", "text": "[provider error mid-response — retrying in 1s (1/3)]"}}, {"no_event": {"type": "error"}}, {"no_event": {"type": "compact"}}, {"request_contains": {"index": 1, "text": "summarize the plan"}}, {"request_lacks": {"index": 1, "text": "The plan has three"}}, {"request_contains": {"index": -1, "text": "summarize the plan"}}, {"request_contains": {"index": -1, "text": "recovered after the retry"}}, {"request_lacks": {"index": -1, "text": "The plan has three"}}, {"final_text_contains": "ship it"}]}{"id": "peer-checkpoint-blocks-shared-tree-git", "why": "#469: with a live co-resident session in the same worktree, the FIRST index/tree-mutating git command must come back un-executed as a checkpoint naming the peer, and the identical re-issue must run. The regression is two graffs silently mutating one git index again.", "live_peer": true, "args": [], "prompt": "init a repo and stage everything", "script": [{"tool": "bash", "arguments": {"command": "git init -q"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"text": "staged, once the checkpoint told me about the peer session"}], "assert": [{"event": {"type": "tool_call_finished", "name": "bash", "is_error": false}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"request_contains": {"index": 2, "text": "shared-tree checkpoint"}}, {"request_contains": {"index": 2, "text": "another graff session already owns this worktree"}}]}{"id": "session-recap-precedes-turn", "why": "#419: every cleanly completed turn must emit a heuristic session_recap before the terminal turn event, so stream-until-turn clients (the GUI agent overview) always learn the session's one-line state and status.", "prompt": "say hi", "script": [{"text": "hello there"}], "assert": [{"event": {"type": "session_recap", "status": "completed", "source": "heuristic", "text": "hello there"}}, {"event": {"type": "turn", "complete": true}}]}{"id": "session-recap-needs-input-heuristic", "why": "#419: a turn that ends on a question reads as needs_input without any model call - the heuristic degrade path the issue asks for when no cheap model is available.", "prompt": "what do you need", "script": [{"text": "Which file should I change?"}], "assert": [{"event": {"type": "session_recap", "status": "needs_input", "source": "heuristic"}}]}diff --git a/scripts/eval/mock_model.py b/scripts/eval/mock_model.pyindex cffc342f..b84d28cc 100644--- a/scripts/eval/mock_model.py+++ b/scripts/eval/mock_model.py@@ -12,6 +12,11 @@ A reply is either:{"text": "..."}{"tool": "todo_write", "arguments": {...}}{"tool": "todo_write", "arguments": {...}, "text": "..."}+ {"text": "...", "stream_error": {"type": "api_error", "message": "..."}}++The last shape streams its text, then a terminal error frame instead of a+finish - a provider that died mid-response - so a case can prove the harness+retries rather than trims or dies.Past the end of the script every call answers with `exhausted_text` (default"done"), so a run that takes more turns than the case scripted still ends@@ -112,6 +117,9 @@ class ScriptedModel:return messagedef _whole(self, reply: dict[str, Any]) -> None:+ if error := reply.get("stream_error"):+ self._send(json.dumps({"type": "error", "error": error}).encode(), "application/json")+ returnmessage = self._message(reply)finish = "tool_calls" if "tool_calls" in message else "stop"self._send(json.dumps({@@ -147,6 +155,15 @@ class ScriptedModel:if hook := getattr(model, "after_stream_delta", None):self.wfile.flush()hook(delta)+ if error := reply.get("stream_error"):+ # A mid-stream server failure: the provider streamed output,+ # then sent a terminal {"type":"error"} frame (xAI's+ # "Internal error during token parsing" shape, ADR 0148).+ self.wfile.write(b"data: " + json.dumps({"type": "error", "error": error}).encode() + b"\n\n")+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ self.close_connection = True+ returnself._chunk({"choices": [{"index": 0, "delta": {}, "finish_reason": finish}],"usage": {"prompt_tokens": 8, "completion_tokens": 4, "total_tokens": 12},diff --git a/src/acp.zig b/src/acp.zigindex 1168d08e..72488480 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -205,7 +205,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_while (true) {const event = (inbox.wait(arena) catch break) orelse break;switch (event) {- .tick => @import("acp_idle.zig").maybeWake(&d, arena, out, io) catch |err| {+ .tick => @import("acp_idle.zig").maybeWake(&d, arena, out, io, root.session_name) catch |err| {std.debug.print("acp: idle wake failed: {t}\n", .{err});},.line => |line| handleLine(&d, arena, out, line) catch |err| {diff --git a/src/acp_idle.zig b/src/acp_idle.zigindex e4989f1f..374f2429 100644--- a/src/acp_idle.zig+++ b/src/acp_idle.zig@@ -8,15 +8,16 @@ const Allocator = std.mem.Allocator;const engine = @import("acp_engine.zig");const proto = @import("acp_protocol.zig");+const idle_wake = @import("idle_wake_sources.zig");const peer_idle = @import("peer_idle.zig");const peer_inbox = @import("peer_inbox.zig");-pub fn maybeWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, io: Io) !void {+pub fn maybeWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, io: Io, session_name: []const u8) !void {const sid = d.session_id orelse return;if (sid.len == 0) return;if (peer_idle.isBusy()) return; // in-flight prompt is not preempted (#1136)var buf: [512]u8 = undefined;- const wake = peer_idle.takeIdleWake(io, &buf) orelse return;+ const wake = idle_wake.takeIdleWake(io, session_name, &buf) orelse return;try promptWake(d, arena, w, wake);}@@ -97,9 +98,9 @@ test "#1007 maybeWake is silent without a session or mail" {var buf: [256]u8 = undefined;var w: Io.Writer = .fixed(&buf);var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined };- try maybeWake(&d, arena.allocator(), &w, std.testing.io);+ try maybeWake(&d, arena.allocator(), &w, std.testing.io, "");try std.testing.expectEqual(@as(usize, 0), w.buffered().len);d.session_id = "s1";- try maybeWake(&d, arena.allocator(), &w, std.testing.io);+ try maybeWake(&d, arena.allocator(), &w, std.testing.io, "s1");try std.testing.expectEqual(@as(usize, 0), w.buffered().len);}diff --git a/src/acp_stream.zig b/src/acp_stream.zigindex e69403a0..2dacbc59 100644--- a/src/acp_stream.zig+++ b/src/acp_stream.zig@@ -380,6 +380,21 @@ test "translateEvent: reasoning and text become chunks" {try testing.expect(std.mem.indexOf(u8, w.buffered(), "agent_message_chunk") != null);}+test "translateEvent: a transient-retry text event is an agent_message_chunk" {+ var buf: [1024]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const ev = try std.json.parseFromSlice(Value, a, "{\"type\":\"text\",\"text\":\"[provider error mid-response — retrying in 1s (1/3)]\"}", .{});+ defer ev.deinit();+ var id_buf: [64]u8 = @splat(0);+ var next: u32 = 0;+ try testing.expectEqual(.text, try translateEvent(&w, "s1", ev.value, &id_buf, &next));+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "agent_message_chunk") != null);+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "provider error mid-response") != null);+}+test "translateEvent: tool_call then tool_result share a minted id" {var buf: [2048]u8 = undefined;var w: Io.Writer = .fixed(&buf);diff --git a/src/agent_gateway_retry.zig b/src/agent_gateway_retry.zigindex 9170f832..1b45ceae 100644--- a/src/agent_gateway_retry.zig+++ b/src/agent_gateway_retry.zig@@ -16,6 +16,10 @@//! / "Body must be valid JSON" (our stringify just succeeded on call 1).//! That phrase is a flake; auth / quota / a real invalid prompt stay//! fail-fast.+//! 4. The transient-server ladder (overloaded / server_error, and xAI's+//! mid-stream "Internal error during token parsing" — ADR 0148): a 5xx that+//! surfaced in-band is retried 3× with 1·2·4 s backoff, never treated as+//! context overflow. Moved here from agent_request_policy.zig (600-line cap).const std = @import("std");const Agent = @import("agent.zig").Agent;@@ -23,6 +27,8 @@ const http = @import("http.zig");const RetryPlan = http.RetryPlan;const util = @import("util.zig");const policy = @import("agent_request_policy.zig");+const telemetry = @import("telemetry.zig");+const main_mod = @import("main.zig");/// Per-request gateway-retry state; a fresh value lives for one request()/// call, so concurrent agents never share counters.@@ -78,11 +84,11 @@ pub fn noteFlake(self: *Agent, state: *GatewayRetryState, err: anyerror) void {if (err == error.Timeout) state.transport_timeouts += 1;}-/// One gate for the envelope-fatal paths: overload first, then a short-/// Codegraff follow-up flake (ADR 0053 DeepSeek `-j 6` 110-byte / ~450ms)-/// `api_error`), then the timeout-gated body-parse retry.+/// One gate for the envelope-fatal paths: transient server error first (3-step+/// ladder below), then a short Codegraff follow-up flake (ADR 0053 DeepSeek+/// `-j 6` 110-byte / ~450ms `api_error`), then the timeout-gated body-parse retry.pub fn afterServerErrorOrParseReject(self: *Agent, etype: []const u8, code: ?[]const u8, msg: []const u8, server_retries: *usize, state: *GatewayRetryState) !bool {- if (try policy.retryTransientServerError(self, etype, code, msg, server_retries)) return true;+ if (try retryTransientServerError(self, etype, code, msg, server_retries)) return true;if (try retryShortGatewayFlake(self, etype, code, msg, server_retries)) return true;return retryBodyParseAfterTimeouts(self, msg, state);}@@ -97,10 +103,6 @@ pub fn isShortGatewayFlake(etype: []const u8, code: ?[]const u8, msg: []const u8// Gateway 110-byte follow-up. etype is often invalid_request_error, which// would otherwise hard-fail on the "invalid" needle. Auth/quota still die.if (isBodyParseRejection(msg)) return true;- // xAI 500s "Internal error during token parsing" on a fat prompt. The- // "internal" flake needle would resend the same body twice and then kill- // the turn; overflow recovery trims instead (agent_overflow.zig).- if (util.indexOfIgnoreCase(msg, "token parsing") != null) return false;const hard = [_][]const u8{ "invalid", "authentication", "unauthorized", "insufficient", "quota", "permission", "tool_choice", "not found" };for (hard) |n| {if (util.indexOfIgnoreCase(etype, n) != null) return false;@@ -158,6 +160,88 @@ fn retryShortGatewayFlake(self: *Agent, etype: []const u8, code: ?[]const u8, msreturn true;}+pub const max_server_retries: usize = 3; // #opencode-parity: bounded retries for a transient in-stream server error++/// #opencode-parity: an in-band error event (an SSE {"type":"error"} or a JSON+/// error envelope) naming a TRANSIENT server condition — Anthropic overloaded_error,+/// OpenAI server_error / server_is_overloaded, plain "overloaded", or xAI's+/// mid-stream "Internal error during token parsing" (ADR 0148) — is a 5xx that+/// surfaced mid-stream and should be retried, not hard-failed. Billing / quota /+/// invalid-input errors are NOT transient and fall through to a hard fail.+pub fn isTransientServerError(etype: []const u8, code: ?[]const u8, msg: []const u8) bool {+ const needles = [_][]const u8{ "overloaded", "server_error", "server_is_overloaded", "token parsing" };+ for (needles) |n| {+ if (util.indexOfIgnoreCase(etype, n) != null) return true;+ if (util.indexOfIgnoreCase(msg, n) != null) return true;+ if (code) |c| if (util.indexOfIgnoreCase(c, n) != null) return true;+ }+ return false;+}++/// The user-facing name for the wait. xAI's token-parse 500 arrives after+/// output began and is not an overload; calling it one misled #1019.+fn transientServerLabel(msg: []const u8) []const u8 {+ return if (util.indexOfIgnoreCase(msg, "token parsing") != null) "provider error mid-response" else "server overloaded";+}++/// A streamed error frame has no Retry-After header. Honor "try again in N" /+/// "retry after N seconds" from the message when it names 1..60 s; otherwise+/// the local 1·2·4 s ladder. Larger waits (rate-limit days) stay display-only.+fn parseRetryAfterSeconds(msg: []const u8) ?u64 {+ const needles = [_][]const u8{ "try again in ", "retry after " };+ for (needles) |n| {+ const pos = util.indexOfIgnoreCase(msg, n) orelse continue;+ var i = pos + n.len;+ while (i < msg.len and msg[i] == ' ') i += 1;+ var j = i;+ while (j < msg.len and std.ascii.isDigit(msg[j])) j += 1;+ if (j == i) continue;+ return std.fmt.parseInt(u64, msg[i..j], 10) catch continue;+ }+ return null;+}++fn serverRetryDelayMs(msg: []const u8) ?u64 {+ const secs = parseRetryAfterSeconds(msg) orelse return null;+ if (secs == 0 or secs > 60) return null;+ return secs * 1000;+}++/// REPL: say(). TUI: session_notice on the bound sink (ADR 0041). ACP/--json:+/// a `text` event, which EventSink already turns into agent_message_chunk.+fn announceTransientRetry(self: *Agent, label: []const u8, delay_ms: u64, attempt: usize) !void {+ var buf: [160]u8 = undefined;+ const line = std.fmt.bufPrint(&buf, "[{s} — retrying in {d}s ({d}/{d})]", .{+ label, delay_ms / 1000, attempt, max_server_retries,+ }) catch {+ try self.say("[{s} — retrying in {d}s ({d}/{d})]\n", .{ label, delay_ms / 1000, attempt, max_server_retries });+ return;+ };+ try self.say("{s}\n", .{line});+ if (self.sink) |s| s.emit(self.io, .{ .session_notice = .{ .text = line, .tone = .dim } });+ if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "text", .text = line });+}++/// If an in-stream error names a transient server condition, back off and retry+/// the request (bounded), like a 5xx — returns true to signal the caller to+/// `continue`. Partial text is cleared so the re-stream starts clean; the WS arm+/// has already retired its socket on the terminal error frame, so the rebuild+/// reconnects with full input. Esc during the backoff propagates as+/// error.Interrupted. #opencode-parity.+pub fn retryTransientServerError(self: *Agent, etype: []const u8, code: ?[]const u8, msg: []const u8, retries: *usize) !bool {+ if (!isTransientServerError(etype, code, msg)) return false;+ if (retries.* >= max_server_retries) return false;+ retries.* += 1;+ self.partial_text.clearRetainingCapacity(); // fresh re-stream after the retry, no concat+ const delay_ms = serverRetryDelayMs(msg) orelse RetryPlan.delayMs(true, retries.* - 1); // 1·2·4s, or the provider's wait+ const label = transientServerLabel(msg);+ try announceTransientRetry(self, label, delay_ms, retries.*);+ if (self.tracer) |tr| tr.note("retry", label);+ if (telemetry.g_telem) |t| t.errorEvent("server_overloaded", if (msg.len > 0) msg else etype);+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;+ return true;+}+/// The gate on the Agent: announce, trace, back off (1·2s — the gateway just/// answered, give it a beat), clear partial text for a fresh re-stream, and/// tell the caller to `continue`. Esc during the backoff still propagates.@@ -198,7 +282,6 @@ test "shouldRetryBodyParseAfterTimeouts (#gateway-artifact): timeout history gattest "isShortGatewayFlake: internal/empty api_error retry; invalid/auth/quota do not" {try std.testing.expect(isShortGatewayFlake("api_error", null, "Internal Server Error"));- try std.testing.expect(!isShortGatewayFlake("api_error", null, "Internal error during token parsing"));try std.testing.expect(isShortGatewayFlake("api_error", null, ""));try std.testing.expect(isShortGatewayFlake("error", null, " "));try std.testing.expect(isShortGatewayFlake("", null, "unknown error"));@@ -213,14 +296,46 @@ test "isShortGatewayFlake: internal/empty api_error retry; invalid/auth/quota dotry std.testing.expect(!isShortGatewayFlake("invalid_request_error", null, "invalid prompt"));}-test "#1019: token-parse 500 is not a short gateway flake (WS etype empty)" {+test "isTransientServerError (#opencode-parity): overload/server_error retry; quota/invalid/auth do not" {+ // transient server conditions → retry like a 5xx+ try std.testing.expect(isTransientServerError("overloaded_error", null, ""));+ try std.testing.expect(isTransientServerError("api_error", "server_error", ""));+ try std.testing.expect(isTransientServerError("", "server_is_overloaded", ""));+ try std.testing.expect(isTransientServerError("", null, "The server is Overloaded, please try again")); // case-insensitive, in message+ // billing / input / auth → NOT transient, must hard-fail+ try std.testing.expect(!isTransientServerError("insufficient_quota", "insufficient_quota", "You exceeded your current quota"));+ try std.testing.expect(!isTransientServerError("invalid_request_error", null, "invalid prompt"));+ try std.testing.expect(!isTransientServerError("authentication_error", null, "invalid api key"));+ // a bare "Internal Server Error" stays on the shorter gateway-flake ladder+ try std.testing.expect(!isTransientServerError("api_error", null, "Internal Server Error"));+}++test "ADR 0148 (reverses #1019): token-parse 500 rides the transient server ladder, not overflow" {const msg = "Internal error during token parsing";// The Responses WS arm calls afterServerErrorOrParseReject with etype "".- try std.testing.expect(!isShortGatewayFlake("", null, msg));- try std.testing.expect(!isShortGatewayFlake("api_error", null, msg));- try std.testing.expect(!isShortGatewayFlake("", null, "xai api error: Internal error during token parsing"));+ try std.testing.expect(isTransientServerError("", null, msg));+ try std.testing.expect(isTransientServerError("api_error", null, msg));+ try std.testing.expect(isTransientServerError("", null, "xai api error: Internal error during token parsing"));+ // Never overflow: no trim, no meter pin — the same request body is resent.+ try std.testing.expect(!@import("agent_overflow.zig").isContextOverflow(msg, null));+ try std.testing.expect(!@import("agent_overflow.zig").isContextOverflow("xai api error: " ++ msg, null));+ // Not a body-parse rejection either; and the no-carve-out flake gate agrees it is retryable.try std.testing.expect(!isBodyParseRejection(msg));- try std.testing.expect(isShortGatewayFlake("api_error", null, "Internal Server Error"));+ try std.testing.expect(isShortGatewayFlake("", null, msg));+ // Wording: the retry line names a mid-response provider error, not an overload.+ try std.testing.expectEqualStrings("provider error mid-response", transientServerLabel(msg));+ try std.testing.expectEqualStrings("server overloaded", transientServerLabel("The server is overloaded"));+}++test "serverRetryDelayMs honors try-again/retry-after seconds, ignores 0 and >60s" {+ try std.testing.expectEqual(@as(u64, 3), parseRetryAfterSeconds("try again in 3 seconds").?);+ try std.testing.expectEqual(@as(u64, 5), parseRetryAfterSeconds("Please Retry After 5s").?);+ try std.testing.expectEqual(@as(u64, 12), parseRetryAfterSeconds("TRY AGAIN IN 12 seconds.").?);+ try std.testing.expect(parseRetryAfterSeconds("Internal error during token parsing") == null);+ try std.testing.expectEqual(@as(u64, 3000), serverRetryDelayMs("overloaded; try again in 3 seconds").?);+ try std.testing.expect(serverRetryDelayMs("try again in 0 seconds") == null);+ try std.testing.expect(serverRetryDelayMs("retry after 90 seconds") == null);+ try std.testing.expect(serverRetryDelayMs("try again in 350000 seconds") == null);}test "#748: error-only SSE is not a truncated gateway body" {diff --git a/src/agent_overflow.zig b/src/agent_overflow.zigindex e0991d6b..98603cca 100644--- a/src/agent_overflow.zig+++ b/src/agent_overflow.zig@@ -80,7 +80,7 @@ const overflow_needles = [_][]const u8{"input token count", // google: "The input token count (N) exceeds the maximum ...""prompt token count", // github copilot: "prompt token count of N exceeds the limit of M""maximum prompt length", // xai: "This model's maximum prompt length is N ..."- "during token parsing", // xai: "Internal error during token parsing" — tokenizer dies on a fat prompt instead of a 413; resending the same body never helps+ // NOT here (ADR 0148 reverses #1019): xai's "Internal error during token parsing" is a mid-stream 500 that lands after output began; agent_gateway_retry.zig retries it."reduce the length of the messages", // groq"exceeds the available context size", // llama.cpp server"exceeded model token limit", // kimi for coding@@ -409,7 +409,7 @@ test "isContextOverflow (#193/#203/#414): guards beat patterns; every provider p.{ .msg = "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)", .want = true, .why = "google gemini" },.{ .msg = "prompt token count of 141000 exceeds the limit of 128000", .want = true, .why = "github copilot" },.{ .msg = "This model's maximum prompt length is 131072 but the request contains 537812 tokens", .want = true, .why = "xai/grok" },- .{ .msg = "Internal error during token parsing", .want = true, .why = "xai tokenizer 500 on a fat prompt; not a gateway flake" },+ .{ .msg = "Internal error during token parsing", .want = false, .why = "xai mid-stream 500, retried not trimmed (ADR 0148)" },.{ .msg = "Please reduce the length of the messages or completion.", .want = true, .why = "groq" },.{ .msg = "the request exceeds the available context size, try increasing it", .want = true, .why = "llama.cpp" },.{ .msg = "Your request exceeded model token limit: 262144 (requested: 300000)", .want = true, .why = "kimi for coding" },diff --git a/src/agent_overflow_tests.zig b/src/agent_overflow_tests.zigindex 51c67a9a..14d6f5ff 100644--- a/src/agent_overflow_tests.zig+++ b/src/agent_overflow_tests.zig@@ -54,17 +54,40 @@ fn trimmableAgent(a: std.mem.Allocator, kind: @import("provider.zig").Provider.Kreturn agent;}-test "#1019: token-parse 500 emergency-trims instead of dying" {+test "token-parse 500 is not overflow: no trim, no pin (ADR 0148 reverses #1019)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();var agent = try trimmableAgent(a, .responses, 131072);- const before = agent.fullRequestEstimateTokens();+ const before = agent.messages.items.len;var retried = false;- try std.testing.expect(recoverContextOverflow(&agent, "Internal error during token parsing", null, &retried));- try std.testing.expect(retried);+ try std.testing.expect(!recoverContextOverflow(&agent, "Internal error during token parsing", null, &retried));+ try std.testing.expect(!retried);+ try std.testing.expect(!agent.last_request_context_overflow);+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);+ try std.testing.expectEqual(before, agent.messages.items.len); // history intact: the transient ladder resends it+}++test "token-parse 500 on an untrimmable history leaves the meter alone (ADR 0148)" {+ // The observed symptom: a small chat with nothing to trim was pinned to the+ // window and force-compacted at the next turn. A real overflow that cannot+ // trim still pins (see the compaction-request test in agent_request_policy);+ // a message that is not an overflow must never reach that code.+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try trimmableAgent(a, .openai, 500_000);+ agent.messages.shrinkRetainingCapacity(1); // one clean user turn: emergencyTrim has nothing to drop+ agent.context_local_tokens = agent.fullRequestEstimateTokens();+ var retried = false;+ try std.testing.expect(!recoverContextOverflow(&agent, "xai api error: Internal error during token parsing", null, &retried));+ try std.testing.expect(!agent.last_request_context_overflow);+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);+ // Contrast: the same untrimmable history with a REAL overflow phrasing pins+ // so the between-turn compactOrRecover path engages (#174) — by design.+ try std.testing.expect(!recoverContextOverflow(&agent, "This model's maximum prompt length is 500000 but the request contains 600000 tokens", null, &retried));try std.testing.expect(agent.last_request_context_overflow);- try std.testing.expect(agent.fullRequestEstimateTokens() < before);+ try std.testing.expectEqual(agent.provider.context, agent.last_context_tokens);}test "recoverContextOverflow (#414): a Bedrock throttle rides the retry ladder instead of compacting" {diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex 860ffd8a..45480bff 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -145,7 +145,7 @@ fn writeCacheAnchor(s: *std.json.Stringify) !void {/// line restores tools-first behavior. Model guidance is composed here too,/// at request time, so provider switches cannot retain another model's note.pub fn schemaAwarePrompt(self: *Agent) ![]const u8 {- const base = try @import("prompt_astra.zig").append(self, self.systemPrompt());+ const base = try @import("prompt_guidance.zig").append(self, self.systemPrompt());if (self.output_schema == null) return base;// #543 degrade: this provider cannot enforce json_schema server-side —// learned on the chat wire (sox), or structural on minimax / kimi-anthropicdiff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 83f5de93..f0f25637 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -358,39 +358,8 @@ pub fn errorCode(root: std.json.ObjectMap) ?[]const u8 {return null;}-const max_server_retries: usize = 3; // #opencode-parity: bounded retries for a transient in-stream server overload--/// #opencode-parity: an in-band error event (an SSE {"type":"error"} or a JSON-/// error envelope) naming a TRANSIENT server condition — Anthropic overloaded_error,-/// OpenAI server_error / server_is_overloaded, or plain "overloaded" — is a 5xx that-/// surfaced mid-stream and should be retried, not hard-failed. Billing / quota /-/// invalid-input errors are NOT transient and fall through to a hard fail.-fn isTransientServerError(etype: []const u8, code: ?[]const u8, msg: []const u8) bool {- const needles = [_][]const u8{ "overloaded", "server_error", "server_is_overloaded" };- for (needles) |n| {- if (util.indexOfIgnoreCase(etype, n) != null) return true;- if (util.indexOfIgnoreCase(msg, n) != null) return true;- if (code) |c| if (util.indexOfIgnoreCase(c, n) != null) return true;- }- return false;-}--/// If an in-stream error names a transient server overload, back off and retry the-/// request (bounded), like a 5xx — returns true to signal the caller to `continue`.-/// Esc during the backoff propagates as error.Interrupted. #opencode-parity.-pub fn retryTransientServerError(self: *Agent, etype: []const u8, code: ?[]const u8, msg: []const u8, retries: *usize) !bool {- if (!isTransientServerError(etype, code, msg)) return false;- if (retries.* >= max_server_retries) return false;- retries.* += 1;- self.partial_text.clearRetainingCapacity(); // fresh re-stream after the retry, no concat- const delay_ms = RetryPlan.delayMs(true, retries.* - 1); // 1·2·4s- try self.say("[server overloaded — retrying in {d}s ({d}/{d})]\n", .{ delay_ms / 1000, retries.*, max_server_retries });- if (self.tracer) |tr| tr.note("retry", "server overloaded (in-stream)");- if (telemetry.g_telem) |t| t.errorEvent("server_overloaded", if (msg.len > 0) msg else etype);- self.sleepInterruptible(delay_ms) catch return error.Interrupted;- return true;-}-+// The transient-server retry ladder (retryTransientServerError) lives in+// agent_gateway_retry.zig with the other in-band error ladders (ADR 0148).pub const GatewayRetryState = @import("agent_gateway_retry.zig").GatewayRetryState;pub const noteRetry = @import("agent_gateway_retry.zig").noteRetry;pub const noteFlake = @import("agent_gateway_retry.zig").noteFlake;@@ -420,18 +389,6 @@ test "sseKeepAliveOnly: comment-only bodies true, data/error/JSON bodies false"try std.testing.expect(!sseKeepAliveOnly("{\"error\":{\"message\":\"x\"}}"));}-test "isTransientServerError (#opencode-parity): overload/server_error retry; quota/invalid/auth do not" {- // transient server conditions → retry like a 5xx- try std.testing.expect(isTransientServerError("overloaded_error", null, ""));- try std.testing.expect(isTransientServerError("api_error", "server_error", ""));- try std.testing.expect(isTransientServerError("", "server_is_overloaded", ""));- try std.testing.expect(isTransientServerError("", null, "The server is Overloaded, please try again")); // case-insensitive, in message- // billing / input / auth → NOT transient, must hard-fail- try std.testing.expect(!isTransientServerError("insufficient_quota", "insufficient_quota", "You exceeded your current quota"));- try std.testing.expect(!isTransientServerError("invalid_request_error", null, "invalid prompt"));- try std.testing.expect(!isTransientServerError("authentication_error", null, "invalid api key"));-}-/// #opencode-parity: a 429 body naming a billing/quota cap (OpenAI insufficient_quota,/// "exceeded your current quota", "quota exceeded") — a usage limit a retry can't/// clear, unlike transient rate-limit throttling — so we fail fast + fail over ratherdiff --git a/src/agent_responses.zig b/src/agent_responses.zigindex f9bdb0d7..26d6b5f9 100644--- a/src/agent_responses.zig+++ b/src/agent_responses.zig@@ -216,6 +216,39 @@ test "#1019: type:error token-parse frame yields failure.message" {}}+// GPT-5.6 Programmatic Tool Calling adds output item types graff does not+// implement: `program`, program-issued `function_call`s carrying `caller`, and+// `program_output`. Unknown items must ride through the parser and+// stepResponses as opaque history (they are valid next-turn input, so the+// server keeps its `call_id`/`caller` pairing) without erroring or hiding the+// final message.+test "GPT-5.6 PTC: unknown `program` / `program_output` items are kept opaque, never an error" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try @import("agent_request_body_responses.zig").testAgentFor(a, "openai", .responses, "gpt-5.6");+ agent.sub = true; // no unstreamed-text surface in a test+ const before = agent.messages.items.len;+ const body =+ "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"program\",\"id\":\"prog_1\",\"code\":\"print(1)\",\"status\":\"completed\"}}\n" +++ "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"program_output\",\"id\":\"po_1\",\"program_id\":\"prog_1\",\"output\":\"1\"}}\n" +++ "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\",\"role\":\"assistant\",\"phase\":\"final_answer\",\"content\":[{\"type\":\"output_text\",\"text\":\"done\"}]}}\n" +++ "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"reasoning\":{\"effort\":\"medium\",\"context\":\"all_turns\"},\"usage\":{\"total_tokens\":7}}}\n";+ const parsed = switch (try parseResponses(&agent, body)) {+ .ok => |root| root,+ .err => return error.TestUnexpectedResult,+ };+ try std.testing.expectEqual(@as(usize, 3), parsed.get("output").?.array.items.len);+ try std.testing.expect(parsed.get("incomplete") == null);+ const final = try agent.stepResponses(parsed);+ try std.testing.expectEqualStrings("done", final.?);+ // All three items are history now, verbatim (phase and program fields intact).+ try std.testing.expectEqual(before + 3, agent.messages.items.len);+ try std.testing.expectEqualStrings("program", agent.messages.items[before].object.get("type").?.string);+ try std.testing.expectEqualStrings("program_output", agent.messages.items[before + 1].object.get("type").?.string);+ try std.testing.expectEqualStrings("final_answer", agent.messages.items[before + 2].object.get("phase").?.string);+}+pub fn errorMessage(obj: std.json.ObjectMap) ?[]const u8 {if (obj.get("error")) |e| {if (e == .object) {diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex ea486c47..18a38520 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -99,7 +99,7 @@ test "the codex .responses arm refreshes auth and re-anchors before resending (#const overflow_at = std.mem.indexOf(u8, arm, "recoverContextOverflow(self, msg, failure.code, &context_retried)") orelse return error.ResponsesPathHasNoOverflowRecovery;try std.testing.expect(overflow_at < std.mem.indexOf(u8, arm, "policy.afterServerErrorOrParseReject(self, \"\", failure.code, msg, &server_retries, &gw_retry)").?);const gate = @embedFile("agent_gateway_retry.zig");- try std.testing.expect(std.mem.indexOf(u8, gate, "policy.retryTransientServerError(self, etype, code, msg, server_retries)") != null);+ try std.testing.expect(std.mem.indexOf(u8, gate, "retryTransientServerError(self, etype, code, msg, server_retries)") != null);// The guard bool is declared OUTSIDE `rebuild:`. Reset it inside the loop and a// permanently dead credential refresh-and-resends a full history forever, whichdiff --git a/src/effort_route.zig b/src/effort_route.zigindex 2a180dbd..7d7db268 100644--- a/src/effort_route.zig+++ b/src/effort_route.zig@@ -146,3 +146,29 @@ test "flash and Gemini map default medium to low; grok and glm-5.3 stay medium"try std.testing.expect(!allows("xai", "grok-4.6", "max"));try std.testing.expect(allows("xai", "grok-4.6", "high"));}++// GPT-5.6 (sol / terra / luna, bare alias, gateway names) accepts+// reasoning.effort up to `max`. The picker shows OpenAI's maximum as Ultra, so+// a typed or saved `max` must normalize to that tag and still reach the wire+// as the API value `max`; grok's allow-list keeps rejecting it. Default stays+// `medium` (Agent.reasoning), which the API also documents as its default.+test "GPT-5.6 family: max is accepted (as Ultra) and wired as max; grok still folds it" {+ const seats = [_]struct { id: []const u8, model: []const u8 }{+ .{ .id = "openai", .model = "gpt-5.6" },+ .{ .id = "openai", .model = "gpt-5.6-terra" },+ .{ .id = "openai", .model = "gpt-5.6-luna" },+ .{ .id = "codex", .model = "gpt-5.6-sol" },+ .{ .id = "codegraff", .model = "openai/gpt-5.6-sol" },+ };+ for (seats) |s| {+ try std.testing.expectEqualStrings("ultra", normalize(s.id, s.model, "max"));+ try std.testing.expect(allows(s.id, s.model, "ultra"));+ try std.testing.expect(allows(s.id, s.model, "xhigh"));+ try std.testing.expectEqualStrings("max", wireEffort(s.model, "ultra"));+ try std.testing.expectEqualStrings("xhigh", wireEffort(s.model, "xhigh"));+ try std.testing.expectEqualStrings("medium", wireEffort(s.model, "medium")); // not a flash/Astra seat: default medium is sent as-is+ }+ try std.testing.expectEqualStrings("max", normalize("xai", "grok-4.6", "max")); // untouched, then refused+ try std.testing.expect(!allows("xai", "grok-4.6", "max"));+ try std.testing.expect(!allows("xai", "grok-4.6", "ultra"));+}diff --git a/src/http_stall.zig b/src/http_stall.zigindex 810934b3..1dbea164 100644--- a/src/http_stall.zig+++ b/src/http_stall.zig@@ -143,3 +143,18 @@ test "stall budget (#680): each reconnect widens the between-lines wait — a qutry std.testing.expectEqual(@as(u64, 20 * 1000), budgetMsWidened(20 * 1000, true, 2));try std.testing.expectEqual(@as(u64, 5 * 1000), budgetMsWidened(5 * 1000, true, 1));}++// GPT-5.6 can pause generation for several seconds mid-stream while a safety+// classifier reviews the output (OpenAI's "Using GPT-5.6" guide). With prose+// already flowing the between-lines budget is the tight regime, so pin that a+// pause of that size never trips it: 30s on the shipped default, and the 15s+// floor still holds it when GRAFF_STREAM_STALL_SECS is set low.+test "stall budget: a several-second GPT-5.6 mid-stream safety pause stays inside the tightened budget" {+ const pause_ms: u64 = 10 * 1000; // "several seconds", with margin+ const base: u64 = 120 * 1000;+ try std.testing.expect(!expired(pause_ms, base, true));+ try std.testing.expect(pause_ms < interFrameBudgetMs(base, true, true, 0));+ try std.testing.expect(pause_ms < interFrameBudgetMs(base, true, false, 0)); // reasoning-only phase: full budget+ try std.testing.expect(pause_ms < budgetMs(20 * 1000, true)); // short override: the floor covers it+ try std.testing.expect(idle_floor_ms > pause_ms);+}diff --git a/src/idle_wake_sources.zig b/src/idle_wake_sources.zignew file mode 100644index 00000000..479d6d13--- /dev/null+++ b/src/idle_wake_sources.zig@@ -0,0 +1,115 @@+//! Idle auto-turn sources shared by the line REPL, TUI, and graff acp.+//! Order matches the TUI poll: interactive-subagent, job idle-stop (#199),+//! schedule, channel-worker, then peer mail (#1001). Accord ping is a side+//! drain, not a wake. `subagent_interactive.takeWake` is engine-side (job+//! registry + session owner) — it does not need a TTY. The TTY-only path is+//! `stealIdleLine`, which the line REPL already calls separately.++const std = @import("std");+const Io = std.Io;++const channel_worker = @import("channel_worker.zig");+const job_notify = @import("job_notify.zig");+const peer_idle = @import("peer_idle.zig");+const peer_inbox = @import("peer_inbox.zig");+const presence_accord = @import("presence_accord.zig");+const presence_chan = @import("presence_chan.zig");+const schedule = @import("schedule.zig");+const subagent_interactive = @import("subagent_interactive.zig");++/// Single-fire poll used by every surface's idle callback. Busy / completion+/// latches stay inside `peer_idle.takeIdleWake` (#1137 / #1138); this helper+/// only unifies which sources run and in which order.+pub fn takeIdleWake(io: Io, session_name: []const u8, buf: []u8) ?[]const u8 {+ if (subagent_interactive.takeWake(io, session_name, buf)) |t| return t;+ if (job_notify.takeIdleWake(io, buf)) |t| return t; // idle-stop waits for a real step boundary (#199)+ if (schedule.takeWake(io, buf)) |t| return t;+ if (channel_worker.takeWake(io, buf)) |t| return t;+ _ = presence_accord.takePing(); // standing link; JSONL is still the drain+ return peer_idle.takeIdleWake(io, buf);+}++fn sourcePin(src: []const u8, needle: []const u8) !usize {+ return std.mem.indexOf(u8, src, needle) orelse return error.MissingPin;+}++fn expectBefore(src: []const u8, earlier: []const u8, later: []const u8) !void {+ const a = try sourcePin(src, earlier);+ const b = try sourcePin(src, later);+ try std.testing.expect(a < b);+}++fn helperBody() []const u8 {+ const src = @embedFile("idle_wake_sources.zig");+ const start = std.mem.indexOf(u8, src, "pub fn takeIdleWake").?;+ const rest = src[start..];+ const end = std.mem.indexOf(u8, rest, "\n}\n").?;+ return rest[0 .. end + 1];+}++test "idle wake helper polls sources in TUI order" {+ const body = helperBody();+ try expectBefore(body, "subagent_interactive.takeWake", "job_notify.takeIdleWake");+ try expectBefore(body, "job_notify.takeIdleWake", "schedule.takeWake");+ try expectBefore(body, "schedule.takeWake", "channel_worker.takeWake");+ try expectBefore(body, "channel_worker.takeWake", "presence_accord.takePing");+ try expectBefore(body, "presence_accord.takePing", "peer_idle.takeIdleWake");+}++test "REPL TUI and ACP idle callbacks delegate to the shared helper" {+ const helper = "idle_wake_sources.zig";+ const tui = @embedFile("tui_launch.zig");+ const repl = @embedFile("readline.zig");+ const acp = @embedFile("acp_idle.zig");+ try std.testing.expect(std.mem.indexOf(u8, tui, helper) != null);+ try std.testing.expect(std.mem.indexOf(u8, repl, helper) != null);+ try std.testing.expect(std.mem.indexOf(u8, acp, helper) != null);+ try std.testing.expect(std.mem.indexOf(u8, tui, "takeIdleWake(") != null);+ try std.testing.expect(std.mem.indexOf(u8, repl, "takeIdleWake(") != null);+ try std.testing.expect(std.mem.indexOf(u8, acp, "takeIdleWake(") != null);+ try std.testing.expect(std.mem.indexOf(u8, tui, "job_notify.takeIdleWake") == null);+ try std.testing.expect(std.mem.indexOf(u8, tui, "schedule.takeWake") == null);+ try std.testing.expect(std.mem.indexOf(u8, tui, "channel_worker.takeWake") == null);+ try std.testing.expect(std.mem.indexOf(u8, tui, "peer_idle.takeIdleWake") == null);+ try std.testing.expect(std.mem.indexOf(u8, repl, "peer_idle.takeIdleWake") == null);+ try std.testing.expect(std.mem.indexOf(u8, acp, "peer_idle.takeIdleWake") == null);+}++test "ACP frontend exit runs finalizeSession like REPL and TUI" {+ const src = @embedFile("session_run.zig");+ const fn_start = std.mem.indexOf(u8, src, "pub fn runFrontendCommands").?;+ const body = src[fn_start..];+ const acp = try sourcePin(body, "runAcpCommand");+ const after_acp = body[acp..];+ const finalize = try sourcePin(after_acp, "finalizeSession(");+ const ret = try sourcePin(after_acp, "return true;");+ try std.testing.expect(finalize < ret);+ try std.testing.expect(std.mem.indexOf(u8, body[0..acp], "finalizeSession(") != null);+ const tui = try sourcePin(body, "tui_launch.maybeRun");+ try std.testing.expect(std.mem.indexOf(u8, body[tui..], "finalizeSession(") != null);+}++test "job notify wins over parked peer mail" {+ peer_inbox.resetForTest();+ peer_idle.resetForTest();+ defer {+ peer_inbox.resetForTest();+ peer_idle.resetForTest();+ }+ const io = std.testing.io;+ var buf: [512]u8 = undefined;+ while (job_notify.takeIdleWake(io, &buf)) |_| {}+ job_notify.record(io, 99, 0, false, "true", false);+ const msg: presence_chan.Message = .{+ .from_pid = 2,+ .from_start = 1,+ .from_session = "s-peer",+ .text = "hold gui/src",+ .to = "s-me",+ };+ _ = peer_inbox.parkHeard(&.{msg}, &.{});+ const first = takeIdleWake(io, "s", &buf) orelse return error.ExpectedJob;+ try std.testing.expect(std.mem.indexOf(u8, first, "[job 99") != null);+ const second = takeIdleWake(io, "s", &buf) orelse return error.ExpectedPeer;+ try std.testing.expect(std.mem.indexOf(u8, second, "[peer]") != null);+}diff --git a/src/main.zig b/src/main.zigindex 3df29599..a8a12283 100644--- a/src/main.zig+++ b/src/main.zig@@ -564,7 +564,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };_ = @import("session_catalog.zig");_ = @import("session_prompt.zig");- _ = @import("prompt_astra.zig");+ _ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig") }; // per-model guidance (Astra, GPT-5.6)_ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation_ = @import("agent_model_loop.zig");_ = @import("publication_policy_tests.zig");diff --git a/src/pricing.zig b/src/pricing.zigindex 85c81389..d834a0b2 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -17,9 +17,16 @@ pub const ModelPrice = struct { name: []const u8, in: f64, out: f64, cache: f64,pub const price_table = [_]ModelPrice{.{ .name = "deepseek-v4-pro", .in = 1.1, .out = 2.2, .cache = 0.11 },.{ .name = "deepseek-v4-flash", .in = 0.14, .out = 0.28, .cache = 0.028 },- .{ .name = "gpt-5.6", .in = 5, .out = 30, .cache = 0.5 }, // Sol / flagship (models.dev 2026-07-09)- .{ .name = "gpt-5.6-terra", .in = 2.5, .out = 15, .cache = 0.25 },- .{ .name = "gpt-5.6-luna", .in = 1, .out = 6, .cache = 0.1 },+ // GPT-5.6 family (developers.openai.com model pages, read 2026-09-21).+ // `gpt-5.6` is the API alias for `gpt-5.6-sol`; graff catalogs the direct+ // sol slug only under codex (flat-rate, see provider.zig #294), so it has+ // no row here on purpose — tier/pin logic relies on that. Sol's $4/$20 is+ // promotional (at least through 2026-11-21; list was $5/$30). Requests+ // above 272K input tokens bill 2× input and 1.5× output for the whole+ // request — the `high_*` tier, as for grok-4.6.+ .{ .name = "gpt-5.6", .in = 4, .out = 20, .cache = 0.4, .high_at = 272_000, .high_in = 8, .high_out = 30, .high_cache = 0.8 },+ .{ .name = "gpt-5.6-terra", .in = 2, .out = 12, .cache = 0.2, .high_at = 272_000, .high_in = 4, .high_out = 18, .high_cache = 0.4 },+ .{ .name = "gpt-5.6-luna", .in = 0.2, .out = 1.2, .cache = 0.02, .high_at = 272_000, .high_in = 0.4, .high_out = 1.8, .high_cache = 0.04 },.{ .name = "gpt-5.5", .in = 5, .out = 30, .cache = 0.5 },.{ .name = "gpt-5.5-codex", .in = 1.25, .out = 10, .cache = 0.125 },.{ .name = "gpt-5.4", .in = 2.5, .out = 15, .cache = 0.25 },diff --git a/src/pricing_tests.zig b/src/pricing_tests.zigindex eac53cb9..0af28b4e 100644--- a/src/pricing_tests.zig+++ b/src/pricing_tests.zig@@ -79,8 +79,17 @@ test "usdFor: per-million math, cache writes, and negative clamping" {try std.testing.expectApproxEqAbs(@as(f64, 0.5), pricing.usdFor(p, 0, 1_000_000, 0), 1e-9);try std.testing.expectApproxEqAbs(@as(f64, 3.0), pricing.usdFor(p, 0, 0, 100_000), 1e-9);try std.testing.expectApproxEqAbs(@as(f64, 0.0), pricing.usdFor(p, -42, -1, 0), 1e-9); // clamped+ // GPT-5.6 (OpenAI model pages): $4 in / $20 out / $0.4 cached; cache+ // writes at 1.25× input; above 272K input tokens the whole request bills+ // 2× input and 1.5× output.const p56 = pricing.priceFor("gpt-5.6").?;- try std.testing.expectApproxEqAbs(@as(f64, 6.25), pricing.usdForUsage(p56, "gpt-5.6", 0, 0, 1_000_000, 0), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), pricing.usdForUsage(p56, "gpt-5.6", 0, 0, 100_000, 0), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.4 + 2.0), pricing.usdForUsage(p56, "gpt-5.6", 100_000, 0, 0, 100_000), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 2.4 + 3.0), pricing.usdForUsage(p56, "gpt-5.6", 300_000, 0, 0, 100_000), 1e-9); // long-context tier+ const terra = pricing.priceFor("gpt-5.6-terra").?; // $2 / $12 / $0.2+ try std.testing.expectApproxEqAbs(@as(f64, 0.2 + 0.02 + 12.0), pricing.usdForUsage(terra, "gpt-5.6-terra", 100_000, 100_000, 0, 1_000_000), 1e-9);+ const luna = pricing.priceFor("gpt-5.6-luna").?; // $0.2 / $1.2 / $0.02+ try std.testing.expectApproxEqAbs(@as(f64, 0.02 + 0.002 + 1.2), pricing.usdForUsage(luna, "gpt-5.6-luna", 100_000, 100_000, 0, 1_000_000), 1e-9);}test "grok-4.6 window is 500k and compact-at is 80%" {diff --git a/src/prompt_astra.zig b/src/prompt_astra.zigindex 84ba3adb..13483f9d 100644--- a/src/prompt_astra.zig+++ b/src/prompt_astra.zig@@ -86,7 +86,7 @@ test "Astra guidance follows model switches, child limits and output schemas" {try std.testing.expect(std.mem.indexOf(u8, child, "A JSON output schema is enforced") != null);agent.output_schema = null;agent.sub = false;- for ([_][]const u8{ "gpt-5.6", "gemini-3.7-flash", "gpt-6-astraish" }) |model| {+ for ([_][]const u8{ "gpt-5.5", "gemini-3.7-flash", "gpt-6-astraish" }) |model| { // gpt-5.6 has its own note (prompt_guidance.zig)agent.provider.model = model;try std.testing.expectEqualStrings("BASE", try compose(&agent));}diff --git a/src/prompt_guidance.zig b/src/prompt_guidance.zignew file mode 100644index 00000000..9cb9e2e7--- /dev/null+++ b/src/prompt_guidance.zig@@ -0,0 +1,104 @@+//! Per-model working guidance, composed at request time (schemaAwarePrompt)+//! so a model switch cannot leave another model's note on the prompt. API+//! features stay in the wire layer; this is only behavior the model must own.+//!+//! GPT-5.6 (sol / terra / luna, the bare `gpt-5.6` alias, gateway `openai/`+//! names): the note follows OpenAI's GPT-5.6 prompting guide. The model is+//! proactive across multi-step work and more concise by default than 5.5, so+//! the note states the autonomy/approval boundary ONCE, names the safe local+//! actions, and adds no brevity rule — repeating "ask first" makes it over-ask,+//! and stacked "be concise" lines cut detail the user wanted. Length control+//! belongs to `text.verbosity`, not to more prose here.+const std = @import("std");+const Agent = @import("agent.zig").Agent;++const gpt56 =+ \\+ \\# GPT-5.6 working guidance+ \\For requests to answer, explain, review, diagnose, or plan: inspect the+ \\relevant material and report; do not implement changes unless the request+ \\also asks for them. For requests to change, build, or fix: make the in-scope+ \\local changes and run relevant non-destructive validation without asking.+ \\Reading files, inspecting logs, editing in-scope code, and running tests are+ \\safe local actions. Confirm before external writes, destructive actions, or a+ \\material expansion of scope; the harness's tool approval gates are the only+ \\approval flow — do not invent additional ones.+ \\Before the first tool call of a multi-step task, state the first step in one+ \\or two sentences; afterwards update only when a phase begins or a finding+ \\changes the plan. Finish with the most relevant validation available+ \\(targeted tests, lint or type checks, a build); if it cannot run, say why and+ \\name the next best check.+;++/// Bare model name, without a gateway vendor prefix (`openai/gpt-5.6-luna`).+fn bareName(model: []const u8) []const u8 {+ return model[if (std.mem.lastIndexOfScalar(u8, model, '/')) |i| i + 1 else 0..];+}++pub fn isGpt56(model: []const u8) bool {+ const bare = bareName(model);+ return std.mem.eql(u8, bare, "gpt-5.6") or std.mem.startsWith(u8, bare, "gpt-5.6-");+}++/// Compose `base` plus the note for the agent's current model, if it has one.+pub fn append(self: *Agent, base: []const u8) ![]const u8 {+ if (isGpt56(self.provider.model)) return std.mem.concat(self.scratchAlloc(), u8, &.{ base, "\n", gpt56 });+ return @import("prompt_astra.zig").append(self, base);+}++test {+ _ = @import("prompt_astra.zig");+}++test "GPT-5.6 guidance follows the model on every Responses route, and only that family" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const arena = state.allocator();+ var agent: Agent = .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5.6", .context = 1_050_000 },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "",+ .out = null,+ .sys_normal = "BASE",+ };+ const compose = @import("agent_request_body_responses.zig").schemaAwarePrompt;+ const routes = [_]struct { id: []const u8, model: []const u8 }{+ .{ .id = "openai", .model = "gpt-5.6" },+ .{ .id = "openai", .model = "gpt-5.6-terra" },+ .{ .id = "openai", .model = "gpt-5.6-luna" },+ .{ .id = "codex", .model = "gpt-5.6-sol" },+ .{ .id = "codegraff", .model = "openai/gpt-5.6-sol" },+ };+ for (routes) |r| {+ agent.provider.id = r.id;+ agent.provider.model = r.model;+ const result = try compose(&agent);+ try std.testing.expect(std.mem.startsWith(u8, result, "BASE\n"));+ try std.testing.expect(std.mem.indexOf(u8, result, "# GPT-5.6 working guidance") != null);+ // Stated once: the approval boundary appears a single time, and no+ // brevity instruction rides along (the model is already concise).+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, result, "Confirm before"));+ try std.testing.expect(std.mem.indexOf(u8, result, "concise") == null);+ try std.testing.expect(std.mem.indexOf(u8, result, "# Astra working guidance") == null);+ }+ // The schema line still lands after the note.+ agent.output_schema = "{\"type\":\"object\"}";+ const schema = try compose(&agent);+ try std.testing.expect(std.mem.indexOf(u8, schema, "# GPT-5.6 working guidance") != null);+ try std.testing.expect(std.mem.indexOf(u8, schema, "A JSON output schema is enforced") != null);+ agent.output_schema = null;+ // Not the family: GPT-5.5, GPT-6 Astra (its own note), other vendors.+ for ([_][]const u8{ "gpt-5.5", "gpt-5.4-mini", "grok-4.6", "claude-sonnet-5", "gpt-6-astra" }) |model| {+ agent.provider.id = "openai";+ agent.provider.model = model;+ const result = try compose(&agent);+ try std.testing.expect(std.mem.indexOf(u8, result, "# GPT-5.6 working guidance") == null);+ }+ try std.testing.expect(isGpt56("openai/gpt-5.6-luna"));+ try std.testing.expect(!isGpt56("gpt-5.65"));+}diff --git a/src/prompts.zig b/src/prompts.zigindex 4bcf787e..0f230f7c 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -470,7 +470,7 @@ pub const sub_system_prompt =\\questions — make reasonable assumptions. Do not narrate tool calls.\\Your final message is returned verbatim to the orchestrator: a concise\\report of the concrete facts you found.-++ parallel_tools_note ++ text.public_write_note ++ text.constraint_authority_note ++ text.publication_ready_note;+++ @import("subagent_brief.zig").report_shape_note ++ parallel_tools_note ++ text.public_write_note ++ text.constraint_authority_note ++ text.publication_ready_note;pub const compact_instruction =\\Summarize this entire conversation for a context handoff. Capture: thediff --git a/src/readline.zig b/src/readline.zigindex ab01cb40..2e5d211c 100644--- a/src/readline.zig+++ b/src/readline.zig@@ -52,7 +52,7 @@ const session = @import("session.zig");const Agent = agent_mod.Agent;const saveSession = session.saveSession;const shutdown_trace = @import("shutdown_trace.zig"); // #364: the quit path's first phase stamp-const peer_idle = @import("peer_idle.zig");+const idle_wake = @import("idle_wake_sources.zig");const rl_history = @import("readline_history.zig");const HistoryNav = rl_history.HistoryNav;const PasteStore = @import("readline_paste.zig").Store;@@ -193,7 +193,7 @@ pub fn readLine(const idle_ms: i32 = if (@import("presence_accord.zig").enabled()) 50 else 200;while (!inputPendingTimed(idle_ms)) {var wake_buf: [512]u8 = undefined;- if (peer_idle.takeIdleWake(root.io, &wake_buf)) |wake| {+ if (idle_wake.takeIdleWake(root.io, root.session_name, &wake_buf)) |wake| {buf.appendSlice(gpa, wake) catch break;try out.writeAll("\r\n");try out.flush();diff --git a/src/schema_agents.zig b/src/schema_agents.zigindex 1fcd2b95..0d3097bb 100644--- a/src/schema_agents.zig+++ b/src/schema_agents.zig@@ -3,9 +3,9 @@ const ToolSpec = @import("schema.zig").ToolSpec;pub const subagent_spec = ToolSpec{.name = "subagent",- .desc = "Delegate a self-contained sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Interactive REPL calls return an id and release the prompt; completion wakes the parent. Headless calls return the report unless run_in_background=true. Call several times for disjoint parallel slices. Keep the critical-path next step local. Prefer code changes with disjoint write sets. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. Use agent_message for feedback and agent_output for results. Do not poll; headless agent_output(wait_ms>0) waits for completion.",+ .desc = "Delegate a self-contained sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Interactive REPL calls return an id and release the prompt; completion wakes the parent. Headless calls return the report unless run_in_background=true. Call several times for disjoint parallel slices. Keep the critical-path next step local. Prefer code changes with disjoint write sets. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. Use agent_message for feedback and agent_output for results. Do not poll; headless agent_output(wait_ms>0) waits for completion. Brief once, in order: context (repo, rules file, hard limits), prompt (numbered steps, search hints), established_facts (paths, lines, findings you already have), scope (what not to do), deliverable (report shape).",.schema =- \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; auto-removed if clean with no unique commits, kept + reported otherwise). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "The task: numbered concrete steps with search hints (symbol names, file names, strings). Self-contained \u2014 the child has none of your context beyond the fields of this call."}, "context": {"type": "string", "description": "Optional: repo/context header \u2014 what the repo is, the rules file to read first, hard constraints (file-size limits, no commit/push, leave unrelated uncommitted work alone). Rendered first. The harness itself prepends the working directory, instructions file, disabled tools and pre-tool hooks; do not repeat those."}, "established_facts": {"type": "string", "description": "Optional: what you already learned and the child must not re-derive \u2014 file paths, line numbers, observed behavior, prior findings. Rendered after the task."}, "scope": {"type": "string", "description": "Optional: what NOT to do, what to skip and merely report if it would balloon, and that deliberately skipped items must be reported."}, "deliverable": {"type": "string", "description": "Optional: the exact shape of the final report \u2014 sections, what to cite, what to leave out (local paths, ids). Omitted: the child reports files changed, verified, skipped, open questions."}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence \u2014 beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider \u2014 except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name \u2014 frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login \u2192 the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Optional: reasoning effort for THIS child \u2014 beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: independent / fan-out children default to \"worktree\" (own branch + checkout; auto-removed if clean with no unique commits, kept + reported otherwise). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]},};diff --git a/src/session_run.zig b/src/session_run.zigindex 6b8b4e7b..af8fd422 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -131,7 +131,10 @@ pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *try finalizeSession(gpa, final_io, arena, out, root, json_mode);return true;}- if (try @import("acp.zig").runAcpCommand(gpa, io, environ_map, root, keys, client, in, out, arena, flags)) return true;+ if (try @import("acp.zig").runAcpCommand(gpa, io, environ_map, root, keys, client, in, out, arena, flags)) {+ try finalizeSession(gpa, final_io, arena, out, root, json_mode);+ return true;+ }if (try tui_launch.maybeRun(gpa, io, environ_map, root, keys, client, arena, flags, json_mode, cwd)) {try finalizeSession(gpa, final_io, arena, out, root, json_mode);return true;@@ -491,7 +494,7 @@ pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer// before the per-turn checkpoint) so a worktree never quits with work left// uncommitted on its scratch branch.jobs.worktreeAutoCommit(gpa, io, "wip: session end");- try out.writeAll("\n");+ if (!json_mode) try out.writeAll("\n"); // TTY restore; ACP's writer is JSON-RPCtry out.flush();}diff --git a/src/subagent.zig b/src/subagent.zigindex 44a6f25a..35b7675d 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -50,14 +50,17 @@ const orch_rows = @import("orchestration_rows.zig"); // #290: a scored tournamen/// instead registers the spawn and returns immediately — see/// spawnSubBackground below.const spawn_gate = @import("subagent_spawn.zig");+const subagent_brief = @import("subagent_brief.zig"); // the structured delegation brief (sections + harness environment header)pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {const obj = tools.json_args.object(input) orelse return .{ .text = try ctx.gpa.dupe(u8, "subagent: arguments must be a JSON object with a \"prompt\" string"), .is_error = true };const label = tools.json_args.str(obj, "description") orelse "subagent";- const prompt = tools.json_args.str(obj, "prompt") orelse "";- if (prompt.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "subagent: missing required \"prompt\" (a self-contained task)"), .is_error = true };- if (spawn_gate.refuse(ctx.from_sub, label, prompt, g_agent_jobs.active)) |why|+ const task = tools.json_args.str(obj, "prompt") orelse "";+ if (task.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "subagent: missing required \"prompt\" (a self-contained task)"), .is_error = true };+ if (spawn_gate.refuse(ctx.from_sub, label, task, g_agent_jobs.active)) |why|return .{ .text = try ctx.gpa.dupe(u8, why), .is_error = true };+ const prompt = try subagent_brief.compose(ctx.gpa, obj, task); // context/established_facts/scope/deliverable around the task in a fixed order; a bare prompt is unchanged+ defer ctx.gpa.free(prompt); // spawnSubBackground dupes it and rebases `ask` onto its copy; the sync path is done with it once flagReport returnsconst sys_override = fleet.resolveOverride(obj);const niche = fleet.resolveNiche(obj);const isolation = fleet.resolveIsolation(obj);diff --git a/src/subagent_brief.zig b/src/subagent_brief.zignew file mode 100644index 00000000..46a3f540--- /dev/null+++ b/src/subagent_brief.zig@@ -0,0 +1,307 @@+//! The delegation brief a child receives. Two halves, one fixed order:+//!+//! 1. The ENVIRONMENT header the harness already knows and no parent should+//! have to type: working directory, the project-instructions file to read+//! first, tools this session disabled, pre-tool hooks that may refuse a+//! call. `withEnvironment` prepends it on every spawn path that runs+//! through subagent_run.runSub (subagent, workflow task, workflow retry) —+//! the judge ranks handed excerpts and is left alone.+//! 2. The PARENT's structured sections from the `subagent` tool call —+//! context, task, established facts, scope, deliverable — rendered by+//! `render` with one heading each, empty ones omitted. A call that passes+//! only `prompt` renders byte-identically to that prompt, so the plain+//! string path is unchanged.+//!+//! Composed in the child's first USER message, not its system prompt: the+//! sections vary per spawn, and the system prompt stays a stable cache prefix.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const json_args = @import("json_args.zig");+const no_local_tools = @import("no_local_tools.zig");+const hooks_mod = @import("hooks.zig");++/// The structured fields of one `subagent` call, in render order. `task` is+/// the required `prompt`; the rest are optional and trimmed before use.+pub const Sections = struct {+ context: ?[]const u8 = null,+ task: []const u8,+ established_facts: ?[]const u8 = null,+ scope: ?[]const u8 = null,+ deliverable: ?[]const u8 = null,++ /// Read the optional sections off the tool-call object; `task` is the+ /// already-validated prompt the caller extracted.+ pub fn fromArgs(obj: std.json.ObjectMap, task: []const u8) Sections {+ return .{+ .context = json_args.str(obj, "context"),+ .task = task,+ .established_facts = json_args.str(obj, "established_facts"),+ .scope = json_args.str(obj, "scope"),+ .deliverable = json_args.str(obj, "deliverable"),+ };+ }++ /// Did the parent fill any section beyond the task itself?+ pub fn structured(self: Sections) bool {+ return present(self.context) or present(self.established_facts) or present(self.scope) or present(self.deliverable);+ }+};++fn present(s: ?[]const u8) bool {+ const v = s orelse return false;+ return std.mem.trim(u8, v, &std.ascii.whitespace).len > 0;+}++pub const heading_context = "## Context";+pub const heading_task = "## Task";+pub const heading_established = "## Established (do not re-derive)";+pub const heading_scope = "## Scope";+pub const heading_deliverable = "## Deliverable";++fn section(w: *Io.Writer, heading: []const u8, body: ?[]const u8, first: *bool) !void {+ const v = body orelse return;+ const t = std.mem.trim(u8, v, &std.ascii.whitespace);+ if (t.len == 0) return;+ if (!first.*) try w.writeAll("\n\n");+ first.* = false;+ try w.print("{s}\n{s}", .{ heading, t });+}++/// The parent's brief as one string. Always an owned copy (the caller frees):+/// a plain task comes back byte-identical, a structured one as headed+/// sections in the fixed order, empties skipped.+pub fn render(alloc: Allocator, s: Sections) ![]u8 {+ if (!s.structured()) return alloc.dupe(u8, s.task);+ var aw: Io.Writer.Allocating = .init(alloc);+ errdefer aw.deinit();+ var first = true;+ try section(&aw.writer, heading_context, s.context, &first);+ try section(&aw.writer, heading_task, s.task, &first);+ try section(&aw.writer, heading_established, s.established_facts, &first);+ try section(&aw.writer, heading_scope, s.scope, &first);+ try section(&aw.writer, heading_deliverable, s.deliverable, &first);+ return aw.toOwnedSlice();+}++/// execSubagent's one call: the structured fields of `obj` around `task`.+pub fn compose(alloc: Allocator, obj: std.json.ObjectMap, task: []const u8) ![]u8 {+ return render(alloc, Sections.fromArgs(obj, task));+}++/// Appended to the child's system prompt: the report shape a parent gets when+/// its brief named no deliverable, so every child answers in the same frame.+pub const report_shape_note =+ \\ When the brief names no deliverable, report in this order: files changed+ \\(one line each, with why), verified (what you ran and saw), skipped (and+ \\why), open questions. State what the brief asked for and nothing else.+;++/// One pre-tool hook the child's calls will pass through.+pub const Guard = struct {+ match: []const u8,+ suggest: []const u8 = "",+};++/// What the harness knows about the child's environment. Every field empty+/// renders to "" — a bare session adds nothing to the brief.+pub const Env = struct {+ cwd: []const u8 = "",+ instructions_file: ?[]const u8 = null,+ disabled_tools: []const []const u8 = &.{},+ pre_tool_hooks: []const Guard = &.{},++ pub fn empty(self: Env) bool {+ return self.cwd.len == 0 and self.instructions_file == null and self.disabled_tools.len == 0 and self.pre_tool_hooks.len == 0;+ }+};++pub const env_heading = "[environment — stated by the harness, not the parent]";++/// The environment header, or "" when there is nothing to say.+pub fn renderEnv(alloc: Allocator, env: Env) ![]u8 {+ if (env.empty()) return alloc.dupe(u8, "");+ var aw: Io.Writer.Allocating = .init(alloc);+ errdefer aw.deinit();+ const w = &aw.writer;+ try w.writeAll(env_heading);+ if (env.cwd.len > 0) try w.print("\nworking directory: {s}", .{env.cwd});+ if (env.instructions_file) |f| try w.print("\nproject instructions: {s} in the working directory — read it first; its rules bind you too", .{f});+ if (env.disabled_tools.len > 0) {+ try w.writeAll("\ndisabled tools this session (do not call them): ");+ for (env.disabled_tools, 0..) |name, i| {+ if (i > 0) try w.writeAll(", ");+ try w.writeAll(name);+ }+ }+ for (env.pre_tool_hooks) |g| {+ if (std.mem.eql(u8, g.match, "*"))+ try w.writeAll("\npre-tool hook: every tool call may be refused; a refusal returns the hook's message — follow it")+ else+ try w.print("\npre-tool hook may refuse: {s}", .{g.match});+ if (g.suggest.len > 0) try w.print(" (use instead: {s})", .{g.suggest});+ }+ return aw.toOwnedSlice();+}++/// The instructions file the ROOT loaded at startup, if any — same list and+/// order as startup.buildSystemPrompt. `dir` null means the process cwd.+pub fn instructionsFile(io: Io, dir: ?[]const u8) ?[]const u8 {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ for ([_][]const u8{ "AGENTS.md", "HARNESS.md", "CLAUDE.md" }) |fname| {+ const path = if (dir) |d| (std.fmt.bufPrint(&buf, "{s}/{s}", .{ d, fname }) catch continue) else fname;+ if (Io.Dir.cwd().access(io, path, .{})) |_| return fname else |_| {}+ }+ return null;+}++/// Gather the header's facts from the live gates. `cwd_override` is the+/// child's isolated worktree when it has one (Agent.agent_cwd).+pub fn detectEnv(io: Io, arena: Allocator, cwd_override: ?[]const u8) Env {+ var env: Env = .{};+ if (cwd_override) |c| {+ env.cwd = c;+ } else {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ if (std.process.currentPath(io, &buf)) |n| {+ env.cwd = arena.dupe(u8, buf[0..n]) catch "";+ } else |_| {}+ }+ env.instructions_file = instructionsFile(io, cwd_override);+ if (no_local_tools.enabled) {+ var list: std.ArrayList([]const u8) = .empty;+ for (no_local_tools.gated_tools ++ no_local_tools.gated_aliases) |name| {+ if (no_local_tools.blocks(name)) list.append(arena, name) catch break;+ }+ env.disabled_tools = list.items;+ }+ env.pre_tool_hooks = guardsFrom(arena, @import("main.zig").g_hooks.pre_tool);+ return env;+}++pub fn guardsFrom(arena: Allocator, pre_tool: []const hooks_mod.Hook) []const Guard {+ if (pre_tool.len == 0) return &.{};+ const out = arena.alloc(Guard, pre_tool.len) catch return &.{};+ for (pre_tool, out) |h, *g| g.* = .{ .match = h.match, .suggest = h.suggest };+ return out;+}++/// Prepend the environment header to a child's brief. The judge is text-only+/// and ranks handed excerpts, so it gets the prompt untouched; so does any+/// child when the header has nothing to say.+pub fn withEnvironment(io: Io, arena: Allocator, kind: []const u8, cwd_override: ?[]const u8, prompt: []const u8) []const u8 {+ if (std.mem.eql(u8, kind, "judge_task")) return prompt;+ const header = renderEnv(arena, detectEnv(io, arena, cwd_override)) catch return prompt;+ if (header.len == 0) return prompt;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ header, prompt }) catch prompt;+}++// ── tests ──────────────────────────────────────────────────────────────────++fn parseArgs(arena: Allocator, json: []const u8) !std.json.ObjectMap {+ const v = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{});+ return v.object;+}++test "render: a plain prompt passes through byte-identically" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const obj = try parseArgs(arena_state.allocator(), "{\"description\":\"scan\",\"prompt\":\"find the caller of foo\"}");+ const out = try compose(gpa, obj, "find the caller of foo");+ defer gpa.free(out);+ try std.testing.expectEqualStrings("find the caller of foo", out);+ // Whitespace-only optional fields count as absent, not as structure.+ const blank = try parseArgs(arena_state.allocator(), "{\"prompt\":\"x\",\"scope\":\" \",\"deliverable\":\"\"}");+ const out2 = try compose(gpa, blank, "x");+ defer gpa.free(out2);+ try std.testing.expectEqualStrings("x", out2);+}++test "render: sections come out in the fixed order, each under its heading" {+ const gpa = std.testing.allocator;+ const out = try render(gpa, .{+ .deliverable = "files changed; verified; skipped",+ .scope = "do not touch unrelated work",+ .established_facts = "runSub composes the prompt at one call site",+ .task = "1. read it\n2. change it",+ .context = "Zig harness; read AGENTS.md; 600 LOC ceiling",+ });+ defer gpa.free(out);+ const expected =+ "## Context\nZig harness; read AGENTS.md; 600 LOC ceiling\n\n" +++ "## Task\n1. read it\n2. change it\n\n" +++ "## Established (do not re-derive)\nrunSub composes the prompt at one call site\n\n" +++ "## Scope\ndo not touch unrelated work\n\n" +++ "## Deliverable\nfiles changed; verified; skipped";+ try std.testing.expectEqualStrings(expected, out);+}++test "render: empty sections are omitted and values are trimmed" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const obj = try parseArgs(arena_state.allocator(), "{\"prompt\":\" do X \",\"established_facts\":\"\\n A is at line 12\\n\",\"context\":\"\"}");+ const out = try compose(gpa, obj, " do X ");+ defer gpa.free(out);+ try std.testing.expectEqualStrings("## Task\ndo X\n\n## Established (do not re-derive)\nA is at line 12", out);+ try std.testing.expect(std.mem.indexOf(u8, out, heading_context) == null);+ try std.testing.expect(std.mem.indexOf(u8, out, heading_scope) == null);+ try std.testing.expect(std.mem.indexOf(u8, out, heading_deliverable) == null);+}++test "renderEnv: an empty environment adds nothing" {+ const gpa = std.testing.allocator;+ const out = try renderEnv(gpa, .{});+ defer gpa.free(out);+ try std.testing.expectEqualStrings("", out);+}++test "renderEnv: cwd, instructions file, disabled tools and hooks, in that order" {+ const gpa = std.testing.allocator;+ const out = try renderEnv(gpa, .{+ .cwd = "/work/repo",+ .instructions_file = "AGENTS.md",+ .disabled_tools = &.{ "shell", "edit_file" },+ .pre_tool_hooks = &.{ .{ .match = "bash|read_file", .suggest = "zigrep" }, .{ .match = "*" } },+ });+ defer gpa.free(out);+ try std.testing.expect(std.mem.startsWith(u8, out, env_heading));+ const cwd = std.mem.indexOf(u8, out, "working directory: /work/repo").?;+ const instr = std.mem.indexOf(u8, out, "project instructions: AGENTS.md").?;+ const disabled = std.mem.indexOf(u8, out, "disabled tools this session (do not call them): shell, edit_file").?;+ const hook = std.mem.indexOf(u8, out, "pre-tool hook may refuse: bash|read_file (use instead: zigrep)").?;+ const star = std.mem.indexOf(u8, out, "every tool call may be refused").?;+ try std.testing.expect(cwd < instr and instr < disabled and disabled < hook and hook < star);+}++test "withEnvironment: header precedes the brief for workers, never for the judge" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = std.testing.io;+ // The judge ranks handed excerpts: no header, the prompt untouched.+ try std.testing.expectEqualStrings("score this", withEnvironment(io, arena, "judge_task", null, "score this"));+ // A worker with an explicit cwd gets the header first, then a blank line, then its brief.+ const out = withEnvironment(io, arena, "subagent", "/tmp", "## Task\ndo X");+ try std.testing.expect(std.mem.startsWith(u8, out, env_heading));+ try std.testing.expect(std.mem.indexOf(u8, out, "working directory: /tmp") != null);+ try std.testing.expect(std.mem.endsWith(u8, out, "\n\n## Task\ndo X"));+}++test "guardsFrom mirrors the loaded pre-tool hooks; report_shape_note names the four report parts" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const hooks = [_]hooks_mod.Hook{.{ .match = "bash", .command = "./guard.sh", .timeout_ms = 1, .suggest = "shell" }};+ const guards = guardsFrom(arena_state.allocator(), &hooks);+ try std.testing.expectEqual(@as(usize, 1), guards.len);+ try std.testing.expectEqualStrings("bash", guards[0].match);+ try std.testing.expectEqualStrings("shell", guards[0].suggest);+ try std.testing.expectEqual(@as(usize, 0), guardsFrom(arena_state.allocator(), &.{}).len);+ for ([_][]const u8{ "files changed", "verified", "skipped", "open questions" }) |part|+ try std.testing.expect(std.mem.indexOf(u8, report_shape_note, part) != null);+}diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex e5596b62..fdb94d3d 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -28,6 +28,7 @@ const trace = @import("trace.zig");const textMessage = @import("messages.zig").textMessage;const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json eventconst subagent_retry = @import("subagent_retry.zig"); // bounded in-worker re-ask: the failover the root has and a worker did not+const subagent_brief = @import("subagent_brief.zig"); // the harness-stated environment header every worker brief opens withfn guiEmit(io: Io, ev: anytype) void {if (!main_mod.json_mode) return;@@ -353,7 +354,10 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constif (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });// Loop deadline + playbook.rideBrief: every spawn path (subagent, workflow,// retry, judge) injects live constraints here from .graff/playbook.jsonl.- const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io)));+ // subagent_brief.withEnvironment first: the harness states the working+ // directory, instructions file, disabled tools and pre-tool hooks once, so+ // no parent has to (the judge is exempt — it ranks handed excerpts).+ const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, subagent_brief.withEnvironment(ctx.io, arena, kind, agent.agent_cwd, prompt), ctx.loop_deadline_ms, util.unixMs(ctx.io)));try agent.messages.append(try textMessage(arena, "user", task_prompt));defer agent.tools_used.deinit(gpa);// Retry transient failures against the same child history.diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 7b3e5df8..07467449 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -379,4 +379,6 @@ test {_ = @import("edit_worktree_tests.zig"); // #747: edit lands on the selected worktree_ = @import("mcp.zig");_ = @import("mcp_rpc.zig");+ _ = @import("subagent_brief.zig"); // structured delegation brief + harness environment header+ _ = @import("idle_wake_sources.zig"); // shared idle auto-turn sources for REPL / TUI / ACP}diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex c75cc2fe..88ccc310 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -12,23 +12,19 @@ const pricing = @import("pricing.zig");const providers = @import("providers.zig");const process_runner = @import("process_runner.zig");const repl = @import("repl.zig");-const version_status = @import("version_status.zig");-const update_cmd = @import("update_cmd.zig");const repl_bash = @import("repl_bash.zig");const repl_glue = @import("repl_glue.zig");const session = @import("session.zig");const tui = @import("tui");const tui_peer = @import("tui_peer.zig");const tui_constraint = @import("tui_constraint.zig");+const tui_command = @import("tui_command.zig");const tui_session = @import("tui_session.zig");const engine_sink = @import("engine_sink.zig");const tui_sink = @import("tui_sink.zig");const tui_acp = @import("tui_acp.zig");-const job_notify = @import("job_notify.zig");-const peer_idle = @import("peer_idle.zig");+const idle_wake = @import("idle_wake_sources.zig");const job_wait = @import("job_wait.zig");-const schedule = @import("schedule.zig");-const channel_worker = @import("channel_worker.zig");const util = @import("util.zig");const obs = @import("obs.zig");const vision = @import("vision.zig");@@ -161,8 +157,9 @@ pub fn run(.idle_wake_fn = idleWakeCb,.peer_fn = tui_peer.peerCb,.constraint_fn = tui_constraint.constraintCb,- .version_fn = versionCb,- .update_fn = updateCb,+ .command_fn = tui_command.commandCb,+ .version_fn = tui_command.versionCb,+ .update_fn = tui_command.updateCb,});try tui_session.syncRoot(&convo, root);}@@ -208,24 +205,10 @@ fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {}}-fn updateCb(ctx: ?*anyopaque, gpa: Allocator, action: []const u8) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- return update_cmd.hostAction(c.io, gpa, c.home, action);-}-fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- if (c.root) |root| if (@import("subagent_interactive.zig").takeWake(c.io, root.session_name, buf)) |t| return t;- if (job_notify.takeIdleWake(c.io, buf)) |t| return t; // an idle stop waits for a real step boundary (#199)- if (schedule.takeWake(c.io, buf)) |t| return t;- if (channel_worker.takeWake(c.io, buf)) |t| return t;- _ = @import("presence_accord.zig").takePing(); // standing link; JSONL is still the drain- return peer_idle.takeIdleWake(c.io, buf);-}--fn versionCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- return version_status.commandText(c.io, gpa, @import("build_options").version) catch null;+ const name = if (c.root) |root| root.session_name else "";+ return idle_wake.takeIdleWake(c.io, name, buf);}/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's@@ -455,6 +438,7 @@ test {_ = tui_acp;_ = repl_bash;_ = tui_peer;+ _ = tui_command;}test "debug HUD names the in-process ACP session" {