graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(goal): harden the epoch fix per adversarial review
justrachd6876e372276
diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex ba7b9f34..53826ab7 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -166,6 +166,7 @@ pub fn compact(self: *Agent) anyerror!usize {self.messages = fresh;self.last_context_tokens = 0;self.context_local_tokens = 0;+ self.goal_note_fp = 0; // the injected goal note died with the old history - re-state in full (#318)installed_summary = true;if (!main_mod.json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});return summary.len;@@ -390,6 +391,7 @@ pub fn emergencyTrim(self: *Agent) usize {var fresh = std.json.Array.init(self.arena);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)const after_tokens = self.fullInputEstimateTokens();accountForReclaimedTokens(self, before_tokens -| after_tokens);return cut;diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 56ae573c..0b5b48b4 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -289,15 +289,13 @@ 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 };+ if (try goal_state.completionGate(self.arena, self)) |refusal| {+ self.completion_gate_armed = true; // an explicit second call this turn closes anyway+ 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_active) {+ if (goal_state.goalActive(self)) {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");diff --git a/src/commands_model.zig b/src/commands_model.zigindex be4b6b62..8c0bae96 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -280,6 +280,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.last_context_tokens = 0;root.context_local_tokens = 0;root.compact_transport_failures = 0;+ root.goal_note_fp = 0; // the goal note may have been in the dropped turns (#318)// Restore files written/edited during the rewound turns, and re-point the// turn counter so the next prompt re-takes turn n.var restored: usize = 0;diff --git a/src/commands_session.zig b/src/commands_session.zigindex 494eb54a..b8b0b5cc 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -139,6 +139,13 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,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")) {+ if (root.goal == null) {+ // Nothing to clear: leave an unscoped (epoch-0) working checklist+ // alone rather than destroying it and steering about a phantom goal.+ try out.writeAll("No active goal. Set one with /goal <objective>.\n");+ try out.flush();+ 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)diff --git a/src/goal_state.zig b/src/goal_state.zigindex 6e105172..d328a622 100644--- a/src/goal_state.zig+++ b/src/goal_state.zig@@ -103,17 +103,36 @@ pub fn applyGoalSteering(arena: Allocator, root: *Agent, base: []const u8) ![]coreturn msg;}-pub const CompletionAction = enum { accept, refuse_open_checklist };+/// Root-only, non-review: does this agent carry an active standing goal?+/// Review turns and subagents share the root Agent struct but not its goal,+/// so they must never gate on it or complete it.+pub fn goalActive(agent: *Agent) bool {+ return !agent.sub and !agent.review_mode and agent.goal != null and agent.goal.?.status == .active;+}++/// True when any todo belongs to `epoch` (the goal has a checklist at all).+pub fn hasCurrent(todos: []const TodoItem, epoch: u64) bool {+ for (todos) |t| if (t.epoch == epoch) return true;+ return false;+}-/// 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;+/// 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.+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 (!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 null; // nonempty checklist, every item completed}-/// The refusal text for completionDecision's .refuse_open_checklist arm.+/// 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 });}@@ -214,11 +233,35 @@ test "steeringGate: inject on change, suppress repeats, refresh after the intervtry 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 "completionGate: open list refused once, no-checklist needs confirm, done list accepts, review exempt (#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.goal = .{ .objective = "ship", .epoch = 1 };+ // No checklist yet: first call must confirm; an armed second call closes.+ const r1 = try completionGate(ar, &root);+ try std.testing.expect(r1 != null and std.mem.indexOf(u8, r1.?, "no checklist") != null);+ root.completion_gate_armed = true;+ try std.testing.expect((try completionGate(ar, &root)) == null);+ // Open current-epoch item: refused with the count.+ root.completion_gate_armed = false;+ try root.todos.append(ar, .{ .content = "a", .status = "pending", .epoch = 1 });+ const r2 = try completionGate(ar, &root);+ try std.testing.expect(r2 != null and std.mem.indexOf(u8, r2.?, "1 open") != null);+ // Fully completed checklist: accepted immediately.+ root.todos.items[0].status = "completed";+ try std.testing.expect((try completionGate(ar, &root)) == null);+ // Review turns never gate (isolated reviews share the root Agent).+ root.review_mode = true;+ root.todos.items[0].status = "pending";+ try std.testing.expect((try completionGate(ar, &root)) == null);+ try std.testing.expect(!goalActive(&root));}test "applyGoalSteering: injects once, suppresses repeats, consumes the one-shot note" {diff --git a/src/mainloop.zig b/src/mainloop.zigindex de088630..0ab3dcad 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -549,7 +549,6 @@ 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-@@ -562,13 +561,14 @@ 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- // 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;+ // 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.+ const work_done = ctx.root.completed != null or+ goal_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 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 => {@@ -578,7 +578,7 @@ pub fn run(ctx: *Ctx) !void {.stop => |outcome| {loop_iters_left = 0;loop_continue_armed = false;- if (outcome == .accepted) if (ctx.root.goal) |*g| {+ if (outcome == .accepted and work_done) if (ctx.root.goal) |*g| {if (g.status == .active) g.status = .complete; // the loop drove the goal to done};try ctx.out.print("{s}↩ /loop stopped — {s}{s}\n", .{ style.dim, @tagName(outcome), style.reset });diff --git a/src/session.zig b/src/session.zigindex 24038ea4..fd8f44ac 100644--- a/src/session.zig+++ b/src/session.zig@@ -15,7 +15,6 @@ 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;@@ -473,9 +472,11 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8root.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)- };+ // Steering gate state belongs to the previous conversation (#318): drop any+ // queued one-shot note and force a full goal-note re-statement next turn.+ root.pending_goal_note = null;+ root.goal_note_fp = 0;+ root.goal_note_age = 0;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);