Skip to content

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

Python

peer mail: room posts no longer reopen a turn that ended with an answer

justracha53242d4e725
diff --git a/src/agent_turn.zig b/src/agent_turn.zig
index 97f4fcc9..03ea82c4 100644
--- a/src/agent_turn.zig
+++ b/src/agent_turn.zig
@@ -98,6 +98,7 @@ pub fn run(self: *Agent, root_turn_prepared: *std.atomic.Value(bool)) anyerror![
if (try @import("named_work.zig").handle(self, final_text)) continue;
if (try pending_work.finish(self, bounced_answer.finish(self, final_text))) |text| {
if (self.feedback) |inbox| if (!inbox.tryFinish(self.io)) continue;
+ settleFinal(self);
return review_deadline.finish(text);
}
continue;
@@ -106,6 +107,14 @@ pub fn run(self: *Agent, root_turn_prepared: *std.atomic.Value(bool)) anyerror![
}
}
+/// A root turn that ends with its answer settles the human task (#1137):
+/// ambient peer mail then waits for the next human prompt instead of
+/// reopening it. A yielded turn is a handoff, already latched harder; a
+/// stopped tool loop did not finish the task and settles nothing.
+fn settleFinal(self: *Agent) void {
+ if (!self.sub) @import("peer_idle.zig").noteFinalAnswer();
+}
+
/// #1686: the previous compaction left the context over the line; wait for
/// real growth (or the 95% wall) instead of compacting on every step.
fn compactionHeld(self: *Agent) bool {
diff --git a/src/peer_idle.zig b/src/peer_idle.zig
index dd5467cd..05eca26c 100644
--- a/src/peer_idle.zig
+++ b/src/peer_idle.zig
@@ -16,6 +16,7 @@ var last_woken_unread: usize = 0;
var last_placed_gen: u64 = 0;
var suppress_idle_wake: bool = false;
var waiting_for_input: bool = false;
+var settled: bool = false;
var turn_busy: std.atomic.Value(bool) = .init(false);
pub fn resetForTest() void {
@@ -23,6 +24,7 @@ pub fn resetForTest() void {
last_placed_gen = 0;
suppress_idle_wake = false;
waiting_for_input = false;
+ settled = false;
turn_busy.store(false, .release);
}
@@ -46,6 +48,28 @@ pub fn noteCompletion() void {
suppress_idle_wake = true;
}
+/// A root turn ended with an ordinary final answer (#1137). The human task
+/// is done just as after `attempt_completion`, but more softly: mail posted
+/// to the folder's room is ambient coordination and no longer starts a turn
+/// on its own. It stays parked and readable, and the next human prompt sees
+/// it. Mail addressed to this session (a DM, or the user's own `/tell`) is an
+/// explicit request and still wakes, so peers can still hand work over.
+pub fn noteFinalAnswer() void {
+ settled = true;
+}
+
+/// Whether the parked mail at or after `from` may start a turn by itself.
+fn mayStartTurn(from: usize) bool {
+ if (settled) return peer_inbox.anyAddressedNeedsTurnFrom(from);
+ return peer_inbox.anyNeedsTurnFrom(from);
+}
+
+/// Mail at or after `from` is held for the next human prompt: the last task
+/// ended with an answer and none of it is addressed to this session.
+pub fn ambientHeld(from: usize) bool {
+ return settled and !peer_inbox.anyAddressedNeedsTurnFrom(from);
+}
+
/// A handoff waits for human input without completing a goal. Peer mail
/// stays readable, but cannot immediately reopen the yielded turn.
pub fn noteHandoff() void {
@@ -61,6 +85,7 @@ pub fn waitingForInput() bool {
pub fn noteHumanPrompt() void {
suppress_idle_wake = false;
waiting_for_input = false;
+ settled = false;
}
pub fn idleWakeSuppressed() bool {
@@ -108,7 +133,8 @@ pub fn takeIdleWake(io: Io, buf: []u8) ?[]const u8 {
const n = peer_inbox.unread();
if (n == 0 or n <= last_woken_unread) return null;
// #1137: fyi-only news stays parked for the next turn; it starts none.
- if (!peer_inbox.anyNeedsTurnFrom(last_woken_unread)) return null;
+ // After a final answer only mail addressed to this session does.
+ if (!mayStartTurn(last_woken_unread)) return null;
last_woken_unread = n;
const wake = peer_inbox.formatWake(arena);
if (wake.len == 0) return null;
@@ -268,6 +294,75 @@ test "#1137 fyi mail stays parked without a turn; a request after it wakes" {
try std.testing.expect(std.mem.indexOf(u8, read, "[fyi] updates need no reply") != null);
}
+test "#1137 room mail after an ordinary final answer stays parked; a DM still wakes" {
+ peer_inbox.resetForTest();
+ resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ resetForTest();
+ }
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var buf: [256]u8 = undefined;
+ // The human's task ended with an ordinary answer, not attempt_completion.
+ noteTurnStart();
+ noteFinalAnswer();
+ noteTurnEnd();
+ try std.testing.expect(!idleWakeSuppressed());
+ // Two unmarked scope updates posted to the folder's room, read in between.
+ const scope: presence_chan.Message = .{ .from_pid = 2, .from_start = 1, .from_session = "s-a", .text = "I only touch gui/src" };
+ _ = peer_inbox.parkHeard(&.{scope}, &.{});
+ try std.testing.expect(takeIdleWake(io, &buf) == null);
+ try std.testing.expectEqual(@as(usize, 1), peer_inbox.unread()); // still readable
+ _ = try peer_inbox.takeAll(arena_state.allocator());
+ noteInboxConsumed();
+ const other: presence_chan.Message = .{ .from_pid = 3, .from_start = 1, .from_session = "s-b", .text = "docs are mine this hour" };
+ _ = peer_inbox.parkHeard(&.{other}, &.{});
+ try std.testing.expect(takeIdleWake(io, &buf) == null);
+ // A request addressed to this session is explicit: it starts a turn.
+ const ask: presence_chan.Message = .{ .from_pid = 2, .from_start = 1, .from_session = "s-a", .text = "can you rerun the parser tests?", .to = "s-me" };
+ _ = peer_inbox.parkHeard(&.{ask}, &.{});
+ const wake = takeIdleWake(io, &buf) orelse return error.ExpectedDirectWake;
+ try std.testing.expect(std.mem.indexOf(u8, wake, "[peer]") != null);
+ // An fyi DM never does.
+ _ = peer_inbox.takeAll(arena_state.allocator()) catch unreachable;
+ noteInboxConsumed();
+ const fyi_dm: presence_chan.Message = .{ .from_pid = 2, .from_start = 1, .from_session = "s-a", .text = "[fyi] done with the parser", .to = "s-me" };
+ _ = peer_inbox.parkHeard(&.{fyi_dm}, &.{});
+ try std.testing.expect(takeIdleWake(io, &buf) == null);
+ // The next human prompt starts a new task: room mail can wake again.
+ noteHumanPrompt();
+ _ = peer_inbox.parkHeard(&.{scope}, &.{});
+ try std.testing.expect(takeIdleWake(io, &buf) != null);
+}
+
+test "#1137 a turn that ended without an answer still wakes on room mail" {
+ peer_inbox.resetForTest();
+ resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ resetForTest();
+ }
+ var buf: [256]u8 = undefined;
+ // Interrupted or failed: no final answer, nothing settled.
+ noteTurnStart();
+ noteTurnEnd();
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-a", .text = "can someone rerun the tests?" }}, &.{});
+ try std.testing.expect(takeIdleWake(std.testing.io, &buf) != null);
+}
+
+test "#1137 every root final answer settles the turn" {
+ const src = @embedFile("agent_turn.zig");
+ const start = std.mem.indexOf(u8, src, "if (done) |final_text| {") orelse return error.MissingPin;
+ const body = src[start..];
+ // The ordinary final settles once, right before it returns the answer.
+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, body, "settleFinal(self);"));
+ const settle = std.mem.indexOf(u8, body, "settleFinal(self);").?;
+ try std.testing.expect(std.mem.indexOfPos(u8, body, settle, "return review_deadline.finish(text);") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, "noteFinalAnswer()") != null);
+}
+
test "daddy idle wake fires after attempt_completion" {
peer_inbox.resetForTest();
resetForTest();
diff --git a/src/peer_inbox.zig b/src/peer_inbox.zig
index 2d0f0411..072d0135 100644
--- a/src/peer_inbox.zig
+++ b/src/peer_inbox.zig
@@ -98,6 +98,18 @@ pub fn anyNeedsTurnFrom(from: usize) bool {
return false;
}
+/// Whether any message parked at or after `from` was addressed to this
+/// session (a DM, or the user's own `/tell` on the device room) and asks for
+/// a turn. Unaddressed posts in this folder's room are ambient.
+pub fn anyAddressedNeedsTurnFrom(from: usize) bool {
+ var i = from;
+ while (i < g_len) : (i += 1) {
+ const p = itemAt(i);
+ if ((p.dm or p.device) and !isFyi(textSlice(p))) return true;
+ }
+ return false;
+}
+
pub fn anyTextPrefixed(want: []const u8) bool {
var i: usize = 0;
while (i < g_len) : (i += 1) {
diff --git a/src/peer_wake_loop.zig b/src/peer_wake_loop.zig
index b23b71d5..082a9bba 100644
--- a/src/peer_wake_loop.zig
+++ b/src/peer_wake_loop.zig
@@ -12,9 +12,11 @@ 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).
+/// never placed after a human prompt (that would steal authority). After a
+/// final answer, room mail is held for the next human prompt.
pub fn shouldInjectAuthoritative(busy: bool, newly_parked: usize) bool {
- return !busy and newly_parked > 0 and !peer_idle.idleWakeSuppressed();
+ return !busy and newly_parked > 0 and !peer_idle.idleWakeSuppressed() and
+ !peer_idle.ambientHeld(peer_inbox.unread() -| newly_parked);
}
/// Same unread generation is exposed at most once. Busy does not block a
@@ -88,6 +90,59 @@ test "#1137 peer arrival between tool batches is not an authoritative user turn"
peer_idle.noteTurnEnd();
}
+fn humanTurns(msgs: []const std.json.Value) usize {
+ var n: usize = 0;
+ for (msgs) |m| {
+ if (session_peer.isHumanUserTurn(m)) n += 1;
+ }
+ return n;
+}
+
+test "#1137 peer batches during tool work, then a final answer: no new turn, no reopened task" {
+ 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);
+ var buf: [256]u8 = undefined;
+
+ // Multi-step tool work: room mail lands at two step boundaries.
+ peer_idle.noteTurnStart();
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 2, .from_start = 1, .from_session = "s-a", .text = "I only touch gui/src" }}, &.{});
+ try std.testing.expect(!shouldInjectAuthoritative(peer_idle.isBusy(), 1));
+ placeWaitingBeforeHuman(&root);
+ try root.messages.append(try @import("messages.zig").textMessage(a, "assistant", "reading the lexer"));
+ _ = peer_inbox.parkHeard(&.{.{ .from_pid = 3, .from_start = 1, .from_session = "s-b", .text = "docs are mine this hour" }}, &.{});
+ try std.testing.expect(!shouldInjectAuthoritative(peer_idle.isBusy(), 1));
+ placeWaitingBeforeHuman(&root);
+ // The human prompt is still the only authoritative user turn.
+ try std.testing.expectEqual(@as(usize, 1), humanTurns(root.messages.items));
+ try std.testing.expect(!session_peer.isHumanUserTurn(root.messages.items[root.messages.items.len - 1]));
+
+ // The turn ends with an ordinary final answer. The parked room mail must
+ // not reopen it, by idle wake or by a history inject.
+ try root.messages.append(try @import("messages.zig").textMessage(a, "assistant", "The parser is fine."));
+ peer_idle.noteFinalAnswer();
+ peer_idle.noteTurnEnd();
+ try std.testing.expect(peer_idle.takeIdleWake(std.testing.io, &buf) == null);
+ try std.testing.expect(!shouldInjectAuthoritative(false, 1));
+ try std.testing.expectEqual(@as(usize, 2), peer_inbox.unread());
+
+ // A later human turn still sees the waiting mail, ahead of its prompt.
+ try root.messages.append(try userText(a, "next task"));
+ placeWaitingBeforeHuman(&root);
+ const items = root.messages.items;
+ try std.testing.expect(session_peer.isHumanUserTurn(items[items.len - 1]));
+ try std.testing.expect(peer_context.isPeerInject(items[items.len - 2]));
+}
+
test "#1137 duplicate unread state is idempotent" {
peer_inbox.resetForTest();
peer_idle.resetForTest();