graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(goal): park todos instead of deleting them; make the completion gate resolvable
Rach Pradhan5d737fa66f30
diff --git a/src/agent.zig b/src/agent.zigindex 5287659a..f2bf18dd 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -132,7 +132,8 @@ pub const Agent = struct {goal_note_fp: u64 = 0, // last-injected standing-goal note fingerprint (goal_state.steeringGate, #318)goal_note_age: u32 = 0, // turns since that note was last injected (refresh interval)pending_goal_note: ?[]const u8 = null, // one-shot supersession note for the next turn (/goal replace|clear)- completion_gate_armed: bool = false, // attempt_completion refused once this turn over an open checklist+ completion_gate_armed: bool = false, // attempt_completion was refused; the promised second call closes the goal. Persists ACROSS turns (a model emits one per turn) until the checklist or goal changes (#318)+ completion_refused: bool = false, // a refused attempt_completion this turn: work the model must react to, so /loop must not read the turn as zero-tool (#318)session_name: []const u8 = "last", // autosave/resume target (<name>.session.json)session_title: ?[]const u8 = null, // human-readable title/rename metadatasys_strict: []const u8 = prompts.main_system_prompt_strict,diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 7c71912a..dbe8fbb8 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -290,14 +290,15 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = message, .is_error = true };}if (try goal_state.completionGate(self.arena, self)) |refusal| {- self.completion_gate_armed = true; // an explicit second call this turn closes anyway+ goal_state.noteCompletionRefused(self); // arm the double-check (across turns) and mark the turn as worked (#318)if (!self.sub) try self.say("\xe2\x8f\xb8 completion deferred \xe2\x80\x94 the standing goal's checklist isn't settled\n", .{});return .{ .text = refusal, .is_error = true };}const result = if (call.input.object.get("result")) |r| r.string else "";self.completed = try self.arena.dupe(u8, result);if (goal_state.goalActive(self)) {- _ = goal_state.closeEpoch(&self.todos, self.goal.?.epoch); // completion closes the checklist (the deferral text's parking promise)+ // .complete retires the epoch (goal_state.currentEpoch): the checklist+ // parks - readable, no longer current - instead of being deleted (#318).self.goal.?.status = .complete; // a normal completion ends the goal - not only /loop's controller (#318)self.goal.?.updated_ms = util.unixMs(self.io);if (self.tracer) |t| t.note("goal", "completed via attempt_completion");@@ -312,8 +313,9 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return self.runEval(note);}if (std.mem.eql(u8, call.name, "todo_write")) {- self.todos.clearRetainingCapacity();const epoch = goal_state.currentEpoch(self.goal); // items belong to the goal that authored them (#318)+ _ = goal_state.clearEpoch(&self.todos, epoch); // replace THIS epoch's list; parked items from earlier goals survive+ goal_state.rearmCompletionGate(self); // a new checklist is new evidence for the completion double-checkif (call.input.object.get("todos")) |list| if (list == .array) {for (list.array.items) |item| {if (item != .object) continue;@@ -327,7 +329,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {});}};- const rendered = self.renderTodos();+ const rendered = self.renderTodos(epoch);if (!self.sub) try self.say("{s}\n", .{rendered});return .{ .text = rendered, .is_error = false };}@@ -353,7 +355,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {}if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);// todo_read- return .{ .text = self.renderTodos(), .is_error = false };+ return .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };}/// The "user message as a tool" half of the loop: the agent callsdiff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 03d66f64..30bbda0f 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -27,6 +27,7 @@ const sessionAge = session.sessionAge;const ansi = @import("ansi.zig");const style = &ansi.style;+const goal_state = @import("goal_state.zig");const jobs = @import("jobs.zig");const subagent = @import("subagent.zig"); // #276 P0-3: g_agent_jobs, for /jobs@@ -133,7 +134,10 @@ fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writerpub 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 (std.mem.eql(u8, line, "/todo")) {- try out.print("{s}\n", .{root.renderTodos()});+ const epoch = goal_state.currentEpoch(root.goal);+ try out.print("{s}\n", .{root.renderTodos(epoch)});+ const parked = goal_state.parkedOpenCount(root.todos.items, epoch);+ if (parked > 0) try out.print("(+{d} unfinished item(s) parked from an earlier goal \xe2\x80\x94 kept in the session, not steering)\n", .{parked});try out.flush();return true;}diff --git a/src/commands_session.zig b/src/commands_session.zigindex b8b0b5cc..03d89930 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -58,6 +58,7 @@ const setTerminalTitle = title_mod.setTerminalTitle;/// after "context cleared" (#178).fn resetConversationSteering(root: *Agent) void {root.goal = null;+ root.completion_gate_armed = false; // a dropped goal re-arms the completion double-check (#318)root.ultracode_mode = false;root.pending_goal_note = null; // a queued supersession note dies with the conversation (#318)root.goal_note_fp = 0;@@ -136,7 +137,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,// bare /goal or /goal status: report the objective + lifecycle state.if (root.goal) |g| {const open = goal_state.openCount(root.todos.items, g.epoch);- try out.print("\xf0\x9f\x8e\xaf Goal: {s}\nStatus: {s}. Checklist: {d} item(s) open. Commands: /goal pause | resume | clear.\n", .{ g.objective, @tagName(g.status), open });+ const parked = goal_state.parkedOpenCount(root.todos.items, g.epoch);+ const state = if (g.status == .complete) "parked unfinished" else "open"; // a retired goal has no open work, only parked work (#318)+ try out.print("\xf0\x9f\x8e\xaf Goal: {s}\nStatus: {s}. Checklist: {d} item(s) {s}. Commands: /goal pause | resume | clear.\n", .{ g.objective, @tagName(g.status), open, state });+ if (parked > 0) try out.print("(+{d} unfinished item(s) parked from earlier goals \xe2\x80\x94 kept in the session, not steering)\n", .{parked});} else try out.writeAll("No active goal. Set one with /goal <objective>.\n");} else if (std.ascii.eqlIgnoreCase(text, "clear") or std.ascii.eqlIgnoreCase(text, "off")) {if (root.goal == null) {@@ -147,14 +151,14 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}const open = goal_state.openCount(root.todos.items, goal_state.currentEpoch(root.goal));- root.goal = null;- root.todos.clearRetainingCapacity(); // the goal's checklist closes with it (#318)+ root.goal = null; // the checklist PARKS with the goal (#318): items keep their epoch and stay in the session, they just stop being current+ goal_state.rearmCompletionGate(root);root.goal_note_fp = 0;if (root.tracer) |t| t.note("goal", "cleared");saveSession(root, arena, root.session_name) catch {};if (open > 0) {root.pending_goal_note = try goal_state.clearedNote(arena, open);- try out.print("Goal cleared \xe2\x80\x94 checklist closed ({d} unfinished item(s) parked). Future turns will not get goal steering.\n", .{open});+ try out.print("Goal cleared \xe2\x80\x94 checklist parked ({d} unfinished item(s) kept in the session, no longer steering). Future turns will not get goal steering.\n", .{open});} else try out.writeAll("Goal cleared. Future turns will not get goal steering.\n");} else if (std.ascii.eqlIgnoreCase(text, "pause")) {if (root.goal) |*g| {@@ -174,20 +178,28 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,} else {const now = unixMs(root.io);const epoch = goal_state.nextEpoch(root.goal);- if (root.goal) |old| {- // Replacement is a supersession boundary (#318): park the old- // checklist and queue a one-shot note so the model does not- // treat inherited items as authorization to keep going.- const parked = goal_state.parkSuperseded(&root.todos, epoch);+ // A COMPLETE goal is already retired and its checklist already parked+ // (#318 D1), so the next /goal is not superseding live work: it takes+ // the adoption branch, exactly like a first /goal.+ const superseded: ?agent_mod.Goal = if (root.goal) |old| (if (old.status == .complete) null else old) else null;+ if (superseded) |old| {+ // Replacement is a supersession boundary (#318): the old+ // checklist parks (retained, no longer current) and a one-shot+ // note tells the model not to treat inherited items as+ // authorization to keep going.+ const parked = goal_state.parkedOpenCount(root.todos.items, epoch);root.pending_goal_note = try goal_state.supersededNote(arena, old.objective, parked);if (root.tracer) |t| t.note("goal", "replaced");- if (parked > 0) try out.print("(superseded \"{s}\" \xe2\x80\x94 parked {d} unfinished checklist item(s))\n", .{ old.objective, parked });+ if (parked > 0) try out.print("(superseded \"{s}\" \xe2\x80\x94 parked {d} unfinished checklist item(s), kept in the session)\n", .{ old.objective, parked });} else {- goal_state.adoptTodos(root.todos.items, epoch); // formalizing an in-flight plan keeps its checklist+ // Formalizing an in-flight plan keeps its checklist; work parked+ // by a finished goal stays parked.+ goal_state.adoptTodos(root.todos.items, goal_state.currentEpoch(root.goal), epoch);if (root.tracer) |t| t.note("goal", "set");}root.goal = .{ .objective = try arena.dupe(u8, text), .status = .active, .epoch = epoch, .created_ms = now, .updated_ms = now };root.goal_note_fp = 0;+ goal_state.rearmCompletionGate(root); // a new objective is new evidence for the completion double-checksaveSession(root, arena, root.session_name) catch {};try out.print("\xf0\x9f\x8e\xaf Goal set: {s} \xe2\x80\x94 starting now (tracked as a live checklist; it steers every turn until /goal pause or /goal clear).\n", .{text});}diff --git a/src/goal_state.zig b/src/goal_state.zigindex 68839580..d9e5f38c 100644--- a/src/goal_state.zig+++ b/src/goal_state.zig@@ -4,6 +4,11 @@//! items instead of bequeathing them to the next objective, and the steering//! note is diff-gated so unchanged state is never re-stated (a re-pasted note//! on every turn is how compaction learned a dead goal's checklist by heart).+//! Parking is RETENTION, never deletion (#318): a parked item keeps its epoch,+//! stays in root.todos and in the session JSON, and merely stops being current.+//! Every query and render here is epoch-scoped instead - the old destructive+//! parkSuperseded/closeEpoch pair is gone, because a mistyped /goal must not be+//! able to erase the user's checklist.//! Pure logic — no Io — so every rule here is unit-tested.const std = @import("std");@@ -19,9 +24,14 @@ pub fn nextEpoch(old: ?agent_mod.Goal) u64 {return if (old) |g| g.epoch + 1 else 1;}-/// Epoch new todos are stamped with: the standing goal's, else 0 (no goal).+/// Epoch new todos are stamped with: the standing goal's while it still owns the+/// work, else 0 (no goal). A COMPLETE goal is not the stamping authority - its+/// checklist parks with it, later writes are unscoped again, and /goal status can+/// never read "complete" with items open. Paused/blocked goals keep their epoch:+/// they are alive, just not steering.pub fn currentEpoch(goal: ?agent_mod.Goal) u64 {- return if (goal) |g| g.epoch else 0;+ const g = goal orelse return 0;+ return if (g.status == .complete) 0 else g.epoch;}/// Not-yet-completed items belonging to `epoch`.@@ -45,28 +55,23 @@ pub fn allDone(todos: []const TodoItem, epoch: u64) bool {return seen;}-/// Remove every item not belonging to `keep_epoch`: a superseded goal's-/// checklist is parked, never inherited by the new objective. Returns how many-/// still-open items were parked so the caller can report them to the user.-pub fn parkSuperseded(todos: *std.ArrayList(TodoItem), keep_epoch: u64) usize {- var parked_open: usize = 0;- var i: usize = 0;- while (i < todos.items.len) {- const t = todos.items[i];- if (t.epoch == keep_epoch) {- i += 1;- continue;- }- if (!std.mem.eql(u8, t.status, "completed")) parked_open += 1;- _ = todos.orderedRemove(i);+/// Still-open items that do NOT belong to `keep_epoch` - the work a supersession+/// parks. Nothing is removed: parked items stay in the list (and in session+/// JSON) under their own epoch, they just stop being current. Callers report the+/// count so the user knows what stopped steering.+pub fn parkedOpenCount(todos: []const TodoItem, keep_epoch: u64) usize {+ var parked: usize = 0;+ for (todos) |t| {+ if (t.epoch == keep_epoch) continue;+ if (!std.mem.eql(u8, t.status, "completed")) parked += 1;}- return parked_open;+ return parked;}-/// Close `epoch`'s checklist: remove all its items. A completed (or force--/// closed) goal takes its list with it - the deferral text promises open items-/// are parked, and /goal status must never read "complete" with items open.-pub fn closeEpoch(todos: *std.ArrayList(TodoItem), epoch: u64) usize {+/// Drop `epoch`'s items so todo_write can write that epoch's checklist afresh.+/// The only removal in this file, and the safe one: it is the authoring goal+/// rewriting its own list. Items from other (parked) epochs are untouched.+pub fn clearEpoch(todos: *std.ArrayList(TodoItem), epoch: u64) usize {var removed: usize = 0;var i: usize = 0;while (i < todos.items.len) {@@ -78,10 +83,39 @@ pub fn closeEpoch(todos: *std.ArrayList(TodoItem), epoch: u64) usize {return removed;}-/// A fresh goal set while an unscoped (pre-goal) checklist exists adopts it:-/// the user just formalized the objective the plan was already serving.-pub fn adoptTodos(todos: []TodoItem, epoch: u64) void {- for (todos) |*t| t.epoch = epoch;+/// A fresh goal set while a current (unscoped, or post-completion) checklist+/// exists adopts it: the user just formalized the objective the plan was already+/// serving. Only `from_epoch` items move - work parked by a finished or+/// superseded goal stays parked and is never resurrected into the new objective.+pub fn adoptTodos(todos: []TodoItem, from_epoch: u64, to_epoch: u64) void {+ for (todos) |*t| {+ if (t.epoch == from_epoch) t.epoch = to_epoch;+ }+}++/// Per-turn reset of the completion gate's turn-scoped flags. `completion_gate_armed`+/// is deliberately NOT reset here (#318): a model emits at most one+/// attempt_completion per turn, so clearing the arm at the turn boundary made+/// every refusal unresolvable - refuse, turn ends, flag clears, refuse again,+/// forever, with nothing the user could type to break out.+pub fn beginTurn(root: *Agent) void {+ root.completion_refused = false;+}++/// The caller's half of a refusal: arm the double-check so the model's promised+/// second attempt_completion closes the goal (this turn or any later one), and+/// record that the turn did work - a refused call is exempt from the tool+/// counter, so without this the /loop reads the turn as silence (#318).+pub fn noteCompletionRefused(root: *Agent) void {+ root.completion_gate_armed = true;+ root.completion_refused = true;+}++/// Re-arm the completion double-check because the evidence changed: todo_write+/// wrote a new current-epoch checklist, or /goal set|replace|clear moved the+/// objective. The next attempt_completion is checked against the new state.+pub fn rearmCompletionGate(root: *Agent) void {+ root.completion_gate_armed = false;}/// Re-state an unchanged active note after this many suppressed turns, in case@@ -134,22 +168,24 @@ pub fn hasCurrent(todos: []const TodoItem, epoch: u64) bool {/// Goal gate for attempt_completion (Cline-style double-check): returns refusal/// text when completion must be deferred - the checklist has open items, or the/// goal has no checklist at all so there is no evidence it is done - and null-/// to accept. The armed flag (set by the caller on refusal, reset each turn)-/// lets an explicit second call close the goal anyway.+/// to accept. The armed flag (set by the caller on refusal) persists until the+/// checklist or the goal changes, so the promised "call it again" closes the goal+/// even when the model makes that call on a LATER turn - which is the only way it+/// ever can, since one attempt_completion per turn is all a model emits.pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {if (!goalActive(agent)) return null;if (agent.completion_gate_armed) return null;const epoch = currentEpoch(agent.goal);const open = openCount(agent.todos.items, epoch);- if (open > 0) return try completionRefusalText(arena, open, renderTodos(agent));+ if (open > 0) return try completionRefusalText(arena, open, renderTodos(agent, epoch));if (!hasCurrent(agent.todos.items, epoch))- return "completion deferred: the standing goal has no checklist yet, so there is no evidence the objective is done. If it truly is, call attempt_completion again to close the goal; otherwise write the remaining plan with todo_write and work it.";+ return "completion deferred: the standing goal has no checklist yet, so there is no evidence the objective is done. If it truly is, call attempt_completion again - now or on a later turn - to close the goal; otherwise write the remaining plan with todo_write and work it.";return null; // nonempty checklist, every item completed}/// The refusal text for completionGate's open-checklist arm.pub fn completionRefusalText(arena: Allocator, open: usize, rendered: []const u8) ![]const u8 {- return std.fmt.allocPrint(arena, "completion deferred: the standing goal still has {d} open checklist item(s):\n{s}\nFinish them, or call attempt_completion again to close the goal anyway (open items will be parked).", .{ open, rendered });+ return std.fmt.allocPrint(arena, "completion deferred: the standing goal still has {d} open checklist item(s):\n{s}\nFinish them, or call attempt_completion again - now or on a later turn - to close the goal anyway; the open items are then parked (kept in the session, no longer steering).", .{ open, rendered });}/// One-shot note for the turn after /goal replaced an active goal — ports@@ -161,18 +197,21 @@ pub fn supersededNote(arena: Allocator, old_objective: []const u8, parked_open:return std.fmt.allocPrint(arena, "[goal update: the standing goal above supersedes the previous goal \"{s}\". Avoid continuing work that only served the previous objective unless it also helps the new one.]", .{old_objective});}-/// One-shot note for the turn after /goal clear closed an unfinished checklist.+/// One-shot note for the turn after /goal clear parked an unfinished checklist.pub fn clearedNote(arena: Allocator, parked_open: usize) ![]const u8 {- return std.fmt.allocPrint(arena, "[goal update: the standing goal was cleared and its checklist closed ({d} unfinished item(s) parked). Do not resume that work unless the user asks for it again.]", .{parked_open});+ return std.fmt.allocPrint(arena, "[goal update: the standing goal was cleared and its checklist parked ({d} unfinished item(s), kept in the session but no longer current). Do not resume that work unless the user asks for it again.]", .{parked_open});}-/// Render the checklist ("[x]/[~]/[ ] content" lines). Moved from agent.zig-/// (600-line cap); member-aliased so self.renderTodos() resolves unchanged.-pub fn renderTodos(self: *Agent) []const u8 {- if (self.todos.items.len == 0) return "(no todos)";+/// Render `epoch`'s checklist ("[x]/[~]/[ ] content" lines). Epoch-scoped (#318):+/// items parked by an earlier goal are retained but never rendered as if they+/// were current work. Moved from agent.zig (600-line cap); member-aliased so+/// self.renderTodos(epoch) resolves unchanged.+pub fn renderTodos(self: *Agent, epoch: u64) []const u8 {+ if (!hasCurrent(self.todos.items, epoch)) return "(no todos)";var aw: Io.Writer.Allocating = .init(self.arena);const w = &aw.writer;for (self.todos.items) |t| {+ if (t.epoch != epoch) continue;const mark = if (std.mem.eql(u8, t.status, "completed"))"[x]"else if (std.mem.eql(u8, t.status, "in_progress"))@@ -184,11 +223,24 @@ pub fn renderTodos(self: *Agent) []const u8 {return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");}+/// The current epoch's checklist, or "" when it has no items - callers that+/// carry the list into steering pick their checklist-free variant on "".+pub fn renderCurrent(root: *Agent) []const u8 {+ const epoch = currentEpoch(root.goal);+ if (!hasCurrent(root.todos.items, epoch)) return "";+ return renderTodos(root, epoch);+}+test "epochs: nextEpoch monotonic from the replaced goal; currentEpoch 0 without a goal" {try std.testing.expectEqual(@as(u64, 1), nextEpoch(null));try std.testing.expectEqual(@as(u64, 4), nextEpoch(.{ .objective = "a", .epoch = 3 }));try std.testing.expectEqual(@as(u64, 0), currentEpoch(null));try std.testing.expectEqual(@as(u64, 7), currentEpoch(.{ .objective = "a", .epoch = 7 }));+ // A completed goal is a dead epoch: later todo_write calls are unscoped+ // again and its own checklist stays parked (#318 D1). Paused/blocked goals+ // are alive - they keep stamping.+ try std.testing.expectEqual(@as(u64, 0), currentEpoch(.{ .objective = "a", .epoch = 7, .status = .complete }));+ try std.testing.expectEqual(@as(u64, 7), currentEpoch(.{ .objective = "a", .epoch = 7, .status = .paused }));}test "openCount/allDone are epoch-scoped; empty checklist is never done (#226)" {@@ -205,7 +257,7 @@ test "openCount/allDone are epoch-scoped; empty checklist is never done (#226)"try std.testing.expect(!allDone(&.{}, 0));}-test "parkSuperseded drops other epochs, counts open ones, keeps the new epoch (#318)" {+test "parking retains: superseded items are counted and kept, never deleted (#318)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const ar = arena_state.allocator();@@ -213,23 +265,77 @@ test "parkSuperseded drops other epochs, counts open ones, keeps the new epoch (try todos.append(ar, .{ .content = "phase3 audit", .status = "pending", .epoch = 1 });try todos.append(ar, .{ .content = "phase3 fix", .status = "completed", .epoch = 1 });try todos.append(ar, .{ .content = "phase2 test", .status = "in_progress", .epoch = 2 });- const parked = parkSuperseded(&todos, 2);- try std.testing.expectEqual(@as(usize, 1), parked); // only the OPEN phase3 item counts- try std.testing.expectEqual(@as(usize, 1), todos.items.len);- try std.testing.expectEqualStrings("phase2 test", todos.items[0].content);- // Completing epoch 2 closes its checklist entirely (the parking promise).- try std.testing.expectEqual(@as(usize, 1), closeEpoch(&todos, 2));- try std.testing.expectEqual(@as(usize, 0), todos.items.len);+ try std.testing.expectEqual(@as(usize, 1), parkedOpenCount(todos.items, 2)); // only the OPEN phase3 item+ try std.testing.expectEqual(@as(usize, 3), todos.items.len); // a mistyped /goal deletes nothing+ try std.testing.expectEqual(@as(u64, 1), todos.items[0].epoch); // parked work keeps its own epoch+ // Retention is safe because every query is epoch-scoped: parked items are+ // invisible to the new goal's open/allDone accounting.+ try std.testing.expectEqual(@as(usize, 1), openCount(todos.items, 2));+ try std.testing.expect(!allDone(todos.items, 2));+ // todo_write rewrites the CURRENT epoch only - parked items survive it.+ try std.testing.expectEqual(@as(usize, 1), clearEpoch(&todos, 2));+ try std.testing.expectEqual(@as(usize, 2), todos.items.len);+ try std.testing.expectEqualStrings("phase3 audit", todos.items[0].content);}-test "adoptTodos re-stamps a pre-goal checklist into the new goal's epoch" {+test "adoptTodos moves the current epoch only; parked work is never resurrected" {var todos = [_]TodoItem{.{ .content = "a", .status = "pending", .epoch = 0 },.{ .content = "b", .status = "completed", .epoch = 0 },+ .{ .content = "parked by a finished goal", .status = "pending", .epoch = 3 },};- adoptTodos(&todos, 5);+ adoptTodos(&todos, 0, 5);try std.testing.expectEqual(@as(u64, 5), todos[0].epoch);try std.testing.expectEqual(@as(u64, 5), todos[1].epoch);+ try std.testing.expectEqual(@as(u64, 3), todos[2].epoch);+}++test "renderTodos is epoch-scoped; renderCurrent goes quiet on a dead epoch (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root: Agent = undefined;+ root.arena = ar;+ root.todos = .empty;+ root.goal = .{ .objective = "ship", .epoch = 2 };+ try root.todos.append(ar, .{ .content = "old phase3 item", .status = "pending", .epoch = 1 });+ try root.todos.append(ar, .{ .content = "current item", .status = "in_progress", .epoch = 2 });+ try std.testing.expectEqualStrings("[~] current item", renderTodos(&root, 2));+ try std.testing.expectEqualStrings("[ ] old phase3 item", renderTodos(&root, 1)); // retained, still readable+ try std.testing.expectEqualStrings("[~] current item", renderCurrent(&root));+ try std.testing.expectEqualStrings("(no todos)", renderTodos(&root, 9));+ // A completed goal has no current epoch: its list parks, nothing renders.+ root.goal.?.status = .complete;+ try std.testing.expectEqualStrings("", renderCurrent(&root));+}++test "the completion double-check survives the turn boundary, re-arms on change (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root: Agent = undefined;+ root.sub = false;+ root.review_mode = false;+ root.arena = ar;+ root.todos = .empty;+ root.completion_gate_armed = false;+ root.completion_refused = false;+ root.goal = .{ .objective = "ship", .epoch = 1 };+ try root.todos.append(ar, .{ .content = "a", .status = "pending", .epoch = 1 });+ // Turn 1: refused; the caller arms the gate and records that the turn worked.+ try std.testing.expect((try completionGate(ar, &root)) != null);+ noteCompletionRefused(&root);+ try std.testing.expect(root.completion_refused);+ // Turn boundary: only the per-turn flag clears. A model emits one+ // attempt_completion per turn, so clearing the arm here made the refusal+ // unresolvable forever - the #318 fix reappearing as the #318 bug.+ beginTurn(&root);+ try std.testing.expect(!root.completion_refused);+ try std.testing.expect(root.completion_gate_armed);+ try std.testing.expect((try completionGate(ar, &root)) == null);+ // New evidence (todo_write, or a /goal change) re-arms the double-check.+ rearmCompletionGate(&root);+ try std.testing.expect((try completionGate(ar, &root)) != null);}test "steeringGate: inject on change, suppress repeats, refresh after the interval, reset on empty" {diff --git a/src/mainloop.zig b/src/mainloop.zigindex 0ab3dcad..c7350487 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -93,7 +93,7 @@ pub fn run(ctx: *Ctx) !void {// here, so an interrupted/errored turn does not resume the loop.loop_continue_armed = false;is_loop_continuation = true;- const todos_render = if (ctx.root.todos.items.len > 0) ctx.root.renderTodos() else "";+ const todos_render = goal_state.renderCurrent(ctx.root); // current epoch only: parked work never re-enters a /loop turn (#318)const note = try repl_glue.continuationSteeringNote(ctx.arena, todos_render);break :blk try std.fmt.allocPrint(ctx.arena, "/loop {s}", .{note});} else if (ctx.interactive) blk: {@@ -392,7 +392,7 @@ pub fn run(ctx: *Ctx) !void {} else 0;ctx.root.tools_used.clear(ctx.io); // per-turn tool log for the turn's nodectx.root.tool_calls_this_turn = 0;- ctx.root.completion_gate_armed = false; // the open-checklist double-check is per turn (#318)+ goal_state.beginTurn(ctx.root); // per-turn gate flags; the ARMED double-check is NOT one of them (#318)ctx.root.seen_tool_keys.clearRetainingCapacity();if (main_mod.json_mode) ctx.root.emit(.{ .type = "started", .provider = ctx.root.provider.id, .model = ctx.root.provider.model });if (ctx.interactive and !main_mod.json_mode) {@@ -562,15 +562,15 @@ pub fn run(ctx: *Ctx) !void {if (loop_prompt != null and !main_mod.json_mode) {if (!is_loop_continuation) loop_iters_left = loop_iter_cap; // fresh /loop run: arm the bound// work_done: the model asserted completion or finished the checklist- // - the only evidence that may complete the goal below. A zero-tool- // turn additionally ends the LOOP (codex RegularTask semantics: no- // /loop should burn 25 continuations on a one-turn prompt) but it- // proves nothing about the goal, so it never touches goal status.+ // - the only evidence that may complete the goal, and the only thing+ // that earns `accepted`. A zero-tool turn ends the LOOP as `idle`+ // (codex RegularTask semantics: no /loop burns 25 continuations on a+ // one-turn prompt); a refused attempt_completion is work, not silence.const work_done = ctx.root.completed != null orgoal_state.allDone(ctx.root.todos.items, goal_state.currentEpoch(ctx.root.goal));- const model_done = work_done or ctx.root.tool_calls_this_turn == 0;+ const model_stopped = repl_glue.turnStopped(ctx.root.tool_calls_this_turn, ctx.root.completion_refused);const gstatus: agent_mod.GoalStatus = if (ctx.root.goal) |g| g.status else .active;- switch (repl_glue.continuationDecision(gstatus, model_done, loop_iters_left)) {+ switch (repl_glue.continuationDecision(gstatus, work_done, model_stopped, loop_iters_left)) {.continue_turn => {loop_iters_left -= 1; // consume one credit for the queued continuationloop_continue_armed = true;diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 06f56218..9040bed5 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -192,6 +192,7 @@ test "goalSteeringNote: active-only gate, completion contract, and no embedded c/// the transcript so #219's ledger can later record it verbatim). Budget-free.pub const ContinuationOutcome = enum {accepted, // the goal's checklist is complete (or the goal itself is complete)+ idle, // the turn did no tool work and asserted nothing - the loop stops, but nothing is done (#318)exhausted, // hit the hard per-/loop iteration bound with work still openblocked, // the goal is blocked and needs the usercancelled, // the goal was paused — the user stepped in@@ -206,23 +207,36 @@ pub const ContinuationDecision = union(enum) {/// authorized by CONTROLLER STATE, never by the model merely stopping. An active/// goal with the checklist still open and iterations left keeps going; a/// completed checklist, a paused/blocked/complete goal, or a spent iteration-/// bound each yield the matching named terminal outcome. No budgets.+/// bound each yield the matching named terminal outcome. No budgets. `accepted`+/// is reserved for real evidence of completion: a turn that merely did nothing+/// stops as `idle` (#318), so the transcript label never overstates the outcome.pub fn continuationDecision(goal_status: agent_mod.GoalStatus,- todos_all_completed: bool,+ work_done: bool,+ model_stopped: bool,iters_left: u32,) ContinuationDecision {- if (todos_all_completed) return .{ .stop = .accepted };+ if (work_done) return .{ .stop = .accepted };switch (goal_status) {.paused => return .{ .stop = .cancelled },.blocked => return .{ .stop = .blocked },.complete => return .{ .stop = .accepted },.active => {},}+ if (model_stopped) return .{ .stop = .idle };if (iters_left == 0) return .{ .stop = .exhausted };return .continue_turn;}+/// Did this turn genuinely stop working? Zero tool calls is the model declining+/// to act - but a REFUSED attempt_completion is exempt from the tool counter,+/// and that is exactly a turn where the model acted and got an is_error back to+/// react to. Reading it as silence killed the /loop on the very turn the+/// completion gate meant to keep alive (#318).+pub fn turnStopped(tool_calls: u64, completion_refused: bool) bool {+ return tool_calls == 0 and !completion_refused;+}+/// The steering appended to each autonomous /loop continuation turn (the/// continuation_steering_item analog): keep working the checklist, verify, and/// stop only when done or blocked — not a per-turn user note.@@ -233,18 +247,32 @@ pub fn continuationSteeringNote(arena: Allocator, todos_render: []const u8) ![]c}test "continuationDecision: one assertion per branch (#226)" {- // todos all complete -> accepted, regardless of status/iters.- try std.testing.expectEqual(ContinuationOutcome.accepted, continuationDecision(.active, true, 5).stop);+ // work asserted or the checklist finished -> accepted, regardless of iters.+ try std.testing.expectEqual(ContinuationOutcome.accepted, continuationDecision(.active, true, false, 5).stop);// active + open todos + iterations left -> continue.- try std.testing.expect(std.meta.activeTag(continuationDecision(.active, false, 5)) == .continue_turn);+ try std.testing.expect(std.meta.activeTag(continuationDecision(.active, false, false, 5)) == .continue_turn);// active + open todos + iteration bound spent -> exhausted.- try std.testing.expectEqual(ContinuationOutcome.exhausted, continuationDecision(.active, false, 0).stop);+ try std.testing.expectEqual(ContinuationOutcome.exhausted, continuationDecision(.active, false, false, 0).stop);// paused -> cancelled (the user stepped in).- try std.testing.expectEqual(ContinuationOutcome.cancelled, continuationDecision(.paused, false, 5).stop);+ try std.testing.expectEqual(ContinuationOutcome.cancelled, continuationDecision(.paused, false, false, 5).stop);// blocked -> blocked.- try std.testing.expectEqual(ContinuationOutcome.blocked, continuationDecision(.blocked, false, 5).stop);+ try std.testing.expectEqual(ContinuationOutcome.blocked, continuationDecision(.blocked, false, false, 5).stop);// complete -> accepted.- try std.testing.expectEqual(ContinuationOutcome.accepted, continuationDecision(.complete, false, 5).stop);+ try std.testing.expectEqual(ContinuationOutcome.accepted, continuationDecision(.complete, false, false, 5).stop);+}++test "a zero-tool turn stops as idle, not accepted; a refused completion keeps the loop (#318)" {+ // The model stopped with the checklist still open: the loop ends, but+ // labelling that `accepted` claimed a goal was done that nobody finished.+ try std.testing.expectEqual(ContinuationOutcome.idle, continuationDecision(.active, false, true, 5).stop);+ // Real evidence still earns `accepted`.+ try std.testing.expectEqual(ContinuationOutcome.accepted, continuationDecision(.active, true, true, 5).stop);+ // A refused attempt_completion is work, so the turn is not "stopped" ...+ try std.testing.expect(turnStopped(0, false));+ try std.testing.expect(!turnStopped(0, true));+ try std.testing.expect(!turnStopped(3, false));+ // ... and the loop runs another turn so the model can react to the refusal.+ try std.testing.expect(std.meta.activeTag(continuationDecision(.active, false, turnStopped(0, true), 5)) == .continue_turn);}test "continuationSteeringNote: renders checklist when present, generic otherwise (#226)" {