lean-ctx 3.6.4

Context Runtime for AI Agents with CCP. 51 MCP tools, 10 read modes, 60+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Context Policy Engine -- declarative rules for context governance.
//!
//! Extends the existing profile/role system with match-based policies
//! that automatically include/exclude/pin/transform context items.
//!
//! Integrates with:
//!   - io_boundary.rs (secret path detection)
//!   - profiles.rs (compression/routing config)
//!   - roles.rs (role-based access control)

use serde::{Deserialize, Serialize};

use super::context_field::{ContextState, ViewKind};

/// A declarative context policy rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextPolicy {
    pub name: String,
    #[serde(rename = "match")]
    pub match_pattern: String,
    pub action: PolicyAction,
    #[serde(default)]
    pub condition: Option<PolicyCondition>,
    #[serde(default)]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyAction {
    Exclude,
    Include,
    Pin,
    SetView { view: String },
    MaxTokens { limit: usize },
    MarkOutdated,
    Redact,
    Audit,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyCondition {
    SourceSeenBefore,
    SourceModifiedRecently,
    TokensAbove { threshold: usize },
    Always,
    AgentIs { agent_id: String },
    AgentRoleIs { role: String },
    ContentContainsSecret,
}

/// A set of loaded policies.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PolicySet {
    pub policies: Vec<ContextPolicy>,
}

impl PolicySet {
    pub fn new() -> Self {
        Self::default()
    }

    /// Built-in default policies that align with existing LeanCTX behavior.
    pub fn defaults() -> Self {
        Self {
            policies: vec![
                ContextPolicy {
                    name: "never_include_secrets".to_string(),
                    match_pattern: "**/.env*".to_string(),
                    action: PolicyAction::Exclude,
                    condition: None,
                    reason: Some("secrets".to_string()),
                },
                ContextPolicy {
                    name: "exclude_private_keys".to_string(),
                    match_pattern: "**/*private_key*".to_string(),
                    action: PolicyAction::Exclude,
                    condition: None,
                    reason: Some("private key material".to_string()),
                },
                ContextPolicy {
                    name: "exclude_credentials".to_string(),
                    match_pattern: "**/credentials*".to_string(),
                    action: PolicyAction::Exclude,
                    condition: None,
                    reason: Some("credentials".to_string()),
                },
                ContextPolicy {
                    name: "delta_after_first_read".to_string(),
                    match_pattern: "src/**".to_string(),
                    action: PolicyAction::SetView {
                        view: "diff".to_string(),
                    },
                    condition: Some(PolicyCondition::SourceSeenBefore),
                    reason: Some("predictive coding: only send prediction errors".to_string()),
                },
                ContextPolicy {
                    name: "compress_large_files".to_string(),
                    match_pattern: "**/*".to_string(),
                    action: PolicyAction::SetView {
                        view: "signatures".to_string(),
                    },
                    condition: Some(PolicyCondition::TokensAbove { threshold: 8000 }),
                    reason: Some("large file budget protection".to_string()),
                },
            ],
        }
    }

    /// Evaluate all policies against a path, returning applicable actions.
    pub fn evaluate(
        &self,
        path: &str,
        seen_before: bool,
        token_count: usize,
    ) -> Vec<PolicyEvalResult> {
        self.evaluate_full(path, seen_before, token_count, None, None, None)
    }

    /// Evaluate with full context including agent/role/content dimensions.
    pub fn evaluate_full(
        &self,
        path: &str,
        seen_before: bool,
        token_count: usize,
        agent_id: Option<&str>,
        role: Option<&str>,
        content: Option<&str>,
    ) -> Vec<PolicyEvalResult> {
        let mut results = Vec::new();
        for policy in &self.policies {
            if !path_matches(&policy.match_pattern, path) {
                continue;
            }
            if let Some(ref condition) = policy.condition {
                if !check_condition(
                    condition,
                    seen_before,
                    token_count,
                    path,
                    agent_id,
                    role,
                    content,
                ) {
                    continue;
                }
            }
            results.push(PolicyEvalResult {
                policy_name: policy.name.clone(),
                action: policy.action.clone(),
                reason: policy.reason.clone().unwrap_or_else(|| policy.name.clone()),
            });
        }
        results
    }

    /// Determine the effective state for an item after policy evaluation.
    pub fn effective_state(
        &self,
        path: &str,
        current: ContextState,
        seen_before: bool,
        token_count: usize,
    ) -> ContextState {
        let evals = self.evaluate(path, seen_before, token_count);
        let mut state = current;
        for eval in &evals {
            match &eval.action {
                PolicyAction::Exclude => state = ContextState::Excluded,
                PolicyAction::Pin => state = ContextState::Pinned,
                PolicyAction::Include => {
                    if state == ContextState::Candidate {
                        state = ContextState::Included;
                    }
                }
                PolicyAction::MarkOutdated => state = ContextState::Stale,
                PolicyAction::MaxTokens { limit } => {
                    if token_count > *limit {
                        state = ContextState::Excluded;
                    }
                }
                PolicyAction::SetView { .. } | PolicyAction::Redact | PolicyAction::Audit => {}
            }
        }
        state
    }

    /// Determine the recommended view for an item after policy evaluation.
    pub fn recommended_view(
        &self,
        path: &str,
        seen_before: bool,
        token_count: usize,
    ) -> Option<ViewKind> {
        let evals = self.evaluate(path, seen_before, token_count);
        for eval in evals.iter().rev() {
            if let PolicyAction::SetView { view } = &eval.action {
                return Some(ViewKind::parse(view));
            }
        }
        None
    }

    /// Load policies from a project's .lean-ctx/policies.json file.
    pub fn load_project(project_root: &std::path::Path) -> Self {
        let path = project_root.join(".lean-ctx").join("policies.json");
        std::fs::read_to_string(&path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_else(Self::defaults)
    }

    /// Save policies to a project's .lean-ctx/policies.json file.
    pub fn save_project(&self, project_root: &std::path::Path) -> Result<(), String> {
        let dir = project_root.join(".lean-ctx");
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        let path = dir.join("policies.json");
        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
        crate::config_io::write_atomic(&path, &json)
    }
}

#[derive(Debug, Clone)]
pub struct PolicyEvalResult {
    pub policy_name: String,
    pub action: PolicyAction,
    pub reason: String,
}

fn path_matches(pattern: &str, path: &str) -> bool {
    if pattern == "**/*" {
        return true;
    }

    if let Some(suffix) = pattern.strip_prefix("**/") {
        if suffix.contains('*') {
            let inner = suffix.replace('*', "");
            return path.contains(&inner);
        }
        return path.contains(suffix) || path.ends_with(suffix);
    }

    if let Some(prefix) = pattern.strip_suffix("/**") {
        return path.starts_with(prefix);
    }

    if pattern.contains("**") {
        let parts: Vec<&str> = pattern.split("**").collect();
        if parts.len() == 2 {
            return path.starts_with(parts[0]) && path.ends_with(parts[1]);
        }
    }

    if let Some(prefix) = pattern.strip_suffix('*') {
        return path.starts_with(prefix);
    }

    path == pattern || path.ends_with(pattern)
}

fn check_condition(
    condition: &PolicyCondition,
    seen_before: bool,
    token_count: usize,
    path: &str,
    agent_id: Option<&str>,
    role: Option<&str>,
    content: Option<&str>,
) -> bool {
    match condition {
        PolicyCondition::SourceSeenBefore => seen_before,
        PolicyCondition::TokensAbove { threshold } => token_count > *threshold,
        PolicyCondition::SourceModifiedRecently => {
            const RECENT_SECS: u64 = 3600;
            std::fs::metadata(path)
                .and_then(|m| m.modified())
                .ok()
                .and_then(|t| t.elapsed().ok())
                .is_some_and(|elapsed| elapsed.as_secs() < RECENT_SECS)
        }
        PolicyCondition::Always => true,
        PolicyCondition::AgentIs { agent_id: expected } => {
            agent_id.is_some_and(|id| id == expected)
        }
        PolicyCondition::AgentRoleIs { role: expected } => role.is_some_and(|r| r == expected),
        PolicyCondition::ContentContainsSecret => {
            content.is_some_and(|c| !crate::core::secret_detection::detect_secrets(c).is_empty())
        }
    }
}

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

    #[test]
    fn default_policies_exclude_env_files() {
        let ps = PolicySet::defaults();
        let results = ps.evaluate(".env", false, 100);
        assert!(
            results
                .iter()
                .any(|r| matches!(r.action, PolicyAction::Exclude)),
            "should exclude .env files"
        );
    }

    #[test]
    fn default_policies_exclude_private_keys() {
        let ps = PolicySet::defaults();
        let results = ps.evaluate("secrets/private_key.pem", false, 100);
        assert!(
            results
                .iter()
                .any(|r| matches!(r.action, PolicyAction::Exclude)),
            "should exclude private key files"
        );
    }

    #[test]
    fn delta_policy_only_when_seen_before() {
        let ps = PolicySet::defaults();
        let first = ps.evaluate("src/main.rs", false, 500);
        let second = ps.evaluate("src/main.rs", true, 500);
        assert!(
            !first
                .iter()
                .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "diff")),
            "should NOT suggest diff on first read"
        );
        assert!(
            second
                .iter()
                .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "diff")),
            "should suggest diff on subsequent read"
        );
    }

    #[test]
    fn large_file_policy_triggers_above_threshold() {
        let ps = PolicySet::defaults();
        let small = ps.evaluate("src/main.rs", false, 500);
        let large = ps.evaluate("src/main.rs", false, 10000);
        assert!(!small
            .iter()
            .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "signatures")),);
        assert!(large
            .iter()
            .any(|r| matches!(&r.action, PolicyAction::SetView { view } if view == "signatures")),);
    }

    #[test]
    fn effective_state_excludes_secrets() {
        let ps = PolicySet::defaults();
        let state = ps.effective_state(".env.local", ContextState::Candidate, false, 100);
        assert_eq!(state, ContextState::Excluded);
    }

    #[test]
    fn recommended_view_for_seen_file() {
        let ps = PolicySet::defaults();
        let view = ps.recommended_view("src/main.rs", true, 500);
        assert_eq!(view, Some(ViewKind::Diff));
    }

    #[test]
    fn recommended_view_none_for_new_file() {
        let ps = PolicySet::defaults();
        let view = ps.recommended_view("src/main.rs", false, 500);
        assert!(view.is_none() || view == Some(ViewKind::Diff),);
    }

    #[test]
    fn path_matches_glob_patterns() {
        assert!(path_matches("**/.env*", ".env"));
        assert!(path_matches("**/.env*", ".env.local"));
        assert!(path_matches("**/.env*", "config/.env.prod"));
        assert!(path_matches("src/**", "src/main.rs"));
        assert!(path_matches("src/**", "src/core/mod.rs"));
        assert!(path_matches("**/*", "anything.txt"));
        assert!(!path_matches("src/**", "tests/test.rs"));
    }

    #[test]
    fn empty_policy_set_changes_nothing() {
        let ps = PolicySet::new();
        let state = ps.effective_state("src/main.rs", ContextState::Included, false, 100);
        assert_eq!(state, ContextState::Included);
    }

    #[test]
    fn custom_policy_works() {
        let ps = PolicySet {
            policies: vec![ContextPolicy {
                name: "pin_readme".to_string(),
                match_pattern: "README.md".to_string(),
                action: PolicyAction::Pin,
                condition: None,
                reason: None,
            }],
        };
        let state = ps.effective_state("README.md", ContextState::Candidate, false, 100);
        assert_eq!(state, ContextState::Pinned);
    }
}