Reference

CLI Reference

Complete reference for every LeanCTX command, flag, and read mode.

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 LeanCTX's 95+ 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 LeanCTX'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 auto (AutoModeResolver picks the best mode per file type and size).

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] [--no-gitignore]

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>.

FlagDescription
--all / -aInclude hidden files (dotfiles)
--depth NLimit directory tree depth (default: 3)
--no-gitignoreShow all files regardless of .gitignore rules. Useful for inspecting build artifacts, node_modules/, or target/ directories.
lean-ctx ls
lean-ctx ls src/components/
lean-ctx ls --all .
lean-ctx ls --depth 5 src/
lean-ctx ls --no-gitignore build/

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. By default, .gitignore rules are respected, use --no-gitignore to override.

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:

ModeOutputUse caseSavings
autoBest mode for contextDefault when no mode specified - AutoModeResolver picks optimal strategy. Routes JSON/YAML/TOML/lock files to map mode automatically.60–95%
fullComplete file contentFiles you will edit. Re-reads cost ~13 tokens (cached).0% (first read), ~99% (cached)
mapCode: deps + exports + signatures. Non-code: structured outlines (headings, keys, lock summaries)Context-only files - understand structure without reading everything. Works for code, config, docs, and lock files.70-90%
signaturestree-sitter AST extraction (18 languages)API surface only - function/method/class signatures.92–99%
aggressiveSyntax-stripped contentMaximum compression while preserving logic.85–95%
entropyShannon entropy + Jaccard filteringKeep only information-dense lines.70–90%
diffChanged lines only (vs. last read)After editing - see only what changed.90–99%
taskTask-filtered contentIB-scored extraction based on current intent - only relevant code for the active task70–90%
referenceCross-reference contextRelated types, callers, and dependencies for the target symbol or function60–85%
lines:N-MSpecific line rangesRead only the section you need. Supports multiple ranges: lines:10-50,80-100varies

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 onboard

The zero-prompt golden path and the recommended way to connect your tools: detects every installed AI editor and shell, wires up the hook and MCP configs, and applies sensible defaults — no questions asked. Run setup instead when you want full control over every option.

lean-ctx onboard       # connect everything, zero prompts

lean-ctx status [--json]

The quick "am I connected?" check: shell hook, MCP configs, rules and daemon state in one glance. Use --json in scripts or CI; use doctor when something is actually broken.

lean-ctx status        # human-readable
lean-ctx status --json # machine-readable

lean-ctx bootstrap

Non-interactive setup plus repair in one command — the CI/container variant of onboard. Idempotent: safe to run on every boot of an ephemeral environment.

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 LeanCTX.

lean-ctx setup

This runs three steps internally:

  1. Installs shell aliases (init --global)
  2. Configures MCP for each detected AI tool
  3. 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 LeanCTX 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 95+ 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, LeanCTX 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.

StyleBehavior
autoAuto-detect: uses drop-in if a .d/ directory exists, otherwise inline (default)
inlineWrites a fenced block directly into your shell profile (~/.zshenv, ~/.bashrc, etc.)
dropinCreates 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.

AgentNotes
cursorCursor IDE (default MCP setup)
claudeClaude Code / Claude Desktop
codexOpenAI Codex CLI
geminiGoogle Gemini CLI
antigravityAntigravity IDE (~/.gemini/antigravity/)
antigravity-cliAntigravity CLI 2.0 (~/.gemini/antigravity-cli/)
openclawOpenClaw (~/.openclaw/openclaw.json)
augmentAugment Code
windsurfWindsurf IDE
copilotGitHub Copilot
clineCline (VS Code extension)
rooRoo Code
aiderAider CLI
continueContinue.dev
zedZed Editor
voidVoid Editor
ampAmp (Sourcegraph)
traeTrae IDE
kiloKilo Code
opencodeOpenCode CLI
piInstalls pi-lean-ctx npm package
customGeneric 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      # Antigravity IDE
lean-ctx init --agent antigravity-cli  # Antigravity CLI 2.0
lean-ctx init --agent openclaw
lean-ctx init --agent augment
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_mode failures  # tee failed-command output to disk
lean-ctx config set checkpoint_interval 20

Settable Configuration Keys

Since v3.6.23, config set accepts any key defined in the config schema (run lean-ctx config schema for the full list). Values are validated by type, and enum keys list their allowed values on invalid input. Commonly used keys:

KeyTypeDefaultDescription
ultra_compactboolfalseEnable ultra-compact output mode for maximum token savings
tee_modestring"failures"When to tee full command output to disk: off, failures (default), or always.
checkpoint_intervalint15Number of MCP calls between automatic checkpoints
themestring"default"Dashboard and TUI theme (default, dark, light, neon)
compression_levelenum"lite"Output compression level: off, lite, standard, max
profilestring""Active profile (e.g. coder, passthrough)
slow_command_threshold_msint5000Threshold in milliseconds for slow-log entries
passthrough_urlsstring[][]URL patterns that bypass compression (comma-separated)
rules_scopestring"both"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 config show v3.6.18

Shows all effective configuration values with their source (env, config, or default). Displays simplified high-level settings and their derived downstream limits in a structured view. Useful for understanding how max_disk_mb scales memory limits proportionally.

lean-ctx config show                       # show effective values with sources
lean-ctx config effective                  # alias for 'show'

lean-ctx tools [minimal|standard|power|show|list]

Controls how many MCP tools your agent sees. Fewer tool definitions mean a smaller system prompt; minimal exposes the core read/search/shell surface, standard the daily-driver set, power everything. show prints the active profile, list all tools with their profile tier.

lean-ctx tools minimal   # smallest prompt footprint
lean-ctx tools standard  # balanced (default for most setups)
lean-ctx tools power     # all tools
lean-ctx tools show      # which profile is active?

lean-ctx compression [off|lite|standard|max]

Sets the global compression level (alias: terse). Higher levels save more tokens per command at the cost of more aggressive summarization — standard is the calibrated default.

lean-ctx compression max       # densest output
lean-ctx compression standard  # default
lean-ctx compression off       # passthrough (same as LEAN_CTX_RAW=1)

lean-ctx profile [list|show|diff|create|set]

Context profiles bundle compression level, read-mode defaults and tool surface into a named, switchable preset — for example a conservative profile for reviews and an aggressive one for exploration.

lean-ctx profile list
lean-ctx profile show
lean-ctx profile set balanced

lean-ctx theme [list|set|export|import]

Terminal color themes for gain, watch and friends.

lean-ctx theme list
lean-ctx theme set neon

lean-ctx rules [sync|diff|lint|status|init]

ContextOps for agent rules: keeps .cursorrules, AGENTS.md, CLAUDE.md and friends in sync from one source, shows drift, and lints rule files across every agent you use.

lean-ctx rules status          # which rule files exist, and are they in sync?
lean-ctx rules sync            # write the synced rules to every agent
lean-ctx rules diff            # show drift before syncing
lean-ctx rules dedup           # find duplicate lean-ctx rule files/blocks (v3.8.3)
lean-ctx rules dedup --apply   # remove the duplicates

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
  • Linux: systemctl --user is-active daemon state and loginctl enable-linger warning
  • Crash-loop log: restart count and log file path
lean-ctx doctor
lean-ctx doctor integrations   # premium integration checks
lean-ctx doctor overhead       # per-client fixed session cost report (v3.8.3)
lean-ctx doctor --migrate-check  # v1.0 migration readiness audit
lean-ctx doctor --fix --json   # repair + machine-readable report

lean-ctx update [<version>] [--check]

Self-update the LeanCTX 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 update 3.8.5   # pin a specific tagged release (v-prefix optional)
lean-ctx update v3.8.5 --check  # report whether the pinned version differs

#447 Pass an optional version to install that exact tagged GitHub release instead of the latest — handy to roll back or A/B an older build. It reuses the normal update path (SHA256-verified download, atomic binary swap, post-update rewire), so no data, config or logs are touched — only the binary is swapped, and a downgrade reads your existing data as-is. Invalid versions are rejected before any network call. The daily auto-update scheduler is unaffected and keeps tracking the latest release.

lean-ctx codesign-setup macOS · #356

Create and trust a persistent, self-signed code-signing identity in a dedicated keychain so macOS stops re-asking for Documents / Desktop / Downloads access after every update. Run it once — it asks for a single Touch ID / login-password confirmation to trust the identity. Afterwards dev-install and the self-updater sign every build with it, giving TCC a stable Designated Requirement instead of a per-build code hash, so a single "Allow" survives all future updates. Without it, lean-ctx falls back to ad-hoc signing and still runs (the prompt may keep returning).

lean-ctx codesign-setup   # one-time: create + trust the signing identity (macOS only)

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 provider <auth|list|logout> v3.6.25

Manage OAuth credentials for context providers. Currently supports Jira Cloud OAuth 2.0 (3LO) as an alternative to Basic auth (email + API token).

lean-ctx provider auth jira      # run the interactive OAuth flow for Jira
lean-ctx provider list           # show configured providers and credential status
lean-ctx provider logout jira    # remove stored Jira OAuth credentials

provider auth jira opens your browser for consent, captures the redirect on a local loopback port, discovers your accessible site (cloudId), and stores tokens in ~/.lean-ctx/credentials/jira-oauth.json (0600). Access tokens are refreshed automatically with refresh-token rotation. LeanCTX ships no embedded client secret, register your own Atlassian OAuth app and provide its credentials via env (see Configuration → Jira OAuth).

To select OAuth for a data source, set JIRA_AUTH=oauth (or simply have a stored credential); Basic auth via JIRA_EMAIL + JIRA_API_TOKEN continues to work unchanged.

lean-ctx uninstall [--keep-config]

Remove all LeanCTX configuration: shell hooks, MCP configs from all editors, .bak files, ~/.config/lean-ctx, project-local .lean-ctx/ and .lean-ctx-id, Claude CLI MCP entries, and daemon/proxy services. Use --keep-config to preserve MCP configs for reinstall.

Removes shell hooks, MCP configurations from all detected editors, .bak files, ~/.config/lean-ctx, project-local .lean-ctx/ and .lean-ctx-id, Claude CLI MCP entries, and daemon/proxy services.

Use --keep-config to preserve MCP configs and rules for reinstall.

lean-ctx uninstall
lean-ctx uninstall --keep-config

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 LeanCTX 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.

FlagOutput
(none)Full dashboard: total saved, rate, USD, top commands, sparklines
--scoreGainScore (0–100) combining compression ratio, cost efficiency, quality, and consistency
--costCost breakdown per model with embedded pricing (supports --model=<name> filter)
--tasksTask classification breakdown across 13 categories (file-ops, search, shell, memory, etc.)
--agentsPer-agent statistics in multi-agent sessions (calls, tokens, cost attribution)
--heatmapFile access heatmap - which files are read most frequently by the AI
--wrappedSpotify-Wrapped-style session summary (supports --period=week|month|all)
--deepCombined deep-dive: report + tasks + cost + agents + heatmap in one output
--liveAuto-refreshing mode (updates every 2s). Press q to quit.
--graph30-day savings chart with daily bars
--dailyBordered day-by-day table with token counts and USD
--pipelinePipeline-view: shows compression stages and per-stage token savings
--opportunityFind missed savings in your shell history — surfaces native commands that should have run through lean-ctx (replaces the old discover/ghost views).
--rawPlain, machine-friendly stats with no styling (pairs with --json).
--jsonRaw JSON export of all stats (for scripting/automation)

Modifiers

FlagOutput
--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)
--resetClear 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 --opportunity            # missed-savings report from shell history
lean-ctx gain --raw --json             # plain machine-friendly stats
lean-ctx gain --json > stats.json      # machine-readable export

Sharing your recap

Turn any recap into something you can post. Sharing is opt-in and privacy-safe: only a whitelisted, aggregate slice (tokens saved, USD estimate, period, compression rate, command/session/file counts, tool names, optional model, and an optional display name) ever leaves your machine, never code, paths, or prompts.

FlagOutput
--svg [=<path>]Write the Wrapped card as an SVG (social / OG image) — defaults to lean-ctx-wrapped.svg
--share [=<path>]Write a self-hostable Wrapped page (HTML) with social-preview meta — defaults to lean-ctx-wrapped.html
--copyCopy a ready-to-post share line to the clipboard (pbcopy/clip/wl-copy/xclip/xsel)
--openWith --svg/--share: also open the written card/page in your browser
--publish [--name=<n>]Anonymously publish the recap and get a permalink at leanctx.com/w/<id> (URL copied to the clipboard). A one-time edit token is stored locally for later removal.
--leaderboardWith --publish: also list the card on the opt-in public leaderboard (off by default)
--unpublish[=<id>]Remove a published permalink (most recent publish if no id is given)
lean-ctx gain --svg                         # SVG card -> lean-ctx-wrapped.svg
lean-ctx gain --share --open                # self-hostable HTML page, opened in browser
lean-ctx gain --copy                        # copy a share line to the clipboard
lean-ctx gain --publish                     # opt-in permalink -> leanctx.com/w/<id>
lean-ctx gain --publish --name="Ada"        # publish with a display name
lean-ctx gain --publish --leaderboard       # publish and join the public leaderboard
lean-ctx gain --unpublish                   # remove your most recent published card

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.

FlagDescription
(none)Pretty-print CEP score with breakdown
--jsonMachine-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] [--host=H] [--project=<path>] [--base-path=<path>] [--auth-token=TOKEN] [--open=MODE]

Open the interactive web dashboard at http://localhost:3333. Features interactive charts, session history, active agents, and project knowledge panels.

FlagDescription
--port=<N>Custom port (default: 3333)
--host=<H>Bind address. Defaults to 127.0.0.1 (loopback only); set 0.0.0.0 for remote access — which requires a token (see --auth-token).
--project=<path>Scope dashboard to a specific project directory instead of the global view
--base-path=<path> v3.7.4Serve the dashboard under a subpath behind a reverse proxy (e.g. https://host/leanctx/); all asset and API URLs are rewritten to honor it. (#355)
--auth-token=<token> #377Pin the Bearer token required for every request (alias --token; overrides LEAN_CTX_HTTP_TOKEN). Mandatory for non-loopback binds; if unset on a loopback bind a random token is generated each start.
--open=<mode> / --no-open #424Reveal mode after start: browser (default — launch the system browser), none (start silently and just print the URL) or vscode (suppress the external browser and print the VS Code Simple Browser steps). Resolved as flag > LEAN_CTX_DASHBOARD_OPEN > the browser default; --no-open is shorthand for none.
lean-ctx dashboard                        # opens at localhost:3333
lean-ctx dashboard --port=8080            # custom port
lean-ctx dashboard --host=0.0.0.0 --auth-token=secret  # remote access, token required
lean-ctx dashboard --project=~/my-app     # scoped to a single project
lean-ctx dashboard --base-path=/leanctx   # mount under a reverse-proxy subpath
lean-ctx dashboard --open=none            # start silently, just print the URL

lean-ctx gain --wrapped [--period=week|month|all]

Generate a shareable "Wrapped" report card of your token savings.

The standalone lean-ctx wrapped command was removed in v3.7; the binary now points you here. The sharing flags (--svg, --share, --copy, --open, --publish, --leaderboard) all live under gain.

FlagPeriod
(none)Current week
--period=weekCurrent week (explicit)
--period=monthCurrent month
--period=allLifetime stats
lean-ctx gain --wrapped
lean-ctx gain --wrapped --period=month
lean-ctx gain --wrapped --period=all

Session Management

lean-ctx sessions [list|show|cleanup]

Manage CCP (Context Continuity Protocol) sessions stored at ~/.lean-ctx/sessions/.

SubcommandAction
listList all saved sessions
showShow the latest session state
cleanupRemove 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 LeanCTX 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] [--json]

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 recall "auth" --json    # machine-readable (v3.7.4)

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

lean-ctx benchmark scorecard [--json]

Reproducible savings + recall + latency scorecard you can publish or attach to a PR.

lean-ctx benchmark scorecard          # human-readable scorecard
lean-ctx benchmark scorecard --json   # machine-readable scorecard

lean-ctx benchmark compare [--output F]

Head-to-head comparison of lean-ctx against competing context tools.

lean-ctx benchmark compare                  # print comparison table
lean-ctx benchmark compare --output cmp.md  # write the comparison to a file

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 [--card]

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.

On its very first run, discover surfaces a concrete, projected token saving for the current project (a one-time "aha", recorded with a marker in ~/.lean-ctx). Add --card to export a shareable "before lean-ctx" SVG of that projection.

FlagOutput
(none)List uncompressed commands found in your shell history
--card [=<path>]Write a shareable "before lean-ctx" SVG — defaults to lean-ctx-before.svg
lean-ctx discover
lean-ctx discover --card                    # SVG -> lean-ctx-before.svg

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.

SubcommandAction
listList all error log files
clearDelete 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 and (re)build the dependency-graph index. A plain graph build rescans incrementally: files whose content is unchanged are reused via their content hash, so the graph always reflects the current source. Pass --force (-f) to purge the cached index and rebuild from scratch. The graph is also built automatically when MCP tools are used.

lean-ctx graph build
lean-ctx graph build --force   # purge cache, rebuild from scratch

lean-ctx graph status

Show graph index statistics: file count, symbol count, edge count, language breakdown, and storage path.

lean-ctx graph status

List files related to a given file based on import/dependency edges in the project graph.

lean-ctx graph related src/server/mod.rs

lean-ctx graph impact <file>

Show the blast radius, all files that depend on the given file and would be affected by changes to it.

lean-ctx graph impact src/core/cache.rs

lean-ctx graph symbol <spec>

Inspect a specific symbol definition. The spec format is file.rs::function_name.

lean-ctx graph symbol src/core/cache.rs::SessionCache

lean-ctx graph context <query>

Query the property graph for a concept or keyword. Searches nodes by name and returns matching definitions.

lean-ctx graph context "authentication"

lean-ctx index <status|build|build-full|watch>

The codebase index behind semantic search, BM25 retrieval and the graph. build refreshes incrementally, build-full rebuilds from scratch, watch keeps it warm as files change.

lean-ctx index status
lean-ctx index build       # incremental refresh
lean-ctx index watch       # continuous re-index

lean-ctx overview [task]

One-screen project orientation: structure, entry points, key files and recent activity. Pass a task description and the overview is ranked for that task.

lean-ctx overview
lean-ctx overview "fix the login flow"

Context Planning & Analysis

These commands expose the planning engine directly: score, assemble and inspect the context your agent gets, before a single token is spent.

lean-ctx plan <task> [--budget=N]

Produces an optimal context plan for a task: which files, in which read mode, under a token budget — ranked by the same Phi scoring the MCP server uses.

lean-ctx plan "add rate limiting to the API" --budget=8000

lean-ctx compile [--mode=<m>] [--budget=N]

Compiles the planned context into ready-to-paste handles (expand with ctx_expand @ref) using knapsack selection under your budget.

lean-ctx control <action> [--target=<t>]

Context field manipulation from the CLI: exclude noisy paths, pin must-have files, raise or lower priorities. The same controls live in Context Control & Overlays.

lean-ctx control exclude --target="dist/**"
lean-ctx control pin --target="src/core/cache.rs"

lean-ctx compress [--signatures]

Manual context compression checkpoint: snapshots the session and compacts what the agent carries forward — the CLI twin of ctx_compress.

lean-ctx verify-cache [path] [--json]

Proves the session cache works on your machine: reads a file twice and shows the second read collapsing to a ~13-token stub. The fastest demo of the caching claim.

lean-ctx verify-cache src/main.rs

lean-ctx smells [scan|summary|rules|file]

Property-graph code smell detection (8 rules): god files, cyclic modules, orphan exports and friends — the structural signals the planner also uses for ranking.

lean-ctx smells scan
lean-ctx smells summary --json

lean-ctx visualize [--output F] [--open]

Generates an interactive HTML report of the project graph (D3.js) you can open and explore.

lean-ctx visualize --open

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
LevelCommandsBehavior
VERBATIMdf, git status, git stash, ls, find, wc, envZero compression. Output passes through completely unmodified.
MINIMALgit diff, git log, docker ps, grep, ruff, npm audit, pytest, pip, curlLight formatting only. All safety-critical data (code diffs, error details, CVE IDs, health status) is fully preserved.
STANDARDcargo build, npm install, eslint, tsc, go build, maven, gradle, dotnetStructured compression. Errors, warnings, and actionable items always preserved.
AGGRESSIVEkubectl describe, aws, terraform, docker imagesHeavy 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 LeanCTX 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]

FlagDescription
(none)Print full audit report to stdout
--period=<p>Time period: today, week, month, all
--project=<path>Scope audit to a specific project directory
--jsonMachine-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 LeanCTX security controls map to OWASP LLM Top 10 categories

lean-ctx audit evidence --from <rfc3339> --to <rfc3339>

Exports a deterministic, Ed25519-signed evidence bundle (open contract evidence-bundle-v1): the tamper-evident audit-chain segment for the period, the resolved policy pack in force, and the CGB + framework coverage reports. Identical inputs produce byte-identical bundles. Auditors verify offline with the standalone leanctx-verify tool — no LeanCTX installation required.

FlagDescription
--from / --toReporting period, RFC 3339 timestamps (required)
--framework <id>Include a framework coverage report: eu-ai-act, iso42001 or soc2
--pack <name|path>Policy pack to resolve and attest (defaults to the active pack)
--out <file.zip>Output path for the bundle
lean-ctx audit evidence --from 2026-05-01T00:00:00Z --to 2026-06-01T00:00:00Z \
    --framework eu-ai-act --out q2-evidence.zip

# verify offline, on any machine (no LeanCTX needed):
leanctx-verify q2-evidence.zip                # 5 PASS/FAIL steps, exit 0 = valid

Policy packs & compliance

Policy packs pin governance expectations — default read mode, allowed/denied tools, redaction patterns, audit retention, context budgets — as reviewable TOML with single inheritance (extends). Built-in packs include baseline, strict-redaction and the framework templates eu-ai-act-deployer, iso42001-aligned and soc2-context.

lean-ctx policy list

Lists built-in packs plus the project pack (.lean-ctx/policy.toml) if present.

lean-ctx policy list

lean-ctx policy show <name> [--toml]

Shows the resolved effective policy after inheritance. --toml prints copy-pasteable TOML — the fastest way to start a project pack from a built-in.

lean-ctx policy show baseline --toml > .lean-ctx/policy.toml

lean-ctx policy validate [path]

Validates a pack file (defaults to .lean-ctx/policy.toml) against the context-policy-packs-v1 contract.

lean-ctx policy validate

lean-ctx policy coverage [--framework <id>] [--json]

Without --framework: automated partial assessment against the Context Governance Benchmark. With --framework (eu-ai-act, iso42001, soc2): renders the per-control compliance report — each control as ENFORCED (verified live against your resolved pack), ENGINE (CI-proven engine guarantee), NOT-ENFORCED (exit code 1, CI-gateable) or GAP (documented organisational duty). See Compliance & Evidence for the full model.

lean-ctx policy coverage --benchmark cgb        # CGB self-assessment
lean-ctx policy coverage --framework eu-ai-act  # EU AI Act control report
lean-ctx policy coverage --framework soc2 --json | jq '.controls[]'

Agent identities

First-class agent identities: every agent is registered with a stable agent_id, a role and a mandatory human owner. Lifecycle transitions (register, suspend, resume, decommission) write tamper-evident audit entries; attestation hashes the running binary and role config to surface drift. See Agent Governance for the model.

lean-ctx agent register --id <id> --role <role> --owner <user@org>

Registers a new identity and provisions its Ed25519 keypair. Fails without an owner — accountability is structural. Prints the SPIFFE-compatible workload id.

lean-ctx agent register --id ci-reviewer-1 --role reviewer --owner alice@org

lean-ctx agent list [--json] / agent show <id>

Registry snapshot: status, owner, role, last heartbeat. show adds attestation hashes and the SPIFFE id (--trust-domain to set yours).

lean-ctx agent list
lean-ctx agent show ci-reviewer-1 --trust-domain org.example

lean-ctx agent heartbeat <id>

Liveness plus re-attestation. Exit code 3 on drift (binary or role config changed since registration) — alertable from any monitor.

lean-ctx agent heartbeat ci-reviewer-1

lean-ctx agent suspend|resume|decommission <id>

Suspension carries a --reason and is reversible; decommissioning is final by design — the record stays for auditability and is never reactivated.

lean-ctx agent suspend ci-reviewer-1 --reason "incident review"
lean-ctx agent resume ci-reviewer-1
lean-ctx agent decommission ci-reviewer-1     # writes the audit-closing entry

lean-ctx agent offboard-owner <user@org>

Suspends every active agent of an owner in one locked transaction, each suspension individually audited — wire it to your SCIM deprovisioning flow. No orphaned agents.

lean-ctx agent offboard-owner alice@org --reason "left company"

lean-ctx agent check <id>

Enforce-path decision point: exit 0 only for registered and active agents. Unregistered, suspended or decommissioned → exit 1 with the reason.

lean-ctx agent check ci-reviewer-1 || echo "denied"

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.

lean-ctx allow <cmd> [--list] [--remove]

Manage the user allowlist extension (shell_allowlist_extra) without hand-editing config.toml. Entries are merged on top of the built-in defaults.

FlagDescription
allow <cmd>Add a command (pattern) to shell_allowlist_extra.
--listList the commands you have added (aliases: list, ls).
--remove <cmd>Remove a command you previously added (aliases: -r, remove, rm).
lean-ctx allow "terraform *"      # allow a new command family
lean-ctx allow --list             # show your added commands
lean-ctx allow --remove "terraform *"

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:

AliasAction
lean-ctx-onEnable all compression aliases
lean-ctx-offDisable compression (human-readable output)
lean-ctx-statusShow 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

LeanCTX 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.

FlagDefaultDescription
--port=<N>8080Port to listen on
--host=<addr>127.0.0.1Bind address (0.0.0.0 for all interfaces)
--statelessoffDisable session persistence - each request is independent
--rate-limit=<N>100Max requests per minute per client
--timeout=<ms>30000Request timeout in milliseconds
--corsoffEnable 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=8080

Once running, all MCP tools are available at POST /v1/tools/<tool_name>. A health endpoint is at GET /health.

lean-ctx watch

Start LeanCTX 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.

FlagDescription
--filter=<pattern>Only show events matching the pattern (e.g. ctx_read, error)
--no-tuiHeadless 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 LeanCTX network proxy. When active, the proxy intercepts MCP traffic and applies compression transparently. Requires the proxy feature gate.

SubcommandDescription
startStart the proxy daemon
stopStop the running proxy
statusShow 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

lean-ctx daemon <start|stop|restart|status|enable|disable>

Manages the background IPC daemon that keeps the index, cache and session state warm between calls. enable/disable control auto-start on login (LaunchAgent on macOS, systemd on Linux) and print the exact service file path; status shows the unit name, file path and supervision state, and restart bounces the daemon through whichever channel is active — the supervised service or a manually started process.

lean-ctx daemon status
lean-ctx daemon enable     # auto-start on login (prints service file path)
lean-ctx daemon restart    # bounce the daemon (service-aware)
lean-ctx daemon disable

lean-ctx stop / lean-ctx restart

stop halts all lean-ctx processes — daemon, proxy and any orphans — in one command (use it before manual builds or upgrades). restart bounces the daemon and applies config.toml changes.

lean-ctx stop              # stop everything cleanly
lean-ctx restart           # apply config changes

Team Plane & Extensions optional · additive

Local single-user features stay free and ungated (the Local-Free Invariant). These commands drive the optional commercial Team plane and the open extension surface.

lean-ctx team <serve|token|sync>

CommandDescription
team serve --config <path>Run the multi-tenant Team Server from a TOML config (workspaces, signing key, port).
team token create --config <path> --id <name> --role <role>Mint an RBAC token. --role = viewer|member|admin|owner; or grant explicit --scope (CSV).
team sync --config <path> --workspace <id>Synchronise local session / knowledge state with a Team Server workspace.
lean-ctx team serve --config team.toml
lean-ctx team token create --config team.toml --id ci --role member
lean-ctx team token create --config team.toml --id indexer --scope search,graph,index

lean-ctx billing <plans|entitlements|usage>

CommandDescription
billing plansList available plans (--json for machine output).
billing entitlements <plan>Show the entitlements a plan grants.
billing usageShow current usage / metering (default subcommand; --json supported).
lean-ctx billing plans
lean-ctx billing usage --json

lean-ctx savings <summary|roi|verify|rechain|sign|export|team>

The savings ledger is a signed, tamper-evident receipt of every token you saved.

CommandDescription
savings summaryHuman-readable savings summary (default subcommand).
savings roiReturn-on-investment view of the ledger (--json supported).
savings verify / verify-batchVerify the hash chain (whole ledger or a batch file).
savings rechainRepair / rebuild the ledger hash chain.
savings sign / pushSign a snapshot (--out) or push it to a Team Server (--team-url).
savings exportExport the ledger (signed snapshot / batch) for archival or a team roll-up.
savings teamPull the aggregated team savings roll-up from the configured Team Server.
lean-ctx savings roi --json
lean-ctx savings sign --out savings.signed.json
lean-ctx savings export > savings.json
lean-ctx savings team                          # team-wide roll-up

lean-ctx finops export [--target=focus|cbf|vantage]

Export ledger costs/savings for FinOps platforms in their native formats.

FlagDescription
--target=<t>focus (FinOps FOCUS CSV, default), cbf (CloudZero Common Bill Format), or vantage (Vantage custom-provider CSV).
--from=<date> / --to=<date>Restrict the export to a date range (YYYY-MM-DD).
--out=<file>Write the export to a file instead of stdout.
--uploadPost the export directly to the target API (cbf or vantage; FOCUS is file-only).
lean-ctx finops export                                   # FOCUS CSV to stdout
lean-ctx finops export --target=cbf --out=bill.csv       # CloudZero CBF file
lean-ctx finops export --target=vantage --from=2026-01-01 --upload

lean-ctx learning [status|export|import]

Inspect, share and merge lean-ctx's adaptive-learning state (learned patterns and tuning).

SubcommandDescription
statusShow the current adaptive-learning state (default subcommand).
exportExport learned patterns as a portable file to share with your team.
importMerge a teammate's exported learning file into your local state.
lean-ctx learning status
lean-ctx learning export > learning.json
lean-ctx learning import learning.json

lean-ctx plugin <list|enable|disable|info|init|hooks>

Plugins are discovered from <config-dir>/lean-ctx/plugins (override with LEAN_CTX_PLUGINS_DIR); WebAssembly extensions load from LEAN_CTX_WASM_DIR.

CommandDescription
plugin listList discovered plugins and their status.
plugin init <name>Scaffold a new plugin (plugin.toml + hooks).
plugin enable|disable <name>Toggle a plugin on or off.
plugin info <name> / hooksInspect a plugin manifest, or list available lifecycle hooks.
lean-ctx plugin init my-compressor
lean-ctx plugin list
lean-ctx conformance --json        # verify the binary + extensions meet the contract

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.

ModeDescription
offTerse Agent disabled - standard MCP output
liteLight compression: removes boilerplate, keeps structure
fullFull terse mode: abbreviated keys, minimal whitespace, Fn refs
ultraMaximum 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).

FlagDescription
(none)Summary report for the current session
--project=<path>Report for a specific project directory
--period=<p>Time period: today, week, month, all
--by-toolBreak down usage by MCP tool
--by-modeBreak down usage by read mode
--jsonMachine-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 LeanCTX content cache that accelerates repeated reads and avoids redundant compression.

lean-ctx cache <subcommand> [flags]

SubcommandDescription
statsShow cache size, hit rate, and entry count
pruneEvict stale and oversized entries to bring the cache back under its size/age budget.
invalidate <pattern>Invalidate cache entries matching a glob pattern
clearClear all cached entries
reset --project=<path>Reset cache for a specific project only
lean-ctx cache stats                           # cache stats
lean-ctx cache prune                           # evict stale / oversized entries
lean-ctx cache invalidate "src/**/*.rs"        # invalidate Rust files
lean-ctx cache clear                           # purge entire cache
lean-ctx cache reset --project=~/my-app        # reset for one project

Gotchas

Manage known gotchas - common pitfalls, edge cases, and warnings that LeanCTX tracks across your projects. Also available as lean-ctx bugs (alias).

lean-ctx gotchas [list|clear|export|stats]

SubcommandDescription
listShow all tracked gotchas for the current project
clearRemove all gotchas for the current project
exportExport captured gotchas as JSON for sharing or backup.
statsShow gotcha counts and how often each one has been surfaced.
lean-ctx gotchas list
lean-ctx gotchas export > gotchas.json
lean-ctx gotchas stats
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 [show|stats|ascii|json]

SubcommandDescription
showRender your buddy with its current mood and stats (default subcommand).
statsShow buddy level, streak and lifetime token savings.
asciiPrint the ASCII-art buddy (great for shell prompts / MOTD).
jsonMachine-readable buddy state for scripts and status bars.
lean-ctx buddy                 # show buddy (default)
lean-ctx buddy stats           # level, streak, lifetime savings
lean-ctx buddy ascii           # ASCII-art buddy
lean-ctx pet json              # alias - machine-readable state

Context Packages

The .ctxpkg format is an open file format. See the specification at ctxpkg.org

Create, manage, and share graph-native context packages using the open .ctxpkg format. Three conformance levels (Basic, Graph, Cognitive), scoped names (@scope/name), and composable knowledge graphs. LeanCTX is the reference implementation.

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 .ctxpkg file. Default output is <name>.ctxpkg. Add --sign for an ed25519 signature (required for publishing); a built-in secret scan blocks credential-shaped content.

lean-ctx pack export my-pkg
lean-ctx pack export my-pkg -o shared/my-pkg.ctxpkg

lean-ctx pack import <file>

Import a package from a .ctxpkg file. Verifies both SHA-256 integrity hashes against the document text (spec §8) and, for signed packages, the ed25519 signature (§9) — a package modified after signing is rejected.

lean-ctx pack import my-pkg.ctxpkg

lean-ctx pack verify <file> [...]

Verify a .ctxpkg file without installing anything: structure, both integrity hashes and the signature, reported per check. Exit code 0/1 makes it CI-friendly — the same checks every conforming reader runs, usable against the official conformance vectors.

lean-ctx pack verify my-pkg.ctxpkg
lean-ctx pack verify vectors/*.ctxpkg   # conformance vectors, exit 1 on any failure

lean-ctx pack install <name>

Merge a package's context into the current project, knowledge facts, graph nodes, and gotchas. With a scoped name (<ns>/<name>) it installs from the hosted registry — verified on your machine and pinned in ctxpkg.lock. Private or paid packages authenticate with a read-only ctxr_… install token (safe for CI; cannot publish).

lean-ctx pack install my-pkg
lean-ctx pack install leanctx/rust-axum-patterns   # from ctxpkg.com

lean-ctx pack publish <file>

Publish a signed package to the hosted registry under your @namespace. Mint the ctxp_… token at ctxpkg.com/account; the server re-verifies name binding, integrity, signature and runs a hard secret scan before accepting.

lean-ctx pack export my-pkg --sign -o my-pkg.ctxpkg
CTXPKG_TOKEN=ctxp_… lean-ctx pack publish my-pkg.ctxpkg

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

FlagDescription
(none)Print current MCP instructions to stdout
--rawOutput raw instruction text without formatting
--jsonOutput as JSON object with metadata
--injectInject 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 LeanCTX into CI/CD pipelines or custom agent frameworks that don't support the MCP instructions handshake natively.