graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(review): bound read-only review runs
Rach Pradhanffac6911fa9f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9d807e40..31cd0e2c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -76,6 +76,9 @@ jobs:- name: JSON live-control protocol testrun: python3 scripts/test-json-controls.py zig-out/bin/graff+ - name: Bounded review mode regression+ run: python3 scripts/test-review-mode.py zig-out/bin/graff+- name: Streamable HTTP MCP handshake and session regressionrun: python3 scripts/test-mcp-streamable-http.py --graff zig-out/bin/graffdiff --git a/README.md b/README.mdindex 96c80b84..9f2752ba 100644--- a/README.md+++ b/README.md@@ -442,6 +442,7 @@ other animation names remain available./animation choose a thinking animation (`/animation` lists every option)/goal [text] set/show a standing objective; /goal pause|resume|status|clear/loop <prompt> work autonomously toward the prompt, stopping with a named outcome when done or blocked+/review <target> one read-only review pass; no edits, delegation, workflows, or web access/rewind [n] list past prompts; /rewind <n> drops prompt n+after & reverts its file edits/image <path> attach an image to your next message (vision models only)/paste attach the clipboard image (macOS); also Ctrl-V (⌘V can't be captured)@@ -466,6 +467,11 @@ turns it back on, and `/goal status` shows the objective and its current state.(plan, act, verify) and stopping on its own with a named outcome (accepted,blocked, cancelled, or exhausted) once the work is done, you step in, or a safetylimit is hit, instead of pausing for confirmation between routine steps.+`/review <target or instructions>` is the deliberately narrower path for code+review: it suppresses goal/eval/ultracode steering, admits only local+read/search tools and read-only shell inspection, and reserves the last of at+most 10 model calls for a tool-free report (with a 40-tool ceiling). Use a+later, explicit turn to fix accepted findings.### MCP serversdiff --git a/scripts/test-review-mode.py b/scripts/test-review-mode.pynew file mode 100644index 00000000..f860b861--- /dev/null+++ b/scripts/test-review-mode.py@@ -0,0 +1,215 @@+#!/usr/bin/env python3+"""Prove review turns are read-only, single-agent, and model-call bounded."""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile++from codex_ws_mock import CodexMock, RecordedRequest+++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg+FINAL_REPLY = "[P1] Example finding — target.txt:1"+BUDGET_REPLY = "No findings. Bounded review completed."+++def response_events(item: dict, response_id: str) -> list[dict]:+ return [+ {"type": "response.output_item.done", "item": item},+ {+ "type": "response.completed",+ "response": {+ "id": response_id,+ "usage": {+ "input_tokens": 100,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 10,+ "total_tokens": 110,+ },+ },+ },+ ]+++def tool(name: str, arguments: dict, ordinal: int) -> list[dict]:+ return response_events(+ {+ "type": "function_call",+ "id": f"fc_review_{ordinal}",+ "call_id": f"call_review_{ordinal}",+ "name": name,+ "arguments": json.dumps(arguments),+ "status": "completed",+ },+ f"resp_review_{ordinal}",+ )+++def message(text: str, ordinal: int) -> list[dict]:+ return response_events(+ {+ "type": "message",+ "id": f"msg_review_{ordinal}",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": text, "annotations": []}],+ },+ f"resp_review_{ordinal}",+ )+++def review_events(request: RecordedRequest) -> list[dict]:+ cases = {+ 1: ("edit_file", {"path": "target.txt", "old_string": "original", "new_string": "changed"}),+ 2: ("workflow", {"phases": [{"title": "fanout", "tasks": [{"description": "edit", "prompt": "change it"}]}]}),+ 3: ("bash", {"command": "touch should-not-exist"}),+ 4: ("read_file", {"path": "target.txt"}),+ }+ if request.ordinal in cases:+ name, arguments = cases[request.ordinal]+ return tool(name, arguments, request.ordinal)+ return message(FINAL_REPLY, request.ordinal)+++def loop_events(request: RecordedRequest) -> list[dict]:+ if not request.body.get("tools"):+ return message(BUDGET_REPLY, request.ordinal)+ return tool("read_file", {"path": "target.txt"}, request.ordinal)+++def environment(tmp: str, port: int) -> dict[str, str]:+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home, exist_ok=True)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump({"tokens": {"access_token": "review-mock", "account_id": "acct-review"}}, fh)+ harness_dir = os.path.join(tmp, ".harness")+ os.makedirs(harness_dir, exist_ok=True)+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)+ env = {+ key: value+ for key, value in os.environ.items()+ if not key.startswith("GRAFF_") and not key.startswith("CODEX_")+ }+ env.update(+ {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ }+ )+ return env+++def run_review(+ tmp: str, port: int, max_model_calls: int | None = None+) -> tuple[list[dict], subprocess.Popen[str]]:+ argv = [GRAFF, "--model", "codex", "--json", "--no-telemetry"]+ if max_model_calls is not None:+ argv.extend(["--max-model-calls", str(max_model_calls)])+ process = subprocess.Popen(+ argv,+ cwd=tmp,+ env=environment(tmp, port),+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ bufsize=1,+ )+ assert process.stdin is not None and process.stdout is not None+ process.stdin.write(json.dumps({"type": "review", "text": "Review target.txt"}) + "\n")+ process.stdin.flush()+ events: list[dict] = []+ for line in process.stdout:+ event = json.loads(line)+ events.append(event)+ if event.get("type") in ("turn", "error"):+ break+ return events, process+++def close(process: subprocess.Popen[str]) -> None:+ if process.stdin:+ process.stdin.close()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.terminate()+ process.wait(timeout=5)+++def main() -> None:+ with tempfile.TemporaryDirectory(prefix="graff-review-mode-") as tmp:+ target = os.path.join(tmp, "target.txt")+ with open(target, "w", encoding="utf-8") as fh:+ fh.write("original")++ mock = CodexMock(events_for_request=review_events)+ port = mock.start()+ try:+ events, process = run_review(tmp, port)+ close(process)+ finally:+ mock.stop()++ rejected = [+ (event.get("name"), event.get("reason"))+ for event in events+ if event.get("type") == "tool_rejected"+ ]+ expected = [+ ("edit_file", "review_mode"),+ ("workflow", "review_mode"),+ ("bash", "review_mode"),+ ]+ if rejected != expected:+ raise AssertionError(f"wrong review rejections: {rejected!r}")+ if events[-1].get("type") != "turn" or events[-1].get("text") != FINAL_REPLY:+ raise AssertionError(f"review did not finish normally: {events[-1]!r}")+ with open(target, encoding="utf-8") as fh:+ if fh.read() != "original":+ raise AssertionError("review edited the target")+ if os.path.exists(os.path.join(tmp, "should-not-exist")):+ raise AssertionError("review ran a mutating shell command")+ if len(mock.recorded_requests()) != 5:+ raise AssertionError("review did not follow the expected bounded tool loop")++ budget_mock = CodexMock(events_for_request=loop_events)+ budget_port = budget_mock.start()+ try:+ budget_events, budget_process = run_review(tmp, budget_port)+ close(budget_process)+ finally:+ budget_mock.stop()+ calls = len(budget_mock.recorded_requests())+ if calls != 10:+ raise AssertionError(f"review model ceiling admitted {calls} calls")+ if budget_events[-1].get("type") != "turn" or budget_events[-1].get("text") != BUDGET_REPLY:+ raise AssertionError(f"review synthesis did not terminate: {budget_events[-1]!r}")++ global_mock = CodexMock(events_for_request=loop_events)+ global_port = global_mock.start()+ try:+ global_events, global_process = run_review(tmp, global_port, max_model_calls=3)+ close(global_process)+ finally:+ global_mock.stop()+ if len(global_mock.recorded_requests()) != 3:+ raise AssertionError("review did not reserve the final global-budget call")+ if global_events[-1].get("type") != "turn":+ raise AssertionError(f"global-budget synthesis failed: {global_events[-1]!r}")++ print("ok review rejects mutation/delegation and reserves local/global synthesis")+++if __name__ == "__main__":+ main()diff --git a/sdk/README.md b/sdk/README.mdindex 846ff533..51c6ac2b 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -56,6 +56,7 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5const harness = Harness.init({ model: "claude-opus-4-8", yolo: true });const session = harness.session();console.log(await session.ask("what files are here?"));+console.log(await session.review("review HEAD against main")); // bounded + read-onlyfor await (const ev of session.send("ask me a follow-up before continuing")) {if (ev.type === "ask_user") session.answer({ text: "continue", callId: ev.call_id });}@@ -64,7 +65,8 @@ session.close();```Options: `binary`, `cwd`, `env`, `model` (model name *or* provider id, e.g. `"codex"`),-`yolo`, and raw `args`. `chat()`/`send()`/`ask()` accept a string or `{ prompt }`.+`yolo`, and raw `args`. `chat()`/`send()`/`ask()` accept a string or `{ prompt }`;+`review()` runs a bounded read-only review turn.## Remote (edge runtimes — no local binary)diff --git a/sdk/generate.py b/sdk/generate.pyindex a673cd58..27159989 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -127,6 +127,8 @@ export interface HarnessOptions {{export interface ChatOptions {{/** User prompt for this turn. */prompt: string;+ /** Run this turn in bounded, read-only review mode. */+ review?: boolean;}}export interface AnswerOptions {{@@ -314,7 +316,8 @@ export class Harness {{/** Run one turn; async-iterate events up to and including `turn`/`error`. */async *chat(input: string | ChatOptions): AsyncGenerator<Event> {{const prompt = typeof input === "string" ? input : input.prompt;- this.proc.stdin.write(JSON.stringify({{ type: "user", text: prompt }}) + "\\n");+ const type = typeof input === "string" || !input.review ? "user" : "review";+ this.proc.stdin.write(JSON.stringify({{ type, text: prompt }}) + "\\n");while (true) {{const ev = await this.next();if (ev === null) {{@@ -338,6 +341,12 @@ export class Harness {{return final;}}+ /** Run one bounded, read-only review turn and return its final report. */+ review(input: string | ChatOptions): Promise<string> {{+ const prompt = typeof input === "string" ? input : input.prompt;+ return this.ask({{ prompt, review: true }});+ }}+/** Answer an in-flight ask_user event. Call this while consuming chat()* when you receive {{ type: "ask_user", call_id, ... }}. */answer(input: string | AnswerOptions): void {{@@ -452,6 +461,7 @@ export class HarnessSession {{/** Send a user turn; async-iterate its events. */send(input: string | ChatOptions): AsyncGenerator<Event> {{ return this.agent.chat(input); }}ask(input: string | ChatOptions): Promise<string> {{ return this.agent.ask(input); }}+ review(input: string | ChatOptions): Promise<string> {{ return this.agent.review(input); }}answer(input: string | AnswerOptions): void {{ return this.agent.answer(input); }}setSystemPrompt(text: string, append = false): Promise<void> {{ return this.agent.setSystemPrompt(text, append); }}close(): void {{ this.agent.close(); }}@@ -560,6 +570,7 @@ export interface RemoteOptions {{export interface ChatOptions {{prompt: string;+ review?: boolean;}}export interface AnswerOptions {{@@ -658,8 +669,9 @@ export class RemoteHarness {{/** Run one turn; async-iterate events up to and including `turn`/`error`. */async *chat(input: string | ChatOptions): AsyncGenerator<Event> {{const prompt = typeof input === "string" ? input : input.prompt;+ const type = typeof input === "string" || !input.review ? "user" : "review";let terminal = false;- for await (const ev of this.send({{ type: "user", text: prompt }})) {{+ for await (const ev of this.send({{ type, text: prompt }})) {{yield ev;if (ev.type === "turn" || ev.type === "error") {{ terminal = true; break; }}}}@@ -676,6 +688,12 @@ export class RemoteHarness {{return final;}}+ /** Run one bounded, read-only review turn and return its final report. */+ review(input: string | ChatOptions): Promise<string> {{+ const prompt = typeof input === "string" ? input : input.prompt;+ return this.ask({{ prompt, review: true }});+ }}+/** Answer an in-flight ask_user event. The original chat() stream continues* and will later yield the ask_user tool_result plus the final turn. */async answer(input: string | AnswerOptions): Promise<void> {{@@ -998,13 +1016,13 @@ class Harness:_report_error("spawn", f"{{binary}}: {{e}}")raise- def chat(self, text: str) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError (after reporting to telemetry) if theharness process dies mid-turn instead of silently yielding nothing."""assert self.proc.stdin and self.proc.stdouttry:- self.proc.stdin.write(json.dumps({{"type": "user", "text": text}}) + "\\n")+ self.proc.stdin.write(json.dumps({{"type": "review" if review else "user", "text": text}}) + "\\n")self.proc.stdin.flush()except OSError as e:_report_error("died", f"harness pipe closed on send: {{e}}")@@ -1035,6 +1053,16 @@ class Harness:raise RuntimeError(ev["message"])return final+ def review(self, text: str) -> str:+ """Run one bounded, read-only review turn and return its report."""+ final = ""+ for ev in self.chat(text, review=True):+ if ev.get("type") == "turn":+ final = ev["text"]+ elif ev.get("type") == "error":+ raise RuntimeError(ev["message"])+ return final+def answer(self, text: str = "", cancelled: bool = False,call_id: Optional[str] = None) -> None:"""Answer an in-flight ask_user event while chat() is being consumed."""@@ -1258,12 +1286,12 @@ class RemoteHarness:except json.JSONDecodeError:continue- def chat(self, text: str) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError if the stream ends without one (thesession process died server-side)."""terminal = False- for ev in self._send({{"type": "user", "text": text}}):+ for ev in self._send({{"type": "review" if review else "user", "text": text}}):yield evif ev.get("type") in ("turn", "error"):terminal = True@@ -1281,6 +1309,16 @@ class RemoteHarness:raise RuntimeError(ev["message"])return final+ def review(self, text: str) -> str:+ """Run one bounded, read-only review turn and return its report."""+ final = ""+ for ev in self.chat(text, review=True):+ if ev.get("type") == "turn":+ final = ev["text"]+ elif ev.get("type") == "error":+ raise RuntimeError(ev["message"])+ return final+def answer(self, text: str = "", cancelled: bool = False,call_id: Optional[str] = None) -> None:"""Answer an in-flight ask_user event. The original chat streamdiff --git a/sdk/py/README.md b/sdk/py/README.mdindex 5f173dd9..5a110a2e 100644--- a/sdk/py/README.md+++ b/sdk/py/README.md@@ -41,6 +41,9 @@ with Harness(yolo=True, model="gpt-5.5") as h:for ev in h.chat("read foo.txt"):print(ev["type"], ev)+ # bounded review: local reads only, no edits/delegation/workflows+ print(h.review("review HEAD against main"))+# replace or extend the system promptwith Harness(yolo=True, system_prompt="You are a code-review bot. Only report bugs.") as bot:print(bot.ask("review main.py"))diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 2e650210..89457d63 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -246,13 +246,13 @@ class Harness:_report_error("spawn", f"{binary}: {e}")raise- def chat(self, text: str) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError (after reporting to telemetry) if theharness process dies mid-turn instead of silently yielding nothing."""assert self.proc.stdin and self.proc.stdouttry:- self.proc.stdin.write(json.dumps({"type": "user", "text": text}) + "\n")+ self.proc.stdin.write(json.dumps({"type": "review" if review else "user", "text": text}) + "\n")self.proc.stdin.flush()except OSError as e:_report_error("died", f"harness pipe closed on send: {e}")@@ -283,6 +283,16 @@ class Harness:raise RuntimeError(ev["message"])return final+ def review(self, text: str) -> str:+ """Run one bounded, read-only review turn and return its report."""+ final = ""+ for ev in self.chat(text, review=True):+ if ev.get("type") == "turn":+ final = ev["text"]+ elif ev.get("type") == "error":+ raise RuntimeError(ev["message"])+ return final+def answer(self, text: str = "", cancelled: bool = False,call_id: Optional[str] = None) -> None:"""Answer an in-flight ask_user event while chat() is being consumed."""@@ -506,12 +516,12 @@ class RemoteHarness:except json.JSONDecodeError:continue- def chat(self, text: str) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError if the stream ends without one (thesession process died server-side)."""terminal = False- for ev in self._send({"type": "user", "text": text}):+ for ev in self._send({"type": "review" if review else "user", "text": text}):yield evif ev.get("type") in ("turn", "error"):terminal = True@@ -529,6 +539,16 @@ class RemoteHarness:raise RuntimeError(ev["message"])return final+ def review(self, text: str) -> str:+ """Run one bounded, read-only review turn and return its report."""+ final = ""+ for ev in self.chat(text, review=True):+ if ev.get("type") == "turn":+ final = ev["text"]+ elif ev.get("type") == "error":+ raise RuntimeError(ev["message"])+ return final+def answer(self, text: str = "", cancelled: bool = False,call_id: Optional[str] = None) -> None:"""Answer an in-flight ask_user event. The original chat streamdiff --git a/sdk/ts/README.md b/sdk/ts/README.mdindex 8c4f92ac..7f51204e 100644--- a/sdk/ts/README.md+++ b/sdk/ts/README.md@@ -37,13 +37,15 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5const harness = Harness.init({ model: "claude-opus-4-8", yolo: true });const session = harness.session();console.log(await session.ask("what files are here?")); // returns final text+console.log(await session.review("review HEAD against main")); // bounded + read-onlyfor await (const ev of session.send("ask me a follow-up before continuing")) {if (ev.type === "ask_user") session.answer({ text: "continue", callId: ev.call_id });}session.close();```-`Harness.init` accepts `{ model, yolo, cwd, env, binary, system_prompt, args }`.+`Harness.init` accepts `{ model, yolo, cwd, env, binary, systemPrompt,+maxToolCalls, maxModelCalls, dedupeToolCalls, args }`.`model` may be a model name **or** a provider id (e.g. `"codex"`, `"moonshot"`).Also exported: `MODELS` and `PROVIDERS`.diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 1bc0c31a..6b49fa91 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -76,6 +76,8 @@ export interface HarnessOptions {export interface ChatOptions {/** User prompt for this turn. */prompt: string;+ /** Run this turn in bounded, read-only review mode. */+ review?: boolean;}export interface AnswerOptions {@@ -263,7 +265,8 @@ export class Harness {/** Run one turn; async-iterate events up to and including `turn`/`error`. */async *chat(input: string | ChatOptions): AsyncGenerator<Event> {const prompt = typeof input === "string" ? input : input.prompt;- this.proc.stdin.write(JSON.stringify({ type: "user", text: prompt }) + "\n");+ const type = typeof input === "string" || !input.review ? "user" : "review";+ this.proc.stdin.write(JSON.stringify({ type, text: prompt }) + "\n");while (true) {const ev = await this.next();if (ev === null) {@@ -287,6 +290,12 @@ export class Harness {return final;}+ /** Run one bounded, read-only review turn and return its final report. */+ review(input: string | ChatOptions): Promise<string> {+ const prompt = typeof input === "string" ? input : input.prompt;+ return this.ask({ prompt, review: true });+ }+/** Answer an in-flight ask_user event. Call this while consuming chat()* when you receive { type: "ask_user", call_id, ... }. */answer(input: string | AnswerOptions): void {@@ -401,6 +410,7 @@ export class HarnessSession {/** Send a user turn; async-iterate its events. */send(input: string | ChatOptions): AsyncGenerator<Event> { return this.agent.chat(input); }ask(input: string | ChatOptions): Promise<string> { return this.agent.ask(input); }+ review(input: string | ChatOptions): Promise<string> { return this.agent.review(input); }answer(input: string | AnswerOptions): void { return this.agent.answer(input); }setSystemPrompt(text: string, append = false): Promise<void> { return this.agent.setSystemPrompt(text, append); }close(): void { this.agent.close(); }diff --git a/sdk/ts/orchestrate.test.ts b/sdk/ts/orchestrate.test.tsindex c2072bed..f51c71e4 100644--- a/sdk/ts/orchestrate.test.ts+++ b/sdk/ts/orchestrate.test.ts@@ -10,6 +10,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {agent,+ backgroundResultRunning,Budget,DEFAULT_CONCURRENCY,parallel,@@ -206,6 +207,28 @@ describe("Run budget admission", () => {rmSync(dir, { recursive: true, force: true });}});++ test("parallel admissions reserve the call budget before runners await", async () => {+ const dir = tmpJournalDir();+ try {+ const runner = new FakeRunner(async () => {+ await sleep(20);+ return ok("done", 10);+ });+ const run = new Run({ dir, budget: { maxCalls: 2 }, runner, concurrency: 3 });+ const results = await run.runParallel([+ () => run.agent("task 1"),+ () => run.agent("task 2"),+ () => run.agent("task 3"),+ ]);+ expect(runner.calls.length).toBe(2);+ expect(results.filter((r) => r && r.ok).length).toBe(2);+ expect(results.filter((r) => r && !r.ok)[0]?.text).toMatch(/budget exhausted/i);+ expect(run.budget.spent()).toEqual({ calls: 2, tokens: 20 });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });});// ── Run: journal write/replay + prefix resume ────────────────────────────@@ -339,4 +362,10 @@ describe("wire-format helpers", () => {expect(parseBackgroundId("[agent 42 started: label]")).toBe(42);expect(parseBackgroundId("not an ack at all")).toBeNull();});++ test("background status distinguishes a pending poll from a terminal result", () => {+ expect(backgroundResultRunning("[agent 7: running]", 7)).toBe(true);+ expect(backgroundResultRunning("[agent 7: completed in 10ms]\n\ndone", 7)).toBe(false);+ expect(backgroundResultRunning("[agent 8: running]", 7)).toBe(false);+ });});diff --git a/sdk/ts/orchestrate.ts b/sdk/ts/orchestrate.tsindex 08a9a137..6673ab20 100644--- a/sdk/ts/orchestrate.ts+++ b/sdk/ts/orchestrate.ts@@ -85,6 +85,10 @@ export interface SubagentSpec {* dispatching process, then poll it via `agent_output` on the same* process. Default false (synchronous). */background?: boolean;+ /** SDK-side deadline for a background subagent to reach a terminal result.+ * The harness process is closed (and force-killed after its grace period)+ * when this expires. Default 120 seconds. */+ backgroundTimeoutMs?: number;}export interface AgentOptions extends Omit<SubagentSpec, "prompt"> {@@ -94,7 +98,7 @@ export interface AgentOptions extends Omit<SubagentSpec, "prompt"> {model?: string;/** Passthrough to the spawned Harness. `yolo` defaults to true: these are* non-interactive, fully scripted dispatches with nothing to confirm. */- harness?: Pick<HarnessOptions, "binary" | "cwd" | "env" | "yolo">;+ harness?: Pick<HarnessOptions, "binary" | "cwd" | "env" | "yolo" | "maxToolCalls" | "maxModelCalls" | "dedupeToolCalls" | "args">;/** Injectable transport. Defaults to a shared `HarnessRunner`; tests* substitute a fake so orchestration logic never needs a live binary. */runner?: AgentRunner;@@ -190,8 +194,20 @@ export class HarnessRunner implements AgentRunner {if (id === null) {return { ok: false, text: first.result?.text ?? "agent(): could not read a background agent id", usage: first.usage, cached: false };}- const second = await this.drive(h, dispatchPrompt("agent_output", { id, wait_ms: 30000 }), "agent_output");- return second.result ?? { ok: false, text: `agent(): agent_output never returned for id ${id}`, usage: second.usage, cached: false };+ const timeoutMs = Math.max(0, spec.backgroundTimeoutMs ?? 120_000);+ const deadline = Date.now() + timeoutMs;+ do {+ const waitMs = Math.min(30_000, Math.max(0, deadline - Date.now()));+ const poll = await this.drive(h, dispatchPrompt("agent_output", { id, wait_ms: waitMs }), "agent_output");+ if (!poll.result) return { ok: false, text: `agent(): agent_output never returned for id ${id}`, usage: poll.usage, cached: false };+ if (!backgroundResultRunning(poll.result.text, id)) return poll.result;+ } while (Date.now() < deadline);+ return {+ ok: false,+ text: `agent(): background agent ${id} exceeded its ${timeoutMs}ms deadline`,+ usage: first.usage,+ cached: false,+ };} finally {h.close();}@@ -217,6 +233,10 @@ export class HarnessRunner implements AgentRunner {export const defaultRunner: AgentRunner = new HarnessRunner();+export function backgroundResultRunning(text: string, id: number): boolean {+ return text.trimStart().startsWith(`[agent ${id}: running]`);+}+// ── Budget: budget.spent()/remaining()/total, fed by real AgentUsage ────export interface BudgetTotals {@@ -267,6 +287,20 @@ export class Budget {this._calls += 1;this._tokens += usage.contextTokens;}++ /** Atomically reserve one SDK call before asynchronous runner work starts.+ * JavaScript executes this synchronously, so parallel fan-out cannot race+ * several calls through the same remaining slot. */+ reserveCall(): boolean {+ if (this.exhausted()) return false;+ this._calls += 1;+ return true;+ }++ /** Complete a previously reserved call with its measured token usage. */+ chargeReserved(usage: AgentUsage): void {+ this._tokens += usage.contextTokens;+ }}// ── Concurrency ──────────────────────────────────────────────────────────@@ -361,6 +395,7 @@ function toSpec(prompt: string, opts: AgentOptions): SubagentSpec {isolation: opts.isolation,isolationFallback: opts.isolationFallback,background: opts.background,+ backgroundTimeoutMs: opts.backgroundTimeoutMs,};}@@ -380,6 +415,7 @@ function hashOpts(spec: SubagentSpec, model: string | undefined): string {isolation: spec.isolation,isolationFallback: spec.isolationFallback,background: spec.background,+ backgroundTimeoutMs: spec.backgroundTimeoutMs,model,};return createHash("sha256").update(stableStringify(relevant)).digest("hex").slice(0, 16);@@ -483,13 +519,13 @@ export class Run {this.diverged = true;}- if (this.budget.exhausted()) {+ if (!this.budget.reserveCall()) {return { ok: false, text: "agent(): budget exhausted, call not admitted", usage: zeroUsage, cached: false };}const runner = opts.runner ?? this.runner;const result = await runner.run(spec, { model: opts.model, harness: opts.harness });- this.budget.charge(result.usage);+ this.budget.chargeReserved(result.usage);this.appendJournal({ key, promptHash, optsHash, ok: result.ok, text: result.text, usage: result.usage, ts: Date.now() });return result;}diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex cbe3a9f1..63ee482b 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -69,6 +69,7 @@ export interface RemoteOptions {export interface ChatOptions {prompt: string;+ review?: boolean;}export interface AnswerOptions {@@ -167,8 +168,9 @@ export class RemoteHarness {/** Run one turn; async-iterate events up to and including `turn`/`error`. */async *chat(input: string | ChatOptions): AsyncGenerator<Event> {const prompt = typeof input === "string" ? input : input.prompt;+ const type = typeof input === "string" || !input.review ? "user" : "review";let terminal = false;- for await (const ev of this.send({ type: "user", text: prompt })) {+ for await (const ev of this.send({ type, text: prompt })) {yield ev;if (ev.type === "turn" || ev.type === "error") { terminal = true; break; }}@@ -185,6 +187,12 @@ export class RemoteHarness {return final;}+ /** Run one bounded, read-only review turn and return its final report. */+ review(input: string | ChatOptions): Promise<string> {+ const prompt = typeof input === "string" ? input : input.prompt;+ return this.ask({ prompt, review: true });+ }+/** Answer an in-flight ask_user event. The original chat() stream continues* and will later yield the ask_user tool_result plus the final turn. */async answer(input: string | AnswerOptions): Promise<void> {diff --git a/src/agent.zig b/src/agent.zigindex 154ad00a..2c7f7fd3 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -6,7 +6,6 @@const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;-const main_mod = @import("main.zig");const provider_mod = @import("provider.zig");const Provider = provider_mod.Provider;@@ -99,7 +98,8 @@ pub const Agent = struct {sys_override: ?[]const u8 = null, // subagent-only: per-child system prompt (swarm prompt variants)agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their owntools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)- tool_calls_this_turn: u64 = 0, // root-only hard budget counter (--max-tool-calls)+ tool_calls_this_turn: u64 = 0,+ model_calls_this_turn: u32 = 0, // root-only hard per-turn budgetsseen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keysmd_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)md_fence: bool = false, // inside a ``` code fence while streaming@@ -122,7 +122,9 @@ pub const Agent = struct {fallback_allow: []const []const u8 = &.{}, // explicit cross-provider allowlist from .harness/settings.jsonfallback_active: bool = false, // current provider/model is a temporary fallback, not the saved preferencefallback_blocked: bool = false, // startup found a cross-provider fallback that is not allowlisted yet- ultracode_mode: bool = false, // persistent ultracode (multi-agent workflow) mode (/ultracode)+ ultracode_mode: bool = false,+ review_mode: bool = false,+ review_finalizing: bool = false, // transient bounded /review stateshow_thinking: bool = true, // stream the model's reasoning live in the TUI (/thinking); off = spinner onlyai_title: bool = true, // AI-generate the tab/session title from the first prompt (/title)goal: ?Goal = null, // structured objective + status lifecycle (/goal, #223)diff --git a/src/agent_request.zig b/src/agent_request.zigindex 356a336a..afc31e83 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -26,6 +26,7 @@ const apiErrorMessage = tools_mod.apiErrorMessage;const mentionsReasoningEffort = tools_mod.mentionsReasoningEffort;const telemetry = @import("telemetry.zig");const run_budget_mod = @import("run_budget.zig");+const review = @import("review.zig");const policy = @import("agent_request_policy.zig");const errorCode = policy.errorCode;@@ -75,6 +76,21 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// Startup paints the prompt while CA loading continues. The root turn and// title task rendezvous here, then issue their requests concurrently.http.waitForClientReady(self.io);+ var active_tools = tools;+ if (self.review_mode) {+ if (self.model_calls_this_turn >= review.max_model_calls) {+ self.last_api_error = "review model-call budget exhausted after the reserved synthesis pass";+ if (self.tracer) |tr| tr.note("budget", self.last_api_error.?);+ return error.ReviewModelBudgetExhausted;+ }+ self.model_calls_this_turn += 1;+ const global_last = if (self.run_budget) |budget| budget.remaining() <= 1 else false;+ self.review_finalizing = self.model_calls_this_turn == review.max_model_calls or global_last;+ if (self.review_finalizing) {+ try self.messages.append(try messages_mod.textMessage(self.arena, "user", review.final_note));+ active_tools = null;+ }+ }var budget_permit: ?run_budget_mod.Permit = null;if (self.run_budget) |budget| {const kind: run_budget_mod.CallKind = if (self.compaction_request) .compaction else self.call_kind;@@ -92,7 +108,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {self.last_request_context_overflow = false;self.last_request_write_failed = false;self.last_usage_includes_output = false;- var force = (self.strict or self.eval_cmd != null) and tools != null;+ var force = (self.strict or self.eval_cmd != null) and active_tools != null;var stream_usage = true; // openai stream_options; dropped if rejectedvar auth_refreshed = false; // #148: at most one forced token refresh + retry// #124: reclaim last request's transient parse garbage FIRST, so everything@@ -146,7 +162,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {const live = !self.sub and self.out != null and !self.stream_quiet;self.streamed_text = false;self.streamed_args = .none;- const body = try self.buildBody(tools, force, live, stream_usage);+ const body = try self.buildBody(active_tools, force, live, stream_usage);defer self.gpa.free(body);const t0: Io.Timestamp = .now(self.io, .awake);if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex fb4c9639..5ea32e73 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -11,6 +11,7 @@ const Io = std.Io;const Value = std.json.Value;const main_mod = @import("main.zig");+const review = @import("review.zig");const agent_mod = @import("agent.zig");const Agent = agent_mod.Agent;const ToolCall = tools_mod.ToolCall;@@ -200,8 +201,16 @@ test "toolPreviewText caps context and preserves an inspect pointer" {pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {if (self.sub) return null;+ if (self.review_mode) if (try review.rejectTool(self.arena, call, self.review_finalizing)) |denied| {+ self.emitToolRejected(call, "review_mode", denied.text);+ return denied;+ };if (std.mem.eql(u8, call.name, "attempt_completion")) return null;- if (main_mod.max_tool_calls) |max| {+ const effective_max: ?u64 = if (self.review_mode)+ @min(main_mod.max_tool_calls orelse review.max_tool_calls, review.max_tool_calls)+ else+ main_mod.max_tool_calls;+ if (effective_max) |max| {if (self.tool_calls_this_turn >= max) {const message = try std.fmt.allocPrint(self.arena, "tool call budget exhausted ({d}/{d}) — answer with what you have or ask for a higher --max-tool-calls", .{ self.tool_calls_this_turn, max });self.emitToolRejected(call, "budget", message);diff --git a/src/approvals.zig b/src/approvals.zigindex 10f16eb4..d009028d 100644--- a/src/approvals.zig+++ b/src/approvals.zig@@ -138,7 +138,7 @@ pub const Approvals = struct {pub fn readOnlyAllowed(cmd: []const u8) bool {const c = std.mem.trim(u8, cmd, " \t");if (!isSimple(c) or escapesCwd(c)) return false;- for (seed) |p| if (matchesPrefix(c, p)) return true;+ for (read_only_seed) |p| if (matchesPrefix(c, p)) return true;return false;}@@ -406,6 +406,8 @@ test "Approvals.readOnlyAllowed: only simple, in-cwd, seed-listed commands passtry std.testing.expect(!Approvals.readOnlyAllowed("cat /etc/passwd")); // escapes cwdtry std.testing.expect(!Approvals.readOnlyAllowed("ls; rm x")); // not simpletry std.testing.expect(!Approvals.readOnlyAllowed("git push")); // mutating git verb, not seeded+ try std.testing.expect(!Approvals.readOnlyAllowed("zig build")); // build.zig can execute arbitrary code+ try std.testing.expect(!Approvals.readOnlyAllowed("zig fmt src")); // formatter rewrites files}test "Approvals.readOnlyExternal: read-only verb reading outside cwd, simple only (#64)" {diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex e2fdf5ff..ca9f9e9a 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -28,6 +28,7 @@ pub const commands = [_]Item{.{ .name = "/rename", .usage = "/rename <title>", .desc = "set the current session title" },.{ .name = "/goal", .usage = "/goal [text|pause|resume|status|clear]", .desc = "set/show a standing objective (tracked as a checklist); pause/resume steering, status shows state, clear removes it" },.{ .name = "/loop", .usage = "/loop <prompt>", .desc = "run an autonomous plan->act->verify pass" },+ .{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one bounded read-only review pass; no edits, delegation, or workflows" },.{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },.{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },.{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },diff --git a/src/commands_session.zig b/src/commands_session.zigindex 03359385..f8a10c3d 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -165,6 +165,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}+ if (std.mem.eql(u8, line, "/review")) {+ try out.writeAll("usage: /review <target or instructions> — one bounded read-only review pass.\n");+ try out.flush();+ return true;+ }if (std.mem.eql(u8, line, "/bash") or std.mem.startsWith(u8, line, "/bash ")) {const cmd = std.mem.trim(u8, line["/bash".len..], " \t\r\n");if (cmd.len == 0) {diff --git a/src/hooks.zig b/src/hooks.zigindex 1df4e454..27519782 100644--- a/src/hooks.zig+++ b/src/hooks.zig@@ -191,13 +191,23 @@ const jobs = @import("jobs.zig");/// Per-file cache for the codedb guard: `codedb outline <path>` is run once/// per source file to check whether codedb actually indexed it (large files-/// are silently skipped — e.g. a 13K-line main.zig). Entries are page-alloc-/// and never freed; the set is small (only files the agent greps). A mutex-/// guards concurrent tool-thread access; a miss is benign (duplicate probe).+/// are silently skipped — e.g. a 13K-line main.zig). A mutex guards concurrent+/// tool-thread access; a miss is benign (duplicate probe).pub const CodedbFileCheck = struct { path: []const u8, indexed: bool };var g_codedb_file_checks: std.ArrayList(CodedbFileCheck) = .empty;var g_codedb_file_mu: Io.Mutex = .init;+pub fn deinitCodedbCache(gpa: Allocator, io: Io) void {+ g_codedb_file_mu.lockUncancelable(io);+ const entries = g_codedb_file_checks.toOwnedSlice(gpa) catch {+ g_codedb_file_mu.unlock(io);+ return;+ };+ g_codedb_file_mu.unlock(io);+ for (entries) |entry| gpa.free(entry.path);+ gpa.free(entries);+}+/// True when `path` is in codedb's symbol index. Runs `codedb outline <path>`/// (cached): returns "not indexed: <path>" when the file is too large or/// otherwise skipped, so the guard knows to let bash through instead ofdiff --git a/src/main.zig b/src/main.zigindex 46c2987c..98596165 100644--- a/src/main.zig+++ b/src/main.zig@@ -253,6 +253,7 @@ pub fn main(init: std.process.Init) !void {// reset each request() so a long REPL/--json/serve session's RSS stays flat.var scratch_state = std.heap.ArenaAllocator.init(gpa);defer scratch_state.deinit();+ defer hooks.deinitCodedbCache(gpa, io);g_session_arena = init.arena;g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.diff --git a/src/mainloop.zig b/src/mainloop.zigindex 97346154..881abba7 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -36,6 +36,7 @@ const hooks = @import("hooks.zig");const readline = @import("readline.zig");const title_mod = @import("title.zig");const mainloop_title = @import("mainloop_title.zig");+const review = @import("review.zig");/// Borrowed pointers into main()'s stack plus immutable arena-owned prompt slices.pub const Ctx = struct {@@ -114,6 +115,7 @@ pub fn run(ctx: *Ctx) !void {std.mem.trim(u8, line["/loop".len..], " \t")elsenull;+ var review_prompt: ?[]const u8 = if (!main_mod.json_mode) review.promptFromLine(line) else null;// /goal <objective>: set the standing goal AND run it as the first turn// right away — codex/opencode both start the loop on a goal instead of// just recording it. Bare /goal (show) and /goal clear/off stay commands.@@ -127,7 +129,7 @@ pub fn run(ctx: *Ctx) !void {if (std.mem.eql(u8, l, "exit") or std.mem.eql(u8, l, "quit") or std.mem.eql(u8, l, "q")) break;}- if (!main_mod.json_mode and repl_glue.isSlashCommandLine(line) and loop_prompt == null and goal_prompt == null) {+ if (!main_mod.json_mode and repl_glue.isSlashCommandLine(line) and loop_prompt == null and goal_prompt == null and review_prompt == null) {// Bare "/" on a TTY: open the filterable command menu.if (ctx.interactive and line.len == 1) {if (pickers.listPicker(ctx.root, ctx.arena, ctx.out, "Command ›", &pickers.command_menu)) |idx| {@@ -146,7 +148,7 @@ pub fn run(ctx: *Ctx) !void {// JSON lines may run a user turn, mutate the system prompt, or append a score.var json_request: ?std.json.Parsed(Value) = null;defer if (json_request) |*request| request.deinit();- const base_msg: []const u8 = if (loop_prompt) |lp| lp else if (goal_prompt) |gp| gp else if (main_mod.json_mode) blk: {+ const base_msg: []const u8 = if (review_prompt) |rp| rp else if (loop_prompt) |lp| lp else if (goal_prompt) |gp| gp else if (main_mod.json_mode) blk: {json_request = std.json.parseFromSlice(Value, ctx.gpa, line, .{ .allocate = .alloc_if_needed }) catch {ctx.root.emit(.{ .type = "error", .message = "invalid JSON (expect {\"type\":\"user\",\"text\":\"...\"})" });continue;@@ -272,6 +274,7 @@ pub fn run(ctx: *Ctx) !void {ctx.root.emit(.{ .type = "system_prompt", .ok = true, .append = append, .chars = ctx.root.sys_normal.len });continue;}+ if (std.mem.eql(u8, rtype, "review")) review_prompt = text;if (parsed.object.get("maxToolCalls") orelse parsed.object.get("max_tool_calls")) |v| switch (v) {.integer => |n| main_mod.max_tool_calls = if (n >= 0) @intCast(n) else null,.null => main_mod.max_tool_calls = null,@@ -282,6 +285,12 @@ pub fn run(ctx: *Ctx) !void {}break :blk text;} else line;+ ctx.root.review_mode = review_prompt != null;+ ctx.root.review_finalizing = false;+ defer {+ ctx.root.review_mode = false;+ ctx.root.review_finalizing = false;+ }if (ctx.root.fallback_blocked) {const message = try std.fmt.allocPrint(ctx.arena, "saved model unavailable; sending to {s} requires explicit consent — run /fallback allow {s} or choose /model", .{ ctx.root.provider.id, ctx.root.provider.id });@@ -296,8 +305,8 @@ pub fn run(ctx: *Ctx) !void {// live todo_write checklist, with the current list appended so the model// resumes the plan instead of re-deriving it (assembled by goalSteeringNote).const todos_render: []const u8 = if (ctx.root.todos.items.len > 0) ctx.root.renderTodos() else "";- const goal_note = try repl_glue.goalSteeringNote(ctx.arena, ctx.root.goal, todos_render);- const eval_note = try repl_glue.evalSteeringNote(+ const goal_note = if (ctx.root.review_mode) "" else try repl_glue.goalSteeringNote(ctx.arena, ctx.root.goal, todos_render);+ const eval_note = if (ctx.root.review_mode) "" else try repl_glue.evalSteeringNote(ctx.arena,ctx.root.eval_cmd,ctx.root.eval_target,@@ -319,7 +328,8 @@ pub fn run(ctx: *Ctx) !void {// Plan mode: steer the model to explore read-only and present a plan// (the gate enforces the read-only part regardless).- const msg: []const u8 = if (!main_mod.plan_mode) loop_msg else try std.fmt.allocPrint(ctx.arena,+ const review_msg = if (review_prompt != null) try review.steeringNote(ctx.arena, loop_msg) else loop_msg;+ const msg: []const u8 = if (!main_mod.plan_mode) review_msg else try std.fmt.allocPrint(ctx.arena,\\{s}\\\\[harness note: plan mode is ON — read-only. Explore with read-only@@ -327,7 +337,7 @@ pub fn run(ctx: *Ctx) !void {\\the changes themselves, sequence, risks) and ask the user to\\approve it. Do not write files or run mutating commands — the\\gate will deny them. The user toggles execution back on with /plan.]- , .{loop_msg});+ , .{review_msg});// Promote a GUI `@[image]` attachment to a native vision block when the// model can see (otherwise it only gets the path and resorts to OCR).@@ -335,7 +345,7 @@ pub fn run(ctx: *Ctx) !void {// Generate the AI title before the root turn and publish it through the// session-scoped nonblocking completion queue.- if (!main_mod.json_mode and ctx.root.ai_title and !ctx.root.ai_title_done) {+ if (!main_mod.json_mode and !ctx.root.review_mode and ctx.root.ai_title and !ctx.root.ai_title_done) {ctx.root.ai_title_done = true;title_jobs.start(ctx, base_msg);}@@ -357,7 +367,10 @@ pub fn run(ctx: *Ctx) !void {}// "ultracode" codeword or persistent /ultracode mode: opt turns into multi-agent workflow mode.- const ultracode_msg = try pickers.applyUltracodeSteering(ctx.arena, msg, base_msg, ctx.root.ultracode_mode or ctx.root.reasoning == .ultra);+ const ultracode_msg = if (ctx.root.review_mode)+ pickers.UltracodeMessage{ .text = msg, .explicit = false }+ else+ try pickers.applyUltracodeSteering(ctx.arena, msg, base_msg, ctx.root.ultracode_mode or ctx.root.reasoning == .ultra);if (ultracode_msg.explicit) {if (!main_mod.json_mode) {if (ctx.interactive) {@@ -386,6 +399,7 @@ pub fn run(ctx: *Ctx) !void {} else 0;ctx.root.tools_used.clear(ctx.io); // per-turn tool log for the turn's nodectx.root.tool_calls_this_turn = 0;+ ctx.root.model_calls_this_turn = 0;ctx.root.seen_tool_keys.clearRetainingCapacity();if (main_mod.json_mode) ctx.root.emit(.{ .type = "started", .provider = ctx.root.provider.id, .model = ctx.root.provider.model });// Breathing room between the submitted input and the turn's firstdiff --git a/src/repl_util.zig b/src/repl_util.zigindex e3a4c73f..2a051b74 100644--- a/src/repl_util.zig+++ b/src/repl_util.zig@@ -19,7 +19,7 @@ pub const HELP_CHAT =\\ /plan /strict /yolo /keepcontext /title modes\\ /rename <name> /animation enso|braille|dragon\\ /bash /save /resume /sessions /trace /trajectory- \\ /agents /skills /hooks /mcp /loop /image /paste /key+ \\ /agents /skills /hooks /mcp /loop /review /image /paste /key\\\\Type a message and press enter to send it to the model. Toggles accept\\[on|off] or flip when bare. Commands needing the agent loop explain so.diff --git a/src/review.zig b/src/review.zignew file mode 100644index 00000000..06db14dd--- /dev/null+++ b/src/review.zig@@ -0,0 +1,88 @@+//! Bounded review-mode policy. A review is a separate, one-shot execution+//! layer: report findings, never silently cross into remediation or delegation.++const std = @import("std");+const ToolCall = @import("tools.zig").ToolCall;+const ExecResult = @import("tools.zig").ExecResult;+const Approvals = @import("approvals.zig").Approvals;++pub const max_model_calls: u32 = 10;+pub const max_tool_calls: u64 = 40;+pub const final_note =+ "Review exploration budget reached. Do not call tools. Return the prioritized, actionable findings you can defend from the evidence already gathered, then the overall verdict. If none qualify, say \"No findings.\"";++pub fn promptFromLine(line: []const u8) ?[]const u8 {+ if (!std.mem.startsWith(u8, line, "/review ")) return null;+ const prompt = std.mem.trim(u8, line["/review".len..], " \t\r\n");+ return if (prompt.len == 0) null else prompt;+}++pub fn steeringNote(arena: std.mem.Allocator, prompt: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena,+ \\{s}+ \\+ \\[review mode: Perform one read-only, defect-first review pass. Inspect+ \\the requested target directly. Start by resolving the comparison and+ \\reading the complete git diff (including staged, unstaged, and untracked+ \\changes when applicable). Run each git command as a separate shell call;+ \\chained commands are rejected. Code search alone is not a review. Continue+ \\through the whole diff, then inspect enough surrounding code, tests, and+ \\callers to prove each issue. Do not modify files, delegate, run workflows,+ \\use the network, or switch from review into implementation. Report only+ \\discrete, actionable regressions the author would likely fix, findings+ \\first and ordered P0-P3 with the smallest useful file:line range. If none+ \\qualify, say "No findings." Then give a brief overall verdict and stop.]+ , .{prompt});+}++/// Hard capability boundary for a review root. Only local reads/searches,+/// read-only shell inspection, and explicit finalization are admitted.+pub fn rejectTool(arena: std.mem.Allocator, call: ToolCall, finalizing: bool) !?ExecResult {+ if (finalizing and !std.mem.eql(u8, call.name, "attempt_completion")) return denied(arena, call.name);+ if (std.mem.eql(u8, call.name, "read_file") or+ std.mem.eql(u8, call.name, "codedb") or+ std.mem.eql(u8, call.name, "attempt_completion")) return null;++ if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {+ const command = call.input.object.get("command") orelse return denied(arena, call.name);+ const background = call.input.object.get("run_in_background");+ if (command == .string and+ (background == null or background.? != .bool or !background.?.bool) and+ Approvals.readOnlyAllowed(command.string)) return null;+ }+ return denied(arena, call.name);+}++fn denied(arena: std.mem.Allocator, name: []const u8) !?ExecResult {+ return .{+ .text = try std.fmt.allocPrint(arena, "review mode is read-only and single-pass; {s} is unavailable — report findings without changing or delegating work", .{name}),+ .is_error = true,+ };+}++test "review command requires a non-empty target" {+ try std.testing.expectEqualStrings("HEAD against main", promptFromLine("/review HEAD against main").?);+ try std.testing.expect(promptFromLine("/review") == null);+ try std.testing.expect(promptFromLine("/review ") == null);+ try std.testing.expect(promptFromLine("please review this") == null);+}++test "review tool boundary admits reads and rejects edits, delegation, and background shell" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const empty = std.json.parseFromSliceLeaky(std.json.Value, arena, "{}", .{}) catch unreachable;+ const read: ToolCall = .{ .id = "1", .name = "read_file", .input = empty };+ const edit: ToolCall = .{ .id = "2", .name = "edit_file", .input = empty };+ const workflow: ToolCall = .{ .id = "3", .name = "workflow", .input = empty };+ const background: ToolCall = .{+ .id = "4",+ .name = "bash",+ .input = std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"command\":\"git status\",\"run_in_background\":true}", .{}) catch unreachable,+ };+ try std.testing.expect((try rejectTool(arena, read, false)) == null);+ try std.testing.expect((try rejectTool(arena, edit, false)).?.is_error);+ try std.testing.expect((try rejectTool(arena, workflow, false)).?.is_error);+ try std.testing.expect((try rejectTool(arena, background, false)).?.is_error);+ try std.testing.expect((try rejectTool(arena, read, true)).?.is_error);+}diff --git a/src/schema.zig b/src/schema.zigindex 9a0f39be..95b2aede 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -52,7 +52,7 @@ const schema_flags_json =\\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},\\ {"flag": "--json", "arg": null, "description": "structured stdio protocol (JSON in, JSONL events out)"},\\ {"flag": "--max-tool-calls", "arg": "N", "description": "hard per-turn root tool-call budget; rejected calls emit tool_rejected/tool_result"},- \\ {"flag": "--max-model-calls", "arg": "N", "description": "invocation-wide provider-call ceiling shared by root, subagents, retries, title, compaction, and judges; default 256"},+ \\ {"flag": "--max-model-calls", "arg": "N", "description": "invocation-wide provider-call ceiling shared by root, subagents, retries, title, compaction, and judges; default unlimited (bounded /review has its own 10-call ceiling)"},\\ {"flag": "--dedupe-tool-calls", "arg": null, "description": "reject duplicate root tool name+normalized-input calls per turn"},\\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"},\\ {"flag": "--learning-privacy", "arg": "local|aggregate|templates|examples", "description": "set the prompt-learning egress ceiling; default local, and template text still requires exact interactive approval"}diff --git a/src/schema_protocol.zig b/src/schema_protocol.zigindex 395da7a6..eaa4aec9 100644--- a/src/schema_protocol.zig+++ b/src/schema_protocol.zig@@ -3,7 +3,7 @@pub const json =\\{\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one bounded read-only review turn with no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",\\ "events": [\\ {"type": "text", "text": "assistant text delta"},