Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(review): match Codex one-shot semantics

Rach Pradhanecfbbbcb117c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 31cd0e2c..1e6f14b4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -76,7 +76,7 @@ jobs:
- name: JSON live-control protocol test
run: python3 scripts/test-json-controls.py zig-out/bin/graff
- - name: Bounded review mode regression
+ - name: Isolated read-only review regression
run: python3 scripts/test-review-mode.py zig-out/bin/graff
- name: Streamable HTTP MCP handshake and session regression
diff --git a/README.md b/README.md
index 9f2752ba..790ed902 100644
--- a/README.md
+++ b/README.md
@@ -469,9 +469,11 @@ blocked, cancelled, or exhausted) once the work is done, you step in, or a safet
limit 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.
+read/search tools and read-only shell inspection, and runs with fresh
+model-visible history and a 40-tool ceiling. There is no review-specific model
+call limit; the ordinary invocation budget is unlimited by default, while an
+explicit `--max-model-calls` still applies. Only the request and final report
+join the parent transcript. Use a later, explicit turn to fix accepted findings.
### MCP servers
diff --git a/scripts/test-review-mode.py b/scripts/test-review-mode.py
index f860b861..7a8bdda2 100644
--- a/scripts/test-review-mode.py
+++ b/scripts/test-review-mode.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Prove review turns are read-only, single-agent, and model-call bounded."""
+"""Prove review turns are isolated, read-only, and naturally terminating."""
from __future__ import annotations
@@ -15,7 +15,9 @@ 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."
+LONG_REPLY = "No findings. Review completed after more than ten calls."
+PARENT_REPLY = "Parent context acknowledged."
+ISOLATED_REPLY = "No findings. Isolated review completed."
def response_events(item: dict, response_id: str) -> list[dict]:
@@ -76,12 +78,26 @@ def review_events(request: RecordedRequest) -> list[dict]:
return message(FINAL_REPLY, request.ordinal)
+def long_review_events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal > 12:
+ return message(LONG_REPLY, request.ordinal)
+ return tool("read_file", {"path": "target.txt"}, 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 isolation_events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal == 1:
+ return message(PARENT_REPLY, request.ordinal)
+ if request.ordinal == 2:
+ return tool("read_file", {"path": "target.txt"}, request.ordinal)
+ if request.ordinal == 3:
+ return message(ISOLATED_REPLY, request.ordinal)
+ return message("Follow-up complete.", 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)
@@ -109,13 +125,13 @@ def environment(tmp: str, port: int) -> dict[str, str]:
return env
-def run_review(
+def start_graff(
tmp: str, port: int, max_model_calls: int | None = None
-) -> tuple[list[dict], subprocess.Popen[str]]:
+) -> 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(
+ return subprocess.Popen(
argv,
cwd=tmp,
env=environment(tmp, port),
@@ -125,8 +141,11 @@ def run_review(
text=True,
bufsize=1,
)
+
+
+def send(process: subprocess.Popen[str], payload: dict) -> list[dict]:
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.write(json.dumps(payload) + "\n")
process.stdin.flush()
events: list[dict] = []
for line in process.stdout:
@@ -134,7 +153,14 @@ def run_review(
events.append(event)
if event.get("type") in ("turn", "error"):
break
- return events, process
+ return events
+
+
+def run_review(
+ tmp: str, port: int, max_model_calls: int | None = None
+) -> tuple[list[dict], subprocess.Popen[str]]:
+ process = start_graff(tmp, port, max_model_calls)
+ return send(process, {"type": "review", "text": "Review target.txt"}), process
def close(process: subprocess.Popen[str]) -> None:
@@ -183,18 +209,18 @@ def main() -> None:
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()
+ long_mock = CodexMock(events_for_request=long_review_events)
+ long_port = long_mock.start()
try:
- budget_events, budget_process = run_review(tmp, budget_port)
- close(budget_process)
+ long_events, long_process = run_review(tmp, long_port)
+ close(long_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}")
+ long_mock.stop()
+ calls = len(long_mock.recorded_requests())
+ if calls != 13:
+ raise AssertionError(f"default review unexpectedly stopped after {calls} calls")
+ if long_events[-1].get("type") != "turn" or long_events[-1].get("text") != LONG_REPLY:
+ raise AssertionError(f"long review did not terminate naturally: {long_events[-1]!r}")
global_mock = CodexMock(events_for_request=loop_events)
global_port = global_mock.start()
@@ -204,11 +230,34 @@ def main() -> None:
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}")
+ raise AssertionError("explicit global model-call budget was not enforced")
+ if global_events[-1].get("type") != "error":
+ raise AssertionError(f"global-budget exhaustion was not surfaced: {global_events[-1]!r}")
+
+ isolation_mock = CodexMock(events_for_request=isolation_events)
+ isolation_port = isolation_mock.start()
+ isolation_process = start_graff(tmp, isolation_port)
+ try:
+ send(isolation_process, {"type": "user", "text": "PARENT_SENTINEL"})
+ send(isolation_process, {"type": "review", "text": "Review target.txt"})
+ send(isolation_process, {"type": "user", "text": "FOLLOWUP_SENTINEL"})
+ close(isolation_process)
+ finally:
+ isolation_mock.stop()
+ requests = isolation_mock.recorded_requests()
+ review_input = json.dumps(requests[1].body.get("input"))
+ if "PARENT_SENTINEL" in review_input or PARENT_REPLY in review_input:
+ raise AssertionError("review inherited the parent model-visible history")
+ if "[review task:" not in requests[1].body.get("instructions", ""):
+ raise AssertionError("review rubric was not installed as base instructions")
+ followup_input = json.dumps(requests[3].body.get("input"))
+ for expected_text in ("PARENT_SENTINEL", PARENT_REPLY, "Review target.txt", ISOLATED_REPLY):
+ if expected_text not in followup_input:
+ raise AssertionError(f"parent transcript lost {expected_text!r}")
+ if "function_call" in followup_input or "call_review_2" in followup_input:
+ raise AssertionError("review-internal tool history leaked into the parent transcript")
- print("ok review rejects mutation/delegation and reserves local/global synthesis")
+ print("ok review is isolated/read-only, admits >10 calls, and honors opt-in budgets")
if __name__ == "__main__":
diff --git a/sdk/README.md b/sdk/README.md
index 51c6ac2b..1c14dd52 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -56,7 +56,7 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5
const 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-only
+console.log(await session.review("review HEAD against main")); // isolated + read-only
for 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 });
}
@@ -66,7 +66,7 @@ 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 }`;
-`review()` runs a bounded read-only review turn.
+`review()` runs an isolated read-only review turn with fresh model-visible history.
## Remote (edge runtimes — no local binary)
diff --git a/sdk/generate.py b/sdk/generate.py
index 27159989..ed4e93dd 100644
--- a/sdk/generate.py
+++ b/sdk/generate.py
@@ -127,7 +127,7 @@ export interface HarnessOptions {{
export interface ChatOptions {{
/** User prompt for this turn. */
prompt: string;
- /** Run this turn in bounded, read-only review mode. */
+ /** Run this turn in isolated, read-only review mode. */
review?: boolean;
}}
@@ -341,7 +341,7 @@ export class Harness {{
return final;
}}
- /** Run one bounded, read-only review turn and return its final report. */
+ /** Run one isolated, 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 }});
@@ -688,7 +688,7 @@ export class RemoteHarness {{
return final;
}}
- /** Run one bounded, read-only review turn and return its final report. */
+ /** Run one isolated, 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 }});
@@ -1054,7 +1054,7 @@ class Harness:
return final
def review(self, text: str) -> str:
- """Run one bounded, read-only review turn and return its report."""
+ """Run one isolated, read-only review turn and return its report."""
final = ""
for ev in self.chat(text, review=True):
if ev.get("type") == "turn":
@@ -1310,7 +1310,7 @@ class RemoteHarness:
return final
def review(self, text: str) -> str:
- """Run one bounded, read-only review turn and return its report."""
+ """Run one isolated, read-only review turn and return its report."""
final = ""
for ev in self.chat(text, review=True):
if ev.get("type") == "turn":
diff --git a/sdk/py/README.md b/sdk/py/README.md
index 5a110a2e..204f6fc5 100644
--- a/sdk/py/README.md
+++ b/sdk/py/README.md
@@ -41,7 +41,7 @@ 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
+ # isolated review: fresh context, local reads only, no edits/delegation/workflows
print(h.review("review HEAD against main"))
# replace or extend the system prompt
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index 89457d63..f09ef96a 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -284,7 +284,7 @@ class Harness:
return final
def review(self, text: str) -> str:
- """Run one bounded, read-only review turn and return its report."""
+ """Run one isolated, read-only review turn and return its report."""
final = ""
for ev in self.chat(text, review=True):
if ev.get("type") == "turn":
@@ -540,7 +540,7 @@ class RemoteHarness:
return final
def review(self, text: str) -> str:
- """Run one bounded, read-only review turn and return its report."""
+ """Run one isolated, read-only review turn and return its report."""
final = ""
for ev in self.chat(text, review=True):
if ev.get("type") == "turn":
diff --git a/sdk/ts/README.md b/sdk/ts/README.md
index 7f51204e..e46f97df 100644
--- a/sdk/ts/README.md
+++ b/sdk/ts/README.md
@@ -37,7 +37,7 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5
const 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-only
+console.log(await session.review("review HEAD against main")); // isolated + read-only
for 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 });
}
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 6b49fa91..bbf28e3b 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -76,7 +76,7 @@ export interface HarnessOptions {
export interface ChatOptions {
/** User prompt for this turn. */
prompt: string;
- /** Run this turn in bounded, read-only review mode. */
+ /** Run this turn in isolated, read-only review mode. */
review?: boolean;
}
@@ -290,7 +290,7 @@ export class Harness {
return final;
}
- /** Run one bounded, read-only review turn and return its final report. */
+ /** Run one isolated, 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 });
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index 63ee482b..4d74ca16 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -187,7 +187,7 @@ export class RemoteHarness {
return final;
}
- /** Run one bounded, read-only review turn and return its final report. */
+ /** Run one isolated, 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 });
diff --git a/src/agent.zig b/src/agent.zig
index 2c7f7fd3..8a3094ca 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -95,11 +95,10 @@ pub const Agent = struct {
call_kind: run_budget_mod.CallKind = .root,
last_cache_read: u64 = 0, // KV-cache read tokens from the latest response
sys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)
- sys_override: ?[]const u8 = null, // subagent-only: per-child system prompt (swarm prompt variants)
+ sys_override: ?[]const u8 = null, // per-child custom prompt or transient isolated-review base
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 own
tools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)
tool_calls_this_turn: u64 = 0,
- model_calls_this_turn: u32 = 0, // root-only hard per-turn budgets
seen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keys
md_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)
md_fence: bool = false, // inside a ``` code fence while streaming
@@ -124,7 +123,6 @@ pub const Agent = struct {
fallback_blocked: bool = false, // startup found a cross-provider fallback that is not allowlisted yet
ultracode_mode: bool = false,
review_mode: bool = false,
- review_finalizing: bool = false, // transient bounded /review state
show_thinking: bool = true, // stream the model's reasoning live in the TUI (/thinking); off = spinner only
ai_title: bool = true, // AI-generate the tab/session title from the first prompt (/title)
goal: ?Goal = null, // structured objective + status lifecycle (/goal, #223)
@@ -273,6 +271,7 @@ pub const Agent = struct {
w.flush() catch return;
}
pub fn systemPrompt(self: *const Agent) []const u8 {
+ if (self.review_mode) return self.sys_override orelse self.sys_normal;
if (self.sub) return self.sys_override orelse prompts.sub_system_prompt;
return if (self.strict) self.sys_strict else self.sys_normal;
}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index afc31e83..70744109 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -26,7 +26,6 @@ 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;
@@ -76,21 +75,6 @@ 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;
@@ -108,7 +92,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 active_tools != null;
+ var force = !self.review_mode and (self.strict or self.eval_cmd != null) and tools != null;
var stream_usage = true; // openai stream_options; dropped if rejected
var auth_refreshed = false; // #148: at most one forced token refresh + retry
// #124: reclaim last request's transient parse garbage FIRST, so everything
@@ -162,7 +146,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(active_tools, force, live, stream_usage);
+ const body = try self.buildBody(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.zig
index 5ea32e73..2228cd3b 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -201,7 +201,7 @@ 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| {
+ if (self.review_mode) if (try review.rejectTool(self.arena, call)) |denied| {
self.emitToolRejected(call, "review_mode", denied.text);
return denied;
};
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index ca9f9e9a..19cdcf20 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -28,7 +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 = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated 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.zig
index f8a10c3d..f3f50d85 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -166,7 +166,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
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.writeAll("usage: /review <target or instructions> — one isolated read-only review pass.\n");
try out.flush();
return true;
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 881abba7..2449eee6 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -286,10 +286,12 @@ pub fn run(ctx: *Ctx) !void {
break :blk text;
} else line;
ctx.root.review_mode = review_prompt != null;
- ctx.root.review_finalizing = false;
+ const parent_system_override = ctx.root.sys_override;
+ if (ctx.root.review_mode)
+ ctx.root.sys_override = try review.systemPrompt(ctx.arena, if (ctx.root.strict) ctx.root.sys_strict else ctx.root.sys_normal);
defer {
ctx.root.review_mode = false;
- ctx.root.review_finalizing = false;
+ ctx.root.sys_override = parent_system_override;
}
if (ctx.root.fallback_blocked) {
@@ -326,10 +328,7 @@ pub fn run(ctx: *Ctx) !void {
\\[harness note: /loop was used. Work autonomously until the prompt is satisfied: make a brief plan, execute it with tools, verify the result, and only stop when you can report completion or you need a required human decision. Keep iterations tight and avoid asking for confirmation between routine steps.]
, .{goal_msg}) else goal_msg;
- // Plan mode: steer the model to explore read-only and present a plan
- // (the gate enforces the read-only part regardless).
- 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,
+ const msg: []const u8 = if (!main_mod.plan_mode or ctx.root.review_mode) loop_msg else try std.fmt.allocPrint(ctx.arena,
\\{s}
\\
\\[harness note: plan mode is ON — read-only. Explore with read-only
@@ -337,7 +336,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.]
- , .{review_msg});
+ , .{loop_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).
@@ -384,6 +383,9 @@ pub fn run(ctx: *Ctx) !void {
ctx.root.tracer.?.note("ultracode", msg[0..@min(msg.len, 120)]);
if (telemetry.g_telem) |t| t.ultracode();
}
+ var review_context = review.Context.begin(ctx.arena, &ctx.root.messages, ctx.root.review_mode);
+ if (ctx.root.review_mode) ctx.root.rebaseContextMeter();
+ defer if (review_context.restore(&ctx.root.messages)) ctx.root.rebaseContextMeter();
if (ctx.root.pending_image) |img| {
try ctx.root.messages.append(try vision.imageMessage(ctx.arena, ctx.root.provider.kind, ultracode_msg.text, img));
ctx.root.pending_image = null;
@@ -399,12 +401,8 @@ pub fn run(ctx: *Ctx) !void {
} else 0;
ctx.root.tools_used.clear(ctx.io); // per-turn tool log for the turn's node
ctx.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 first
- // output — without it the reply starts on the very next line and
- // reads as a continuation of what the user typed.
if (ctx.interactive and !main_mod.json_mode) {
try ctx.out.writeAll("\n");
try ctx.out.flush();
@@ -415,11 +413,14 @@ pub fn run(ctx: *Ctx) !void {
// reported inside request(); anything else is surfaced here. Either
// way we drop back to the prompt (or emit a JSON error/turn event).
const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys, ctx.arena, ctx.out);
- // No successful-path history mutation occurs between the trajectory,
- // terminal event, and compaction gate. Reuse one full-history scan for
- // all three instead of serializing an increasingly large history 3x.
+ // Reuse one full-history scan for trace, terminal event, and compaction.
const post_turn_context_tokens = ctx.root.effectiveContextTokens();
mainloop_trace.record(ctx.root, ctx.io, ctx.arena, base_msg, turn_id, turn_started, turn_result, post_turn_context_tokens, turn_before, &prev_turn_id, &prev_prompt_fp);
+ const isolated_review = review_context.restore(&ctx.root.messages);
+ if (isolated_review) {
+ ctx.root.rebaseContextMeter();
+ try ctx.root.messages.append(try messages.textMessage(ctx.arena, "user", base_msg));
+ }
const final_text = turn_result catch |err| switch (err) {
error.Interrupted => {
// Esc: keep what streamed so far in history (as an assistant
@@ -515,13 +516,15 @@ pub fn run(ctx: *Ctx) !void {
continue;
},
};
+ if (isolated_review)
+ try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", final_text));
+ const session_context_tokens = if (isolated_review) ctx.root.effectiveContextTokens() else post_turn_context_tokens;
if (main_mod.json_mode) {
const emitted_text = if (final_text.len == 0 and ctx.root.partial_text.items.len > 0)
std.mem.trim(u8, ctx.root.partial_text.items, " \t\r\n")
else
final_text;
ctx.root.emit(.{ .type = "finalizing" });
- const context_tokens = post_turn_context_tokens;
// #124: allocator-level leak telemetry (GRAFF_MEM_DEBUG=1) — arena
// capacity per turn separates a session-arena leak from gpa-side
// growth, which OS-level RSS sampling can't tell apart. Emit this
@@ -532,7 +535,7 @@ pub fn run(ctx: *Ctx) !void {
.session_arena_kb = if (main_mod.g_session_arena) |a| a.queryCapacity() / 1024 else 0,
.scratch_arena_kb = if (ctx.root.scratch_arena) |a| a.queryCapacity() / 1024 else 0,
});
- ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = !ctx.root.eval_repair_pending, .metadata_complete = context_tokens > 0 });
+ ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = session_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = !ctx.root.eval_repair_pending, .metadata_complete = session_context_tokens > 0 });
}
// Apply only if already complete; poll never waits for title generation.
@@ -548,11 +551,10 @@ pub fn run(ctx: *Ctx) !void {
}
}
- const context_tokens = post_turn_context_tokens;
- if (context_tokens >= ctx.root.provider.compactAt()) {
+ if (session_context_tokens >= ctx.root.provider.compactAt()) {
// Trim on failure only when we're genuinely against the window — at
// 80–95% a transient compaction failure can recover next turn.
- const near_cap = ctx.root.provider.nearContextLimit(context_tokens);
+ const near_cap = ctx.root.provider.nearContextLimit(session_context_tokens);
ctx.root.compactOrRecover(near_cap);
}
diff --git a/src/providers.zig b/src/providers.zig
index 4691332b..be1a63ac 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -216,6 +216,8 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*I
if (root.tracer) |tr| tr.textDelta(text);
return text;
} else |err| {
+ // A Codex-shaped review is an isolated one-shot, not a provider switch for its parent.
+ if (root.review_mode) return err;
if (err != error.ApiError or root.partial_text.items.len != 0 or root.tool_calls_this_turn != 0)
return err;
const detail = root.last_api_error orelse return err;
diff --git a/src/review.zig b/src/review.zig
index 06db14dd..93a902cc 100644
--- a/src/review.zig
+++ b/src/review.zig
@@ -1,4 +1,4 @@
-//! Bounded review-mode policy. A review is a separate, one-shot execution
+//! Isolated 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");
@@ -6,10 +6,28 @@ 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.\"";
+
+/// Give a review a fresh model-visible history while retaining the parent
+/// transcript. The caller restores the parent after the one-shot review and
+/// records only its user request and final report there.
+pub const Context = struct {
+ parent: ?std.json.Array = null,
+
+ pub fn begin(arena: std.mem.Allocator, messages: *std.json.Array, isolate: bool) Context {
+ if (!isolate) return .{};
+ const parent = messages.*;
+ messages.* = std.json.Array.init(arena);
+ return .{ .parent = parent };
+ }
+
+ pub fn restore(self: *Context, messages: *std.json.Array) bool {
+ const parent = self.parent orelse return false;
+ messages.* = parent;
+ self.parent = null;
+ return true;
+ }
+};
pub fn promptFromLine(line: []const u8) ?[]const u8 {
if (!std.mem.startsWith(u8, line, "/review ")) return null;
@@ -17,11 +35,11 @@ pub fn promptFromLine(line: []const u8) ?[]const u8 {
return if (prompt.len == 0) null else prompt;
}
-pub fn steeringNote(arena: std.mem.Allocator, prompt: []const u8) ![]const u8 {
+pub fn systemPrompt(arena: std.mem.Allocator, base: []const u8) ![]const u8 {
return std.fmt.allocPrint(arena,
\\{s}
\\
- \\[review mode: Perform one read-only, defect-first review pass. Inspect
+ \\[review task: 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;
@@ -32,13 +50,12 @@ pub fn steeringNote(arena: std.mem.Allocator, prompt: []const u8) ![]const u8 {
\\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});
+ , .{base});
}
/// 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);
+pub fn rejectTool(arena: std.mem.Allocator, call: ToolCall) !?ExecResult {
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;
@@ -80,9 +97,22 @@ test "review tool boundary admits reads and rejects edits, delegation, and backg
.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);
+ try std.testing.expect((try rejectTool(arena, read)) == null);
+ try std.testing.expect((try rejectTool(arena, edit)).?.is_error);
+ try std.testing.expect((try rejectTool(arena, workflow)).?.is_error);
+ try std.testing.expect((try rejectTool(arena, background)).?.is_error);
+}
+
+test "review context hides and restores parent history" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var history = std.json.Array.init(arena);
+ try history.append(.{ .string = "parent" });
+ var context = Context.begin(arena, &history, true);
+ try std.testing.expectEqual(@as(usize, 0), history.items.len);
+ try history.append(.{ .string = "review" });
+ try std.testing.expect(context.restore(&history));
+ try std.testing.expectEqualStrings("parent", history.items[0].string);
+ try std.testing.expect(!context.restore(&history));
}
diff --git a/src/schema.zig b/src/schema.zig
index 95b2aede..b5bf60c3 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 unlimited (bounded /review has its own 10-call ceiling)"},
+ \\ {"flag": "--max-model-calls", "arg": "N", "description": "opt-in invocation-wide provider-call ceiling shared by root, review, subagents, retries, title, compaction, and judges; default unlimited"},
\\ {"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.zig
index eaa4aec9..13d3e8a7 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\":\"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",
+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and 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"},