The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: entrypoint parity matrix with a real stdio MCP server (C19, C15)
teknium1ae4c5a0874c7
diff --git a/tests/e2e/core/parity/__init__.py b/tests/e2e/core/parity/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/parity/_boot_contract.py b/tests/e2e/core/parity/_boot_contract.pynew file mode 100644index 00000000000..f693e7973e0--- /dev/null+++ b/tests/e2e/core/parity/_boot_contract.py@@ -0,0 +1,54 @@+"""Bridge to the Desktop's real READY-sentinel parser (``apps/desktop/electron/backend-ready.ts``).++There is no shared constant for the sentinel format, and regexing the TS source+would test a copy of the contract. Instead the captured backend stdout is fed+through the parser itself under Node (``desktop_ready_parse.mjs``), so the Python+side asserts exactly what the Desktop would conclude from those bytes.+"""++from __future__ import annotations++import json+import re+import shutil+import subprocess+from pathlib import Path++import pytest++from tests.e2e.core.parity._helpers import REPO_ROOT++PARSER_TS = REPO_ROOT / "apps" / "desktop" / "electron" / "backend-ready.ts"+BRIDGE_MJS = Path(__file__).with_name("desktop_ready_parse.mjs")+# Native TypeScript type-stripping landed unflagged in Node 22.18 / 23.6.+_MIN_NODE = (22, 18)+++def node_binary() -> str | None:+ node = shutil.which("node")+ if not node:+ return None+ out = subprocess.run([node, "--version"], capture_output=True, text=True, timeout=30,+ stdin=subprocess.DEVNULL).stdout.strip()+ m = re.match(r"v(\d+)\.(\d+)", out)+ if not m or (int(m.group(1)), int(m.group(2))) < _MIN_NODE:+ return None+ return node+++def require_node() -> str:+ node = node_binary()+ if node is None:+ pytest.skip(f"needs node >= {'.'.join(map(str, _MIN_NODE))} to run the Desktop READY parser")+ return node+++def desktop_parse(stdout_bytes: str) -> dict:+ """What ``waitForDashboardPort`` resolves/rejects with for this exact stdout stream."""+ proc = subprocess.run(+ [require_node(), str(BRIDGE_MJS), str(PARSER_TS), "5000"], input=stdout_bytes,+ capture_output=True, text=True, timeout=60,+ )+ assert proc.returncode == 0, f"desktop parser bridge crashed: {proc.stderr[-2000:]}"+ return json.loads(proc.stdout.strip().splitlines()[-1])+diff --git a/tests/e2e/core/parity/_drive_acp.py b/tests/e2e/core/parity/_drive_acp.pynew file mode 100644index 00000000000..25bd77afef6--- /dev/null+++ b/tests/e2e/core/parity/_drive_acp.py@@ -0,0 +1,149 @@+"""Entrypoint driver for the parity matrix: the ACP stdio server (``hermes acp``).++Follows the driver contract in ``_drive_cli``. The client side speaks+newline-delimited JSON-RPC 2.0 itself (no SDK client) so the driver controls+every byte and the shutdown path: ``initialize`` -> ``session/new`` (ACP's+documented cwd channel) -> ``session/prompt``, collecting+``agent_message_chunk`` text from ``session/update`` notifications, then stdin+EOF — the way an editor host closes the server.+"""++from __future__ import annotations++import json+import queue+import subprocess+import threading+import time+from typing import Any++from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv, terminate+from tests.fakes.fake_llm_provider import FakeLLMServer++ACP_TOOLSET = "hermes-acp" # acp_adapter/session.py::_expand_acp_enabled_toolsets default+EOF_EXIT_TIMEOUT = 30.0+++class _AcpClient:+ """Minimal ACP client over a subprocess's stdio (one reader thread)."""++ def __init__(self, proc: subprocess.Popen) -> None:+ self.proc = proc+ self._next_id = 0+ self._inbox: queue.Queue[dict[str, Any] | None] = queue.Queue()+ self.chunks: list[str] = []+ self.updates: list[dict[str, Any]] = []+ self.server_requests: list[str] = []+ self.stray_stdout: list[str] = []+ threading.Thread(target=self._pump, daemon=True).start()++ def _pump(self) -> None:+ for line in self.proc.stdout: # type: ignore[union-attr]+ line = line.strip()+ if not line:+ continue+ try:+ self._inbox.put(json.loads(line))+ except json.JSONDecodeError:+ # stdout must stay pure JSON-RPC; keep evidence instead of crashing.+ self.stray_stdout.append(line)+ self._inbox.put(None)++ def _send(self, msg: dict[str, Any]) -> None:+ self.proc.stdin.write(json.dumps(msg) + "\n") # type: ignore[union-attr]+ self.proc.stdin.flush() # type: ignore[union-attr]++ def request(self, method: str, params: dict[str, Any], timeout: float) -> dict[str, Any]:+ self._next_id += 1+ rid = self._next_id+ self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})+ deadline = time.monotonic() + timeout+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise AssertionError(f"ACP {method} got no response within {timeout}s")+ try:+ msg = self._inbox.get(timeout=remaining)+ except queue.Empty:+ continue+ if msg is None:+ raise AssertionError(f"ACP server closed stdout during {method} (rc={self.proc.poll()})")+ if "method" in msg:+ self._handle_incoming(msg)+ elif msg.get("id") == rid:+ if "error" in msg:+ raise AssertionError(f"ACP {method} failed: {msg['error']}")+ return msg.get("result") or {}++ def _handle_incoming(self, msg: dict[str, Any]) -> None:+ method, params = msg["method"], msg.get("params") or {}+ if "id" not in msg: # notification+ if method == "session/update":+ update = params.get("update") or {}+ self.updates.append(update)+ content = update.get("content") or {}+ if update.get("sessionUpdate") == "agent_message_chunk" and content.get("type") == "text":+ self.chunks.append(content.get("text", ""))+ return+ self.server_requests.append(method)+ if method == "session/request_permission":+ # An editor user clicking "allow once" (fall back to the first offered option).+ options = params.get("options") or []+ pick = next((o for o in options if o.get("kind") == "allow_once"), options[0] if options else None)+ outcome = ({"outcome": "selected", "optionId": pick["optionId"]} if pick+ else {"outcome": "cancelled"})+ self._send({"jsonrpc": "2.0", "id": msg["id"], "result": {"outcome": outcome}})+ return+ # We advertise no fs/terminal client capabilities, so anything else is unexpected.+ self._send({"jsonrpc": "2.0", "id": msg["id"],+ "error": {"code": -32601, "message": f"client does not implement {method}"}})+++def drive_acp(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ stderr_path = ph.root / "acp_stderr.log"+ with open(stderr_path, "w", encoding="utf-8") as stderr_fh:+ proc = subprocess.Popen(+ hermes_argv("acp"), cwd=ph.project, env=ph.env(), stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=stderr_fh, text=True, bufsize=1,+ )+ client = _AcpClient(proc)+ graceful = True+ stop_reason = None+ try:+ init = client.request("initialize", {+ "protocolVersion": 1,+ "clientCapabilities": {"fs": {"readTextFile": False, "writeTextFile": False}, "terminal": False},+ "clientInfo": {"name": "parity-suite", "version": "1.0"},+ }, timeout=60)+ session = client.request("session/new", {"cwd": str(ph.project), "mcpServers": []},+ timeout=120)+ session_id = session["sessionId"]+ result = client.request("session/prompt", {+ "sessionId": session_id, "prompt": [{"type": "text", "text": prompt}],+ }, timeout=TURN_TIMEOUT)+ stop_reason = result.get("stopReason")+ finally:+ # Normal host shutdown: close the pipe and let the server exit on EOF.+ try:+ proc.stdin.close() # type: ignore[union-attr]+ except OSError:+ pass+ try:+ proc.wait(timeout=EOF_EXIT_TIMEOUT)+ except subprocess.TimeoutExpired:+ graceful = False+ terminate(proc)+ return DriveResult(+ final_text="".join(client.chunks),+ toolset=ACP_TOOLSET,+ cwd_channel="session/new cwd",+ graceful_exit=graceful,+ extra={+ "stop_reason": stop_reason,+ "returncode": proc.returncode,+ "agent_info": (init or {}).get("agentInfo"),+ "server_requests": client.server_requests,+ "stray_stdout": client.stray_stdout[:20],+ "stderr_log": str(stderr_path),+ },+ )diff --git a/tests/e2e/core/parity/_drive_cli.py b/tests/e2e/core/parity/_drive_cli.pynew file mode 100644index 00000000000..1d87cd4665a--- /dev/null+++ b/tests/e2e/core/parity/_drive_cli.py@@ -0,0 +1,43 @@+"""Entrypoint drivers for the parity matrix: CLI subprocess entrypoints.++Driver contract (every ``_drive_*.py`` module follows it)::++ def drive(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult++* spawn the REAL entrypoint with ``ph.env()`` (hermetic fake HOME, no real+ credentials) — cwd ``ph.project`` unless the surface documents another cwd+ channel (then use that channel and say so in ``DriveResult.cwd_channel``);+* run exactly ONE user turn with ``prompt`` against ``srv`` (the scripted+ responder makes the model call the MCP canary tool, then answer+ ``FINAL_ANSWER``);+* return what the surface delivered to ITS client in ``final_text``;+* stop the entrypoint through its NORMAL shutdown path (exit, stdin EOF,+ SIGTERM, RPC) before returning; never SIGKILL except as a last resort after a+ bounded graceful wait (and then report it via ``graceful_exit=False``).+"""++from __future__ import annotations++import subprocess++from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv+from tests.fakes.fake_llm_provider import FakeLLMServer+++def _run_cli(ph: ParityHome, *args: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ hermes_argv(*args), cwd=ph.project, env=ph.env(), capture_output=True, text=True,+ timeout=TURN_TIMEOUT, stdin=subprocess.DEVNULL,+ )+++def drive_oneshot(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ proc = _run_cli(ph, "-z", prompt)+ assert proc.returncode == 0, f"hermes -z exited {proc.returncode}: {proc.stderr[-2000:]}"+ return DriveResult(final_text=proc.stdout.strip(), toolset="hermes-cli")+++def drive_chat_q(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ proc = _run_cli(ph, "chat", "-q", prompt, "-Q")+ assert proc.returncode == 0, f"hermes chat -q exited {proc.returncode}: {proc.stderr[-2000:]}"+ return DriveResult(final_text=proc.stdout.strip(), toolset="hermes-cli")diff --git a/tests/e2e/core/parity/_drive_cron.py b/tests/e2e/core/parity/_drive_cron.pynew file mode 100644index 00000000000..83bf4faac2b--- /dev/null+++ b/tests/e2e/core/parity/_drive_cron.py@@ -0,0 +1,70 @@+"""Entrypoint driver for the parity matrix: cron run-now (``hermes cron run <id>``).++Follows the driver contract in ``_drive_cli``. ``hermes cron create`` writes the+job (``--deliver local``: no platform; ``--workdir``: cron's documented+per-job cwd/context channel, see ``hermes cron create --help``), then+``hermes cron run <id>`` executes it. With no gateway owning the store the CLI+runs the job synchronously through ``cron.scheduler.run_job`` — the same agent+build the ticker uses (``hermes_cli/cron.py::_job_action`` forces the+synchronous path) — and prints ``Ran now: succeeded.``. The job's saved output+file (``cron/output/<id>/<ts>.md``, ``## Response`` section) is what cron+delivers locally, so that is ``final_text``.++Both CLI calls run from the fake HOME, not the project: a scheduled job's+process cwd is whatever the ticker had, so the workdir is the only channel+that may carry the project context.+"""++from __future__ import annotations++import re+import subprocess++from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome, hermes_argv+from tests.fakes.fake_llm_provider import FakeLLMServer++# cron/scheduler.py::_resolve_cron_enabled_toolsets -> _get_platform_tools(cfg, "cron") default.+CRON_TOOLSET = "hermes-cron"+_JOB_ID = re.compile(r"Created job: (\S+)")+_RESPONSE = re.compile(r"^## Response\s*\n(.*)\Z", re.S | re.M)+++def _cron(ph: ParityHome, *args: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ hermes_argv("cron", *args), cwd=ph.home, env=ph.env(), capture_output=True, text=True,+ timeout=TURN_TIMEOUT, stdin=subprocess.DEVNULL,+ )+++def drive_cron(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ created = _cron(ph, "create", "1d", prompt, "--name", "parity", "--deliver", "local",+ "--workdir", str(ph.project))+ match = _JOB_ID.search(created.stdout)+ assert created.returncode == 0 and match, (+ f"hermes cron create exited {created.returncode}: {created.stdout[-1000:]} {created.stderr[-2000:]}")+ job_id = match.group(1)++ ran = _cron(ph, "run", job_id)+ assert ran.returncode == 0, f"hermes cron run exited {ran.returncode}: {ran.stderr[-2000:]}"+ # Anything but a synchronous verdict means the run was handed to a ticker/background+ # worker this driver cannot observe — a harness problem, not a parity result.+ assert "Ran now:" in ran.stdout, f"hermes cron run did not execute synchronously: {ran.stdout[-1000:]}"++ outputs = sorted((ph.hermes_home / "cron" / "output" / job_id).glob("*.md"))+ final_text = None+ if outputs:+ body = outputs[-1].read_text(encoding="utf-8")+ m = _RESPONSE.search(body)+ final_text = (m.group(1) if m else body).strip()+ return DriveResult(+ final_text=final_text,+ toolset=CRON_TOOLSET,+ cwd_channel="job workdir",+ graceful_exit=True, # both CLI invocations exited on their own (subprocess.run, no signal)+ extra={+ "job_id": job_id,+ "run_stdout": ran.stdout.strip()[-500:],+ "run_succeeded": "Ran now: succeeded." in ran.stdout,+ "output_file": str(outputs[-1]) if outputs else None,+ },+ )diff --git a/tests/e2e/core/parity/_drive_gateway.py b/tests/e2e/core/parity/_drive_gateway.pynew file mode 100644index 00000000000..3f2862e78ca--- /dev/null+++ b/tests/e2e/core/parity/_drive_gateway.py@@ -0,0 +1,246 @@+"""Entrypoint drivers for the parity matrix: messaging gateway + OpenAI-compatible API server.++Both follow the driver contract in ``_drive_cli``. Daemon surfaces have no launch+directory, so the documented cwd channel ``terminal.cwd`` is pinned in config.yaml+(``DriveResult.cwd_channel = "terminal.cwd"``) and credentials go in the fixture+home's ``.env`` exactly as a user configures them.++* ``drive_gateway`` — the REAL gateway entrypoint (``gateway.run.main``: host-attach+ decision, PID claim, MCP discovery, ``GatewayRunner.start()``, signal handlers,+ graceful shutdown tail) in a subprocess; only the Telegram adapter instance is a+ recording fake (``_gateway_child.py``), fed one inbound DM through its normal+ ``handle_message`` path.+* ``drive_api_server`` — the stock ``python -m gateway.run`` with only the+ ``api_server`` platform enabled (loopback, free port, strong key); one+ non-streaming ``POST /v1/chat/completions``.++Both stop through the normal operator path of ``hermes gateway stop``: write the+planned-stop marker for the gateway PID, then SIGTERM (a bare SIGTERM is treated+as an unexpected kill and exits non-zero on purpose so supervisors revive it).+"""++from __future__ import annotations++import contextlib+import json+import os+import queue+import secrets+import signal+import socket+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path+from typing import Any++from tests.e2e.core.parity._helpers import TURN_TIMEOUT, DriveResult, ParityHome+from tests.fakes.fake_llm_provider import FakeLLMServer++GATEWAY_CHILD = Path(__file__).with_name("_gateway_child.py")+_LINE_PREFIX = "PARITY-GW "+STOP_TIMEOUT = 60.0+# Telegram private chats use the user id as chat id; the child reads it from the env+# (importing the child here would import gateway.run into the test process).+PARITY_USER_ID = "424242"+++def _append_env(ph: ParityHome, values: dict[str, str]) -> None:+ path = ph.hermes_home / ".env"+ existing = path.read_text(encoding="utf-8") if path.exists() else ""+ if existing and not existing.endswith("\n"):+ existing += "\n"+ path.write_text(existing + "".join(f"{k}={v}\n" for k, v in values.items()), encoding="utf-8")+++def _spawn(ph: ParityHome, argv: list[str], log_name: str, extra_env: dict[str, str] | None = None):+ log_path = ph.root / log_name+ log = open(log_path, "wb") # noqa: SIM115 - closed by _stop+ proc = subprocess.Popen(+ argv, cwd=ph.project, env=ph.env(extra_env), stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE, stderr=log, text=True, bufsize=1,+ )+ proc._parity_log = log # type: ignore[attr-defined]+ proc._parity_log_path = log_path # type: ignore[attr-defined]+ return proc+++def _stdout_pump(proc: subprocess.Popen) -> "queue.Queue[str | None]":+ lines: queue.Queue[str | None] = queue.Queue()++ def pump() -> None:+ assert proc.stdout is not None+ for line in proc.stdout:+ lines.put(line)+ lines.put(None)++ threading.Thread(target=pump, daemon=True, name="parity-gw-stdout").start()+ return lines+++def _log_tail(proc: subprocess.Popen, n: int = 4000) -> str:+ try:+ return proc._parity_log_path.read_text(encoding="utf-8", errors="replace")[-n:] # type: ignore[attr-defined]+ except OSError:+ return ""+++def _stop(ph: ParityHome, proc: subprocess.Popen) -> bool:+ """``hermes gateway stop`` semantics (planned-stop marker for the PID, then SIGTERM),+ in its worst-case interleaving: the SIGTERM lands only AFTER the gateway's+ planned-stop watcher has already consumed the marker. Any interleaving of the+ CLI's two steps must still be a clean planned exit (exit 0; a non-zero exit+ makes systemd/launchd revive a gateway the operator just stopped).++ Returns True when the gateway exited 0 on its own within ``STOP_TIMEOUT``.+ """+ graceful = False+ try:+ if proc.poll() is None:+ marker = subprocess.run(+ [sys.executable, "-c",+ "import sys; from gateway.status import write_planned_stop_marker as w, "+ "_get_planned_stop_marker_path as p; ok = w(int(sys.argv[1])); print(p()); "+ "sys.exit(0 if ok else 1)",+ str(proc.pid)],+ cwd=ph.project, env=ph.env(), capture_output=True, text=True, timeout=60,+ stdin=subprocess.DEVNULL,+ )+ assert marker.returncode == 0, f"planned-stop marker write failed: {marker.stderr[-1000:]}"+ marker_path = Path(marker.stdout.strip().splitlines()[-1])+ deadline = time.monotonic() + STOP_TIMEOUT+ while marker_path.exists() and proc.poll() is None and time.monotonic() < deadline:+ time.sleep(0.05)+ if proc.poll() is None:+ with contextlib.suppress(ProcessLookupError):+ os.kill(proc.pid, signal.SIGTERM)+ try:+ proc.wait(timeout=STOP_TIMEOUT)+ graceful = proc.returncode == 0+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=10)+ finally:+ proc._parity_log.close() # type: ignore[attr-defined]+ return graceful+++# Messaging gateway (Telegram-shaped fake adapter) ------------------------------------+++def _collect_delivered(events: list[dict[str, Any]]) -> str:+ """Final text of every message the client would see (sends, updated by later edits)."""+ messages: dict[str, str] = {}+ for ev in events:+ if ev["kind"] in ("send", "edit"):+ messages[ev["message_id"]] = ev["content"]+ return "\n".join(messages.values())+++def drive_gateway(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ ph.pin_terminal_cwd()+ # A real Telegram setup: bot token + allowlisted user in the profile .env.+ _append_env(ph, {"TELEGRAM_BOT_TOKEN": "123456:parity-fake-token",+ "TELEGRAM_ALLOWED_USERS": PARITY_USER_ID})+ proc = _spawn(ph, [sys.executable, str(GATEWAY_CHILD)], "gateway.stderr.log",+ {"PARITY_GATEWAY_PROMPT": prompt, "PARITY_GATEWAY_USER": PARITY_USER_ID})+ lines = _stdout_pump(proc)+ events: list[dict[str, Any]] = []+ outcome: str | None = None+ graceful = False+ try:+ deadline = time.monotonic() + TURN_TIMEOUT+ while outcome is None:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise AssertionError(f"gateway turn timed out; events={events}\n{_log_tail(proc)}")+ try:+ line = lines.get(timeout=remaining)+ except queue.Empty:+ continue+ if line is None:+ raise AssertionError(+ f"gateway exited {proc.wait()} before the turn completed; events={events}\n{_log_tail(proc)}")+ if not line.startswith(_LINE_PREFIX):+ continue+ ev = json.loads(line[len(_LINE_PREFIX):])+ events.append(ev)+ if ev["kind"] == "complete":+ outcome = ev["outcome"]+ finally:+ graceful = _stop(ph, proc)+ return DriveResult(+ final_text=_collect_delivered(events), toolset="hermes-telegram", cwd_channel="terminal.cwd",+ graceful_exit=graceful,+ extra={"outcome": outcome, "exit_code": proc.returncode, "events": events,+ "stderr_log": str(proc._parity_log_path)}, # type: ignore[attr-defined]+ )+++# OpenAI-compatible API server -------------------------------------------------------+++def _free_loopback_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _http(method: str, url: str, *, key: str | None = None, body: dict | None = None,+ timeout: float = 5.0) -> tuple[int, str]:+ data = json.dumps(body).encode() if body is not None else None+ req = urllib.request.Request(url, data=data, method=method)+ if data is not None:+ req.add_header("Content-Type", "application/json")+ if key:+ req.add_header("Authorization", f"Bearer {key}")+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return resp.status, resp.read().decode("utf-8", "replace")+ except urllib.error.HTTPError as exc:+ return exc.code, exc.read().decode("utf-8", "replace")+++def drive_api_server(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ ph.pin_terminal_cwd()+ port = _free_loopback_port()+ key = secrets.token_hex(32)+ _append_env(ph, {"API_SERVER_ENABLED": "true", "API_SERVER_KEY": key,+ "API_SERVER_HOST": "127.0.0.1", "API_SERVER_PORT": str(port)})+ proc = _spawn(ph, [sys.executable, "-m", "gateway.run"], "api_server.stderr.log")+ base = f"http://127.0.0.1:{port}"+ status: int | None = None+ payload: dict[str, Any] = {}+ graceful = False+ try:+ deadline = time.monotonic() + TURN_TIMEOUT+ while True:+ if proc.poll() is not None:+ raise AssertionError(f"api server exited {proc.returncode} before ready\n{_log_tail(proc)}")+ if time.monotonic() >= deadline:+ raise AssertionError(f"api server never became ready on {base}\n{_log_tail(proc)}")+ try:+ if _http("GET", f"{base}/health", timeout=2.0)[0] == 200:+ break+ except (OSError, urllib.error.URLError):+ pass+ time.sleep(0.2)+ status, raw = _http(+ "POST", f"{base}/v1/chat/completions", key=key, timeout=TURN_TIMEOUT,+ body={"model": "hermes-agent", "messages": [{"role": "user", "content": prompt}],+ "stream": False},+ )+ payload = json.loads(raw) if raw.strip().startswith("{") else {"raw": raw}+ assert status == 200, f"/v1/chat/completions -> {status}: {raw[-2000:]}\n{_log_tail(proc)}"+ finally:+ graceful = _stop(ph, proc)+ choices = payload.get("choices") or [{}]+ text = (choices[0].get("message") or {}).get("content")+ return DriveResult(+ final_text=text, toolset="hermes-api-server", cwd_channel="terminal.cwd", graceful_exit=graceful,+ extra={"http_status": status, "exit_code": proc.returncode,+ "stderr_log": str(proc._parity_log_path)}, # type: ignore[attr-defined]+ )diff --git a/tests/e2e/core/parity/_drive_rpc.py b/tests/e2e/core/parity/_drive_rpc.pynew file mode 100644index 00000000000..2dcc71c16d2--- /dev/null+++ b/tests/e2e/core/parity/_drive_rpc.py@@ -0,0 +1,272 @@+"""Entrypoint drivers for the parity matrix: the JSON-RPC surfaces.++* ``drive_tui_gateway`` — ``python -m tui_gateway.entry`` over stdio, exactly how+ the Ink TUI spawns it (launch dir = the user's shell cwd); stops on stdin EOF.+* ``drive_serve`` — ``hermes serve --host 127.0.0.1 --port 0`` spawned the way the+ Desktop spawns it (``TERMINAL_CWD`` + ``HERMES_DASHBOARD_SESSION_TOKEN`` ++ ``HERMES_DESKTOP=1`` env, stdin closed), port read from the READY sentinel on+ stdout, one turn over the ``/api/ws`` JSON-RPC WebSocket; stops on SIGTERM.++Both speak the same contract (``tui_gateway/contracts``): ``session.create`` →+``prompt.submit`` → ``message.complete`` event. Follows the driver contract in+``_drive_cli``.+"""++from __future__ import annotations++import json+import queue+import subprocess+import threading+import time+import uuid+from dataclasses import dataclass, field+from typing import Any, Callable++from tests.e2e.core.parity._helpers import (+ TURN_TIMEOUT,+ DriveResult,+ ParityHome,+ hermes_argv,+ terminate,+)+from tests.fakes.fake_llm_provider import FakeLLMServer++import sys++READY_TIMEOUT = 120.0+++class RpcClient:+ """Minimal JSON-RPC 2.0 client over a line/frame transport (``send`` + ``recv`` callables)."""++ def __init__(self, send: Callable[[str], None], frames: "queue.Queue[str | None]") -> None:+ self._send = send+ self._frames = frames+ self._next_id = 0+ self.events: list[dict[str, Any]] = []+ self._responses: dict[Any, dict[str, Any]] = {}++ def _pump(self, timeout: float) -> bool:+ try:+ raw = self._frames.get(timeout=timeout)+ except queue.Empty:+ return False+ if raw is None:+ raise AssertionError("JSON-RPC transport closed")+ msg = json.loads(raw)+ if msg.get("method") == "event":+ self.events.append(msg.get("params") or {})+ elif "id" in msg and "method" in msg:+ # Server→client request (approval/clarify/...): this scripted turn never needs one.+ self._send(json.dumps({"jsonrpc": "2.0", "id": msg["id"],+ "error": {"code": -32601, "message": "parity driver: unsupported"}}))+ elif "id" in msg:+ self._responses[msg["id"]] = msg+ return True++ def call(self, method: str, params: dict[str, Any] | None = None, timeout: float = 60.0) -> Any:+ self._next_id += 1+ rid = f"parity-{self._next_id}"+ self._send(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}))+ deadline = time.monotonic() + timeout+ while rid not in self._responses:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise AssertionError(f"{method}: no response within {timeout}s")+ self._pump(min(remaining, 0.5))+ resp = self._responses.pop(rid)+ if "error" in resp:+ raise AssertionError(f"{method} failed: {resp['error']}")+ return resp.get("result")++ def wait_event(self, etype: str, pred: Callable[[dict], bool] = lambda _e: True,+ timeout: float = TURN_TIMEOUT) -> dict[str, Any]:+ deadline = time.monotonic() + timeout+ seen = 0+ while True:+ for ev in self.events[seen:]:+ if ev.get("type") == etype and pred(ev):+ return ev+ seen = len(self.events)+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise AssertionError(+ f"no {etype!r} event within {timeout}s; saw {[e.get('type') for e in self.events][-30:]}")+ self._pump(min(remaining, 0.5))+++def run_turn(rpc: RpcClient, prompt: str, create_params: dict[str, Any]) -> str:+ created = rpc.call("session.create", create_params, timeout=TURN_TIMEOUT)+ sid = created["session_id"]+ rpc.call("prompt.submit", {"session_id": sid, "text": prompt}, timeout=TURN_TIMEOUT)+ done = rpc.wait_event("message.complete", lambda e: e.get("session_id") == sid)+ payload = done.get("payload") or {}+ text = payload.get("text")+ return text if isinstance(text, str) else json.dumps(text)+++@dataclass+class StreamCapture:+ """Every stdout line (in order) plus the stderr text of a child, pumped on threads."""++ stdout_lines: "queue.Queue[str | None]" = field(default_factory=queue.Queue)+ stdout_seen: list[str] = field(default_factory=list)+ stderr_chunks: list[str] = field(default_factory=list)++ def start(self, proc: subprocess.Popen) -> "StreamCapture":+ def out() -> None:+ assert proc.stdout is not None+ for line in proc.stdout:+ self.stdout_seen.append(line)+ self.stdout_lines.put(line)+ self.stdout_lines.put(None)++ def err() -> None:+ assert proc.stderr is not None+ for line in proc.stderr:+ self.stderr_chunks.append(line)++ threading.Thread(target=out, daemon=True, name="parity-stdout").start()+ threading.Thread(target=err, daemon=True, name="parity-stderr").start()+ return self++ @property+ def stderr(self) -> str:+ return "".join(self.stderr_chunks)+++# tui_gateway (stdio) ---------------------------------------------------------------+++def spawn_tui_gateway(ph: ParityHome) -> tuple[subprocess.Popen, StreamCapture]:+ proc = subprocess.Popen(+ [sys.executable, "-m", "tui_gateway.entry"], cwd=ph.project, env=ph.env(),+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1,+ )+ return proc, StreamCapture().start(proc)+++def drive_tui_gateway(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ proc, cap = spawn_tui_gateway(ph)++ def send(line: str) -> None:+ assert proc.stdin is not None+ proc.stdin.write(line + "\n")+ proc.stdin.flush()++ graceful = False+ try:+ rpc = RpcClient(send, cap.stdout_lines)+ rpc.wait_event("gateway.ready", timeout=READY_TIMEOUT)+ text = run_turn(rpc, prompt, {})+ finally:+ # Normal stop for a stdio gateway: the client closes the pipe.+ if proc.stdin is not None and not proc.stdin.closed:+ proc.stdin.close()+ try:+ proc.wait(timeout=60)+ graceful = True+ except subprocess.TimeoutExpired:+ terminate(proc)+ return DriveResult(final_text=text, toolset="hermes-cli", graceful_exit=graceful,+ extra={"exit_code": proc.returncode, "stderr_tail": cap.stderr[-2000:]})+++# hermes serve (Desktop backend) ------------------------------------------------------+++@dataclass+class ServeProcess:+ proc: subprocess.Popen+ cap: StreamCapture+ token: str+++def spawn_serve(ph: ParityHome) -> ServeProcess:+ """Spawn ``hermes serve`` with the Desktop's argv/env/stdio shape (electron/main.ts)."""+ token = uuid.uuid4().hex+ env = ph.env({+ "TERMINAL_CWD": str(ph.project),+ "HERMES_DASHBOARD_SESSION_TOKEN": token,+ "HERMES_DESKTOP": "1",+ })+ proc = subprocess.Popen(+ hermes_argv("serve", "--host", "127.0.0.1", "--port", "0"), cwd=ph.home, env=env,+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1,+ )+ return ServeProcess(proc=proc, cap=StreamCapture().start(proc), token=token)+++def first_stdout_line(sp: ServeProcess, timeout: float = READY_TIMEOUT) -> str:+ """The first stdout line, failing fast if the sentinel shows up on stderr instead."""+ deadline = time.monotonic() + timeout+ while True:+ try:+ line = sp.cap.stdout_lines.get(timeout=0.2)+ except queue.Empty:+ line = ""+ if line is None:+ raise AssertionError(f"serve exited {sp.proc.poll()} before any stdout line\n{sp.cap.stderr[-3000:]}")+ if line:+ return line+ if "HERMES_BACKEND_READY" in sp.cap.stderr:+ raise AssertionError(+ "READY sentinel was written to STDERR; the Desktop only watches stdout "+ f"(backend-ready.ts):\n{sp.cap.stderr[-1500:]}")+ if time.monotonic() >= deadline:+ raise AssertionError(f"no stdout line from serve within {timeout}s\n{sp.cap.stderr[-3000:]}")+++def desktop_port(sp: ServeProcess, timeout: float = READY_TIMEOUT) -> int:+ """The port the Desktop would learn from this backend's stdout (junk-tolerant, like+ backend-ready.ts). The strict "sentinel is the first line" rule is test_boot_contract's."""+ from tests.e2e.core.parity._boot_contract import desktop_parse++ deadline = time.monotonic() + timeout+ seen = ""+ while True:+ remaining = deadline - time.monotonic()+ line = first_stdout_line(sp, timeout=max(remaining, 0.1))+ seen += line+ verdict = desktop_parse(seen)+ if "port" in verdict:+ return int(verdict["port"])+++def ws_rpc(port: int, token: str) -> tuple[RpcClient, Callable[[], None]]:+ from websockets.sync.client import connect++ ws = connect(f"ws://127.0.0.1:{port}/api/ws?token={token}", open_timeout=30, max_size=None)+ frames: queue.Queue[str | None] = queue.Queue()++ def pump() -> None:+ try:+ for msg in ws:+ frames.put(msg if isinstance(msg, str) else msg.decode())+ except Exception:+ pass+ frames.put(None)++ threading.Thread(target=pump, daemon=True, name="parity-ws").start()+ return RpcClient(ws.send, frames), ws.close+++def drive_serve(ph: ParityHome, srv: FakeLLMServer, prompt: str) -> DriveResult:+ sp = spawn_serve(ph)+ graceful = False+ try:+ port = desktop_port(sp)+ rpc, close = ws_rpc(port, sp.token)+ try:+ rpc.wait_event("gateway.ready", timeout=READY_TIMEOUT)+ text = run_turn(rpc, prompt, {"cwd": str(ph.project)})+ finally:+ close()+ finally:+ # Desktop quit path: SIGTERM, bounded wait.+ code = terminate(sp.proc, timeout=60)+ graceful = code is not None and code in (0, -15, 143)+ return DriveResult(final_text=text, toolset="hermes-cli", cwd_channel="TERMINAL_CWD + session.create cwd",+ graceful_exit=graceful,+ extra={"exit_code": sp.proc.returncode, "stderr_tail": sp.cap.stderr[-2000:]})diff --git a/tests/e2e/core/parity/_gateway_child.py b/tests/e2e/core/parity/_gateway_child.pynew file mode 100644index 00000000000..8413b72d4e2--- /dev/null+++ b/tests/e2e/core/parity/_gateway_child.py@@ -0,0 +1,118 @@+"""Lane-private child process for ``_drive_gateway.drive_gateway``.++Runs the REAL messaging gateway entrypoint (``gateway.run.main`` — what+``python -m gateway.run`` / the ``hermes gateway run`` service executes: host+attach decision, PID claim, MCP discovery, ``GatewayRunner.start()``, signal+handlers, the graceful shutdown tail) with exactly one substitution: the+Telegram adapter instance is a recording fake. Everything behind the adapter+(authorization, session store, SessionDB, agent cache, AIAgent, hooks, plugins,+MCP) is production code.++The fake adapter injects ONE inbound DM through the adapter's normal+``handle_message`` path once the runner is running, prints every outbound+``send()`` and the ``on_processing_complete`` outcome as ``PARITY-GW <json>``+lines on stdout, and otherwise waits for the parent's normal stop+(planned-stop marker + SIGTERM, exactly like ``hermes gateway stop``).+"""++from __future__ import annotations++import asyncio+import json+import os+import sys+from typing import Any, Dict, Optional++from gateway.config import Platform+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, SendResult++import gateway.run as gateway_run++PARITY_USER_ID = os.environ.get("PARITY_GATEWAY_USER", "424242")+PARITY_CHAT_ID = PARITY_USER_ID # Telegram private chats use the user id as chat id+++# The gateway rebinds sys.stdout during startup; report on a private dup of the original pipe.+_REPORT = os.fdopen(os.dup(1), "w", buffering=1, encoding="utf-8")+++def emit(kind: str, **payload: Any) -> None:+ _REPORT.write("PARITY-GW " + json.dumps({"kind": kind, **payload}) + "\n")+ _REPORT.flush()+++class ParityTelegramAdapter(BasePlatformAdapter):+ """Telegram-shaped adapter: no network, records outbound text, injects one DM."""++ def __init__(self, config: Any, platform: Platform) -> None:+ super().__init__(config, platform)+ self._sent = 0+ self._inject_task: Optional[asyncio.Task] = None++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ self._mark_connected()+ if self._inject_task is None:+ self._inject_task = asyncio.create_task(self._inject_once())+ return True++ async def _inject_once(self) -> None:+ # Inbound arriving while startup restore runs is queued and replayed later (the first+ # handle_message then "completes" without a turn); inject once the gateway is serving.+ runner = self.gateway_runner+ while not getattr(runner, "_running", False) or getattr(runner, "_startup_restore_in_progress", True):+ await asyncio.sleep(0.05)+ emit("ready")+ source = self.build_source(+ chat_id=PARITY_CHAT_ID, chat_name="parity", chat_type="dm",+ user_id=PARITY_USER_ID, user_name="parity-user", message_id="1",+ )+ event = MessageEvent(+ text=os.environ["PARITY_GATEWAY_PROMPT"], source=source, message_id="1",+ user_id=PARITY_USER_ID, user_name="parity-user",+ )+ await self.handle_message(event)+ emit("accepted", accepted=bool(getattr(event, "_gateway_accepted", False)))++ async def disconnect(self) -> None:+ if self._inject_task is not None and not self._inject_task.done():+ self._inject_task.cancel()+ self._mark_disconnected()++ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:+ self._sent += 1+ message_id = f"parity-{self._sent}"+ emit("send", chat_id=str(chat_id), message_id=message_id, content=content)+ return SendResult(success=True, message_id=message_id)++ async def edit_message(self, chat_id: str, message_id: str, content: str, *,+ finalize: bool = False) -> SendResult:+ emit("edit", chat_id=str(chat_id), message_id=message_id, content=content)+ return SendResult(success=True, message_id=message_id)++ async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:+ return {"name": "parity", "type": "dm", "chat_id": chat_id}++ async def on_processing_complete(self, event: MessageEvent, outcome: Any) -> None:+ emit("complete", outcome=str(getattr(outcome, "value", outcome)))+++_real_instantiate = gateway_run.GatewayRunner._instantiate_adapter+++def _instantiate_adapter(self, platform: Platform, config: Any):+ if platform == Platform.TELEGRAM:+ return ParityTelegramAdapter(config, platform)+ return _real_instantiate(self, platform, config)+++def main() -> None:+ # The one seam: adapter construction (``GatewayRunner._create_adapter`` still wires runner ++ # handlers onto whatever this returns, exactly as for the real Telegram adapter).+ gateway_run.GatewayRunner._instantiate_adapter = _instantiate_adapter+ sys.argv = ["gateway.run"]+ gateway_run.main()+++if __name__ == "__main__":+ main()diff --git a/tests/e2e/core/parity/_helpers.py b/tests/e2e/core/parity/_helpers.pynew file mode 100644index 00000000000..91ef2127471--- /dev/null+++ b/tests/e2e/core/parity/_helpers.py@@ -0,0 +1,453 @@+"""Shared fixture HERMES_HOME + invariant checks for the entrypoint-parity suite.++One fixture home carries every feature that has historically been wired into+some entrypoints and forgotten in others (issue class C19): a shell hook and a+Python-plugin hook on ``pre_llm_call`` (both write a marker AND inject a+context canary), an ``AGENTS.md`` context file in the working directory, a+skill, a memory entry, a stdio MCP server (issue class C15) whose tool returns a+canary, the custom provider pointed at the recording fake, and a toolset+restriction (``agent.disabled_toolsets``).++Every entrypoint driver runs ONE turn against the scripted fake provider+(turn 1: call the MCP tool; turn 2: answer) and hands the recorded requests to+:func:`collect_observation`; the test then asserts the same invariants for+every entrypoint, so any red cell is a wiring-parity bug.+"""++from __future__ import annotations++import json+import os+import re+import signal+import subprocess+import sys+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable, Iterable++import yaml++from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall, write_hermes_home++REPO_ROOT = Path(__file__).resolve().parents[4]+FIXTURE_MCP_SERVER = Path(__file__).with_name("fixture_mcp_server.py")++MCP_SERVER_NAME = "parity"+MCP_TOOL_NAME = "mcp__parity__parity_canary"+FINAL_ANSWER = "PARITY-TURN-COMPLETE"+PLUGIN_NAME = "parity-plugin"+# Always-available (no credential/check_fn gate) toolset the fixture disables.+DISABLED_TOOLSET = "todo"++_SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")+_PASSTHROUGH_ENV = frozenset({+ "PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ",+ "SYSTEMROOT", "SystemRoot", "COMSPEC", "PATHEXT", "WINDIR", "TEMP", "TMP",+})+++TURN_TIMEOUT = 240.0+++@dataclass+class DriveResult:+ """What an entrypoint driver reports back (see ``_drive_cli`` for the contract)."""++ final_text: str | None+ toolset: str # the platform toolset this surface documents (a toolsets.py key)+ cwd_channel: str = "launch dir"+ graceful_exit: bool = True+ extra: dict[str, Any] = field(default_factory=dict)+++@dataclass+class ParityHome:+ """Filesystem layout + canaries of one fixture home."""++ root: Path+ home: Path+ hermes_home: Path+ project: Path+ markers: Path+ pid_log: Path+ tag: str+ canaries: dict[str, str] = field(default_factory=dict)++ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:+ """Hermetic env for a subprocess Hermes: fake HOME, no real credentials."""+ import pwd # POSIX-only; the suite is Linux-gated++ real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve()+ assert real_root not in (self.hermes_home.resolve(), *self.hermes_home.resolve().parents), (+ f"fixture HERMES_HOME {self.hermes_home} is inside the real {real_root}")+ # Allowlist, not denylist: the runner may itself be a Hermes process whose+ # TERMINAL_CWD / HERMES_* / credential env would silently reroute the child.+ env = {+ k: v for k, v in os.environ.items()+ if (k in _PASSTHROUGH_ENV or k.startswith("LC_")) and not k.endswith(_SECRET_ENV_SUFFIXES)+ }+ env.update({+ "HOME": str(self.home),+ "HERMES_HOME": str(self.hermes_home),+ "PYTHONPATH": str(REPO_ROOT),+ "PYTHONUNBUFFERED": "1",+ "NO_COLOR": "1",+ "TERM": "dumb",+ # Orphan-scan tag: every process in the spawned tree inherits it.+ "PARITY_TREE_TAG": self.tag,+ # The child's HOME is the fixture home, so its ``~/.hermes/state.db`` IS+ # the tmp HERMES_HOME's db; under a pytest ancestor the live-DB guard+ # (hermes_state_guard) would refuse it. This is the guard's documented+ # child-process escape hatch; the path is tmp_path by construction.+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ })+ env.update(extra or {})+ return env++ def update_config(self, mutate: Callable[[dict], None]) -> None:+ """Apply ``mutate`` to config.yaml (for surfaces with a documented config-only channel)."""+ path = self.hermes_home / "config.yaml"+ cfg = yaml.safe_load(path.read_text(encoding="utf-8"))+ mutate(cfg)+ path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")++ def pin_terminal_cwd(self) -> None:+ """Documented cwd channel for daemon surfaces (gateway, api_server): ``terminal.cwd``."""+ self.update_config(lambda cfg: cfg.setdefault("terminal", {}).__setitem__("cwd", str(self.project)))+++def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True) -> ParityHome:+ """Write the full fixture home under ``root`` (a tmp_path)."""+ home = root / "home"+ hermes_home = home / ".hermes"+ project = root / "project"+ markers = root / "markers"+ for d in (hermes_home, project, markers):+ d.mkdir(parents=True, exist_ok=True)+ tag = uuid.uuid4().hex+ c = {name: f"{name.upper()}-{uuid.uuid4().hex[:12]}" for name in (+ "context", "skill", "memory", "shell_hook", "plugin_hook", "mcp")}+ ph = ParityHome(root=root, home=home, hermes_home=hermes_home, project=project,+ markers=markers, pid_log=root / "mcp_pids.log", tag=tag, canaries=c)++ write_hermes_home(hermes_home, base_url)+ cfg = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))+ cfg["agent"]["disabled_toolsets"] = [DISABLED_TOOLSET]+ cfg["hooks"] = {"pre_llm_call": [{+ "command": f"{sys.executable} {hermes_home / 'agent-hooks' / 'shell_hook.py'}",+ "timeout": 30,+ }]}+ cfg["hooks_auto_accept"] = True+ cfg["plugins"] = {"enabled": [PLUGIN_NAME]}+ cfg["mcp_servers"] = {MCP_SERVER_NAME: {+ "command": sys.executable,+ "args": [str(FIXTURE_MCP_SERVER)],+ "env": {+ "PARITY_MCP_CANARY": c["mcp"],+ "PARITY_MCP_PID_LOG": str(ph.pid_log),+ "PARITY_MCP_SPAWN_GRANDCHILD": "1" if grandchild else "0",+ "PARITY_TREE_TAG": tag,+ # Only the MCP server and its descendants carry this one.+ "PARITY_MCP_TREE_TAG": tag,+ "PYTHONPATH": str(REPO_ROOT),+ },+ "connect_timeout": 60,+ "timeout": 60,+ }}+ # Keep turns hermetic and short: no title/aux model chatter decides anything here.+ cfg.setdefault("display", {})["compact"] = True+ (hermes_home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")++ hooks_dir = hermes_home / "agent-hooks"+ hooks_dir.mkdir()+ (hooks_dir / "shell_hook.py").write_text(+ "import json, os, sys\n"+ "payload = json.load(sys.stdin)\n"+ f"with open({str(markers / 'shell_hook.log')!r}, 'a') as fh:\n"+ " fh.write(json.dumps({'event': payload.get('hook_event_name'),\n"+ " 'session_id': payload.get('session_id')}) + '\\n')\n"+ f"print(json.dumps({{'context': {c['shell_hook']!r}}}))\n",+ encoding="utf-8",+ )++ plugin_dir = hermes_home / "plugins" / PLUGIN_NAME+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "plugin.yaml").write_text(+ f"name: {PLUGIN_NAME}\nversion: 1.0.0\ndescription: parity suite marker plugin\n",+ encoding="utf-8",+ )+ (plugin_dir / "__init__.py").write_text(+ "import json\n"+ "def register(ctx):\n"+ " def _pre_llm_call(**kwargs):\n"+ f" with open({str(markers / 'plugin_hook.log')!r}, 'a') as fh:\n"+ " fh.write(json.dumps({'platform': kwargs.get('platform'),\n"+ " 'session_id': kwargs.get('session_id')}) + '\\n')\n"+ f" return {{'context': {c['plugin_hook']!r}}}\n"+ " ctx.register_hook('pre_llm_call', _pre_llm_call)\n",+ encoding="utf-8",+ )++ skill_dir = hermes_home / "skills" / "parity-skill"+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(+ "---\nname: parity-skill\n"+ f"description: Use when checking entrypoint parity {c['skill']}.\n---\n\n"+ "# Parity skill\n\nNothing to do.\n",+ encoding="utf-8",+ )++ mem_dir = hermes_home / "memories"+ mem_dir.mkdir()+ (mem_dir / "MEMORY.md").write_text(f"The parity memory canary is {c['memory']}.", encoding="utf-8")++ (project / "AGENTS.md").write_text(+ f"# Project rules\n\nThe parity context canary is {c['context']}.\n", encoding="utf-8")+ return ph+++# Scripted provider -----------------------------------------------------------+++def parity_responder(nonce: str) -> Callable[[dict[str, Any]], Any]:+ """Stateless script: call the MCP tool until a tool result exists, then answer.++ Stateless so a retried request (or a second concurrent entrypoint request)+ cannot desynchronise the script.+ """++ def respond(record: dict[str, Any]):+ body = record["body"]+ if any(m.get("role") == "tool" for m in body.get("messages") or []):+ return Text(FINAL_ANSWER)+ args = {"nonce": nonce}+ if MCP_TOOL_NAME in _tool_names(body) or "tool_call" not in _tool_names(body):+ return ToolCall(MCP_TOOL_NAME, args)+ # Tool Search active: MCP tools sit in the deferred catalog behind the bridge.+ return ToolCall("tool_call", {"calls": [{"name": MCP_TOOL_NAME, "arguments": args}]})++ return respond+++def start_provider(nonce: str) -> FakeLLMServer:+ srv = FakeLLMServer(parity_responder(nonce))+ srv.start()+ return srv+++# Observation + invariants ----------------------------------------------------+++def _text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(p.get("text", "") for p in content if isinstance(p, dict))+ return ""+++def _tool_names(body: dict[str, Any]) -> set[str]:+ return {(t.get("function") or {}).get("name") or t.get("name") for t in body.get("tools") or []}+++_CATALOG_LINE = re.compile(r"^- ([A-Za-z0-9_.:-]+): ", re.M)+++def offered_tool_names(body: dict[str, Any]) -> set[str]:+ """Direct tool schemas plus the Tool Search deferred catalog (names the model may invoke)."""+ names = _tool_names(body)+ for t in body.get("tools") or []:+ fn = t.get("function") or {}+ if fn.get("name") == "tool_search":+ names |= set(_CATALOG_LINE.findall(fn.get("description") or ""))+ return names+++@dataclass+class Observation:+ entrypoint: str+ system: str+ first_user: str+ tool_names: set[str]+ tool_results: list[str]+ main_requests: int+ shell_hook_events: list[dict]+ plugin_hook_events: list[dict]+ final_text: str | None = None+ extra: dict[str, Any] = field(default_factory=dict)+++def _read_jsonl(path: Path) -> list[dict]:+ if not path.exists():+ return []+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]+++def collect_observation(entrypoint: str, ph: ParityHome, srv: FakeLLMServer,+ final_text: str | None = None) -> Observation:+ mains = srv.main_requests()+ assert mains, f"{entrypoint}: no main-turn request reached the provider"+ first = mains[0]+ msgs = first.get("messages") or []+ system = "\n".join(_text(m.get("content")) for m in msgs if m.get("role") == "system")+ users = [_text(m.get("content")) for m in msgs if m.get("role") == "user"]+ tool_results = [+ _text(m.get("content")) for body in mains for m in body.get("messages") or []+ if m.get("role") == "tool"+ ]+ return Observation(+ entrypoint=entrypoint, system=system, first_user=users[-1] if users else "",+ tool_names=offered_tool_names(first), tool_results=tool_results, main_requests=len(mains),+ shell_hook_events=_read_jsonl(ph.markers / "shell_hook.log"),+ plugin_hook_events=_read_jsonl(ph.markers / "plugin_hook.log"),+ final_text=final_text,+ )+++def disabled_tool_names() -> set[str]:+ from toolsets import resolve_toolset++ return set(resolve_toolset(DISABLED_TOOLSET))+++# Agent features every surface must carry when its documented toolset includes them.+_FEATURE_TOOLS = ("terminal", "read_file", "write_file", "patch", "search_files", "memory",+ "skills_list", "skill_view")+++def required_tool_names(toolset: str) -> set[str]:+ """The core feature tools the surface's documented toolset promises, plus the MCP tool."""+ from toolsets import resolve_toolset++ promised = set(resolve_toolset(toolset))+ return {t for t in _FEATURE_TOOLS if t in promised} | {MCP_TOOL_NAME}+++def check_invariants(obs: Observation, ph: ParityHome, *, toolset: str = "hermes-cli",+ context_file: bool = True) -> dict[str, bool]:+ """Evaluate every parity invariant; returns {cell: ok} (all must be True)."""+ c = ph.canaries+ cells = {+ "context_file": c["context"] in obs.system,+ "skill_index": c["skill"] in obs.system,+ "memory": c["memory"] in obs.system,+ "shell_hook_fired": bool(obs.shell_hook_events),+ "shell_hook_injected": c["shell_hook"] in obs.first_user,+ "plugin_hook_fired": bool(obs.plugin_hook_events),+ "plugin_hook_injected": c["plugin_hook"] in obs.first_user,+ "mcp_tool_offered": MCP_TOOL_NAME in obs.tool_names,+ "mcp_call_returned_canary": any(c["mcp"] in r for r in obs.tool_results),+ "toolset_restriction": not (obs.tool_names & disabled_tool_names()),+ "feature_tools": required_tool_names(toolset) <= obs.tool_names,+ "turn_completed": obs.main_requests >= 2,+ }+ if not context_file:+ cells.pop("context_file")+ return cells+++# Process-tree hygiene --------------------------------------------------------+++def tagged_pids(tag: str, var: str = "PARITY_TREE_TAG") -> set[int]:+ """Live PIDs whose environment carries ``<var>=<tag>`` (reparented orphans included)."""+ needle = f"{var}={tag}".encode()+ found: set[int] = set()+ me = os.getpid()+ for entry in os.listdir("/proc"):+ if not entry.isdigit() or int(entry) == me:+ continue+ try:+ with open(f"/proc/{entry}/environ", "rb") as fh:+ env = fh.read()+ with open(f"/proc/{entry}/stat", "rb") as fh:+ state = fh.read().rsplit(b")", 1)[1].split()[0]+ except OSError:+ continue+ if state != b"Z" and needle in env.split(b"\0"):+ found.add(int(entry))+ return found+++def mcp_pids(ph: ParityHome) -> dict[str, list[int]]:+ out: dict[str, list[int]] = {}+ if ph.pid_log.exists():+ for line in ph.pid_log.read_text(encoding="utf-8").splitlines():+ kind, pid = line.split()+ out.setdefault(kind, []).append(int(pid))+ return out+++def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.05):+ deadline = time.monotonic() + timeout+ while True:+ value = pred()+ if value:+ return value+ if time.monotonic() >= deadline:+ raise AssertionError(f"timed out after {timeout}s waiting for {what}")+ time.sleep(interval)+++def wait_no_orphans(ph: ParityHome, timeout: float = 30.0, *, mcp_only: bool = True) -> set[int]:+ """Poll until no MCP-tree process (or, ``mcp_only=False``, no tagged process at all)+ survives; returns the survivors (empty = clean)."""+ var = "PARITY_MCP_TREE_TAG" if mcp_only else "PARITY_TREE_TAG"+ deadline = time.monotonic() + timeout+ survivors = tagged_pids(ph.tag, var)+ while survivors and time.monotonic() < deadline:+ time.sleep(0.1)+ survivors = tagged_pids(ph.tag, var)+ return survivors+++def describe_pids(pids: Iterable[int]) -> list[str]:+ out = []+ for pid in sorted(pids):+ try:+ with open(f"/proc/{pid}/cmdline", "rb") as fh:+ cmd = fh.read().replace(b"\0", b" ").decode(errors="replace")+ out.append(f"{pid}: {cmd[:160]}")+ except OSError:+ out.append(f"{pid}: <gone>")+ return out+++def kill_tagged(ph: ParityHome) -> None:+ """Test cleanup: SIGKILL anything this fixture spawned that is still alive."""+ for pid in tagged_pids(ph.tag):+ try:+ os.kill(pid, signal.SIGKILL)+ except OSError:+ pass+++def hermes_argv(*args: str) -> list[str]:+ return [sys.executable, "-m", "hermes_cli.main", *args]+++def terminate(proc: subprocess.Popen, timeout: float = 30.0) -> int | None:+ """Graceful SIGTERM (the normal stop), SIGKILL only if it overstays."""+ if proc.poll() is None:+ proc.send_signal(signal.SIGTERM)+ try:+ proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=10)+ return proc.returncode+++def format_cells(results: Iterable[tuple[str, dict[str, bool]]]) -> str:+ rows = list(results)+ cols = sorted({k for _, cells in rows for k in cells})+ head = "| entrypoint | " + " | ".join(cols) + " |"+ sep = "|---" * (len(cols) + 1) + "|"+ body = [+ f"| {ep} | " + " | ".join(("✅" if cells.get(k) else ("—" if k not in cells else "❌")) for k in cols) + " |"+ for ep, cells in rows+ ]+ return "\n".join([head, sep, *body])diff --git a/tests/e2e/core/parity/desktop_ready_parse.mjs b/tests/e2e/core/parity/desktop_ready_parse.mjsnew file mode 100644index 00000000000..a2bd9f36af5--- /dev/null+++ b/tests/e2e/core/parity/desktop_ready_parse.mjs@@ -0,0 +1,30 @@+// Feed bytes (stdin) through the Desktop's REAL READY-sentinel parser.+//+// Imports apps/desktop/electron/backend-ready.ts itself (Node >= 22.18 strips the+// types natively) and drives `waitForDashboardPort` with a child-shaped emitter+// whose stdout emits exactly the bytes the Python test captured from the backend's+// stdout. Prints {"port": N} or {"error": "..."}. The Python side therefore never+// re-implements or regexes the TS contract: if the parser changes, this follows.+import { EventEmitter } from 'node:events'+import { pathToFileURL } from 'node:url'++const [parserPath, timeoutMs] = process.argv.slice(2)+const { waitForDashboardPort } = await import(pathToFileURL(parserPath).href)++const chunks = []+for await (const chunk of process.stdin) {+ chunks.push(chunk)+}++const child = new EventEmitter()+child.stdout = new EventEmitter()+const pending = waitForDashboardPort(child, Number(timeoutMs) || 5000)+child.stdout.emit('data', Buffer.concat(chunks))+// Nothing more will arrive: the captured stream ended here.+child.emit('exit', 0, null)++try {+ console.log(JSON.stringify({ port: await pending }))+} catch (err) {+ console.log(JSON.stringify({ error: String(err && err.message ? err.message : err) }))+}diff --git a/tests/e2e/core/parity/fixture_mcp_server.py b/tests/e2e/core/parity/fixture_mcp_server.pynew file mode 100644index 00000000000..9ecc19efea9--- /dev/null+++ b/tests/e2e/core/parity/fixture_mcp_server.py@@ -0,0 +1,60 @@+"""Tiny stdio MCP server used by the entrypoint-parity suite.++Exposes one tool, ``parity_canary``, whose result is the value of the+``PARITY_MCP_CANARY`` env var — so a test can prove a REAL tool call round-tripped+through the real Hermes MCP client (discovery, transport, liveness checks, result+plumbing) instead of a registered-but-dead schema.++``PARITY_MCP_SPAWN_GRANDCHILD=1`` makes the server fork a long-lived grandchild at+startup (the shape of npx/uvx wrappers and servers with worker helpers) so+shutdown tests can prove Hermes reaps the whole process tree, not just its direct+child. Every PID the server owns is appended to ``PARITY_MCP_PID_LOG`` so the test+can check liveness of exactly the processes this fixture created.+"""++from __future__ import annotations++import os+import subprocess+import sys+++def _log_pid(kind: str, pid: int) -> None:+ path = os.environ.get("PARITY_MCP_PID_LOG")+ if not path:+ return+ with open(path, "a", encoding="utf-8") as fh:+ fh.write(f"{kind} {pid}\n")+++def _spawn_grandchild() -> None:+ # Inherits the environment (and so the orphan-scan tag). Reads nothing,+ # writes nothing, lives until killed: an orphan if the tree is not reaped.+ child = subprocess.Popen(+ [sys.executable, "-c", "import time\nwhile True: time.sleep(60)"],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ _log_pid("grandchild", child.pid)+++def main() -> None:+ from mcp.server import MCPServer++ _log_pid("server", os.getpid())+ if os.environ.get("PARITY_MCP_SPAWN_GRANDCHILD") == "1":+ _spawn_grandchild()++ server = MCPServer("parity")++ @server.tool()+ def parity_canary(nonce: str = "") -> str:+ """Return the parity fixture canary (echoing the caller's nonce)."""+ return f"{os.environ.get('PARITY_MCP_CANARY', 'NO-CANARY')}:{nonce}"++ server.run(transport="stdio")+++if __name__ == "__main__":+ main()diff --git a/tests/e2e/core/parity/test_entrypoint_parity.py b/tests/e2e/core/parity/test_entrypoint_parity.pynew file mode 100644index 00000000000..79878c20c7a--- /dev/null+++ b/tests/e2e/core/parity/test_entrypoint_parity.py@@ -0,0 +1,177 @@+"""Entrypoint parity matrix (issue classes C19 + C15).++One fixture HERMES_HOME (shell hook + plugin hook on ``pre_llm_call``, AGENTS.md,+a skill, a memory entry, a stdio MCP server that spawns a grandchild, the custom+provider pointed at the recording fake, a disabled toolset) and ONE scripted turn+per entrypoint: the fake model calls the MCP canary tool, then answers.++For every entrypoint the same invariants must hold on the FIRST turn after a cold+start — any red cell is a wiring-parity bug of the "works in the CLI, missing in+Desktop/gateway/ACP/cron" class:++* the request carries the context file, the skill index and the memory entry;+* both hooks fired AND their injected context reached the model;+* the MCP tool was offered and a REAL call returned the fixture's canary (the+ inverted ``_stdio_children_dead`` burst failed exactly here on every surface);+* the documented toolset's core feature tools are present, the disabled toolset+ is absent;+* the surface delivered the model's answer to its client;+* after the surface's normal shutdown no MCP server / grandchild survives.++``PARITY_TABLE_OUT=<path>`` appends a markdown row per entrypoint (REPORT.md table).+"""++from __future__ import annotations++import json+import os+import sys+import time+import uuid+from concurrent.futures import ThreadPoolExecutor+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Callable++import pytest++from tests.e2e.core.parity import _drive_acp, _drive_cli, _drive_cron, _drive_gateway, _drive_rpc+from tests.e2e.core.parity._helpers import (+ FINAL_ANSWER,+ DriveResult,+ ParityHome,+ build_parity_home,+ check_invariants,+ collect_observation,+ describe_pids,+ kill_tagged,+ mcp_pids,+ start_provider,+ wait_no_orphans,+)+++# Linux-only (/proc process-tree scans). The live-system guard bypass is needed+# ONLY for the orphan sweep: orphans reparented to init (the exact failure this suite+# hunts) sit outside the pytest subtree, and kill_tagged() signals nothing but+# PIDs carrying this run's unique PARITY_TREE_TAG. Children run with a tmp+# HOME/HERMES_HOME (asserted in ParityHome.env), so no real state is reachable.+pytestmark = [+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree checks use /proc"),+ pytest.mark.live_system_guard_bypass,+]++PROMPT = "Call the parity canary tool, then report."++Driver = Callable[..., DriveResult]++DRIVERS: dict[str, Driver] = {+ "oneshot (-z)": _drive_cli.drive_oneshot,+ "chat -q": _drive_cli.drive_chat_q,+ "tui_gateway (stdio)": _drive_rpc.drive_tui_gateway,+ "serve (Desktop WS)": _drive_rpc.drive_serve,+ "gateway (fake adapter)": _drive_gateway.drive_gateway,+ "api_server": _drive_gateway.drive_api_server,+ "acp (stdio)": _drive_acp.drive_acp,+ "cron (run-now)": _drive_cron.drive_cron,+}++# Cells that are red on current main for a tracked, open bug. Strict: the test+# FAILS as soon as the cell turns green, so the entry is removed with the fix+# instead of silently masking a later regression of the same cell.+KNOWN_RED: dict[tuple[str, str], str] = {+ # ACP builds its AIAgent without the configured agent.disabled_toolsets.+ ("acp (stdio)", "toolset_restriction"): "#74582",+}+++@dataclass+class Row:+ entrypoint: str+ cells: dict[str, bool] = field(default_factory=dict)+ error: str | None = None+ detail: str = ""+ toolset: str | None = None+ cwd_channel: str | None = None+ other_survivors: list[str] = field(default_factory=list)+ wall_s: float = 0.0+++def _run_row(entrypoint: str, root: Path) -> Row:+ """Drive one entrypoint end to end and evaluate every cell. Never raises: the+ row carries the error, and its own process tree is swept before returning."""+ row = Row(entrypoint)+ started = time.monotonic()+ srv = start_provider(uuid.uuid4().hex[:8])+ ph: ParityHome | None = None+ try:+ ph = build_parity_home(root, srv.base_url)+ result = DRIVERS[entrypoint](ph, srv, PROMPT)+ row.toolset, row.cwd_channel = result.toolset, result.cwd_channel+ obs = collect_observation(entrypoint, ph, srv, result.final_text)+ cells = check_invariants(obs, ph, toolset=result.toolset)+ cells["answer_delivered"] = FINAL_ANSWER in (result.final_text or "")+ cells["graceful_exit"] = result.graceful_exit+ pids = mcp_pids(ph)+ # Vacuity guard: the orphan check only means something if the tree existed.+ cells["mcp_tree_spawned"] = bool(pids.get("server")) and bool(pids.get("grandchild"))+ survivors = wait_no_orphans(ph, timeout=30.0)+ cells["zero_mcp_orphans"] = not survivors+ # Report-only: non-MCP descendants still alive (timing-dependent, e.g. a+ # picker-prewarm `gh auth token` orphaned by a fast host exit).+ row.other_survivors = describe_pids(wait_no_orphans(ph, timeout=10.0, mcp_only=False))+ row.cells = cells+ stderr_tail = str(result.extra.get("stderr_tail", ""))+ log = result.extra.get("stderr_log")+ if log and Path(log).exists():+ stderr_tail = Path(log).read_text(encoding="utf-8", errors="replace")+ row.detail = (+ f" tools offered: {sorted(obs.tool_names)}\n"+ f" tool results: {[r[-300:] for r in obs.tool_results]}\n"+ f" surviving MCP-tree pids: {describe_pids(survivors)} (mcp pid log {pids})\n"+ f" final text: {(result.final_text or '')[-300:]!r}\n"+ f" host exit code: {result.extra.get('exit_code')}\n"+ f" host stderr tail: {stderr_tail[-1500:]}"+ )+ except Exception as exc: # noqa: BLE001 - reported per row+ row.error = f"{type(exc).__name__}: {exc}"[:4000]+ finally:+ if ph is not None:+ kill_tagged(ph)+ srv.stop()+ row.wall_s = round(time.monotonic() - started, 1)+ return row++[email protected](scope="module")+def matrix(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Row]:+ """All entrypoints driven CONCURRENTLY (each in its own home, provider and+ process tree): the file's wall time is the slowest cold start, not the sum.+ Everything, including the orphan sweep, completes during setup, while the+ first test's live-guard bypass is in effect."""+ roots = {ep: tmp_path_factory.mktemp(f"parity{i}") for i, ep in enumerate(DRIVERS)}+ with ThreadPoolExecutor(max_workers=len(DRIVERS), thread_name_prefix="parity") as pool:+ futures = {ep: pool.submit(_run_row, ep, roots[ep]) for ep in DRIVERS}+ rows = {ep: fut.result() for ep, fut in futures.items()}+ out = os.environ.get("PARITY_TABLE_OUT")+ if out:+ with open(out, "a", encoding="utf-8") as fh:+ for row in rows.values():+ fh.write(json.dumps({+ **asdict(row), "detail": None,+ "known_red": {c: ref for (ep, c), ref in KNOWN_RED.items() if ep == row.entrypoint},+ }) + "\n")+ return rows++[email protected]("entrypoint", list(DRIVERS))+def test_entrypoint_parity(entrypoint: str, matrix: dict[str, Row]) -> None:+ row = matrix[entrypoint]+ assert row.error is None, f"{entrypoint}: turn failed before the cells could be evaluated:\n{row.error}"+ known = {cell for (ep, cell) in KNOWN_RED if ep == entrypoint}+ fixed = sorted(cell for cell in known if row.cells.get(cell))+ assert not fixed, (+ f"{entrypoint}: {fixed} now green — drop the KNOWN_RED entry "+ f"({[KNOWN_RED[(entrypoint, c)] for c in fixed]}) so the cell is enforced again")+ failed = sorted(k for k, ok in row.cells.items() if not ok and k not in known)+ assert not failed, f"{entrypoint}: parity cells red: {failed}\n{row.detail}"