use crate::{
core, doctor, heatmap, hook_handlers, report, setup, shell, status, token_report, uninstall,
};
pub mod analytics;
pub(crate) mod benchmark_run;
pub(crate) mod calibrate;
mod cmd_help;
mod evidence;
pub(crate) mod evidence_cost;
pub(crate) mod evidence_realworld;
pub(crate) mod evidence_report;
pub(crate) mod evidence_workflow;
mod help;
mod lifecycle;
mod network;
pub(crate) mod pair;
mod server;
pub(crate) mod suggest;
pub mod verify;
#[allow(clippy::wildcard_imports)]
use analytics::*;
#[allow(clippy::wildcard_imports)]
use help::*;
#[allow(clippy::wildcard_imports)]
use lifecycle::*;
#[allow(clippy::wildcard_imports)]
use network::*;
#[allow(clippy::wildcard_imports)]
use server::*;
pub fn run() {
let mut args: Vec<String> = std::env::args().collect();
// On Linux, if the binary was replaced while running, systemd may write
// the path with " (deleted)" suffix into ExecStart, causing "(deleted)"
// to appear as an argument. Strip it defensively.
if args.get(1).is_some_and(|a| a == "(deleted)") {
args.remove(1);
}
match crate::cli::codex_protected_cmd::protected_gitlab_dispatch(&args) {
Ok(Some(code)) => std::process::exit(code),
Ok(None) => {}
Err(error) => {
eprintln!("Error: {error}");
std::process::exit(1);
}
}
if !is_server_mode(&args) {
restore_sigpipe_default();
}
let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
if !enters_mcp {
crate::core::logging::init_logging();
}
// Default-on telemetry is disclosed once on the first interactive command;
// setup and `telemetry` print the same disclosure themselves.
if !enters_mcp
&& !is_server_mode(&args)
&& !matches!(args.get(1).map(String::as_str), Some("setup" | "telemetry"))
{
crate::core::telemetry_consent::maybe_show_notice();
}
// Counts the command (from a closed list, never its arguments).
if !enters_mcp && !is_server_mode(&args) {
crate::core::telemetry_features::record_cli(&args);
}
if args.len() > 1 {
let rest = args[2..].to_vec();
if let Some(usage) = cmd_help::guarded_help(&args[1], &rest) {
print!("{usage}");
return;
}
match args[1].as_str() {
"-c" | "exec" => handle_exec(&args, &rest),
"-t" | "--track" => handle_track(&args),
"badge" => {
crate::cli::badge_cmd::cmd_badge(&rest);
return;
}
"shell" | "--shell" => {
shell::interactive();
return;
}
"gain" => {
cmd_gain(&rest);
return;
}
"spend" => {
cmd_spend(&rest);
return;
}
"savings" => {
cmd_savings(&rest);
return;
}
"learning" => {
cmd_learning(&rest);
return;
}
"autopilot" => {
let code = crate::cli::autopilot_cmd::cmd_autopilot(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"conformance" | "selftest" => {
cmd_conformance(&rest);
return;
}
"health" => {
let code = crate::cli::health_cmd::cmd_health(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"quality-lab" | "quality_lab" => {
let code = crate::cli::quality_lab_cmd::cmd_quality_lab(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"billing" => {
cmd_billing(&rest);
return;
}
"finops" => {
cmd_finops(&rest);
return;
}
"roi" => {
// Local ROI is individual + free. The team roll-up lives on its own
// surface (`savings team` / the web account), not under `roi`.
super::cmd_roi(&rest);
return;
}
"output-savings" | "output_savings" => {
// #895 Track B: measured (A/B holdout) or estimated output-token
// reduction. Local + free, like `roi`.
super::cmd_output_savings(&rest);
return;
}
"value-report" | "value_report" => {
super::cmd_value_report(&rest);
return;
}
"evidence-export" => {
super::cmd_evidence_export(&rest);
return;
}
"evidence" => {
let code = evidence::run(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"shadow" => {
super::cmd_shadow(&rest);
return;
}
"triage" => {
super::cmd_triage(&rest);
return;
}
"scenario" => {
if let Err(error) = crate::cli::scenario_cmd::cmd_scenario_from_cli(&rest) {
eprintln!("scenario: {error}");
std::process::exit(2);
}
return;
}
"measure" => {
super::cmd_measure(&rest);
return;
}
"token-report" | "report-tokens" => {
let code = token_report::run_cli(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"pack" => {
crate::cli::cmd_pack(&rest);
return;
}
"migrate" => {
let Some(source) = rest.first() else {
eprintln!("Usage: lean-ctx migrate <headroom|config|task-receipt> [source]");
std::process::exit(2);
};
let migrate_args = crate::cli::migrate_cmd::MigrateArgs {
source: source.clone(),
input: rest
.iter()
.skip(1)
.find(|arg| !arg.starts_with("--"))
.map(Into::into),
dry_run: rest.iter().any(|arg| arg == "--dry-run"),
rollback: rest.iter().any(|arg| arg == "--rollback"),
force: rest.iter().any(|arg| arg == "--force"),
};
if let Err(error) = crate::cli::migrate_cmd::cmd_migrate(&migrate_args) {
eprintln!("Migration failed: {error}");
std::process::exit(1);
}
return;
}
"policy" => {
crate::cli::cmd_policy(&rest);
return;
}
"addon" | "addons" => {
crate::cli::cmd_addon(&rest);
return;
}
// Subprocess plugins are not coming back. An addon is a signed
// package: a sandboxed WASM module, or a declared MCP server the
// user consents to by reading its argv — either way the trust
// decision is bounded and visible (`lean-ctx addon`).
"plugin" | "plugins" => {
eprintln!(
"Plugin commands have been removed. Extensions are WASM addons now — \
see `lean-ctx addon help`."
);
std::process::exit(1);
}
"embeddings" => {
crate::cli::embeddings_cmd::cmd_embeddings(&rest);
return;
}
"model" => {
crate::cli::model_cmd::cmd_model(&rest);
return;
}
"enable-gpu" | "gpu" => {
core::updater::enable_gpu(&rest);
return;
}
"rules" => {
crate::cli::rules_cmd::cmd_rules(&rest);
return;
}
"proof" => {
crate::cli::cmd_proof(&rest);
return;
}
"prove" => {
crate::cli::cmd_prove(&rest);
return;
}
"value" => {
crate::cli::cmd_value(&rest);
return;
}
"prompt-segment" => {
crate::cli::cmd_prompt_segment(&rest);
return;
}
// Hidden: run by the prepare-commit-msg hook from `init --git-trailer`.
"git-trailer" => {
crate::cli::cmd_git_trailer(&rest);
return;
}
"claude-mod" | "claude_mod" => {
crate::cli::claude_mod_cmd::cmd_claude_mod(&rest);
return;
}
"statusline" => {
crate::cli::cmd_statusline(&rest);
return;
}
"inspect" => {
crate::cli::cmd_inspect(&rest);
return;
}
"snapshot" => {
crate::cli::cmd_snapshot(&rest);
return;
}
"verify" => {
if verify::looks_like_bundle_command(&rest) {
let code = verify::run(&rest);
if code != 0 {
std::process::exit(code);
}
} else {
crate::cli::cmd_verify(&rest);
}
return;
}
"eval" => {
crate::cli::eval_cmd::cmd_eval(&rest);
return;
}
"verify-cache" | "cache-selftest" => {
let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"visualize" => {
super::cmd_visualize(&rest);
return;
}
"audit" => {
match rest.first().map(String::as_str) {
Some("evidence") => crate::cli::audit_report::cmd_evidence(&rest[1..]),
Some("determinism") => crate::cli::audit_report::cmd_determinism(&rest[1..]),
_ => println!("{}", crate::cli::audit_report::generate_report()),
}
return;
}
"compliance" => {
crate::cli::cmd_compliance(&rest);
return;
}
"agent" => {
crate::cli::cmd_agent(&rest);
return;
}
"instructions" => {
crate::cli::cmd_instructions(&rest);
return;
}
"index" => {
crate::cli::cmd_index(&rest);
return;
}
"semantic-search" | "search-code" => {
crate::cli::cmd_semantic_search(&rest);
core::stats::flush();
return;
}
"explore" => {
crate::cli::explore_cmd::cmd_explore(&rest);
core::stats::flush();
return;
}
"repomap" | "repo-map" => {
crate::cli::cmd_repomap(&rest);
core::stats::flush();
return;
}
"cep" => {
println!("{}", core::stats::format_cep_report());
return;
}
"demo" => {
super::cmd_demo(&rest);
return;
}
"dashboard" => {
cmd_dashboard(&rest);
return;
}
"team" => {
cmd_team(&rest);
return;
}
"provider" => {
cmd_provider(&rest);
return;
}
"serve" => {
cmd_serve(&rest);
return;
}
"watch" => {
cmd_watch(&rest);
return;
}
"proxy" => {
cmd_proxy(&rest);
return;
}
"daemon" => {
cmd_daemon(&rest);
return;
}
"init" => {
super::cmd_init(&rest);
return;
}
"setup" => {
handle_setup(&rest);
return;
}
"onboard" => {
handle_onboard(&rest);
return;
}
"install" => {
handle_install(&rest);
return;
}
"bootstrap" => {
handle_bootstrap(&rest);
return;
}
"wrap" => {
let code = crate::cli::wrap_cmd::cmd_wrap(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"unwrap" => {
let code = crate::cli::wrap_cmd::cmd_unwrap(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"status" => {
let code = status::run_cli(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"cognitive" => {
crate::cli::cognitive::run();
return;
}
"read" => {
let success = super::cmd_read(&rest);
if !success {
std::process::exit(1);
}
return;
}
"call" => {
super::cmd_call(&rest);
return;
}
"diff" => {
super::cmd_diff(&rest);
return;
}
"grep" => {
super::cmd_grep(&rest);
return;
}
"glob" => {
super::cmd_glob(&rest);
return;
}
"find" => {
super::cmd_find(&rest);
return;
}
"ls" => {
super::cmd_ls(&rest);
return;
}
"deps" => {
super::cmd_deps(&rest);
return;
}
"discover" => {
super::cmd_discover(&rest);
return;
}
"engine" => {
super::cmd_engine(&rest);
return;
}
"ghost" => {
super::cmd_ghost(&rest);
return;
}
"filter" => {
super::cmd_filter(&rest);
return;
}
"heatmap" => {
heatmap::cmd_heatmap(&rest);
return;
}
"graph" => {
cmd_graph(&rest);
return;
}
"smells" => {
cmd_smells(&rest);
return;
}
"session" => {
super::cmd_session_action(&rest);
return;
}
"ledger" => {
super::cmd_ledger(&rest);
return;
}
"ocla" => {
super::cmd_ocla(&rest);
return;
}
"control" | "context-control" => {
super::cmd_control(&rest);
return;
}
"plan" | "context-plan" => {
super::cmd_plan(&rest);
return;
}
"compile" | "context-compile" => {
super::cmd_compile(&rest);
return;
}
"import" => {
crate::cli::import_cmd::cmd_import(&rest);
return;
}
"checkpoints" => {
crate::cli::checkpoint_cmd::cmd_checkpoints(&rest);
return;
}
"knowledge" => {
super::cmd_knowledge(&rest);
return;
}
"kit" | "kits" => {
super::cmd_kit(&rest);
return;
}
"skillify" => {
super::cmd_skillify(&rest);
return;
}
"summary" => {
super::cmd_summary(&rest);
return;
}
"overview" => {
super::cmd_overview(&rest);
return;
}
"compress" => {
super::cmd_compress(&rest);
return;
}
"wrapped" => {
eprintln!("'lean-ctx wrapped' has been removed. Use: lean-ctx gain --wrapped");
std::process::exit(1);
}
"sessions" | "session-store" => {
super::cmd_sessions(&rest);
return;
}
"benchmark" => {
if rest.is_empty()
|| rest.first().is_some_and(|arg| {
matches!(
arg.as_str(),
"--real"
| "--format"
| "--json"
| "--output"
| "-o"
| "--share"
| "--help"
| "-h"
)
})
{
super::cmd_benchmark_real(&rest);
} else {
super::cmd_benchmark(&rest);
}
return;
}
"benchmark-run" | "bench-run" => {
let code = benchmark_run::cmd_benchmark_run(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"calibrate" => {
let code = calibrate::cmd_calibrate(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"pair" => {
let code = pair::cmd_pair(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"compact" => {
cmd_compact(&rest);
return;
}
"profile" => {
super::cmd_profile(&rest);
return;
}
"tools" => {
// `tools health` is the token-budget / rot report (#848); it is
// distinct from tool *profiles* and routed before the forward.
if rest.first().map(String::as_str) == Some("health") {
super::cmd_tools_health(&rest[1..]);
return;
}
// Canonical, unambiguous entry point for MCP *tool* profiles
// (how many tools the agent sees). Disambiguates from
// `lean-ctx profile`, which manages *context* profiles.
let mut forwarded = vec!["tools".to_string()];
forwarded.extend(rest.iter().cloned());
super::cmd_profile(&forwarded);
return;
}
"config" => {
super::cmd_config(&rest);
return;
}
"allow" => {
super::cmd_allow(&rest);
return;
}
"allow-path" => {
super::cmd_allow_path(&rest);
return;
}
"security" => {
super::cmd_security(&rest);
return;
}
"yolo" => {
super::cmd_yolo(&rest);
return;
}
"secure" | "lockdown" => {
super::cmd_secure(&rest);
return;
}
"trust" => {
super::cmd_trust(&rest);
return;
}
"untrust" => {
super::cmd_untrust(&rest);
return;
}
"stats" => {
super::cmd_stats(&rest);
return;
}
"introspect" => {
super::cmd_introspect(&rest);
return;
}
"cache" => {
super::cmd_cache(&rest);
return;
}
"theme" => {
super::cmd_theme(&rest);
return;
}
"enterprise" => {
super::cmd_enterprise(&rest);
return;
}
"tee" => {
super::cmd_tee(&rest);
return;
}
"terse" | "compression" => {
super::cmd_compression(&rest);
return;
}
"slow-log" => {
super::cmd_slow_log(&rest);
return;
}
"debug-log" => {
super::cmd_debug_log(&rest);
return;
}
// Editor focus ingress (#500): called by the VS Code extension on
// tab change; <10ms, no daemon required.
"editor-signal" => {
let file = rest
.iter()
.position(|a| a == "--file")
.and_then(|i| rest.get(i + 1));
if let Some(path) = file {
if let Err(e) = core::editor_signal::record_focus(path) {
eprintln!("editor-signal: {e}");
std::process::exit(1);
}
} else {
eprintln!("usage: lean-ctx editor-signal --file <path>");
std::process::exit(2);
}
return;
}
"editor-session" => {
handle_editor_session(&rest);
return;
}
// Editor semantic bridge (VS Code/Cursor/Windsurf extension):
// where the extension announces its loopback bridge.
"editor-bridge" => {
if rest.first().map(String::as_str) != Some("dir") {
eprintln!("usage: lean-ctx editor-bridge dir");
std::process::exit(2);
}
match crate::lsp::editor_bridge::ensure_bridge_dir() {
Ok(dir) => println!("{}", dir.display()),
Err(e) => {
eprintln!("editor-bridge: {e}");
std::process::exit(1);
}
}
return;
}
"update" | "--self-update" => {
core::updater::run(&rest);
return;
}
"restart" => {
cmd_restart();
return;
}
"stop" => {
cmd_stop();
return;
}
"dev-install" => {
cmd_dev_install();
return;
}
"codesign-setup" => {
cmd_codesign_setup();
return;
}
"doctor" => {
let code = doctor::run_cli(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"codex-protected" => {
let code = super::cmd_codex_protected(&rest);
if code != 0 {
std::process::exit(code);
}
return;
}
"harden" => {
super::harden::run(&rest);
return;
}
"export-rules" => {
super::export_rules::run(&rest);
return;
}
"completions" => {
super::completions::run_completions(&rest);
return;
}
"__complete" => {
#[allow(non_snake_case)]
super::completions::run___complete(&rest);
return;
}
"gotchas" | "bugs" => {
super::cloud::cmd_gotchas(&rest);
return;
}
"learn" => {
super::cmd_learn(&rest);
return;
}
"buddy" | "pet" => {
super::cloud::cmd_buddy(&rest);
return;
}
"hook" => {
hook_handlers::mark_hook_environment();
let action = rest.first().map_or("help", std::string::String::as_str);
// Security admission precedes compression bypasses, runtime-env
// capture, and the legacy fail-open watchdogs.
if hook_handlers::handle_protected_gate(action) {
return;
}
// Hooks run inside the agent shell environment, so they can see
// runtime/session vars (e.g. CODEX_THREAD_ID) that the long-lived
// MCP server process never receives. Bridge them for ctx_shell (#370).
core::agent_runtime_env::capture();
// Gating hooks (rewrite/redirect) self-bound their work and FAIL OPEN
// inside the handler (#1035), so they must NOT also carry the
// force-exit watchdog (which would `exit(1)` with no decision and
// wedge the host). The remaining hooks keep the simple zombie-guard.
match action {
// Observation is loss-tolerant telemetry. It gets a shorter,
// successful fail-open watchdog so it can never make Codex
// report a PostToolUse timeout under load.
"observe" => {
hook_handlers::arm_fail_open_watchdog(hook_handlers::OBSERVE_HOOK_BUDGET);
}
// Gating hooks self-bound and fail open inside their handlers.
"rewrite" | "redirect" | "deny" | "vibe-pre-tool" => {}
_ => hook_handlers::arm_watchdog(std::time::Duration::from_secs(5)),
}
match action {
"rewrite" => hook_handlers::handle_rewrite(),
"redirect" => hook_handlers::handle_redirect(),
"deny" => hook_handlers::handle_deny(),
"read-dedup" => hook_handlers::handle_read_dedup(),
"observe" => {
let lifecycle = external_lifecycle_guard(
"hook_observe",
None,
core::execution_lifecycle::ToolSurface::Hook,
);
let _ = lifecycle
.context()
.advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
hook_handlers::handle_observe();
let _ = lifecycle.context().skip(
core::execution_lifecycle::LifecycleStage::ReversiblePostProcess,
"hook observation has no output transform",
);
let _ = lifecycle.context().skip(
core::execution_lifecycle::LifecycleStage::RecordContextIr,
"hook observation has no Context IR intent",
);
let _ = lifecycle.context().skip(
core::execution_lifecycle::LifecycleStage::RecordLedger,
"hook observation has no ledger intent",
);
let _ = lifecycle.complete(
core::execution_lifecycle::CompletionObservation::tool_result(
0, 0, "hook", true,
),
);
}
"post-commit" => hook_handlers::handle_post_commit(),
"copilot" => hook_handlers::handle_copilot(),
"codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
"codex-session-start" => hook_handlers::handle_codex_session_start(),
"rewrite-inline" => hook_handlers::handle_rewrite_inline(),
"vibe-pre-tool" => hook_handlers::handle_vibe_pre_tool(),
_ => {
eprintln!(
"Usage: lean-ctx hook <rewrite|redirect|deny|read-dedup|observe|post-commit|copilot|codex-pretooluse|codex-session-start|rewrite-inline|vibe-pre-tool>"
);
eprintln!(
" Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
);
std::process::exit(1);
}
}
return;
}
"report-issue" | "report" => {
report::run(&rest);
return;
}
"uninstall" => {
// Safety: `--help`/`-h` must NEVER fall through to a real
// uninstall (issue #476). Short-circuit before any removal.
if rest.iter().any(|a| a == "--help" || a == "-h") {
uninstall::print_help();
return;
}
let dry_run = rest.iter().any(|a| a == "--dry-run");
let keep_config = rest.iter().any(|a| a == "--keep-config");
let keep_binary = rest.iter().any(|a| a == "--keep-binary");
uninstall::run(dry_run, keep_config, keep_binary);
return;
}
// `raw` is the primary name; `bypass` is kept as a back-compat alias.
// The old "bypass" wording read to a model like a *security* bypass,
// but this only skips compression — the shell allowlist and path jail
// still apply (GH security audit, finding 5).
"raw" | "bypass" => handle_raw(&args, &rest),
"safety-levels" | "safety" => {
println!("{}", core::compression_safety::format_safety_table());
return;
}
"cheat" | "cheatsheet" | "cheat-sheet" => {
super::cmd_cheatsheet();
return;
}
"login" => {
super::cloud::cmd_login(&rest);
return;
}
"register" => {
super::cloud::cmd_register(&rest);
return;
}
"forgot-password" => {
super::cloud::cmd_forgot_password(&rest);
return;
}
"sync" => {
super::cloud::cmd_sync(&rest);
return;
}
"contribute" => {
super::cloud::cmd_contribute();
return;
}
"telemetry" => {
super::telemetry_cmd::cmd_telemetry(&rest);
return;
}
"cloud" => {
super::cloud::cmd_cloud(&rest);
return;
}
"upgrade" => {
super::cloud::cmd_upgrade(&rest);
return;
}
"--version" | "-V" => {
println!("{}", core::integrity::origin_line());
return;
}
"help" => {
let want_all = rest
.iter()
.any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
if want_all {
print_help();
} else {
print_help_concise();
}
return;
}
"--help" | "-h" => {
if rest
.iter()
.any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
{
print_help();
} else {
print_help_concise();
}
return;
}
"mcp" => {}
_ => {
let unknown = &args[1];
eprintln!("lean-ctx: unknown command '{unknown}'");
if let Some(suggestion) = suggest::closest_command(unknown) {
eprintln!(" did you mean '{suggestion}'?");
}
eprintln!(" run 'lean-ctx help' for the full command list");
std::process::exit(1);
}
}
}
// Bare `lean-ctx` on an interactive terminal: a human almost certainly did
// not mean to start a silent stdio MCP server, so print the quickstart.
//
// #1595: the TTY test alone is not a safe *stop* condition. An MCP client
// that spawns the server under a PTY (Devin, several containerized agent
// runners, anything driving the child through `script`/`expect`) hands it a
// terminal on stdin and is then answered with the quickstart instead of a
// server — the connection simply never comes up, with no error to see.
// A TTY tells us a human *might* be watching; it never tells us a client is
// not. So the guidance goes to stderr, which MCP clients log rather than
// parse, and the server starts either way: the human reads what is going on
// and presses Ctrl-C, the client completes its handshake on stdout.
if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
eprint!("{}", quickstart_text());
}
if let Err(e) = run_mcp_server() {
tracing::error!("lean-ctx: {e}");
std::process::exit(1);
}
}
fn handle_editor_session(args: &[String]) {
let value_for = |flag: &str| {
args.iter()
.position(|argument| argument == flag)
.and_then(|index| args.get(index + 1))
};
let fields = (
value_for("--event"),
value_for("--source"),
value_for("--workspace"),
value_for("--session-id"),
);
let (Some(event), Some(source), Some(workspace), Some(session_id)) = fields else {
eprintln!(
"usage: lean-ctx editor-session --event <open|heartbeat|close> \
--source <editor> --workspace <path> --session-id <id>"
);
std::process::exit(2);
};
if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
event, source, workspace, session_id,
) {
eprintln!("editor-session: {error}");
std::process::exit(1);
}
}
/// Help for `lean-ctx setup`. Printed for `--help`/`-h` and unknown flags so
/// asking about setup can never accidentally *run* setup (#476 class, #658).
fn print_setup_help() {
println!("Usage: lean-ctx setup [options]");
println!();
println!("Guided setup: shell hook, agent hooks/rules, MCP registrations.");
println!("Protected Codex: setup codex-protected --project <DIR> [--policy-pack <NAME>]");
println!(
" Checks a separate protected session; add --start to launch. See subcommand --help."
);
println!(
"Optional proprietary runtime: setup runtime <configure|status|sync-configured|rollback-configured|activate-configured|activate-personal|renew-configured|deactivate>. Installation/activation requires --accept-proprietary; rollback-configured restores the retained production version. Staging-only operator commands additionally require --staging.\nSharing (requires --accept-proprietary): share-identity; share-invite --recipient ACCOUNT_UUID --output ABSOLUTE_PRIVATE_FILE [--context-id UUID --revision N --expires-at RFC3339]; share-publish --project ABSOLUTE_DIRECTORY --invitation ABSOLUTE_PRIVATE_FILE; share-continue --project ABSOLUTE_DIRECTORY --invitation ABSOLUTE_PRIVATE_FILE [--expected-head SHA256]. Omit expected-head only for an empty destination. Transfer invitation files confidentially to their named recipient."
);
println!("Interactive by default; runs non-interactively without a TTY.");
println!();
println!("Options:");
println!(" --non-interactive No prompts; apply defaults");
println!(" --yes, -y Assume yes for all prompts");
println!(" --fix Repair an existing installation");
println!(" --json Machine-readable report (implies non-interactive)");
println!(" --no-auto-approve Skip auto-approve configuration");
println!(" --skip-rules Do not write agent rules files");
println!(" --help, -h Show this help (never runs setup)");
println!();
println!("See also: lean-ctx onboard (one-command setup), lean-ctx doctor");
}
/// Long-lived server entry points keep Rust's default ignored SIGPIPE: they
/// must survive peers closing sockets/pipes early. Bare `lean-ctx` counts as
/// a server because MCP clients spawn the binary without a subcommand.
fn is_server_mode(args: &[String]) -> bool {
args.len() == 1
|| args.get(1).is_some_and(|a| {
matches!(
a.as_str(),
"mcp" | "daemon" | "proxy" | "serve" | "watch" | "dashboard" | "gateway"
)
})
}
/// Extract `KEY=VALUE` prefixes from a command string and promote lean-ctx control variables
/// (`LEAN_CTX_*`) into the process environment.
/// Returns the remaining command string without the extracted prefixes.
///
/// Only `LEAN_CTX_*` variables are set in the process env — arbitrary user vars like `FOO=bar`
/// are left for the child shell to handle.
fn extract_and_apply_env_prefix(cmd: &str) -> String {
let mut rest = cmd.trim_start();
let mut last_rest = rest;
loop {
if let Some(eq_pos) = rest.find('=') {
let key = &rest[..eq_pos];
if !key.is_empty()
&& key
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
{
let after_eq = &rest[eq_pos + 1..];
if let Some(space_pos) = after_eq.find(' ') {
let value = &after_eq[..space_pos];
if key.starts_with("LEAN_CTX_") {
// SAFETY: runs before tokio runtime spawns threads.
unsafe { std::env::set_var(key, value) };
}
rest = after_eq[space_pos..].trim_start();
last_rest = rest;
continue;
}
}
}
break;
}
last_rest.to_string()
}
fn handle_exec(args: &[String], rest: &[String]) -> ! {
let raw = rest.first().is_some_and(|a| a == "--raw");
let cmd_args = if raw { &args[3..] } else { &args[2..] };
let command = if cmd_args.len() == 1 {
cmd_args[0].clone()
} else {
shell::join_command(cmd_args)
};
// Extract LEAN_CTX_* env-var prefixes from the command string and set them in process env
// so should_pass_through() / is_disabled() can see them. The child shell still gets the full
// original command. (#1321)
let _stripped_command = extract_and_apply_env_prefix(&command);
// The `lean-ctx -c` wrapper runs inside the agent shell, which carries
// runtime/session vars the MCP server never sees. Bridge them so ctx_shell
// can forward them too (#370).
core::agent_runtime_env::capture();
if crate::shell::reentry::should_pass_through() {
passthrough(&command);
}
if raw {
core::runtime_flags::enable_raw();
} else {
core::runtime_flags::enable_compress();
}
let code = execute_cli_shell("exec", &command, None, false)
.map_or_else(|code| code, |(observation, _)| observation.exit_code);
std::process::exit(code);
}
fn handle_track(args: &[String]) -> ! {
let cmd_args = &args[2..];
let command = shell::join_command(cmd_args);
let is_passthrough = crate::shell::reentry::should_pass_through();
if cmd_args.len() <= 1 && is_passthrough {
passthrough(cmd_args.first().map_or("", String::as_str));
}
let (command, argv) = if cmd_args.len() > 1 {
(command.as_str(), Some(cmd_args))
} else {
(cmd_args.first().map_or("", String::as_str), None)
};
let code = execute_cli_shell("track", command, argv, is_passthrough)
.map_or_else(|code| code, |(observation, _)| observation.exit_code);
std::process::exit(code);
}
fn execute_cli_shell(
name: &str,
command: &str,
argv: Option<&[String]>,
is_passthrough: bool,
) -> Result<
(
shell::ShellDispatchObservation,
Option<core::execution_lifecycle::LifecycleGuard<'static>>,
),
i32,
> {
let prepared = match argv {
Some(args) => shell::prepare_exec_argv(args),
None => shell::prepare_exec(command),
}?;
let lifecycle = (!is_passthrough).then(|| {
external_lifecycle_guard(
name,
Some(command),
core::execution_lifecycle::ToolSurface::Cli,
)
});
if let Some(guard) = &lifecycle {
let _ = guard
.context()
.advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
}
let observation = shell::execute_prepared(prepared);
if let Some(guard) = &lifecycle {
use core::execution_lifecycle::LifecycleStage;
for stage in [
LifecycleStage::ReversiblePostProcess,
LifecycleStage::RecordContextIr,
LifecycleStage::RecordLedger,
LifecycleStage::RecordEvidence,
] {
let _ = guard
.context()
.skip(stage, "CLI shell adapter has no artifact observation");
}
let _ = guard.complete(cli_shell_completion(observation.exit_code));
}
Ok((observation, lifecycle))
}
fn cli_shell_completion(code: i32) -> core::execution_lifecycle::CompletionObservation {
let mut observation =
core::execution_lifecycle::CompletionObservation::tool_result(0, 0, "cli-shell", code == 0);
"local".clone_into(&mut observation.provider);
observation.outcome_signals.clear();
observation
}
#[cfg(all(test, unix))]
#[path = "cli_shell_admission_tests.rs"]
mod cli_shell_admission_tests;
pub(super) fn external_lifecycle_guard(
tool_name: &str,
query: Option<&str>,
surface: core::execution_lifecycle::ToolSurface,
) -> core::execution_lifecycle::LifecycleGuard<'static> {
let session_id = std::env::var("CODEX_THREAD_ID")
.or_else(|_| std::env::var("CLAUDE_SESSION_ID"))
.unwrap_or_else(|_| format!("cli-{}", std::process::id()));
let project_root = std::env::current_dir()
.ok()
.map(|path| path.to_string_lossy().into_owned());
let lifecycle = core::execution_lifecycle::ExecutionLifecycle::global();
let context = lifecycle.begin(
core::execution_lifecycle::ToolRequest {
tool_name: tool_name.to_owned(),
query: query.map(str::to_owned),
session_id,
agent_id: "cli".to_owned(),
surface,
idempotency_key: None,
},
core::execution_lifecycle::RuntimeContext {
client_name: Some("lean-ctx-cli".to_owned()),
project_root,
},
core::execution_lifecycle::ProductEntitlements::default(),
);
core::execution_lifecycle::LifecycleGuard::new(lifecycle, context)
}
fn handle_setup(rest: &[String]) {
if rest.first().map(String::as_str) == Some("codex-protected") {
let code = super::cmd_setup_codex_protected(&rest[1..]);
if code != 0 {
std::process::exit(code);
}
return;
}
// Safety (#476 class): `--help`/`-h` — or any unknown flag — must NEVER
// fall through to a real setup run that mutates shell + agent configs.
if rest.iter().any(|a| a == "--help" || a == "-h") {
print_setup_help();
return;
}
if rest == ["runtime", "configure"] || rest == ["runtime", "configure", "--staging"] {
if !setup::configure_runtime() {
std::process::exit(2);
}
return;
}
if rest.first().map(String::as_str) == Some("runtime") {
crate::cli::cmd_engine(rest);
return;
}
const KNOWN: &[&str] = &[
"--non-interactive",
"--yes",
"-y",
"--fix",
"--json",
"--no-auto-approve",
"--skip-rules",
"--no-agent-aliases",
];
if let Some(unknown) = rest.iter().find(|a| !KNOWN.contains(&a.as_str())) {
eprintln!("setup: unknown flag or argument '{unknown}'\n");
print_setup_help();
std::process::exit(2);
}
let non_interactive = rest.iter().any(|a| a == "--non-interactive");
let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
let fix = rest.iter().any(|a| a == "--fix");
let json = rest.iter().any(|a| a == "--json");
let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
let skip_rules = rest.iter().any(|a| a == "--skip-rules");
let no_agent_aliases = rest.iter().any(|a| a == "--no-agent-aliases");
if no_agent_aliases {
let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
}
if non_interactive || fix || json || yes {
let opts = setup::SetupOptions {
non_interactive,
yes,
fix,
json,
no_auto_approve,
skip_rules,
..Default::default()
};
run_setup_options(opts, json);
} else {
setup::run_setup();
}
}
fn handle_onboard(rest: &[String]) {
if rest.iter().any(|a| a == "--help" || a == "-h") {
println!("Usage: lean-ctx onboard [--no-agent-aliases]");
println!("Connect your AI tools with one command: detects installed");
println!("agents, installs hooks/rules/MCP registrations, verifies.");
println!();
println!(" --no-agent-aliases Do not install claude/codex/gemini shell aliases");
println!();
println!("Fine-grained control: lean-ctx setup --help");
return;
}
if rest.iter().any(|a| a == "--no-agent-aliases") {
let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
}
setup::run_onboard();
}
fn handle_install(rest: &[String]) {
// Plain `lean-ctx install` is a natural thing to type after installing the
// binary; keep it as guided setup unless repair mode was explicitly asked.
let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
let json = rest.iter().any(|a| a == "--json");
if !repair {
setup::run_setup();
return;
}
run_repair_setup(json);
}
fn handle_bootstrap(rest: &[String]) {
let json = rest.iter().any(|a| a == "--json");
run_repair_setup(json);
}
fn run_repair_setup(json: bool) {
let opts = setup::SetupOptions {
non_interactive: true,
yes: true,
fix: true,
json,
..Default::default()
};
run_setup_options(opts, json);
}
fn handle_raw(args: &[String], rest: &[String]) -> ! {
if rest.is_empty() {
eprintln!("Usage: lean-ctx raw \"command\"");
eprintln!(
"Runs the command with output passed through unchanged (no compression). \
The shell allowlist still applies."
);
std::process::exit(1);
}
let command = if rest.len() == 1 {
rest[0].clone()
} else {
shell::join_command(&args[2..])
};
core::runtime_flags::enable_raw();
let code = shell::exec(&command);
std::process::exit(code);
}
fn run_setup_options(opts: setup::SetupOptions, json: bool) {
match setup::run_setup_with_options(opts) {
Ok(report) => {
if json {
println!(
"{}",
serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string())
);
}
if !report.success {
std::process::exit(1);
}
}
Err(e) => {
eprintln!("{e}");
std::process::exit(1);
}
}
}
/// Restore the default SIGPIPE disposition for short-lived CLI invocations.
///
/// Rust's runtime ignores SIGPIPE process-wide, so `lean-ctx doctor | head`
/// made `println!` panic with BrokenPipe; the LineWriter flush in stdout's
/// Drop then panicked again *during unwinding*, which aborts — the SIGABRT
/// (exit 134) of upstream #378 / GL#436. Real CLIs (cat, grep, rg) terminate
/// silently with exit 141 instead; SIG_DFL gives us exactly that. Children
/// spawned via std::process::Command are unaffected either way (std resets
/// their SIGPIPE disposition since Rust 1.65).
#[cfg(unix)]
fn restore_sigpipe_default() {
// SAFETY: signal(2) with SIG_DFL has no preconditions and is called once
// during single-threaded startup, before any I/O.
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
}
#[cfg(not(unix))]
fn restore_sigpipe_default() {}
/// Run the command raw in the user's shell. Pass-through only skips lean-ctx
/// compression; the allowlist is a security boundary and applies exactly as on
/// the compress path. An agent process can inherit `LEAN_CTX_WRAPPED` from a
/// wrapped parent, so every Bash-hook rewrite to `lean-ctx -c` landed here and
/// ran unchecked (GH #2004, a regression of the #1408 fix).
fn passthrough(command: &str) -> ! {
if let Some(code) = shell::exec::allowlist_gate(command) {
std::process::exit(code);
}
let (shell, flag) = shell::shell_and_flag();
let mut cmd = std::process::Command::new(&shell);
cmd.arg(&flag).arg(command);
shell::reentry::mark_child(&mut cmd);
shell::platform::apply_utf8_locale(&mut cmd);
let status = cmd.status().map_or(127, shell::exit_status::exit_code);
std::process::exit(status);
}
pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
// A failed runtime build (e.g. exhausted FDs) must not abort with a panic
// backtrace the user can't act on — report it plainly and exit.
match tokio::runtime::Runtime::new() {
Ok(rt) => rt.block_on(future),
Err(e) => {
eprintln!("lean-ctx: failed to create async runtime: {e}");
std::process::exit(1);
}
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod env_prefix_tests;