use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
const DEFAULT_MAX_HOPS: u32 = 5;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
#[default]
Off,
Advise,
Enforce,
}
impl Mode {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Mode::Off => "off",
Mode::Advise => "advise",
Mode::Enforce => "enforce",
}
}
}
impl std::fmt::Display for Mode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PolicyConfig {
pub mode: Mode,
pub deadline_ms: u64,
pub notify_on_fail_open: bool,
pub max_hops: u32,
pub scopes: BTreeMap<String, Scope>,
pub rules: Vec<crate::rules::Rule>,
}
impl Default for PolicyConfig {
fn default() -> Self {
Self {
mode: Mode::Off,
deadline_ms: 100,
notify_on_fail_open: true,
max_hops: DEFAULT_MAX_HOPS,
scopes: BTreeMap::new(),
rules: Vec::new(),
}
}
}
impl PolicyConfig {
#[must_use]
pub fn scope_for(&self, tenant: Option<&str>) -> Option<&Scope> {
if self.mode == Mode::Off {
return None;
}
self.scopes.get(tenant?)
}
#[must_use]
pub fn status_for(&self, tenant: Option<&str>) -> PolicyStatus {
let scope = tenant.and_then(|t| self.scopes.get(t));
PolicyStatus {
mode: self.mode,
scope_configured: scope.is_some(),
enforcing_without_scope: self.mode == Mode::Enforce && scope.is_none(),
scope: scope.map(ScopeSummary::of),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PolicyStatus {
pub mode: Mode,
pub scope_configured: bool,
pub scope: Option<ScopeSummary>,
pub enforcing_without_scope: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ScopeSummary {
pub allow_paths: usize,
pub deny_paths: usize,
pub max_impacted_symbols: Option<usize>,
pub max_impacted_files: Option<usize>,
}
impl ScopeSummary {
fn of(scope: &Scope) -> Self {
Self {
allow_paths: scope.allow_paths.len(),
deny_paths: scope.deny_paths.len(),
max_impacted_symbols: scope.max_impacted_symbols,
max_impacted_files: scope.max_impacted_files,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Scope {
pub allow_paths: Vec<String>,
pub deny_paths: Vec<String>,
pub max_impacted_symbols: Option<usize>,
pub max_impacted_files: Option<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViolationKind {
PathOutOfScope,
BlastRadiusExceeded,
}
#[derive(Debug, Clone)]
pub struct Violation {
pub kind: ViolationKind,
pub message: String,
pub rule: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BlastRadius {
pub symbols: usize,
pub files: usize,
}
impl Scope {
#[must_use]
pub fn check_path(&self, rel: &str, tenant: &str) -> Option<Violation> {
if let Some(pattern) = self.deny_paths.iter().find(|p| glob_matches(p, rel)) {
return Some(Violation {
kind: ViolationKind::PathOutOfScope,
message: format!(
"hank: `{rel}` is explicitly denied to tenant `{tenant}` (matches deny_paths \
pattern `{pattern}`). This path is outside your capability scope — do not \
retry it; if the change genuinely belongs there, ask for a wider scope."
),
rule: format!("deny_paths:{pattern}"),
});
}
if self.allow_paths.is_empty() || self.allow_paths.iter().any(|p| glob_matches(p, rel)) {
return None;
}
Some(Violation {
kind: ViolationKind::PathOutOfScope,
message: format!(
"hank: `{rel}` is outside the writable capability scope of tenant `{tenant}` \
(allowed: {}). Make the change inside your scope, or ask for a wider one.",
self.allow_paths.join(", ")
),
rule: "allow_paths".to_string(),
})
}
#[must_use]
pub fn check_blast(&self, radius: BlastRadius, rel: &str, tenant: &str) -> Option<Violation> {
let symbols_over = self
.max_impacted_symbols
.is_some_and(|max| radius.symbols > max);
let files_over = self
.max_impacted_files
.is_some_and(|max| radius.files > max);
if !symbols_over && !files_over {
return None;
}
let mut exceeded = Vec::new();
let mut fired = Vec::new();
if let (true, Some(max)) = (symbols_over, self.max_impacted_symbols) {
exceeded.push(format!("{} symbols (ceiling {max})", radius.symbols));
fired.push("max_impacted_symbols");
}
if let (true, Some(max)) = (files_over, self.max_impacted_files) {
exceeded.push(format!("{} files (ceiling {max})", radius.files));
fired.push("max_impacted_files");
}
Some(Violation {
rule: fired.join("+"),
kind: ViolationKind::BlastRadiusExceeded,
message: format!(
"hank: editing `{rel}` reaches {} — beyond the blast radius allowed for tenant \
`{tenant}`. Split this into a narrower change that touches fewer callers, or ask \
for a wider capability scope. (tree-sitter tier: the reach is an approximation.)",
exceeded.join(" and ")
),
})
}
#[must_use]
pub fn glob_errors(&self) -> Vec<(String, String)> {
self.allow_paths
.iter()
.chain(self.deny_paths.iter())
.filter_map(|pattern| {
glob::Pattern::new(pattern)
.err()
.map(|e| (pattern.clone(), e.to_string()))
})
.collect()
}
}
fn glob_matches(pattern: &str, rel: &str) -> bool {
let direct = glob::Pattern::new(pattern).is_ok_and(|p| p.matches(rel));
if direct {
return true;
}
match pattern.strip_suffix("/**") {
Some(prefix) => glob::Pattern::new(&format!("{prefix}/*")).is_ok_and(|p| p.matches(rel)),
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scope() -> Scope {
Scope {
allow_paths: vec!["src/**".to_string(), "tests/**".to_string()],
deny_paths: vec!["src/config.rs".to_string()],
max_impacted_symbols: Some(5),
max_impacted_files: Some(2),
}
}
#[test]
fn allows_a_path_inside_scope() {
assert!(scope().check_path("src/graph/blast.rs", "t").is_none());
assert!(scope().check_path("src/policy.rs", "t").is_none());
}
#[test]
fn denies_a_path_outside_scope() {
let violation = scope()
.check_path("docs/hank-spec.md", "polecat-3")
.unwrap();
assert_eq!(violation.kind, ViolationKind::PathOutOfScope);
assert!(violation.message.contains("docs/hank-spec.md"));
assert!(violation.message.contains("polecat-3"));
assert!(violation.message.contains("src/**"));
}
#[test]
fn deny_paths_beat_allow_paths() {
let violation = scope().check_path("src/config.rs", "t").unwrap();
assert_eq!(violation.kind, ViolationKind::PathOutOfScope);
assert!(violation.message.contains("deny_paths"));
}
#[test]
fn empty_allow_paths_permits_anything() {
let open = Scope {
deny_paths: vec!["secrets/**".to_string()],
..Scope::default()
};
assert!(open.check_path("anywhere/at/all.rs", "t").is_none());
assert!(open.check_path("secrets/key.rs", "t").is_some());
}
#[test]
fn blast_radius_within_ceilings_is_allowed() {
let radius = BlastRadius {
symbols: 5,
files: 2,
};
assert!(scope().check_blast(radius, "src/a.rs", "t").is_none());
}
#[test]
fn blast_radius_over_ceiling_is_denied_with_numbers() {
let radius = BlastRadius {
symbols: 47,
files: 12,
};
let violation = scope()
.check_blast(radius, "src/a.rs", "polecat-3")
.unwrap();
assert_eq!(violation.kind, ViolationKind::BlastRadiusExceeded);
assert!(violation.message.contains("47 symbols (ceiling 5)"));
assert!(violation.message.contains("12 files (ceiling 2)"));
assert!(violation.message.contains("polecat-3"));
}
#[test]
fn absent_ceilings_never_trip() {
let unbounded = Scope::default();
let radius = BlastRadius {
symbols: 9999,
files: 9999,
};
assert!(unbounded.check_blast(radius, "src/a.rs", "t").is_none());
}
#[test]
fn mode_off_yields_no_scope_even_when_one_is_configured() {
let mut config = PolicyConfig {
mode: Mode::Off,
..PolicyConfig::default()
};
config.scopes.insert("t".to_string(), scope());
assert!(config.scope_for(Some("t")).is_none());
config.mode = Mode::Enforce;
assert!(config.scope_for(Some("t")).is_some());
assert!(config.scope_for(Some("other")).is_none());
assert!(config.scope_for(None).is_none());
}
#[test]
fn malformed_globs_are_reported_and_never_match() {
let broken = Scope {
allow_paths: vec!["src/[".to_string()],
..Scope::default()
};
assert_eq!(broken.glob_errors().len(), 1);
assert!(broken.check_path("src/a.rs", "t").is_some());
}
#[test]
fn mode_parses_from_toml_and_rejects_typos() {
#[derive(Deserialize)]
struct Wrapper {
mode: Mode,
}
let ok: Wrapper = toml::from_str("mode = \"enforce\"").unwrap();
assert_eq!(ok.mode, Mode::Enforce);
assert!(toml::from_str::<Wrapper>("mode = \"enfroce\"").is_err());
}
fn config_with_scope(mode: Mode) -> PolicyConfig {
let mut config = PolicyConfig {
mode,
..PolicyConfig::default()
};
config.scopes.insert("weaver".to_string(), scope());
config
}
#[test]
fn status_reports_a_configured_scope_with_its_ceilings() {
let status = config_with_scope(Mode::Enforce).status_for(Some("weaver"));
assert_eq!(status.mode, Mode::Enforce);
assert!(status.scope_configured);
assert!(!status.enforcing_without_scope);
let summary = status.scope.unwrap();
assert_eq!(summary.allow_paths, 2);
assert_eq!(summary.deny_paths, 1);
assert_eq!(summary.max_impacted_files, Some(2));
}
#[test]
fn status_flags_enforce_with_no_scope_for_the_tenant() {
let status = config_with_scope(Mode::Enforce).status_for(Some("someone-else"));
assert!(!status.scope_configured);
assert!(
status.enforcing_without_scope,
"enforce + no tenant scope must be flagged, not read as healthy"
);
assert!(status.scope.is_none());
}
#[test]
fn status_shows_a_scope_even_when_mode_is_off() {
let status = config_with_scope(Mode::Off).status_for(Some("weaver"));
assert_eq!(status.mode, Mode::Off);
assert!(status.scope_configured);
assert!(!status.enforcing_without_scope);
}
#[test]
fn status_without_a_tenant_configures_no_scope() {
let status = config_with_scope(Mode::Enforce).status_for(None);
assert!(!status.scope_configured);
assert!(status.enforcing_without_scope);
}
}