graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(loop): /loop takes a time budget and tells the model where it stands
Rach Pradhan8ca1df3e2353
diff --git a/README.md b/README.mdindex 148a934c..d672a1c4 100644--- a/README.md+++ b/README.md@@ -465,7 +465,7 @@ other animation names remain available./ultracode toggle persistent multi-agent workflow mode/animation choose a thinking animation (`/animation` lists every option)/goal [text] set/show a standing objective; /goal pause|resume|status|clear-/loop <prompt> work autonomously toward the prompt, stopping with a named outcome when done or blocked+/loop [30m] <prompt> work autonomously toward the prompt, stopping with a named outcome; an optional 30s/30m/2h budget paces the run/review <target> one read-only review pass; no edits, delegation, workflows, or web access/rewind [n] list past prompts; /rewind <n> drops prompt n+after & reverts its file edits/image <path> attach an image to your next message (vision models only)@@ -491,8 +491,15 @@ turns it back on, and `/goal status` shows the objective and its current state.(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, idlewhen 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.+or blocked when you step in or it needs you, exhausted when a safety limit is+hit, and expired when a time budget runs out.+Start the prompt with a duration to give the run one: `/loop 30m fix the flaky+test` (also `45s`, `2h`). Each continuation turn then tells the model where it+stands: which continuation it is on, how long the run has taken, how much of the+budget is left, and one phase hint (explore, implement, finish, wrap up).+Nothing is enforced except the stop itself, and the model is never cut off+mid-turn. Subagents spawned during a timed run are told the parent's remaining+time, minus a margin for the parent to integrate their results.`/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 a47077dc..6d2f17b4 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -137,6 +137,7 @@ pub const Agent = struct {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)+ loop_deadline_ms: ?i64 = null, // the running /loop's wall-clock deadline (goal_pacing.LoopClock); read by the subagent spawn path so a child inherits it. Run-local: never saved, cleared on stop/steerhistory_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 metadatadiff --git a/src/goal_flow.zig b/src/goal_flow.zigindex 713afbfa..83b16fff 100644--- a/src/goal_flow.zig+++ b/src/goal_flow.zig@@ -149,8 +149,14 @@ pub fn applyGoalSet(root: *Agent, objective: []const u8, now_ms: i64) GoalSetRes/// 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 {+pub fn loopTurnDecision(root: *Agent, iters_left: u32, now_ms: i64) repl_glue.ContinuationDecision {const work_done = root.completed != null or goal_state.checklistFinished(root);+ // A `/loop 30m ...` deadline is the run's ONLY hard effect (#224 dropped+ // goal budget enforcement, and that stands): it stops the run and names the+ // outcome. It flips no goal status and is never `accepted` - the work is+ // unfinished, that is the whole point. Real completion evidence still wins,+ // so a run that finished on its last second reports accepted, not expired.+ if (!work_done) if (root.loop_deadline_ms) |d| if (now_ms >= d) return .{ .stop = .expired };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);@@ -240,6 +246,7 @@ fn flowRoot(arena: Allocator) Agent {root.pending_goal_note = null;root.history_rewrites = 0;root.tool_calls_this_turn = 0;+ root.loop_deadline_ms = null;return root;}diff --git a/src/goal_pacing.zig b/src/goal_pacing.zignew file mode 100644index 00000000..ddedb874--- /dev/null+++ b/src/goal_pacing.zig@@ -0,0 +1,241 @@+//! Time-aware /loop pacing: the optional duration prefix on `/loop`, the run+//! clock it arms, and the pacing line every continuation turn carries.+//!+//! Everything the model reads here is INFORMATION, never enforcement. This+//! repo dropped goal budget enforcement on purpose (#224), and that stands: a+//! deadline's only hard effect is that the /loop controller stops the run with+//! the `expired` outcome. The rest is guidance, on the prior art's reasoning -+//! codex renders tokens_used/token_budget/remaining_tokens into its+//! continuation prompt on every turn, and LemonHarness feeds wall-clock phases+//! (explore, implement, validate, wrap up), both because a model that cannot+//! see the clock cannot pace itself and will happily spend a whole budget on+//! exploration.+//!+//! Pure text and arithmetic - no Io, the caller passes the clock reading - so+//! every rule here is unit-tested. Reached through the `test { _ = ... }` hook+//! in main.zig; without that line these tests silently compile to nothing.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Agent = @import("agent.zig").Agent;++/// A parsed `/loop` argument: an optional wall-clock budget and the prompt.+pub const LoopBudget = struct {+ /// Milliseconds from now until the run's deadline, or null for no deadline.+ deadline_ms_delta: ?i64 = null,+ /// The prompt the turn actually runs. Never empty for a parsed budget.+ prompt: []const u8,+};++/// Parse the text after `/loop`. A leading `<integer><s|m|h>` followed by+/// whitespace and a nonempty prompt is a budget; ANYTHING else is not, and the+/// whole text is the prompt. That fallback is the important half: `/loop 30m`+/// on its own is someone asking the model about thirty minutes, not an empty+/// run, and `/loop 30mins of cleanup` is a sentence. Rejecting silently costs+/// nothing (the run just has no deadline); guessing wrong would either eat the+/// user's prompt or start a run they never asked to be timed.+pub fn parseLoopBudget(text: []const u8) LoopBudget {+ const trimmed = std.mem.trim(u8, text, " \t");+ const none: LoopBudget = .{ .prompt = trimmed };+ var digits: usize = 0;+ while (digits < trimmed.len and std.ascii.isDigit(trimmed[digits])) digits += 1;+ if (digits == 0 or digits >= trimmed.len) return none;+ const unit: i64 = switch (trimmed[digits]) {+ 's' => std.time.ms_per_s,+ 'm' => std.time.ms_per_min,+ 'h' => std.time.ms_per_hour,+ else => return none,+ };+ const rest = trimmed[digits + 1 ..];+ // The unit must END the token: "30mins" is a word, not a budget.+ if (rest.len == 0 or (rest[0] != ' ' and rest[0] != '\t')) return none;+ const prompt = std.mem.trim(u8, rest, " \t");+ if (prompt.len == 0) return none;+ const n = std.fmt.parseInt(i64, trimmed[0..digits], 10) catch return none;+ if (n <= 0) return none; // "0m" is not a deadline that already passed, it is a typo+ const delta = std.math.mul(i64, n, unit) catch return none;+ return .{ .deadline_ms_delta = delta, .prompt = prompt };+}++/// The same parse straight off an input line, so the caller stays one line.+/// Returns null when the line is not a `/loop` invocation at all.+pub fn loopBudgetFromLine(line: []const u8) ?LoopBudget {+ if (!std.mem.startsWith(u8, line, "/loop ")) return null;+ return parseLoopBudget(line["/loop".len..]);+}++/// The wall clock of ONE /loop run: when it started and when it must stop.+/// Run-local like LoopListGate and never persisted - a fresh run, a user steer+/// and a stop all reset it. The deadline is mirrored onto the Agent so a+/// subagent spawned mid-run can inherit it (goal_pacing.childTaskPrompt).+pub const LoopClock = struct {+ started_ms: i64 = 0,+ deadline_ms: ?i64 = null,++ pub fn arm(self: *LoopClock, root: *Agent, now_ms: i64, delta: ?i64) void {+ self.started_ms = now_ms;+ self.deadline_ms = if (delta) |d| now_ms +| d else null;+ root.loop_deadline_ms = self.deadline_ms;+ }++ pub fn clear(self: *LoopClock, root: *Agent) void {+ self.* = .{};+ root.loop_deadline_ms = null;+ }++ /// Has the run's budget run out as of `now_ms`? Always false without one.+ pub fn expired(self: LoopClock, now_ms: i64) bool {+ const d = self.deadline_ms orelse return false;+ return now_ms >= d;+ }+};++/// What every freshly-typed input line does to the run clock. A `/loop ...`+/// line starts a run: its clock begins now (not after the first turn, so a+/// "30m" the user typed really is 30 minutes of theirs) and the previous run's+/// completion evidence is dropped - a checklist finished BEFORE this prompt is+/// not evidence that THIS prompt is done, which ended a standing goal's next+/// run at iteration 1 as accepted (#318). Any other line means no run is in+/// flight, so the clock clears and its deadline stops reaching subagents; a+/// turn that errors out mid-run would otherwise leave one armed for good.+pub fn armFreshRun(clock: *LoopClock, root: *Agent, now_ms: i64, budget: ?LoopBudget) void {+ const b = budget orelse return clock.clear(root);+ root.todos_dirty = false;+ clock.arm(root, now_ms, b.deadline_ms_delta);+}++/// "45s" / "12m" / "1h5m" - short enough to sit inside a bracketed note.+pub fn fmtDur(arena: Allocator, ms: i64) ![]const u8 {+ const secs = @divTrunc(@max(0, ms), std.time.ms_per_s);+ if (secs < 60) return std.fmt.allocPrint(arena, "{d}s", .{secs});+ const mins = @divTrunc(secs, 60);+ if (mins < 60) return std.fmt.allocPrint(arena, "{d}m", .{mins});+ return std.fmt.allocPrint(arena, "{d}h{d}m", .{ @divTrunc(mins, 60), @mod(mins, 60) });+}++/// One phase hint, chosen by how much of the budget is LEFT. Straight from+/// LemonHarness's phase split, compressed to a single sentence so it can ride+/// on every continuation without becoming noise the model learns to skip.+fn phaseHint(pct_left: i64) []const u8 {+ if (pct_left >= 70) return "There is room to explore and plan freely before committing.";+ if (pct_left >= 30) return "Focus on implementation; do not re-explore ground you have already settled.";+ if (pct_left >= 10) return "Prioritize finishing and validating what exists over starting new work.";+ return "Wrap up now: preserve what works, start nothing new, and report the exact state.";+}++/// The pacing line appended to each /loop continuation turn. The iteration+/// count is unconditional - a model that cannot see how many continuations it+/// has left cannot decide whether to open a new thread of work - and a run with+/// a wall-clock budget also gets the remaining time and one phase hint.+pub fn pacingNote(arena: Allocator, now_ms: i64, clock: LoopClock, iters_used: u32, iters_cap: u32) ![]const u8 {+ const elapsed = try fmtDur(arena, now_ms - clock.started_ms);+ const deadline = clock.deadline_ms orelse+ return std.fmt.allocPrint(arena, "[pace: continuation {d} of {d}, {s} elapsed. No wall-clock budget was set for this run.]", .{ iters_used, iters_cap, elapsed });+ const total = @max(1, deadline - clock.started_ms);+ const left = @max(0, deadline - now_ms);+ const pct = @divTrunc(left * 100, total);+ return std.fmt.allocPrint(arena, "[pace: continuation {d} of {d}, {s} elapsed, ~{s} of the time budget left ({d}%). {s}]", .{ iters_used, iters_cap, elapsed, try fmtDur(arena, left), pct, phaseHint(pct) });+}++test "parseLoopBudget: a duration prefix arms a deadline, anything else is prompt" {+ const b1 = parseLoopBudget("30m fix the flaky test");+ try std.testing.expectEqual(@as(?i64, 30 * std.time.ms_per_min), b1.deadline_ms_delta);+ try std.testing.expectEqualStrings("fix the flaky test", b1.prompt);+ try std.testing.expectEqual(@as(?i64, 45 * std.time.ms_per_s), parseLoopBudget("45s ship it").deadline_ms_delta);+ try std.testing.expectEqual(@as(?i64, 2 * std.time.ms_per_hour), parseLoopBudget(" 2h land the release ").deadline_ms_delta);+ try std.testing.expectEqualStrings("land the release", parseLoopBudget(" 2h land the release ").prompt);+}++test "parseLoopBudget: every ambiguous shape stays a prompt, verbatim" {+ // The one that matters: a bare duration is a QUESTION, not an empty run.+ const bare = parseLoopBudget("30m");+ try std.testing.expect(bare.deadline_ms_delta == null);+ try std.testing.expectEqualStrings("30m", bare.prompt);+ for ([_][]const u8{+ "30mins of cleanup", // the unit has to end the token+ "30 m fix it", // and be attached to the number+ "30x fix it", // unknown unit+ "fix it in 30m", // not a prefix+ "0m fix it", // a zero budget is a typo, not an instant deadline+ "30m ", // no prompt after the duration+ "99999999999999999999h go", // parseInt overflow+ }) |text| {+ const b = parseLoopBudget(text);+ try std.testing.expect(b.deadline_ms_delta == null);+ try std.testing.expectEqualStrings(std.mem.trim(u8, text, " \t"), b.prompt);+ }+ // And the whole thing only fires on a real /loop line.+ try std.testing.expect(loopBudgetFromLine("/goal 30m ship") == null);+ try std.testing.expectEqual(@as(?i64, 5 * std.time.ms_per_min), loopBudgetFromLine("/loop 5m ship").?.deadline_ms_delta);+}++test "LoopClock: arms and clears the Agent-visible deadline together" {+ var root: Agent = undefined;+ root.loop_deadline_ms = null;+ var clock: LoopClock = .{};+ clock.arm(&root, 1_000, null);+ try std.testing.expect(clock.deadline_ms == null and root.loop_deadline_ms == null);+ try std.testing.expect(!clock.expired(9_999_999)); // no budget, never expires+ clock.arm(&root, 1_000, 60_000);+ try std.testing.expectEqual(@as(?i64, 61_000), clock.deadline_ms);+ try std.testing.expectEqual(@as(?i64, 61_000), root.loop_deadline_ms); // the subagent-visible copy+ try std.testing.expect(!clock.expired(60_999));+ try std.testing.expect(clock.expired(61_000)); // the instant it lands, not one tick later+ clock.clear(&root);+ try std.testing.expect(clock.deadline_ms == null and root.loop_deadline_ms == null and clock.started_ms == 0);+}++test "armFreshRun: a /loop line starts the clock, any other line ends it" {+ var root: Agent = undefined;+ root.loop_deadline_ms = null;+ root.todos_dirty = true; // left over from the previous run+ var clock: LoopClock = .{};++ armFreshRun(&clock, &root, 5_000, loopBudgetFromLine("/loop 30m fix the flaky test"));+ try std.testing.expectEqual(@as(i64, 5_000), clock.started_ms); // the user's 30m starts when they typed it+ try std.testing.expectEqual(@as(?i64, 5_000 + 30 * std.time.ms_per_min), root.loop_deadline_ms);+ try std.testing.expect(!root.todos_dirty);++ // A /loop with no duration still starts a run, just an untimed one.+ armFreshRun(&clock, &root, 9_000, loopBudgetFromLine("/loop keep going"));+ try std.testing.expectEqual(@as(i64, 9_000), clock.started_ms);+ try std.testing.expect(root.loop_deadline_ms == null);++ // Any other typed line means no run is in flight. Without this a turn that+ // errored out mid-run left a deadline armed, and every later subagent - of+ // any turn, forever - was told to hurry for a run that ended long ago.+ armFreshRun(&clock, &root, 12_000, loopBudgetFromLine("/loop 5m ship"));+ try std.testing.expect(root.loop_deadline_ms != null);+ armFreshRun(&clock, &root, 13_000, null);+ try std.testing.expect(root.loop_deadline_ms == null and clock.deadline_ms == null and clock.started_ms == 0);+}++test "pacingNote: iterations always, then remaining time and one phase hint" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();++ // No budget: the model still learns how many continuations it has left.+ const plain = try pacingNote(ar, 90_000, .{ .started_ms = 0 }, 3, 25);+ try std.testing.expectEqualStrings("[pace: continuation 3 of 25, 1m elapsed. No wall-clock budget was set for this run.]", plain);++ const clock: LoopClock = .{ .started_ms = 0, .deadline_ms = 60 * std.time.ms_per_min };+ const hints = [_]struct { now: i64, frag: []const u8 }{+ .{ .now = 6 * std.time.ms_per_min, .frag = "explore and plan freely" }, // 90% left+ .{ .now = 30 * std.time.ms_per_min, .frag = "Focus on implementation" }, // 50% left+ .{ .now = 42 * std.time.ms_per_min, .frag = "Focus on implementation" }, // 30% left, the low edge+ .{ .now = 45 * std.time.ms_per_min, .frag = "Prioritize finishing" }, // 25% left+ .{ .now = 55 * std.time.ms_per_min, .frag = "Wrap up now" }, // 8% left+ .{ .now = 70 * std.time.ms_per_min, .frag = "Wrap up now" }, // already over+ };+ for (hints) |h| {+ const note = try pacingNote(ar, h.now, clock, 1, 25);+ try std.testing.expect(std.mem.indexOf(u8, note, h.frag) != null);+ try std.testing.expect(std.mem.indexOf(u8, note, "continuation 1 of 25") != null);+ try std.testing.expect(std.mem.indexOf(u8, note, "of the time budget left") != null);+ }+ // The boundaries are inclusive-from-above, and an overrun never reports+ // negative time left.+ try std.testing.expect(std.mem.indexOf(u8, try pacingNote(ar, 18 * std.time.ms_per_min, clock, 1, 25), "explore and plan freely") != null); // exactly 70%+ try std.testing.expect(std.mem.indexOf(u8, try pacingNote(ar, 70 * std.time.ms_per_min, clock, 1, 25), "~0s of the time budget left (0%)") != null);+}diff --git a/src/goal_persist_tests.zig b/src/goal_persist_tests.zigindex 2ed7a683..1cdcd0cf 100644--- a/src/goal_persist_tests.zig+++ b/src/goal_persist_tests.zig@@ -48,6 +48,7 @@ fn blankRoot(arena: Allocator) Agent {root.completed = null;root.tool_calls_this_turn = 0;root.goal_note_fp = 0;+ root.loop_deadline_ms = null;return root;}@@ -317,7 +318,7 @@ test "/loop: a restored all-[x] list is idle, not accepted (#318)" {);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(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25, 0).stop);try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status); // and nothing was retired}@@ -329,7 +330,7 @@ test "/loop: a finished list accepts and retires only a retirable goal (#318)" {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.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 0).stop);try std.testing.expect(goal_flow.acceptLoopOutcome(&root));try std.testing.expectEqual(agent_mod.GoalStatus.complete, root.goal.?.status);@@ -337,11 +338,11 @@ test "/loop: a finished list accepts and retires only a retirable goal (#318)" {// 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.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 0).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.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 0).stop);try std.testing.expect(!goal_flow.acceptLoopOutcome(&root));try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);}@@ -359,20 +360,20 @@ test "/loop: a refused completion is work, and a leftover complete goal decides// 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);+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25, 0)) == .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);+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25, 0).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);+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25, 0)) == .continue_turn);+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.exhausted, goal_flow.loopTurnDecision(&root, 0, 0).stop);root.tool_calls_this_turn = 0;- try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25).stop);+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.idle, goal_flow.loopTurnDecision(&root, 25, 0).stop);}test "a fresh /loop cannot stop accepted off a checklist finished before it (#318)" {@@ -388,14 +389,47 @@ test "a fresh /loop cannot stop accepted off a checklist finished before it (#31root.todos_dirty = true;root.tool_calls_this_turn = 1;// Stale evidence reads as work_done -> accepted on B's very first decision...- try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25).stop);+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 0).stop);// ...which is why mainloop clears todos_dirty when a FRESH /loop arms: the// new prompt starts with no completion evidence of its own, and only a// todo_write (or attempt_completion) made DURING the run can stop it.root.todos_dirty = false;- try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25)) == .continue_turn);+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25, 0)) == .continue_turn);goal_state.noteTodoWrite(&root); // the model re-plans and finishes in-run- try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25).stop);+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 0).stop);+}++test "/loop: a passed wall-clock deadline stops as expired and flips nothing" {+ 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, .status = .active };+ try root.todos.append(ar, .{ .content = "still open", .status = "pending", .epoch = 1 });+ root.tool_calls_this_turn = 3; // the turn worked; it simply ran out of clock+ root.loop_deadline_ms = 10_000; // `/loop 30m ...` armed this++ // One second short of it the run continues exactly as before.+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25, 9_999)) == .continue_turn);+ // On it, the run stops with its own named outcome. This is the deadline's+ // ONLY hard effect: #224 dropped goal budget ENFORCEMENT and that stands,+ // so the goal is untouched and the checklist is left exactly as it is.+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.expired, goal_flow.loopTurnDecision(&root, 25, 10_000).stop);+ try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);+ try std.testing.expectEqual(@as(usize, 1), goal_state.openCount(root.todos.items, 1));+ // expired is not accepted, so mainloop never runs acceptLoopOutcome on it -+ // and if it somehow did, the goal is still active work, not a completion.+ try std.testing.expect(goal_flow.acceptLoopOutcome(&root)); // proof the two paths differ+ root.goal.?.status = .active;++ // Real completion evidence outranks the clock: a run that finished on its+ // last second reports accepted, not expired.+ root.completed = "shipped";+ try std.testing.expectEqual(repl_glue.ContinuationOutcome.accepted, goal_flow.loopTurnDecision(&root, 25, 99_999).stop);+ // And a run with no budget never expires, however long it goes.+ root.completed = null;+ root.loop_deadline_ms = null;+ try std.testing.expect(std.meta.activeTag(goal_flow.loopTurnDecision(&root, 25, 1 << 40)) == .continue_turn);}test "an accepted claim while paused still consumes the double-check arm (#318)" {diff --git a/src/main.zig b/src/main.zigindex 39893116..03ee7b7a 100644--- a/src/main.zig+++ b/src/main.zig@@ -595,4 +595,5 @@ test { // pull in tests from imported modules (mcp.zig)_ = @import("goal_persist_tests.zig");_ = @import("goal_flow.zig");_ = @import("goal_todo.zig");+ _ = @import("goal_pacing.zig");}diff --git a/src/mainloop.zig b/src/mainloop.zigindex cc5af8b5..6545a924 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -25,6 +25,7 @@ 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 goal_pacing = @import("goal_pacing.zig");const eval_memory = @import("eval_memory.zig");const mainloop_score = @import("mainloop_score.zig");const mainloop_trace = @import("mainloop_trace.zig");@@ -70,6 +71,7 @@ pub fn run(ctx: *Ctx) !void {var loop_iters_left: u32 = 0; // continuation turns still authorized this /loop runvar loop_continue_armed = false; // a continuation turn is queued for the next readlinevar loop_list: goal_flow.LoopListGate = .{}; // diff-gate for the checklist copy in continuation prompts (#318)+ var loop_clock: goal_pacing.LoopClock = .{}; // this run's wall clock: `/loop 30m <prompt>` arms a deadline, and every continuation is told where it standswhile (true) {// Titles can land between interactions but never join the response path.@@ -83,6 +85,7 @@ pub fn run(ctx: *Ctx) !void {loop_iters_left = 0; // #226: a user steer/force cancels the autonomous /loop runloop_continue_armed = false;loop_list.reset();+ loop_clock.clear(ctx.root); // and its deadline stops reaching subagentsif (e.force) {try ctx.out.print("{s}↳ force ›{s} {s}\n", .{ style.yellow, style.reset, e.text });} else {@@ -100,7 +103,8 @@ pub fn run(ctx: *Ctx) !void {// 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});+ const pace = try goal_pacing.pacingNote(ctx.arena, util.unixMs(ctx.io), loop_clock, loop_iter_cap - loop_iters_left, loop_iter_cap);+ break :blk try std.fmt.allocPrint(ctx.arena, "/loop {s}\n{s}", .{ note, pace });} else if (ctx.interactive) blk: {try ctx.root.prompt();break :blk (try readline.readLine(ctx.root, ctx.in, ctx.out, ctx.gpa, ctx.history, ctx.linebuf)) orelse break;@@ -110,22 +114,16 @@ pub fn run(ctx: *Ctx) !void {title_jobs.poll(ctx);const line = std.mem.trim(u8, raw_line, " \t\r");if (line.len == 0) continue;- const loop_prompt: ?[]const u8 = if (!main_mod.json_mode and std.mem.startsWith(u8, line, "/loop "))- std.mem.trim(u8, line["/loop".len..], " \t")- else- null;- // A checklist finished BEFORE this /loop is not evidence its prompt is done:- // stale todos_dirty ended a standing goal's next run at iteration 1 as accepted (#318).- if (loop_prompt != null and !is_loop_continuation) ctx.root.todos_dirty = false;+ // `/loop [<n>s|m|h] <prompt>`: an unambiguous duration arms this run's wall clock; anything else is prompt.+ const loop_budget: ?goal_pacing.LoopBudget = if (main_mod.json_mode) null else goal_pacing.loopBudgetFromLine(line);+ const loop_prompt: ?[]const u8 = if (loop_budget) |b| b.prompt else null;+ // A fresh line starts (or ends) a /loop run: its wall clock begins here, and stale todos_dirty+ // is dropped - a checklist finished BEFORE this prompt ended the next run at iteration 1 (#318).+ if (!is_loop_continuation) goal_pacing.armFreshRun(&loop_clock, ctx.root, util.unixMs(ctx.io), loop_budget);var review_prompt: ?[]const u8 = if (!main_mod.json_mode) review.promptFromLine(line) else null;- // /goal <objective>: set the standing goal AND run it as the first turn- // right away — codex/opencode both start the loop on a goal instead of- // just recording it. Bare /goal (show) and /goal clear/off stay commands.- const goal_prompt: ?[]const u8 = if (!main_mod.json_mode and std.mem.startsWith(u8, line, "/goal ")) gblk: {- const g = std.mem.trim(u8, line["/goal".len..], " \t");- if (g.len == 0 or std.ascii.eqlIgnoreCase(g, "clear") or std.ascii.eqlIgnoreCase(g, "off") or std.ascii.eqlIgnoreCase(g, "pause") or std.ascii.eqlIgnoreCase(g, "resume") or std.ascii.eqlIgnoreCase(g, "status")) break :gblk null;- break :gblk g;- } else null;+ // /goal <objective>: set the standing goal AND run it as the first turn right away — codex/opencode+ // both start the loop on a goal instead of just recording it (the parse itself is in repl_glue).+ const goal_prompt: ?[]const u8 = if (main_mod.json_mode) null else repl_glue.goalPromptFromLine(line);if (!main_mod.json_mode) {const l = if (line.len > 0 and line[0] == '/') line[1..] else line;if (std.mem.eql(u8, l, "exit") or std.mem.eql(u8, l, "quit") or std.mem.eql(u8, l, "q")) break;@@ -570,7 +568,7 @@ pub fn run(ctx: *Ctx) !void {loop_iters_left = loop_iter_cap; // fresh /loop run: arm the boundloop_list.reset(); // and a clean gate: its first continuation carries the list in full}- switch (goal_flow.loopTurnDecision(ctx.root, loop_iters_left)) {+ switch (goal_flow.loopTurnDecision(ctx.root, loop_iters_left, util.unixMs(ctx.io))) {.continue_turn => {loop_iters_left -= 1; // consume one credit for the queued continuationloop_continue_armed = true;@@ -579,6 +577,7 @@ pub fn run(ctx: *Ctx) !void {loop_iters_left = 0;loop_continue_armed = false;loop_list.reset();+ loop_clock.clear(ctx.root);// 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);diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 260eac72..05c179bc 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -213,6 +213,7 @@ pub const ContinuationOutcome = enum {accepted, // the goal's checklist is complete (or the goal itself is complete)idle, // the turn did no tool work and asserted nothing - the loop stops, but nothing is done (#318)exhausted, // hit the hard per-/loop iteration bound with work still open+ expired, // the run's wall-clock budget (`/loop 30m ...`) ran out with work still openblocked, // the goal is blocked and needs the usercancelled, // the goal was paused — the user stepped in};@@ -568,6 +569,25 @@ pub fn isSlashCommandLine(line: []const u8) bool {return true;}+/// `/goal <objective>` sets the standing goal AND runs it as the first turn, so the caller needs the+/// objective back as a prompt; a bare `/goal` and the lifecycle words stay commands. Extracted from+/// mainloop (600-line cap), and kept beside isSlashCommandLine: both settle "command, or prompt?".+pub fn goalPromptFromLine(line: []const u8) ?[]const u8 {+ if (!std.mem.startsWith(u8, line, "/goal ")) return null;+ const g = std.mem.trim(u8, line["/goal".len..], " \t");+ if (g.len == 0) return null;+ for ([_][]const u8{ "clear", "off", "pause", "resume", "status" }) |sub|+ if (std.ascii.eqlIgnoreCase(g, sub)) return null;+ return g;+}++test "goalPromptFromLine: an objective runs a turn, the lifecycle words do not" {+ try std.testing.expectEqualStrings("ship phase 2", goalPromptFromLine("/goal ship phase 2 ").?);+ try std.testing.expect(goalPromptFromLine("/goal ") == null); // bare /goal shows the objective+ try std.testing.expect(goalPromptFromLine("/goal PAUSE") == null); // case-insensitive, like handleCommand+ try std.testing.expectEqualStrings("clear the flaky tests", goalPromptFromLine("/goal clear the flaky tests").?); // merely STARTS with one+}+test "absolute path prompts are not mistaken for slash commands" {try std.testing.expect(isSlashCommandLine("/"));try std.testing.expect(isSlashCommandLine("/help"));