graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(session): persist peer-channel cursor and inbox across resume (#584)
Rach24390f4521d2
diff --git a/docs/adr/0014-session-resume-carries-the-room-cursor.md b/docs/adr/0014-session-resume-carries-the-room-cursor.mdnew file mode 100644index 00000000..52103a36--- /dev/null+++ b/docs/adr/0014-session-resume-carries-the-room-cursor.md@@ -0,0 +1,41 @@+# 0014. Session resume carries the room cursor, not a replay++Status: accepted 2026-08-20++## Context++ADR 0004 made peer speech pull: a one-line `[peer]` wake in history, bodies in+a process-local inbox. That is cheap *inside one process*. `/resume` starts a+new process. The worktree/device JSONL offsets (`g_inbox_off`, `g_device_off`)+and the parked ring reset to zero, so the first drain is treated as a late+join and re-injects the last 10 room lines. Compact already knew those wakes+are not the human; resume did not.++Codex persists a thread and reuses `prompt_cache_key` across compact and+resume (`codex-rs` remote compact snapshots). OpenCode pages session parts+from a cursor and keeps side-channel state out of the next request; its+`promptCacheKey` is the session id. Claude Code's SendMessage inbox is a file+per agent — resume pulls, it does not replay the room into the conversation.++A peer-only wake also counted as a user turn (`hasMeaningfulState`,+`sessionTitle`, `firstUserTitle`), so overheard chatter could mint or name a+session.++## Decision++- `.session.json` stores `chan_off`, `device_off`, and `peer_inbox`. Save+ strips `[peer]` / `[presence]` injects from `messages`. Resume restores the+ cursor and mailbox, then injects at most one wake if something is still+ unread.+- A legacy file with no cursor fields seeks both rooms to the tail (same as+ `-p`). One-shots stay at the tail and do not restore the inbox.+- Peer injects are not a human turn for title or "meaningful state."++## Consequences++- `/resume` of a talking session continues the room; it does not pay the+ backlog again or title itself `[peer] 1 unread…`.+- Unread bodies survive a crash only because they are now on the session+ file. The JSONL rooms remain the log; the session file is the cursor.+- Revisit if the inbox must be shared across two processes on the same+ session name (today one process owns a session file).diff --git a/docs/adr/README.md b/docs/adr/README.mdindex d4c8e11b..c301fb4f 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -24,6 +24,7 @@ record only when you need the evidence or the edge cases.| [0011](0011-prompt-cache-max-is-visible.md) | Prompt-cache max is `/cache` posture, not a new default; `/btw` rides the parent prefix. || [0012](0012-overflow-handles-named-limits-extra-roots.md) | Fat tool results become `tr_N` handles; named `--context-limit` caps prefix bytes; `--add-dir` extra roots are PathConfine allow-lists, not cwd/skill/session sources. || [0013](0013-list-dir-lives-in-codedb.md) | Directory listing is `codedb list_dir` (in-process BFS, gitignore, 10k cap), not a new always-on catalog tool. |+| [0014](0014-session-resume-carries-the-room-cursor.md) | `/resume` restores the peer-channel byte cursor and inbox; it does not replay the room into history. |## When to write onediff --git a/src/peer_channel.zig b/src/peer_channel.zigindex 34500607..34304806 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -129,6 +129,12 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {pub const backlog_tail_max = 10;var g_backlog_tail_cut = false;+/// Resume already restored the room cursor — the next drain is incremental,+/// never a first-join backlog replay.+pub fn markCaughtUp() void {+ g_backlog_tail_cut = true;+}+/// Of a first-drain backlog the REPL prints only this many trailing lines;/// the rest still lands in history (the model coordinates from it) behind a/// "delivered to context" marker. Live drains are unaffected.diff --git a/src/peer_inbox.zig b/src/peer_inbox.zigindex cc735ba5..aaf5d316 100644--- a/src/peer_inbox.zig+++ b/src/peer_inbox.zig@@ -36,11 +36,15 @@ var g_items: [inbox_cap]Parked = undefined;var g_head: usize = 0;var g_len: usize = 0;-pub fn resetForTest() void {+pub fn clear() void {g_head = 0;g_len = 0;}+pub fn resetForTest() void {+ clear();+}+pub fn unread() usize {return g_len;}@@ -125,6 +129,53 @@ pub fn takeAll(arena: Allocator) []const u8 {return buf.items;}+/// Digest parked bodies so a save skips only when the mailbox is unchanged.+pub fn mixFingerprint(f: anytype) void {+ f.num(g_len);+ var i: usize = 0;+ while (i < g_len) : (i += 1) {+ const p = itemAt(i);+ f.text(fromSlice(p));+ f.text(textSlice(p));+ f.flag(p.dm);+ f.flag(p.device);+ }+}++/// The parked ring as a JSON array for `.session.json`.+pub fn writeJson(s: *std.json.Stringify) !void {+ try s.beginArray();+ var i: usize = 0;+ while (i < g_len) : (i += 1) {+ const p = itemAt(i);+ try s.beginObject();+ try s.objectField("from");+ try s.write(fromSlice(p));+ try s.objectField("text");+ try s.write(textSlice(p));+ try s.objectField("dm");+ try s.write(p.dm);+ try s.objectField("device");+ try s.write(p.device);+ try s.endObject();+ }+ try s.endArray();+}++/// Replace the ring from a saved `peer_inbox` array. Garbage is skipped.+pub fn restoreJson(v: std.json.Value) void {+ clear();+ if (v != .array) return;+ for (v.array.items) |item| {+ if (item != .object) continue;+ const from = if (item.object.get("from")) |f| (if (f == .string) f.string else continue) else continue;+ const text = if (item.object.get("text")) |t| (if (t == .string) t.string else continue) else continue;+ const dm = if (item.object.get("dm")) |d| (d == .bool and d.bool) else false;+ const device = if (item.object.get("device")) |d| (d == .bool and d.bool) else false;+ parkOne(from, text, dm, device);+ }+}+/// 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";@@ -200,3 +251,21 @@ test "formatList: one short line per peer; empty is honest" {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);}++test "inbox JSON round-trip: restoreJson rebuilds the ring" {+ resetForTest();+ defer resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ _ = parkHeard(&.{msg("s-a", "hold the tree", "")}, &.{});+ var aw: std.Io.Writer.Allocating = .init(a);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try writeJson(&s);+ clear();+ try testing.expectEqual(@as(usize, 0), unread());+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, aw.writer.buffered(), .{});+ restoreJson(parsed);+ try testing.expectEqual(@as(usize, 1), unread());+ try testing.expect(std.mem.indexOf(u8, takeAll(a), "hold the tree") != null);+}diff --git a/src/presence.zig b/src/presence.zigindex 756e97ac..61c968da 100644--- a/src/presence.zig+++ b/src/presence.zig@@ -16,78 +16,19 @@ const util = @import("util.zig");const main_mod = @import("main.zig"); // `unattended`: one-shots join channel rooms at the tail, not the backlogconst unixMs = util.unixMs;+const presence_mutate = @import("presence_mutate.zig");const Owner = worktree_lease.Owner;+pub const isSharedTreeGit = presence_mutate.isSharedTreeGit;+pub const isSharedTreeShell = presence_mutate.isSharedTreeShell;+/// Per-user registry: <home>/.graff/live. Deliberately NOT the per-project .graff/sessions of session_index.zig — presence is device-local and keyed by worktree identity so two checkouts of one repo stay distinct (#320).pub const registry_subdir = ".graff/live";const max_peers = 16;const record_max = 4096;-/// Git subcommands that mutate the index, refs, or working tree — the shared state the #469 collision tore up. Read-only git (status/log/diff) and remote-only git (fetch/push) stay ungated: the checkpoint exists because two sessions edit ONE uncommitted tree, not because git ran.-fn isSharedTreeSubcommand(sub: []const u8) bool {- const subs = [_][]const u8{- "add", "rm", "mv", "commit", "reset",- "restore", "checkout", "switch", "stash", "pull",- "rebase", "merge", "cherry-pick", "revert", "am",- "apply", "clean", "update-index",- };- for (subs) |s| if (std.mem.eql(u8, sub, s)) return true;- return false;-}--/// Whether `cmd` runs an index/tree-mutating git subcommand. Tokenizes on-/// shell separators so `cd x && git add -A` and `sh -c 'git rm y'` classify by-/// the subcommand, and skips git's global options so `git -C repo reset` is-/// seen as `reset`. A quoted "git add" inside an echo string is a known false-/// positive — the cost is one needless checkpoint line, the same trade-/// harness_policy.isDestructiveGit makes for its substring scan.-pub fn isSharedTreeGit(cmd: []const u8) bool {- var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");- while (it.next()) |tok| {- if (!std.mem.eql(u8, tok, "git")) continue;- while (it.next()) |arg| {- if (arg[0] == '-') {- // -C/-c take the NEXT token as their value; skip it too.- if (std.mem.eql(u8, arg, "-C") or std.mem.eql(u8, arg, "-c")) _ = it.next();- continue;- }- return isSharedTreeSubcommand(arg);- }- return false; // a bare `git` mutates nothing- }- return false;-}--/// The shell half of the #469 incident vector: `mv` (any form — a rename can-/// disappear a file a peer just wrote) and recursive `rm`. Plain `rm` of one-/// file stays ungated: the checkpoint exists for tree-level disruption, and-/// it fires once per peer regardless, so the odd false positive costs one-/// line, never a workflow.-pub fn isSharedTreeShell(cmd: []const u8) bool {- var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");- while (it.next()) |tok| {- if (std.mem.eql(u8, tok, "mv")) {- var operands: usize = 0;- while (it.next()) |arg| {- if (arg[0] == '-') continue;- operands += 1;- }- if (operands >= 2) return true;- continue;- }- if (std.mem.eql(u8, tok, "rm")) {- while (it.next()) |arg| {- if (arg[0] != '-') break;- if (std.mem.indexOfAny(u8, arg, "rR") != null) return true;- }- continue;- }- }- return false;-}-/// The on-disk shape. Older/newer graffs tolerate each other via/// ignore_unknown_fields both ways (a superset write parses down fine).const RecordJson = struct {@@ -296,6 +237,7 @@ pub fn deinit(gpa: Allocator) void {g_chan = null;g_self = .{};g_inbox_off = 0;+ g_device_off = 0;g_tail_seeked = false;g_acked_len = 0;}@@ -438,6 +380,48 @@ pub fn ownIdentity() []const u8 {pub const device_room = "chan-all.jsonl";+/// Byte cursors into the worktree and device JSONL rooms. Persist these on+/// the session file so `/resume` continues instead of re-hearing the tail+/// (ADR 0014). Codex keeps a thread cursor; Claude persists the inbox.+pub const RoomCursor = struct { chan: u64, device: u64 };++pub fn roomCursor() RoomCursor {+ return .{ .chan = g_inbox_off, .device = g_device_off };+}++pub fn adoptRoomCursor(c: RoomCursor) void {+ g_inbox_off = c.chan;+ g_device_off = c.device;+ g_tail_seeked = true;+}++/// Join at the live tail — same as a `-p` one-shot. Used when a resumed+/// session has no saved cursor (legacy file) so we do not replay stale room.+pub fn seekRoomsToTail(io: Io, arena: Allocator) void {+ const dir_path = g_dir orelse {+ g_tail_seeked = true;+ return;+ };+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch {+ g_tail_seeked = true;+ 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);+ g_tail_seeked = true;+}++pub fn resetRoomCursorForTest() void {+ g_inbox_off = 0;+ g_device_off = 0;+ g_tail_seeked = false;+}+/// Every live session on this device, any worktree (self excluded) — the/// /tell target list. Like liveTreePeers but identity-blind.pub fn liveAllPeers(io: Io, arena: Allocator) []const Owner {@@ -491,37 +475,15 @@ pub fn drainDevice(io: Io, arena: Allocator) []const Message {return out.items;}-test "isSharedTreeGit: flags index/tree-mutating git, ignores read-only git" {- try std.testing.expect(isSharedTreeGit("git add -A"));- try std.testing.expect(isSharedTreeGit("git commit -m \"wip\""));- try std.testing.expect(isSharedTreeGit("GIT_EDITOR=true git commit --amend"));- try std.testing.expect(isSharedTreeGit("git -C /tmp/repo reset HEAD~1"));- try std.testing.expect(isSharedTreeGit("git -c user.name=x commit"));- try std.testing.expect(isSharedTreeGit("cd sub && git stash"));- try std.testing.expect(isSharedTreeGit("sh -c 'git rm -r old/'"));- try std.testing.expect(isSharedTreeGit("git checkout -- src/"));- try std.testing.expect(!isSharedTreeGit("git status"));- try std.testing.expect(!isSharedTreeGit("git log --oneline -5"));- try std.testing.expect(!isSharedTreeGit("git diff HEAD"));- try std.testing.expect(!isSharedTreeGit("git push origin main"));- try std.testing.expect(!isSharedTreeGit("git branch"));- try std.testing.expect(!isSharedTreeGit("gh issue list"));- try std.testing.expect(!isSharedTreeGit("git"));- try std.testing.expect(!isSharedTreeGit("ls src/"));-}--test "isSharedTreeShell: flags mv and recursive rm, leaves everyday commands alone" {- try std.testing.expect(isSharedTreeShell("mv old/ new/"));- try std.testing.expect(isSharedTreeShell("mv a.ts b.ts"));- try std.testing.expect(isSharedTreeShell("mv src/a src/b dest/"));- try std.testing.expect(isSharedTreeShell("rm -rf node_modules"));- try std.testing.expect(isSharedTreeShell("rm -r build"));- try std.testing.expect(isSharedTreeShell("cd x && mv a b"));- try std.testing.expect(!isSharedTreeShell("rm -f .lock"));- try std.testing.expect(!isSharedTreeShell("rm one-file.txt"));- try std.testing.expect(!isSharedTreeShell("mv")); // no operands: a usage error, not a tree event- try std.testing.expect(!isSharedTreeShell("ls -la"));- try std.testing.expect(!isSharedTreeShell("echo moved"));+test "roomCursor adopt/reset: resume continues from the saved byte offset" {+ resetRoomCursorForTest();+ defer resetRoomCursorForTest();+ adoptRoomCursor(.{ .chan = 4096, .device = 128 });+ const cur = roomCursor();+ try std.testing.expectEqual(@as(u64, 4096), cur.chan);+ try std.testing.expectEqual(@as(u64, 128), cur.device);+ resetRoomCursorForTest();+ try std.testing.expectEqual(@as(u64, 0), roomCursor().chan);}test "presence record round-trips pid, identity, and goal" {diff --git a/src/presence_mutate.zig b/src/presence_mutate.zignew file mode 100644index 00000000..d1486615--- /dev/null+++ b/src/presence_mutate.zig@@ -0,0 +1,104 @@+//! Shared-tree mutation classifiers for the #469 collision gate.+//! Split out of presence.zig so that file can hold the durable room cursor+//! without crossing the 600-line ceiling.++const std = @import("std");++/// Git subcommands that mutate the index, refs, or working tree — the shared+/// state the #469 collision tore up. Read-only git (status/log/diff) and+/// remote-only git (fetch/push) stay ungated: the checkpoint exists because+/// two sessions edit ONE uncommitted tree, not because git ran.+fn isSharedTreeSubcommand(sub: []const u8) bool {+ const subs = [_][]const u8{+ "add", "rm", "mv", "commit", "reset",+ "restore", "checkout", "switch", "stash", "pull",+ "rebase", "merge", "cherry-pick", "revert", "am",+ "apply", "clean", "update-index",+ };+ for (subs) |s| if (std.mem.eql(u8, sub, s)) return true;+ return false;+}++/// Whether `cmd` runs an index/tree-mutating git subcommand. Tokenizes on+/// shell separators so `cd x && git add -A` and `sh -c 'git rm y'` classify by+/// the subcommand, and skips git's global options so `git -C repo reset` is+/// seen as `reset`. A quoted "git add" inside an echo string is a known false+/// positive — the cost is one needless checkpoint line, the same trade+/// harness_policy.isDestructiveGit makes for its substring scan.+pub fn isSharedTreeGit(cmd: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ while (it.next()) |tok| {+ if (!std.mem.eql(u8, tok, "git")) continue;+ while (it.next()) |arg| {+ if (arg[0] == '-') {+ // -C/-c take the NEXT token as their value; skip it too.+ if (std.mem.eql(u8, arg, "-C") or std.mem.eql(u8, arg, "-c")) _ = it.next();+ continue;+ }+ return isSharedTreeSubcommand(arg);+ }+ return false; // a bare `git` mutates nothing+ }+ return false;+}++/// The shell half of the #469 incident vector: `mv` (any form — a rename can+/// disappear a file a peer just wrote) and recursive `rm`. Plain `rm` of one+/// file stays ungated: the checkpoint exists for tree-level disruption, and+/// it fires once per peer regardless, so the odd false positive costs one+/// line, never a workflow.+pub fn isSharedTreeShell(cmd: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ while (it.next()) |tok| {+ if (std.mem.eql(u8, tok, "mv")) {+ var operands: usize = 0;+ while (it.next()) |arg| {+ if (arg[0] == '-') continue;+ operands += 1;+ }+ if (operands >= 2) return true;+ continue;+ }+ if (std.mem.eql(u8, tok, "rm")) {+ while (it.next()) |arg| {+ if (arg[0] != '-') break;+ if (std.mem.indexOfAny(u8, arg, "rR") != null) return true;+ }+ continue;+ }+ }+ return false;+}++test "isSharedTreeGit: flags index/tree-mutating git, ignores read-only git" {+ try std.testing.expect(isSharedTreeGit("git add -A"));+ try std.testing.expect(isSharedTreeGit("git commit -m \"wip\""));+ try std.testing.expect(isSharedTreeGit("GIT_EDITOR=true git commit --amend"));+ try std.testing.expect(isSharedTreeGit("git -C /tmp/repo reset HEAD~1"));+ try std.testing.expect(isSharedTreeGit("git -c user.name=x commit"));+ try std.testing.expect(isSharedTreeGit("cd sub && git stash"));+ try std.testing.expect(isSharedTreeGit("sh -c 'git rm -r old/'"));+ try std.testing.expect(isSharedTreeGit("git checkout -- src/"));+ try std.testing.expect(!isSharedTreeGit("git status"));+ try std.testing.expect(!isSharedTreeGit("git log --oneline -5"));+ try std.testing.expect(!isSharedTreeGit("git diff HEAD"));+ try std.testing.expect(!isSharedTreeGit("git push origin main"));+ try std.testing.expect(!isSharedTreeGit("git branch"));+ try std.testing.expect(!isSharedTreeGit("gh issue list"));+ try std.testing.expect(!isSharedTreeGit("git"));+ try std.testing.expect(!isSharedTreeGit("ls src/"));+}++test "isSharedTreeShell: flags mv and recursive rm, leaves everyday commands alone" {+ try std.testing.expect(isSharedTreeShell("mv old/ new/"));+ try std.testing.expect(isSharedTreeShell("mv a.ts b.ts"));+ try std.testing.expect(isSharedTreeShell("mv src/a src/b dest/"));+ try std.testing.expect(isSharedTreeShell("rm -rf node_modules"));+ try std.testing.expect(isSharedTreeShell("rm -r build"));+ try std.testing.expect(isSharedTreeShell("cd x && mv a b"));+ try std.testing.expect(!isSharedTreeShell("rm -f .lock"));+ try std.testing.expect(!isSharedTreeShell("rm one-file.txt"));+ try std.testing.expect(!isSharedTreeShell("mv")); // no operands: a usage error, not a tree event+ try std.testing.expect(!isSharedTreeShell("ls -la"));+ try std.testing.expect(!isSharedTreeShell("echo moved"));+}diff --git a/src/session.zig b/src/session.zigindex 67110671..6dfae8e2 100644--- a/src/session.zig+++ b/src/session.zig@@ -28,6 +28,7 @@ const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stconst protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resumeconst http_headers = @import("http_headers.zig"); // the k3/codex prompt-cache key survives one tooconst session_transcript = @import("session_transcript.zig"); // #441: the append-only history this file's rewrites discard+const session_peer = @import("session_peer.zig"); // ADR 0014: room cursor + inbox ride the session fileconst Agent = agent_mod.Agent;const Keys = provider_mod.Keys;const unixMs = util.unixMs;@@ -94,8 +95,7 @@ pub fn sessionTitle(root: *Agent) []const u8 {if (root.session_title) |title| return title;for (root.messages.items) |m| {if (m != .object) continue;- const role = if (m.object.get("role")) |v| (if (v == .string) v.string else "") else "";- if (!std.mem.eql(u8, role, "user")) continue;+ if (!session_peer.isHumanUserTurn(m)) continue;if (m.object.get("content")) |c| switch (c) {.string => |text| return utf8Prefix(std.mem.trim(u8, text, " \t\r\n"), 80),.array => |arr| for (arr.items) |part| {@@ -128,8 +128,7 @@ pub fn hasMeaningfulState(root: *Agent) bool {if (root.tools_used.entries.items.len > 0) return true;for (root.messages.items) |m| {if (m != .object) continue;- const role = if (m.object.get("role")) |v| (if (v == .string) v.string else "") else "";- if (std.mem.eql(u8, role, "user")) return true;+ if (session_peer.isHumanUserTurn(m)) return true;}return false;}@@ -169,6 +168,7 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {f.num(root.context_local_tokens);f.num(protocol_seq.current());f.json(Value{ .array = root.messages });+ session_peer.mixFingerprint(&f);return f.final();}@@ -299,8 +299,9 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64try s.objectField("updated_ms");try s.write(unixMs(root.io));try s.objectField("messages");+ const saved_msgs = try session_peer.messagesForSave(arena, root.messages.items);const messages_start = aw.writer.buffered().len;- try s.write(Value{ .array = root.messages });+ try s.write(Value{ .array = saved_msgs });const messages_bytes = aw.writer.buffered().len - messages_start;const context_estimate = root.contextEstimateFromInputBytes(messages_bytes);// Preserve the last authoritative provider reading across resume. Responses@@ -325,6 +326,7 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64// kimi-code/codex key cache affinity on the durable conversation id; persisting ours keeps /resume warm.try s.objectField("cache_key");try s.write(http_headers.sessionId(root.io));+ try session_peer.writeFields(&s);try s.endObject();// #289: two graffs in one workspace share this file — the writer makes the@@ -376,7 +378,7 @@ pub fn appendTodosFromValue(arena: Allocator, todos: *std.ArrayList(agent_mod.To}}-fn contextTokensFromSession(obj: std.json.ObjectMap) u64 {+pub fn contextTokensFromSession(obj: std.json.ObjectMap) u64 {const v = obj.get("context_tokens") orelse return 0;if (v != .integer or v.integer <= 0) return 0;return @intCast(v.integer);@@ -389,19 +391,19 @@ pub fn cacheKeyFromSession(obj: std.json.ObjectMap) ?[]const u8 {}/// The persisted --json sequence high-water mark (#330); 0 for sessions saved/// before it existed, so a resume of one starts the numbering fresh.-fn eventSeqFromSession(obj: std.json.ObjectMap) u64 {+pub fn eventSeqFromSession(obj: std.json.ObjectMap) u64 {const v = obj.get("event_seq") orelse return 0;if (v != .integer or v.integer <= 0) return 0;return @intCast(v.integer);}-fn contextLocalTokensFromSession(obj: std.json.ObjectMap) ?u64 {+pub fn contextLocalTokensFromSession(obj: std.json.ObjectMap) ?u64 {const v = obj.get("context_local_tokens") orelse return null;if (v != .integer or v.integer < 0) return null;return @intCast(v.integer);}-fn restoreContextMeter(root: *Agent, saved_context_tokens: u64, saved_local_tokens: ?u64) void {+pub fn restoreContextMeter(root: *Agent, saved_context_tokens: u64, saved_local_tokens: ?u64) void {const current_local = root.fullRequestEstimateTokens();// A provider reading is meaningful across resume only after separating its// locally measurable component. Preserve the server-only delta (encrypted@@ -512,89 +514,5 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8root.last_request_write_failed = false;root.fallback_active = false;root.fallback_blocked = false;-}--test "session context meter restores hidden delta and legacy sessions re-estimate" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();-- const current = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":90000,\"context_local_tokens\":20000}", .{});- try std.testing.expectEqual(@as(u64, 90_000), contextTokensFromSession(current.object));- try std.testing.expectEqual(@as(u64, 20_000), contextLocalTokensFromSession(current.object).?);- const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});- try std.testing.expectEqual(@as(u64, 0), contextTokensFromSession(legacy.object));- try std.testing.expect(contextLocalTokensFromSession(legacy.object) == null);- const invalid = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":-1}", .{});- try std.testing.expectEqual(@as(u64, 0), contextTokensFromSession(invalid.object));- const invalid_local = try std.json.parseFromSliceLeaky(Value, a, "{\"context_local_tokens\":-1}", .{});- try std.testing.expect(contextLocalTokensFromSession(invalid_local.object) == null);-- // Model a resumed Responses history whose compact encrypted-reasoning handle- // serializes much smaller than the authoritative server token reading.- var msgs = std.json.Array.init(a);- const reasoning = "{\"type\":\"reasoning\",\"encrypted_content\":\"" ++ util.repeatBytes("x", 8192) ++ "\"}";- try msgs.append(try std.json.parseFromSliceLeaky(Value, a, reasoning, .{}));- var root: Agent = undefined;- root.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 100_000 };- root.messages = msgs;- root.sub = false;- root.strict = false;- root.sys_normal = "";- root.sys_strict = "";- root.tools_responses = "";- root.last_cache_read = 12_345;-- const local_estimate = root.fullRequestEstimateTokens();- try std.testing.expect(local_estimate < 90_000);- restoreContextMeter(&root, contextTokensFromSession(current.object), contextLocalTokensFromSession(current.object));- try std.testing.expectEqual(local_estimate + 70_000, root.last_context_tokens);- try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);- try std.testing.expect(root.last_context_tokens > local_estimate);-- // A legitimate over-window reading remains evidence when its paired local- // estimate matches the current request.- restoreContextMeter(&root, 150_000, local_estimate);- try std.testing.expectEqual(@as(u64, 150_000), root.last_context_tokens);-- // An unknown window still preserves the paired hidden delta; no clamping is- // needed or safe.- root.provider.context = 0;- restoreContextMeter(&root, 90_000, local_estimate);- try std.testing.expectEqual(root.fullRequestEstimateTokens() + (90_000 - local_estimate), root.last_context_tokens);- root.provider.context = 100_000;-- // A legacy session has no saved meter, but non-empty restored history must- // still produce a live local reading rather than resetting to zero.- root.last_cache_read = 99;- restoreContextMeter(&root, contextTokensFromSession(legacy.object), contextLocalTokensFromSession(legacy.object));- try std.testing.expectEqual(local_estimate, root.last_context_tokens);- try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);-- // A meter from an intermediate build without the paired local component is- // also ungrounded and must not force destructive recovery after resume.- const unpaired = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":99000}", .{});- restoreContextMeter(&root, contextTokensFromSession(unpaired.object), contextLocalTokensFromSession(unpaired.object));- try std.testing.expectEqual(local_estimate, root.last_context_tokens);-}--test "event_seq round-trips so a replacement graff continues the sequence (#330)" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();-- const saved = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":41}", .{});- try std.testing.expectEqual(@as(u64, 41), eventSeqFromSession(saved.object));- // Legacy sessions and corrupt values leave the live counter alone.- const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});- try std.testing.expectEqual(@as(u64, 0), eventSeqFromSession(legacy.object));- const bad = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":-3}", .{});- try std.testing.expectEqual(@as(u64, 0), eventSeqFromSession(bad.object));-- protocol_seq.resetForTest();- defer protocol_seq.resetForTest();- protocol_seq.restore(eventSeqFromSession(saved.object));- try std.testing.expectEqual(@as(u64, 42), protocol_seq.next()); // no id is ever reissued- protocol_seq.restore(eventSeqFromSession(legacy.object));- try std.testing.expectEqual(@as(u64, 43), protocol_seq.next());+ session_peer.restore(root, obj);}diff --git a/src/session_peer.zig b/src/session_peer.zignew file mode 100644index 00000000..48abe1b4--- /dev/null+++ b/src/session_peer.zig@@ -0,0 +1,206 @@+//! Durable peer-channel state on the session file (ADR 0014).+//!+//! Codex keeps a thread cursor and reuses `prompt_cache_key` across compact+//! and resume. OpenCode pages session parts from a cursor and does not replay+//! side-channel chatter into the next request. Claude Code's SendMessage inbox+//! lives on disk so resume can pull. Graff's room offsets and parked inbox+//! used to be process-local: `/resume` re-drained the last 10 JSONL lines,+//! re-injected a `[peer]` wake, and titled the session after the firehose.+//!+//! The session file now carries the byte cursors and the parked bodies.+//! History on disk drops the perishable wakes (ADR 0004). Resume restores+//! the mailbox; it does not replay the room.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const main_mod = @import("main.zig");+const peer_channel = @import("peer_channel.zig");+const peer_context = @import("peer_context.zig");+const peer_inbox = @import("peer_inbox.zig");+const presence = @import("presence.zig");+const session_writer = @import("session_writer.zig");++/// A human user turn — not a `[peer]` / `[presence]` inject. Title, meaningful-+/// state, and "first prompt" all use this so a wake cannot mint a session.+pub fn isHumanUserTurn(m: Value) bool {+ if (m != .object) return false;+ const role = m.object.get("role") orelse return false;+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;+ return !peer_context.isPeerInject(m);+}++/// Messages written to `.session.json`: wakes stay out. The transcript still+/// recorded them when they first entered history; compact / resume must not+/// keep paying for them on every later request.+pub fn messagesForSave(arena: Allocator, items: []const Value) !std.json.Array {+ var out = std.json.Array.init(arena);+ for (items) |m| {+ if (peer_context.isPeerInject(m)) continue;+ try out.append(m);+ }+ return out;+}++pub fn dropAllInjects(msgs: *std.json.Array) void {+ var i: usize = 0;+ while (i < msgs.items.len) {+ if (peer_context.isPeerInject(msgs.items[i])) {+ _ = msgs.orderedRemove(i);+ continue;+ }+ i += 1;+ }+}++pub fn mixFingerprint(f: *session_writer.Fingerprint) void {+ const cur = presence.roomCursor();+ f.num(cur.chan);+ f.num(cur.device);+ peer_inbox.mixFingerprint(f);+}++pub fn writeFields(s: *std.json.Stringify) !void {+ const cur = presence.roomCursor();+ try s.objectField("chan_off");+ try s.write(cur.chan);+ try s.objectField("device_off");+ try s.write(cur.device);+ try s.objectField("peer_inbox");+ try peer_inbox.writeJson(s);+}++fn u64Field(obj: std.json.ObjectMap, name: []const u8) ?u64 {+ const v = obj.get(name) orelse return null;+ if (v != .integer or v.integer < 0) return null;+ return @intCast(v.integer);+}++fn injectWake(root: *Agent) void {+ var obj: std.json.ObjectMap = .empty;+ obj.put(root.arena, "role", .{ .string = "user" }) catch return;+ obj.put(root.arena, "content", .{ .string = peer_context.capInject(peer_inbox.formatWake(root.arena)) }) catch return;+ root.messages.append(.{ .object = obj }) catch {};+}++/// After messages are restored: drop leftover wakes, adopt the room cursor+/// (or seek to tail on a legacy file / `-p` one-shot), restore the mailbox,+/// and inject at most one wake when something is still unread.+pub fn restore(root: *Agent, obj: std.json.ObjectMap) void {+ dropAllInjects(&root.messages);+ // One-shots must not hear predating chatter (ADR 0004 measured ~4k tokens+ // of stale room on the first step). Inbox restore would re-surface it.+ if (main_mod.unattended) {+ presence.seekRoomsToTail(root.io, root.arena);+ peer_inbox.clear();+ return;+ }+ if (obj.get("chan_off") != null or obj.get("device_off") != null) {+ presence.adoptRoomCursor(.{+ .chan = u64Field(obj, "chan_off") orelse 0,+ .device = u64Field(obj, "device_off") orelse 0,+ });+ // Catch-up after downtime is live traffic, not a first-join backlog.+ // Without this, deliverInbound would drop everything past the last 10.+ peer_channel.markCaughtUp();+ } else {+ // Pre-0014 file: no cursor. Seek rather than replay the last 10 lines.+ presence.seekRoomsToTail(root.io, root.arena);+ }+ if (obj.get("peer_inbox")) |v| peer_inbox.restoreJson(v);+ if (peer_inbox.unread() > 0) injectWake(root);+}++const testing = std.testing;++fn userText(arena: Allocator, s: []const u8) !Value {+ const raw = try std.fmt.allocPrint(arena, "{{\"role\":\"user\",\"content\":\"{s}\"}}", .{s});+ return std.json.parseFromSliceLeaky(Value, arena, raw, .{});+}++fn asstText(arena: Allocator, s: []const u8) !Value {+ const raw = try std.fmt.allocPrint(arena, "{{\"role\":\"assistant\",\"content\":\"{s}\"}}", .{s});+ return std.json.parseFromSliceLeaky(Value, arena, raw, .{});+}++test "isHumanUserTurn: peer wakes are not a human prompt" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try testing.expect(isHumanUserTurn(try userText(a, "keep going")));+ try testing.expect(!isHumanUserTurn(try userText(a, "[peer] 1 unread from s-2 — peer_message action=inbox")));+ try testing.expect(!isHumanUserTurn(try userText(a, "[peer message from a]: hold off")));+ try testing.expect(!isHumanUserTurn(try asstText(a, "keep going")));+}++test "messagesForSave / dropAllInjects: wakes leave the durable history" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var live = std.json.Array.init(a);+ try live.append(try userText(a, "fix the parser"));+ try live.append(try userText(a, "[peer] 2 unread from s-a — peer_message action=inbox"));+ try live.append(try asstText(a, "on it"));+ try live.append(try userText(a, "[presence] 1 other live session"));+ const saved = try messagesForSave(a, live.items);+ try testing.expectEqual(@as(usize, 2), saved.items.len);+ try testing.expectEqualStrings("fix the parser", saved.items[0].object.get("content").?.string);+ try testing.expectEqualStrings("on it", saved.items[1].object.get("content").?.string);+ dropAllInjects(&live);+ try testing.expectEqual(@as(usize, 2), live.items.len);+}++test "writeFields / restoreJson: inbox bodies survive a process restart" {+ peer_inbox.clear();+ defer peer_inbox.clear();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const presence_chan = @import("presence_chan.zig");+ const local = [_]presence_chan.Message{.{ .from_session = "s-a", .text = "hold gui/src", .to = "" }};+ const device = [_]presence_chan.Message{.{ .from_session = "s-b", .text = "your turn", .to = "me" }};+ try testing.expectEqual(@as(usize, 2), peer_inbox.parkHeard(&local, &device));++ var aw: std.Io.Writer.Allocating = .init(a);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try writeFields(&s);+ try s.endObject();+ const parsed = try std.json.parseFromSliceLeaky(Value, a, aw.writer.buffered(), .{});+ try testing.expect(parsed.object.get("chan_off") != null);+ try testing.expect(parsed.object.get("device_off") != null);++ peer_inbox.clear();+ try testing.expectEqual(@as(usize, 0), peer_inbox.unread());+ peer_inbox.restoreJson(parsed.object.get("peer_inbox").?);+ try testing.expectEqual(@as(usize, 2), peer_inbox.unread());+ const body = peer_inbox.takeAll(a);+ try testing.expect(std.mem.indexOf(u8, body, "hold gui/src") != null);+ try testing.expect(std.mem.indexOf(u8, body, "your turn") != null);+}++test "legacy session without cursor fields seeks rather than replaying (restore path)" {+ // restore() with no chan_off seeks; seek is a no-op without a registry.+ // What we can prove here: leftover wakes are stripped and an empty inbox+ // does not mint a new wake.+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ peer_inbox.clear();+ defer peer_inbox.clear();+ presence.resetRoomCursorForTest();+ defer presence.resetRoomCursorForTest();+ var root: Agent = undefined;+ root.arena = a;+ root.io = testing.io;+ root.messages = std.json.Array.init(a);+ try root.messages.append(try userText(a, "real prompt"));+ try root.messages.append(try userText(a, "[peer] 3 unread from old — peer_message action=inbox"));+ const empty = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});+ restore(&root, empty.object);+ try testing.expectEqual(@as(usize, 1), root.messages.items.len);+ try testing.expect(isHumanUserTurn(root.messages.items[0]));+}diff --git a/src/session_tests.zig b/src/session_tests.zigindex 2a8457dd..8d64e21e 100644--- a/src/session_tests.zig+++ b/src/session_tests.zig@@ -365,3 +365,100 @@ test "cache_key round-trips: parsed on load, garbage and absence rejected" {, .{});try std.testing.expect(session.cacheKeyFromSession(wrong_type.object) == null);}++test "hasMeaningfulState: a peer wake alone is not a conversation" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var root: Agent = undefined;+ root.goal = null;+ root.todos = .empty;+ root.tools_used = .{};+ root.messages = std.json.Array.init(arena);+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "role", .{ .string = "user" });+ try obj.put(arena, "content", .{ .string = "[peer] 1 unread from s-2 — peer_message action=inbox" });+ try root.messages.append(.{ .object = obj });+ try std.testing.expect(!session.hasMeaningfulState(&root));+ var human: std.json.ObjectMap = .empty;+ try human.put(arena, "role", .{ .string = "user" });+ try human.put(arena, "content", .{ .string = "keep going" });+ try root.messages.append(.{ .object = human });+ try std.testing.expect(session.hasMeaningfulState(&root));+}++test "session context meter restores hidden delta and legacy sessions re-estimate" {+ const util = @import("util.zig");+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const current = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":90000,\"context_local_tokens\":20000}", .{});+ try std.testing.expectEqual(@as(u64, 90_000), session.contextTokensFromSession(current.object));+ try std.testing.expectEqual(@as(u64, 20_000), session.contextLocalTokensFromSession(current.object).?);+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});+ try std.testing.expectEqual(@as(u64, 0), session.contextTokensFromSession(legacy.object));+ try std.testing.expect(session.contextLocalTokensFromSession(legacy.object) == null);+ const invalid = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":-1}", .{});+ try std.testing.expectEqual(@as(u64, 0), session.contextTokensFromSession(invalid.object));+ const invalid_local = try std.json.parseFromSliceLeaky(Value, a, "{\"context_local_tokens\":-1}", .{});+ try std.testing.expect(session.contextLocalTokensFromSession(invalid_local.object) == null);++ var msgs = std.json.Array.init(a);+ const reasoning = "{\"type\":\"reasoning\",\"encrypted_content\":\"" ++ util.repeatBytes("x", 8192) ++ "\"}";+ try msgs.append(try std.json.parseFromSliceLeaky(Value, a, reasoning, .{}));+ var root: Agent = undefined;+ root.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 100_000 };+ root.messages = msgs;+ root.sub = false;+ root.strict = false;+ root.sys_normal = "";+ root.sys_strict = "";+ root.tools_responses = "";+ root.last_cache_read = 12_345;++ const local_estimate = root.fullRequestEstimateTokens();+ try std.testing.expect(local_estimate < 90_000);+ session.restoreContextMeter(&root, session.contextTokensFromSession(current.object), session.contextLocalTokensFromSession(current.object));+ try std.testing.expectEqual(local_estimate + 70_000, root.last_context_tokens);+ try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);+ try std.testing.expect(root.last_context_tokens > local_estimate);++ session.restoreContextMeter(&root, 150_000, local_estimate);+ try std.testing.expectEqual(@as(u64, 150_000), root.last_context_tokens);++ root.provider.context = 0;+ session.restoreContextMeter(&root, 90_000, local_estimate);+ try std.testing.expectEqual(root.fullRequestEstimateTokens() + (90_000 - local_estimate), root.last_context_tokens);+ root.provider.context = 100_000;++ root.last_cache_read = 99;+ session.restoreContextMeter(&root, session.contextTokensFromSession(legacy.object), session.contextLocalTokensFromSession(legacy.object));+ try std.testing.expectEqual(local_estimate, root.last_context_tokens);+ try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);++ const unpaired = try std.json.parseFromSliceLeaky(Value, a, "{\"context_tokens\":99000}", .{});+ session.restoreContextMeter(&root, session.contextTokensFromSession(unpaired.object), session.contextLocalTokensFromSession(unpaired.object));+ try std.testing.expectEqual(local_estimate, root.last_context_tokens);+}++test "event_seq round-trips so a replacement graff continues the sequence (#330)" {+ const protocol_seq = @import("protocol_seq.zig");+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const saved = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":41}", .{});+ try std.testing.expectEqual(@as(u64, 41), session.eventSeqFromSession(saved.object));+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});+ try std.testing.expectEqual(@as(u64, 0), session.eventSeqFromSession(legacy.object));+ const bad = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":-3}", .{});+ try std.testing.expectEqual(@as(u64, 0), session.eventSeqFromSession(bad.object));++ protocol_seq.resetForTest();+ defer protocol_seq.resetForTest();+ protocol_seq.restore(session.eventSeqFromSession(saved.object));+ try std.testing.expectEqual(@as(u64, 42), protocol_seq.next());+ protocol_seq.restore(session.eventSeqFromSession(legacy.object));+ try std.testing.expectEqual(@as(u64, 43), protocol_seq.next());+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 456486f7..88e8b9e1 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -126,6 +126,8 @@ const peer_context = @import("peer_context.zig"); // ADR 0004 / #563 slice Fconst peer_context_compact_test = @import("peer_context_compact_test.zig");const peer_inbox = @import("peer_inbox.zig"); // Claude-style list/inbox pullconst peer_target = @import("peer_target.zig"); // exact DM / goal targeting+const session_peer = @import("session_peer.zig"); // ADR 0014 room cursor + inbox+const presence_mutate = @import("presence_mutate.zig"); // shared-tree classifiersconst workspace_switch = @import("workspace_switch.zig"); // ADR 0006 mid-session worktree switchconst result_read = @import("result_read.zig"); // overflow handle pagerconst handle_preview = @import("handle_preview.zig"); // notable lines on first spill@@ -270,6 +272,8 @@ test {_ = peer_context_compact_test;_ = peer_inbox;_ = peer_target;+ _ = session_peer;+ _ = presence_mutate;_ = workspace_switch;_ = result_read;_ = context_limits;diff --git a/src/title.zig b/src/title.zigindex 6d374012..18733f8d 100644--- a/src/title.zig+++ b/src/title.zig@@ -24,6 +24,7 @@ const extractText = providers.extractText;const messages_mod = @import("messages.zig");const textMessage = messages_mod.textMessage;+const peer_context = @import("peer_context.zig");pub fn titleFromPrompt(prompt: []const u8) []const u8 {const trimmed = std.mem.trim(u8, prompt, " \t\r\n");@@ -59,6 +60,7 @@ pub fn firstUserTitle(arena: Allocator, msgs: std.json.Array) []const u8 {if (m != .object) continue;const role = if (m.object.get("role")) |r| (if (r == .string) r.string else "") else "";if (!std.mem.eql(u8, role, "user")) continue;+ if (peer_context.isPeerInject(m)) continue;return titleFromPrompt(extractText(arena, m));}return "Chat";@@ -247,6 +249,7 @@ test "firstUserTitle: first user message becomes the header title, else Chat (#8var msgs = std.json.Array.init(a);try msgs.append(mk(a, "{\"role\":\"assistant\",\"content\":\"hi\"}"));+ try msgs.append(mk(a, "{\"role\":\"user\",\"content\":\"[peer] 1 unread from s-2 — peer_message action=inbox\"}"));try msgs.append(mk(a, "{\"role\":\"user\",\"content\":\"Fix the parser\\nmore detail\"}"));try std.testing.expectEqualStrings("Fix the parser", firstUserTitle(a, msgs));