use std::collections::BTreeSet;
use std::path::Path;
use std::time::Duration;
use super::tools::{
ImpactResponse, NeighborsResponse, ReachItem, ReconciliationItem, RefItem, ReferencesResponse,
};
use crate::config::HankConfig;
use crate::daemon::client::{
expected_same_root_daemon, fetch_impact, fetch_neighbors, fetch_references,
};
use crate::daemon::ReachedItem;
use crate::graph::Dir;
use crate::reconcile::reconcile;
const DAEMON_TIMEOUT: Duration = Duration::from_millis(500);
fn usable_daemon(config_override: Option<&Path>, root: &Path) -> Option<(String, u16)> {
let config = HankConfig::resolve(config_override, root).ok()?;
match expected_same_root_daemon(&config, root, DAEMON_TIMEOUT)? {
Ok(addr) => Some(addr),
Err(reason) => {
eprintln!("hank mcp: daemon expected but unusable, transient fallback: {reason}");
None
}
}
}
fn reach_item(r: &ReachedItem, tier: &str) -> ReachItem {
ReachItem {
name: r.name.clone(),
file: r.file.clone(),
start_line: r.start_line,
distance: r.distance,
via: r.via.clone(),
tier: tier.to_string(),
}
}
pub(super) fn neighbors(
config_override: Option<&Path>,
root: &Path,
symbol: &str,
dir: Dir,
) -> Option<NeighborsResponse> {
let (host, port) = usable_daemon(config_override, root)?;
match fetch_neighbors(&host, port, symbol, dir, DAEMON_TIMEOUT) {
Ok(reply) => Some(NeighborsResponse {
symbol: reply.symbol.clone(),
found: reply.found,
count: reply.neighbors.len(),
neighbors: reply
.neighbors
.iter()
.map(|r| reach_item(r, &reply.tier))
.collect(),
tier: reply.tier,
}),
Err(reason) => {
eprintln!("hank mcp: daemon neighbors query failed, transient fallback: {reason}");
None
}
}
}
pub(super) fn impact(
config_override: Option<&Path>,
root: &Path,
symbol: &str,
hops: u32,
cochange: Option<&[String]>,
) -> Option<ImpactResponse> {
let (host, port) = usable_daemon(config_override, root)?;
let reply = match fetch_impact(&host, port, symbol, hops, DAEMON_TIMEOUT) {
Ok(reply) => reply,
Err(reason) => {
eprintln!("hank mcp: daemon impact query failed, transient fallback: {reason}");
return None;
}
};
let structural: BTreeSet<String> = reply.files.iter().cloned().collect();
let reconciliation = cochange.map(|cochange| {
let cochange_set: BTreeSet<String> = cochange.iter().cloned().collect();
let recon = reconcile(&structural, &cochange_set);
ReconciliationItem {
corroborated: recon.corroborated,
structural_only: recon.structural_only,
cochange_only: recon.cochange_only,
}
});
Some(ImpactResponse {
symbol: reply.symbol.clone(),
found: reply.found,
hops: reply.hops,
count: reply.count,
reachable: reply
.reachable
.iter()
.map(|r| reach_item(r, &reply.tier))
.collect(),
structural_files: reply.files,
reconciliation,
tier: reply.tier,
})
}
pub(super) fn references(
config_override: Option<&Path>,
root: &Path,
symbol: &str,
) -> Option<ReferencesResponse> {
let (host, port) = usable_daemon(config_override, root)?;
match fetch_references(&host, port, symbol, DAEMON_TIMEOUT) {
Ok(reply) => Some(ReferencesResponse {
symbol: reply.symbol,
count: reply.count,
definitions: reply
.definitions
.iter()
.map(|d| RefItem {
file: d.file.clone(),
name: symbol.to_string(),
kind: d.kind.clone(),
start_line: d.start_line,
tier: reply.tier.clone(),
})
.collect(),
searched_symbols: None,
tier: reply.tier.clone(),
}),
Err(reason) => {
eprintln!("hank mcp: daemon references query failed, transient fallback: {reason}");
None
}
}
}
pub(super) fn tenant_layer(
config_override: Option<&Path>,
root: &Path,
) -> Option<serde_json::Value> {
let (host, port) = usable_daemon(config_override, root)?;
let body = crate::daemon::client::fetch_status_json(&host, port, DAEMON_TIMEOUT).ok()?;
let layer = body.get("tenant_layer")?.clone();
(!layer.is_null()).then_some(layer)
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
use crate::daemon::{http, ResidentEngine};
fn repo() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("leaf.rs"), "fn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("caller.rs"), "fn caller() { leaf(); }\n").unwrap();
dir
}
fn daemon_config(dir: &Path, port: u16) -> std::path::PathBuf {
let path = dir.join("hank-test-config.toml");
std::fs::write(
&path,
format!(
"[hank.serve]\nuse_daemon = true\nbind_address = \"127.0.0.1\"\n\
mcp_http_port = {port}\n"
),
)
.unwrap();
path
}
async fn spawn_daemon(engine: ResidentEngine) -> u16 {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let _ = axum::serve(listener, http::router(engine)).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
port
}
#[test]
fn no_daemon_expected_is_none_the_normal_silent_case() {
let dir = repo();
assert!(neighbors(None, dir.path(), "leaf", Dir::Callers).is_none());
assert!(impact(None, dir.path(), "leaf", 5, None).is_none());
}
#[test]
fn daemon_expected_but_DOWN_is_none_so_the_tool_falls_back() {
let dir = repo();
let config = daemon_config(dir.path(), 1);
assert!(neighbors(Some(&config), dir.path(), "leaf", Dir::Callers).is_none());
assert!(impact(Some(&config), dir.path(), "leaf", 5, None).is_none());
}
#[tokio::test]
async fn daemon_up_and_same_root_answers_from_the_RESIDENT_graph() {
let dir = repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let port = spawn_daemon(engine).await;
let config = daemon_config(dir.path(), port);
std::fs::write(dir.path().join("late.rs"), "fn late() { leaf(); }\n").unwrap();
let root = dir.path().to_path_buf();
let response = tokio::task::spawn_blocking(move || {
neighbors(
Some(&daemon_config(&root, port)),
&root,
"leaf",
Dir::Callers,
)
})
.await
.unwrap()
.expect("an up, same-root daemon must answer");
assert!(response.found);
let names: Vec<&str> = response.neighbors.iter().map(|n| n.name.as_str()).collect();
assert!(names.contains(&"caller"), "got {names:?}");
assert!(
!names.contains(&"late"),
"`late` postdates the resident graph — its presence would mean a \
transient build answered, not the daemon: {names:?}"
);
assert_eq!(response.tier, "treesitter");
let root = dir.path().to_path_buf();
let cfg = config.clone();
let imp = tokio::task::spawn_blocking(move || {
impact(
Some(&cfg),
&root,
"leaf",
5,
Some(&["caller.rs".to_string(), "ghost.rs".to_string()]),
)
})
.await
.unwrap()
.expect("impact must come from the daemon too");
assert!(imp.found);
assert!(imp.structural_files.contains(&"caller.rs".to_string()));
let recon = imp
.reconciliation
.expect("cochange given -> reconciliation");
assert_eq!(recon.corroborated, vec!["caller.rs".to_string()]);
assert_eq!(recon.cochange_only, vec!["ghost.rs".to_string()]);
let root = dir.path().to_path_buf();
let cfg = config.clone();
let refs = tokio::task::spawn_blocking(move || references(Some(&cfg), &root, "late"))
.await
.unwrap()
.expect("references must come from the daemon");
assert_eq!(refs.count, 0, "resident graph predates late.rs");
let root = dir.path().to_path_buf();
let cfg = config.clone();
let refs = tokio::task::spawn_blocking(move || references(Some(&cfg), &root, "leaf"))
.await
.unwrap()
.expect("references must come from the daemon");
assert_eq!(refs.count, 1);
assert_eq!(refs.definitions[0].name, "leaf");
assert_eq!(refs.definitions[0].tier, "treesitter");
}
#[tokio::test]
async fn a_daemon_serving_a_DIFFERENT_root_is_refused_not_believed() {
let repo_a = repo();
let repo_b = repo();
let engine_b = ResidentEngine::build(repo_b.path(), None).unwrap();
let port = spawn_daemon(engine_b).await;
let root_a = repo_a.path().to_path_buf();
let response = tokio::task::spawn_blocking(move || {
neighbors(
Some(&daemon_config(&root_a, port)),
&root_a,
"leaf",
Dir::Callers,
)
})
.await
.unwrap();
assert!(
response.is_none(),
"a wrong-root daemon must be refused so the tool falls back"
);
}
}