use super::*;
use crate::types::Tier;
impl Cli {
pub(super) fn status(&self) -> anyhow::Result<()> {
let root = std::env::current_dir()?;
let config = self.load_config(&root)?;
let tenant = self.tenant.as_deref().unwrap_or("(single-tenant)");
let base_commit = crate::git::resolve_commit(&root, &config.base_ref);
let policy = config.policy.status_for(self.tenant.as_deref());
let rule_set = measure_rule_set(&config);
if self.json {
let out = serde_json::json!({
"base_ref": config.base_ref,
"base_commit": base_commit,
"tenant": tenant,
"tiers": Tier::served(),
"quipu": { "enabled": config.quipu.enabled, "branch_model": config.quipu.branch_model },
"policy": policy,
"metrics": { "record_paths": config.metrics.record_paths },
"rule_set": {
"local": rule_set.local,
"graph_enabled": rule_set.graph_enabled,
"projected": rule_set.projected,
"structural": rule_set.structural,
"text": rule_set.text,
"error": rule_set.error,
"state": rule_set.state().as_str(),
"digest": rule_set.digest,
"attempts": rule_set.attempts,
"verification": "unsigned",
},
"signed_rule_set": { "loaded": false, "state": "never-loaded",
"note": "rules above are an unsigned live projection; the resident signed cache is not yet available" },
});
println!("{}", serde_json::to_string_pretty(&out)?);
} else {
let commit = base_commit.as_deref().map_or_else(
|| "(unresolved — not a git repo or ref absent)".to_string(),
|c| c[..c.len().min(12)].to_string(),
);
println!("{}", "hank status".bold());
println!(" base ref : {}", config.base_ref);
println!(" base commit : {commit}");
println!(" tenant : {tenant}");
println!(" tiers : {}", Tier::served().join(", "));
println!(
" quipu : enabled={} branch_model={}",
config.quipu.enabled, config.quipu.branch_model
);
println!(
" audit : record_paths={}",
match config.metrics.record_paths {
crate::audit::PathRecording::Off => "off (guard records carry no path)",
crate::audit::PathRecording::Relative => "relative",
crate::audit::PathRecording::Absolute => "absolute",
}
);
print_policy_status(&policy);
print_rule_set_status(&config, &rule_set);
}
if rule_set.state() == RuleSetState::Degraded {
std::process::exit(EXIT_RULE_SET_DEGRADED);
}
Ok(())
}
}
pub(super) const EXIT_RULE_SET_DEGRADED: i32 = 3;
fn print_policy_status(policy: &crate::policy::PolicyStatus) {
let scope = match &policy.scope {
Some(s) => {
let ceiling = |c: Option<usize>| c.map_or_else(|| "—".to_string(), |n| n.to_string());
format!(
"configured (allow={} deny={} sym≤{} files≤{})",
s.allow_paths,
s.deny_paths,
ceiling(s.max_impacted_symbols),
ceiling(s.max_impacted_files),
)
}
None => "none for this tenant".to_string(),
};
println!(" policy : mode={} scope={scope}", policy.mode);
if policy.enforcing_without_scope {
println!(
" {} enforce mode but NO scope for this tenant — nothing is enforced",
"⚠".yellow().bold()
);
}
}
pub(super) struct RuleSetStatus {
pub local: usize,
pub projected: Option<usize>,
pub structural: usize,
pub text: usize,
pub error: Option<String>,
pub graph_enabled: bool,
pub digest: Option<String>,
pub attempts: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RuleSetState {
Off,
Loaded,
Empty,
Degraded,
}
impl RuleSetState {
pub(super) fn as_str(self) -> &'static str {
match self {
RuleSetState::Off => "off",
RuleSetState::Loaded => "loaded",
RuleSetState::Empty => "empty",
RuleSetState::Degraded => "degraded",
}
}
}
impl RuleSetStatus {
pub(super) fn state(&self) -> RuleSetState {
if !self.graph_enabled {
return RuleSetState::Off;
}
match (self.projected, &self.error) {
(_, Some(_)) => RuleSetState::Degraded,
(Some(0), None) => RuleSetState::Empty,
(Some(_), None) => RuleSetState::Loaded,
(None, None) => RuleSetState::Degraded,
}
}
}
pub(super) fn measure_rule_set(config: &HankConfig) -> RuleSetStatus {
let local = config.policy.rules.len();
#[allow(unused_mut)]
let mut st = RuleSetStatus {
local,
projected: None,
structural: 0,
text: 0,
error: None,
graph_enabled: false,
digest: None,
attempts: 0,
};
#[cfg(feature = "quipu")]
{
if !config.quipu.enabled || config.quipu.endpoint.is_empty() {
return st;
}
st.graph_enabled = true;
for attempt in 1..=PROJECTION_ATTEMPTS {
st.attempts = attempt;
let mut registry = crate::project::ProjectionRegistry::new(&config.quipu.endpoint);
match registry.refresh() {
Ok(()) => {
st.text = registry.text_rules().len();
st.structural = registry.policies().len();
st.projected = Some(st.text + st.structural);
st.digest = Some(rule_set_digest(®istry));
st.error = None;
break;
}
Err(e) => {
st.error = Some(e.to_string());
if attempt < PROJECTION_ATTEMPTS {
std::thread::sleep(PROJECTION_BACKOFF);
}
}
}
}
}
st
}
#[cfg(feature = "quipu")]
const PROJECTION_ATTEMPTS: usize = 3;
#[cfg(feature = "quipu")]
const PROJECTION_BACKOFF: std::time::Duration = std::time::Duration::from_millis(250);
#[cfg(feature = "quipu")]
fn rule_set_digest(registry: &crate::project::ProjectionRegistry) -> String {
use sha2::{Digest, Sha256};
let mut ids: Vec<String> = registry
.text_rules()
.iter()
.map(|r| {
format!(
"text\u{1f}{}\u{1f}{}\u{1f}{:?}\u{1f}{}",
r.name,
r.pattern,
r.tier,
r.exempt_path_regex.as_deref().unwrap_or("")
)
})
.collect();
ids.extend(registry.policies().iter().map(|p| {
format!(
"struct\u{1f}{}\u{1f}{}\u{1f}{}",
p.rule.name, p.rule.pattern, p.effect
)
}));
ids.sort();
format!("sha256:{}", hex::encode(Sha256::digest(ids.join("\u{1e}"))))
}
fn print_rule_set_status(config: &HankConfig, st: &RuleSetStatus) {
let local = st.local;
{
if !st.graph_enabled {
println!(
" rule set : {local} local structural rule(s); graph plane OFF \
(quipu disabled or not built in — nothing is projected)"
);
println!(" rule provenance: local config only");
return;
}
match (st.projected, &st.error) {
(_, Some(e)) => {
println!(
" rule set : {} — could not project from {} after {} attempt(s) ({e}); \
{local} local rule(s) only",
"COULD NOT TELL".red().bold(),
config.quipu.endpoint,
st.attempts,
);
println!(
" {} the guard is FAILING OPEN for governed rules until this clears \
(exit {EXIT_RULE_SET_DEGRADED})",
"⚠".red().bold()
);
}
(Some(0), None) => {
println!(
" rule set : {}",
format!("0 projected from quipu + {local} local").yellow()
);
println!(
" {} the graph projected NO rules — the plane is armed and empty",
"⚠".yellow().bold()
);
}
(Some(total), None) => {
println!(
" rule set : {}",
format!(
"{total} projected from quipu ({} structural, {} text) + {local} local",
st.structural, st.text
)
.green()
);
if let Some(d) = &st.digest {
println!(" rule digest : {} (unsigned)", &d[..d.len().min(23)]);
}
}
(None, None) => {}
}
}
println!(
" rule provenance: unsigned live projection — the signed resident cache \
does not exist yet, so rules are trusted on transport alone"
);
}