use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use super::measure::{measure_within, relative};
use super::{deny_envelope, first_notice_for_session, system_message, HookInput};
use crate::config::HankConfig;
use crate::extract::language_for_extension;
use crate::policy::{BlastRadius, Mode};
use crate::types::Freshness;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Allow,
Deny(String),
Notify(String),
}
pub fn run_pre_edit(tenant: Option<&str>, config_override: Option<&Path>) -> 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("."));
match guard(&buf, &root, tenant, config_override) {
Outcome::Allow => {}
Outcome::Deny(reason) => println!("{}", deny_envelope(&reason)),
Outcome::Notify(message) => println!("{}", system_message(&message)),
}
Ok(())
}
#[derive(Debug, Clone)]
struct Decision {
outcome: Outcome,
rule: Option<String>,
}
impl From<Outcome> for Decision {
fn from(outcome: Outcome) -> Self {
Self {
outcome,
rule: None,
}
}
}
impl Decision {
fn ruled(outcome: Outcome, rule: impl Into<String>) -> Self {
Self {
outcome,
rule: Some(rule.into()),
}
}
}
#[must_use]
pub fn guard(
input_json: &str,
default_root: &Path,
tenant: Option<&str>,
config_override: Option<&Path>,
) -> Outcome {
let started = Instant::now();
let decision = guard_inner(input_json, default_root, tenant, config_override);
let result = match &decision.outcome {
Outcome::Allow => "allow",
Outcome::Deny(_) => "deny",
Outcome::Notify(_) => "notify",
};
let input = HookInput::parse(input_json);
let file_path = input.as_ref().and_then(|i| i.tool_input.file_path.clone());
let ext = file_path
.as_ref()
.and_then(|f| {
Path::new(f)
.extension()
.and_then(OsStr::to_str)
.map(str::to_string)
})
.unwrap_or_default();
let root = input
.as_ref()
.map_or_else(|| default_root.to_path_buf(), |i| i.root(default_root));
let config = HankConfig::resolve(config_override, &root).ok();
let mode = config.as_ref().map_or("?", |c| c.policy.mode.as_str());
let mut fields: Vec<(&str, serde_json::Value)> = vec![
("result", result.into()),
("mode", mode.into()),
(
"duration_ms",
u64::try_from(started.elapsed().as_millis())
.unwrap_or(u64::MAX)
.into(),
),
("ext", ext.into()),
];
if let (Some(config), Some(file_path)) = (config.as_ref(), file_path.as_ref()) {
let file = PathBuf::from(file_path);
let rel = relative(&file, &root);
if let Some(recorded) = crate::audit::record_path(config.metrics.record_paths, &rel, &file)
{
fields.push(("path", recorded.into()));
}
}
if let Some(rule) = decision.rule {
fields.push(("rule", rule.into()));
}
crate::metrics::emit("guard", &fields);
decision.outcome
}
#[must_use]
fn guard_inner(
input_json: &str,
default_root: &Path,
tenant: Option<&str>,
config_override: Option<&Path>,
) -> Decision {
let started = Instant::now();
let Some(input) = HookInput::parse(input_json) else {
return Outcome::Allow.into();
};
let Some(file_path) = input.tool_input.file_path.clone() else {
return Outcome::Allow.into();
};
let root = input.root(default_root);
let config = match HankConfig::resolve(config_override, &root) {
Ok(config) => config,
Err(e) => return fail_open(&input, "config", &format!("unreadable config ({e})")).into(),
};
let file = PathBuf::from(&file_path);
let rel = relative(&file, &root);
if let Some(decision) = rule_check(&config, &input, &rel) {
return decision;
}
#[cfg(feature = "quipu")]
if let Some(decision) = governed_check(&config, &input, &root, &rel) {
return decision;
}
let (Some(tenant), Some(scope)) = (tenant, config.policy.scope_for(tenant)) else {
return Outcome::Allow.into();
};
let glob_errors = scope.glob_errors();
if !glob_errors.is_empty() {
let detail: Vec<String> = glob_errors
.iter()
.map(|(pattern, why)| format!("`{pattern}` ({why})"))
.collect();
return fail_open(
&input,
"globs",
&format!(
"scope for tenant `{tenant}` has malformed path globs: {}",
detail.join(", ")
),
)
.into();
}
if let Some(violation) = scope.check_path(&rel, tenant) {
return Decision::ruled(
decide(config.policy.mode, violation.message),
violation.rule,
);
}
let budget = Duration::from_millis(config.policy.deadline_ms)
.checked_sub(started.elapsed())
.unwrap_or_default();
if scope.max_impacted_symbols.is_none() && scope.max_impacted_files.is_none() {
return Outcome::Allow.into(); }
let (reply, daemon_absent) = blast_reply(&config, &root, &file, &rel, &input, budget);
let radius = if reply.measured {
BlastRadius {
symbols: reply.symbols,
files: reply.files,
}
} else {
let reason = reply
.reason
.clone()
.unwrap_or_else(|| "unmeasured".to_string());
eprintln!("hank: blast radius UNMEASURED for `{rel}`: {reason}");
let kind = format!("unmeasured-{}-{rel}", reply.kind);
if first_notice_for_session(input.session_id.as_deref(), &kind) {
return Decision::ruled(
Outcome::Notify(format!(
"hank: blast-radius rules were NOT EVALUATED for `{rel}` — \
{reason}. The edit is allowed (the guard fails open), but \
tenant `{tenant}`'s ceilings did not apply to it. Treat this \
file as UNGUARDED by blast radius, not as within limits."
)),
"unmeasured",
);
}
return Outcome::Allow.into();
};
let verdict = match scope.check_blast(radius, &rel, tenant) {
Some(violation) => Decision::ruled(
decide(config.policy.mode, violation.message),
violation.rule,
),
None => Outcome::Allow.into(),
};
if let Some(reason) = daemon_absent {
eprintln!("hank: resident guard daemon EXPECTED but unusable: {reason}");
if matches!(verdict.outcome, Outcome::Allow)
&& first_notice_for_session(input.session_id.as_deref(), "daemon-absent")
{
return Outcome::Notify(format!(
"hank: the resident guard daemon is DOWN ({reason}). This edit was guarded by a \
transient rebuild and ALLOWED — but the daemon a caller could kill to bypass \
the guard on every edit is not running. Restart it."
))
.into();
}
}
verdict
}
fn blast_reply(
config: &HankConfig,
root: &Path,
file: &Path,
rel: &str,
input: &HookInput,
budget: Duration,
) -> (crate::daemon::MeasureReply, Option<String>) {
let transient = || {
crate::daemon::MeasureReply::from_sizing(&measure_within(
root,
file,
rel,
input,
config.policy.max_hops,
budget,
))
};
if !config.serve.use_daemon {
return (transient(), None);
}
let anchors: Vec<String> = input
.replaced_texts()
.into_iter()
.map(str::to_string)
.collect();
match crate::daemon::client::fetch_measure(
&config.serve.bind_address,
config.serve.mcp_http_port,
&file.to_string_lossy(),
rel,
&anchors,
config.policy.max_hops,
budget,
) {
Ok(reply) => (reply, None),
Err(reason) => (transient(), Some(reason)),
}
}
#[path = "rule_planes.rs"]
mod rule_planes;
#[cfg(feature = "quipu")]
use rule_planes::governed_check;
use rule_planes::rule_check;
#[cfg(all(test, feature = "quipu"))]
use rule_planes::text_plane;
fn introduced_text(input: &HookInput) -> Option<String> {
if let Some(content) = &input.tool_input.content {
return Some(content.clone());
}
let mut parts: Vec<&str> = Vec::new();
if let Some(new) = input.tool_input.new_string.as_deref() {
parts.push(new);
}
for edit in &input.tool_input.edits {
if let Some(new) = edit.new_string.as_deref() {
parts.push(new);
}
}
if parts.is_empty() {
None
} else {
Some(parts.join("\n"))
}
}
fn decide(mode: Mode, message: String) -> Outcome {
match mode {
Mode::Enforce => Outcome::Deny(message),
Mode::Advise => Outcome::Notify(format!("hank (advise, not blocking): {message}")),
Mode::Off => Outcome::Allow,
}
}
fn fail_open(input: &HookInput, kind: &str, reason: &str) -> Outcome {
eprintln!("hank: policy guard failed open: {reason}");
crate::metrics::emit("fail_open", &[("fail_kind", kind.into())]);
if first_notice_for_session(input.session_id.as_deref(), kind) {
return Outcome::Notify(format!(
"hank: policy guard failed open ({reason}) — edits are UNGUARDED this session."
));
}
Outcome::Allow
}
#[cfg(test)]
#[path = "pre_edit_test.rs"]
mod pre_edit_test;