Skip to content

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

Python

Shell waits and todo_write replies stop costing turns (ADR 0233)

justrach5bf5ca585db2
diff --git a/build.zig b/build.zig
index b6519aab..33c02ae5 100644
--- a/build.zig
+++ b/build.zig
@@ -193,6 +193,9 @@ pub fn build(b: *std.Build) void {
const repl_background_wait_test = b.addSystemCommand(&.{ "python3", "scripts/test-repl-background-wait.py" });
repl_background_wait_test.addArtifactArg(exe);
test_step.dependOn(&repl_background_wait_test.step);
+ const shell_wait_todo_test = b.addSystemCommand(&.{ "python3", "scripts/test-shell-wait-and-todo-reply.py" });
+ shell_wait_todo_test.addArtifactArg(exe);
+ test_step.dependOn(&shell_wait_todo_test.step);
const workflow_isolation_test = b.addSystemCommand(&.{ "python3", "scripts/test-workflow-isolation.py" });
workflow_isolation_test.addArtifactArg(exe);
test_step.dependOn(&workflow_isolation_test.step);
diff --git a/docs/adr/0233-tool-results-the-model-already-has.md b/docs/adr/0233-tool-results-the-model-already-has.md
new file mode 100644
index 00000000..26355bd2
--- /dev/null
+++ b/docs/adr/0233-tool-results-the-model-already-has.md
@@ -0,0 +1,45 @@
+# 0233. No tool result the model already has
+
+Status: accepted 2026-10-02
+
+## Context
+
+Reading a week of session transcripts tool by tool showed two results that
+cost the model without telling it anything new.
+
+- **A one-second shell wait.** Some models send `timeout: 1000` on many shell
+ commands, as a habit of reading output after a second rather than as a
+ request to stop waiting. graff honored it as the foreground wait, so about
+ half of those commands (`git`, `gh`, `node`, `python3`) were parked after one
+ second. On an interactive surface a park ends the turn (ADR 0154) and the
+ result arrives on a later turn: the agent stopped mid-task for a command
+ that would have finished in two seconds, and the next request re-sent the
+ whole context.
+- **`todo_write` echoing the list.** The result was the full rendered
+ checklist, which the model had just sent as the call's arguments, and every
+ later request carried it again. The replies ran nearly twice the size of
+ the calls.
+
+## Decision
+
+- Interactive roots (TUI, line REPL, GUI, ACP) ignore a model's `timeout`:
+ the foreground wait is the 15s of ADR 0154. A park there yields the turn,
+ so a shorter wait only stops the agent sooner.
+- Unattended roots still honor a shorter `timeout`, because a parked job lets
+ the run keep working (ADR 0215), but not below 5s
+ (`exec_bash.min_model_wait_ms`). The shell tool's description says both.
+- `todo_write` answers the model with counts (`Todo list saved: N done, N in
+ progress, N pending.`), the items graff kept that the call left out
+ (finished items, open verification), and the existing notes about dropped or
+ kept work. The rendered list still goes to the UI through
+ `todo_list_updated`. A rejected write answers as before.
+
+## Consequences
+
+- A command that runs past 5s (unattended) or 15s (interactive) still parks;
+ `run_in_background` remains the way to start work that should not hold the
+ turn.
+- A model that wants its plan in front of it again calls `todo_read`.
+- `scripts/test-shell-wait-and-todo-reply.py` sends a two-second command with
+ `timeout: 1000` and a todo write through a scripted REPL and checks both
+ results; it fails on a build without this change.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c6f9d084..05060fee 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -257,6 +257,7 @@ record only when you need the evidence or the edge cases.
| [0228](0228-read-only-child-calls-declared-read-only-mcp-tools.md) | An MCP tool is a read when its server declares `readOnlyHint: true` (`mcp.Tool.read_only`). A read-only (informational) child may call those and inherits only those from its root; undeclared MCP tools stay refused. |
| [0229](0229-every-chatgpt-login-is-chatgpt-new.md) | The Codex client's login no longer works, so every ChatGPT login name (`chatgpt`, `codex`, `openai`, `gpt`, `oai`) and the model picker run the `chatgpt-new` sign-in, and `chatgpt-new` precedes `codex` in the provider table. The `codex` provider stays for an existing Codex CLI `auth.json`. Replaces ADR 0221's "Codex first". |
| [0231](0231-no-round-trip-the-model-does-not-need.md) | No call the task did not ask for: a named small MCP server (and subagents, when asked for) loads with the first request, with the slim-shape note; `write_file` refuses to replace an unread file unless `replace: true` and reports created/replaced and JSON validity; inherited child MCP tools are never deferred; a piped bracketed paste is one prompt; unwatched (`-p`, piped) sessions get no `ask_user` and no low-effort reasoning summaries. |
+| [0233](0233-tool-results-the-model-already-has.md) | No tool result the model already has: interactive roots ignore a model's shell `timeout` (the 15s park of ADR 0154 stands) and unattended roots floor it at 5s, so a `timeout: 1000` habit no longer parks quick commands and ends the turn; `todo_write` answers the model with counts and the items graff kept, not the list it just sent (the UI still gets the full list). |
## When to write one
diff --git a/scripts/test-shell-wait-and-todo-reply.py b/scripts/test-shell-wait-and-todo-reply.py
new file mode 100755
index 00000000..aa2b9f8b
--- /dev/null
+++ b/scripts/test-shell-wait-and-todo-reply.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Offline (ADR 0233): a scripted `graff repl` runs a two-second command that
+the model sent with `timeout: 1000`, then writes a todo list.
+
+- The command finishes in the foreground: a model's one-second wait is raised
+ to the 5s floor instead of parking the command after one second.
+- todo_write answers with counts, not the list the model just sent.
+"""
+import json
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / "scripts/eval"))
+from mock_model import ScriptedModel
+
+PROMPT = "Run the slow check, then plan the follow-up."
+MARKER = "slow-check-finished"
+TODOS = [
+ {"content": "inspect the slow check output", "status": "completed"},
+ {"content": "write the follow-up fix", "status": "in_progress"},
+ {"content": "verify the follow-up fix", "status": "pending"},
+]
+
+
+class Model(ScriptedModel):
+ def __init__(self):
+ super().__init__([], exhausted_text="All done.")
+ self.root_bodies = []
+
+ def next_reply(self, body):
+ with self._lock:
+ self.requests.append(body)
+ if PROMPT in json.dumps(body.get("messages", [])) and body.get("tools"):
+ self.root_bodies.append(body)
+ n = len(self.root_bodies)
+ if not body.get("tools"):
+ return {"text": "Short title"}
+ if n == 1:
+ return {"tool": "shell", "arguments": {"command": f"sleep 2; echo {MARKER}", "timeout": 1000}}
+ if n == 2:
+ return {"tool": "todo_write", "arguments": {"todos": TODOS}}
+ return {"text": "All done."}
+
+
+def tool_results(body):
+ return [m.get("content") for m in body.get("messages", []) if m.get("role") == "tool"]
+
+
+def main():
+ binary = (Path(sys.argv[1]) if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve()
+ model = Model()
+ port = model.start(0)
+ try:
+ with tempfile.TemporaryDirectory() as tmp:
+ home = Path(tmp) / "home"
+ work = Path(tmp) / "work"
+ home.mkdir()
+ work.mkdir()
+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY") and not k.startswith(("GRAFF_", "HARNESS_"))}
+ env.update(HOME=str(home), AI_GATEWAY_API_KEY="local", GRAFF_FLEET="off",
+ GRAFF_VERCEL_URL=f"http://127.0.0.1:{port}/v1/chat/completions",
+ GRAFF_NO_TELEMETRY="1", GRAFF_NO_SMOLIFY="1", GRAFF_BEHAVIOR_UPLOAD="off", NO_COLOR="1")
+ proc = subprocess.run([str(binary), "repl", "--yolo", "--old", "--model", "vercel"],
+ input=PROMPT + "\n", text=True, encoding="utf-8", errors="replace", capture_output=True,
+ cwd=work, env=env, timeout=120)
+ finally:
+ model.stop()
+ tail = f"\nstdout:\n{proc.stdout[-1500:]}\nstderr:\n{proc.stderr[-1500:]}"
+ assert len(model.root_bodies) >= 3, f"expected three root requests, got {len(model.root_bodies)}{tail}"
+ shell_out = tool_results(model.root_bodies[1])[-1]
+ assert MARKER in shell_out, f"the two-second command did not finish in the foreground: {shell_out!r}{tail}"
+ assert "foreground wait" not in shell_out, f"the command was parked: {shell_out!r}"
+ todo_out = tool_results(model.root_bodies[2])[-1]
+ assert todo_out.startswith("Todo list saved: 1 done, 1 in progress, 1 pending."), f"todo_write reply: {todo_out!r}"
+ assert not any(t["content"] in todo_out for t in TODOS), f"todo_write echoed the list back: {todo_out!r}"
+ print("PASS a model's 1s shell wait is raised to the floor; todo_write replies with counts (ADR 0233)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 3872afb6..11a36d4f 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -345,7 +345,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
// no usable items is rejected untouched (#318). goal_todo owns the rule.
const r = try goal_todo.applyTodoWrite(self, if (tools_mod.json_args.object(call.input)) |o| o.get("todos") else null);
if (!self.sub and !r.rejected) engine_sink.forAgent(self).emit(self.io, .{ .todo_list_updated = .{ .text = r.text } });
- return .{ .text = r.text, .is_error = r.rejected };
+ return .{ .text = r.reply(), .is_error = r.rejected }; // ADR 0233: the UI got the full list above
}
if (std.mem.eql(u8, call.name, "clock_sleep")) {
const parsed = parseClockSleepMs(call.input) catch return .{
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index e8197fab..5c06f676 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -2,8 +2,9 @@
//! auto-background path (#620) has room without growing exec.zig.
//!
//! Root foreground: spawn a job, wait up to 120s unattended (interactive
-//! REPL/TUI/GUI: 15s, ADR 0154). A shorter `timeout` may promote earlier; a
-//! larger one cannot extend the wait. Then promote rather than kill — the
+//! REPL/TUI/GUI: 15s, ADR 0154). Unattended, a shorter `timeout` may promote
+//! earlier, not below 5s; interactive surfaces ignore it (ADR 0233). A larger
+//! one cannot extend the wait. Then promote rather than kill — the
//! process keeps running and the model gets a job id. Interactive parked
//! jobs yield the parent like subagents. Subagents stay on the #93
//! kill-at-120s path (no TTY, no /jobs UI).
@@ -119,13 +120,21 @@ fn rootWaitMs(input: Value) u64 {
return rootWaitMsFor(input, false);
}
+/// ADR 0233: the shortest foreground wait a model's `timeout` may ask for.
+/// Some models send `timeout: 1000` as a read-output-after habit; honored,
+/// it parked half of those commands (git, gh, node) after one second.
+pub const min_model_wait_ms: u64 = 5 * 1000;
+
fn rootWaitMsFor(input: Value, interactive: bool) u64 {
const bound = defaultRootWaitMs(interactive);
+ // An interactive park ends the turn (ADR 0154), so a shorter wait only
+ // stops the agent sooner; the 15s bound stands (ADR 0233).
+ if (interactive) return bound;
const t = intField(input, "timeout") orelse return bound;
if (t <= 0) return bound;
// #850: timeout may shorten the foreground wait; it must not recreate the
// #620 hang by stretching it toward the 10h job-wait cap.
- return @min(@as(u64, @intCast(t)), bound);
+ return std.math.clamp(@as(u64, @intCast(t)), @min(min_model_wait_ms, bound), bound);
}
test "rootWaitMs: omitted/zero use 120s; a shorter timeout may promote earlier" {
@@ -201,6 +210,17 @@ test "rootWaitMs: lean unattended oneshot defaults to 15s; shorter timeout still
try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
}
+test "ADR 0233: a one-second timeout waits 5s unattended and the full 15s interactive" {
+ const one_second = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":1000}", .{});
+ defer one_second.deinit();
+ try std.testing.expectEqual(min_model_wait_ms, rootWaitMs(one_second.value));
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMsFor(one_second.value, true));
+ const ten_seconds = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":10000}", .{});
+ defer ten_seconds.deinit();
+ try std.testing.expectEqual(@as(u64, 10_000), rootWaitMs(ten_seconds.value));
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMsFor(ten_seconds.value, true));
+}
+
test "rootWaitMs: interactive REPL parks at 15s (ADR 0154)" {
const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
defer empty.deinit();
diff --git a/src/goal_todo.zig b/src/goal_todo.zig
index f64603db..09cc00f9 100644
--- a/src/goal_todo.zig
+++ b/src/goal_todo.zig
@@ -95,7 +95,19 @@ pub fn retireFinishedForNewAsk(root: *Agent) usize {
return n;
}
-pub const WriteResult = struct { text: []const u8, rejected: bool = false, dropped_open: usize = 0, kept_verify: usize = 0 };
+pub const WriteResult = struct {
+ /// The rendered list, for the UI (`todo_list_updated`).
+ text: []const u8,
+ /// What the model reads back: counts and only what graff kept (ADR 0233).
+ model_text: []const u8 = "",
+ rejected: bool = false,
+ dropped_open: usize = 0,
+ kept_verify: usize = 0,
+
+ pub fn reply(self: WriteResult) []const u8 {
+ return if (self.model_text.len > 0) self.model_text else self.text;
+ }
+};
/// The whole todo_write handler: replace the current epoch's checklist with
/// `list` (the tool call's "todos" argument, already parsed), preserving
@@ -130,14 +142,17 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {
}
}
const rendered = goal_state.renderTodos(root, epoch);
- if (cleared.dropped_open == 0 and cleared.kept_verify == 0) return .{ .text = rendered };
+ const reply = try @import("todo_reply.zig").text(root.arena, root.todos.items, epoch, incoming.items, cleared.dropped_open, cleared.kept_verify);
+ if (cleared.dropped_open == 0 and cleared.kept_verify == 0) return .{ .text = rendered, .model_text = reply };
if (cleared.kept_verify > 0 and cleared.dropped_open == 0)
return .{
.text = try std.fmt.allocPrint(root.arena, "{s}\n({d} verification item(s) you left out were kept as unresolved acceptance requirements)", .{ rendered, cleared.kept_verify }),
+ .model_text = reply,
.kept_verify = cleared.kept_verify,
};
return .{
.text = try std.fmt.allocPrint(root.arena, "{s}\n({d} open item(s) you left out were dropped; re-list one to keep it)", .{ rendered, cleared.dropped_open }),
+ .model_text = reply,
.dropped_open = cleared.dropped_open,
.kept_verify = cleared.kept_verify,
};
@@ -215,6 +230,25 @@ test "a replace keeps omitted completed items and still drops omitted open ones"
try std.testing.expect(goal_state.checklistFinished(&root));
}
+test "ADR 0233: the model reads counts and kept items; the UI keeps the rendered list" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = todoRoot(ar);
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1 };
+ _ = try applyTodoWrite(&root, try todosArg(ar,
+ \\{"todos":[{"content":"write the helper","status":"completed"},
+ \\ {"content":"wire it up","status":"in_progress"}]}
+ ));
+ const r = try applyTodoWrite(&root, try todosArg(ar,
+ \\{"todos":[{"content":"wire it up","status":"completed"}]}
+ ));
+ try std.testing.expectEqualStrings("[x] write the helper\n[x] wire it up", r.text);
+ try std.testing.expectEqualStrings("Todo list saved: 2 done, 0 in progress, 0 pending.\nKept from before (not in your list):\n[x] write the helper", r.reply());
+ const rejected = try applyTodoWrite(&root, try todosArg(ar, "{\"todos\":[]}"));
+ try std.testing.expectEqualStrings(rejected.text, rejected.reply());
+}
+
test "an incoming item with the same content replaces the preserved one, never duplicates it" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/shell_tool.zig b/src/shell_tool.zig
index 4b4a91a9..f2414d49 100644
--- a/src/shell_tool.zig
+++ b/src/shell_tool.zig
@@ -21,9 +21,9 @@ const jobs = @import("jobs.zig");
const exec_bash = @import("exec_bash.zig");
pub const tool_name = "shell";
-pub const tool_desc = "Run a shell command via /bin/sh -c in the current working directory, read a background job, or stop one. action=run (default when command is set) returns stdout/stderr/exit. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands still running after 120s (lean -p: 15s, or a shorter timeout ms) move to the background and return a job id. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. action=output wait_ms>0 blocks until exit (up to 10h) for a finite job; a persistent server snapshots immediately (wait_ms is ignored) and stays on /jobs. action=kill stops it. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity; the user pins a long-lived server with /jobs keep. bash/bash_output/bash_kill still dispatch. Not a PTY: you cannot type into the process. Type in the composer to steer the turn.";
+pub const tool_desc = "Run a shell command via /bin/sh -c in the current working directory, read a background job, or stop one. action=run (default when command is set) returns stdout/stderr/exit. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands still running after 120s (interactive sessions and lean -p: 15s) move to the background and return a job id. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. action=output wait_ms>0 blocks until exit (up to 10h) for a finite job; a persistent server snapshots immediately (wait_ms is ignored) and stays on /jobs. action=kill stops it. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity; the user pins a long-lived server with /jobs keep. bash/bash_output/bash_kill still dispatch. Not a PTY: you cannot type into the process. Type in the composer to steer the turn.";
pub const tool_schema =
- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["run", "output", "kill"], "description": "run a command, read a job, or stop a job. Default run when command is set."}, "command": {"type": "string", "description": "Shell command to execute (action=run)"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background. A shorter value promotes earlier; a larger value cannot extend past the 120s (lean -p: 15s) bound. 0 uses the default. Ignored when run_in_background is true. A persistent server's action=output is a snapshot, not wait-until-exit."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false). Do not poll it."}, "id": {"type": "integer", "description": "Job id for action=output or kill"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. Finite jobs: >0 waits until exit (10h cap). Persistent servers: snapshot now; wait_ms is ignored. Do not poll."}}}
+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["run", "output", "kill"], "description": "run a command, read a job, or stop a job. Default run when command is set."}, "command": {"type": "string", "description": "Shell command to execute (action=run)"}, "timeout": {"type": "integer", "description": "Unattended runs only: foreground wait in milliseconds before auto-background. A shorter value promotes earlier, not below 5000; a larger value cannot extend past the 120s (lean -p: 15s) bound. Interactive sessions always wait 15s. 0 uses the default. Ignored when run_in_background is true. A persistent server's action=output is a snapshot, not wait-until-exit."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false). Do not poll it."}, "id": {"type": "integer", "description": "Job id for action=output or kill"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. Finite jobs: >0 waits until exit (10h cap). Persistent servers: snapshot now; wait_ms is ignored. Do not poll."}}}
;
pub const Action = enum { run, output, kill };
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 45585fbd..be0d5e3e 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -404,4 +404,5 @@ test {
_ = @import("output_elide.zig"); // #1271: over-cap output keeps head and tail
_ = @import("graff_dir.zig"); // #1273: .graff/.gitignore keeps run state out of git
_ = @import("additional_tools.zig"); // ADR 0221: loaded tools as additional_tools items on the ChatGPT plan route
+ _ = @import("todo_reply.zig"); // ADR 0233: todo_write replies with counts, not the list
}
diff --git a/src/todo_reply.zig b/src/todo_reply.zig
new file mode 100644
index 00000000..b62b1bec
--- /dev/null
+++ b/src/todo_reply.zig
@@ -0,0 +1,86 @@
+//! What todo_write tells the model (ADR 0233). The model just sent the list,
+//! so echoing it back cost its tokens a second time, then again on every
+//! later request that carried the result; the replies ran nearly twice the
+//! size of the calls. The reply is the counts, any item
+//! graff kept that the call left out (a finished item, open verification),
+//! and the notes about dropped or kept work. The full list still goes to the
+//! UI through `todo_list_updated`.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const TodoItem = @import("agent.zig").TodoItem;
+
+pub fn text(arena: Allocator, todos: []const TodoItem, epoch: u64, incoming: []const []const u8, dropped_open: usize, kept_verify: usize) ![]const u8 {
+ var done: usize = 0;
+ var doing: usize = 0;
+ var open: usize = 0;
+ for (todos) |t| {
+ if (t.epoch != epoch or t.retired) continue;
+ if (std.mem.eql(u8, t.status, "completed")) {
+ done += 1;
+ } else if (std.mem.eql(u8, t.status, "in_progress")) {
+ doing += 1;
+ } else {
+ open += 1;
+ }
+ }
+ var aw: std.Io.Writer.Allocating = .init(arena);
+ const w = &aw.writer;
+ try w.print("Todo list saved: {d} done, {d} in progress, {d} pending.", .{ done, doing, open });
+ var kept_header = false;
+ for (todos) |t| {
+ if (t.epoch != epoch or t.retired or mentions(incoming, t.content)) continue;
+ if (!kept_header) try w.writeAll("\nKept from before (not in your list):");
+ kept_header = true;
+ try w.print("\n{s} {s}", .{ mark(t.status), t.content });
+ }
+ if (kept_verify > 0) try w.print("\n({d} verification item(s) you left out were kept as unresolved acceptance requirements)", .{kept_verify});
+ if (dropped_open > 0) try w.print("\n({d} open item(s) you left out were dropped; re-list one to keep it)", .{dropped_open});
+ return aw.writer.buffered();
+}
+
+fn mark(status: []const u8) []const u8 {
+ if (std.mem.eql(u8, status, "completed")) return "[x]";
+ if (std.mem.eql(u8, status, "in_progress")) return "[~]";
+ return "[ ]";
+}
+
+fn mentions(contents: []const []const u8, content: []const u8) bool {
+ for (contents) |c| if (std.mem.eql(u8, c, content)) return true;
+ return false;
+}
+
+test "todo_write reply: counts only when graff kept nothing the call left out" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const todos = [_]TodoItem{
+ .{ .content = "write the helper", .status = "completed", .epoch = 1 },
+ .{ .content = "wire it up", .status = "in_progress", .epoch = 1 },
+ .{ .content = "ship it", .status = "pending", .epoch = 1 },
+ .{ .content = "another goal's item", .status = "pending", .epoch = 2 },
+ };
+ const sent = [_][]const u8{ "write the helper", "wire it up", "ship it" };
+ const got = try text(arena_state.allocator(), &todos, 1, &sent, 0, 0);
+ try std.testing.expectEqualStrings("Todo list saved: 1 done, 1 in progress, 1 pending.", got);
+}
+
+test "todo_write reply: names what graff kept and what the call dropped" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const todos = [_]TodoItem{
+ .{ .content = "write the helper", .status = "completed", .epoch = 1 },
+ .{ .content = "verify the fix", .status = "pending", .epoch = 1 },
+ .{ .content = "wire it up", .status = "in_progress", .epoch = 1 },
+ .{ .content = "retired", .status = "completed", .epoch = 1, .retired = true },
+ };
+ const sent = [_][]const u8{"wire it up"};
+ const got = try text(arena_state.allocator(), &todos, 1, &sent, 2, 1);
+ try std.testing.expectEqualStrings(
+ \\Todo list saved: 1 done, 1 in progress, 1 pending.
+ \\Kept from before (not in your list):
+ \\[x] write the helper
+ \\[ ] verify the fix
+ \\(1 verification item(s) you left out were kept as unresolved acceptance requirements)
+ \\(2 open item(s) you left out were dropped; re-list one to keep it)
+ , got);
+}