lean-ctx 3.12.3

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported 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
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx <command> --help` must describe the command, never run it (#1906).
//!
//! Most handlers never looked at `--help`: `secure --help` rewrote the config,
//! `proof --help` wrote proof artifacts, `skillify --help` generated rules,
//! `upgrade --help` installed a release. Instead of teaching ~100 handlers the
//! flag one by one, the dispatcher answers it centrally from the `help all`
//! reference — the single place every command is documented — and only hands
//! `--help` to handlers whose own help is verified to be side-effect free.
//!
//! Every dispatcher arm is listed in exactly one of [`SELF_HELP`], [`EXEMPT`]
//! or [`GUARDED`]; a unit test parses `mod.rs` so a new command cannot slip
//! through unclassified.

use super::help::full_help_text;

/// Arms whose handler prints real usage for a leading `--help`/`-h` and exits
/// 0 without touching disk (covered by the `cli_help` integration test).
/// `--help` anywhere later (`index build --help`) still goes to the guard,
/// because sub-actions are not all help-aware.
const SELF_HELP: &[&[&str]] = &[
    &["autopilot"],
    &["spend"],
    &["savings"],
    &["output-savings", "output_savings"],
    &["value-report", "value_report"],
    &["evidence-export"],
    &["evidence"],
    &["compliance"],
    &["shadow"],
    &["finops"],
    &["roi"],
    &["token-report", "report-tokens"],
    &["policy"],
    &["addon", "addons"],
    &["enable-gpu", "gpu"],
    &["rules"],
    &["value"],
    &["prompt-segment"],
    &["statusline"],
    &["inspect"],
    &["gateway"],
    &["claude-mod", "claude_mod"],
    &["agent"],
    &["activity"],
    &["bus"],
    &["presence"],
    &["capabilities"],
    &["client"],
    &["agents"],
    &["instructions"],
    &["index"],
    &["semantic-search", "search-code"],
    &["explore"],
    &["cockpit", "dashboard"],
    &["provider"],
    &["serve"],
    &["proxy"],
    &["daemon"],
    &["init"],
    &["setup"],
    &["onboard"],
    &["wrap"],
    &["unwrap"],
    &["status"],
    &["ocla"],
    &["import"],
    &["checkpoints"],
    &["knowledge"],
    &["tasks"],
    &["docs"],
    &["kit", "kits"],
    &["skillify"],
    &["summary"],
    &["benchmark"],
    &["security"],
    &["trust"],
    &["untrust"],
    &["update", "--self-update"],
    &["doctor"],
    &["harden"],
    &["gotchas", "bugs"],
    &["uninstall"],
    &["cheat", "cheatsheet", "cheat-sheet"],
    &["telemetry"],
    &["hive"],
];

/// Arms the guard never intercepts: passthroughs whose arguments belong to the
/// wrapped command, the help/version entry points themselves, the completion
/// engine, and removed commands that only print a pointer to the replacement.
const EXEMPT: &[&[&str]] = &[
    &["-c", "exec"],
    &["-t", "--track"],
    &["raw", "bypass"],
    &["help"],
    &["--help", "-h"],
    &["--version", "-V"],
    &["__complete"],
    &["wrapped"],
    &["plugin", "plugins"],
    &["watch"],
];

/// Arms answered from the `help all` reference. Each needs at least one
/// reference line whose leading word is one of its names.
const GUARDED: &[&[&str]] = &[
    // Their bare form reads live state, which takes a lock / touches the
    // project index, so `--help` must never reach the handler.
    &["cache"],
    &["terse", "compression"],
    &["migrate"],
    // Launches an interactive Codex session; `--help` must never start it.
    &["codex-protected"],
    &["shell", "--shell"],
    &["gain"],
    &["learning"],
    &["conformance", "selftest"],
    &["health"],
    &["triage"],
    &["scenario"],
    &["pack"],
    &["embeddings"],
    &["model"],
    &["proof"],
    &["git-trailer"],
    &["snapshot"],
    &["verify"],
    &["verify-cache", "cache-selftest"],
    &["audit"],
    &["repomap", "repo-map"],
    &["cep"],
    &["install"],
    &["bootstrap"],
    &["read"],
    &["call"],
    &["diff"],
    &["grep"],
    &["glob"],
    &["find"],
    &["ls"],
    &["deps"],
    &["discover"],
    &["engine"],
    &["ghost"],
    &["filter"],
    &["heatmap"],
    &["graph"],
    &["smells"],
    &["session"],
    &["ledger"],
    &["control", "context-control"],
    &["plan", "context-plan"],
    &["compile", "context-compile"],
    &["overview"],
    &["compress"],
    &["sessions", "session-store"],
    &["compact"],
    &["profile"],
    &["tools"],
    &["config"],
    &["allow"],
    &["allow-path"],
    &["project"],
    &["workspace"],
    &["yolo"],
    &["secure", "lockdown"],
    &["stats"],
    &["introspect"],
    &["theme"],
    &["tee"],
    &["slow-log"],
    &["debug-log"],
    &["editor-signal"],
    &["editor-session"],
    &["editor-bridge"],
    &["restart"],
    &["stop"],
    &["dev-install"],
    &["codesign-setup"],
    &["export-rules"],
    &["completions"],
    &["learn"],
    &["hook"],
    &["report-issue", "report"],
    &["safety-levels", "safety"],
    &["upgrade"],
    &["mcp"],
];

/// `help all` sections that describe something other than commands.
const NON_COMMAND_SECTIONS: &[&str] = &[
    "SHELL HOOK PATTERNS",
    "READ MODES:",
    "ENVIRONMENT:",
    "OPTIONS:",
    "TROUBLESHOOTING:",
];

/// [`SELF_HELP`] arms whose handler honours `--help` at *any* position with its
/// own, richer usage (`init --agent claude --help`, #1849 — covered by the
/// `init_help_safety_1849` integration test; `hive tasks --help` prints the
/// tasks usage, `hive worker --help` the hive one; `serve --port 9 --help`
/// prints every serve flag and starts nothing, `serve_args::parse`).
const SELF_HELP_ANYWHERE: &[&str] = &["init", "hive", "serve"];

fn group_of<'a>(table: &'a [&'a [&'a str]], cmd: &str) -> Option<&'a [&'a str]> {
    table.iter().copied().find(|group| group.contains(&cmd))
}

/// Arms whose arguments are operands — a search pattern, a path or tool
/// arguments — so a later `-h` may be data (`grep -h src` searches for `-h`).
/// Here `-h` means help only on its own. Every other arm treats `-h` before a
/// `--` like `--help`: `cache prune -h` printed nothing and pruned (#2230).
const DASH_H_OPERAND: &[&str] = &["read", "call", "diff", "grep", "glob", "find", "ls", "deps"];

fn wants_help(cmd: &str, rest: &[String]) -> bool {
    let mut flags = rest.iter().take_while(|a| *a != "--");
    if DASH_H_OPERAND.contains(&cmd) {
        flags.any(|a| a == "--help") || matches!(rest, [only] if only == "-h")
    } else {
        flags.any(|a| a == "--help" || a == "-h")
    }
}

/// Measurement and demo commands removed by the focus release, and the
/// research and evaluation commands removed from the engine afterwards.
const REMOVED_COMMANDS: &[&str] = &[
    "visualize",
    "demo",
    "calibrate",
    "benchmark-run",
    "bench-run",
    "pair",
    "quality-lab",
    "quality_lab",
    "eval",
    "measure",
    "prove",
];

/// Research and evaluation commands removed from the engine (2026-10-30).
const RESEARCH_COMMANDS: &[&str] = &["quality-lab", "quality_lab", "eval", "measure", "prove"];

/// The stderr message for a removed command; the dispatcher exits with 2.
pub(super) fn removed_notice(cmd: &str) -> Option<String> {
    REMOVED_COMMANDS.contains(&cmd).then(|| {
        if cmd == "pair" {
            return "lean-ctx: 'pair' was removed: remote pairing was never implemented and \
                    the command only listed installed agent CLIs. LeanCTX does not launch \
                    agents; see ctx_work_graph action=start (docs/migration/focus-2026-10.md)."
                .to_string();
        }
        if RESEARCH_COMMANDS.contains(&cmd) {
            return format!(
                "lean-ctx: '{cmd}' was removed: research and evaluation tooling is no longer \
                 part of the engine. Measured savings: `lean-ctx gain`; fixed context cost: \
                 `lean-ctx doctor overhead`."
            );
        }
        format!(
            "lean-ctx: '{cmd}' was removed with the focus release; use `lean-ctx gain`, \
             `lean-ctx benchmark`, `lean-ctx doctor` or `lean-ctx cockpit --export` \
             (HTML report) instead (docs/migration/focus-2026-10.md)."
        )
    })
}

/// `lean-ctx <cmd> --help` (or `-h`, see [`DASH_H_OPERAND`]) on any arm the
/// guard covers: a read-only request that must not create telemetry state or
/// show first-run notices either.
pub(super) fn is_help_request(cmd: &str, rest: &[String]) -> bool {
    wants_help(cmd, rest) && group_of(EXEMPT, cmd).is_none()
}

/// The usage text to print instead of running `cmd`, or `None` when the arm
/// should run as usual (no help requested, exempt, or self-helping handler).
pub(super) fn guarded_help(cmd: &str, rest: &[String]) -> Option<String> {
    if !wants_help(cmd, rest) || group_of(EXEMPT, cmd).is_some() {
        return None;
    }
    let leading_help = rest.first().is_some_and(|a| a == "--help" || a == "-h");
    if (leading_help || SELF_HELP_ANYWHERE.contains(&cmd)) && group_of(SELF_HELP, cmd).is_some() {
        return None;
    }
    let group = group_of(GUARDED, cmd)
        .or_else(|| group_of(SELF_HELP, cmd))
        .unwrap_or(&[]);
    let lines = reference_lines(&full_help_text(), group);
    if lines.is_empty() {
        // Unknown command: let the dispatcher's own "unknown command" path answer.
        return None;
    }
    Some(format!(
        "Usage (lean-ctx {cmd}):\n{}\n\nFull command reference: lean-ctx help all\n",
        lines.join("\n")
    ))
}

/// Reference lines (plus their indented continuation lines) whose leading word
/// — after an optional `lean-ctx ` prefix — names one of `names`.
fn reference_lines(help: &str, names: &[&str]) -> Vec<String> {
    let mut out = Vec::new();
    let mut in_commands = true;
    let mut matched = false;
    for line in help.lines() {
        if !line.starts_with(' ') && !line.is_empty() {
            in_commands = !NON_COMMAND_SECTIONS.iter().any(|s| line.starts_with(s));
            matched = false;
            continue;
        }
        if !in_commands {
            continue;
        }
        let trimmed = line.trim_start();
        if line.len() - trimmed.len() > 8 {
            if matched {
                out.push(line.to_string());
            }
            continue;
        }
        let word = trimmed
            .strip_prefix("lean-ctx ")
            .unwrap_or(trimmed)
            .split_whitespace()
            .next()
            .unwrap_or("");
        let word = word.split('|').next().unwrap_or(word);
        matched = names.contains(&word);
        if matched {
            out.push(line.to_string());
        }
    }
    out
}

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

    /// Every `"name" | "alias" =>` arm of the top-level dispatcher match.
    fn dispatcher_arms() -> Vec<Vec<String>> {
        let src = include_str!("mod.rs");
        let start = src
            .find("        match args[1].as_str() {")
            .expect("dispatcher match");
        let mut arms = Vec::new();
        for line in src[start..].lines().skip(1) {
            if line.starts_with("        }") {
                break;
            }
            let Some(head) = line.strip_prefix("            \"") else {
                continue;
            };
            let Some((names, _)) = head.split_once("=>") else {
                continue;
            };
            let names: Vec<String> = format!("\"{names}")
                .split('|')
                .map(|n| n.trim().trim_matches('"').to_string())
                .collect();
            arms.push(names);
        }
        arms
    }

    #[test]
    fn every_dispatcher_arm_is_classified_exactly_once() {
        let arms = dispatcher_arms();
        assert!(arms.len() > 100, "parser found only {} arms", arms.len());
        let mut seen: BTreeMap<Vec<String>, usize> = BTreeMap::new();
        for group in SELF_HELP.iter().chain(EXEMPT).chain(GUARDED) {
            let key: Vec<String> = group.iter().map(|s| (*s).to_string()).collect();
            *seen.entry(key).or_default() += 1;
        }
        for arm in &arms {
            assert_eq!(
                seen.get(arm),
                Some(&1),
                "dispatcher arm {arm:?} must appear in exactly one of SELF_HELP / EXEMPT / GUARDED"
            );
        }
        assert_eq!(
            seen.len(),
            arms.len(),
            "a SELF_HELP / EXEMPT / GUARDED entry names no dispatcher arm"
        );
    }

    #[test]
    fn every_non_exempt_arm_has_reference_lines() {
        let help = full_help_text();
        for group in SELF_HELP.iter().chain(GUARDED) {
            // `hive` prints its own help and stays out of `help all` until
            // the release switch is on (3.12.1).
            if group[0] == "hive" && !lean_ctx_hive::HIVE_AVAILABLE {
                continue;
            }
            assert!(
                !reference_lines(&help, group).is_empty(),
                "`help all` has no line for {group:?}; `lean-ctx {} --help` would print nothing",
                group[0]
            );
        }
    }

    fn args(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn guarded_commands_answer_help_without_running() {
        let out = guarded_help("secure", &args(&["--help"])).expect("guarded");
        assert!(out.starts_with("Usage (lean-ctx secure):"));
        assert!(out.contains("Restore secure defaults"));
        assert!(guarded_help("lockdown", &args(&["-h"])).is_some());
        assert!(guarded_help("proof", &args(&["--format", "json", "--help"])).is_some());
    }

    #[test]
    fn continuation_lines_follow_their_command() {
        let out = guarded_help("uninstall", &args(&["--keep-config", "--help"])).unwrap();
        assert!(out.contains("--dry-run previews without changing anything"));
        assert!(!out.contains("SHELL HOOK"));
    }

    #[test]
    fn self_help_handlers_keep_a_leading_help_flag() {
        assert_eq!(guarded_help("doctor", &args(&["--help"])), None);
        assert_eq!(guarded_help("doctor", &args(&["-h"])), None);
        // A later `--help` is not guaranteed to reach a help-aware code path.
        assert!(guarded_help("index", &args(&["build", "--help"])).is_some());
        // ...except for handlers verified to honour it anywhere (#1849).
        assert_eq!(
            guarded_help("init", &args(&["--agent", "claude", "--help"])),
            None
        );
    }

    #[test]
    // Named so it avoids the `gh[ops]_` token prefixes the history secret
    // rule (SEC001) matches on.
    fn passthrough_and_non_help_invocations_are_untouched() {
        assert_eq!(guarded_help("-c", &args(&["ls", "--help"])), None);
        assert_eq!(guarded_help("raw", &args(&["cargo", "--help"])), None);
        assert_eq!(guarded_help("grep", &args(&["fn", "src"])), None);
        assert_eq!(guarded_help("grep", &args(&["--", "--help"])), None);
        // For operand-taking arms `-h` is only help on its own; elsewhere it
        // may be a pattern or path.
        assert_eq!(guarded_help("ls", &args(&["-h", "src"])), None);
        assert_eq!(guarded_help("grep", &args(&["-h", "src"])), None);
        assert_eq!(guarded_help("read", &args(&["src/main.rs", "-h"])), None);
        assert!(guarded_help("grep", &args(&["-h"])).is_some());
    }

    /// `cache prune -h` pruned indexes and knowledge stores instead of
    /// printing help, because `-h` counted only as the lone argument (#2230).
    #[test]
    fn dash_h_after_a_subcommand_prints_help_2230() {
        for sub in ["prune", "clear", "reset", "invalidate"] {
            let rest = args(&[sub, "-h"]);
            let out = guarded_help("cache", &rest).unwrap_or_else(|| panic!("cache {sub} -h"));
            assert!(out.starts_with("Usage (lean-ctx cache):"), "{out}");
            assert!(is_help_request("cache", &rest), "{sub}");
        }
        // Self-help arms answer a later `-h` from the guard, like `--help`.
        assert!(guarded_help("knowledge", &args(&["forget", "-h"])).is_some());
        // After `--` it is an operand: `cache invalidate -- -h` names a file.
        let operand = args(&["invalidate", "--", "-h"]);
        assert_eq!(guarded_help("cache", &operand), None);
        assert!(!is_help_request("cache", &operand));
    }

    #[test]
    fn reference_lines_skip_non_command_sections() {
        // `grep` appears under SHELL HOOK PATTERNS ("utils curl, grep/rg");
        // only the command reference and examples may be returned.
        let lines = reference_lines(&full_help_text(), &["grep"]);
        assert!(
            lines.iter().any(|l| l.contains("grep <pattern>")),
            "{lines:?}"
        );
        assert!(lines.iter().all(|l| !l.contains("grep/rg")), "{lines:?}");
    }

    /// `hive <sub> --help` reaches the hive handler, which prints the
    /// subcommand's own usage, never the generic reference lines.
    #[test]
    fn hive_subcommand_help_is_answered_by_hive() {
        for sub in ["tasks", "worker"] {
            let rest = vec![sub.to_owned(), "--help".to_owned()];
            assert_eq!(guarded_help("hive", &rest), None, "{sub}");
        }
    }
}