use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use crate::config::HankConfig;
use crate::graph::{Base, CodeGraph, Dir, TenantRegistry};
use crate::hook::Sizing;
use crate::policy::PolicyConfig;
pub mod client;
#[cfg(feature = "mcp")]
pub(crate) mod http;
mod tenanted;
pub mod wire;
use wire::{def_item, graph_tier, reached_item};
pub use wire::{
AdvisedSymbol, DefItem, Definitions, EditReply, EngineStatus, FileSymbolItem, FileSymbols,
Impact, MeasureReply, Neighbors, ReachedItem,
};
#[derive(Clone)]
pub struct ResidentEngine {
inner: Arc<Engine>,
}
struct Engine {
root: PathBuf,
graph: CodeGraph,
config: HankConfig,
built_at: SystemTime,
nodes: usize,
edges: usize,
registry: Option<RwLock<TenantRegistry>>,
}
impl ResidentEngine {
pub fn build(root: &Path, config_override: Option<&Path>) -> anyhow::Result<Self> {
let config = HankConfig::resolve(config_override, root)?;
let graph = CodeGraph::build(root)?;
let (nodes, edges) = graph.stats();
let registry = Base::build_at(root, "HEAD")
.ok()
.map(|base| RwLock::new(TenantRegistry::with_tenancy(base, config.tenancy.clone())));
Ok(Self {
inner: Arc::new(Engine {
root: root.to_path_buf(),
graph,
config,
built_at: SystemTime::now(),
nodes,
edges,
registry,
}),
})
}
#[must_use]
pub fn graph(&self) -> &CodeGraph {
&self.inner.graph
}
#[must_use]
pub fn root(&self) -> &Path {
&self.inner.root
}
#[must_use]
pub fn policy(&self) -> &PolicyConfig {
&self.inner.config.policy
}
#[must_use]
pub fn neighbors(&self, symbol: &str, dir: Dir) -> Neighbors {
let graph = self.graph();
Neighbors {
symbol: symbol.to_string(),
found: graph.has_symbol(symbol),
neighbors: graph.direct(symbol, dir).iter().map(reached_item).collect(),
tier: graph_tier(),
}
}
#[must_use]
pub fn impact(&self, symbol: &str, hops: u32) -> Impact {
let graph = self.graph();
let reachable = graph.reachable(symbol, Dir::Callers, hops);
let files: std::collections::BTreeSet<String> =
reachable.iter().map(|r| r.file.clone()).collect();
Impact {
symbol: symbol.to_string(),
found: graph.has_symbol(symbol),
hops,
count: reachable.len(),
reachable: reachable.iter().map(reached_item).collect(),
files: files.into_iter().collect(),
tier: graph_tier(),
}
}
#[must_use]
pub fn references(&self, symbol: &str) -> Definitions {
let defs = self.graph().definitions(symbol);
Definitions {
symbol: symbol.to_string(),
found: !defs.is_empty(),
count: defs.len(),
definitions: defs.into_iter().map(def_item).collect(),
tier: graph_tier(),
}
}
#[must_use]
pub fn symbols(&self, rel: &str) -> FileSymbols {
let symbols = self.graph().file_symbols(rel);
FileSymbols {
file: rel.to_string(),
known: !symbols.is_empty(),
count: symbols.len(),
symbols: symbols
.into_iter()
.map(|n| FileSymbolItem {
name: n.name.clone(),
kind: n.kind.clone(),
start_line: n.start_line,
})
.collect(),
tier: graph_tier(),
}
}
#[must_use]
pub fn measure_edit(
&self,
file: &Path,
rel: &str,
anchors: &[String],
max_hops: u32,
) -> Sizing {
crate::hook::measure_with_graph(self.graph(), file, rel, anchors, max_hops)
}
#[must_use]
pub fn status(&self) -> EngineStatus {
let uptime_secs = self.inner.built_at.elapsed().map_or(0, |d| d.as_secs());
EngineStatus {
status: "ok",
root: self.inner.root.display().to_string(),
nodes: self.inner.nodes,
edges: self.inner.edges,
uptime_secs,
tier: crate::types::Tier::served(),
tenant_layer: self
.inner
.registry
.as_ref()
.and_then(|lock| lock.read().ok())
.map(|reg| reg.status()),
}
}
}
#[cfg(feature = "mcp")]
pub async fn serve(
root: &Path,
config_override: Option<&Path>,
bind: &str,
port: u16,
) -> anyhow::Result<()> {
let engine = ResidentEngine::build(root, config_override)?;
let status = engine.status();
eprintln!(
"hank daemon: resident graph built — {} nodes, {} edges from {}",
status.nodes, status.edges, status.root
);
http::serve(engine, bind, port).await
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
fn chain_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("mid.rs"), "fn caller() { leaf(); }\n").unwrap();
std::fs::write(dir.path().join("top.rs"), "fn top() { caller(); }\n").unwrap();
dir
}
#[test]
fn callers_of_a_known_symbol_come_from_the_resident_graph() {
let dir = chain_repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let n = engine.neighbors("leaf", Dir::Callers);
assert!(n.found, "leaf is in the graph");
assert!(
n.neighbors.iter().any(|r| r.name == "caller"),
"leaf's direct caller is `caller`, got {:?}",
n.neighbors
);
assert_eq!(n.tier, "treesitter");
}
#[test]
fn an_unknown_symbol_is_NOT_FOUND_distinct_from_no_neighbors() {
let dir = chain_repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let missing = engine.neighbors("does_not_exist", Dir::Callers);
assert!(!missing.found);
assert!(missing.neighbors.is_empty());
let top = engine.neighbors("top", Dir::Callers);
assert!(top.found, "top exists");
assert!(top.neighbors.is_empty(), "nothing calls top");
}
#[test]
fn measure_edit_sizes_against_the_resident_graph() {
let dir = chain_repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let file = dir.path().join("leaf.rs");
let sizing = engine.measure_edit(&file, "leaf.rs", &["fn leaf".to_string()], 5);
match sizing {
Sizing::Measured(radius) => {
assert_eq!(radius.symbols, 2, "leaf reaches caller and top");
assert_eq!(radius.files, 2, "in mid.rs and top.rs");
}
other => panic!("expected a measured radius, got {other:?}"),
}
}
#[test]
fn measure_edit_reports_UNMEASURED_for_an_unparseable_file_never_a_silent_zero() {
let dir = chain_repo();
std::fs::write(dir.path().join("notes.md"), "# hi\n").unwrap();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let file = dir.path().join("notes.md");
let sizing = engine.measure_edit(&file, "notes.md", &[], 5);
assert!(
!matches!(sizing, Sizing::Measured(_)),
"an unparseable file must be UNMEASURED, not a measured zero: {sizing:?}"
);
}
#[test]
fn impact_follows_the_chain_transitively() {
let dir = chain_repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let imp = engine.impact("leaf", 5);
assert!(imp.found);
let names: Vec<&str> = imp.reachable.iter().map(|r| r.name.as_str()).collect();
assert!(names.contains(&"caller"), "got {names:?}");
assert!(names.contains(&"top"), "got {names:?}");
}
#[test]
fn a_resident_impact_query_is_far_under_the_SLO() {
let dir = chain_repo();
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let start = std::time::Instant::now();
for _ in 0..100 {
let _ = engine.impact("leaf", 5);
}
let per_query = start.elapsed() / 100;
assert!(
per_query < std::time::Duration::from_millis(50),
"a resident-graph impact query took {per_query:?} — the SLO win is that \
this path has no rebuild cost"
);
}
}