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";
const MAX_SIGNALS_BYTES: u64 = 4 * 1024 * 1024;
#[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 {
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()
}
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)),
Kind::UnregulatedMcpServer => (UnregulatedKind::McpServer, true),
_ => return None,
};
fits.then(|| UnregulatedName::new(name))
.flatten()
.map(|n| (kind, n))
}
}
pub(crate) fn sink_open() -> bool {
super::secrets::sink().is_some()
}
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());
}
}
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()
}
pub fn host_call(client: &str) {
if !sink_open() {
return;
}
let family = host_family(client);
if !host_regulated(family) {
record(Kind::UnregulatedHost, &[family]);
}
}
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)
}
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()
}
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()]);
}
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()
}
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());
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}");
}
}