Skip to content

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

Python

fix(goal): a compaction must not make the model forget its checklist

Rach Pradhan2acb0edbd7bd
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index 53826ab7..6b34eccc 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -12,6 +12,7 @@ const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
const prompts = @import("prompts.zig");
const compact_instruction = prompts.compact_instruction;
+const goal_flow = @import("goal_flow.zig");
const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
@@ -151,15 +152,7 @@ pub fn compact(self: *Agent) anyerror!usize {
}
var fresh = std.json.Array.init(self.arena);
- const handoff = try std.fmt.allocPrint(self.arena,
- \\Context: the earlier conversation was compacted to save space.
- \\Summary of the earlier work:
- \\
- \\{s}
- \\
- \\Continue assisting the user based on this summary.
- , .{summary});
- try fresh.append(try textMessage(self.arena, "user", handoff));
+ try fresh.append(try textMessage(self.arena, "user", try handoffMessage(self, summary)));
// Preserve a valid recent suffix verbatim (up to ~8k estimated tokens),
// including its user boundary and paired tool calls/results.
for (recent_messages) |message| try fresh.append(message);
@@ -172,6 +165,27 @@ pub fn compact(self: *Agent) anyerror!usize {
return summary.len;
}
+/// The message a successful compaction installs as the new history head: the
+/// model's handoff summary, plus the harness-kept standing state when a goal is
+/// live (#318). That state is HISTORY, not steering, for two reasons: a
+/// mid-turn compaction (agent.zig's in-loop call) must reach the tool loop
+/// immediately rather than at the next turn boundary, and feeding it through
+/// goalSteeringNote would move that note's diff-gate fingerprint on every
+/// compaction, defeating the suppression the gate exists for. With no live goal
+/// the text is byte-identical to what it always was.
+pub fn handoffMessage(self: *Agent, summary: []const u8) ![]const u8 {
+ const base = try std.fmt.allocPrint(self.arena,
+ \\Context: the earlier conversation was compacted to save space.
+ \\Summary of the earlier work:
+ \\
+ \\{s}
+ \\
+ \\Continue assisting the user based on this summary.
+ , .{summary});
+ const standing = (try goal_flow.compactionSnapshot(self.arena, self)) orelse return base;
+ return std.fmt.allocPrint(self.arena, "{s}\n\n{s}", .{ base, standing });
+}
+
/// Clone JSON arrays/objects while borrowing immutable leaf strings. Send-time
/// normalization replaces Value slots rather than mutating string bytes, so
/// separate containers are sufficient to isolate a compaction request without
@@ -392,6 +406,12 @@ pub fn emergencyTrim(self: *Agent) usize {
for (self.messages.items[cut..]) |m| fresh.append(m) catch return 0;
self.messages = fresh;
self.goal_note_fp = 0; // trimmed history may have carried the goal note (#318)
+ // No synthetic message exists here to hang the standing state on (unlike
+ // compact()'s handoff), so it rides the next turn's one-shot slot. Only
+ // when that slot is free: a queued /goal replace|clear note is the USER's
+ // instruction and outranks the harness restating itself (#318).
+ if (self.pending_goal_note == null)
+ self.pending_goal_note = goal_flow.compactionSnapshot(self.arena, self) catch null;
const after_tokens = self.fullInputEstimateTokens();
accountForReclaimedTokens(self, before_tokens -| after_tokens);
return cut;
diff --git a/src/agent_compact_test.zig b/src/agent_compact_test.zig
index 9e4f0490..8d99174a 100644
--- a/src/agent_compact_test.zig
+++ b/src/agent_compact_test.zig
@@ -19,6 +19,7 @@ const recentContextStart = compact.recentContextStart;
const cleanUserTurn = compact.cleanUserTurn;
const emergencyCutIndex = compact.emergencyCutIndex;
const emergencyTrim = compact.emergencyTrim;
+const handoffMessage = compact.handoffMessage;
test "compaction accepts only complete provider terminal states" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
@@ -398,6 +399,11 @@ test "emergencyTrim preserves the authoritative meter after a partial cut" {
agent.sys_normal = "";
agent.sys_strict = "";
agent.tools_responses = "";
+ // emergencyTrim now re-queues the standing goal state (#318), so the fields
+ // that decision reads have to be real even in the no-goal case.
+ agent.review_mode = false;
+ agent.goal = null;
+ agent.pending_goal_note = null;
const before = agent.fullInputEstimateTokens();
const before_request = agent.fullRequestEstimateTokens();
@@ -426,3 +432,104 @@ test "emergencyCutIndex: skips a tool_result user message at the midpoint" {
try items.append(try textMessage(a, "assistant", "x")); // 7
try std.testing.expectEqual(@as(?usize, 6), emergencyCutIndex(items.items));
}
+
+test "a compaction handoff carries the live checklist across the summary (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent: Agent = undefined;
+ agent.arena = a;
+ agent.sub = false;
+ agent.review_mode = false;
+ agent.todos = .empty;
+ agent.goal = .{ .objective = "ship the epoch fix", .epoch = 2 };
+ try agent.todos.append(a, .{ .content = "write the helper", .status = "completed", .epoch = 2 });
+ try agent.todos.append(a, .{ .content = "wire it into compact", .status = "completed", .epoch = 2 });
+ try agent.todos.append(a, .{ .content = "test it", .status = "pending", .epoch = 2 });
+ try agent.todos.append(a, .{ .content = "parked by an older goal", .status = "pending", .epoch = 1 });
+
+ const handoff = try handoffMessage(&agent, "the model summarized the earlier work");
+ // The summary and its framing are unchanged...
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "the model summarized the earlier work") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "Continue assisting the user based on this summary.") != null);
+ // ...and the state a summary cannot be trusted to carry rides with it. The
+ // last todo_write result is not in the ~8k suffix after a long tool loop,
+ // and the summarizer may never have seen the item statuses at all.
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "ship the epoch fix") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "Checklist (1 open)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "[x] write the helper") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "[x] wire it into compact") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "[ ] test it") != null);
+ // The REPLACES warning is the whole point: without it the model rewrote the
+ // list from the summary's prose, todo_write's clearEpoch dropped the three
+ // completed items, allDone flipped false, and the goal never completed -
+ // durably, because the autosave persisted the damaged list (#318).
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "todo_write REPLACES") != null);
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "todo_read") != null);
+ // Parked work is never resurrected into the handoff.
+ try std.testing.expect(std.mem.indexOf(u8, handoff, "parked by an older goal") == null);
+
+ // A subagent shares the Agent struct but not the goal, so its handoff is
+ // byte-identical to the pre-#318 text - as is a session with no goal.
+ agent.sub = true;
+ const plain = try handoffMessage(&agent, "the model summarized the earlier work");
+ try std.testing.expect(std.mem.indexOf(u8, plain, "standing state") == null);
+ try std.testing.expect(std.mem.endsWith(u8, plain, "Continue assisting the user based on this summary."));
+ agent.sub = false;
+ agent.goal = null;
+ try std.testing.expectEqualStrings(plain, try handoffMessage(&agent, "the model summarized the earlier work"));
+}
+
+test "an emergency trim re-queues the standing state, never over a user note (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const roles = [_][]const u8{ "user", "assistant", "user", "assistant", "user", "assistant", "user", "assistant" };
+
+ var agent: Agent = undefined;
+ agent.arena = a;
+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 270_000 };
+ agent.last_context_tokens = 200_000;
+ agent.context_local_tokens = 200_000;
+ agent.sub = false;
+ agent.review_mode = false;
+ agent.strict = false;
+ agent.sys_normal = "";
+ agent.sys_strict = "";
+ agent.tools_responses = "";
+ agent.todos = .empty;
+ agent.goal = .{ .objective = "keep the tree green", .epoch = 1 };
+ agent.pending_goal_note = null;
+ try agent.todos.append(a, .{ .content = "audit the loop", .status = "in_progress", .epoch = 1 });
+
+ // emergencyTrim has no synthetic message of its own to append the standing
+ // state to (compact() does), so it hands it to the one-shot slot instead -
+ // otherwise a mid-turn trim leaves the rest of the turn checklist-blind.
+ var items = std.json.Array.init(a);
+ for (roles) |role| try items.append(try textMessage(a, role, "a retained message with some measurable bytes"));
+ agent.messages = items;
+ try std.testing.expectEqual(@as(usize, 4), emergencyTrim(&agent));
+ try std.testing.expect(agent.pending_goal_note != null);
+ try std.testing.expect(std.mem.indexOf(u8, agent.pending_goal_note.?, "keep the tree green") != null);
+ try std.testing.expect(std.mem.indexOf(u8, agent.pending_goal_note.?, "[~] audit the loop") != null);
+ try std.testing.expectEqual(@as(u64, 0), agent.goal_note_fp);
+
+ // A queued supersession note (/goal replace|clear) always wins: it is the
+ // user changing the objective, and the standing state is only the harness
+ // restating itself. Clobbering it lost "stop working the old objective".
+ var again = std.json.Array.init(a);
+ for (roles) |role| try again.append(try textMessage(a, role, "a retained message with some measurable bytes"));
+ agent.messages = again;
+ agent.pending_goal_note = "[goal update: the standing goal above supersedes the previous goal]";
+ _ = emergencyTrim(&agent);
+ try std.testing.expectEqualStrings("[goal update: the standing goal above supersedes the previous goal]", agent.pending_goal_note.?);
+
+ // And with no live goal there is nothing to queue at all.
+ var third = std.json.Array.init(a);
+ for (roles) |role| try third.append(try textMessage(a, role, "a retained message with some measurable bytes"));
+ agent.messages = third;
+ agent.goal = null;
+ agent.pending_goal_note = null;
+ _ = emergencyTrim(&agent);
+ try std.testing.expect(agent.pending_goal_note == null);
+}
diff --git a/src/goal_flow.zig b/src/goal_flow.zig
index 32de98fb..80f0497b 100644
--- a/src/goal_flow.zig
+++ b/src/goal_flow.zig
@@ -10,6 +10,7 @@ const Allocator = std.mem.Allocator;
const agent_mod = @import("agent.zig");
const goal_state = @import("goal_state.zig");
const repl_glue = @import("repl_glue.zig");
+const utf8Prefix = @import("util.zig").utf8Prefix;
const Agent = agent_mod.Agent;
const TodoItem = agent_mod.TodoItem;
@@ -31,6 +32,45 @@ pub fn standingGoalFromFlag(objective: []const u8, todos: []const TodoItem, now_
};
}
+/// The checklist render carried into a compaction handoff is capped here: a
+/// pathological 200-item list must never eat the very context the compaction
+/// was run to reclaim. Over the cap the render is cut at a line boundary and
+/// the model is pointed at todo_read for the rest.
+pub const snapshot_render_cap: usize = 2_000;
+
+/// The standing state a compaction handoff has to carry across the summary
+/// boundary (#318). compact() rebuilds history as [handoff summary] + an ~8k
+/// suffix, so the last todo_write result - the ONLY place the live checklist
+/// ever reaches the model - is usually gone, and the summarizer may not have
+/// seen the item statuses either (trimOldestToolOutputs blanks old outputs
+/// before the summary request). The model then rewrote the list from prose,
+/// todo_write REPLACED the epoch, three already-completed items came back as
+/// pending, allDone flipped false, and the goal could never finish - durably,
+/// because the autosave persisted the damaged list. So the harness restates
+/// the list itself, once, as part of the new history.
+/// Returns null unless a root, non-review agent has an ACTIVE goal, which also
+/// excludes subagents and /review turns: they share the Agent struct but not
+/// the goal. Allocates from `arena`, which MUST outlive compact()'s temporary
+/// compaction arena - the text goes into the history that survives it.
+pub fn compactionSnapshot(arena: Allocator, root: *Agent) !?[]const u8 {
+ if (!goal_state.goalActive(root)) return null;
+ const objective = root.goal.?.objective;
+ const rendered = goal_state.renderCurrent(root);
+ if (rendered.len == 0)
+ return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives compaction): goal: {s}. No checklist has been written for it yet - plan the work with todo_write, and read the list back with todo_read at any time.]", .{objective});
+ const open = goal_state.openCount(root.todos.items, goal_state.currentEpoch(root.goal));
+ return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives compaction): goal: {s}. Checklist ({d} open):\n{s}\nThis list is live harness state, read it back with todo_read at any time. todo_write REPLACES the current goal's whole list, so include already-completed items when rewriting.]", .{ objective, open, try capRender(arena, rendered) });
+}
+
+/// Cut an oversized checklist render at a line boundary (never mid-item, never
+/// mid-codepoint) and say so, rather than pasting it whole.
+fn capRender(arena: Allocator, rendered: []const u8) ![]const u8 {
+ if (rendered.len <= snapshot_render_cap) return rendered;
+ const head = utf8Prefix(rendered, snapshot_render_cap);
+ const cut = std.mem.lastIndexOfScalar(u8, head, '\n') orelse head.len;
+ return std.fmt.allocPrint(arena, "{s}\n[checklist truncated for the handoff - call todo_read for the full list]", .{rendered[0..cut]});
+}
+
/// A root agent in the shape the goal helpers read; no live turn behind it.
fn flowRoot(arena: Allocator) Agent {
var root: Agent = undefined;
@@ -191,3 +231,87 @@ test "a cleared goal's OPEN items never become the next goal's work (#318)" {
try std.testing.expect(std.mem.indexOf(u8, refusal.?, "open checklist item") == null);
try std.testing.expectEqualStrings("", goal_state.renderCurrent(&root)); // B never renders A's list
}
+
+test "compactionSnapshot: no live goal, no checklist, and a capped render (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = flowRoot(ar);
+
+ // No goal: nothing to restate, and the handoff stays byte-identical.
+ try std.testing.expect((try compactionSnapshot(ar, &root)) == null);
+
+ // A goal that has not planned yet gets the list-free variant - never the
+ // "(no todos)" placeholder, which reads as a checklist that exists and is
+ // empty rather than one the model still has to write.
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1 };
+ const bare = (try compactionSnapshot(ar, &root)).?;
+ try std.testing.expect(std.mem.indexOf(u8, bare, "ship phase 2") != null);
+ try std.testing.expect(std.mem.indexOf(u8, bare, "Checklist (") == null);
+ try std.testing.expect(std.mem.indexOf(u8, bare, "(no todos)") == null);
+
+ // Only an ACTIVE root goal is restated: a paused goal is not steering, and
+ // a review turn or subagent shares the Agent struct but not the objective.
+ root.goal.?.status = .paused;
+ try std.testing.expect((try compactionSnapshot(ar, &root)) == null);
+ root.goal.?.status = .active;
+ root.review_mode = true;
+ try std.testing.expect((try compactionSnapshot(ar, &root)) == null);
+ root.review_mode = false;
+ root.sub = true;
+ try std.testing.expect((try compactionSnapshot(ar, &root)) == null);
+ root.sub = false;
+
+ // Parked work never re-enters the handoff, and the open count is the
+ // current epoch's.
+ try root.todos.append(ar, .{ .content = "parked by an older goal", .status = "pending", .epoch = 0 });
+ try root.todos.append(ar, .{ .content = "write the helper", .status = "completed", .epoch = 1 });
+ try root.todos.append(ar, .{ .content = "test it", .status = "pending", .epoch = 1 });
+ const snap = (try compactionSnapshot(ar, &root)).?;
+ try std.testing.expect(std.mem.indexOf(u8, snap, "Checklist (1 open)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, snap, "[x] write the helper") != null);
+ try std.testing.expect(std.mem.indexOf(u8, snap, "[ ] test it") != null);
+ try std.testing.expect(std.mem.indexOf(u8, snap, "parked by an older goal") == null);
+ try std.testing.expect(std.mem.indexOf(u8, snap, "todo_write REPLACES") != null);
+
+ // A pathological list is cut at a line boundary instead of pasted whole:
+ // the restatement must not undo the compaction it rides on.
+ var i: usize = 0;
+ while (i < 400) : (i += 1)
+ try root.todos.append(ar, .{ .content = "a checklist item with some measurable length", .status = "pending", .epoch = 1 });
+ const capped = (try compactionSnapshot(ar, &root)).?;
+ try std.testing.expect(capped.len < snapshot_render_cap + 600);
+ try std.testing.expect(std.mem.indexOf(u8, capped, "checklist truncated") != null);
+ try std.testing.expect(std.mem.indexOf(u8, capped, "Checklist (401 open)") != null);
+ try std.testing.expect(std.mem.endsWith(u8, capped, "when rewriting.]")); // the REPLACES warning survives the cut
+}
+
+test "a compaction does not move the goal note's diff-gate fingerprint (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = flowRoot(ar);
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1 };
+ try root.todos.append(ar, .{ .content = "write the test", .status = "pending", .epoch = 1 });
+
+ // The restatement is HISTORY (compact() appends it to the handoff message),
+ // never steering. Routing it through goalSteeringNote would change that
+ // note's text on the turn after every compaction, re-fingerprinting the
+ // diff-gate whose entire job is to stop the checklist being re-pasted.
+ const before = try repl_glue.goalSteeringNote(ar, root.goal);
+ const snap = (try compactionSnapshot(ar, &root)).?;
+ root.goal_note_fp = 0; // the reset compact()/emergencyTrim really do perform
+ const after = try repl_glue.goalSteeringNote(ar, root.goal);
+ try std.testing.expectEqualStrings(before, after);
+ try std.testing.expect(std.mem.indexOf(u8, after, "write the test") == null); // the note still embeds no checklist
+ try std.testing.expect(std.mem.indexOf(u8, snap, "[ ] write the test") != null); // the snapshot is where it lives
+
+ // Both note variants now point at todo_read and warn that a todo_write
+ // REPLACES the list: rewriting it from a summary is exactly how the three
+ // completed items were lost after every compaction (#318).
+ const standing = try repl_glue.goalSteeringNote(ar, .{ .objective = "keep the tree green", .standing = true });
+ for ([_][]const u8{ after, standing }) |n| {
+ try std.testing.expect(std.mem.indexOf(u8, n, "todo_read") != null);
+ try std.testing.expect(std.mem.indexOf(u8, n, "REPLACES") != null);
+ }
+}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 4bdd1ed0..c5fdc470 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -298,8 +298,8 @@ pub fn run(ctx: *Ctx) !void {
}
// Persistent goal steering (#318): the diff-gated standing-goal note
- // plus a one-shot supersession note when /goal was replaced or cleared.
- // The checklist is NOT re-injected - it lives in todo_write results.
+ // plus one-shot notes (/goal replace|clear, and the standing state an
+ // emergency trim re-queues). Compaction restates the checklist itself.
var goal_msg: []const u8 = try goal_state.applyGoalSteering(ctx.arena, ctx.root, base_msg);
const eval_note = if (ctx.root.review_mode) "" else try repl_glue.evalSteeringNote(
ctx.arena,
diff --git a/src/prompts.zig b/src/prompts.zig
index 6e70e15d..2becc9dc 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -79,9 +79,9 @@ pub const sub_system_prompt =
pub const compact_instruction =
\\Summarize this entire conversation for a context handoff. Capture: the
\\user's goals, all important facts and decisions, file paths and code
- \\that was created or modified, command results that matter, and any
- \\pending or unfinished work. Be thorough but compact. Reply with only
- \\the summary.
+ \\that was created or modified, command results that matter, the current
+ \\task checklist and each item's status, and any pending or unfinished
+ \\work. Be thorough but compact. Reply with only the summary.
;
test "root prompt permits explicit external targets without weakening confinement" {
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 78e4abac..0ef2e380 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -93,11 +93,12 @@ pub const ReplStreamSink = struct {
};
/// The standing-goal steering note for a turn when /goal is set. The checklist
-/// itself is deliberately NOT embedded (#318): the model already sees it in
-/// todo_write tool results, and re-pasting it every turn is how items from a
-/// dead goal kept steering later work (and how compaction memorized them).
-/// Returns "" when goal is null/inactive so the caller can skip the append;
-/// injection is diff-gated by goal_state.steeringGate.
+/// itself is deliberately NOT embedded (#318): the model sees it in todo_write
+/// results, and re-pasting it every turn is how a dead goal's items kept
+/// steering later work. The ONE exception is compaction, where those results
+/// are gone - goal_flow.compactionSnapshot restates the list into the new
+/// history instead, so this text (and its fingerprint) never moves. Returns ""
+/// when goal is null/inactive; injection is diff-gated by goal_state.steeringGate.
pub fn goalSteeringNote(arena: Allocator, goal: ?agent_mod.Goal) ![]const u8 {
const g = goal orelse return "";
if (g.status != .active) return ""; // paused/blocked/complete/budget_limited never steer (#223)
@@ -106,8 +107,8 @@ pub fn goalSteeringNote(arena: Allocator, goal: ?agent_mod.Goal) ![]const u8 {
// attempt_completion "to end this steering", and one such call left the rest
// of a headless/SDK session running unsteered (#318).
if (g.standing)
- return std.fmt.allocPrint(arena, "[standing goal: {s} - keep this objective in view on every task; track multi-step work as a live todo_write checklist, marking each item in_progress when you start and completed when done. This steering persists for the whole session.]", .{g.objective});
- return std.fmt.allocPrint(arena, "[standing goal: {s} - track this as a live todo_write checklist and work through it, marking each item in_progress when you start and completed when done. When the objective is verifiably done, call attempt_completion - that completes the goal and ends this steering.]", .{g.objective});
+ return std.fmt.allocPrint(arena, "[standing goal: {s} - keep this objective in view on every task; track multi-step work as a live todo_write checklist (todo_read shows the current one; todo_write REPLACES it, so include already-completed items when rewriting), marking each item in_progress when you start and completed when done. This steering persists for the whole session.]", .{g.objective});
+ return std.fmt.allocPrint(arena, "[standing goal: {s} - track this as a live todo_write checklist and work through it (todo_read shows the current one; todo_write REPLACES it, so include already-completed items when rewriting), marking each item in_progress when you start and completed when done. When the objective is verifiably done, call attempt_completion - that completes the goal and ends this steering.]", .{g.objective});
}
/// Extract a 0-100 score from an eval command's output: a `score` key (JSON or