lean-ctx 3.12.2

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Context gateway coverage per configured host (G7): what lean-ctx can
//! actually see and stop, from `core::host_coverage`.

use crate::doctor::{BOLD, DIM, GREEN, Outcome, RST, YELLOW};
use lean_ctx::core::host_coverage::{self, CoverageLevel, HostCoverage};

/// Coverage of every host lean-ctx is configured for on this machine.
pub(crate) fn configured_host_coverage(home: &std::path::Path) -> Vec<HostCoverage> {
    let routed = crate::proxy_setup::egress_routed_hosts(home);
    let mut seen = std::collections::BTreeSet::new();
    let mut coverage = Vec::new();
    for target in lean_ctx::core::editor_registry::build_targets(home) {
        let key = target.agent_key;
        let hooks = lean_ctx_hooks::hooks::installed_hook_mode(&key, home);
        let registered = std::fs::read_to_string(&target.config_path)
            .is_ok_and(|content| content.contains("lean-ctx"));
        let is_routed = routed.contains(&key.as_str());
        if !(registered || hooks.is_some() || is_routed) || !seen.insert(key.clone()) {
            continue;
        }
        let installed = hooks.or(registered.then_some(lean_ctx_hooks::hooks::HookMode::Mcp));
        coverage.push(host_coverage::classify(&key, installed, is_routed));
    }
    coverage
}

/// Shadow-mode state as it is actually in effect on this machine: `shadow_mode`
/// in config is only a permission, the behaviour needs lean-ctx hooks installed
/// in a host. `deny` hosts run Replace (native Read/Grep/Glob denied); `steer`
/// hosts run Hybrid (hooks reroute native calls, nothing is denied).
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ShadowHosts {
    pub deny: Vec<String>,
    pub steer: Vec<String>,
}

pub(crate) fn shadow_hosts(home: &std::path::Path) -> ShadowHosts {
    let mut hosts = ShadowHosts::default();
    let mut seen = std::collections::BTreeSet::new();
    for target in lean_ctx::core::editor_registry::build_targets(home) {
        let key = target.agent_key;
        if !seen.insert(key.clone()) {
            continue;
        }
        match lean_ctx_hooks::hooks::installed_hook_mode(&key, home) {
            Some(lean_ctx_hooks::hooks::HookMode::Replace) => hosts.deny.push(key),
            Some(lean_ctx_hooks::hooks::HookMode::Hybrid) => hosts.steer.push(key),
            Some(lean_ctx_hooks::hooks::HookMode::Mcp) | None => {}
        }
    }
    hosts
}

/// Short state word plus plain-text detail for the shadow-mode line. Never
/// claims "active" unless at least one host really has lean-ctx hooks.
pub(crate) fn shadow_status(shadow_mode: bool, hosts: &ShadowHosts) -> (&'static str, String) {
    if !shadow_mode {
        return (
            "disabled",
            "(explicitly disabled via config; native tools are never denied)".to_string(),
        );
    }
    if !hosts.deny.is_empty() {
        let mut detail = format!(
            "(Read/Grep/Glob denied โ†’ ctx_* mandatory for: {})",
            hosts.deny.join(", ")
        );
        if !hosts.steer.is_empty() {
            detail.push_str(&format!("; steering only: {}", hosts.steer.join(", ")));
        }
        return ("active", detail);
    }
    if !hosts.steer.is_empty() {
        return (
            "steering",
            format!(
                "(hooks route native calls to ctx_*, nothing denied: {})",
                hosts.steer.join(", ")
            ),
        );
    }
    (
        "not active",
        "(no host has lean-ctx hooks yet โ€” run: lean-ctx setup)".to_string(),
    )
}

pub(crate) fn gateway_coverage_outcome() -> Outcome {
    let Some(home) = dirs::home_dir() else {
        return Outcome {
            ok: true,
            line: format!("{BOLD}Gateway coverage{RST}  {DIM}home directory not resolvable{RST}"),
        };
    };
    render(&configured_host_coverage(&home))
}

fn render(coverage: &[HostCoverage]) -> Outcome {
    if coverage.is_empty() {
        return Outcome {
            ok: true,
            line: format!("{BOLD}Gateway coverage{RST}  {DIM}no configured host{RST}"),
        };
    }
    let mut groups: std::collections::BTreeMap<std::cmp::Reverse<CoverageLevel>, Vec<&str>> =
        std::collections::BTreeMap::new();
    for host in coverage {
        groups
            .entry(std::cmp::Reverse(host.level))
            .or_default()
            .push(host.host.as_str());
    }
    let summary = groups
        .iter()
        .map(|(level, hosts)| format!("{}: {}", level.0.as_str(), hosts.join(", ")))
        .collect::<Vec<_>>()
        .join("  ยท  ");
    let fully = coverage
        .iter()
        .all(|host| host.level == CoverageLevel::Enforced);
    let (color, hint) = if fully {
        (GREEN, String::new())
    } else {
        (
            YELLOW,
            format!(
                "\n{DIM}         Only proxy-routed model traffic is checked end to end; other hosts' native tools bypass the gateway. Route supported hosts: lean-ctx proxy enable{RST}"
            ),
        )
    };
    Outcome {
        ok: true,
        line: format!("{BOLD}Gateway coverage{RST}  {color}{summary}{RST}{hint}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lean_ctx_hooks::hooks::HookMode;

    #[test]
    fn coverage_line_groups_hosts_by_level_and_hints_at_gaps() {
        let line = render(&[
            host_coverage::classify("codex", Some(HookMode::Replace), true),
            host_coverage::classify("claude", Some(HookMode::Replace), false),
            host_coverage::classify("zed", Some(HookMode::Mcp), false),
        ])
        .line;
        let enforced = line.find("enforced: codex").expect("enforced group");
        let partial = line.find("partial: claude").expect("partial group");
        assert!(enforced < partial, "strongest level first");
        assert!(line.contains("not_observable: zed"));
        assert!(line.contains("lean-ctx proxy enable"));
    }

    #[test]
    fn shadow_mode_is_never_active_without_a_hooked_host() {
        // Fresh install: shadow_mode defaults to true, but no host has hooks โ€”
        // doctor/status must not claim native tools are denied.
        let (state, detail) = shadow_status(true, &ShadowHosts::default());
        assert_eq!(state, "not active");
        assert!(!detail.contains("denied โ†’"), "{detail}");
        let hooked = ShadowHosts {
            deny: vec!["claude".into()],
            steer: Vec::new(),
        };
        let (state, detail) = shadow_status(true, &hooked);
        assert_eq!(state, "active");
        assert!(detail.contains("claude"), "{detail}");
    }
}