use super::{GateMode, cognitive_delta, format_gate_notice, worst_regression};
use crate::core::config::Config;
pub(crate) enum GateOutcome {
Allow(Option<String>),
Block(String),
}
pub(crate) fn evaluate(old: &str, new: &str, ext: &str) -> GateOutcome {
let cfg = Config::load();
evaluate_with(
old,
new,
ext,
GateMode::parse(&cfg.code_health.gate),
cfg.code_health.cognitive_threshold,
)
}
pub(crate) fn evaluate_with(
old: &str,
new: &str,
ext: &str,
mode: GateMode,
threshold: u32,
) -> GateOutcome {
if matches!(mode, GateMode::Off) {
return GateOutcome::Allow(None);
}
let deltas = cognitive_delta(old, new, ext);
let Some(worst) = worst_regression(&deltas, threshold) else {
return GateOutcome::Allow(None);
};
let notice = format_gate_notice(worst, threshold);
if matches!(mode, GateMode::Block) && worst.crosses_threshold(threshold) {
GateOutcome::Block(format!(
"{notice}\n(set [code_health] gate=\"warn\" to allow)"
))
} else {
GateOutcome::Allow(Some(notice))
}
}
#[cfg(all(test, feature = "tree-sitter"))]
mod tests {
use super::*;
const FLAT: &str = "fn f(a: bool) { if a {} }";
const DEEP: &str = "fn f(a: bool) { if a { if a { if a { if a { if a { if a {} } } } } } }";
#[test]
fn off_mode_allows_silently() {
match evaluate_with(FLAT, DEEP, "rs", GateMode::Off, 15) {
GateOutcome::Allow(None) => {}
_ => panic!("off mode must allow with no notice"),
}
}
#[test]
fn warn_mode_allows_with_notice() {
match evaluate_with(FLAT, DEEP, "rs", GateMode::Warn, 15) {
GateOutcome::Allow(Some(notice)) => assert!(notice.contains("[CODE HEALTH]")),
_ => panic!("warn mode must allow with a notice"),
}
}
#[test]
fn block_mode_blocks_threshold_crossing() {
match evaluate_with(FLAT, DEEP, "rs", GateMode::Block, 15) {
GateOutcome::Block(reason) => assert!(reason.contains("[CODE HEALTH]")),
GateOutcome::Allow(_) => panic!("block mode must block a clean→over edit"),
}
}
#[test]
fn no_regression_allows_silently() {
match evaluate_with(FLAT, FLAT, "rs", GateMode::Block, 15) {
GateOutcome::Allow(None) => {}
_ => panic!("unchanged complexity must allow silently"),
}
}
}