Skip to content

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

Python

fix(review): remove implicit limits and isolate parent state

Rach Pradhanc40525f6f57c
diff --git a/scripts/test-review-mode.py b/scripts/test-review-mode.py
index 7a8bdda2..9c5f2723 100644
--- a/scripts/test-review-mode.py
+++ b/scripts/test-review-mode.py
@@ -79,11 +79,17 @@ def review_events(request: RecordedRequest) -> list[dict]:
def long_review_events(request: RecordedRequest) -> list[dict]:
- if request.ordinal > 12:
+ if request.ordinal > 45:
return message(LONG_REPLY, request.ordinal)
return tool("read_file", {"path": "target.txt"}, request.ordinal)
+def tool_budget_events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal <= 4:
+ return tool("read_file", {"path": "target.txt"}, request.ordinal)
+ return message("Explicit tool budget respected.", request.ordinal)
+
+
def loop_events(request: RecordedRequest) -> list[dict]:
return tool("read_file", {"path": "target.txt"}, request.ordinal)
@@ -98,6 +104,12 @@ def isolation_events(request: RecordedRequest) -> list[dict]:
return message("Follow-up complete.", request.ordinal)
+def strict_eval_events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal == 1:
+ return tool("eval", {"note": "establish a failing parent verifier"}, request.ordinal)
+ return tool("attempt_completion", {"result": "Strict review 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)
@@ -126,11 +138,16 @@ def environment(tmp: str, port: int) -> dict[str, str]:
def start_graff(
- tmp: str, port: int, max_model_calls: int | None = None
+ tmp: str,
+ port: int,
+ max_model_calls: int | None = None,
+ extra_args: list[str] | None = None,
) -> 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)])
+ if extra_args:
+ argv.extend(extra_args)
return subprocess.Popen(
argv,
cwd=tmp,
@@ -207,7 +224,7 @@ def main() -> None:
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")
+ raise AssertionError("review did not follow the expected policy tool loop")
long_mock = CodexMock(events_for_request=long_review_events)
long_port = long_mock.start()
@@ -217,7 +234,7 @@ def main() -> None:
finally:
long_mock.stop()
calls = len(long_mock.recorded_requests())
- if calls != 13:
+ if calls != 46:
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}")
@@ -234,6 +251,40 @@ def main() -> None:
if global_events[-1].get("type") != "error":
raise AssertionError(f"global-budget exhaustion was not surfaced: {global_events[-1]!r}")
+ tool_budget_mock = CodexMock(events_for_request=tool_budget_events)
+ tool_budget_port = tool_budget_mock.start()
+ tool_budget_process = start_graff(tmp, tool_budget_port)
+ try:
+ tool_budget_events_seen = send(
+ tool_budget_process,
+ {
+ "type": "review",
+ "text": "Review target.txt",
+ "maxToolCalls": 3,
+ },
+ )
+ close(tool_budget_process)
+ finally:
+ tool_budget_mock.stop()
+ budget_rejections = [
+ event
+ for event in tool_budget_events_seen
+ if event.get("type") == "tool_rejected"
+ and event.get("reason") == "budget"
+ ]
+ if len(budget_rejections) != 1:
+ raise AssertionError(
+ f"explicit tool budget was not enforced once: {budget_rejections!r}"
+ )
+ if (
+ tool_budget_events_seen[-1].get("type") != "turn"
+ or tool_budget_events_seen[-1].get("text")
+ != "Explicit tool budget respected."
+ ):
+ raise AssertionError(
+ f"review did not recover from explicit tool budget: {tool_budget_events_seen[-1]!r}"
+ )
+
isolation_mock = CodexMock(events_for_request=isolation_events)
isolation_port = isolation_mock.start()
isolation_process = start_graff(tmp, isolation_port)
@@ -256,8 +307,65 @@ def main() -> None:
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 is isolated/read-only, admits >10 calls, and honors opt-in budgets")
+ if "[review task:" in requests[3].body.get("instructions", ""):
+ raise AssertionError("review system prompt leaked into the parent follow-up")
+
+ sessions = os.path.join(tmp, ".graff", "sessions")
+ os.makedirs(sessions, exist_ok=True)
+ with open(
+ os.path.join(sessions, "strict-eval.session.json"),
+ "w",
+ encoding="utf-8",
+ ) as fh:
+ json.dump(
+ {
+ "provider": "codex",
+ "model": "gpt-5.6-sol",
+ "strict": True,
+ "messages": [],
+ },
+ fh,
+ )
+ strict_mock = CodexMock(events_for_request=strict_eval_events)
+ strict_port = strict_mock.start()
+ strict_process = start_graff(
+ tmp,
+ strict_port,
+ max_model_calls=2,
+ extra_args=["--eval", "false", "--resume", "strict-eval"],
+ )
+ try:
+ parent_eval_events = send(
+ strict_process, {"type": "user", "text": "Establish failing eval state"}
+ )
+ if (
+ parent_eval_events[-1].get("type") != "turn"
+ or parent_eval_events[-1].get("complete") is not False
+ ):
+ raise AssertionError(
+ f"parent eval did not enter repair-pending state: {parent_eval_events[-1]!r}"
+ )
+ strict_events = send(
+ strict_process, {"type": "review", "text": "Review target.txt"}
+ )
+ close(strict_process)
+ finally:
+ strict_mock.stop()
+ if len(strict_mock.recorded_requests()) != 2:
+ raise AssertionError("strict/eval review did not finish in one additional model call")
+ instructions = strict_mock.recorded_requests()[1].body.get("instructions", "")
+ if "STRICT MODE:" in instructions:
+ raise AssertionError("review inherited the parent strict system note")
+ if (
+ strict_events[-1].get("type") != "turn"
+ or strict_events[-1].get("text") != "Strict review complete."
+ or strict_events[-1].get("complete") is not True
+ ):
+ raise AssertionError(
+ f"parent eval gate blocked review finalization: {strict_events[-1]!r}"
+ )
+
+ print("ok review is isolated/read-only, admits >40 tools, and honors opt-in budgets")
if __name__ == "__main__":
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 2228cd3b..f7a134be 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -206,11 +206,7 @@ pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {
return denied;
};
if (std.mem.eql(u8, call.name, "attempt_completion")) return null;
- 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 (main_mod.max_tool_calls) |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);
@@ -285,7 +281,7 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]const
/// Handle a meta tool inline on the agent's own thread.
pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
if (std.mem.eql(u8, call.name, "attempt_completion")) {
- if (self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {
+ if (!self.review_mode and self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {
const message = if (self.eval_repair_pending)
"completion blocked: the latest verifier contradicted the plan; repair the failure and run eval until it meets the target"
else
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 2449eee6..c79ae89d 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -288,7 +288,7 @@ pub fn run(ctx: *Ctx) !void {
ctx.root.review_mode = review_prompt != null;
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);
+ ctx.root.sys_override = try review.systemPrompt(ctx.arena, ctx.root.sys_normal);
defer {
ctx.root.review_mode = false;
ctx.root.sys_override = parent_system_override;
@@ -383,9 +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);
+ var review_context = review.Context.begin(ctx.arena, ctx.root, ctx.root.review_mode);
if (ctx.root.review_mode) ctx.root.rebaseContextMeter();
- defer if (review_context.restore(&ctx.root.messages)) ctx.root.rebaseContextMeter();
+ defer if (review_context.restore(ctx.root)) 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;
@@ -416,10 +416,12 @@ pub fn run(ctx: *Ctx) !void {
// 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);
+ const isolated_review = review_context.restore(ctx.root);
if (isolated_review) {
- ctx.root.rebaseContextMeter();
+ ctx.root.review_mode = false;
+ ctx.root.sys_override = parent_system_override;
try ctx.root.messages.append(try messages.textMessage(ctx.arena, "user", base_msg));
+ ctx.root.rebaseContextMeter();
}
const final_text = turn_result catch |err| switch (err) {
error.Interrupted => {
@@ -535,9 +537,8 @@ 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 = session_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = !ctx.root.eval_repair_pending, .metadata_complete = session_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 = isolated_review or !ctx.root.eval_repair_pending, .metadata_complete = session_context_tokens > 0 });
}
-
// Apply only if already complete; poll never waits for title generation.
title_jobs.poll(ctx);
fleet.joinElites(ctx.io); // publish backgrounded fleet champions for the next turn (no-op once joined)
diff --git a/src/review.zig b/src/review.zig
index 93a902cc..3b0a9fa8 100644
--- a/src/review.zig
+++ b/src/review.zig
@@ -6,24 +6,36 @@ const ToolCall = @import("tools.zig").ToolCall;
const ExecResult = @import("tools.zig").ExecResult;
const Approvals = @import("approvals.zig").Approvals;
-pub const max_tool_calls: u64 = 40;
-
/// 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,
+ parent_context_tokens: u64 = 0,
+ parent_context_local_tokens: u64 = 0,
+ parent_usage_includes_output: bool = false,
- pub fn begin(arena: std.mem.Allocator, messages: *std.json.Array, isolate: bool) Context {
+ pub fn begin(arena: std.mem.Allocator, root: anytype, isolate: bool) Context {
if (!isolate) return .{};
- const parent = messages.*;
- messages.* = std.json.Array.init(arena);
- return .{ .parent = parent };
+ const context = Context{
+ .parent = root.messages,
+ .parent_context_tokens = root.last_context_tokens,
+ .parent_context_local_tokens = root.context_local_tokens,
+ .parent_usage_includes_output = root.last_usage_includes_output,
+ };
+ root.messages = std.json.Array.init(arena);
+ root.last_context_tokens = 0;
+ root.context_local_tokens = 0;
+ root.last_usage_includes_output = false;
+ return context;
}
- pub fn restore(self: *Context, messages: *std.json.Array) bool {
+ pub fn restore(self: *Context, root: anytype) bool {
const parent = self.parent orelse return false;
- messages.* = parent;
+ root.messages = parent;
+ root.last_context_tokens = self.parent_context_tokens;
+ root.context_local_tokens = self.parent_context_local_tokens;
+ root.last_usage_includes_output = self.parent_usage_includes_output;
self.parent = null;
return true;
}
@@ -107,12 +119,24 @@ 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));
+ const Root = struct {
+ messages: std.json.Array,
+ last_context_tokens: u64 = 900,
+ context_local_tokens: u64 = 300,
+ last_usage_includes_output: bool = true,
+ };
+ var root = Root{ .messages = std.json.Array.init(arena) };
+ try root.messages.append(.{ .string = "parent" });
+ var context = Context.begin(arena, &root, true);
+ try std.testing.expectEqual(@as(usize, 0), root.messages.items.len);
+ try std.testing.expectEqual(@as(u64, 0), root.last_context_tokens);
+ try std.testing.expectEqual(@as(u64, 0), root.context_local_tokens);
+ try std.testing.expect(!root.last_usage_includes_output);
+ try root.messages.append(.{ .string = "review" });
+ try std.testing.expect(context.restore(&root));
+ try std.testing.expectEqualStrings("parent", root.messages.items[0].string);
+ try std.testing.expectEqual(@as(u64, 900), root.last_context_tokens);
+ try std.testing.expectEqual(@as(u64, 300), root.context_local_tokens);
+ try std.testing.expect(root.last_usage_includes_output);
+ try std.testing.expect(!context.restore(&root));
}