graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
test(tui): pin markdown idempotence under every chunk boundary
Rach Pradhan39cf1c2a7b80
diff --git a/TUI/markdown_stream_tests.zig b/TUI/markdown_stream_tests.zignew file mode 100644index 00000000..75b800fb--- /dev/null+++ b/TUI/markdown_stream_tests.zig@@ -0,0 +1,300 @@+//! Streaming-markdown conformance: the pager renders assistant prose from the+//! ACCUMULATED text every frame, so a chunked arrival sequence must land on+//! exactly the bytes a one-shot render produces, and every intermediate frame+//! has to be a legal frame on its own.+//!+//! Two properties are pinned here:+//! IDEMPOTENCE — feeding a document in N-byte chunks and rendering after+//! each chunk ends byte-identical to rendering it once.+//! PREFIX SAFETY — every intermediate frame is valid UTF-8, carries no C0+//! control the model smuggled in, never holds a truncated+//! escape sequence, and closes every SGR weight it opened.++const std = @import("std");++const markdown = @import("markdown.zig");+const theme_mod = @import("theme.zig");++/// Documents that exercise every state the renderer threads across lines:+/// fences (closed, open, CRLF, block-comment), tables, nested lists, inline+/// markers (matched and dangling), emoji and CJK.+const fixtures = [_][]const u8{+ // 0 — a closed fence with strings, escapes, numbers and a comment.+ "# Title\nintro text\n```zig\nconst x: u32 = 0x1f; // note\nconst s = \"a\\nb\";\n```\ntail line\n",+ // 1 — a fence that never closes: the stream ended mid-block.+ "before\n```py\ndef f(x):\n return x + 1\n",+ // 2 — CRLF everywhere, fence included.+ "para one\r\n```js\r\nlet a = 1; /* open\r\nstill comment */ let b = 2;\r\n```\r\nafter\r\n",+ // 3 — a pipe table plus a dangling partial row.+ "| Path | What |\n| --- | --- |\n| src/ | the product |\n| `TUI/` | pager |\n",+ // 4 — nested lists, emoji, CJK.+ "- top level 🚀\n - nested 日本語 item\n - another ✓ one\n- back out 中文字\n",+ // 5 — inline markers: matched, dangling, and adjacent.+ "a `code` b **bold** c `open d **half e ``\nsecond **line** with `tick`\n",+ // 6 — emoji and CJK INSIDE a fence, where the lexer walks bytes.+ "```go\nfmt.Println(\"日本語 🚀 done\")\n```\n",+ // 7 — prose carrying raw terminal control the model must never be able to+ // paint with, plus a bare CR mid-line.+ "safe \x1b[31mred?\x1b[0m and \x07bell\rreturn\nnext line\n",+ // 8 — a fence whose info string is a grok citation path.+ "```12:34:src/main.rs\nlet v: Vec<u8> = vec![1, 2, 3];\n```\n",+ // 9 — headings, rules and a fence opened immediately after a table.+ "## Heading\n| a | b |\n|---|---|\n| 1 | 2 |\n```sh\necho \"hi \\\n```\n",+};++fn oneShot(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {+ return markdown.renderThemed(a, src, th, width);+}++/// Walk the frame the way a terminal would and reject anything a live pager+/// could not survive.+fn checkFrame(frame: []const u8) !void {+ try std.testing.expect(std.unicode.utf8ValidateSlice(frame));+ var i: usize = 0;+ var open_bold = false;+ while (i < frame.len) {+ const b = frame[i];+ if (b == 0x1b) {+ const end = theme_mod.skipEsc(frame, i);+ // A truncated escape reaches the terminal as garbage and swallows+ // the glyphs behind it: the last byte must be a real final byte.+ try std.testing.expect(end > i + 1);+ const fin = frame[end - 1];+ try std.testing.expect(fin >= 0x40 and fin <= 0x7e);+ const seq = frame[i..end];+ if (std.mem.eql(u8, seq, theme_mod.bold)) open_bold = true;+ if (std.mem.eql(u8, seq, "\x1b[22m") or std.mem.eql(u8, seq, theme_mod.reset)) open_bold = false;+ i = end;+ continue;+ }+ if (b == '\n') {+ // Weight must not bleed across a row: run.zig pads from whatever+ // state the row left behind.+ try std.testing.expect(!open_bold);+ i += 1;+ continue;+ }+ // \t is legal prose; every other C0 (CR, BEL, NUL…) moves or rings the+ // terminal and must have been filtered out of the model's text.+ try std.testing.expect(b >= 0x20 or b == '\t');+ try std.testing.expect(b != 0x7f);+ i += 1;+ }+ try std.testing.expect(!open_bold);+}++/// Accumulate `src` in `chunk`-byte deltas, rendering after each one, and+/// return the final frame. Every intermediate frame is checked.+fn streamRender(+ a: std.mem.Allocator,+ src: []const u8,+ th: theme_mod.Theme,+ width: usize,+ chunk: usize,+) ![]const u8 {+ var acc = std.array_list.Managed(u8).init(a);+ defer acc.deinit();+ var last: []const u8 = "";+ var i: usize = 0;+ while (i < src.len) {+ const n = @min(chunk, src.len - i);+ try acc.appendSlice(src[i .. i + n]);+ i += n;+ last = try markdown.renderThemed(a, acc.items, th, width);+ try checkFrame(last);+ }+ return last;+}++test "idempotence: chunked arrival lands on the one-shot render" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ for ([_]theme_mod.Id{ .night, .day }) |id| {+ const th = theme_mod.of(id);+ for (fixtures) |src| {+ const want = try oneShot(a, src, th, 60);+ try checkFrame(want);+ var chunk: usize = 1;+ while (chunk <= 7) : (chunk += 1) {+ const got = try streamRender(a, src, th, 60, chunk);+ try std.testing.expectEqualStrings(want, got);+ }+ }+ }+}++test "prefix safety: a split at EVERY byte boundary renders a legal frame" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ for (fixtures) |src| {+ const want = try oneShot(a, src, th, 48);+ var k: usize = 0;+ while (k <= src.len) : (k += 1) {+ // The rolling window: the model stopped exactly here.+ const head = try markdown.renderThemed(a, src[0..k], th, 48);+ try checkFrame(head);+ // …and then the rest arrives in one go.+ const settled = try markdown.renderThemed(a, src, th, 48);+ try std.testing.expectEqualStrings(want, settled);+ }+ _ = arena.reset(.retain_capacity);+ }+}++test "a glyph split across chunks never leaves replacement garbage" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ const src = "emoji 🚀 and 日本語 text";+ var k: usize = 0;+ while (k <= src.len) : (k += 1) {+ const head = try markdown.renderThemed(a, src[0..k], th, 40);+ // Valid UTF-8 at every boundary: a half-written glyph is HELD BACK+ // until its tail arrives rather than painted as U+FFFD.+ try std.testing.expect(std.unicode.utf8ValidateSlice(head));+ }+ const full = try markdown.renderThemed(a, src, th, 40);+ try std.testing.expect(std.mem.indexOf(u8, full, "🚀") != null);+ try std.testing.expect(std.mem.indexOf(u8, full, "日本語") != null);+}++test "CRLF: a carriage return never reaches the frame" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ const out = try markdown.renderThemed(a, "alpha\r\nbeta\r\n```zig\r\nconst x = 1;\r\n```\r\n", th, 40);+ try std.testing.expect(std.mem.indexOfScalar(u8, out, '\r') == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "alpha") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "const") != null);+ // A CR line ending must not survive as a visible column either.+ var it = std.mem.splitScalar(u8, out, '\n');+ while (it.next()) |ln| try std.testing.expect(theme_mod.visibleLen(ln) <= 40);+}++test "model text cannot smuggle its own SGR or cursor control into the frame" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ const out = try markdown.renderThemed(a, "hi \x1b[2Jwiped \x1b[38;2;255;0;0mred\x1b[0m done", th, 40);+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[2J") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[38;2;255;0;0m") == null);+ // The literal parameter bytes must not be left behind as text either.+ try std.testing.expect(std.mem.indexOf(u8, out, "[2J") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "wiped") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "done") != null);+ // A truncated escape at the very end of a delta is dropped whole — no+ // half-sequence on the wire, no leftover parameter bytes as text.+ const cut = try markdown.renderThemed(a, "tail \x1b[9987", th, 40);+ try std.testing.expect(std.mem.indexOf(u8, cut, "9987") == null);+ try std.testing.expect(std.mem.indexOf(u8, cut, "tail") != null);+ try checkFrame(cut);+}++test "an unterminated fence renders as tentative code and settles when it closes" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ const syntax = @import("syntax.zig");+ const bg = syntax.codeBg(false);+ const open = try markdown.renderThemed(a, "```zig\nconst x = 1;", th, 40);+ try std.testing.expect(std.mem.indexOf(u8, open, bg) != null); // already code+ const closed = try markdown.renderThemed(a, "```zig\nconst x = 1;\n```\nafter", th, 40);+ // The code row is byte-identical before and after the fence closes: the+ // block settles, it does not re-render differently.+ const open_row = std.mem.sliceTo(open[std.mem.indexOf(u8, open, bg).?..], '\n');+ const closed_row = std.mem.sliceTo(closed[std.mem.indexOf(u8, closed, bg).?..], '\n');+ try std.testing.expectEqualStrings(open_row, closed_row);+}++test "highlighting state is per BLOCK, not per chunk" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ const syntax = @import("syntax.zig");+ const comment = syntax.color(.comment, false);+ // The block comment opens on one line and closes on the next; the lexer+ // must carry that across the line break no matter how the bytes arrived.+ const src = "```js\nlet a = 1; /* open\nstill inside\n*/ let b = 2;\n```\n";+ const want = try markdown.renderThemed(a, src, th, 60);+ try std.testing.expect(std.mem.indexOf(u8, want, comment) != null);+ var chunk: usize = 1;+ while (chunk <= 5) : (chunk += 1) {+ const got = try streamRender(a, src, th, 60, chunk);+ try std.testing.expectEqualStrings(want, got);+ }+ // A SECOND fence restarts the lexer: an open block comment in the first+ // one must not colour the second one's first line.+ const two = try markdown.renderThemed(a, "```js\n/* open\n```\n```js\nlet c = 3;\n```\n", th, 60);+ var rows = std.mem.splitScalar(u8, two, '\n');+ var body: []const u8 = "";+ while (rows.next()) |ln| {+ // The last banded row is the second fence's only code line; its tokens+ // are SGR-separated, so match on the band, not on the text.+ if (std.mem.indexOf(u8, ln, syntax.codeBg(false)) != null) body = ln;+ }+ try std.testing.expect(body.len > 0);+ try std.testing.expect(std.mem.indexOf(u8, body, comment) == null);+ try std.testing.expect(std.mem.indexOf(u8, body, syntax.color(.keyword, false)) != null);+}++test "inline emphasis split across chunks stays literal, then settles" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const th = theme_mod.of(.night);+ // Half a marker pair is TEXT: it must not open a weight that then runs on+ // into the rest of the message.+ for ([_][]const u8{ "a **bol", "a **bold*", "a `open", "a *" }) |half| {+ const frame = try markdown.renderThemed(a, half, th, 40);+ try std.testing.expect(std.mem.indexOf(u8, frame, theme_mod.bold) == null);+ try checkFrame(frame);+ }+ // The closing marker arrives and the span settles into a closed weight.+ const done = try markdown.renderThemed(a, "a **bold** b", th, 40);+ try std.testing.expect(std.mem.indexOf(u8, done, theme_mod.bold) != null);+ try std.testing.expect(std.mem.indexOf(u8, done, "\x1b[22m") != null);+ try checkFrame(done);+ // …and the marker itself is gone, not left on screen.+ try std.testing.expect(std.mem.indexOf(u8, done, "**") == null);+}++test "end to end: hostile assistant prose cannot corrupt a transcript row" {+ const app = @import("app.zig");+ const scrollback = @import("scrollback.zig");+ var m: app.Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.assistant, "row one\rWIPED \x1b[2J\x1b[38;2;255;0;0mred\r\n```zig\r\nconst x = 1; // 日本語 🚀\r\n```\r\ndone");+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const frame = try scrollback.render(&m, arena.allocator(), 40, 0);+ try std.testing.expect(std.mem.indexOfScalar(u8, frame, '\r') == null);+ try std.testing.expect(std.mem.indexOf(u8, frame, "\x1b[2J") == null);+ try std.testing.expect(std.mem.indexOf(u8, frame, "\x1b[38;2;255;0;0m") == null);+ try std.testing.expect(std.unicode.utf8ValidateSlice(frame));+ try std.testing.expect(std.mem.indexOf(u8, frame, "日本語") != null);+ var it = std.mem.splitScalar(u8, frame, '\n');+ while (it.next()) |ln| try std.testing.expect(theme_mod.visibleLen(ln) <= 40);+}++test "renderUser is chunk-safe too" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const src = "look at \x1b[31m@[/tmp/a.png]\r /goal 日本語 🚀";+ var k: usize = 0;+ while (k <= src.len) : (k += 1) {+ const head = try markdown.renderUser(a, src[0..k], theme_mod.emerald, theme_mod.zinc200);+ try std.testing.expect(std.unicode.utf8ValidateSlice(head));+ try std.testing.expect(std.mem.indexOfScalar(u8, head, '\r') == null);+ try std.testing.expect(std.mem.indexOf(u8, head, "[31m") == null);+ }+}diff --git a/TUI/root.zig b/TUI/root.zigindex 3349e7a1..3ab4dccf 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -64,6 +64,7 @@ test {_ = @import("chrome.zig");_ = @import("models.zig");_ = @import("markdown.zig");+ _ = @import("markdown_stream_tests.zig");_ = @import("syntax.zig");_ = @import("dump.zig");_ = @import("effort.zig");diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 9ca8730d..25d02a54 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -242,6 +242,12 @@ if wanted tuiguard; thenif python3 scripts/test-tui-typed-events.py zig-out/bin/graff; then :; elserecord_fail tuiguardfi+ # Streaming markdown: the answer arrives as 1-3 codepoint deltas whose+ # boundaries land mid-escape, mid-fence and mid-marker. Both the live tail+ # and the settled row must be free of the model's own CR/SGR bytes.+ if python3 scripts/test-tui-stream-markdown.py zig-out/bin/graff; then :; else+ record_fail tuiguard+ fififidiff --git a/scripts/test-tui-stream-markdown.py b/scripts/test-tui-stream-markdown.pynew file mode 100644index 00000000..7ac974a9--- /dev/null+++ b/scripts/test-tui-stream-markdown.py@@ -0,0 +1,343 @@+#!/usr/bin/env python3+"""Live proof: the fullscreen TUI's markdown pipeline is safe under STREAMING.++Against the real binary, under a pty, with a mock codex backend that streams the+answer as `response.output_text.delta` events split every 1-3 codepoints — so+the splits land mid-word, mid-escape-sequence, mid-code-fence and mid-inline+marker — the probe photographs the screen TWICE:++ * mid-turn, while a slow tool runs, so the PENDING row's live tail is showing+ raw model bytes as they arrive, and+ * after the turn, when the assistant row has settled through the markdown+ renderer.++Both frames must be clean: no carriage return the model sent (a bare CR rewinds+the row and everything after it overwrites), none of the model's OWN escape+sequences (a smuggled SGR repaints the pager), no U+FFFD from a delta that cut a+glyph in half, and no text lost around any of it. The settled frame must also+show the fenced block as code with its markers hidden.++Usage: python3 scripts/test-tui-stream-markdown.py [path/to/graff]+Exit 0 = pass. Skips (exit 0, notice) with no pty support or no binary.+"""++from __future__ import annotations++import json+import os+import re+import sys+import tempfile+import time++from codex_ws_mock import CodexMock, RecordedRequest++BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")+BOOT_MAX = 20.0+ANSWER_MAX = 30.0+ROWS, COLS = 40, 110++# A colour no graff theme paints, so finding it on the wire can only mean the+# model's own escape survived the renderer.+SMUGGLED = "\x1b[38;2;7;7;7m"+# Streamed as deltas and shown by the PENDING row's live tail while a tool runs.+# The hostile bytes sit in the last four lines — that is the tail window.+LIVE = (+ "STREAMMD_START\r\n"+ "padding prose line\r\n"+ "wiped" + SMUGGLED + "byte and a bare\rreturn\r\n"+ "日本語 \U0001f680 STREAMMD_LIVE\r\n"+)+# The settled assistant row, rendered through the markdown pipeline.+ANSWER = (+ "Here is **bold** and `code` with 日本語 \U0001f680.\r\n"+ "\r\n"+ "```zig\r\n"+ "const answer: u32 = 0x1f; // 日本語 \U0001f680\r\n"+ "```\r\n"+ "wiped" + SMUGGLED + "byte and a bare\rreturn\r\n"+ "STREAMMD_OK\r\n"+)+++def deltas(text: str) -> list[dict]:+ """Cut the text into 1-3 codepoint deltas — the finest split a JSON event+ stream can express. Boundaries land mid-word, mid-escape-sequence, mid-fence+ and mid-inline-marker. (A split INSIDE a UTF-8 sequence is a transport-level+ event a JSON string cannot carry; the unit suite fuzzes that byte-wise.)"""+ out, i, n = [], 0, 1+ while i < len(text):+ piece = text[i : i + n]+ i += n+ n = n % 3 + 1+ out.append({"type": "response.output_text.delta", "delta": piece})+ return out+++def completed(response_id: str) -> dict:+ return {+ "type": "response.completed",+ "response": {+ "id": response_id,+ "usage": {+ "input_tokens": 10,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 10,+ "total_tokens": 20,+ },+ },+ }+++def events(request: RecordedRequest) -> list[dict]:+ if request.ordinal == 1:+ # Prose first, then a slow tool call: the turn stays open long enough to+ # photograph the live tail, which is where raw model bytes land.+ return [+ *deltas(LIVE),+ {+ "type": "response.output_item.done",+ "item": {+ "type": "function_call",+ "id": "fc_streammd",+ "call_id": "call_streammd",+ "name": "bash",+ "arguments": json.dumps({"command": "sleep 6"}),+ "status": "completed",+ },+ },+ completed("resp_streammd_live"),+ ]+ item = {+ "type": "message",+ "id": "msg_streammd",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": ANSWER, "annotations": []}],+ }+ return [+ *deltas(ANSWER),+ {"type": "response.output_item.done", "item": item},+ completed("resp_streammd_done"),+ ]+++def drain(fd, seconds):+ import select++ out = b""+ end = time.time() + seconds+ while time.time() < end:+ r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))+ if not r:+ continue+ try:+ chunk = os.read(fd, 65536)+ except OSError:+ break+ if not chunk:+ break+ out += chunk+ return out+++def resize(fd, rows, cols):+ import fcntl+ import struct+ import termios++ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))+++def boot(fd):+ out = b""+ end = time.time() + BOOT_MAX+ while time.time() < end:+ out += drain(fd, 0.3)+ if b"\x1b[?1049h" in out:+ return out + drain(fd, 1.5)+ return out+++def wait_for(fd, needle, seconds):+ out = b""+ end = time.time() + seconds+ while time.time() < end:+ out += drain(fd, 0.3)+ if needle.encode() in out:+ return out+ return None+++def spawn(cwd, env_extra, unset):+ import pty++ pid, fd = pty.fork()+ if pid == 0:+ os.chdir(cwd)+ for name in unset:+ os.environ.pop(name, None)+ os.environ.update(env_extra)+ os.execv(BIN, [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"])+ resize(fd, ROWS, COLS)+ return pid, fd+++def reap(pid, fd):+ import signal++ try:+ os.write(fd, b"\x11") # Ctrl+Q+ drain(fd, 2.0)+ except OSError:+ pass+ for call in (lambda: os.kill(pid, signal.SIGKILL), lambda: os.waitpid(pid, 0)):+ try:+ call()+ except OSError:+ pass+++def full_frame(fd):+ """The bytes of one FORCED full repaint, plus its visible rows."""+ resize(fd, ROWS - 1, COLS)+ drain(fd, 0.4)+ resize(fd, ROWS, COLS)+ stream = drain(fd, 1.5)+ parts = stream.rsplit(b"\x1b[2J\x1b[H", 1)+ if len(parts) < 2:+ return None, None+ raw = parts[1]+ text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", raw)+ text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)+ return raw, [ln.decode(errors="replace") for ln in text.split(b"\r\n")]+++def workspace(tmp, port):+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump({"tokens": {"access_token": "streammd-mock", "account_id": "acct-md"}}, fh)+ harness = os.path.join(tmp, ".harness")+ os.makedirs(harness)+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)+ empty_mcp = os.path.join(tmp, "empty-mcp.json")+ with open(empty_mcp, "w", encoding="utf-8") as fh:+ fh.write('{"mcpServers": {}}')+ env = {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_MCP_CONFIG": empty_mcp,+ "GRAFF_LEARN_AUTO": "off",+ }+ unset = tuple(+ name+ for name in os.environ+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")+ and name not in env+ )+ return env, unset+++def hostile_clean(raw, body, where):+ """The three ways raw model bytes corrupt a row, checked on one frame."""+ # 1. no carriage return the model sent — the pager's own row breaks are+ # \r\n (doubled to \r\r\n by the pty's ONLCR), so a CR that does not lead+ # into a line feed can only have come from the model's text.+ if re.search(rb"\r(?!\r*\n)", raw):+ return f"{where}: a bare carriage return from the model reached the frame"+ # 2. none of the model's own escapes, as bytes or as leftover text.+ if SMUGGLED.encode() in raw:+ return f"{where}: the model's own SGR escape reached the terminal"+ if "[38;2;7;7;7m" in body:+ return f"{where}: the model's escape landed as literal text instead"+ # 3. every glyph whole on both sides of a delta boundary.+ if "�" in body:+ return f"{where}: a delta boundary left a replacement character on screen"+ for glyph in ("日本語", "\U0001f680"):+ if glyph not in body:+ return f"{where}: {glyph!r} did not survive the stream"+ if "wiped" not in body or "byte and a bare" not in body:+ return f"{where}: text around the smuggled escape was lost"+ return None+++def check_live(raw, rows):+ body = "\n".join(rows)+ if "STREAMMD_LIVE" not in body:+ return f"the live tail never showed the streamed prose: {rows[:12]!r}"+ return hostile_clean(raw, body, "live tail")+++def check_settled(raw, rows):+ body = "\n".join(rows)+ if "STREAMMD_OK" not in body:+ return f"the streamed answer never settled on screen: {rows[:12]!r}"+ err = hostile_clean(raw, body, "settled row")+ if err:+ return err+ # 4. the fence rendered as code: tokens on screen, markers hidden.+ if "const answer" not in body.replace(" ", " "):+ return "the fenced code line never rendered"+ if "```" in body:+ return "a raw fence marker leaked onto the screen"+ return None+++def run():+ mock = CodexMock(events_for_request=events)+ port = mock.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-stream-md-") as tmp:+ env, unset = workspace(tmp, port)+ pid, fd = spawn(tmp, env, unset)+ try:+ boot(fd)+ os.write(fd, b"stream some markdown\r")+ # Mid-turn: the tool is sleeping, so the live tail is on screen.+ if wait_for(fd, "STREAMMD_LIVE", ANSWER_MAX) is None:+ return "the live tail never showed the streamed prose"+ raw, rows = full_frame(fd)+ if rows is None:+ return "no full repaint to read the live tail from"+ err = check_live(raw, rows)+ if err:+ return err+ # …and then the settled assistant row.+ if wait_for(fd, "STREAMMD_OK", ANSWER_MAX) is None:+ return "the turn never produced its streamed answer"+ drain(fd, 1.0)+ raw, rows = full_frame(fd)+ if rows is None:+ return "no full repaint to read the settled row from"+ return check_settled(raw, rows)+ finally:+ reap(pid, fd)+ finally:+ mock.stop()+++def main():+ if not os.path.exists(BIN):+ print(f"tui-stream-markdown: {BIN} not built — skipping")+ return 0+ try:+ import pty # noqa: F401+ except ImportError:+ print("tui-stream-markdown: no pty support here — skipping")+ return 0+ err = run()+ if err:+ print(f" ✗ stream markdown: {err}")+ return 1+ print(" ✓ stream markdown: live tail AND settled row survive chunked deltas — no CR, no smuggled SGR, glyphs whole")+ return 0+++if __name__ == "__main__":+ sys.exit(main())