Skip to content

The agent that grows with you

test: C2 terminal transcript integrity over a real PTY (classic CLI + Ink TUI)

teknium12f3d25c1db39
diff --git a/tests/e2e/core/terminal/_pty.py b/tests/e2e/core/terminal/_pty.py
new file mode 100644
index 00000000000..86c06b51a89
--- /dev/null
+++ b/tests/e2e/core/terminal/_pty.py
@@ -0,0 +1,349 @@
+"""Drive a real ``hermes`` CLI / Ink TUI process under a real PTY, rendered through :mod:`._vt`.
+
+The child runs with an isolated HOME/HERMES_HOME (only the fake LLM provider configured, no
+inherited credentials) as the session leader of its own PTY, so SIGWINCH from a resize reaches the
+foreground process group exactly as in a terminal emulator, and every process it spawns can be
+found afterwards by session id (orphans keep the sid even after being reparented to init).
+
+Input follows prompt_toolkit's rules: text and the submitting ``\\r`` never share one write (that
+is a paste and inserts a newline); we wait until the typed text is echoed on screen, then send CR.
+"""
+
+from __future__ import annotations
+
+import fcntl
+import os
+import re
+import signal
+import sqlite3
+import struct
+import subprocess
+import sys
+import termios
+import threading
+import time
+from pathlib import Path
+from typing import Callable
+
+from tests.e2e.core.terminal._vt import Screen
+from tests.fakes.fake_llm_provider import FakeLLMServer, write_hermes_home
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+
+# Right-edge scrollbar glyphs the Ink TUI paints in the last column of its transcript viewport.
+_SCROLLBAR = "│┃║▐▕█░▒▓"
+_WS = re.compile(r"\s+")
+_DIGITS = re.compile(r"\d")
+
+_SESSION_LEADER = (
+ "import fcntl, os, sys, termios\n"
+ "fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n"
+ "os.execv(sys.argv[1], sys.argv[1:])\n"
+)
+
+
+def canon(text: str) -> str:
+ """Whitespace-free form: independent of where the terminal (or Ink) wrapped a line."""
+ return _WS.sub("", text)
+
+
+def poll(fn: Callable[[], object], *, timeout: float, what: str, interval: float = 0.05):
+ deadline = time.monotonic() + timeout
+ while True:
+ value = fn()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise AssertionError(f"timed out after {timeout:.0f}s waiting for {what}")
+ time.sleep(interval)
+
+
+def _operator_home() -> Path:
+ import pwd
+ return Path(pwd.getpwuid(os.getuid()).pw_dir)
+
+
+def _sid_of(pid: int) -> int | None:
+ try:
+ stat = Path(f"/proc/{pid}/stat").read_text()
+ except OSError:
+ return None
+ # comm may contain spaces/parens: fields after the last ')' are fixed.
+ fields = stat.rsplit(")", 1)[1].split()
+ if fields[0] == "Z":
+ return None # zombie: already dead, only waiting to be reaped
+ return int(fields[3])
+
+
+def _start_time(pid: int) -> int | None:
+ """Kernel start time of a live (non-zombie) process, the stable half of its identity."""
+ try:
+ fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
+ except OSError:
+ return None
+ return None if fields[0] == "Z" else int(fields[19])
+
+
+def session_members(sid: int) -> list[int]:
+ out = []
+ for entry in os.listdir("/proc"):
+ if entry.isdigit() and _sid_of(int(entry)) == sid:
+ out.append(int(entry))
+ return out
+
+
+def cmdline(pid: int) -> str:
+ try:
+ return Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
+ except OSError:
+ return "?"
+
+
+class PtyHermes:
+ """One interactive ``hermes`` process on a PTY with an emulated screen."""
+
+ def __init__(self, root: Path, argv_tail: list[str], llm: FakeLLMServer, *, rows: int, cols: int,
+ extra_config: str = "") -> None:
+ self.root = root
+ self.home = root / "home"
+ self.hermes_home = self.home / ".hermes"
+ operator = (_operator_home() / ".hermes").resolve()
+ assert operator not in (self.hermes_home.resolve(), *self.hermes_home.resolve().parents), (
+ f"sandbox {self.hermes_home} sits inside the operator's Hermes home")
+ write_hermes_home(self.hermes_home, llm.base_url, extra_config=extra_config)
+ self.llm = llm
+ self.screen = Screen(rows, cols)
+ self.raw = bytearray()
+ self._lock = threading.Lock()
+ (root / "tmp").mkdir(parents=True, exist_ok=True)
+ (root / "work").mkdir(parents=True, exist_ok=True)
+ env = {k: os.environ[k] for k in ("PATH", "LANG", "LC_ALL") if k in os.environ}
+ env.update(
+ HOME=str(self.home), HERMES_HOME=str(self.hermes_home), PYTHONPATH=str(REPO_ROOT),
+ TMPDIR=str(root / "tmp"), TERM="xterm-256color", COLORTERM="truecolor",
+ PYTHONUNBUFFERED="1", HERMES_STATE_DB_GUARD_BYPASS="1",
+ )
+ master, slave = os.openpty()
+ self._set_winsize(master, rows, cols)
+ self.master = master
+ self.pts = os.ttyname(slave)
+ self.proc = subprocess.Popen(
+ [sys.executable, "-c", _SESSION_LEADER, sys.executable, "-m", "hermes_cli.main", *argv_tail],
+ stdin=slave, stdout=slave, stderr=slave, cwd=str(root / "work"), env=env,
+ start_new_session=True, close_fds=True)
+ os.close(slave)
+ self.sid = self.proc.pid # start_new_session: the child is its own session leader
+ self.seen_members: set[tuple[int, int]] = set()
+ self._reader = threading.Thread(target=self._read_loop, name="pty-reader", daemon=True)
+ self._reader.start()
+
+ # -- io -------------------------------------------------------------------------------------
+
+ @staticmethod
+ def _set_winsize(fd: int, rows: int, cols: int) -> None:
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
+
+ def _read_loop(self) -> None:
+ while True:
+ try:
+ data = os.read(self.master, 65536)
+ except OSError:
+ return
+ if not data:
+ return
+ with self._lock:
+ self.raw.extend(data)
+ self.screen.feed(data)
+
+ def write(self, data: str) -> None:
+ os.write(self.master, data.encode("utf-8"))
+
+ def resize(self, rows: int, cols: int) -> None:
+ with self._lock:
+ self._set_winsize(self.master, rows, cols) # kernel delivers SIGWINCH to the fg pgrp
+ self.screen.resize(rows, cols)
+
+ # -- screen views ---------------------------------------------------------------------------
+
+ def lines(self) -> list[str]:
+ """What the user can see or scroll back to: the alt screen when a fullscreen UI owns it,
+ otherwise scrollback + the main screen. Scrollbar glyphs in the last column are dropped."""
+ with self._lock:
+ rows = self.screen.display() if self.screen.alt_active else self.screen.transcript()
+ cols = self.screen.cols
+ out = []
+ for line in rows:
+ if len(line) >= cols and line[cols - 1] in _SCROLLBAR:
+ line = line[: cols - 1]
+ out.append(line)
+ return out
+
+ def text(self) -> str:
+ return canon("".join(self.lines()))
+
+ def count(self, needle: str) -> int:
+ return self.text().count(canon(needle))
+
+ def wait_for_text(self, needle: str, timeout: float = 60.0) -> None:
+ try:
+ poll(lambda: canon(needle) in self.text() or self._dead(), timeout=timeout,
+ what=f"{needle[:40]!r} on screen")
+ except AssertionError as exc:
+ raise AssertionError(f"{exc}\n--- screen ---\n{self.dump()}") from None
+ assert self.proc.poll() is None, f"hermes exited ({self.proc.returncode}) waiting for {needle[:40]!r}\n{self.dump()}"
+
+ def wait_quiet(self, idle: float = 1.0, timeout: float = 30.0) -> None:
+ """Wait for a settled frame: the screen has not changed for ``idle`` seconds, ignoring
+ digits (status-bar clocks such as elapsed/since-last-turn tick every second while idle;
+ a busy spinner or a still-streaming reply changes non-digit cells and keeps us waiting)."""
+ def frame() -> str:
+ return _DIGITS.sub("#", "\n".join(self.lines()))
+ state = {"frame": frame(), "since": time.monotonic()}
+
+ def settled() -> bool:
+ self.track_members()
+ cur = frame()
+ now = time.monotonic()
+ if cur != state["frame"]:
+ state["frame"], state["since"] = cur, now
+ return now - state["since"] >= idle
+ try:
+ poll(settled, timeout=timeout, what="a settled frame", interval=0.1)
+ except AssertionError as exc:
+ with self._lock:
+ tail = bytes(self.raw[-600:])
+ raise AssertionError(f"{exc}\n--- screen ---\n{self.dump()}\n--- last bytes ---\n{tail!r}") from None
+
+ def _raw_mode(self) -> bool:
+ """The app put the slave side in full raw mode (cfmakeraw / libuv RAW: no canonical
+ editing, no echo, no CR->NL). Startup terminal probes use a partial raw mode that keeps
+ ICRNL, and a CR typed then would reach the app as a newline, not Enter."""
+ fd = os.open(self.pts, os.O_RDWR | os.O_NOCTTY)
+ try:
+ iflag, _o, _c, lflag = termios.tcgetattr(fd)[:4]
+ finally:
+ os.close(fd)
+ return not (lflag & (termios.ICANON | termios.ECHO) or iflag & termios.ICRNL)
+
+ def wait_ready(self, timeout: float = 120.0) -> None:
+ """The UI owns the terminal (raw mode) and its first frame has settled."""
+ deadline = time.monotonic() + timeout
+ while True:
+ remaining = max(1.0, deadline - time.monotonic())
+ poll(lambda: self._dead() or self._raw_mode(), timeout=remaining,
+ what="the UI to take the terminal (raw mode)")
+ assert self.proc.poll() is None, f"hermes exited ({self.proc.returncode}) during startup\n{self.dump()}"
+ self.wait_quiet(1.0, timeout=max(1.0, deadline - time.monotonic()))
+ if self._raw_mode():
+ return
+ if time.monotonic() >= deadline:
+ raise AssertionError(f"UI never settled in raw mode\n{self.dump()}")
+
+ def _dead(self) -> bool:
+ return self.proc.poll() is not None
+
+ def dump(self) -> str:
+ return "\n".join(self.lines()[-80:])
+
+ # -- interaction ----------------------------------------------------------------------------
+
+ def submit(self, text: str, timeout: float = 30.0) -> None:
+ """Type ``text``, wait for its echo in the composer, then press Enter in a separate write."""
+ before = self.count(text)
+ self.write(text)
+ poll(lambda: self.count(text) > before or self._dead(), timeout=timeout, what=f"echo of {text!r}")
+ # Not synchronization but input pacing: the classic CLI treats an Enter arriving within
+ # 50 ms of the last buffer change as a pasted newline (_RAPID_INPUT_ENTER_WINDOW_S), so a
+ # human-speed gap (10x that window) must separate the text from the submitting CR.
+ time.sleep(0.5)
+ self.write("\r")
+
+ def track_members(self) -> None:
+ """Remember every process in the PTY session and every descendant of the child (a
+ descendant that called setsid() has left the session but is still ours)."""
+ found = {(pid, _start_time(pid)) for pid in session_members(self.sid)}
+ try:
+ import psutil
+ found |= {(c.pid, _start_time(c.pid)) for c in psutil.Process(self.proc.pid).children(recursive=True)}
+ except Exception: # noqa: BLE001 - the child may exit between the scan and the walk
+ pass
+ self.seen_members.update(item for item in found if item[1] is not None)
+
+ def exit(self, command: str = "/exit", timeout: float = 60.0) -> int:
+ self.track_members()
+ self.submit(command)
+ deadline = time.monotonic() + timeout
+ while self.proc.poll() is None and time.monotonic() < deadline:
+ self.track_members()
+ time.sleep(0.05)
+ if self.proc.poll() is None:
+ raise AssertionError(f"hermes did not exit within {timeout:.0f}s of {command}\n{self.dump()}")
+ return self.proc.returncode
+
+ def leftover_processes(self, timeout: float = 15.0) -> list[str]:
+ """Processes still alive in the child's session, or seen as its descendants, after exit."""
+ def alive() -> list[int]:
+ pids = set(session_members(self.sid))
+ # Same pid AND same start time: a recycled pid is not our leftover.
+ pids |= {pid for pid, started in self.seen_members if _start_time(pid) == started}
+ return sorted(pids)
+ try:
+ poll(lambda: not alive(), timeout=timeout, what="the PTY session to empty")
+ except AssertionError:
+ return [f"{p}: {cmdline(p)}" for p in alive()]
+ return []
+
+ def close(self) -> None:
+ """Hard cleanup of exactly the tree this harness spawned (by session id, never by pattern)."""
+ try:
+ os.killpg(self.sid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ leftovers = set(session_members(self.sid)) # members that moved to their own process group
+ leftovers |= {pid for pid, started in self.seen_members if _start_time(pid) == started}
+ for pid in leftovers:
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ try:
+ self.proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ pass
+ try:
+ os.close(self.master)
+ except OSError:
+ pass
+ self._reader.join(timeout=5)
+ (self.root / "pty.raw").write_bytes(bytes(self.raw))
+
+ # -- persisted transcript -------------------------------------------------------------------
+
+ def wait_turns_persisted(self, n_replies: int, timeout: float = 90.0) -> None:
+ """Block until state.db holds ``n_replies`` non-empty assistant rows: the agent finished the
+ turn (a completion signal independent of what the screen shows, so a garbled render is
+ reported by the rendering assertions instead of as a timeout)."""
+ def done() -> bool:
+ if self._dead():
+ return True
+ try:
+ rows = self.persisted_messages()
+ except sqlite3.Error:
+ return False
+ return sum(1 for _s, r, c in rows if r == "assistant" and c.strip()) >= n_replies
+ poll(done, timeout=timeout, what=f"{n_replies} assistant replies persisted", interval=0.1)
+ assert self.proc.poll() is None, f"hermes exited ({self.proc.returncode}) mid-turn\n{self.dump()}"
+
+ def persisted_messages(self) -> list[tuple[str, str, str]]:
+ """(session_id, role, content) for every user/assistant row in the sandbox state.db."""
+ db = self.hermes_home / "state.db"
+ if not db.exists():
+ return []
+ conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
+ try:
+ rows = conn.execute(
+ "SELECT session_id, role, COALESCE(content, '') FROM messages "
+ "WHERE role IN ('user', 'assistant') ORDER BY id").fetchall()
+ finally:
+ conn.close()
+ return [(str(s), str(r), str(c)) for s, r, c in rows]
diff --git a/tests/e2e/core/terminal/_vt.py b/tests/e2e/core/terminal/_vt.py
new file mode 100644
index 00000000000..ba70e72ae92
--- /dev/null
+++ b/tests/e2e/core/terminal/_vt.py
@@ -0,0 +1,361 @@
+"""A small, dependency-free VT100/xterm screen emulator for PTY transcript assertions.
+
+A raw PTY byte dump shows frame HISTORY (every repaint, every spinner tick, every cursor-up
+redraw), not what the user finally sees, so "the reply appears exactly once" can only be judged
+on an emulated grid. This implements the subset prompt_toolkit (classic CLI) and Ink (TUI)
+actually emit: cursor motion, erase, scroll regions, insert/delete, autowrap with pending-wrap,
+the alternate screen, and wide characters. Lines that scroll off the top of the main screen go to
+``history`` (the terminal's scrollback), exactly like xterm; ``ESC[3J`` clears it.
+
+Everything unknown (SGR colours, OSC titles/hyperlinks, DEC private modes other than the alt
+screen and autowrap, DCS/APC strings, kitty keyboard flags) is parsed and ignored so it can never
+leak into the text grid.
+"""
+
+from __future__ import annotations
+
+import unicodedata
+
+
+def char_width(ch: str) -> int:
+ if unicodedata.combining(ch) or ch in "\u200b\u200c\u200d\ufe0e\ufe0f":
+ return 0
+ if unicodedata.east_asian_width(ch) in ("W", "F"):
+ return 2
+ return 1
+
+
+class _Grid:
+ def __init__(self, rows: int, cols: int) -> None:
+ self.rows, self.cols = rows, cols
+ self.lines = [self.blank() for _ in range(rows)]
+
+ def blank(self) -> list[str]:
+ return [" "] * self.cols
+
+
+class Screen:
+ def __init__(self, rows: int, cols: int, *, history_limit: int = 200_000) -> None:
+ self.rows, self.cols = rows, cols
+ self.history: list[str] = []
+ self.history_limit = history_limit
+ self._main = _Grid(rows, cols)
+ self._alt = _Grid(rows, cols)
+ self.grid = self._main
+ self.alt_active = False
+ self.x = self.y = 0
+ self.top, self.bottom = 0, rows - 1
+ self.autowrap = True
+ self._pending_wrap = False
+ self._saved = (0, 0)
+ self._main_saved_cursor = (0, 0)
+ self._state = "ground"
+ self._params = ""
+ self._pending_bytes = b""
+
+ # -- public ---------------------------------------------------------------------------------
+
+ def feed(self, data: bytes | str) -> None:
+ if isinstance(data, bytes):
+ data = self._pending_bytes + data
+ # Keep an incomplete trailing UTF-8 sequence for the next chunk.
+ cut = len(data)
+ for back in range(1, min(4, len(data)) + 1):
+ b = data[-back]
+ if b & 0xC0 == 0x80:
+ continue
+ if b & 0x80:
+ need = 2 if b & 0xE0 == 0xC0 else 3 if b & 0xF0 == 0xE0 else 4
+ if back < need:
+ cut = len(data) - back
+ break
+ self._pending_bytes = data[cut:]
+ data = data[:cut].decode("utf-8", "replace")
+ for ch in data:
+ self._step(ch)
+
+ def resize(self, rows: int, cols: int) -> None:
+ """Mimic a terminal resize: truncate/pad lines; content above the new height scrolls into history."""
+ for grid in (self._main, self._alt):
+ lines = [ln[:cols] + [" "] * max(0, cols - len(ln)) for ln in grid.lines]
+ if grid is self._main and len(lines) > rows:
+ # xterm keeps the cursor row visible: push surplus top rows into scrollback.
+ surplus = max(0, min(len(lines) - rows, self.y - rows + 1 if not self.alt_active else 0))
+ surplus = max(surplus, 0)
+ for ln in lines[:surplus]:
+ self._push_history("".join(ln))
+ lines = lines[surplus:]
+ if not self.alt_active:
+ self.y -= surplus
+ lines = lines[:rows] + [[" "] * cols for _ in range(rows - len(lines[:rows]))]
+ grid.lines, grid.rows, grid.cols = lines, rows, cols
+ self.rows, self.cols = rows, cols
+ self.top, self.bottom = 0, rows - 1
+ self.x, self.y = min(self.x, cols - 1), max(0, min(self.y, rows - 1))
+ self._pending_wrap = False
+
+ def display(self) -> list[str]:
+ return ["".join(c for c in ln if c is not None).rstrip() for ln in self.grid.lines]
+
+ def main_display(self) -> list[str]:
+ return ["".join(c for c in ln if c is not None).rstrip() for ln in self._main.lines]
+
+ def transcript(self) -> list[str]:
+ """Scrollback followed by the visible main screen (what a user can scroll through)."""
+ return list(self.history) + self.main_display()
+
+ # -- parser ---------------------------------------------------------------------------------
+
+ def _step(self, ch: str) -> None:
+ st = self._state
+ if st == "ground":
+ if ch == "\x1b":
+ self._state = "esc"
+ elif ch < " " or ch == "\x7f":
+ self._control(ch)
+ else:
+ self._print(ch)
+ elif st == "esc":
+ self._state = "ground"
+ if ch == "[":
+ self._state, self._params = "csi", ""
+ elif ch == "]":
+ self._state = "osc"
+ elif ch in "PX^_":
+ self._state = "str"
+ elif ch in "()*+#% ":
+ self._state = "esc_skip1"
+ elif ch == "7":
+ self._saved = (self.x, self.y)
+ elif ch == "8":
+ self.x, self.y = self._saved
+ self._pending_wrap = False
+ elif ch == "M":
+ self._reverse_index()
+ elif ch == "D":
+ self._linefeed()
+ elif ch == "E":
+ self.x = 0
+ self._linefeed()
+ elif ch == "c":
+ self._full_reset()
+ elif st == "esc_skip1":
+ self._state = "ground"
+ elif st == "csi":
+ if "\x40" <= ch <= "\x7e":
+ self._state = "ground"
+ self._csi(self._params, ch)
+ elif ch == "\x1b":
+ self._state = "esc"
+ else:
+ self._params += ch
+ elif st in ("osc", "str"):
+ if ch == "\x07":
+ self._state = "ground"
+ elif ch == "\x1b":
+ self._state = st + "_esc"
+ elif st in ("osc_esc", "str_esc"):
+ # ESC \ terminates; anything else stays inside the string.
+ self._state = "ground" if ch == "\\" else st[:-4]
+
+ def _control(self, ch: str) -> None:
+ if ch == "\r":
+ self.x = 0
+ self._pending_wrap = False
+ elif ch in "\n\x0b\x0c":
+ self._linefeed()
+ elif ch == "\b":
+ self.x = max(0, self.x - 1)
+ self._pending_wrap = False
+ elif ch == "\t":
+ self.x = min(self.cols - 1, (self.x // 8 + 1) * 8)
+
+ def _print(self, ch: str) -> None:
+ w = char_width(ch)
+ if w == 0:
+ return
+ if self._pending_wrap:
+ self.x = 0
+ self._linefeed()
+ self._pending_wrap = False
+ if w == 2 and self.x == self.cols - 1:
+ if self.autowrap:
+ self.grid.lines[self.y][self.x] = " "
+ self.x = 0
+ self._linefeed()
+ else:
+ return
+ line = self.grid.lines[self.y]
+ line[self.x] = ch
+ if w == 2:
+ line[self.x + 1] = None # type: ignore[call-overload]
+ if self.x + w >= self.cols:
+ self.x = self.cols - 1
+ self._pending_wrap = self.autowrap
+ else:
+ self.x += w
+
+ # -- movement / scrolling ------------------------------------------------------------------
+
+ def _push_history(self, text: str) -> None:
+ self.history.append(text.replace("\x00", "").rstrip())
+ if len(self.history) > self.history_limit:
+ del self.history[: len(self.history) - self.history_limit]
+
+ def _scroll_up(self, n: int = 1) -> None:
+ g = self.grid
+ for _ in range(n):
+ gone = g.lines.pop(self.top)
+ if g is self._main and self.top == 0:
+ self._push_history("".join(c for c in gone if c is not None))
+ g.lines.insert(self.bottom, g.blank())
+
+ def _scroll_down(self, n: int = 1) -> None:
+ g = self.grid
+ for _ in range(n):
+ g.lines.pop(self.bottom)
+ g.lines.insert(self.top, g.blank())
+
+ def _linefeed(self) -> None:
+ self._pending_wrap = False
+ if self.y == self.bottom:
+ self._scroll_up()
+ elif self.y < self.rows - 1:
+ self.y += 1
+
+ def _reverse_index(self) -> None:
+ if self.y == self.top:
+ self._scroll_down()
+ elif self.y > 0:
+ self.y -= 1
+
+ def _full_reset(self) -> None:
+ self._main, self._alt = _Grid(self.rows, self.cols), _Grid(self.rows, self.cols)
+ self.grid, self.alt_active = self._main, False
+ self.x = self.y = 0
+ self.top, self.bottom = 0, self.rows - 1
+ self.autowrap, self._pending_wrap = True, False
+
+ # -- CSI ------------------------------------------------------------------------------------
+
+ def _csi(self, raw: str, final: str) -> None:
+ private = raw[:1] if raw[:1] in "?<>=" else ""
+ body = raw[len(private):]
+ if any(c in body for c in " !\"#$%&'*+,-./"): # intermediates (DECSCUSR etc.): ignore
+ return
+ try:
+ args = [int(p) if p else 0 for p in body.split(";")] if body else []
+ except ValueError:
+ return # sub-parameters (colon form) only appear in SGR, which we ignore anyway
+
+ def a(i: int = 0, default: int = 1) -> int:
+ v = args[i] if len(args) > i else 0
+ return v or default
+
+ if private == "?":
+ if final in "hl":
+ on = final == "h"
+ for mode in args:
+ if mode == 7:
+ self.autowrap = on
+ elif mode in (47, 1047, 1049):
+ self._set_alt(on, save_cursor=mode == 1049)
+ return
+ if private:
+ return
+ self._pending_wrap = False if final not in "m" else self._pending_wrap
+ g = self.grid
+ if final == "A":
+ self.y = max(self.top if self.y >= self.top else 0, self.y - a())
+ elif final == "B" or final == "e":
+ self.y = min(self.bottom if self.y <= self.bottom else self.rows - 1, self.y + a())
+ elif final == "C" or final == "a":
+ self.x = min(self.cols - 1, self.x + a())
+ elif final == "D":
+ self.x = max(0, self.x - a())
+ elif final == "E":
+ self.x, self.y = 0, min(self.rows - 1, self.y + a())
+ elif final == "F":
+ self.x, self.y = 0, max(0, self.y - a())
+ elif final in "G`":
+ self.x = min(self.cols - 1, a() - 1)
+ elif final == "d":
+ self.y = min(self.rows - 1, a() - 1)
+ elif final in "Hf":
+ self.y = min(self.rows - 1, a(0) - 1)
+ self.x = min(self.cols - 1, a(1) - 1)
+ elif final == "J":
+ mode = args[0] if args else 0
+ if mode == 0:
+ g.lines[self.y][self.x:] = [" "] * (self.cols - self.x)
+ for r in range(self.y + 1, self.rows):
+ g.lines[r] = g.blank()
+ elif mode == 1:
+ g.lines[self.y][: self.x + 1] = [" "] * (self.x + 1)
+ for r in range(self.y):
+ g.lines[r] = g.blank()
+ elif mode == 2:
+ g.lines = [g.blank() for _ in range(self.rows)]
+ elif mode == 3:
+ self.history.clear()
+ elif final == "K":
+ mode = args[0] if args else 0
+ line = g.lines[self.y]
+ if mode == 0:
+ line[self.x:] = [" "] * (self.cols - self.x)
+ elif mode == 1:
+ line[: self.x + 1] = [" "] * (self.x + 1)
+ else:
+ g.lines[self.y] = g.blank()
+ elif final == "X":
+ n = min(a(), self.cols - self.x)
+ g.lines[self.y][self.x:self.x + n] = [" "] * n
+ elif final == "P":
+ line = g.lines[self.y]
+ n = min(a(), self.cols - self.x)
+ del line[self.x:self.x + n]
+ line.extend([" "] * n)
+ elif final == "@":
+ line = g.lines[self.y]
+ n = min(a(), self.cols - self.x)
+ line[self.x:self.x] = [" "] * n
+ del line[self.cols:]
+ elif final in "LM":
+ if self.top <= self.y <= self.bottom:
+ for _ in range(min(a(), self.bottom - self.y + 1)):
+ if final == "L":
+ g.lines.pop(self.bottom)
+ g.lines.insert(self.y, g.blank())
+ else:
+ g.lines.pop(self.y)
+ g.lines.insert(self.bottom, g.blank())
+ self.x = 0
+ elif final == "S":
+ self._scroll_up(a())
+ elif final == "T":
+ self._scroll_down(a())
+ elif final == "r":
+ top = (args[0] if args and args[0] else 1) - 1
+ bottom = (args[1] if len(args) > 1 and args[1] else self.rows) - 1
+ if 0 <= top < bottom < self.rows:
+ self.top, self.bottom = top, bottom
+ self.x = self.y = 0
+ elif final == "s":
+ self._saved = (self.x, self.y)
+ elif final == "u":
+ self.x, self.y = self._saved
+
+ def _set_alt(self, on: bool, *, save_cursor: bool) -> None:
+ if on == self.alt_active:
+ return
+ if on:
+ if save_cursor:
+ self._main_saved_cursor = (self.x, self.y)
+ self._alt = _Grid(self.rows, self.cols)
+ self.grid, self.alt_active = self._alt, True
+ else:
+ self.grid, self.alt_active = self._main, False
+ if save_cursor:
+ self.x, self.y = self._main_saved_cursor
+ self.top, self.bottom = 0, self.rows - 1
+ self._pending_wrap = False
diff --git a/tests/e2e/core/terminal/test_terminal_transcript_pty.py b/tests/e2e/core/terminal/test_terminal_transcript_pty.py
new file mode 100644
index 00000000000..7e8532ca802
--- /dev/null
+++ b/tests/e2e/core/terminal/test_terminal_transcript_pty.py
@@ -0,0 +1,207 @@
+"""C2 on terminal surfaces: what the classic CLI and the Ink TUI finally show is the transcript,
+exactly once, unmangled, and matches what was persisted.
+
+Real chain: a real ``hermes chat --cli`` / ``hermes --tui`` process (the TUI spawns its real Node
+frontend and real ``tui_gateway`` child) on a real PTY, a real AIAgent + SessionDB on disk, and the
+recording fake OpenAI-compatible provider streaming scripted multi-chunk replies, a tool-call turn
+and a reasoning turn. The byte stream is rendered through a VT emulator so assertions are made on
+the grid a user would see (plus the scrollback they could scroll to), not on repaint history.
+
+Invariants, checked on the settled final frame of every scenario:
+ * every scripted assistant reply is on screen exactly once and verbatim (== the scripted text,
+ so streamed deltas were neither double-appended, dropped nor reordered);
+ * every user prompt is echoed exactly once, and prompts/replies appear in conversation order;
+ * a tool call's command is rendered once; reasoning is never rendered twice;
+ * rendered == persisted: every user/assistant row in state.db is on screen exactly once, and the
+ persisted assistant text equals the scripted stream;
+ * ``/exit`` exits 0 within a bounded time and leaves no process behind in the PTY session.
+
+The ``resize`` scenarios change the terminal width while a long reply is streaming (SIGWINCH via
+the PTY), the recurring "history re-appended on resize" shape. ``resize_scrollback`` replays it on
+a normal 24-row classic-CLI terminal, where earlier turns already sit in scrollback: that case is a
+strict xfail for the open live bug #95375 and turns red (XPASS) once it is fixed.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.terminal._pty import REPO_ROOT, PtyHermes, canon
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="real PTY + /proc session scan"),
+ # Cleanup SIGKILLs only processes whose session id is the PTY child this test spawned; a
+ # grandchild reparented to init after its parent died is outside the pid subtree but still ours.
+ pytest.mark.live_system_guard_bypass,
+]
+
+TITLE = "Scripted session title"
+
+
+class DuplicateRender(AssertionError):
+ """A message rendered more (or fewer) times than once: the C2 failure itself, as opposed to a
+ harness timeout, so an xfail for a known duplication bug can never swallow a hang."""
+
+
+def _long_reply(tag: str, words: int) -> str:
+ return f"{tag} begins " + " ".join(f"{tag.lower()}{i:03d}" for i in range(words)) + f" {tag}-END"
+
+
+@dataclass
+class Turn:
+ prompt: str
+ responses: list # scripted provider responses consumed by this user turn
+ reply: str # final assistant text the user must see
+ resize_to: tuple[int, int] | None = None # (rows, cols) applied mid-stream
+ tool_command: str | None = None
+ reasoning: str | None = None
+
+
+@dataclass
+class Scenario:
+ name: str
+ turns: list[Turn] = field(default_factory=list)
+ rows: int = 80 # tall enough that the whole conversation stays on screen / in the TUI viewport
+
+
+def _scenarios(surface: str) -> dict[str, Scenario]:
+ long_a = _long_reply("ALPHA", 140)
+ long_r = _long_reply("RESIZE", 120)
+ tool_cmd = "echo TOOLMARK-7f3a"
+ # Classic CLI resizes are widen-only: a real terminal truncates or reflows narrowed rows
+ # (emulator-specific), which is not the invariant under test. Two of them, because the CLI
+ # seeds its width baseline on the first SIGWINCH and only repaints on an observed change.
+ # The TUI repaints its own fullscreen viewport, so it gets both directions.
+ widths = [(116,), (132,)] if surface == "cli" else [(128,), (84,)]
+
+ def resize_turns(tag: str, rows: int) -> list[Turn]:
+ return [
+ Turn(f"warm up {tag} delta-q1", [Text("DELTA short warmup reply DELTA-END")],
+ "DELTA short warmup reply DELTA-END"),
+ *[
+ Turn(f"stream while resizing {tag} epsilon-q{i + 2}",
+ [Text(long_r.replace("RESIZE", f"RESIZE{i}"), chunk_chars=5, delay_per_chunk=0.012)],
+ long_r.replace("RESIZE", f"RESIZE{i}"), resize_to=(rows, cols))
+ for i, (cols,) in enumerate(widths)
+ ],
+ Turn(f"after the resize {tag} omega-q9", [Text("OMEGA settled reply OMEGA-END")],
+ "OMEGA settled reply OMEGA-END"),
+ ]
+
+ return {
+ "turns": Scenario("turns", [
+ Turn("first question alpha-q1", [Text(long_a, chunk_chars=7, delay_per_chunk=0.002)], long_a),
+ Turn("please run the tool beta-q2",
+ [ToolCall("terminal", {"command": tool_cmd}), Text("BETA after the tool BETA-END")],
+ "BETA after the tool BETA-END", tool_command=tool_cmd),
+ Turn("think then answer gamma-q3",
+ [Text("GAMMA answered with reasoning GAMMA-END",
+ reasoning="scripted reasoning about gamma zeta-reason")],
+ "GAMMA answered with reasoning GAMMA-END", reasoning="scripted reasoning about gamma zeta-reason"),
+ ]),
+ "resize": Scenario("resize", resize_turns("tall", 80)),
+ # A normal 24-row terminal: by the time the width changes, earlier turns have already
+ # scrolled into the terminal's scrollback, where a redraw must not print them again.
+ "resize_scrollback": Scenario("resize_scrollback", resize_turns("short", 24), rows=24),
+ }
+
+
+def _tui_available() -> bool:
+ return shutil.which("node") is not None and (REPO_ROOT / "ui-tui" / "dist" / "entry.js").is_file()
+
+
+SURFACES = {
+ "cli": ["chat", "--cli", "--yolo"],
+ "tui": ["--tui", "--yolo"],
+}
+
+
+MATRIX = [
+ ("cli", "turns"),
+ ("cli", "resize"),
+ pytest.param("cli", "resize_scrollback", marks=pytest.mark.xfail(
+ strict=True, raises=DuplicateRender,
+ reason="LIVE BUG #95375 (open): a width-changing resize clears only the visible screen "
+ "(CSI 2J) and replays the last 200 output lines, so turns already in scrollback "
+ "are printed again. strict: this XPASSes (and fails) once it is fixed.")),
+ ("tui", "turns"),
+ ("tui", "resize"),
+]
+
+
[email protected](("surface", "scenario"), MATRIX)
+def test_terminal_transcript_integrity(surface: str, scenario: str, tmp_path: Path) -> None:
+ if surface == "tui" and not _tui_available():
+ if os.environ.get("HERMES_E2E_REQUIRE_TUI") == "1":
+ pytest.fail("ui-tui/dist/entry.js or node missing but HERMES_E2E_REQUIRE_TUI=1")
+ pytest.skip("Ink TUI not built (cd ui-tui && npm run build) or node missing")
+
+ spec = _scenarios(surface)[scenario]
+ script = [r for turn in spec.turns for r in turn.responses]
+ rows, cols = spec.rows, 100
+ with FakeLLMServer(script, aux=lambda _req: Text(TITLE)) as llm:
+ term = PtyHermes(tmp_path, SURFACES[surface], llm, rows=rows, cols=cols)
+ try:
+ term.wait_ready()
+ expected_main = 0
+ for done, turn in enumerate(spec.turns, start=1):
+ term.submit(turn.prompt)
+ expected_main += len(turn.responses)
+ if turn.resize_to:
+ # Resize once the stream is visibly under way, then keep streaming.
+ first_words = canon(turn.reply)[:24]
+ term.wait_for_text(first_words)
+ term.resize(*turn.resize_to)
+ llm.wait_for_requests(expected_main, timeout=60)
+ term.wait_turns_persisted(done)
+ term.wait_quiet(1.0, timeout=60)
+
+ final = term.lines()
+ text = canon("".join(final))
+ dump = "\n".join(final[-120:])
+
+ positions = []
+ for turn in spec.turns:
+ n_reply = text.count(canon(turn.reply))
+ if n_reply != 1:
+ raise DuplicateRender(
+ f"[{surface}/{scenario}] assistant reply rendered {n_reply}x (want exactly 1, verbatim): "
+ f"{turn.reply[:60]!r}\n{dump}")
+ n_prompt = text.count(canon(turn.prompt))
+ if n_prompt != 1:
+ raise DuplicateRender(
+ f"[{surface}/{scenario}] user prompt echoed {n_prompt}x (want 1): {turn.prompt!r}\n{dump}")
+ positions += [text.index(canon(turn.prompt)), text.index(canon(turn.reply))]
+ if turn.tool_command:
+ n_cmd = text.count(canon(turn.tool_command))
+ assert n_cmd == 1, f"[{surface}/{scenario}] tool call rendered {n_cmd}x\n{dump}"
+ if turn.reasoning:
+ n_reason = text.count(canon(turn.reasoning))
+ assert n_reason <= 1, f"[{surface}/{scenario}] reasoning rendered {n_reason}x\n{dump}"
+ assert positions == sorted(positions), (
+ f"[{surface}/{scenario}] transcript out of conversation order\n{dump}")
+
+ code = term.exit()
+ assert code == 0, f"[{surface}/{scenario}] /exit returned {code}\n{term.dump()}"
+ leftovers = term.leftover_processes()
+ assert not leftovers, f"[{surface}/{scenario}] processes left after /exit: {leftovers}"
+
+ persisted = term.persisted_messages()
+ sessions = {s for s, _r, _c in persisted}
+ assert len(sessions) == 1, f"turns split across sessions: {sessions}"
+ users = [c for _s, r, c in persisted if r == "user"]
+ assistants = [c for _s, r, c in persisted if r == "assistant" and c.strip()]
+ assert users == [t.prompt for t in spec.turns], f"persisted user rows {users!r}"
+ assert assistants == [t.reply for t in spec.turns], "persisted assistant text != scripted stream"
+ for content in users + assistants:
+ assert text.count(canon(content)) == 1, (
+ f"[{surface}/{scenario}] persisted row not rendered exactly once: {content[:60]!r}")
+ finally:
+ term.close()