lean-ctx-cloud 3.12.12

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! K10, K12 and K13: counts the stores do not keep, recorded where they
//! happen while engine metrics are on (the same switch as `super::secrets`).
//!
//! - K10 `refetch[]`: per filter (a read mode, `shell_output`,
//!   `search_output`), outputs served truncated — a compressed `ctx_read`
//!   view, a firewalled tool output with a `ctx_expand` pointer — and the
//!   ones the agent fetched back in full (the compressed read's full
//!   re-read, a `ctx_expand` of the archive);
//! - K12 `policy_blocks[]`: per rule, refusals in force (`blocked`) and the
//!   ones the same rule in monitor/warn mode only evaluated (`would_block`):
//!   the shell allowlist (`gateway.security_violation`), the path jail
//!   (`gateway.path_jail`), secret-like paths and secret filters
//!   (`security.block_secrets`), destination and egress admission
//!   (`gateway.destination`, `gateway.egress`);
//! - K13 `unregulated[]`: what no *enforcing* rule covers at decision time
//!   (monitor mode does not regulate): programs a shell command ran
//!   (`shell_security = off`, or no allowlist), by known-program name; tool
//!   calls of a host family without an intercepting hook (anything but
//!   replace mode with the native-tool deny hook), by host family; calls
//!   the MCP gateway relayed to a downstream server, named only when the
//!   workspace's signed Cloud policy names that server, else `other`.
//!
//! The engine names these where they happen
//! ([`lean_ctx::core::cloud_signals`]); this module is the recorder the
//! connector registers there ([`crate::register_hooks`]), plus
//! the counts only the connector can name (host families, relayed MCP
//! servers).
//!
//! Each record is `{ts, kind, name, project}` in `signals.jsonl` (0600,
//! bounded); `name` is a closed wire name (`FilterName`, `RuleId`,
//! `UnregulatedName`), never a path, a command line or a mode argument.
//! The collector reads the log per hour and prunes it.

use std::io::Write as _;
use std::path::Path;

#[cfg(test)]
use lean_ctx_protocol::cloud::metrics_v2::OTHER;
use lean_ctx_protocol::cloud::metrics_v2::{
    FilterName, HOST_FAMILIES, KNOWN_PROGRAMS, RuleId, UnregulatedKind, UnregulatedName,
    host_family,
};
use serde::{Deserialize, Serialize};

use super::buffer::dir_in;
use crate::state::write_private;
pub(crate) use lean_ctx::core::cloud_signals::SignalKind as Kind;
#[cfg(test)]
use lean_ctx::core::cloud_signals::{
    admission_rules, program_name, read_mode_filter, secrets_rule, shell_rule,
};
pub use lean_ctx::core::cloud_signals::{
    blocked, output_filter, path_jail_rule, recording, refetched, truncated,
};

pub(crate) const SIGNALS_FILE: &str = "signals.jsonl";
/// The log stops growing here; the collector prunes what it has read.
const MAX_SIGNALS_BYTES: u64 = 4 * 1024 * 1024;

/// One record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Signal {
    pub(crate) ts: String,
    pub(crate) kind: Kind,
    pub(crate) name: String,
    #[serde(default)]
    pub(crate) project: Option<String>,
}

impl Signal {
    /// The name as the wire type of its kind, `None` when it is not one
    /// (a record is never trusted for more than it can be).
    pub(crate) fn filter(&self) -> Option<FilterName> {
        matches!(self.kind, Kind::Truncated | Kind::Refetched)
            .then(|| FilterName::new(&self.name))
            .flatten()
    }

    pub(crate) fn rule(&self) -> Option<RuleId> {
        matches!(self.kind, Kind::Blocked | Kind::WouldBlock)
            .then(|| RuleId::new(&self.name))
            .flatten()
    }

    /// K13 of any kind: the wire kind and a name that kind allows.
    pub(crate) fn unregulated(&self) -> Option<(UnregulatedKind, UnregulatedName)> {
        let name = self.name.as_str();
        let (kind, fits) = match self.kind {
            Kind::UnregulatedProgram => (UnregulatedKind::Program, KNOWN_PROGRAMS.contains(&name)),
            Kind::UnregulatedHost => (UnregulatedKind::Host, HOST_FAMILIES.contains(&name)),
            // The shape rule of [`UnregulatedName`] (no path, no token).
            Kind::UnregulatedMcpServer => (UnregulatedKind::McpServer, true),
            _ => return None,
        };
        fits.then(|| UnregulatedName::new(name))
            .flatten()
            .map(|n| (kind, n))
    }
}

/// Whether this recorder keeps anything now (engine metrics on).
pub(crate) fn sink_open() -> bool {
    super::secrets::sink().is_some()
}

/// Append one record of `kind` per name: the registered recorder.
pub(crate) fn record(kind: Kind, names: &[&str]) {
    if names.is_empty() {
        return;
    }
    let Some(dir) = super::secrets::sink() else {
        return;
    };
    let path = dir.join(SIGNALS_FILE);
    if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_SIGNALS_BYTES) {
        return;
    }
    let project = lean_ctx::core::savings_ledger::project_scope::current_project_key();
    let ts =
        lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
    let mut lines = String::new();
    for name in names {
        let signal = Signal {
            ts: ts.clone(),
            kind,
            name: (*name).to_string(),
            project: project.clone(),
        };
        if let Ok(line) = serde_json::to_string(&signal) {
            lines.push_str(&line);
            lines.push('\n');
        }
    }
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path);
    if let Ok(mut file) = file {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = file.set_permissions(std::fs::Permissions::from_mode(0o600));
        }
        let _ = file.write_all(lines.as_bytes());
    }
}

/// Whether a host family's tool calls are regulated: the native-tool deny
/// hook is enforcing (replace mode) for a host that supports it. Hybrid,
/// MCP-only and off leave native tools outside the gateway.
pub(crate) fn host_regulated(family: &str) -> bool {
    lean_ctx::core::host_coverage::tool_integration(family)
        == lean_ctx::core::host_coverage::ToolIntegration::DenyNativeTools
        && lean_ctx::core::hook_mode::replace_mode_chosen()
}

/// K13: one tool call of the host `client` (its MCP client id), counted by
/// host family when no enforcing rule regulates that host.
pub fn host_call(client: &str) {
    if !sink_open() {
        return;
    }
    let family = host_family(client);
    if !host_regulated(family) {
        record(Kind::UnregulatedHost, &[family]);
    }
}

/// The wire name of a downstream MCP server: its id when the workspace's
/// signed policy names it (`server` or `server::tool` in its allowed or
/// denied tools), else `other`. Never a hash of the id.
pub(crate) fn mcp_server_name(server: &str, policy_names: &[String]) -> UnregulatedName {
    let named = policy_names.iter().any(|entry| {
        entry == server
            || entry
                .strip_prefix(server)
                .is_some_and(|rest| rest.starts_with("::"))
    });
    let probe = Signal {
        ts: String::new(),
        kind: Kind::UnregulatedMcpServer,
        name: server.to_string(),
        project: None,
    };
    named
        .then(|| probe.unregulated().map(|(_, n)| n))
        .flatten()
        .unwrap_or_else(UnregulatedName::other)
}

/// Tool entries of the installed, verified Cloud policy (default and every
/// vault), the only source that may name an MCP server on the wire.
fn signed_policy_tool_entries() -> Vec<String> {
    use crate::effective_floor as floor;
    let Some(dir) = floor::floor_dir() else {
        return Vec::new();
    };
    let Ok((Some(text), required)) = floor::read(&dir) else {
        return Vec::new();
    };
    let Ok(Some(installed)) = floor::check(Some(&text), required.as_deref()) else {
        return Vec::new();
    };
    std::iter::once(&installed.policy.effective)
        .chain(installed.policy.vaults.iter().map(|v| &v.effective))
        .flat_map(|p| {
            p.context
                .allowed_tools
                .iter()
                .flatten()
                .chain(p.context.denied_tools.iter().flatten())
                .cloned()
                .collect::<Vec<_>>()
        })
        .collect()
}

/// K13: one call the MCP gateway relays to `handle` (`server::tool`). The
/// engine enforces tool rules on its own tools only, so no rule regulates a
/// downstream server's tools: every relayed call is unregulated.
pub fn mcp_relay_call(handle: &str) {
    if !sink_open() {
        return;
    }
    let server = handle.split_once("::").map_or(handle, |(s, _)| s);
    let name = mcp_server_name(server, &signed_policy_tool_entries());
    record(Kind::UnregulatedMcpServer, &[name.as_str()]);
}

/// Every record under `cloud_data`.
pub fn signals(cloud_data: &Path) -> Vec<(lean_ctx_time::UtcDateTime, Signal)> {
    let Ok(text) = std::fs::read_to_string(dir_in(cloud_data).join(SIGNALS_FILE)) else {
        return Vec::new();
    };
    text.lines()
        .filter_map(|line| serde_json::from_str::<Signal>(line).ok())
        .filter_map(|signal| {
            let at = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&signal.ts)
                .ok()?
                .to_utc();
            Some((at, signal))
        })
        .collect()
}

/// Drop records older than `before` (closed hours are built once).
pub(crate) fn prune(cloud_data: &Path, before: lean_ctx_time::UtcDateTime) {
    let path = dir_in(cloud_data).join(SIGNALS_FILE);
    if !path.is_file() {
        return;
    }
    let kept: String = signals(cloud_data)
        .into_iter()
        .filter(|(at, _)| *at >= before)
        .filter_map(|(_, signal)| serde_json::to_string(&signal).ok())
        .map(|line| line + "\n")
        .collect();
    if kept.is_empty() {
        let _ = std::fs::remove_file(path);
    } else {
        let _ = write_private(&dir_in(cloud_data), SIGNALS_FILE, kept.as_bytes());
    }
}

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

    #[test]
    fn names_are_closed_wire_names_or_other() {
        assert_eq!(read_mode_filter("lines:10-20").as_str(), "lines");
        assert_eq!(read_mode_filter("signatures").as_str(), "signatures");
        assert_eq!(read_mode_filter("/etc/passwd").as_str(), OTHER);
        assert_eq!(output_filter("ctx_shell").as_str(), "shell_output");
        assert_eq!(output_filter("ctx_search").as_str(), "search_output");
        assert_eq!(output_filter("ctx_tree").as_str(), OTHER);
        assert_eq!(program_name("/usr/bin/git").as_str(), "git");
        assert_eq!(program_name("terraform").as_str(), "terraform");
        for content in ["./deploy-acme.sh", "acme-internal-cli", "rm -rf /", "Git"] {
            assert_eq!(program_name(content).as_str(), OTHER, "{content}");
        }
        assert_eq!(shell_rule().as_str(), "gateway.security_violation");
        assert_eq!(path_jail_rule().as_str(), "gateway.path_jail");
        assert_eq!(secrets_rule().as_str(), "security.block_secrets");
    }

    #[test]
    fn admission_reasons_map_to_closed_rules() {
        let rules = |codes: &[&str]| -> Vec<String> {
            admission_rules(codes.iter().copied())
                .iter()
                .map(|r| r.as_str().to_string())
                .collect()
        };
        assert_eq!(rules(&["secret.blocked"]), ["security.block_secrets"]);
        assert_eq!(
            rules(&[
                "destination.remote_restricted",
                "destination.constraint_unsatisfied"
            ]),
            ["gateway.destination"]
        );
        assert_eq!(rules(&["egress.restricted_content"]), ["gateway.egress"]);
        assert!(rules(&["destination.constraint_satisfied", "secret.redacted"]).is_empty());
    }

    #[test]
    fn an_mcp_server_is_named_only_by_the_signed_policy() {
        let policy = vec!["github::create_issue".to_string(), "linear".to_string()];
        assert_eq!(mcp_server_name("github", &policy).as_str(), "github");
        assert_eq!(mcp_server_name("linear", &policy).as_str(), "linear");
        assert_eq!(mcp_server_name("acme-internal", &policy).as_str(), OTHER);
        assert_eq!(
            mcp_server_name("git", &policy).as_str(),
            OTHER,
            "prefix only"
        );
        assert_eq!(mcp_server_name("github", &[]).as_str(), OTHER);
    }

    #[test]
    fn host_families_without_a_deny_hook_are_unregulated() {
        assert!(!host_regulated(OTHER));
        assert!(!host_regulated("opencode") || lean_ctx::core::hook_mode::replace_mode_chosen());
    }

    #[test]
    fn a_record_is_only_what_its_kind_allows() {
        let signal = |kind, name: &str| Signal {
            ts: "2026-10-26T16:00:00Z".into(),
            kind,
            name: name.into(),
            project: None,
        };
        assert!(signal(Kind::Truncated, "map").filter().is_some());
        assert!(
            signal(Kind::Truncated, "gateway.path_jail")
                .filter()
                .is_none()
        );
        assert!(
            signal(Kind::WouldBlock, "gateway.path_jail")
                .rule()
                .is_some()
        );
        assert!(signal(Kind::WouldBlock, "map").rule().is_none());
        assert!(
            signal(Kind::UnregulatedProgram, "git")
                .unregulated()
                .is_some()
        );
        assert_eq!(
            signal(Kind::UnregulatedHost, "cursor").unregulated(),
            Some((
                UnregulatedKind::Host,
                UnregulatedName::new("cursor").unwrap()
            ))
        );
        assert!(
            signal(Kind::UnregulatedHost, "claude-code")
                .unregulated()
                .is_none()
        );
        assert!(
            signal(Kind::UnregulatedHost, "terraform")
                .unregulated()
                .is_none()
        );
        assert!(
            signal(Kind::UnregulatedMcpServer, "github")
                .unregulated()
                .is_some()
        );
        assert!(
            signal(Kind::UnregulatedMcpServer, "other")
                .unregulated()
                .is_some()
        );
        assert!(
            signal(Kind::UnregulatedMcpServer, &"a".repeat(32))
                .unregulated()
                .is_none()
        );
        assert!(signal(Kind::Blocked, "git").unregulated().is_none());
        // An MCP-server-shaped name is not a program.
        assert!(
            signal(Kind::UnregulatedProgram, "github")
                .unregulated()
                .is_none()
        );
        let json = serde_json::to_value(signal(Kind::Refetched, "full")).unwrap();
        assert_eq!(json.as_object().unwrap().len(), 4, "{json}");
    }
}