graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): /plan and /strict are engine policy, not footer labels
Rach Pradhan732bd04f646d
diff --git a/TUI/app.zig b/TUI/app.zigindex 64426805..ff978485 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -10,7 +10,10 @@ const theme_mod = @import("theme.zig");pub const Screen = enum { welcome, agent };pub const Focus = enum { prompt, scrollback };pub const Overlay = enum { none, palette, help, theme, model, effort, settings, rewind, slash, debug, image, file, jump };-pub const AgentMode = enum { normal, plan, always_approve };+/// One vocabulary with the engine (#551): the Model does not keep a private+/// copy of the permission policy, it holds the engine's own enum and hands it+/// straight to the turn backend.+pub const AgentMode = engine.Mode;pub const EscArm = enum { none, clear, rewind };pub const EntryKind = enum { user, assistant, tool, system, err, pending };diff --git a/TUI/engine.zig b/TUI/engine.zigindex e332b7d4..e8588a8d 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -11,6 +11,13 @@ pub const ToolEvent = events_mod.Tool;pub const Effort = enum { low, medium, high, xhigh, max, ultra };+/// The session's permission policy. This is ENGINE state, not a badge: the+/// turn backend maps it onto the harness's plan gate and approval policy+/// (repl_glue.replTurnCb). Before #551 round 2 the TUI kept its own copy and+/// the engine was never told, so a footer reading "Plan" sat over a turn that+/// was writing files.+pub const Mode = enum { normal, plan, always_approve };+pub const Turn = struct {role: Role,text: []const u8,@@ -22,6 +29,10 @@ pub const Params = struct {fast: bool = false,thinking: bool = false,ultracode: bool = false,+ /// Permission policy for this turn (Shift+Tab, Ctrl+O, /plan).+ mode: Mode = .normal,+ /// /strict — selects the strict system prompt on the turn's agent.+ strict: bool = false,goal: []const u8 = "",};diff --git a/TUI/turn.zig b/TUI/turn.zigindex 86364874..710529ca 100644--- a/TUI/turn.zig+++ b/TUI/turn.zig@@ -38,6 +38,11 @@ pub fn startJob(self: *Model) void {.fast = self.fast,.thinking = self.thinking_show,.ultracode = self.ultracode or self.effort == .ultra,+ // Policy travels WITH the turn (#551): the engine applies the plan+ // gate and the strict prompt from these, so the footer and the run+ // can no longer disagree.+ .mode = self.mode,+ .strict = self.strict,.goal = self.goal orelse "",},.stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },diff --git a/src/repl.zig b/src/repl.zigindex ed0857e9..dd50bd1d 100644--- a/src/repl.zig+++ b/src/repl.zig@@ -30,8 +30,10 @@ const model_turn = @import("repl_model_turn.zig");const model_commands = @import("repl_model_commands.zig");const model_render = @import("repl_model_render.zig");const repl_run = @import("repl_run.zig");+const repl_types = @import("repl_types.zig");test {+ _ = repl_types;_ = parser_mod;_ = util;_ = repl_markdown;@@ -54,46 +56,14 @@ test {// keeps repl.zig decoupled from the harness's Agent/Provider (no circular import).// ----------------------------------------------------------------------------pub const Effort = enum { low, medium, high, xhigh, max, ultra };--pub const Turn = struct {- role: Role,- text: []const u8,- pub const Role = enum { user, assistant };-};--pub const Params = struct {- effort: Effort = .medium,- fast: bool = false,- thinking: bool = false,- ultracode: bool = false,- goal: []const u8 = "", // "" = none-};--pub const StreamBuf = struct {- // Single-writer (worker thread) / single-reader (render loop), lock-free: a- // fixed pre-allocated buffer (no realloc → stable pointer) + an atomic- // length. The worker appends bytes then release-stores the new length; the- // reader acquire-loads it and reads the committed prefix. Overflow drops- // extra bytes — only the live preview is affected (the final reply uses- // runTurn's return value).- buf: []u8 = &.{},- len: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),- pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {- const cur = self.len.load(.monotonic);- if (cur >= self.buf.len) return;- const n = @min(bytes.len, self.buf.len - cur);- @memcpy(self.buf[cur .. cur + n], bytes[0..n]);- self.len.store(cur + n, .release);- }- pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {- const n = self.len.load(.acquire);- if (n == 0) return null;- return gpa.dupe(u8, self.buf[0..n]) catch null;- }-};--pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf) ?[]const u8;+// The vocabulary itself lives in repl_types.zig (move+alias, 600-line cap);+// #551 grew Params a `mode`/`strict` so a frontend's policy reaches the engine.+pub const Effort = repl_types.Effort;+pub const Turn = repl_types.Turn;+pub const Mode = repl_types.Mode;+pub const Params = repl_types.Params;+pub const StreamBuf = repl_types.StreamBuf;+pub const TurnFn = repl_types.TurnFn;pub var g_turn_fn: ?TurnFn = null;pub var g_turn_ctx: ?*anyopaque = null;diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 416ee4b5..91599541 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -274,108 +274,15 @@ test "a zero-tool turn stops as idle, not accepted; a refused completion keeps ttry std.testing.expect(std.meta.activeTag(continuationDecision(.active, false, turnStopped(0, true), 5)) == .continue_turn);}-/// repl.TurnFn — run a full ROOT agent turn (tools + MCP) for `graff repl`, so-/// the model can read files, run bash, search the codebase, etc. — not a bare-/// completion. Auto-approves tools (yolo: the chat repl has no permission UI),-/// in=null (never blocks on a prompt). Output streams into a thread-safe sink-/// the repl polls to render live; the clean final text is runTurn's return-/// value. Returns the final assistant text (raw markdown, owned by gpa) or null.-pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Turn, params: repl.Params, stream: *repl.StreamBuf) ?[]const u8 {- const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();- var sink: ReplStreamSink = undefined;- sink.init(stream); // agent output streams into the repl's live pane (thread-safe)- var approvals: Approvals = .{ .yolo = true };- const sys = if (params.goal.len > 0)- (std.fmt.allocPrint(arena, "{s}\n\n# Standing goal (from the user)\n{s}\n\nTrack this as a todo_write checklist and work through it across turns - mark each item in_progress when you start and completed when done. Keep the list current; don't repeat finished items.", .{ c.sys_normal, params.goal }) catch c.sys_normal)- else- c.sys_normal;- var agent: Agent = .{- .gpa = gpa,- .arena = arena,- .io = c.io,- .client = c.client,- .provider = c.provider,- .messages = std.json.Array.init(arena),- .sub = false, // root: enables the full tool set + agentic loop- .label = "repl",- .out = &sink.writer,- .in = null, // never prompt for tool approval / ask_user- .stream_quiet = false, // stream tokens live into the repl pane- .registry = c.registry,- .tracer = c.tracer,- .run_budget = c.run_budget,- .approvals = &approvals,- // #551: a frontend that wants the engine's TYPED events installs its- // sink for this thread's turn (engine_sink.bindTurnSink). Null for- // `graff repl` and every headless caller, which keeps the process-mode- // default. Never re-parse rendered output to learn what the engine did.- .sink = @import("engine_sink.zig").turnSink(),- .tools_anthropic = c.tools_anthropic,- .tools_openai = c.tools_openai,- .tools_responses = c.tools_responses,- .reasoning = switch (params.effort) {- .low => .low,- .medium => .medium,- .high => .high,- .xhigh => .xhigh,- .max => .max,- .ultra => .ultra,- },- .fast = params.fast,- .fallback_allow = c.fallback_allow,- .fallback_active = c.fallback_active,- .fallback_blocked = c.fallback_blocked,- .ultracode_mode = params.ultracode,- .show_thinking = params.thinking,- };- // #326: the funnel — also recomputes sys_ultra/sys_ultra_strict from- // `sys`, so ultracode/effort-ultra here carries the REAL composed base.- prompts.setSystemPrompts(&agent, sys, arena) catch return null;- defer agent.tools_used.deinit(gpa);- for (history) |t| {- const role = switch (t.role) {- .user => "user",- .assistant => "assistant",- };- agent.messages.append(textMessage(arena, role, t.text) catch return null) catch return null;- }- defer {- c.provider = agent.provider;- c.fallback_active = agent.fallback_active;- c.fallback_blocked = agent.fallback_blocked;- }- const final = providers.runTurnWithFallback(&agent, &c.keys, arena, &sink.writer) catch |err| switch (err) {- // A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),- // so postStream can return error.StreamStalled. Don't collapse it to- // null — the pane renders that as "model call failed — check /model and- // your API key", mislabeling a harness stall as an auth/config problem.- // Keep the streamed partial + an honest marker, mirroring mainloop.- error.StreamStalled => {- const partial = std.mem.trim(u8, agent.partial_text.items, " \t\r\n");- return if (partial.len > 0)- std.fmt.allocPrint(gpa, "{s}\n\n[response ended early: stream stalled]", .{partial}) catch null- else- gpa.dupe(u8, "[response ended early: stream stalled]") catch null;- },- error.StreamDropped => {- // A mid-stream provider drop (#133), same handling as a stall: keep- // the streamed partial + an honest marker, never a null that the- // pane would render as "model call failed".- const partial = std.mem.trim(u8, agent.partial_text.items, " \t\r\n");- return if (partial.len > 0)- std.fmt.allocPrint(gpa, "{s}\n\n[response ended early: connection dropped]", .{partial}) catch null- else- gpa.dupe(u8, "[response ended early: connection dropped]") catch null;- },- error.FallbackConsentRequired => return gpa.dupe(u8, "Saved model unavailable. Allow this provider with /fallback in the standard REPL, or choose another model.") catch null,- else => return null,- };- const trimmed = std.mem.trim(u8, final, " \t\r\n");- if (trimmed.len == 0) return null;- return gpa.dupe(u8, trimmed) catch null;+/// repl.TurnFn — one full ROOT agent turn. The body lives in repl_turn.zig+/// (move+alias, 600-line cap); `repl_glue.replTurnCb` still resolves, and+/// repl_turn.Policy is where a turn's mode/strict becomes engine behavior.+pub const replTurnCb = @import("repl_turn.zig").replTurnCb;++test {+ // An alias does not pull a sibling's tests in — name it so the policy+ // regressions in repl_turn.zig are actually compiled and run.+ _ = @import("repl_turn.zig");}/// repl.ModelFn adapter — switch the active model by name. Resolve its providerdiff --git a/src/repl_turn.zig b/src/repl_turn.zignew file mode 100644index 00000000..dcad59a2--- /dev/null+++ b/src/repl_turn.zig@@ -0,0 +1,282 @@+//! The chat frontends' turn backend: one full ROOT agent turn (tools + MCP)+//! per repl.TurnFn call. Split out of repl_glue.zig (600-line cap) when #551+//! made a turn carry POLICY as well as text — `mode` and `strict` used to be+//! frontend labels the engine never saw, so the TUI could show "Plan" over a+//! turn that was auto-approving writes.+//!+//! `turnAgent` is deliberately its own function: it is the exact construction+//! a live turn runs on, so a test can build one and interrogate the gate and+//! the system prompt without a provider in the loop.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const main_mod = @import("main.zig");+const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const approvals_mod = @import("approvals.zig");+const Approvals = approvals_mod.Approvals;+const messages_mod = @import("messages.zig");+const textMessage = messages_mod.textMessage;+const prompts = @import("prompts.zig");+const providers = @import("providers.zig");+const repl = @import("repl.zig");+const repl_glue = @import("repl_glue.zig");+const ReplCtx = repl_glue.ReplCtx;++/// What a turn's permission mode means to the engine. One place, so the gate+/// and the badge can never drift again.+pub const Policy = struct {+ /// main.plan_mode for the length of the turn: read-only, writes denied.+ plan: bool,+ /// Approvals.yolo. On for the non-plan modes because these frontends have+ /// no approval prompt (in = null) — off would deny every unsaved tool+ /// rather than ask. Plan mode does not need it: its gate runs BEFORE the+ /// approval gate and is what refuses the writes.+ yolo: bool,+ /// Agent.strict — systemPrompt() picks sys_strict/sys_ultra_strict.+ strict: bool,++ pub fn from(params: repl.Params) Policy {+ return .{+ .plan = params.mode == .plan,+ .yolo = params.mode != .plan,+ .strict = params.strict,+ };+ }+};++/// The Agent a turn runs on. `out` is the live pane writer; `approvals` must+/// outlive the returned agent (the caller owns both). The system prompts are+/// composed here through the #326 funnel, so ultracode/strict/effort-ultra all+/// resolve against the REAL base rather than the comptime default.+pub fn turnAgent(+ c: *ReplCtx,+ gpa: Allocator,+ arena: Allocator,+ params: repl.Params,+ out: *Io.Writer,+ approvals: *Approvals,+) !Agent {+ const sys = if (params.goal.len > 0)+ (std.fmt.allocPrint(arena, "{s}\n\n# Standing goal (from the user)\n{s}\n\nTrack this as a todo_write checklist and work through it across turns - mark each item in_progress when you start and completed when done. Keep the list current; don't repeat finished items.", .{ c.sys_normal, params.goal }) catch c.sys_normal)+ else+ c.sys_normal;+ var agent: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = c.io,+ .client = c.client,+ .provider = c.provider,+ .messages = std.json.Array.init(arena),+ .sub = false, // root: enables the full tool set + agentic loop+ .label = "repl",+ .out = out,+ .in = null, // never prompt for tool approval / ask_user+ .stream_quiet = false, // stream tokens live into the repl pane+ .registry = c.registry,+ .tracer = c.tracer,+ .run_budget = c.run_budget,+ .approvals = approvals,+ // #551: a frontend that wants the engine's TYPED events installs its+ // sink for this thread's turn (engine_sink.bindTurnSink). Null for+ // `graff repl` and every headless caller, which keeps the process-mode+ // default. Never re-parse rendered output to learn what the engine did.+ .sink = @import("engine_sink.zig").turnSink(),+ .tools_anthropic = c.tools_anthropic,+ .tools_openai = c.tools_openai,+ .tools_responses = c.tools_responses,+ .reasoning = switch (params.effort) {+ .low => .low,+ .medium => .medium,+ .high => .high,+ .xhigh => .xhigh,+ .max => .max,+ .ultra => .ultra,+ },+ .fast = params.fast,+ .fallback_allow = c.fallback_allow,+ .fallback_active = c.fallback_active,+ .fallback_blocked = c.fallback_blocked,+ .ultracode_mode = params.ultracode,+ .show_thinking = params.thinking,+ .strict = Policy.from(params).strict,+ };+ try prompts.setSystemPrompts(&agent, sys, arena);+ return agent;+}++/// repl.TurnFn — run a full ROOT agent turn (tools + MCP) for the chat+/// frontends, so the model can read files, run bash, search the codebase, etc.+/// Output streams into a thread-safe sink the frontend polls to render live;+/// the clean final text is runTurn's return value. Returns the final assistant+/// text (raw markdown, owned by gpa) or null.+pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Turn, params: repl.Params, stream: *repl.StreamBuf) ?[]const u8 {+ const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var sink: repl_glue.ReplStreamSink = undefined;+ sink.init(stream); // agent output streams into the repl's live pane (thread-safe)+ const policy = Policy.from(params);+ // plan_mode is a process global (agent_tool_gate/exec read it), so it is+ // armed and restored around the call rather than left set — a chat turn+ // must not silently change the mode of whatever else shares this process.+ const plan_saved = main_mod.plan_mode;+ main_mod.plan_mode = policy.plan;+ defer main_mod.plan_mode = plan_saved;+ var approvals: Approvals = .{ .yolo = policy.yolo };+ var agent = turnAgent(c, gpa, arena, params, &sink.writer, &approvals) catch return null;+ defer agent.tools_used.deinit(gpa);+ for (history) |t| {+ const role = switch (t.role) {+ .user => "user",+ .assistant => "assistant",+ };+ agent.messages.append(textMessage(arena, role, t.text) catch return null) catch return null;+ }+ defer {+ c.provider = agent.provider;+ c.fallback_active = agent.fallback_active;+ c.fallback_blocked = agent.fallback_blocked;+ }+ const final = providers.runTurnWithFallback(&agent, &c.keys, arena, &sink.writer) catch |err| switch (err) {+ // A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),+ // so postStream can return error.StreamStalled. Don't collapse it to+ // null — the pane renders that as "model call failed — check /model and+ // your API key", mislabeling a harness stall as an auth/config problem.+ // Keep the streamed partial + an honest marker, mirroring mainloop.+ error.StreamStalled => return earlyEnd(gpa, &agent, "stream stalled"),+ // A mid-stream provider drop (#133), same handling as a stall.+ error.StreamDropped => return earlyEnd(gpa, &agent, "connection dropped"),+ error.FallbackConsentRequired => return gpa.dupe(u8, "Saved model unavailable. Allow this provider with /fallback in the standard REPL, or choose another model.") catch null,+ else => return null,+ };+ const trimmed = std.mem.trim(u8, final, " \t\r\n");+ if (trimmed.len == 0) return null;+ return gpa.dupe(u8, trimmed) catch null;+}++/// Keep whatever streamed plus an honest marker — never a null, which the pane+/// renders as "model call failed — check /model and your API key".+fn earlyEnd(gpa: Allocator, agent: *Agent, why: []const u8) ?[]const u8 {+ const partial = std.mem.trim(u8, agent.partial_text.items, " \t\r\n");+ return if (partial.len > 0)+ std.fmt.allocPrint(gpa, "{s}\n\n[response ended early: {s}]", .{ partial, why }) catch null+ else+ std.fmt.allocPrint(gpa, "[response ended early: {s}]", .{why}) catch null;+}++// ── tests ───────────────────────────────────────────────────────────────────++const testing = std.testing;++fn testCtx(client: *std.http.Client) ReplCtx {+ return .{+ .io = testing.io,+ .client = client,+ .keys = .{ .values = @splat(null) },+ .home = "",+ .provider = .{+ .id = "anthropic",+ .kind = .anthropic,+ .auth = .x_api_key,+ .url = "",+ .api_key = "",+ .model = "sonnet",+ .context = 200_000,+ },+ .fallback_allow = &.{},+ .fallback_active = false,+ .fallback_blocked = false,+ .registry = null,+ .tracer = null,+ .run_budget = null,+ .sys_normal = "BASE-PROMPT",+ .tools_anthropic = "[]",+ .tools_openai = "[]",+ .tools_responses = "[]",+ };+}++test "plan mode on a chat turn actually denies a write_file (#551)" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var client: std.http.Client = undefined;+ var c = testCtx(&client);+ var discard_buf: [64]u8 = undefined;+ var discarding: Io.Writer.Discarding = .init(&discard_buf);++ var call_input: std.json.ObjectMap = .empty;+ try call_input.put(arena, "path", .{ .string = "notes.md" });+ try call_input.put(arena, "content", .{ .string = "hello" });+ const call: @import("tools.zig").ToolCall = .{+ .id = "t1",+ .name = "write_file",+ .input = .{ .object = call_input },+ };++ const plan_saved = main_mod.plan_mode;+ defer main_mod.plan_mode = plan_saved;++ // Plan mode: exactly the params a /plan TUI turn sends.+ {+ const params: repl.Params = .{ .mode = .plan };+ const policy = Policy.from(params);+ try testing.expect(policy.plan);+ // Auto-approval is NOT what stops the write; the plan gate is.+ try testing.expect(!policy.yolo);+ main_mod.plan_mode = policy.plan;+ var approvals: Approvals = .{ .yolo = policy.yolo };+ var agent = try turnAgent(&c, testing.allocator, arena, params, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(testing.allocator);+ const denied = (try agent.gateTool(call)) orelse return error.PlanModeLetTheWriteThrough;+ try testing.expect(denied.is_error);+ try testing.expect(std.mem.indexOf(u8, denied.text, "plan mode") != null);+ }++ // The same call in the default mode is not refused — the denial above is+ // the mode doing its job, not a write_file that never works here.+ {+ const params: repl.Params = .{ .mode = .always_approve };+ const policy = Policy.from(params);+ try testing.expect(!policy.plan);+ try testing.expect(policy.yolo);+ main_mod.plan_mode = policy.plan;+ var approvals: Approvals = .{ .yolo = policy.yolo };+ var agent = try turnAgent(&c, testing.allocator, arena, params, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(testing.allocator);+ try testing.expect((try agent.gateTool(call)) == null);+ }+}++test "/strict selects the strict system prompt on the turn's agent (#551)" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var client: std.http.Client = undefined;+ var c = testCtx(&client);+ var discard_buf: [64]u8 = undefined;+ var discarding: Io.Writer.Discarding = .init(&discard_buf);+ var approvals: Approvals = .{ .yolo = true };++ var relaxed = try turnAgent(&c, testing.allocator, arena, .{}, &discarding.writer, &approvals);+ defer relaxed.tools_used.deinit(testing.allocator);+ try testing.expect(!relaxed.strict);+ try testing.expectEqualStrings(relaxed.sys_normal, relaxed.systemPrompt());++ var strict = try turnAgent(&c, testing.allocator, arena, .{ .strict = true }, &discarding.writer, &approvals);+ defer strict.tools_used.deinit(testing.allocator);+ try testing.expect(strict.strict);+ try testing.expectEqualStrings(strict.sys_strict, strict.systemPrompt());+ // Not the same text — a /strict that resolved back to sys_normal would be+ // the label-only bug wearing a different hat.+ try testing.expect(!std.mem.eql(u8, strict.sys_normal, strict.systemPrompt()));++ // /strict composes with ultracode rather than being replaced by it (#326).+ var both = try turnAgent(&c, testing.allocator, arena, .{ .strict = true, .ultracode = true }, &discarding.writer, &approvals);+ defer both.tools_used.deinit(testing.allocator);+ try testing.expectEqualStrings(both.sys_ultra_strict, both.systemPrompt());+}diff --git a/src/repl_types.zig b/src/repl_types.zignew file mode 100644index 00000000..d1c14e3c--- /dev/null+++ b/src/repl_types.zig@@ -0,0 +1,84 @@+//! The turn-backend vocabulary shared by every chat frontend: what a turn is+//! asked to do (Params), what it is given (Turn history), and where its prose+//! streams (StreamBuf). Moved out of repl.zig, which is at the 600-line cap+//! (#123's move+alias pattern) — `repl.Params` and friends still resolve, and+//! the mutable `g_*` hooks deliberately stay declared in repl.zig, because an+//! alias would freeze their value.+//!+//! Nothing here imports the harness. `src/repl_glue.zig` is the one place that+//! translates these into an Agent, and #551 is why `mode`/`strict` live on+//! Params at all: a frontend's permission policy has to REACH the engine, not+//! sit beside it as a label.++const std = @import("std");++pub const Effort = enum { low, medium, high, xhigh, max, ultra };++pub const Turn = struct {+ role: Role,+ text: []const u8,+ pub const Role = enum { user, assistant };+};++/// The session's permission policy, as a turn backend must apply it: `.plan`+/// arms main.plan_mode (the read-only gate), `.always_approve` is --yolo.+pub const Mode = enum { normal, plan, always_approve };++pub const Params = struct {+ effort: Effort = .medium,+ fast: bool = false,+ thinking: bool = false,+ ultracode: bool = false,+ /// always_approve by default: the scripted chat REPL has no mode surface.+ /// A frontend that has one (the TUI) sends its real mode instead.+ mode: Mode = .always_approve,+ /// /strict — selects the strict system prompt for the turn.+ strict: bool = false,+ goal: []const u8 = "", // "" = none+};++pub const StreamBuf = struct {+ // Single-writer (worker thread) / single-reader (render loop), lock-free: a+ // fixed pre-allocated buffer (no realloc → stable pointer) + an atomic+ // length. The worker appends bytes then release-stores the new length; the+ // reader acquire-loads it and reads the committed prefix. Overflow drops+ // extra bytes — only the live preview is affected (the final reply uses+ // runTurn's return value).+ buf: []u8 = &.{},+ len: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),+ pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {+ const cur = self.len.load(.monotonic);+ if (cur >= self.buf.len) return;+ const n = @min(bytes.len, self.buf.len - cur);+ @memcpy(self.buf[cur .. cur + n], bytes[0..n]);+ self.len.store(cur + n, .release);+ }+ pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {+ const n = self.len.load(.acquire);+ if (n == 0) return null;+ return gpa.dupe(u8, self.buf[0..n]) catch null;+ }+};++pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf) ?[]const u8;++test "Params defaults keep the scripted REPL auto-approving, and plan is opt-in" {+ const p: Params = .{};+ try std.testing.expectEqual(Mode.always_approve, p.mode);+ try std.testing.expect(!p.strict);+ const planning: Params = .{ .mode = .plan, .strict = true };+ try std.testing.expectEqual(Mode.plan, planning.mode);+ try std.testing.expect(planning.strict);+}++test "StreamBuf: append publishes length, overflow drops silently" {+ var buf: [8]u8 = undefined;+ var s: StreamBuf = .{ .buf = &buf };+ s.appendBytes("hi");+ try std.testing.expectEqual(@as(usize, 2), s.len.load(.acquire));+ s.appendBytes("0123456789");+ try std.testing.expectEqual(@as(usize, 8), s.len.load(.acquire));+ const snap = s.snapshot(std.testing.allocator) orelse return error.NoSnapshot;+ defer std.testing.allocator.free(snap);+ try std.testing.expectEqualStrings("hi012345", snap);+}diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 35ac8601..57bb7c33 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -172,6 +172,15 @@ fn turnCb(.fast = params.fast,.thinking = params.thinking,.ultracode = params.ultracode,+ // #551: the footer's mode IS the turn's policy now. The two enums are+ // mapped explicitly so a new mode on either side is a compile error+ // rather than a badge that quietly means nothing.+ .mode = switch (params.mode) {+ .normal => .normal,+ .plan => .plan,+ .always_approve => .always_approve,+ },+ .strict = params.strict,.goal = params.goal,}, liveStream(stream));if (result != null) {