Skip to main content

lean_ctx_ext/core/
context_policies.rs

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