lean-ctx 3.9.14

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ 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
use std::path::{Path, PathBuf};

use crate::core::{events, pathjail, roles, secret_detection};

/// Reads a file without following symlinks (TOCTOU protection).
/// Falls back to regular read on non-Unix platforms.
#[cfg(unix)]
pub(crate) fn read_file_nofollow(path: &str) -> Result<String, std::io::Error> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path);
    match file {
        Ok(mut f) => {
            use std::io::Read;
            let mut buf = Vec::new();
            f.read_to_end(&mut buf)?;
            Ok(String::from_utf8_lossy(&buf).into_owned())
        }
        Err(e) if e.raw_os_error() == Some(libc::ELOOP) => Err(std::io::Error::other(format!(
            "Symlink detected at {path} — refusing to follow (TOCTOU protection)"
        ))),
        Err(e) => Err(e),
    }
}

/// Windows parity (GL#442): no O_NOFOLLOW exists, so lstat first and refuse
/// symlinks *and* NTFS junctions/reparse points before opening. Small TOCTOU
/// window remains between the check and the open (documented in SECURITY.md).
#[cfg(not(unix))]
pub fn read_file_nofollow(path: &str) -> Result<String, std::io::Error> {
    if let Ok(meta) = std::fs::symlink_metadata(path) {
        if crate::core::pathutil::is_symlink_or_reparse(&meta) {
            return Err(std::io::Error::other(format!(
                "Symlink detected at {path} — refusing to follow (TOCTOU protection)"
            )));
        }
    }
    std::fs::read_to_string(path)
}

/// Reads a file as lossy UTF-8, rejecting binary files.
/// Uses O_NOFOLLOW on Unix to prevent TOCTOU symlink attacks.
pub(crate) fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
    if crate::core::binary_detect::is_binary_file(path) {
        let msg = crate::core::binary_detect::binary_file_message(path);
        return Err(std::io::Error::other(msg));
    }
    read_file_nofollow(path).map(strip_utf8_bom)
}

/// A UTF-8 BOM is an encoding artifact, not content — leaking it corrupts the
/// first line of every downstream view (limitations doc #11). Shared by both
/// file readers (this module's and `tools::ctx_read::read_file_lossy`).
pub(crate) fn strip_utf8_bom(s: String) -> String {
    match s.strip_prefix('\u{feff}') {
        Some(rest) => rest.to_owned(),
        None => s,
    }
}

/// Result of a file read with secret scanning applied.
pub(crate) struct ScannedRead {
    pub content: String,
    pub secret_matches: Vec<secret_detection::SecretMatch>,
    pub was_redacted: bool,
}

fn redact_for_role(config_redact: bool, role_name: &str) -> bool {
    config_redact || role_name.eq_ignore_ascii_case("regulated")
}

/// Reads a file and applies secret detection/redaction per config.
///
/// - `enabled=true, redact=false`: returns original content + warnings in `secret_matches`
/// - `enabled=true, redact=true`: returns redacted content + `was_redacted=true`
/// - `role=regulated`: redacts detected secrets even when `redact=false`
/// - `enabled=false`: returns original content, no scanning
pub(crate) fn read_file_scanned(path: &str) -> Result<ScannedRead, std::io::Error> {
    let raw = read_file_lossy(path)?;
    let cfg = crate::core::config::Config::load();
    let sd = &cfg.secret_detection;
    let role_name = roles::active_role_name();

    if !sd.enabled {
        return Ok(ScannedRead {
            content: raw,
            secret_matches: Vec::new(),
            was_redacted: false,
        });
    }

    let mut scan_config = sd.clone();
    scan_config.redact = redact_for_role(sd.redact, &role_name);
    let (content, matches) = secret_detection::scan_and_redact(&raw, &scan_config);

    if !matches.is_empty() {
        let names: Vec<&str> = matches.iter().map(|m| m.pattern_name).collect();
        let mut unique: Vec<&str> = names;
        unique.sort_unstable();
        unique.dedup();
        let msg = format!(
            "[SECRET DETECTION] {} secret(s) found in {}: {}",
            matches.len(),
            path,
            unique.join(", ")
        );
        events::emit_policy_violation(&role_name, "read_file", &msg);
        tracing::warn!("{msg}");
    }

    let was_redacted = scan_config.redact && !matches.is_empty();
    Ok(ScannedRead {
        content,
        secret_matches: matches,
        was_redacted,
    })
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BoundaryMode {
    Warn,
    Enforce,
}

impl BoundaryMode {
    fn parse(s: &str) -> Self {
        match s.trim().to_lowercase().as_str() {
            "enforce" | "strict" => Self::Enforce,
            _ => Self::Warn,
        }
    }
}

pub(crate) fn boundary_mode_effective(role: &roles::Role) -> BoundaryMode {
    if let Ok(v) = std::env::var("LEAN_CTX_IO_BOUNDARY_MODE")
        && !v.trim().is_empty()
    {
        return BoundaryMode::parse(&v);
    }
    BoundaryMode::parse(&role.io.boundary_mode)
}

pub(crate) fn is_secret_like(path: &Path) -> Option<&'static str> {
    let file = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
    let lower = file.to_lowercase();

    // Directory-level sensitive roots
    for comp in path.components() {
        if let std::path::Component::Normal(s) = comp {
            let c = s.to_string_lossy().to_lowercase();
            if c == ".ssh" {
                return Some(".ssh directory");
            }
            if c == ".aws" {
                return Some(".aws directory");
            }
            if c == ".gnupg" {
                return Some(".gnupg directory");
            }
        }
    }

    // Common secret-like files (deny-by-default unless explicitly allowed).
    if lower == ".env" {
        return Some(".env file");
    }
    if lower.starts_with(".env.") {
        let allow_suffixes = [".example", ".sample", ".template", ".dist", ".defaults"];
        if allow_suffixes.iter().any(|s| lower.ends_with(s)) {
            return None;
        }
        return Some(".env.* file");
    }

    if matches!(
        lower.as_str(),
        "id_rsa"
            | "id_ed25519"
            | "id_ecdsa"
            | "id_dsa"
            | "authorized_keys"
            | "known_hosts"
            | ".npmrc"
            | ".netrc"
            | ".pypirc"
            | ".dockerconfigjson"
            | "credentials.json"
            | "secrets.json"
            | "secrets.yaml"
            | "secrets.yml"
            | "keystore.jks"
            | "truststore.jks"
            | ".htpasswd"
            | "shadow"
            | "master.key"
    ) {
        return Some("credential file");
    }

    if lower.starts_with("service-account") {
        let p = std::path::Path::new(&lower);
        if p.extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json") || ext.eq_ignore_ascii_case("key"))
        {
            return Some("service account key");
        }
    }

    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let secret_exts = ["pem", "key", "p12", "pfx", "kdbx"];
    if secret_exts.iter().any(|e| ext.eq_ignore_ascii_case(e)) {
        return Some("secret key material");
    }

    // AWS credentials file (often inside .aws/)
    if lower == "credentials" && path.to_string_lossy().to_lowercase().contains("/.aws/") {
        return Some("aws credentials");
    }

    None
}

pub(crate) fn check_secret_path_for_tool(
    tool: &str,
    path: &Path,
) -> Result<Option<String>, String> {
    let role_name = roles::active_role_name();
    let role = roles::active_role();
    let mode = boundary_mode_effective(&role);

    let Some(reason) = is_secret_like(path) else {
        return Ok(None);
    };

    if role.io.allow_secret_paths {
        return Ok(None);
    }

    let msg = format!(
        "[I/O BOUNDARY] Secret-like path detected ({reason}): {}.\n\
Role: {role_name}. To allow: switch role to 'admin' or set io.allow_secret_paths=true in the active role.",
        path.display()
    );
    events::emit_policy_violation(&role_name, tool, &msg);

    match mode {
        BoundaryMode::Enforce => Err(format!("ERROR: {msg}")),
        BoundaryMode::Warn => {
            if crate::core::protocol::meta_visible() {
                Ok(Some(format!("[BOUNDARY WARNING] {msg}")))
            } else {
                Ok(None)
            }
        }
    }
}

pub(crate) fn jail_and_check_path(
    tool: &str,
    candidate: &Path,
    jail_root: &Path,
) -> Result<(PathBuf, Option<String>), String> {
    let role_name = roles::active_role_name();
    let jailed = pathjail::jail_path(candidate, jail_root).map_err(|e| {
        // Only a real jail escape is a security event. A path that simply doesn't exist
        // (stale graph entry, removed file) is benign — emitting a policy violation for it
        // spams the event feed and mislabels missing files as denials.
        if !matches!(
            e,
            crate::core::error::PathJailError::NoExistingAncestor { .. }
        ) {
            let msg = format!("pathjail denied: {} ({e})", candidate.display());
            events::emit_policy_violation(&role_name, tool, &msg);
        }
        e.to_string()
    })?;
    let warning = check_secret_path_for_tool(tool, &jailed)?;
    Ok((jailed, warning))
}

pub(crate) fn ensure_ignore_gitignore_allowed(tool: &str) -> Result<(), String> {
    let role_name = roles::active_role_name();
    let role = roles::active_role();
    if role.io.allow_ignore_gitignore {
        return Ok(());
    }
    let msg = format!(
        "[I/O BOUNDARY] ignore_gitignore requires explicit policy.\n\
Role '{role_name}' does not allow scanning .gitignore'd paths. \
An agent cannot escalate to a privileged role at runtime, so configure this where lean-ctx starts:\n\
- set LEAN_CTX_ROLE=admin, or\n\
- add `io.allow_ignore_gitignore = true` to a role file (~/.lean-ctx/roles/<name>.toml), then select it via LEAN_CTX_ROLE.\n\
Docs: https://leanctx.com/docs/security/#ignore-gitignore"
    );
    events::emit_policy_violation(&role_name, tool, &msg);
    Err(format!("ERROR: {msg}"))
}

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

    #[test]
    fn regulated_role_forces_redaction_when_config_disabled() {
        let mut config = crate::core::config::SecretDetectionConfig {
            redact: false,
            custom_patterns: vec!["TOP_SECRET".to_string()],
            ..Default::default()
        };
        config.redact = redact_for_role(config.redact, "regulated");

        let (content, matches) = secret_detection::scan_and_redact("token=TOP_SECRET", &config);

        assert!(!matches.is_empty());
        assert_eq!(content, "token=[REDACTED:custom_pattern]");
    }

    #[cfg(unix)]
    #[test]
    fn nofollow_rejects_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.txt");
        std::fs::write(&real, "secret").unwrap();
        let link = dir.path().join("link.txt");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let result = read_file_nofollow(&link.to_string_lossy());
        assert!(result.is_err());
    }

    #[test]
    fn nofollow_reads_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("regular.txt");
        std::fs::write(&file, "hello").unwrap();
        let content = read_file_nofollow(&file.to_string_lossy()).unwrap();
        assert_eq!(content, "hello");
    }

    #[test]
    fn env_is_secret_like() {
        assert_eq!(is_secret_like(Path::new(".env")), Some(".env file"));
        assert_eq!(is_secret_like(Path::new(".env.local")), Some(".env.* file"));
        assert_eq!(is_secret_like(Path::new(".env.example")), None);
    }

    #[test]
    fn key_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("key.pem")),
            Some("secret key material")
        );
        assert_eq!(
            is_secret_like(Path::new("cert.KEY")),
            Some("secret key material")
        );
    }

    #[test]
    fn credentials_json_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("credentials.json")),
            Some("credential file")
        );
        assert_eq!(
            is_secret_like(Path::new("secrets.yaml")),
            Some("credential file")
        );
    }

    #[test]
    fn service_account_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("service-account.json")),
            Some("service account key")
        );
        assert_eq!(
            is_secret_like(Path::new("service-account-prod.key")),
            Some("service account key")
        );
    }

    #[test]
    fn htpasswd_and_shadow_are_secret_like() {
        assert_eq!(
            is_secret_like(Path::new(".htpasswd")),
            Some("credential file")
        );
        assert_eq!(is_secret_like(Path::new("shadow")), Some("credential file"));
    }

    // The CLI full-read path (`cli_cache::check_and_read`) reads through THIS
    // `read_file_lossy`, not the ctx_read one — both must strip the UTF-8 BOM
    // or the CLI leaks it while the MCP path doesn't (limitations doc #11).
    #[test]
    fn read_file_lossy_strips_utf8_bom() {
        let p = std::env::temp_dir().join("lean_ctx_io_bom_test.txt");
        std::fs::write(&p, b"\xEF\xBB\xBFhello\n").unwrap();
        let s = read_file_lossy(p.to_str().unwrap()).unwrap();
        let _ = std::fs::remove_file(&p);
        assert!(!s.starts_with('\u{feff}'), "BOM must be stripped");
        assert!(s.starts_with("hello"));
    }
}