#![allow(dead_code)]
pub mod uds_mock;
#[allow(unused_imports)]
pub use uds_mock::{MockMemoryDaemon, spawn as spawn_mock_memory_daemon};
use std::process::Stdio;
use std::time::Duration;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;
const WIRE_TIMEOUT: Duration = Duration::from_secs(5);
pub fn tcode_command() -> TcodeCommand {
let isolation = ChildIsolation::new();
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.env_clear().envs(isolation.env());
TcodeCommand {
cmd,
_isolation: isolation,
}
}
pub struct TcodeCommand {
cmd: std::process::Command,
_isolation: ChildIsolation,
}
impl std::ops::Deref for TcodeCommand {
type Target = std::process::Command;
fn deref(&self) -> &Self::Target {
&self.cmd
}
}
impl std::ops::DerefMut for TcodeCommand {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cmd
}
}
const INHERITED_ENV_ALLOWLIST: &[&str] = &[
"PATH",
"TMPDIR",
"LANG",
"LC_ALL",
"LC_CTYPE",
"USER",
"LOGNAME",
"RUST_BACKTRACE",
"RUST_LOG",
];
pub struct ChildIsolation {
root: tempfile::TempDir,
}
impl ChildIsolation {
pub fn new() -> Self {
let root = tempfile::Builder::new()
.prefix("tcode-child-")
.tempdir()
.expect("#9139: cannot create the child isolation root — refusing to spawn");
for dir in ["home", "data"] {
std::fs::create_dir(root.path().join(dir))
.expect("#9139: cannot create the child isolation tree — refusing to spawn");
}
Self { root }
}
pub fn home(&self) -> std::path::PathBuf {
self.root.path().join("home")
}
pub fn data_dir(&self) -> std::path::PathBuf {
self.root.path().join("data")
}
pub fn memory_socket(&self) -> std::path::PathBuf {
self.root.path().join("no-memory-daemon.sock")
}
pub fn env(&self) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
let mut env: Vec<(std::ffi::OsString, std::ffi::OsString)> = INHERITED_ENV_ALLOWLIST
.iter()
.filter_map(|key| std::env::var_os(key).map(|value| ((*key).into(), value)))
.collect();
env.push((trusty_common::test_harness::FORCE_ENV.into(), "1".into()));
env.push(("HOME".into(), self.home().into()));
env.push((
trusty_common::data_dir::DATA_DIR_OVERRIDE_ENV.into(),
self.data_dir().into(),
));
env.push((
trusty_common::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV.into(),
self.memory_socket().into(),
));
env
}
}
pub fn project_with_agents() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("project tempdir");
let agents = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents).expect("mkdir agents");
std::fs::write(
agents.join("pm.md"),
"---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
)
.expect("write pm.md");
std::fs::write(
agents.join("python-engineer.md"),
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
)
.expect("write python-engineer.md");
tmp
}
pub fn home_with_user_level_agents() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("home tempdir");
let agents = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents).expect("mkdir user-level agents");
std::fs::write(
agents.join("pm.md"),
"---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
)
.expect("write pm.md");
std::fs::write(
agents.join("python-engineer.md"),
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
)
.expect("write python-engineer.md");
tmp
}
pub struct StdioSession {
child: Child,
stdin: ChildStdin,
lines: Lines<BufReader<ChildStdout>>,
_project: Option<tempfile::TempDir>,
_isolation: ChildIsolation,
}
impl StdioSession {
pub fn spawn() -> Self {
let project = tempfile::tempdir().expect("throwaway project root");
let mut session = Self::spawn_inner(Some(project.path()), None, None, &[], &[]);
session._project = Some(project);
session
}
pub fn spawn_with_mock_llm(project: &std::path::Path) -> Self {
Self::spawn_inner(
Some(project),
Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
None,
&[],
&[],
)
}
pub fn spawn_with_mock_llm_variant(project: &std::path::Path, mock_llm_value: &str) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], &[])
}
pub fn spawn_with_mock_llm_variant_and_env(
project: &std::path::Path,
mock_llm_value: &str,
envs: &[(&str, &str)],
) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, envs, &[])
}
pub fn spawn_with_mock_llm_variant_and_envs(
project: &std::path::Path,
mock_llm_value: &str,
extra_envs: &[(&str, &str)],
) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], extra_envs)
}
pub fn spawn_projectless_with_mock_llm(home: &std::path::Path) -> Self {
Self::spawn_inner(
None,
Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
Some(home),
&[],
&[],
)
}
fn spawn_inner(
project: Option<&std::path::Path>,
mock_llm_value: Option<&str>,
home: Option<&std::path::Path>,
envs: &[(&str, &str)],
extra_envs: &[(&str, &str)],
) -> Self {
let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.arg("serve");
let isolation = ChildIsolation::new();
cmd.env_clear().envs(isolation.env());
for (key, value) in extra_envs {
cmd.env(key, value);
}
if let Some(project) = project {
cmd.arg("--project").arg(project);
}
cmd.arg("--stdio");
if let Some(home) = home {
cmd.env("HOME", home);
}
if let Some(value) = mock_llm_value {
cmd.env(trusty_code::task::mock_llm::MOCK_LLM_ENV, value);
}
for (key, value) in envs {
cmd.env(key, value);
}
let mut child = cmd
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.expect("spawn `tcode serve --stdio`");
let stdin = child.stdin.take().expect("child stdin");
let stdout = child.stdout.take().expect("child stdout");
let lines = BufReader::new(stdout).lines();
Self {
child,
stdin,
lines,
_project: None,
_isolation: isolation,
}
}
pub async fn write_request(&mut self, id: i64, method: &str, params: Value) {
let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let mut line = serde_json::to_string(&req).expect("serialise request");
line.push('\n');
self.stdin
.write_all(line.as_bytes())
.await
.expect("write request line");
self.stdin.flush().await.expect("flush stdin");
}
pub async fn call(&mut self, id: i64, method: &str, params: Value) -> Value {
self.write_request(id, method, params).await;
timeout(WIRE_TIMEOUT, async {
loop {
let line = self.next_line().await;
if let Some(resp) = find_response(&line, id) {
return resp;
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for a response to id={id} ({method})"))
}
pub async fn read_lines(&mut self, max_lines: usize) -> Vec<String> {
let mut collected = Vec::new();
let _ = timeout(WIRE_TIMEOUT, async {
while collected.len() < max_lines {
collected.push(self.next_line().await);
}
})
.await;
collected
}
async fn next_line(&mut self) -> String {
self.lines
.next_line()
.await
.expect("read stdout line")
.expect("tcode serve --stdio closed stdout unexpectedly")
}
pub async fn shutdown_via_eof_and_assert_clean_exit(mut self) {
drop(self.stdin);
let status = timeout(WIRE_TIMEOUT, self.child.wait())
.await
.expect("timed out waiting for the daemon to exit after stdin EOF")
.expect("wait() failed");
assert!(
status.success(),
"daemon must exit 0 on stdin EOF, got {status:?}"
);
}
}
pub struct SocketDaemon {
child: Child,
pub socket: std::path::PathBuf,
_project: Option<tempfile::TempDir>,
isolation: ChildIsolation,
}
const SOCKET_READY_TIMEOUT: Duration = Duration::from_secs(30);
const STREAM_FRAME_TIMEOUT: Duration = Duration::from_secs(10);
pub async fn spawn_socket_daemon() -> SocketDaemon {
let project = tempfile::tempdir().expect("throwaway project root");
let mut daemon = spawn_socket_daemon_with_env(project.path(), &[]).await;
daemon._project = Some(project);
daemon
}
pub async fn spawn_socket_daemon_with_env(
project: &std::path::Path,
envs: &[(&str, &str)],
) -> SocketDaemon {
let isolation = ChildIsolation::new();
let socket = isolation
.data_dir()
.join("trusty-code")
.join("trusty-code.sock");
let log = isolation.home().join("daemon.stderr");
let stderr = std::fs::File::create(&log).expect("daemon stderr log");
let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.arg("serve").arg("--project").arg(project);
cmd.env_clear().envs(isolation.env());
for (key, value) in envs {
cmd.env(key, value);
}
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr))
.kill_on_drop(true)
.spawn()
.expect("spawn `tcode serve`");
let started = std::time::Instant::now();
while !trusty_common::uds::socket_is_serving(&socket, Duration::from_millis(200)).await {
if let Some(status) = child.try_wait().expect("try_wait") {
panic!(
"`tcode serve` exited ({status}) before answering on {}\nstderr:\n{}",
socket.display(),
std::fs::read_to_string(&log).unwrap_or_default()
);
}
assert!(
started.elapsed() < SOCKET_READY_TIMEOUT,
"`tcode serve` never answered on {}\nstderr:\n{}",
socket.display(),
std::fs::read_to_string(&log).unwrap_or_default()
);
tokio::time::sleep(Duration::from_millis(50)).await;
}
SocketDaemon {
child,
socket,
_project: None,
isolation,
}
}
impl SocketDaemon {
pub async fn call(&self, id: i64, method: &str, params: Value) -> Value {
let request = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
trusty_common::uds::send_framed_request::<Value, Value>(
&self.socket,
&request,
STREAM_FRAME_TIMEOUT,
)
.await
.unwrap_or_else(|e| panic!("{method} must answer over the socket: {e}"))
}
pub async fn open_events(&self, session_id: &str) -> trusty_common::uds::FramedStream<Value> {
let request = json!({
"jsonrpc": "2.0",
"id": 0,
"method": "session.events",
"params": {"session_id": session_id},
"stream": true,
});
trusty_common::uds::send_framed_stream_request(&self.socket, &request, STREAM_FRAME_TIMEOUT)
.await
.unwrap_or_else(|e| panic!("session.events must open over the socket: {e}"))
}
pub fn data_dir(&self) -> std::path::PathBuf {
self.isolation.data_dir()
}
pub fn stderr(&self) -> String {
std::fs::read_to_string(self.isolation.home().join("daemon.stderr")).unwrap_or_default()
}
pub async fn shutdown_via_sigterm_and_assert_clean_exit(mut self) {
let pid = self.child.id().expect("child has a pid") as i32;
unsafe {
libc::kill(pid, libc::SIGTERM);
}
let status = timeout(Duration::from_secs(20), self.child.wait())
.await
.expect("timed out waiting for the daemon to exit after SIGTERM")
.expect("wait() failed");
assert!(
status.success(),
"daemon must exit 0 after graceful SIGTERM shutdown, got {status:?}\nstderr:\n{}",
self.stderr()
);
assert!(
!self.socket.exists(),
"a clean stop must unlink {}",
self.socket.display()
);
}
}
pub async fn read_stream_until(
stream: &mut trusty_common::uds::FramedStream<Value>,
frames: &mut Vec<Value>,
until: impl Fn(&Value) -> bool,
) {
if frames.iter().any(&until) {
return;
}
loop {
match stream.next_frame().await {
Some(Ok(frame)) => {
let done = until(&frame);
frames.push(frame);
if done {
return;
}
}
Some(Err(e)) => panic!("session.events failed after {frames:?}: {e}"),
None => panic!("session.events ended before the awaited frame: {frames:?}"),
}
}
}
pub fn kind_is(kind: &'static str) -> impl Fn(&Value) -> bool {
move |frame| frame["kind"] == kind
}
pub fn find_response(line: &str, id: i64) -> Option<Value> {
let v: Value = serde_json::from_str(line).ok()?;
if v.get("id").and_then(|i| i.as_i64()) == Some(id) {
Some(v)
} else {
None
}
}
pub fn find_session_event(line: &str, session_id: &str) -> Option<Value> {
let v: Value = serde_json::from_str(line).ok()?;
if v.get("method").and_then(|m| m.as_str()) == Some("session.event")
&& v["params"]["session_id"].as_str() == Some(session_id)
{
Some(v["params"].clone())
} else {
None
}
}
pub async fn run_task_to_completion(daemon: &mut StdioSession, task_description: &str) -> String {
let run_resp = daemon
.call(1, "task.run", json!({"task_description": task_description}))
.await;
assert!(run_resp["error"].is_null(), "task.run failed: {run_resp}");
let session_id = run_resp["result"]["session_id"]
.as_str()
.expect("task.run must return a session_id")
.to_string();
let attach_resp = daemon
.call(2, "session.attach", json!({"session_id": session_id}))
.await;
assert!(
attach_resp["error"].is_null(),
"attach failed: {attach_resp}"
);
let mut kinds: Vec<String> = attach_resp["result"]["events"]
.as_array()
.expect("attach must return a replay events array")
.iter()
.map(|e| {
e["kind"]
.as_str()
.expect("kind must be a string")
.to_string()
})
.collect();
let mut iterations = 0;
while !kinds.iter().any(|k| k == "session_done") {
iterations += 1;
assert!(
iterations < 20,
"gave up waiting for session_done after {iterations} read rounds; kinds so far: {kinds:?}"
);
let lines = daemon.read_lines(20).await;
assert!(
!lines.is_empty(),
"timed out waiting for more events; kinds so far: {kinds:?}"
);
for line in &lines {
if let Some(envelope) = find_session_event(line, &session_id) {
kinds.push(
envelope["kind"]
.as_str()
.expect("kind must be a string")
.to_string(),
);
}
}
}
session_id
}
pub fn assert_envelopes_contiguous(envelopes: &[Value]) -> (u64, u64) {
assert!(
!envelopes.is_empty(),
"expected at least one envelope to check"
);
let mut previous: Option<u64> = None;
for envelope in envelopes {
for field in ["session_id", "seq", "at", "kind", "event"] {
assert!(
envelope.get(field).is_some(),
"envelope missing required field {field:?}: {envelope}"
);
}
let seq = envelope["seq"].as_u64().expect("seq must be a u64");
if let Some(prev) = previous {
assert_eq!(
seq,
prev + 1,
"seq must increase by exactly 1 with no gaps or duplicates: {envelope}"
);
}
previous = Some(seq);
}
let first = envelopes[0]["seq"].as_u64().unwrap();
let last = envelopes[envelopes.len() - 1]["seq"].as_u64().unwrap();
(first, last)
}