use super::help::full_help_text;
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"],
&["computer"],
&["claude-mod", "claude_mod"],
&["agent"],
&["activity"],
&["bus"],
&["presence"],
&["capabilities"],
&["archive"],
&["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"],
&["cloud"],
&["models"],
&["run"],
];
const EXEMPT: &[&[&str]] = &[
&["-c", "exec"],
&["-t", "--track"],
&["raw", "bypass"],
&["help"],
&["--help", "-h"],
&["--version", "-V"],
&["__complete"],
&["wrapped"],
&["plugin", "plugins"],
&["watch"],
];
const GUARDED: &[&[&str]] = &[
&["cache"],
&["terse", "compression"],
&["migrate"],
&["codex-protected"],
&["decisions"],
&["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"],
&["hotspots"],
&["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"],
];
const NON_COMMAND_SECTIONS: &[&str] = &[
"SHELL HOOK PATTERNS",
"READ MODES:",
"ENVIRONMENT:",
"OPTIONS:",
"TROUBLESHOOTING:",
];
const SELF_HELP_ANYWHERE: &[&str] = &["init", "cloud", "serve"];
fn group_of<'a>(table: &'a [&'a [&'a str]], cmd: &str) -> Option<&'a [&'a str]> {
table.iter().copied().find(|group| group.contains(&cmd))
}
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")
}
}
const REMOVED_COMMANDS: &[&str] = &[
"visualize",
"demo",
"calibrate",
"benchmark-run",
"bench-run",
"pair",
"quality-lab",
"quality_lab",
"eval",
"measure",
"prove",
];
const RESEARCH_COMMANDS: &[&str] = &["quality-lab", "quality_lab", "eval", "measure", "prove"];
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)."
)
})
}
pub(super) fn is_help_request(cmd: &str, rest: &[String]) -> bool {
wants_help(cmd, rest) && group_of(EXEMPT, cmd).is_none()
}
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() {
return None;
}
Some(format!(
"Usage (lean-ctx {cmd}):\n{}\n\nFull command reference: lean-ctx help all\n",
lines.join("\n")
))
}
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;
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) {
if matches!(group[0], "cloud" | "models") && !lean_ctx_cloud::CLOUD_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);
assert!(guarded_help("index", &args(&["build", "--help"])).is_some());
assert_eq!(
guarded_help("init", &args(&["--agent", "claude", "--help"])),
None
);
}
#[test]
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);
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());
}
#[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}");
}
assert!(guarded_help("knowledge", &args(&["forget", "-h"])).is_some());
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() {
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:?}");
}
#[test]
fn cloud_subcommand_help_is_answered_by_cloud() {
for sub in ["tasks", "worker"] {
let rest = vec![sub.to_owned(), "--help".to_owned()];
assert_eq!(guarded_help("cloud", &rest), None, "{sub}");
}
}
}