pub mod evaluate;
pub mod matcher;
pub mod store;
pub mod validate;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use arc_swap::ArcSwap;
use serde::Deserialize as _;
use crate::core::error::ERR_RULE_SKIPPED;
use crate::generated::types::{
AgentFunction, PolicyBundle, PolicyRule, PolicyRuleConditionsItem,
PolicyRuleConditionsItemField, PolicyRuleConditionsItemOp, PolicyRuleMode, PolicyRuleSeverity,
};
pub use evaluate::{evaluate, evaluate_command, normalize, PolicyMatch, SHELL_TOOL_NAMES};
pub use matcher::matches;
pub use store::{BundleMeta, CachedBundle, StoreError};
pub use validate::validate_rule;
pub const RULE_KIND_COMMAND: &str = "command";
pub const RULE_KIND_REQUEST: &str = "request";
pub const RULE_ACTION_DENY: &str = "deny";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
pub rule_id: String,
pub match_pattern: String,
pub mode: PolicyRuleMode,
pub severity: PolicyRuleSeverity,
pub reason: String,
pub scoped_functions: Option<Vec<AgentFunction>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ResidentBundle {
pub command_rules: Vec<Rule>,
pub request_rules: Vec<PolicyRule>,
pub enforcement_enabled: bool,
pub revision: i64,
pub built_at: SystemTime,
pub organization_id: String,
pub capture_identity_signals: bool,
pub agent_function: Option<AgentFunction>,
}
impl ResidentBundle {
pub fn from_bundle(bundle: &PolicyBundle) -> Self {
let mut command_rules = Vec::new();
let mut request_rules = Vec::new();
for wire in &bundle.rules {
if let Err(detail) = validate::validate_rule(wire) {
skip_rule(&wire.rule_id, "gate_violation", &detail);
continue;
}
match project_rule(wire) {
Some(Plane::Command(rule)) => command_rules.push(rule),
Some(Plane::Request(rule)) => request_rules.push(rule),
None => {}
}
}
let built_at = parse_built_at(&bundle.built_at).unwrap_or_else(|| {
tracing::warn!(
target: "policy",
built_at = %bundle.built_at,
"bundle built_at is not RFC 3339; reporting bundle age as 0"
);
SystemTime::now()
});
let client_config = bundle.client_config.as_ref();
Self {
command_rules,
request_rules,
enforcement_enabled: bundle.enforcement_enabled,
revision: bundle.revision,
built_at,
organization_id: bundle.organization_id.clone(),
capture_identity_signals: client_config
.and_then(|c| c.capture_identity_signals)
.unwrap_or(false),
agent_function: client_config
.and_then(|c| c.agent_context.as_ref())
.and_then(|c| c.function.as_deref())
.and_then(parse_agent_function),
}
}
pub fn age_seconds(&self, now: SystemTime) -> u64 {
now.duration_since(self.built_at)
.unwrap_or(Duration::ZERO)
.as_secs()
}
}
const MAX_LOGGED_FUNCTION_LEN: usize = 64;
fn parse_agent_function(raw: &str) -> Option<AgentFunction> {
match raw.parse::<AgentFunction>() {
Ok(function) => Some(function),
Err(_) => {
let shown = if raw.len() > MAX_LOGGED_FUNCTION_LEN {
"<oversized>"
} else {
raw
};
tracing::warn!(
target: "policy",
function = %shown,
function_len = raw.len(),
"agent_context.function is not a known AgentFunction; scoped rules will match nothing"
);
None
}
}
}
#[allow(clippy::large_enum_variant)]
enum Plane {
Command(Rule),
Request(PolicyRule),
}
fn skip_rule(rule_id: &str, reason: &'static str, detail: &str) {
tracing::warn!(
target: "policy",
code = ERR_RULE_SKIPPED,
rule_id = %rule_id,
reason,
detail = %detail,
"skipping one rule; the rest of the bundle stays active"
);
}
fn project_rule(rule: &PolicyRule) -> Option<Plane> {
match rule.kind.as_str() {
RULE_KIND_COMMAND => {
if rule.action != RULE_ACTION_DENY {
skip_rule(&rule.rule_id, "unknown_action", &rule.action);
return None;
}
let Some(match_pattern) = rule.match_pattern.clone() else {
skip_rule(
&rule.rule_id,
"gate_violation",
"kind=command carries no match_pattern",
);
return None;
};
let scoped_functions = scoped_functions(&rule.conditions);
if scoped_functions.as_ref().is_some_and(|s| s.is_empty()) {
tracing::warn!(
target: "policy",
rule_id = %rule.rule_id,
"rule conditions intersect to no agent function; it can never match on any agent"
);
}
Some(Plane::Command(Rule {
rule_id: rule.rule_id.clone(),
match_pattern,
mode: rule.mode,
severity: rule.severity,
reason: rule.reason.clone(),
scoped_functions,
}))
}
RULE_KIND_REQUEST => {
let mut held = rule.clone();
if held.mode == PolicyRuleMode::Enforce {
tracing::warn!(
target: "policy",
code = ERR_RULE_SKIPPED,
rule_id = %rule.rule_id,
reason = "enforce_coerced",
"request rule authored enforce is held as observe; nothing acts on the request plane in this phase"
);
held.mode = PolicyRuleMode::Observe;
}
Some(Plane::Request(held))
}
unknown => {
skip_rule(&rule.rule_id, "unknown_kind", unknown);
None
}
}
}
fn scoped_functions(conditions: &[PolicyRuleConditionsItem]) -> Option<Vec<AgentFunction>> {
let mut scope: Option<Vec<AgentFunction>> = None;
for condition in conditions {
match (condition.field, condition.op) {
(PolicyRuleConditionsItemField::AgentFunction, PolicyRuleConditionsItemOp::In) => {
let allowed = &condition.value;
scope = Some(match scope {
None => allowed.clone(),
Some(mut so_far) => {
so_far.retain(|f| allowed.contains(f));
so_far
}
});
}
}
}
scope.map(|mut set| {
set.sort_unstable();
set.dedup();
set
})
}
pub fn parse_bundle_tolerant(
mut doc: serde_json::Value,
) -> Result<PolicyBundle, serde_json::Error> {
if let Some(rules) = doc
.get_mut("rules")
.and_then(serde_json::Value::as_array_mut)
{
rules.retain(|raw| match PolicyRule::deserialize(raw) {
Ok(_) => true,
Err(e) => {
skip_rule(
raw.get("rule_id")
.and_then(serde_json::Value::as_str)
.unwrap_or("<unnamed>"),
"unrecognized_field",
&e.to_string(),
);
false
}
});
}
serde_json::from_value(doc)
}
fn parse_built_at(raw: &str) -> Option<SystemTime> {
chrono::DateTime::parse_from_rfc3339(raw)
.ok()
.map(|dt| SystemTime::from(dt.with_timezone(&chrono::Utc)))
}
pub type PolicyHandle = Arc<ArcSwap<Option<ResidentBundle>>>;
pub fn new_handle(initial: Option<ResidentBundle>) -> PolicyHandle {
Arc::new(ArcSwap::from_pointee(initial))
}
#[cfg(test)]
pub(crate) mod test_support {
use super::*;
use crate::generated::types::{ChurnLayer, PolicyRuleParams, PolicyRuleSelect};
pub fn wire_rule(
rule_id: &str,
pattern: &str,
mode: PolicyRuleMode,
severity: PolicyRuleSeverity,
) -> PolicyRule {
PolicyRule {
action: RULE_ACTION_DENY.to_string(),
conditions: Vec::new(),
kind: RULE_KIND_COMMAND.to_string(),
match_pattern: Some(pattern.to_string()),
mode,
params: None,
reason: format!("{rule_id} says no"),
rule_id: rule_id.to_string(),
rule_version: None,
select: None,
severity,
}
}
pub fn scoped_wire_rule(
rule_id: &str,
pattern: &str,
conditions: Vec<PolicyRuleConditionsItem>,
) -> PolicyRule {
PolicyRule {
conditions,
..wire_rule(
rule_id,
pattern,
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
)
}
}
pub fn wire_request_rule(rule_id: &str, action: &str, mode: PolicyRuleMode) -> PolicyRule {
let (select, params) = match action {
"prefix_reorder" => (
Some(PolicyRuleSelect {
exclude_layers: vec![ChurnLayer::Tools],
model_in: vec!["claude-opus-5".to_string()],
..Default::default()
}),
None,
),
"history_trim" => (
Some(PolicyRuleSelect {
min_messages: Some(40),
..Default::default()
}),
Some(PolicyRuleParams {
keep_messages: Some(20),
..Default::default()
}),
),
"prompt_edit" => (
None,
Some(PolicyRuleParams {
marker: Some("<!--openlatch-->".to_string()),
..Default::default()
}),
),
other => panic!("no fixture for request action {other}"),
};
PolicyRule {
action: action.to_string(),
conditions: Vec::new(),
kind: RULE_KIND_REQUEST.to_string(),
match_pattern: None,
mode,
params,
reason: format!("{rule_id} reshapes the request"),
rule_id: rule_id.to_string(),
rule_version: Some(3),
select,
severity: PolicyRuleSeverity::Low,
}
}
pub fn wire_bundle(rules: Vec<PolicyRule>, enforcement_enabled: bool) -> PolicyBundle {
PolicyBundle {
built_at: "2026-07-21T09:00:00Z".to_string(),
client_config: None,
enforcement_enabled,
organization_id: "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42".to_string(),
revision: 42,
rules,
schema_version: 1,
signature: None,
}
}
pub fn rule(rule_id: &str, pattern: &str, mode: PolicyRuleMode) -> Rule {
Rule {
rule_id: rule_id.to_string(),
match_pattern: pattern.to_string(),
mode,
severity: PolicyRuleSeverity::High,
reason: format!("{rule_id} says no"),
scoped_functions: None,
}
}
pub fn function_in(functions: &[AgentFunction]) -> PolicyRuleConditionsItem {
PolicyRuleConditionsItem {
field: PolicyRuleConditionsItemField::AgentFunction,
op: PolicyRuleConditionsItemOp::In,
value: functions.to_vec(),
}
}
fn keep_callsites_live() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let _ = tracing::subscriber::set_global_default(
tracing_subscriber::fmt()
.with_writer(std::io::sink)
.with_max_level(tracing::Level::TRACE)
.finish(),
);
});
}
pub fn capture_logs<T>(f: impl FnOnce() -> T) -> (T, String) {
use std::io::Write;
use std::sync::Mutex;
#[derive(Clone, Default)]
struct Buffer(Arc<Mutex<Vec<u8>>>);
impl Write for Buffer {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().expect("log buffer").extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buffer {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
keep_callsites_live();
let buffer = Buffer::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(buffer.clone())
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.finish();
let out = tracing::subscriber::with_default(subscriber, f);
let logs = String::from_utf8(buffer.0.lock().expect("log buffer").clone())
.expect("log output is utf-8");
(out, logs)
}
pub fn resident(rules: Vec<Rule>, enforcement_enabled: bool) -> ResidentBundle {
ResidentBundle {
command_rules: rules,
request_rules: Vec::new(),
enforcement_enabled,
revision: 42,
built_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_784_000_000),
organization_id: "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42".to_string(),
capture_identity_signals: false,
agent_function: None,
}
}
}
#[cfg(test)]
mod tests {
use super::test_support::*;
use super::*;
#[test]
fn from_bundle_keeps_known_rules() {
let bundle = wire_bundle(
vec![wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::Critical,
)],
true,
);
let resident = ResidentBundle::from_bundle(&bundle);
assert_eq!(resident.command_rules.len(), 1);
assert_eq!(resident.command_rules[0].rule_id, "OL-CMD-001");
assert_eq!(
resident.command_rules[0].severity,
PolicyRuleSeverity::Critical
);
assert_eq!(resident.revision, 42);
assert!(resident.enforcement_enabled);
assert_eq!(
resident.organization_id,
"0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42"
);
}
#[test]
fn from_bundle_skips_unknown_kind_and_action() {
let mut unknown_kind = wire_rule(
"OL-NET-001",
"*curl*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
);
unknown_kind.kind = "network".to_string();
let mut unknown_action = wire_rule(
"OL-CMD-002",
"*sudo*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
);
unknown_action.action = "require_approval".to_string();
let known = wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
);
let bundle = wire_bundle(vec![unknown_kind, unknown_action, known], true);
let resident = ResidentBundle::from_bundle(&bundle);
let ids: Vec<&str> = resident
.command_rules
.iter()
.map(|r| r.rule_id.as_str())
.collect();
assert_eq!(ids, vec!["OL-CMD-001"]);
}
#[test]
fn a_rule_with_an_unrecognised_field_is_dropped_and_the_bundle_survives() {
let doc = serde_json::json!({
"schema_version": 1,
"revision": 42,
"built_at": "2026-07-21T09:00:00Z",
"organization_id": "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42",
"enforcement_enabled": true,
"signature": null,
"rules": [
{
"rule_id": "OL-FUTURE-001",
"kind": "command",
"action": "deny",
"match_pattern": "*curl*",
"mode": "enforce",
"severity": "high",
"reason": "authored against a newer schema",
"unknown_key_from_the_future": { "nested": true }
},
{
"rule_id": "OL-CMD-001",
"kind": "command",
"action": "deny",
"match_pattern": "*rm -rf*",
"mode": "enforce",
"severity": "high",
"reason": "OL-CMD-001 says no"
}
]
});
let bundle = parse_bundle_tolerant(doc).expect("the bundle still parses");
let ids: Vec<&str> = bundle.rules.iter().map(|r| r.rule_id.as_str()).collect();
assert_eq!(
ids,
vec!["OL-CMD-001"],
"the future rule is dropped; every rule this build CAN read survives"
);
assert!(
bundle.enforcement_enabled,
"the rest of the document is untouched"
);
}
#[test]
fn a_malformed_envelope_still_fails() {
let doc = serde_json::json!({
"schema_version": 1,
"revision": "not-a-number",
"built_at": "2026-07-21T09:00:00Z",
"organization_id": "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42",
"enforcement_enabled": true,
"rules": []
});
assert!(parse_bundle_tolerant(doc).is_err());
}
#[test]
fn built_at_parses_rfc3339_with_microseconds() {
let mut bundle = wire_bundle(vec![], true);
bundle.built_at = "2026-07-21T09:00:00.123456Z".to_string();
let resident = ResidentBundle::from_bundle(&bundle);
let secs = resident
.built_at
.duration_since(SystemTime::UNIX_EPOCH)
.expect("after epoch")
.as_secs();
assert_eq!(secs, 1_784_624_400);
}
#[test]
fn unparsable_built_at_does_not_disarm_the_bundle() {
let mut bundle = wire_bundle(
vec![wire_rule(
"OL-CMD-001",
"*rm*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
)],
true,
);
bundle.built_at = "not a timestamp".to_string();
let resident = ResidentBundle::from_bundle(&bundle);
assert_eq!(resident.command_rules.len(), 1);
assert_eq!(resident.age_seconds(SystemTime::now()), 0);
}
#[test]
fn age_is_clamped_at_zero_when_the_clock_is_behind() {
let bundle = resident(vec![], true);
let before_built = bundle.built_at - Duration::from_secs(3_600);
assert_eq!(bundle.age_seconds(before_built), 0);
assert_eq!(
bundle.age_seconds(bundle.built_at + Duration::from_secs(90)),
90
);
}
#[test]
fn handle_starts_empty_and_hot_swaps() {
let handle = new_handle(None);
assert!(handle.load().is_none());
handle.store(Arc::new(Some(resident(
vec![rule("OL-CMD-001", "*rm*", PolicyRuleMode::Enforce)],
true,
))));
let loaded = handle.load();
let bundle = loaded.as_ref().as_ref().expect("bundle resident");
assert_eq!(bundle.command_rules.len(), 1);
}
fn bundle_doc(client_config: Option<serde_json::Value>) -> serde_json::Value {
let mut doc = serde_json::to_value(wire_bundle(vec![], true)).expect("fixture serializes");
if let Some(cc) = client_config {
doc.as_object_mut()
.expect("object")
.insert("client_config".to_string(), cc);
}
doc
}
fn capture_flag_of(client_config: Option<serde_json::Value>) -> bool {
let bundle =
parse_bundle_tolerant(bundle_doc(client_config)).expect("the bundle document parses");
ResidentBundle::from_bundle(&bundle).capture_identity_signals
}
#[test]
fn identity_capture_is_off_unless_the_bundle_says_true() {
assert!(
!capture_flag_of(None),
"no client_config at all — the shape every pre-I-1 bundle has"
);
assert!(
!capture_flag_of(Some(serde_json::json!({}))),
"client_config present but silent on the key"
);
assert!(!capture_flag_of(Some(
serde_json::json!({"capture_identity_signals": false})
)));
assert!(capture_flag_of(Some(
serde_json::json!({"capture_identity_signals": true})
)));
}
#[test]
fn an_unknown_key_inside_client_config_is_ignored_not_fatal() {
assert!(capture_flag_of(Some(serde_json::json!({
"capture_identity_signals": true,
"some_future_client_knob": {"nested": ["shape"]}
}))));
}
fn agent_function_of(client_config: Option<serde_json::Value>) -> Option<AgentFunction> {
let bundle =
parse_bundle_tolerant(bundle_doc(client_config)).expect("the bundle document parses");
ResidentBundle::from_bundle(&bundle).agent_function
}
#[test]
fn agent_function_projects_from_client_config() {
assert_eq!(
agent_function_of(Some(serde_json::json!({
"agent_context": {"function": "marketing"}
}))),
Some(AgentFunction::Marketing)
);
assert_eq!(
agent_function_of(Some(serde_json::json!({
"capture_identity_signals": true,
"agent_context": {"function": "it_ops"}
}))),
Some(AgentFunction::ItOps),
"the snake_case wire spelling parses"
);
assert_eq!(
agent_function_of(Some(serde_json::json!({
"agent_context": {"function": "unknown"}
}))),
Some(AgentFunction::Unknown),
"`unknown` is a real value, not the absence of one"
);
assert_eq!(agent_function_of(None), None, "no client_config at all");
assert_eq!(
agent_function_of(Some(serde_json::json!({}))),
None,
"client_config without agent_context"
);
assert_eq!(
agent_function_of(Some(serde_json::json!({"agent_context": {}}))),
None,
"agent_context without function"
);
}
#[test]
fn an_unparsable_agent_function_is_none_not_fatal() {
let scoped = scoped_wire_rule(
"OL-CMD-002",
"*psql*",
vec![function_in(&[AgentFunction::Marketing])],
);
let unconditional = wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::Critical,
);
let mut doc = bundle_doc(Some(
serde_json::json!({"agent_context": {"function": "astrology"}}),
));
doc["rules"] = serde_json::to_value([scoped, unconditional]).expect("rules serialize");
let bundle = parse_bundle_tolerant(doc).expect("the bundle survives");
let resident = ResidentBundle::from_bundle(&bundle);
assert_eq!(resident.agent_function, None);
assert_eq!(resident.command_rules.len(), 2, "no rule is dropped");
assert!(
evaluate_command(&resident, "sudo rm -rf /tmp").is_some_and(|m| !m.shadow),
"the unconditional deny still blocks"
);
assert!(
evaluate_command(&resident, "psql -h prod").is_none(),
"the scoped rule matches nothing on an install with no readable context"
);
assert_eq!(
agent_function_of(Some(serde_json::json!({"agent_context": {"function": ""}}))),
None,
"an empty string is no context either"
);
for shape in [
serde_json::json!({"agent_context": {"function": 42}}),
serde_json::json!({"agent_context": "marketing"}),
] {
assert!(
parse_bundle_tolerant(bundle_doc(Some(shape.clone()))).is_err(),
"expected a whole-document failure for {shape}"
);
}
}
#[test]
fn an_unparsable_agent_function_says_so_in_the_log() {
let (function, logs) = capture_logs(|| {
agent_function_of(Some(
serde_json::json!({"agent_context": {"function": "astrology"}}),
))
});
assert_eq!(function, None);
assert!(logs.contains("astrology"), "{logs}");
assert!(logs.contains("not a known AgentFunction"), "{logs}");
let long = "x".repeat(MAX_LOGGED_FUNCTION_LEN + 1);
let (function, logs) = capture_logs(|| {
agent_function_of(Some(
serde_json::json!({"agent_context": {"function": long}}),
))
});
assert_eq!(function, None);
assert!(
!logs.contains("xxxxx"),
"the value itself must not appear: {logs}"
);
assert!(
logs.contains(&format!("function_len={}", MAX_LOGGED_FUNCTION_LEN + 1)),
"{logs}"
);
let (_, logs) = capture_logs(|| agent_function_of(None));
assert!(!logs.contains("not a known AgentFunction"), "{logs}");
}
#[test]
fn a_rule_whose_conditions_cannot_all_hold_is_kept_and_reported() {
let dead = scoped_wire_rule(
"OL-CMD-002",
"*psql*",
vec![
function_in(&[AgentFunction::Sales]),
function_in(&[AgentFunction::Legal]),
],
);
let (resident, logs) =
capture_logs(|| ResidentBundle::from_bundle(&wire_bundle(vec![dead], true)));
assert_eq!(resident.command_rules.len(), 1, "kept, not dropped");
assert_eq!(
resident.command_rules[0].scoped_functions,
Some(Vec::new()),
"the intersection is empty"
);
assert!(logs.contains("OL-CMD-002"), "{logs}");
assert!(logs.contains("can never match"), "{logs}");
assert!(
!logs.contains(ERR_RULE_SKIPPED),
"an inert rule is not lost enforcement coverage: {logs}"
);
}
#[test]
fn a_rule_with_an_unknown_condition_field_is_dropped_not_fatal() {
let mut doc = bundle_doc(Some(
serde_json::json!({"agent_context": {"function": "marketing"}}),
));
doc["rules"] = serde_json::json!([
{
"rule_id": "OL-CMD-002",
"kind": "command",
"action": "deny",
"match_pattern": "*psql*",
"conditions": [
{"field": "agent.owner", "op": "in", "value": ["marketing"]}
],
"mode": "enforce",
"severity": "high",
"reason": "authored against a wider condition vocabulary"
},
{
"rule_id": "OL-CMD-003",
"kind": "command",
"action": "deny",
"match_pattern": "*curl*",
"conditions": [
{"field": "agent.function", "op": "not_in", "value": ["marketing"]}
],
"mode": "enforce",
"severity": "high",
"reason": "authored against a wider op vocabulary"
},
{
"rule_id": "OL-CMD-004",
"kind": "command",
"action": "deny",
"match_pattern": "*ssh*",
"conditions": [
{"field": "agent.function", "op": "in", "value": ["astrology"]}
],
"mode": "enforce",
"severity": "high",
"reason": "authored against a wider function vocabulary"
},
{
"rule_id": "OL-CMD-001",
"kind": "command",
"action": "deny",
"match_pattern": "*rm -rf*",
"conditions": [
{"field": "agent.function", "op": "in", "value": ["marketing"]}
],
"mode": "enforce",
"severity": "high",
"reason": "OL-CMD-001 says no"
}
]);
let (resident, logs) = capture_logs(|| {
let bundle = parse_bundle_tolerant(doc).expect("the bundle still parses");
ResidentBundle::from_bundle(&bundle)
});
let ids: Vec<&str> = resident
.command_rules
.iter()
.map(|r| r.rule_id.as_str())
.collect();
assert_eq!(ids, vec!["OL-CMD-001"], "only the readable rule survives");
assert_eq!(resident.agent_function, Some(AgentFunction::Marketing));
assert!(
evaluate_command(&resident, "sudo rm -rf /tmp").is_some_and(|m| !m.shadow),
"the surviving scoped deny still blocks on a member install"
);
assert!(logs.contains(ERR_RULE_SKIPPED), "{logs}");
assert!(logs.contains("unrecognized_field"), "{logs}");
assert!(logs.contains("OL-CMD-002"), "{logs}");
assert!(logs.contains("OL-CMD-003"), "{logs}");
assert!(logs.contains("OL-CMD-004"), "{logs}");
}
#[test]
fn conditions_project_to_the_intersection_of_their_sets() {
let projected = |conditions: Vec<PolicyRuleConditionsItem>| {
let wire = scoped_wire_rule("OL-CMD-002", "*psql*", conditions);
let resident = ResidentBundle::from_bundle(&wire_bundle(vec![wire], true));
assert_eq!(resident.command_rules.len(), 1, "the rule loads");
resident.command_rules[0].scoped_functions.clone()
};
assert_eq!(projected(vec![]), None);
assert_eq!(
projected(vec![function_in(&[
AgentFunction::Sales,
AgentFunction::Marketing,
AgentFunction::Sales,
])]),
Some(vec![AgentFunction::Sales, AgentFunction::Marketing]),
"sorted in enum order and deduplicated"
);
assert_eq!(
projected(vec![
function_in(&[AgentFunction::Marketing, AgentFunction::Sales]),
function_in(&[AgentFunction::Sales, AgentFunction::Finance]),
]),
Some(vec![AgentFunction::Sales])
);
assert_eq!(
projected(vec![
function_in(&[AgentFunction::Marketing]),
function_in(&[AgentFunction::Finance]),
]),
Some(vec![]),
"disjoint conditions keep the rule, scoped to nobody"
);
}
#[test]
fn scoped_rule_from_platform_bundle_denies_only_the_named_function() {
let load = |function: &str| {
let doc = serde_json::json!({
"schema_version": 1,
"organization_id": "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42",
"revision": 78,
"built_at": "2026-08-16T08:00:00Z",
"enforcement_enabled": true,
"rules": [{
"rule_id": "OL-CMD-002",
"kind": "command",
"match_pattern": "*psql*",
"conditions": [
{"field": "agent.function", "op": "in", "value": ["marketing", "sales"]}
],
"action": "deny",
"mode": "enforce",
"severity": "high",
"reason": "Direct database access is not part of a marketing or sales workflow"
}],
"signature": null,
"client_config": {
"capture_identity_signals": false,
"agent_context": {"function": function}
}
});
let wire = parse_bundle_tolerant(doc).expect("the platform bundle parses");
ResidentBundle::from_bundle(&wire)
};
let marketing = load("marketing");
assert_eq!(marketing.agent_function, Some(AgentFunction::Marketing));
assert_eq!(
marketing.command_rules[0].scoped_functions,
Some(vec![AgentFunction::Sales, AgentFunction::Marketing])
);
assert!(evaluate_command(&marketing, "psql -h prod").is_some_and(|m| !m.shadow));
let engineering = load("engineering");
assert_eq!(
engineering.command_rules.len(),
1,
"the rule is held, not dropped"
);
assert!(evaluate_command(&engineering, "psql -h prod").is_none());
}
#[test]
fn mixed_bundle_loads_both_planes() {
let bundle = wire_bundle(
vec![
wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::Critical,
),
wire_request_rule("OL-REQ-001", "prefix_reorder", PolicyRuleMode::Observe),
wire_request_rule("OL-REQ-002", "history_trim", PolicyRuleMode::Observe),
],
true,
);
let resident = ResidentBundle::from_bundle(&bundle);
assert_eq!(resident.command_rules.len(), 1);
assert_eq!(resident.command_rules[0].rule_id, "OL-CMD-001");
let request_ids: Vec<&str> = resident
.request_rules
.iter()
.map(|r| r.rule_id.as_str())
.collect();
assert_eq!(request_ids, vec!["OL-REQ-001", "OL-REQ-002"]);
}
#[test]
fn command_plane_unchanged() {
let deny = wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::Critical,
);
let alone = ResidentBundle::from_bundle(&wire_bundle(vec![deny.clone()], true));
let alongside = ResidentBundle::from_bundle(&wire_bundle(
vec![
deny,
wire_request_rule("OL-REQ-001", "prompt_edit", PolicyRuleMode::Observe),
],
true,
));
assert_eq!(alone.command_rules, alongside.command_rules);
assert_eq!(
evaluate_command(&alone, "sudo rm -rf /tmp").map(|m| m.rule_id),
evaluate_command(&alongside, "sudo rm -rf /tmp").map(|m| m.rule_id)
);
assert!(evaluate_command(&alongside, "sudo rm -rf /tmp").is_some_and(|m| !m.shadow));
}
#[test]
fn command_rule_from_platform_bundle_is_not_skipped() {
let canonical = r#"{
"schema_version": 1,
"organization_id": "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42",
"revision": 42,
"built_at": "2026-07-21T09:00:00Z",
"enforcement_enabled": true,
"rules": [{
"rule_id": "OL-CMD-001",
"kind": "command",
"match_pattern": "*rm -rf*",
"action": "deny",
"mode": "enforce",
"severity": "critical",
"reason": "Recursive delete of a root path"
}],
"signature": null
}"#;
let with_nulls = canonical.replace(
r#""kind": "command","#,
r#""kind": "command", "rule_version": null, "select": null, "params": null,"#,
);
for (label, body) in [("canonical", canonical), ("nulls", with_nulls.as_str())] {
let wire: PolicyBundle =
serde_json::from_str(body).unwrap_or_else(|e| panic!("{label} bundle parses: {e}"));
let resident = ResidentBundle::from_bundle(&wire);
assert_eq!(resident.command_rules.len(), 1, "{label}");
let verdict = evaluate_command(&resident, "sudo rm -rf /tmp")
.unwrap_or_else(|| panic!("{label} deny still matches"));
assert_eq!(verdict.rule_id, "OL-CMD-001", "{label}");
assert!(!verdict.shadow, "{label} deny still blocks");
}
}
#[test]
fn old_shape_bundle_still_loads() {
let body = r#"{
"schema_version": 1,
"organization_id": "0192f8a1-4c3b-7e2a-9f10-5d8c3b1a7e42",
"revision": 7,
"built_at": "2026-07-20T11:30:00Z",
"enforcement_enabled": true,
"rules": [
{"rule_id": "OL-CMD-001", "kind": "command", "match_pattern": "*rm -rf*",
"action": "deny", "mode": "enforce", "severity": "critical", "reason": "no"},
{"rule_id": "OL-CMD-002", "kind": "command", "match_pattern": "*curl*",
"action": "deny", "mode": "observe", "severity": "low", "reason": "watch"}
],
"signature": null
}"#;
let wire: PolicyBundle = serde_json::from_str(body).expect("v1 bundle parses");
let resident = ResidentBundle::from_bundle(&wire);
assert_eq!(resident.command_rules.len(), 2);
assert!(resident.request_rules.is_empty());
assert_eq!(resident.revision, 7);
}
#[test]
fn a_callsite_first_reached_from_a_bare_thread_is_still_captured() {
fn probe() {
tracing::warn!(target: "policy", code = "OL-CAPTURE-PROBE", "probe");
}
let (_, logs) = capture_logs(|| {
std::thread::spawn(probe)
.join()
.expect("probe thread joins");
probe();
});
assert!(logs.contains("OL-CAPTURE-PROBE"), "{logs}");
}
#[test]
fn gate_violation_skips_one_rule() {
let mut bad = wire_rule(
"OL-CMD-002",
"*curl*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
);
bad.select = Some(Default::default());
let good = wire_rule(
"OL-CMD-001",
"*rm -rf*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::Critical,
);
let (resident, logs) =
capture_logs(|| ResidentBundle::from_bundle(&wire_bundle(vec![bad, good], true)));
let ids: Vec<&str> = resident
.command_rules
.iter()
.map(|r| r.rule_id.as_str())
.collect();
assert_eq!(ids, vec!["OL-CMD-001"]);
assert!(
evaluate_command(&resident, "sudo rm -rf /tmp").is_some_and(|m| !m.shadow),
"the surviving deny still blocks"
);
assert!(logs.contains(ERR_RULE_SKIPPED), "{logs}");
assert!(logs.contains("gate_violation"), "{logs}");
assert!(logs.contains("OL-CMD-002"), "{logs}");
}
#[test]
fn prefix_reorder_with_min_messages_is_skipped() {
let mut bad = wire_request_rule("OL-REQ-001", "prefix_reorder", PolicyRuleMode::Observe);
bad.select
.as_mut()
.expect("fixture has a select")
.min_messages = Some(4);
let (resident, logs) = capture_logs(|| {
ResidentBundle::from_bundle(&wire_bundle(
vec![
bad,
wire_request_rule("OL-REQ-002", "prefix_reorder", PolicyRuleMode::Observe),
],
true,
))
});
let ids: Vec<&str> = resident
.request_rules
.iter()
.map(|r| r.rule_id.as_str())
.collect();
assert_eq!(ids, vec!["OL-REQ-002"]);
assert!(logs.contains("gate_violation"), "{logs}");
}
#[test]
fn history_trim_with_marker_is_skipped() {
let mut bad = wire_request_rule("OL-REQ-001", "history_trim", PolicyRuleMode::Observe);
bad.params.as_mut().expect("fixture has params").marker = Some("x".to_string());
let (resident, logs) =
capture_logs(|| ResidentBundle::from_bundle(&wire_bundle(vec![bad], true)));
assert!(resident.request_rules.is_empty());
assert!(logs.contains("gate_violation"), "{logs}");
}
#[test]
fn request_rule_without_rule_version_is_skipped() {
let mut bad = wire_request_rule("OL-REQ-001", "prompt_edit", PolicyRuleMode::Observe);
bad.rule_version = None;
let (resident, logs) =
capture_logs(|| ResidentBundle::from_bundle(&wire_bundle(vec![bad], true)));
assert!(resident.request_rules.is_empty());
assert!(logs.contains(ERR_RULE_SKIPPED), "{logs}");
assert!(logs.contains("gate_violation"), "{logs}");
}
#[test]
fn authored_enforce_request_rule_logs_coercion() {
let bundle = wire_bundle(
vec![
wire_request_rule("OL-REQ-001", "prefix_reorder", PolicyRuleMode::Enforce),
wire_request_rule("OL-REQ-002", "history_trim", PolicyRuleMode::Observe),
],
true,
);
let (resident, logs) = capture_logs(|| ResidentBundle::from_bundle(&bundle));
assert_eq!(resident.request_rules.len(), 2, "neither rule is dropped");
assert!(logs.contains("enforce_coerced"), "{logs}");
assert!(logs.contains("OL-REQ-001"), "{logs}");
assert!(
!logs.contains("OL-REQ-002"),
"an observe rule is not coerced: {logs}"
);
assert!(
resident
.request_rules
.iter()
.all(|r| r.mode == PolicyRuleMode::Observe),
"every resident request rule is held as observe"
);
}
#[test]
fn a_large_bundle_loads_without_per_rule_compilation() {
let rules: Vec<PolicyRule> = (0..500)
.map(|i| {
wire_rule(
&format!("OL-CMD-{i:03}"),
&format!("*pattern-{i}*"),
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
)
})
.collect();
let started = std::time::Instant::now();
let resident = ResidentBundle::from_bundle(&wire_bundle(rules, true));
let elapsed = started.elapsed();
assert_eq!(resident.command_rules.len(), 500);
assert!(
elapsed < Duration::from_secs(5),
"500 rules took {elapsed:?}"
);
}
#[test]
fn unknown_command_action_is_skipped_by_projection() {
let mut rule = wire_rule(
"OL-CMD-002",
"*sudo*",
PolicyRuleMode::Enforce,
PolicyRuleSeverity::High,
);
rule.action = "require_approval".to_string();
assert!(project_rule(&rule).is_none());
}
}