Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(eval): isolate clipboard commands for each TUI probe

yxlyx22e52100b2cb
diff --git a/docs/adr/0097-isolate-probe-clipboards.md b/docs/adr/0097-isolate-probe-clipboards.md
new file mode 100644
index 00000000..5b98631b
--- /dev/null
+++ b/docs/adr/0097-isolate-probe-clipboards.md
@@ -0,0 +1,32 @@
+# 0097. Offline PTY probes own their clipboard command boundary
+
+Status: accepted 2026-09-10
+
+## Context
+
+The selection, click, and scrollbar probes can write the same host clipboard.
+Concurrent writes make otherwise correct selection assertions fail (#836).
+Serializing one pool does not protect it from another pool or from applications,
+and restoring the clipboard afterwards can overwrite newly copied user content.
+
+## Decision
+
+The offline tuiguard pool gives each probe a temporary command-backed clipboard.
+Private `pbcopy`, `pbpaste`, and `xclip` commands are prepended to that probe's
+PATH and inherited by its Graff child. They preserve the subprocess copy/paste
+boundary and exact bytes without reading or writing the user's clipboard.
+
+Keep these environments per probe, never mutate the parent's environment, and
+remove their files after the probe exits or its process group is terminated.
+Independent probes remain parallel; no selection or OSC52 assertion is skipped.
+
+## Consequences
+
+Gate runs test selection, subprocess delivery, and OSC52 bytes deterministically
+without interfering with concurrent runs or normal desktop use. They do not test
+the operating system's clipboard service. Direct invocation of the individual
+probe scripts retains that integration path when it is explicitly wanted.
+
+The pool integrity suite covers copy/paste, independent environments, cleanup,
+and environment inheritance. The real-binary pool covers the complete selection
+path with these commands in place.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index ced7d19c..1629fd5f 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -107,6 +107,7 @@ record only when you need the evidence or the edge cases.
| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. |
| [0095](0095-live-evals-are-gated-prs.md) | Live evals are gated PRs with no SPEC.md; score pass @ n=3 and list$ on passing reps only. |
| [0096](0096-desktop-link-destination.md) | Persist the desktop link destination outside origin-scoped storage; validate once and reveal the focused chat's Browser without navigating the app. |
+| [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. |
## When to write one
diff --git a/scripts/eval/clipboard_fixture.py b/scripts/eval/clipboard_fixture.py
new file mode 100644
index 00000000..4aacf0e8
--- /dev/null
+++ b/scripts/eval/clipboard_fixture.py
@@ -0,0 +1,40 @@
+"""Private clipboard command boundary for offline PTY probes.
+
+The probe and its Graff child share these commands through PATH. Direct probe
+runs still exercise the OS clipboard; the parallel gate must neither race with
+other probes nor read or replace the user's clipboard.
+"""
+from contextlib import contextmanager
+import os
+from pathlib import Path
+import shlex
+import sys
+import tempfile
+
+
+@contextmanager
+def private_clipboard():
+ with tempfile.TemporaryDirectory(prefix="tuiguard-clipboard-") as directory:
+ root = Path(directory)
+ clipboard = root / "clipboard"
+ clipboard.write_bytes(b"")
+ handler = root / "clipboard.py"
+ handler.write_text(
+ "import os, pathlib, sys\n"
+ "path = pathlib.Path(__file__).with_name('clipboard')\n"
+ "if sys.argv[1] in ('pbpaste',) or '-o' in sys.argv[2:] or '-out' in sys.argv[2:]:\n"
+ " sys.stdout.buffer.write(path.read_bytes())\n"
+ "else:\n"
+ " temporary = path.with_name('write-' + str(os.getpid()))\n"
+ " temporary.write_bytes(sys.stdin.buffer.read())\n"
+ " temporary.replace(path)\n",
+ encoding="utf-8",
+ )
+ for command in ("pbcopy", "pbpaste", "xclip"):
+ wrapper = root / command
+ wrapper.write_text(
+ f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(handler))} {command} \"$@\"\n",
+ encoding="utf-8",
+ )
+ wrapper.chmod(0o700)
+ yield {**os.environ, "PATH": str(root) + os.pathsep + os.environ.get("PATH", "")}
diff --git a/scripts/eval/test_tier1_tuiguard.py b/scripts/eval/test_tier1_tuiguard.py
index e54d4d16..f501a343 100644
--- a/scripts/eval/test_tier1_tuiguard.py
+++ b/scripts/eval/test_tier1_tuiguard.py
@@ -6,10 +6,14 @@ from __future__ import annotations
import importlib.util
import os
from pathlib import Path
+import shutil
+import subprocess
import sys
import tempfile
import time
import unittest
+from concurrent.futures import ThreadPoolExecutor
+from threading import Barrier
from unittest import mock
@@ -97,5 +101,112 @@ time.sleep(60)
self.assertIn("still running: test-tui-hover.py", joined)
[email protected](os.name == "posix", "POSIX clipboard wrappers")
+class ClipboardTests(unittest.TestCase):
+ def clipboard(self, env, command, data=None):
+ fixture_dir = Path(env["PATH"].split(os.pathsep)[0])
+ executable = shutil.which(command[0], path=env["PATH"])
+ self.assertIsNotNone(executable)
+ self.assertEqual(Path(executable).parent, fixture_dir)
+ return subprocess.run(
+ command, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ env=env, check=True, timeout=5,
+ ).stdout
+
+ def test_copy_paste_preserves_exact_bytes(self) -> None:
+ payload = b"\x00\xffclipboard\r\nUTF-8: \xe2\x98\x83\n\n"
+ with tuiguard.private_clipboard() as env:
+ for copy, paste in (
+ (["pbcopy"], ["pbpaste"]),
+ (["xclip", "-selection", "clipboard"],
+ ["xclip", "-selection", "clipboard", "-o"]),
+ (["pbcopy"], ["xclip", "-selection", "clipboard", "-o"]),
+ (["xclip", "-selection", "clipboard"], ["pbpaste"]),
+ ):
+ for data in (payload, b""):
+ with self.subTest(copy=copy, paste=paste, data=data):
+ self.clipboard(env, copy, data)
+ self.assertEqual(self.clipboard(env, paste), data)
+
+ def test_concurrent_contexts_do_not_interfere(self) -> None:
+ barrier = Barrier(2)
+
+ def roundtrip(payload):
+ with tuiguard.private_clipboard() as env:
+ self.clipboard(env, ["pbcopy"], payload)
+ barrier.wait(timeout=10)
+ self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)
+ return env["PATH"]
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ futures = [pool.submit(roundtrip, data) for data in (b"first", b"second")]
+ paths = [future.result(timeout=20) for future in futures]
+ self.assertNotEqual(*paths)
+
+ def test_context_cleanup_and_process_path_unchanged(self) -> None:
+ original_path = os.environ.get("PATH")
+ for exceptional in (False, True):
+ with self.subTest(exceptional=exceptional):
+ try:
+ with tuiguard.private_clipboard() as env:
+ fixture_dir = Path(env["PATH"].split(os.pathsep)[0])
+ self.assertTrue(fixture_dir.is_dir())
+ self.assertEqual(os.environ.get("PATH"), original_path)
+ self.clipboard(env, ["pbcopy"], b"cleanup")
+ if exceptional:
+ raise RuntimeError("context exit")
+ except RuntimeError as exc:
+ self.assertEqual(str(exc), "context exit")
+ self.assertFalse(fixture_dir.exists())
+ self.assertEqual(os.environ.get("PATH"), original_path)
+
+ def test_nested_run_probe_environments_remain_separate(self) -> None:
+ original_path = os.environ.get("PATH")
+ environments = []
+
+ def run_command(argv, timeout, *, env):
+ environments.append(env)
+ payload = Path(argv[1]).name.encode()
+ self.clipboard(env, ["pbcopy"], payload)
+ if len(environments) == 1:
+ tuiguard.run_probe("inner.py", "/nonexistent/graff", timeout)
+ self.assertIsNot(env, environments[1])
+ self.assertNotEqual(env["PATH"], environments[1]["PATH"])
+ self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)
+ self.assertEqual(os.environ.get("PATH"), original_path)
+ return 0, "", 0.0, False
+
+ with mock.patch.object(tuiguard, "run_command", side_effect=run_command):
+ tuiguard.run_probe("outer.py", "/nonexistent/graff", 1.0)
+ self.assertEqual(len(environments), 2)
+ for env in environments:
+ self.assertFalse(Path(env["PATH"].split(os.pathsep)[0]).exists())
+ self.assertEqual(os.environ.get("PATH"), original_path)
+
+ def test_parallel_run_probe_environments_remain_separate(self) -> None:
+ original_path = os.environ.get("PATH")
+ barrier = Barrier(2)
+
+ def run_command(argv, timeout, *, env):
+ payload = Path(argv[1]).name.encode()
+ self.clipboard(env, ["pbcopy"], payload)
+ barrier.wait(timeout=10)
+ self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)
+ self.assertEqual(os.environ.get("PATH"), original_path)
+ return 0, env["PATH"], 0.0, False
+
+ with mock.patch.object(tuiguard, "run_command", side_effect=run_command):
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ futures = [
+ pool.submit(tuiguard.run_probe, name, "/nonexistent/graff", 1.0)
+ for name in ("first.py", "second.py")
+ ]
+ results = [future.result(timeout=20) for future in futures]
+ self.assertNotEqual(results[0][2], results[1][2])
+ for result in results:
+ self.assertFalse(Path(result[2].split(os.pathsep)[0]).exists())
+ self.assertEqual(os.environ.get("PATH"), original_path)
+
+
if __name__ == "__main__":
raise SystemExit(unittest.main())
diff --git a/scripts/eval/tier1_tuiguard.py b/scripts/eval/tier1_tuiguard.py
index 1951bc82..61cfe542 100755
--- a/scripts/eval/tier1_tuiguard.py
+++ b/scripts/eval/tier1_tuiguard.py
@@ -26,6 +26,7 @@ import sys
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from pathlib import Path
+from clipboard_fixture import private_clipboard
ROOT = Path(__file__).resolve().parents[2]
SCRIPTS = ROOT / "scripts"
@@ -105,12 +106,13 @@ def terminate_group(proc: subprocess.Popen[str]) -> None:
proc.kill()
-def run_command(argv: list[str], timeout: float, cwd: Path | None = None) -> tuple[int, str, float, bool]:
+def run_command(argv: list[str], timeout: float, cwd: Path | None = None, env: dict[str, str] | 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),
+ env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
@@ -130,10 +132,14 @@ def run_command(argv: list[str], timeout: float, cwd: Path | None = None) -> tup
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,
- )
+ # Each probe and its child use a private command-backed clipboard. A pool
+ # lock alone cannot protect the user's clipboard from another test process.
+ with private_clipboard() as env:
+ status, blob, elapsed, timed_out = run_command(
+ [sys.executable, str(SCRIPTS / script), binary],
+ timeout,
+ env=env,
+ )
return script, status, blob, elapsed, timed_out