Skip to content

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

Python

Keep peer inbox wakes from restarting a finished turn

Cursor Agente8a60a04d1a9
diff --git a/docs/adr/0147-finish-is-not-cleanup-fanout.md b/docs/adr/0147-finish-is-not-cleanup-fanout.md
index eec0d17b..dce44a0a 100644
--- a/docs/adr/0147-finish-is-not-cleanup-fanout.md
+++ b/docs/adr/0147-finish-is-not-cleanup-fanout.md
@@ -21,7 +21,9 @@ preemption was already out of scope (#430, ADR 0134).
without bound.
- `deliverInbound` parks inbound during a root turn. Paint and the
one-line `[peer]` wake wait until idle. Same latch on REPL, TUI, and
- `graff acp`.
+ `graff acp`. A wake is never the newest authoritative user turn
+ while tools continue, and `attempt_completion` does not auto-run a
+ peer wake (#1137). The same unread generation is exposed at most once.
## Consequences
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 21e83ff8..5df23edc 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -254,6 +254,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
const cleaned = try cite_markup.dupe(self.arena, raw);
const result = if (!@import("builtin").is_test and self.pr_verification == .draft) try std.fmt.allocPrint(self.arena, "Draft handoff — CI is not verified.\n\n{s}", .{cleaned}) else cleaned;
self.completed = result;
+ if (!self.sub) @import("peer_idle.zig").noteCompletion();
if (!self.sub) task_outcome.noteGoalCompleted(self);
// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).
// A --goal standing objective is exempt: the completion is recorded above, the steering stays, and only /goal clear|pause|<new> retires it.
diff --git a/src/main.zig b/src/main.zig
index d0995be5..793eb02e 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -569,7 +569,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("agent_model_loop.zig");
_ = @import("publication_policy_tests.zig");
_ = @import("jobs_completion_tests.zig");
- _ = .{ @import("readline_paste_number_tests.zig"), @import("test_hooks.zig") }; // unreached modules; their tests were silently skipped
+ _ = .{ @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };
_ = @import("list_dir_nearmiss.zig");
_ = @import("repo_map.zig");
_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index 63d35ac5..58c40290 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -250,8 +250,9 @@ pub fn deliverInbound(root: *Agent) void {
}
/// Mid-turn mail stays parked. Announce only when idle and something new landed.
+/// A completed turn does not get a task-authoritative wake (#1137).
pub fn shouldAnnounce(busy: bool, newly_parked: usize) bool {
- return !busy and newly_parked > 0;
+ return @import("peer_wake_loop.zig").shouldInjectAuthoritative(busy, newly_parked);
}
/// Emit the drain's visible half as one bracketed unit: a blank notice, the
@@ -499,6 +500,8 @@ test "summarizeTranscript: last prompt, last words, last tool, from complete lin
}
test "#1136 shouldAnnounce: park during a turn, announce only when idle" {
+ @import("peer_idle.zig").resetForTest();
+ defer @import("peer_idle.zig").resetForTest();
try std.testing.expect(!shouldAnnounce(true, 3));
try std.testing.expect(!shouldAnnounce(true, 0));
try std.testing.expect(!shouldAnnounce(false, 0));
diff --git a/src/peer_idle.zig b/src/peer_idle.zig
index d56d499e..e4968caa 100644
--- a/src/peer_idle.zig
+++ b/src/peer_idle.zig
@@ -13,10 +13,14 @@ const presence = @import("presence.zig");
const presence_chan = @import("presence_chan.zig");
var last_woken_unread: usize = 0;
+var last_placed_gen: u64 = 0;
+var suppress_idle_wake: bool = false;
var turn_busy: std.atomic.Value(bool) = .init(false);
pub fn resetForTest() void {
last_woken_unread = 0;
+ last_placed_gen = 0;
+ suppress_idle_wake = false;
turn_busy.store(false, .release);
}
@@ -34,6 +38,30 @@ pub fn isBusy() bool {
return turn_busy.load(.acquire);
}
+/// Accepted `attempt_completion` ends the task. Parked mail stays readable
+/// but must not start another assistant/tool cycle (#1137).
+pub fn noteCompletion() void {
+ suppress_idle_wake = true;
+}
+
+/// A later human prompt re-opens idle auto-turn.
+pub fn noteHumanPrompt() void {
+ suppress_idle_wake = false;
+}
+
+pub fn idleWakeSuppressed() bool {
+ return suppress_idle_wake;
+}
+
+pub fn markPlaced(gen: u64) void {
+ last_placed_gen = gen;
+ last_woken_unread = peer_inbox.unread();
+}
+
+pub fn placedGeneration() u64 {
+ return last_placed_gen;
+}
+
fn ingest(io: Io, arena: Allocator) void {
const local = presence.drainChannel(io, arena);
const device = presence.drainDevice(io, arena);
@@ -53,7 +81,7 @@ fn ingest(io: Io, arena: Allocator) void {
/// buffer so a spent Agent arena cannot hide new JSONL. Does not inject
/// history — `runTurn`'s deliverInbound handles leftover room bytes.
pub fn takeIdleWake(io: Io, buf: []u8) ?[]const u8 {
- if (isBusy()) return null;
+ if (isBusy() or suppress_idle_wake) return null;
var scratch: [64 * 1024]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&scratch);
const arena = fba.allocator();
@@ -71,6 +99,7 @@ pub fn takeIdleWake(io: Io, buf: []u8) ?[]const u8 {
/// `action=inbox` consumed the batch — a later peer can wake again.
pub fn noteInboxConsumed() void {
last_woken_unread = 0;
+ last_placed_gen = 0;
}
test "#1001 idle wake fires once per new unread batch" {
@@ -106,6 +135,29 @@ test "#1001 idle wake fires once per new unread batch" {
try std.testing.expect(takeIdleWake(io, &buf) == null);
}
+test "#1137 idle wake is silent after attempt_completion until a human prompt" {
+ peer_inbox.resetForTest();
+ resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ resetForTest();
+ }
+ var buf: [256]u8 = undefined;
+ const msg: presence_chan.Message = .{
+ .from_pid = 2,
+ .from_start = 1,
+ .from_session = "s-peer",
+ .text = "hold the tree",
+ .to = "s-me",
+ };
+ _ = peer_inbox.parkHeard(&.{msg}, &.{});
+ noteCompletion();
+ try std.testing.expect(takeIdleWake(std.testing.io, &buf) == null);
+ noteHumanPrompt();
+ const wake = takeIdleWake(std.testing.io, &buf) orelse return error.ExpectedWakeAfterHuman;
+ try std.testing.expect(std.mem.indexOf(u8, wake, "[peer]") != null);
+}
+
test "#1136 idle wake is silent while a root turn is in flight" {
peer_inbox.resetForTest();
resetForTest();
@@ -130,6 +182,26 @@ test "#1136 idle wake is silent while a root turn is in flight" {
try std.testing.expect(std.mem.indexOf(u8, wake, "[peer]") != null);
}
+test "#1137 same unread generation does not idle-wake twice" {
+ peer_inbox.resetForTest();
+ resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ resetForTest();
+ }
+ var buf: [256]u8 = undefined;
+ const msg: presence_chan.Message = .{
+ .from_pid = 2,
+ .from_start = 1,
+ .from_session = "s-peer",
+ .text = "hold the tree",
+ .to = "s-me",
+ };
+ _ = peer_inbox.parkHeard(&.{msg}, &.{});
+ try std.testing.expect(takeIdleWake(std.testing.io, &buf) != null);
+ try std.testing.expect(takeIdleWake(std.testing.io, &buf) == null);
+}
+
test "#1001 more mail after a wake can fire again" {
peer_inbox.resetForTest();
resetForTest();
diff --git a/src/peer_inbox.zig b/src/peer_inbox.zig
index 05d337ec..8cba8bc6 100644
--- a/src/peer_inbox.zig
+++ b/src/peer_inbox.zig
@@ -46,12 +46,22 @@ var g_items: [inbox_cap]Parked = undefined;
var g_head: usize = 0;
var g_len: usize = 0;
var g_dropped: usize = 0;
+var g_gen: u64 = 0;
+
+pub fn generation() u64 {
+ return g_gen;
+}
+
+fn bumpGen() void {
+ g_gen +%= 1;
+}
pub fn clear() void {
for (0..g_len) |i| itemAt(i).deinit();
g_head = 0;
g_len = 0;
g_dropped = 0;
+ bumpGen();
}
pub fn resetForTest() void {
@@ -115,6 +125,7 @@ pub fn parkHeard(local: []const Message, device: []const Message) usize {
parkOne(m.from_session, m.text, m.to.len > 0, true);
n += 1;
}
+ if (n > 0) bumpGen();
return n;
}
diff --git a/src/peer_wake_loop.zig b/src/peer_wake_loop.zig
new file mode 100644
index 00000000..b23b71d5
--- /dev/null
+++ b/src/peer_wake_loop.zig
@@ -0,0 +1,159 @@
+//! #1137: peer inbox wakes stay ambient. They must not become the newest
+//! authoritative user turn, interrupt tool-result continuation, or restart
+//! a completed turn. Bodies stay in the inbox until `action=inbox`.
+
+const std = @import("std");
+
+const Agent = @import("agent.zig").Agent;
+const peer_context = @import("peer_context.zig");
+const peer_inbox = @import("peer_inbox.zig");
+const peer_idle = @import("peer_idle.zig");
+const session_peer = @import("session_peer.zig");
+const session_wake = @import("session_wake.zig");
+
+/// Mid-turn mail only parks. A history wake waits for idle (#1136) and is
+/// never placed after a human prompt (that would steal authority).
+pub fn shouldInjectAuthoritative(busy: bool, newly_parked: usize) bool {
+ return !busy and newly_parked > 0 and !peer_idle.idleWakeSuppressed();
+}
+
+/// Same unread generation is exposed at most once. Busy does not block a
+/// place *before* the current human prompt — that keeps the human newest.
+pub fn shouldPlaceWaiting(_: bool, last_is_human: bool) bool {
+ if (!last_is_human or !peer_inbox.pending()) return false;
+ return peer_inbox.generation() != peer_idle.placedGeneration();
+}
+
+fn lastIsHuman(root: *Agent) bool {
+ const items = root.messages.items;
+ if (items.len == 0) return false;
+ return session_peer.isHumanUserTurn(items[items.len - 1]);
+}
+
+/// Keep the human prompt newest. If mail is waiting, put one wake *before*
+/// that prompt. If the inbox was cleared, drop a leftover wake.
+pub fn placeWaitingBeforeHuman(root: *Agent) void {
+ if (root.sub) return;
+ if (lastIsHuman(root)) peer_idle.noteHumanPrompt();
+ if (!peer_inbox.pending()) {
+ session_peer.dropAllInjects(&root.messages);
+ peer_idle.markPlaced(peer_inbox.generation());
+ return;
+ }
+ if (!shouldPlaceWaiting(peer_idle.isBusy(), lastIsHuman(root))) return;
+ const wake = session_wake.message(root.arena, peer_context.capInject(peer_inbox.formatWake(root.arena))) catch return;
+ root.messages.append(wake) catch return;
+ const n = root.messages.items.len;
+ if (n >= 2) std.mem.swap(std.json.Value, &root.messages.items[n - 1], &root.messages.items[n - 2]);
+ peer_idle.markPlaced(peer_inbox.generation());
+}
+
+fn dummyRoot(arena: std.mem.Allocator, msgs: std.json.Array) Agent {
+ const drop = struct {
+ fn emit(_: *anyopaque, _: @import("engine_sink.zig").Stamped) void {}
+ };
+ const vt = @import("engine_sink.zig").VTable{ .emit = drop.emit, .durable = false };
+ var root: Agent = undefined;
+ root.sub = false;
+ root.arena = arena;
+ root.messages = msgs;
+ root.sink = .{ .ctx = undefined, .vt = &vt };
+ return root;
+}
+
+fn userText(arena: std.mem.Allocator, s: []const u8) !std.json.Value {
+ return @import("messages.zig").textMessage(arena, "user", s);
+}
+
+test "#1137 peer arrival between tool batches is not an authoritative user turn" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "inspect the parser"));
+ try msgs.append(try @import("messages.zig").textMessage(a, "assistant", "running tools"));
+ var root = dummyRoot(a, msgs);
+ peer_idle.noteTurnStart();
+ try std.testing.expect(!shouldInjectAuthoritative(peer_idle.isBusy(), 2));
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-peer", .text = "hold gui" }}, &.{});
+ placeWaitingBeforeHuman(&root);
+ try std.testing.expectEqual(@as(usize, 2), root.messages.items.len);
+ try std.testing.expect(session_peer.isHumanUserTurn(root.messages.items[0]));
+ peer_idle.noteTurnEnd();
+}
+
+test "#1137 duplicate unread state is idempotent" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "inspect the parser"));
+ var root = dummyRoot(a, msgs);
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-peer", .text = "hold gui" }}, &.{});
+ placeWaitingBeforeHuman(&root);
+ const after_first = root.messages.items.len;
+ try std.testing.expect(after_first == 2);
+ try std.testing.expect(peer_context.isPeerInject(root.messages.items[0]));
+ try std.testing.expect(session_peer.isHumanUserTurn(root.messages.items[1]));
+ placeWaitingBeforeHuman(&root);
+ try std.testing.expectEqual(after_first, root.messages.items.len);
+}
+
+test "#1137 peer arrival after attempt_completion does not auto-run" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-peer", .text = "hold gui" }}, &.{});
+ peer_idle.noteCompletion();
+ try std.testing.expect(peer_idle.idleWakeSuppressed());
+ try std.testing.expect(!shouldInjectAuthoritative(false, 1));
+ var buf: [256]u8 = undefined;
+ try std.testing.expect(peer_idle.takeIdleWake(std.testing.io, &buf) == null);
+ try std.testing.expectEqual(@as(usize, 1), peer_inbox.unread());
+}
+
+test "#1137 later human turn still sees waiting peer mail" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "next task"));
+ var root = dummyRoot(a, msgs);
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-peer", .text = "hold gui" }}, &.{});
+ peer_idle.noteCompletion();
+ var wake_buf: [256]u8 = undefined;
+ try std.testing.expect(peer_idle.takeIdleWake(std.testing.io, &wake_buf) == null);
+ placeWaitingBeforeHuman(&root);
+ try std.testing.expect(!peer_idle.idleWakeSuppressed());
+ try std.testing.expectEqual(@as(usize, 2), root.messages.items.len);
+ try std.testing.expect(peer_context.isPeerInject(root.messages.items[0]));
+ try std.testing.expect(session_peer.isHumanUserTurn(root.messages.items[1]));
+ try std.testing.expectEqual(@as(usize, 1), peer_inbox.unread());
+ const body = try peer_inbox.takeAll(a);
+ peer_idle.noteInboxConsumed();
+ try std.testing.expect(std.mem.indexOf(u8, body, "hold gui") != null);
+ placeWaitingBeforeHuman(&root);
+ try std.testing.expectEqual(@as(usize, 1), root.messages.items.len);
+ try std.testing.expect(session_peer.isHumanUserTurn(root.messages.items[0]));
+}
diff --git a/src/turn_inbox.zig b/src/turn_inbox.zig
index ca157fe3..b983a877 100644
--- a/src/turn_inbox.zig
+++ b/src/turn_inbox.zig
@@ -10,6 +10,7 @@ const session_wake = @import("session_wake.zig");
const main_mod = @import("main.zig");
pub fn deliver(self: *Agent) !void {
+ @import("peer_wake_loop.zig").placeWaitingBeforeHuman(self);
@import("peer_channel.zig").deliverInbound(self);
try @import("subagent_feedback.zig").deliverToAgent(self);
@import("job_notify.zig").deliver(self);