Skip to content

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

Python

fix: harden tty and trace reliability (#271 #272)

Rach Pradhan014769a9dd81
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 70ab6688..9d807e40 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -70,6 +70,9 @@ jobs:
- name: Behavioral trace stream, re-scorer, and replay round trip
run: python3 scripts/test-behavior-trace.py zig-out/bin/graff
+ - name: Concurrent operational trace isolation and JSONL integrity
+ run: 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
@@ -85,6 +88,9 @@ jobs:
- name: PTY spinner anti-stealth test
run: python3 scripts/test-pty-spinner.py zig-out/bin/graff
+ - name: YOLO background-TTY job-control regression
+ run: python3 scripts/test-yolo-job-control.py zig-out/bin/graff
+
- name: PTY REPL interaction test
run: python3 scripts/test-pty-repl.py zig-out/bin/graff
diff --git a/docs/behavioral-trajectories.md b/docs/behavioral-trajectories.md
index f5d3bd78..9fcaa2c8 100644
--- a/docs/behavioral-trajectories.md
+++ b/docs/behavioral-trajectories.md
@@ -14,7 +14,7 @@ adapter, or fleet/DGM selection from general behavioral scores.
| Stream | Lifetime | Purpose |
| --- | --- | --- |
-| `harness.trace.jsonl` | Truncated at startup | Operational API/tool latency and error counters, with active behavioral-turn attribution, used to debug the harness. |
+| `.graff/traces/<run_id>.jsonl` | One exclusively created file per invocation | Operational API/tool latency and error counters, with active behavioral-turn attribution, used to debug the harness. |
| `.graff/behavior/<run_id>.jsonl` | Up to one exclusively-created file per initialized agent session | Experimental lifecycle and caller-asserted belief events. |
| `harness.trajectory.jsonl` | Append-only across runs | Existing DGM/MAP-Elites lineage and fitness ledger. Its record shapes are unchanged. |
@@ -28,6 +28,13 @@ exits nonzero or the parsed score misses `--until`. Every other invocation path
still contains lifecycle events only. Adapter rows in the example below are
illustrative.
+The retired `harness.trace.jsonl` path is never opened, truncated, appended, or
+repaired by current releases. It may still exist as an ignored legacy artifact
+from an older installation. Current operational traces use random run IDs,
+exclusive creation, a single mutexed writer, complete in-memory JSON records,
+and stop writing after any failed file drain. This prevents a stale descriptor
+from seeking past a later truncation and creating sparse NUL gaps (#242/#272).
+
For an eval-driven session, `eval` is a verifier boundary and must be the only
tool in its batch. A red result marks the current expectation as contradicted,
drops the remaining plan, and ends that model turn. The next turn is a repair
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index ea3d9c8a..753a3e79 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -99,10 +99,26 @@ and connects Streamable HTTP tools without a Node bridge.
Codegraff OAuth responsibilities were split into sibling modules. CI checks
both tracked and newly created sources so the ceiling cannot silently drift.
+## Reliability fixes
+
+- Raw terminal reads and mode changes now mask POSIX job-control signals around
+ the syscall. A transient foreground-process-group race therefore returns an
+ input error instead of suspending the whole `graff --yolo` job with SIGTTIN.
+ YOLO-launched skill installers also receive a null stdin instead of inheriting
+ the controlling terminal.
+- Operational traces remain isolated in exclusively created
+ `.graff/traces/<run_id>.jsonl` files. CI now runs concurrent tool turns through
+ WS→SSE fallback and rejects NUL bytes, malformed records, mixed run identity,
+ timestamp rollback, or recreation of the retired shared trace path.
+
## Validation
- Complete Zig test suite and native build
- Windows cross-build
+- A real PTY job-control regression that fails the pre-fix binary with
+ `STOPPED 21` and keeps the fixed YOLO process running
+- Concurrent tool/fallback trace validation with independently parseable,
+ monotonic, fully correlated JSONL
- End-to-end local learning and hidden-holdout tournament flows
- Adapter retry/crash recovery and process-tree cleanup
- Aggregate receipt signature and deletion-token cross-checks
diff --git a/scripts/test-run-isolation.py b/scripts/test-run-isolation.py
index ff16a461..e01f7fca 100644
--- a/scripts/test-run-isolation.py
+++ b/scripts/test-run-isolation.py
@@ -9,7 +9,7 @@ import subprocess
import sys
import tempfile
-from codex_ws_mock import CodexMock
+from codex_ws_mock import CodexMock, RecordedRequest, turn_events
_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
@@ -30,7 +30,7 @@ def records(path: str) -> list[dict]:
return parsed
-def validate_run_file(path: str) -> tuple[str, int, str]:
+def validate_run_file(path: str) -> tuple[tuple[str, int, str], list[dict]]:
run_id = os.path.basename(path).removesuffix(".jsonl")
rows = records(path)
identity = (run_id, rows[0].get("pid"), rows[0].get("session_id"))
@@ -42,14 +42,44 @@ def validate_run_file(path: str) -> tuple[str, int, str]:
current = (row.get("run_id"), row.get("pid"), row.get("session_id"))
if current != identity:
raise AssertionError(f"mixed identity in {path}: {current!r} != {identity!r}")
- return identity
+ return identity, rows
+
+
+def response_events(item: dict, response_id: str) -> list[dict]:
+ return [
+ {"type": "response.output_item.done", "item": item},
+ turn_events(response_id)[1],
+ ]
+
+
+def events(request: RecordedRequest) -> list[dict]:
+ """Make every process execute one real tool before its final response."""
+ inputs = request.body.get("input", [])
+ if any(
+ isinstance(item, dict) and item.get("type") == "function_call_output"
+ for item in inputs
+ ):
+ return turn_events(f"resp_isolation_done_{request.ordinal}")
+ return response_events(
+ {
+ "type": "function_call",
+ "id": f"fc_isolation_{request.ordinal}",
+ "call_id": f"call_isolation_{request.ordinal}",
+ "name": "read_file",
+ "arguments": json.dumps({"path": "fixture.txt"}),
+ "status": "completed",
+ },
+ f"resp_isolation_tool_{request.ordinal}",
+ )
def main() -> None:
- mock = CodexMock()
+ mock = CodexMock(events_for_request=events)
port = mock.start()
try:
with tempfile.TemporaryDirectory(prefix="graff-run-isolation-") as tmp:
+ with open(os.path.join(tmp, "fixture.txt"), "w", encoding="utf-8") as fh:
+ fh.write("concurrent trace fixture\n")
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:
@@ -77,7 +107,9 @@ def main() -> None:
"HOME": tmp,
"CODEX_HOME": codex_home,
"GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",
- "GRAFF_CODEX_WS": "off",
+ # Both concurrent processes exercise the WS -> SSE fallback
+ # path named in #272 while their tool events overlap.
+ "GRAFF_WS_FORCE_FAIL_COUNT": "2",
"GRAFF_FLEET": "off",
"GRAFF_NO_TELEMETRY": "1",
}
@@ -121,20 +153,38 @@ def main() -> None:
f"expected two trace + trajectory files, got {traces!r}, {trajectories!r}"
)
- trace_ids = {validate_run_file(path) for path in traces}
- trajectory_ids = {validate_run_file(path) for path in trajectories}
- if trace_ids != trajectory_ids:
+ trace_runs = dict(validate_run_file(path) for path in traces)
+ trajectory_runs = dict(validate_run_file(path) for path in trajectories)
+ if trace_runs.keys() != trajectory_runs.keys():
raise AssertionError(
- f"trace/trajectory correlation mismatch: {trace_ids!r} != {trajectory_ids!r}"
+ "trace/trajectory correlation mismatch: "
+ f"{trace_runs.keys()!r} != {trajectory_runs.keys()!r}"
)
- if {pid for _run_id, pid, _session_id in trace_ids} != expected_pids:
+ if {pid for _run_id, pid, _session_id in trace_runs} != expected_pids:
raise AssertionError(
- f"record PIDs do not match child processes: {trace_ids!r}, {expected_pids!r}"
+ "record PIDs do not match child processes: "
+ f"{trace_runs.keys()!r}, {expected_pids!r}"
+ )
+ for identity, rows in trace_runs.items():
+ if not any(row.get("ev") == "tool" for row in rows):
+ raise AssertionError(f"missing tool event in trace {identity!r}")
+ times = [row["t"] for row in rows if isinstance(row.get("t"), int)]
+ if times != sorted(times):
+ raise AssertionError(f"timestamp rollback within trace {identity!r}")
+ if os.path.exists(os.path.join(tmp, "harness.trace.jsonl")):
+ raise AssertionError("current run recreated retired harness.trace.jsonl")
+ if mock.ws_turns != 0 or mock.sse_turns != 4:
+ raise AssertionError(
+ f"expected four SSE tool/final turns after forced fallback, "
+ f"got ws={mock.ws_turns} sse={mock.sse_turns}"
)
finally:
mock.stop()
- print("ok two simultaneous runs produced isolated, fully correlated JSONL")
+ print(
+ "ok concurrent tool runs survived WS->SSE fallback with isolated, "
+ "valid, monotonic JSONL"
+ )
if __name__ == "__main__":
diff --git a/scripts/test-yolo-job-control.py b/scripts/test-yolo-job-control.py
new file mode 100644
index 00000000..d120ba88
--- /dev/null
+++ b/scripts/test-yolo-job-control.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+"""Regression for #271: a TTY foreground race must not suspend Graff.
+
+The wrapper and Graff occupy separate process groups in one real PTY session.
+While a delayed model response keeps the thinking/steer watcher active, the
+wrapper briefly takes the terminal foreground and the test queues one input
+byte. An unguarded background read receives SIGTTIN and stops Graff; the fixed
+reader blocks that job-control signal around the syscall and remains running.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import pty
+import select
+import signal
+import sys
+import tempfile
+import time
+
+from codex_ws_mock import CodexMock, RecordedRequest, turn_events
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+def delayed_events(request: RecordedRequest) -> list[dict]:
+ time.sleep(2.0)
+ return turn_events(f"resp_job_control_{request.ordinal}")
+
+
+def read_line(fd: int, timeout: float = 5.0) -> str:
+ deadline = time.monotonic() + timeout
+ data = bytearray()
+ while b"\n" not in data:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise AssertionError(f"timed out waiting for wrapper status: {data!r}")
+ ready, _, _ = select.select([fd], [], [], remaining)
+ if not ready:
+ continue
+ chunk = os.read(fd, 1024)
+ if not chunk:
+ raise AssertionError(f"wrapper status pipe closed early: {data!r}")
+ data.extend(chunk)
+ return bytes(data).split(b"\n", 1)[0].decode("ascii", errors="replace")
+
+
+def wait_for(master: int, needle: bytes, transcript: bytearray, timeout: float) -> None:
+ deadline = time.monotonic() + timeout
+ while needle not in transcript:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise AssertionError(
+ f"timed out waiting for {needle!r}; tail={bytes(transcript[-2000:])!r}"
+ )
+ ready, _, _ = select.select([master], [], [], min(0.1, remaining))
+ if not ready:
+ continue
+ try:
+ chunk = os.read(master, 65536)
+ except OSError:
+ chunk = b""
+ if not chunk:
+ raise AssertionError(
+ f"PTY closed before {needle!r}; tail={bytes(transcript[-2000:])!r}"
+ )
+ transcript.extend(chunk)
+
+
+def wrapper(
+ control_fd: int,
+ status_fd: int,
+ argv: list[str],
+ cwd: str,
+ env: dict[str, str],
+) -> None:
+ """Session-leader child: move Graff in/out of the PTY foreground."""
+ signal.signal(signal.SIGTTOU, signal.SIG_IGN)
+ graff_pid = os.fork()
+ if graff_pid == 0:
+ try:
+ os.setpgid(0, 0)
+ os.chdir(cwd)
+ os.execvpe(argv[0], argv, env)
+ except BaseException:
+ os._exit(127)
+
+ try:
+ try:
+ os.setpgid(graff_pid, graff_pid)
+ except PermissionError:
+ pass
+ os.tcsetpgrp(0, graff_pid)
+ os.write(status_fd, f"READY {graff_pid}\n".encode("ascii"))
+ if os.read(control_fd, 1) != b"B":
+ raise RuntimeError("missing background command")
+
+ os.tcsetpgrp(0, os.getpgrp())
+ os.write(status_fd, b"BACKGROUND\n")
+ time.sleep(0.5)
+ waited_pid, status = os.waitpid(
+ graff_pid, os.WNOHANG | os.WUNTRACED | os.WCONTINUED
+ )
+ stopped = waited_pid == graff_pid and os.WIFSTOPPED(status)
+ if stopped:
+ os.write(
+ status_fd,
+ f"STOPPED {os.WSTOPSIG(status)}\n".encode("ascii"),
+ )
+ os.kill(graff_pid, signal.SIGCONT)
+ else:
+ os.write(status_fd, b"RUNNING\n")
+ os.tcsetpgrp(0, graff_pid)
+ os.kill(graff_pid, signal.SIGTERM)
+ try:
+ os.waitpid(graff_pid, 0)
+ except ChildProcessError:
+ pass
+ os._exit(2 if stopped else 0)
+ except BaseException as exc:
+ try:
+ os.write(status_fd, f"WRAPPER_ERROR {exc!r}\n".encode("ascii"))
+ os.kill(graff_pid, signal.SIGKILL)
+ os.waitpid(graff_pid, 0)
+ except BaseException:
+ pass
+ os._exit(3)
+
+
+def main() -> None:
+ mock = CodexMock(events_for_request=delayed_events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-yolo-job-control-") as tmp:
+ 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": "job-control-mock",
+ "account_id": "acct-job-control",
+ }
+ },
+ fh,
+ )
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir)
+ with open(
+ os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8"
+ ) as fh:
+ json.dump(
+ {"ai_title": False, "skills": {"codedbpro": False}},
+ fh,
+ )
+
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.startswith("GRAFF_")
+ and not key.startswith("CODEX_")
+ and key != "NO_COLOR"
+ }
+ env.update(
+ {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "TERM": "xterm-256color",
+ "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",
+ }
+ )
+ argv = [
+ GRAFF,
+ "--model",
+ "codex",
+ "--no-telemetry",
+ "--no-resume",
+ "--yolo",
+ ]
+ control_r, control_w = os.pipe()
+ status_r, status_w = os.pipe()
+ wrapper_pid, master = pty.fork()
+ if wrapper_pid == 0:
+ os.close(control_w)
+ os.close(status_r)
+ wrapper(control_r, status_w, argv, tmp, env)
+
+ os.close(control_r)
+ os.close(status_w)
+ transcript = bytearray()
+ try:
+ ready = read_line(status_r)
+ if not ready.startswith("READY "):
+ raise AssertionError(f"wrapper failed to start Graff: {ready}")
+ wait_for(master, b"\x1b[?2004h", transcript, 10.0)
+ os.write(master, b"wait before replying\r")
+ wait_for(master, b"thinking", transcript, 10.0)
+ os.write(control_w, b"B")
+ if read_line(status_r) != "BACKGROUND":
+ raise AssertionError("wrapper did not take the PTY foreground")
+ # Make the steer watcher pass poll(2) and attempt its raw read.
+ os.write(master, b"x")
+ outcome = read_line(status_r)
+ if outcome != "RUNNING":
+ raise AssertionError(
+ f"Graff was suspended by background TTY input: {outcome}"
+ )
+ _, status = os.waitpid(wrapper_pid, 0)
+ if os.waitstatus_to_exitcode(status) != 0:
+ raise AssertionError(f"wrapper exited {os.waitstatus_to_exitcode(status)}")
+ finally:
+ for fd in (master, control_w, status_r):
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ try:
+ os.kill(wrapper_pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ finally:
+ mock.stop()
+
+ print("ok --yolo remained running across a background-TTY input race")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 6fd7ff8c..03359385 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -353,9 +353,15 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.print("installing {s}{s}{s}: {s}{s}{s}\n", .{ style.accent, sk.name, style.reset, style.dim, sk.install, style.reset });
try out.flush();
// The user typed the install command themselves — that's the
- // consent; the installer runs with our stdio so its progress
- // and any sudo prompt reach the terminal directly.
- var child = std.process.spawn(root.io, .{ .argv = &.{ "/bin/sh", "-c", sk.install } }) catch |err| {
+ // consent. Interactive sessions keep stdin for a possible sudo
+ // prompt; --yolo promised not to prompt, so its child receives
+ // the null device instead of inheriting the controlling TTY
+ // (issue #271). Progress still streams through stdout/stderr.
+ const yolo = if (root.approvals) |approvals| approvals.yolo else false;
+ var child = std.process.spawn(root.io, .{
+ .argv = &.{ "/bin/sh", "-c", sk.install },
+ .stdin = if (yolo) .ignore else .inherit,
+ }) catch |err| {
try out.print("failed to launch installer: {t}\n", .{err});
try out.flush();
return true;
diff --git a/src/term.zig b/src/term.zig
index 44385be3..23035a67 100644
--- a/src/term.zig
+++ b/src/term.zig
@@ -77,6 +77,33 @@ pub const tty = struct {
/// input-mode word on Windows.
pub const RawState = if (is_windows) struct { in_mode: u32 } else std.posix.termios;
+ /// POSIX job control can move a process group out of the foreground between
+ /// a readiness check and the actual read/tcsetattr. A background terminal
+ /// read normally stops the whole group with SIGTTIN (issue #271), while a
+ /// terminal-mode change may do the same with SIGTTOU. Block only around the
+ /// syscall; POSIX then returns EIO instead of suspending Graff. The mask is
+ /// per-thread and restored immediately.
+ const JobControlGuard = if (is_windows) struct {
+ fn init(comptime _: enum { input, output }) @This() {
+ return .{};
+ }
+ fn deinit(_: *@This()) void {}
+ } else struct {
+ old: std.posix.sigset_t,
+
+ fn init(comptime operation: enum { input, output }) @This() {
+ var set = std.posix.sigemptyset();
+ std.posix.sigaddset(&set, if (operation == .input) .TTIN else .TTOU);
+ var old: std.posix.sigset_t = undefined;
+ std.posix.sigprocmask(std.posix.SIG.BLOCK, &set, &old);
+ return .{ .old = old };
+ }
+
+ fn deinit(self: *@This()) void {
+ std.posix.sigprocmask(std.posix.SIG.SETMASK, &self.old, null);
+ }
+ };
+
/// One-time: let the Windows console interpret ANSI/VT escapes. No-op
/// elsewhere. Call once from main before any styled output.
pub fn enableVtOutput() void {
@@ -141,6 +168,8 @@ pub const tty = struct {
}
raw.cc[@intFromEnum(std.posix.V.MIN)] = if (blocking) 1 else 0;
raw.cc[@intFromEnum(std.posix.V.TIME)] = 0;
+ var job_control = JobControlGuard.init(.output);
+ defer job_control.deinit();
std.posix.tcsetattr(fd, .NOW, raw) catch return null;
return orig;
}
@@ -151,6 +180,8 @@ pub const tty = struct {
_ = win.SetConsoleMode(win.GetStdHandle(win.STD_INPUT_HANDLE), state.in_mode);
return;
}
+ var job_control = JobControlGuard.init(.output);
+ defer job_control.deinit();
std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, state) catch {};
}
@@ -197,6 +228,8 @@ pub const tty = struct {
}
return out;
}
+ var job_control = JobControlGuard.init(.input);
+ defer job_control.deinit();
return std.posix.read(std.posix.STDIN_FILENO, buf) catch 0;
}
};