Skip to content

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

Python

Scope optional review deadlines to their owning turn

justrachefee32d846cf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c0fcd4b8..b1afeed7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -118,7 +118,9 @@ jobs:
run: python3 scripts/test-acp-steer.py zig-out/bin/graff
- name: Isolated read-only review regression
- run: python3 scripts/test-review-mode.py zig-out/bin/graff
+ run: |
+ python3 scripts/test-review-mode.py zig-out/bin/graff
+ python3 scripts/test-review-deadline.py zig-out/bin/graff
- name: Automatic learning bootstrap and its idle-workspace guard
run: python3 scripts/test-learn-auto-init.py zig-out/bin/graff
diff --git a/docs/adr/0125-review-deadlines-belong-to-one-turn.md b/docs/adr/0125-review-deadlines-belong-to-one-turn.md
new file mode 100644
index 00000000..156f992c
--- /dev/null
+++ b/docs/adr/0125-review-deadlines-belong-to-one-turn.md
@@ -0,0 +1,34 @@
+# 0125. Review deadlines belong to one turn
+
+Status: accepted 2026-09-15
+
+## Context
+
+Review mode supports call and tool limits, but a single stalled model request can
+consume wall time without reaching another call-count check (#306). A timer that
+outlives its review can incorrectly cancel an unrelated follow-up.
+
+## Decision
+
+`GRAFF_REVIEW_MAX_SECONDS` opts explicit root reviews into a wall-time limit.
+Unset or zero remains unlimited; positive integer values up to 86400 are accepted.
+Malformed values reject the review instead of silently disabling the limit.
+Ordinary turns and subagents do not inherit a review deadline.
+
+Each review owns a joined watcher. At the deadline it requests cancellation with
+a distinct harness source, preserving any previously recorded user cancellation.
+The watcher stops and joins before the turn returns. A result arriving after the
+deadline cannot become successful completion. Reports say the review is incomplete
+and do not blame the user. Follow-up turns receive their normal fresh cancel state.
+
+This uses the existing cooperative cancellation paths, including network waits;
+it is not process isolation for an uninterruptible operating-system call.
+It adds no default cap and does not change review's read-only capabilities.
+
+## Verification
+
+Unit tests cover parsing, watcher teardown, cancellation provenance and late
+results. `scripts/test-review-deadline.py` holds a model response open, observes the
+review timeout, then completes ordinary/review/ordinary follow-ups in the same
+process. The ordinary turns deliberately exceed the configured review limit.
+The existing long-review and explicit call/tool-budget regressions remain intact.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 5d6e1773..8e743ef9 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -137,6 +137,8 @@ record only when you need the evidence or the edge cases.
| [0124](0124-review-checkpoints-preserve-unfinished-scope.md) | Explicit reviews request a findings checkpoint every twenty calls without forcing completion or changing authority. |
+| [0125](0125-review-deadlines-belong-to-one-turn.md) | Opt-in review deadlines use joined turn-owned watchers, preserve user cancellation, and cannot validate late results. |
+
## When to write one
Write an ADR when a decision is load-bearing and non-obvious: it was reached
diff --git a/docs/review-guardrails.md b/docs/review-guardrails.md
new file mode 100644
index 00000000..4041aeba
--- /dev/null
+++ b/docs/review-guardrails.md
@@ -0,0 +1,33 @@
+# Review guardrails
+
+Use `/review <target>` in a supported interactive client or the JSON request
+`{"type":"review","text":"Review the current diff"}` for the dedicated read-only
+review mode. Ordinary chat text is not a request to enter this mode automatically.
+Review mode rejects mutation, workflow expansion and delegation. A later user
+request may start a separate implementation turn.
+
+Long reviews request a findings checkpoint every twenty model calls. The request
+asks for verified findings, remaining uncertainty and the next inspection. It
+neither completes the review nor authorizes fixes.
+
+Set `GRAFF_REVIEW_MAX_SECONDS=120` in the harness process environment to give each
+explicit root review a two-minute wall-time limit. Unset or `0` is unlimited;
+accepted positive values range from `1` through `86400`. This limit uses existing
+cancellation support. A timeout reports incomplete findings, preserves saved
+history, and leaves later turns available. Ordinary user turns are not timed by
+this setting. The existing `--max-model-calls` process-wide cap and per-request
+`maxToolCalls` remain separate opt-in controls.
+
+Run the offline production regressions locally:
+
+```sh
+zig build
+python3 scripts/test-review-mode.py zig-out/bin/graff
+python3 scripts/test-review-deadline.py zig-out/bin/graff
+python3 scripts/eval-tier2.py --only review-checkpoint-preserves-unfinished-scope
+```
+
+The first two also run in CI. Set `GRAFF_REVIEW_EVIDENCE` to a private directory
+when running the deadline test to retain its protocol events and harness traces.
+These are scripted-model regressions of the actual harness, not a claim about
+an unscripted model's review quality.
diff --git a/scripts/test-review-deadline.py b/scripts/test-review-deadline.py
new file mode 100644
index 00000000..9314ae54
--- /dev/null
+++ b/scripts/test-review-deadline.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""A review deadline interrupts a stalled request without cancelling later turns."""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import sys
+import tempfile
+import threading
+import time
+
+spec = importlib.util.spec_from_file_location('review_fixture', Path(__file__).with_name('test-review-mode.py'))
+fixture = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(fixture)
+original_environment = fixture.environment
+
+
+def environment(tmp, port):
+ env = original_environment(tmp, port)
+ env['GRAFF_REVIEW_MAX_SECONDS'] = '1'
+ return env
+
+
+fixture.environment = environment
+release = threading.Event()
+
+
+def responses(request):
+ if request.ordinal == 1:
+ release.wait(8)
+ return fixture.message('This late review response must not complete the review.', 1)
+ if request.ordinal in (2, 4):
+ time.sleep(1.2)
+ return fixture.message('Follow-up remains usable.', request.ordinal)
+
+
+def main():
+ evidence = Path(os.environ['GRAFF_REVIEW_EVIDENCE']) if os.environ.get('GRAFF_REVIEW_EVIDENCE') else None
+ with tempfile.TemporaryDirectory(prefix='graff-review-deadline-') as temp:
+ mock = fixture.CodexMock(events_for_request=responses)
+ port = mock.start()
+ proc = fixture.start_graff(temp, port)
+ turns = []
+ try:
+ started = time.monotonic()
+ events = fixture.send(proc, {'type': 'review', 'text': 'Review the current workspace.'})
+ elapsed = time.monotonic()-started
+ turns.append(events)
+ assert elapsed < 4, f'deadline failed to interrupt stalled model request: {elapsed:.2f}s'
+ assert events[-1]['type'] == 'error', events[-1]
+ assert 'wall-time limit' in json.dumps(events[-1]), events[-1]
+ assert not any(e.get('type') == 'turn' and e.get('complete') for e in events), events
+ release.set()
+ for kind in ('user', 'review', 'user'):
+ events = fixture.send(proc, {'type': kind, 'text': 'Read-only follow-up.'})
+ turns.append(events)
+ assert events[-1]['type'] == 'turn', events[-1]
+ assert events[-1]['text'] == 'Follow-up remains usable.', events[-1]
+ print(f'PASS review deadline interrupted stalled request in {elapsed:.2f}s; three later turns survived')
+ finally:
+ release.set()
+ fixture.close(proc, 'review deadline')
+ mock.stop()
+ if evidence:
+ import shutil
+ evidence.mkdir(parents=True, exist_ok=True, mode=0o700)
+ (evidence/'turns.json').write_text(json.dumps(turns, indent=2))
+ (evidence/'requests.json').write_text(json.dumps([r.body for r in mock.recorded_requests()], indent=2))
+ for name in ('traces', 'trajectories', 'sessions'):
+ source = Path(temp)/'.graff'/name
+ if source.exists(): shutil.copytree(source, evidence/name, dirs_exist_ok=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/agent.zig b/src/agent.zig
index 45a149cd..8e1cdd1a 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -330,8 +330,7 @@ pub const Agent = struct {
}
pub fn runTurn(self: *Agent) anyerror![]const u8 {
- // Defensive for restored/embedded agents whose provider was assigned
- // directly instead of going through providers.applyProvider.
+ // Restore catalog invariants before starting the turn.
try self.ensureRootTools(self.provider.kind);
var pending_work: empty_completion.PendingWork = .{};
self.completed = null;
@@ -339,9 +338,11 @@ pub const Agent = struct {
@import("named_work.zig").beginTurn(self);
var task_scope = @import("task_intent.zig").State.begin(self);
if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();
+ var review_deadline = try @import("review_deadline.zig").start(self);
+ defer review_deadline.stop();
while (true) {
try task_scope.beforeRequest(self);
- if (try @import("turn_chrome.zig").beforeRequest(self)) |paused| return paused;
+ if (try @import("turn_chrome.zig").beforeRequest(self)) |paused| return review_deadline.finish(paused);
// Esc during a tool join lands here; root consumes, subagents bail.
if (esc_cancel.load(.acquire)) {
if (!self.sub) esc_cancel.store(false, .release);
@@ -392,13 +393,13 @@ pub const Agent = struct {
}
}
const hist_len = self.messages.items.len;
- const root = self.request(if (self.text_only) null else self.toolsJson()) catch |err| return @import("agent_model_loop.zig").finishError(self, err);
+ const root = self.request(if (self.text_only) null else self.toolsJson()) catch |err| return review_deadline.finish(try @import("agent_model_loop.zig").finishError(self, err));
const done = try @import("agent_steps.zig").stepForWire(self, root);
if (done) |final_text| {
// Retry empty replies; reconcile plain finals with live work (#745).
if (try empty_completion.handle(self, final_text, hist_len)) continue;
if (try @import("named_work.zig").handle(self, final_text)) continue;
- if (try pending_work.finish(self, final_text)) |text| return text;
+ if (try pending_work.finish(self, final_text)) |text| return review_deadline.finish(text);
continue;
}
self.empty_completion_retries = 0;
diff --git a/src/cancel_source.zig b/src/cancel_source.zig
index 37e4ccd8..0e6fd4e0 100644
--- a/src/cancel_source.zig
+++ b/src/cancel_source.zig
@@ -16,6 +16,8 @@ const Tracer = @import("trace.zig").Tracer;
pub const Source = enum(u8) {
/// Nobody recorded one: the harness ended the turn, not the user.
none,
+ /// An explicit review wall-time limit, never a user cancel.
+ review_deadline,
/// A lone Esc on the line REPL's raw stdin.
esc_key,
/// Double Enter with a queued steer line (escPressed marks it force).
@@ -36,6 +38,12 @@ pub fn cancel(s: Source) void {
Agent.esc_cancel.store(true, .release);
}
+/// A deadline must not replace an already recorded user cancellation.
+pub fn cancelIfIdle(s: Source) void {
+ if (source.cmpxchgStrong(0, @intFromEnum(s), .acq_rel, .acquire) == null)
+ Agent.esc_cancel.store(true, .release);
+}
+
/// A cancel that came off raw stdin: a double Enter with a queued steer
/// line is the force path, anything else is a real Esc.
pub fn cancelFromStdin() void {
@@ -60,17 +68,19 @@ pub fn take(tracer: ?*Tracer) Source {
}
pub fn byUser(s: Source) bool {
- return s != .none;
+ return s != .none and s != .review_deadline;
}
/// The transcript marker appended as the (incomplete) assistant turn.
pub fn marker(s: Source) []const u8 {
+ if (s == .review_deadline) return "[review stopped: wall-time limit reached; findings are incomplete]";
return if (byUser(s)) "[response interrupted by user]" else "[response ended early: cancelled by the harness, not the user]";
}
/// The yellow chrome line the line REPL prints.
pub fn chrome(s: Source) []const u8 {
return switch (s) {
+ .review_deadline => "✗ review stopped (wall-time limit; findings incomplete)",
.esc_key => "✗ interrupted (esc)",
.force_steer => "✗ interrupted (force)",
.json_cancel, .acp_cancel, .ui_cancel => "✗ interrupted (cancel)",
@@ -80,6 +90,7 @@ pub fn chrome(s: Source) []const u8 {
/// The --json error message.
pub fn jsonMessage(s: Source) []const u8 {
+ if (s == .review_deadline) return "review wall-time limit reached; findings are incomplete";
return if (byUser(s)) "turn cancelled" else "turn cancelled by the harness (no user cancel recorded)";
}
diff --git a/src/main.zig b/src/main.zig
index d874e555..c2aac6c6 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("subagent_recovery.zig");
_ = @import("acp_agent_activity.zig");
_ = @import("read_image.zig");
- _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig") };
+ _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig") };
}
diff --git a/src/review_deadline.zig b/src/review_deadline.zig
new file mode 100644
index 00000000..c19db66c
--- /dev/null
+++ b/src/review_deadline.zig
@@ -0,0 +1,123 @@
+//! Opt-in review deadline. The watcher belongs to one turn and is joined before
+//! its storage or the turn's cancellation state can be reused.
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const cancel = @import("cancel_source.zig");
+const A = std.mem.Allocator;
+const State = struct {
+ io: std.Io,
+ until_ns: i128,
+ done: std.atomic.Value(bool) = .init(false),
+ expired: std.atomic.Value(bool) = .init(false),
+
+ fn watch(self: *State) void {
+ while (!self.done.load(.acquire)) {
+ if (std.Io.Timestamp.now(self.io, .awake).nanoseconds >= self.until_ns) {
+ if (self.done.cmpxchgStrong(false, true, .acq_rel, .acquire) == null) {
+ self.expired.store(true, .release);
+ cancel.cancelIfIdle(.review_deadline);
+ }
+ return;
+ }
+ self.io.sleep(.fromMilliseconds(20), .awake) catch return;
+ }
+ }
+};
+
+pub const Watch = struct {
+ state: ?*State = null,
+ thread: ?std.Thread = null,
+ allocator: A = undefined,
+ expired: bool = false,
+
+ pub fn stop(self: *Watch) void {
+ const state = self.state orelse return;
+ state.done.store(true, .release);
+ self.thread.?.join();
+ self.expired = state.expired.load(.acquire);
+ self.allocator.destroy(state);
+ self.state = null;
+ }
+
+ pub fn finish(self: *Watch, text: []const u8) ![]const u8 {
+ self.stop();
+ if (self.expired) return error.Interrupted;
+ return text;
+ }
+};
+
+fn startMs(a: A, io: std.Io, ms: u64) !Watch {
+ if (ms == 0) return .{};
+ const state = try a.create(State);
+ errdefer a.destroy(state);
+ state.* = .{ .io = io, .until_ns = @as(i128, std.Io.Timestamp.now(io, .awake).nanoseconds) + @as(i128, ms) * std.time.ns_per_ms };
+ return .{ .state = state, .thread = try std.Thread.spawn(.{}, State.watch, .{state}), .allocator = a };
+}
+
+pub fn parseSeconds(raw: []const u8) !u64 {
+ const n = std.fmt.parseInt(u64, std.mem.trim(u8, raw, " \t"), 10) catch return error.InvalidReviewTimeLimit;
+ if (n > 86400) return error.InvalidReviewTimeLimit;
+ return n;
+}
+
+pub fn start(agent: *Agent) !Watch {
+ if (!agent.review_mode or agent.sub) return .{};
+ const raw = std.c.getenv("GRAFF_REVIEW_MAX_SECONDS") orelse return .{};
+ const seconds = try parseSeconds(std.mem.span(raw));
+ if (seconds != 0) if (agent.tracer) |tr| tr.note("review_deadline", "explicit wall-time limit armed");
+ return startMs(agent.gpa, agent.io, seconds * 1000);
+}
+
+test "review deadline rejects malformed limits and permits explicit unlimited" {
+ try std.testing.expectEqual(@as(u64, 0), try parseSeconds("0"));
+ try std.testing.expectEqual(@as(u64, 30), try parseSeconds(" 30 "));
+ for ([_][]const u8{ "", "-1", "later", "86401" }) |raw|
+ try std.testing.expectError(error.InvalidReviewTimeLimit, parseSeconds(raw));
+}
+
+test "review watcher is joined and cannot cancel a later turn" {
+ cancel.clear();
+ defer cancel.clear();
+ var watch = try startMs(std.testing.allocator, std.testing.io, 20);
+ watch.stop();
+ try std.testing.io.sleep(.fromMilliseconds(50), .awake);
+ try std.testing.expect(!Agent.esc_cancel.load(.acquire));
+ watch.stop();
+}
+
+test "review deadline cancels with harness provenance and preserves a user cancellation" {
+ cancel.clear();
+ defer cancel.clear();
+ var watch = try startMs(std.testing.allocator, std.testing.io, 1);
+ defer watch.stop();
+ try waitForExpiration(&watch);
+ watch.stop();
+ try std.testing.expect(Agent.esc_cancel.load(.acquire));
+ try std.testing.expectEqual(cancel.Source.review_deadline, cancel.take(null));
+ cancel.clear();
+ cancel.cancel(.json_cancel);
+ var second = try startMs(std.testing.allocator, std.testing.io, 1);
+ defer second.stop();
+ try waitForExpiration(&second);
+ second.stop();
+ try std.testing.expectEqual(cancel.Source.json_cancel, cancel.take(null));
+}
+
+test "a result arriving after the review deadline cannot become successful completion" {
+ cancel.clear();
+ defer cancel.clear();
+ var watch = try startMs(std.testing.allocator, std.testing.io, 1);
+ defer watch.stop();
+ try waitForExpiration(&watch);
+ try std.testing.expectError(error.Interrupted, watch.finish("late findings"));
+ try std.testing.expect(!cancel.byUser(.review_deadline));
+ try std.testing.expect(std.mem.indexOf(u8, cancel.marker(.review_deadline), "incomplete") != null);
+}
+
+fn waitForExpiration(watch: *Watch) !void {
+ const until = std.Io.Timestamp.now(std.testing.io, .awake).nanoseconds + 5 * std.time.ns_per_s;
+ while (!watch.state.?.expired.load(.acquire)) {
+ if (std.Io.Timestamp.now(std.testing.io, .awake).nanoseconds >= until) return error.DeadlineDidNotFire;
+ try std.testing.io.sleep(.fromMilliseconds(10), .awake);
+ }
+}