lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
pub(super) fn effective_allowlist() -> Vec<String> {
    filter_valid_entries(raw_allowlist_entries())
}

/// The same union `effective_allowlist()` builds, before `*`-placement
/// filtering — shared with the invalid-entry and upgrade-advisory doctor
/// checks, which need to see entries `effective_allowlist()` would drop.
fn raw_allowlist_entries() -> Vec<String> {
    use crate::core::config::shell_policy;
    // LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE completely replaces the config (test
    // and debug builds only; see `config::shell_policy`).
    if let Some(ov) = shell_policy::env("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE") {
        return ov
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
    }
    let cfg = shell_policy::config();
    let mut list = cfg.shell_allowlist.clone();
    // `shell_allowlist_extra` is purely additive (written by `lean-ctx allow <cmd>`),
    // so users can permit a command without nuking the built-in defaults. It only
    // matters in restricted mode — when the base list is empty all commands pass anyway.
    if !list.is_empty() {
        for entry in &cfg.shell_allowlist_extra {
            if !entry.is_empty() && !list.contains(entry) {
                list.push(entry.clone());
            }
        }
    }
    if let Some(env_val) = shell_policy::env("LEAN_CTX_SHELL_ALLOWLIST") {
        for entry in env_val
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
        {
            if !list.contains(&entry) {
                list.push(entry);
            }
        }
    }
    list
}

/// Public accessor: entries the effective allowlist silently dropped for
/// invalid `*` placement (§4 of the design doc). Used by `lean-ctx doctor`
/// to surface a count, and by `--fix` to know which raw config lines to
/// comment out.
#[must_use]
pub fn invalid_allowlist_entries_pub() -> Vec<String> {
    raw_allowlist_entries()
        .into_iter()
        .filter(|e| !is_valid_allowlist_entry(e))
        .collect()
}

/// Public accessor: multi-word entries with no trailing `*` — their meaning
/// changed under subcommand scoping (now exact-match only, previously
/// "whole binary"). Used by the `lean-ctx doctor` upgrade advisory (§2 of
/// the design doc). Always empty when `shell_allowlist_subcommand_scoping =
/// false`, since those entries' meaning didn't change under the compat path.
#[must_use]
pub fn narrowed_allowlist_entries_pub() -> Vec<String> {
    if !crate::core::config::shell_policy::config().shell_allowlist_subcommand_scoping {
        return Vec::new();
    }
    raw_allowlist_entries()
        .into_iter()
        .filter(|e| is_valid_allowlist_entry(e))
        .filter(|e| {
            let words: Vec<&str> = e.split_whitespace().collect();
            words.len() > 1 && words.last() != Some(&"*")
        })
        .collect()
}

/// §2 "Shadowing warnings": is `a` made useless by a different entry already
/// in `entries`? Entry A is shadowed by B when B matches every command A
/// matches: B is a single word equal to A's first word, or B ends in `*` and
/// B's words before the `*` are a leading run of A's words (ignoring A's own
/// trailing `*`). Returns the first covering entry, in list order. Shared by
/// `lean-ctx allow` (write-time warning) and `lean-ctx doctor` (read-only
/// advisory) so the rule can't drift between the two.
#[must_use]
pub fn shadowing_entry(entries: &[String], a: &str) -> Option<String> {
    let a_words: Vec<&str> = a.split_whitespace().collect();
    let a_prefix: &[&str] = if a_words.last() == Some(&"*") {
        &a_words[..a_words.len() - 1]
    } else {
        &a_words
    };
    entries
        .iter()
        .find(|b| {
            if b.as_str() == a {
                return false;
            }
            let b_words: Vec<&str> = b.split_whitespace().collect();
            if b_words.len() == 1 {
                b_words.first() == a_words.first()
            } else if b_words.last() == Some(&"*") {
                let b_prefix = &b_words[..b_words.len() - 1];
                b_prefix.len() <= a_prefix.len() && a_prefix.starts_with(b_prefix)
            } else {
                false
            }
        })
        .cloned()
}

/// All shadowed entries in `entries`, paired with the entry that covers each
/// one — used by the `lean-ctx doctor` advisory (§2).
#[must_use]
pub fn shadowed_allowlist_entries_pub(entries: &[String]) -> Vec<(String, String)> {
    entries
        .iter()
        .filter_map(|a| shadowing_entry(entries, a).map(|b| (a.clone(), b)))
        .collect()
}

/// §4 of the design doc: an entry's only valid `*` placement is a single
/// trailing token. Bare `*`, an embedded `*`, or more than one `*` are
/// invalid.
pub fn is_valid_allowlist_entry(entry: &str) -> bool {
    let words: Vec<&str> = entry.split_whitespace().collect();
    match words.iter().filter(|w| **w == "*").count() {
        0 => true,
        1 => words.len() > 1 && words.last() == Some(&"*"),
        _ => false,
    }
}

/// Drops invalid entries rather than failing closed on the whole allowlist
/// (§4): removing one allow-entry can only make matching *more*
/// restrictive, never less, so this is safe by construction — mirrors the
/// `ShellSecurity::resolve()` precedent (an unknown value falls back to
/// enforce, never to open).
fn filter_valid_entries(entries: Vec<String>) -> Vec<String> {
    entries
        .into_iter()
        .filter(|entry| {
            let valid = is_valid_allowlist_entry(entry);
            if !valid {
                tracing::warn!(
                    "[shell_allowlist] dropping invalid allowlist entry '{entry}': `*` must be \
                     the single trailing token, not embedded, bare, or repeated"
                );
            }
            valid
        })
        .collect()
}

/// Could this token plausibly be an executable name?
///
/// Deliberately permissive — the point is to catch obvious scanner debris
/// (unbalanced parens, quotes, `$`, `&`, embedded spaces), not to validate
/// against the filesystem. A name that would need quoting to type is not a name
/// the user should be told to allowlist.
pub(super) fn is_plausible_command_name(base: &str) -> bool {
    if base.is_empty() {
        return false;
    }
    !base.chars().any(|c| {
        c.is_whitespace() || matches!(c, '(' | ')' | '"' | '\'' | '$' | '&' | '|' | ';' | '`')
    })
}

/// Builds the actionable, self-diagnosing message shown when a command's base binary
/// is not in the allowlist. Unlike a bare "not allowed" string, it tells the user
/// (1) the exact additive fix, (2) the real config path the MCP server reads, and
/// (3) — crucially — whether their `config.toml` silently failed to parse (in which
/// case lean-ctx is on defaults, which is the usual reason an allowlist edit "did
/// nothing"). That last signal is otherwise invisible over an MCP/stdio transport.
pub(super) fn allowlist_block_message(base: &str, tokens: &[String], entries: &[String]) -> String {
    let cfg_path = crate::core::config::shell_policy::config_path().map_or_else(
        || "~/.lean-ctx/config.toml".to_string(),
        |p| p.display().to_string(),
    );

    // #1814: a `$var` command word is a *correct* split, not a mis-split — the
    // variable genuinely is the command, and the allowlist cannot see what it
    // expands to at run time. Sending that caller to file a mis-split bug wastes
    // their time and ours, and "quote the fragment differently" cannot help:
    // no quoting makes a variable command allowable. Say what actually works.
    if let Some(name) = base.strip_prefix('$') {
        let hint = name.trim_start_matches('{').trim_end_matches('}');
        return format!(
            "[BLOCKED — DO NOT RETRY] '{base}' expands to the command name at run time, so \
             the allowlist cannot see which command would run.\n\
             Write the command literally instead (e.g. `echo hi`, `.venv/bin/python -c ...`) — \
             that is the form the allowlist can gate.\n\
             Do NOT run `lean-ctx allow {hint}`; it would allowlist the variable's name, not \
             the command.\n\
             Config in effect: {cfg_path}"
        );
    }

    // A base that cannot be a command name means the scanner mis-split the line,
    // not that the user needs to allow something. Printing
    // `lean-ctx allow print(urllib.parse.quote(sys.argv[1],safe=))` — a real
    // example from GH #1646 — invites the reader to copy a command that cannot
    // work and hides the actual fault. Say which it is.
    if !is_plausible_command_name(base) {
        return format!(
            "[BLOCKED] '{base}' is not in the shell allowlist — but it does not look like a \
             command name, which means lean-ctx split your command line wrongly rather than \
             finding a command to gate.\n\
             Do NOT run `lean-ctx allow` on it; that would allowlist a fragment.\n\
             Quote the fragment differently if you can, and please report the original command \
             at https://github.com/yvgude/lean-ctx/issues — a mis-split is a bug in lean-ctx.\n\
             Config in effect: {cfg_path}"
        );
    }

    // A nested shell (`bash -c '…'`, `sh script.sh`) is the most common block
    // agents retry: the command already runs in a shell, so the wrapper is
    // redundant — and allowlisting the shell would let any script through.
    if matches!(base, "sh" | "bash" | "zsh" | "dash" | "ksh") {
        return format!(
            "[BLOCKED — DO NOT RETRY] A nested '{base}' is not run: the command already \
             executes in a shell, and a nested shell would hide what it runs from the \
             allowlist.\n\
             Do this instead: drop the `{base} -c` wrapper and pass the inner command \
             directly (pipes, `&&`, loops and functions all work); for a script file, run \
             the commands it contains, or allow that one script deliberately.\n\
             Do NOT run `lean-ctx allow {base}`: it would admit every script, not this \
             command.\n\
             Config in effect: {cfg_path}"
        );
    }

    let mut msg = format!(
        "[BLOCKED — DO NOT RETRY] '{base}' is not in the shell allowlist. \
         This is a permanent restriction, not a transient error.\n\
         Fix (additive, keeps the defaults): run  lean-ctx allow {base}\n\
         Config in effect: {cfg_path}\n\
         Or disable the allowlist entirely: set  shell_allowlist = []\n\
         Or turn off all shell gating (you own the risk): set  shell_security = \"off\"  \
         in that file — compression still applies.\n\
         Do NOT reroute through ctx_execute(language=\"shell\"): both tools enforce the same \
         policy. Allow the command explicitly or change shell_security deliberately."
    );

    if let Some(detail) = closest_entry_detail(tokens, entries) {
        msg.push_str(&detail);
    }

    if crate::core::config::cloud_infra_commands().contains(&base) {
        msg.push_str(
            "\nNote: cloud/infra CLIs (terraform, kubectl, aws, …) are deliberately \
             excluded from the defaults — they mutate remote infrastructure with \
             ambient credentials. Opting in is a deliberate user decision.",
        );
    }

    // The notes below describe `Config::load`'s file; a release build's gate
    // reads only the file named above (`config::shell_policy`).
    let ambient = !crate::core::config::shell_policy::pinned();
    if ambient && let Some(parse_err) = crate::core::config::last_config_parse_error() {
        msg.push_str(&format!(
            "\n\n⚠ Your config.toml currently FAILS to parse, so lean-ctx is running on the \
             built-in defaults — this is almost certainly why editing the allowlist had no \
             effect. Fix the TOML error below, then retry:\n  {parse_err}\n  File: {cfg_path}"
        ));
    } else if ambient && let Some(missing) = crate::core::config::Config::missing_config_path() {
        // The resolved config doesn't exist → lean-ctx is on defaults. An edit
        // made to a config.toml in a different dir (XDG vs legacy ~/.lean-ctx) or
        // under a sandboxed/container HOME is never read — say so over MCP (#540).
        msg.push_str(&format!(
            "\n\n⚠ No config file exists at {} — lean-ctx is running on built-in defaults. \
             If you added the command to a config.toml in a DIFFERENT location (XDG \
             ~/.config/lean-ctx vs legacy ~/.lean-ctx, or your MCP client launches lean-ctx \
             in a sandbox/container with a different HOME), the runtime never reads it. \
             `lean-ctx doctor` prints the path actually in effect; pin it with \
             LEAN_CTX_CONFIG_DIR.",
            missing.display()
        ));
    }

    // A project-local `shell_allowlist`/`shell_allowlist_extra` is silently
    // withheld for an untrusted workspace; surface that here so the edit's
    // no-op reason isn't buried in an MCP-invisible stderr warning (#540).
    if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
        msg.push_str("\n\n⚠ ");
        msg.push_str(&notice);
    }

    msg
}

/// §6 of the design doc: names the closest matching allowlist entry and
/// where the command's tokens diverge from it, so an LLM agent can
/// self-correct without a human round-trip. Only fires when at least one
/// entry shares the base binary — otherwise "not in the shell allowlist"
/// already says enough. Longest common token prefix; ties resolve to the
/// first entry in list order (same convention as `levenshtein::closest()`).
fn closest_entry_detail(tokens: &[String], entries: &[String]) -> Option<String> {
    let base = tokens.first()?.as_str();
    let mut best: Option<(&str, usize)> = None;
    for entry in entries {
        let words: Vec<&str> = entry.split_whitespace().collect();
        if words.first() != Some(&base) {
            continue;
        }
        let shared = tokens
            .iter()
            .zip(words.iter())
            .take_while(|(t, w)| t.as_str() == **w)
            .count();
        if best.is_none_or(|(_, len)| shared > len) {
            best = Some((entry.as_str(), shared));
        }
    }
    let (entry, shared) = best?;
    let entry_words: Vec<&str> = entry.split_whitespace().collect();
    let diverges_at = entry_words.get(shared).copied();
    let got = tokens.get(shared).map(String::as_str);
    let mut detail = match (diverges_at, got) {
        (Some(expected), Some(got)) => {
            format!("\n(closest entry '{entry}' requires subcommand '{expected}', got '{got}')")
        }
        _ => format!("\n(closest entry '{entry}')"),
    };
    if got.is_some_and(|g| g.starts_with('-')) {
        detail.push_str(
            "\nGlobal options before the subcommand are not matched. Run \
             `cd <dir> && <cmd>` instead, or add an explicit allowlist entry.",
        );
    }
    Some(detail)
}
/// Public accessor: the fully-resolved allowlist actually enforced by the MCP tools
/// (base `shell_allowlist` + additive `shell_allowlist_extra` + env), deduplicated.
/// Empty means blocklist-only mode (all commands pass). Used by `lean-ctx allow`
/// and `lean-ctx doctor` to show users exactly what the runtime sees.
#[must_use]
pub fn effective_allowlist_pub() -> Vec<String> {
    effective_allowlist()
}

/// GH #1466: Check whether the user has explicitly allowed an interpreter for
/// inline/heredoc use in Claude Code's own permission system.
///
/// Reads `permissions.allow` from both global (`~/.claude/settings.json`) and
/// project-local (`.claude/settings.local.json`) settings. Entries like
/// `Bash(python3:*)` or `Bash(python3:)` grant the interpreter `python3`
/// inline-execution rights, bypassing the heredoc/eval-flag block.
///
/// Cached per-process to avoid re-reading settings on every shell invocation.
pub(super) fn claude_allows_interpreter_inline(interpreter: &str) -> bool {
    use std::sync::OnceLock;

    static CACHE: OnceLock<Vec<String>> = OnceLock::new();

    let allowed = CACHE.get_or_init(|| {
        let mut interpreters = Vec::new();
        collect_claude_bash_permissions(&mut interpreters);
        interpreters
    });

    allowed.iter().any(|a| a == interpreter)
}

/// Parse `Bash(<cmd>:...)` entries from Claude's `permissions.allow` arrays.
fn collect_claude_bash_permissions(out: &mut Vec<String>) {
    let paths = claude_settings_paths();
    for path in &paths {
        if let Ok(content) = std::fs::read_to_string(path) {
            if let Ok(json) = crate::core::jsonc::parse_jsonc(&content) {
                extract_bash_interpreters(&json, out);
            }
        }
    }
}

/// Returns candidate Claude settings paths (global + project-local).
fn claude_settings_paths() -> Vec<std::path::PathBuf> {
    let mut paths = Vec::with_capacity(2);

    if let Some(home) = crate::core::config::shell_policy::settings_home() {
        paths.push(home.join(".claude").join("settings.json"));
    }

    if let Ok(cwd) = std::env::current_dir() {
        paths.push(cwd.join(".claude").join("settings.local.json"));
    }

    paths
}

/// Extract interpreter names from `Bash(<interpreter>:...)` permission entries.
pub(super) fn extract_bash_interpreters(json: &serde_json::Value, out: &mut Vec<String>) {
    let allow = json
        .pointer("/permissions/allow")
        .and_then(|v| v.as_array());

    let Some(arr) = allow else { return };

    for entry in arr {
        let Some(s) = entry.as_str() else { continue };
        if let Some(inner) = parse_bash_permission(s) {
            if !inner.is_empty() && !out.contains(&inner) {
                out.push(inner);
            }
        }
    }
}

/// Parse a Claude permission entry like `Bash(python3:*)` → `Some("python3")`.
/// Accepted formats: `Bash(cmd:)`, `Bash(cmd:*)`, `Bash(cmd:<anything>)`.
pub(super) fn parse_bash_permission(entry: &str) -> Option<String> {
    let rest = entry.strip_prefix("Bash(")?;
    let rest = rest.strip_suffix(')')?;
    let colon_pos = rest.find(':')?;
    let cmd = &rest[..colon_pos];
    if cmd.is_empty() {
        return None;
    }
    let base = cmd.rsplit('/').next().unwrap_or(cmd);
    Some(base.to_string())
}

#[cfg(test)]
mod tests {
    use super::{allowlist_block_message, shadowing_entry};

    /// §2 of the design doc: pure-helper shadowing rule, all five agreed cases.
    #[test]
    fn shadowing_rule_matches_design_doc_cases() {
        let entries = |a: &str, b: &str| vec![a.to_string(), b.to_string()];

        assert_eq!(
            shadowing_entry(&entries("git status", "git"), "git status"),
            Some("git".to_string()),
            "a single-word entry shadows any multi-word entry sharing its first word"
        );
        assert_eq!(
            shadowing_entry(&entries("git status -s", "git status *"), "git status -s"),
            Some("git status *".to_string()),
            "a trailing-* entry shadows a longer exact entry sharing its prefix"
        );
        assert_eq!(
            shadowing_entry(&entries("git status", "git status *"), "git status"),
            Some("git status *".to_string()),
            "a trailing-* entry shadows the identical exact entry"
        );
        assert_eq!(
            shadowing_entry(&entries("git log", "git status *"), "git log"),
            None,
            "different subcommands must not shadow each other"
        );
        assert_eq!(
            shadowing_entry(&entries("git status *", "git status"), "git status *"),
            None,
            "an exact entry must not shadow a broader trailing-* entry"
        );
    }

    /// #1814: a `$var` command word is a *correct* split, not a mis-split. The
    /// old text asked the caller to file a bug for intended behaviour and
    /// suggested re-quoting, which cannot help — no quoting makes a variable
    /// command gateable.
    #[test]
    fn variable_command_word_explains_expansion_not_a_parser_bug() {
        for base in ["$X", "$PY", "${CMD}"] {
            let msg = allowlist_block_message(base, &[], &[]);
            assert!(
                msg.contains("expands to the command name at run time"),
                "{base}: must explain expansion, got: {msg}"
            );
            assert!(
                !msg.contains("mis-split"),
                "{base}: must not blame the parser, got: {msg}"
            );
            assert!(
                !msg.contains("github.com/yvgude/lean-ctx/issues"),
                "{base}: must not request a bug report for intended behaviour"
            );
        }
    }

    /// The genuine mis-split guidance must survive for tokens that really are
    /// not command names — that is what #1646 added it for.
    #[test]
    fn genuine_mis_splits_still_ask_for_a_report() {
        let msg = allowlist_block_message("print(urllib.parse.quote(sys.argv[1],safe=))", &[], &[]);
        assert!(msg.contains("mis-split"), "got: {msg}");
        assert!(msg.contains("github.com/yvgude/lean-ctx/issues"));
    }

    /// An ordinary unknown command keeps the actionable `lean-ctx allow` path.
    #[test]
    fn ordinary_command_still_offers_allow() {
        let msg = allowlist_block_message("ncat", &[], &[]);
        assert!(msg.contains("lean-ctx allow ncat"), "got: {msg}");
        assert!(!msg.contains("expands to the command name"));
    }

    /// A nested shell is redundant, and allowing it would admit every script:
    /// the message says to drop the wrapper and never to allow the shell.
    #[test]
    fn nested_shell_says_drop_the_wrapper_not_allow_it() {
        for shell in ["bash", "sh", "zsh"] {
            let msg = allowlist_block_message(shell, &[], &[]);
            assert!(
                msg.contains(&format!("drop the `{shell} -c` wrapper")),
                "got: {msg}"
            );
            assert!(
                msg.contains(&format!("Do NOT run `lean-ctx allow {shell}`")),
                "got: {msg}"
            );
            assert!(!msg.contains("Fix (additive"), "got: {msg}");
        }
    }
}