graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(goal): scope todos to goal epochs; stop steering after completion (#318)
justrach5db9d7c910fe
diff --git a/src/agent.zig b/src/agent.zigindex 8a3094ca..5287659a 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -29,6 +29,7 @@ const ansi = @import("ansi.zig");const style = &ansi.style;const prompt_ui = @import("agent_prompt.zig");const agent_tests = @import("agent_tests.zig");+const goal_state = @import("goal_state.zig");const reasoningPromptLabel = prompt_ui.reasoningLabel;const reasoningPromptColor = prompt_ui.reasoningColor;@@ -39,6 +40,7 @@ const contextPercent = prompt_ui.contextPercent;pub const TodoItem = struct {content: []const u8,status: []const u8,+ epoch: u64 = 0, // the goal epoch that authored this item (#318); 0 = no goal};/// Governed-run status for a standing /goal (#223). Only `.active` steers turns;@@ -52,6 +54,7 @@ pub const GoalStatus = enum { active, paused, blocked, complete };pub const Goal = struct {objective: []const u8,status: GoalStatus = .active,+ epoch: u64 = 0, // monotonic per session; todos are stamped with it so a replaced goal cannot bequeath its checklist (#318)created_ms: i64 = 0,updated_ms: i64 = 0,};@@ -126,6 +129,10 @@ pub const Agent = struct {show_thinking: bool = true, // stream the model's reasoning live in the TUI (/thinking); off = spinner onlyai_title: bool = true, // AI-generate the tab/session title from the first prompt (/title)goal: ?Goal = null, // structured objective + status lifecycle (/goal, #223)+ 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 checklistsession_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,@@ -448,21 +455,7 @@ pub const Agent = struct {pub const emitAskUser = @import("agent_tools.zig").emitAskUser;pub const sayToolUse = @import("agent_tools.zig").sayToolUse;pub const sayToolResult = @import("agent_tools.zig").sayToolResult;- pub fn renderTodos(self: *Agent) []const u8 {- if (self.todos.items.len == 0) return "(no todos)";- var aw: Io.Writer.Allocating = .init(self.arena);- const w = &aw.writer;- for (self.todos.items) |t| {- const mark = if (std.mem.eql(u8, t.status, "completed"))- "[x]"- else if (std.mem.eql(u8, t.status, "in_progress"))- "[~]"- else- "[ ]";- w.print("{s} {s}\n", .{ mark, t.content }) catch break;- }- return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");- }+ pub const renderTodos = goal_state.renderTodos; // body in goal_state.zig (600-line cap)// Context management (compaction/emergency-trim) and the --eval/--until// eval-driven loop (+ optional LLM-as-judge) live in agent_compact.zigdiff --git a/src/agent_tools.zig b/src/agent_tools.zigindex f7a134be..56ae573c 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -30,6 +30,7 @@ const tty = terminal.tty;const schema = @import("schema.zig");const isMetaName = schema.isMetaName;const eval_control = @import("agent_eval_control.zig");+const goal_state = @import("goal_state.zig");pub const toolInvalidatesEval = eval_control.toolInvalidatesEval;pub const gateTool = @import("agent_tool_gate.zig").gateTool;pub const firstWord = @import("agent_tool_gate.zig").firstWord;@@ -288,8 +289,20 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {"completion blocked: workspace state is not verified; run eval and meet the target after the final change";return .{ .text = message, .is_error = true };}+ const goal_active = !self.sub and self.goal != null and self.goal.?.status == .active;+ const open = goal_state.openCount(self.todos.items, goal_state.currentEpoch(self.goal));+ if (goal_state.completionDecision(goal_active, open, self.completion_gate_armed) == .refuse_open_checklist) {+ self.completion_gate_armed = true; // second call this turn closes the goal anyway+ return .{ .text = try goal_state.completionRefusalText(self.arena, open, self.renderTodos()), .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_active) {+ 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");+ try self.say("\xf0\x9f\x8e\xaf standing goal complete\n", .{});+ }// Skip the re-print only when the result streamed live in full.if (!self.sub and !self.argStreamedFully(call)) try self.say("{s}\n", .{result});return .{ .text = "completion recorded", .is_error = false };@@ -300,6 +313,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {}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)if (call.input.object.get("todos")) |list| if (list == .array) {for (list.array.items) |item| {if (item != .object) continue;@@ -309,6 +323,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {try self.todos.append(self.arena, .{.content = try self.arena.dupe(u8, content.string),.status = try self.arena.dupe(u8, status),+ .epoch = epoch,});}};diff --git a/src/commands_session.zig b/src/commands_session.zigindex f3f50d85..494eb54a 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -13,6 +13,7 @@ const provider_mod = @import("provider.zig");const util = @import("util.zig");const tools_mod = @import("tools.zig");const session_mod = @import("session.zig");+const goal_state = @import("goal_state.zig");const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;const ToolCall = tools_mod.ToolCall;@@ -58,6 +59,9 @@ const setTerminalTitle = title_mod.setTerminalTitle;fn resetConversationSteering(root: *Agent) void {root.goal = null;root.ultracode_mode = false;+ root.pending_goal_note = null; // a queued supersession note dies with the conversation (#318)+ root.goal_note_fp = 0;+ root.goal_note_age = 0;}test "/clear + /new reset conversation steering — goal and ultracode_mode don't survive (#178)" {@@ -131,12 +135,20 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (text.len == 0 or std.ascii.eqlIgnoreCase(text, "status")) {// bare /goal or /goal status: report the objective + lifecycle state.if (root.goal) |g| {- try out.print("\xf0\x9f\x8e\xaf Goal: {s}\nStatus: {s}. Commands: /goal pause | resume | clear.\n", .{ g.objective, @tagName(g.status) });+ 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 });} 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")) {+ 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_note_fp = 0;+ if (root.tracer) |t| t.note("goal", "cleared");saveSession(root, arena, root.session_name) catch {};- try out.writeAll("Goal cleared. Future turns will not get goal steering.\n");+ 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});+ } 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| {g.status = .paused;@@ -148,12 +160,27 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (root.goal) |*g| {g.status = .active;g.updated_ms = unixMs(root.io);+ root.goal_note_fp = 0; // re-state the note on the next turn, not a stale-suppressed repeatsaveSession(root, arena, root.session_name) catch {};try out.print("\xf0\x9f\x8e\xaf Goal resumed: {s} - steering every turn again.\n", .{g.objective});} else try out.writeAll("No goal to resume. Set one with /goal <objective>.\n");} else {const now = unixMs(root.io);- root.goal = .{ .objective = try arena.dupe(u8, text), .status = .active, .created_ms = now, .updated_ms = now };+ 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);+ 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 });+ } else {+ goal_state.adoptTodos(root.todos.items, epoch); // formalizing an in-flight plan keeps its checklist+ 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;saveSession(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.zignew file mode 100644index 00000000..6e105172--- /dev/null+++ b/src/goal_state.zig@@ -0,0 +1,260 @@+//! Goal-scoped todo epochs, steering-injection policy, and the completion gate+//! (#318). A standing /goal owns its checklist: todos are stamped with the+//! goal's epoch at write time, a replaced or cleared goal parks its unfinished+//! 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).+//! Pure logic — no Io — so every rule here is unit-tested.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const TodoItem = agent_mod.TodoItem;+const repl_glue = @import("repl_glue.zig");++/// Epoch for a goal that replaces `old` (0 is the no-goal/legacy epoch).+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).+pub fn currentEpoch(goal: ?agent_mod.Goal) u64 {+ return if (goal) |g| g.epoch else 0;+}++/// Not-yet-completed items belonging to `epoch`.+pub fn openCount(todos: []const TodoItem, epoch: u64) usize {+ var n: usize = 0;+ for (todos) |t| {+ if (t.epoch == epoch and !std.mem.eql(u8, t.status, "completed")) n += 1;+ }+ return n;+}++/// True only when `epoch` has a nonempty checklist and every item is completed+/// (#226 — an empty list is "no plan yet", never "done").+pub fn allDone(todos: []const TodoItem, epoch: u64) bool {+ var seen = false;+ for (todos) |t| {+ if (t.epoch != epoch) continue;+ if (!std.mem.eql(u8, t.status, "completed")) return false;+ seen = true;+ }+ 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);+ }+ return parked_open;+}++/// 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;+}++/// Re-state an unchanged active note after this many suppressed turns, in case+/// the last statement aged out of the model's effective attention.+pub const refresh_turns: u32 = 8;++pub const SteeringGate = struct { inject: bool, fp: u64, age: u32 };++/// Diff-gate for the standing-goal note: inject when the note text changed or+/// the refresh interval lapsed; suppress verbatim repeats. Codex renders all+/// standing context as a diff against a snapshot for the same reason.+pub fn steeringGate(note: []const u8, last_fp: u64, age: u32, refresh_every: u32) SteeringGate {+ if (note.len == 0) return .{ .inject = false, .fp = 0, .age = 0 };+ const fp = std.hash.Wyhash.hash(0, note);+ if (fp != last_fp or age + 1 >= refresh_every) return .{ .inject = true, .fp = fp, .age = 0 };+ return .{ .inject = false, .fp = fp, .age = age + 1 };+}++/// Assemble this turn's goal steering onto `base`: the diff-gated standing+/// note plus any one-shot supersession note (consumed here). Review turns are+/// isolated and get neither.+pub fn applyGoalSteering(arena: Allocator, root: *Agent, base: []const u8) ![]const u8 {+ if (root.review_mode) return base;+ var msg = base;+ const note = try repl_glue.goalSteeringNote(arena, root.goal);+ const gate = steeringGate(note, root.goal_note_fp, root.goal_note_age, refresh_turns);+ root.goal_note_fp = gate.fp;+ root.goal_note_age = gate.age;+ if (gate.inject) msg = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, note });+ if (root.pending_goal_note) |one_shot| {+ msg = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, one_shot });+ root.pending_goal_note = null;+ }+ return msg;+}++pub const CompletionAction = enum { accept, refuse_open_checklist };++/// Cline-style double-check: the first attempt_completion while the standing+/// goal's checklist still has open items is refused (with the list echoed); a+/// second call closes the goal anyway. No goal, or a clean checklist, accepts.+pub fn completionDecision(goal_active: bool, open_todos: usize, retry_armed: bool) CompletionAction {+ if (!goal_active or open_todos == 0 or retry_armed) return .accept;+ return .refuse_open_checklist;+}++/// The refusal text for completionDecision's .refuse_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 });+}++/// One-shot note for the turn after /goal replaced an active goal — ports+/// codex's objective_updated.md steering: the new objective supersedes, and+/// work that only served the old one must not silently continue.+pub fn supersededNote(arena: Allocator, old_objective: []const u8, parked_open: usize) ![]const u8 {+ if (parked_open > 0)+ return std.fmt.allocPrint(arena, "[goal update: the standing goal above supersedes the previous goal \"{s}\"; {d} unfinished checklist item(s) from it were parked. Avoid continuing work that only served the previous objective unless it also helps the new one. Start a fresh todo_write checklist for this objective.]", .{ old_objective, 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.+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});+}++/// 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)";+ var aw: Io.Writer.Allocating = .init(self.arena);+ const w = &aw.writer;+ for (self.todos.items) |t| {+ const mark = if (std.mem.eql(u8, t.status, "completed"))+ "[x]"+ else if (std.mem.eql(u8, t.status, "in_progress"))+ "[~]"+ else+ "[ ]";+ w.print("{s} {s}\n", .{ mark, t.content }) catch break;+ }+ return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");+}++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 }));+}++test "openCount/allDone are epoch-scoped; empty checklist is never done (#226)" {+ const todos = [_]TodoItem{+ .{ .content = "old work", .status = "pending", .epoch = 1 },+ .{ .content = "done here", .status = "completed", .epoch = 2 },+ .{ .content = "also done", .status = "completed", .epoch = 2 },+ };+ try std.testing.expectEqual(@as(usize, 1), openCount(&todos, 1));+ try std.testing.expectEqual(@as(usize, 0), openCount(&todos, 2));+ try std.testing.expect(!allDone(&todos, 1)); // open item+ try std.testing.expect(allDone(&todos, 2)); // all its items completed+ try std.testing.expect(!allDone(&todos, 3)); // no items at all+ try std.testing.expect(!allDone(&.{}, 0));+}++test "parkSuperseded drops other epochs, counts open ones, keeps the new epoch (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var todos: std.ArrayList(TodoItem) = .empty;+ 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);+}++test "adoptTodos re-stamps a pre-goal checklist into the new goal's epoch" {+ var todos = [_]TodoItem{+ .{ .content = "a", .status = "pending", .epoch = 0 },+ .{ .content = "b", .status = "completed", .epoch = 0 },+ };+ adoptTodos(&todos, 5);+ try std.testing.expectEqual(@as(u64, 5), todos[0].epoch);+ try std.testing.expectEqual(@as(u64, 5), todos[1].epoch);+}++test "steeringGate: inject on change, suppress repeats, refresh after the interval, reset on empty" {+ // Empty note (no goal / paused): nothing injected, fingerprint resets so a+ // resumed goal re-injects immediately.+ const off = steeringGate("", 123, 5, 8);+ try std.testing.expect(!off.inject and off.fp == 0 and off.age == 0);+ // First sight of a note: inject.+ const g1 = steeringGate("[standing goal: x]", 0, 0, 8);+ try std.testing.expect(g1.inject);+ // Verbatim repeat: suppressed, age climbs.+ const g2 = steeringGate("[standing goal: x]", g1.fp, g1.age, 8);+ try std.testing.expect(!g2.inject and g2.age == 1);+ // Changed note (new objective/epoch): inject again.+ const g3 = steeringGate("[standing goal: y]", g2.fp, g2.age, 8);+ try std.testing.expect(g3.inject);+ // Refresh interval lapse re-states an unchanged note.+ const g4 = steeringGate("[standing goal: y]", g3.fp, 7, 8);+ try std.testing.expect(g4.inject and g4.age == 0);+}++test "completionDecision: goal-scoped double-check (#318)" {+ try std.testing.expectEqual(CompletionAction.accept, completionDecision(false, 3, false)); // no goal: informal todos never block+ try std.testing.expectEqual(CompletionAction.accept, completionDecision(true, 0, false)); // clean checklist+ try std.testing.expectEqual(CompletionAction.refuse_open_checklist, completionDecision(true, 2, false)); // first call refused+ try std.testing.expectEqual(CompletionAction.accept, completionDecision(true, 2, true)); // explicit second call closes anyway+}++test "applyGoalSteering: injects once, suppresses repeats, consumes the one-shot note" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root: Agent = undefined;+ root.review_mode = false;+ root.goal = .{ .objective = "ship it", .epoch = 1 };+ root.goal_note_fp = 0;+ root.goal_note_age = 0;+ root.pending_goal_note = null;+ const m1 = try applyGoalSteering(ar, &root, "hi");+ try std.testing.expect(std.mem.indexOf(u8, m1, "[standing goal: ship it") != null);+ const m2 = try applyGoalSteering(ar, &root, "hi");+ try std.testing.expectEqualStrings("hi", m2); // verbatim repeat suppressed+ root.pending_goal_note = "[goal update: x]";+ const m3 = try applyGoalSteering(ar, &root, "hi");+ try std.testing.expect(std.mem.indexOf(u8, m3, "[goal update: x]") != null);+ try std.testing.expect(root.pending_goal_note == null); // one-shot consumed+ // Review turns are isolated: no steering, gate state untouched.+ root.review_mode = true;+ root.pending_goal_note = "[goal update: y]";+ try std.testing.expectEqualStrings("hi", try applyGoalSteering(ar, &root, "hi"));+ try std.testing.expect(root.pending_goal_note != null); // preserved for the next normal turn+}++test "supersededNote and clearedNote name the parked work" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ const s1 = try supersededNote(ar, "phase 3", 4);+ try std.testing.expect(std.mem.indexOf(u8, s1, "supersedes the previous goal \"phase 3\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, s1, "4 unfinished") != null);+ const s2 = try supersededNote(ar, "phase 3", 0);+ try std.testing.expect(std.mem.indexOf(u8, s2, "parked") == null);+ const c = try clearedNote(ar, 2);+ try std.testing.expect(std.mem.indexOf(u8, c, "2 unfinished") != null);+}diff --git a/src/main.zig b/src/main.zigindex e0b5b779..07df2a99 100644--- a/src/main.zig+++ b/src/main.zig@@ -592,4 +592,5 @@ test { // pull in tests from imported modules (mcp.zig)// they silently compile to nothing and the suite still reports green._ = @import("scoring_slot_test.zig");_ = @import("readline_history.zig");+ _ = @import("goal_state.zig");}diff --git a/src/mainloop.zig b/src/mainloop.zigindex c79ae89d..de088630 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -23,6 +23,7 @@ const fleet = @import("fleet.zig");const jobs = @import("jobs.zig");const session = @import("session.zig");const repl_glue = @import("repl_glue.zig");+const goal_state = @import("goal_state.zig");const eval_memory = @import("eval_memory.zig");const mainloop_score = @import("mainloop_score.zig");const mainloop_trace = @import("mainloop_trace.zig");@@ -54,13 +55,6 @@ pub const Ctx = struct {sys_strict: []const u8,};-/// True only when a nonempty live checklist is entirely completed (#226).-fn allTodosDone(root: *agent_mod.Agent) bool {- if (root.todos.items.len == 0) return false;- for (root.todos.items) |t| if (!std.mem.eql(u8, t.status, "completed")) return false;- return true;-}-/// Run turns until EOF/quit; main then performs final save/worktree cleanup.pub fn run(ctx: *Ctx) !void {var title_jobs: mainloop_title.Jobs = .{};@@ -303,11 +297,10 @@ pub fn run(ctx: *Ctx) !void {continue;}- // Persistent goal steering: the objective plus a nudge to track it as a- // live todo_write checklist, with the current list appended so the model- // resumes the plan instead of re-deriving it (assembled by goalSteeringNote).- const todos_render: []const u8 = if (ctx.root.todos.items.len > 0) ctx.root.renderTodos() else "";- const goal_note = if (ctx.root.review_mode) "" else try repl_glue.goalSteeringNote(ctx.arena, ctx.root.goal, todos_render);+ // 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.+ 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,ctx.root.eval_cmd,@@ -317,15 +310,13 @@ pub fn run(ctx: *Ctx) !void {ctx.root.eval_repair_pending,eval_memory.load(ctx.root),);- var goal_msg: []const u8 = base_msg;- if (goal_note.len > 0) goal_msg = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ goal_msg, goal_note });if (eval_note.len > 0) goal_msg = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ goal_msg, eval_note });// /loop asks the model to work autonomously through plan→act→verify.const loop_msg: []const u8 = if (loop_prompt != null) try std.fmt.allocPrint(ctx.arena,\\{s}\\- \\[harness note: /loop was used. Work autonomously until the prompt is satisfied: make a brief plan, execute it with tools, verify the result, and only stop when you can report completion or you need a required human decision. Keep iterations tight and avoid asking for confirmation between routine steps.]+ \\[harness note: /loop was used. Work autonomously until the prompt is satisfied: make a brief plan, execute it with tools, verify the result, and only stop when you can report completion or you need a required human decision. Keep iterations tight and avoid asking for confirmation between routine steps. Track multi-step work with todo_write and finish by calling attempt_completion with the final result - that ends the loop. A turn that uses no tools also ends the loop, so if the prompt needs no tool work, just answer it.], .{goal_msg}) else goal_msg;const msg: []const u8 = if (!main_mod.plan_mode or ctx.root.review_mode) loop_msg else try std.fmt.allocPrint(ctx.arena,@@ -401,6 +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)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) {@@ -557,6 +549,7 @@ pub fn run(ctx: *Ctx) !void {// 80–95% a transient compaction failure can recover next turn.const near_cap = ctx.root.provider.nearContextLimit(session_context_tokens);ctx.root.compactOrRecover(near_cap);+ ctx.root.goal_note_fp = 0; // history rewritten - re-state goal steering in full next turn (#318)}// #226: /loop controller-authorized continuation. After a cleanly-@@ -569,7 +562,13 @@ pub fn run(ctx: *Ctx) !void {// never resumes the loop.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- const model_done = ctx.root.completed != null or allTodosDone(ctx.root);+ // A turn that used no tools is a natural finish (codex RegularTask+ // semantics): without this, a /loop on a one-turn prompt burned all+ // 25 continuations inventing follow-on work. attempt_completion is+ // budget-exempt and does not count, so text+completion still lands here.+ const model_done = ctx.root.completed != null or+ goal_state.allDone(ctx.root.todos.items, goal_state.currentEpoch(ctx.root.goal)) or+ ctx.root.tool_calls_this_turn == 0;const gstatus: agent_mod.GoalStatus = if (ctx.root.goal) |g| g.status else .active;switch (repl_glue.continuationDecision(gstatus, model_done, loop_iters_left)) {.continue_turn => {diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex ed0aa6d8..06f56218 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -92,19 +92,16 @@ pub const ReplStreamSink = struct {}};-/// The standing-goal steering note appended to each turn when /goal is set: the-/// objective, an instruction to track it as a todo_write checklist, and the-/// current checklist render when one exists. Returns "" when goal is null so the-/// caller can skip the append. Pass todos_render="" when there are no todos — do-/// NOT pass renderTodos()'s "(no todos)" placeholder, which would leak into the prompt.-pub fn goalSteeringNote(arena: Allocator, goal: ?agent_mod.Goal, todos_render: []const u8) ![]const u8 {+/// 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.+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)- const progress: []const u8 = if (todos_render.len > 0)- try std.fmt.allocPrint(arena, "\n\nChecklist so far:\n{s}", .{todos_render})- else- "";- return std.fmt.allocPrint(arena, "[standing goal: {s} - track this as a todo_write checklist and work through it, marking each item in_progress when you start and completed when done.]{s}", .{ g.objective, progress });+ 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});}/// Extract a 0-100 score from an eval command's output: a `score` key (JSON or@@ -170,26 +167,24 @@ pub fn evalSteeringNote(, .{ state, target, gate, notes });}-test "goalSteeringNote: active-only gate + checklist assembly, no (no todos) leak" {+test "goalSteeringNote: active-only gate, completion contract, and no embedded checklist (#318)" {var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();const ar = arena.allocator();// No goal -> empty note, caller skips the append.- try std.testing.expectEqualStrings("", try goalSteeringNote(ar, null, ""));+ try std.testing.expectEqualStrings("", try goalSteeringNote(ar, null));// A paused (non-active) goal never steers (#223): empty note.- try std.testing.expectEqualStrings("", try goalSteeringNote(ar, .{ .objective = "close all issues", .status = .paused }, ""));+ try std.testing.expectEqualStrings("", try goalSteeringNote(ar, .{ .objective = "close all issues", .status = .paused }));- // Active goal, no todos -> bracket note, no checklist, and never the "(no todos)" placeholder.- const n1 = try goalSteeringNote(ar, .{ .objective = "close all issues" }, "");- try std.testing.expect(std.mem.startsWith(u8, n1, "[standing goal: close all issues - track this as a todo_write checklist"));+ // Active goal -> bracket note with the completion contract; the checklist+ // is never embedded (it reaches the model via todo_write results).+ const n1 = try goalSteeringNote(ar, .{ .objective = "close all issues" });+ try std.testing.expect(std.mem.startsWith(u8, n1, "[standing goal: close all issues - track this as a live todo_write checklist"));+ try std.testing.expect(std.mem.indexOf(u8, n1, "attempt_completion") != null);try std.testing.expect(std.mem.indexOf(u8, n1, "Checklist so far") == null);try std.testing.expect(std.mem.indexOf(u8, n1, "(no todos)") == null);-- // Active goal + live todos -> the rendered checklist is appended verbatim.- const n2 = try goalSteeringNote(ar, .{ .objective = "ship 0.0.177" }, "[x] wire steering\n[ ] add test");- try std.testing.expect(std.mem.indexOf(u8, n2, "Checklist so far:\n[x] wire steering\n[ ] add test") != null);}/// #226 continuation gate — the outcome when a /loop turn finishes: the loopdiff --git a/src/schema.zig b/src/schema.zigindex 17113ed7..8f9c0321 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -130,7 +130,7 @@ const base_specs = [_]ToolSpec{const meta_specs = [_]ToolSpec{.{.name = "todo_write",- .desc = "Replace your task list. Use to plan and track multi-step work. Each item has content and status (pending|in_progress|completed).",+ .desc = "Replace your task list. Use to plan and track multi-step work. Each item has content and status (pending|in_progress|completed). The list belongs to the current standing goal; when a goal is replaced or cleared its items are parked automatically.",.schema =\\{"type": "object", "properties": {"todos": {"type": "array", "items": {"type": "object", "properties": {"content": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]}}, "required": ["content", "status"]}}}, "required": ["todos"]},@@ -156,7 +156,7 @@ const meta_specs = [_]ToolSpec{},.{.name = "attempt_completion",- .desc = "Signal that the task is complete. Put your final answer to the user in the result field. In strict mode this is the only way to end a turn.",+ .desc = "Signal that the task is complete. Put your final answer to the user in the result field. In strict mode this is the only way to end a turn. Completing also closes the standing /goal; if its checklist still has open items you will be asked once to finish or confirm.",.schema =\\{"type": "object", "properties": {"result": {"type": "string", "description": "Final answer to present to the user"}}, "required": ["result"]},diff --git a/src/session.zig b/src/session.zigindex 9c3a0957..24038ea4 100644--- a/src/session.zig+++ b/src/session.zig@@ -15,6 +15,7 @@ const Value = std.json.Value;const Allocator = std.mem.Allocator;const agent_mod = @import("agent.zig");+const goal_state = @import("goal_state.zig");const provider_mod = @import("provider.zig");const util = @import("util.zig");const Agent = agent_mod.Agent;@@ -235,12 +236,29 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {try s.write(g.objective);try s.objectField("status");try s.write(@tagName(g.status));+ try s.objectField("epoch");+ try s.write(g.epoch);try s.objectField("created_ms");try s.write(g.created_ms);try s.objectField("updated_ms");try s.write(g.updated_ms);try s.endObject();} else try s.write(null);+ // #318: the checklist is durable, goal-scoped state - persist it with the+ // epoch that authored each item so resume cannot mix goals and checklists.+ try s.objectField("todos");+ try s.beginArray();+ for (root.todos.items) |t| {+ try s.beginObject();+ try s.objectField("content");+ try s.write(t.content);+ try s.objectField("status");+ try s.write(t.status);+ try s.objectField("epoch");+ try s.write(t.epoch);+ try s.endObject();+ }+ try s.endArray();try s.objectField("title");if (root.session_title) |title| try s.write(title) else try s.write(sessionTitle(root));try s.objectField("updated_ms");@@ -287,13 +305,57 @@ fn goalFromValue(v: Value, now_ms: i64) ?agent_mod.Goal {const txt = if (go.get("objective")) |o| (if (o == .string and o.string.len > 0) o.string else null) else null;const objective = txt orelse return null;const st: agent_mod.GoalStatus = if (go.get("status")) |s| (if (s == .string) (std.meta.stringToEnum(agent_mod.GoalStatus, s.string) orelse .active) else .active) else .active;+ const ep: u64 = if (go.get("epoch")) |e| (if (e == .integer and e.integer >= 0) @intCast(e.integer) else 0) else 0;const cms: i64 = if (go.get("created_ms")) |c| (if (c == .integer) c.integer else 0) else 0;const ums: i64 = if (go.get("updated_ms")) |u| (if (u == .integer) u.integer else 0) else 0;- return .{ .objective = objective, .status = st, .created_ms = cms, .updated_ms = ums };+ return .{ .objective = objective, .status = st, .epoch = ep, .created_ms = cms, .updated_ms = ums };}return null;}+/// Parse the persisted `todos` array (#318). The caller clears the list first+/// so nothing from a previous conversation survives a resume. Pure (no Io) so+/// it round-trips in unit tests.+fn appendTodosFromValue(arena: Allocator, todos: *std.ArrayList(agent_mod.TodoItem), v: Value) !void {+ if (v != .array) return;+ for (v.array.items) |item| {+ if (item != .object) continue;+ const content = if (item.object.get("content")) |c| (if (c == .string) c.string else continue) else continue;+ const status = if (item.object.get("status")) |s| (if (s == .string) s.string else "pending") else "pending";+ const epoch: u64 = if (item.object.get("epoch")) |e| (if (e == .integer and e.integer >= 0) @intCast(e.integer) else 0) else 0;+ try todos.append(arena, .{ .content = content, .status = status, .epoch = epoch });+ }+}++test "todos round-trip: appendTodosFromValue parses content/status/epoch, skips junk (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const parsed = try std.json.parseFromSliceLeaky(Value, a,+ \\[{"content":"wire epochs","status":"completed","epoch":2},+ \\ {"content":"add test","status":"pending","epoch":2},+ \\ {"status":"orphan, no content"}, 17]+ , .{});+ var todos: std.ArrayList(agent_mod.TodoItem) = .empty;+ try appendTodosFromValue(a, &todos, parsed);+ try std.testing.expectEqual(@as(usize, 2), todos.items.len);+ try std.testing.expectEqualStrings("wire epochs", todos.items[0].content);+ try std.testing.expectEqual(@as(u64, 2), todos.items[1].epoch);+ // Legacy sessions (no todos field / wrong type): nothing appended.+ try appendTodosFromValue(a, &todos, .null);+ try std.testing.expectEqual(@as(usize, 2), todos.items.len);+}++test "goalFromValue: epoch round-trips; legacy goals default to epoch 0 (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const v = try std.json.parseFromSliceLeaky(Value, a, "{\"objective\":\"x\",\"status\":\"active\",\"epoch\":3}", .{});+ try std.testing.expectEqual(@as(u64, 3), goalFromValue(v, 1).?.epoch);+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "\"just a string\"", .{});+ try std.testing.expectEqual(@as(u64, 0), goalFromValue(legacy, 1).?.epoch);+}+test "goalFromValue: legacy string -> active; object round-trips; paused stays paused (#223)" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();@@ -409,6 +471,11 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8root.strict = strict;root.ultracode_mode = ultracode_mode;root.goal = goal;+ root.todos.clearRetainingCapacity(); // never inherit another conversation's checklist (#318)+ if (obj.get("todos")) |tv| try appendTodosFromValue(arena, &root.todos, tv);+ if (root.goal) |*g| if (g.status == .active and goal_state.allDone(root.todos.items, g.epoch)) {+ g.status = .complete; // restored active with a finished checklist -> reconcile, don't re-run it (#318)+ };root.session_title = title;// Rebase the saved server-only delta onto today's prompt/tool-schema input.restoreContextMeter(root, saved_context_tokens, saved_local_tokens);diff --git a/src/session_run.zig b/src/session_run.zigindex 616337f2..b44d8b78 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -122,7 +122,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mtracer.note("ultracode", prompt_text[0..@min(prompt_text.len, 120)]);if (telemetry.g_telem) |t| t.ultracode();}- const goal_note = try repl_glue.goalSteeringNote(arena, root.goal, if (root.todos.items.len > 0) root.renderTodos() else "");+ const goal_note = try repl_glue.goalSteeringNote(arena, root.goal);const eval_note = try repl_glue.evalSteeringNote(arena,root.eval_cmd,