#![cfg(feature = "server")]
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use once_cell::sync::Lazy;
use symforge::{
domain::{
ControlStateDir, LanguageId, ReferenceKind, ReferenceRecord, SymbolKind, SymbolRecord,
},
live_index::{IndexedFile, LiveIndex, ParseStatus, SharedIndex},
sidecar::spawn_sidecar,
};
use tempfile::TempDir;
use tokio::sync::Mutex;
static CWD_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
fn fixtures_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
.join("sidecar_contract")
}
fn update_goldens() -> bool {
std::env::var("UPDATE_GOLDENS")
.map(|v| v == "1")
.unwrap_or(false)
}
fn normalize_newlines(s: &str) -> String {
s.replace("\r\n", "\n")
}
fn assert_golden(name: &str, actual: &str) {
let path = fixtures_dir().join(name);
let actual = normalize_newlines(actual);
if update_goldens() {
std::fs::create_dir_all(path.parent().unwrap()).expect("create fixtures dir");
std::fs::write(&path, actual.as_bytes()).expect("write golden");
return;
}
let expected = std::fs::read_to_string(&path).unwrap_or_else(|_| {
panic!(
"missing sidecar contract golden: {}\n\
\n\
Regenerate with:\n\
\n UPDATE_GOLDENS=1 cargo test --test sidecar_contract -- --test-threads=1\n\
\n\
Golden files lock the sidecar HTTP contract (ADR 0002). They are consumed\n\
by external hooks we don't control — any change must be explicit and reviewable.",
path.display()
)
});
let expected = normalize_newlines(&expected);
if expected != actual {
panic!(
"sidecar HTTP contract drift in golden `{name}`.\n\
\n\
The live response diverged from the committed golden. If the change is\n\
intentional, regenerate the goldens in the same commit so reviewers see\n\
the contract diff:\n\
\n UPDATE_GOLDENS=1 cargo test --test sidecar_contract -- --test-threads=1\n\
\n\
Note: this contract is consumed by hooks in user environments. A rename,\n\
field removal, or shape change is a breaking change (ADR 0002).\n\
\n\
--- expected (golden) ---\n{expected}\n\
--- actual (live) ---\n{actual}\n\
--- end ---\n"
);
}
}
fn medium_fixture_content() -> Vec<u8> {
let mut out = String::from("// fixed fixture content\n");
while out.lines().count() <= 50 {
out.push_str("// golden fixture padding\n");
}
while out.len() <= 200 {
out.push_str("// pad\n");
}
out.into_bytes()
}
fn make_rust_file_with_symbols(path: &str, symbols: Vec<(&str, SymbolKind)>) -> IndexedFile {
let content = medium_fixture_content();
let symbol_records: Vec<SymbolRecord> = symbols
.into_iter()
.enumerate()
.map(|(i, (name, kind))| SymbolRecord {
name: name.to_string(),
kind,
depth: 0,
sort_order: i as u32,
byte_range: (0, content.len() as u32),
line_range: (1, 1),
doc_byte_range: None,
item_byte_range: None,
})
.collect();
IndexedFile {
relative_path: path.to_string(),
language: LanguageId::Rust,
classification: symforge::domain::FileClassification::for_code_path(path),
content: content.clone(),
symbols: symbol_records,
parse_status: ParseStatus::Parsed,
parse_diagnostic: None,
byte_len: content.len() as u64,
content_hash: "golden".to_string(),
references: vec![],
alias_map: HashMap::new(),
mtime_secs: 0,
}
}
fn make_rust_file_with_refs(
path: &str,
symbols: Vec<(&str, SymbolKind)>,
refs: Vec<(&str, ReferenceKind, u32)>,
) -> IndexedFile {
let mut file = make_rust_file_with_symbols(path, symbols);
file.references = refs
.into_iter()
.map(|(name, kind, line)| ReferenceRecord {
name: name.to_string(),
qualified_name: None,
kind,
byte_range: (0, 0),
line_range: (line, line),
enclosing_symbol_index: Some(0),
})
.collect();
file
}
fn build_shared_index(root: &Path, files: Vec<IndexedFile>) -> SharedIndex {
LiveIndex::from_indexed_files(
root,
files
.into_iter()
.map(|file| (file.relative_path.clone(), file))
.collect(),
)
.expect("tempdir root resolves")
}
fn build_bootstrap_placeholder_index(files: Vec<IndexedFile>) -> SharedIndex {
let shared = LiveIndex::empty();
{
let mut guard = shared.write();
for file in files {
let path = file.relative_path.clone();
guard.add_file(path, file);
}
}
shared
}
fn control_state(root: &Path) -> ControlStateDir {
ControlStateDir::new(root.join(symforge::paths::SYMFORGE_DIR_NAME))
}
fn raw_http_get(port: u16, path: &str, query: &str) -> anyhow::Result<String> {
let addr: std::net::SocketAddr = format!("127.0.0.1:{port}").parse()?;
let timeout = Duration::from_millis(1000);
let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
let request_path = if query.is_empty() {
path.to_string()
} else {
format!("{path}?{query}")
};
let request = format!(
"GET {request_path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"
);
stream.write_all(request.as_bytes())?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
let body = response
.split_once("\r\n\r\n")
.map(|(_, b)| b)
.unwrap_or("")
.to_string();
Ok(body)
}
fn stable_cwd() -> PathBuf {
std::env::current_dir().unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")))
}
fn restore_cwd(path: &Path) {
if std::env::set_current_dir(path).is_err() {
std::env::set_current_dir(env!("CARGO_MANIFEST_DIR"))
.expect("manifest dir must be a valid cwd fallback");
}
}
fn normalize_health_json(body: &str) -> String {
let mut value: serde_json::Value =
serde_json::from_str(body).expect("/health body must be valid JSON");
if let Some(obj) = value.as_object_mut()
&& obj.contains_key("uptime_secs")
{
obj.insert("uptime_secs".into(), serde_json::Value::from(0u64));
}
let mut out = serde_json::to_string_pretty(&value).unwrap();
out.push('\n');
out
}
fn normalize_stats_json(body: &str) -> String {
let value: serde_json::Value =
serde_json::from_str(body).expect("/stats body must be valid JSON");
let mut out = serde_json::to_string_pretty(&value).unwrap();
out.push('\n');
out
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_health_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_shared_index(
tmp.path(),
vec![
make_rust_file_with_symbols("src/alpha.rs", vec![("alpha", SymbolKind::Function)]),
make_rust_file_with_symbols("src/beta.rs", vec![("beta", SymbolKind::Function)]),
],
);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let body = raw_http_get(handle.port, "/health", "").expect("GET /health");
let normalized = normalize_health_json(&body);
assert_golden("health.json", &normalized);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_health_contract_golden_bootstrap_placeholder() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_bootstrap_placeholder_index(vec![
make_rust_file_with_symbols("src/alpha.rs", vec![("alpha", SymbolKind::Function)]),
make_rust_file_with_symbols("src/beta.rs", vec![("beta", SymbolKind::Function)]),
]);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let body = raw_http_get(handle.port, "/health", "").expect("GET /health");
let normalized = normalize_health_json(&body);
assert_golden("health_bootstrap_placeholder.json", &normalized);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_stats_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_shared_index(tmp.path(), vec![]);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let body = raw_http_get(handle.port, "/stats", "").expect("GET /stats");
let normalized = normalize_stats_json(&body);
assert_golden("stats.json", &normalized);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_outline_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_shared_index(
tmp.path(),
vec![make_rust_file_with_symbols(
"src/lib.rs",
vec![
("hello", SymbolKind::Function),
("Config", SymbolKind::Struct),
],
)],
);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let canonical = raw_http_get(handle.port, "/outline", "path=src/lib.rs").expect("GET /outline");
let workflow = raw_http_get(handle.port, "/workflows/source-read", "path=src/lib.rs")
.expect("GET /workflows/source-read");
assert_eq!(
normalize_newlines(&workflow),
normalize_newlines(&canonical),
"workflow adapter /workflows/source-read must be byte-identical to /outline"
);
assert_golden("outline.txt", &canonical);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_impact_edit_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let src_dir = tmp.path().join("src");
std::fs::create_dir_all(&src_dir).unwrap();
std::fs::write(src_dir.join("edit.rs"), medium_fixture_content()).unwrap();
let index = build_shared_index(
tmp.path(),
vec![make_rust_file_with_symbols(
"src/edit.rs",
vec![("edited", SymbolKind::Function)],
)],
);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let _warmup =
raw_http_get(handle.port, "/impact", "path=src/edit.rs").expect("warmup GET /impact");
let canonical = raw_http_get(handle.port, "/impact", "path=src/edit.rs").expect("GET /impact");
let workflow = raw_http_get(
handle.port,
"/workflows/post-edit-impact",
"path=src/edit.rs",
)
.expect("GET /workflows/post-edit-impact");
assert_eq!(
normalize_newlines(&workflow),
normalize_newlines(&canonical),
"workflow adapter /workflows/post-edit-impact must be byte-identical to /impact"
);
assert_golden("impact.txt", &canonical);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_impact_new_file_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let src_dir = tmp.path().join("src");
std::fs::create_dir_all(&src_dir).unwrap();
std::fs::write(
src_dir.join("fresh.rs"),
b"pub fn make_thing() {}\npub struct Thing;\n",
)
.unwrap();
let index = build_shared_index(tmp.path(), vec![]);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let body = raw_http_get(handle.port, "/impact", "path=src/fresh.rs&new_file=true")
.expect("GET /impact?new_file=true");
assert_golden("impact_new_file.txt", &body);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_symbol_context_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let definer =
make_rust_file_with_symbols("src/def.rs", vec![("do_thing", SymbolKind::Function)]);
let caller = make_rust_file_with_refs(
"src/call.rs",
vec![("caller", SymbolKind::Function)],
vec![("do_thing", ReferenceKind::Call, 1)],
);
let index = build_shared_index(tmp.path(), vec![definer, caller]);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let canonical =
raw_http_get(handle.port, "/symbol-context", "name=do_thing").expect("GET /symbol-context");
let workflow = raw_http_get(
handle.port,
"/workflows/search-hit-expansion",
"name=do_thing",
)
.expect("GET /workflows/search-hit-expansion");
assert_eq!(
normalize_newlines(&workflow),
normalize_newlines(&canonical),
"workflow adapter /workflows/search-hit-expansion must be byte-identical to /symbol-context"
);
assert_golden("symbol_context.txt", &canonical);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_repo_map_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_shared_index(
tmp.path(),
vec![
make_rust_file_with_symbols("src/alpha.rs", vec![("alpha", SymbolKind::Function)]),
make_rust_file_with_symbols("src/beta.rs", vec![("beta", SymbolKind::Function)]),
make_rust_file_with_symbols("src/gamma.rs", vec![("gamma", SymbolKind::Function)]),
],
);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let canonical = raw_http_get(handle.port, "/repo-map", "").expect("GET /repo-map");
let workflow =
raw_http_get(handle.port, "/workflows/repo-start", "").expect("GET /workflows/repo-start");
assert_eq!(
normalize_newlines(&workflow),
normalize_newlines(&canonical),
"workflow adapter /workflows/repo-start must be byte-identical to /repo-map"
);
assert_golden("repo_map.txt", &canonical);
handle.shutdown_and_join().await;
restore_cwd(&original);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_prompt_context_contract_golden() {
let tmp = TempDir::new().unwrap();
let _guard = CWD_LOCK.lock().await;
let original = stable_cwd();
std::env::set_current_dir(tmp.path()).unwrap();
let index = build_shared_index(
tmp.path(),
vec![make_rust_file_with_symbols(
"src/lib.rs",
vec![("hello", SymbolKind::Function)],
)],
);
let handle = spawn_sidecar(
Arc::clone(&index),
"127.0.0.1",
Some(tmp.path().to_path_buf()),
Some(control_state(tmp.path())),
)
.await
.expect("spawn_sidecar");
tokio::time::sleep(Duration::from_millis(20)).await;
let query = "text=please%20inspect%20src%2Flib.rs";
let canonical =
raw_http_get(handle.port, "/prompt-context", query).expect("GET /prompt-context");
let workflow = raw_http_get(handle.port, "/workflows/prompt-context", query)
.expect("GET /workflows/prompt-context");
assert_eq!(
normalize_newlines(&workflow),
normalize_newlines(&canonical),
"workflow adapter /workflows/prompt-context must be byte-identical to /prompt-context"
);
assert_golden("prompt_context.txt", &canonical);
handle.shutdown_and_join().await;
restore_cwd(&original);
}