Skip to main content

lean_ctx/core/
context_policies.rs

1//! Context Policy Engine -- declarative rules for context governance.
2//!
3//! Extends the existing profile/role system with match-based policies
4//! that automatically include/exclude/pin/transform context items.
5//!
6//! Integrates with:
7//!   - io_boundary.rs (secret path detection)
8//!   - profiles.rs (compression/routing config)
9//!   - roles.rs (role-based access control)
10
11use serde::{Deserialize, Serialize};
12
13use super::context_field::{ContextState, ViewKind};
14
15/// A declarative context policy rule.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ContextPolicy {
18    pub name: String,
19    #[serde(rename = "match")]
20    pub match_pattern: String,
21    pub action: PolicyAction,
22    #[serde(default)]
23    pub condition: Option<PolicyCondition>,
24    #[serde(default)]
25    pub reason: Option<String>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum PolicyAction {
31    Exclude,
32    Include,
33    Pin,
34    SetView { view: String },
35    MaxTokens { limit: usize },
36    MarkOutdated,
37    Redact,
38    Audit,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum PolicyCondition {
44    SourceSeenBefore,
45    SourceModifiedRecently,
46    TokensAbove { threshold: usize },
47    Always,
48    AgentIs { agent_id: String },
49    AgentRoleIs { role: String },
50    ContentContainsSecret,
51}
52
53/// A set of loaded policies.
54#[derive(Debug, Clone, Default, Serialize, Deserialize)]
55pub struct PolicySet {
56    pub policies: Vec<ContextPolicy>,
57}
58
59impl PolicySet {
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    /// Built-in default policies that align with existing LeanCTX behavior.
65    pub fn defaults() -> Self {
66        let mut policies = Self::security_defaults().policies;
67        policies.extend(Self::attach_compat_defaults().policies);
68        Self { policies }
69    }
70
71    /// Open Engine safety defaults. These remain mechanism-level security policy.
72    pub fn security_defaults() -> Self {
73        Self {
74            policies: vec![
75                ContextPolicy {
76                    name: "never_include_secrets".to_string(),
77                    match_pattern: "**/.env*".to_string(),
78                    action: PolicyAction::Exclude,
79                    condition: None,
80                    reason: Some("secrets".to_string()),
81                },
82                ContextPolicy {
83                    name: "exclude_private_keys".to_string(),
84                    match_pattern: "**/*private_key*".to_string(),
85                    action: PolicyAction::Exclude,
86                    condition: None,
87                    reason: Some("private key material".to_string()),
88                },
89                ContextPolicy {
90                    name: "exclude_credentials".to_string(),
91                    match_pattern: "**/credentials*".to_string(),
92                    action: PolicyAction::Exclude,
93                    condition: None,
94                    reason: Some("credentials".to_string()),
95                },
96            ],
97        }
98    }
99
100    /// Frozen OSS Attach compatibility heuristics.
101    ///
102    /// These preserve the supported Coding-Agent experience but are not the
103    /// canonical Product policy surface and must not gain new lifecycle rules.
104    pub fn attach_compat_defaults() -> Self {
105        Self {
106            policies: vec![
107                ContextPolicy {
108                    name: "delta_after_first_read".to_string(),
109                    match_pattern: "src/**".to_string(),
110                    action: PolicyAction::SetView {
111                        view: "diff".to_string(),
112                    },
113                    condition: Some(PolicyCondition::SourceSeenBefore),
114                    reason: Some("predictive coding: only send prediction errors".to_string()),
115                },
116                ContextPolicy {
117                    name: "compress_large_files".to_string(),
118                    match_pattern: "**/*".to_string(),
119                    action: PolicyAction::SetView {
120                        view: "signatures".to_string(),
121                    },
122                    condition: Some(PolicyCondition::TokensAbove { threshold: 8000 }),
123                    reason: Some("large file budget protection".to_string()),
124                },
125            ],
126        }
127    }
128
129    /// Evaluate all policies against a path, returning applicable actions.
130    pub fn evaluate(
131        &self,
132        path: &str,
133        seen_before: bool,
134        token_count: usize,
135    ) -> Vec<PolicyEvalResult> {
136        self.evaluate_full(path, seen_before, token_count, None, None, None)
137    }
138
139    /// Evaluate with full context including agent/role/content dimensions.
140    pub fn evaluate_full(
141        &self,
142        path: &str,
143        seen_before: bool,
144        token_count: usize,
145        agent_id: Option<&str>,
146        role: Option<&str>,
147        content: Option<&str>,
148    ) -> Vec<PolicyEvalResult> {
149        let mut results = Vec::new();
150        for policy in &self.policies {
151            if !path_matches(&policy.match_pattern, path) {
152                continue;
153            }
154            if let Some(ref condition) = policy.condition
155                && !check_condition(
156                    condition,
157                    seen_before,
158                    token_count,
159                    path,
160                    agent_id,
161                    role,
162                    content,
163                )
164            {
165                continue;
166            }
167            results.push(PolicyEvalResult {
168                policy_name: policy.name.clone(),
169                action: policy.action.clone(),
170                reason: policy.reason.clone().unwrap_or_else(|| policy.name.clone()),
171            });
172        }
173        results
174    }
175
176    /// Determine the effective state for an item after policy evaluation.
177    pub fn effective_state(
178        &self,
179        path: &str,
180        current: ContextState,
181        seen_before: bool,
182        token_count: usize,
183    ) -> ContextState {
184        let evals = self.evaluate(path, seen_before, token_count);
185        let mut state = current;
186        for eval in &evals {
187            match &eval.action {
188                PolicyAction::Exclude => state = ContextState::Excluded,
189                PolicyAction::Pin => state = ContextState::Pinned,
190                PolicyAction::Include => {
191                    if state == ContextState::Candidate {
192                        state = ContextState::Included;
193                    }
194                }
195                PolicyAction::MarkOutdated => state = ContextState::Stale,
196                PolicyAction::MaxTokens { limit } => {
197                    if token_count > *limit {
198                        state = ContextState::Excluded;
199                    }
200                }
201                PolicyAction::SetView { .. } | PolicyAction::Redact | PolicyAction::Audit => {}
202            }
203        }
204        state
205    }
206
207    /// Determine the recommended view for an item after policy evaluation.
208    pub fn recommended_view(
209        &self,
210        path: &str,
211        seen_before: bool,
212        token_count: usize,
213    ) -> Option<ViewKind> {
214        let evals = self.evaluate(path, seen_before, token_count);
215        for eval in evals.iter().rev() {
216            if let PolicyAction::SetView { view } = &eval.action {
217                return Some(ViewKind::parse(view));
218            }
219        }
220        None
221    }
222
223    /// Load policies from a project's .lean-ctx/policies.json file.
224    pub fn load_project(project_root: &std::path::Path) -> Self {
225        if crate::core::pathutil::is_data_dir_collision(project_root) {
226            return Self::defaults();
227        }
228        let path = project_root.join(".lean-ctx").join("policies.json");
229        std::fs::read_to_string(&path)
230            .ok()
231            .and_then(|s| serde_json::from_str(&s).ok())
232            .unwrap_or_else(Self::defaults)
233    }
234
235    /// Save policies to a project's .lean-ctx/policies.json file.
236    pub fn save_project(&self, project_root: &std::path::Path) -> Result<(), String> {
237        let dir = crate::core::pathutil::safe_project_data_dir(project_root)?;
238        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
239        let path = dir.join("policies.json");
240        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
241        crate::config_io::write_atomic(&path, &json)
242    }
243}
244
245#[derive(Debug, Clone)]
246pub struct PolicyEvalResult {
247    pub policy_name: String,
248    pub action: PolicyAction,
249    pub reason: String,
250}
251
252fn path_matches(pattern: &str, path: &str) -> bool {
253    if pattern == "**/*" {
254        return true;
255    }
256
257    if let Some(suffix) = pattern.strip_prefix("**/") {
258        if suffix.contains('*') {
259            let inner = suffix.replace('*', "");
260            return path.contains(&inner);
261        }
262        return path.contains(suffix) || path.ends_with(suffix);
263    }
264
265    if let Some(prefix) = pattern.strip_suffix("/**") {
266        return path.starts_with(prefix);
267    }
268
269    if pattern.contains("**") {
270        let parts: Vec<&str> = pattern.split("**").collect();
271        if parts.len() == 2 {
272            return path.starts_with(parts[0]) && path.ends_with(parts[1]);
273        }
274    }
275
276    if let Some(prefix) = pattern.strip_suffix('*') {
277        return path.starts_with(prefix);
278    }
279
280    path == pattern || path.ends_with(pattern)
281}
282
283fn check_condition(
284    condition: &PolicyCondition,
285    seen_before: bool,
286    token_count: usize,
287    path: &str,
288    agent_id: Option<&str>,
289    role: Option<&str>,
290    content: Option<&str>,
291) -> bool {
292    match condition {
293        PolicyCondition::SourceSeenBefore => seen_before,
294        PolicyCondition::TokensAbove { threshold } => token_count > *threshold,
295        PolicyCondition::SourceModifiedRecently => {
296            const RECENT_SECS: u64 = 3600;
297            std::fs::metadata(path)
298                .and_then(|m| m.modified())
299                .ok()
300                .and_then(|t| t.elapsed().ok())
301                .is_some_and(|elapsed| elapsed.as_secs() < RECENT_SECS)
302        }
303        PolicyCondition::Always => true,
304        PolicyCondition::AgentIs { agent_id: expected } => {
305            agent_id.is_some_and(|id| id == expected)
306        }
307        PolicyCondition::AgentRoleIs { role: expected } => role.is_some_and(|r| r == expected),
308        PolicyCondition::ContentContainsSecret => {
309            content.is_some_and(|c| !crate::core::secret_detection::detect_secrets(c).is_empty())
310        }
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    #[test]
319    fn default_policies_exclude_env_files() {
320        let ps = PolicySet::defaults();
321        let results = ps.evaluate(".env", false, 100);
322        assert!(
323            results
324                .iter()
325                .any(|r| matches!(r.action, PolicyAction::Exclude)),
326            "should exclude .env files"
327        );
328    }
329
330    #[test]
331    fn default_policy_partitions_preserve_order_and_ownership() {
332        let security = PolicySet::security_defaults();
333        let attach = PolicySet::attach_compat_defaults();
334        let defaults = PolicySet::defaults();
335
336        let security_names: Vec<_> = security
337            .policies
338            .iter()
339            .map(|policy| policy.name.as_str())
340            .collect();
341        let attach_names: Vec<_> = attach
342            .policies
343            .iter()
344            .map(|policy| policy.name.as_str())
345            .collect();
346        let default_names: Vec<_> = defaults
347            .policies
348            .iter()
349            .map(|policy| policy.name.as_str())
350            .collect();
351
352        assert_eq!(
353            security_names,
354            [
355                "never_include_secrets",
356                "exclude_private_keys",
357                "exclude_credentials",
358            ]
359        );
360        assert_eq!(
361            attach_names,
362            ["delta_after_first_read", "compress_large_files"]
363        );
364        assert_eq!(
365            default_names,
366            security_names
367                .into_iter()
368                .chain(attach_names)
369                .collect::<Vec<_>>()
370        );
371        assert!(
372            security
373                .policies
374                .iter()
375                .all(|policy| matches!(policy.action, PolicyAction::Exclude))
376        );
377        assert!(
378            attach
379                .policies
380                .iter()
381                .all(|policy| matches!(policy.action, PolicyAction::SetView { .. }))
382        );
383    }
384
385    #[test]
386    fn default_policies_exclude_private_keys() {
387        let ps = PolicySet::defaults();
388        let results = ps.evaluate("secrets/private_key.pem", false, 100);
389        assert!(
390            results
391                .iter()
392                .any(|r| matches!(r.action, PolicyAction::Exclude)),
393            "should exclude private key files"
394        );
395    }
396
397    #[test]
398    fn delta_policy_only_when_seen_before() {
399        let ps = PolicySet::defaults();
400        let first = ps.evaluate("src/main.rs", false, 500);
401        let second = ps.evaluate("src/main.rs", true, 500);
402        assert!(
403            !first
404                .iter()
405                .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "diff")),
406            "should NOT suggest diff on first read"
407        );
408        assert!(
409            second
410                .iter()
411                .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "diff")),
412            "should suggest diff on subsequent read"
413        );
414    }
415
416    #[test]
417    fn large_file_policy_triggers_above_threshold() {
418        let ps = PolicySet::defaults();
419        let small = ps.evaluate("src/main.rs", false, 500);
420        let large = ps.evaluate("src/main.rs", false, 10000);
421        assert!(
422            !small.iter().any(
423                |r| matches!(&r.action, PolicyAction::SetView { view } if view == "signatures")
424            ),
425        );
426        assert!(
427            large.iter().any(
428                |r| matches!(&r.action, PolicyAction::SetView { view } if view == "signatures")
429            ),
430        );
431    }
432
433    #[test]
434    fn effective_state_excludes_secrets() {
435        let ps = PolicySet::defaults();
436        let state = ps.effective_state(".env.local", ContextState::Candidate, false, 100);
437        assert_eq!(state, ContextState::Excluded);
438    }
439
440    #[test]
441    fn recommended_view_for_seen_file() {
442        let ps = PolicySet::defaults();
443        let view = ps.recommended_view("src/main.rs", true, 500);
444        assert_eq!(view, Some(ViewKind::Diff));
445    }
446
447    #[test]
448    fn recommended_view_none_for_new_file() {
449        let ps = PolicySet::defaults();
450        let view = ps.recommended_view("src/main.rs", false, 500);
451        assert!(view.is_none() || view == Some(ViewKind::Diff),);
452    }
453
454    #[test]
455    fn path_matches_glob_patterns() {
456        assert!(path_matches("**/.env*", ".env"));
457        assert!(path_matches("**/.env*", ".env.local"));
458        assert!(path_matches("**/.env*", "config/.env.prod"));
459        assert!(path_matches("src/**", "src/main.rs"));
460        assert!(path_matches("src/**", "src/core/mod.rs"));
461        assert!(path_matches("**/*", "anything.txt"));
462        assert!(!path_matches("src/**", "tests/test.rs"));
463    }
464
465    #[test]
466    fn empty_policy_set_changes_nothing() {
467        let ps = PolicySet::new();
468        let state = ps.effective_state("src/main.rs", ContextState::Included, false, 100);
469        assert_eq!(state, ContextState::Included);
470    }
471
472    #[test]
473    fn custom_policy_works() {
474        let ps = PolicySet {
475            policies: vec![ContextPolicy {
476                name: "pin_readme".to_string(),
477                match_pattern: "README.md".to_string(),
478                action: PolicyAction::Pin,
479                condition: None,
480                reason: None,
481            }],
482        };
483        let state = ps.effective_state("README.md", ContextState::Candidate, false, 100);
484        assert_eq!(state, ContextState::Pinned);
485    }
486}