graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(peer): treat channel speech as a working set, not the conversation
Cursor Agent44fafdaf97c3
diff --git a/docs/adr/0004-peer-speech-is-a-working-set.md b/docs/adr/0004-peer-speech-is-a-working-set.mdnew file mode 100644index 00000000..90739b3e--- /dev/null+++ b/docs/adr/0004-peer-speech-is-a-working-set.md@@ -0,0 +1,48 @@+# 0004. Peer speech is a working set, not the conversation++Status: accepted 2026-08-18++## Context++#469 injects co-resident speech into history as `role: user` (`[peer message+from …]`, plus a presence roster). Each `deliverInbound` **appends** another+blob that lives until generic compaction. Compaction then treats those blobs+as the human: `cleanUserTurn` is true, so `recentContextStart` will keep the+peer firehose in the ~8k verbatim suffix and summarize the real prompt away,+and `emergencyCutIndex` can restart the conversation on a coordination ping.++That is already a measured failure. `-p` one-shots seek the room to its tail+because ~4k tokens of stale chatter on the first step made ephemeral workers+*answer old messages*. Interactive sessions still dump up to 10 backlog lines+into history (the REPL only *shows* 2).++Surgically deleting those lines from live history is also wrong: it busts the+prompt-cache prefix, rewrites inbound the model already answered, and can eat+a trailing unreplied inject if compact runs between drain and reply. The+append-only JSONL room is the log; history is not a second copy of it.++## Decision++- The worktree/device JSONL room is the source of truth. History holds a+ **working set**: a short roster when the live set changes, and only the+ newest few inbound lines (byte-capped). `-p` still hears nothing that+ predates the process.+- Peer injects are not a human user turn. `cleanUserTurn`,+ `recentContextStart`, `emergencyCutIndex`, and `dropPriorTurnReasoning`+ ignore them as conversation boundaries.+- Forget at compact, never mid-turn. The summarizer does not see peer+ injects. The kept suffix drops *spent* injects (a later turn already+ followed them) and keeps a trailing *unreplied* inject. `durableState`+ restates who is live now, not quoted speech.+- Do not reopen device-wide model `"all"`. Do not invent a lock-claim parser+ here; the collision gate remains the safety net for a forgotten "I'm+ editing foo".++## Consequences++- Two sessions can talk without the room becoming another uncapped tool+ output. `/peek` and a later `peer_peek` re-read the log from disk.+- A compact that runs on a pending inbound does not swallow it.+- Revisit when structured claims exist (issue #563, later lock-claim slice):+ a live path+intent may then survive compact as harness state, the same way+ the goal checklist does.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex ee1fb423..696f0a17 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -14,6 +14,7 @@ record only when you need the evidence or the edge cases.| [0001](0001-structured-outputs-are-a-formatting-step.md) | Structured output is a final formatting step. Never constrain the agentic phase with a schema grammar, and do not use `--output-schema` unless a program consumes the result. || [0002](0002-xai-defaults-to-the-responses-wire.md) | xAI runs on the Responses wire by default (WS turns, lossless server compaction). `GRAFF_XAI_WIRE=chat` opts out; WS stays an explicit provider list. || [0003](0003-codegraff-wire-follows-model-capability.md) | Codegraff uses Responses + WS for GPT-5.6 and grok-4.6 aliases; Claude, Gemini, and other aliases stay on Chat Completions. |+| [0004](0004-peer-speech-is-a-working-set.md) | Peer speech is a working set in history, not a second copy of the room; compact drops spent injects and never treats them as the human. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 1f504f10..d57ef8c7 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -39,13 +39,13 @@{"id": "budget-exhausted-past-the-landing-dies-fatal", "why": "#368 exhaustedFatal, the harness's own last words - and the FIRST case that can exist at all, since the runner auto-failed every nonzero exit until expected_exit landed. The #390 landing reserve buys the run ONE tools-free final call; it cannot stop a model that answers that call with a tool call anyway, and executing that tool demands a call the pool cannot admit. A one-shot (-p) run must then die LOUDLY: exit 1 with the harness naming what ran out, that the work is PARTIAL and was NOT rolled back, and where the trace is - never the bare 'turn failed: RunBudgetExhausted' that #368 replaced, and never a silent exit 0. The asserts pin the whole ordering: request 1 carries the full toolset, request 2 IS the landing call (note present, tools gone), and only PAST it does the run die. NOTE (-p): one-shot sets root.out = null, so the --json event stream is empty and no event/final_text assert is expressible here; the same exhaustion inside the stdin/mainloop shape is non-fatal by design (an error event, exit 0), which is why this case must be one-shot. GRAFF_FLEET=on plus the workflow call makes the run carry a real orchestration decision, so exhaustedFatal's other half fires too - it files the score-0 exhausted:true orch_outcome row before dying (verified by hand in the workspace: kind:\"orch_outcome\" ... \"exhausted\":true,\"landed\":false). That row is NOT asserted: it is written as the process dies, after every scripted bash step could run, and the runner keeps no post-mortem surface - it becomes assertable when the trajectory_row extension lands.", "args": ["--max-model-calls", "2", "-p", "fix the failing checks in parser.py"], "env": {"GRAFF_FLEET": "on"}, "expected_exit": 1, "timeout_s": 90, "prompt": "fix the failing checks in parser.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read parser.py and locate the failing check"}]}]}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "never reached: the pool was dry two calls ago"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"stderr_contains": "model-call budget exhausted"}, {"stderr_contains": "(--max-model-calls 2)"}, {"stderr_contains": "Work done so far is PARTIAL and was NOT rolled back"}, {"stderr_contains": "raise --max-model-calls or re-run to continue"}]}{"id": "new-ask-retires-finished-checklist", "why": "#394: completed items from PRIOR asks piled up. The omitted-completed preserve rule (2896b32) is per-ASK, but the parking never expired: five unrelated goals in one session came back from todo_read as one 13-item [x] pile, and every new prompt inherited it. A checklist that is FULLY completed retires at the next user ask, so the second ask's list holds the second ask's work only - while an unfinished list still crosses the turn untouched (compaction-keeps-completed) and an omission inside one ask still preserves (todo-preserves-completed).", "args": [], "prompt": "rename the config flag", "second_prompt": "unrelated: draft the release notes", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "rename the flag in config.zig", "status": "completed"}]}}, {"text": "the flag is renamed"}, {"tool": "todo_write", "arguments": {"todos": [{"content": "draft the release notes", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "the release notes are drafted"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 1}}, {"request_contains": {"index": -1, "text": "[~] draft the release notes"}}, {"request_lacks": {"index": -1, "text": "[x] rename the flag in config.zig\\n[~] draft the release notes"}}, {"final_text_contains": "the release notes are drafted"}]}{"id": "btw-side-question-leaves-no-trace", "why": "#415: /btw must be answered from the LIVE context with NO tools and then vanish. The next turn's request is where the regression would show: a side question that reaches it has reached root.messages, which is the only way it could also reach the session file OR the append-only transcript (#441) - both are written from that same array.", "prompt": "build it", "controls_after_turn": [{"type": "btw", "text": "what did that linker error actually mean?"}], "second_prompt": "ok, carry on", "script": [{"text": "the link step failed with an undefined symbol"}, {"text": "SIDE-ONLY it means the entry point was renamed"}, {"text": "moving on"}], "assert": [{"event": {"type": "btw", "ok": true, "persisted": false}}, {"request_contains": {"index": 1, "text": "what did that linker error actually mean?"}}, {"request_contains": {"index": 1, "text": "the link step failed with an undefined symbol"}}, {"request_lacks": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "what did that linker error actually mean?"}}, {"request_lacks": {"index": -1, "text": "SIDE-ONLY"}}, {"request_contains": {"index": -1, "text": "the link step failed with an undefined symbol"}}]}-{"id": "peer-checkpoint-blocks-shared-tree-git", "why": "#469: with a live co-resident session in the same worktree, the FIRST index/tree-mutating git command must come back un-executed as a checkpoint naming the peer, and the identical re-issue must run. The regression is two graffs silently mutating one git index again.", "live_peer": true, "args": [], "prompt": "init a repo and stage everything", "script": [{"tool": "bash", "arguments": {"command": "git init -q"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"text": "staged, once the checkpoint told me about the peer session"}], "assert": [{"event": {"type": "tool_call_finished", "name": "bash", "is_error": false}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"request_contains": {"index": 2, "text": "shared-tree checkpoint (#469)"}}, {"request_contains": {"index": 2, "text": "another graff session already owns this worktree"}}]}+{"id": "peer-checkpoint-blocks-shared-tree-git", "why": "#469: with a live co-resident session in the same worktree, the FIRST index/tree-mutating git command must come back un-executed as a checkpoint naming the peer, and the identical re-issue must run. The regression is two graffs silently mutating one git index again.", "live_peer": true, "args": [], "prompt": "init a repo and stage everything", "script": [{"tool": "bash", "arguments": {"command": "git init -q"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"text": "staged, once the checkpoint told me about the peer session"}], "assert": [{"event": {"type": "tool_call_finished", "name": "bash", "is_error": false}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"request_contains": {"index": 2, "text": "shared-tree checkpoint"}}, {"request_contains": {"index": 2, "text": "another graff session already owns this worktree"}}]}{"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": "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"}}]}-{"id": "peer-checkpoint-blocks-file-writes", "why": "#469: the once-per-peer checkpoint must guard the files themselves, not only git - the incident's other vector was one session moving/editing files the other had open. A live peer makes the first write_file come back un-executed, and the identical retry lands.", "live_peer": true, "args": [], "prompt": "create notes.txt with hello in it", "script": [{"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"text": "created, after the checkpoint told me about the peer"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint (#469)"}}, {"request_contains": {"index": 1, "text": "another graff session already owns this worktree"}}]}-{"id": "peer-message-all-broadcasts-device-wide", "why": "#469: session 'all' must reach every live session on the device, not only same-folder peers. The regression is a broadcast silently scoped to one worktree.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "device-wide room"}}]}+{"id": "peer-checkpoint-blocks-file-writes", "why": "#469: the once-per-peer checkpoint must guard the files themselves, not only git - the incident's other vector was one session moving/editing files the other had open. A live peer makes the first write_file come back un-executed, and the identical retry lands.", "live_peer": true, "args": [], "prompt": "create notes.txt with hello in it", "script": [{"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"text": "created, after the checkpoint told me about the peer"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint"}}, {"request_contains": {"index": 1, "text": "another graff session already owns this worktree"}}]}+{"id": "peer-message-all-broadcasts-device-wide", "why": "#563: model \"all\" is retired — it flooded every folder. peer_message with session=all must error and tell the model to post bare or name one session. Device-wide broadcast stays the user's /tell all.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "\"all\" is retired"}}]}{"id": "peer-awareness-precedes-first-reply", "why": "#469: the model can only auto-decide to coordinate with sessions it knows about - with a live peer, the FIRST request must already carry the presence note (who else is live, with goals), before any collision forces the issue.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_contains": {"index": 0, "text": "other live graff session"}}, {"request_contains": {"index": 0, "text": "peer_message"}}]}{"id": "readonly-exact-key-prefers-one-search", "why": "Named-file guidance forced a whole-file read before an exact-key search, adding avoidable context and a provider round trip. A read-only keyed lookup should call read_file once with contains set to the exact key, answer from the numbered match, and never read the entire file.", "args": [], "workspace_seed": {"catalog.py": "SKU0001 = {'price': 100, 'stock': 1}\nSKU0002 = {'price': 200, 'stock': 2}\nSKU0420 = {'price': 31415, 'stock': 27}\nSKU0900 = {'price': 900, 'stock': 9}\n"}, "prompt": "Read catalog.py without editing it. Find SKU0420. Reply with exactly one line in the format SKU0420|price=<price>|stock=<stock> and nothing else.", "script": [{"tool": "read_file", "arguments": {"path": "catalog.py", "contains": "SKU0420"}}, {"text": "SKU0420|price=31415|stock=27"}], "assert": [{"request_contains": {"index": 0, "text": "contains set to the exact key"}}, {"event": {"type": "tool_call", "name": "read_file"}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 1}}, {"final_text_contains": "SKU0420|price=31415|stock=27"}]}diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex 1c93b863..92e2d3c4 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -17,6 +17,7 @@ const goal_flow = @import("goal_flow.zig");// branch could see the other, so the break only appeared at integration.const prompts = @import("prompts.zig");const handoff_note = @import("compact_handoff_note.zig"); // #411: both halves of "what survives a compaction"+const peer_context = @import("peer_context.zig"); // ADR 0004: peer injects are not a human turnconst compact_note_glue = @import("compact_note_glue.zig"); // #391const server_compact = @import("agent_server_compact.zig"); // #compact-ab telemetry@@ -140,10 +141,7 @@ pub fn compact(self: *Agent) anyerror!usize {// (WriteFailed) rather than returning a clean overflow, so compaction could// never run once near the cap. Old tool outputs are superseded by the summary// anyway; truncating them keeps the request sendable + all pairing intact.- // Build the summary request on a temporary deep copy of every JSON- // container. Pruning reasoning and truncating tool output must be- // transactional: if the summary call fails or returns empty, the live- // conversation remains byte-for-byte usable for the next attempt.+ // Summary construction is transactional: a failed/empty reply restores the live conversation.var compact_arena_state = std.heap.ArenaAllocator.init(self.gpa);defer compact_arena_state.deinit();const compact_arena = compact_arena_state.allocator();@@ -155,8 +153,10 @@ pub fn compact(self: *Agent) anyerror!usize {const recent_messages = live_messages.items[recent_start..];var summary_messages = std.json.Array.init(compact_arena);try summary_messages.ensureTotalCapacity(recent_start);- for (live_messages.items[0..recent_start]) |item|+ for (live_messages.items[0..recent_start]) |item| {+ if (peer_context.isPeerInject(item)) continue; // ADR 0004: do not ask the summarizer to hoard the roomtry summary_messages.append(try cloneJsonValue(compact_arena, item));+ }self.messages = summary_messages;var installed_summary = false;defer if (!installed_summary) {@@ -208,7 +208,7 @@ pub fn compact(self: *Agent) anyerror!usize {try fresh.append(try textMessage(self.arena, "user", try handoffMessage(self, summary, live_messages.items[0..recent_start])));// Preserve a valid recent suffix verbatim (up to ~8k estimated tokens),// including its user boundary and paired tool calls/results.- for (recent_messages) |message| try fresh.append(message);+ try peer_context.appendWorkingSet(&fresh, recent_messages, live_messages.items);self.messages = fresh;self.compact_summary_failures = 0; // #379: a usable summary ends the streakself.last_context_tokens = 0;@@ -335,7 +335,7 @@ pub fn cleanUserTurn(m: Value) bool {if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;const content = m.object.get("content") orelse return true;switch (content) {- .string => return true, // a plain-text user turn+ .string => |s| return !peer_context.isPeerInjectContent(s),.array => |arr| {// An anthropic user message that only carries tool_result blocks// is the response half of a tool call — it can't begin a@@ -364,7 +364,7 @@ pub fn dropPriorTurnReasoning(self: *Agent) usize {for (self.messages.items, 0..) |m, i| {if (m != .object) continue;const role = m.object.get("role") orelse continue;- if (role == .string and std.mem.eql(u8, role.string, "user")) last_user = i;+ if (role == .string and std.mem.eql(u8, role.string, "user") and !peer_context.isPeerInject(m)) last_user = i;}var w: usize = 0;for (self.messages.items, 0..) |m, i| {diff --git a/src/compact_handoff_note.zig b/src/compact_handoff_note.zigindex 436653b4..115a92d8 100644--- a/src/compact_handoff_note.zig+++ b/src/compact_handoff_note.zig@@ -48,6 +48,7 @@ const Agent = agent_mod.Agent;const compact_instruction = @import("prompts.zig").compact_instruction;const session_transcript = @import("session_transcript.zig");const tool_spill = @import("tool_spill.zig");+const peer_context = @import("peer_context.zig");/// Most modified paths named before the list is elided. A compaction runs at/// the point context is scarce, so this block has to stay a note rather than@@ -66,7 +67,9 @@ const persists_note =\\the command lines that worked, identifiers. Spend the words instead on what\\disk cannot give back - the decisions and why they were made, what was tried\\and failed, the constraints the user set, and the exact state of the- \\unfinished work.+ \\unfinished work. Peer-channel notes are a working set, not the conversation:+ \\do not transcribe [peer message] or [presence] lines; the harness drops them+ \\and restates who is still live after this summary (the room log stays on disk).;/// The user message compact() sends to ask for the handoff summary: the@@ -101,6 +104,7 @@ pub fn durableState(arena: Allocator, root: *Agent, discarded: []const Value) !?if (try fileLine(arena, root)) |line| try lines.append(arena, line);if (try handleLine(arena, discarded)) |line| try lines.append(arena, line);if (try transcriptLine(arena, root)) |line| try lines.append(arena, line);+ if (try peer_context.durableRosterLine(arena, root.io)) |line| try lines.append(arena, line);if (lines.items.len == 0) return null;return try std.fmt.allocPrint(arena,\\[durable state, re-derived by the harness at this compaction rather than@@ -230,6 +234,8 @@ test "the summary request says what persists and asks for names, not contents (#try testing.expect(std.mem.startsWith(u8, req, compact_instruction));try testing.expect(std.mem.indexOf(u8, req, "Record NAMES, not contents") != null);try testing.expect(std.mem.indexOf(u8, req, "restated to you in full") != null);+ try testing.expect(std.mem.indexOf(u8, req, "Peer-channel notes are a working set") != null);+ try testing.expect(std.mem.indexOf(u8, req, "do not transcribe [peer message]") != null);// The ground truth itself belongs on the FAR side of the summary, where the// model cannot summarize it away. It must not be in the request.try testing.expect(std.mem.indexOf(u8, req, "durable state, re-derived") == null);diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex 8fa3d309..b119274b 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -25,6 +25,7 @@ const presence = @import("presence.zig");const presence_chan = @import("presence_chan.zig");const worktree_lease = @import("worktree_lease.zig");const repl = @import("repl.zig");+const peer_context = @import("peer_context.zig");const Agent = agent_mod.Agent;const ToolCall = tools_mod.ToolCall;@@ -34,7 +35,7 @@ const Owner = worktree_lease.Owner;pub const tool_name = "peer_message";pub const tool_desc = "Post a message to the shared graff channel: live graff sessions hear it at their next step 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. Hearing is folder-scoped: bare posts go to this folder's room and every session in it hears them; `session` names one intended recipient (name substring, possibly in another folder) — a cross-folder post is delivered to the addressed session only, never broadcast. Device-wide broadcast is the user's /tell all, not this tool. 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 for this folder's room), \"all\" for every live session on this device, or a session name in another folder"}, "text": {"type": "string", "description": "one or two sentences of coordination intent"}}, "required": ["text"]}+ \\{"type": "object", "properties": {"session": {"type": "string", "description": "peer session name substring (omit for this folder's room). A name in another folder is a DM via the device room, delivered to that session only. Not \"all\" — device-wide broadcast is the user's /tell all"}, "text": {"type": "string", "description": "one or two sentences of coordination intent"}}, "required": ["text"]};/// Resolve the one peer a message is for. `want` is a session-name substring@@ -141,15 +142,16 @@ fn peerNoteIfChanged(root: *Agent) ?[]const u8 {if (peers.len == 0 and g_peer_fp == 0) return null;var buf: std.ArrayList(u8) = .empty;if (peers.len == 0) {- buf.appendSlice(root.arena, "[#469 presence] the other live graff sessions are gone — the shared tree is yours alone now.") catch return null;+ buf.appendSlice(root.arena, "[presence] the other live graff sessions are gone — the shared tree is yours alone now.") catch return null;} else {const mine = presence.ownIdentity();- buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, "[#469 presence] {d} other live graff session(s):", .{peers.len}) catch return null) catch return null;+ buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, "[presence] {d} other live graff session(s):", .{peers.len}) catch return null) catch return null;for (peers) |p| {const where: []const u8 = if (std.mem.eql(u8, p.identity, mine)) "this folder" else p.identity;- buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, " {s} (goal: {s}, {s});", .{ p.session_id, if (p.goal.len > 0) p.goal else "?", where }) catch break) catch break;+ const goal = peer_context.clip(if (p.goal.len > 0) p.goal else "?", 40);+ buf.appendSlice(root.arena, std.fmt.allocPrint(root.arena, " {s} ({s}, {s});", .{ p.session_id, goal, where }) catch break) catch break;}- buf.appendSlice(root.arena, " Coordinate with the peer_message tool before restructuring shared files — bare posts stay in this folder, \"all\" or a name in another folder reaches every session on this device.") catch {};+ buf.appendSlice(root.arena, " Coordinate with peer_message before touching shared files — bare post = this folder's room; name a session to address them.") catch {};}const text = buf.items;const fp = std.hash.Wyhash.hash(0, text);@@ -234,7 +236,7 @@ pub fn deliverInbound(root: *Agent) void {if (repl.g_debug) markers.append(root.arena, n) catch {};}if (omitted > 0) {- const marker = std.fmt.allocPrint(root.arena, "[#469 channel: {d} older message(s) predating this session omitted]", .{omitted}) catch "";+ const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} older message(s) predating this session omitted]", .{omitted}) catch "";if (marker.len > 0) {buf.appendSlice(root.arena, marker) catch {};buf.append(root.arena, '\n') catch {};@@ -242,7 +244,7 @@ pub fn deliverInbound(root: *Agent) void {}}if (skipped > 0) {- const marker = std.fmt.allocPrint(root.arena, "[#469 device room: {d} message(s) not addressed to this session skipped — folder-scoped hearing]", .{skipped}) catch "";+ const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} message(s) not addressed to this session skipped — folder-scoped hearing]", .{skipped}) catch "";if (marker.len > 0) {buf.appendSlice(root.arena, marker) catch {};buf.append(root.arena, '\n') catch {};@@ -250,23 +252,34 @@ pub fn deliverInbound(root: *Agent) void {}}var lines: std.ArrayList([]const u8) = .empty;+ const hist = peer_context.historyWindow(is_backlog_drain, local_msgs.len + device_msgs.len);+ if (hist.hidden > 0) {+ const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} backlog message(s) omitted from context — keeping last {d}]", .{ hist.hidden, peer_context.history_tail_max }) catch "";+ if (marker.len > 0) {+ buf.appendSlice(root.arena, marker) catch {};+ buf.append(root.arena, '\n') catch {};+ }+ }+ var line_i: usize = 0;for ([2][]const presence.Message{ local_msgs, device_msgs }, [2][]const u8{ "", " · device" }) |msgs, scope| {for (msgs) |m| {- const goal = if (m.from_goal.len > 0) std.fmt.allocPrint(root.arena, " (goal: {s})", .{m.from_goal}) catch "" else "";+ const goal = if (m.from_goal.len > 0) std.fmt.allocPrint(root.arena, " (goal: {s})", .{peer_context.clip(m.from_goal, 40)}) catch "" else "";// 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}{s} — #469 channel]: {s}", .{ m.from_session, goal, to, scope, m.text }) catch continue;- buf.appendSlice(root.arena, line) catch {};- buf.append(root.arena, '\n') catch {};+ const line = std.fmt.allocPrint(root.arena, "[peer message from {s}{s}{s}{s}]: {s}", .{ m.from_session, goal, to, scope, peer_context.clip(m.text, peer_context.line_clip) }) catch continue;+ if (line_i >= hist.start) {+ buf.appendSlice(root.arena, line) catch {};+ buf.append(root.arena, '\n') catch {};+ }lines.append(root.arena, line) catch {};+ line_i += 1;}}- // History gets every line (the model coordinates from it); the REPL prints- // only the tail of a first-drain backlog so a resume is not a wall of- // text. Live incremental drains render every line — those are new.+ // History gets the working-set tail (ADR 0004); the REPL prints only the+ // last backlog_repl_show of a first-drain so a resume is not a wall.if (window.hidden > 0) {- const marker = std.fmt.allocPrint(root.arena, "[#469 channel: {d} backlog message(s) delivered to context — showing last {d}]", .{ window.hidden, backlog_repl_show }) catch "";+ const marker = std.fmt.allocPrint(root.arena, "[peer channel: {d} backlog message(s) delivered to context — showing last {d}]", .{ window.hidden, backlog_repl_show }) catch "";if (marker.len > 0 and repl.g_debug) markers.append(root.arena, marker) catch {};}renderPeerBlock(sink, root.io, any_visible, markers.items, lines.items[window.start..]);@@ -274,7 +287,7 @@ pub fn deliverInbound(root: *Agent) void {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;+ obj.put(root.arena, "content", .{ .string = peer_context.capInject(buf.items) }) catch return;root.messages.append(.{ .object = obj }) catch {};}@@ -390,14 +403,17 @@ pub fn summarizeTranscript(arena: Allocator, text: []const u8) PeekSummary {fn firstText(obj: std.json.ObjectMap) ?[]const u8 {const content = obj.get("content") orelse return null;switch (content) {- .string => |s| return if (s.len > 0 and !std.mem.startsWith(u8, s, "[peer message")) s else null,+ .string => |s| return if (s.len > 0 and !peer_context.isPeerInjectContent(s)) s else null,.array => |arr| {for (arr.items) |blk| {if (blk != .object) continue;const t = blk.object.get("type") orelse continue;if (t == .string and std.mem.eql(u8, t.string, "text")) {if (blk.object.get("text")) |v| {- if (v == .string and v.string.len > 0) return v.string;+ if (v == .string and v.string.len > 0) {+ if (peer_context.isPeerInjectContent(v.string)) continue;+ return v.string;+ }}}}@@ -407,14 +423,6 @@ fn firstText(obj: std.json.ObjectMap) ?[]const u8 {}}-fn clip(text: []const u8, max: usize) []const u8 {- const t = std.mem.trim(u8, text, " \t\r\n");- return if (t.len <= max) t else t[0..max];-}--/// The transcript path for a peer: shared worktree means shared .graff;-/// cross-folder peers are reached through their recorded identity (a git dir-/// whose parent is the tree root, or the cwd realpath outside git).fn transcriptPath(arena: Allocator, peer: Owner) []const u8 {const mine = presence.ownIdentity();const base = if (std.mem.eql(u8, peer.identity, mine))@@ -465,8 +473,8 @@ pub fn peekCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Wrconst sum = summarizeTranscript(arena, window);const goal = if (peer.goal.len > 0) peer.goal else "?";try out.print("⚡ {s} · pid {d} · goal: {s}\n", .{ peer.session_id, peer.pid, goal });- if (sum.last_prompt.len > 0) try out.print(" last prompt: {s}\n", .{clip(sum.last_prompt, 120)});- if (sum.last_said.len > 0) try out.print(" last said: {s}\n", .{clip(sum.last_said, 120)});+ if (sum.last_prompt.len > 0) try out.print(" last prompt: {s}\n", .{peer_context.clip(sum.last_prompt, 120)});+ if (sum.last_said.len > 0) try out.print(" last said: {s}\n", .{peer_context.clip(sum.last_said, 120)});if (sum.last_tool.len > 0) try out.print(" last tool: {s}", .{sum.last_tool});if (sum.messages > 0)try out.print("{s}{d} transcript messages\n", .{ if (sum.last_tool.len > 0) " · " else " ", sum.messages })@@ -516,7 +524,7 @@ test "summarizeTranscript: last prompt, last words, last tool, from complete lin++ "\n" ++\\{"role":"assistant","content":[{"type":"text","text":"switched the query to display_name"}]}++ "\n" ++- \\{"role":"user","content":"[peer message from s-2 — #469 channel]: hold off"}+ \\{"role":"user","content":"[peer message from s-2]: hold off"}++ "\n" ++ "{\"role\":\"user\",\"content\":\"a torn last line";const sum = summarizeTranscript(arena, text);try std.testing.expectEqualStrings("refactor the digest job", sum.last_prompt); // peer-channel quotes are not the peer's doings@@ -570,11 +578,11 @@ test "renderPeerBlock: blank notices bracket the block; silence when nothing isdefer rec.deinit(std.testing.allocator);const vt: engine_sink.VTable = .{ .emit = recordNoticeText, .durable = false };const sink: engine_sink.EngineSink = .{ .ctx = &rec, .vt = &vt };- const markers = [_][]const u8{"[#469 presence] 1 other live session"};- const lines = [_][]const u8{ "[peer message from a — #469 channel]: one", "[peer message from b — #469 channel]: two" };+ const markers = [_][]const u8{"[presence] 1 other live session"};+ const lines = [_][]const u8{ "[peer message from a]: one", "[peer message from b]: two" };renderPeerBlock(sink, undefined, true, &markers, &lines);try std.testing.expectEqualDeep(&[_][]const u8{- "", "[#469 presence] 1 other live session", lines[0], lines[1], "",+ "", "[presence] 1 other live session", lines[0], lines[1], "",}, rec.items);// A history-only drain paints nothing — no stray blank pair.rec.clearRetainingCapacity();diff --git a/src/peer_context.zig b/src/peer_context.zignew file mode 100644index 00000000..7e47bf59--- /dev/null+++ b/src/peer_context.zig@@ -0,0 +1,220 @@+//! Peer speech in the model's history is a working set, not the conversation+//! (ADR 0004 / #563 slice F).+//!+//! The JSONL room in presence_chan.zig is the log. deliverInbound copies a+//! short tail into a user-role note so the model can coordinate *this step*.+//! Those notes are perishable: they are not a human turn, they must not fence+//! compaction or emergency trim, and compact drops every spent one (a later+//! turn already followed it) while keeping a trailing unreplied inject so a+//! compact between drain and reply cannot swallow inbound.+//!+//! Detection is prefix-based because that is how the inject is serialized+//! today. Slice C can replace the fake user role; until then every compact+//! and peek path has to agree on the same prefixes, including the #469-era+//! strings still sitting in resumed transcripts.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const Io = std.Io;++const presence = @import("presence.zig");++/// First-drain lines that actually ride every later request. The room still+/// keeps the rest; the REPL show-count (2) is a display cap, not this.+pub const history_tail_max: usize = 3;++/// Hard ceiling on one deliverInbound blob, so a long roster plus a few+/// clipped lines cannot become another uncapped tool output.+pub const inject_byte_cap: usize = 800;++/// Per-line clip inside that blob. The tool already asks for one or two+/// sentences; the receiver enforces it.+pub const line_clip: usize = 200;++pub fn isPeerInjectContent(s: []const u8) bool {+ const t = std.mem.trimStart(u8, s, " \t\r\n");+ if (std.mem.startsWith(u8, t, "[peer message")) return true;+ if (std.mem.startsWith(u8, t, "[presence]")) return true;+ if (std.mem.startsWith(u8, t, "[#469 presence]")) return true;+ if (std.mem.startsWith(u8, t, "[#469 channel")) return true;+ if (std.mem.startsWith(u8, t, "[#469 device room")) return true;+ if (std.mem.startsWith(u8, t, "[peer channel")) return true;+ return false;+}++pub fn isPeerInject(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;+ const content = m.object.get("content") orelse return false;+ switch (content) {+ .string => |s| return isPeerInjectContent(s),+ .array => |arr| {+ for (arr.items) |blk| {+ if (blk != .object) continue;+ const t = blk.object.get("type") orelse continue;+ if (!(t == .string and std.mem.eql(u8, t.string, "text"))) continue;+ if (blk.object.get("text")) |v| {+ if (v == .string and isPeerInjectContent(v.string)) return true;+ }+ }+ return false;+ },+ else => return false,+ }+}++pub fn clip(text: []const u8, max: usize) []const u8 {+ const t = std.mem.trim(u8, text, " \t\r\n");+ return if (t.len <= max) t else t[0..max];+}++pub fn capInject(text: []const u8) []const u8 {+ if (text.len <= inject_byte_cap) return text;+ const tail = text[text.len - inject_byte_cap ..];+ if (std.mem.indexOfScalar(u8, tail, '\n')) |nl| return tail[nl + 1 ..];+ return tail;+}++/// First-drain history window: same shape as the REPL display window, but+/// capped at `history_tail_max` so the model does not eat the whole room.+pub const TailWindow = struct { start: usize, hidden: usize };++pub fn historyWindow(is_backlog: bool, count: usize) TailWindow {+ if (!is_backlog or count <= history_tail_max) return .{ .start = 0, .hidden = 0 };+ return .{ .start = count - history_tail_max, .hidden = count - history_tail_max };+}++/// Copy `kept` into `dest`, dropping peer injects a later turn already+/// followed. If `kept` is empty (the whole history was summarized) and the+/// original tail is still an unreplied inject, keep that one — compact must+/// not eat inbound the model has not seen.+pub fn appendWorkingSet(dest: *std.json.Array, kept: []const Value, original: []const Value) !void {+ for (kept, 0..) |m, i| {+ if (isPeerInject(m) and i + 1 < kept.len) continue;+ try dest.append(m);+ }+ if (kept.len == 0 and original.len > 0) {+ const last = original[original.len - 1];+ if (isPeerInject(last)) try dest.append(last);+ }+}++/// One durable-state line naming who is live *now*. Speech stays in the+/// JSONL room; quoting it here would just survive compact as another leak.+pub fn durableRosterLine(arena: Allocator, io: Io) !?[]const u8 {+ const peers = presence.liveAllPeers(io, arena);+ if (peers.len == 0) return null;+ var buf: std.ArrayList(u8) = .empty;+ try buf.appendSlice(arena, "- live co-resident sessions (working set; speech is in the worktree channel, not this summary): ");+ for (peers, 0..) |p, i| {+ if (i > 0) try buf.appendSlice(arena, "; ");+ const goal = if (p.goal.len > 0) clip(p.goal, 40) else "?";+ const piece = try std.fmt.allocPrint(arena, "{s} ({s})", .{ p.session_id, goal });+ try buf.appendSlice(arena, piece);+ if (buf.items.len > 240) {+ try buf.appendSlice(arena, "; …");+ break;+ }+ }+ return buf.items;+}++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 "isPeerInjectContent: live prefixes and the #469-era strings in old transcripts" {+ try testing.expect(isPeerInjectContent("[peer message from s-2]: hold off"));+ try testing.expect(isPeerInjectContent(" [presence] 1 other live graff session(s)"));+ try testing.expect(isPeerInjectContent("[#469 presence] 1 other live graff session(s)"));+ try testing.expect(isPeerInjectContent("[#469 channel: 8 older message(s) predating this session omitted]"));+ try testing.expect(isPeerInjectContent("[peer channel: 8 older message(s) predating this session omitted]"));+ try testing.expect(isPeerInjectContent("[#469 device room: 2 message(s) not addressed to this session skipped]"));+ try testing.expect(!isPeerInjectContent("refactor the digest job"));+ try testing.expect(!isPeerInjectContent(""));+}++test "isPeerInject: user-role string or text block; assistant and tool_result are not" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try testing.expect(isPeerInject(try userText(a, "[peer message from a]: hold gui/src")));+ try testing.expect(!isPeerInject(try userText(a, "please finish the retry ladder")));+ try testing.expect(!isPeerInject(try asstText(a, "[peer message from a]: hold gui/src")));+ const block = try std.json.parseFromSliceLeaky(Value, a, "{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"[presence] 1 other live session\"}]}", .{});+ try testing.expect(isPeerInject(block));+ const tr = try std.json.parseFromSliceLeaky(Value, a, "{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"content\":\"ok\"}]}", .{});+ try testing.expect(!isPeerInject(tr));+}++test "historyWindow: live drains are uncapped; a first-drain backlog keeps only the tail" {+ try testing.expectEqualDeep(TailWindow{ .start = 0, .hidden = 0 }, historyWindow(false, 25));+ try testing.expectEqualDeep(TailWindow{ .start = 0, .hidden = 0 }, historyWindow(true, history_tail_max));+ try testing.expectEqualDeep(TailWindow{ .start = 7, .hidden = 7 }, historyWindow(true, 10));+}++test "appendWorkingSet: drops spent injects, keeps a trailing unreplied one, salvages when the suffix is empty" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const peer = try userText(a, "[peer message from a]: locking src/foo.zig");+ const human = try userText(a, "keep going");+ const asst = try asstText(a, "on it");+ const later = try userText(a, "[peer message from b]: your turn");++ var kept = std.json.Array.init(a);+ try kept.append(human);+ try kept.append(asst);+ try kept.append(peer);+ try kept.append(asst);+ try kept.append(later);+ var dest = std.json.Array.init(a);+ try appendWorkingSet(&dest, kept.items, kept.items);+ try testing.expectEqual(@as(usize, 4), dest.items.len); // spent `peer` dropped; trailing `later` kept+ try testing.expectEqualStrings("keep going", dest.items[0].object.get("content").?.string);+ try testing.expect(isPeerInject(dest.items[3]));++ dest = std.json.Array.init(a);+ var original = std.json.Array.init(a);+ try original.append(human);+ try original.append(later);+ try appendWorkingSet(&dest, &.{}, original.items);+ try testing.expectEqual(@as(usize, 1), dest.items.len);+ try testing.expect(isPeerInject(dest.items[0]));++ dest = std.json.Array.init(a);+ original = std.json.Array.init(a);+ try original.append(later);+ try original.append(human);+ try appendWorkingSet(&dest, &.{}, original.items);+ try testing.expectEqual(@as(usize, 0), dest.items.len); // last was the human; nothing to salvage+}++test "durableRosterLine: nothing live means no line (honesty rule)" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try testing.expectEqual(@as(?[]const u8, null), try durableRosterLine(a, testing.io));+}++test "capInject: the working-set blob cannot outgrow inject_byte_cap; overflow keeps the tail" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const pad = try a.alloc(u8, 2000);+ @memset(pad, 'x');+ const long = try std.fmt.allocPrint(a, "[peer message from a]: {s}\n[peer message from b]: newest\n", .{pad});+ const out = capInject(long);+ try testing.expect(out.len <= inject_byte_cap);+ try testing.expect(std.mem.indexOf(u8, out, "newest") != null);+}diff --git a/src/peer_context_compact_test.zig b/src/peer_context_compact_test.zignew file mode 100644index 00000000..717e9943--- /dev/null+++ b/src/peer_context_compact_test.zig@@ -0,0 +1,82 @@+//! Compact/trim boundaries for peer injects (ADR 0004). Lives beside+//! agent_compact_test.zig so that file stays under the 600-line ceiling.++const std = @import("std");+const util = @import("util.zig");+const Value = std.json.Value;+const textMessage = @import("messages.zig").textMessage;+const compact = @import("agent_compact.zig");++test "cleanUserTurn: a peer inject is not a human user turn" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[peer message from a]: hold gui/src")));+ try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[presence] 1 other live graff session(s)")));+ try std.testing.expect(!compact.cleanUserTurn(try textMessage(a, "user", "[#469 presence] leftover from a resumed transcript")));+ try std.testing.expect(compact.cleanUserTurn(try textMessage(a, "user", "keep going")));+}++test "emergencyCutIndex: a peer inject at the midpoint is not a conversation start" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var items = std.json.Array.init(a);+ try items.append(try textMessage(a, "user", "old")); // 0+ try items.append(try textMessage(a, "assistant", "x")); // 1+ try items.append(try textMessage(a, "user", "still old")); // 2+ try items.append(try textMessage(a, "assistant", "x")); // 3+ try items.append(try textMessage(a, "user", "[peer message from a]: hold gui/src")); // 4 midpoint — skip+ try items.append(try textMessage(a, "assistant", "x")); // 5+ try items.append(try textMessage(a, "user", "keep going")); // 6+ try items.append(try textMessage(a, "assistant", "x")); // 7+ try std.testing.expectEqual(@as(?usize, 6), compact.emergencyCutIndex(items.items));+}++test "recentContextStart: a peer inject is not a keep-verbatim boundary" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try textMessage(a, "user", "old request"));+ try msgs.append(try textMessage(a, "assistant", &util.repeatBytes("x", 36_000)));+ try msgs.append(try textMessage(a, "user", "[peer message from a]: hold gui/src"));+ try msgs.append(try textMessage(a, "assistant", "noted"));+ try msgs.append(try textMessage(a, "user", "recent request"));+ try msgs.append(try textMessage(a, "assistant", "recent answer"));+ const start = compact.recentContextStart(msgs.items, 8_000);+ try std.testing.expectEqual(@as(usize, 4), start);+ try std.testing.expectEqualStrings("recent request", msgs.items[start].object.get("content").?.string);+ try std.testing.expect(!compact.cleanUserTurn(msgs.items[2]));+}++test "dropPriorTurnReasoning: a peer inject is not the last-user fence" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const Agent = @import("agent.zig").Agent;+ var agent: Agent = undefined;+ agent.arena = a;+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 270_000 };+ var items = std.json.Array.init(a);+ try items.append(try textMessage(a, "user", "old prompt"));+ var old_r: std.json.ObjectMap = .empty;+ try old_r.put(a, "type", .{ .string = "reasoning" });+ try old_r.put(a, "encrypted", .{ .string = "old" });+ try items.append(.{ .object = old_r });+ try items.append(try textMessage(a, "assistant", "old"));+ try items.append(try textMessage(a, "user", "new prompt"));+ var new_r: std.json.ObjectMap = .empty;+ try new_r.put(a, "type", .{ .string = "reasoning" });+ try new_r.put(a, "encrypted", .{ .string = "new" });+ try items.append(.{ .object = new_r });+ try items.append(try textMessage(a, "assistant", "new"));+ try items.append(try textMessage(a, "user", "[peer message from a]: hold"));+ agent.messages = items;+ // Last real user is "new prompt". Only the older reasoning drops. If the+ // peer inject were the fence, both blobs would go — the API still needs+ // the current turn's reasoning between a function_call and its output.+ const dropped = compact.dropPriorTurnReasoning(&agent);+ try std.testing.expectEqual(@as(usize, 1), dropped);+ try std.testing.expectEqual(@as(usize, 6), agent.messages.items.len);+}diff --git a/src/presence.zig b/src/presence.zigindex 21533dd2..c51791bf 100644--- a/src/presence.zig+++ b/src/presence.zig@@ -337,7 +337,7 @@ pub fn gateCheck(io: Io, arena: Allocator) ?[]const u8 {g_acked_len += 1;}const warning = worktree_lease.duplicateOwnerWarning(arena, peer, unixMs(io) - peer.last_seen_ms);- return std.fmt.allocPrint(arena, "{s}shared-tree checkpoint (#469): the action was NOT performed. Re-issue the identical call to proceed — this fires once per live peer, across git mutations, file writes, and shell moves alike — coordinate first via the peer_message tool (session \"{s}\"), or keep your edits disjoint from theirs.", .{ warning, peer.session_id }) catch warning;+ return std.fmt.allocPrint(arena, "{s}shared-tree checkpoint: the action was NOT performed. Re-issue the identical call to proceed — this fires once per live peer, across git mutations, file writes, and shell moves alike — coordinate first via the peer_message tool (session \"{s}\"), or keep your edits disjoint from theirs.", .{ warning, peer.session_id }) catch warning;}// The channel's wire format (Message, chanName, postMessage, readNewMessages)diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 710913e0..58dc96c3 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -122,6 +122,8 @@ const playbook_reflect = @import("playbook_reflect.zig");// the same way, so neither pulls its tests in without these.const compact_note = @import("compact_note.zig");const compact_note_glue = @import("compact_note_glue.zig");+const peer_context = @import("peer_context.zig"); // ADR 0004 / #563 slice F+const peer_context_compact_test = @import("peer_context_compact_test.zig");// #345: the global-vs-project MCP config merge. mcp.zig does reference its// decls, but the hook makes the coverage explicit rather than contingent on@@ -249,6 +251,8 @@ test {_ = playbook_reflect;_ = compact_note;_ = compact_note_glue;+ _ = peer_context;+ _ = peer_context_compact_test;_ = shutdown_trace;_ = credential_store;_ = engine_events;