graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(gate,budget,ci): policy-file write guard, steering denials, partial-state budget report, pty exit headroom
justrach4a86ec9222ab
diff --git a/scripts/test-pty-parallel-cancel.py b/scripts/test-pty-parallel-cancel.pyindex 6383d537..8017dbef 100755--- a/scripts/test-pty-parallel-cancel.py+++ b/scripts/test-pty-parallel-cancel.py@@ -153,9 +153,20 @@ def main() -> None:session.wait_for_literal("interrupted (esc)", start=cursor)assert_processes_gone(pid_paths)session.send_key("ctrl-d")- result = session.read_until_exit(5)+ # #364: every cancel assertion above already PASSED when CI+ # failed here — only the exit was slow. Shutdown drains the+ # session writer, reaps jobs, and joins the fleet worker; on a+ # loaded ubuntu runner 5s was not enough. Give it headroom and,+ # when it still fails, dump the transcript so the next+ # occurrence is diagnosable instead of a bare exit code.+ result = session.read_until_exit(30)if result.timed_out or result.exit_code != 0:- raise AssertionError(f"REPL exit={result.exit_code} timed_out={result.timed_out}")+ raw = session.raw+ tail = (raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else str(raw))[-2000:]+ raise AssertionError(+ f"REPL exit={result.exit_code} timed_out={result.timed_out}\n"+ f"--- pty transcript tail ---\n{tail}"+ )finally:mock.stop()print("ok parallel Esc reports terminal states and kills command descendants")diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 85e05f64..7e24a590 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -127,7 +127,25 @@ fn gateSmolifySecrets(arena: std.mem.Allocator, call: ToolCall) !?ExecResult {/// The permission gate, root side: an unapproved external action prompts the/// user. Subagents never prompt; their gate is the executor's allowlist.+/// #366: the harness's own policy file is not the model's to edit. A worker+/// was observed writing pre_approved_tools into it after a denial — a write+/// that takes effect on next load is self-privilege-escalation, cwd-jail or+/// not. Applies to root AND subagents, before every other gate.+fn gateHarnessPolicyWrite(self: *Agent, call: ToolCall) !?ExecResult {+ if (!(std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file"))) return null;+ const obj = json_args.object(call.input) orelse return null;+ const pv = obj.get("path") orelse return null;+ if (pv != .string) return null;+ const path = std.mem.trim(u8, pv.string, " \t");+ if (!(std.mem.eql(u8, path, Approvals.settings_path) or std.mem.endsWith(u8, path, "/" ++ Approvals.settings_path))) return null;+ return .{+ .text = try self.arena.dupe(u8, "refused: " ++ Approvals.settings_path ++ " is the harness's own policy file (approvals, hooks, pre-approvals) — a model never widens its own permissions. Ask the USER to change config, or proceed without this tool."),+ .is_error = true,+ };+}+pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {+ if (try gateHarnessPolicyWrite(self, call)) |blocked| return blocked; // #366: before the sub branch — children are exactly who must not widen approvalsif (self.sub) {if (std.mem.eql(u8, call.name, "learn_candidate")) return .{.text = try self.arena.dupe(u8, "learning is root-only — subagents cannot run mutators, evaluators, or publish grades"),@@ -253,12 +271,16 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;} else return null;+ // #369: a denial that just says "not pre-approved" strands the model —+ // observed spirals: probing .harness/settings.json, retrying the same+ // tool, burning the whole call budget. Name what was denied, forbid the+ // dead ends, and point at a productive next move.const in = self.in orelse return .{- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask in one-shot mode — pre-approve it in .harness/settings.json, or run with --yolo"),+ .text = try std.fmt.allocPrint(self.arena, "tool denied ({s}): not pre-approved, and this unattended run has no user to ask. Do NOT retry it, probe harness config, or try to change approvals — use a different tool you already have, or finish and report the limitation. The USER can pre-approve it in {s} or run with --yolo.", .{ prompt_line, Approvals.settings_path }),.is_error = true,};const w = self.out orelse return .{- .text = try self.arena.dupe(u8, "not pre-approved, and no interactive user to ask — pre-approve it in .harness/settings.json, or run with --yolo"),+ .text = try std.fmt.allocPrint(self.arena, "tool denied ({s}): not pre-approved, and no interactive user to ask. Do NOT retry it or probe harness config — use a different tool you already have, or finish and report the limitation. The USER can pre-approve it in {s} or run with --yolo.", .{ prompt_line, Approvals.settings_path }),.is_error = true,};try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });@@ -309,6 +331,25 @@ test "Smolify arguments containing recognizable secrets fail closed locally" {try std.testing.expect((try gateSmolifySecrets(arena, .{ .id = "3", .name = "read_file", .input = secret })) == null);}+test "gateHarnessPolicyWrite: the model never edits the harness's own policy file (#366)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var agent: Agent = undefined;+ agent.arena = arena;+ const settings = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"path\":\".harness/settings.json\",\"content\":\"{}\"}", .{});+ const nested = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"path\":\"../other/.harness/settings.json\",\"content\":\"{}\"}", .{});+ const normal = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"path\":\"src/main.zig\",\"content\":\"x\"}", .{});+ // Both write tools are refused on the policy file, any spelling of it…+ const direct = (try gateHarnessPolicyWrite(&agent, .{ .id = "1", .name = "write_file", .input = settings })).?;+ try std.testing.expect(direct.is_error);+ try std.testing.expect(std.mem.indexOf(u8, direct.text, "policy file") != null);+ try std.testing.expect((try gateHarnessPolicyWrite(&agent, .{ .id = "2", .name = "edit_file", .input = nested })) != null);+ // …while ordinary paths and other tools pass through untouched.+ try std.testing.expect((try gateHarnessPolicyWrite(&agent, .{ .id = "3", .name = "write_file", .input = normal })) == null);+ try std.testing.expect((try gateHarnessPolicyWrite(&agent, .{ .id = "4", .name = "bash", .input = settings })) == null);+}+test "private template collector covers subagents and workflow stages" {const io = std.testing.io;learning_privacy.setMode(io, .templates);diff --git a/src/run_budget.zig b/src/run_budget.zigindex ed56a4cd..4a48df79 100644--- a/src/run_budget.zig+++ b/src/run_budget.zig@@ -98,6 +98,14 @@ pub const RunBudget = struct {return self.model_calls.load(.acquire);}+ /// #368: RunBudgetExhausted used to end a -p run with a bare "turn+ /// failed:" line. The model never gets a concluding call at this point,+ /// so the HARNESS owns the last line: what ran out, that the work is+ /// partial and not rolled back, and where the evidence lives.+ pub fn exhaustedFatal(max_model_calls: u64, run_id: []const u8) noreturn {+ std.process.fatal("model-call budget exhausted (--max-model-calls {d}) before the task completed. Work done so far is PARTIAL and was NOT rolled back; inspect this run under .graff/traces/{s}.jsonl, then raise --max-model-calls or re-run to continue.", .{ max_model_calls, run_id });+ }+/// True when at least `calls` more model calls fit under the ceiling./// Advisory (racy against concurrent children) — for skipping OPTIONAL/// spending (e.g. a RED repair continuation), never for admission;diff --git a/src/session_run.zig b/src/session_run.zigindex 8b00dd95..a6a84ec8 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -144,14 +144,14 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m// then emit/upload the terminal behavioral event.fleet.joinElites(io);jobs.jobsReap(gpa, io);- // Mirror main's teardown fully: flush buffered OTLP telemetry too,- // not just the behavioral batch, so a fatal one-shot is not invisible- // in ordinary telemetry while visible in behavioral data.+ // Mirror main's teardown fully: flush buffered OTLP telemetry too, so+ // a fatal one-shot is visible in ordinary telemetry, not only behavioral.if (telemetry.g_telem) |t| t.flush();if (tracer.behavior) |behavior| behavior.finish(.failed);switch (err) {error.FallbackConsentRequired => std.process.fatal("saved model unavailable; provider '{s}' is not allowlisted — run graff interactively, then /fallback allow {s}", .{ root.provider.id, root.provider.id }),error.ApiError => std.process.fatal("{s}", .{root.last_api_error orelse "api error"}),+ error.RunBudgetExhausted => @import("run_budget.zig").RunBudget.exhaustedFatal(if (root.run_budget) |b| b.max_model_calls else 0, &@import("scoring.zig").g_run_id), // #368else => |e| std.process.fatal("turn failed: {t}", .{e}),}};