graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Preserve failed sub-agent evidence and agent inspection
Rach Pradhan7514c3fdd712
diff --git a/apps/native/app/visual-tests/agents/fixture.tsx b/apps/native/app/visual-tests/agents/fixture.tsxindex 86187e7f..36ff9937 100644--- a/apps/native/app/visual-tests/agents/fixture.tsx+++ b/apps/native/app/visual-tests/agents/fixture.tsx@@ -1,11 +1,14 @@'use client';-import { useCallback, useState } from 'react';+import { useCallback, useRef, useState } from 'react';import AgentsPane from '@/components/site/AgentsPane';import { applyAppearance, type Appearance } from '@/lib/appearance';export default function Fixture() {const [scenario, setScenario] = useState('connected');const [sent, setSent] = useState('');+ const scenarioRef = useRef(scenario);+ scenarioRef.current = scenario;const request = useCallback(async (_root: string | undefined, params: Record<string, unknown>) => {+ const scenario = scenarioRef.current;if (scenario === 'error') throw new Error('Observer unavailable');if (params.action === 'send') { setSent(JSON.stringify(params)); return { delivery: 'queued' }; }if (params.action === 'children') return {children: [@@ -29,7 +32,7 @@ export default function Fixture() {{ session: 'peer-a', title: 'Implement navigation', startId: '11', pid: 1, task: 'Refine keyboard navigation', workspace: '/demo/workspace', status: scenario === 'idle' ? 'waiting' : 'working', resources: { rssMiB: 20, cpuPercent: 1.2 } },...(params.scope === 'device' ? [{ session: 'peer-b', title: 'Review accessibility', startId: '12', pid: 2, task: 'Check focus order', workspace: '/demo/second', status: 'waiting', resources: null }] : []),], messages: [{ from_session: 'peer-a', to: 'peer-b', ts_ms: 1000, text: 'The navigation update is ready for review.', kind: 'handoff' }], delivery: 'Queued' };- }, [scenario]);+ }, []);return <main className="flex h-screen flex-col bg-page text-ink"><nav className="flex gap-3 p-3">{['connected', 'idle', 'empty', 'error'].map(value => <button key={value} data-agent-case={value} onClick={() => setScenario(value)}>{value}</button>)}{['light', 'dark', 'codegraff'].map(theme => <button key={theme} data-agent-theme={theme} onClick={() => applyAppearance(theme as Appearance)}>{theme}</button>)}</nav><div className="flex min-h-0 flex-1 gap-3 p-3"><div className="flex-1 min-w-0 p-5"><h1>Workspace conversation</h1><p>The agent panel keeps coordination alongside your work.</p><output data-agent-sent className="break-all">{sent}</output></div><AgentsPane root="/demo/workspace" onClose={() => {}} request={request} /></div>diff --git a/apps/native/components/site/AgentsPane.tsx b/apps/native/components/site/AgentsPane.tsxindex 81141fc6..a585ef14 100644--- a/apps/native/components/site/AgentsPane.tsx+++ b/apps/native/components/site/AgentsPane.tsx@@ -37,7 +37,7 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {}, [root, scope, refresh, request]);const connected = snapshot?.agents ?? [];const agents = connected.filter(agent => showIdle || agent.status === 'working');- const selected = agents.find(a => recipient && agentKey(a) === agentKey(recipient));+ const selected = connected.find(a => recipient && agentKey(a) === agentKey(recipient));const name = (session: string) => connected.find(a => a.session === session)?.title || session || 'Workspace';const choose = (agent: LocalAgent) => { setRecipient(agent); setNotice(''); setComposing(false); content.current?.scrollTo({top:0}); };const submit = async () => {@@ -59,7 +59,7 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {<div ref={content} className="min-h-0 flex-1 overflow-y-auto p-3 space-y-4">{error && <p role="alert" className="text-sm text-ink-2">{error} <button className="underline" onClick={() => setRefresh(n => n + 1)}>Retry</button></p>}{!snapshot && !error && <p role="status" className="text-sm text-ink-3">Finding local Graffs…</p>}- {snapshot && !agents.length && <p className="text-sm text-ink-3">No {showIdle ? 'connected' : 'active'} Graffs {scope === 'workspace' ? 'in this workspace' : 'on this laptop'}.{!showIdle && connected.length > 0 ? ' Show idle agents to see connected sessions waiting for input.' : ' Start a Graff session to coordinate.'}</p>}+ {snapshot && !selected && !agents.length && <p className="text-sm text-ink-3">No {showIdle ? 'connected' : 'active'} Graffs {scope === 'workspace' ? 'in this workspace' : 'on this laptop'}.{!showIdle && connected.length > 0 ? ' Show idle agents to see connected sessions waiting for input.' : ' Start a Graff session to coordinate.'}</p>}{!selected && <ul className="space-y-2">{agents.map(agent => <li key={agentKey(agent)}><button onClick={() => choose(agent)} aria-pressed={false} className="w-full rounded-xl border border-line p-3 text-left hover:bg-hover"><span className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate text-sm font-medium">{agentName(agent)}</span><span className="text-xs text-ink-3">{agent.status === 'working' ? 'Working' : agent.status === 'waiting' ? 'Waiting' : 'Connected'}</span></span><span className="mt-1 block text-xs text-ink-2 break-words">{agent.task || 'No task published'}</span>@@ -74,7 +74,7 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {</div>{selected && <button className="shrink-0 border-t border-line px-4 py-3 text-left text-xs hover:bg-hover" aria-expanded={composing} onClick={() => setComposing(value => !value)}>{composing ? 'Hide message composer' : 'Message this Graff…'}</button>}{(!selected || composing) && <form className="space-y-2 border-t border-line p-3" onSubmit={e => { e.preventDefault(); void submit(); }}>- <label className="block text-xs text-ink-2">To<select aria-label="Message recipient" value={selected ? agentKey(selected) : ''} onChange={e => { setRecipient(agents.find(a => agentKey(a) === e.target.value) ?? null); setNotice(''); }} className="ml-2 max-w-[85%] rounded-lg bg-hover px-2 py-1 text-ink"><option value="">Select a Graff</option>{agents.map(a => <option key={agentKey(a)} value={agentKey(a)}>{agentName(a)}</option>)}</select></label>+ <label className="block text-xs text-ink-2">To<select aria-label="Message recipient" value={selected ? agentKey(selected) : ''} onChange={e => { setRecipient(agents.find(a => agentKey(a) === e.target.value) ?? null); setNotice(''); }} className="ml-2 max-w-[85%] rounded-lg bg-hover px-2 py-1 text-ink"><option value="">Select a Graff</option>{selected && !agents.some(a => agentKey(a) === agentKey(selected)) && <option value={agentKey(selected)}>{agentName(selected)}</option>}{agents.map(a => <option key={agentKey(a)} value={agentKey(a)}>{agentName(a)}</option>)}</select></label>{recipient && !selected && <p className="text-xs text-ink-3">Recipient is unavailable in this view. Select another Graff or show idle agents.</p>}<textarea ref={input} aria-label="Message to Graff" value={text} onChange={e => setText(e.target.value)} maxLength={8192} rows={2} placeholder="Ask a peer, share context, or request a handoff…" className="w-full resize-y rounded-xl border border-line bg-surface p-3 text-sm outline-none focus:border-accent" /><div className="flex items-center gap-2"><select aria-label="Coordination type" value={kind} onChange={e => setKind(e.target.value)} className="rounded-lg bg-hover p-2 text-xs"><option value="message">Message</option><option value="handoff">Handoff request</option></select><button type="submit" disabled={!selected || !text.trim() || sending || !!error} className="ml-auto rounded-lg bg-hover-2 px-3 py-2 text-sm disabled:opacity-40">{sending ? 'Queuing…' : 'Send to Graff'}</button></div>diff --git a/apps/native/components/site/SubagentActivity.tsx b/apps/native/components/site/SubagentActivity.tsxindex 28fd14c9..508e8349 100644--- a/apps/native/components/site/SubagentActivity.tsx+++ b/apps/native/components/site/SubagentActivity.tsx@@ -63,10 +63,10 @@ export default function SubagentActivity({root, parent, scope, request}: {root?:// Snapshot replay time is not the child's execution time.return {...value, tools:value.tools.map(tool => ({...tool, startedAt:undefined, elapsedMs:undefined}))};}, [activity, selected]);- const visibleChildren = children.filter(child => showFinished || child.status === 'working');+ const visibleChildren = children.filter(child => showFinished || child.status !== 'completed');return <section aria-label="Sub-agents" className="space-y-3 rounded-xl border border-line p-3"><h3 className="text-sm font-medium">Sub-agents</h3>- <label className="flex items-center gap-2 text-xs text-ink-3"><input type="checkbox" checked={showFinished} onChange={e => setShowFinished(e.target.checked)} />Show finished sub-agents</label>+ <label className="flex items-center gap-2 text-xs text-ink-3"><input type="checkbox" checked={showFinished} onChange={e => setShowFinished(e.target.checked)} />Show completed sub-agents</label>{loaded && children.length > 0 && !visibleChildren.length && <p className="text-xs text-ink-3">No active sub-agents.</p>}{error ? <p role="alert" className="text-xs text-ink-2">{error} <button className="underline" onClick={() => setRefresh(n => n + 1)}>Retry</button></p>: !loaded ? <p role="status" className="text-xs text-ink-3">Finding sub-agents…</p>diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjsindex eb6a319d..5e265335 100644--- a/apps/native/electron/agents-visual.cjs+++ b/apps/native/electron/agents-visual.cjs@@ -4,7 +4,7 @@ const path = require('node:path');async function runAgentVisuals({ win, origin, output }) {const js = source => win.webContents.executeJavaScript(source);const selectChild = id => js(`(()=>{const id=${JSON.stringify(id)}, button=document.querySelector('[data-child-agent="'+id+'"]');if(button){button.click();return;}const select=document.querySelector('[aria-label="Select sub-agent"]');Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(select,id);select.dispatchEvent(new Event('change',{bubbles:true}));})()`);- const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 40)); } console.error(await js('document.body.innerText')); fs.writeFileSync(path.join(output, 'agents-failed.png'), (await win.webContents.capturePage()).toPNG()); throw Error(`Agent visual timeout: ${source}`); };+ const wait = async source => { for (let i = 0; i < 200; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 40)); } console.error(await js('document.body.innerText')); fs.writeFileSync(path.join(output, 'agents-failed.png'), (await win.webContents.capturePage()).toPNG()); throw Error(`Agent visual timeout: ${source}`); };win.webContents.on('console-message', (_e, level, message) => { if (level >= 2) console.error('Agent fixture:', message); });win.show(); win.focus();await win.loadURL(`${origin}/visual-tests/agents`);@@ -22,6 +22,18 @@ async function runAgentVisuals({ win, origin, output }) {assert.equal(await js(`document.querySelectorAll('li button').length`), 0, 'A peer disappears when it stops working');await js(`document.querySelector('[data-agent-case="connected"]').click()`);await wait(`document.querySelectorAll('li button').length === 1`);+ await js(`document.querySelector('li button').click()`);+ await selectChild('child-working');+ await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('Live')`);+ await js(`document.querySelector('[data-agent-case="idle"]').click()`);+ await new Promise(resolve => setTimeout(resolve, 5500));+ assert.equal(await js(`document.querySelector('[aria-label="Sub-agent activity"] strong')?.textContent`), 'Inspect navigation', 'Inspection survives the parent becoming idle');+ await js(`Array.from(document.querySelectorAll('button')).find(b => b.textContent === 'Message this Graff…').click()`);+ assert.equal(await js(`document.querySelector('[aria-label="Message recipient"] option:checked')?.textContent`), 'Implement navigation', 'Idle selection remains an explicit recipient');+ await js(`document.querySelector('[aria-label="Back to all agents"]').click()`);+ await wait(`document.body.textContent.includes('No active Graffs')`);+ await js(`document.querySelector('[data-agent-case="connected"]').click()`);+ await wait(`document.querySelectorAll('li button').length === 1`);await js(`document.querySelectorAll('[aria-label="Agent scope"] button')[1].click()`);await wait(`document.querySelectorAll('li button').length === 1`);assert.equal(await js(`document.querySelector('[aria-label="Message recipient"]').textContent.includes('Review accessibility')`), false, 'Idle peers are excluded from active recipients');@@ -32,8 +44,8 @@ async function runAgentVisuals({ win, origin, output }) {await wait(`document.querySelector('[data-child-agent="child-working"]')`);assert.notEqual(await js(`document.activeElement.getAttribute('aria-label')`), 'Message to Graff', 'Inspection should not move focus into the send form');assert.equal(await js(`document.querySelector('[data-child-agent="child-completed"]')`), null, 'Completed children are hidden by default');- assert.equal(await js(`document.querySelector('[data-child-agent="child-failed"]')`), null, 'Failed children are hidden by default');- await js(`Array.from(document.querySelectorAll('label')).find(l => l.textContent.includes('Show finished sub-agents')).querySelector('input').click()`);+ assert.equal(await js(`!!document.querySelector('[data-child-agent="child-failed"]')`), true, 'Failed children stay visible by default');+ await js(`Array.from(document.querySelectorAll('label')).find(l => l.textContent.includes('Show completed sub-agents')).querySelector('input').click()`);await selectChild('child-working');await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('Live')`);assert.equal(await js(`document.querySelector('[data-tool-summary]')?.getAttribute('aria-expanded')`), 'false');diff --git a/docs/adr/0076-local-agent-panel.md b/docs/adr/0076-local-agent-panel.mdindex e8a24a01..0884aefb 100644--- a/docs/adr/0076-local-agent-panel.md+++ b/docs/adr/0076-local-agent-panel.md@@ -10,7 +10,10 @@ room history, and explicit addressed human messages. Discovery compares processstart identities, not PID alone. Old peers without a verifiable identity areexcluded. The panel defaults to currently working peers; “Show idle agents”reveals other verified connected sessions, including waiting and legacy peers.-The count and recipient picker follow this filter as presence refreshes.+The count and recipient picker follow this filter as presence refreshes, except+that an explicitly selected connected peer remains inspectable and addressable+when it becomes idle. Filtering the list must not tear down an open inspection;+disconnection still invalidates the selection.Coordination history is collapsed by default. Legacy activity is shown as connected, never inferred from CPU usage.A lightweight observer entry point bypasses provider, MCP and session startup.diff --git a/docs/adr/0082-subagent-activity-through-acp.md b/docs/adr/0082-subagent-activity-through-acp.mdindex c714835d..287c153d 100644--- a/docs/adr/0082-subagent-activity-through-acp.md+++ b/docs/adr/0082-subagent-activity-through-acp.md@@ -26,8 +26,9 @@ child identifier. Inspection neither consumes inboxes nor sends instructions.The GUI opens a focused child selector after selecting a parent Graff. It reusesthe existing transcript and collapsed tool disclosures. Late responses from aprevious selection are discarded. Polling pauses when the window is hidden and-stops for completed children. The list defaults to working children, with an-explicit “Show finished sub-agents” option for completed and failed results.+stops for completed children. The list defaults to working and failed children,+with an explicit “Show completed sub-agents” option for successful results.+Failures remain visible because they need attention, not a history opt-in.An already-open activity remains readable when that child finishes. Messaging remains an explicit separate action.## Consequencesdiff --git a/docs/adr/0088-failed-children-return-partial-evidence.md b/docs/adr/0088-failed-children-return-partial-evidence.mdnew file mode 100644index 00000000..63618f71--- /dev/null+++ b/docs/adr/0088-failed-children-return-partial-evidence.md@@ -0,0 +1,28 @@+# 0088. Failed children return partial evidence++Status: accepted++## Context++A child can read files or produce findings before its next model request fails.+The failure return previously preserved the error and worktree location but+omitted that evidence. A parent could not summarize useful partial work, and+workflow failure excerpts retained only the cause.++## Decision++Keep the result marked as an error and append bounded, explicitly incomplete+evidence from assistant text, tool results, and the interrupted response.+Exclude user instructions and reasoning blocks. Prefer recent history, cap each+excerpt and the total evidence, and disclose truncation. Workflow synthesis+retains a small evidence excerpt alongside its existing failure-cause excerpt.+The parent must distinguish reported findings, observed tool results, and work+still requiring verification. No additional model call is needed for recovery.++## Consequences++Failure still controls retry and completion status. Partial output is not proof+of a successful task. Evidence is limited to retained history and the current+interrupted response; it is not a complete audit trail. Empty recovery returns+only the original failure. A scripted budget-exhaustion case proves that an+actual failed child returns its earlier file-read result to the parent.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex b1e5d54b..6eaa120a 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -98,6 +98,7 @@ record only when you need the evidence or the edge cases.| [0085](0085-in-session-update-is-next-launch.md) | `/update` installs a verified release for the next launch; this session keeps its original binary. || [0086](0086-desktop-drafts-belong-to-open-chats.md) | Unsent desktop drafts and uploads belong to open chats and survive hidden panes; closing a chat disposes them. || [0087](0087-bounded-desktop-presentation-work.md) | Bound syntax caches and live code rendering; project saved transcripts before sending them to the renderer and measure identical desktop workloads. |+| [0088](0088-failed-children-return-partial-evidence.md) | Failed children return bounded partial evidence with error status intact, including an excerpt for workflow synthesis. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 2f1f32e8..f33ac7d2 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -13,6 +13,7 @@{"id": "review-repeat-failure-gets-anchor-revision", "why": "report_anchors gives review/research a real verifier (cited paths must resolve against the tree), so a review-class repeat failure now earns the R0d revision prescription instead of jumping to the judge fleet — the anchors are the external feedback Weng's gate demands.", "args": [], "prompt": "review the findings in report.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "reviewed solo as told"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "re-reviewing against the cited code as prescribed"}], "second_prompt": "that review missed real problems in report.py — go again", "assert": [{"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"request_lacks": {"index": 1, "text": "(escalation R0d):"}}, {"request_contains": {"index": -1, "text": "(escalation R0d):"}}, {"request_contains": {"index": -1, "text": "revision case"}}, {"final_text_contains": "re-reviewing against the cited code"}]}{"id": "budget-final-call-lands-the-answer", "why": "#390: the pool's FINAL admitted model call belongs to the answer. The run's last request must offer no tools and carry the landing note, so the model answers from gathered evidence instead of asking for a tool the budget can never pay for — the audit-smoke run died exactly this way, exhausted mid-tool-loop with the work done and nothing narrated.", "args": ["--max-model-calls", "2"], "prompt": "keep reading the todo list forever", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "landing: the todo list is empty; nothing else was verified"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_contains": {"index": -1, "text": "budget landing"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "landing: the todo list is empty"}]}{"id": "escalation-third-failure-earns-the-fleet", "why": "GREEN regression lock. Ladder cell prior_failure_count>=2: the one deep retry is spent, so a THIRD ask of the same class must escape R0d and run as an R3 fleet. Guards the `prior_failure_count == 1` gate and the noteDeclined bump on the R0d decline — loosen either and the run loops on solo revisions forever, which is exactly the stuck-task failure the ladder exists to break.", "args": [], "prompt": "fix the crash in stats.py", "second_prompt": "still crashing in stats.py after that fix — go again", "script": [{"tool": "bash", "arguments": {"command": "echo 'def mean(xs): return sum(xs)/len(xs)' > stats.py && echo seeded-stats"}}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"text": "made the edit solo; the test still crashes"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"text": "FLEET-FINDER-REPORT: stats.py divides by len(xs) with no empty-list guard"}, {"text": "FLEET-VERIFY-REPORT: confirmed against stats.py — the guard is missing"}, {"text": "the fleet confirmed the missing empty-list guard in stats.py"}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "seeded-stats\n"}}, {"request_contains": {"index": 2, "text": "(escalation R0):"}}, {"request_lacks": {"index": 2, "text": "(escalation R0d):"}}, {"request_contains": {"index": 4, "text": "(escalation R0d):"}}, {"request_contains": {"index": 4, "text": "second failure earns the fleet"}}, {"events_at_least": {"match": {"type": "agent_route"}, "count": 2}}, {"events_at_most": {"match": {"type": "agent_route"}, "count": 2}}, {"request_contains": {"index": 6, "text": "FLEET-FINDER-REPORT"}}, {"request_contains": {"index": -1, "text": "FLEET-VERIFY-REPORT"}}, {"final_text_contains": "missing empty-list guard"}], "timeout_s": 120}+{"id":"failed-child-partial-evidence","why":"A failed child must return observed tool evidence to its parent with failure status intact, so the parent can summarize incomplete work without inventing success.","args":["--max-model-calls","3"],"workspace_seed":{"example.txt":"RECOVERED-EVIDENCE: parser accepts an empty record.\n"},"prompt":"Use one subagent to inspect example.txt, then summarize what it found even if interrupted.","script":[{"tool":"subagent","arguments":{"description":"Inspect parser","prompt":"Read example.txt and report findings."}},{"tool":"read_file","arguments":{"path":"example.txt"}},{"text":"The child read that the parser accepts an empty record, but it exhausted its budget before completing the review."}],"assert":[{"event":{"type":"tool_result","name":"subagent","is_error":true}},{"request_contains":{"index":-1,"text":"Partial work recovered (task failed; claims require verification)"}},{"request_contains":{"index":-1,"text":"RECOVERED-EVIDENCE: parser accepts an empty record."}},{"request_contains":{"index":-1,"text":"model-call-budget failure"}},{"final_text_contains":"before completing the review"}]}{"id": "child-refused-last-call-root-lands", "why": "#390 hard half (green regression lock): with cap 2, call 1 spawns a child; the child's acquire sees one slot left and is refused BEFORE the network (run_budget.zig depth>0 guard), surfacing as an is_error subagent tool_result classified [model-call-budget failure] with retry ruled out - and the ROOT takes call 2 as the landing call. Deleting the guard lets a worker eat the last slot and the run dies narrating. The bracket now also carries the attempt count - 1 attempt locks that a budget refusal is never blind-retried by the worker retry ladder.", "args": ["--max-model-calls", "2"], "prompt": "spawn a subagent to survey the payments module, then summarize what happened", "script": [{"tool": "subagent", "arguments": {"description": "survey payments", "prompt": "read every file under payments/ and list the exported functions"}}, {"text": "landing: the survey child was refused by the run budget; nothing was surveyed and nothing is verified"}], "assert": [{"event": {"type": "tool_call", "name": "subagent"}}, {"event": {"type": "tool_result", "name": "subagent", "is_error": true}}, {"request_contains": {"index": -1, "text": "model-call budget exhausted for this graff run"}}, {"request_contains": {"index": -1, "text": "[model-call-budget failure, 1 attempt]"}}, {"request_contains": {"index": -1, "text": "retry is NOT safe as-is"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "the survey child was refused"}]}{"id": "uncapped-run-never-sees-landing-note", "why": "#390 containment (green regression lock): with no --max-model-calls the landing machinery must be invisible - no [budget landing] on any request and tools still offered on the last one. Guards the max_model_calls != 0 gate in agent_request.zig: a hand-rolled remaining()-style check saturates to 0 under cap 0 and would strip tools from every normal run.", "args": [], "prompt": "check the todo list and report", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "uncapped: the list is checked and empty"}], "assert": [{"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "uncapped: the list is checked"}]}{"id": "repair-ask-review-word-does-not-cross-cell", "why": "Intuition trap (green regression lock): 'fix the bug the review found in report.py' must cell as BUGFIX so its R0 decline parks in the bugfix column; the follow-up 'critique report.py' cells as REVIEW with a clean history and must get the plain R0 advisory, never the R0d revision prescription. Fails if the decline ledger collapses to one counter or classOf lets the word 'review' inside a repair ask steal the cell. Live replay measures whether the model treats the two asks as different kinds of work.", "args": [], "prompt": "ultracode fix the bug the review found in report.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read report.py and locate the defect"}]}, {"title": "implement the fix", "tasks": [{"description": "fix", "prompt": "fix the defect in report.py"}]}]}}, {"text": "declined, so I repaired report.py myself"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "declined again with the plain advisory, so I critiqued report.py solo"}], "second_prompt": "now ultracode critique report.py, the earlier pass missed real problems", "assert": [{"events_at_least": {"match": {"type": "tool_result", "name": "workflow", "is_error": false}, "count": 2}}, {"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"request_contains": {"index": -1, "text": "(escalation R0):"}}, {"request_lacks": {"index": -1, "text": "(escalation R0d):"}}, {"request_lacks": {"index": -1, "text": "revision case"}}, {"final_text_contains": "critiqued report.py solo"}]}diff --git a/src/main.zig b/src/main.zigindex 9a7830b1..52fa4a72 100644--- a/src/main.zig+++ b/src/main.zig@@ -514,7 +514,6 @@ pub fn main(init: std.process.Init) !void {try mainloop.run(&loop_ctx);try session_run.finalizeSession(gpa, startup_timing.shutdown_trace.at(io, "final-save"), arena, out, &root, json_mode);}-// The `graff mcp` CLI (list/add servers in .mcp.json) + the trusted-companion check live in mcp_cli.zig.const mcp_cli = @import("mcp_cli.zig");// Provider-switch core lives in providers.zig; the interactive pickers, ultracode steering, and login/auth flow live in pickers.zig.const providers = @import("providers.zig");@@ -595,6 +594,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("presence_record.zig");_ = @import("acp_agents.zig");_ = @import("subagent_activity.zig");+ _ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");_ = @import("read_image.zig");}diff --git a/src/subagent_recovery.zig b/src/subagent_recovery.zignew file mode 100644index 00000000..713e5132--- /dev/null+++ b/src/subagent_recovery.zig@@ -0,0 +1,116 @@+//! Evidence for a parent's summary when a child cannot finish its report.+const std = @import("std");+const util = @import("util.zig");+const Value = std.json.Value;+const A = std.mem.Allocator;+pub const marker = "\n\nPartial work recovered (task failed; claims require verification):\n";+const cap = 8192;++const Evidence = struct {+ a: A,+ text: std.ArrayList(u8) = .empty,+ truncated: bool = false,+ fn add(self: *Evidence, label: []const u8, raw: []const u8) !void {+ const body = std.mem.trim(u8, raw, " \t\r\n");+ if (body.len == 0) return;+ const room = cap -| self.text.items.len;+ if (room <= label.len + 2) {+ self.truncated = true;+ return;+ }+ const head = util.utf8Prefix(body, @min(2048, room - label.len - 2));+ try self.text.appendSlice(self.a, label);+ try self.text.appendSlice(self.a, head);+ try self.text.appendSlice(self.a, "\n\n");+ self.truncated = self.truncated or head.len < body.len;+ }+ fn blocks(self: *Evidence, value: Value, label: []const u8) !void {+ if (value == .string) return self.add(label, value.string);+ if (value != .array) return;+ for (value.array.items) |block| {+ if (block != .object) continue;+ const ty = str(block, "type");+ if (std.mem.eql(u8, ty, "text") or std.mem.eql(u8, ty, "output_text")) try self.add(label, str(block, "text"));+ }+ }+ fn message(self: *Evidence, msg: Value) !void {+ if (msg != .object) return;+ const ty = str(msg, "type");+ const role = str(msg, "role");+ if (std.mem.eql(u8, ty, "function_call_output")) {+ if (msg.object.get("output")) |output| try self.blocks(output, "Tool result: ");+ } else if (std.mem.eql(u8, role, "assistant") or std.mem.eql(u8, ty, "model_output")) {+ if (msg.object.get("content")) |content| try self.blocks(content, "Reported finding: ");+ } else if (std.mem.eql(u8, role, "tool")) {+ if (msg.object.get("content")) |content| try self.blocks(content, "Tool result: ");+ } else if (std.mem.eql(u8, role, "user")) {+ const content = msg.object.get("content") orelse return;+ if (content != .array) return;+ for (content.array.items) |block| {+ if (!std.mem.eql(u8, str(block, "type"), "tool_result")) continue;+ if (block.object.get("content")) |result| try self.blocks(result, "Tool result: ");+ }+ }+ }+};+fn str(value: Value, key: []const u8) []const u8 {+ if (value != .object) return "";+ const field = value.object.get(key) orelse return "";+ return if (field == .string) field.string else "";+}++/// No extra model call: return evidence, never fabricate a successful summary.+pub fn append(a: A, failure: []const u8, history: []const Value, partial: []const u8) ![]u8 {+ var evidence: Evidence = .{ .a = a };+ defer evidence.text.deinit(a);+ try evidence.add("Interrupted response: ", partial);+ // Favor recent evidence when the child has a long history.+ var i = history.len;+ while (i > 0) {+ i -= 1;+ try evidence.message(history[i]);+ }+ if (evidence.text.items.len == 0) return a.dupe(u8, failure);+ return std.fmt.allocPrint(a, "{s}{s}{s}{s}\nSummarize useful findings, cite observed tool evidence, and state what remains unfinished. Do not infer success from partial output.", .{ failure, marker, evidence.text.items, if (evidence.truncated) "[Partial evidence truncated.]\n" else "" });+}++/// Workflow failure excerpts retain a small evidence section for synthesis.+pub fn excerpt(a: A, failure: []const u8, cause: []const u8) []const u8 {+ const start = std.mem.indexOf(u8, failure, marker) orelse return cause;+ return std.fmt.allocPrint(a, "{s}{s}", .{ cause, util.utf8Prefix(failure[start..], 2048) }) catch cause;+}++test "failed subagent recovery preserves findings and tool evidence but excludes instructions and reasoning" {+ const a = std.testing.allocator;+ const parsed = try std.json.parseFromSlice(Value, a,+ \\[{"role":"user","content":"private task"},{"role":"assistant","content":[{"type":"thinking","text":"hidden reasoning"},{"type":"text","text":"Found the faulty branch"}]},{"type":"function_call_output","output":"check passed"},{"role":"tool","content":"file updated"},{"role":"user","content":[{"type":"tool_result","content":"test failed"}]}]+ , .{});+ defer parsed.deinit();+ const report = try append(a, "transport failure", parsed.value.array.items, "Still checking");+ defer a.free(report);+ for ([_][]const u8{ "transport failure", "Found the faulty branch", "check passed", "file updated", "test failed", "Still checking", "task failed" }) |text| try std.testing.expect(std.mem.indexOf(u8, report, text) != null);+ try std.testing.expect(std.mem.indexOf(u8, report, "private task") == null);+ try std.testing.expect(std.mem.indexOf(u8, report, "hidden reasoning") == null);+}++test "failed subagent recovery leaves empty evidence honest" {+ const a = std.testing.allocator;+ const report = try append(a, "authentication failed", &.{}, " \n\t");+ defer a.free(report);+ try std.testing.expectEqualStrings("authentication failed", report);+}++test "failed subagent recovery caps evidence and retains it in workflow excerpts" {+ const a = std.testing.allocator;+ const raw = try a.alloc(u8, 20000);+ defer a.free(raw);+ @memset(raw, 'x');+ const report = try append(a, "transport failure", &.{}, raw);+ defer a.free(report);+ try std.testing.expect(report.len < 9000);+ try std.testing.expect(std.mem.indexOf(u8, report, "truncated") != null);+ const short = excerpt(a, report, "transport failure");+ defer a.free(short);+ try std.testing.expect(short.len <= 2065);+ try std.testing.expect(std.mem.indexOf(u8, short, "task failed") != null);+}diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 1ba26834..84743b73 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -418,6 +418,11 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constif (telemetry.g_telem) |t| t.runEvent(&fp, sys_override != null, run_ok, run_ms, used_tools);const text = report catch |err| {var out = subagentFailure(gpa, sub_id, err, agent.last_api_error, attempts);+ const recovered = @import("subagent_recovery.zig").append(gpa, out.text, agent.messages.items, agent.partial_text.items) catch null;+ if (recovered) |body| {+ gpa.free(out.text);+ out.text = body;+ }if (wt) |w| {const tail = if (pool_seat)@import("experiment_pool.zig").deliverNote(gpa, ctx.io, .{ .path = w.path, .branch = w.branch, .base = w.base })diff --git a/src/workflow.zig b/src/workflow.zigindex beb3d9f0..fecc5ccf 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -138,8 +138,8 @@ pub fn failExcerpt(arena: Allocator, text: []const u8) []const u8 {for (flat) |*c| if (c.* == '\n' or c.* == '\r' or c.* == '\t') {c.* = ' ';};- if (head.len == trimmed.len) return flat;- return std.fmt.allocPrint(arena, "{s}…", .{flat}) catch flat;+ const cause = if (head.len == trimmed.len) flat else std.fmt.allocPrint(arena, "{s}…", .{flat}) catch flat;+ return @import("subagent_recovery.zig").excerpt(arena, text, cause);}/// #5 conditional-phase gate: a phase carrying a non-empty `when` runs only when