use super::*;
pub(super) fn rule_check(config: &HankConfig, input: &HookInput, rel: &str) -> Option<Decision> {
if config.policy.mode == Mode::Off {
return None;
}
let rules = &config.policy.rules;
if rules.is_empty() {
return None;
}
let errors = crate::rules::errors(rules);
if !errors.is_empty() {
let detail: Vec<String> = errors
.iter()
.map(|(name, why)| format!("`{name}` ({why})"))
.collect();
return Some(
fail_open(
input,
"rules",
&format!("policy rules do not compile: {}", detail.join(", ")),
)
.into(),
);
}
let ext = Path::new(rel).extension().and_then(OsStr::to_str)?;
let language = language_for_extension(ext)?;
let introduced = introduced_text(input)?;
let violations = crate::rules::evaluate(rules, &introduced, language, rel);
if violations.is_empty() {
return None;
}
let message = rule_verdict_message(&violations, Freshness::Fresh);
let fired = fired_rule_ids(violations.iter().map(|v| v.rule.as_str()));
Some(Decision::ruled(decide(config.policy.mode, message), fired))
}
fn fired_rule_ids<'a>(ids: impl Iterator<Item = &'a str>) -> String {
let mut seen: Vec<&str> = ids.collect();
seen.sort_unstable();
seen.dedup();
seen.join("+")
}
fn rule_verdict_message(
violations: &[crate::rules::RuleViolation],
freshness: Freshness,
) -> String {
let body = violations
.iter()
.map(|v| v.message.clone())
.collect::<Vec<_>>()
.join("\n");
let note = match freshness {
Freshness::Fresh => {
"verdict freshness: fresh (evaluated against the exact proposed \
edit and the loaded policy set)"
}
Freshness::Stale => {
"verdict freshness: STALE — the projected policy registry could not \
be refreshed from quipu, so this verdict may not reflect the latest governed policy"
}
Freshness::Recomputing => {
"verdict freshness: recomputing — the policy registry is \
mid-refresh"
}
};
format!("{body}\n({note})")
}
#[cfg(feature = "quipu")]
pub(super) fn governed_check(
config: &HankConfig,
input: &HookInput,
root: &Path,
rel: &str,
) -> Option<Decision> {
use crate::project::RepoExposure;
if config.policy.mode == Mode::Off || !config.quipu.enabled || config.quipu.endpoint.is_empty()
{
return None;
}
let introduced = introduced_text(input)?;
let mut registry = crate::project::ProjectionRegistry::new(&config.quipu.endpoint);
if let Err(e) = registry.refresh() {
return Some(
fail_open(
input,
"projection",
&format!("could not project governed policy from quipu: {e}"),
)
.into(),
);
}
let rules: Vec<crate::rules::Rule> =
registry.policies().iter().map(|p| p.rule.clone()).collect();
let mut errors = crate::rules::errors(&rules);
errors.extend(crate::textrules::errors(registry.text_rules()));
if !errors.is_empty() {
let detail: Vec<String> = errors
.iter()
.map(|(name, why)| format!("`{name}` ({why})"))
.collect();
return Some(
fail_open(
input,
"projection-rules",
&format!("projected policies do not compile: {}", detail.join(", ")),
)
.into(),
);
}
let mut messages: Vec<String> = Vec::new();
let mut any_blocking = false;
let mut structural_count = 0usize;
let target = target_file(input, root);
let target_root = target.as_deref().and_then(crate::git::repo_root_containing);
let target_rel = match (&target, &target_root) {
(Some(file), Some(tr)) => relative(file, tr),
_ => rel.to_string(),
};
let text_violations =
crate::textrules::evaluate(registry.text_rules(), &introduced, &target_rel);
let mut exposure_label = "n/a";
let mut target_repo: Option<String> = None;
if !text_violations.is_empty() {
let repo = target_root
.as_deref()
.and_then(crate::git::origin_repo_name);
let exposure = match (&target_root, &repo) {
(Some(_), Some(repo)) => {
crate::project::fetch_repo_exposure(&config.quipu.endpoint, repo)
}
(Some(tr), None) => RepoExposure::Unknown(format!(
"the tree containing this file ({}) has no `origin` remote, so \
its exposure cannot be resolved",
tr.display()
)),
(None, _) => RepoExposure::Unknown(
"this file is not inside a git work tree, so its exposure cannot \
be resolved"
.into(),
),
};
exposure_label = match exposure {
RepoExposure::Public => "public",
RepoExposure::Internal => "internal",
RepoExposure::Unknown(_) => "unknown",
};
target_repo = repo;
let (text_messages, text_blocks) = text_plane(&text_violations, &exposure);
messages.extend(text_messages);
any_blocking |= text_blocks;
}
if let Some(language) = Path::new(rel)
.extension()
.and_then(OsStr::to_str)
.and_then(language_for_extension)
{
let violations =
crate::project::evaluate_projected(registry.policies(), &introduced, language, rel);
structural_count = violations.len();
for v in &violations {
if v.blocking {
any_blocking = true;
}
messages.push(v.message.clone());
}
}
if messages.is_empty() {
return None;
}
let rule_names: Vec<serde_json::Value> = text_violations
.iter()
.map(|v| serde_json::Value::from(v.rule.clone()))
.collect();
crate::metrics::emit(
"governed",
&[
("rules", rule_names.into()),
(
"mode",
match config.policy.mode {
Mode::Off => "off",
Mode::Advise => "advise",
Mode::Enforce => "enforce",
}
.into(),
),
("structural", (structural_count as u64).into()),
("blocking", any_blocking.into()),
("exposure", exposure_label.into()),
(
"repo",
target_repo
.unwrap_or_else(|| "unresolved".to_string())
.into(),
),
],
);
let blocks = config.policy.mode == Mode::Enforce && any_blocking;
let message = rule_verdict_message_from(&messages.join("\n"), registry.freshness());
let mut fired: Vec<&str> = text_violations.iter().map(|v| v.rule.as_str()).collect();
if structural_count > 0 {
fired.push("governed-structural");
}
let outcome = if blocks {
Outcome::Deny(message)
} else {
Outcome::Notify(format!("hank (governed, not blocking): {message}"))
};
Some(Decision::ruled(outcome, fired_rule_ids(fired.into_iter())))
}
#[cfg(feature = "quipu")]
fn target_file(input: &HookInput, root: &Path) -> Option<PathBuf> {
let raw = input.tool_input.file_path.as_deref()?;
let path = Path::new(raw);
Some(if path.is_absolute() {
path.to_path_buf()
} else {
root.join(path)
})
}
#[cfg(feature = "quipu")]
pub(super) fn text_plane(
violations: &[crate::textrules::TextViolation],
exposure: &crate::project::RepoExposure,
) -> (Vec<String>, bool) {
use crate::project::RepoExposure;
use crate::textrules::TextTier;
let mut messages: Vec<String> = Vec::new();
let mut any_blocking = false;
for v in violations {
if v.tier == TextTier::Block && *exposure == RepoExposure::Public {
any_blocking = true;
}
messages.push(v.message.clone());
}
match exposure {
RepoExposure::Public => messages.push(
"[exposure: this repo has a PUBLIC remote (per the graph), so \
block-tier rules block]"
.to_string(),
),
RepoExposure::Internal => messages.push(
"[exposure: downgraded to a warning — the graph knows this repo and \
it has no public remote, so the token leaks nowhere; the same edit \
would BLOCK in a public repo]"
.to_string(),
),
RepoExposure::Unknown(reason) => messages.push(format!(
"[exposure: warning, NOT blocking — the repo's exposure is unknown \
({reason}), and a governed rule never blocks on a guess. Add this \
repo's `repo_<name>` entity and remote facts to quipu to pin it.]"
)),
}
(messages, any_blocking)
}
#[cfg(feature = "quipu")]
fn rule_verdict_message_from(body: &str, freshness: Freshness) -> String {
let note = match freshness {
Freshness::Fresh => "verdict freshness: fresh (governed policy projected from quipu)",
Freshness::Stale => {
"verdict freshness: STALE — the projected policy registry could not \
be refreshed from quipu, so this verdict may not reflect the latest governed policy"
}
Freshness::Recomputing => {
"verdict freshness: recomputing — the policy registry is \
mid-refresh"
}
};
format!("{body}\n({note})")
}