graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): the engine owns the conversation, not the rendered transcript
Rach Pradhan4e6b12b248a8
diff --git a/TUI/app.zig b/TUI/app.zigindex ff978485..a76e9c4b 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -264,6 +264,15 @@ pub const Model = struct {self.screen = .welcome;}+ /// /new, /clear, Ctrl+N twice: start over. Distinct from clearHistory,+ /// which the compaction replay also uses — that one REPLACES the visible+ /// transcript for a conversation the engine has just rewritten and must+ /// keep, while this one throws the conversation away too (#551).+ pub fn newSession(self: *Model) void {+ self.clearHistory();+ engine.historyChanged(.reset);+ }+pub fn userTurnCount(self: *const Model) usize {var n: usize = 0;for (self.history.items) |e| {diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex 2ca7b6d5..53350c18 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -75,7 +75,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.quit_requested = true;return .quit;} else if (std.mem.eql(u8, canon, "/new")) {- self.clearHistory();+ self.newSession();self.push(.system, "started a new conversation") catch {};self.screen = .welcome;} else if (std.mem.eql(u8, canon, "/home")) {@@ -264,6 +264,10 @@ pub fn rewind(self: *Model) void {var j = self.history.items.len;while (j > i - 1) : (j -= 1) self.freeEntry(self.history.items[j - 1]);self.history.shrinkRetainingCapacity(i - 1);+ // The engine holds the conversation, so taking the turn back has to reach+ // it too — otherwise the next request still carries the prompt the user+ // just withdrew (#551).+ engine.historyChanged(.rewind);self.push(.system, "rewound the last turn") catch {};}diff --git a/TUI/dispatch_tests.zig b/TUI/dispatch_tests.zigindex 0c665a55..b2cc9ebd 100644--- a/TUI/dispatch_tests.zig+++ b/TUI/dispatch_tests.zig@@ -86,6 +86,58 @@ test "/new /compact /rewind are blocked while a job is pending (#521)" {try std.testing.expectEqualStrings("hi", m.history.items[0].text);}+test "cutting the transcript reaches the engine's conversation (#551)" {+ // The model's history lives in the engine now, so a TUI-local truncation+ // that never told it left the discarded turns in the next request body.+ const Seen = struct {+ var ops: std.ArrayList(engine.HistoryOp) = .empty;+ fn f(_: ?*anyopaque, op: engine.HistoryOp) void {+ ops.append(std.testing.allocator, op) catch {};+ }+ };+ Seen.ops = .empty;+ defer Seen.ops.deinit(std.testing.allocator);+ engine.g_history_fn = Seen.f;+ defer engine.g_history_fn = null;++ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "alpha");+ try m.push(.assistant, "beta");++ _ = dispatch.applyLine(&m, "/rewind");+ try std.testing.expectEqual(@as(usize, 1), Seen.ops.items.len);+ try std.testing.expectEqual(engine.HistoryOp.rewind, Seen.ops.items[0]);++ _ = dispatch.applyLine(&m, "/new");+ try std.testing.expectEqual(@as(usize, 2), Seen.ops.items.len);+ try std.testing.expectEqual(engine.HistoryOp.reset, Seen.ops.items[1]);++ // /clear is the same command under another name, and Ctrl+N (twice) is the+ // same session reset from the keyboard.+ _ = dispatch.applyLine(&m, "/clear");+ try std.testing.expectEqual(engine.HistoryOp.reset, Seen.ops.items[Seen.ops.items.len - 1]);+ const before = Seen.ops.items.len;++ // Compaction must NOT come through here: it REWROTE the conversation, and+ // resetting on the replay would throw away the summary it just produced.+ engine.g_compact_fn = struct {+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, out: *engine.CompactOut) bool {+ out.note = gpa.dupe(u8, "history compacted") catch "";+ const turns = gpa.alloc(engine.Turn, 1) catch return false;+ turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "Context: earlier work") catch "" };+ out.turns = turns;+ return true;+ }+ }.f;+ defer engine.g_compact_fn = null;+ try m.push(.user, "gamma");+ _ = dispatch.applyLine(&m, "/compact");+ try settle(&m);+ try std.testing.expectEqual(before, Seen.ops.items.len);+}+test "/compact never crops locally; engine stub rewrites history" {var m: Model = undefined;m.setup(std.testing.allocator);diff --git a/TUI/engine.zig b/TUI/engine.zigindex e8588a8d..61e6bc68 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -82,6 +82,13 @@ pub const CompactOut = struct {};pub const CompactFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, out: *CompactOut) bool;+/// The frontend just discarded part of its transcript. The engine owns the+/// conversation the model actually sees (#551), so it has to be told: without+/// this, /new left the whole old session in the request body and /rewind left+/// a prompt the user had taken back.+pub const HistoryOp = enum { reset, rewind };+pub const HistoryFn = *const fn (turn_ctx: ?*anyopaque, op: HistoryOp) void;+pub const Job = struct {thread: std.Thread = undefined,threaded: bool = true,@@ -151,6 +158,13 @@ pub var g_bash_fn: ?BashFn = null;pub var g_files_fn: ?FilesFn = null;pub var g_copy_fn: ?CopyFn = null;pub var g_compact_fn: ?CompactFn = null;+pub var g_history_fn: ?HistoryFn = null;++/// Tell the engine the transcript was cut. Silent when nothing is wired+/// (offline TUI, unit tests).+pub fn historyChanged(op: HistoryOp) void {+ if (g_history_fn) |f| f(g_turn_ctx, op);+}pub var g_model_name: []const u8 = "";pub var g_models: []const u8 = "";pub var g_cwd: []const u8 = ".";diff --git a/TUI/nav.zig b/TUI/nav.zigindex 92bbc0a6..d8af7145 100644--- a/TUI/nav.zig+++ b/TUI/nav.zig@@ -51,7 +51,7 @@ fn isCtrl(k: Key, c: u8) bool {fn ctrlN(self: *Model) void {if (self.new_arm_until_ms != 0 and self.now_ms <= self.new_arm_until_ms) {- self.clearHistory();+ self.newSession();self.new_arm_until_ms = 0;self.setToast("new session");return;diff --git a/TUI/root.zig b/TUI/root.zigindex 698bef74..8f660ba9 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -25,6 +25,8 @@ pub const ModelFn = engine.ModelFn;pub const CancelFn = engine.CancelFn;pub const CompactOut = engine.CompactOut;pub const CompactFn = engine.CompactFn;+pub const HistoryOp = engine.HistoryOp;+pub const HistoryFn = engine.HistoryFn;pub const RunOpts = run_mod.RunOpts;pub const run = run_mod.run;pub const restore = @import("restore.zig");diff --git a/TUI/run.zig b/TUI/run.zigindex 8c037375..5389c9a6 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -39,6 +39,7 @@ pub const RunOpts = struct {files_fn: ?engine.FilesFn = null,copy_fn: ?engine.CopyFn = null,compact_fn: ?engine.CompactFn = null,+ history_fn: ?engine.HistoryFn = null,};pub fn run(@@ -58,6 +59,7 @@ pub fn run(engine.g_files_fn = opts.files_fn;engine.g_copy_fn = opts.copy_fn;engine.g_compact_fn = opts.compact_fn;+ engine.g_history_fn = opts.history_fn;engine.g_model_name = opts.model_name;engine.g_models = opts.models;engine.g_cwd = opts.cwd;diff --git a/src/repl_compact.zig b/src/repl_compact.zigindex 8432a3f5..92180f5d 100644--- a/src/repl_compact.zig+++ b/src/repl_compact.zig@@ -27,13 +27,17 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const replout.note = gpa.dupe(u8, "compaction needs a live session") catch "";return false;}));- if (history.len == 0) {+ // With a session conversation the engine's own history is what gets+ // compacted — `history` is only the frontend's projection of it, and+ // summarizing that would throw away the tool blocks compaction exists to+ // fold up (#551).+ if (history.len == 0 and (c.convo == null or c.convo.?.len() == 0)) {out.note = gpa.dupe(u8, "nothing to compact") catch "";return false;}- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();+ var scratch_state = std.heap.ArenaAllocator.init(gpa);+ defer scratch_state.deinit();+ const arena = if (c.convo) |cv| cv.alloc() else scratch_state.allocator();var discard_buf: [256]u8 = undefined;var discarding: Io.Writer.Discarding = .init(&discard_buf);var approvals: Approvals = .{ .yolo = true };@@ -65,7 +69,10 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const replreturn false;};defer agent.tools_used.deinit(gpa);- for (history) |t| {+ if (c.convo) |cv| {+ agent.scratch_arena = &scratch_state;+ agent.messages = cv.list().*;+ } else for (history) |t| {const role = switch (t.role) {.user => "user",.assistant => "assistant",@@ -78,6 +85,11 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const replreturn false;};}+ // Whatever compact() did to the borrowed list — rewrite, or nothing at all+ // on a failure that leaves history untouched — is the session's state now.+ defer if (c.convo) |cv| {+ cv.list().* = agent.messages;+ };const n = agent.compact() catch |err| {out.note = (switch (err) {error.EmptySummary => gpa.dupe(u8, "compaction failed: empty summary, history unchanged"),diff --git a/src/repl_convo.zig b/src/repl_convo.zignew file mode 100644index 00000000..f2bffc62--- /dev/null+++ b/src/repl_convo.zig@@ -0,0 +1,202 @@+//! The chat session's conversation, owned by the ENGINE (#551).+//!+//! Before this file the TUI rebuilt the model's history out of its own+//! rendered rows every turn: `.user`/`.assistant` text only, every tool row+//! dropped, into a throwaway Agent. So the model never saw the tool_use /+//! tool_result blocks from its own previous turns — it could not remember what+//! it had read or run — and because the prefix was re-materialized each time,+//! prompt caching had nothing stable to hit.+//!+//! Now the conversation lives here for the life of the session, exactly as+//! mainloop's root agent keeps `root.messages`, and the frontend's transcript+//! is a PROJECTION of it. The per-turn Agent borrows these messages and hands+//! them back, so assistant turns and tool blocks accumulate in place.+//!+//! Allocation: message content must outlive the turn that created it, so this+//! owns a dedicated arena and the turn agent uses it as its `arena` (the+//! allocator `messageMutationAlloc` writes provider responses into). Per-turn+//! parse garbage goes to the agent's `scratch_arena`, which is reset per+//! request — the same split the root agent has had since #124.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const messages_mod = @import("messages.zig");+const repl = @import("repl.zig");++pub const Conversation = struct {+ arena: std.heap.ArenaAllocator,+ /// Initialized lazily by `list()`: the arena's allocator embeds a pointer+ /// to the arena, so nothing may allocate from it until the Conversation+ /// has settled at its final address.+ messages: std.json.Array = undefined,+ live: bool = false,++ pub fn init(gpa: Allocator) Conversation {+ return .{ .arena = std.heap.ArenaAllocator.init(gpa) };+ }++ pub fn deinit(self: *Conversation) void {+ self.arena.deinit();+ }++ pub fn alloc(self: *Conversation) Allocator {+ return self.arena.allocator();+ }++ pub fn list(self: *Conversation) *std.json.Array {+ if (!self.live) {+ self.messages = std.json.Array.init(self.arena.allocator());+ self.live = true;+ }+ return &self.messages;+ }++ pub fn len(self: *Conversation) usize {+ return if (self.live) self.messages.items.len else 0;+ }++ /// `/new` and `/clear`: the session starts over, and the memory goes with+ /// it. Everything the old messages pointed at lived in this arena.+ pub fn reset(self: *Conversation) void {+ _ = self.arena.reset(.free_all);+ self.live = false;+ }++ /// `/rewind`: drop back to just before the last human prompt, so the+ /// engine's history matches the transcript the frontend just truncated.+ /// A tool result is a user-role message with ARRAY content, so it is never+ /// mistaken for the prompt.+ pub fn rewind(self: *Conversation) void {+ if (!self.live) return;+ var i = self.messages.items.len;+ while (i > 0) {+ i -= 1;+ if (isUserPrompt(self.messages.items[i])) {+ self.messages.shrinkRetainingCapacity(i);+ return;+ }+ }+ self.messages.clearRetainingCapacity();+ }++ /// Fold the frontend's flattened transcript into the session conversation.+ /// An empty conversation adopts all of it — the first turn, or a transcript+ /// replayed after a compaction. A live one takes only the trailing user+ /// message: everything before it is already here, in richer form than the+ /// frontend could hand back.+ pub fn adopt(self: *Conversation, history: []const repl.Turn) !void {+ const msgs = self.list();+ if (msgs.items.len == 0) {+ for (history) |t| try msgs.append(try textOf(self.alloc(), t));+ return;+ }+ if (history.len == 0) return;+ const last = history[history.len - 1];+ if (last.role != .user) return;+ try msgs.append(try textOf(self.alloc(), last));+ }++ /// Put a line into the conversation that the model did not produce and did+ /// not ask for — a `!cmd` the user ran, and what it printed. The model has+ /// to see it: the user is talking about that output on the next turn.+ pub fn note(self: *Conversation, text: []const u8) !void {+ const msgs = self.list();+ try msgs.append(try messages_mod.textMessage(self.alloc(), "user", text));+ }++ /// Replace the whole conversation (compaction rewrote it). The messages+ /// must already be allocated from this conversation's arena.+ pub fn replace(self: *Conversation, rewritten: []const Value) !void {+ const msgs = self.list();+ msgs.clearRetainingCapacity();+ try msgs.appendSlice(rewritten);+ }+};++fn textOf(a: Allocator, t: repl.Turn) !Value {+ return messages_mod.textMessage(a, switch (t.role) {+ .user => "user",+ .assistant => "assistant",+ }, t.text);+}++fn isUserPrompt(v: Value) bool {+ if (v != .object) return false;+ const role = v.object.get("role") orelse return false;+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;+ const content = v.object.get("content") orelse return false;+ return content == .string;+}++const testing = std.testing;++fn roleOf(v: Value) []const u8 {+ return v.object.get("role").?.string;+}++test "adopt takes the whole transcript once, then only the new prompt" {+ var convo = Conversation.init(testing.allocator);+ defer convo.deinit();++ // Turn 1: nothing here yet, so the frontend's transcript seeds it.+ try convo.adopt(&.{.{ .role = .user, .text = "one" }});+ try testing.expectEqual(@as(usize, 1), convo.len());++ // The engine then writes what only it knows: a tool call and its result.+ const msgs = convo.list();+ try msgs.append(try messages_mod.textMessage(convo.alloc(), "assistant", "TOOL_USE_BLOCK"));++ // Turn 2: the frontend hands back its flattened rows. The tool block must+ // survive, and "one" must not be duplicated.+ try convo.adopt(&.{+ .{ .role = .user, .text = "one" },+ .{ .role = .assistant, .text = "answer" },+ .{ .role = .user, .text = "two" },+ });+ try testing.expectEqual(@as(usize, 3), convo.len());+ try testing.expectEqualStrings("TOOL_USE_BLOCK", msgs.items[1].object.get("content").?.string);+ try testing.expectEqualStrings("two", msgs.items[2].object.get("content").?.string);+}++test "reset clears the conversation; rewind drops back to before the last prompt" {+ var convo = Conversation.init(testing.allocator);+ defer convo.deinit();+ try convo.adopt(&.{.{ .role = .user, .text = "first" }});+ const msgs = convo.list();+ try msgs.append(try messages_mod.textMessage(convo.alloc(), "assistant", "reply"));+ try convo.adopt(&.{ .{ .role = .user, .text = "first" }, .{ .role = .assistant, .text = "reply" }, .{ .role = .user, .text = "second" } });+ try testing.expectEqual(@as(usize, 3), convo.len());++ convo.rewind();+ try testing.expectEqual(@as(usize, 2), convo.len());+ try testing.expectEqualStrings("assistant", roleOf(convo.list().items[1]));++ convo.reset();+ try testing.expectEqual(@as(usize, 0), convo.len());+ // Usable again after a reset — the arena was freed, not poisoned.+ try convo.adopt(&.{.{ .role = .user, .text = "fresh" }});+ try testing.expectEqual(@as(usize, 1), convo.len());+ try testing.expectEqualStrings("fresh", convo.list().items[0].object.get("content").?.string);+}++test "a tool result is not mistaken for the human prompt on rewind" {+ var convo = Conversation.init(testing.allocator);+ defer convo.deinit();+ try convo.adopt(&.{.{ .role = .user, .text = "run it" }});+ const a = convo.alloc();+ const msgs = convo.list();+ try msgs.append(try messages_mod.textMessage(a, "assistant", "calling"));+ // Anthropic wraps a tool_result in a USER message whose content is an array.+ var blocks = std.json.Array.init(a);+ try blocks.append(try messages_mod.toolResultMessage(a, .anthropic, "id-1", "ok", false));+ var wrapper: std.json.ObjectMap = .empty;+ try wrapper.put(a, "role", .{ .string = "user" });+ try wrapper.put(a, "content", .{ .array = blocks });+ try msgs.append(.{ .object = wrapper });++ convo.rewind();+ // Back to before "run it" — not to just before the tool result.+ try testing.expectEqual(@as(usize, 0), convo.len());+}diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 91599541..8d1abeb0 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -53,8 +53,21 @@ pub const ReplCtx = struct {tools_anthropic: []const u8,tools_openai: []const u8,tools_responses: []const u8,+ /// The session's conversation, when the frontend wants the engine to own+ /// it (#551). Null = the caller has no session memory and each turn is+ /// built from the transcript it passes in, which is what `graff repl`'s+ /// scripted path still does.+ convo: ?*repl_convo.Conversation = null,};+/// The engine-owned conversation, in repl_convo.zig (move+alias, #123).+pub const Conversation = repl_convo.Conversation;+const repl_convo = @import("repl_convo.zig");++test {+ _ = repl_convo;+}+/// The live-pane writer, in repl_stream_sink.zig (move+alias, #123).pub const ReplStreamSink = @import("repl_stream_sink.zig").ReplStreamSink;diff --git a/src/repl_turn.zig b/src/repl_turn.zigindex dcad59a2..e96372a0 100644--- a/src/repl_turn.zig+++ b/src/repl_turn.zig@@ -107,6 +107,36 @@ pub fn turnAgent(return agent;}+/// Give the turn's agent the session's history. With a conversation the agent+/// BORROWS it — only the new prompt is folded in, so the request's prefix is+/// byte-identical to last turn's (prompt caching) and the model still sees the+/// tool calls it made earlier. Without one, the frontend's transcript is+/// materialized into the throwaway arena, which is all `graff repl` needs.+fn borrowHistory(c: *ReplCtx, agent: *Agent, history: []const repl.Turn, arena: Allocator, scratch: *std.heap.ArenaAllocator) !void {+ const cv = c.convo orelse {+ for (history) |t| {+ const role = switch (t.role) {+ .user => "user",+ .assistant => "assistant",+ };+ try agent.messages.append(try textMessage(arena, role, t.text));+ }+ return;+ };+ try cv.adopt(history);+ agent.messages = cv.list().*;+ // Transient parse garbage goes here instead of the session arena (#124).+ agent.scratch_arena = scratch;+}++/// Hand the conversation back. runTurn appended this turn's assistant message+/// and every tool_use/tool_result pair to the borrowed list, and a managed+/// ArrayList is a VALUE — not copying it back would drop the whole turn.+fn returnHistory(c: *ReplCtx, agent: *Agent) void {+ const cv = c.convo orelse return;+ cv.list().* = agent.messages;+}+/// 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;@@ -114,9 +144,15 @@ pub fn turnAgent(/// 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();+ // Per-turn scratch. When the session owns a conversation this is the+ // agent's `scratch_arena` (reset per request, #124) and the conversation's+ // arena is the agent's `arena`, so provider responses — the tool_use and+ // tool_result blocks — are written where they OUTLIVE the turn. Without a+ // conversation it is both, which is the old throwaway behavior.+ var scratch_state = std.heap.ArenaAllocator.init(gpa);+ defer scratch_state.deinit();+ const scratch = scratch_state.allocator();+ const arena = if (c.convo) |cv| cv.alloc() else scratch;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);@@ -129,17 +165,12 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tuvar 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;- }+ borrowHistory(c, &agent, history, arena, &scratch_state) catch return null;defer {c.provider = agent.provider;c.fallback_active = agent.fallback_active;c.fallback_blocked = agent.fallback_blocked;+ returnHistory(c, &agent);}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),@@ -252,6 +283,127 @@ test "plan mode on a chat turn actually denies a write_file (#551)" {}}+/// Stand in for the provider round trip: write into the borrowed history+/// exactly the shape agent_steps writes for an anthropic tool turn — an+/// assistant message carrying a tool_use block, then the user message carrying+/// its tool_result. This is the content the TUI's flattened `.user`/`.assistant`+/// rows can never carry back, which is the whole point of the conversation.+fn fakeToolTurn(agent: *Agent, id: []const u8, cmd: []const u8, result: []const u8) !void {+ const a = agent.arena;+ var use: std.json.ObjectMap = .empty;+ try use.put(a, "type", .{ .string = "tool_use" });+ try use.put(a, "id", .{ .string = id });+ try use.put(a, "name", .{ .string = "bash" });+ var input: std.json.ObjectMap = .empty;+ try input.put(a, "command", .{ .string = cmd });+ try use.put(a, "input", .{ .object = input });+ var content = std.json.Array.init(a);+ try content.append(.{ .object = use });+ var assistant: std.json.ObjectMap = .empty;+ try assistant.put(a, "role", .{ .string = "assistant" });+ try assistant.put(a, "content", .{ .array = content });+ try agent.messages.append(.{ .object = assistant });++ var results = std.json.Array.init(a);+ try results.append(try @import("messages.zig").toolResultMessage(a, .anthropic, id, result, false));+ var wrapper: std.json.ObjectMap = .empty;+ try wrapper.put(a, "role", .{ .string = "user" });+ try wrapper.put(a, "content", .{ .array = results });+ try agent.messages.append(.{ .object = wrapper });+}++test "turn 2 carries turn 1's tool_use and tool_result; /clear drops both (#551)" {+ const gpa = testing.allocator;+ var client: std.http.Client = undefined;+ var c = testCtx(&client);+ var convo = @import("repl_convo.zig").Conversation.init(gpa);+ defer convo.deinit();+ c.convo = &convo;+ var discard_buf: [64]u8 = undefined;+ var discarding: Io.Writer.Discarding = .init(&discard_buf);+ var approvals: Approvals = .{ .yolo = true };+ const tools = "[{\"name\":\"bash\",\"description\":\"\",\"input_schema\":{\"type\":\"object\"}}]";++ // ── turn 1: the user asks, the engine runs a tool ──────────────────────+ {+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ var agent = try turnAgent(&c, gpa, convo.alloc(), .{}, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(gpa);+ try borrowHistory(&c, &agent, &.{.{ .role = .user, .text = "count the files" }}, convo.alloc(), &scratch);+ try fakeToolTurn(&agent, "call-1", "ls | wc -l", "42");+ try agent.messages.append(try textMessage(agent.arena, "assistant", "there are 42"));+ returnHistory(&c, &agent);+ }++ // ── turn 2: the request must still contain turn 1's tool exchange ──────+ {+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ var agent = try turnAgent(&c, gpa, convo.alloc(), .{}, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(gpa);+ try borrowHistory(&c, &agent, &.{+ .{ .role = .user, .text = "count the files" },+ .{ .role = .assistant, .text = "there are 42" },+ .{ .role = .user, .text = "and how many are zig?" },+ }, convo.alloc(), &scratch);+ const body = try agent.buildBody(tools, false, true, true);+ defer gpa.free(body);+ try testing.expect(std.mem.indexOf(u8, body, "tool_use") != null);+ try testing.expect(std.mem.indexOf(u8, body, "call-1") != null);+ try testing.expect(std.mem.indexOf(u8, body, "tool_result") != null);+ try testing.expect(std.mem.indexOf(u8, body, "ls | wc -l") != null);+ try testing.expect(std.mem.indexOf(u8, body, "and how many are zig?") != null);+ // The first prompt appears ONCE — adopt() folds in only the new tail,+ // it does not re-materialize the transcript on top of itself.+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, body, "count the files"));+ returnHistory(&c, &agent);+ }++ // ── /clear: the next turn carries neither ─────────────────────────────+ convo.reset();+ {+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ var agent = try turnAgent(&c, gpa, convo.alloc(), .{}, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(gpa);+ try borrowHistory(&c, &agent, &.{.{ .role = .user, .text = "fresh start" }}, convo.alloc(), &scratch);+ const body = try agent.buildBody(tools, false, true, true);+ defer gpa.free(body);+ try testing.expect(std.mem.indexOf(u8, body, "tool_use") == null);+ try testing.expect(std.mem.indexOf(u8, body, "call-1") == null);+ try testing.expect(std.mem.indexOf(u8, body, "tool_result") == null);+ try testing.expect(std.mem.indexOf(u8, body, "count the files") == null);+ try testing.expect(std.mem.indexOf(u8, body, "fresh start") != null);+ returnHistory(&c, &agent);+ }+}++test "without a conversation every turn is still built from the transcript" {+ // `graff repl`'s scripted path has no session memory and must keep working+ // exactly as it did — this is the branch the TUI no longer takes.+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ 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 agent = try turnAgent(&c, gpa, arena, .{}, &discarding.writer, &approvals);+ defer agent.tools_used.deinit(gpa);+ try borrowHistory(&c, &agent, &.{+ .{ .role = .user, .text = "one" },+ .{ .role = .assistant, .text = "two" },+ }, arena, &scratch);+ try testing.expectEqual(@as(usize, 2), agent.messages.items.len);+ try testing.expect(agent.scratch_arena == null);+ returnHistory(&c, &agent); // a no-op without a conversation+}+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();diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 57bb7c33..87e4b890 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -86,6 +86,13 @@ pub fn run(.tools_openai = root.tools_openai,.tools_responses = root.tools_responses,};+ // #551: the session's conversation belongs to the engine and outlives every+ // turn, so tool_use/tool_result blocks accumulate the way mainloop's root+ // messages do instead of being rebuilt from rendered rows each turn. It is+ // created here, on the frame that owns the whole TUI session.+ var convo = repl_glue.Conversation.init(gpa);+ defer convo.deinit();+ repl_ctx.convo = &convo;var models_buf = std.array_list.Managed(u8).init(arena);for (pricing.models()) |mi| {if (mi.name.len == 0) continue;@@ -110,9 +117,23 @@ pub fn run(.files_fn = filesCb,.copy_fn = copyCb,.compact_fn = compactCb,+ .history_fn = historyCb,});}+/// The transcript was cut, so cut the conversation the same way: /new starts+/// over, /rewind takes back the last prompt and everything the engine did for+/// it. Compaction does NOT come through here — it rewrites the conversation+/// rather than discarding it.+fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return));+ const convo = c.convo orelse return;+ switch (op) {+ .reset => convo.reset(),+ .rewind => convo.rewind(),+ }+}+/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's/// appendBytes publish `stream.len` as bytes arrive. Layout is identical/// (buf + atomic len); a copy would hide the live tail until the turn ends.