#![cfg(feature = "server")]
use std::fs;
use std::path::Path;
use serde_json::{Value, json};
use symforge::live_index::LiveIndex;
use symforge::protocol::SymForgeServer;
const FIXTURE_FILES: &[&str] = &[
"Cargo.toml",
"src/lib.rs",
"src/a.rs",
"src/b.rs",
"src/c.rs",
"src/main.rs",
];
fn git(args: &[&str], root: &Path) {
let output = symforge::process_util::hidden_command("git")
.args(args)
.current_dir(root)
.output()
.unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn bootstrap_fixture() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");
for rel in FIXTURE_FILES {
let from = fixture_src.join(rel);
let to = root.join(rel);
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
}
fs::copy(&from, &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
}
git(&["init"], root);
git(&["config", "user.email", "test@test.com"], root);
git(&["config", "user.name", "Test"], root);
git(&["add", "."], root);
git(&["commit", "-m", "initial"], root);
fs::write(
root.join("src/a.rs"),
"use cbm_impact_fixture::core;\n\n\
// S1a fixture bootstrap: real body change, same call graph.\n\
pub fn call_a() -> u32 {\n core() + 1\n}\n",
)
.expect("rewrite src/a.rs");
git(&["commit", "-am", "change a"], root);
dir
}
fn server_over(root: &Path) -> SymForgeServer {
let shared = LiveIndex::load(root).expect("load index");
SymForgeServer::new(
shared,
"detect_impact_test".to_string(),
std::sync::Arc::new(parking_lot::Mutex::new(
symforge::watcher::WatcherInfo::default(),
)),
Some(root.to_path_buf()),
None,
)
}
fn impact_payload(body: &str) -> Value {
const MARKER: &str = "--- impact payload ---\n";
let start = body
.find(MARKER)
.unwrap_or_else(|| panic!("no impact payload marker in:\n{body}"));
let json_text = &body[start + MARKER.len()..];
let json_text = json_text.split("\n\nWarning:").next().unwrap_or(json_text);
serde_json::from_str(json_text)
.unwrap_or_else(|e| panic!("parse impact payload: {e}\n---\n{json_text}"))
}
#[tokio::test]
async fn detect_impact_fixture_blast_matches_expected() {
let dir = bootstrap_fixture();
let server = server_over(dir.path());
let body = server
.dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
.await;
let payload = impact_payload(&body);
assert_eq!(payload["changed_files"], json!(["src/a.rs"]));
let changed_names: Vec<&str> = payload["changed_symbols"]
.as_array()
.expect("changed_symbols array")
.iter()
.map(|s| s["name"].as_str().expect("symbol name"))
.collect();
assert_eq!(
changed_names,
vec!["call_a"],
"src/a.rs defines exactly one symbol: call_a"
);
let blast = payload["blast_radius"]
.as_array()
.expect("blast_radius array");
assert_eq!(blast.len(), 1, "unexpected blast radius: {blast:?}");
assert_eq!(blast[0]["symbol"], json!("src/main.rs::main"));
assert_eq!(blast[0]["hop"], json!(1));
assert_eq!(blast[0]["risk"], json!("critical"));
assert_eq!(payload["risk_summary"]["critical"], json!(1));
assert_eq!(payload["risk_summary"]["high"], json!(0));
assert_eq!(payload["risk_summary"]["medium"], json!(0));
assert_eq!(payload["risk_summary"]["low"], json!(0));
assert_eq!(payload["pagination"]["blast_radius"]["total"], json!(1));
assert_eq!(payload["pagination"]["blast_radius"]["returned"], json!(1));
assert_eq!(
payload["pagination"]["blast_radius"]["truncated"],
json!(false)
);
}
#[tokio::test]
async fn detect_impact_defaults_base_branch_to_main_when_unset() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");
for rel in FIXTURE_FILES {
let to = root.join(rel);
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
}
fs::copy(fixture_src.join(rel), &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
}
git(&["init"], root);
git(&["config", "user.email", "test@test.com"], root);
git(&["config", "user.name", "Test"], root);
git(&["add", "."], root);
git(&["commit", "-m", "initial"], root);
git(&["branch", "-M", "main"], root);
git(&["checkout", "-b", "feature"], root);
fs::write(
root.join("src/a.rs"),
"use cbm_impact_fixture::core;\n\n\
// committed on feature, not merged into main.\n\
pub fn call_a() -> u32 {\n core()\n}\n",
)
.expect("rewrite src/a.rs");
git(&["commit", "-am", "change a on feature"], root);
let server = server_over(root);
let body = server
.dispatch_tool_for_tests("detect_impact", json!({}))
.await;
let payload = impact_payload(&body);
assert_eq!(
payload["changed_files"],
json!(["src/a.rs"]),
"omitting base_branch/since must diff against the default `main` branch \
(a real blast radius), not return an empty uncommitted-only result:\n{body}"
);
assert!(
body.contains("base: main"),
"default resolution must disclose the resolved base ref:\n{body}"
);
assert!(
!body.contains("differs from origin/main"),
"no origin/main → no staleness note:\n{body}"
);
}
#[tokio::test]
async fn detect_impact_non_git_repo_clear_error() {
let dir = tempfile::tempdir().expect("tempdir");
fs::write(dir.path().join("lib.rs"), "pub fn core() {}\n").expect("write fixture file");
let server = server_over(dir.path());
let body = server
.dispatch_tool_for_tests("detect_impact", json!({}))
.await;
assert!(
body.contains("Git unavailable"),
"expected a clear git-unavailable error, got:\n{body}"
);
}
#[tokio::test]
async fn detect_impact_default_prefers_origin_main_over_stale_local() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let fixture_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cbm_impact");
for rel in FIXTURE_FILES {
let to = root.join(rel);
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).unwrap_or_else(|e| panic!("mkdir for {rel}: {e}"));
}
fs::copy(fixture_src.join(rel), &to).unwrap_or_else(|e| panic!("copy {rel}: {e}"));
}
git(&["init"], root);
git(&["config", "user.email", "test@test.com"], root);
git(&["config", "user.name", "Test"], root);
git(&["add", "."], root);
git(&["commit", "-m", "C0 initial"], root);
git(&["branch", "-M", "main"], root);
fs::write(
root.join("src/b.rs"),
"pub fn call_b() -> u32 {\n 2\n}\n// C1: on origin/main only.\n",
)
.expect("rewrite src/b.rs");
git(&["commit", "-am", "C1 change b"], root);
git(&["update-ref", "refs/remotes/origin/main", "main"], root);
git(&["checkout", "-b", "feature"], root);
git(&["branch", "-f", "main", "HEAD~1"], root);
fs::write(
root.join("src/a.rs"),
"use cbm_impact_fixture::core;\n\n\
// C2: on feature only.\n\
pub fn call_a() -> u32 {\n core()\n}\n",
)
.expect("rewrite src/a.rs");
git(&["commit", "-am", "C2 change a on feature"], root);
let server = server_over(root);
let body = server
.dispatch_tool_for_tests("detect_impact", json!({}))
.await;
let payload = impact_payload(&body);
assert_eq!(
payload["changed_files"],
json!(["src/a.rs"]),
"default must diff against origin/main (true delta), not stale local main:\n{body}"
);
assert!(
body.contains("base: origin/main"),
"must disclose the resolved base ref:\n{body}"
);
assert!(
body.contains("local main is behind origin/main"),
"must disclose direction-aware staleness (local behind) vs origin/main:\n{body}"
);
}
#[tokio::test]
async fn detect_impact_caps_large_changed_set() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
fs::create_dir_all(root.join("src")).expect("mkdir src");
fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"caps_fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
)
.expect("write Cargo.toml");
let mut changed = String::from("pub fn core() -> u32 {\n 0\n}\n");
for i in 0..210 {
changed.push_str(&format!("pub fn pad_{i}() -> u32 {{\n {i}\n}}\n"));
}
fs::write(root.join("src/changed.rs"), &changed).expect("write changed.rs");
let mut callers = String::new();
for i in 0..210 {
callers.push_str(&format!("pub fn caller_{i}() -> u32 {{\n core()\n}}\n"));
}
fs::write(root.join("src/callers.rs"), &callers).expect("write callers.rs");
git(&["init"], root);
git(&["config", "user.email", "test@test.com"], root);
git(&["config", "user.name", "Test"], root);
git(&["add", "."], root);
git(&["commit", "-m", "initial"], root);
let mut changed = String::from("pub fn core() -> u32 {\n 1\n}\n");
for i in 0..210 {
changed.push_str(&format!("pub fn pad_{i}() -> u32 {{\n {}\n}}\n", i + 1));
}
fs::write(root.join("src/changed.rs"), &changed).expect("rewrite changed.rs");
git(&["commit", "-am", "touch changed"], root);
let server = server_over(root);
let body = server
.dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
.await;
let payload = impact_payload(&body);
assert_eq!(payload["changed_files"], json!(["src/changed.rs"]));
assert_eq!(payload["pagination"]["changed_files"]["total"], json!(1));
assert_eq!(
payload["pagination"]["changed_files"]["truncated"],
json!(false)
);
assert_eq!(
payload["changed_symbols"].as_array().expect("array").len(),
200,
"changed_symbols array must be capped at 200:\n{body}"
);
assert_eq!(
payload["pagination"]["changed_symbols"]["total"],
json!(211)
);
assert_eq!(
payload["pagination"]["changed_symbols"]["returned"],
json!(200)
);
assert_eq!(
payload["pagination"]["changed_symbols"]["truncated"],
json!(true)
);
assert_eq!(
payload["blast_radius"].as_array().expect("array").len(),
200,
"blast_radius array must be capped at 200:\n{body}"
);
assert_eq!(payload["pagination"]["blast_radius"]["total"], json!(210));
assert_eq!(
payload["pagination"]["blast_radius"]["returned"],
json!(200)
);
assert_eq!(
payload["pagination"]["blast_radius"]["truncated"],
json!(true)
);
assert_eq!(
payload["risk_summary"]["high"],
json!(210),
"risk_summary must reflect the full blast set, not the capped list:\n{body}"
);
assert!(
body.contains("[truncated]"),
"summary must disclose truncation:\n{body}"
);
}
#[tokio::test]
async fn detect_impact_depth_cap_at_five() {
let dir = bootstrap_fixture();
let server = server_over(dir.path());
let body = server
.dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1", "depth": 99 }))
.await;
assert!(
body.contains("depth clamped to 5 (requested 99)"),
"expected a depth-cap warning, got:\n{body}"
);
let payload = impact_payload(&body);
assert_eq!(payload["changed_files"], json!(["src/a.rs"]));
}
#[tokio::test]
async fn detect_impact_default_source_focuses_changed_set() {
let dir = bootstrap_fixture();
let root = dir.path();
fs::create_dir_all(root.join("data")).expect("mkdir data");
fs::write(
root.join("data/config.json"),
"{\n \"alpha_key\": 1,\n \"beta_key\": 2\n}\n",
)
.expect("write data file");
let server = server_over(root);
let body = server
.dispatch_tool_for_tests("detect_impact", json!({ "since": "HEAD~1" }))
.await;
let payload = impact_payload(&body);
assert_eq!(
payload["changed_files"],
json!(["src/a.rs"]),
"default detect_impact must source-focus the seed and drop untracked data files:\n{body}"
);
let changed_names: Vec<&str> = payload["changed_symbols"]
.as_array()
.expect("changed_symbols array")
.iter()
.map(|s| s["name"].as_str().expect("symbol name"))
.collect();
assert!(
!changed_names
.iter()
.any(|n| n.contains("alpha_key") || n.contains("beta_key")),
"no data-file-derived (JSON key) symbols may seed the impact walk: {changed_names:?}\n{body}"
);
let body_incl = server
.dispatch_tool_for_tests(
"detect_impact",
json!({ "since": "HEAD~1", "include_data": true }),
)
.await;
let payload_incl = impact_payload(&body_incl);
let incl_files: Vec<&str> = payload_incl["changed_files"]
.as_array()
.expect("changed_files array")
.iter()
.map(|f| f.as_str().expect("file path"))
.collect();
assert!(
incl_files.contains(&"data/config.json"),
"include_data=true must restore the untracked data file in the changed-set: {incl_files:?}\n{body_incl}"
);
}