graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(goal): gate a standing goal's claims; keep its checklist across resumes
Rach Pradhanddfdeaf3dd86
diff --git a/README.md b/README.mdindex 12ac000f..148a934c 100644--- a/README.md+++ b/README.md@@ -488,10 +488,11 @@ session. See [Permission modes](#permission-modes).`/goal pause` stops the steering without losing the objective, `/goal resume`turns it back on, and `/goal status` shows the objective and its current state.`/loop <prompt>` works autonomously toward the prompt, running turn after turn-(plan, act, verify) and stopping on its own with a named outcome (accepted,-idle, blocked, cancelled, or exhausted) once the work is done, the model stops-making tool progress without claiming completion (idle), you step in, or a-safety limit is hit, instead of pausing for confirmation between routine steps.+(plan, act, verify) instead of pausing for confirmation between routine steps,+and stops on its own with a named outcome: accepted once the work is done, idle+when the model stops making tool progress without claiming completion, cancelled+or blocked when you step in or it needs you, and exhausted when a safety limit+is hit.`/review <target or instructions>` is the deliberately narrower path for codereview: it suppresses goal/eval/ultracode steering, admits only localread/search tools and read-only shell inspection, and runs with freshdiff --git a/src/agent.zig b/src/agent.zigindex 4b0ffe67..a47077dc 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -136,6 +136,8 @@ pub const Agent = struct {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)todos_dirty: bool = false, // todo_write ran in THIS process: a checklist restored from disk is persisted state, never evidence that the current prompt is done (#318)+ goal_flag: ?[]const u8 = null, // --goal objective verbatim: re-applied over EVERY loadSession, including /resume, so the flag's contract survives restores (#318)+ history_rewrites: u32 = 0, // bumped by compact()/emergencyTrim; state pasted into the dead history (e.g. the /loop checklist copy) must be re-carried (#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_compact.zig b/src/agent_compact.zigindex 6b34eccc..d8f6a4b2 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -160,6 +160,7 @@ pub fn compact(self: *Agent) anyerror!usize {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)+ self.history_rewrites +%= 1; // readers of pasted state (the /loop checklist gate) re-carry it (#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;@@ -406,6 +407,7 @@ pub fn emergencyTrim(self: *Agent) usize {for (self.messages.items[cut..]) |m| fresh.append(m) catch return 0;self.messages = fresh;self.goal_note_fp = 0; // trimmed history may have carried the goal note (#318)+ self.history_rewrites +%= 1; // and the /loop checklist gate's pasted copies (#318)// No synthetic message exists here to hang the standing state on (unlike// compact()'s handoff), so it rides the next turn's one-shot slot. Only// when that slot is free: a queued /goal replace|clear note is the USER'sdiff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 30bbda0f..eb1e0dcb 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -28,6 +28,7 @@ const ansi = @import("ansi.zig");const style = &ansi.style;const goal_state = @import("goal_state.zig");+const goal_flow = @import("goal_flow.zig");const jobs = @import("jobs.zig");const subagent = @import("subagent.zig"); // #276 P0-3: g_agent_jobs, for /jobs@@ -467,6 +468,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;};root.session_name = name;+ // The third restore path (#318): --goal outranks the restored goal here+ // too, idempotently, or /resume was the one door that silently dropped it.+ if (root.goal_flag) |g| root.pending_goal_note = goal_flow.reapplyFlagGoal(arena, root, g, util.unixMs(root.io)) catch null;try out.print("resumed {s}{s} — {d} message(s), {s} via {s}{s}\n", .{name, session_ext, root.messages.items.len, root.provider.model, root.provider.id,if (root.strict) " (strict)" else "",diff --git a/src/goal_flow.zig b/src/goal_flow.zigindex 2807830e..8aba6fa0 100644--- a/src/goal_flow.zig+++ b/src/goal_flow.zig@@ -15,23 +15,44 @@ const Agent = agent_mod.Agent;const TodoItem = agent_mod.TodoItem;/// The Goal `--goal <text>` seeds: a STANDING objective (the flag's documented-/// contract is "every turn, incl. --json/-p/SDK"), stamped above every epoch-/// already present in `todos` so a resumed session's parked checklist can never-/// become its work, and so it never aliases the epoch-0 no-goal bucket (#318).-/// `objective` must already be owned by the session arena. Also used to-/// RE-apply the flag after a resume: loadSession overwrites root.goal with the-/// goal from disk, so `graff -r <session> --goal X` silently dropped X.-pub fn standingGoalFromFlag(objective: []const u8, todos: []const TodoItem, now_ms: i64) agent_mod.Goal {+/// contract is "every turn, incl. --json/-p/SDK"), stamped above `old` (the+/// goal it displaces, if any) and every epoch already present in `todos`, so a+/// resumed session's parked checklist can never become its work and it never+/// aliases the epoch-0 no-goal bucket (#318).+/// `objective` must already be owned by the session arena. Re-application over+/// a loadSession goes through reapplyFlagGoal, which keeps the same objective's+/// goal instead of re-minting it.+pub fn standingGoalFromFlag(objective: []const u8, old: ?agent_mod.Goal, todos: []const TodoItem, now_ms: i64) agent_mod.Goal {return .{.objective = objective,.status = .active,.standing = true,- .epoch = goal_state.nextEpoch(null, todos),+ .epoch = goal_state.nextEpoch(old, todos),.created_ms = now_ms,.updated_ms = now_ms,};}+/// Re-apply the --goal flag over whatever loadSession restored (#318). The flag+/// wins, but idempotently: resuming the SAME standing objective keeps the+/// restored goal - epoch, checklist and timestamps - instead of minting a new+/// epoch and parking the objective's own work on every restart. A different+/// restored goal is displaced like any supersession; when it was live with open+/// items the returned note must be queued (pending_goal_note, always null right+/// after a load) so neither the model nor the user loses the boundary silently.+pub fn reapplyFlagGoal(arena: Allocator, root: *Agent, objective: []const u8, now_ms: i64) !?[]const u8 {+ if (root.goal) |g| if (g.standing and std.mem.eql(u8, g.objective, objective)) return null;+ const displaced: ?agent_mod.Goal = if (root.goal) |old| (if (old.status == .complete) null else old) else null;+ root.goal = standingGoalFromFlag(objective, root.goal, root.todos.items, now_ms);+ root.goal_note_fp = 0; // re-state the (now standing) note on the next turn+ goal_state.resetCompletionGate(root); // a new objective is fresh evidence for the double-check+ if (displaced) |old| {+ const parked = goal_state.parkedOpenCount(root.todos.items, root.goal.?.epoch);+ if (parked > 0) return try goal_state.supersededNote(arena, old.objective, parked);+ }+ return null;+}+/// The checklist render carried into a compaction handoff is capped here: a/// pathological 200-item list must never eat the very context the compaction/// was run to reclaim. Over the cap the render is cut at a line boundary and@@ -57,9 +78,9 @@ pub fn compactionSnapshot(arena: Allocator, root: *Agent) !?[]const u8 {const objective = root.goal.?.objective;const rendered = goal_state.renderCurrent(root);if (rendered.len == 0)- return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives compaction): goal: {s}. No checklist has been written for it yet - plan the work with todo_write, and read the list back with todo_read at any time.]", .{objective});+ return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives context rewrites): goal: {s}. No checklist has been written for it yet - plan the work with todo_write, and read the list back with todo_read at any time.]", .{objective});const open = goal_state.openCount(root.todos.items, goal_state.currentEpoch(root.goal));- return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives compaction): goal: {s}. Checklist ({d} open):\n{s}\nThis list is live harness state, read it back with todo_read at any time. todo_write REPLACES the current goal's whole list, so include already-completed items when rewriting.]", .{ objective, open, try capRender(arena, rendered) });+ return try std.fmt.allocPrint(arena, "[standing state (harness-kept, survives context rewrites): goal: {s}. Checklist ({d} open):\n{s}\nThis list is live harness state, read it back with todo_read at any time. todo_write REPLACES the current goal's whole list, so include already-completed items when rewriting.]", .{ objective, open, try capRender(arena, rendered) });}/// Cut an oversized checklist render at a line boundary (never mid-item, never@@ -152,18 +173,28 @@ pub fn continuationSteeringNote(arena: Allocator, todos_render: []const u8, pastpub const LoopListGate = struct {fp: u64 = 0,age: u32 = 0,+ rewrites_seen: u32 = 0,pub fn reset(self: *LoopListGate) void {self.* = .{};}/// This continuation turn's steering note, pasting the render only when the- /// model has not just been handed the same list.- pub fn note(self: *LoopListGate, arena: Allocator, todos_render: []const u8) ![]const u8 {- const gate = goal_state.steeringGate(todos_render, self.fp, self.age, goal_state.refresh_turns);+ /// model has not just been handed the same list. A history rewrite+ /// (root.history_rewrites: compaction or emergency trim) kills every copy+ /// already pasted - including MID-turn, where mainloop's post-turn hook+ /// never fires because the meter is already back under the window - so the+ /// first continuation after one re-carries the list in full.+ pub fn note(self: *LoopListGate, arena: Allocator, root: *Agent) ![]const u8 {+ if (root.history_rewrites != self.rewrites_seen) {+ self.reset();+ self.rewrites_seen = root.history_rewrites;+ }+ const rendered = goal_state.renderCurrent(root);+ const gate = goal_state.steeringGate(rendered, self.fp, self.age, goal_state.refresh_turns);self.fp = gate.fp;self.age = gate.age;- return continuationSteeringNote(arena, todos_render, gate.inject);+ return continuationSteeringNote(arena, rendered, gate.inject);}};@@ -194,6 +225,9 @@ fn flowRoot(arena: Allocator) Agent {root.completion_gate_armed = false;root.completion_refused = false;root.completed = null;+ root.goal_note_fp = 0;+ root.pending_goal_note = null;+ root.history_rewrites = 0;return root;}@@ -202,27 +236,34 @@ test "a --goal standing objective outlives the model's own completion (#318)" {defer arena_state.deinit();const ar = arena_state.allocator();var root = flowRoot(ar);- root.goal = standingGoalFromFlag("keep the tree green", root.todos.items, 7);+ root.goal = standingGoalFromFlag("keep the tree green", null, root.todos.items, 7);try std.testing.expect(root.goal.?.standing);try std.testing.expectEqual(@as(u64, 1), root.goal.?.epoch); // never epoch 0: that bucket is the no-goal one- // The gate never fires for it: there is no close event to double-check, so- // the arm never arms and open work never produces a refusal either.- try std.testing.expect((try goal_state.completionGate(ar, &root)) == null);- try root.todos.append(ar, .{ .content = "an open item", .status = "pending", .epoch = 1 });- try std.testing.expect((try goal_state.completionGate(ar, &root)) == null);- try std.testing.expect(!root.completion_gate_armed);-- // attempt_completion: the result is recorded (the handler does that above- // the branch), but the objective stays active and keeps steering. Before- // this, one attempt_completion left every later turn of a headless/SDK- // session unsteered - and the note itself coached the model into making it.+ // The completion CLAIM is double-checked exactly like a /goal objective:+ // an unearned "done" is worst in the flag's own headless sessions, where it+ // ended a /loop as accepted with open work. Only RETIREMENT is exempt.+ const r1 = try goal_state.completionGate(ar, &root);+ try std.testing.expect(r1 != null and std.mem.indexOf(u8, r1.?, "no checklist") != null);+ try std.testing.expect(std.mem.indexOf(u8, r1.?, "keeps steering") != null); // the refusal never promises a close+ goal_state.noteCompletionRefused(&root);+ try std.testing.expect((try goal_state.completionGate(ar, &root)) == null); // the promised second call is accepted...++ // ...and the accepted claim is recorded, but the objective stays active and+ // keeps steering. Before this, one attempt_completion left every later turn+ // of a headless/SDK session unsteered.root.completed = "shipped the first task";try std.testing.expect(!goal_state.retireOnCompletion(&root, 99));try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);try std.testing.expect(root.completed != null);try std.testing.expect(goal_state.goalActive(&root));+ // Open work refuses with the standing consequence: the items stay active.+ goal_state.resetCompletionGate(&root);+ try root.todos.append(ar, .{ .content = "an open item", .status = "pending", .epoch = 1 });+ const r2 = try goal_state.completionGate(ar, &root);+ try std.testing.expect(r2 != null and std.mem.indexOf(u8, r2.?, "stay active") != null);+// A /goal-typed objective is unchanged: it still retires on completion.root.goal = .{ .objective = "ship phase 2", .epoch = 1 };try std.testing.expect(goal_state.retireOnCompletion(&root, 99));@@ -238,7 +279,7 @@ test "resume never auto-retires a standing goal over a finished checklist (#318)// A restored session whose --goal checklist is all done. reconcileRestored// retires a /goal objective here (the model finished and quit), but a// standing one is the user's policy for the session, not a task that ended.- root.goal = standingGoalFromFlag("keep the tree green", root.todos.items, 7);+ root.goal = standingGoalFromFlag("keep the tree green", null, root.todos.items, 7);try root.todos.append(ar, .{ .content = "done", .status = "completed", .epoch = 1 });try std.testing.expect(goal_state.allDone(root.todos.items, 1));try std.testing.expect(!goal_state.reconcileRestored(&root));@@ -260,7 +301,7 @@ test "--goal seeded onto a resumed session lands above every restored epoch (#31// instantly its "finished checklist" and completion was free.try root.todos.append(ar, .{ .content = "old unscoped work", .status = "completed", .epoch = 0 });try root.todos.append(ar, .{ .content = "parked", .status = "pending", .epoch = 3 });- root.goal = standingGoalFromFlag("keep the tree green", root.todos.items, 7);+ root.goal = standingGoalFromFlag("keep the tree green", null, root.todos.items, 7);try std.testing.expectEqual(@as(u64, 4), root.goal.?.epoch);try std.testing.expectEqual(@as(u64, 4), goal_state.currentEpoch(root.goal));try std.testing.expect(!goal_state.hasCurrent(root.todos.items, 4));@@ -451,26 +492,74 @@ test "LoopListGate pastes the checklist once per change, not once per turn (#318var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const ar = arena_state.allocator();+ var root = flowRoot(ar);+ root.goal = .{ .objective = "ship", .epoch = 1 };+ try root.todos.append(ar, .{ .content = "a", .status = "pending", .epoch = 1 });+ try root.todos.append(ar, .{ .content = "b", .status = "pending", .epoch = 1 });var gate: LoopListGate = .{};// Turn 1 of a run carries the list; the next turns do not, so a 25-turn// /loop no longer writes 25 near-identical copies into root.messages (all// autosaved, and all fed verbatim into the next compaction's summary).- try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, "[ ] a\n[ ] b"), "[ ] a") != null);+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[ ] a") != null);var i: usize = 0;while (i < 3) : (i += 1)- try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, "[ ] a\n[ ] b"), "[ ] a") == null);+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[ ] a") == null);// A real change to the list is carried immediately.- try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, "[x] a\n[ ] b"), "[x] a") != null);+ root.todos.items[0].status = "completed";+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[x] a") != null);// An unchanged list is re-stated after the refresh interval, in case it// aged out of the model's effective attention.i = 0;var restated = false;while (i < goal_state.refresh_turns) : (i += 1)- restated = restated or std.mem.indexOf(u8, try gate.note(ar, "[x] a\n[ ] b"), "[x] a") != null;+ restated = restated or std.mem.indexOf(u8, try gate.note(ar, &root), "[x] a") != null;try std.testing.expect(restated);- // reset() is what a fresh run, a user steer, a stop and a compaction do:- // the very next continuation carries the list in full again.+ // A history rewrite (compaction or emergency trim, possibly MID-turn where+ // no post-turn hook fires) destroyed every pasted copy: the next+ // continuation re-carries the list in full, then gates again.+ _ = try gate.note(ar, &root); // settle into suppression+ root.history_rewrites += 1;+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[x] a") != null);+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[x] a") == null);+ // reset() is what a fresh run, a user steer and a stop do: the very next+ // continuation carries the list in full again.gate.reset();- try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, "[x] a\n[ ] b"), "[x] a") != null);+ try std.testing.expect(std.mem.indexOf(u8, try gate.note(ar, &root), "[x] a") != null);+}++test "re-applying --goal on resume keeps the same objective's own checklist (#318)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = flowRoot(ar);+ // Run 1 of `graff -r sess --goal X` wrote a checklist under the standing+ // goal. Run 2 of the IDENTICAL command must find that work, not park it:+ // re-minting an epoch on every restart orphaned the objective's own list.+ root.goal = standingGoalFromFlag("keep the tree green", null, root.todos.items, 7);+ try root.todos.append(ar, .{ .content = "a", .status = "completed", .epoch = 1 });+ try root.todos.append(ar, .{ .content = "b", .status = "pending", .epoch = 1 });+ try std.testing.expect((try reapplyFlagGoal(ar, &root, "keep the tree green", 9)) == null);+ try std.testing.expectEqual(@as(u64, 1), root.goal.?.epoch);+ try std.testing.expectEqual(@as(i64, 7), root.goal.?.created_ms); // the restored goal, not a re-mint+ try std.testing.expectEqualStrings("[x] a\n[ ] b", goal_state.renderCurrent(&root));++ // A DIFFERENT flag objective displaces a live restored /goal like any+ // supersession: new standing goal above every epoch, and the note reports+ // the parked work so the model does not silently continue it.+ root.goal = .{ .objective = "ship phase 2", .epoch = 1, .status = .active };+ root.completion_gate_armed = true; // a stale arm must not survive the boundary+ const note = try reapplyFlagGoal(ar, &root, "keep master green", 11);+ try std.testing.expect(note != null and std.mem.indexOf(u8, note.?, "ship phase 2") != null);+ try std.testing.expect(root.goal.?.standing);+ try std.testing.expectEqual(@as(u64, 2), root.goal.?.epoch);+ try std.testing.expect(!root.completion_gate_armed);+ try std.testing.expectEqual(@as(usize, 1), goal_state.parkedOpenCount(root.todos.items, 2)); // b parked, never adopted++ // Displacing an already-complete goal queues nothing: its work already+ // parked when it retired, so there is no live boundary to announce.+ root.goal.?.standing = false;+ root.goal.?.status = .complete;+ try std.testing.expect((try reapplyFlagGoal(ar, &root, "keep the tree green", 12)) == null);+ try std.testing.expect(root.goal.?.standing and root.goal.?.status == .active);}diff --git a/src/goal_state.zig b/src/goal_state.zigindex a36236cb..ad03a3c8 100644--- a/src/goal_state.zig+++ b/src/goal_state.zig@@ -234,24 +234,37 @@ pub fn hasCurrent(todos: []const TodoItem, epoch: u64) bool {/// 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) persists until the-/// checklist or the goal changes, so the promised "call it again" closes the goal+/// checklist or the goal changes, so the promised "call it again" is honored/// 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.+/// A standing --goal is gated like any other goal (#318: an unearned "done" is+/// exactly what the flag's headless sessions need double-checked - exempting+/// them here let one premature claim end a /loop as accepted with open work);+/// standing only exempts RETIREMENT (retireOnCompletion), so a confirmed claim+/// is recorded and the objective keeps steering.pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {if (!goalActive(agent)) return null;- if (agent.goal.?.standing) return null; // a standing --goal has no close event to gate: the arm never arms for it (#318)if (agent.completion_gate_armed) return null;+ const standing = agent.goal.?.standing;const epoch = currentEpoch(agent.goal);const open = openCount(agent.todos.items, epoch);- if (open > 0) return try completionRefusalText(arena, open, renderTodos(agent, epoch));- if (!hasCurrent(agent.todos.items, epoch))+ if (open > 0) return try completionRefusalText(arena, open, renderTodos(agent, epoch), standing);+ if (!hasCurrent(agent.todos.items, epoch)) {+ if (standing) return "completion deferred: the standing goal has no checklist yet, so there is no evidence this task is done. If it truly is, call attempt_completion again - now or on a later turn - to record it (the standing objective keeps steering either way); 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 - 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 });+/// The refusal text for completionGate's open-checklist arm. The second-call+/// consequence differs (#318): a /goal objective closes and parks its open+/// items; a standing --goal records the completion and stays active.+pub fn completionRefusalText(arena: Allocator, open: usize, rendered: []const u8, standing: bool) ![]const u8 {+ const consequence = if (standing)+ "to record completion anyway; the standing objective and its open items stay active"+ else+ "to close the goal anyway; the open items are then parked (kept in the session, no longer steering)";+ 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 - {s}.", .{ open, rendered, consequence });}/// One-shot note for the turn after /goal replaced an active goal — portsdiff --git a/src/mainloop.zig b/src/mainloop.zigindex 0f861242..418587ee 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -96,10 +96,10 @@ 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 = goal_state.renderCurrent(ctx.root); // current epoch only: parked work never re-enters a /loop turn (#318)// Gated: these prompts persist in root.messages, autosave, and are- // compaction input, so the list is pasted only when it changed (#318).- const note = try loop_list.note(ctx.arena, todos_render);+ // compaction input, so the current epoch's list is pasted only when+ // it changed or a history rewrite destroyed the pasted copies (#318).+ const note = try loop_list.note(ctx.arena, ctx.root);break :blk try std.fmt.allocPrint(ctx.arena, "/loop {s}", .{note});} else if (ctx.interactive) blk: {try ctx.root.prompt();@@ -553,8 +553,7 @@ pub fn run(ctx: *Ctx) !void {// Trim on failure only when we're genuinely against the window — at// 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);- loop_list.reset(); // the pasted copies died with the old history - re-carry the list once, mirroring goal_note_fp (#318)+ ctx.root.compactOrRecover(near_cap); // loop_list re-carries via root.history_rewrites, incl. MID-turn rewrites this block never sees (#318)}// #226: /loop controller-authorized continuation. After a cleanly-diff --git a/src/session_run.zig b/src/session_run.zigindex 719f2ac8..1a7877b4 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -266,7 +266,10 @@ pub fn buildRootAgent(const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}", .{util.unixMs(io)});root.session_name = if (flags.resume_flag) |name| (if (!flags.new_session_flag and !flags.no_resume_flag) name else fresh_session_name) else fresh_session_name;repl_glue.loadThinkingSettings(io, arena, &root); // {"effort":...,"fast":...} persisted by /effort and /fast- if (flags.goal_flag) |g| root.goal = goal_flow.standingGoalFromFlag(try arena.dupe(u8, g), root.todos.items, util.unixMs(io)); // --goal is STANDING (#318): it applies to every turn (incl. --json/-p/SDK) and the model can never retire it+ if (flags.goal_flag) |g| { // --goal is STANDING (#318): every turn (incl. --json/-p/SDK), never model-retired+ root.goal_flag = try arena.dupe(u8, g); // kept: re-applied over every loadSession, incl. /resume+ root.goal = goal_flow.standingGoalFromFlag(root.goal_flag.?, null, root.todos.items, util.unixMs(io));+ }if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);if (flags.eval_target_flag) |t| root.eval_target = t;if (flags.eval_niche_flag) |n| root.eval_niche = try arena.dupe(u8, n);@@ -295,9 +298,8 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, areif (!will_resume) session.saveSession(root, arena, root.session_name) catch {};if (flags.oneshot_prompt != null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag) {session.loadSession(root, keys, arena, root.session_name) catch {};- // loadSession overwrites root.goal with the goal from disk, so `-r <s> --goal X`- // silently dropped X. The flag wins, on an epoch above every restored one (#318).- if (flags.goal_flag) |g| root.goal = goal_flow.standingGoalFromFlag(arena.dupe(u8, g) catch g, root.todos.items, util.unixMs(root.io));+ // loadSession overwrote root.goal; the flag wins, idempotently (#318).+ if (root.goal_flag) |g| root.pending_goal_note = goal_flow.reapplyFlagGoal(arena, root, g, util.unixMs(root.io)) catch null;}}@@ -310,8 +312,8 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, arepub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: *provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {if (!(flags.oneshot_prompt == null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag)) return;if (session.loadSession(root, keys, arena, root.session_name)) |_| {- // --goal outranks the restored goal here too (see saveOrResumeSession, #318).- if (flags.goal_flag) |g| root.goal = goal_flow.standingGoalFromFlag(try arena.dupe(u8, g), root.todos.items, util.unixMs(root.io));+ // --goal outranks the restored goal here too, idempotently (#318).+ if (root.goal_flag) |g| root.pending_goal_note = goal_flow.reapplyFlagGoal(arena, root, g, util.unixMs(root.io)) catch null;if (root.messages.items.len > 0) {if (!json_mode) {// Prefer the saved AI summary; fall back to the first user