graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
presence + peer channel: co-resident graffs see, warn, checkpoint, and message each other (#469)
Rach Pradhan6e60e5cbb1f1
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex bf9464bb..9a27c68e 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -43,3 +43,5 @@{"id": "session-recap-precedes-turn", "why": "#419: every cleanly completed turn must emit a heuristic session_recap before the terminal turn event, so stream-until-turn clients (the GUI agent overview) always learn the session's one-line state and status.", "prompt": "say hi", "script": [{"text": "hello there"}], "assert": [{"event": {"type": "session_recap", "status": "completed", "source": "heuristic", "text": "hello there"}}, {"event": {"type": "turn", "complete": true}}]}{"id": "session-recap-needs-input-heuristic", "why": "#419: a turn that ends on a question reads as needs_input without any model call - the heuristic degrade path the issue asks for when no cheap model is available.", "prompt": "what do you need", "script": [{"text": "Which file should I change?"}], "assert": [{"event": {"type": "session_recap", "status": "needs_input", "source": "heuristic"}}]}{"id": "session-recap-model-silent-without-cheap-rung", "why": "#419: the cheap-model recap is silently disabled when the provider has no ladder rung (lmstudio in the mock rig) - no event, no error, the heuristic recap still lands.", "prompt": "say hi", "script": [{"text": "hi"}], "controls_after_turn": [{"type": "set_mode", "mode": "normal"}], "assert": [{"event": {"type": "session_recap", "source": "heuristic"}}, {"no_event": {"type": "session_recap", "source": "model"}}]}+{"id": "peer-message-queued-for-live-peer", "why": "#469 phase 2: a session must be able to message a live co-resident peer (the channel half of the crosstalk fix). The regression is peer_message erroring while a peer is genuinely live, or claiming delivery it did not make.", "live_peer": true, "args": [], "prompt": "tell the other session to hold off gui/src until you land the move", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src until I land the move"}}, {"text": "told them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "queued for"}}]}+{"id": "peer-message-without-peer-errors-clean", "why": "#469 phase 2: with no live peer, peer_message must come back as a clean error that says so - never a fake delivery, never a crash. The regression is a send reported into the void.", "args": [], "prompt": "tell the other session to hold off", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src"}}, {"text": "nobody to tell"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "[error] no live co-resident"}}]}diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.pyindex dc363437..bc6fccb8 100644--- a/scripts/eval-tier2.py+++ b/scripts/eval-tier2.py@@ -116,6 +116,7 @@ def execute(case: dict[str, Any], graff: str, port: int,provider: str | None, model: str | None) -> Run:scripted = ScriptedModel(case.get("script", []))bound = 0 if provider else scripted.start(port)+ peer = Nonetry:with tempfile.TemporaryDirectory(prefix="graff-tier2-") as workspace:env = {@@ -141,6 +142,23 @@ def execute(case: dict[str, Any], graff: str, port: int,dest = pathlib.Path(workspace) / reldest.parent.mkdir(parents=True, exist_ok=True)dest.write_text(content, encoding="utf-8")+ # A genuinely live second graff in the same workspace, for #469+ # presence cases: the checkpoint only exists while a co-resident+ # session does, and a real peer announces (and probes) better than+ # any fixture — a forged record can never carry a live start-id.+ if case.get("live_peer"):+ peer = subprocess.Popen(+ [graff, "--json", "--yolo", "--model", model or "lmstudio"],+ cwd=workspace, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)+ live_dir = pathlib.Path(workspace) / ".graff" / "live"+ deadline = time.time() + 30+ while time.time() < deadline:+ if live_dir.is_dir() and any(live_dir.glob("*.json")):+ break+ if peer.poll() is not None:+ break+ time.sleep(0.1)argv = [graff, "--json", "--yolo", "--model", model or "lmstudio"]if provider:argv += ["--subagent-provider", provider]@@ -174,6 +192,8 @@ def execute(case: dict[str, Any], graff: str, port: int,passreturn Run(events, list(scripted.requests), stderr, code)finally:+ if peer is not None:+ peer.kill()if bound:scripted.stop()# The port is fixed, so let the socket clear before the next case.diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 89c9c239..0e3d56cd 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex c08cc7d9..a86fdb66 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";export const HARNESS_VERSION = "0.11";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -433,4 +433,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"];diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex 4e587f86..3dc8d5bb 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.11";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -324,4 +324,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"];diff --git a/src/agent.zig b/src/agent.zigindex 02db444e..ab779c99 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -33,6 +33,7 @@ const run_budget_mod = @import("run_budget.zig");const prompt_ui = @import("agent_prompt.zig");const agent_tests = @import("agent_tests.zig");const goal_state = @import("goal_state.zig");+const peer_channel = @import("peer_channel.zig"); // #469: turn-boundary peer message deliverypub const TodoItem = struct {content: []const u8,@@ -314,6 +315,9 @@ pub const Agent = struct {try self.ensureRootTools(self.provider.kind);// No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.self.completed = null;+ // #469: co-resident sessions' queued messages land at the turn boundary+ // — durable in history, visible as events, never mid-turn.+ peer_channel.deliverInbound(self);if (!self.sub) esc_cancel.store(false, .release); // fresh turn, no stale cancelwhile (true) {// Esc during a tool join (set by escWatchTask) lands here: thediff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 7e24a590..043bd2af 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -17,6 +17,7 @@ const companionReadOnly = skills.companionReadOnly;const fleet = @import("fleet.zig");const telemetry = @import("telemetry.zig");const learning_privacy = @import("learning_privacy.zig");+const presence = @import("presence.zig");const TemplateCandidates = struct {items: [16][]const u8 = undefined,@@ -167,6 +168,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {if (std.mem.eql(u8, call.name, "learn_candidate") orstd.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") orstd.mem.eql(u8, call.name, "imagegen") or // #352: writes a file and spawns a workspace-write child+ std.mem.eql(u8, call.name, "peer_message") or // #469: appends to a peer's inbox — a side effect(mcp.Registry.isMcp(call.name) and !companionReadOnly(call.name, call.input))) return .{.text = try self.arena.dupe(u8, "plan mode is on — read-only. Fold this change into the plan you present; the user applies it after approving (/plan toggles the mode off)."),.is_error = true,@@ -212,6 +214,16 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {const cmd_val = args.get("command") orelse return null;if (cmd_val != .string) return null;const cmd = std.mem.trim(u8, cmd_val.string, " \t");+ // #469: one deliberate checkpoint per live co-owner before this session+ // touches the shared index/tree — fires under --yolo too, where no+ // approvals prompt would ever surface the collision. The model sees+ // the peer's identity + goal and re-issues the command to proceed.+ if (presence.isSharedTreeGit(cmd)) {+ if (presence.gateCheck(self.io, self.arena)) |checkpoint| return .{+ .text = checkpoint,+ .is_error = true,+ };+ }const destructive_git = Approvals.isDestructiveGit(cmd);const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);if (gate_ok and approvals.allowed(self.io, cmd)) return null;diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex ba5ccc2d..e34ba9e7 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -36,6 +36,7 @@ const isMetaName = schema.isMetaName;const eval_control = @import("agent_eval_control.zig");const goal_state = @import("goal_state.zig");const goal_todo = @import("goal_todo.zig"); // todo_write's replace path + the omitted-completed preserve rule+const peer_channel = @import("peer_channel.zig"); // #469: peer_message's handlerpub const toolInvalidatesEval = eval_control.toolInvalidatesEval;pub const gateTool = @import("agent_tool_gate.zig").gateTool;pub const firstWord = @import("agent_tool_gate.zig").firstWord;@@ -291,6 +292,8 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]const/// Handle a meta tool inline on the agent's own thread.pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {+ // #469: sideways coordination between co-resident root sessions.+ if (std.mem.eql(u8, call.name, peer_channel.tool_name)) return peer_channel.handleMessage(self, call);if (std.mem.eql(u8, call.name, "attempt_completion")) {if (!self.review_mode and self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {const message = if (self.eval_repair_pending)diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 59edc5c3..db3843cc 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -30,6 +30,7 @@ pub const commands = [_]Item{.{ .name = "/loop", .usage = "/loop [30m] <prompt>", .desc = "the same autonomous run as /goal, without adopting a standing objective" },.{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },.{ .name = "/never", .usage = "/never [<text>|rm <id>]", .desc = "standing constraints that ride every subagent brief and survive compaction; bare lists them, rm <id> retires one (alias /constraint)" },+ .{ .name = "/tell", .usage = "/tell <session> <text>", .desc = "message a live co-resident graff session in this folder; /sessions lists who's around" },.{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },.{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },.{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 7cbfa380..2b424e26 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -43,6 +43,7 @@ const kimi_catalog = @import("kimi_catalog.zig");const providers = @import("providers.zig");const command_catalog = @import("command_catalog.zig");const side_question = @import("side_question.zig"); // #415 /btw+const peer_channel = @import("peer_channel.zig"); // #469 /tell + the /sessions "live now" sectionconst serde = @import("serde.zig");const mcp_cli = @import("mcp_cli.zig");@@ -529,6 +530,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}+ if (std.mem.startsWith(u8, line, "/tell") and (line.len == 5 or line[5] == ' ' or line[5] == '\t')) return peer_channel.tellCommand(root, arena, line, out); // #469if (std.mem.eql(u8, line, "/sessions")) {var entries = listSavedSessions(root, arena);defer entries.deinit(arena);@@ -542,6 +544,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,}}if (entries.items.len == 0) try out.writeAll("(no saved sessions in cwd)\n");+ try peer_channel.writeLiveSection(root, arena, out); // #469: co-resident live sessions, with goalstry out.flush();return true;}diff --git a/src/goal_flow.zig b/src/goal_flow.zigindex a970ea81..80da0102 100644--- a/src/goal_flow.zig+++ b/src/goal_flow.zig@@ -10,6 +10,7 @@ const Allocator = std.mem.Allocator;const agent_mod = @import("agent.zig");const goal_state = @import("goal_state.zig");const repl_glue = @import("repl_glue.zig");+const presence = @import("presence.zig");const utf8Prefix = @import("util.zig").utf8Prefix;const Agent = agent_mod.Agent;const TodoItem = agent_mod.TodoItem;@@ -55,6 +56,7 @@ pub fn reapplyFlagGoal(arena: Allocator, root: *Agent, objective: []const u8, no}const displaced: ?agent_mod.Goal = if (root.goal) |old| (if (old.status == .complete) null else old) else null;root.goal = standingGoalFromFlag(objective, root.goal, root.todos.items, now_ms);+ presence.noteGoal(root.io, root.gpa, root.arena, objective); // #469: co-resident sessions read our goal off the presence recordroot.goal_note_fp = 0; // re-state the (now standing) note on the next turngoal_state.resetCompletionGate(root); // a new objective is fresh evidence for the double-checkif (displaced) |old| {@@ -148,6 +150,7 @@ pub fn applyGoalSet(root: *Agent, objective: []const u8, now_ms: i64) GoalSetResgoal_state.adoptTodos(root.todos.items, goal_state.currentEpoch(root.goal), epoch);const parked_open = goal_state.parkedOpenCount(root.todos.items, epoch);root.goal = .{ .objective = objective, .status = .active, .epoch = epoch, .created_ms = now_ms, .updated_ms = now_ms };+ presence.noteGoal(root.io, root.gpa, root.arena, objective); // #469: keep the presence record's goal current for peersroot.goal_note_fp = 0; // re-state the note on the next turn, not a stale-suppressed repeatgoal_state.resetCompletionGate(root); // a new objective is new evidence for the completion double-checkreturn .{ .superseded = superseded, .parked_open = parked_open };diff --git a/src/peer_channel.zig b/src/peer_channel.zignew file mode 100644index 00000000..e4c5b0a3--- /dev/null+++ b/src/peer_channel.zig@@ -0,0 +1,168 @@+//! The #469 channel half: what co-resident root sessions SAY to each other,+//! on top of what presence.zig knows (WHO is out there, liveness-probed).+//!+//! Four surfaces, one inbox primitive:+//! - peer_message: the model-facing tool, so a session can coordinate the+//! way a parent steers a subagent — "I'm restructuring gui/src, hold" —+//! except sideways, between roots. Queued, one-way, never synchronous.+//! - /tell <session> <text>: the user's own line into a peer's inbox.+//! - /sessions: the saved-session list gains a "live now" section.+//! - deliverInbound: drains our inbox at the turn boundary (agent.runTurn)+//! so a peer's message lands in context as a first-class note — durable in+//! history, visible to the user as an event, never mid-turn (#430's+//! input-inversion path can move it mid-turn later).++const std = @import("std");++const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const tools_mod = @import("tools.zig");+const engine_sink = @import("engine_sink.zig");+const presence = @import("presence.zig");+const worktree_lease = @import("worktree_lease.zig");++const Agent = agent_mod.Agent;+const ToolCall = tools_mod.ToolCall;+const ExecResult = tools_mod.ExecResult;+const Owner = worktree_lease.Owner;++pub const tool_name = "peer_message";+pub const tool_desc = "Send a message to another live graff session working in this same folder (a co-resident peer you learned about from the startup co-owner warning or a shared-tree checkpoint). The message lands in their context at their next turn boundary, stamped with your session name and current goal. Use it to coordinate the way you would steer a subagent, but sideways: announce what you are restructuring, ask them to hold off a directory, or split the work. `session` selects the peer by name substring; omit it when exactly one peer is live. Delivery is queued and one-way — the tool result only confirms the send, never a reply.";+pub const tool_schema =+ \\{"type": "object", "properties": {"session": {"type": "string", "description": "peer session name substring (omit when only one peer is live)"}, "text": {"type": "string", "description": "one or two sentences of coordination intent"}}, "required": ["text"]}+;++/// Resolve the one peer a message is for. `want` is a session-name substring+/// or a decimal pid; empty wants exactly one live peer.+fn resolvePeer(peers: []const Owner, want: []const u8) union(enum) { one: Owner, none, ambiguous } {+ if (want.len == 0) return if (peers.len == 1) .{ .one = peers[0] } else if (peers.len == 0) .none else .ambiguous;+ var found: ?Owner = null;+ var count: usize = 0;+ for (peers) |p| {+ const pid_match = std.fmt.parseInt(i32, want, 10) catch null;+ const named = std.mem.indexOf(u8, p.session_id, want) != null;+ if (named or (pid_match != null and pid_match.? == p.pid)) {+ found = p;+ count += 1;+ }+ }+ if (count == 1) return .{ .one = found.? };+ return if (count == 0) .none else .ambiguous;+}++fn peerListText(arena: Allocator, peers: []const Owner) []const u8 {+ var buf: std.ArrayList(u8) = .empty;+ for (peers) |p| {+ const line = std.fmt.allocPrint(arena, "\"{s}\" (pid {d}, goal: {s})", .{ p.session_id, p.pid, if (p.goal.len > 0) p.goal else "?" }) catch continue;+ buf.appendSlice(arena, line) catch {};+ buf.appendSlice(arena, ", ") catch {};+ }+ const items = buf.items;+ return if (items.len >= 2) items[0 .. items.len - 2] else items;+}++pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {+ const obj = tools_mod.json_args.object(call.input) orelse return .{+ .text = "peer_message needs an object input with a text field",+ .is_error = true,+ };+ const text = tools_mod.json_args.str(obj, "text") orelse "";+ if (text.len == 0) return .{ .text = "peer_message: empty text — say what you want the peer to know", .is_error = true };+ const want = tools_mod.json_args.str(obj, "session") orelse "";+ const peers = presence.liveTreePeers(self.io, self.arena);+ if (peers.len == 0) return .{+ .text = "no live co-resident graff sessions in this worktree — the presence registry says you are alone here (a peer shows up via the startup warning when one starts)",+ .is_error = true,+ };+ const target = switch (resolvePeer(peers, want)) {+ .one => |p| p,+ .none => return .{+ .text = try std.fmt.allocPrint(self.arena, "no live peer matches \"{s}\" — live now: {s}", .{ want, peerListText(self.arena, peers) }),+ .is_error = true,+ },+ .ambiguous => return .{+ .text = try std.fmt.allocPrint(self.arena, "more than one live peer — name one with `session`: {s}", .{peerListText(self.arena, peers)}),+ .is_error = true,+ },+ };+ if (!presence.postTo(self.io, self.arena, target, text)) return .{+ .text = "delivery failed — the presence registry is unavailable (this session may never have announced itself)",+ .is_error = true,+ };+ return .{+ .text = try std.fmt.allocPrint(self.arena, "queued for \"{s}\" (pid {d}) — it lands at their next turn boundary. Delivery is one-way: their answer, if any, arrives the same way.", .{ target.session_id, target.pid }),+ .is_error = false,+ };+}++/// The receiving half, called once at the top of a root agent's turn: every+/// queued peer message becomes one durable user-role note in history plus a+/// user-visible event. Never fails a turn — delivery trouble is silence, not+/// an error, because a peer's inbox must never break our session.+pub fn deliverInbound(root: *Agent) void {+ if (root.sub) return;+ const msgs = presence.drainInbox(root.io, root.arena);+ if (msgs.len == 0) return;+ const sink = engine_sink.forAgent(root);+ var buf: std.ArrayList(u8) = .empty;+ for (msgs) |m| {+ const goal = if (m.from_goal.len > 0) std.fmt.allocPrint(root.arena, " (goal: {s})", .{m.from_goal}) catch "" else "";+ const line = std.fmt.allocPrint(root.arena, "[peer message from {s}{s} — #469 channel]: {s}", .{ m.from_session, goal, m.text }) catch continue;+ buf.appendSlice(root.arena, line) catch {};+ buf.append(root.arena, '\n') catch {};+ sink.emit(root.io, .{ .session_notice = .{ .text = line, .tone = .plain } });+ }+ if (buf.items.len == 0) return;+ buf.appendSlice(root.arena, "(reply with the peer_message tool — queued, one-way)") catch {};+ var obj: std.json.ObjectMap = .empty;+ obj.put(root.arena, "role", .{ .string = "user" }) catch return;+ obj.put(root.arena, "content", .{ .string = buf.items }) catch return;+ root.messages.append(.{ .object = obj }) catch {};+}++/// /tell <session> <text…>: the user's line into a peer's inbox.+pub fn tellCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ const rest = std.mem.trim(u8, line["/tell".len..], " \t");+ const peers = presence.liveTreePeers(root.io, arena);+ const split = std.mem.indexOfAny(u8, rest, " \t");+ const target = if (split) |i| rest[0..i] else "";+ const text = if (split) |i| std.mem.trim(u8, rest[i + 1 ..], " \t") else "";+ if (target.len == 0 or text.len == 0) {+ try out.writeAll("usage: /tell <session> <text> — message a live co-resident graff session\n");+ if (peers.len == 0) try out.writeAll(" (no live peers in this worktree right now)\n") else try out.print(" live now: {s}\n", .{peerListText(arena, peers)});+ try out.flush();+ return true;+ }+ const peer = switch (resolvePeer(peers, target)) {+ .one => |p| p,+ .none => {+ try out.print("no live peer matches \"{s}\"\n", .{target});+ try out.flush();+ return true;+ },+ .ambiguous => {+ try out.print("more than one live peer matches — live now: {s}\n", .{peerListText(arena, peers)});+ try out.flush();+ return true;+ },+ };+ if (presence.postTo(root.io, arena, peer, text))+ try out.print("⇢ queued for {s} (pid {d}) — lands at their next turn boundary\n", .{ peer.session_id, peer.pid })+ else+ try out.writeAll("delivery failed — presence registry unavailable\n");+ try out.flush();+ return true;+}++/// The "live now" section /sessions appends under the saved-session list.+pub fn writeLiveSection(root: *Agent, arena: Allocator, out: *Io.Writer) !void {+ const peers = presence.liveTreePeers(root.io, arena);+ if (peers.len == 0) return;+ try out.writeAll(" live now in this worktree:\n");+ for (peers) |p| {+ const goal = if (p.goal.len > 0) p.goal else "?";+ try out.print(" ⚡ {s} · pid {d} · goal: {s}\n", .{ p.session_id, p.pid, goal });+ }+}diff --git a/src/presence.zig b/src/presence.zignew file mode 100644index 00000000..577a04a1--- /dev/null+++ b/src/presence.zig@@ -0,0 +1,569 @@+//! Cross-session presence registry (#469): the disk + lifecycle half that+//! worktree_lease.zig's pure #320 logic never got wired to. Every root session+//! writes a small owner record (pid + start identity + worktree identity ++//! current goal) into the per-user registry at birth and removes it at exit.+//! Liveness is PROBED via proc_identity (#413), never trusted from the file,+//! so a crashed session's record reaps itself on the next read — no heartbeat+//! thread, no reaper daemon.+//!+//! Adherence is structural, not prompt-level:+//! - announce/retire/goal updates are wired into session_run + goal_flow, so+//! a session cannot forget to register;+//! - agent_tool_gate refuses the FIRST index/worktree-mutating git command+//! issued while a live foreign session co-owns this worktree — under+//! --yolo too, where no approvals prompt exists — until the command is+//! re-issued. That re-issue is the deliberate acknowledgment the #469+//! incident (two --yolo sessions, one staging renames under the other)+//! never had a chance to make.+//!+//! No locking, no arbitration (#469 v1 non-goals): the registry carries+//! presence + intent; humans and agents still serialize the work.++const std = @import("std");+const builtin = @import("builtin");++const Io = std.Io;+const Allocator = std.mem.Allocator;++const proc_identity = @import("proc_identity.zig");+const worktree_lease = @import("worktree_lease.zig");+const util = @import("util.zig");++const unixMs = util.unixMs;++const Owner = worktree_lease.Owner;++/// 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 on-disk shape. Older/newer graffs tolerate each other via+/// ignore_unknown_fields both ways (a superset write parses down fine).+const RecordJson = struct {+ pid: i32 = 0,+ start_id: u64 = 0,+ session_id: []const u8 = "",+ identity: []const u8 = "",+ goal: []const u8 = "",+ last_seen_ms: i64 = 0,+};++pub fn formatRecord(arena: Allocator, owner: Owner) ![]const u8 {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(RecordJson{+ .pid = owner.pid,+ .start_id = owner.start_id,+ .session_id = owner.session_id,+ .identity = owner.identity,+ .goal = owner.goal,+ .last_seen_ms = owner.last_seen_ms,+ });+ return aw.writer.buffered();+}++pub fn parseRecord(arena: Allocator, text: []const u8) ?Owner {+ const rec = std.json.parseFromSliceLeaky(RecordJson, arena, text, .{ .ignore_unknown_fields = true }) catch return null;+ if (rec.pid == 0) return null;+ return .{+ .pid = rec.pid,+ .start_id = rec.start_id,+ .session_id = rec.session_id,+ .identity = rec.identity,+ .goal = rec.goal,+ .last_seen_ms = rec.last_seen_ms,+ };+}++/// A directory listing's worth of records with each pid's OS probe aligned —+/// the exact pair duplicateOwner/ownerVerdict consume.+pub const Peers = struct {+ records: []const Owner,+ probes: []const proc_identity.Probe,+};++/// Read every record in `dir`, probe each pid, reap the provably dead, and+/// return the survivors. Best-effort throughout: an unreadable registry means+/// "no peers", never an error propagated into a tool call.+pub fn listPeers(io: Io, arena: Allocator, dir: Io.Dir) Peers {+ var records: std.ArrayList(Owner) = .empty;+ var probes: std.ArrayList(proc_identity.Probe) = .empty;+ var d = dir;+ var it = d.iterate();+ while (it.next(io) catch null) |entry| {+ if (entry.kind != .file) continue;+ if (!std.mem.endsWith(u8, entry.name, ".json")) continue;+ if (records.items.len >= max_peers) break;+ const text = d.readFileAlloc(io, entry.name, arena, .limited(record_max)) catch continue;+ const rec = parseRecord(arena, text) orelse continue;+ const live = proc_identity.probe(io, rec.pid);+ if (live == .gone) {+ // Provably dead (#413): reap on read so the registry self-cleans+ // even when the owner crashed without retire().+ d.deleteFile(io, entry.name) catch {};+ continue;+ }+ records.append(arena, rec) catch break;+ probes.append(arena, live) catch break;+ }+ return .{ .records = records.items, .probes = probes.items };+}++/// One stable key per (pid, start identity) — what a checkpoint acknowledgment+/// is remembered by. Start identity, not pid alone: a reused pid must read as+/// a NEW peer, not an already-acked one (#320's whole point).+pub fn ackKey(rec: Owner) u64 {+ var buf: [32]u8 = undefined;+ const text = std.fmt.bufPrint(&buf, "{d}:{d}", .{ rec.pid, rec.start_id }) catch unreachable;+ return std.hash.Wyhash.hash(0, text);+}++/// The first live foreign co-owner of `my_identity` that has not been+/// acknowledged yet, if any. Pure: the probe results and the ack set are the+/// caller's, so tests need no processes and no filesystem.+pub fn unackedPeer(peers: Peers, my_identity: []const u8, my_pid: i32, acked: []const u64) ?Owner {+ for (peers.records, 0..) |rec, i| {+ if (i >= peers.probes.len) break;+ switch (worktree_lease.ownerVerdict(rec, my_identity, my_pid, peers.probes[i])) {+ .live_foreign, .live_unverified => {+ const key = ackKey(rec);+ var seen = false;+ for (acked) |k| {+ if (k == key) {+ seen = true;+ break;+ }+ }+ if (!seen) return rec;+ },+ else => {},+ }+ }+ return null;+}++// --- wired layer: one root session per process, so module state is the+// registry handle. announce is the ONLY writer of this state; retire/noteGoal/+// gateCheck no-op when it never ran (tests, subagents, homeless runs). ---++var g_dir: ?[]const u8 = null; // gpa-owned registry dir path+var g_identity: []const u8 = ""; // gpa-owned own worktree identity+var g_own_name: ?[]const u8 = null; // gpa-owned own record's file name+var g_session: []const u8 = ""; // gpa-owned session id, for rewrites+var g_goal: []const u8 = ""; // last-known goal (session-arena-owned is fine: both outlive the session)+var g_self: proc_identity.Record = .{}; // own pid + start-id, settled by announce+var g_inbox_off: u64 = 0; // bytes of our own inbox already delivered+var g_acked: [max_peers]u64 = undefined;+var g_acked_len: usize = 0;++fn writeOwn(io: Io, arena: Allocator) void {+ const dir_path = g_dir orelse return;+ const name = g_own_name orelse return;+ var owner = worktree_lease.selfOwner(io, g_identity, g_session, unixMs(io));+ owner.goal = g_goal;+ const text = formatRecord(arena, owner) catch return;+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return;+ defer dir.close(io);+ dir.writeFile(io, .{ .sub_path = name, .data = text }) catch {};+}++/// Register this root session and report any LIVE co-owner already present —+/// the #469 "see each other before, not mid-collision" moment. Returns an+/// arena-owned warning for the caller to surface (null = alone, or registry+/// unavailable). Never fails a session: every failure mode degrades to+/// silence, because presence must never be the reason graff did not start.+pub fn announce(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, session_id: []const u8, goal: []const u8) ?[]const u8 {+ if (builtin.is_test) return null; // tests get the parameterized store, never the real registry+ if (home.len == 0) return null;+ const dir_path = std.fmt.allocPrint(gpa, "{s}/{s}", .{ home, registry_subdir }) catch return null;+ Io.Dir.cwd().createDirPath(io, dir_path) catch return null;+ const identity = worktree_lease.currentIdentity(gpa, io, arena);+ if (identity.id.len == 0) return null;+ const self = proc_identity.selfRecord(io);+ var name_buf: [64]u8 = undefined;+ const name = std.fmt.bufPrint(&name_buf, "{d}-{x}.json", .{ self.pid, self.start_id }) catch return null;+ g_dir = dir_path;+ g_identity = gpa.dupe(u8, identity.id) catch return null;+ g_session = gpa.dupe(u8, session_id) catch "";+ g_goal = gpa.dupe(u8, goal) catch "";+ g_self = self;+ g_own_name = gpa.dupe(u8, name) catch return null;+ // Peer check BEFORE writing our own record: the warning describes the tree+ // as it was when we arrived.+ const warning = blk: {+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch break :blk null;+ defer dir.close(io);+ const peers = listPeers(io, arena, dir);+ const dup = worktree_lease.duplicateOwner(peers.records, peers.probes, g_identity, self.pid) orelse break :blk null;+ break :blk worktree_lease.duplicateOwnerWarning(arena, dup, unixMs(io) - dup.last_seen_ms);+ };+ writeOwn(io, arena);+ return warning;+}++/// Remove our record. Best-effort: a crashed session leaves it behind and the+/// next listPeers probes it dead and reaps it — retire is hygiene, not+/// correctness.+/// Free the gpa-owned globals. finalizeSession calls this at exit: a Debug+/// build's SafeAllocator reports any gpa allocation still held at process end+/// as a leak (and exits non-zero), and these five strings are otherwise+/// exactly that. After deinit the module is inert.+pub fn deinit(gpa: Allocator) void {+ if (g_dir) |p| gpa.free(p);+ if (g_identity.len > 0) gpa.free(g_identity);+ if (g_session.len > 0) gpa.free(g_session);+ if (g_goal.len > 0) gpa.free(g_goal);+ if (g_own_name) |n| gpa.free(n);+ g_dir = null;+ g_identity = "";+ g_session = "";+ g_goal = "";+ g_own_name = null;+ g_self = .{};+ g_inbox_off = 0;+ g_acked_len = 0;+}++pub fn retire(io: Io) void {+ const dir_path = g_dir orelse return;+ const name = g_own_name orelse return;+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return;+ defer dir.close(io);+ dir.deleteFile(io, name) catch {};+ var inbox_buf: [inbox_name_max]u8 = undefined;+ dir.deleteFile(io, inboxName(&inbox_buf, g_self.pid, g_self.start_id)) catch {};+}++/// Refresh our record's goal — the coordination payload a peer's checkpoint+/// prints. Only the goal_flow setters call this; a cleared goal keeps the+/// last-known text rather than going blank mid-supersession. The goal is+/// re-duped onto the gpa (freeing the previous) so g_goal stays gpa-owned —+/// deinit frees it, and the caller's slice is usually session-arena memory.+pub fn noteGoal(io: Io, gpa: Allocator, arena: Allocator, goal: []const u8) void {+ if (g_own_name == null) return; // never announced (tests, subagents): io may be undefined — touch nothing+ const owned = gpa.dupe(u8, goal) catch return;+ if (g_goal.len > 0) gpa.free(g_goal);+ g_goal = owned;+ writeOwn(io, arena);+}++/// The tool-gate half (#469): null = no unacknowledged live co-owner, else the+/// checkpoint text the model sees as its (un-executed) tool result. Seeing a+/// peer ACKs it, so the re-issued command runs and one process checkpoints at+/// most once per peer — awareness is the goal, not a tollbooth.+pub fn gateCheck(io: Io, arena: Allocator) ?[]const u8 {+ const dir_path = g_dir orelse return null;+ if (g_identity.len == 0) return null;+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return null;+ defer dir.close(io);+ const peers = listPeers(io, arena, dir);+ const peer = unackedPeer(peers, g_identity, proc_identity.selfPid(), g_acked[0..g_acked_len]) orelse return null;+ if (g_acked_len < g_acked.len) {+ g_acked[g_acked_len] = ackKey(peer);+ 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 command was NOT run. Re-issue the identical command to proceed — this fires once per live peer — coordinate first via the peer_message tool (session \"{s}\"), or keep your edits disjoint from theirs.", .{ warning, peer.session_id }) catch warning;+}++// --- the channel (#469 phase 2): one append-only JSONL inbox per session,+// named from the same (pid, start-id) as its presence record so a sender needs+// nothing the record doesn't already carry. Appends use the read+write+// positional pattern from session_transcript (#462: write-only handles break+// appends on Windows). Delivery is queued — a sender never blocks on the+// receiver, and two busy sessions cannot deadlock (#417's rule). ---++pub const inbox_name_max = 96;++/// One inbox line. `from_*` identify the sender's presence record at send+/// time; the harness writes them, never the model.+pub const Message = struct {+ from_pid: i32 = 0,+ from_session: []const u8 = "",+ from_goal: []const u8 = "",+ ts_ms: i64 = 0,+ text: []const u8 = "",+};++pub fn inboxName(buf: *[inbox_name_max]u8, pid: i32, start_id: u64) []const u8 {+ return std.fmt.bufPrint(buf, "{d}-{x}.inbox.jsonl", .{ pid, start_id }) catch unreachable;+}++/// Append one message to `target`'s inbox under `dir`. Best-effort: false on+/// any I/O or serialization failure — a lost message is reported by the+/// caller, never thrown into a tool call.+pub fn postMessage(io: Io, arena: Allocator, dir: Io.Dir, target: Owner, msg: Message) bool {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(msg) catch return false;+ aw.writer.writeAll("\n") catch return false;+ var name_buf: [inbox_name_max]u8 = undefined;+ const name = inboxName(&name_buf, target.pid, target.start_id);+ const f = dir.createFile(io, name, .{ .truncate = false, .read = true }) catch return false;+ defer f.close(io);+ const end: u64 = if (f.stat(io)) |st| st.size else |_| blk: {+ const st = dir.statFile(io, name, .{}) catch return false;+ break :blk st.size;+ };+ f.writePositionalAll(io, aw.writer.buffered(), end) catch return false;+ return true;+}++/// Read complete inbox lines after `offset`, advancing it past everything+/// parsed. A trailing partial line stays for the next drain — a writer+/// mid-append never yields a torn message. A file shorter than the offset was+/// recreated; restart from the top rather than skip it forever.+pub fn readNewMessages(io: Io, arena: Allocator, dir: Io.Dir, name: []const u8, offset: *u64) []const Message {+ const text = dir.readFileAlloc(io, name, arena, .limited(256 * 1024)) catch return &.{};+ if (text.len < offset.*) offset.* = 0;+ if (text.len == offset.*) return &.{};+ var msgs: std.ArrayList(Message) = .empty;+ var pos: usize = @intCast(offset.*);+ while (std.mem.indexOfScalarPos(u8, text, pos, '\n')) |nl| {+ const line = text[pos..nl];+ pos = nl + 1;+ const m = std.json.parseFromSliceLeaky(Message, arena, line, .{ .ignore_unknown_fields = true }) catch continue;+ if (m.from_pid == 0 or m.text.len == 0) continue;+ msgs.append(arena, m) catch break;+ }+ offset.* = @intCast(pos);+ return msgs.items;+}++/// The live co-owners of MY worktree: every registry record whose verdict is+/// live_foreign/live_unverified. The sender's target list for peer_message+/// and /tell; already probed, with the provably dead reaped.+pub fn liveTreePeers(io: Io, arena: Allocator) []const Owner {+ const dir_path = g_dir orelse return &.{};+ if (g_identity.len == 0) return &.{};+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return &.{};+ defer dir.close(io);+ const peers = listPeers(io, arena, dir);+ var live: std.ArrayList(Owner) = .empty;+ for (peers.records, 0..) |rec, i| {+ if (i >= peers.probes.len) break;+ switch (worktree_lease.ownerVerdict(rec, g_identity, g_self.pid, peers.probes[i])) {+ .live_foreign, .live_unverified => live.append(arena, rec) catch break,+ else => {},+ }+ }+ return live.items;+}++/// Send-side wrapper for the wired layer: stamp the message with OUR record+/// and append it to the target's inbox. false when this session never+/// announced (tests, subagents) or the write failed.+pub fn postTo(io: Io, arena: Allocator, target: Owner, text: []const u8) bool {+ const dir_path = g_dir orelse return false;+ if (g_self.pid == 0) return false;+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return false;+ defer dir.close(io);+ return postMessage(io, arena, dir, target, .{+ .from_pid = g_self.pid,+ .from_session = g_session,+ .from_goal = g_goal,+ .ts_ms = unixMs(io),+ .text = text,+ });+}++/// Drain OUR inbox: every complete message since the last drain. Empty when+/// unannounced, inbox-less, or caught up.+pub fn drainInbox(io: Io, arena: Allocator) []const Message {+ const dir_path = g_dir orelse return &.{};+ if (g_self.pid == 0) return &.{};+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return &.{};+ defer dir.close(io);+ var name_buf: [inbox_name_max]u8 = undefined;+ return readNewMessages(io, arena, dir, inboxName(&name_buf, g_self.pid, g_self.start_id), &g_inbox_off);+}++pub fn ownSession() []const u8 {+ return g_session;+}++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 "presence record round-trips pid, identity, and goal" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const owner: Owner = .{+ .pid = 4242,+ .start_id = 0xdeadbeef,+ .session_id = "session-1",+ .identity = "/repo/.git",+ .goal = "agent-inbox redesign",+ .last_seen_ms = 123456,+ };+ const text = try formatRecord(arena, owner);+ const back = parseRecord(arena, text) orelse return error.ExpectedRecord;+ try std.testing.expectEqual(owner.pid, back.pid);+ try std.testing.expectEqual(owner.start_id, back.start_id);+ try std.testing.expectEqualStrings(owner.session_id, back.session_id);+ try std.testing.expectEqualStrings(owner.identity, back.identity);+ try std.testing.expectEqualStrings(owner.goal, back.goal);+ try std.testing.expectEqual(owner.last_seen_ms, back.last_seen_ms);+}++test "parseRecord: rejects garbage and pid-less records, tolerates extra fields" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ try std.testing.expect(parseRecord(arena, "not json") == null);+ try std.testing.expect(parseRecord(arena, "{\"goal\":\"x\"}") == null);+ const forward = parseRecord(arena, "{\"pid\":7,\"start_id\":3,\"future\":\"field\"}") orelse return error.ExpectedRecord;+ try std.testing.expectEqual(7, forward.pid);+}++test "listPeers: probes liveness, reaps the provably dead, keeps the alive" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const self = proc_identity.selfRecord(io);+ const alive: Owner = .{ .pid = self.pid, .start_id = self.start_id, .session_id = "s-live", .identity = "/x/.git", .goal = "g" };+ try tmp.dir.writeFile(io, .{ .sub_path = "live.json", .data = try formatRecord(arena, alive) });+ // pid -7 can never hold a process (probe: pid <= 0 is .gone), so the reap+ // path is exercised identically on every platform.+ const dead: Owner = .{ .pid = -7, .start_id = 1, .session_id = "s-dead", .identity = "/x/.git" };+ try tmp.dir.writeFile(io, .{ .sub_path = "dead.json", .data = try formatRecord(arena, dead) });+ const peers = listPeers(io, arena, tmp.dir);+ try std.testing.expectEqual(1, peers.records.len);+ try std.testing.expectEqualStrings("s-live", peers.records[0].session_id);+ var buf: [16]u8 = undefined;+ try std.testing.expectError(error.FileNotFound, tmp.dir.readFile(io, "dead.json", &buf));+}++test "unackedPeer: returns the live foreign co-owner once, then yields to the ack" {+ const my_identity = "/repo/.git";+ const foreign: Owner = .{ .pid = 4242, .start_id = 99, .session_id = "s-b", .identity = "/repo/.git", .goal = "theirs" };+ const other_tree: Owner = .{ .pid = 4343, .start_id = 98, .session_id = "s-c", .identity = "/repo/.git/worktrees/wt1" };+ const records = [_]Owner{ other_tree, foreign };+ const probes = [_]proc_identity.Probe{ .{ .id = 98 }, .{ .id = 99 } };+ const peers: Peers = .{ .records = &records, .probes = &probes };+ const found = unackedPeer(peers, my_identity, 1, &.{}) orelse return error.ExpectedPeer;+ try std.testing.expectEqualStrings("s-b", found.session_id);+ const key = ackKey(found);+ try std.testing.expect(unackedPeer(peers, my_identity, 1, &.{key}) == null);+ // A new session reusing that pid is a NEW peer, not an acked one.+ const reused: Owner = .{ .pid = 4242, .start_id = 100, .session_id = "s-d", .identity = "/repo/.git" };+ const records2 = [_]Owner{reused};+ const probes2 = [_]proc_identity.Probe{.{ .id = 100 }};+ try std.testing.expect(unackedPeer(.{ .records = &records2, .probes = &probes2 }, my_identity, 1, &.{key}) != null);+}++test "inbox: post then drain returns each message once, in order, sender-stamped" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const target: Owner = .{ .pid = 4242, .start_id = 0xabc, .session_id = "s-b", .identity = "/repo/.git" };+ const msg: Message = .{ .from_pid = 1, .from_session = "s-a", .from_goal = "agent-inbox redesign", .ts_ms = 7, .text = "hold off gui/src until I land the move" };+ try std.testing.expect(postMessage(io, arena, tmp.dir, target, msg));+ try std.testing.expect(postMessage(io, arena, tmp.dir, target, .{ .from_pid = 1, .from_session = "s-a", .ts_ms = 8, .text = "second note" }));+ var name_buf: [inbox_name_max]u8 = undefined;+ const name = inboxName(&name_buf, target.pid, target.start_id);+ var off: u64 = 0;+ const first = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(2, first.len);+ try std.testing.expectEqualStrings("s-a", first[0].from_session);+ try std.testing.expectEqualStrings("agent-inbox redesign", first[0].from_goal);+ try std.testing.expectEqualStrings("hold off gui/src until I land the move", first[0].text);+ try std.testing.expectEqualStrings("second note", first[1].text);+ // A second drain at the same offset is empty: delivery is exactly-once per reader.+ try std.testing.expectEqual(0, readNewMessages(io, arena, tmp.dir, name, &off).len);+}++test "readNewMessages: a torn trailing line waits for the next drain" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const target: Owner = .{ .pid = 9, .start_id = 1, .session_id = "s-t" };+ try std.testing.expect(postMessage(io, arena, tmp.dir, target, .{ .from_pid = 2, .from_session = "s-x", .ts_ms = 1, .text = "whole" }));+ var name_buf: [inbox_name_max]u8 = undefined;+ const name = inboxName(&name_buf, 9, 1);+ // Simulate a writer mid-append: half a JSON line, no newline yet.+ const f = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });+ const st = try f.stat(io);+ try f.writePositionalAll(io, "{\"from_pid\":2,\"tex", st.size);+ f.close(io);+ var off: u64 = 0;+ const first = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(1, first.len); // only the complete line+ try std.testing.expectEqualStrings("whole", first[0].text);+ // Finish the torn line; the next drain picks it up.+ const f2 = try tmp.dir.createFile(io, name, .{ .truncate = false, .read = true });+ const st2 = try f2.stat(io);+ try f2.writePositionalAll(io, "t\":\"rest\"}\n", st2.size);+ f2.close(io);+ const second = readNewMessages(io, arena, tmp.dir, name, &off);+ try std.testing.expectEqual(1, second.len);+ try std.testing.expectEqualStrings("rest", second[0].text);+}diff --git a/src/schema.zig b/src/schema.zigindex bcb33fd4..646247fd 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -14,6 +14,7 @@ const mcp = @import("mcp.zig");const pricing = @import("pricing.zig");const learn_store = @import("learn_store.zig");const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill` tool's name/desc/schema live there+const peer_channel = @import("peer_channel.zig"); // #469: the peer_message tool's name/desc/schema live thereconst no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capabilityconst imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle@@ -198,7 +199,8 @@ const learn_candidate_spec = ToolSpec{,};-pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, agent_output_spec, learn_candidate_spec };+pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, agent_output_spec, learn_candidate_spec, peer_spec };+const peer_spec = ToolSpec{ .name = peer_channel.tool_name, .desc = peer_channel.tool_desc, .schema = peer_channel.tool_schema };// The common catalog (clock_sleep off) is static too. Previously every root// startup allocated and filled a filtered ToolSpec array before rendering even@@ -223,7 +225,7 @@ const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });-pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name };+pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, peer_channel.tool_name };pub fn isMetaName(name: []const u8) bool {for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;diff --git a/src/session_run.zig b/src/session_run.zigindex b1b11e37..4c963cad 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -52,6 +52,7 @@ const providers = @import("providers.zig");const messages_mod = @import("messages.zig");const session = @import("session.zig");const session_settings = @import("session_settings.zig");+const presence = @import("presence.zig");const goal_flow = @import("goal_flow.zig");const fleet = @import("fleet.zig");const hooks = @import("hooks.zig");@@ -277,6 +278,12 @@ pub fn buildRootAgent(root.goal_flag = try arena.dupe(u8, g); // kept: re-applied over every loadSession, incl. /resumeroot.goal = goal_flow.standingGoalFromFlag(root.goal_flag.?, null, root.todos.items, util.unixMs(io));}+ // #469: register this root session so co-resident graffs see it (and it+ // them) BEFORE anyone touches the shared tree — a live co-owner is named+ // at birth here, not discovered mid-collision.+ if (presence.announce(io, gpa, arena, root.home, root.session_name, if (root.goal) |g| g.objective else "")) |warning| {+ if (!main_mod.json_mode and flags.oneshot_prompt == null) try out.print("{s}", .{warning});+ }if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);if (flags.eval_target_flag) |t| root.eval_target = t;if (flags.eval_niche_flag) |n| root.eval_niche = try arena.dupe(u8, n);@@ -356,6 +363,10 @@ pub fn compactResumedSession(root: *agent_mod.Agent) void {/// final turn left uncommitted. Moved out of main() verbatim (600-line/// goal); `root` is already stable main()-owned storage.pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, json_mode: bool) !void {+ // #469: our presence record leaves the registry with us; a crashed session+ // skips this and gets reaped by the next reader's liveness probe instead.+ presence.retire(io);+ presence.deinit(gpa); // its gpa-owned globals must not reach the exit-time leak checkif (!json_mode and root.messages.items.len > 0) {const sink = engine_sink.writerSink(out);if (session.saveSession(root, arena, root.session_name)) |_| {diff --git a/src/worktree_lease.zig b/src/worktree_lease.zigindex 547a43c0..8cc54d5c 100644--- a/src/worktree_lease.zig+++ b/src/worktree_lease.zig@@ -67,6 +67,9 @@ pub const Owner = struct {start_id: proc_identity.StartId = 0,session_id: []const u8 = "",identity: []const u8 = "",+ /// #469: the owner's last-known objective — the coordination payload a+ /// peer reads to decide whether its work overlaps. Empty when unknown.+ goal: []const u8 = "",last_seen_ms: i64 = 0,};@@ -146,10 +149,11 @@ pub fn probeOwners(io: Io, records: []const Owner, out: []proc_identity.Probe) [pub fn duplicateOwnerWarning(arena: Allocator, rec: Owner, age_ms: i64) []const u8 {const mins = @divTrunc(if (age_ms > 0) age_ms else 0, std.time.ms_per_min);+ const goal = if (rec.goal.len > 0) std.fmt.allocPrint(arena, "\n goal: {s}", .{rec.goal}) catch "" else "";return std.fmt.allocPrint(arena,- "⚠ another graff session already owns this worktree\n pid {d} · session {s} · active {d}m\n you would both be editing the same uncommitted tree — restart with -w for an isolated worktree, or continue knowing edits can collide\n",- .{ rec.pid, if (rec.session_id.len > 0) rec.session_id else "unknown", mins },+ "⚠ another graff session already owns this worktree\n pid {d} · session {s} · active {d}m{s}\n you would both be editing the same uncommitted tree — restart with -w for an isolated worktree, or continue knowing edits can collide\n",+ .{ rec.pid, if (rec.session_id.len > 0) rec.session_id else "unknown", mins, goal },) catch "⚠ another graff session already owns this worktree\n";}