graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
test(tui): live proofs for the scroll gutter and the OSC 52 copy, gated in tier 1
Rach Pradhanf94b59554f51
diff --git a/TUI/scrollbar_tests.zig b/TUI/scrollbar_tests.zignew file mode 100644index 00000000..ce85395b--- /dev/null+++ b/TUI/scrollbar_tests.zig@@ -0,0 +1,312 @@+//! The scroll gutter and the OSC 52 clipboard channel, driven through the REAL+//! model — render.zig composing frames, keys.zig moving the viewport,+//! selection.zig capturing a drag — rather than through hand-written frames.+//!+//! Both features are post-passes over a composed frame, and both are only+//! honest if the composer, the painter and the capture agree about which rows+//! they own. That agreement is what these tests hold.++const std = @import("std");++const app = @import("app.zig");+const engine = @import("engine.zig");+const glyphs = @import("glyphs.zig");+const keys = @import("keys.zig");+const osc52 = @import("osc52.zig");+const paint_mod = @import("paint.zig");+const render_mod = @import("render.zig");+const scrollbar = @import("scrollbar.zig");+const selection = @import("selection.zig");+const theme_mod = @import("theme.zig");+const Model = app.Model;++const testing = std.testing;+const W: usize = 60;+const H: usize = 20;++fn longTranscript(m: *Model) !void {+ var buf: [64]u8 = undefined;+ for (0..40) |i| {+ const s = try std.fmt.bufPrint(&buf, "transcript row {d} with a little body text", .{i});+ try m.push(.assistant, s);+ }+}++fn frameAt(m: *Model, now_ms: u64) ![]const u8 {+ return render_mod.render(m, testing.allocator, W, H, now_ms);+}++/// Rows carrying the thumb, and the column it landed on.+const Marks = struct { rows: std.array_list.Managed(usize), col: usize };++fn marks(a: std.mem.Allocator, frame: []const u8) !Marks {+ var out = Marks{ .rows = std.array_list.Managed(usize).init(a), .col = 0 };+ var row: usize = 0;+ var it = std.mem.splitScalar(u8, frame, '\n');+ while (it.next()) |ln| : (row += 1) {+ const at = std.mem.indexOf(u8, ln, glyphs.scroll_thumb) orelse continue;+ try out.rows.append(row);+ out.col = theme_mod.visibleLen(ln[0..at]);+ }+ return out;+}++test "scrolling a real transcript raises a thumb inside the viewport" {+ const a = testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try longTranscript(&m);++ // Parked at the tail, nothing has scrolled yet: no gutter.+ const tail = try frameAt(&m, 1_000);+ defer a.free(tail);+ try testing.expect(std.mem.indexOf(u8, tail, glyphs.scroll_thumb) == null);++ // Scroll up. The thumb has to be inside the band, on the LAST column, and+ // the same number of rows the geometry says.+ keys.scrollBy(&m, 9);+ const up = try frameAt(&m, 1_000);+ defer a.free(up);+ const got = try marks(ar, up);+ try testing.expect(got.rows.items.len > 0);+ try testing.expectEqual(W - 1, got.col);+ const t = scrollbar.current(&m).?;+ try testing.expectEqual(t.len, got.rows.items.len);+ try testing.expectEqual(m.band.top + t.top, got.rows.items[0]);+ try testing.expect(got.rows.items[got.rows.items.len - 1] < m.band.top + m.band.len);+ // Contiguous — a gutter with a hole in it is a bug, not a style.+ for (got.rows.items, 0..) |r, i| try testing.expectEqual(got.rows.items[0] + i, r);+ // Every marked row still measures exactly the terminal width, so the+ // painter's full/short branch sees what it expects.+ var it = std.mem.splitScalar(u8, up, '\n');+ var row: usize = 0;+ while (it.next()) |ln| : (row += 1) {+ if (std.mem.indexOf(u8, ln, glyphs.scroll_thumb) == null) continue;+ try testing.expectEqual(W, theme_mod.visibleLen(ln));+ }+}++test "the thumb travels down the track as the viewport approaches the tail" {+ const a = testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try longTranscript(&m);+ const far = try frameAt(&m, 1_000); // lays down the band+ a.free(far);++ keys.scrollBy(&m, 30);+ const high = try frameAt(&m, 1_000);+ defer a.free(high);+ keys.scrollBy(&m, -20);+ const low = try frameAt(&m, 1_000);+ defer a.free(low);++ const h = try marks(ar, high);+ const l = try marks(ar, low);+ try testing.expect(h.rows.items.len > 0 and l.rows.items.len > 0);+ // Scrolled back TOWARD the tail: the thumb moved down, never up.+ try testing.expect(l.rows.items[0] > h.rows.items[0]);+}++test "back at the tail the gutter fades, and the row repaints clean" {+ const a = testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try longTranscript(&m);+ const before = try frameAt(&m, 1_000);+ defer a.free(before);+ try testing.expect(std.mem.indexOf(u8, before, glyphs.scroll_thumb) == null);++ keys.scrollBy(&m, 8);+ const banded = try frameAt(&m, 1_000);+ defer a.free(banded);+ try testing.expect(std.mem.indexOf(u8, banded, glyphs.scroll_thumb) != null);++ // Back to the tail. Inside the fade window it lingers...+ keys.scrollBy(&m, -8);+ const lingering = try frameAt(&m, 1_000);+ defer a.free(lingering);+ try testing.expect(std.mem.indexOf(u8, lingering, glyphs.scroll_thumb) != null);+ // ...and past it the frame is byte-for-byte the one before any of this.+ const clean = try frameAt(&m, 1_000 + scrollbar.fade_ms);+ defer a.free(clean);+ try testing.expect(std.mem.indexOf(u8, clean, glyphs.scroll_thumb) == null);+ try testing.expectEqualStrings(before, clean);++ // The painter's side of the promise: a diff paint from the gutter frame to+ // the clean one rewrites exactly the rows the thumb was on, and a FORCED+ // full repaint of the clean frame carries no thumb either — so the two+ // paths agree about what the screen shows.+ const diff = try paintTo(ar, clean, banded, false);+ try testing.expect(std.mem.indexOf(u8, diff, glyphs.scroll_thumb) == null);+ const had = try marks(ar, banded);+ var buf: [16]u8 = undefined;+ for (had.rows.items) |r| {+ const cup = try std.fmt.bufPrint(&buf, "\x1b[{d};1H", .{r + 1});+ try testing.expect(std.mem.indexOf(u8, diff, cup) != null);+ }+ const full = try paintTo(ar, clean, clean, true);+ try testing.expect(std.mem.indexOf(u8, full, glyphs.scroll_thumb) == null);+}++fn paintTo(a: std.mem.Allocator, frame: []const u8, prev: []const u8, force: bool) ![]u8 {+ var aw = std.Io.Writer.Allocating.init(a);+ try paint_mod.paint(&aw.writer, frame, H, W, prev, "\x1b[48;2;20;20;20m", force, null);+ return aw.toOwnedSlice();+}++test "a live drag hides the gutter — the band owns those rows" {+ const a = testing.allocator;+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try longTranscript(&m);+ const first = try frameAt(&m, 1_000);+ a.free(first);+ keys.scrollBy(&m, 8);+ const scrolled = try frameAt(&m, 1_000);+ defer a.free(scrolled);+ try testing.expect(std.mem.indexOf(u8, scrolled, glyphs.scroll_thumb) != null);+ // Press and drag inside the transcript: the thumb goes, the band arrives.+ const top = m.mid_origin + m.sticky_rows;+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 2), .down = true } });+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 30, .y = @intCast(top + 4), .down = true } });+ const dragging = try frameAt(&m, 1_000);+ defer a.free(dragging);+ try testing.expect(std.mem.indexOf(u8, dragging, "\x1b[7m") != null);+ try testing.expect(std.mem.indexOf(u8, dragging, glyphs.scroll_thumb) == null);+ // ...and the capture is text, with no gutter glyph smuggled into it.+ try testing.expect(std.mem.indexOf(u8, m.sel_text, glyphs.scroll_thumb) == null);+}++// ---------------------------------------------------------------- OSC 52++var copied: [4096]u8 = undefined;+var copied_len: usize = 0;+var copy_ok: bool = true;++fn fakeCopy(_: ?*anyopaque, text: []const u8) bool {+ if (!copy_ok) return false;+ copied_len = @min(text.len, copied.len);+ @memcpy(copied[0..copied_len], text[0..copied_len]);+ return true;+}++fn expectPayload(seq: []const u8, want: []const u8) !void {+ try testing.expect(std.mem.startsWith(u8, seq, osc52.prefix));+ try testing.expect(std.mem.endsWith(u8, seq, osc52.terminator));+ const body = seq[osc52.prefix.len .. seq.len - osc52.terminator.len];+ const enc = std.base64.standard.Encoder;+ const b64 = try testing.allocator.alloc(u8, enc.calcSize(want.len));+ defer testing.allocator.free(b64);+ _ = enc.encode(b64, want);+ try testing.expectEqualStrings(b64, body);+}++test "a drag-copy arms OSC 52 with the exact base64 of the captured rows" {+ engine.g_copy_fn = fakeCopy;+ defer engine.g_copy_fn = null;+ copy_ok = true;+ copied_len = 0;+ const a = testing.allocator;+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try m.push(.assistant, "OSCME alpha line");+ try m.push(.assistant, "OSCME beta line");+ const first = try frameAt(&m, 0);+ a.free(first);+ const top = m.mid_origin + m.sticky_rows;+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 1), .down = true } });+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 40, .y = @intCast(top + 2), .down = true } });+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 40, .y = @intCast(top + 2), .down = false } });+ const after = try frameAt(&m, 0);+ defer a.free(after);+ // The escape is NOT in the frame: a frame is repainted, a clipboard write+ // happens once.+ try testing.expect(std.mem.indexOf(u8, after, osc52.prefix) == null);+ const seq = selection.takeOsc52(&m);+ defer a.free(seq);+ try testing.expect(seq.len > 0);+ try expectPayload(seq, m.sel_text);+ try testing.expect(std.mem.indexOf(u8, m.sel_text, "OSCME alpha") != null);+ // Both channels carried it, so the toast says so without qualification.+ try testing.expectEqualStrings(m.sel_text, copied[0..copied_len]);+ try testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);+ try testing.expect(std.mem.indexOf(u8, m.toast, "OSC 52") == null);+ // Taking it clears it: the next paint owes the terminal nothing.+ try testing.expectEqual(@as(usize, 0), selection.takeOsc52(&m).len);+}++test "with no local clipboard the copy still succeeds, via OSC 52" {+ // The SSH case: pbcopy/xclip are absent or fail, and the only channel that+ // reaches the user's machine is the escape.+ engine.g_copy_fn = fakeCopy;+ defer engine.g_copy_fn = null;+ copy_ok = false;+ defer copy_ok = true;+ const a = testing.allocator;+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ try m.push(.assistant, "REMOTE alpha line");+ try m.push(.assistant, "REMOTE beta line");+ const first = try frameAt(&m, 0);+ a.free(first);+ const top = m.mid_origin + m.sticky_rows;+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 1), .down = true } });+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 40, .y = @intCast(top + 2), .down = true } });+ _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 40, .y = @intCast(top + 2), .down = false } });+ const after = try frameAt(&m, 0);+ defer a.free(after);+ const seq = selection.takeOsc52(&m);+ defer a.free(seq);+ try expectPayload(seq, m.sel_text);+ try testing.expect(std.mem.indexOf(u8, m.toast, "copied (OSC 52)") != null);+}++test "past the cap the local copy still lands and the toast says why not" {+ engine.g_copy_fn = fakeCopy;+ defer engine.g_copy_fn = null;+ copy_ok = true;+ copied_len = 0;+ const a = testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ var m: Model = undefined;+ m.setup(a);+ defer m.deinit();+ // A frame far larger than the cap, with the band over all of it. Going+ // through selection.paint means the capture is the real one, not a string+ // handed to the encoder.+ const row = try ar.alloc(u8, 120);+ @memset(row, 'y');+ const rows = (osc52.max_bytes / row.len) + 40;+ var frame = std.array_list.Managed(u8).init(ar);+ for (0..rows) |i| {+ if (i > 0) try frame.append('\n');+ try frame.appendSlice(row);+ }+ m.last_term_width = row.len;+ m.sel = .{ .active = true, .copy_pending = true, .a_row = 0, .a_col = 0, .h_row = rows - 1, .h_col = row.len - 1 };+ _ = try selection.paint(&m, ar, frame.items, row.len);+ try testing.expect(m.sel_text.len > osc52.max_bytes);+ try testing.expectEqual(@as(usize, 0), selection.takeOsc52(&m).len);+ try testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);+ try testing.expect(std.mem.indexOf(u8, m.toast, "too big for OSC 52") != null);+ // The local clipboard is unaffected by the cap — it took the whole thing.+ try testing.expect(copied_len > 0);+}diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 1f9b5a7c..bd2148ba 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -299,6 +299,16 @@ if wanted tuiguard; thenif python3 scripts/test-tui-stream-markdown.py zig-out/bin/graff; then :; elserecord_fail tuiguardfi+ # The scroll gutter has to land on a CELL and then leave no trace, and the+ # OSC 52 copy has to leave the process — neither is visible to a unit test.+ # Reads the thumb off the last column of the virtual screen, compares that+ # column against a forced full repaint once it fades, and matches the+ # base64 on the wire against the rows the drag covered. Each of the three+ # is a verified gate: removing the fade rule, the fade EXPIRY, or the tty+ # write each fails a different check.+ if python3 scripts/test-tui-scrollbar-osc52.py zig-out/bin/graff; then :; else+ record_fail tuiguard+ fififidiff --git a/scripts/test-tui-scrollbar-osc52.py b/scripts/test-tui-scrollbar-osc52.pynew file mode 100755index 00000000..b1f23f2c--- /dev/null+++ b/scripts/test-tui-scrollbar-osc52.py@@ -0,0 +1,271 @@+#!/usr/bin/env python3+"""Live proof for the scroll gutter and the OSC 52 clipboard channel.++Both features are invisible to a unit test in the way that matters: one is a+glyph that has to land on a specific CELL of a real terminal, the other is a+byte string that has to leave the process. So this probe drives the real binary+under a pty, reads the virtual screen back (scripts/ptyharness.py), and checks:++ A. thumb scroll off the tail and the LAST column of the viewport shows a+ contiguous run of thumb glyphs, inside the transcript band and+ nowhere else — not on the top bar, not on the composer.+ B. travel scrolling back toward the tail moves that run DOWN the track.+ C. no residue back at the tail, past the fade window, no thumb survives+ anywhere on the grid — and the last column of every row is+ identical to what a FORCED FULL REPAINT of the same frame puts+ there. A diff paint that skipped the gutter rows would leave a+ glyph the full repaint does not, and this is what catches it.+ D. osc52 a drag-copy puts `ESC ] 52 ; c ; <base64> BEL` on the wire, and+ the base64 decodes to exactly the screen rows the drag covered.+ Asserted against the BYTE STREAM, because that is the thing an+ SSH client on the far end actually receives.++Usage: python3 scripts/test-tui-scrollbar-osc52.py [path/to/graff]+ (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.+"""+import base64+import os+import re+import subprocess+import sys+import tempfile+import time++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")+COLS, ROWS = 100, 30+THUMB = "❚"+MARK = "GUTTERMARK_QX"+FADE = 1.5 # TUI/scrollbar.zig fade_ms+OSC52 = re.compile(rb"\x1b\]52;c;([A-Za-z0-9+/=]*)\x07")++WHEEL_UP = b"\x1b[<64;40;10M"+WHEEL_DOWN = b"\x1b[<65;40;10M"+++def fresh_ws():+ ws = tempfile.mkdtemp(prefix="tui-gutter-")+ empty = os.path.join(ws, "empty-mcp.json")+ with open(empty, "w") as f:+ f.write('{"mcpServers": {}}')+ return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}+++def fill(h, blocks=8):+ """Transcript content with no model call: `!` lines run in-session, so the+ text on screen is known exactly and nothing streams while we scroll."""+ for tag in range(blocks):+ body = "%s filler %d-%d padded out so the transcript outruns the viewport"+ lines = "".join((body % (MARK, tag, k)) + r"\n" for k in range(4))+ h.inject_keys((r"!printf '" + lines + r"'" + "\r").encode())+ h.pump(1.0)+ h.pump(1.5)+++def thumb_rows(h):+ """Rows whose LAST column carries the thumb."""+ return [y for y in range(ROWS) if h.cell(COLS - 1, y).ch == THUMB]+++def last_column(h):+ return [h.cell(COLS - 1, y).ch for y in range(ROWS)]+++def full_repaint(h):+ """A resize invalidates run.zig's diff baseline, so what follows is one+ whole frame laid down from a cleared screen."""+ h.resize(COLS, ROWS - 1)+ h.pump(0.6)+ h.resize(COLS, ROWS)+ h.pump(1.5)+++def sgr(btn, col, row, press=True):+ return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()+++def check_thumb(h):+ # Nothing has scrolled yet: no gutter on a tail-parked viewport.+ if thumb_rows(h):+ return "the gutter is up before anything scrolled", None+ for _ in range(5):+ h.inject_keys(WHEEL_UP)+ h.pump(0.25)+ h.pump(0.5)+ rows = thumb_rows(h)+ if not rows:+ return "scrolling off the tail raised no thumb on the last column", None+ if rows != list(range(rows[0], rows[0] + len(rows))):+ return f"the thumb is not one contiguous run: {rows}", None+ # It has to be INSIDE the transcript, not on the chrome. The composer box+ # is the last thing on screen and draws its own right wall, so a thumb on+ # it would be sitting on that wall.+ lines = h.screen_lines()+ box_rows = [y for y, ln in enumerate(lines) if "│" in ln or "╰" in ln or "╭" in ln]+ if box_rows and rows[-1] >= min(box_rows):+ return f"the thumb reached the composer: rows {rows}, box starts at {min(box_rows)}", None+ if rows[0] == 0:+ return "the thumb is on the top bar, not in the viewport", None+ # And it is the ONLY place that glyph appears — a gutter that also printed+ # into the body would be indistinguishable from content.+ stray = [(x, y) for y in range(ROWS) for x in range(COLS - 1) if h.cell(x, y).ch == THUMB]+ if stray:+ return f"the thumb glyph appears off the last column at {stray[:3]}", None+ return None, rows+++def check_travel(h, high):+ for _ in range(3):+ h.inject_keys(WHEEL_DOWN)+ h.pump(0.25)+ h.pump(0.5)+ low = thumb_rows(h)+ if not low:+ return "the gutter vanished while still scrolled off the tail", None+ if low[0] <= high[0]:+ return f"scrolling toward the tail did not move the thumb down ({high} -> {low})", None+ return None, low+++def check_no_residue(h):+ # All the way back to the tail, then past the fade window.+ for _ in range(24):+ h.inject_keys(WHEEL_DOWN)+ h.pump(0.06)+ h.pump(FADE + 1.0)+ left = thumb_rows(h)+ if left:+ return f"the gutter never faded at the tail: rows {left}"+ everywhere = [(x, y) for y in range(ROWS) for x in range(COLS) if h.cell(x, y).ch == THUMB]+ if everywhere:+ return f"a thumb glyph survived somewhere on the grid: {everywhere[:3]}"+ # The equality check that makes "no residue" mean something: the diff paint+ # that took the gutter away must have left the screen where a full repaint+ # of the same frame would.+ diffed = last_column(h)+ full_repaint(h)+ fresh = last_column(h)+ if diffed != fresh:+ bad = [i for i, (a, b) in enumerate(zip(diffed, fresh)) if a != b]+ return (+ f"the last column differs from a forced full repaint at rows {bad[:5]}: "+ f"{[diffed[i] for i in bad[:5]]!r} vs {[fresh[i] for i in bad[:5]]!r}"+ )+ return None+++def check_osc52(h):+ """Drag two known rows and read the escape off the wire."""+ lines = h.screen_lines()+ hits = [i for i, ln in enumerate(lines) if MARK in ln]+ if len(hits) < 3:+ return f"not enough {MARK} rows on screen to drag ({len(hits)})"+ first, last = hits[0], hits[0] + 1+ seen = len(h.raw)+ h.inject_keys(sgr(0, 1, first + 1))+ h.pump(0.35)+ h.inject_keys(sgr(32, COLS, last + 1))+ h.pump(0.5)+ if b"\x1b[7m" not in bytes(h.raw[seen:]):+ return "the drag painted no inverse-video band, so nothing was selected"+ before_release = len(h.raw)+ if OSC52.search(bytes(h.raw[seen:])):+ return "an OSC 52 escape went out before the button was released"+ h.inject_keys(sgr(0, COLS, last + 1, press=False))+ h.pump(1.5)+ tail = bytes(h.raw[before_release:])+ found = OSC52.findall(tail)+ if not found:+ return "the release emitted no OSC 52 sequence"+ if len(found) > 1:+ return f"the release emitted {len(found)} OSC 52 sequences; a clipboard write happens once"+ try:+ payload = base64.b64decode(found[0], validate=True).decode("utf-8", "replace")+ except Exception as e: # noqa: BLE001+ return f"the OSC 52 body is not valid base64 ({e})"+ # The band survives the release, so the rows on screen right now ARE the+ # rows that were copied. Text-only capture: each row loses its padding.+ want = "\n".join(h.screen_lines()[first:last + 1]).rstrip()+ want = "\n".join(ln.rstrip() for ln in want.split("\n"))+ if payload != want:+ return f"OSC 52 carried {payload!r}, but the dragged rows read {want!r}"+ if MARK not in payload:+ return f"the OSC 52 payload does not contain {MARK}: {payload!r}"+ return None+++def run(PtyHarness):+ ws, env = fresh_ws()+ h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=ws, env=env)+ try:+ if not h.wait_for_boot():+ return "the TUI never entered the alt screen"+ h.wait_for_text("Enter:send", timeout=10)+ fill(h)+ if MARK not in h.screen_contents():+ return f"the transcript never showed {MARK} (no `!` output)"+ err, high = check_thumb(h)+ if err:+ return err+ print(f" thumb: rows {high[0]}..{high[-1]} on column {COLS - 1}")+ err, low = check_travel(h, high)+ if err:+ return err+ print(f" travel: {high[0]}..{high[-1]} -> {low[0]}..{low[-1]} toward the tail")+ err = check_no_residue(h)+ if err:+ return err+ print(" residue: gutter faded, last column == a forced full repaint")+ err = check_osc52(h)+ if err:+ return err+ print(" osc52: the wire carried the exact base64 of the dragged rows")+ return None+ finally:+ h.close()+++def main():+ if not os.path.exists(BIN):+ print(f"tui-scrollbar-osc52: {BIN} not built — skipping")+ return 0+ try:+ import pty # noqa: F401+ except ImportError:+ print("tui-scrollbar-osc52: no pty support here — skipping")+ return 0+ import ptyharness++ # The local half of the copy writes the real clipboard; put it back.+ saved = None+ if sys.platform == "darwin":+ try:+ saved = subprocess.run(["pbpaste"], capture_output=True, check=True).stdout+ except Exception: # noqa: BLE001+ saved = None+ try:+ err = run(ptyharness.PtyHarness)+ except ptyharness.PtyTimeout as e:+ err = str(e).splitlines()[0]+ except OSError as e:+ if getattr(e, "errno", None) == 5:+ err = "pty EIO — the graff process died mid-check"+ else:+ print(f"tui-scrollbar-osc52: pty unavailable ({e}) — skipping")+ return 0+ finally:+ if saved is not None:+ try:+ subprocess.run(["pbcopy"], input=saved, check=False)+ except Exception: # noqa: BLE001+ pass+ if err:+ print(f" ✗ scrollbar/osc52: {err}")+ return 1+ print(" ✓ scrollbar/osc52: the gutter tracks the viewport and leaves no residue; a copy reaches the terminal")+ return 0+++if __name__ == "__main__":+ sys.exit(main())