use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::TempDir;
const ADOPTION_LOG_RELATIVE: &str = ".symforge/hook-adoption.log";
const PORT_FILE_RELATIVE: &str = ".symforge/sidecar.port";
const READ_PAYLOAD: &str = r#"{"tool_name":"Read","tool_input":{"file_path":"src/foo.rs"}}"#;
#[test]
fn run_hook_no_sidecar_writes_source_read_no_sidecar_event() {
let tmp = TempDir::new().expect("tempdir creation");
let contents = run_hook_in_tempdir(tmp.path(), READ_PAYLOAD);
assert!(
contents.contains("\tsource-read\tno-sidecar"),
"log must contain a tab-separated `source-read\\tno-sidecar` entry \
(regression: record_hook_outcome_with_detail removed from the \
port-file-missing dispatch branch); got:\n{contents}"
);
}
#[test]
fn run_hook_stale_port_writes_source_read_no_sidecar_event() {
let tmp = TempDir::new().expect("tempdir creation");
std::fs::create_dir_all(tmp.path().join(".symforge")).expect("create .symforge dir");
let listener = TcpListener::bind("127.0.0.1:0").expect("bind stale-port listener");
let stale_port = listener
.local_addr()
.expect("stale-port local_addr")
.port();
std::fs::write(
tmp.path().join(PORT_FILE_RELATIVE),
stale_port.to_string(),
)
.expect("write stale port file");
let contents = run_hook_in_tempdir(tmp.path(), READ_PAYLOAD);
drop(listener);
assert!(
contents.contains("\tsource-read\tno-sidecar"),
"log must contain a tab-separated `source-read\\tno-sidecar` entry \
(regression: record_hook_outcome_with_detail removed from the \
stale-port dispatch branch); got:\n{contents}"
);
}
#[test]
fn run_hook_routed_success_writes_source_read_routed_event() {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock sidecar listener");
let port = listener
.local_addr()
.expect("mock sidecar local_addr")
.port();
let mock = thread::spawn(move || {
if let Ok((mut stream, _)) = listener.accept() {
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
let mut buf = [0u8; 2048];
let _ = stream.read(&mut buf);
let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
}
});
let tmp = TempDir::new().expect("tempdir creation");
std::fs::create_dir_all(tmp.path().join(".symforge")).expect("create .symforge dir");
std::fs::write(tmp.path().join(PORT_FILE_RELATIVE), port.to_string())
.expect("write mock port file");
let contents = run_hook_in_tempdir(tmp.path(), READ_PAYLOAD);
drop(mock);
assert!(
contents.contains("\tsource-read\trouted"),
"log must contain a tab-separated `source-read\\trouted` entry \
(regression: record_hook_outcome removed from the success \
dispatch branch); got:\n{contents}"
);
}
fn run_hook_in_tempdir(cwd: &Path, payload: &str) -> String {
let bin = env!("CARGO_BIN_EXE_symforge");
let mut child = Command::new(bin)
.arg("hook")
.current_dir(cwd)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("symforge binary should spawn");
child
.stdin
.as_mut()
.expect("piped stdin")
.write_all(payload.as_bytes())
.expect("write hook payload to child stdin");
drop(child.stdin.take());
let status = wait_with_timeout(&mut child, Duration::from_secs(15))
.expect("hook subprocess should exit within 15s")
.expect("hook subprocess status readable");
assert!(
status.success(),
"symforge hook exited non-zero: {status:?}"
);
let log_path = cwd.join(ADOPTION_LOG_RELATIVE);
assert!(
log_path.exists(),
"run_hook must append to {ADOPTION_LOG_RELATIVE} under the child's cwd; \
missing at {}. This usually means a record_hook_outcome* call was \
removed from the run_hook dispatch branch being exercised.",
log_path.display()
);
std::fs::read_to_string(&log_path).expect("log readable")
}
fn wait_with_timeout(
child: &mut Child,
timeout: Duration,
) -> std::io::Result<Option<ExitStatus>> {
let start = Instant::now();
loop {
match child.try_wait()? {
Some(status) => return Ok(Some(status)),
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
return Ok(None);
}
thread::sleep(Duration::from_millis(25));
}
}
}
}