graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
peer channel: one shared room per worktree, not per-session inboxes (#469)
Rach Pradhan77162b197f50
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 9a27c68e..952f1e88 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -43,5 +43,5 @@{"id": "session-recap-precedes-turn", "why": "#419: every cleanly completed turn must emit a heuristic session_recap before the terminal turn event, so stream-until-turn clients (the GUI agent overview) always learn the session's one-line state and status.", "prompt": "say hi", "script": [{"text": "hello there"}], "assert": [{"event": {"type": "session_recap", "status": "completed", "source": "heuristic", "text": "hello there"}}, {"event": {"type": "turn", "complete": true}}]}{"id": "session-recap-needs-input-heuristic", "why": "#419: a turn that ends on a question reads as needs_input without any model call - the heuristic degrade path the issue asks for when no cheap model is available.", "prompt": "what do you need", "script": [{"text": "Which file should I change?"}], "assert": [{"event": {"type": "session_recap", "status": "needs_input", "source": "heuristic"}}]}{"id": "session-recap-model-silent-without-cheap-rung", "why": "#419: the cheap-model recap is silently disabled when the provider has no ladder rung (lmstudio in the mock rig) - no event, no error, the heuristic recap still lands.", "prompt": "say hi", "script": [{"text": "hi"}], "controls_after_turn": [{"type": "set_mode", "mode": "normal"}], "assert": [{"event": {"type": "session_recap", "source": "heuristic"}}, {"no_event": {"type": "session_recap", "source": "model"}}]}-{"id": "peer-message-queued-for-live-peer", "why": "#469 phase 2: a session must be able to message a live co-resident peer (the channel half of the crosstalk fix). The regression is peer_message erroring while a peer is genuinely live, or claiming delivery it did not make.", "live_peer": true, "args": [], "prompt": "tell the other session to hold off gui/src until you land the move", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src until I land the move"}}, {"text": "told them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "queued for"}}]}+{"id": "peer-message-queued-for-live-peer", "why": "#469 phase 2: a session must be able to message a live co-resident peer (the channel half of the crosstalk fix). The regression is peer_message erroring while a peer is genuinely live, or claiming delivery it did not make.", "live_peer": true, "args": [], "prompt": "tell the other session to hold off gui/src until you land the move", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src until I land the move"}}, {"text": "told them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "posted to the worktree channel"}}]}{"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"}}]}diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex db3843cc..c1631d9e 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -30,7 +30,7 @@ pub const commands = [_]Item{.{ .name = "/loop", .usage = "/loop [30m] <prompt>", .desc = "the same autonomous run as /goal, without adopting a standing objective" },.{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },.{ .name = "/never", .usage = "/never [<text>|rm <id>]", .desc = "standing constraints that ride every subagent brief and survive compaction; bare lists them, rm <id> retires one (alias /constraint)" },- .{ .name = "/tell", .usage = "/tell <session> <text>", .desc = "message a live co-resident graff session in this folder; /sessions lists who's around" },+ .{ .name = "/tell", .usage = "/tell <session|all> <text>", .desc = "post to this folder's shared graff channel — every live session hears it; /sessions lists who's around" },.{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },.{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },.{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },diff --git a/src/commands_session.zig b/src/commands_session.zigindex a9b1cfff..59078931 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -14,6 +14,7 @@ const util = @import("util.zig");const tools_mod = @import("tools.zig");const session_mod = @import("session.zig");const goal_state = @import("goal_state.zig");+const proc_identity = @import("proc_identity.zig");const goal_flow = @import("goal_flow.zig");const prompts = @import("prompts.zig"); // #445: the transcript line's compaction flag resets with the conversationconst Agent = agent_mod.Agent;@@ -117,7 +118,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.session_recap = null;root.recap_generation +%= 1;root.tui_header_shown = false;- root.session_name = try std.fmt.allocPrint(arena, "session-{d}", .{unixMs(root.io)});+ root.session_name = try std.fmt.allocPrint(arena, "session-{d}-{d}", .{ unixMs(root.io), proc_identity.selfPid() }); // same-ms uniqueness, see session_runprompts.resetSessionCompacted(root, arena); // #445: after the rename, so the re-arm reads the NEW sessionsaveSession(root, arena, root.session_name) catch {};try out.print("new session → {s}{s}\n", .{ root.session_name, session_ext });diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex e4c5b0a3..fdf5d0be 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -29,7 +29,7 @@ const ExecResult = tools_mod.ExecResult;const Owner = worktree_lease.Owner;pub const tool_name = "peer_message";-pub const tool_desc = "Send a message to another live graff session working in this same folder (a co-resident peer you learned about from the startup co-owner warning or a shared-tree checkpoint). The message lands in their context at their next turn boundary, stamped with your session name and current goal. Use it to coordinate the way you would steer a subagent, but sideways: announce what you are restructuring, ask them to hold off a directory, or split the work. `session` selects the peer by name substring; omit it when exactly one peer is live. Delivery is queued and one-way — the tool result only confirms the send, never a reply.";+pub const tool_desc = "Post a message to this folder's shared graff channel: every OTHER live graff session working here hears it at its next turn boundary, stamped with your session name and current goal. Use it to coordinate the way you would steer a subagent, but sideways: announce what you are restructuring, ask the others to hold off a directory, or split the work. `session` names the intended recipient (name substring) when the message is meant for one peer — they all still hear it. Delivery is queued and one-way — the tool result only confirms the post, never a reply.";pub const tool_schema =\\{"type": "object", "properties": {"session": {"type": "string", "description": "peer session name substring (omit when only one peer is live)"}, "text": {"type": "string", "description": "one or two sentences of coordination intent"}}, "required": ["text"]};@@ -76,23 +76,26 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {.text = "no live co-resident graff sessions in this worktree — the presence registry says you are alone here (a peer shows up via the startup warning when one starts)",.is_error = true,};- const target = switch (resolvePeer(peers, want)) {- .one => |p| p,+ // `session` is validated so a mistyped target errors usefully, but every+ // peer hears the post either way — the channel is a room, not a DM.+ const to: []const u8 = if (want.len == 0) "" else switch (resolvePeer(peers, want)) {+ .one => |p| p.session_id,.none => return .{.text = try std.fmt.allocPrint(self.arena, "no live peer matches \"{s}\" — live now: {s}", .{ want, peerListText(self.arena, peers) }),.is_error = true,},.ambiguous => return .{- .text = try std.fmt.allocPrint(self.arena, "more than one live peer — name one with `session`: {s}", .{peerListText(self.arena, peers)}),+ .text = try std.fmt.allocPrint(self.arena, "more than one live peer matches — name one with `session`: {s}", .{peerListText(self.arena, peers)}),.is_error = true,},};- if (!presence.postTo(self.io, self.arena, target, text)) return .{+ if (!presence.postTo(self.io, self.arena, text, to)) return .{.text = "delivery failed — the presence registry is unavailable (this session may never have announced itself)",.is_error = true,};+ const addressed = if (to.len > 0) try std.fmt.allocPrint(self.arena, " (for \"{s}\")", .{to}) else "";return .{- .text = try std.fmt.allocPrint(self.arena, "queued for \"{s}\" (pid {d}) — it lands at their next turn boundary. Delivery is one-way: their answer, if any, arrives the same way.", .{ target.session_id, target.pid }),+ .text = try std.fmt.allocPrint(self.arena, "posted to the worktree channel{s} — {d} live peer(s) hear it at their next turn boundary. Delivery is one-way: any answer arrives the same way.", .{ addressed, peers.len }),.is_error = false,};}@@ -103,26 +106,31 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {/// an error, because a peer's inbox must never break our session.pub fn deliverInbound(root: *Agent) void {if (root.sub) return;- const msgs = presence.drainInbox(root.io, root.arena);+ const msgs = presence.drainChannel(root.io, root.arena);if (msgs.len == 0) return;const sink = engine_sink.forAgent(root);+ const own = presence.ownSession();var buf: std.ArrayList(u8) = .empty;for (msgs) |m| {const goal = if (m.from_goal.len > 0) std.fmt.allocPrint(root.arena, " (goal: {s})", .{m.from_goal}) catch "" else "";- const line = std.fmt.allocPrint(root.arena, "[peer message from {s}{s} — #469 channel]: {s}", .{ m.from_session, goal, m.text }) catch continue;+ // Addressing is rendered, not enforced: everyone hears the line, and+ // the marker says who it was meant for.+ const to = if (m.to.len == 0) "" else if (std.mem.indexOf(u8, m.to, own) != null or std.mem.indexOf(u8, own, m.to) != null) " → you" else std.fmt.allocPrint(root.arena, " → {s}", .{m.to}) catch "";+ const line = std.fmt.allocPrint(root.arena, "[peer message from {s}{s}{s} — #469 channel]: {s}", .{ m.from_session, goal, to, m.text }) catch continue;buf.appendSlice(root.arena, line) catch {};buf.append(root.arena, '\n') catch {};sink.emit(root.io, .{ .session_notice = .{ .text = line, .tone = .plain } });}if (buf.items.len == 0) return;- buf.appendSlice(root.arena, "(reply with the peer_message tool — queued, one-way)") catch {};+ buf.appendSlice(root.arena, "(reply with the peer_message tool — queued, one-way; everyone here hears it)") catch {};var obj: std.json.ObjectMap = .empty;obj.put(root.arena, "role", .{ .string = "user" }) catch return;obj.put(root.arena, "content", .{ .string = buf.items }) catch return;root.messages.append(.{ .object = obj }) catch {};}-/// /tell <session> <text…>: the user's line into a peer's inbox.+/// /tell <session|all> <text…>: the user's line into the shared channel.+/// Every co-resident session hears it; the target only marks who it's FOR.pub fn tellCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {const rest = std.mem.trim(u8, line["/tell".len..], " \t");const peers = presence.liveTreePeers(root.io, arena);@@ -130,13 +138,13 @@ pub fn tellCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Wrconst target = if (split) |i| rest[0..i] else "";const text = if (split) |i| std.mem.trim(u8, rest[i + 1 ..], " \t") else "";if (target.len == 0 or text.len == 0) {- try out.writeAll("usage: /tell <session> <text> — message a live co-resident graff session\n");+ try out.writeAll("usage: /tell <session|all> <text> — post to this worktree's shared graff channel\n");if (peers.len == 0) try out.writeAll(" (no live peers in this worktree right now)\n") else try out.print(" live now: {s}\n", .{peerListText(arena, peers)});try out.flush();return true;}- const peer = switch (resolvePeer(peers, target)) {- .one => |p| p,+ const to: []const u8 = if (std.mem.eql(u8, target, "all")) "" else switch (resolvePeer(peers, target)) {+ .one => |p| p.session_id,.none => {try out.print("no live peer matches \"{s}\"\n", .{target});try out.flush();@@ -148,10 +156,10 @@ pub fn tellCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Wrreturn true;},};- if (presence.postTo(root.io, arena, peer, text))- try out.print("⇢ queued for {s} (pid {d}) — lands at their next turn boundary\n", .{ peer.session_id, peer.pid })- else- try out.writeAll("delivery failed — presence registry unavailable\n");+ if (presence.postTo(root.io, arena, text, to)) {+ const addressed = if (to.len > 0) try std.fmt.allocPrint(arena, " (for {s})", .{to}) else "";+ try out.print("⇢ posted to the worktree channel{s} — {d} live peer(s) hear it at their next turn boundary\n", .{ addressed, peers.len });+ } else try out.writeAll("delivery failed — presence registry unavailable\n");try out.flush();return true;}diff --git a/src/presence.zig b/src/presence.zigindex 577a04a1..3b4c7367 100644--- a/src/presence.zig+++ b/src/presence.zig@@ -194,7 +194,8 @@ var g_own_name: ?[]const u8 = null; // gpa-owned own record's file namevar g_session: []const u8 = ""; // gpa-owned session id, for rewritesvar g_goal: []const u8 = ""; // last-known goal (session-arena-owned is fine: both outlive the session)var g_self: proc_identity.Record = .{}; // own pid + start-id, settled by announce-var g_inbox_off: u64 = 0; // bytes of our own inbox already delivered+var g_chan: ?[]const u8 = null; // gpa-owned channel file name (hash of g_identity)+var g_inbox_off: u64 = 0; // bytes of the shared channel already deliveredvar g_acked: [max_peers]u64 = undefined;var g_acked_len: usize = 0;@@ -229,6 +230,8 @@ pub fn announce(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, sessg_session = gpa.dupe(u8, session_id) catch "";g_goal = gpa.dupe(u8, goal) catch "";g_self = self;+ var chan_buf: [chan_name_max]u8 = undefined;+ g_chan = gpa.dupe(u8, chanName(&chan_buf, g_identity)) catch null;g_own_name = gpa.dupe(u8, name) catch return null;// Peer check BEFORE writing our own record: the warning describes the tree// as it was when we arrived.@@ -256,11 +259,13 @@ pub fn deinit(gpa: Allocator) void {if (g_session.len > 0) gpa.free(g_session);if (g_goal.len > 0) gpa.free(g_goal);if (g_own_name) |n| gpa.free(n);+ if (g_chan) |c| gpa.free(c);g_dir = null;g_identity = "";g_session = "";g_goal = "";g_own_name = null;+ g_chan = null;g_self = .{};g_inbox_off = 0;g_acked_len = 0;@@ -272,8 +277,8 @@ pub fn retire(io: Io) void {var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return;defer dir.close(io);dir.deleteFile(io, name) catch {};- var inbox_buf: [inbox_name_max]u8 = undefined;- dir.deleteFile(io, inboxName(&inbox_buf, g_self.pid, g_self.start_id)) catch {};+ // The shared channel is NOT ours to delete: co-resident sessions may+ // still be mid-drain, and its bytes are the room's history.}/// Refresh our record's goal — the coordination payload a peer's checkpoint@@ -308,69 +313,15 @@ pub fn gateCheck(io: Io, arena: Allocator) ?[]const u8 {return std.fmt.allocPrint(arena, "{s}shared-tree checkpoint (#469): the command was NOT run. Re-issue the identical command to proceed — this fires once per live peer — coordinate first via the peer_message tool (session \"{s}\"), or keep your edits disjoint from theirs.", .{ warning, peer.session_id }) catch warning;}-// --- the channel (#469 phase 2): one append-only JSONL inbox per session,-// named from the same (pid, start-id) as its presence record so a sender needs-// nothing the record doesn't already carry. Appends use the read+write-// positional pattern from session_transcript (#462: write-only handles break-// appends on Windows). Delivery is queued — a sender never blocks on the-// receiver, and two busy sessions cannot deadlock (#417's rule). -----pub const inbox_name_max = 96;--/// One inbox line. `from_*` identify the sender's presence record at send-/// time; the harness writes them, never the model.-pub const Message = struct {- from_pid: i32 = 0,- from_session: []const u8 = "",- from_goal: []const u8 = "",- ts_ms: i64 = 0,- text: []const u8 = "",-};--pub fn inboxName(buf: *[inbox_name_max]u8, pid: i32, start_id: u64) []const u8 {- return std.fmt.bufPrint(buf, "{d}-{x}.inbox.jsonl", .{ pid, start_id }) catch unreachable;-}--/// Append one message to `target`'s inbox under `dir`. Best-effort: false on-/// any I/O or serialization failure — a lost message is reported by the-/// caller, never thrown into a tool call.-pub fn postMessage(io: Io, arena: Allocator, dir: Io.Dir, target: Owner, msg: Message) bool {- var aw: std.Io.Writer.Allocating = .init(arena);- var s: std.json.Stringify = .{ .writer = &aw.writer };- s.write(msg) catch return false;- aw.writer.writeAll("\n") catch return false;- var name_buf: [inbox_name_max]u8 = undefined;- const name = inboxName(&name_buf, target.pid, target.start_id);- const f = dir.createFile(io, name, .{ .truncate = false, .read = true }) catch return false;- defer f.close(io);- const end: u64 = if (f.stat(io)) |st| st.size else |_| blk: {- const st = dir.statFile(io, name, .{}) catch return false;- break :blk st.size;- };- f.writePositionalAll(io, aw.writer.buffered(), end) catch return false;- return true;-}+// The channel's wire format (Message, chanName, postMessage, readNewMessages)+// lives in presence_chan.zig — split out under the 600-line ceiling. This file+// keeps the wired layer: which dir/name/offset a LIVE session uses.-/// Read complete inbox lines after `offset`, advancing it past everything-/// parsed. A trailing partial line stays for the next drain — a writer-/// mid-append never yields a torn message. A file shorter than the offset was-/// recreated; restart from the top rather than skip it forever.-pub fn readNewMessages(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, offset: *u64) []const Message {- const text = dir.readFileAlloc(io, name, arena, .limited(256 * 1024)) catch return &.{};- if (text.len < offset.*) offset.* = 0;- if (text.len == offset.*) return &.{};- var msgs: std.ArrayList(Message) = .empty;- var pos: usize = @intCast(offset.*);- while (std.mem.indexOfScalarPos(u8, text, pos, '\n')) |nl| {- const line = text[pos..nl];- pos = nl + 1;- const m = std.json.parseFromSliceLeaky(Message, arena, line, .{ .ignore_unknown_fields = true }) catch continue;- if (m.from_pid == 0 or m.text.len == 0) continue;- msgs.append(arena, m) catch break;- }- offset.* = @intCast(pos);- return msgs.items;-}+const presence_chan = @import("presence_chan.zig");+pub const Message = presence_chan.Message;+const chanName = presence_chan.chanName;+const isOwn = presence_chan.isOwn;+const chan_name_max = presence_chan.chan_name_max;/// The live co-owners of MY worktree: every registry record whose verdict is/// live_foreign/live_unverified. The sender's target list for peer_message@@ -392,32 +343,43 @@ pub fn liveTreePeers(io: Io, arena: Allocator) []const Owner {return live.items;}-/// Send-side wrapper for the wired layer: stamp the message with OUR record-/// and append it to the target's inbox. false when this session never+/// Post to the shared worktree channel, stamped with OUR record. `to` names+/// the intended recipient (session substring or pid) and is metadata only —+/// every co-resident session hears the line. false when this session never/// announced (tests, subagents) or the write failed.-pub fn postTo(io: Io, arena: Allocator, target: Owner, text: []const u8) bool {+pub fn postTo(io: Io, arena: Allocator, text: []const u8, to: []const u8) bool {const dir_path = g_dir orelse return false;+ const chan = g_chan orelse return false;if (g_self.pid == 0) return false;var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return false;defer dir.close(io);- return postMessage(io, arena, dir, target, .{+ return presence_chan.postMessage(io, arena, dir, chan, .{.from_pid = g_self.pid,+ .from_start = g_self.start_id,.from_session = g_session,.from_goal = g_goal,+ .to = to,.ts_ms = unixMs(io),.text = text,});}-/// Drain OUR inbox: every complete message since the last drain. Empty when-/// unannounced, inbox-less, or caught up.-pub fn drainInbox(io: Io, arena: Allocator) []const Message {+/// Drain the shared channel: every complete message since our last drain,+// minus our own echo. Empty when unannounced or caught up. A session that+/// joins late hears the channel's whole backlog once — context, not spam:+/// the room predates it.+pub fn drainChannel(io: Io, arena: Allocator) []const Message {const dir_path = g_dir orelse return &.{};+ const chan = g_chan orelse return &.{};if (g_self.pid == 0) return &.{};var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return &.{};defer dir.close(io);- var name_buf: [inbox_name_max]u8 = undefined;- return readNewMessages(io, arena, dir, inboxName(&name_buf, g_self.pid, g_self.start_id), &g_inbox_off);+ const raw = presence_chan.readNewMessages(io, arena, dir, chan, &g_inbox_off);+ var out: std.ArrayList(Message) = .empty;+ for (raw) |m| {+ if (!isOwn(m, g_self.pid, g_self.start_id)) out.append(arena, m) catch break;+ }+ return out.items;}pub fn ownSession() []const u8 {@@ -513,57 +475,3 @@ test "unackedPeer: returns the live foreign co-owner once, then yields to the acconst probes2 = [_]proc_identity.Probe{.{ .id = 100 }};try std.testing.expect(unackedPeer(.{ .records = &records2, .probes = &probes2 }, my_identity, 1, &.{key}) != null);}--test "inbox: post then drain returns each message once, in order, sender-stamped" {- const io = std.testing.io;- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const arena = arena_state.allocator();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const target: Owner = .{ .pid = 4242, .start_id = 0xabc, .session_id = "s-b", .identity = "/repo/.git" };- const msg: Message = .{ .from_pid = 1, .from_session = "s-a", .from_goal = "agent-inbox redesign", .ts_ms = 7, .text = "hold off gui/src until I land the move" };- try std.testing.expect(postMessage(io, arena, tmp.dir, target, msg));- try std.testing.expect(postMessage(io, arena, tmp.dir, target, .{ .from_pid = 1, .from_session = "s-a", .ts_ms = 8, .text = "second note" }));- var name_buf: [inbox_name_max]u8 = undefined;- const name = inboxName(&name_buf, target.pid, target.start_id);- var off: u64 = 0;- const first = readNewMessages(io, arena, tmp.dir, name, &off);- try std.testing.expectEqual(2, first.len);- try std.testing.expectEqualStrings("s-a", first[0].from_session);- try std.testing.expectEqualStrings("agent-inbox redesign", first[0].from_goal);- try std.testing.expectEqualStrings("hold off gui/src until I land the move", first[0].text);- try std.testing.expectEqualStrings("second note", first[1].text);- // A second drain at the same offset is empty: delivery is exactly-once per reader.- try std.testing.expectEqual(0, readNewMessages(io, arena, tmp.dir, name, &off).len);-}--test "readNewMessages: a torn trailing line waits for the next drain" {- const io = std.testing.io;- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const arena = arena_state.allocator();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const target: Owner = .{ .pid = 9, .start_id = 1, .session_id = "s-t" };- try std.testing.expect(postMessage(io, arena, tmp.dir, target, .{ .from_pid = 2, .from_session = "s-x", .ts_ms = 1, .text = "whole" }));- var name_buf: [inbox_name_max]u8 = undefined;- const name = inboxName(&name_buf, 9, 1);- // Simulate a writer mid-append: half a JSON line, no newline yet.- const f = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });- const st = try f.stat(io);- try f.writePositionalAll(io, "{\"from_pid\":2,\"tex", st.size);- f.close(io);- var off: u64 = 0;- const first = readNewMessages(io, arena, tmp.dir, name, &off);- try std.testing.expectEqual(1, first.len); // only the complete line- try std.testing.expectEqualStrings("whole", first[0].text);- // Finish the torn line; the next drain picks it up.- const f2 = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });- const st2 = try f2.stat(io);- try f2.writePositionalAll(io, "t\":\"rest\"}\n", st2.size);- f2.close(io);- const second = readNewMessages(io, arena, tmp.dir, name, &off);- try std.testing.expectEqual(1, second.len);- try std.testing.expectEqualStrings("rest", second[0].text);-}diff --git a/src/presence_chan.zig b/src/presence_chan.zignew file mode 100644index 00000000..693b2ecb--- /dev/null+++ b/src/presence_chan.zig@@ -0,0 +1,142 @@+//! The wire format half of the #469 channel: ONE append-only JSONL log per+//! worktree, shared by every co-resident session — a room, not per-session+//! inboxes, so a message addressed to one agent is still HEARD by the others.+//! Named from a hash of the worktree identity so two checkouts never+//! cross-hear. Appends use the read+write positional pattern from+//! session_transcript (#462: write-only handles break appends on Windows).+//! Delivery is queued — a sender never blocks on a receiver, and two busy+//! sessions cannot deadlock (#417's rule). Every reader keeps its own byte+//! offset and skips only its OWN messages; `to` is addressing metadata, not a+//! delivery rule.+//!+//! Everything here is parameterized and pure-ish (dir + name + allocator in,+//! bytes out) so tests need no process registry; the wired layer that knows+//! WHICH dir/name/offset a live session uses is presence.zig+//! (postTo/drainChannel), split out under the 600-line ceiling.++const std = @import("std");++const Io = std.Io;+const Allocator = std.mem.Allocator;++pub const chan_name_max = 96;++/// One channel line. `from_*` identify the sender's presence record at send+/// time; the harness writes them, never the model. `to` is a session-name+/// substring naming who the message is FOR — everyone still hears it.+pub const Message = struct {+ from_pid: i32 = 0,+ from_start: u64 = 0,+ from_session: []const u8 = "",+ from_goal: []const u8 = "",+ to: []const u8 = "",+ ts_ms: i64 = 0,+ text: []const u8 = "",+};++/// The channel file for a worktree identity: content-hash, so it is stable+/// across sessions and carries no path separators.+pub fn chanName(buf: *[chan_name_max]u8, identity: []const u8) []const u8 {+ return std.fmt.bufPrint(buf, "chan-{x}.jsonl", .{std.hash.Wyhash.hash(0, identity)}) catch unreachable;+}++/// Whether this message is our own echo — the one thing a drain skips.+pub fn isOwn(msg: Message, self_pid: i32, self_start: u64) bool {+ return msg.from_pid == self_pid and msg.from_start == self_start;+}++/// Append one message to the channel named `name` under `dir`. Best-effort:+/// false on any I/O or serialization failure — a lost message is reported by+/// the caller, never thrown into a tool call.+pub fn postMessage(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, msg: Message) bool {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(msg) catch return false;+ aw.writer.writeAll("\n") catch return false;+ const f = dir.createFile(io, name, .{ .truncate = false, .read = true }) catch return false;+ defer f.close(io);+ const end: u64 = if (f.stat(io)) |st| st.size else |_| blk: {+ const st = dir.statFile(io, name, .{}) catch return false;+ break :blk st.size;+ };+ f.writePositionalAll(io, aw.writer.buffered(), end) catch return false;+ return true;+}++/// Read complete channel lines after `offset`, advancing it past everything+/// parsed. A trailing partial line stays for the next drain — a writer+/// mid-append never yields a torn message. A file shorter than the offset was+/// recreated; restart from the top rather than skip it forever.+pub fn readNewMessages(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, offset: *u64) []const Message {+ const text = dir.readFileAlloc(io, name, arena, .limited(256 * 1024)) catch return &.{};+ if (text.len < offset.*) offset.* = 0;+ if (text.len == offset.*) return &.{};+ var msgs: std.ArrayList(Message) = .empty;+ var pos: usize = @intCast(offset.*);+ while (std.mem.indexOfScalarPos(u8, text, pos, '\n')) |nl| {+ const line = text[pos..nl];+ pos = nl + 1;+ const m = std.json.parseFromSliceLeaky(Message, arena, line, .{ .ignore_unknown_fields = true }) catch continue;+ if (m.from_pid == 0 or m.text.len == 0) continue;+ msgs.append(arena, m) catch break;+ }+ offset.* = @intCast(pos);+ return msgs.items;+}++test "channel: every reader hears every message once; only the sender's own echo drops" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var name_buf: [chan_name_max]u8 = undefined;+ const name = chanName(&name_buf, "/repo/.git");+ const msg: Message = .{ .from_pid = 1, .from_start = 11, .from_session = "s-a", .from_goal = "agent-inbox redesign", .to = "s-b", .ts_ms = 7, .text = "hold off gui/src until I land the move" };+ try std.testing.expect(postMessage(io, arena, tmp.dir, name, msg));+ try std.testing.expect(postMessage(io, arena, tmp.dir, name, .{ .from_pid = 2, .from_start = 22, .from_session = "s-c", .ts_ms = 8, .text = "second note" }));+ var off: u64 = 0;+ const first = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(2, first.len);+ try std.testing.expectEqualStrings("s-a", first[0].from_session);+ try std.testing.expectEqualStrings("agent-inbox redesign", first[0].from_goal);+ try std.testing.expectEqualStrings("s-b", first[0].to);+ try std.testing.expectEqualStrings("hold off gui/src until I land the move", first[0].text);+ try std.testing.expectEqualStrings("second note", first[1].text);+ // A second drain at the same offset is empty: delivery is exactly-once per reader.+ try std.testing.expectEqual(0, readNewMessages(io, arena, tmp.dir, name, &off).len);+ // The room model: self-echo is the ONLY thing a drain drops.+ try std.testing.expect(isOwn(first[0], 1, 11));+ try std.testing.expect(!isOwn(first[0], 2, 22));+ try std.testing.expect(!isOwn(first[0], 1, 12)); // same pid, new boot: a new voice+}++test "readNewMessages: a torn trailing line waits for the next drain" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var name_buf: [chan_name_max]u8 = undefined;+ const name = chanName(&name_buf, "/repo/.git");+ try std.testing.expect(postMessage(io, arena, tmp.dir, name, .{ .from_pid = 2, .from_start = 1, .from_session = "s-x", .ts_ms = 1, .text = "whole" }));+ // Simulate a writer mid-append: half a JSON line, no newline yet.+ const f = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });+ const st = try f.stat(io);+ try f.writePositionalAll(io, "{\"from_pid\":2,\"tex", st.size);+ f.close(io);+ var off: u64 = 0;+ const first = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(1, first.len); // only the complete line+ try std.testing.expectEqualStrings("whole", first[0].text);+ // Finish the torn line; the next drain picks it up.+ const f2 = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });+ const st2 = try f2.stat(io);+ try f2.writePositionalAll(io, "t\":\"rest\"}\n", st2.size);+ f2.close(io);+ const second = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(1, second.len);+ try std.testing.expectEqualStrings("rest", second[0].text);+}diff --git a/src/session_run.zig b/src/session_run.zigindex 4c963cad..9a68cfe5 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -53,6 +53,7 @@ const messages_mod = @import("messages.zig");const session = @import("session.zig");const session_settings = @import("session_settings.zig");const presence = @import("presence.zig");+const proc_identity = @import("proc_identity.zig");const goal_flow = @import("goal_flow.zig");const fleet = @import("fleet.zig");const hooks = @import("hooks.zig");@@ -267,7 +268,10 @@ pub fn buildRootAgent(.tools_responses = "",};// #410: the durable session's name is settled BEFORE the prompt funnel runs — setRootSystemPrompts composes the transcript line out of it.- const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}", .{util.unixMs(io)});+ // The pid suffix keeps two graffs started in the same millisecond from+ // sharing a session name — which would also share one .session.json file+ // (#289 contention) and collide as presence peers (#469).+ const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}-{d}", .{ util.unixMs(io), proc_identity.selfPid() });root.session_name = if (flags.resume_flag) |name| (if (!flags.new_session_flag and !flags.no_resume_flag) name else fresh_session_name) else fresh_session_name;try prompts.setRootSystemPrompts(&root, sys_normal, arena); // #381: same funnel + the live .graff/playbook.jsonl constraint block// Startup pays for one provider format, not all three. Other formats are