This is the exhaustive reference for every lean-ctx command. For a quick cheat sheet, see Quick Reference. For analytics and dashboard details, see Analytics Guide.
Shell Compression
These commands run shell commands through lean-ctx's 60+ compression patterns. Output is automatically stripped of noise, boilerplate, and redundancy before reaching the LLM.
lean-ctx -c "<command>"
Execute any shell command and compress its output. Alias: lean-ctx exec.
lean-ctx -c "git status"
lean-ctx -c "kubectl get pods -A"
lean-ctx -c "cargo build 2>&1"
lean-ctx exec "docker ps" The shell hook (installed via lean-ctx init) makes this automatic for common commands - you don't need to prefix them with -c. Use -c explicitly for commands not covered by the shell hook.
lean-ctx shell
Start an interactive shell session where all command output is compressed. Wraps your default shell (zsh, bash, or fish).
lean-ctx shell
# Now every command output is compressed automatically
git log --oneline -20
docker compose logs
# Exit with Ctrl+D or 'exit' Raw Mode
Skip compression entirely when you need full, unmodified output. Three ways to activate:
# CLI flag
lean-ctx -c --raw git log --stat
# Shell function (after lean-ctx init --global)
lean-ctx-raw kubectl get pods -o yaml
# MCP parameter
ctx_shell(command="cat package.json", raw=true)
# Environment variable
LEAN_CTX_RAW=1 lean-ctx -c npm list
# Bypass command - guaranteed zero compression
lean-ctx bypass "git diff HEAD~1"
# Kill-switch: disable ALL compression
LEAN_CTX_DISABLED=1 lean-ctx -c git status lean-ctx bypass "<command>"
Run any command with guaranteed zero compression. Internally sets LEAN_CTX_RAW=1 before executing the command. Use when you need absolute certainty that output is unmodified.
lean-ctx bypass "git diff HEAD~1" # guaranteed unmodified output
lean-ctx bypass "docker logs myapp" # no compression, no truncation
lean-ctx bypass "npm audit" # raw vulnerability report Tip: bypass is equivalent to LEAN_CTX_RAW=1 lean-ctx -c "command" but more convenient. The command string is passed directly to the shell.
File Operations
Direct CLI access to lean-ctx's file reading, searching, and navigation tools. These are the same operations the MCP server provides to AI tools.
lean-ctx read <file> [-m <mode>]
Read a file with optional compression mode. Default mode is full.
lean-ctx read src/main.rs # auto-selects best mode
lean-ctx read src/main.rs -m full # full content (cached)
lean-ctx read src/main.rs -m map # dependency graph + exports
lean-ctx read src/main.rs -m signatures # tree-sitter AST extraction
lean-ctx read src/main.rs -m aggressive # syntax-stripped
lean-ctx read src/main.rs -m entropy # Shannon entropy filtered
lean-ctx read src/main.rs -m diff # changed lines only
lean-ctx read src/main.rs -m task # IB-filtered for current task
lean-ctx read src/main.rs -m reference # cross-reference context
lean-ctx read src/main.rs -m lines:10-50 # specific line range
lean-ctx read src/main.rs -m lines:10-50,80 # multiple ranges lean-ctx diff <file1> <file2>
Compressed diff between two files with structured change summaries.
lean-ctx diff old.rs new.rs lean-ctx grep <pattern> [path]
Search file contents with compressed, grouped results. Uses ripgrep internally.
lean-ctx grep "pub fn" src/
lean-ctx grep "TODO" .
lean-ctx grep "async fn.*Result" rust/src/ lean-ctx find <pattern> [path]
Find files by name pattern. Respects .gitignore and outputs a compact file tree.
lean-ctx find "*.rs" src/
lean-ctx find "test_*" . lean-ctx ls [path] [--all|-a] [--depth N]
Compact directory listing as a tree map with file counts. Supports <code>--all</code>/<code>-a</code> (include hidden files) and <code>--depth N</code> (limit depth). Flags like <code>-la</code>, <code>-l</code>, <code>-R</code> are not supported — use the shell hook for standard <code>ls</code>.
| Flag | Description |
|---|---|
--all / -a | Include hidden files (dotfiles) |
--depth N | Limit directory tree depth (default: 3) |
lean-ctx ls
lean-ctx ls src/components/
lean-ctx ls --all .
lean-ctx ls --depth 5 src/ Note: lean-ctx ls is a compressed tree view, not a drop-in ls replacement.
Flags like -la, -l, -R are rejected with a clear error. Use the shell
hook (ls -la directly) for standard ls behavior.
lean-ctx deps [path]
Show project dependency graph. Detects package manager and extracts dependencies.
lean-ctx deps .
lean-ctx deps frontend/ Read Modes
Read modes control how lean-ctx read and the MCP tool ctx_read compress file content. Choose the right mode for your use case:
| Mode | Output | Use case | Savings |
|---|---|---|---|
auto | Best mode for context | Default when no mode specified - lean-ctx picks optimal strategy | 60–95% |
full | Complete file content | Files you will edit. Re-reads cost ~13 tokens (cached). | 0% (first read), ~99% (cached) |
map | Dependency graph + exports + key signatures | Context-only files - understand structure without reading everything. | 70-90% |
signatures | tree-sitter AST extraction (21 languages) | API surface only - function/method/class signatures. | 92–99% |
aggressive | Syntax-stripped content | Maximum compression while preserving logic. | 85–95% |
entropy | Shannon entropy + Jaccard filtering | Keep only information-dense lines. | 70–90% |
diff | Changed lines only (vs. last read) | After editing - see only what changed. | 90–99% |
task | Task-filtered content | IB-scored extraction based on current intent - only relevant code for the active task | 70–90% |
reference | Cross-reference context | Related types, callers, and dependencies for the target symbol or function | 60–85% |
lines:N-M | Specific line ranges | Read only the section you need. Supports multiple ranges: lines:10-50,80-100 | varies |
Supported languages for signatures mode: TypeScript, JavaScript, Rust, Python, Go, Java, C, C++, Ruby, C#, Kotlin, Swift, PHP (18 total via tree-sitter).
Setup & Configuration
lean-ctx setup
One-command setup. Auto-detects your shell (zsh/bash/fish/PowerShell), finds installed AI tools, and configures MCP server + shell hooks. Run once after installing lean-ctx.
lean-ctx setup This runs three steps internally:
- Installs shell aliases (
init --global) - Configures MCP for each detected AI tool
- Verifies everything works (
doctor)
Since v3.3.3, the setup wizard includes a Premium Features step where you can configure Terse Agent Mode, Tool Result Archive, and Output Density interactively.
Since v3.5.16, setup also configures Shell Activation — you can choose when
lean-ctx shell aliases auto-activate: always (default), agents-only
(only when AI agent env vars are detected), or off (manual via lean-ctx-on).
See Shell Activation for details.
lean-ctx init [--global | <shell>] [--style=auto|inline|dropin]
Install shell compression aliases into your shell profile.
# File-based: writes aliases directly into your shell profile
lean-ctx init # install for current shell
lean-ctx init --global # same, explicit flag
# Install style (v3.5.19+)
lean-ctx init --global --style=dropin # drop-in file in ~/.zshenv.d/
lean-ctx init --global --style=inline # fenced block in ~/.zshenv (default)
lean-ctx init --global --style=auto # auto-detect (default)
# Eval-based: prints hook code to stdout (like starship, zoxide, atuin)
eval "$(lean-ctx init bash)" # bash: add to ~/.bashrc
eval "$(lean-ctx init zsh)" # zsh: add to ~/.zshrc
lean-ctx init fish | source # fish: add to config.fish
lean-ctx init powershell | Invoke-Expression # PowerShell: add to $PROFILE This writes a block to ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish, or your PowerShell profile. The block includes aliases for git, docker, npm, cargo, ls, find, and 60+ other commands. Use --style=dropin for modular dotfile setups (v3.5.19+).
eval pattern: The eval method prints hook code to stdout, ensuring it always matches the installed binary version. This is the same pattern used by starship, zoxide, and atuin. Hooks are never stale after upgrades.
Install Style (v3.5.19+)
Controls how shell hooks are installed. By default, lean-ctx auto-detects the best approach. Users with modular dotfile managers (chezmoi, yadm, stow, oh-my-zsh) benefit from dropin style. Migration between styles is transparent — hand-edits are preserved via timestamped backups.
| Style | Behavior |
|---|---|
auto | Auto-detect: uses drop-in if a .d/ directory exists, otherwise inline (default) |
inline | Writes a fenced block directly into your shell profile (~/.zshenv, ~/.bashrc, etc.) |
dropin | Creates a numbered drop-in file (e.g. ~/.zshenv.d/00-lean-ctx.zsh). Ideal for chezmoi, yadm, stow, oh-my-zsh custom/. |
lean-ctx init --agent <name>
Configure MCP for a specific AI tool without running full setup.
| Agent | Notes |
|---|---|
cursor | Cursor IDE (default MCP setup) |
claude | Claude Code / Claude Desktop |
codex | OpenAI Codex CLI |
gemini | Google Gemini CLI |
antigravity | Alias for gemini |
windsurf | Windsurf IDE |
copilot | GitHub Copilot |
cline | Cline (VS Code extension) |
roo | Roo Code |
aider | Aider CLI |
continue | Continue.dev |
zed | Zed Editor |
void | Void Editor |
amp | Amp (Sourcegraph) |
trae | Trae IDE |
kilo | Kilo Code |
opencode | OpenCode CLI |
pi | Installs pi-lean-ctx npm package |
custom | Generic MCP config - prompts for path |
lean-ctx init --agent cursor
lean-ctx init --agent claude
lean-ctx init --agent codex
lean-ctx init --agent gemini
lean-ctx init --agent antigravity # alias for gemini
lean-ctx init --agent windsurf
lean-ctx init --agent copilot
lean-ctx init --agent cline
lean-ctx init --agent roo
lean-ctx init --agent aider
lean-ctx init --agent continue
lean-ctx init --agent zed
lean-ctx init --agent void
lean-ctx init --agent amp
lean-ctx init --agent trae
lean-ctx init --agent kilo
lean-ctx init --agent opencode
lean-ctx init --agent pi # installs pi-lean-ctx npm package
lean-ctx init --agent custom # generic MCP config lean-ctx config [set <key> <value>]
Show or edit configuration stored at ~/.lean-ctx/config.toml.
lean-ctx config # show current config
lean-ctx config set ultra_compact true # enable ultra-compact mode
lean-ctx config set tee_on_error true # log errors to ~/.lean-ctx/tee/
lean-ctx config set checkpoint_interval 20 Settable Configuration Keys
| Key | Type | Default | Description |
|---|---|---|---|
ultra_compact | bool | false | Enable ultra-compact output mode for maximum token savings |
tee_mode | string | "off" | Tee logging mode: off, on_error, always |
checkpoint_interval | int | 15 | Number of MCP calls between automatic checkpoints |
theme | string | "default" | Dashboard and TUI theme (default, dark, light, neon) |
slow_command_threshold_ms | int | 5000 | Threshold in milliseconds for slow-log entries |
passthrough_urls | string[] | [] | URL patterns that bypass compression (comma-separated) |
rules_scope | string | "project" | Scope for rules loading: project, global, or both |
lean-ctx config set theme neon
lean-ctx config set slow_command_threshold_ms 3000
lean-ctx config set passthrough_urls "localhost:3000,api.example.com"
lean-ctx config set rules_scope both lean-ctx config schema v3.5.21
Outputs a complete JSON schema of all configuration keys, including types, defaults, descriptions, and env var overrides. Useful for editor autocompletion and CI validation.
lean-ctx config schema # print full JSON schema to stdout
lean-ctx config schema > config-schema.json # save for editor integration lean-ctx config validate v3.5.21
Validates config.toml against the schema. Warns about unknown keys with
Levenshtein-distance "did you mean?" suggestions. Returns exit code 1 on errors (CI-friendly).
lean-ctx config validate # validate ~/.lean-ctx/config.toml
lean-ctx config validate && echo "OK" # CI gate - fails on invalid config lean-ctx doctor
Run 11 installation and environment diagnostics:
- Binary installed and in PATH
- Shell hook active
- MCP config for detected editors
- Stats file persistence
- Cache directory
- Supported shell detected
- AI tool detection
- Version check
- Rules injection status
- Claude Code instructions (rules + skill installed)
- Build integrity verification
lean-ctx doctor lean-ctx update [--check]
Self-update the lean-ctx binary from GitHub Releases.
lean-ctx update # download and install latest version
lean-ctx update --check # check if a newer version is available (no install) lean-ctx login <email> [--password <pw>] v3.3.3
Authenticate with LeanCTX Cloud. Only attempts login - does not create a new account. If password is omitted, prompts interactively.
lean-ctx login user@example.com
lean-ctx login user@example.com --password mypassword
On success, saves the API key to ~/.lean-ctx/cloud/credentials.json and syncs
your data. If your email is not yet verified, you'll receive a reminder to check your inbox.
lean-ctx register <email> [--password <pw>] v3.3.3
Create a new LeanCTX Cloud account. Separate from login - no auto-fallback.
A verification email is sent after registration.
lean-ctx register user@example.com
lean-ctx register user@example.com --password mypassword lean-ctx forgot-password <email>
Request a password reset email for an existing LeanCTX Cloud account.
lean-ctx forgot-password user@example.com lean-ctx uninstall
Remove all lean-ctx configuration: shell hooks, MCP configs from all editors, and the ~/.lean-ctx/ data directory. Prints instructions for removing the binary.
lean-ctx uninstall lean-ctx harden [--undo]
Activate strict enforcement mode. Prevents agents from using native Read/Grep/Shell by injecting LEAN_CTX_HARDEN=1 into all discovered MCP configurations.
lean-ctx harden # activate strict enforcement
lean-ctx harden --undo # revert to normal mode When activated, harden mode performs the following:
- Sets <code>LEAN_CTX_HARDEN=1</code> in all MCP server configs (Cursor, Claude, Windsurf, etc.)
- Optionally adds <code>Bash</code> to Claude Code's <code>permissions.deny</code> list to enforce lean-ctx shell usage
lean-ctx export-rules [--format=mdc|agents|claude] [--project=<path>]
Export high-confidence knowledge facts from the project's knowledge graph as editor-native rule files.
lean-ctx export-rules # auto-detect format
lean-ctx export-rules --format=mdc # Cursor .mdc rule file
lean-ctx export-rules --format=agents # AGENTS.md section
lean-ctx export-rules --format=claude # CLAUDE.md section
lean-ctx export-rules --project=/path/to/repo # specify project root Only facts with confidence ≥ 0.8 and publishable archetypes (Architecture, Convention, Decision, Dependency, Gotcha) are exported. Facts carry provenance tracking.
lean-ctx ledger [status|reset|evict <paths...>|prune]
Manage the context pressure ledger. View current pressure, clear entries, evict specific files, or prune stale entries.
lean-ctx ledger # show current pressure status
lean-ctx ledger status # same as above
lean-ctx ledger reset # clear all entries, reset pressure to zero
lean-ctx ledger evict src/old.rs src/unused.ts # evict specific paths
lean-ctx ledger prune # remove entries for files that no longer exist The evict action also adds exclusion overlays, preventing evicted paths from re-accumulating pressure. Use reset when switching task focus entirely.
Analytics & Dashboards
For a detailed guide with screenshots and interpretations, see Analytics Guide.
lean-ctx gain [flags]
Visual terminal dashboard showing lifetime token savings.
Powered by the GainEngine - a unified observability API that consolidates compression metrics, cost tracking, and session analytics into a single GainScore (0–100). Uses embedded ModelPricing (no network required) and a TaskClassifier with 13 categories.
| Flag | Output |
|---|---|
(none) | Full dashboard: total saved, rate, USD, top commands, sparklines |
--score | GainScore (0–100) combining compression ratio, cost efficiency, quality, and consistency |
--cost | Cost breakdown per model with embedded pricing (supports --model=<name> filter) |
--tasks | Task classification breakdown across 13 categories (file-ops, search, shell, memory, etc.) |
--agents | Per-agent statistics in multi-agent sessions (calls, tokens, cost attribution) |
--heatmap | File access heatmap - which files are read most frequently by the AI |
--wrapped | Spotify-Wrapped-style session summary (supports --period=week|month|all) |
--deep | Combined deep-dive: report + tasks + cost + agents + heatmap in one output |
--live | Auto-refreshing mode (updates every 2s). Press q to quit. |
--graph | 30-day savings chart with daily bars |
--daily | Bordered day-by-day table with token counts and USD |
--pipeline | Pipeline-view: shows compression stages and per-stage token savings |
--json | Raw JSON export of all stats (for scripting/automation) |
Modifiers
| Flag | Output |
|---|---|
--model=<name> | Filter cost/score output to a specific model (e.g. --model=claude-4-sonnet) |
--period=<p> | Time window for analytics: today, week, month, all (default: all) |
--limit=<n> | Max rows in ranked tables (default: 10) |
--reset | Clear all stats data and start fresh |
lean-ctx gain # overview with GainScore
lean-ctx gain --score # GainScore breakdown
lean-ctx gain --cost --model=claude-4-sonnet # cost for specific model
lean-ctx gain --tasks # task classification heatmap
lean-ctx gain --agents # multi-agent cost attribution
lean-ctx gain --deep # full deep-dive report
lean-ctx gain --wrapped --period=week # weekly summary
lean-ctx gain --live # real-time monitoring
lean-ctx gain --graph # ASCII savings graph
lean-ctx gain --daily # daily breakdown
lean-ctx gain --pipeline # per-stage compression breakdown
lean-ctx gain --json > stats.json # machine-readable export The ctx_gain MCP tool provides the same analytics programmatically - AI agents can query token savings, cost breakdowns, and GainScore directly during a session. See MCP Tools Reference.
lean-ctx cep [--json]
CEP (Cognitive Efficiency Protocol) impact report showing score trends, cache hit rates, and mode distribution.
Internally uses ctx_gain --score to compute the Context Efficiency Protocol score.
The CEP score ranges from 0–100 and measures how efficiently context is being utilized across
read modes, shell compression, and deduplication.
| Flag | Description |
|---|---|
(none) | Pretty-print CEP score with breakdown |
--json | Machine-readable JSON output |
lean-ctx cep # show CEP score with breakdown
lean-ctx cep --json # JSON output for CI/CD integration lean-ctx dashboard [--port=N] [--project=<path>]
Open the interactive web dashboard at http://localhost:3333. Features interactive charts, session history, active agents, and project knowledge panels.
| Flag | Description |
|---|---|
--port=<N> | Custom port (default: 3333) |
--project=<path> | Scope dashboard to a specific project directory instead of the global view |
lean-ctx dashboard # opens at localhost:3333
lean-ctx dashboard --port=8080 # custom port
lean-ctx dashboard --project=~/my-app # scoped to a single project lean-ctx wrapped [--week|--month|--all]
Generate a shareable "Wrapped" report card of your token savings.
| Flag | Period |
|---|---|
(none) | Current week |
--week | Current week (explicit) |
--month | Current month |
--all | Lifetime stats |
lean-ctx wrapped
lean-ctx wrapped --month
lean-ctx wrapped --all Session Management
lean-ctx sessions [list|show|cleanup]
Manage CCP (Context Continuity Protocol) sessions stored at ~/.lean-ctx/sessions/.
| Subcommand | Action |
|---|---|
list | List all saved sessions |
show | Show the latest session state |
cleanup | Remove old/stale sessions |
lean-ctx sessions list
lean-ctx sessions show
lean-ctx sessions cleanup lean-ctx session
Show adoption statistics - how much of your workflow uses lean-ctx compression.
lean-ctx session Knowledge Management
Full CLI access to the persistent project knowledge store. Facts, patterns, and conventions survive across sessions and enable cumulative project understanding.
lean-ctx knowledge remember <value> --category <c> --key <k>
Store a fact in the project knowledge base with optional confidence score.
lean-ctx knowledge remember "Uses JWT for auth" --category auth --key token-type
lean-ctx knowledge remember "PostgreSQL 16" --category arch --key database --confidence 0.95 lean-ctx knowledge recall [query] [--category <c>] [--mode auto|semantic|hybrid]
Retrieve facts by query text or category. Supports semantic recall when embeddings are enabled.
lean-ctx knowledge recall "authentication"
lean-ctx knowledge recall --category security
lean-ctx knowledge recall "auth" --mode semantic lean-ctx knowledge search <query>
Search across all projects and sessions for matching facts.
lean-ctx knowledge search "database migration" lean-ctx knowledge export [--format json|jsonl|simple] [--output <path>]
Export the project knowledge base. Outputs to stdout by default (pipe-friendly). Three formats: json (full native, default), jsonl (one fact per line), simple (community-compatible array for migration from other tools).
lean-ctx knowledge export # full JSON to stdout
lean-ctx knowledge export --format jsonl --output backup.jsonl # JSONL to file
lean-ctx knowledge export --format simple | jq '.[].key' # pipe-friendly lean-ctx knowledge import <path> [--merge replace|append|skip-existing] [--dry-run]
Import facts from a JSON, JSONL, or native export file. Auto-detects input format. Default merge strategy is skip-existing (safe — never overwrites).
lean-ctx knowledge import backup.json --dry-run # preview changes
lean-ctx knowledge import facts.jsonl --merge replace # overwrite existing
lean-ctx knowledge import migration.json --merge skip-existing lean-ctx knowledge remove --category <c> --key <k>
Remove a specific fact from the knowledge base.
lean-ctx knowledge remove --category auth --key token-type lean-ctx knowledge status
Show knowledge base summary — fact counts, categories, and last update time.
lean-ctx knowledge status lean-ctx knowledge health
Health report with quality metrics, stale fact detection, and room balance.
lean-ctx knowledge health Benchmarking
lean-ctx benchmark run [path] [--json]
Run real token benchmarks on your project files using tiktoken (o200k_base). Measures exact savings for each read mode across every file.
lean-ctx benchmark run # benchmark current directory
lean-ctx benchmark run src/ # benchmark specific path
lean-ctx benchmark run . --json # output as JSON lean-ctx benchmark report [path]
Generate a shareable Markdown report from benchmark results.
lean-ctx benchmark report # generate report for current directory
lean-ctx benchmark report src/ > BENCHMARK.md Tee & Filters
lean-ctx tee [list|clear|show <file>|last]
Manage full output tee files saved to ~/.lean-ctx/tee/. Use lean-ctx tee last to view the most recent saved output. Configure via tee_mode: always, failures, or never.
lean-ctx filter [list|validate|init]
Manage custom compression filters in ~/.lean-ctx/filters/*.toml.
# Create example filter
lean-ctx filter init
# List loaded filters
lean-ctx filter list
# Validate filter syntax
lean-ctx filter validate Utilities
lean-ctx discover
Scan your shell history for commands that could benefit from compression but aren't being intercepted. Shows per-command token estimates and USD savings projection.
lean-ctx discover lean-ctx ghost [--json]
Reveals hidden token waste in your workflow - shows unoptimized shell commands, redundant reads,
and oversized contexts with a monthly USD savings estimate. Use --json for CI integration.
lean-ctx ghost
lean-ctx ghost --json lean-ctx cheatsheet
Print a compact cheat sheet of all commands and workflows directly in your terminal.
lean-ctx cheatsheet lean-ctx tee [list|clear|show <file>]
Manage error log files stored at ~/.lean-ctx/tee/. When tee_on_error is enabled in config, failed commands log their full output here.
| Subcommand | Action |
|---|---|
list | List all error log files |
clear | Delete all error logs |
show <file> | Display a specific error log |
lean-ctx tee list
lean-ctx tee show 2026-03-29_10-30.log
lean-ctx tee clear lean-ctx slow-log [list|clear]
Show or clear the slow command log at ~/.lean-ctx/slow-commands.log. Commands that take longer than expected are logged here for debugging.
lean-ctx slow-log list
lean-ctx slow-log clear Project Graph
Build or inspect the project dependency graph. The graph indexes file relationships (imports, exports, symbols) and is used by heat-ranking, intent analysis, and smart preloading.
lean-ctx graph build
Scan the project directory and build the dependency graph index. The graph is also built automatically when MCP tools are used.
lean-ctx graph build Context Heat Map
Visualize file token density and dependency graph connectivity as a color-coded heat map. Files with high token counts and many connections appear hotter.
lean-ctx heatmap
Display a terminal heat map of all files in the current project, sorted by heat score (combination of token count and graph connectivity).
lean-ctx heatmap Safety Levels
LeanCTX categorizes every supported command into a safety level that determines how aggressively output is compressed. Higher levels never remove safety-critical information (errors, CVEs, health status).
lean-ctx safety-levels
Displays a detailed table showing exactly how each command type is compressed, what data is preserved, and what global safety features are active.
lean-ctx safety-levels | Level | Commands | Behavior |
|---|---|---|
VERBATIM | df, git status, git stash, ls, find, wc, env | Zero compression. Output passes through completely unmodified. |
MINIMAL | git diff, git log, docker ps, grep, ruff, npm audit, pytest, pip, curl | Light formatting only. All safety-critical data (code diffs, error details, CVE IDs, health status) is fully preserved. |
STANDARD | cargo build, npm install, eslint, tsc, go build, maven, gradle, dotnet | Structured compression. Errors, warnings, and actionable items always preserved. |
AGGRESSIVE | kubectl describe, aws, terraform, docker images | Heavy compression for verbose output. Still preserves error messages and safety-critical keywords. |
Global safety features apply to ALL levels: safety-needle scan (preserves CRITICAL, FATAL, panic, CVE-*, OOMKilled, etc.), safeguard ratio (blocks >95% compression), authentication detection (masks tokens/passwords), and minimum token threshold (no compression below 50 tokens).
Audit
Generate a compliance report covering all lean-ctx activity in the current or specified project. The audit report includes file reads, compression ratios, security events, per-agent budget usage, and an OWASP alignment summary.
lean-ctx audit [flags]
| Flag | Description |
|---|---|
(none) | Print full audit report to stdout |
--period=<p> | Time period: today, week, month, all |
--project=<path> | Scope audit to a specific project directory |
--json | Machine-readable JSON output for CI/CD integration |
lean-ctx audit # full audit report
lean-ctx audit --period=week # weekly audit
lean-ctx audit --project=~/my-app --json # JSON export for CI Report Sections
- File Reads — total reads, unique files, cache hit rate, read modes used
- Compression Ratios — per-mode and aggregate token savings
- Security Events — cross-project boundary violations, blocked reads, secret detection hits
- Budget Usage — per-agent token consumption vs. configured limits
- OWASP Alignment — summary of how lean-ctx security controls map to OWASP LLM Top 10 categories
Shell Allowlist
The shell_allowlist configuration restricts which commands ctx_shell
can execute. When enabled, only commands matching the allowlist patterns are permitted —
all others are rejected with an error. This provides an additional security layer on top of
the existing safety levels.
# config.toml
[shell_allowlist]
enabled = true
commands = [
"git *",
"cargo *",
"npm *",
"node *",
"ls *",
"cat *",
"grep *",
]
When a command is blocked by the allowlist, ctx_shell returns an error
indicating the command is not permitted, along with the list of allowed patterns.
Use lean-ctx config set shell_allowlist.enabled false to disable.
Shell Aliases
After running lean-ctx init --global, these aliases are available in your shell. They let you toggle compression on and off without restarting:
| Alias | Action |
|---|---|
lean-ctx-on | Enable all compression aliases |
lean-ctx-off | Disable compression (human-readable output) |
lean-ctx-status | Show whether compression is currently active |
lean-ctx-raw <cmd> | Run a single command without compression |
lean-ctx-status # check current state
lean-ctx-off # temporarily disable for human reading
git log # now shows full, uncompressed output
lean-ctx-on # re-enable for AI sessions When to disable: Turn off compression when you want to read command output yourself (debugging, reviewing logs). Turn it back on before starting an AI coding session.
Server & Services
lean-ctx can run as a long-lived HTTP server, a TUI watcher, or a network proxy. These modes are useful for CI/CD pipelines, multi-agent orchestration, and headless environments.
lean-ctx serve [flags] feature: http-server
Start an HTTP/REST server that exposes all MCP tools as REST endpoints.
Requires the http-server feature gate.
Supports both stateful (session-persisted) and stateless modes.
| Flag | Default | Description |
|---|---|---|
--port=<N> | 9119 | Port to listen on |
--host=<addr> | 127.0.0.1 | Bind address (0.0.0.0 for all interfaces) |
--stateless | off | Disable session persistence - each request is independent |
--rate-limit=<N> | 100 | Max requests per minute per client |
--timeout=<ms> | 30000 | Request timeout in milliseconds |
--cors | off | Enable CORS headers for browser access |
# Start server with defaults
lean-ctx serve
# Public-facing with rate limits
lean-ctx serve --host=0.0.0.0 --port=8080 --rate-limit=50
# Stateless mode for CI/CD
lean-ctx serve --stateless --timeout=60000
# With CORS for web dashboard
lean-ctx serve --cors --port=9119
Once running, all MCP tools are available at POST /v1/tools/<tool_name>.
A health endpoint is at GET /health.
lean-ctx watch
Start lean-ctx in TUI (Terminal UI) mode with a live event bus.
Monitors all MCP activity in real time and writes events to
~/.lean-ctx/events.jsonl for post-hoc analysis.
| Flag | Description |
|---|---|
--filter=<pattern> | Only show events matching the pattern (e.g. ctx_read, error) |
--no-tui | Headless mode - stream events to stdout as JSONL |
lean-ctx watch # full TUI with live event stream
lean-ctx watch --filter=ctx_shell # only shell events
lean-ctx watch --no-tui # headless JSONL to stdout lean-ctx proxy <start|stop|status> feature-gated
Manage the lean-ctx network proxy. When active, the proxy intercepts MCP traffic
and applies compression transparently. Requires the proxy feature gate.
| Subcommand | Description |
|---|---|
start | Start the proxy daemon |
stop | Stop the running proxy |
status | Show proxy status (running/stopped, port, uptime) |
lean-ctx proxy start # start proxy daemon
lean-ctx proxy status # check if proxy is running
lean-ctx proxy stop # stop the proxy Terse Agent
The Terse Agent controls output density for AI agent communication. It persists across sessions and can be toggled at any time. See also the Configuration guide.
lean-ctx terse [lite|full|ultra|off]
Query or set the Terse Agent mode. Without arguments, shows the current mode. With an argument, sets the mode persistently.
| Mode | Description |
|---|---|
off | Terse Agent disabled - standard MCP output |
lite | Light compression: removes boilerplate, keeps structure |
full | Full terse mode: abbreviated keys, minimal whitespace, Fn refs |
ultra | Maximum density: single-line responses, aggressive abbreviation, diff-only |
lean-ctx terse # show current terse mode
lean-ctx terse lite # set to lite mode
lean-ctx terse full # set to full mode
lean-ctx terse ultra # maximum compression
lean-ctx terse off # disable terse agent Token Reports
Generate detailed token usage reports for analysis and cost tracking.
lean-ctx token-report [flags]
Display a comprehensive token usage report for the current or specified project.
Also available as lean-ctx report-tokens (alias).
| Flag | Description |
|---|---|
(none) | Summary report for the current session |
--project=<path> | Report for a specific project directory |
--period=<p> | Time period: today, week, month, all |
--by-tool | Break down usage by MCP tool |
--by-mode | Break down usage by read mode |
--json | Machine-readable JSON output |
lean-ctx token-report # current session summary
lean-ctx token-report --period=week # weekly report
lean-ctx token-report --by-tool --period=month # monthly per-tool breakdown
lean-ctx report-tokens --json > report.json # alias, JSON export Cache Management
Manage the lean-ctx content cache that accelerates repeated reads and avoids redundant compression.
lean-ctx cache <subcommand> [flags]
| Subcommand | Description |
|---|---|
status | Show cache size, hit rate, and entry count |
clear | Clear all cached entries |
invalidate <pattern> | Invalidate cache entries matching a glob pattern |
reset --project=<path> | Reset cache for a specific project only |
lean-ctx cache status # cache stats
lean-ctx cache clear # purge entire cache
lean-ctx cache invalidate "src/**/*.rs" # invalidate Rust files
lean-ctx cache reset --project=~/my-app # reset for one project Gotchas
Manage known gotchas - common pitfalls, edge cases, and warnings that lean-ctx
tracks across your projects. Also available as lean-ctx bugs (alias).
lean-ctx gotchas [list|add|remove|clear]
| Subcommand | Description |
|---|---|
list | Show all tracked gotchas for the current project |
add "<description>" | Add a new gotcha entry |
remove <id> | Remove a gotcha by its ID |
clear | Remove all gotchas for the current project |
lean-ctx gotchas list
lean-ctx gotchas add "ctx_shell timeout on M1 with Docker Rosetta"
lean-ctx gotchas remove 3
lean-ctx bugs list # alias for gotchas list
lean-ctx bugs clear Buddy
The Buddy (also called Pet) is an interactive companion feature that provides contextual tips, encouragement, and session insights. Purely cosmetic and opt-in.
lean-ctx buddy [status|on|off|name <name>]
| Subcommand | Description |
|---|---|
status | Show buddy status and current name |
on | Enable the buddy |
off | Disable the buddy |
name <name> | Give your buddy a custom name |
lean-ctx buddy status # check buddy state
lean-ctx buddy on # enable buddy
lean-ctx buddy name Ferris # name your buddy
lean-ctx pet off # alias - disable buddy Context Packages
Create, manage, and share portable context packages that bundle knowledge, graph data, session findings, and gotchas into versioned archives.
lean-ctx pack create --name <name> [--layers <layers>]
Create a context package from the current project. Layers default to all available
(knowledge,graph,session,patterns,gotchas).
lean-ctx pack create --name my-pkg
lean-ctx pack create --name api-knowledge --layers knowledge,gotchas
lean-ctx pack create --name full-snapshot --version 2.0.0 lean-ctx pack list
List all installed packages with version and auto-load status.
lean-ctx pack list lean-ctx pack info <name>
Show detailed metadata, layers, stats, and integrity hash for a package.
lean-ctx pack info my-pkg lean-ctx pack export <name> [-o <file>]
Export a package to a portable .lctxpkg file. Default output is <name>.lctxpkg.
lean-ctx pack export my-pkg
lean-ctx pack export my-pkg -o shared/my-pkg.lctxpkg lean-ctx pack import <file>
Import a package from a .lctxpkg file. Verifies SHA-256 integrity before installing.
lean-ctx pack import my-pkg.lctxpkg lean-ctx pack install <name>
Merge a package's context into the current project — knowledge facts, graph nodes, and gotchas.
lean-ctx pack install my-pkg lean-ctx pack remove <name>
Remove a package from the local registry.
lean-ctx pack remove my-pkg lean-ctx pack auto-load <name> <on|off>
Enable or disable auto-loading. When enabled, the package is merged into the project
context automatically when ctx_overview runs at session start.
lean-ctx pack auto-load my-pkg on
lean-ctx pack auto-load my-pkg off Instructions
Manually retrieve MCP server instructions. Useful in headless or non-interactive environments where the MCP handshake does not automatically deliver instructions.
lean-ctx instructions [flags] v3.3.x
| Flag | Description |
|---|---|
(none) | Print current MCP instructions to stdout |
--raw | Output raw instruction text without formatting |
--json | Output as JSON object with metadata |
--inject | Inject instructions into the active agent session |
lean-ctx instructions # print formatted instructions
lean-ctx instructions --raw # raw text for piping
lean-ctx instructions --json # JSON with metadata
lean-ctx instructions --inject # inject into running session This is particularly useful when integrating lean-ctx into CI/CD pipelines or custom agent frameworks that don't support the MCP instructions handshake natively.