from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
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]:
env = {
"TCODE_MOCK_LLM": mock_llm,
"TCODE_TELEMETRY_DATA_DIR": str(data_dir),
"PATH": _inherited_path(),
"HOME": str(Path.home()),
}
if extra_env:
env.update(extra_env)
proc = subprocess.Popen(
[str(tcode_bin), "serve", "--project", str(project), "--http", "--port", "0"],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
env=env,
)
assert proc.stderr is not None
base_url = None
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
line = proc.stderr.readline()
if not line:
if proc.poll() is not None:
raise RuntimeError(
f"tcode serve exited early (code {proc.returncode}) before reporting its address"
)
continue
match = re.search(r"listening on (http://\S+)", line)
if match:
base_url = match.group(1)
break
if base_url is None:
proc.kill()
raise RuntimeError("timed out waiting for tcode serve to report its bound address")
def _drain():
while proc.poll() is None:
if proc.stderr.readline() == "":
break
threading.Thread(target=_drain, daemon=True).start()
return proc, base_url
def _inherited_path() -> str:
import os
return os.environ.get("PATH", "/usr/bin:/bin")
class RpcError(RuntimeError):
pass
def rpc_call(base_url: 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")
req = urllib.request.Request(
f"{base_url}/rpc", data=body, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=30) as resp:
payload = json.loads(resp.read())
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(base_url: str, session_id: str, timeout_s: float = 60) -> str:
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
status = rpc_call(base_url, "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, base_url = spawn_daemon(tcode_bin, project, data_dir)
budget_samples = []
try:
created = rpc_call(base_url, "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(
base_url,
"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(base_url, session_id)
total_turns += TURNS_PER_CALL
budget = rpc_call(
base_url, "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(base_url, "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())