graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(repl): /btw asks a side question that is never persisted (#415)
Rach Pradhan44b4abb81646
diff --git a/README.md b/README.mdindex 4f735ba8..fc60233d 100644--- a/README.md+++ b/README.md@@ -484,6 +484,7 @@ other animation names remain available./yolo toggle bash auto-approval (skip permission prompts)/trace toggle this run's JSONL event trace and show its path/compact summarize history into a fresh context+/btw <question> one side question about this conversation: no tools, billed, never added to the session/save | /resume | /sessions session persistence; bare /resume → interactive picker/todo show the current task list/skills list SKILL.md playbooks + companion tools; add/remove toggles onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 1c2bfc25..ec330625 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -38,3 +38,4 @@{"id": "orch-landed-turn-files-outcome-row", "why": "The landed-turn funnel: before it, flushPending fired only from the eval funnel and exhaustedFatal, so the learned rung policy never saw an ordinary success - blind to exactly the outcome it optimizes (a rung that lands within budget). A no-eval turn that admits a workflow decision must file its kind:\"orch_outcome\" row when the turn lands, so the next boot's fold has evidence from everyday runs, not just scored ones and deaths.", "env": {"GRAFF_FLEET": "on"}, "prompt": "fix the bug in stats.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "implement the fix", "tasks": [{"description": "fix", "prompt": "fix the defect in stats.py"}]}]}}, {"text": "declined solo - fixed it myself"}, {"tool": "bash", "arguments": {"command": "grep -h '\"kind\":\"orch_outcome\"' .graff/trajectories/*.jsonl | grep '\"arm\":\"R0\"' | grep -q '\"source\":\"bootstrap\"' && echo outcome-row-filed"}}, {"text": "the learning layer recorded the landing"}], "second_prompt": "did the learning layer record that?", "assert": [{"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"event": {"type": "tool_result", "name": "bash", "text": "outcome-row-filed\n"}}, {"final_text_contains": "recorded the landing"}]}{"id": "budget-exhausted-past-the-landing-dies-fatal", "why": "#368 exhaustedFatal, the harness's own last words - and the FIRST case that can exist at all, since the runner auto-failed every nonzero exit until expected_exit landed. The #390 landing reserve buys the run ONE tools-free final call; it cannot stop a model that answers that call with a tool call anyway, and executing that tool demands a call the pool cannot admit. A one-shot (-p) run must then die LOUDLY: exit 1 with the harness naming what ran out, that the work is PARTIAL and was NOT rolled back, and where the trace is - never the bare 'turn failed: RunBudgetExhausted' that #368 replaced, and never a silent exit 0. The asserts pin the whole ordering: request 1 carries the full toolset, request 2 IS the landing call (note present, tools gone), and only PAST it does the run die. NOTE (-p): one-shot sets root.out = null, so the --json event stream is empty and no event/final_text assert is expressible here; the same exhaustion inside the stdin/mainloop shape is non-fatal by design (an error event, exit 0), which is why this case must be one-shot. GRAFF_FLEET=on plus the workflow call makes the run carry a real orchestration decision, so exhaustedFatal's other half fires too - it files the score-0 exhausted:true orch_outcome row before dying (verified by hand in the workspace: kind:\"orch_outcome\" ... \"exhausted\":true,\"landed\":false). That row is NOT asserted: it is written as the process dies, after every scripted bash step could run, and the runner keeps no post-mortem surface - it becomes assertable when the trajectory_row extension lands.", "args": ["--max-model-calls", "2", "-p", "fix the failing checks in parser.py"], "env": {"GRAFF_FLEET": "on"}, "expected_exit": 1, "timeout_s": 90, "prompt": "fix the failing checks in parser.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read parser.py and locate the failing check"}]}]}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "never reached: the pool was dry two calls ago"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"stderr_contains": "model-call budget exhausted"}, {"stderr_contains": "(--max-model-calls 2)"}, {"stderr_contains": "Work done so far is PARTIAL and was NOT rolled back"}, {"stderr_contains": "raise --max-model-calls or re-run to continue"}]}{"id": "new-ask-retires-finished-checklist", "why": "#394: completed items from PRIOR asks piled up. The omitted-completed preserve rule (2896b32) is per-ASK, but the parking never expired: five unrelated goals in one session came back from todo_read as one 13-item [x] pile, and every new prompt inherited it. A checklist that is FULLY completed retires at the next user ask, so the second ask's list holds the second ask's work only - while an unfinished list still crosses the turn untouched (compaction-keeps-completed) and an omission inside one ask still preserves (todo-preserves-completed).", "args": [], "prompt": "rename the config flag", "second_prompt": "unrelated: draft the release notes", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "rename the flag in config.zig", "status": "completed"}]}}, {"text": "the flag is renamed"}, {"tool": "todo_write", "arguments": {"todos": [{"content": "draft the release notes", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "the release notes are drafted"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 1}}, {"request_contains": {"index": -1, "text": "[~] draft the release notes"}}, {"request_lacks": {"index": -1, "text": "[x] rename the flag in config.zig\\n[~] draft the release notes"}}, {"final_text_contains": "the release notes are drafted"}]}+{"id": "btw-side-question-leaves-no-trace", "why": "#415: /btw must be answered from the LIVE context with NO tools and then vanish. The next turn's request is where the regression would show: a side question that reaches it has reached root.messages, which is the only way it could also reach the session file OR the append-only transcript (#441) - both are written from that same array.", "prompt": "build it", "controls_after_turn": [{"type": "btw", "text": "what did that linker error actually mean?"}], "second_prompt": "ok, carry on", "script": [{"text": "the link step failed with an undefined symbol"}, {"text": "SIDE-ONLY it means the entry point was renamed"}, {"text": "moving on"}], "assert": [{"event": {"type": "btw", "ok": true, "persisted": false}}, {"request_contains": {"index": 1, "text": "what did that linker error actually mean?"}}, {"request_contains": {"index": 1, "text": "the link step failed with an undefined symbol"}}, {"request_lacks": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "what did that linker error actually mean?"}}, {"request_lacks": {"index": -1, "text": "SIDE-ONLY"}}, {"request_contains": {"index": -1, "text": "the link step failed with an undefined symbol"}}]}diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 8cd3dfd7..59edc5c3 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -50,6 +50,7 @@ pub const commands = [_]Item{.{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },.{ .name = "/doctor", .desc = "read-only health check: goal/todo invariants, and why steering will or will not be appended" },+ .{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — no tools, billed, never added to the session" },.{ .name = "/compact", .desc = "summarize history into a fresh context" },.{ .name = "/rewind", .usage = "/rewind [n]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits" },.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex be576efd..7cbfa380 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -42,6 +42,7 @@ const models_cache = @import("models_cache.zig");const kimi_catalog = @import("kimi_catalog.zig");const providers = @import("providers.zig");const command_catalog = @import("command_catalog.zig");+const side_question = @import("side_question.zig"); // #415 /btwconst serde = @import("serde.zig");const mcp_cli = @import("mcp_cli.zig");@@ -152,6 +153,7 @@ fn ownedSessionName(arena: Allocator, arg: []const u8, fallback: []const u8) Allpub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {if (try commands_privacy.tryHandle(root, line, out)) return true;if (try playbook_glue.command(root, arena, line, out)) return true; // #381 /never | /constraint+ if (try side_question.command(root, arena, line, out)) return true; // #415 /btw// #321: doctor.zig shipped with a catalog entry but no dispatch, so /doctor// was advertised in /help and the `/` menu while answering "unknown command".if (std.mem.eql(u8, line, "/doctor")) {diff --git a/src/json_controls.zig b/src/json_controls.zignew file mode 100644index 00000000..7b01db71--- /dev/null+++ b/src/json_controls.zig@@ -0,0 +1,89 @@+//! The `--json` control fields mainloop applies inline: a request that changes+//! state, or answers something, WITHOUT becoming a turn.+//!+//! Split out of mainloop.zig, which sits at the 600-line ceiling (AGENTS.md),+//! so #415's `{"type":"btw"}` had somewhere to land. The per-request tool knobs+//! moved with it because they are the same shape — a field read off the parsed+//! request and applied on the spot — and moving them is what made the room.++const std = @import("std");+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const main_mod = @import("main.zig");+const side_question = @import("side_question.zig");++/// `{"type":"btw","text":"…"}` — #415's side question, the GUI's half of the+/// feature. True when the request WAS a side question and is now fully+/// answered, so the caller must not go on to run a turn for it.+///+/// `text` is the caller's already-validated non-empty text field. The answer+/// event carries `persisted:false` explicitly: a client that logs the stream+/// must be able to tell this apart from an ordinary assistant turn, because+/// the session it is mirroring does not contain it.+pub fn sideQuestion(root: *Agent, arena: Allocator, rtype: []const u8, text: []const u8) bool {+ if (!std.mem.eql(u8, rtype, "btw")) return false;+ if (side_question.ask(root, arena, text)) |answer| {+ root.emit(.{ .type = "btw", .ok = true, .text = answer, .persisted = false });+ } else {+ root.emit(.{ .type = "error", .message = "side question failed; the conversation is unchanged" });+ }+ return true;+}++/// The per-request tool ceilings, in both the camelCase the GUI sends and the+/// snake_case the CLI's own JSON uses. An explicit `null` clears the ceiling;+/// anything else is ignored rather than guessed at.+pub fn applyToolKnobs(obj: std.json.ObjectMap) void {+ if (obj.get("maxToolCalls") orelse obj.get("max_tool_calls")) |v| switch (v) {+ .integer => |n| main_mod.max_tool_calls = if (n >= 0) @intCast(n) else null,+ .null => main_mod.max_tool_calls = null,+ else => {},+ };+ if (obj.get("dedupeToolCalls") orelse obj.get("dedupe_tool_calls")) |v| {+ if (v == .bool) main_mod.dedupe_tool_calls = v.bool;+ }+}++test "applyToolKnobs reads both spellings and ignores junk" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ // Process-wide knobs: restore them or the next test inherits this one's.+ const max_before = main_mod.max_tool_calls;+ const dedupe_before = main_mod.dedupe_tool_calls;+ defer main_mod.max_tool_calls = max_before;+ defer main_mod.dedupe_tool_calls = dedupe_before;++ const camel = try std.json.parseFromSliceLeaky(std.json.Value, a,+ \\{"maxToolCalls":7,"dedupeToolCalls":true}+ , .{});+ applyToolKnobs(camel.object);+ try std.testing.expectEqual(@as(?u64, 7), main_mod.max_tool_calls);+ try std.testing.expect(main_mod.dedupe_tool_calls);++ const snake = try std.json.parseFromSliceLeaky(std.json.Value, a,+ \\{"max_tool_calls":null,"dedupe_tool_calls":false}+ , .{});+ applyToolKnobs(snake.object);+ try std.testing.expect(main_mod.max_tool_calls == null);+ try std.testing.expect(!main_mod.dedupe_tool_calls);++ // A wrong-typed knob leaves the current value alone rather than resetting it.+ main_mod.max_tool_calls = 3;+ const junk = try std.json.parseFromSliceLeaky(std.json.Value, a,+ \\{"maxToolCalls":"lots","dedupeToolCalls":"yes"}+ , .{});+ applyToolKnobs(junk.object);+ try std.testing.expectEqual(@as(?u64, 3), main_mod.max_tool_calls);+ try std.testing.expect(!main_mod.dedupe_tool_calls);+}++test "sideQuestion claims only its own control type" {+ // `root` is undefined on purpose: a case that reached the agent would be a+ // case that made a network call, and this one must not.+ var root: Agent = undefined;+ try std.testing.expect(!sideQuestion(&root, std.testing.allocator, "review", "look at HEAD"));+ try std.testing.expect(!sideQuestion(&root, std.testing.allocator, "user", "btw"));+ try std.testing.expect(!sideQuestion(&root, std.testing.allocator, "", "anything"));+}diff --git a/src/mainloop.zig b/src/mainloop.zigindex ab83bc20..381cb5ed 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -26,6 +26,7 @@ const goal_state = @import("goal_state.zig");const goal_flow = @import("goal_flow.zig");const goal_pacing = @import("goal_pacing.zig");const eval_memory = @import("eval_memory.zig");+const json_controls = @import("json_controls.zig"); // #415: the --json controls that never become a turnconst mainloop_score = @import("mainloop_score.zig");const mainloop_trace = @import("mainloop_trace.zig");const scoring = @import("scoring.zig");@@ -276,14 +277,10 @@ pub fn run(ctx: *Ctx) !void {continue;}if (std.mem.eql(u8, rtype, "review")) review_prompt = text;- if (parsed.object.get("maxToolCalls") orelse parsed.object.get("max_tool_calls")) |v| switch (v) {- .integer => |n| main_mod.max_tool_calls = if (n >= 0) @intCast(n) else null,- .null => main_mod.max_tool_calls = null,- else => {},- };- if (parsed.object.get("dedupeToolCalls") orelse parsed.object.get("dedupe_tool_calls")) |v| {- if (v == .bool) main_mod.dedupe_tool_calls = v.bool;- }+ // #415: a side question is ANSWERED here and never becomes a turn —+ // no tools, billed, and nothing added to the session or its transcript.+ if (json_controls.sideQuestion(ctx.root, ctx.arena, rtype, text)) continue;+ json_controls.applyToolKnobs(parsed.object);break :blk text;} else line;ctx.root.review_mode = review_prompt != null;diff --git a/src/side_question.zig b/src/side_question.zignew file mode 100644index 00000000..485ce4ed--- /dev/null+++ b/src/side_question.zig@@ -0,0 +1,163 @@+//! #415 — `/btw`: a throwaway side question, answered from the LIVE+//! conversation with tools disabled, rendered once, and then dropped.+//!+//! THE POINT. "what did that error actually mean?" is a question ABOUT the work+//! in progress, not a step of it. Asking it the ordinary way costs the session+//! two permanent messages plus their re-send on every turn after, and it is+//! summary input at the next compaction. `/btw` buys the answer and keeps none+//! of the exchange.+//!+//! HOW IT LEAVES NO TRACE. The turn runs on a THROWAWAY agent over a+//! container-deep CLONE of the root's history, in an arena that dies with the+//! call — the shape compact_note_glue.askModel already uses, and for the same+//! reason: send-time normalization mutates `messages` in place (normalization+//! of Responses history, capOversizedToolOutputs, #390's landing note), so only+//! a clone may be handed to it. `root.messages` is read once, to clone, and+//! written never.+//!+//! That single fact is what keeps it out of BOTH persistence paths, which is+//! worth spelling out because they are not the same path:+//! - the session file is a rewrite of `root.messages` (session.saveSessionTo);+//! - the append-only transcript (#441) is an OBSERVATION of `root.messages`,+//! taken inside session.queueSave (session_transcript.record). It is+//! append-only, so a line written by mistake could never be taken back.+//! Neither runs here, and neither could see the exchange if it did: the side+//! agent's messages live in an arena the root holds no pointer to, and its+//! `sub = true` makes `record` refuse it outright at the first line.+//!+//! NO TOOLS, GENUINELY. `Agent.request(null)` omits the `tools` field from the+//! body entirely rather than sending an empty array, for all three wire+//! formats — the same trick compaction and the title task use. `text_only` is+//! set too, so the agent stays tool-less if it is ever driven through+//! `runTurn` instead.+//!+//! IT IS STILL BILLED. The request goes through `Agent.request` like any+//! other, so recordUsage/recordCost bank it in `pricing.g_cost` — the tally the+//! `[usage]` footer, `/cost` and the telemetry summary all read. Not keeping an+//! exchange is not a reason to hide what it cost.+//!+//! SINGLE-SHOT, deliberately. The issue names multi-turn side threads a+//! possible v2; there is no side history here to continue.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const agent_compact = @import("agent_compact.zig");+const ansi = @import("ansi.zig");+const style = &ansi.style;+const textMessage = @import("messages.zig").textMessage;+const title = @import("title.zig");++/// Bounded reply. A side question wants an answer, not a report; the ceiling+/// also bounds what a `/btw` can cost when the model misreads the brief.+pub const output_limit: u32 = 1024;++/// Shown when `/btw` arrives with nothing to ask. Says what the command is for,+/// because an empty one is nearly always a half-typed line.+pub const usage_hint = "/btw <question> — ask one side question about this conversation; " +++ "it runs with no tools and is never added to the session";++/// Appended to the ROOT's own system prompt for this one call. The model keeps+/// its identity and its project context — the question is about the work in+/// front of it — and is told the two things that are only true here.+pub const side_note =+ \\[side question: the user has asked something ALONGSIDE the conversation+ \\above, not as the next step of it. Answer it from what is already in this+ \\context. You have NO tools on this turn: do not claim to have read, run or+ \\changed anything, and if the context does not contain the answer, say so+ \\plainly instead of guessing. Be brief. Neither the question nor your answer+ \\is added to the conversation, so do not treat this as work done, do not+ \\update any checklist, and do not refer back to it later.]+;++/// True for the `/btw` command line in any of its forms, including the empty+/// one — telling "not my command" apart from "my command, no question" is what+/// lets the refusal be a message rather than an "unknown command".+pub fn isCommand(line: []const u8) bool {+ return std.mem.eql(u8, line, "/btw") or std.mem.startsWith(u8, line, "/btw ");+}++/// The question in a `/btw` line, or null when there is none. Null covers both+/// "not a /btw line" and "/btw with nothing after it"; `isCommand` separates+/// them for the caller that has to answer differently.+pub fn questionFromLine(line: []const u8) ?[]const u8 {+ if (!isCommand(line)) return null;+ const question = std.mem.trim(u8, line["/btw".len..], " \t\r\n");+ return if (question.len == 0) null else question;+}++/// The throwaway agent the side question runs on, exposed so a test can inspect+/// the exact request this feature would send without making one.+///+/// The ROOT's provider, because the cloned history is in that wire format, and+/// the ROOT's system prompt, because the question is about the work in it.+/// `sub = true` keeps it off stdout and out of every root-only path — including+/// the transcript, which refuses a subagent outright. `message_mutation_arena`+/// points at the same throwaway arena so a mid-request history rewrite cannot+/// allocate out of the session's.+pub fn build(self: *Agent, arena: Allocator, question: []const u8) !Agent {+ var messages = try agent_compact.cloneJsonArray(arena, self.messages);+ try messages.append(try textMessage(arena, "user", question));+ return .{+ .gpa = self.gpa,+ .arena = arena,+ .io = self.io,+ .client = self.client,+ .provider = self.provider,+ .messages = messages,+ .sub = true, // never touches stdout, the root's state, or the transcript+ .text_only = true, // and could not be handed tools even through runTurn+ .label = "btw",+ .out = null,+ .tracer = self.tracer,+ .run_budget = self.run_budget,+ .reasoning = self.reasoning,+ .fast = self.fast,+ .stream_quiet = true,+ .call_kind = .judge, // an auxiliary, bounded, non-recursive call+ .responses_output_limit = output_limit,+ .message_mutation_arena = arena,+ .sys_override = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ self.systemPrompt(), side_note }),+ };+}++/// One tool-less request over a clone of the live history. The answer is duped+/// into `out_arena` (the caller's turn arena, not the session's) and everything+/// else — the clone, the reply tree, the side agent — dies with the scratch+/// arena before this returns. Null on any failure: a side question that could+/// not be answered must still leave the conversation exactly as it found it.+pub fn ask(self: *Agent, out_arena: Allocator, question: []const u8) ?[]const u8 {+ var arena_state = std.heap.ArenaAllocator.init(self.gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var agent = build(self, arena, question) catch return null;+ defer agent.tools_used.deinit(self.gpa);+ defer agent.closeCodexWs(); // its own socket + response-id anchor, gpa-owned+ const root = agent.request(null) catch return null;+ const text = std.mem.trim(u8, title.assistantText(self.provider.kind, root), " \t\r\n");+ if (text.len == 0) return null;+ return out_arena.dupe(u8, text) catch null;+}++/// The `/btw` slash command. Returns false when `line` is not one, so it can sit+/// in a tryHandle chain beside every other command.+pub fn command(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (!isCommand(line)) return false;+ const question = questionFromLine(line) orelse {+ try out.print("{s}\n", .{usage_hint});+ try out.flush();+ return true;+ };+ try out.print("{s}↳ btw ›{s} {s}\n", .{ style.accent, style.reset, question });+ try out.flush();+ const answer = ask(root, arena, question) orelse {+ try out.print("{s}side question failed — the conversation is unchanged{s}\n", .{ style.yellow, style.reset });+ try out.flush();+ return true;+ };+ try out.print("{s}\n{s}(side question — not added to this session){s}\n", .{ answer, style.dim, style.reset });+ try out.flush();+ return true;+}diff --git a/src/side_question_tests.zig b/src/side_question_tests.zignew file mode 100644index 00000000..b8b9a70e--- /dev/null+++ b/src/side_question_tests.zig@@ -0,0 +1,271 @@+//! side_question.zig's tests (#415). A separate file for the 600-line cap,+//! mirroring compact_note_glue_tests.zig, and hooked from test_hooks.zig —+//! side_question.zig itself is reached in production from commands_misc, but+//! nothing references THIS file, which is what would make its tests compile to+//! nothing and still report green (AGENTS.md).+//!+//! WHAT IS NOT COVERED, stated plainly: `ask` issues a real provider request,+//! which a unit test cannot drive. Everything up to and including the exact+//! bytes that request would put on the wire IS covered, through the same+//! `build` the production path calls; so is everything after it that could+//! touch the session. The refusal path is driven through the real `command`+//! entry point with `provider`/`client` undefined, so a pass there is itself+//! the proof that no call was attempted.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const Provider = @import("provider.zig").Provider;+const messages_mod = @import("messages.zig");+const pricing = @import("pricing.zig");+const session = @import("session.zig");+const session_transcript = @import("session_transcript.zig");+const session_writer = @import("session_writer.zig");+const side_question = @import("side_question.zig");++const question = "btw, what did that linker error actually mean?";++fn provider(kind: Provider.Kind) Provider {+ return .{+ .id = switch (kind) {+ .anthropic => "anthropic",+ .openai => "openai",+ .responses => "codex",+ },+ .kind = kind,+ .auth = .bearer,+ .url = "",+ .api_key = "",+ .model = "test-model",+ .context = 200_000,+ };+}++/// A root mid-conversation: two messages the side question must be able to see.+/// `client` stays undefined — nothing here may reach the network.+fn root(arena: Allocator, kind: Provider.Kind) !Agent {+ var msgs = std.json.Array.init(arena);+ try msgs.append(try messages_mod.textMessage(arena, "user", "build it"));+ try msgs.append(try messages_mod.textMessage(arena, "assistant", "undefined symbol _graff_main"));+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = provider(kind),+ .messages = msgs,+ .sub = false,+ .label = "root",+ .out = null,+ .session_name = "btw",+ .sys_normal = "ROOT-BASE",+ .sys_strict = "ROOT-BASE-STRICT",+ .tools_anthropic = "[{\"name\":\"bash\"}]",+ .tools_openai = "[{\"name\":\"bash\"}]",+ .tools_responses = "[{\"name\":\"bash\"}]",+ };+}++fn serialize(arena: Allocator, msgs: std.json.Array) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(Value{ .array = msgs });+ return aw.writer.buffered();+}++test "/btw (#415): the side request carries the live context and the question, with NO tools" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ // Every wire format, because "no tools" is written three times in buildBody+ // and a fourth caller getting one of them wrong is exactly how a `/btw`+ // would quietly grow the ability to edit files.+ for ([_]Provider.Kind{ .anthropic, .openai, .responses }) |kind| {+ var r = try root(arena, kind);+ var agent = try side_question.build(&r, arena, question);+ defer agent.tools_used.deinit(std.testing.allocator);+ const body = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(body);++ // The answer is produced FROM the existing context: the conversation so+ // far is in the request, with the question appended after it.+ try std.testing.expect(std.mem.indexOf(u8, body, "undefined symbol _graff_main") != null);+ const asked = std.mem.indexOf(u8, body, "what did that linker error") orelse+ return error.TestUnexpectedResult;+ try std.testing.expect(asked > std.mem.indexOf(u8, body, "undefined symbol _graff_main").?);++ // No toolset, and not an empty one either — the key is absent.+ try std.testing.expect(std.mem.indexOf(u8, body, "\"tools\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, body, "\"bash\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, body, "tool_choice") == null);+ try std.testing.expect(agent.text_only); // and runTurn could not add any++ // The root's own prompt, plus the note that says why this turn is odd.+ try std.testing.expect(std.mem.indexOf(u8, body, "ROOT-BASE") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "You have NO tools on this turn") != null);+ // It is a subagent for every root-only path, the transcript included.+ try std.testing.expect(agent.sub);+ }+}++test "/btw (#415): root.messages is byte-identical before and after, and the clone is deep" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var r = try root(arena, .anthropic);+ const before = try serialize(arena, r.messages);+ const before_len = r.messages.items.len;++ var agent = try side_question.build(&r, arena, question);+ defer agent.tools_used.deinit(std.testing.allocator);++ // Do to the clone everything a real request does to a history: append (the+ // question is already one; #390's landing note is another) and rewrite an+ // existing message in place, which is what capOversizedToolOutputs does.+ try agent.messages.append(try messages_mod.textMessage(arena, "assistant", "it means the entry point was renamed"));+ try agent.messages.items[1].object.put(arena, "content", .{ .string = "TRUNCATED BY THE SIDE REQUEST" });++ try std.testing.expectEqual(before_len, r.messages.items.len);+ try std.testing.expectEqualStrings(before, try serialize(arena, r.messages));+ // Not merely equal — the in-place rewrite above proves the clone does not+ // share the ObjectMaps, which a shallow array copy would.+ try std.testing.expect(std.mem.indexOf(u8, before, "undefined symbol _graff_main") != null);+}++test "/btw (#415): neither the session file nor the append-only transcript sees the exchange" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ // Both are per-PROCESS state; a test that reaches saveSessionTo resets them.+ session_writer.resetForTest();+ defer session_writer.resetForTest();+ session_transcript.resetForTest();+ defer session_transcript.resetForTest();+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();++ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ var r = try root(arena, .anthropic);+ r.client = &client;++ // The conversation as it stands, through the REAL save path — which is also+ // the only place the transcript ever observes a message (#441).+ try session.saveSessionTo(&r, arena, tmp.dir, "btw");+ session.flushSaves();+ const transcript_path = session_transcript.activePath(&r, arena) orelse+ return error.TestUnexpectedResult;+ const saved_before = try tmp.dir.readFileAlloc(io, ".graff/sessions/btw.session.json", gpa, .limited(64 * 1024));+ defer gpa.free(saved_before);+ const lines_before = try tmp.dir.readFileAlloc(io, transcript_path, gpa, .limited(64 * 1024));+ defer gpa.free(lines_before);+ const count_before = session_transcript.lineCount();+ const writes_before = session_writer.stats().writes;++ // Now the whole side exchange, in its own arena exactly as `ask` runs it:+ // the question goes in, the model's answer comes back, and the arena dies.+ {+ var side_arena = std.heap.ArenaAllocator.init(gpa);+ defer side_arena.deinit();+ const sa = side_arena.allocator();+ var agent = try side_question.build(&r, sa, question);+ defer agent.tools_used.deinit(gpa);+ try agent.messages.append(try messages_mod.textMessage(sa, "assistant", "SIDE ANSWER: the entry point was renamed"));+ try std.testing.expectEqual(@as(usize, 4), agent.messages.items.len); // it happened+ }++ // The next autosave is the moment either path could leak it. Neither does:+ // there is nothing new in `root.messages`, so #273 skips the write whole and+ // the transcript is never even consulted.+ try session.saveSessionTo(&r, arena, tmp.dir, "btw");+ session.flushSaves();++ // The transcript first, because it is the path that cannot be undone: it is+ // append-only, so a line written here stays written.+ const lines_after = try tmp.dir.readFileAlloc(io, transcript_path, gpa, .limited(64 * 1024));+ defer gpa.free(lines_after);+ try std.testing.expectEqualStrings(lines_before, lines_after);+ try std.testing.expectEqual(count_before, session_transcript.lineCount());++ const saved_after = try tmp.dir.readFileAlloc(io, ".graff/sessions/btw.session.json", gpa, .limited(64 * 1024));+ defer gpa.free(saved_after);+ try std.testing.expectEqualStrings(saved_before, saved_after);+ // And the save was not merely idempotent — #273 skipped the write whole,+ // because nothing in `root.messages` had changed for it to write.+ try std.testing.expectEqual(writes_before, session_writer.stats().writes);++ // And neither file ever held a word of it, which is the claim the byte+ // comparison alone would still allow if the FIRST save had leaked it.+ for ([_][]const u8{ saved_after, lines_after }) |text| {+ try std.testing.expect(std.mem.indexOf(u8, text, "linker error") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "SIDE ANSWER") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "side question") == null);+ }+ // The conversation itself is still there — this is a no-leak test, not a+ // test that the session file happens to be empty.+ try std.testing.expect(std.mem.indexOf(u8, lines_after, "undefined symbol _graff_main") != null);+}++test "/btw (#415): the side turn's usage lands in the tally the [usage] footer prints" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = std.testing.io;++ var r = try root(arena, .anthropic);+ var agent = try side_question.build(&r, arena, question);+ defer agent.tools_used.deinit(std.testing.allocator);++ // Not persisting the exchange is not a reason to hide what it cost: the+ // side agent banks through the same recordUsage every other request does,+ // into the same process-wide tally /cost and the [usage] footer render.+ const before = pricing.g_cost.snap(io);+ var usage: std.json.ObjectMap = .empty;+ try usage.put(arena, "input_tokens", .{ .integer = 1200 });+ try usage.put(arena, "output_tokens", .{ .integer = 40 });+ var response: std.json.ObjectMap = .empty;+ try response.put(arena, "usage", .{ .object = usage });+ agent.recordUsage(response, 4800);+ const after = pricing.g_cost.snap(io);++ try std.testing.expectEqual(before.api_calls + 1, after.api_calls);+ try std.testing.expectEqual(before.in_tokens + 1200, after.in_tokens);+ try std.testing.expectEqual(before.out_tokens + 40, after.out_tokens);+}++test "/btw (#415): an empty question is refused cleanly, without a model call" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ try std.testing.expectEqualStrings("why did that fail?", side_question.questionFromLine("/btw why did that fail?").?);+ try std.testing.expectEqualStrings("why?", side_question.questionFromLine("/btw why? ").?);+ try std.testing.expect(side_question.questionFromLine("/btw") == null);+ try std.testing.expect(side_question.questionFromLine("/btw ") == null);+ // Not a /btw line at all: the chain must fall through to the next handler.+ try std.testing.expect(!side_question.isCommand("/btwixt"));+ try std.testing.expect(!side_question.isCommand("btw, what?"));+ try std.testing.expect(side_question.isCommand("/btw"));++ var r = try root(arena, .anthropic);+ r.client = undefined;+ r.provider = undefined; // a request from here would fault+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();++ // Handled (so it is not reported as an unknown command) but not asked.+ try std.testing.expect(try side_question.command(&r, arena, "/btw ", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "/btw <question>") != null);+ try std.testing.expectEqual(@as(usize, 2), r.messages.items.len); // and nothing appended++ // A line that is not ours is declined without printing anything.+ aw.clearRetainingCapacity();+ try std.testing.expect(!try side_question.command(&r, arena, "/btwixt", &aw.writer));+ try std.testing.expectEqual(@as(usize, 0), aw.writer.buffered().len);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 906f62ab..12475182 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -79,6 +79,17 @@ const session_settings_tests = @import("session_settings_tests.zig");const session_transcript_tests = @import("session_transcript_tests.zig");+// #415: /btw's tests. side_question.zig is reached in production from+// commands_misc.tryHandle, but nothing references THIS file, so without the+// hook its whole suite compiles to nothing and reports green.+const side_question_tests = @import("side_question_tests.zig");++// #415: and json_controls.zig's own. It IS imported by mainloop.zig, which is+// not enough - mainloop is reached from main() rather than from the test root's+// analysis, so its imports' test blocks compile to nothing (eval-tier1 --only+// reach caught exactly this).+const json_controls = @import("json_controls.zig");+// #445: moved off commands_session.zig when the transcript-line reset needed// three lines there and the file was at exactly 600. The tests are unchanged.const commands_session_test = @import("commands_session_test.zig");@@ -234,4 +245,6 @@ test {_ = pipeline_score;_ = retry_hint;_ = agent_compact_summary_test;+ _ = side_question_tests;+ _ = json_controls;}