graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Stabilize settings and concurrent transport ownership
Rach Pradhan4ea82e6ac7cf
diff --git a/apps/native/components/primitives/ModelEffortButtons.tsx b/apps/native/components/primitives/ModelEffortButtons.tsxindex b4db94cc..507b3179 100644--- a/apps/native/components/primitives/ModelEffortButtons.tsx+++ b/apps/native/components/primitives/ModelEffortButtons.tsx@@ -21,21 +21,29 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMoconst [open, setOpen] = useState(false);const [saving, setSaving] = useState(false);const [error, setError] = useState("");- const savingRef = useRef(false);- const blocked = busy || pending || saving || !onCommand;+ const requestRef = useRef(0);+ const [desired, setDesired] = useState<string | null>(null);+ const blocked = busy || pending || !onCommand;const [position, setPosition] = useState({ left: 0, bottom: 0 });const [draft, setDraft] = useState(0);const panel = useRef<HTMLDivElement>(null);const effortButton = useRef<HTMLButtonElement>(null);const levels = model.effortLevels ?? [];const index = Math.max(0, levels.indexOf(model.effort ?? "medium"));+ const confirmed = useRef(index); confirmed.current = index;const show = () => {const rect = effortButton.current?.getBoundingClientRect();if (rect) setPosition({ left: Math.max(effortPanelMargin, Math.min(window.innerWidth - effortPanelWidth - effortPanelMargin, rect.right - effortPanelWidth)), bottom: window.innerHeight - rect.top + 10 });if (modelOpen) openModel();- setDraft(index); setOpen(true);+ setDraft(Math.max(0, levels.indexOf(desired ?? model.effort ?? "medium"))); setOpen(true);};- useEffect(() => { setDraft(index); }, [index]);+ useEffect(() => {+ if (desired === null) setDraft(index);+ else if (!saving && model.effort === desired) setDesired(null);+ }, [index, model.effort, desired, saving]);+ useEffect(() => {+ requestRef.current++; setDesired(null); setSaving(false); setError(""); setDraft(index);+ }, [model.key]);useEffect(() => {const button = buttonRef.current;const listener = () => show(); button?.addEventListener("graff-effort-open", listener);@@ -49,13 +57,25 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMoreturn () => { document.removeEventListener("pointerdown", dismiss); document.removeEventListener("keydown", escape); };}, [open, buttonRef]);const change = async (command: string) => {- if (blocked || savingRef.current || !onCommand) return;- savingRef.current = true; setSaving(true); setError("");+ if (blocked || !onCommand) return;+ const request = ++requestRef.current;+ if (command.startsWith("/effort ")) {+ const effort = command.slice(8);+ setDesired(effort); setDraft(Math.max(0, levels.indexOf(effort)));+ }+ setSaving(true); setError("");try { await onCommand(command); }- catch (err) { setDraft(index); setError(err instanceof Error ? err.message : "Could not save. Try again."); }- finally { savingRef.current = false; setSaving(false); }+ catch (err) {+ if (request === requestRef.current) {+ setDesired(null); setDraft(confirmed.current);+ setError(err instanceof Error ? err.message : "Could not save. Try again.");+ }+ } finally { if (request === requestRef.current) setSaving(false); }+ };+ const apply = (value: string) => {+ const effort = levels[Number(value)];+ if (effort && effort !== (desired ?? model.effort)) void change(`/effort ${effort}`);};- const apply = () => { if (levels[draft] && levels[draft] !== model.effort) void change(`/effort ${levels[draft]}`); };const progress = levels.length > 1 ? draft / (levels.length - 1) : 0;const displayName = model.name.replace(/^gpt-/i, "GPT-").replace(/-(astra|sol|terra|luna)$/i, (_, name: string) => ` ${name[0].toUpperCase()}${name.slice(1)}`);return <div data-model-controls className={`flex w-full min-w-0 items-center gap-0.5 ${wide ? "col-start-2 row-start-2 justify-self-start" : "col-start-3 row-start-1"}`}>@@ -65,13 +85,13 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo<span className="truncate" title={pending ? `Next message: ${displayName}` : displayName}>{displayName}{pending && <span className="text-ink-3"> · Next</span>}</span><span className="shrink-0"><Chevron /></span></button>{levels.length > 0 && <button ref={effortButton} type="button" aria-label="Select effort" aria-expanded={open} onClick={show}- className="flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs text-ink-3 hover:bg-hover">{labels[model.effort ?? ""] ?? "Effort"}<Chevron /></button>}+ className="flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs text-ink-3 hover:bg-hover">{labels[desired ?? model.effort ?? ""] ?? "Effort"}<Chevron /></button>}{model.key && levels.length === 0 && <span className="shrink-0 px-2 text-xs text-ink-3" title={model.effortLevels ? "This model does not offer configurable reasoning effort." : "Reasoning settings will appear after this model's capabilities are loaded."}>{model.effortLevels ? "Fixed reasoning" : "Reasoning pending"}</span>}{showContextMeter && <ContextMeter reading={contextMeter} />}{open && createPortal(<div ref={panel} role="dialog" aria-label="Reasoning effort" style={{ ...position, width: effortPanelWidth }}className="motion-surface fixed z-[100] max-w-[calc(100vw-24px)] rounded-window border border-line bg-page px-2 pb-[7px] pt-1.5 text-ink shadow-[0_8px_24px_-8px_rgb(0_0_0/18%)]"><div className="flex h-[25px] items-center justify-between gap-1.5">- <button type="button" aria-label="Fast mode" aria-pressed={!!model.fast} disabled={blocked || !model.fastSupported}+ <button type="button" aria-label="Fast mode" aria-pressed={!!model.fast} disabled={blocked || saving || !model.fastSupported}title={model.fastSupported ? "Priority service for lower latency; may use more of your allowance" : "Fast mode is available for Codex models"}onClick={() => void change(`/fast ${model.fast ? "off" : "on"}`)}className={`flex size-5 shrink-0 items-center justify-center rounded-full transition-colors disabled:opacity-30 [&_svg]:size-3.5 ${model.fast ? "bg-accent-tint text-accent" : "text-ink-3 hover:bg-hover"}`}><Bolt filled={!!model.fast} /></button>@@ -82,7 +102,7 @@ export default function ModelEffortButtons({ model, buttonRef, modelOpen, openMo<div aria-hidden="true" className={styles.track}><div className={styles.fill} style={{ width: draft === 0 ? 0 : `calc(10px + (100% - 20px) * ${progress})` }} /></div><div aria-hidden="true" className={styles.stops}>{levels.map((level, i) => <span key={level} className={`${styles.stop} ${i < draft ? styles.passed : ""}`} style={{ left: `${i / Math.max(1, levels.length - 1) * 100}%` }} />)}</div><input type="range" aria-label="Reasoning effort level" aria-valuetext={labels[levels[draft]] ?? levels[draft]} min={0} max={Math.max(0, levels.length - 1)} step={1} value={draft} disabled={blocked}- onChange={event => setDraft(Number(event.target.value))} onPointerUp={apply} onKeyUp={apply}+ onChange={event => setDraft(Number(event.target.value))} onPointerUp={event => apply(event.currentTarget.value)} onKeyUp={event => apply(event.currentTarget.value)}className={styles.range} /></div>{error && <p role="alert" className="mt-2 text-xs text-red">{error}</p>}diff --git a/apps/native/components/site/useQuietSettings.ts b/apps/native/components/site/useQuietSettings.tsindex 9e66d0c1..6bbd463f 100644--- a/apps/native/components/site/useQuietSettings.ts+++ b/apps/native/components/site/useQuietSettings.ts@@ -20,7 +20,7 @@ export function useQuietSettings(options: {// Graff handles these commands before the model loop and session history.// Consume the confirmation without creating a conversation turn.for await (const _ of prompt(options.handleOf(id), session, command)) { /* drain */ }- const catalog = await fetchModels(options.handleOf(id));+ const catalog = await fetchModels(options.handleOf(id), undefined, false);const selected = catalog.models.find(model => model.key === catalog.current);const [setting, value] = command.slice(1).split(" ");if (setting === "effort" ? selected?.effort !== value : selected?.fast !== (value === "on")) throw Error("Graff did not apply this setting. Try again.");diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex cea11406..dc939700 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -242,8 +242,8 @@ type GraffModelsResult = {* with live credentials, already in the agent's election order. The same* model name can be served by several providers; the highest-ranked seat* wins its row (spawn-by-name resolves through graff's own routing anyway). */-export async function fetchModels(chat?: ChatHandle, root?: string): Promise<{ models: ModelChoice[]; current: string | null; commands?: AcpCommand[] }> {- const res = chat ? await rpc(chat, "graff/models") : await fetch(`/api/models?${new URLSearchParams(root ? { root } : {})}`, { cache: "no-store" });+export async function fetchModels(chat?: ChatHandle, root?: string, refresh = true): Promise<{ models: ModelChoice[]; current: string | null; commands?: AcpCommand[] }> {+ const res = chat ? await rpc(chat, "graff/models", { refresh }) : await fetch(`/api/models?${new URLSearchParams(root ? { root } : {})}`, { cache: "no-store" });const body = (await res.json()) as { result?: GraffModelsResult; error?: string };if (!body.result) throw new Error(body.error ?? "graff/models failed");return modelChoices(body.result);diff --git a/apps/native/scripts/test-model-catalog.mjs b/apps/native/scripts/test-model-catalog.mjsindex cc0cc916..7b8ffb9a 100644--- a/apps/native/scripts/test-model-catalog.mjs+++ b/apps/native/scripts/test-model-catalog.mjs@@ -55,6 +55,7 @@ try {await page.keyboard.press('Escape');};await setEffort('End');+ await checkEffortTransitions(page);await page.waitForFunction(() => document.querySelector('[aria-label="Select effort"]')?.textContent?.includes('High'));const first = await page.locator('[data-tab-id]').first().getAttribute('data-tab-id');await page.getByRole('button', { name: 'New chat', exact: true }).click();@@ -66,6 +67,17 @@ try {await page.waitForFunction(() => document.querySelector('[aria-label="Select effort"]')?.textContent?.includes('High'));await page.locator(`[data-tab-id="${second}"]`).click();await page.waitForFunction(() => document.querySelector('[aria-label="Select effort"]')?.textContent?.includes('Light'));+ await page.evaluate(() => { window.holdEffort = true; });+ await effort.click(); await page.getByRole('slider', { name: 'Reasoning effort level' }).press('ArrowRight');+ await page.waitForFunction(() => window.effortReplies.length === 1);+ await page.keyboard.press('Escape'); await page.locator(`[data-tab-id="${first}"]`).click();+ assert.match(await effort.innerText(), /High/);+ await page.evaluate(() => window.effortReplies.shift()(false));+ await page.locator(`[data-tab-id="${second}"]`).click();+ await page.waitForFunction(() => document.querySelector('[aria-label="Select effort"]')?.textContent?.includes('Medium'));+ await page.locator(`[data-tab-id="${first}"]`).click(); assert.match(await effort.innerText(), /High/);+ await page.locator(`[data-tab-id="${second}"]`).click();+ await page.evaluate(() => { window.holdEffort = false; }); await setEffort('Home');const composer = page.getByRole('textbox', { name: 'Prompt', exact: true });await composer.fill('hold fixture'); await composer.press('Enter');await page.waitForFunction(() => typeof window.finishCatalogTurn === 'function');@@ -87,12 +99,59 @@ try {console.log('Model catalog UI: retry, capability refresh, per-chat effort, and queued next-model selection passed');} finally { await browser.close(); server?.kill('SIGTERM'); }+async function checkEffortTransitions(page) {+ const effort = page.getByRole('button', { name: 'Select effort', exact: true });+ const range = page.getByRole('slider', { name: 'Reasoning effort level' });+ const resets = () => page.evaluate(() => window.catalogCalls.filter(call => ['bootstrap', 'session/cancel'].includes(call.method)).length);+ const before = await resets();+ await page.evaluate(() => { window.holdEffort = true; });+ await effort.click(); await range.press('Home');+ await page.waitForFunction(() => window.effortReplies.length === 1);+ const stable = async (name, value) => {+ const frames = await page.evaluate(async () => {+ const samples = [];+ for (let i = 0; i < 8; i++) {+ await new Promise(requestAnimationFrame);+ const input = document.querySelector('[aria-label="Reasoning effort level"]');+ samples.push({ label: document.querySelector('[aria-label="Select effort"]')?.textContent, value: input?.value, disabled: input?.disabled, opacity: input ? getComputedStyle(input.parentElement).opacity : null });+ }+ return samples;+ });+ for (const frame of frames) {+ assert.ok(frame.label.includes(name), JSON.stringify(frame));+ assert.equal(frame.value, value); assert.equal(frame.disabled, false); assert.equal(frame.opacity, '1');+ }+ };+ await stable('Light', '0');+ await page.keyboard.press('Escape'); await effort.click();+ await stable('Light', '0');+ await range.press('End');+ await stable('High', '2');+ await page.evaluate(() => window.effortReplies.shift()(false));+ await page.waitForFunction(() => window.effortReplies.length === 1);+ await stable('High', '2');+ await page.evaluate(() => window.effortReplies.shift()(true));+ await page.getByRole('alert').filter({ hasText: 'fixture rejected' }).waitFor();+ await stable('Light', '0');+ await range.press('End');+ await page.waitForFunction(() => window.effortReplies.length === 1);+ await stable('High', '2');+ await page.evaluate(() => window.effortReplies.shift()(false));+ await page.waitForFunction(() => !document.querySelector('[role="status"]')?.textContent?.includes('Saving'));+ await page.keyboard.press('Escape'); await effort.click(); await stable('High', '2');+ await page.keyboard.press('Escape');+ await page.evaluate(() => { window.holdEffort = false; });+ assert.equal(await resets(), before, 'Effort changes must not restart or cancel the chat');+ assert.equal(await page.evaluate(() => window.catalogCalls.findLast(call => call.method === 'graff/models')?.params?.refresh), false, 'Confirmation must skip provider discovery');+}+function installCatalogFixture() {const fallback = window.fetch;let fail = true;const chats = new Map();window.catalogCalls = [];window.catalogReads = 0;+ window.effortReplies = [];const json = body => new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });const catalog = state => ({ result: {models: ['gpt-astra', 'gpt-sol'].map(name => ({ name, provider: 'codex', authenticated: true, context: 1000, cost: 'plan', current: name === state.model, effortLevels: ['low', 'medium', 'high'] })),@@ -121,6 +180,10 @@ function installCatalogFixture() {controller.enqueue(encode({ jsonrpc: '2.0', method: 'session/update', params: { update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Still working' } } } }));window.finishCatalogTurn = () => { controller.enqueue(encode({ jsonrpc: '2.0', id: 1, result: { stopReason: 'end_turn' } })); controller.close(); delete window.finishCatalogTurn; };} }));+ if (text.startsWith('/effort ') && window.holdEffort) {+ const rejected = await new Promise(resolve => window.effortReplies.push(resolve));+ if (rejected) return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32000, message: 'fixture rejected' } }) + '\n');+ }if (text.startsWith('/effort ')) chats.get(body.chat).effort = text.split(' ')[1];return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { stopReason: 'end_turn' } }) + '\n');}diff --git a/docs/adr/0159-picker-catalog-refresh-is-bounded.md b/docs/adr/0159-picker-catalog-refresh-is-bounded.mdindex 9e68c9dc..34164b43 100644--- a/docs/adr/0159-picker-catalog-refresh-is-bounded.md+++ b/docs/adr/0159-picker-catalog-refresh-is-bounded.md@@ -15,7 +15,9 @@ gateway catalog using existing credentials. Limit the request to 500 ms and2 MiB, and retry no more than once per 30 seconds in a harness process.Replace only that provider's rows after a successful, nonempty parse. Keepthe previous catalog after transport errors, bad responses, or timeout.-Catalog refresh does not change the selected provider or model.+Catalog refresh does not change the selected provider or model. Setting+confirmations request local state with `refresh: false` so they do not wait+for unrelated provider discovery; initial and picker-open requests refresh.Other providers retain local cache hydration. The explicit full catalogrefresh command remains the way to refresh all providers.diff --git a/docs/adr/0161-default-model-stays-on-selected-provider.md b/docs/adr/0161-default-model-stays-on-selected-provider.mdnew file mode 100644index 00000000..bedcb43e--- /dev/null+++ b/docs/adr/0161-default-model-stays-on-selected-provider.md@@ -0,0 +1,19 @@+# 0161. Default model stays on the selected provider++Status: accepted 2026-09-23++## Decision++A release's preferred default is eligible only on a provider whose catalog+advertises it. Preserve credential selection precedence and explicit model+choices, including saved sessions. Updating a model preference must not+silently move a user onto a different billing route.++The bundled gateway catalog and its startup default move together after+checking the published catalog. Providers without that model retain their+existing defaults. Picker ordering remains governed by ADR 0017.++## Validation++Pricing and provider tests cover supported routes, unsupported routes,+explicit model selection, and direct-credential precedence over the gateway.diff --git a/docs/adr/0162-http2-streams-own-exclusive-sessions.md b/docs/adr/0162-http2-streams-own-exclusive-sessions.mdnew file mode 100644index 00000000..839adfd8--- /dev/null+++ b/docs/adr/0162-http2-streams-own-exclusive-sessions.md@@ -0,0 +1,31 @@+# 0162. HTTP/2 streams own exclusive sessions++Status: accepted 2026-09-23++## Context++The HTTP/2 connection reader is sequential, not a stream multiplexer. Returning+one shared mutable session after unlocking the pool allowed concurrent parent+and child requests to read each other's frames. Switching origins or cancelling+one request could also close another request's active session.++## Decision++The process pool holds at most one idle session. A request removes that session+under the pool mutex and owns an exclusive lease until its stream is destroyed.+Concurrent requests dial independent sessions outside the mutex. Only a stream+that reached END_STREAM can return its session to an empty idle slot; failed,+cancelled, or surplus sessions close through their own leases.++## Consequences++Sequential requests retain connection reuse. Concurrent requests pay for+separate connections rather than serialize behind long streams. Cancellation+cannot invalidate another request's connection. True HTTP/2 multiplexing would+require a connection-owned reader and per-stream dispatch before relaxing this+ownership rule.++The local TLS integration test gates responses on simultaneous parent and+background-child requests, while unit tests cover lease ownership and release.+This corrects a demonstrated transport hazard; it does not establish the cause+of a separately reported resolver crash.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex a7f59c72..8a2d4888 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -184,6 +184,9 @@ record only when you need the evidence or the edge cases.| [0159](0159-picker-catalog-refresh-is-bounded.md) | Opening a model surface refreshes only the gateway catalog, with a short deadline and the existing snapshot as fallback. || [0160](0160-model-picks-wait-for-next-prompt.md) | Running model picks stay per chat and apply only at the next prompt boundary without cancelling the current response. |+| [0161](0161-default-model-stays-on-selected-provider.md) | Default model preferences stay on the selected provider; explicit and saved choices win. |++| [0162](0162-http2-streams-own-exclusive-sessions.md) | HTTP/2 requests exclusively lease active sessions; the process pool owns only one idle connection. |## When to write onediff --git a/docs/interactive-workflow-tests.md b/docs/interactive-workflow-tests.mdindex eab71809..7a0d7dad 100644--- a/docs/interactive-workflow-tests.md+++ b/docs/interactive-workflow-tests.md@@ -45,8 +45,10 @@ OpenSSL, and the fetched dependencies. The local provider requires TLS withHTTP/2 and exercises streamed ACP updates, a follow-up on the same connection,and flow control in both directions. A stalled response is cancelled throughACP, must return `stopReason: "cancelled"`, and must release its stream before-another prompt succeeds on the same ACP session. Untrusted certificates and-mismatched hostnames must fail before a provider request is accepted.+another prompt succeeds on the same ACP session. A background child and its+parent must both reach the provider before either response completes, with+independent HTTP/2 transports. Untrusted certificates and mismatched hostnames+must fail before a provider request is accepted.The test verifies the pinned dependency's content hash, then builds a temporaryharness with one additive test-CA load in a private dependency copy. Systemdiff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex c6f8542a..67e6d3b1 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -110,7 +110,7 @@{"id":"review-checkpoint-preserves-unfinished-scope","why":"#306: a long read-only review requests an evidence checkpoint without forcing completion or granting edits.","args":["--old"],"prompt_options":{"type":"review"},"prompt":"Review target.txt without modifying it.","workspace_seed":{"target.txt":"original\n"},"script":[{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"tool":"read_file","arguments":{"path":"target.txt"}},{"text":"No findings. Review finished."}],"assert":[{"events_at_least":{"match":{"type":"review_checkpoint","complete":false},"count":1}},{"events_at_most":{"match":{"type":"review_checkpoint"},"count":1}},{"request_contains":{"text":"Review checkpoint:"}},{"request_contains":{"text":"next inspection tool call"}},{"file_equals":{"path":"target.txt","content":"original\n"}},{"final_text_contains":"No findings. Review finished."}]}{"id": "same-turn-two-writes-land", "why": "Two write_file calls in one assistant message must both land. Serial mutating batches must not drop the second write; parallel must not race-lose it either.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "create a.txt and b.txt", "script": [{"tools": [{"tool": "write_file", "arguments": {"path": "a.txt", "content": "alpha\n"}}, {"tool": "write_file", "arguments": {"path": "b.txt", "content": "beta\n"}}]}, {"tool": "bash", "arguments": {"command": "grep -qx alpha a.txt && grep -qx beta b.txt && echo BOTH_LANDED"}}, {"text": "both files are in"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "write_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"event": {"type": "tool_result", "name": "bash", "text": "BOTH_LANDED\n"}}, {"final_text_contains": "both files are in"}]}{"id": "same-turn-write-then-edit-same-file", "why": "write_file then edit_file on the same path in one assistant message used to race (#337). Serial batches make the edit see the write; a lost race fails old_string or missing file.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "create n.txt then change v1 to v2", "script": [{"tools": [{"tool": "write_file", "arguments": {"path": "n.txt", "content": "v1\n"}}, {"tool": "edit_file", "arguments": {"path": "n.txt", "old_string": "v1", "new_string": "v2"}}]}, {"tool": "bash", "arguments": {"command": "grep -qx v2 n.txt && echo EDIT_SAW_WRITE"}}, {"text": "the file now says v2"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"event": {"type": "tool_call", "name": "edit_file"}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"event": {"type": "tool_result", "name": "bash", "text": "EDIT_SAW_WRITE\n"}}, {"final_text_contains": "v2"}]}-{"id": "parallel-fast-shell-batch-resumes", "why": "#1166: several fast shell calls in one batch must each return once, then the next model step must run. A heap trap after reaping used to kill the process before the second request.", "args": [], "prompt": "run the three checks", "script": [{"tools": [{"tool": "bash", "arguments": {"command": "printf AAA"}}, {"tool": "bash", "arguments": {"command": "printf BBBBB"}}, {"tool": "bash", "arguments": {"command": "printf CCCCCCC"}}]}, {"text": "all three checks returned"}], "assert": [{"events_at_least": {"match": {"type": "tool_result", "name": "bash"}, "count": 3}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 0}}, {"request_contains": {"index": -1, "text": "AAA"}}, {"request_contains": {"index": -1, "text": "BBBBB"}}, {"request_contains": {"index": -1, "text": "CCCCCCC"}}, {"final_text_contains": "all three checks returned"}]}+{"id": "parallel-fast-shell-batch-resumes", "why": "#1166: fast shell results must appear exactly once and reach the second model request before final completion and clean process exit. Repeated varied-size allocator stress lives in scripts/eval/parallel_shell_stress.py.", "args": [], "prompt": "run the three checks", "script": [{"tools": [{"tool": "bash", "arguments": {"command": "printf AAA"}}, {"tool": "bash", "arguments": {"command": "printf BBBBB"}}, {"tool": "bash", "arguments": {"command": "printf CCCCCCC"}}]}, {"text": "all three checks returned"}], "assert": [{"events_at_least": {"match": {"type": "tool_result", "name": "bash"}, "count": 3}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 0}}, {"request_contains": {"index": -1, "text": "AAA"}}, {"request_contains": {"index": -1, "text": "BBBBB"}}, {"request_contains": {"index": -1, "text": "CCCCCCC"}}, {"final_text_contains": "all three checks returned"}, {"events_at_most": {"match": {"type": "tool_result", "name": "bash"}, "count": 3}}, {"events_at_least": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_0", "is_error": false}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_0", "is_error": false}, "count": 1}}, {"request_contains": {"index": 1, "text": "AAA"}}, {"events_at_least": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_1", "is_error": false}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_1", "is_error": false}, "count": 1}}, {"request_contains": {"index": 1, "text": "BBBBB"}}, {"events_at_least": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_2", "is_error": false}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_result", "name": "bash", "id": "call_1_2", "is_error": false}, "count": 1}}, {"request_contains": {"index": 1, "text": "CCCCCCC"}}]}{"args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "github_fixture": {"checks": "SUCCESS", "runs": "success", "review_files": ["packages/client/package.json", "packages/client/test_runner.py", "packages/client/value.py", ".github/workflows/client.yml"]}, "workspace_seed": {"prepare.py": "import json, pathlib, subprocess\nrun=lambda *args: subprocess.check_output(args,text=True).strip()\nstate=json.loads(pathlib.Path('gh-state.json').read_text())\nstate['base_sha']=run('git','rev-parse','HEAD')\npathlib.Path('packages/client/value.py').write_text('VALUE = 2\\n')\nrun('git','add','packages/client/value.py')\nrun('git','-c','user.name=Fixture','-c','[email protected]','-c','commit.gpgsign=false','commit','-qm','change')\nstate['initial_head']=run('git','rev-parse','HEAD')\npathlib.Path('gh-state.json').write_text(json.dumps(state))\n", "packages/client/package.json": "{\"scripts\": {\"test\": \"python3 test_runner.py\"}}", "packages/client/test_runner.py": "import os\nfrom value import VALUE\nassert VALUE == int(os.environ.get('EXPECTED', '2'))\nprint('CHECK_RECEIPT_OK')\n", "packages/client/value.py": "VALUE = 1\n", ".github/workflows/client.yml": "name: client\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: cd packages/client && python3 test_runner.py\n"}, "prompt": "Run the isolated publication fixture and report its result.", "id": "publication-shell-check-evidence", "why": "#1168/#1178/#1180: canonical shell checks and unchanged nested runner configuration reach immutable publication review.", "script": [{"tool": "shell", "arguments": {"command": "python3 prepare.py"}}, {"tool": "shell", "arguments": {"action": "run", "command": "cd packages/client && python3 test_runner.py"}}, {"tool": "shell", "arguments": {"command": "gh pr ready 1"}}, {"text": "{\"verdict\":\"supported\",\"reason\":\"Fixture confirms supplied committed runner and observed check.\"}"}, {"text": "Publication fixture complete."}], "assert": [{"request_contains": {"index": 3, "text": "CHECK_RECEIPT_OK"}}, {"request_contains": {"index": 3, "text": "packages/client/package.json"}}, {"request_contains": {"index": 3, "text": "packages/client/test_runner.py"}}, {"request_contains": {"index": 3, "text": ".github/workflows/client.yml"}}, {"file_equals": {"path": "mutations.jsonl", "content": "[\"pr\", \"ready\", \"1\"]\n"}}]}{"args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "github_fixture": {"checks": "SUCCESS", "runs": "success", "review_files": ["packages/client/package.json", "packages/client/test_runner.py", "packages/client/value.py", ".github/workflows/client.yml"]}, "workspace_seed": {"prepare.py": "import json, pathlib, subprocess\nrun=lambda *args: subprocess.check_output(args,text=True).strip()\nstate=json.loads(pathlib.Path('gh-state.json').read_text())\nstate['base_sha']=run('git','rev-parse','HEAD')\npathlib.Path('packages/client/value.py').write_text('VALUE = 2\\n')\nrun('git','add','packages/client/value.py')\nrun('git','-c','user.name=Fixture','-c','[email protected]','-c','commit.gpgsign=false','commit','-qm','change')\nstate['initial_head']=run('git','rev-parse','HEAD')\npathlib.Path('gh-state.json').write_text(json.dumps(state))\n", "packages/client/package.json": "{\"scripts\": {\"test\": \"python3 test_runner.py\"}}", "packages/client/test_runner.py": "import os\nfrom value import VALUE\nassert VALUE == int(os.environ.get('EXPECTED', '2'))\nprint('CHECK_RECEIPT_OK')\n", "packages/client/value.py": "VALUE = 1\n", ".github/workflows/client.yml": "name: client\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: cd packages/client && python3 test_runner.py\n"}, "prompt": "Run the isolated publication fixture and report its result.", "id": "publication-shell-failed-check-retained", "why": "#1168: recording canonical shell successes must also preserve its failures in the publication gate.", "script": [{"tool": "shell", "arguments": {"command": "python3 prepare.py"}}, {"tool": "shell", "arguments": {"command": "cd packages/client && EXPECTED=3 python3 test_runner.py"}}, {"tool": "shell", "arguments": {"command": "gh pr ready 1"}}, {"text": "Publication remains blocked by the observed failed check."}], "assert": [{"request_contains": {"text": "observed local check has no successful completion"}}, {"no_event": {"type": "tool_call_finished", "name": "shell", "is_error": false, "text": "https://example.invalid/pull/1"}}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('mutations.jsonl').exists()"]}{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "github_fixture": {"checks": "SUCCESS", "runs": "success", "review_files": ["packages/client/package.json", "packages/client/test_runner.py", "packages/client/value.py", ".github/workflows/client.yml"]}, "workspace_seed": {"prepare.py": "import json, pathlib, subprocess\nrun=lambda *args: subprocess.check_output(args,text=True).strip()\nstate=json.loads(pathlib.Path('gh-state.json').read_text())\nstate['base_sha']=run('git','rev-parse','HEAD')\npathlib.Path('packages/client/value.py').write_text('VALUE = 2\\n')\nrun('git','add','packages/client/value.py')\nrun('git','-c','user.name=Fixture','-c','[email protected]','-c','commit.gpgsign=false','commit','-qm','change')\nstate['initial_head']=run('git','rev-parse','HEAD')\npathlib.Path('gh-state.json').write_text(json.dumps(state))\n", "packages/client/package.json": "{\"scripts\": {\"test\": \"python3 test_runner.py\"}}", "packages/client/test_runner.py": "import os\nfrom value import VALUE\nassert VALUE == int(os.environ.get('EXPECTED', '2'))\nprint('CHECK_RECEIPT_OK')\n", "packages/client/value.py": "VALUE = 1\n", ".github/workflows/client.yml": "name: client\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: cd packages/client && python3 test_runner.py\n"}, "prompt": "Run the isolated publication fixture and report its result.", "id": "publication-rlm-check-evidence", "why": "#1168/#1178/#1180: canonical shell checks and unchanged nested runner configuration reach immutable publication review.", "script": [{"tool": "shell", "arguments": {"command": "python3 prepare.py"}}, {"tool": "rlm", "arguments": {"code": "print(bash(\"cd packages/client && python3 test_runner.py\"))"}}, {"tool": "shell", "arguments": {"command": "gh pr ready 1"}}, {"text": "{\"verdict\":\"supported\",\"reason\":\"Fixture confirms supplied committed runner and observed check.\"}"}, {"text": "Publication fixture complete."}], "assert": [{"request_contains": {"index": 3, "text": "CHECK_RECEIPT_OK"}}, {"request_contains": {"index": 3, "text": "packages/client/package.json"}}, {"request_contains": {"index": 3, "text": "packages/client/test_runner.py"}}, {"request_contains": {"index": 3, "text": ".github/workflows/client.yml"}}, {"file_equals": {"path": "mutations.jsonl", "content": "[\"pr\", \"ready\", \"1\"]\n"}}]}diff --git a/scripts/eval/http2-acp-mock.cjs b/scripts/eval/http2-acp-mock.cjsindex c54520a2..f3de0322 100644--- a/scripts/eval/http2-acp-mock.cjs+++ b/scripts/eval/http2-acp-mock.cjs@@ -8,6 +8,7 @@ const server = http2.createSecureServer({key: fs.readFileSync(key), cert: fs.readFileSync(cert), allowHTTP1: false,});let sessions = 0, requests = 0;+const concurrent = [];server.on('session', session => {session.fixtureId = ++sessions;record({ event: 'session', session: sessions, alpn: session.socket.alpnProtocol });@@ -27,6 +28,31 @@ server.on('stream', (stream, headers) => {stream: stream.id, method: headers[':method'], path: headers[':path'], body: JSON.parse(body) });stream.respond({ ':status': 200, 'content-type': 'text/event-stream' });const delta = text => `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: text }, finish_reason: null }] })}\n\n`;+ if (request === 5) {+ const tool = { index: 0, id: 'fixture-child', type: 'function', function: {+ name: 'subagent', arguments: JSON.stringify({ description: 'Inspect fixture',+ prompt: 'CHILD-CONCURRENCY-FIXTURE: return child complete, no tools required.',+ run_in_background: true, isolation: 'shared_cwd', model: JSON.parse(body).model }) } };+ stream.end(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { tool_calls: [tool] }, finish_reason: null }] })}\n\n` ++ 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\ndata: [DONE]\n\n');+ return;+ }+ if (request > 5) {+ const messages = JSON.parse(body).messages;+ const lastUser = messages.filter(m => m.role === 'user').at(-1);+ const child = JSON.stringify(lastUser).includes('CHILD-CONCURRENCY-FIXTURE');+ concurrent.push({ stream, session, child, delta });+ record({ event: 'concurrent-arrival', session, child });+ // Neither response completes until root and child are both reading.+ // Sharing one non-multiplexing Conn corrupts or deadlocks this boundary.+ if (concurrent.length === 2) {+ record({ event: 'concurrent-ready', sessions: concurrent.map(c => c.session),+ roles: concurrent.map(c => c.child) });+ for (const c of concurrent) c.stream.end(c.delta(c.child ? 'child complete' : 'root complete') ++ 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n');+ }+ return;+ }if (request === 3) {// No END_STREAM or completion event: only ACP cancellation can finish// this turn within the test deadline. The next request remains usable.diff --git a/scripts/eval/parallel_shell_stress.py b/scripts/eval/parallel_shell_stress.pynew file mode 100644index 00000000..2e15d601--- /dev/null+++ b/scripts/eval/parallel_shell_stress.py@@ -0,0 +1,115 @@+#!/usr/bin/env python3+"""Offline #1166 stress: fast shell batches, exact results, next turn, clean exit.++Uses the same real harness and scripted HTTP model as tier 2. On macOS enable+malloc scribbling and heap checks; Zig-owned allocations retain build checks.+Run: python3 scripts/eval/parallel_shell_stress.py --repeat 20+"""+import argparse+from collections import Counter+import importlib.util+import json+from pathlib import Path+import platform+import shlex+import sys++REPO = Path(__file__).resolve().parents[2]+spec = importlib.util.spec_from_file_location('tier2', REPO / 'scripts/eval-tier2.py')+tier2 = importlib.util.module_from_spec(spec)+spec.loader.exec_module(tier2)+++def make_case(iteration, count, legacy=False, barrier=False):+ sizes = [0, 1, 31, 255, 1023, 2047, 4095, 8191]+ expected = {}+ calls = []+ for i in range(count):+ size = sizes[(i + iteration) % len(sizes)]+ marker = f'RESULT-{iteration}-{i}:'+ expected[f'call_1_{i}'] = marker + chr(65 + i % 26) * size + ':END'+ # A separate overlap run waits for every process to start; fast runs+ # have no sleeps/barriers, stressing simultaneous job completion.+ setup = ''+ if barrier:+ setup = (f'from pathlib import Path; import time; '+ f'Path("started-{i}").touch(); deadline=time.monotonic()+5; '+ f'\nwhile len(list(Path(".").glob("started-*"))) < {count}:\n'+ ' assert time.monotonic()<deadline, "batch serialized"\n time.sleep(.005)\n')+ code = setup + f'print({marker!r} + {chr(65 + i % 26)!r} * {size} + ":END")'+ calls.append({'tool': 'bash' if legacy else 'shell',+ 'arguments': {'command': ('printf %s ' + shlex.quote(expected[f'call_1_{i}'])+ if not barrier and size < 256+ else 'python3 -c ' + shlex.quote(code))}})+ case = {+ 'id': f'parallel-shell-{iteration}-{count}-' + ('bash' if legacy else 'shell') + ('-overlap' if barrier else ''),+ 'prompt': 'Execute the independent fixture commands, then report completion.',+ 'args': ['--old'] if legacy else [],+ 'script': [{'tools': calls}, {'text': 'BATCH-COMPLETE'}],+ 'timeout_s': 45,+ 'assert': [{'final_text_contains': 'BATCH-COMPLETE'}],+ 'env': {},+ }+ if platform.system() == 'Darwin':+ case['env'] = {'MallocScribble': '1', 'MallocPreScribble': '1',+ 'MallocCheckHeapStart': '1', 'MallocCheckHeapEach': '1000',+ 'MallocErrorAbort': '1', 'MallocNanoZone': '0'}+ return case, expected+++def verify(case, expected, run):+ failures = tier2.evaluate(case, run)+ if run.exit_code != 0:+ failures.append(f'process exit {run.exit_code}')+ if len(run.requests) != 2:+ failures.append(f'expected two model requests, got {len(run.requests)}')+ results = [e for e in run.events if e.get('type') == 'tool_result']+ ids = Counter(e.get('id') for e in results)+ if ids != Counter({key: 1 for key in expected}):+ failures.append(f'tool-result identity/count mismatch: {ids}')+ for event in results:+ wanted = expected.get(event.get('id'))+ if wanted is not None and wanted not in event.get('text', ''):+ failures.append(f'wrong result bytes for {event.get("id")}')+ if event.get('is_error') or event.get('cancelled'):+ failures.append(f'failed/cancelled result {event.get("id")}')+ if len(run.requests) >= 2:+ messages = [m for m in run.requests[1].get('messages', []) if m.get('role') == 'tool']+ if Counter(m.get('tool_call_id') for m in messages) != Counter({key: 1 for key in expected}):+ failures.append('second request missing/duplicating tool results')+ for message in messages:+ wanted = expected.get(message.get('tool_call_id'))+ if wanted is not None and wanted not in message.get('content', ''):+ failures.append(f'corrupt model result {message.get("tool_call_id")}')+ for marker in ('memory corruption', 'double free', 'use after free', 'incorrect checksum', 'panic:'):+ if marker in run.stderr.lower():+ failures.append(f'allocator/runtime diagnostic: {marker}')+ return failures+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--graff', default=str(REPO / 'zig-out/bin/graff'))+ parser.add_argument('--repeat', type=int, default=20)+ parser.add_argument('--evidence-dir', type=Path)+ args = parser.parse_args()+ if args.repeat < 1:+ parser.error('--repeat must be positive')+ scenarios = [(n, [2, 3, 5, 8][n % 4], n % 2 == 1, False) for n in range(args.repeat)]+ scenarios += [(args.repeat, 3, False, True)]+ total = 0+ for scenario in scenarios:+ case, expected = make_case(*scenario)+ run = tier2.execute(case, str(Path(args.graff).resolve()), 1234, None, None, args.evidence_dir)+ failures = verify(case, expected, run)+ if failures:+ print(json.dumps({'case': case['id'], 'failures': failures, 'stderr': run.stderr[-2000:]}, indent=2))+ return 1+ total += len(expected)+ print(f'PASS {case["id"]}: {len(expected)} exact results; resumed; exit 0', flush=True)+ print(f'PASS {len(scenarios)} processes / {total} shell results; allocator diagnostics={platform.system() == "Darwin"}')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex af99428e..e0680d9e 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2628,+ "test_count_baseline": 2633,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/test-acp-http2.py b/scripts/test-acp-http2.pyindex 815ebe0d..9104cf67 100644--- a/scripts/test-acp-http2.py+++ b/scripts/test-acp-http2.py@@ -228,11 +228,25 @@ def exercise(root, binary, name, cert, host, success):assert all(r['alpn'] == 'h2' for r in records if r['event'] == 'session')assert requests[3]['session'] != requests[2]['session'], 'Incomplete HTTP/2 connection was reused'print('PASS ACP TLS HTTP/2: stalled cancellation, stream closure, same-session recovery', flush=True)+ result, updates = call('session/prompt', {'sessionId': sid, 'prompt': [+ {'type': 'text', 'text': 'Run the concurrent fixture child and continue the root.'}]}, 7, timeout=30)+ assert result.get('result', {}).get('stopReason') == 'end_turn', result+ assert 'root complete' in response_text(updates), 'Root response missing after child launch'+ records = [json.loads(line) for line in log.read_text().splitlines()]+ ready = next(r for r in records if r['event'] == 'concurrent-ready')+ assert sorted(ready['roles']) == [False, True], 'Root and child did not overlap'+ assert len(set(ready['sessions'])) == 2, 'Root and child shared a mutable HTTP/2 transport'+ assert len([r for r in records if r['event'] == 'request']) == 7, 'Concurrent requests retried unexpectedly'+ print('PASS ACP TLS HTTP/2: simultaneous root and background child streams', flush=True)print(f'PASS ACP TLS HTTP/2: {name}', flush=True)except Exception:stderr.flush()print('Server observations:', [(r.get('event'), r.get('request'), r.get('stream')) for r in(json.loads(line) for line in log.read_text().splitlines())])+ records = [json.loads(line) for line in log.read_text().splitlines()]+ for record in records:+ if record['event'] == 'request' and record['request'] >= 6:+ print('Concurrent fixture tool results:', [m.get('content') for m in record['body'].get('messages', []) if m.get('role') == 'tool'][-2:])print((case/'stderr').read_text()[-5000:])raisefinally:diff --git a/src/acp.zig b/src/acp.zigindex dd90b6f1..4249c096 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -133,7 +133,7 @@ fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requelive.local_catalog_loaded = true;}const er = @import("effort_route.zig");- @import("gateway_picker_catalog.zig").refresh(root.gpa, root.io, root.arena, keys.*);+ if (@import("gateway_picker_catalog.zig").requested(req.params)) @import("gateway_picker_catalog.zig").refresh(root.gpa, root.io, root.arena, keys.*);const catalog = pricing.models();const Row = struct {name: []const u8,diff --git a/src/agent_stream_h2.zig b/src/agent_stream_h2.zigindex 1ae27495..506da235 100644--- a/src/agent_stream_h2.zig+++ b/src/agent_stream_h2.zig@@ -47,9 +47,10 @@ pub fn postStream(self: *Agent, body: []const u8) !?[]u8 {n += 1;}- const sess = http2_pool.sessionFor(gpa, self.io, origin.host, origin.port) catch return null;+ const lease = http2_pool.acquire(gpa, self.io, origin.host, origin.port) catch return null;+ const sess = lease.session;var keep = false;- defer if (!keep) http2_pool.invalidate(self.io);+ defer lease.release(keep);var lines = sess.startLines(.{.method = "POST",.scheme = "https",diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zigindex 00d52054..b1deb111 100644--- a/src/agent_tool_batch.zig+++ b/src/agent_tool_batch.zig@@ -28,7 +28,7 @@ pub const skipped_text = "tool execution skipped because the operation was abort/// Write / edit / imagegen serialize the whole batch so a later edit cannot/// race a write on the same path. Mixing bash with write/edit still/// serializes, because write/edit do. Shell-only batches stay parallel-/// (#266) but join on the caller thread (#1166).+/// (#266); the parent joins all results before converting/freeing them (#1166).pub fn isSequential(name: []const u8) bool {if (std.mem.eql(u8, name, "write_file")) return true;if (std.mem.eql(u8, name, "edit_file")) return true;@@ -40,8 +40,9 @@ fn isShellName(name: []const u8) bool {return std.mem.eql(u8, name, "shell") or std.mem.eql(u8, name, "bash");}-/// Shell job reaping is not safe on pool threads: fast parallel completions-/// corrupted a free block after every result was already persisted (#1166).+/// Preserve the async scheduling policy introduced for #1166. This is not+/// thread affinity: Threaded Io may run async work on its pool too. Safety+/// relies on owned outputs and joining every future before result cleanup.pub fn batchNeedsCooperative(calls: []const ToolCall, idx: []const usize) bool {for (idx) |i| {if (isShellName(calls[i].name)) return true;@@ -186,8 +187,8 @@ fn runParallel(self: *Agent, ctx: ToolCtx, calls: []const ToolCall, ext_idx: []cdefer self.gpa.free(outputs);const cooperative = batchNeedsCooperative(calls, spawn_at.items);for (spawn_at.items, futures) |i, *fut| {- // Shell batches start together cooperatively so #266 still holds, but- // they do not share io.concurrent worker threads (#1166).+ // Async may fall back to inline execution under saturation; it does+ // not guarantee execution on the caller thread (Threaded Io).fut.* = if (cooperative)self.io.async(execTool, .{ ctx, calls[i] })elsediff --git a/src/gateway_picker_catalog.zig b/src/gateway_picker_catalog.zigindex 03d7e2f0..7c539ba4 100644--- a/src/gateway_picker_catalog.zig+++ b/src/gateway_picker_catalog.zig@@ -8,6 +8,27 @@ const util = @import("util.zig");var last_attempt: ?i64 = null;+/// Setting confirmations need current local state, not provider discovery.+pub fn requested(params: ?std.json.Value) bool {+ const value = params orelse return true;+ if (value != .object) return true;+ const flag = value.object.get("refresh") orelse return true;+ return flag != .bool or flag.bool;+}++test "gateway refresh is skipped only by explicit false" {+ const a = std.testing.allocator;+ try std.testing.expect(requested(null));+ for ([_][]const u8{ "{}", "null", "{\"refresh\":true}", "{\"refresh\":\"false\"}" }) |input| {+ const parsed = try std.json.parseFromSlice(std.json.Value, a, input, .{});+ defer parsed.deinit();+ try std.testing.expect(requested(parsed.value));+ }+ const parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"refresh\":false}", .{});+ defer parsed.deinit();+ try std.testing.expect(!requested(parsed.value));+}+pub fn refresh(gpa: Allocator, io: Io, arena: Allocator, keys: provider.Keys) void {const key = keys.get("codegraff") orelse return;const now = util.unixMs(io);diff --git a/src/http2_pool.zig b/src/http2_pool.zigindex d65db9be..0f53bfa1 100644--- a/src/http2_pool.zig+++ b/src/http2_pool.zig@@ -1,5 +1,5 @@-//! Process-wide HTTP/2 session for HTTPS SSE (http-zig). GRAFF_HTTP2=0|off-//! latches HTTP/1.1. One session per origin; peer close redials inside Session.+//! One idle HTTP/2 session for HTTPS SSE (http-zig). Active requests own+//! exclusive leases: Conn is not a concurrent stream multiplexer.const std = @import("std");const builtin = @import("builtin");@@ -9,9 +9,6 @@ const main_mod = @import("main.zig");var mu: Io.Mutex = .init;var session: ?*http_zig.Session = null;-var host_buf: [256]u8 = undefined;-var host_len: usize = 0;-var port: u16 = 0;pub fn enabled() bool {return main_mod.g_http2;@@ -32,44 +29,49 @@ pub fn parseOrigin(url: []const u8) !Origin {return .{ .host = u.host, .port = u.port, .path = u.path };}-pub fn sessionFor(gpa: std.mem.Allocator, io: Io, host: []const u8, p: u16) !*http_zig.Session {+pub const Lease = struct {+ session: *http_zig.Session,++ pub fn release(self: Lease, keep: bool) void {+ if (!keep) {+ self.session.close();+ return;+ }+ const io = self.session.io;+ mu.lockUncancelable(io);+ const occupied = session != null;+ if (!occupied) session = self.session;+ mu.unlock(io);+ if (occupied) self.session.close();+ }+};++fn takeIdle(io: Io, host: []const u8, p: u16) ?*http_zig.Session {mu.lockUncancelable(io);- defer mu.unlock(io);- if (session) |s| {- if (p == port and host_len == host.len and std.mem.eql(u8, host_buf[0..host_len], host))- return s;+ const idle = session;+ session = null;+ mu.unlock(io);+ if (idle) |s| {+ if (p == s.port and std.mem.eql(u8, s.host, host)) return s;s.close();- session = null;}- if (host.len > host_buf.len) return error.NameTooLong;- @memcpy(host_buf[0..host.len], host);- host_len = host.len;- port = p;- const s = try http_zig.Session.open(gpa, io, host, p);- session = s;- return s;+ return null;}-/// Drop the process-wide session. Tests allocate it with `std.testing.allocator`.-pub fn resetForTest() void {- if (!builtin.is_test) return;- const live = session orelse return;- const io = live.io;- mu.lockUncancelable(io);- defer mu.unlock(io);- if (session) |current| current.close();- session = null;- host_len = 0;+pub fn acquire(gpa: std.mem.Allocator, io: Io, host: []const u8, p: u16) !Lease {+ // Dial outside the mutex: concurrent root/child requests need separate+ // transports, and cancellation of one must not invalidate another.+ return .{ .session = takeIdle(io, host, p) orelse try http_zig.Session.open(gpa, io, host, p) };}-/// Drop the pooled session. A stream that did not reach END_STREAM must not-/// be reused: the next turn would read the previous frame.-pub fn invalidate(io: Io) void {- mu.lockUncancelable(io);- defer mu.unlock(io);- if (session) |s| s.close();+/// Tests release every active lease before clearing the idle pool.+pub fn resetForTest() void {+ if (!builtin.is_test) return;+ mu.lockUncancelable(std.testing.io);+ const idle = session;session = null;- host_len = 0;+ mu.unlock(std.testing.io);+ if (idle) |s| s.close();}pub fn keepAfter(ended: bool) bool {@@ -126,3 +128,44 @@ test "want is https-only" {main_mod.g_http2 = false;try std.testing.expect(!want("https://api.x.ai/v1/responses"));}++fn testSession(host: []const u8) !*http_zig.Session {+ const gpa = std.testing.allocator;+ const s = try gpa.create(http_zig.Session);+ errdefer gpa.destroy(s);+ s.* = .{ .gpa = gpa, .io = std.testing.io, .host = try gpa.dupe(u8, host), .port = 443 };+ return s;+}++test "HTTP2 leases exclusively own same-origin and different-origin sessions" {+ defer resetForTest();+ const root = try testSession("localhost");+ (Lease{ .session = root }).release(true);+ const active = try acquire(std.testing.allocator, std.testing.io, "localhost", 443);+ try std.testing.expectEqual(root, active.session);+ try std.testing.expect(takeIdle(std.testing.io, "localhost", 443) == null);+ try std.testing.expect(takeIdle(std.testing.io, "other.localhost", 443) == null);+ // Neither another checkout nor clearing the idle pool can close root.+ resetForTest();+ try std.testing.expectEqualStrings("localhost", active.session.host);+ active.release(true);+ const reused = try acquire(std.testing.allocator, std.testing.io, "localhost", 443);+ try std.testing.expectEqual(root, reused.session);+ reused.release(false);+}++test "HTTP2 cancellation closes only its lease while another session is idle" {+ defer resetForTest();+ const cancelled = Lease{ .session = try testSession("localhost") };+ const healthy = try testSession("other.localhost");+ (Lease{ .session = healthy }).release(true);+ cancelled.release(false);+ const reused = try acquire(std.testing.allocator, std.testing.io, "other.localhost", 443);+ try std.testing.expectEqual(healthy, reused.session);+ reused.release(true);+ // A concurrent completed request cannot replace or free the idle winner.+ (Lease{ .session = try testSession("localhost") }).release(true);+ const winner = try acquire(std.testing.allocator, std.testing.io, "other.localhost", 443);+ try std.testing.expectEqual(healthy, winner.session);+ winner.release(false);+}diff --git a/src/oauth_codegraff.zig b/src/oauth_codegraff.zigindex c8f78e49..d33cd922 100644--- a/src/oauth_codegraff.zig+++ b/src/oauth_codegraff.zig@@ -69,7 +69,7 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {return;};try writeKey(io, arena, home, key);- try out.print("{s}✓{s} logged into codegraff — key saved to ~/{s}. /model deepseek-v4-pro\n", .{ style.green, style.reset, key_file });+ try out.print("{s}✓{s} logged into codegraff — key saved to ~/{s}. /model mimo-v2.6-pro\n", .{ style.green, style.reset, key_file });try out.flush();return;} else if (std.mem.eql(u8, status, "denied")) {diff --git a/src/pricing.zig b/src/pricing.zigindex 19930895..b1ae2bfe 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -299,6 +299,8 @@ pub const model_table = [_]ModelInfo{.{ .provider = "codegraff", .name = "grok-build", .context = 256_000 },.{ .provider = "codegraff", .name = "glm-5.2", .context = 204_800 },.{ .provider = "codegraff", .name = "glm-5.3-flash", .context = 202_752 },+ .{ .provider = "codegraff", .name = "mimo-v2.6-pro", .context = 1_048_576 },+ .{ .provider = "codegraff", .name = "mimo-v2.6-flash", .context = 1_048_576 },.{ .provider = "codegraff", .name = "mimo-v2.5", .context = 128_000 },.{ .provider = "codegraff", .name = "mimo-v2.5-pro", .context = 128_000 },// Kimi Code offline fallback. Authenticated startup replaces this slice@@ -402,6 +404,8 @@ fn pureKimiGeneration(name: []const u8) ?u32 {/// the newest explicit pure generation (`k3`, then future `k4`, etc.) over/// compatibility aliases and K2 point-release ids.pub fn providerDefaultModel(provider_id: []const u8, fallback: []const u8) []const u8 {+ for (models()) |model| if (std.mem.eql(u8, model.provider, provider_id) and+ std.mem.eql(u8, model.name, "mimo-v2.6-pro")) return model.name;if (std.mem.eql(u8, provider_id, "codex")) {for (models()) |model| if (std.mem.eql(u8, model.provider, "codex")) return model.name;return fallback;diff --git a/src/pricing_tests.zig b/src/pricing_tests.zigindex 070aacaf..69232928 100644--- a/src/pricing_tests.zig+++ b/src/pricing_tests.zig@@ -280,3 +280,28 @@ test "OpenRouter defaults to Claude Sonnet 4.6 on the chat completions surface"try std.testing.expect(pricing.providerModelInTable("openrouter", "anthropic/claude-sonnet-4.6"));try std.testing.expectEqual(@as(u64, 1_000_000), pricing.contextFor("openrouter", "anthropic/claude-sonnet-4.6"));}++test "startup preference stays on providers that advertise the preferred model" {+ const saved = pricing.active_model_table;+ defer pricing.active_model_table = saved;+ const rows = [_]pricing.ModelInfo{+ .{ .provider = "codegraff", .name = "mimo-v2.6-pro", .context = 1_048_576 },+ .{ .provider = "xiaomi", .name = "mimo-v2.6-pro", .context = 1_048_576 },+ .{ .provider = "codex", .name = "gpt-5.6-sol", .context = 272_000 },+ };+ pricing.active_model_table = &rows;+ try std.testing.expectEqualStrings("mimo-v2.6-pro", pricing.providerDefaultModel("codegraff", "old-default"));+ try std.testing.expectEqualStrings("mimo-v2.6-pro", pricing.providerDefaultModel("xiaomi", "old-default"));+ try std.testing.expectEqualStrings("gpt-5.6-sol", pricing.providerDefaultModel("codex", "old-default"));+ try std.testing.expectEqualStrings("deepseek-v4-pro", pricing.providerDefaultModel("deepseek", "deepseek-v4-pro"));+}++test "provider defaults preserve explicit model selection" {+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ try std.testing.expect(keys.set("codegraff", "test-key", .login));+ try std.testing.expectEqualStrings("mimo-v2.6-pro", (try keys.defaultProvider()).model);+ try std.testing.expectEqualStrings("deepseek-v4-pro", (try keys.providerById("codegraff", "deepseek-v4-pro")).model);+ try std.testing.expect(keys.set("xiaomi", "test-key", .environment));+ try std.testing.expectEqualStrings("xiaomi", (try keys.defaultProvider()).id);+ try std.testing.expectEqualStrings("mimo-v2.6-pro", (try keys.defaultProvider()).model);+}diff --git a/src/provider.zig b/src/provider.zigindex f3975d9e..25f997c6 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -77,7 +77,7 @@ pub const provider_specs = [_]ProviderSpec{// anthropic-version auth as Messages), so new Claude releases appear// without a rebuild; the baked pricing.zig rows stay the offline fallback..{ .id = "anthropic", .display_name = "Anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "https://api.anthropic.com/v1/messages", .env_key = "ANTHROPIC_API_KEY", .default_model = "claude-opus-4-8", .catalog = .anthropic, .models_url = "https://api.anthropic.com/v1/models?limit=1000" },- .{ .id = "codegraff", .display_name = "Codegraff", .kind = .openai, .auth = .bearer, .url = "https://gateway.codegraff.com/v1/chat/completions", .env_key = "CODEGRAFF_API_KEY", .default_model = "deepseek-v4-pro", .login = .codegraff_device, .catalog = .openai, .models_url = "https://gateway.codegraff.com/v1/models", .takes_effort = true },+ .{ .id = "codegraff", .display_name = "Codegraff", .kind = .openai, .auth = .bearer, .url = "https://gateway.codegraff.com/v1/chat/completions", .env_key = "CODEGRAFF_API_KEY", .default_model = "mimo-v2.6-pro", .login = .codegraff_device, .catalog = .openai, .models_url = "https://gateway.codegraff.com/v1/models", .takes_effort = true },.{ .id = "deepseek", .display_name = "DeepSeek", .kind = .openai, .auth = .bearer, .url = "https://api.deepseek.com/chat/completions", .env_key = "DEEPSEEK_API_KEY", .default_model = "deepseek-v4-pro", .takes_effort = true },.{ .id = "openai", .display_name = "OpenAI", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },// Google AI Studio on its first-party Interactions API — the wire Googlediff --git a/src/provider_codegraff_tests.zig b/src/provider_codegraff_tests.zigindex 40589239..d2029633 100644--- a/src/provider_codegraff_tests.zig+++ b/src/provider_codegraff_tests.zig@@ -234,6 +234,7 @@ test "the gateway still serves the startup default when it is the only credentiatry std.testing.expect(keys.set("codegraff", "gateway-key", .login));const got = try keys.defaultProvider();try std.testing.expectEqualStrings("codegraff", got.id);+ try std.testing.expectEqualStrings("mimo-v2.6-pro", got.model);const none: provider.Keys = .{ .values = @splat(null) };try std.testing.expectError(error.MissingKey, none.defaultProvider());diff --git a/src/subagent_mimo_tests.zig b/src/subagent_mimo_tests.zigindex 146860d9..b3b5bfdd 100644--- a/src/subagent_mimo_tests.zig+++ b/src/subagent_mimo_tests.zig@@ -74,7 +74,10 @@ test "MiMo gateway preference requires live catalog availability and keeps credetry std.testing.expectEqualStrings("codegraff", frontier.provider.?.id);try std.testing.expectEqualStrings("mimo-v2.6-pro", frontier.provider.?.model);try std.testing.expectEqualStrings(base.api_key, frontier.provider.?.api_key);- pricing.active_model_table = &pricing.model_table;+ const unavailable = [_]pricing.ModelInfo{+ .{ .provider = "codegraff", .name = "gpt-5.6-luna", .context = 272_000 },+ };+ pricing.active_model_table = &unavailable;try std.testing.expectEqualStrings("deepseek-v4-flash", ladder.forModel("codegraff", base.model).?.small.?);}