from __future__ import annotations
import argparse
import atexit
import json
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import socket
from pathlib import Path
TURNS_PER_CALL = 7
PM_AGENT_MD = """---
name: pm
model: bedrock/us.anthropic.claude-sonnet-4-6
---
You are the PM. (Soak harness fixture — never actually invoked; the real
turns come from `TCODE_MOCK_LLM=echo-soak`'s scripted client.)
"""
def build_project_fixture(root: Path) -> None:
agents_dir = root / ".claude" / "agents"
agents_dir.mkdir(parents=True, exist_ok=True)
(agents_dir / "pm.md").write_text(PM_AGENT_MD, encoding="utf-8")
def spawn_daemon(
tcode_bin: Path,
project: Path,
data_dir: Path,
mock_llm: str = "echo-soak",
extra_env: dict[str, str] | None = None,
) -> tuple[subprocess.Popen, str]:
daemon_data = Path(tempfile.mkdtemp(prefix="tc-soak-", dir="/tmp"))
atexit.register(shutil.rmtree, daemon_data, ignore_errors=True)
env = {
"TCODE_MOCK_LLM": mock_llm,
"TCODE_TELEMETRY_DATA_DIR": str(data_dir),
"PATH": _inherited_path(),
"HOME": str(Path.home()),
"TRUSTY_DATA_DIR_OVERRIDE": str(daemon_data),
}
if extra_env:
env.update(extra_env)
sock = str(daemon_data / "trusty-code" / "trusty-code.sock")
assert len(sock.encode()) < 100, f"socket path too long for sun_path: {sock}"
proc = subprocess.Popen(
[str(tcode_bin), "serve", "--project", str(project)],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
env=env,
)
assert proc.stderr is not None
deadline = time.monotonic() + 30
while True:
if proc.poll() is not None:
raise RuntimeError(
f"tcode serve exited early (code {proc.returncode}): {proc.stderr.read()}"
)
try:
rpc_call(sock, "ping", {})
break
except (OSError, ValueError):
if time.monotonic() > deadline:
proc.kill()
raise RuntimeError(f"timed out waiting for tcode serve to answer on {sock}")
time.sleep(0.1)
def _drain():
while proc.poll() is None:
if proc.stderr.readline() == "":
break
threading.Thread(target=_drain, daemon=True).start()
return proc, sock
def _inherited_path() -> str:
import os
return os.environ.get("PATH", "/usr/bin:/bin")
class RpcError(RuntimeError):
pass
def rpc_call(sock: str, method: str, params: dict, request_id: int = 1) -> dict:
body = json.dumps(
{"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}
).encode("utf-8")
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
conn.settimeout(30)
conn.connect(sock)
conn.sendall(body + b"\n")
conn.shutdown(socket.SHUT_WR)
data = b""
while not data.endswith(b"\n"):
chunk = conn.recv(65536)
if not chunk:
break
data += chunk
payload = json.loads(data)
if "error" in payload and payload["error"] is not None:
raise RpcError(f"{method} failed: {payload['error']}")
return payload["result"]
def wait_for_terminal_status(sock: str, session_id: str, timeout_s: float = 60) -> str:
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
status = rpc_call(sock, "session.status", {"session_id": session_id})["status"]
if status not in ("running", "created"):
return status
time.sleep(0.1)
raise TimeoutError(f"session {session_id} did not reach a terminal status in {timeout_s}s")
def run_soak(tcode_bin: Path, calls: int, out_dir: Path) -> dict:
out_dir.mkdir(parents=True, exist_ok=True)
data_dir = out_dir / "telemetry"
data_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="tcode-soak-project-") as project_dir:
project = Path(project_dir)
build_project_fixture(project)
proc, sock = spawn_daemon(tcode_bin, project, data_dir)
budget_samples = []
try:
created = rpc_call(sock, "session.create", {"task": "compression soak turn 0"})
session_id = created["id"]
print(f"session_id={session_id}", file=sys.stderr)
total_turns = 0
for call_num in range(1, calls + 1):
rpc_call(
sock,
"task.run",
{
"task_description": f"soak call {call_num}",
"session_id": session_id,
"mode": "daily-driver",
},
request_id=call_num,
)
status = wait_for_terminal_status(sock, session_id)
total_turns += TURNS_PER_CALL
budget = rpc_call(
sock, "session.get_context_budget", {"session_id": session_id}
)
budget_samples.append({"call": call_num, "turns": total_turns, **budget})
print(
f"call {call_num}/{calls}: status={status} turns~={total_turns} "
f"budget={budget.get('working_context_pct')}",
file=sys.stderr,
)
rpc_call(sock, "session.cancel", {"session_id": session_id})
finally:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
budget_path = out_dir / "context_budget_samples.json"
budget_path.write_text(json.dumps(budget_samples, indent=2), encoding="utf-8")
return {
"session_id": session_id,
"total_turns": total_turns,
"compression_jsonl": str(data_dir / "compression.jsonl"),
"context_budget_samples": str(budget_path),
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--tcode-bin",
type=Path,
default=None,
help="Path to the built tcode binary (default: target/debug/tcode "
"resolved relative to the workspace root)",
)
parser.add_argument(
"--calls",
type=int,
default=32,
help=f"Number of task.run calls (each drives {TURNS_PER_CALL} PM "
f"turns); 32 * {TURNS_PER_CALL} = {32 * TURNS_PER_CALL} turns, "
"comfortably past the 200-turn floor",
)
parser.add_argument(
"--out-dir",
type=Path,
default=None,
help="Output directory for the isolated telemetry dir + budget "
"samples (default: a fresh tempdir, printed on stdout)",
)
args = parser.parse_args(argv)
tcode_bin = args.tcode_bin
if tcode_bin is None:
workspace_root = Path(__file__).resolve().parents[3]
tcode_bin = workspace_root / "target" / "debug" / "tcode"
if not tcode_bin.exists():
print(
f"tcode binary not found at {tcode_bin}; build it first with "
"`cargo build -p trusty-code --bin tcode`",
file=sys.stderr,
)
return 2
out_dir = args.out_dir or Path(tempfile.mkdtemp(prefix="tcode-compression-soak-"))
result = run_soak(tcode_bin, args.calls, out_dir)
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())