graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: bound tuiguard (#704) and address peers by title (#700)
Cursor Agentad68f0f77d46
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c0ff0ec6..9ad3a7d7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -18,6 +18,9 @@ jobs:- name: Zig source-size guard integrity testsrun: python3 scripts/test-zig-lines.py+ - name: Tuiguard pool deadline integrity (#704)+ run: python3 scripts/eval/test_tier1_tuiguard.py+- name: Model-shape benchmark integrityrun: python3 benchmarks/test_model_shape.pydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8efec730..3099c031 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,10 @@ current is part of cutting a release.for drafts abandoned before submit.- Suite floor **1868** (was 1861). Tournament E2E parent timeout300s and 45s default barrier so CI cannot flake on #467 rendezvous.+ Tuiguard probes have a per-probe deadline and a parent wave budget+ so one wedged PTY child cannot hang pre-push (#704).+ `peer_message` resolves a live session by its visible title or+ saved-session base (#700). Presence is still device-local.No tag until asked.## v0.0.282 (2026-08-31)diff --git a/docs/adr/0057-peer-title-is-an-address.md b/docs/adr/0057-peer-title-is-an-address.mdnew file mode 100644index 00000000..0581595b--- /dev/null+++ b/docs/adr/0057-peer-title-is-an-address.md@@ -0,0 +1,24 @@+# 0057. peer_message addresses a session by its visible title++Status: accepted 2026-08-31++## Context++Presence records carried pid, opaque `session_id`, worktree identity, and+goal. Users refer to a live session by the title in `.session.json`.+`peer_message session:"Fixing login recovery"` missed. Goal substring is+the wrong substitute: goals can be absent, stale, or shared.++## Decision++Device-local presence stores `title` and `session_base`. Resolve in this+order: exact title, exact saved-session base, unique normalized+title/slug, then the existing id/pid/name/goal path. Duplicate titles+are ambiguous (return candidates). Refresh on announce, `/rename`,+AI title, `/resume`, `/save`, `/new`, `/clear`. Older records without+the fields still parse. Presence stays device-local.++## Consequences++`action=list` leads with title and base. Cross-laptop discovery is still+not implied. Title is not a global name.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 1d8d15c7..e1890014 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -67,6 +67,7 @@ record only when you need the evidence or the edge cases.| [0054](0054-deepseek-thinking-disabled-at-low.md) | DeepSeek family default low sends `thinking.type=disabled`; `/effort high` still thinks. GLM stays low-only. || [0055](0055-lean-oneshot-bash-15s.md) | Lean `-p` bash auto-backgrounds at 15s; interactive / `--no-lean` stay 120s (ADR 0026). || [0056](0056-composer-image-chips-sync-on-delete.md) | Composer image chips sync on delete and reuse `#N`; `clipboard_paste` MIME/bytes wait until send. |+| [0057](0057-peer-title-is-an-address.md) | `peer_message` resolves exact title / saved-session base before opaque id or goal. |## When to write onediff --git a/docs/releases/v0.0.283.md b/docs/releases/v0.0.283.mdindex 14cd13c3..d5b964a9 100644--- a/docs/releases/v0.0.283.md+++ b/docs/releases/v0.0.283.md@@ -25,3 +25,11 @@ This cut raises the release-cut floor to **1868** (slack 25).The tournament E2E parent timeout is 300s (was 180) and the four-armbarrier defaults to 45s when unset, so a loaded CI runner cannot spendthe whole parent budget at rendezvous (#467).++Tuiguard (#704) kills a wedged PTY probe's process group at 60s (90s+for the long ones) and fails the parent if a wave overruns, naming+whoever is still running.++`peer_message` (#700) lists the visible title and saved-session base+and resolves those before opaque id / goal fragments. Duplicate titles+are ambiguous. Older presence files without the new fields still parse.diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 44ef7f50..154f6af0 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -241,10 +241,11 @@ if wanted tuiguard; thenif ((!build_ok)); thenskip_dependent tuiguardelse- announce tuiguard "17 PTY probes in a 4–8 process pool (#641)"+ announce tuiguard "17 PTY probes in a 4–8 process pool (#641 / #704)"# Same 17 scripts as the old serial loop (pty-guard through model-picker).- # Each owns its pty/tmp/mock; the pool is the wall-time win.- if python3 scripts/eval/tier1_tuiguard.py zig-out/bin/graff; then :; else+ # Each owns its pty/tmp/mock; the pool is the wall-time win. Deadlines+ # (#704) are checked first so a wedged probe cannot hang pre-push.+ if python3 scripts/eval/test_tier1_tuiguard.py && python3 scripts/eval/tier1_tuiguard.py zig-out/bin/graff; then :; elserecord_fail tuiguardfifidiff --git a/scripts/eval/test_tier1_tuiguard.py b/scripts/eval/test_tier1_tuiguard.pynew file mode 100644index 00000000..6784e3a7--- /dev/null+++ b/scripts/eval/test_tier1_tuiguard.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""Integrity tests for the tuiguard pool deadlines (#704)."""++from __future__ import annotations++import importlib.util+import os+from pathlib import Path+import sys+import tempfile+import time+import unittest+from unittest import mock+++RUNNER_PATH = Path(__file__).with_name("tier1_tuiguard.py")+SPEC = importlib.util.spec_from_file_location("tier1_tuiguard", RUNNER_PATH)+if SPEC is None or SPEC.loader is None:+ raise RuntimeError(f"cannot import {RUNNER_PATH}")+tuiguard = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(tuiguard)+++class DeadlineTests(unittest.TestCase):+ def test_probe_timeout_uses_long_list_and_env(self) -> None:+ self.assertEqual(tuiguard.probe_timeout("test-tui-click.py"), 90.0)+ self.assertEqual(tuiguard.probe_timeout("tui-pty-guard.py"), 60.0)+ with mock.patch.dict(os.environ, {"GRAFF_TUIGUARD_PROBE_TIMEOUT": "0.4"}):+ self.assertEqual(tuiguard.probe_timeout("test-tui-click.py"), 0.4)++ def test_parent_budget_is_waves_times_longest_plus_slack(self) -> None:+ names = ("a.py", "b.py", "c.py")+ with mock.patch.object(tuiguard, "probe_timeout", return_value=10.0):+ # 3 probes / 2 workers = 2 waves → 20 + 60+ self.assertEqual(tuiguard.parent_budget(2, names), 80.0)++ def test_run_command_kills_a_wedged_child(self) -> None:+ status, blob, elapsed, timed_out = tuiguard.run_command(+ [sys.executable, "-c", "import time; time.sleep(30)"],+ timeout=0.3,+ )+ self.assertTrue(timed_out)+ self.assertEqual(status, 124)+ self.assertLess(elapsed, 5.0)+ self.assertGreaterEqual(elapsed, 0.25)+ _ = blob++ def test_run_command_kills_the_process_group(self) -> None:+ if not hasattr(os, "fork") or not hasattr(os, "kill"):+ self.skipTest("posix process groups")+ scratch = tempfile.TemporaryDirectory(prefix="tuiguard-pg-")+ self.addCleanup(scratch.cleanup)+ marker = Path(scratch.name) / "pids"+ child = r"""+import os, sys, time+from pathlib import Path+marker = Path(sys.argv[1])+g = os.fork()+if g == 0:+ time.sleep(60)+ os._exit(0)+marker.write_text(f"{os.getpid()}\n{g}\n", encoding="utf-8")+time.sleep(60)+"""+ status, _, elapsed, timed_out = tuiguard.run_command(+ [sys.executable, "-c", child, str(marker)],+ timeout=0.4,+ )+ self.assertTrue(timed_out)+ self.assertEqual(status, 124)+ self.assertLess(elapsed, 5.0)+ time.sleep(0.1)+ pids = [int(x) for x in marker.read_text(encoding="utf-8").split() if x.strip()]+ self.assertEqual(len(pids), 2)+ for pid in pids:+ with self.assertRaises(OSError):+ os.kill(pid, 0)++ def test_run_pool_names_still_running_on_parent_deadline(self) -> None:+ def hang(script: str, binary: str, timeout: float):+ time.sleep(5)+ return script, 0, "", 5.0, False++ with mock.patch.object(tuiguard, "run_probe", side_effect=hang):+ with mock.patch("builtins.print") as printer:+ rc = tuiguard.run_pool(+ "/nonexistent/graff",+ probes=("test-tui-hover.py",),+ jobs=1,+ parent_seconds=0.2,+ )+ self.assertEqual(rc, 1)+ joined = " ".join(+ str(call.args[0]) for call in printer.call_args_list if call.args+ )+ self.assertIn("still running: test-tui-hover.py", joined)+++if __name__ == "__main__":+ raise SystemExit(unittest.main())diff --git a/scripts/eval/tier1_tuiguard.py b/scripts/eval/tier1_tuiguard.pyindex 86825a4d..3d7cbd79 100755--- a/scripts/eval/tier1_tuiguard.py+++ b/scripts/eval/tier1_tuiguard.py@@ -1,21 +1,30 @@#!/usr/bin/env python3-"""Run the 17 tuiguard PTY probes as a process pool (#641).+"""Run the 17 tuiguard PTY probes as a process pool (#641 / #704).Each probe owns its own pty/tmp/mock and is independent of the others. Theserial loop in eval-tier1.sh was the dominant post-src wall (2–4 min). A 4–8worker pool brings that to roughly one long probe (fold-headers / hover).+A wedged child used to keep the pool (and therefore pre-push) alive for+hours: `subprocess.run` and `as_completed` had no deadline (#704). Each+probe now has an explicit timeout that kills its process group, the parent+has a wave-budget deadline, and a timeout names the still-running scripts.+Usage: python3 scripts/eval/tier1_tuiguard.py [path/to/graff]Exit 0 when every probe passes (or skips itself); 1 if any fails.GRAFF_TUIGUARD_JOBS overrides the pool size (default: min(8, cpu_count)).+GRAFF_TUIGUARD_PROBE_TIMEOUT overrides every per-probe deadline (seconds)."""from __future__ import annotations+import mathimport os+import signalimport subprocessimport sys-from concurrent.futures import ProcessPoolExecutor, as_completed+import time+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, waitfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]@@ -41,6 +50,19 @@ PROBES = ("test-tui-model-picker.py",)+# Warm-run walls from a green 4-worker pool: click ~35s, hover ~20s,+# model-picker ~19s. 90s is ~2.5× the longest; the rest stay at 60s.+DEFAULT_TIMEOUT = 60.0+LONG_TIMEOUT = 90.0+PARENT_SLACK = 60.0+PROBE_TIMEOUTS = {+ "test-tui-click.py": LONG_TIMEOUT,+ "test-tui-hover.py": LONG_TIMEOUT,+ "test-tui-fold-headers.py": LONG_TIMEOUT,+ "test-tui-model-picker.py": LONG_TIMEOUT,+ "test-tui-layout-cache.py": LONG_TIMEOUT,+}+def _jobs() -> int:raw = os.environ.get("GRAFF_TUIGUARD_JOBS", "").strip()@@ -50,17 +72,122 @@ def _jobs() -> int:return max(1, min(8, cpus, len(PROBES)))-def run_probe(script: str, binary: str) -> tuple[str, int, str]:- path = SCRIPTS / script- proc = subprocess.run(- [sys.executable, str(path), binary],- cwd=ROOT,- capture_output=True,+def probe_timeout(script: str) -> float:+ raw = os.environ.get("GRAFF_TUIGUARD_PROBE_TIMEOUT", "").strip()+ if raw:+ return float(raw)+ return PROBE_TIMEOUTS.get(script, DEFAULT_TIMEOUT)+++def parent_budget(jobs: int, names: tuple[str, ...] = PROBES) -> float:+ """Worst-case wall: ceil(n/jobs) waves of the longest probe, plus slack."""+ workers = max(1, jobs)+ waves = math.ceil(len(names) / workers)+ longest = max(probe_timeout(n) for n in names) if names else DEFAULT_TIMEOUT+ return waves * longest + PARENT_SLACK+++def terminate_group(proc: subprocess.Popen[str]) -> None:+ if proc.poll() is not None:+ return+ if os.name == "posix":+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ return+ except OSError:+ pass+ proc.kill()+++def run_command(argv: list[str], timeout: float, cwd: Path | None = None) -> tuple[int, str, float, bool]:+ """Run argv in its own session. On timeout, kill the whole group."""+ t0 = time.monotonic()+ proc = subprocess.Popen(+ argv,+ cwd=str(cwd or ROOT),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,text=True,errors="replace",+ start_new_session=True,+ )+ try:+ out, _ = proc.communicate(timeout=timeout)+ elapsed = time.monotonic() - t0+ return proc.returncode or 0, (out or "").rstrip(), elapsed, False+ except subprocess.TimeoutExpired:+ terminate_group(proc)+ leftover, _ = proc.communicate()+ elapsed = time.monotonic() - t0+ blob = (leftover or "").rstrip()+ return 124, blob, elapsed, True+++def run_probe(script: str, binary: str, timeout: float) -> tuple[str, int, str, float, bool]:+ status, blob, elapsed, timed_out = run_command(+ [sys.executable, str(SCRIPTS / script), binary],+ timeout,)- blob = (proc.stdout + proc.stderr).rstrip()- return script, proc.returncode, blob+ return script, status, blob, elapsed, timed_out+++def run_pool(+ binary: str,+ probes: tuple[str, ...] = PROBES,+ jobs: int | None = None,+ parent_seconds: float | None = None,+) -> int:+ workers = jobs if jobs is not None else _jobs()+ print(f" {len(probes)} probes, {workers} workers")+ failed: list[str] = []+ raw_parent = os.environ.get("GRAFF_TUIGUARD_PARENT_TIMEOUT", "").strip()+ if parent_seconds is not None:+ budget = parent_seconds+ elif raw_parent:+ budget = float(raw_parent)+ else:+ budget = parent_budget(workers, probes)+ deadline = time.monotonic() + budget+ # Threads wait on per-probe Popen; the probe is already a process group.+ # A process pool hid child output until join and could not abandon a+ # wedged worker without waiting on the context manager (#704).+ pool = ThreadPoolExecutor(max_workers=max(1, workers))+ try:+ futs = {+ pool.submit(run_probe, name, binary, probe_timeout(name)): name+ for name in probes+ }+ pending = set(futs)+ while pending:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ stuck = ", ".join(sorted(futs[f] for f in pending))+ print(f" tuiguard: parent deadline; still running: {stuck}")+ return 1+ done, pending = wait(+ pending, timeout=min(remaining, 0.25), return_when=FIRST_COMPLETED+ )+ for fut in done:+ script, status, blob, elapsed, timed_out = fut.result()+ if blob:+ for line in blob.splitlines():+ print(f" [{script}] {line}")+ print(f" [{script}] {elapsed:.1f}s")+ if timed_out:+ failed.append(script)+ print(f" FAIL {script} (timeout after {elapsed:.1f}s)")+ elif status != 0:+ failed.append(script)+ print(f" FAIL {script} (exit {status})")+ else:+ print(f" ok {script}")+ finally:+ pool.shutdown(wait=False, cancel_futures=True)+ if failed:+ print(f" {len(failed)}/{len(probes)} probes failed: {', '.join(failed)}")+ return 1+ print(f" all {len(probes)} probes passed")+ return 0def main() -> int:@@ -68,26 +195,7 @@ def main() -> int:if not os.path.isfile(binary):print(f" tuiguard: no binary at {binary}", file=sys.stderr)return 1- jobs = _jobs()- print(f" {len(PROBES)} probes, {jobs} workers")- failed: list[str] = []- with ProcessPoolExecutor(max_workers=jobs) as pool:- futs = {pool.submit(run_probe, name, binary): name for name in PROBES}- for fut in as_completed(futs):- script, status, blob = fut.result()- if blob:- for line in blob.splitlines():- print(f" [{script}] {line}")- if status != 0:- failed.append(script)- print(f" FAIL {script} (exit {status})")- else:- print(f" ok {script}")- if failed:- print(f" {len(failed)}/{len(PROBES)} probes failed: {', '.join(failed)}")- return 1- print(f" all {len(PROBES)} probes passed")- return 0+ return run_pool(binary)if __name__ == "__main__":diff --git a/src/cli.zig b/src/cli.zigindex 6de82ded..f4a81719 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -23,6 +23,8 @@ pub const changelog_text =\\──────────\\0.0.283\\ • deleted composer image chips reuse #N; paste traces omit MIME/bytes until send (#702)+ \\ • peer_message addresses a live session by its visible title or saved-session base (#700)+ \\ • tuiguard fails a wedged PTY probe instead of hanging pre-push (#704)\\\\0.0.282\\ • pasted-text chips are atomic spans — a typed lookalike stays literal (#674)diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 289a346a..5082b8db 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -20,6 +20,7 @@ const mcp_config_path = main_mod.mcp_config_path;const session_ext = session.session_ext;const saveSession = session.saveSession;const session = @import("session.zig");+const presence = @import("presence.zig");const listSavedSessions = session.listSavedSessions;const sessionAge = session.sessionAge;@@ -493,6 +494,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;};root.session_name = name;+ presence.noteLabelsFrom(root.io, root.gpa, arena, root.session_title, root.session_name);try out.print("saved session → {s}{s}\n", .{ name, session_ext });try out.flush();return true;diff --git a/src/commands_resume.zig b/src/commands_resume.zigindex 8028e7a2..0dfbbb31 100644--- a/src/commands_resume.zig+++ b/src/commands_resume.zig@@ -10,6 +10,7 @@ const session = @import("session.zig");const session_branch = @import("session_branch.zig");const main_mod = @import("main.zig");const pickers = @import("pickers.zig");+const presence = @import("presence.zig");const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;@@ -61,6 +62,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,error.BranchAlreadyExists => reject(out, "branch failed: destination already exists\n", .{}),else => reject(out, "resume failed: {t}\n", .{err}),};+ presence.noteLabelsFrom(root.io, root.gpa, arena, root.session_title, root.session_name);if (resumed.branched) {try out.print("branched {s}{s} → {s}{s} — {d} message(s), {s} via {s}{s}\n", .{ resumed.source, session.session_ext, resumed.target, session.session_ext, root.messages.items.len, root.provider.model, root.provider.id, if (root.strict) " (strict)" else "" });} else {diff --git a/src/commands_session.zig b/src/commands_session.zigindex 46ea6884..664fdf62 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -23,6 +23,7 @@ const Keys = provider_mod.Keys;const ToolCall = tools_mod.ToolCall;const saveSession = session_mod.saveSession;const unixMs = util.unixMs;+const presence = @import("presence.zig");const session_ext = session_mod.session_ext;const ansi = @import("ansi.zig");@@ -102,6 +103,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.compact_transport_failures = 0;root.tui_header_shown = false;root.session_title = null; // re-summarize the now-empty conversation+ presence.noteLabelsFrom(root.io, root.gpa, arena, null, root.session_name);root.ai_title_done = false;root.title_generation +%= 1;root.session_recap = null; // #419: nothing to recap in an empty conversation@@ -136,6 +138,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.session_name = try std.fmt.allocPrint(arena, "session-{d}-{d}", .{ unixMs(root.io), proc_identity.selfPid() }); // same-ms uniqueness, see session_runprompts.resetSessionCompacted(root, arena); // #445: after the rename, so the re-arm reads the NEW sessionsaveSession(root, arena, root.session_name) catch {};+ presence.noteLabelsFrom(root.io, root.gpa, arena, null, root.session_name);try out.print("new session → {s}{s}\n", .{ root.session_name, session_ext });try out.flush();return true;@@ -149,6 +152,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.ai_title_done = true; // a manual /rename wins over the auto-titlerroot.title_generation +%= 1; // discard any still-running AI resultsaveSession(root, arena, root.session_name) catch {};+ presence.noteLabelsFrom(root.io, root.gpa, arena, root.session_title, root.session_name);try out.print("session title → {s}\n", .{title});}try out.flush();diff --git a/src/main.zig b/src/main.zigindex a7cbf573..6baf87eb 100644--- a/src/main.zig+++ b/src/main.zig@@ -593,4 +593,5 @@ test { // pull in tests from imported modules (mcp.zig)_ = @import("goal_flow.zig");_ = @import("goal_todo.zig");_ = @import("goal_pacing.zig");+ _ = @import("presence_record.zig");}diff --git a/src/mainloop_title.zig b/src/mainloop_title.zigindex abbd6ef3..54fcd5c4 100644--- a/src/mainloop_title.zig+++ b/src/mainloop_title.zig@@ -9,6 +9,7 @@ const main_mod = @import("main.zig");const provider_mod = @import("provider.zig");const session = @import("session.zig");const title_mod = @import("title.zig");+const presence = @import("presence.zig");const Job = struct {future: ?Io.Future(void) = null,@@ -23,6 +24,7 @@ fn apply(ctx: anytype, title: []const u8) void {if (ctx.root.session_title) |stored| {title_mod.setTerminalTitle(ctx.out, stored, main_mod.g_cwd_display);session.renameSession(ctx.root, ctx.arena, session.slugifyTitle(ctx.arena, stored));+ presence.noteLabelsFrom(ctx.root.io, ctx.root.gpa, ctx.arena, stored, ctx.root.session_name);}}diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex 9b41c828..db47d624 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -34,9 +34,9 @@ const ExecResult = tools_mod.ExecResult;const Owner = worktree_lease.Owner;pub const tool_name = "peer_message";-pub const tool_desc = "Ping a co-resident session, list who is live, or read parked inbound. action=list | inbox | send (default). session is a DM (id/pid/name/goal); omit for this folder's room. Not \"all\".";+pub const tool_desc = "Ping a co-resident session, list who is live, or read parked inbound. action=list | inbox | send (default). session is a DM (visible title, saved-session base, id/pid/name/goal); omit for this folder's room. Presence is device-local. Not \"all\".";pub const tool_schema =- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox"], "description": "send (default): ping a peer. list: who is live. inbox: read+clear parked inbound."}, "session": {"type": "string", "description": "who to ping: exact session name, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}}}+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox"], "description": "send (default): ping a peer. list: who is live (title, base, id, pid, worktree, goal). inbox: read+clear parked inbound."}, "session": {"type": "string", "description": "who to ping: exact visible title, exact saved-session base, unique normalized title/slug, id, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Presence is device-local. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}}};/// Whether the named session sits in MY worktree (routes the post: worktree@@ -97,7 +97,7 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {.is_error = true,},.ambiguous => return .{- .text = try std.fmt.allocPrint(self.arena, "more than one live peer matches — name one with `session` (id, pid, or a unique goal fragment): {s}", .{peerListText(self.arena, presence.liveAllPeers(self.io, self.arena))}),+ .text = try std.fmt.allocPrint(self.arena, "more than one live peer matches — name one with `session` (title, base, id, or pid): {s}", .{peerListText(self.arena, presence.liveAllPeers(self.io, self.arena))}),.is_error = true,},};@@ -441,10 +441,12 @@ pub fn writeLiveSection(root: *Agent, arena: Allocator, out: *Io.Writer) !void {wrote_remote = true;}const goal = if (p.goal.len > 0) p.goal else "?";+ const shown = if (p.title.len > 0) p.title else p.session_id;+ const base = if (p.session_base.len > 0) p.session_base else p.session_id;if (local)- try out.print(" ⚡ {s} · pid {d} · goal: {s}\n", .{ p.session_id, p.pid, goal })+ try out.print(" ⚡ {s} · {s} · {s} · pid {d} · goal: {s}\n", .{ shown, base, p.session_id, p.pid, goal })else- try out.print(" ⚡ {s} · pid {d} · {s} · goal: {s}\n", .{ p.session_id, p.pid, p.identity, goal });+ try out.print(" ⚡ {s} · {s} · {s} · pid {d} · {s} · goal: {s}\n", .{ shown, base, p.session_id, p.pid, p.identity, goal });}}diff --git a/src/peer_inbox.zig b/src/peer_inbox.zigindex aaf5d316..e24b3129 100644--- a/src/peer_inbox.zig+++ b/src/peer_inbox.zig@@ -185,10 +185,12 @@ pub fn formatList(arena: Allocator, peers: []const Owner, mine: []const u8) []cofor (peers) |p| {const where: []const u8 = if (std.mem.eql(u8, p.identity, mine)) "this-folder" else if (p.identity.len > 0) p.identity else "?";const goal = peer_context.clip(if (p.goal.len > 0) p.goal else "?", 40);- const line = std.fmt.allocPrint(arena, "{s} pid {d} {s} · {s}\n", .{ p.session_id, p.pid, where, goal }) catch continue;+ const shown = if (p.title.len > 0) p.title else p.session_id;+ const base = if (p.session_base.len > 0) p.session_base else p.session_id;+ const line = std.fmt.allocPrint(arena, "{s} [{s}] {s} pid {d} {s} · {s}\n", .{ shown, base, p.session_id, p.pid, where, goal }) catch continue;buf.appendSlice(arena, line) catch {};}- buf.appendSlice(arena, "DM with session=<id|pid|goal fragment>; omit session for this folder's room.") catch {};+ buf.appendSlice(arena, "DM with session=<title|base|id|pid|goal>; omit session for this folder's room. Presence is device-local.") catch {};return buf.items;}@@ -248,8 +250,25 @@ test "formatList: one short line per peer; empty is honest" {};const text = formatList(a, &peers, "here");try testing.expect(std.mem.startsWith(u8, text, "2 live:\n"));- try testing.expect(std.mem.indexOf(u8, text, "session-aaa pid 11 this-folder · rewrite the targeting") != null);- try testing.expect(std.mem.indexOf(u8, text, "session-bbb pid 22 /other/.git · paint chips") != null);+ try testing.expect(std.mem.indexOf(u8, text, "session-aaa [session-aaa] session-aaa pid 11 this-folder · rewrite the targeting") != null);+ try testing.expect(std.mem.indexOf(u8, text, "session-bbb [session-bbb] session-bbb pid 22 /other/.git · paint chips") != null);+}++test "formatList: title and saved-session base lead the line" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const peers = [_]Owner{.{+ .session_id = "session--aaa",+ .pid = 11,+ .goal = "recover login",+ .identity = "here",+ .title = "Fixing login recovery",+ .session_base = "fixing-login-recovery",+ }};+ const text = formatList(a, &peers, "here");+ try testing.expect(std.mem.indexOf(u8, text, "Fixing login recovery [fixing-login-recovery] session--aaa pid 11 this-folder · recover login") != null);+ try testing.expect(std.mem.indexOf(u8, text, "device-local") != null);}test "inbox JSON round-trip: restoreJson rebuilds the ring" {diff --git a/src/peer_target.zig b/src/peer_target.zigindex f085a9c8..77935075 100644--- a/src/peer_target.zig+++ b/src/peer_target.zig@@ -3,7 +3,8 @@//! The JSONL rooms stay append-only logs (ADR 0004). Delivery is the//! working set: a bare worktree post is still a room, but a named target is//! a DM — only that session parks it. `session` on peer_message resolves-//! by exact id, pid, unique name fragment, or unique **goal** fragment so a+//! by exact title, exact saved-session base, unique normalized title/slug,+//! then exact id, pid, unique name fragment, or unique **goal** fragment so a//! model can ping "the one doing the digest job" without guessing names.//!//! A standing liaison subagent is the wrong shape: children never drain the@@ -43,13 +44,45 @@ pub fn deviceHears(m: Message, own: []const u8) bool {return m.from_user and m.to.len == 0;}-fn countWhere(peers: []const Owner, comptime kind: enum { exact_id, pid, name, goal }, want: []const u8) Resolve {+/// Filesystem-safe slug, same rule as `session.slugifyTitle` (60-char cap).+pub fn slugify(src: []const u8, dest: []u8) []const u8 {+ var n: usize = 0;+ var last_dash = true;+ for (src) |c| {+ if (n >= dest.len or n >= 60) break;+ const lc = std.ascii.toLower(c);+ if ((lc >= 'a' and lc <= 'z') or (lc >= '0' and lc <= '9')) {+ dest[n] = lc;+ n += 1;+ last_dash = false;+ } else if (!last_dash) {+ dest[n] = '-';+ n += 1;+ last_dash = true;+ }+ }+ if (n > 0 and dest[n - 1] == '-') n -= 1;+ return dest[0..n];+}++fn slugEq(a: []const u8, b: []const u8) bool {+ var aa: [64]u8 = undefined;+ var bb: [64]u8 = undefined;+ const sa = slugify(a, &aa);+ const sb = slugify(b, &bb);+ return sa.len > 0 and std.mem.eql(u8, sa, sb);+}++fn countWhere(peers: []const Owner, comptime kind: enum { exact_title, exact_base, normalized, exact_id, pid, name, goal }, want: []const u8) Resolve {var found: ?Owner = null;var n: usize = 0;const pid_val: ?i32 = if (kind == .pid) std.fmt.parseInt(i32, want, 10) catch null else null;if (kind == .pid and pid_val == null) return .none;for (peers) |p| {const hit = switch (kind) {+ .exact_title => p.title.len > 0 and std.mem.eql(u8, p.title, want),+ .exact_base => p.session_base.len > 0 and std.mem.eql(u8, p.session_base, want),+ .normalized => (p.title.len > 0 and slugEq(p.title, want)) or (p.session_base.len > 0 and slugEq(p.session_base, want)),.exact_id => std.mem.eql(u8, p.session_id, want),.pid => p.pid == pid_val.?,.name => std.mem.indexOf(u8, p.session_id, want) != null,@@ -65,11 +98,18 @@ fn countWhere(peers: []const Owner, comptime kind: enum { exact_id, pid, name, g/// Pick the one live peer `want` names. Empty wants exactly one peer (the/// caller decides whether that becomes a DM or a room post). Precedence:-/// exact session id, then pid, then unique name fragment, then unique goal-/// fragment. A name hit always beats a goal hit so "digest" naming a session-/// does not steal a peer whose goal happens to mention digest.+/// exact title, exact saved-session base, unique normalized title/slug,+/// then exact session id, pid, unique name fragment, unique goal fragment.+/// Title/base beat opaque-id/goal so a visible name cannot lose to a+/// fragment of someone else's id (#700).pub fn resolvePeer(peers: []const Owner, want: []const u8) Resolve {if (want.len == 0) return if (peers.len == 1) .{ .one = peers[0] } else if (peers.len == 0) .none else .ambiguous;+ const by_title = countWhere(peers, .exact_title, want);+ if (by_title != .none) return by_title;+ const by_base = countWhere(peers, .exact_base, want);+ if (by_base != .none) return by_base;+ const by_norm = countWhere(peers, .normalized, want);+ if (by_norm != .none) return by_norm;const exact = countWhere(peers, .exact_id, want);if (exact == .one) return exact;const by_pid = countWhere(peers, .pid, want);@@ -87,6 +127,10 @@ fn peer(id: []const u8, pid: i32, goal: []const u8) Owner {return .{ .session_id = id, .pid = pid, .goal = goal };}+fn titled(id: []const u8, pid: i32, title: []const u8, base: []const u8) Owner {+ return .{ .session_id = id, .pid = pid, .title = title, .session_base = base };+}+test "addressedTo: exact id, then substring either way; empty is never a hit" {try testing.expect(addressedTo("session-111-us", "session-111-us"));try testing.expect(addressedTo("session-111", "session-111-us"));@@ -146,3 +190,29 @@ test "resolvePeer: a goal fragment pings the session doing that work" {try testing.expectEqualStrings("session-bbb", resolvePeer(&peers, "hover").one.session_id);try testing.expect(resolvePeer(&peers, "the") == .ambiguous); // both goals contain it}++test "resolvePeer: exact title and saved-session base beat opaque id" {+ const peers = [_]Owner{+ titled("session--aaa", 1, "Fixing login recovery", "fixing-login-recovery"),+ titled("session--bbb", 2, "Paint hover chips", "paint-hover-chips"),+ };+ try testing.expectEqualStrings("session--aaa", resolvePeer(&peers, "Fixing login recovery").one.session_id);+ try testing.expectEqualStrings("session--aaa", resolvePeer(&peers, "fixing-login-recovery").one.session_id);+ try testing.expectEqualStrings("session--bbb", resolvePeer(&peers, "Paint hover chips").one.session_id);+ try testing.expect(resolvePeer(&peers, "login") == .none); // not exact, not a unique slug+}++test "resolvePeer: unique normalized title; duplicate titles are ambiguous" {+ const unique = [_]Owner{+ titled("session--aaa", 1, "Fixing login recovery", "fixing-login-recovery"),+ titled("session--bbb", 2, "Other work", "other-work"),+ };+ try testing.expectEqualStrings("session--aaa", resolvePeer(&unique, "FIXING LOGIN RECOVERY").one.session_id);+ const dup = [_]Owner{+ titled("session--aaa", 1, "Same title", "same-title"),+ titled("session--bbb", 2, "Same title", "same-title-2"),+ };+ try testing.expect(resolvePeer(&dup, "Same title") == .ambiguous);+ const legacy = [_]Owner{peer("session-digest", 11, "refactor the digest job")};+ try testing.expectEqualStrings("session-digest", resolvePeer(&legacy, "digest").one.session_id);+}diff --git a/src/presence.zig b/src/presence.zigindex 7362f298..94f70418 100644--- a/src/presence.zig+++ b/src/presence.zig@@ -18,8 +18,11 @@ const main_mod = @import("main.zig"); // `unattended`: one-shots join channel roconst unixMs = util.unixMs;const presence_mutate = @import("presence_mutate.zig");const no_local_tools = @import("no_local_tools.zig");+const presence_record = @import("presence_record.zig");const Owner = worktree_lease.Owner;+pub const formatRecord = presence_record.formatRecord;+pub const parseRecord = presence_record.parseRecord;pub const isSharedTreeGit = presence_mutate.isSharedTreeGit;pub const isSharedTreeShell = presence_mutate.isSharedTreeShell;@@ -30,44 +33,6 @@ pub const registry_subdir = ".graff/live";const max_peers = 16;const record_max = 4096;-/// 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 {@@ -143,6 +108,8 @@ var g_dir: ?[]const u8 = null; // gpa-owned registry dir pathvar g_identity: []const u8 = ""; // gpa-owned own worktree identityvar g_own_name: ?[]const u8 = null; // gpa-owned own record's file namevar g_session: []const u8 = ""; // gpa-owned session id, for rewrites+var g_title: []const u8 = ""; // gpa-owned visible title (#700)+var g_session_base: []const u8 = ""; // gpa-owned saved-session slug (#700)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 announcevar g_chan: ?[]const u8 = null; // gpa-owned channel file name (hash of g_identity)@@ -157,6 +124,8 @@ fn writeOwn(io: Io, arena: Allocator) void {const name = g_own_name orelse return;var owner = worktree_lease.selfOwner(io, g_identity, g_session, unixMs(io));owner.goal = g_goal;+ owner.title = g_title;+ owner.session_base = g_session_base;const text = formatRecord(arena, owner) catch return;var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return;defer dir.close(io);@@ -231,12 +200,16 @@ 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_title.len > 0) gpa.free(g_title);+ if (g_session_base.len > 0) gpa.free(g_session_base);if (g_goal.len > 0) gpa.free(g_goal);if (g_own_name) |n| gpa.free(n);if (g_chan) |c| gpa.free(c);g_dir = null;g_identity = "";g_session = "";+ g_title = "";+ g_session_base = "";g_goal = "";g_own_name = null;g_chan = null;@@ -269,6 +242,35 @@ pub fn noteGoal(io: Io, gpa: Allocator, arena: Allocator, goal: []const u8) voidwriteOwn(io, arena);}+/// Refresh the visible title and saved-session base (#700). Empty title is+/// honest (pre-title sessions). session_base is the durable file slug; when+/// set it also becomes the live session_id so a rename is addressable.+pub fn noteLabels(io: Io, gpa: Allocator, arena: Allocator, title: []const u8, session_base: []const u8) void {+ if (g_own_name == null) return;+ const owned_title = gpa.dupe(u8, title) catch return;+ const owned_base = gpa.dupe(u8, session_base) catch {+ gpa.free(owned_title);+ return;+ };+ if (g_title.len > 0) gpa.free(g_title);+ if (g_session_base.len > 0) gpa.free(g_session_base);+ g_title = owned_title;+ g_session_base = owned_base;+ if (session_base.len > 0) {+ const owned_session = gpa.dupe(u8, session_base) catch {+ writeOwn(io, arena);+ return;+ };+ if (g_session.len > 0) gpa.free(g_session);+ g_session = owned_session;+ }+ writeOwn(io, arena);+}++pub fn noteLabelsFrom(io: Io, gpa: Allocator, arena: Allocator, title: ?[]const u8, session_base: []const u8) void {+ noteLabels(io, gpa, arena, title orelse "", session_base);+}+/// 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@@ -510,38 +512,6 @@ test "roomCursor adopt/reset: resume continues from the saved byte offset" {try std.testing.expectEqual(@as(u64, 0), roomCursor().chan);}-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" {// Windows: the live self-record probes .gone on the runner (OpenProcess on own pid fails there) — skip until diagnosed on a real Windows box.if (builtin.os.tag == .windows) return error.SkipZigTest;diff --git a/src/presence_record.zig b/src/presence_record.zignew file mode 100644index 00000000..4606d02d--- /dev/null+++ b/src/presence_record.zig@@ -0,0 +1,91 @@+//! On-disk presence record: JSON shape, format, parse (#469 / #700).+//!+//! Older/newer graffs tolerate each other via ignore_unknown_fields both+//! ways (a superset write parses down). Missing title/session_base stay+//! empty so pre-#700 files still resolve by id/pid/goal.++const std = @import("std");+const Allocator = std.mem.Allocator;+const worktree_lease = @import("worktree_lease.zig");++const Owner = worktree_lease.Owner;++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,+ title: []const u8 = "",+ session_base: []const u8 = "",+};++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,+ .title = owner.title,+ .session_base = owner.session_base,+ });+ 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,+ .title = rec.title,+ .session_base = rec.session_base,+ };+}++test "presence record round-trips pid, identity, goal, title, and base" {+ 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,+ .title = "Fixing login recovery",+ .session_base = "fixing-login-recovery",+ };+ 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);+ try std.testing.expectEqualStrings(owner.title, back.title);+ try std.testing.expectEqualStrings(owner.session_base, back.session_base);+}++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);+ try std.testing.expectEqualStrings("", forward.title);+ try std.testing.expectEqualStrings("", forward.session_base);+}diff --git a/src/session_run.zig b/src/session_run.zigindex 11d41c87..1df844a9 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -364,6 +364,7 @@ pub fn buildRootAgent(} });}}+ presence.noteLabelsFrom(io, gpa, arena, root.session_title, root.session_name);if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);// #502: --output-schema (inline JSON or @file) → structured outputs.if (flags.output_schema_flag) |schema_arg| {diff --git a/src/worktree_lease.zig b/src/worktree_lease.zigindex 8cc54d5c..371e8eb2 100644--- a/src/worktree_lease.zig+++ b/src/worktree_lease.zig@@ -71,6 +71,10 @@ pub const Owner = struct {/// peer reads to decide whether its work overlaps. Empty when unknown.goal: []const u8 = "",last_seen_ms: i64 = 0,+ /// #700: the human title from `.session.json`. Empty on older records.+ title: []const u8 = "",+ /// #700: durable saved-session file base (slug). Empty on older records.+ session_base: []const u8 = "",};pub const OwnerVerdict = enum {