use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use super::{HookInput, ToolInput};
use crate::config::HankConfig;
use crate::daemon::client::{expected_same_root_daemon, fetch_edit};
use crate::extract::extract_symbols;
use crate::graph::{CodeGraph, Dir};
const DAEMON_TIMEOUT: Duration = Duration::from_millis(500);
const MAX_LISTED: usize = 8;
pub fn run_post_edit(tenant: Option<&str>) -> anyhow::Result<()> {
let mut buf = String::new();
std::io::stdin().lock().read_to_string(&mut buf).ok();
let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
if let Some(text) = advisory_for(&buf, &root, tenant) {
let envelope = serde_json::json!({
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": text,
}
});
println!("{envelope}");
}
Ok(())
}
#[must_use]
pub fn advisory_for(input_json: &str, default_root: &Path, tenant: Option<&str>) -> Option<String> {
let input = HookInput::parse(input_json)?;
let file_path = input.tool_input.file_path.clone()?;
let file = PathBuf::from(&file_path);
if file.extension().and_then(OsStr::to_str) != Some("rs") {
return None;
}
let root = input.root(default_root);
let rel = file
.strip_prefix(&root)
.unwrap_or(&file)
.display()
.to_string();
let source = std::fs::read_to_string(&file).ok()?;
let symbols = extract_symbols(&source, "rust").ok()?;
if symbols.is_empty() {
return None;
}
let names: Vec<String> = match edited_line_spans(&input.tool_input, &source) {
Some(spans) if !spans.is_empty() => {
let scoped: Vec<String> = symbols
.into_iter()
.filter(|sym| {
spans
.iter()
.any(|&(lo, hi)| sym.start_line <= hi && sym.end_line >= lo)
})
.map(|sym| sym.name)
.collect();
if scoped.is_empty() {
return None;
}
scoped
}
_ => symbols.into_iter().map(|s| s.name).collect(),
};
let (mut per_symbol, files) =
resident_feed(&root, &rel, tenant).or_else(|| transient_callers(&root, &rel, &names))?;
per_symbol.sort();
per_symbol.dedup();
if per_symbol.is_empty() {
return None;
}
Some(render(&rel, &per_symbol, &files))
}
fn edited_line_spans(tool_input: &ToolInput, source: &str) -> Option<Vec<(usize, usize)>> {
let mut needles: Vec<&str> = Vec::new();
if let Some(ns) = tool_input.new_string.as_deref() {
needles.push(ns);
}
for e in &tool_input.edits {
if let Some(ns) = e.new_string.as_deref() {
needles.push(ns);
}
}
let mut spans: Vec<(usize, usize)> = Vec::new();
for needle in needles {
if needle.is_empty() {
continue; }
let added_lines = needle.matches('\n').count();
let mut from = 0usize;
while let Some(rel) = source[from..].find(needle) {
let byte = from + rel;
let start_line = source[..byte].matches('\n').count() + 1; spans.push((start_line, start_line + added_lines));
from = byte + needle.len().max(1);
}
}
if spans.is_empty() {
None
} else {
Some(spans)
}
}
type ExternalCallers = (Vec<(String, usize)>, BTreeSet<String>);
fn resident_feed(root: &Path, rel: &str, tenant: Option<&str>) -> Option<ExternalCallers> {
let config = HankConfig::resolve(None, root).ok()?;
let (host, port) = match expected_same_root_daemon(&config, root, DAEMON_TIMEOUT)? {
Ok(addr) => addr,
Err(reason) => {
eprintln!("hank post-edit: daemon expected but unusable, transient fallback: {reason}");
return None;
}
};
let tenant = tenant.unwrap_or("single-tenant");
match fetch_edit(&host, port, tenant, rel, DAEMON_TIMEOUT) {
Ok(reply) => Some((
reply
.advised
.into_iter()
.map(|a| (a.symbol, a.external_callers))
.collect(),
reply.files.into_iter().collect(),
)),
Err(reason) => {
eprintln!("hank post-edit: daemon edit feed failed, transient fallback: {reason}");
None
}
}
}
fn transient_callers(root: &Path, rel: &str, names: &[String]) -> Option<ExternalCallers> {
let graph = CodeGraph::build(root).ok()?;
let mut per_symbol: Vec<(String, usize)> = Vec::new();
let mut files: BTreeSet<String> = BTreeSet::new();
for name in names {
let external: Vec<_> = graph
.direct(name, Dir::Callers)
.into_iter()
.filter(|caller| caller.file != rel)
.collect();
if !external.is_empty() {
per_symbol.push((name.clone(), external.len()));
for caller in &external {
files.insert(caller.file.clone());
}
}
}
Some((per_symbol, files))
}
fn render(rel: &str, per_symbol: &[(String, usize)], files: &BTreeSet<String>) -> String {
let mut out = format!(
"Hank (tree-sitter): your edit to {rel} touches symbol(s) with callers elsewhere \
— re-check these still compile.\n"
);
for (name, count) in per_symbol.iter().take(MAX_LISTED) {
out.push_str(&format!(" {name} <- {count} caller(s)\n"));
}
if per_symbol.len() > MAX_LISTED {
out.push_str(&format!(
" ... and {} more\n",
per_symbol.len() - MAX_LISTED
));
}
let file_list: Vec<&str> = files.iter().map(String::as_str).collect();
out.push_str(&format!("Impacted files: {}", file_list.join(", ")));
out
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
#[test]
fn advises_on_cross_file_impact() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.rs"), "fn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("b.rs"), "fn mid() { leaf(); }\n").unwrap();
let payload = serde_json::json!({
"tool_name": "Edit",
"cwd": dir.path().to_str().unwrap(),
"tool_input": { "file_path": dir.path().join("a.rs").to_str().unwrap() },
})
.to_string();
let text = advisory_for(&payload, dir.path(), None).expect("expected an advisory");
assert!(text.contains("leaf"));
assert!(text.contains("b.rs"));
}
#[test]
fn scopes_advisory_to_the_edited_symbol() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.rs"),
"fn leaf() {\n let x = 2;\n}\nfn other() {}\n",
)
.unwrap();
std::fs::write(dir.path().join("b.rs"), "fn m() { leaf(); other(); }\n").unwrap();
let payload = serde_json::json!({
"tool_name": "Edit",
"cwd": dir.path().to_str().unwrap(),
"tool_input": {
"file_path": dir.path().join("a.rs").to_str().unwrap(),
"old_string": "let x = 1;",
"new_string": "let x = 2;",
},
})
.to_string();
let text = advisory_for(&payload, dir.path(), None).expect("expected an advisory");
assert!(
text.contains("leaf"),
"advises on the edited symbol: {text}"
);
assert!(
!text.contains("other"),
"must NOT cry wolf on the untouched symbol: {text}"
);
}
#[test]
fn no_advice_when_edit_is_outside_every_symbol() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.rs"), "// header updated\nfn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("b.rs"), "fn m() { leaf(); }\n").unwrap();
let payload = serde_json::json!({
"tool_name": "Edit",
"cwd": dir.path().to_str().unwrap(),
"tool_input": {
"file_path": dir.path().join("a.rs").to_str().unwrap(),
"old_string": "// header",
"new_string": "// header updated",
},
})
.to_string();
assert!(
advisory_for(&payload, dir.path(), None).is_none(),
"a comment-only edit must not advise on symbols it did not touch"
);
}
#[test]
fn edited_line_spans_locates_edit_and_falls_back() {
let src = "aaa\nbbb\nccc\n";
let ti = ToolInput {
new_string: Some("bbb".into()),
..Default::default()
};
assert_eq!(edited_line_spans(&ti, src), Some(vec![(2, 2)]));
let ti = ToolInput {
new_string: Some(String::new()),
..Default::default()
};
assert_eq!(edited_line_spans(&ti, src), None);
assert_eq!(edited_line_spans(&ToolInput::default(), src), None);
}
#[test]
fn quiet_when_no_external_callers() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.rs"),
"fn leaf() {}\nfn mid() { leaf(); }\n",
)
.unwrap();
let payload = serde_json::json!({
"cwd": dir.path().to_str().unwrap(),
"tool_input": { "file_path": dir.path().join("a.rs").to_str().unwrap() },
})
.to_string();
assert!(advisory_for(&payload, dir.path(), None).is_none());
}
#[test]
fn quiet_on_non_rust_or_garbage() {
assert!(advisory_for("not json", Path::new("."), None).is_none());
let payload = serde_json::json!({ "tool_input": { "file_path": "README.md" } }).to_string();
assert!(advisory_for(&payload, Path::new("."), None).is_none());
}
fn write_daemon_config(root: &Path, port: u16) {
let bobbin = root.join(".bobbin");
std::fs::create_dir_all(&bobbin).unwrap();
std::fs::write(
bobbin.join("config.toml"),
format!(
"[hank.serve]\nuse_daemon = true\nbind_address = \"127.0.0.1\"\n\
mcp_http_port = {port}\n"
),
)
.unwrap();
}
fn edit_payload(root: &Path, file: &str) -> String {
serde_json::json!({
"tool_name": "Edit",
"cwd": root.to_str().unwrap(),
"tool_input": { "file_path": root.join(file).to_str().unwrap() },
})
.to_string()
}
#[test]
fn daemon_EXPECTED_but_DOWN_falls_back_to_the_transient_advisory() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.rs"), "fn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("b.rs"), "fn mid() { leaf(); }\n").unwrap();
write_daemon_config(dir.path(), 1);
let text = advisory_for(&edit_payload(dir.path(), "a.rs"), dir.path(), None)
.expect("the transient fallback must still advise");
assert!(text.contains("leaf"));
assert!(text.contains("b.rs"));
}
#[cfg(feature = "mcp")]
#[tokio::test(flavor = "multi_thread")]
async fn daemon_up_and_same_root_advises_from_the_RESIDENT_view_and_feeds_the_overlay() {
use crate::daemon::{http, ResidentEngine};
let dir = tempfile::tempdir().unwrap();
let run = |args: &[&str]| {
let out = std::process::Command::new("git")
.arg("-C")
.arg(dir.path())
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?} failed");
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
std::fs::write(dir.path().join("a.rs"), "fn leaf() {}\n").unwrap();
std::fs::write(dir.path().join("b.rs"), "fn mid() { leaf(); }\n").unwrap();
run(&["add", "-A"]);
run(&["commit", "-qm", "base"]);
let engine = ResidentEngine::build(dir.path(), None).unwrap();
let observer = engine.clone();
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(std::time::Duration::from_millis(50)).await;
write_daemon_config(dir.path(), port);
std::fs::write(dir.path().join("a.rs"), "fn leaf() {}\nfn added() {}\n").unwrap();
std::fs::write(dir.path().join("late.rs"), "fn late() { leaf(); }\n").unwrap();
let payload = edit_payload(dir.path(), "a.rs");
let root = dir.path().to_path_buf();
let text = tokio::task::spawn_blocking(move || advisory_for(&payload, &root, Some("t1")))
.await
.unwrap()
.expect("an up, same-root daemon must advise");
assert!(text.contains("b.rs"), "{text}");
assert!(
!text.contains("late.rs"),
"`late.rs` is uncommitted and untouched — its presence means a \
transient build answered, not the tenant view: {text}"
);
let reg = observer.registry().expect("repo ⇒ tenant layer");
let reg = reg.read().unwrap();
let overlay = reg.overlay("t1").expect("the edit created t1's overlay");
assert!(overlay.is_touched("a.rs"));
}
}