Skip to content

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

Python

Let any agent join the device rooms with graff peer

justrach8ca304faf94f
diff --git a/docs/adr/0203-external-agents-join-rooms-through-graff-peer.md b/docs/adr/0203-external-agents-join-rooms-through-graff-peer.md
new file mode 100644
index 00000000..02752110
--- /dev/null
+++ b/docs/adr/0203-external-agents-join-rooms-through-graff-peer.md
@@ -0,0 +1,44 @@
+# 0203. Other agents join the device rooms through `graff peer`
+
+Status: accepted 2026-09-26
+
+## Context
+
+The worktree and device rooms (ADR 0004, 0134) only had graff sessions in
+them. Other coding agents on the same machine (Claude Code, Codex, scripts)
+could not list, address, or hear graff sessions, and graff could not address
+them. Every such agent can run a shell command, so a command is the smallest
+common interface.
+
+Two read-path costs also grew with room age: every drain read the whole room
+file (and returned nothing once a room passed 256 KiB), and joining at the
+tail read up to 16 MiB just to learn the file length.
+
+## Decision
+
+- `graff peer list | send | inbox` works on the same JSONL rooms and presence
+ records graff sessions use. There is no second format.
+- An external agent's record is owned by the nearest non-shell ancestor
+ process, so it lives and is reaped with the agent. Records are named
+ `{pid}-{start}-{name}.ext.json`, so one process can host several named
+ agents. `activity` is `external`.
+- Delivery follows `peer_target`: every unaddressed worktree line, and only
+ device lines addressed to the agent. A read cursor per agent sits beside
+ the records. A first read joins at the tail.
+- A DM is held (exit 3) when the recipient wrote to the sender after the
+ sender's last read. The held messages are shown and marked read, so the
+ next send goes through; `--anyway` skips the check.
+- A send wakes only the graff sessions that hear it, over their Accord
+ socket. Oversize lines are replaced by a small marker, because a wake needs
+ only the frame kind.
+- `inbox --wake` prints one line when there is mail, for agent hooks.
+- Drains read only the bytes after their offset, at most 1 MiB per drain. An
+ unterminated line longer than that is skipped. Tail joins use `stat`.
+
+## Consequences
+
+External agents appear in `peer_message action=list` and can be addressed by
+name. A graff session in the same worktree as an external agent now gets the
+shared-tree checkpoint for it, which is the intended collision warning.
+Windows is not supported yet (no parent-process walk). Cross-device rooms are
+a separate decision.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index efe08cbb..a527d76e 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -229,6 +229,7 @@ record only when you need the evidence or the edge cases.
| [0200](0200-desktop-page-transitions-preserve-tabs.md) | Desktop restart/reload confirms active-turn interruption and restores tab references from saved sessions in their workspaces. |
| [0201](0201-cli-beta-channel-is-explicit.md) | CLI beta updates require explicit opt-in, select the newest numeric release branch, verify pinned assets, and activate on next launch. |
| [0202](0202-acp-sessions-adopt-client-cwd.md) | ACP sessions adopt the client `cwd`, report the worktree as `_meta["graff/worktree"]` (null in a main checkout), and `graff worktree` exits non-zero when it refuses or does nothing. |
+| [0203](0203-external-agents-join-rooms-through-graff-peer.md) | Other agents join the device rooms with `graff peer list/send/inbox`: same JSONL rooms and records, owned by the agent's process; a DM is held while the recipient's newer message is unread; drains read only new bytes. |
## When to write one
diff --git a/docs/agents-panel.md b/docs/agents-panel.md
index 488db761..a94fcc18 100644
--- a/docs/agents-panel.md
+++ b/docs/agents-panel.md
@@ -35,6 +35,27 @@ The desktop's short-lived observer runs the same vendor extension before model,
credential, MCP and session startup. It remains available during another Graff's
active turn. It accepts only local peer requests and creates no session.
+## Other agents
+
+Any agent that can run a shell command can join the same rooms with
+`graff peer` (ADR 0203):
+
+```sh
+graff peer list # live agents on this device
+graff peer send --to "Fixing login" "tests are green on my side"
+graff peer send "parser landed" # everyone in this worktree
+graff peer inbox # messages since your last read
+```
+
+The default name is `<agent>@<folder>`; set `--as` or `GRAFF_PEER_NAME` to
+choose one. A DM is not sent while the recipient has written to you since your
+last read; the command prints what you missed and exits 3. Read it, then send
+again, or pass `--anyway`.
+
+To give Claude Code the same one-line wake graff sessions get, add a
+`UserPromptSubmit` hook that runs `graff peer inbox --wake`. It prints nothing
+when there is no mail.
+
## Offline verification
`bun run test:visual` in the desktop package exercises theme rendering, panel
diff --git a/src/additional_tests.zig b/src/additional_tests.zig
index dab0eed8..9afce85f 100644
--- a/src/additional_tests.zig
+++ b/src/additional_tests.zig
@@ -10,6 +10,7 @@ test {
_ = @import("provider_codegraff_tests.zig");
_ = @import("agent_responses.zig");
_ = @import("session_branch.zig");
+ _ = @import("peer_cli.zig");
}
test "oneshot -p still uses the live stall-watched transport" {
diff --git a/src/args.zig b/src/args.zig
index 90c3119c..0412ae5f 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -124,7 +124,7 @@ pub fn parse(init: std.process.Init) !Flags {
_ = it.next(); // argv[0]
while (it.next()) |arg| {
if (flags.positionals.items.len > 0 and
- (std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn")))
+ (std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") or std.mem.eql(u8, flags.positionals.items[0], "peer")))
{
try flags.positionals.append(arena, try arena.dupe(u8, arg));
} else if (std.mem.startsWith(u8, arg, "-")) {
diff --git a/src/cli.zig b/src/cli.zig
index 67aeb180..74f1d872 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -69,6 +69,7 @@ pub const usage_text =
\\ graff worktree prune drop git registrations for worktrees whose dirs were deleted
\\ graff servers background servers graff started (this session's or older): pid, port, age
\\ graff servers stop <pid> end one (its whole process tree); `prune` drops records of dead ones
+ \\ graff peer list|send|inbox talk with other agents on this device (Claude Code, Codex, graff)
\\ graff sandboxes list your gateway sandboxes (what's burning credits)
\\ graff sandboxes stop <id> spin a sandbox down (stops it + settles the meter)
\\ graff cube new spin up a cloud graff (sandbox + serve + preview URL)
diff --git a/src/peer_cli.zig b/src/peer_cli.zig
new file mode 100644
index 00000000..9133d0e4
--- /dev/null
+++ b/src/peer_cli.zig
@@ -0,0 +1,480 @@
+//! `graff peer`: the device's agent rooms for any agent with a shell (Claude
+//! Code, Codex, scripts), not only graff sessions. The rooms are the same
+//! JSONL logs graff sessions use (ADR 0004, 0134); Accord wakes a recipient.
+//!
+//! graff peer list [--json] live agents on this device
+//! graff peer send [--to NAME] [TEXT] worktree room, or a DM (stdin if no TEXT)
+//! graff peer inbox [--peek] [--json] new messages since the last read
+//! graff peer inbox --wake one line when there is mail (for hooks)
+//!
+//! Identity: `--as NAME`, else `$GRAFF_PEER_NAME`, else `<agent>@<folder>`.
+//! The presence record is owned by the nearest non-shell ancestor, so it lives
+//! as long as the agent process and is reaped with it. A send to someone who
+//! wrote to you after your last read is held until you read it (`--anyway`
+//! sends regardless) — a reply should answer the latest message, not an
+//! earlier one.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const accord = @import("accord");
+const presence = @import("presence.zig");
+const presence_chan = @import("presence_chan.zig");
+const presence_record = @import("presence_record.zig");
+const presence_accord = @import("presence_accord.zig");
+const peer_target = @import("peer_target.zig");
+const proc_identity = @import("proc_identity.zig");
+const worktree_lease = @import("worktree_lease.zig");
+const util = @import("util.zig");
+
+const Message = presence_chan.Message;
+const Owner = worktree_lease.Owner;
+
+pub const usage =
+ \\usage: graff peer <list|send|inbox> [options]
+ \\ list [--json] live agents on this device
+ \\ send [--to NAME] [--anyway] TEXT post to this worktree's room, or DM NAME (TEXT or stdin)
+ \\ inbox [--peek] [--json] [--wake] messages since your last read
+ \\ --as NAME your name (default $GRAFF_PEER_NAME or agent@folder)
+ \\
+;
+
+pub const Opts = struct {
+ action: []const u8 = "",
+ as: ?[]const u8 = null,
+ to: ?[]const u8 = null,
+ text: []const u8 = "",
+ json: bool = false,
+ peek: bool = false,
+ wake: bool = false,
+ anyway: bool = false,
+};
+
+pub fn parseOpts(arena: Allocator, args: []const []const u8) error{ Usage, OutOfMemory }!Opts {
+ var o: Opts = .{};
+ var words: std.ArrayList([]const u8) = .empty;
+ var i: usize = 0;
+ while (i < args.len) : (i += 1) {
+ const a = args[i];
+ if (std.mem.eql(u8, a, "--as") or std.mem.eql(u8, a, "--to")) {
+ i += 1;
+ if (i >= args.len) return error.Usage;
+ if (a[2] == 'a') o.as = args[i] else o.to = args[i];
+ } else if (std.mem.eql(u8, a, "--json")) {
+ o.json = true;
+ } else if (std.mem.eql(u8, a, "--peek")) {
+ o.peek = true;
+ } else if (std.mem.eql(u8, a, "--wake")) {
+ o.wake = true;
+ } else if (std.mem.eql(u8, a, "--anyway")) {
+ o.anyway = true;
+ } else if (std.mem.startsWith(u8, a, "--")) {
+ return error.Usage;
+ } else if (o.action.len == 0) {
+ o.action = a;
+ } else {
+ try words.append(arena, a);
+ }
+ }
+ if (o.action.len == 0) return error.Usage;
+ o.text = try std.mem.join(arena, " ", words.items);
+ return o;
+}
+
+/// Everything a room operation needs, so tests can point it at a tmp dir.
+pub const Ctx = struct {
+ dir: Io.Dir,
+ name: []const u8,
+ owner: proc_identity.Record,
+ identity: []const u8,
+};
+
+pub const Room = enum { tree, device };
+pub const Heard = struct { room: Room, m: Message };
+
+/// Per-agent read position, beside the records in ~/.graff/live.
+pub const Cursor = struct {
+ tree_room: []const u8 = "",
+ tree: u64 = 0,
+ device: u64 = 0,
+};
+
+const shells = [_][]const u8{ "sh", "bash", "zsh", "dash", "fish", "ksh", "tcsh", "csh", "env", "nohup", "timeout", "xargs", "sudo" };
+
+pub fn isShell(comm: []const u8) bool {
+ const c = std.mem.trimStart(u8, comm, "-");
+ for (shells) |s| if (std.mem.eql(u8, c, s)) return true;
+ return false;
+}
+
+pub const Ancestor = struct {
+ rec: proc_identity.Record,
+ info: proc_identity.Parent,
+ path_buf: [std.fs.max_path_bytes]u8 = undefined,
+ path_len: usize = 0,
+
+ /// A readable agent name. Versioned installs run a binary named like
+ /// `2.1.282`, so fall back to the executable path's nearest real folder.
+ pub fn comm(a: *const Ancestor) []const u8 {
+ const c = std.mem.trimStart(u8, a.info.comm(), "-");
+ if (c.len > 0 and std.ascii.isAlphabetic(c[0])) return c;
+ return labelFromPath(a.path_buf[0..a.path_len]) orelse "agent";
+ }
+};
+
+/// Last path component that names a program: starts with a letter and is not
+/// packaging (`versions`, `bin`, app bundle folders).
+pub fn labelFromPath(path: []const u8) ?[]const u8 {
+ const skip = [_][]const u8{ "versions", "bin", "libexec", "Resources", "MacOS", "Contents", "current" };
+ var it = std.mem.splitBackwardsScalar(u8, path, '/');
+ outer: while (it.next()) |part| {
+ if (part.len == 0 or !std.ascii.isAlphabetic(part[0])) continue;
+ for (skip) |s| if (std.mem.eql(u8, part, s)) continue :outer;
+ return part;
+ }
+ return null;
+}
+
+extern "c" fn proc_pidpath(pid: c_int, buf: [*]u8, size: u32) c_int;
+
+fn exePath(pid: i32, buf: []u8) usize {
+ switch (builtin.os.tag) {
+ .macos => {
+ const n = proc_pidpath(pid, buf.ptr, @intCast(buf.len));
+ return if (n > 0) @intCast(n) else 0;
+ },
+ .linux => {
+ // Raw syscall, like proc_identity: Io.Dir reads under /proc can
+ // panic on the io_uring backend.
+ var lb: [64]u8 = undefined;
+ const link = std.fmt.bufPrintZ(&lb, "/proc/{d}/exe", .{pid}) catch return 0;
+ const rc = std.os.linux.readlink(link, buf.ptr, buf.len);
+ return if (@as(isize, @bitCast(rc)) < 0) 0 else rc;
+ },
+ else => return 0,
+ }
+}
+
+/// The long-lived agent behind this command: the nearest ancestor that is not
+/// a shell. Falls back to the direct parent.
+pub fn agentAncestor(io: Io) ?Ancestor {
+ const self = proc_identity.parentOf(proc_identity.selfPid()) orelse return null;
+ var pid = self.ppid;
+ var depth: usize = 0;
+ while (depth < 8 and pid > 1) : (depth += 1) {
+ const p = proc_identity.parentOf(pid) orelse break;
+ if (!isShell(p.comm())) {
+ const start: u64 = switch (proc_identity.probe(io, pid)) {
+ .id => |v| v,
+ else => 0,
+ };
+ var a: Ancestor = .{ .rec = .{ .pid = pid, .start_id = start }, .info = p };
+ a.path_len = exePath(pid, &a.path_buf);
+ return a;
+ }
+ pid = p.ppid;
+ }
+ return .{ .rec = .{ .pid = self.ppid, .start_id = 0 }, .info = .{ .ppid = 0 } };
+}
+
+/// "zigrepper" for /x/zigrepper/.git; "zigrepper:wt" for a linked worktree.
+pub fn folderLabel(identity: []const u8, buf: []u8) []const u8 {
+ if (std.mem.indexOf(u8, identity, "/.git/worktrees/")) |at| {
+ const repo = std.fs.path.basename(identity[0..at]);
+ const wt = std.fs.path.basename(identity);
+ return std.fmt.bufPrint(buf, "{s}:{s}", .{ repo, wt }) catch repo;
+ }
+ const trimmed = if (std.mem.endsWith(u8, identity, "/.git")) identity[0 .. identity.len - 5] else identity;
+ return std.fs.path.basename(trimmed);
+}
+
+/// One record per (owner process, name): a harness may run several named
+/// agents under one process.
+fn recordName(buf: []u8, owner: proc_identity.Record, name: []const u8) []const u8 {
+ var slug_buf: [64]u8 = undefined;
+ return std.fmt.bufPrint(buf, "{d}-{x}-{s}.ext.json", .{ owner.pid, owner.start_id, peer_target.slugify(name, &slug_buf) }) catch "";
+}
+
+fn cursorName(buf: []u8, name: []const u8) []const u8 {
+ var slug_buf: [64]u8 = undefined;
+ return std.fmt.bufPrint(buf, "ext-{s}.cursor", .{peer_target.slugify(name, &slug_buf)}) catch "ext.cursor";
+}
+
+fn treeRoomName(buf: *[presence_chan.chan_name_max]u8, identity: []const u8) []const u8 {
+ return if (identity.len == 0) "" else presence_chan.chanName(buf, identity);
+}
+
+/// Write (or refresh) this agent's presence record so graff sessions can list
+/// and address it.
+pub fn join(io: Io, arena: Allocator, ctx: Ctx) void {
+ var buf: [160]u8 = undefined;
+ const text = presence_record.formatRecord(arena, .{
+ .pid = ctx.owner.pid,
+ .start_id = ctx.owner.start_id,
+ .session_id = ctx.name,
+ .identity = ctx.identity,
+ .last_seen_ms = util.unixMs(io),
+ .activity = "external",
+ .title = ctx.name,
+ .session_base = ctx.name,
+ }) catch return;
+ ctx.dir.writeFile(io, .{ .sub_path = recordName(&buf, ctx.owner, ctx.name), .data = text }) catch {};
+}
+
+/// Null when this agent never read before: the caller joins at the tail.
+pub fn loadCursor(io: Io, arena: Allocator, ctx: Ctx) ?Cursor {
+ var buf: [96]u8 = undefined;
+ const text = ctx.dir.readFileAlloc(io, cursorName(&buf, ctx.name), arena, .limited(4096)) catch return null;
+ return std.json.parseFromSliceLeaky(Cursor, arena, text, .{ .ignore_unknown_fields = true }) catch null;
+}
+
+pub fn saveCursor(io: Io, arena: Allocator, ctx: Ctx, cur: Cursor) void {
+ var buf: [96]u8 = undefined;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(cur) catch return;
+ ctx.dir.writeFile(io, .{ .sub_path = cursorName(&buf, ctx.name), .data = aw.writer.buffered() }) catch {};
+}
+
+pub fn tailCursor(io: Io, arena: Allocator, ctx: Ctx) Cursor {
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const tree = treeRoomName(&tb, ctx.identity);
+ return .{
+ .tree_room = arena.dupe(u8, tree) catch "",
+ .tree = if (tree.len > 0) presence_chan.roomSize(io, ctx.dir, tree) else 0,
+ .device = presence_chan.roomSize(io, ctx.dir, presence.device_room),
+ };
+}
+
+/// New messages for this agent since `cur`, advancing it. The working-set
+/// rules are graff's own (peer_target): every unaddressed worktree line, and
+/// only lines addressed to us (or the user's /tell all) from the device room.
+pub fn collect(io: Io, arena: Allocator, ctx: Ctx, cur: *Cursor) []const Heard {
+ var out: std.ArrayList(Heard) = .empty;
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const tree = treeRoomName(&tb, ctx.identity);
+ if (tree.len > 0) {
+ // Moved to another folder: start that room at its tail.
+ if (!std.mem.eql(u8, cur.tree_room, tree)) {
+ cur.tree_room = arena.dupe(u8, tree) catch tree;
+ cur.tree = presence_chan.roomSize(io, ctx.dir, tree);
+ }
+ for (presence_chan.readNewMessages(io, arena, ctx.dir, tree, &cur.tree)) |m| {
+ if (isOwn(m, ctx.name) or !peer_target.treeHears(m, ctx.name)) continue;
+ out.append(arena, .{ .room = .tree, .m = m }) catch break;
+ }
+ }
+ for (presence_chan.readNewMessages(io, arena, ctx.dir, presence.device_room, &cur.device)) |m| {
+ if (isOwn(m, ctx.name) or !peer_target.deviceHears(m, ctx.name)) continue;
+ out.append(arena, .{ .room = .device, .m = m }) catch break;
+ }
+ return out.items;
+}
+
+fn isOwn(m: Message, name: []const u8) bool {
+ return std.mem.eql(u8, m.from_session, name);
+}
+
+/// Unread messages from the agent we are about to send to. Non-empty means
+/// the send is held: they said something after our last read.
+pub fn unreadFrom(heard: []const Heard, target: Owner) usize {
+ var n: usize = 0;
+ for (heard) |h| {
+ if (std.mem.eql(u8, h.m.from_session, target.session_id) or h.m.from_pid == target.pid) n += 1;
+ }
+ return n;
+}
+
+pub fn livePeers(io: Io, arena: Allocator, ctx: Ctx) []const Owner {
+ const peers = presence.listPeersBounded(io, arena, ctx.dir, 64);
+ var out: std.ArrayList(Owner) = .empty;
+ for (peers.records) |rec| {
+ if (rec.pid == ctx.owner.pid and std.mem.eql(u8, rec.session_id, ctx.name)) continue;
+ out.append(arena, rec) catch break;
+ }
+ return out.items;
+}
+
+pub fn writeHeard(w: *Io.Writer, h: Heard) !void {
+ const secs: u64 = @intCast(@divFloor(@max(h.m.ts_ms, 0), 1000));
+ const day = secs % 86400;
+ const to = if (h.m.to.len == 0) "all" else h.m.to;
+ try w.print("[{s} from=@{s} to={s} {d:0>2}:{d:0>2}:{d:0>2}Z] {s}\n", .{
+ @tagName(h.room), h.m.from_session, to, day / 3600, (day / 60) % 60, day % 60, h.m.text,
+ });
+}
+
+/// Wake a live graff session over its Accord socket. The receiver only needs
+/// the frame kind to start draining, so an oversize line is replaced by a
+/// small marker instead of being dropped.
+pub fn wake(io: Io, gpa: Allocator, dir_path: []const u8, rec: Owner, line: []const u8) void {
+ if (!presence_accord.enabled()) return;
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.fmt.bufPrint(&path_buf, "{s}/{d}-{x}.accord.sock", .{ dir_path, rec.pid, rec.start_id }) catch return;
+ if (!presence_accord.fitsUnixSocketPath(path)) return;
+ const addr = Io.net.UnixAddress.init(path) catch return;
+ const stream = addr.connect(io) catch return;
+ const sess = gpa.create(accord.Session) catch {
+ stream.close(io);
+ return;
+ };
+ defer gpa.destroy(sess);
+ sess.* = .{ .io = io, .gpa = gpa, .role = .client, .stream = stream };
+ sess.start() catch {
+ sess.shutdown();
+ return;
+ };
+ defer sess.shutdown();
+ const payload = if (line.len <= accord.max_payload) line else "{\"kind\":\"wake\"}";
+ sess.send(1, .msg, .{}, payload) catch {};
+}
+
+pub const SendResult = union(enum) {
+ posted: struct { room: Room, target: ?Owner, woke: usize },
+ held: []const Heard,
+ no_target,
+ ambiguous: []const Owner,
+ no_room,
+};
+
+pub fn send(io: Io, gpa: Allocator, arena: Allocator, dir_path: []const u8, ctx: Ctx, cur: *Cursor, to: ?[]const u8, text: []const u8, anyway: bool) SendResult {
+ const peers = livePeers(io, arena, ctx);
+ var target: ?Owner = null;
+ if (to) |want| switch (peer_target.resolvePeer(peers, want)) {
+ .one => |p| target = p,
+ .none => return .no_target,
+ .ambiguous => return .{ .ambiguous = peers },
+ };
+ if (target) |t| if (!anyway) {
+ const heard = collect(io, arena, ctx, cur);
+ if (unreadFrom(heard, t) > 0) return .{ .held = heard };
+ };
+ const room: Room = if (target) |t|
+ (if (ctx.identity.len > 0 and std.mem.eql(u8, t.identity, ctx.identity)) .tree else .device)
+ else
+ .tree;
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const room_name = if (room == .tree) treeRoomName(&tb, ctx.identity) else presence.device_room;
+ if (room_name.len == 0) return .no_room;
+ const msg: Message = .{
+ .from_pid = ctx.owner.pid,
+ .from_start = ctx.owner.start_id,
+ .from_session = ctx.name,
+ .to = if (target) |t| t.session_id else "",
+ .ts_ms = util.unixMs(io),
+ .text = text,
+ };
+ if (!presence_chan.postMessage(io, arena, ctx.dir, room_name, msg)) return .no_room;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(msg) catch {};
+ var woke: usize = 0;
+ // Wake only who hears it: the DM target, or this worktree's agents.
+ for (peers) |p| {
+ const hears = if (target) |t| p.pid == t.pid and p.start_id == t.start_id else std.mem.eql(u8, p.identity, ctx.identity);
+ if (!hears or std.mem.eql(u8, p.activity, "external")) continue;
+ wake(io, gpa, dir_path, p, aw.writer.buffered());
+ woke += 1;
+ }
+ return .{ .posted = .{ .room = room, .target = target, .woke = woke } };
+}
+
+fn readStdin(io: Io, arena: Allocator) []const u8 {
+ if (Io.File.stdin().isTty(io) catch true) return "";
+ var buf: [4096]u8 = undefined;
+ var r = Io.File.stdin().reader(io, &buf);
+ const all = r.interface.allocRemaining(arena, .limited(64 * 1024)) catch return "";
+ return std.mem.trim(u8, all, " \t\r\n");
+}
+
+pub fn command(gpa: Allocator, io: Io, arena: Allocator, home: []const u8, env_name: ?[]const u8, args: []const []const u8) !void {
+ var obuf: [4096]u8 = undefined;
+ // Streaming, not positional: agents often capture stdout to a file, and a
+ // positional writer would overwrite it from offset 0.
+ var w = Io.File.stdout().writerStreaming(io, &obuf);
+ const out = &w.interface;
+ defer out.flush() catch {};
+ const opts = parseOpts(arena, args) catch {
+ try out.writeAll(usage);
+ return;
+ };
+ if (builtin.os.tag != .macos and builtin.os.tag != .linux) std.process.fatal("graff peer: macOS and Linux only for now", .{});
+ if (home.len == 0) std.process.fatal("graff peer: no HOME", .{});
+ const dir_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, presence.registry_subdir });
+ try Io.Dir.cwd().createDirPath(io, dir_path);
+ var dir = try Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true });
+ defer dir.close(io);
+
+ const anc = agentAncestor(io) orelse std.process.fatal("graff peer: cannot identify the calling agent process", .{});
+ const identity = worktree_lease.currentIdentity(gpa, io, arena).id;
+ var fb: [256]u8 = undefined;
+ const name = opts.as orelse env_name orelse
+ try std.fmt.allocPrint(arena, "{s}@{s}", .{ anc.comm(), if (identity.len > 0) folderLabel(identity, &fb) else "device" });
+ const ctx: Ctx = .{ .dir = dir, .name = name, .owner = anc.rec, .identity = identity };
+ join(io, arena, ctx);
+ var cur = loadCursor(io, arena, ctx) orelse blk: {
+ const t = tailCursor(io, arena, ctx);
+ saveCursor(io, arena, ctx, t);
+ break :blk t;
+ };
+
+ if (std.mem.eql(u8, opts.action, "list") or std.mem.eql(u8, opts.action, "ls")) {
+ const peers = livePeers(io, arena, ctx);
+ if (opts.json) {
+ var s: std.json.Stringify = .{ .writer = out };
+ try s.write(peers);
+ try out.writeAll("\n");
+ return;
+ }
+ try out.print("you: {s}\n", .{name});
+ if (peers.len == 0) try out.writeAll("no other agents on this device\n");
+ for (peers) |p| {
+ var lb: [256]u8 = undefined;
+ const label = if (p.title.len > 0) p.title else p.session_id;
+ try out.print(" {s:<40} pid {d:<7} {s:<9} {s}\n", .{ util.utf8Prefix(label, 40), @as(u32, @intCast(@max(p.pid, 0))), p.activity, folderLabel(p.identity, &lb) });
+ }
+ } else if (std.mem.eql(u8, opts.action, "inbox")) {
+ var peek = cur;
+ const heard = collect(io, arena, ctx, if (opts.peek or opts.wake) &peek else &cur);
+ if (opts.wake) {
+ if (heard.len == 0) return;
+ try out.print("[peer] {d} new message{s} for {s} — read them with: graff peer inbox --as \"{s}\"\n", .{ heard.len, if (heard.len == 1) "" else "s", name, name });
+ return;
+ }
+ if (!opts.peek) saveCursor(io, arena, ctx, cur);
+ if (heard.len == 0 and !opts.json) try out.writeAll("no new messages\n");
+ for (heard) |h| {
+ if (opts.json) {
+ var s: std.json.Stringify = .{ .writer = out };
+ try s.write(.{ .room = @tagName(h.room), .from = h.m.from_session, .to = h.m.to, .ts_ms = h.m.ts_ms, .text = h.m.text });
+ try out.writeAll("\n");
+ } else try writeHeard(out, h);
+ }
+ } else if (std.mem.eql(u8, opts.action, "send")) {
+ const text = if (opts.text.len > 0) opts.text else readStdin(io, arena);
+ if (text.len == 0) std.process.fatal("graff peer send: no message (pass TEXT or pipe it on stdin)", .{});
+ switch (send(io, gpa, arena, dir_path, ctx, &cur, opts.to, text, opts.anyway)) {
+ .posted => |p| if (p.target) |t|
+ try out.print("sent to {s} ({s} room, {d} woken)\n", .{ if (t.title.len > 0) t.title else t.session_id, @tagName(p.room), p.woke })
+ else
+ try out.print("posted to this worktree's room ({d} woken)\n", .{p.woke}),
+ .held => |heard| {
+ saveCursor(io, arena, ctx, cur);
+ try out.writeAll("NOT SENT: they wrote to you after your last read. Read this, then resend (or pass --anyway):\n");
+ for (heard) |h| try writeHeard(out, h);
+ out.flush() catch {};
+ std.process.exit(3);
+ },
+ .no_target => std.process.fatal("graff peer send: no live agent matches '{s}' — see graff peer list", .{opts.to.?}),
+ .ambiguous => std.process.fatal("graff peer send: '{s}' matches several agents — use the exact name from graff peer list", .{opts.to.?}),
+ .no_room => std.process.fatal("graff peer send: not in a git worktree — pass --to NAME to DM someone", .{}),
+ }
+ } else {
+ try out.writeAll(usage);
+ }
+}
+
+test {
+ _ = @import("peer_cli_tests.zig");
+}
diff --git a/src/peer_cli_tests.zig b/src/peer_cli_tests.zig
new file mode 100644
index 00000000..d0bf708f
--- /dev/null
+++ b/src/peer_cli_tests.zig
@@ -0,0 +1,149 @@
+//! Tests for `graff peer` (peer_cli.zig), split out under the 600-line
+//! ceiling. Every room operation runs against a tmp dir with a fixed owner,
+//! so no process walking or real registry is involved.
+
+const std = @import("std");
+const testing = std.testing;
+const peer_cli = @import("peer_cli.zig");
+const presence = @import("presence.zig");
+const presence_chan = @import("presence_chan.zig");
+
+const tree_identity = "/work/repo/.git";
+
+fn ctxFor(dir: std.Io.Dir, name: []const u8, pid: i32) peer_cli.Ctx {
+ return .{ .dir = dir, .name = name, .owner = .{ .pid = pid, .start_id = 1 }, .identity = tree_identity };
+}
+
+fn post(arena: std.mem.Allocator, dir: std.Io.Dir, room: []const u8, from: []const u8, pid: i32, to: []const u8, text: []const u8) !void {
+ try testing.expect(presence_chan.postMessage(testing.io, arena, dir, room, .{ .from_pid = pid, .from_start = 1, .from_session = from, .to = to, .ts_ms = 1, .text = text }));
+}
+
+test "wake: an external send lands one msg frame on a graff session's Accord socket" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ const io = testing.io;
+ const gpa = testing.allocator;
+ const accord = @import("accord");
+ const presence_accord = @import("presence_accord.zig");
+ presence_accord.test_enabled = true;
+ defer presence_accord.test_enabled = false;
+ const dir = "graff-peer-wake";
+ try std.Io.Dir.cwd().createDirPath(io, dir);
+ defer std.Io.Dir.cwd().deleteTree(io, dir) catch {};
+ // The socket name a graff session with this pid/start would bind.
+ var listener = try accord.listenUnix(io, dir ++ "/4242-abc.accord.sock");
+ defer listener.deinit(io);
+ var sender = try io.concurrent(peer_cli.wake, .{ io, gpa, dir, .{ .pid = 4242, .start_id = 0xabc }, "{\"text\":\"hi\"}" });
+ const sess = try gpa.create(accord.Session);
+ defer gpa.destroy(sess);
+ sess.* = .{ .io = io, .gpa = gpa, .role = .server, .stream = try listener.accept(io) };
+ try sess.start();
+ defer sess.shutdown();
+ const got = try sess.recv(1);
+ defer got.deinit(gpa);
+ try testing.expectEqual(accord.Kind.msg, got.kind);
+ try testing.expectEqualStrings("{\"text\":\"hi\"}", got.payload);
+ sender.await(io);
+}
+
+test "parseOpts: action, flags, and the rest joined as the message" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const o = try peer_cli.parseOpts(arena_state.allocator(), &.{ "send", "--to", "graff-a", "hold", "off", "src/", "--anyway" });
+ try testing.expectEqualStrings("send", o.action);
+ try testing.expectEqualStrings("graff-a", o.to.?);
+ try testing.expectEqualStrings("hold off src/", o.text);
+ try testing.expect(o.anyway);
+ try testing.expectError(error.Usage, peer_cli.parseOpts(arena_state.allocator(), &.{ "send", "--to" }));
+ try testing.expectError(error.Usage, peer_cli.parseOpts(arena_state.allocator(), &.{ "inbox", "--bogus" }));
+}
+
+test "labelFromPath: a versioned install is named by its folder" {
+ try testing.expectEqualStrings("claude", peer_cli.labelFromPath("/Users/u/.local/share/claude/versions/2.1.282").?);
+ try testing.expectEqualStrings("codex", peer_cli.labelFromPath("/Applications/ChatGPT.app/Contents/Resources/codex").?);
+ try testing.expectEqualStrings("node", peer_cli.labelFromPath("/usr/local/bin/node").?);
+ try testing.expect(peer_cli.labelFromPath("/1/2") == null);
+}
+
+test "isShell and folderLabel" {
+ try testing.expect(peer_cli.isShell("-zsh"));
+ try testing.expect(peer_cli.isShell("bash"));
+ try testing.expect(!peer_cli.isShell("claude"));
+ var buf: [128]u8 = undefined;
+ try testing.expectEqualStrings("repo", peer_cli.folderLabel("/work/repo/.git", &buf));
+ try testing.expectEqualStrings("repo:wt1", peer_cli.folderLabel("/work/repo/.git/worktrees/wt1", &buf));
+}
+
+test "collect: worktree lines and device DMs are heard; own lines and other DMs are not" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const ctx = ctxFor(tmp.dir, "claude@repo", 50);
+ var cur = peer_cli.tailCursor(testing.io, arena, ctx);
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const tree = presence_chan.chanName(&tb, tree_identity);
+ try post(arena, tmp.dir, tree, "graff-a", 10, "", "room note");
+ try post(arena, tmp.dir, tree, "claude@repo", 50, "", "my own echo");
+ try post(arena, tmp.dir, tree, "graff-a", 10, "graff-b", "dm for someone else");
+ try post(arena, tmp.dir, presence.device_room, "graff-c", 11, "claude@repo", "device dm for me");
+ try post(arena, tmp.dir, presence.device_room, "graff-c", 11, "", "unaddressed device chatter");
+ const heard = peer_cli.collect(testing.io, arena, ctx, &cur);
+ try testing.expectEqual(@as(usize, 2), heard.len);
+ try testing.expectEqualStrings("room note", heard[0].m.text);
+ try testing.expectEqual(peer_cli.Room.device, heard[1].room);
+ try testing.expectEqualStrings("device dm for me", heard[1].m.text);
+ try testing.expectEqual(@as(usize, 0), peer_cli.collect(testing.io, arena, ctx, &cur).len);
+}
+
+test "cursor: saved position survives, and a first read joins at the tail" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const ctx = ctxFor(tmp.dir, "codex@repo", 51);
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const tree = presence_chan.chanName(&tb, tree_identity);
+ try post(arena, tmp.dir, tree, "graff-a", 10, "", "before joining");
+ try testing.expect(peer_cli.loadCursor(testing.io, arena, ctx) == null);
+ const t = peer_cli.tailCursor(testing.io, arena, ctx);
+ peer_cli.saveCursor(testing.io, arena, ctx, t);
+ try post(arena, tmp.dir, tree, "graff-a", 10, "", "after joining");
+ var cur = peer_cli.loadCursor(testing.io, arena, ctx) orelse return error.ExpectedCursor;
+ const heard = peer_cli.collect(testing.io, arena, ctx, &cur);
+ try testing.expectEqual(@as(usize, 1), heard.len);
+ try testing.expectEqualStrings("after joining", heard[0].m.text);
+}
+
+test "send: a DM to an agent that wrote since our last read is held, then goes through" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir = try tmp.dir.openDir(testing.io, ".", .{ .iterate = true });
+ defer dir.close(testing.io);
+ const self = @import("proc_identity.zig").selfRecord(testing.io);
+ // The recipient is this test process, so the registry keeps its record live.
+ const text = try @import("presence_record.zig").formatRecord(arena, .{ .pid = self.pid, .start_id = self.start_id, .session_id = "graff-a", .identity = tree_identity, .activity = "external" });
+ try dir.writeFile(testing.io, .{ .sub_path = "graff-a.json", .data = text });
+ const ctx: peer_cli.Ctx = .{ .dir = dir, .name = "claude@repo", .owner = .{ .pid = 52, .start_id = 1 }, .identity = tree_identity };
+ var cur = peer_cli.tailCursor(testing.io, arena, ctx);
+ var tb: [presence_chan.chan_name_max]u8 = undefined;
+ const tree = presence_chan.chanName(&tb, tree_identity);
+ try post(arena, dir, tree, "graff-a", self.pid, "claude@repo", "wait, I changed the plan");
+ switch (peer_cli.send(testing.io, testing.allocator, arena, ".", ctx, &cur, "graff-a", "sounds good", false)) {
+ .held => |heard| try testing.expectEqualStrings("wait, I changed the plan", heard[0].m.text),
+ else => return error.ExpectedHeld,
+ }
+ switch (peer_cli.send(testing.io, testing.allocator, arena, ".", ctx, &cur, "graff-a", "ok, following the new plan", false)) {
+ .posted => |p| try testing.expectEqual(peer_cli.Room.tree, p.room),
+ else => return error.ExpectedPosted,
+ }
+ var off: u64 = 0;
+ const log = presence_chan.readNewMessages(testing.io, arena, dir, tree, &off);
+ try testing.expectEqualStrings("ok, following the new plan", log[log.len - 1].text);
+ try testing.expectEqualStrings("graff-a", log[log.len - 1].to);
+ try testing.expect(peer_cli.send(testing.io, testing.allocator, arena, ".", ctx, &cur, "nobody-here", "hi", false) == .no_target);
+}
diff --git a/src/presence.zig b/src/presence.zig
index 8ccd2522..907c2269 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -214,8 +214,7 @@ pub fn rebind(io: Io, gpa: Allocator, arena: Allocator) void {
return;
};
defer dir.close(io);
- if (dir.readFileAlloc(io, chan, arena, .limited(16 * 1024 * 1024)) catch null) |text|
- g_inbox_off = @intCast(text.len);
+ g_inbox_off = presence_chan.roomSize(io, dir, chan);
};
writeOwn(io, arena);
}
@@ -393,10 +392,10 @@ pub fn drainChannel(io: Io, arena: Allocator) []const Message {
defer dir.close(io);
if (main_mod.unattended and !g_tail_seeked) {
g_tail_seeked = true;
- if (dir.readFileAlloc(io, chan, arena, .limited(16 * 1024 * 1024)) catch null) |text| g_inbox_off = @intCast(text.len);
+ g_inbox_off = presence_chan.roomSize(io, dir, chan);
// The device room too: deliverInbound always drains the worktree
// channel first, so one fast-forward covers both rooms.
- if (dir.readFileAlloc(io, device_room, arena, .limited(16 * 1024 * 1024)) catch null) |text| g_device_off = @intCast(text.len);
+ g_device_off = presence_chan.roomSize(io, dir, device_room);
}
const raw = presence_chan.readNewMessages(io, arena, dir, chan, &g_inbox_off);
var out: std.ArrayList(Message) = .empty;
@@ -452,12 +451,9 @@ pub fn seekRoomsToTail(io: Io, arena: Allocator) void {
return;
};
defer dir.close(io);
- if (g_chan) |chan| {
- if (dir.readFileAlloc(io, chan, arena, .limited(16 * 1024 * 1024)) catch null) |text|
- g_inbox_off = @intCast(text.len);
- }
- if (dir.readFileAlloc(io, device_room, arena, .limited(16 * 1024 * 1024)) catch null) |text|
- g_device_off = @intCast(text.len);
+ _ = arena;
+ if (g_chan) |chan| g_inbox_off = presence_chan.roomSize(io, dir, chan);
+ g_device_off = presence_chan.roomSize(io, dir, device_room);
g_tail_seeked = true;
}
diff --git a/src/presence_chan.zig b/src/presence_chan.zig
index fea33872..1a2db535 100644
--- a/src/presence_chan.zig
+++ b/src/presence_chan.zig
@@ -70,16 +70,37 @@ pub fn postMessage(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, msg:
return true;
}
+/// Most bytes one drain reads. A drain reads only what follows its offset, so
+/// a long-lived room costs the new lines, not the whole log.
+pub const drain_window: usize = 1024 * 1024;
+
+/// Current byte length of a room, or 0 when it does not exist yet. Joining at
+/// the tail needs only this, never the bytes.
+pub fn roomSize(io: Io, dir: Io.Dir, name: []const u8) u64 {
+ const st = dir.statFile(io, name, .{}) catch return 0;
+ return st.size;
+}
+
/// 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.
+/// recreated; restart from the top rather than skip it forever. Reads at most
+/// `drain_window` bytes from the offset; the rest waits for the next drain.
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 &.{};
+ return readNewMessagesWindow(io, arena, dir, name, offset, drain_window);
+}
+
+pub fn readNewMessagesWindow(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, offset: *u64, window: usize) []const Message {
+ const f = dir.openFile(io, name, .{}) catch return &.{};
+ defer f.close(io);
+ const size = (f.stat(io) catch return &.{}).size;
+ if (size < offset.*) offset.* = 0;
+ if (size == offset.*) return &.{};
+ const want: usize = @intCast(@min(size - offset.*, window));
+ const buf = arena.alloc(u8, want) catch return &.{};
+ const text = buf[0 .. f.readPositionalAll(io, buf, offset.*) catch return &.{}];
var msgs: std.ArrayList(Message) = .empty;
- var pos: usize = @intCast(offset.*);
+ var pos: usize = 0;
while (std.mem.indexOfScalarPos(u8, text, pos, '\n')) |nl| {
const line = text[pos..nl];
pos = nl + 1;
@@ -87,7 +108,10 @@ pub fn readNewMessages(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8,
if (m.from_pid == 0 or m.text.len == 0) continue;
msgs.append(arena, m) catch break;
}
- offset.* = @intCast(pos);
+ // A single line longer than the window can never complete inside it; skip
+ // it rather than re-read the same bytes forever.
+ if (pos == 0 and text.len == window) pos = text.len;
+ offset.* += pos;
return msgs.items;
}
@@ -162,6 +186,52 @@ test "readNewMessages: a torn trailing line waits for the next drain" {
try std.testing.expectEqualStrings("rest", second[0].text);
}
+test "readNewMessages: a room past the old 256 KiB read cap still delivers new lines" {
+ 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 big: std.ArrayList(u8) = .empty;
+ for (0..1500) |_| {
+ try big.appendSlice(arena, "{\"from_pid\":9,\"from_start\":1,\"text\":\"");
+ try big.appendNTimes(arena, 'x', 200);
+ try big.appendSlice(arena, "\"}\n");
+ }
+ try tmp.dir.writeFile(io, .{ .sub_path = "room.jsonl", .data = big.items });
+ var off: u64 = roomSize(io, tmp.dir, "room.jsonl");
+ try std.testing.expect(off > 256 * 1024);
+ try std.testing.expect(postMessage(io, arena, tmp.dir, "room.jsonl", .{ .from_pid = 2, .from_start = 1, .ts_ms = 1, .text = "after the cap" }));
+ const got = readNewMessages(io, arena, tmp.dir, "room.jsonl", &off);
+ try std.testing.expectEqual(@as(usize, 1), got.len);
+ try std.testing.expectEqualStrings("after the cap", got[0].text);
+ try std.testing.expectEqual(roomSize(io, tmp.dir, "room.jsonl"), off);
+}
+
+test "readNewMessagesWindow: a line longer than the window is skipped, not re-read forever" {
+ 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 long_line: [301]u8 = @as([300]u8, @splat('y')) ++ "\n".*;
+ try tmp.dir.writeFile(io, .{ .sub_path = "room.jsonl", .data = &long_line });
+ try std.testing.expect(postMessage(io, arena, tmp.dir, "room.jsonl", .{ .from_pid = 2, .from_start = 1, .ts_ms = 1, .text = "ok" }));
+ var off: u64 = 0;
+ var heard: usize = 0;
+ var drains: usize = 0;
+ while (off < roomSize(io, tmp.dir, "room.jsonl") and drains < 32) : (drains += 1) {
+ const got = readNewMessagesWindow(io, arena, tmp.dir, "room.jsonl", &off, 128);
+ for (got) |m| {
+ if (std.mem.eql(u8, m.text, "ok")) heard += 1;
+ }
+ }
+ try std.testing.expectEqual(@as(usize, 1), heard);
+ try std.testing.expect(drains < 32);
+}
+
test "postMessage dual-writes JSONL when Accord live is on" {
if (@import("builtin").os.tag == .windows) return;
const io = std.testing.io;
diff --git a/src/proc_identity.zig b/src/proc_identity.zig
index aca24d5b..f8c158c8 100644
--- a/src/proc_identity.zig
+++ b/src/proc_identity.zig
@@ -222,6 +222,75 @@ fn probeDarwin(io: Io, pid: i32) Probe {
return if (usec == 0) .unknown else .{ .id = usec };
}
+/// A process's parent pid and short command name (`comm`, truncated by the
+/// kernel to 15 bytes). `graff peer` walks these to find the long-lived agent
+/// behind a per-command shell.
+pub const Parent = struct {
+ ppid: i32,
+ comm_buf: [16]u8 = @splat(0),
+ comm_len: u8 = 0,
+
+ pub fn comm(p: *const Parent) []const u8 {
+ return p.comm_buf[0..p.comm_len];
+ }
+};
+
+pub fn parentOf(pid: i32) ?Parent {
+ if (pid <= 0) return null;
+ switch (builtin.os.tag) {
+ .linux => {
+ var path_buf: [64]u8 = undefined;
+ const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/stat", .{pid}) catch return null;
+ const fd = std.posix.openat(std.posix.AT.FDCWD, path, .{}, 0) catch return null;
+ defer _ = std.posix.system.close(fd);
+ var buf: [4096]u8 = undefined;
+ const n = std.posix.read(fd, &buf) catch return null;
+ return parseLinuxParent(buf[0..n]);
+ },
+ .macos => {
+ var info: darwin.ProcBsdInfo = undefined;
+ const size: c_int = @sizeOf(darwin.ProcBsdInfo);
+ if (darwin.proc_pidinfo(@intCast(pid), darwin.PROC_PIDTBSDINFO, 0, &info, size) != size) return null;
+ var p: Parent = .{ .ppid = @intCast(info.ppid) };
+ const c = std.mem.sliceTo(&info.comm, 0);
+ @memcpy(p.comm_buf[0..c.len], c);
+ p.comm_len = @intCast(c.len);
+ return p;
+ },
+ else => return null,
+ }
+}
+
+/// Fields 2 (comm, between the first '(' and the LAST ')') and 4 (ppid) of
+/// a `/proc/<pid>/stat` line.
+pub fn parseLinuxParent(text: []const u8) ?Parent {
+ const open = std.mem.indexOfScalar(u8, text, '(') orelse return null;
+ const close = std.mem.lastIndexOfScalar(u8, text, ')') orelse return null;
+ if (close <= open) return null;
+ var it = std.mem.tokenizeAny(u8, text[close + 1 ..], " \t\r\n");
+ _ = it.next() orelse return null; // field 3: state
+ const ppid = std.fmt.parseInt(i32, it.next() orelse return null, 10) catch return null;
+ var p: Parent = .{ .ppid = ppid };
+ const c = text[open + 1 .. close];
+ const n = @min(c.len, p.comm_buf.len);
+ @memcpy(p.comm_buf[0..n], c[0..n]);
+ p.comm_len = @intCast(n);
+ return p;
+}
+
+test "parseLinuxParent: ppid and a comm holding spaces and ')'" {
+ const p = parseLinuxParent("4242 (my (odd) cmd) S 777 4242 4242 0 -1") orelse return error.ExpectedParent;
+ try std.testing.expectEqual(@as(i32, 777), p.ppid);
+ try std.testing.expectEqualStrings("my (odd) cmd", p.comm());
+ try std.testing.expect(parseLinuxParent("garbage") == null);
+}
+
+test "parentOf: this process has a live parent" {
+ if (builtin.os.tag != .linux and builtin.os.tag != .macos) return error.SkipZigTest;
+ const p = parentOf(selfPid()) orelse return error.ExpectedParent;
+ try std.testing.expect(p.ppid > 0);
+}
+
const win = struct {
const w = std.os.windows;
const PROCESS_QUERY_LIMITED_INFORMATION: w.DWORD = 0x1000;
diff --git a/src/startup.zig b/src/startup.zig
index 0eb78d68..5ed54f36 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -389,6 +389,13 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
return true;
}
+ // `graff peer <list|send|inbox>`: the device's agent rooms for any agent
+ // with a shell (Claude Code, Codex, scripts), not only graff sessions.
+ if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "peer")) {
+ try @import("peer_cli.zig").command(gpa, io, arena, init.environ_map.get("HOME") orelse "", init.environ_map.get("GRAFF_PEER_NAME"), flags.positionals.items[1..]);
+ return true;
+ }
+
// `graff sandboxes [stop <id>]`: list the account's gateway sandboxes or
// spin one down. Key resolution mirrors a normal run: CODEGRAFF_API_KEY
// env first, else the `graff login` file via loadCodegraffKey.