Skip to content

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

Python

refactor(goal): make the two untested goal wirings testable, and test them

Rach Pradhan1e9e1b652fe2
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 5563c00c..79caeaef 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -14,6 +14,7 @@ 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 goal_flow = @import("goal_flow.zig");
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
const ToolCall = tools_mod.ToolCall;
@@ -178,30 +179,19 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
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);
- const epoch = goal_state.nextEpoch(root.goal, root.todos.items); // above every parked epoch too, or a cleared goal's list becomes this one's (#318)
- // 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| {
+ // The whole state transition (new epoch above every parked one,
+ // adopt-or-supersede, gate + fingerprint resets) is
+ // goal_flow.applyGoalSet; this handler only reports it.
+ const res = goal_flow.applyGoalSet(root, try arena.dupe(u8, text), unixMs(root.io));
+ if (res.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);
+ root.pending_goal_note = try goal_state.supersededNote(arena, old.objective, res.parked_open);
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), kept in the session)\n", .{ old.objective, parked });
- } else {
- // 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.resetCompletionGate(root); // a new objective is new evidence for the completion double-check
+ if (res.parked_open > 0) try out.print("(superseded \"{s}\" \xe2\x80\x94 parked {d} unfinished checklist item(s), kept in the session)\n", .{ old.objective, res.parked_open });
+ } else if (root.tracer) |t| t.note("goal", "set");
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_flow.zig b/src/goal_flow.zig
index 80f0497b..5c2ca46e 100644
--- a/src/goal_flow.zig
+++ b/src/goal_flow.zig
@@ -71,6 +71,74 @@ fn capRender(arena: Allocator, rendered: []const u8) ![]const u8 {
return std.fmt.allocPrint(arena, "{s}\n[checklist truncated for the handoff - call todo_read for the full list]", .{rendered[0..cut]});
}
+pub const GoalSetResult = struct {
+ /// The live goal this one replaced, or null when there was nothing to
+ /// supersede (no goal, or one already retired). The caller prints it and
+ /// queues the supersession note.
+ superseded: ?agent_mod.Goal,
+ /// Open items that do NOT belong to the new epoch, i.e. the work that
+ /// stopped steering. Retained, never deleted (#318).
+ parked_open: usize,
+};
+
+/// The pure state transition behind `/goal <objective>` (set and replace are
+/// the same transition): the new epoch, the adopt-or-supersede choice, the
+/// goal assignment, and the gate/fingerprint resets. Printing, tracing and the
+/// session save stay with the caller, which is what makes the rules here
+/// unit-testable - the two riskiest of them had no test at all before, since
+/// they only existed inside a slash-command handler.
+/// `objective` must already be owned by the session arena. `standing` is left
+/// at its default false: a typed /goal is a task the model may complete, only
+/// the --goal flag makes an objective standing (goal_flow.standingGoalFromFlag).
+pub fn applyGoalSet(root: *Agent, objective: []const u8, now_ms: i64) GoalSetResult {
+ const epoch = goal_state.nextEpoch(root.goal, root.todos.items);
+ // 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;
+ // Formalizing an in-flight plan keeps its checklist; work parked by a
+ // finished or superseded goal stays parked and is never resurrected.
+ if (superseded == null)
+ goal_state.adoptTodos(root.todos.items, goal_state.currentEpoch(root.goal), epoch);
+ const parked_open = goal_state.parkedOpenCount(root.todos.items, epoch);
+ root.goal = .{ .objective = objective, .status = .active, .epoch = epoch, .created_ms = now_ms, .updated_ms = now_ms };
+ root.goal_note_fp = 0; // re-state the note on the next turn, not a stale-suppressed repeat
+ goal_state.resetCompletionGate(root); // a new objective is new evidence for the completion double-check
+ return .{ .superseded = superseded, .parked_open = parked_open };
+}
+
+/// The /loop controller's per-turn decision, assembled from root state. Split
+/// out of mainloop (#318) so the composition itself is testable: which turns
+/// count as work, which count as silence, and which goal status is read.
+/// work_done is the only evidence that may complete the goal and the only
+/// thing that earns `accepted` - a checklist restored from disk is not it
+/// (checklistFinished gates on this-process freshness). A zero-tool turn ends
+/// the LOOP as `idle` (codex RegularTask semantics: no /loop burns 25
+/// continuations on a one-turn prompt), but a REFUSED attempt_completion is
+/// work, not silence. A session with no goal reads as .active, so a bare /loop
+/// is governed by its work and its iteration bound alone.
+pub fn loopTurnDecision(root: *Agent, iters_left: u32) repl_glue.ContinuationDecision {
+ const work_done = root.completed != null or goal_state.checklistFinished(root);
+ const model_stopped = repl_glue.turnStopped(root.tool_calls_this_turn, root.completion_refused);
+ const gstatus: agent_mod.GoalStatus = if (root.goal) |g| g.status else .active;
+ return repl_glue.continuationDecision(gstatus, work_done, model_stopped, iters_left);
+}
+
+/// The goal-side effect of a /loop run that stopped as `accepted`: the loop
+/// drove the objective to done, so it retires. Returns true when it flipped.
+/// A standing --goal is the user's policy for the whole session and outlives
+/// any single completion (#318); a paused or already-complete goal is not the
+/// loop's to change either.
+pub fn acceptLoopOutcome(root: *Agent) bool {
+ if (root.goal) |*g| {
+ if (g.status == .active and !g.standing) {
+ g.status = .complete;
+ return true;
+ }
+ }
+ return false;
+}
+
/// A root agent in the shape the goal helpers read; no live turn behind it.
fn flowRoot(arena: Allocator) Agent {
var root: Agent = undefined;
diff --git a/src/goal_persist_tests.zig b/src/goal_persist_tests.zig
index 289603f9..2823ed56 100644
--- a/src/goal_persist_tests.zig
+++ b/src/goal_persist_tests.zig
@@ -12,6 +12,8 @@ const Allocator = std.mem.Allocator;
const agent_mod = @import("agent.zig");
const session = @import("session.zig");
const goal_state = @import("goal_state.zig");
+const goal_flow = @import("goal_flow.zig");
+const repl_glue = @import("repl_glue.zig");
const Agent = agent_mod.Agent;
/// Restore `json` onto `root` the way loadSession does (session.zig): parse the
@@ -30,6 +32,9 @@ fn resumeSession(arena: Allocator, root: *Agent, json: []const u8) !void {
}
/// A root agent in the state loadSession hands back: no live turn behind it.
+/// The turn-scoped fields matter too - goal_flow.loopTurnDecision reads them
+/// to decide whether a /loop continues, and "restored, no work yet" is exactly
+/// the state #318's never-completing loop started from.
fn blankRoot(arena: Allocator) Agent {
var root: Agent = undefined;
root.arena = arena;
@@ -39,6 +44,10 @@ fn blankRoot(arena: Allocator) Agent {
root.goal = null;
root.todos_dirty = false;
root.completion_gate_armed = false;
+ root.completion_refused = false;
+ root.completed = null;
+ root.tool_calls_this_turn = 0;
+ root.goal_note_fp = 0;
return root;
}
@@ -220,3 +229,148 @@ test "resume: a paused or already-complete goal is restored verbatim (#318)" {
try std.testing.expectEqual(@as(u64, 0), goal_state.currentEpoch(root2.goal)); // dead epoch: later writes are unscoped
try std.testing.expectEqualStrings("", goal_state.renderCurrent(&root2));
}
+
+test "/goal over live work supersedes it and never inherits its checklist (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ try resumeSession(ar, &root,
+ \\{"goal":{"objective":"ship phase 2","status":"active","epoch":2,"created_ms":1,"updated_ms":2},
+ \\ "todos":[{"content":"fix the tests","status":"completed","epoch":2},
+ \\ {"content":"verify in the browser","status":"pending","epoch":2},
+ \\ {"content":"parked earlier","status":"pending","epoch":1}]}
+ );
+ root.completion_gate_armed = true; // a refusal the old objective was still answering
+
+ const res = goal_flow.applyGoalSet(&root, "ship phase 3", 5_000);
+ try std.testing.expect(res.superseded != null);
+ try std.testing.expectEqualStrings("ship phase 2", res.superseded.?.objective);
+ try std.testing.expectEqual(@as(usize, 2), res.parked_open); // both open items stopped steering
+ try std.testing.expectEqual(@as(u64, 3), root.goal.?.epoch); // above the live goal AND every parked epoch
+ try std.testing.expect(!root.goal.?.standing); // a typed /goal is retirable; only --goal is standing
+ try std.testing.expect(!root.completion_gate_armed); // new objective, new evidence for the double-check
+ try std.testing.expectEqual(@as(u64, 0), root.goal_note_fp); // and the note re-states next turn
+ // The new objective starts with no plan of its own, and nothing was deleted.
+ try std.testing.expectEqualStrings("", goal_state.renderCurrent(&root));
+ try std.testing.expectEqual(@as(usize, 3), root.todos.items.len);
+}
+
+test "/goal over a retired goal adopts only its OPEN current items (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ // A goal that already completed is not live work, so the next /goal is not
+ // superseding anything - it takes the adoption branch, like a first /goal.
+ // But a COMPLETE goal's epoch is dead (currentEpoch 0), so there is nothing
+ // current to adopt and its finished list stays parked where it is.
+ try resumeSession(ar, &root,
+ \\{"goal":{"objective":"ship phase 2","status":"complete","epoch":2,"created_ms":1,"updated_ms":2},
+ \\ "todos":[{"content":"fix the tests","status":"completed","epoch":2},
+ \\ {"content":"leftover","status":"pending","epoch":2}]}
+ );
+ const res = goal_flow.applyGoalSet(&root, "ship phase 3", 5_000);
+ try std.testing.expect(res.superseded == null); // nothing live was replaced
+ try std.testing.expectEqual(@as(u64, 3), root.goal.?.epoch);
+ try std.testing.expect(!goal_state.hasCurrent(root.todos.items, 3));
+ try std.testing.expectEqual(@as(usize, 1), goal_state.parkedOpenCount(root.todos.items, 3));
+ // Born with no checklist, so completion is gated rather than free (#318).
+ const refusal = try goal_state.completionGate(ar, &root);
+ try std.testing.expect(refusal != null and std.mem.indexOf(u8, refusal.?, "no checklist") != null);
+}
+
+test "the first /goal adopts the in-flight unscoped plan, minus finished work (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ // The model planned before the user named the objective: an epoch-0 list.
+ // Formalizing it should keep the OPEN items (the plan the /goal serves) and
+ // leave the completed ones parked - carrying those in made the fresh goal
+ // born "done": openCount 0 with a checklist present, so the double-check's
+ // confirm-once arm was skipped and completion was free before any work.
+ try root.todos.append(ar, .{ .content = "already done", .status = "completed", .epoch = 0 });
+ try root.todos.append(ar, .{ .content = "still open", .status = "in_progress", .epoch = 0 });
+ const res = goal_flow.applyGoalSet(&root, "make the tests pass", 5_000);
+ try std.testing.expect(res.superseded == null);
+ try std.testing.expectEqual(@as(u64, 1), root.goal.?.epoch);
+ try std.testing.expectEqualStrings("[~] still open", goal_state.renderCurrent(&root));
+ try std.testing.expectEqual(@as(usize, 1), goal_state.openCount(root.todos.items, 1));
+ try std.testing.expectEqual(@as(u64, 0), root.todos.items[0].epoch); // the finished item parked
+ const refusal = try goal_state.completionGate(ar, &root);
+ try std.testing.expect(refusal != null and std.mem.indexOf(u8, refusal.?, "1 open") != null);
+}
+
+test "/loop: a restored all-[x] list is idle, not accepted (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ // A standing --goal survives the resume with its finished checklist intact
+ // (reconcileRestored leaves it alone), so this is the exact state a fresh
+ // /loop starts from: goal active, every item [x], zero tools run yet. It
+ // used to stop at iteration 1 as `accepted` with nothing done.
+ try resumeSession(ar, &root,
+ \\{"goal":{"objective":"keep the tree green","status":"active","epoch":2,"standing":true,"created_ms":1,"updated_ms":2},
+ \\ "todos":[{"content":"fix the tests","status":"completed","epoch":2}]}
+ );
+ try std.testing.expect(goal_state.allDone(root.todos.items, 2));
+ try std.testing.expect(!root.todos_dirty); // the freshness flag is what saves it
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25).stop);
+ try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status); // and nothing was retired
+}
+
+test "/loop: a finished list accepts and retires only a retirable goal (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1 };
+ try root.todos.append(ar, .{ .content = "fix the tests", .status = "completed", .epoch = 1 });
+ goal_state.noteTodoWrite(&root); // THIS process finished the list: real evidence
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25).stop);
+ try std.testing.expect(goal_flow.acceptLoopOutcome(&root));
+ try std.testing.expectEqual(agent_mod.GoalStatus.complete, root.goal.?.status);
+
+ // A paused goal is the user stepping in, and a standing --goal is their
+ // policy for the whole session: the loop still stops as accepted, but
+ // neither objective is the loop's to retire (#318).
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1, .status = .paused };
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25).stop);
+ try std.testing.expect(!goal_flow.acceptLoopOutcome(&root));
+ try std.testing.expectEqual(agent_mod.GoalStatus.paused, root.goal.?.status);
+ root.goal = .{ .objective = "keep the tree green", .epoch = 1, .standing = true };
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25).stop);
+ try std.testing.expect(!goal_flow.acceptLoopOutcome(&root));
+ try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);
+}
+
+test "/loop: a refused completion is work, and a leftover complete goal decides nothing (#318)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var root = blankRoot(ar);
+ root.goal = .{ .objective = "ship phase 2", .epoch = 1 };
+ try root.todos.append(ar, .{ .content = "verify in the browser", .status = "pending", .epoch = 1 });
+ // The completion gate refused: the model called attempt_completion (which
+ // is exempt from the tool counter) and got an is_error back to react to.
+ // Reading that as silence killed the /loop on the very turn the gate meant
+ // to keep alive, so the promised second call could never happen (#318).
+ goal_state.noteCompletionRefused(&root);
+ try std.testing.expectEqual(@as(u64, 0), root.tool_calls_this_turn);
+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25)) == .continue_turn);
+ // Genuine silence on the same state does stop the loop.
+ root.completion_refused = false;
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25).stop);
+
+ // A goal left .complete by an earlier run or a resume reconciliation must
+ // not label a fresh /loop `accepted` at iteration 1 before anything has
+ // happened: it decides nothing, exactly like .active.
+ root.goal.?.status = .complete;
+ root.tool_calls_this_turn = 3;
+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25)) == .continue_turn);
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.exhausted, goal_flow.loopTurnDecision(&root, 0).stop);
+ root.tool_calls_this_turn = 0;
+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25).stop);
+}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index c5fdc470..b514d7e9 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -24,6 +24,7 @@ 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 goal_flow = @import("goal_flow.zig");
const eval_memory = @import("eval_memory.zig");
const mainloop_score = @import("mainloop_score.zig");
const mainloop_trace = @import("mainloop_trace.zig");
@@ -561,16 +562,7 @@ 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
- // work_done: the model asserted completion or finished the checklist
- // - 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 or
- goal_state.checklistFinished(ctx.root); // a checklist restored from disk is not evidence (#318)
- 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, work_done, model_stopped, loop_iters_left)) {
+ switch (goal_flow.loopTurnDecision(ctx.root, loop_iters_left)) {
.continue_turn => {
loop_iters_left -= 1; // consume one credit for the queued continuation
loop_continue_armed = true;
@@ -578,9 +570,9 @@ pub fn run(ctx: *Ctx) !void {
.stop => |outcome| {
loop_iters_left = 0;
loop_continue_armed = false;
- if (outcome == .accepted and work_done) if (ctx.root.goal) |*g| {
- if (g.status == .active and !g.standing) g.status = .complete; // the loop drove the goal to done; a --goal standing objective outlives it (#318)
- };
+ // Only work_done reaches `accepted`, so the loop drove the
+ // goal to done; a --goal standing objective outlives it (#318).
+ if (outcome == .accepted) _ = goal_flow.acceptLoopOutcome(ctx.root);
try ctx.out.print("{s}↩ /loop stopped — {s}{s}\n", .{ style.dim, @tagName(outcome), style.reset });
try ctx.out.flush();
},