Skip to content

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

Python

feat(peer): pull inbox/list instead of pushing the room into history

Cursor Agent86616c0aae90
diff --git a/docs/adr/0004-peer-speech-is-a-working-set.md b/docs/adr/0004-peer-speech-is-a-working-set.md
index 90739b3e..1467f52b 100644
--- a/docs/adr/0004-peer-speech-is-a-working-set.md
+++ b/docs/adr/0004-peer-speech-is-a-working-set.md
@@ -1,48 +1,48 @@
# 0004. Peer speech is a working set, not the conversation
-Status: accepted 2026-08-18
+Status: accepted 2026-08-18 (amended 2026-08-18: pull, not push)
## Context
-#469 injects co-resident speech into history as `role: user` (`[peer message
-from …]`, plus a presence roster). Each `deliverInbound` **appends** another
-blob that lives until generic compaction. Compaction then treats those blobs
-as the human: `cleanUserTurn` is true, so `recentContextStart` will keep the
-peer firehose in the ~8k verbatim suffix and summarize the real prompt away,
-and `emergencyCutIndex` can restart the conversation on a coordination ping.
+#469 used to inject co-resident speech into history as `role: user`
+(`[peer message from …]`, plus a presence roster). Each `deliverInbound`
+**appended** another blob that lived until generic compaction. Compaction
+then treated those blobs as the human: `cleanUserTurn` is true, so
+`recentContextStart` kept the peer firehose in the ~8k verbatim suffix
+and summarized the real prompt away.
-That is already a measured failure. `-p` one-shots seek the room to its tail
-because ~4k tokens of stale chatter on the first step made ephemeral workers
-*answer old messages*. Interactive sessions still dump up to 10 backlog lines
-into history (the REPL only *shows* 2).
+That is a measured failure. `-p` one-shots seek the room to its tail
+because ~4k tokens of stale chatter on the first step made ephemeral
+workers *answer old messages*. Interactive sessions still dumped roster
++ clipped bodies + a footer into every later request.
-Surgically deleting those lines from live history is also wrong: it busts the
-prompt-cache prefix, rewrites inbound the model already answered, and can eat
-a trailing unreplied inject if compact runs between drain and reply. The
-append-only JSONL room is the log; history is not a second copy of it.
+Claude Code's product split is list / send / per-agent inbox — pull, not
+a chat firehose. Anthropic's global-workspace write-up is interpretability
+inside one model, not a multi-agent product; the useful borrow is the
+tiny bottleneck, not J-space.
## Decision
- The worktree/device JSONL room is the source of truth. History holds a
- **working set**: a short roster when the live set changes, and only the
- newest few inbound lines (byte-capped). `-p` still hears nothing that
- predates the process.
-- Peer injects are not a human user turn. `cleanUserTurn`,
+ **one-line `[peer]` wake** when new inbound is parked. Bodies wait in a
+ process-local ring (`peer_inbox.zig`). The model pulls with
+ `peer_message action=inbox` and `action=list`. No roster essay, no
+ full text, no footer paragraph in history.
+- Peer injects (wakes and leftover `[peer message]` / `[presence]` lines
+ in old transcripts) are not a human user turn. `cleanUserTurn`,
`recentContextStart`, `emergencyCutIndex`, and `dropPriorTurnReasoning`
ignore them as conversation boundaries.
- Forget at compact, never mid-turn. The summarizer does not see peer
- injects. The kept suffix drops *spent* injects (a later turn already
- followed them) and keeps a trailing *unreplied* inject. `durableState`
- restates who is live now, not quoted speech.
-- Do not reopen device-wide model `"all"`. Do not invent a lock-claim parser
- here; the collision gate remains the safety net for a forgotten "I'm
- editing foo".
+ injects. The kept suffix drops *spent* injects and keeps a trailing
+ *unreplied* wake. `durableState` restates a **count**, not names and
+ goals.
+- Do not reopen device-wide model `"all"`. Do not spawn a standing
+ liaison. The collision gate remains the mutate-time wake.
## Consequences
- Two sessions can talk without the room becoming another uncapped tool
- output. `/peek` and a later `peer_peek` re-read the log from disk.
-- A compact that runs on a pending inbound does not swallow it.
-- Revisit when structured claims exist (issue #563, later lock-claim slice):
- a live path+intent may then survive compact as harness state, the same way
- the goal checklist does.
+ output. The human still sees the full `session_notice` lines.
+- A compact that runs on a pending wake does not swallow it.
+- Revisit when structured claims exist (issue #563, later lock-claim
+ slice): a live path+intent may then survive compact as harness state.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 696f0a17..f9622e13 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -14,7 +14,7 @@ record only when you need the evidence or the edge cases.
| [0001](0001-structured-outputs-are-a-formatting-step.md) | Structured output is a final formatting step. Never constrain the agentic phase with a schema grammar, and do not use `--output-schema` unless a program consumes the result. |
| [0002](0002-xai-defaults-to-the-responses-wire.md) | xAI runs on the Responses wire by default (WS turns, lossless server compaction). `GRAFF_XAI_WIRE=chat` opts out; WS stays an explicit provider list. |
| [0003](0003-codegraff-wire-follows-model-capability.md) | Codegraff uses Responses + WS for GPT-5.6 and grok-4.6 aliases; Claude, Gemini, and other aliases stay on Chat Completions. |
-| [0004](0004-peer-speech-is-a-working-set.md) | Peer speech is a working set in history, not a second copy of the room; compact drops spent injects and never treats them as the human. |
+| [0004](0004-peer-speech-is-a-working-set.md) | Peer speech is pull: a one-line `[peer]` wake in history, bodies in the inbox ring; compact drops spent injects and never treats them as the human. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 86362b5e..aaac0afd 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -47,5 +47,7 @@
{"id": "peer-message-without-peer-errors-clean", "why": "#469 phase 2: with no live peer, peer_message must come back as a clean error that says so - never a fake delivery, never a crash. The regression is a send reported into the void.", "args": [], "prompt": "tell the other session to hold off", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src"}}, {"text": "nobody to tell"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "[error] no live co-resident"}}]}
{"id": "peer-checkpoint-blocks-file-writes", "why": "#469: the once-per-peer checkpoint must guard the files themselves, not only git - the incident's other vector was one session moving/editing files the other had open. A live peer makes the first write_file come back un-executed, and the identical retry lands.", "live_peer": true, "args": [], "prompt": "create notes.txt with hello in it", "script": [{"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"text": "created, after the checkpoint told me about the peer"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint"}}, {"request_contains": {"index": 1, "text": "another graff session already owns this worktree"}}]}
{"id": "peer-message-all-broadcasts-device-wide", "why": "#563: model \"all\" is retired — it flooded every folder. peer_message with session=all must error and tell the model to post bare or name one session. Device-wide broadcast stays the user's /tell all.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "\"all\" is retired"}}]}
-{"id": "peer-awareness-precedes-first-reply", "why": "#469: the model can only auto-decide to coordinate with sessions it knows about - with a live peer, the FIRST request must already carry the presence note (who else is live, with goals), before any collision forces the issue.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_contains": {"index": 0, "text": "other live graff session"}}, {"request_contains": {"index": 0, "text": "peer_message"}}]}
+{"id": "peer-awareness-is-pull-not-push", "why": "#563: leadership is pull. A live peer must NOT dump a roster or inbound bodies into the first request — that was the token leak. Who is live is peer_message action=list; bodies wait behind a one-line wake only when something was parked.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_lacks": {"index": 0, "text": "other live graff session"}}, {"request_lacks": {"index": 0, "text": "[peer message"}}, {"request_lacks": {"index": 0, "text": "[presence]"}}]}
+{"id": "peer-message-list-names-live-peer", "why": "#563: action=list is ListAgents. With a live peer the tool result must name that they are live, not error, and not require text.", "live_peer": true, "args": [], "prompt": "who else is here", "script": [{"tool": "peer_message", "arguments": {"action": "list"}}, {"text": "saw them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "live"}}]}
+{"id": "peer-message-inbox-empty-when-quiet", "why": "#563: action=inbox is the mailbox. With nothing parked it must say so in the tool result — never invent a body, never require text.", "args": [], "prompt": "check the peer inbox", "script": [{"tool": "peer_message", "arguments": {"action": "inbox"}}, {"text": "nothing waiting"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "inbox empty"}}]}
{"id": "readonly-exact-key-prefers-one-search", "why": "Named-file guidance forced a whole-file read before an exact-key search, adding avoidable context and a provider round trip. A read-only keyed lookup should call read_file once with contains set to the exact key, answer from the numbered match, and never read the entire file.", "args": [], "workspace_seed": {"catalog.py": "SKU0001 = {'price': 100, 'stock': 1}\nSKU0002 = {'price': 200, 'stock': 2}\nSKU0420 = {'price': 31415, 'stock': 27}\nSKU0900 = {'price': 900, 'stock': 9}\n"}, "prompt": "Read catalog.py without editing it. Find SKU0420. Reply with exactly one line in the format SKU0420|price=<price>|stock=<stock> and nothing else.", "script": [{"tool": "read_file", "arguments": {"path": "catalog.py", "contains": "SKU0420"}}, {"text": "SKU0420|price=31415|stock=27"}], "assert": [{"request_contains": {"index": 0, "text": "contains set to the exact key"}}, {"event": {"type": "tool_call", "name": "read_file"}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 1}}, {"final_text_contains": "SKU0420|price=31415|stock=27"}]}
diff --git a/src/agent_tool_render.zig b/src/agent_tool_render.zig
index 2b65f9f8..17a7ac3f 100644
--- a/src/agent_tool_render.zig
+++ b/src/agent_tool_render.zig
@@ -65,10 +65,12 @@ fn toolDetail(t: ToolInvocation) []const u8 {
"description"
else if (std.mem.eql(u8, t.name, "imagegen"))
"prompt"
- else if (std.mem.eql(u8, t.name, "peer_message"))
- "text"
- else
- return "";
+ else if (std.mem.eql(u8, t.name, "peer_message")) blk: {
+ if (stringField(t.input, "action")) |act| {
+ if (act.len > 0 and !std.mem.eql(u8, act, "send")) break :blk "action";
+ }
+ break :blk "text";
+ } else return "";
const detail = stringField(t.input, field) orelse return "";
const end = std.mem.indexOfScalar(u8, detail, '\n') orelse detail.len;
return std.mem.trim(u8, detail[0..end], " \t\r");
diff --git a/src/compact_handoff_note.zig b/src/compact_handoff_note.zig
index 115a92d8..84131103 100644
--- a/src/compact_handoff_note.zig
+++ b/src/compact_handoff_note.zig
@@ -68,8 +68,9 @@ const persists_note =
\\disk cannot give back - the decisions and why they were made, what was tried
\\and failed, the constraints the user set, and the exact state of the
\\unfinished work. Peer-channel notes are a working set, not the conversation:
- \\do not transcribe [peer message] or [presence] lines; the harness drops them
- \\and restates who is still live after this summary (the room log stays on disk).
+ \\do not transcribe [peer] wakes or [peer message] or [presence] lines; the
+ \\harness drops them. Who is live and what they said are pull: peer_message
+ \\action=list / action=inbox (the room log stays on disk).
;
/// The user message compact() sends to ask for the handoff summary: the
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index 844b8397..34500607 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -1,17 +1,16 @@
//! The #469 channel half: what co-resident root sessions SAY to each other,
//! on top of what presence.zig knows (WHO is out there, liveness-probed).
//!
-//! Four surfaces, one inbox primitive:
-//! - peer_message: the model-facing tool, so a session can coordinate the
-//! way a parent steers a subagent — "I'm restructuring gui/src, hold" —
-//! except sideways, between roots. Queued, one-way, never synchronous.
+//! Claude-style pull (token-maxxing): history does not eat the room. Bodies
+//! park in peer_inbox.zig; the model reads them with `action=inbox` and
+//! discovers who is live with `action=list`. deliverInbound injects a
+//! one-line `[peer]` wake and still paints the full lines for the human.
+//!
+//! Surfaces:
+//! - peer_message: send (default), list, inbox. Queued, one-way.
//! - /tell <session> <text>: the user's own line into a peer's inbox.
//! - /sessions: the saved-session list gains a "live now" section.
-//! - deliverInbound: drains the channel at every step boundary of the turn
-//! loop (agent.runTurn), so a peer's message lands mid-task — between tool
-//! batches — as a first-class note, durable in history and visible to the
-//! user as an event. True mid-request injection (interrupting a streamed
-//! response) remains #430 territory; step boundaries are the safe seams.
+//! - deliverInbound: drain + park at every root step boundary.
const std = @import("std");
@@ -26,6 +25,7 @@ const presence_chan = @import("presence_chan.zig");
const worktree_lease = @import("worktree_lease.zig");
const repl = @import("repl.zig");
const peer_context = @import("peer_context.zig");
+const peer_inbox = @import("peer_inbox.zig");
const peer_target = @import("peer_target.zig");
const Agent = agent_mod.Agent;
@@ -34,9 +34,9 @@ const ExecResult = tools_mod.ExecResult;
const Owner = worktree_lease.Owner;
pub const tool_name = "peer_message";
-pub const tool_desc = "Ping a co-resident graff session, or the folder room. Omit session to post to this folder (everyone here hears it). Set session to ping ONE peer: exact session name, pid, unique name fragment, or unique goal fragment (the one doing that work). A named target is a DM — only they hear it. Cross-folder names ride the device room. Device-wide broadcast is the user's /tell all, not this tool. Delivery is queued and one-way: the tool result names who you pinged, never a reply.";
+pub const tool_desc = "Ping a co-resident session, list who is live, or read parked inbound. action=list | inbox | send (default). session is a DM (id/pid/name/goal); omit for this folder's room. Not \"all\".";
pub const tool_schema =
- \\{"type": "object", "properties": {"session": {"type": "string", "description": "who to ping: exact session name, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent"}}, "required": ["text"]}
+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox"], "description": "send (default): ping a peer. list: who is live. inbox: read+clear parked inbound."}, "session": {"type": "string", "description": "who to ping: exact session name, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}}}
;
/// Whether the named session sits in MY worktree (routes the post: worktree
@@ -61,7 +61,19 @@ fn peerListText(arena: Allocator, peers: []const Owner) []const u8 {
pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {
const obj = tools_mod.json_args.object(call.input) orelse return .{
- .text = "peer_message needs an object input with a text field",
+ .text = "peer_message needs an object input",
+ .is_error = true,
+ };
+ const action = tools_mod.json_args.str(obj, "action") orelse "send";
+ if (std.mem.eql(u8, action, "list")) {
+ const everyone = presence.liveAllPeers(self.io, self.arena);
+ return .{ .text = peer_inbox.formatList(self.arena, everyone, presence.ownIdentity()), .is_error = false };
+ }
+ if (std.mem.eql(u8, action, "inbox")) {
+ return .{ .text = peer_inbox.takeAll(self.arena), .is_error = false };
+ }
+ if (!std.mem.eql(u8, action, "send")) return .{
+ .text = "peer_message action must be send, list, or inbox",
.is_error = true,
};
const text = tools_mod.json_args.str(obj, "text") orelse "";
@@ -109,46 +121,11 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {
};
}
-var g_peer_fp: u64 = 0; // fingerprint of the last-injected awareness note
-var g_peer_note_rewrites: u64 = 0; // history_rewrites when it was injected
-
-/// The proactive half of #469: the model can only auto-decide to coordinate
-/// with sessions it KNOWS about — this renders the live peer set (who, where,
-/// what goal) as a context note. Returned only when the set changed since the
-/// last injection, or a history rewrite may have compacted the note away, so
-/// a steady peer set costs zero tokens. Null while the device has no peers at
-/// all and none were ever announced — solo sessions never hear about this.
-fn peerNoteIfChanged(root: *Agent) ?[]const u8 {
- const peers = presence.liveAllPeers(root.io, root.arena);
- if (peers.len == 0 and g_peer_fp == 0) return null;
- var buf: std.ArrayList(u8) = .empty;
- if (peers.len == 0) {
- buf.appendSlice(root.arena, "[presence] the other live graff sessions are gone — the shared tree is yours alone now.") catch return null;
- } else {
- const mine = presence.ownIdentity();
- buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, "[presence] {d} other live graff session(s):", .{peers.len}) catch return null) catch return null;
- for (peers) |p| {
- const where: []const u8 = if (std.mem.eql(u8, p.identity, mine)) "this folder" else p.identity;
- const goal = peer_context.clip(if (p.goal.len > 0) p.goal else "?", 40);
- buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, " {s} ({s}, {s});", .{ p.session_id, goal, where }) catch break) catch break;
- }
- buf.appendSlice(root.arena, " Name a session (id, pid, or a unique goal fragment) to DM them; omit session for this folder's room.") catch {};
- }
- const text = buf.items;
- const fp = std.hash.Wyhash.hash(0, text);
- if (fp == g_peer_fp and root.history_rewrites == g_peer_note_rewrites) return null;
- g_peer_fp = fp;
- g_peer_note_rewrites = root.history_rewrites;
- return text;
-}
-
/// The receiving half, called at every step boundary of a root agent's turn:
-/// queued peer messages plus the peer-awareness note become one durable
-/// user-role note in history plus user-visible events. Never fails a turn —
-/// delivery trouble is silence, not an error, because a peer must never break
-/// our session.
-/// The room tail a late joiner hears in full; anything older collapses into
-/// one "N omitted" marker instead of flooding the first history note.
+/// drain the rooms, park heard bodies, paint them for the human, and inject
+/// at most a one-line `[peer]` wake. Never fails a turn — delivery trouble
+/// is silence, not an error, because a peer must never break our session.
+/// The room tail a late joiner parks; anything older is seek-skipped.
pub const backlog_tail_max = 10;
var g_backlog_tail_cut = false;
@@ -166,7 +143,6 @@ fn displayWindow(is_backlog: bool, count: usize) DisplayWindow {
pub fn deliverInbound(root: *Agent) void {
if (root.sub) return;
- const note = peerNoteIfChanged(root);
var local_msgs = presence.drainChannel(root.io, root.arena);
var device_msgs = presence.drainDevice(root.io, root.arena);
// Only the process's FIRST drain carries the rooms' whole backlog; later
@@ -181,8 +157,6 @@ pub fn deliverInbound(root: *Agent) void {
local_msgs = local_msgs[dl..];
device_msgs = device_msgs[dd..];
}
- if (note == null and local_msgs.len == 0 and device_msgs.len == 0 and omitted == 0) return;
- const sink = engine_sink.forAgent(root);
const own = presence.ownSession();
// Named worktree posts are DMs; the JSONL still has the line.
var tree_heard: std.ArrayList(presence.Message) = .empty;
@@ -196,75 +170,42 @@ pub fn deliverInbound(root: *Agent) void {
if (peer_target.deviceHears(m, own)) heard.append(root.arena, m) catch break else skipped += 1;
}
device_msgs = heard.items;
+ if (local_msgs.len == 0 and device_msgs.len == 0 and omitted == 0 and skipped == 0) return;
+ const sink = engine_sink.forAgent(root);
// The visible block gets one blank line of air on either side: peer lines
// land mid-stream at a step boundary and used to butt straight against
// the assistant text above and whatever follows below — one clump.
const window = displayWindow(is_backlog_drain, local_msgs.len + device_msgs.len);
const any_visible = local_msgs.len + device_msgs.len > window.start or
- (repl.g_debug and (note != null or omitted > 0 or skipped > 0 or window.hidden > 0));
- var buf: std.ArrayList(u8) = .empty;
- // Debug-only notices ride inside the block's bracket, in drain order.
+ (repl.g_debug and (omitted > 0 or skipped > 0 or window.hidden > 0));
var markers: std.ArrayList([]const u8) = .empty;
- if (note) |n| {
- buf.appendSlice(root.arena, n) catch {};
- buf.append(root.arena, '\n') catch {};
- if (repl.g_debug) markers.append(root.arena, n) catch {};
- }
- if (omitted > 0) {
+ if (omitted > 0 and repl.g_debug) {
const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} older message(s) predating this session omitted]", .{omitted}) catch "";
- if (marker.len > 0) {
- buf.appendSlice(root.arena, marker) catch {};
- buf.append(root.arena, '\n') catch {};
- if (repl.g_debug) markers.append(root.arena, marker) catch {};
- }
+ if (marker.len > 0) markers.append(root.arena, marker) catch {};
}
- if (skipped > 0) {
+ if (skipped > 0 and repl.g_debug) {
const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} message(s) not addressed to this session skipped — folder-scoped hearing]", .{skipped}) catch "";
- if (marker.len > 0 and repl.g_debug) markers.append(root.arena, marker) catch {};
+ if (marker.len > 0) markers.append(root.arena, marker) catch {};
}
- var lines: std.ArrayList([]const u8) = .empty;
- const hist = peer_context.historyWindow(is_backlog_drain, local_msgs.len + device_msgs.len);
- if (hist.hidden > 0) {
- const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} backlog message(s) omitted from context — keeping last {d}]", .{ hist.hidden, peer_context.history_tail_max }) catch "";
- if (marker.len > 0) {
- buf.appendSlice(root.arena, marker) catch {};
- buf.append(root.arena, '\n') catch {};
- }
+ if (window.hidden > 0 and repl.g_debug) {
+ const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} backlog message(s) showing last {d}]", .{ window.hidden, backlog_repl_show }) catch "";
+ if (marker.len > 0) markers.append(root.arena, marker) catch {};
}
- var line_i: usize = 0;
- var room_line = false;
- var dm_from: []const u8 = "";
+ var lines: std.ArrayList([]const u8) = .empty;
for ([2][]const presence.Message{ local_msgs, device_msgs }, [2][]const u8{ "", " · device" }) |msgs, scope| {
for (msgs) |m| {
const goal = if (m.from_goal.len > 0) std.fmt.allocPrint(root.arena, " (goal: {s})", .{peer_context.clip(m.from_goal, 40)}) catch "" else "";
const to = if (m.to.len == 0) "" else if (peer_target.addressedTo(m.to, own)) " → you" else std.fmt.allocPrint(root.arena, " → {s}", .{m.to}) catch "";
const line = std.fmt.allocPrint(root.arena, "[peer message from {s}{s}{s}{s}]: {s}", .{ m.from_session, goal, to, scope, peer_context.clip(m.text, peer_context.line_clip) }) catch continue;
- if (m.to.len == 0) room_line = true else if (dm_from.len == 0) dm_from = m.from_session;
- if (line_i >= hist.start) {
- buf.appendSlice(root.arena, line) catch {};
- buf.append(root.arena, '\n') catch {};
- }
lines.append(root.arena, line) catch {};
- line_i += 1;
}
}
- // History gets the working-set tail (ADR 0004); the REPL prints only the
- // last backlog_repl_show of a first-drain so a resume is not a wall.
- if (window.hidden > 0) {
- const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} backlog message(s) delivered to context — showing last {d}]", .{ window.hidden, backlog_repl_show }) catch "";
- if (marker.len > 0 and repl.g_debug) markers.append(root.arena, marker) catch {};
- }
renderPeerBlock(sink, root.io, any_visible, markers.items, lines.items[window.start..]);
- if (buf.items.len == 0) return;
- if (!room_line and dm_from.len > 0) {
- const hint = std.fmt.allocPrint(root.arena, "(this ping is for you — reply with peer_message session=\"{s}\")", .{dm_from}) catch "(this ping is for you — reply with the peer_message tool)";
- buf.appendSlice(root.arena, hint) catch {};
- } else {
- buf.appendSlice(root.arena, "(reply with peer_message — omit session for the room, or name one peer to DM)") catch {};
- }
+ if (peer_inbox.parkHeard(local_msgs, device_msgs) == 0) return;
+ // History gets the wake only (ADR 0004). Bodies wait in the ring.
var obj: std.json.ObjectMap = .empty;
obj.put(root.arena, "role", .{ .string = "user" }) catch return;
- obj.put(root.arena, "content", .{ .string = peer_context.capInject(buf.items) }) catch return;
+ obj.put(root.arena, "content", .{ .string = peer_context.capInject(peer_inbox.formatWake(root.arena)) }) catch return;
root.messages.append(.{ .object = obj }) catch {};
}
diff --git a/src/peer_context.zig b/src/peer_context.zig
index 7e47bf59..6e2510aa 100644
--- a/src/peer_context.zig
+++ b/src/peer_context.zig
@@ -1,12 +1,13 @@
//! Peer speech in the model's history is a working set, not the conversation
-//! (ADR 0004 / #563 slice F).
+//! (ADR 0004 / #563).
//!
-//! The JSONL room in presence_chan.zig is the log. deliverInbound copies a
-//! short tail into a user-role note so the model can coordinate *this step*.
-//! Those notes are perishable: they are not a human turn, they must not fence
-//! compaction or emergency trim, and compact drops every spent one (a later
-//! turn already followed it) while keeping a trailing unreplied inject so a
-//! compact between drain and reply cannot swallow inbound.
+//! The JSONL room in presence_chan.zig is the log. deliverInbound parks
+//! bodies in peer_inbox.zig and injects a one-line `[peer]` wake so the
+//! model knows to `action=inbox`. Those wakes are perishable: they are not
+//! a human turn, they must not fence compaction or emergency trim, and
+//! compact drops every spent one (a later turn already followed it) while
+//! keeping a trailing unreplied inject so a compact between drain and
+//! reply cannot swallow the wake.
//!
//! Detection is prefix-based because that is how the inject is serialized
//! today. Slice C can replace the fake user role; until then every compact
@@ -24,9 +25,9 @@ const presence = @import("presence.zig");
/// keeps the rest; the REPL show-count (2) is a display cap, not this.
pub const history_tail_max: usize = 3;
-/// Hard ceiling on one deliverInbound blob, so a long roster plus a few
-/// clipped lines cannot become another uncapped tool output.
-pub const inject_byte_cap: usize = 800;
+/// Hard ceiling on one deliverInbound wake. The bodies live in the inbox
+/// ring; this is only the one-liner that says they are waiting.
+pub const inject_byte_cap: usize = 240;
/// Per-line clip inside that blob. The tool already asks for one or two
/// sentences; the receiver enforces it.
@@ -34,6 +35,7 @@ pub const line_clip: usize = 200;
pub fn isPeerInjectContent(s: []const u8) bool {
const t = std.mem.trimStart(u8, s, " \t\r\n");
+ if (std.mem.startsWith(u8, t, "[peer]")) return true;
if (std.mem.startsWith(u8, t, "[peer message")) return true;
if (std.mem.startsWith(u8, t, "[presence]")) return true;
if (std.mem.startsWith(u8, t, "[#469 presence]")) return true;
@@ -101,24 +103,13 @@ pub fn appendWorkingSet(dest: *std.json.Array, kept: []const Value, original: []
}
}
-/// One durable-state line naming who is live *now*. Speech stays in the
-/// JSONL room; quoting it here would just survive compact as another leak.
+/// One durable-state line: a count, not the roster. `action=list` is the
+/// pull; quoting names and goals here would just survive compact as another
+/// leak.
pub fn durableRosterLine(arena: Allocator, io: Io) !?[]const u8 {
const peers = presence.liveAllPeers(io, arena);
if (peers.len == 0) return null;
- var buf: std.ArrayList(u8) = .empty;
- try buf.appendSlice(arena, "- live co-resident sessions (working set; speech is in the worktree channel, not this summary): ");
- for (peers, 0..) |p, i| {
- if (i > 0) try buf.appendSlice(arena, "; ");
- const goal = if (p.goal.len > 0) clip(p.goal, 40) else "?";
- const piece = try std.fmt.allocPrint(arena, "{s} ({s})", .{ p.session_id, goal });
- try buf.appendSlice(arena, piece);
- if (buf.items.len > 240) {
- try buf.appendSlice(arena, "; …");
- break;
- }
- }
- return buf.items;
+ return try std.fmt.allocPrint(arena, "- {d} live co-resident session(s); peer_message action=list to see who (speech is pull, not this summary)", .{peers.len});
}
const testing = std.testing;
@@ -134,6 +125,7 @@ fn asstText(arena: Allocator, s: []const u8) !Value {
}
test "isPeerInjectContent: live prefixes and the #469-era strings in old transcripts" {
+ try testing.expect(isPeerInjectContent("[peer] 1 unread from s-2 — peer_message action=inbox"));
try testing.expect(isPeerInjectContent("[peer message from s-2]: hold off"));
try testing.expect(isPeerInjectContent(" [presence] 1 other live graff session(s)"));
try testing.expect(isPeerInjectContent("[#469 presence] 1 other live graff session(s)"));
diff --git a/src/peer_context_compact_test.zig b/src/peer_context_compact_test.zig
index 717e9943..556e12ec 100644
--- a/src/peer_context_compact_test.zig
+++ b/src/peer_context_compact_test.zig
@@ -11,6 +11,7 @@ test "cleanUserTurn: a peer inject is not a human user turn" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
+ try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[peer] 1 unread from a — peer_message action=inbox")));
try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[peer message from a]: hold gui/src")));
try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[presence] 1 other live graff session(s)")));
try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[#469 presence] leftover from a resumed transcript")));
diff --git a/src/peer_inbox.zig b/src/peer_inbox.zig
new file mode 100644
index 00000000..e14c0382
--- /dev/null
+++ b/src/peer_inbox.zig
@@ -0,0 +1,218 @@
+//! Process-local parked inbound for `peer_message` (Claude-style pull).
+//!
+//! The JSONL room is the log. `deliverInbound` does not copy bodies into
+//! history — it parks a small ring here and injects a one-line `[peer]` wake.
+//! `action=inbox` reads+clears; `action=list` is who is live. Bodies never
+//! ride every later request unless the model asked. A standing liaison is
+//! still the wrong shape (ADR 0004): this is a mailbox, not another model.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+const peer_context = @import("peer_context.zig");
+const presence_chan = @import("presence_chan.zig");
+const worktree_lease = @import("worktree_lease.zig");
+
+const Message = presence_chan.Message;
+const Owner = worktree_lease.Owner;
+
+/// How many inbound bodies the process will hold. Older ones fall out; the
+/// room still has them on disk.
+pub const inbox_cap: usize = 8;
+
+const from_cap: usize = 48;
+const text_cap: usize = 200;
+
+const Parked = struct {
+ from: [from_cap]u8 = undefined,
+ from_len: u8 = 0,
+ text: [text_cap]u8 = undefined,
+ text_len: u8 = 0,
+ dm: bool = false,
+ device: bool = false,
+};
+
+var g_items: [inbox_cap]Parked = undefined;
+var g_head: usize = 0;
+var g_len: usize = 0;
+
+pub fn resetForTest() void {
+ g_head = 0;
+ g_len = 0;
+}
+
+pub fn unread() usize {
+ return g_len;
+}
+
+fn copyInto(dest: []u8, src: []const u8) u8 {
+ const n = @min(dest.len, src.len);
+ @memcpy(dest[0..n], src[0..n]);
+ return @intCast(n);
+}
+
+fn parkOne(from: []const u8, text: []const u8, dm: bool, device: bool) void {
+ if (g_len == inbox_cap) {
+ g_head = (g_head + 1) % inbox_cap;
+ g_len -= 1;
+ }
+ const i = (g_head + g_len) % inbox_cap;
+ var item: Parked = .{ .dm = dm, .device = device };
+ item.from_len = copyInto(&item.from, from);
+ item.text_len = copyInto(&item.text, peer_context.clip(text, text_cap));
+ g_items[i] = item;
+ g_len += 1;
+}
+
+/// Copy heard room/device lines into the ring. Returns how many we parked
+/// (overflow still counts as parked — the newest stay). Pointers are copied
+/// into static buffers because the drain's arena may reset next step.
+pub fn parkHeard(local: []const Message, device: []const Message) usize {
+ var n: usize = 0;
+ for (local) |m| {
+ parkOne(m.from_session, m.text, m.to.len > 0, false);
+ n += 1;
+ }
+ for (device) |m| {
+ parkOne(m.from_session, m.text, m.to.len > 0, true);
+ n += 1;
+ }
+ return n;
+}
+
+fn itemAt(i: usize) Parked {
+ return g_items[(g_head + i) % inbox_cap];
+}
+
+fn fromSlice(p: Parked) []const u8 {
+ return p.from[0..p.from_len];
+}
+
+fn textSlice(p: Parked) []const u8 {
+ return p.text[0..p.text_len];
+}
+
+/// One-line history wake. Cheap on purpose: the bodies wait in the ring.
+pub fn formatWake(arena: Allocator) []const u8 {
+ if (g_len == 0) return "[peer] 0 unread — peer_message action=inbox";
+ const first = fromSlice(itemAt(0));
+ var extra: usize = 0;
+ var i: usize = 1;
+ while (i < g_len) : (i += 1) {
+ if (!std.mem.eql(u8, fromSlice(itemAt(i)), first)) extra += 1;
+ }
+ const who = if (extra == 0)
+ std.fmt.allocPrint(arena, "from {s}", .{first}) catch "from a peer"
+ else
+ std.fmt.allocPrint(arena, "from {s} + {d} more", .{ first, extra }) catch "from peers";
+ return std.fmt.allocPrint(arena, "[peer] {d} unread {s} — peer_message action=inbox", .{ g_len, who }) catch "[peer] unread — peer_message action=inbox";
+}
+
+/// Read+clear. Tool result only — does not re-enter history.
+pub fn takeAll(arena: Allocator) []const u8 {
+ if (g_len == 0) return "inbox empty";
+ var buf: std.ArrayList(u8) = .empty;
+ var i: usize = 0;
+ while (i < g_len) : (i += 1) {
+ const p = itemAt(i);
+ const flag = if (p.device and p.dm) " · device DM" else if (p.device) " · device" else if (p.dm) " · DM" else "";
+ const line = std.fmt.allocPrint(arena, "[peer message from {s}{s}]: {s}\n", .{ fromSlice(p), flag, textSlice(p) }) catch continue;
+ buf.appendSlice(arena, line) catch {};
+ }
+ buf.appendSlice(arena, "(inbox cleared — reply with peer_message; omit session for the room, or name one peer to DM)") catch {};
+ g_head = 0;
+ g_len = 0;
+ return buf.items;
+}
+
+/// Claude ListAgents: who is live, one short line each. Pull, not a push.
+pub fn formatList(arena: Allocator, peers: []const Owner, mine: []const u8) []const u8 {
+ if (peers.len == 0) return "no other live graff sessions";
+ var buf: std.ArrayList(u8) = .empty;
+ const head = std.fmt.allocPrint(arena, "{d} live:\n", .{peers.len}) catch "live:\n";
+ buf.appendSlice(arena, head) catch {};
+ for (peers) |p| {
+ const where: []const u8 = if (std.mem.eql(u8, p.identity, mine)) "this-folder" else if (p.identity.len > 0) p.identity else "?";
+ const goal = peer_context.clip(if (p.goal.len > 0) p.goal else "?", 40);
+ const line = std.fmt.allocPrint(arena, "{s} pid {d} {s} · {s}\n", .{ p.session_id, p.pid, where, goal }) catch continue;
+ buf.appendSlice(arena, line) catch {};
+ }
+ buf.appendSlice(arena, "DM with session=<id|pid|goal fragment>; omit session for this folder's room.") catch {};
+ return buf.items;
+}
+
+const testing = std.testing;
+
+fn msg(from: []const u8, text: []const u8, to: []const u8) Message {
+ return .{ .from_session = from, .text = text, .to = to };
+}
+
+fn peer(id: []const u8, pid: i32, goal: []const u8, identity: []const u8) Owner {
+ return .{ .session_id = id, .pid = pid, .goal = goal, .identity = identity };
+}
+
+test "parkHeard then takeAll formats bodies and clears the ring" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const n = parkHeard(&.{msg("session-aaa", "hold gui/src", "")}, &.{msg("session-bbb", "your turn", "session-me")});
+ try testing.expectEqual(@as(usize, 2), n);
+ try testing.expectEqual(@as(usize, 2), unread());
+ const body = takeAll(a);
+ try testing.expect(std.mem.indexOf(u8, body, "[peer message from session-aaa]: hold gui/src") != null);
+ try testing.expect(std.mem.indexOf(u8, body, "[peer message from session-bbb · device DM]: your turn") != null);
+ try testing.expectEqual(@as(usize, 0), unread());
+ try testing.expectEqualStrings("inbox empty", takeAll(a));
+}
+
+test "parkHeard: the ring drops the oldest when it overflows inbox_cap" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var i: usize = 0;
+ while (i < inbox_cap + 2) : (i += 1) {
+ const from = try std.fmt.allocPrint(a, "s-{d}", .{i});
+ const text = try std.fmt.allocPrint(a, "line {d}", .{i});
+ _ = parkHeard(&.{msg(from, text, "")}, &.{});
+ }
+ try testing.expectEqual(inbox_cap, unread());
+ const body = takeAll(a);
+ try testing.expect(std.mem.indexOf(u8, body, "line 0") == null);
+ try testing.expect(std.mem.indexOf(u8, body, "line 1") == null);
+ try testing.expect(std.mem.indexOf(u8, body, try std.fmt.allocPrint(a, "line {d}", .{inbox_cap + 1})) != null);
+}
+
+test "formatWake names the first sender and stays one line" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ _ = parkHeard(&.{msg("session-aaa", "hold", "")}, &.{});
+ const one = formatWake(a);
+ try testing.expect(std.mem.startsWith(u8, one, "[peer] 1 unread from session-aaa"));
+ try testing.expect(std.mem.indexOf(u8, one, "action=inbox") != null);
+ try testing.expect(std.mem.indexOfScalar(u8, one, '\n') == null);
+ _ = parkHeard(&.{msg("session-bbb", "go", "")}, &.{});
+ const two = formatWake(a);
+ try testing.expect(std.mem.startsWith(u8, two, "[peer] 2 unread from session-aaa + 1 more"));
+}
+
+test "formatList: one short line per peer; empty is honest" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try testing.expectEqualStrings("no other live graff sessions", formatList(a, &.{}, "here"));
+ const peers = [_]Owner{
+ peer("session-aaa", 11, "rewrite the targeting", "here"),
+ peer("session-bbb", 22, "paint chips", "/other/.git"),
+ };
+ const text = formatList(a, &peers, "here");
+ try testing.expect(std.mem.startsWith(u8, text, "2 live:\n"));
+ try testing.expect(std.mem.indexOf(u8, text, "session-aaa pid 11 this-folder · rewrite the targeting") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "session-bbb pid 22 /other/.git · paint chips") != null);
+}
diff --git a/src/peer_target.zig b/src/peer_target.zig
index e3b01a7c..f085a9c8 100644
--- a/src/peer_target.zig
+++ b/src/peer_target.zig
@@ -2,7 +2,7 @@
//!
//! The JSONL rooms stay append-only logs (ADR 0004). Delivery is the
//! working set: a bare worktree post is still a room, but a named target is
-//! a DM — only that session injects it. `session` on peer_message resolves
+//! a DM — only that session parks it. `session` on peer_message resolves
//! by exact id, pid, unique name fragment, or unique **goal** fragment so a
//! model can ping "the one doing the digest job" without guessing names.
//!
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 1d2b6c0a..0defce03 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -124,6 +124,7 @@ const compact_note = @import("compact_note.zig");
const compact_note_glue = @import("compact_note_glue.zig");
const peer_context = @import("peer_context.zig"); // ADR 0004 / #563 slice F
const peer_context_compact_test = @import("peer_context_compact_test.zig");
+const peer_inbox = @import("peer_inbox.zig"); // Claude-style list/inbox pull
const peer_target = @import("peer_target.zig"); // exact DM / goal targeting
// #345: the global-vs-project MCP config merge. mcp.zig does reference its
@@ -254,6 +255,7 @@ test {
_ = compact_note_glue;
_ = peer_context;
_ = peer_context_compact_test;
+ _ = peer_inbox;
_ = peer_target;
_ = shutdown_trace;
_ = credential_store;