graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
test(peer): pin the #469 block bracket as an event sequence + PTY delivery smoke
Rach Pradhan752ff092e3ea
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3ba893ad..6fba4ea2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -28,10 +28,17 @@ jobs:with:node-version: 22- - name: TypeScript SDK validation+ - uses: oven-sh/setup-bun@v2++ - name: TypeScript SDK test, typecheck, build, and package smoke+ working-directory: sdk/tsrun: |- node -e "JSON.parse(require('fs').readFileSync('sdk/ts/package.json','utf8')); console.log('package.json ok')"- node --experimental-strip-types -e "import('./sdk/ts/harness.ts').then(m => { if (!m.Harness || !m.runAgent || !m.MODELS) throw new Error('missing exports'); console.log('ts sdk ok:', m.MODELS.length, 'models'); })"+ npm install --ignore-scripts+ bun test+ npm run typecheck+ npm run build+ npm pack --dry-run+ node -e "import('./dist/harness.js').then(m => { if (!m.Harness || !m.runAgent || !m.MODELS) throw new Error('missing exports'); console.log('ts sdk ok:', m.MODELS.length, 'models'); })"# Zig build / fmt / test + SDK drift, pinned to the exact 0.17 dev build the# codebase targets.@@ -76,8 +83,10 @@ jobs:- name: Concurrent operational trace isolation and JSONL integrityrun: python3 scripts/test-run-isolation.py zig-out/bin/graff- - name: JSON live-control protocol test- run: python3 scripts/test-json-controls.py zig-out/bin/graff+ - name: JSON live-control and mid-turn cancellation tests+ run: |+ python3 scripts/test-json-controls.py zig-out/bin/graff+ python3 scripts/test-json-cancel.py zig-out/bin/graff- name: Isolated read-only review regressionrun: python3 scripts/test-review-mode.py zig-out/bin/graff@@ -136,6 +145,9 @@ jobs:- name: PTY /goal autonomous collapse wiring testrun: python3 scripts/test-pty-goal-loop.py zig-out/bin/graff+ - name: PTY peer-channel delivery smoke test (#469)+ run: python3 scripts/test-pty-peer-channel.py zig-out/bin/graff+- name: AI title and first turn run in parallelrun: python3 scripts/test-title-parallel.py zig-out/bin/graffdiff --git a/scripts/test-pty-peer-channel.py b/scripts/test-pty-peer-channel.pynew file mode 100644index 00000000..981baeef--- /dev/null+++ b/scripts/test-pty-peer-channel.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Real-PTY smoke test for the #469 peer-message delivery pipeline.++A device-room broadcast planted while the session sits at the prompt must+render as a [peer message from ...] line during the next turn's first step+boundary. This pins the end-to-end plumbing (chan-all.jsonl -> drainDevice ->+deliverInbound -> session_notice), which no unit test reaches.++It deliberately does NOT assert the blank-line bracket: a rendered PTY+transcript cannot attribute a blank line to the drain (the turn card, tool-row+groups, and stream lead-in all emit their own blanks depending on position),+so that assertion false-passes on pre-fix builds. The bracket is pinned+deterministically by the renderPeerBlock unit test in src/peer_channel.zig.++The injected line rides the device room: from_user + unaddressed is heard by+every session, and the room's fixed name needs no identity hash. The isolated+HOME makes that room private to this test, so nothing here reaches real peer+sessions. The title request is answered by content match — it races the first+turn call, so it must not consume a scripted reply.+"""++import json+import os+import sys+import tempfile+import time++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "eval"))++from mock_model import ScriptedModel # noqa: E402+from pty_harness import PtySession, terminal_text # noqa: E402+++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg++PEER_LINE = "[peer message from session-fake-peer"+TITLE_MARK = "You summarize what a coding session is about"+++class TitleAwareModel(ScriptedModel):+ """Script the turn replies; answer title calls out of band so the title+ race can never eat a scripted turn reply."""++ def next_reply(self, body):+ messages = body.get("messages", [])+ if any(TITLE_MARK in str(m.get("content", "")) for m in messages):+ return {"text": "spacing probe session"}+ return super().next_reply(body)+++def main() -> None:+ model = TitleAwareModel([{"text": "mock reply"}], exhausted_text="mock reply")+ model.start(1234)+ try:+ with tempfile.TemporaryDirectory(prefix="graff-pty-peer-") as tmp:+ home = os.path.join(tmp, "home")+ repo = os.path.join(tmp, "repo")+ os.makedirs(repo)+ os.system(f"git init -q {repo}")+ env = {+ "HOME": home,+ "CODEGRAFF_API_KEY": "local-pty-test",+ "LMSTUDIO_API_KEY": "local-pty-test",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_NO_SMOLIFY": "1",+ }+ with PtySession(+ GRAFF,+ ["--model", "lmstudio", "--yolo"],+ cwd=repo,+ env=env,+ unset_env=("CODEX_HOME", "NO_COLOR"),+ timeout=25.0,+ ) as session:+ session.wait_for_literal("] ›")++ live = os.path.join(home, ".graff", "live")+ deadline = time.time() + 10+ while not os.path.isdir(live) and time.time() < deadline:+ time.sleep(0.1)+ assert os.path.isdir(live), "presence registry never appeared"++ cursor = len(session.raw)+ with open(os.path.join(live, "chan-all.jsonl"), "a") as fh:+ fh.write(json.dumps({+ "from_pid": 999999, "from_start": 1,+ "from_session": "session-fake-peer", "from_goal": "",+ "to": "", "ts_ms": int(time.time() * 1000),+ "text": "spacing probe", "from_user": True,+ }) + "\n")+ session.send_line("hi")+ end = session.wait_for_literal("mock reply", start=cursor)+ session.pump_for(0.5)++ rendered = terminal_text(bytes(session.raw[cursor:end]))+ lines = rendered.split("\n")+ idx = next(+ (i for i, l in enumerate(lines) if PEER_LINE in l), None+ )+ assert idx is not None, (+ "peer block never rendered\n--- transcript ---\n" + rendered+ )+ print("ok: device-room broadcast renders as a peer line mid-session")+ finally:+ model.stop()+++if __name__ == "__main__":+ main()diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex 2f161a9b..8fa3d309 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -219,25 +219,26 @@ pub fn deliverInbound(root: *Agent) void {if (deviceHears(m, own)) heard.append(root.arena, m) catch break else skipped += 1;}device_msgs = heard.items;- // A blank line of air on either side of the visible block: peer lines+ // The visible block gets one blank line of air on either side: peer lines// land mid-stream at a step boundary and used to butt straight against// the assistant text above and whatever follows below — one clump.const window = displayWindow(is_backlog_drain, local_msgs.len + device_msgs.len);const any_visible = local_msgs.len + device_msgs.len > window.start or(repl.g_debug and (note != null or omitted > 0 or skipped > 0 or window.hidden > 0));- if (any_visible) sink.emit(root.io, .{ .session_notice = .{ .text = "", .tone = .plain } });var buf: std.ArrayList(u8) = .empty;+ // Debug-only notices ride inside the block's bracket, in drain order.+ var markers: std.ArrayList([]const u8) = .empty;if (note) |n| {buf.appendSlice(root.arena, n) catch {};buf.append(root.arena, '\n') catch {};- if (repl.g_debug) sink.emit(root.io, .{ .session_notice = .{ .text = n, .tone = .plain } });+ if (repl.g_debug) markers.append(root.arena, n) catch {};}if (omitted > 0) {const marker = std.fmt.allocPrint(root.arena, "[#469 channel: {d} older message(s) predating this session omitted]", .{omitted}) catch "";if (marker.len > 0) {buf.appendSlice(root.arena, marker) catch {};buf.append(root.arena, '\n') catch {};- if (repl.g_debug) sink.emit(root.io, .{ .session_notice = .{ .text = marker, .tone = .plain } });+ if (repl.g_debug) markers.append(root.arena, marker) catch {};}}if (skipped > 0) {@@ -245,7 +246,7 @@ pub fn deliverInbound(root: *Agent) void {if (marker.len > 0) {buf.appendSlice(root.arena, marker) catch {};buf.append(root.arena, '\n') catch {};- if (repl.g_debug) sink.emit(root.io, .{ .session_notice = .{ .text = marker, .tone = .plain } });+ if (repl.g_debug) markers.append(root.arena, marker) catch {};}}var lines: std.ArrayList([]const u8) = .empty;@@ -266,11 +267,9 @@ pub fn deliverInbound(root: *Agent) void {// text. Live incremental drains render every line — those are new.if (window.hidden > 0) {const marker = std.fmt.allocPrint(root.arena, "[#469 channel: {d} backlog message(s) delivered to context — showing last {d}]", .{ window.hidden, backlog_repl_show }) catch "";- if (marker.len > 0 and repl.g_debug) sink.emit(root.io, .{ .session_notice = .{ .text = marker, .tone = .plain } });+ if (marker.len > 0 and repl.g_debug) markers.append(root.arena, marker) catch {};}- for (lines.items[window.start..]) |line|- sink.emit(root.io, .{ .session_notice = .{ .text = line, .tone = .plain } });- if (any_visible) sink.emit(root.io, .{ .session_notice = .{ .text = "", .tone = .plain } });+ renderPeerBlock(sink, root.io, any_visible, markers.items, lines.items[window.start..]);if (buf.items.len == 0) return;buf.appendSlice(root.arena, "(reply with the peer_message tool — queued, one-way; everyone here hears it)") catch {};var obj: std.json.ObjectMap = .empty;@@ -279,6 +278,20 @@ pub fn deliverInbound(root: *Agent) void {root.messages.append(.{ .object = obj }) catch {};}+/// Emit the drain's visible half as one bracketed unit: a blank notice, the+/// debug markers and peer lines in drain order, a closing blank. Nothing at+/// all when nothing is visible — a drain that only refreshed history must not+/// paint. Pure aside from the sink, so the bracketing is unit-testable+/// without a live presence registry (a PTY transcript can't tell the fix's+/// blanks apart from a neighbor's, the event sequence can).+fn renderPeerBlock(sink: engine_sink.EngineSink, io: Io, any_visible: bool, markers: []const []const u8, lines: []const []const u8) void {+ if (!any_visible) return;+ sink.emit(io, .{ .session_notice = .{ .text = "", .tone = .plain } });+ for (markers) |m| sink.emit(io, .{ .session_notice = .{ .text = m, .tone = .plain } });+ for (lines) |l| sink.emit(io, .{ .session_notice = .{ .text = l, .tone = .plain } });+ sink.emit(io, .{ .session_notice = .{ .text = "", .tone = .plain } });+}+/// /tell <session|all> <text…>: the user's line into the channel. `all` (or a/// target in another folder) rides the device-wide room — every live session/// hears it; a local target stays on the worktree room.@@ -536,3 +549,35 @@ test "displayWindow: only a backlog drain is windowed, to its trailing lines" {// A longer backlog prints only the tail; the rest is context-only.try std.testing.expectEqualDeep(DisplayWindow{ .start = 8, .hidden = 8 }, displayWindow(true, 10));}++fn recordNoticeText(ctx: *anyopaque, ev: engine_sink.Stamped) void {+ const rec: *std.ArrayList([]const u8) = @ptrCast(@alignCast(ctx));+ if (ev.event == .session_notice)+ rec.append(std.testing.allocator, ev.event.session_notice.text) catch {};+}++test "renderPeerBlock: blank notices bracket the block; silence when nothing is visible" {+ // emit(undefined, ...) is sound only while json_mode is false (no lock+ // taken): pin it so a leaky earlier test can never turn this into UB.+ const main_mod = @import("main.zig");+ const protocol_seq = @import("protocol_seq.zig");+ const saved_json = main_mod.json_mode;+ main_mod.json_mode = false;+ defer main_mod.json_mode = saved_json;+ protocol_seq.resetForTest();+ defer protocol_seq.resetForTest();+ var rec: std.ArrayList([]const u8) = .empty;+ defer rec.deinit(std.testing.allocator);+ const vt: engine_sink.VTable = .{ .emit = recordNoticeText, .durable = false };+ const sink: engine_sink.EngineSink = .{ .ctx = &rec, .vt = &vt };+ const markers = [_][]const u8{"[#469 presence] 1 other live session"};+ const lines = [_][]const u8{ "[peer message from a — #469 channel]: one", "[peer message from b — #469 channel]: two" };+ renderPeerBlock(sink, undefined, true, &markers, &lines);+ try std.testing.expectEqualDeep(&[_][]const u8{+ "", "[#469 presence] 1 other live session", lines[0], lines[1], "",+ }, rec.items);+ // A history-only drain paints nothing — no stray blank pair.+ rec.clearRetainingCapacity();+ renderPeerBlock(sink, undefined, false, &markers, &lines);+ try std.testing.expectEqual(@as(usize, 0), rec.items.len);+}