ドキュメント

CLIリファレンス

すべてのlean-ctxコマンド、フラグ、読み取りモードの完全なリファレンス。

すべてのlean-ctxコマンドの完全なリファレンスです。クイックチートシートはクイックリファレンスを参照してください。アナリティクスとダッシュボードの詳細はアナリティクスガイドを参照してください。


シェル圧縮

これらのコマンドは、シェルコマンドをlean-ctxの95以上の圧縮パターンで処理します。出力はLLMに到達する前にノイズ、ボイラープレート、冗長性が自動的に除去されます。

lean-ctx -c "<command>"

任意のシェルコマンドを実行し、出力を圧縮。エイリアス: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"

シェルフック(lean-ctx initでインストール)は一般的なコマンドに対してこれを自動化します - -cプレフィックスは不要です。シェルフックの対象外のコマンドには-cを明示的に使用してください。

lean-ctx shell

すべてのコマンド出力が圧縮されるインタラクティブシェルセッションを開始。デフォルトシェル(zsh、bash、または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モード

圧縮なしの完全な出力が必要な場合、3つの方法で有効化できます:

# 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>"

圧縮なしを保証して任意のコマンドを実行します。内部的にコマンド実行前にLEAN_CTX_RAW=1を設定します。出力が未変更であることを絶対的に確認したい場合に使用します。

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

ヒント: bypassLEAN_CTX_RAW=1 lean-ctx -c "command" と同等ですが、より便利です。コマンド文字列はシェルに直接渡されます。


ファイル操作

lean-ctxのファイル読み取り、検索、ナビゲーションツールへの直接CLIアクセス。MCPサーバーがAIツールに提供するものと同じ操作です。

lean-ctx read <file> [-m <mode>]

オプションの圧縮モードを指定してファイルを読み取り。デフォルトモードは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>

構造化された変更概要付きの2ファイル間の圧縮差分。

lean-ctx diff old.rs new.rs

lean-ctx grep <pattern> [path]

圧縮されたグループ化結果によるファイル内容検索。内部でripgrepを使用。

lean-ctx grep "pub fn" src/
lean-ctx grep "TODO" .
lean-ctx grep "async fn.*Result" rust/src/

lean-ctx find <pattern> [path]

名前パターンでファイルを検索。.gitignoreを尊重し、コンパクトなファイルツリーを出力。

lean-ctx find "*.rs" src/
lean-ctx find "test_*" .

lean-ctx ls [path]

ファイル数付きのコンパクトなツリーマップとしてのディレクトリ一覧。

lean-ctx ls
lean-ctx ls src/components/

lean-ctx deps [path]

プロジェクトの依存関係グラフを表示。パッケージマネージャーを検出し、依存関係を抽出。

lean-ctx deps .
lean-ctx deps frontend/

読み取りモード

読み取りモードはlean-ctx readおよびMCPツールctx_readがファイル内容を圧縮する方法を制御します。ユースケースに合ったモードを選択してください:

モード出力ユースケースSavings
auto最適なコンテキストモードモード未指定時のデフォルト:lean-ctx が最適戦略を選択60–95%
full完全なファイル内容編集するファイル。再読み込みは約13 token(cache済み)。0%(初回読み取り)、約99%(cache済み)
map依存関係グラフ + エクスポート + 主要シグネチャコンテキスト参照用ファイル - すべてを読まずに構造を把握。90–98%
signaturestree-sitter AST抽出(18言語対応)APIサーフェスのみ - 関数/メソッド/クラスのシグネチャ。92–99%
aggressive構文除去済みコンテンツロジックを保持しつつ最大圧縮。85–95%
entropyShannonエントロピー + Jaccardフィルタリング情報密度の高い行のみを保持。70–90%
diff変更行のみ(前回の読み取りとの差分)編集後 - 変更箇所のみを確認。90–99%
taskタスクに絞った内容現在の意図に基づく IB スコア抽出-アクティブなタスクに必要なコードだけ返す70–90%
referenceクロスリファレンス・コンテキスト対象シンボル/関数の関連型・呼び出し元・依存関係60–85%
lines:N-M特定の行範囲必要なセクションのみを読み取り。複数範囲に対応:lines:10-50,80-100varies

signaturesモード対応言語:TypeScript、JavaScript、Rust、Python、Go、Java、C、C++、Ruby、C#、Kotlin、Swift、PHP(tree-sitter経由で合計14言語)。


セットアップと設定

lean-ctx setup

ワンコマンドセットアップ。シェル(zsh/bash/fish/PowerShell)を自動検出し、インストール済みのAIツールを検出し、MCPサーバーとシェルフックを設定。lean-ctxインストール後に一度だけ実行。

lean-ctx setup

内部で3つのステップを実行します:

  1. シェルエイリアスをインストール(init --global
  2. 検出された各AIツール用にMCPを設定
  3. すべてが動作するか検証(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.

lean-ctx init [--global | <shell>]

シェルプロファイルにシェル圧縮エイリアスをインストール。

# File-based: writes aliases directly into your shell profile
lean-ctx init           # install for current shell
lean-ctx init --global  # same, explicit flag

# 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

~/.zshrc~/.bashrc~/.config/fish/config.fish、またはPowerShellプロファイルにブロックを書き込みます。ブロックにはgit、docker、npm、cargo、他95以上のコマンドのエイリアスが含まれます。

evalパターン: evalメソッドはhookコードをstdoutに出力し、常にインストールされたバイナリバージョンと一致することを保証します。これはstarshipzoxideatuinが使用するのと同じパターンです。アップグレード後にhookが古くなることはありません。

lean-ctx init --agent <name>

フルセットアップを実行せずに、特定のAIツール用にMCPを設定。

AgentNotes
cursorCursor IDE (default MCP setup)
claudeClaude Code / Claude Desktop
codexOpenAI Codex CLI
geminiGoogle Gemini CLI
antigravityAlias for gemini
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  # 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>]

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

KeyTypeDefaultDescription
ultra_compactboolfalseEnable ultra-compact output mode for maximum token savings
tee_modestring"off"Tee logging mode: off, on_error, always
checkpoint_intervalint15Number of MCP calls between automatic checkpoints
themestring"default"Dashboard and TUI theme (default, dark, light, neon)
slow_command_threshold_msint5000Threshold in milliseconds for slow-log entries
passthrough_urlsstring[][]URL patterns that bypass compression (comma-separated)
rules_scopestring"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 doctor

8つのインストールおよび環境診断を実行:

  • バイナリがインストールされPATHに存在
  • シェルフックが有効
  • 検出されたエディタのMCP設定
  • 統計ファイルの永続化
  • cacheディレクトリ
  • 対応シェルの検出
  • AIツールの検出
  • バージョン確認
  • Rules injection status
  • Claude Code instructions (rules + skill installed)
  • Build integrity verification
lean-ctx doctor

lean-ctx update [--check]

GitHub Releasesからlean-ctxバイナリをセルフアップデート。

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

すべてのlean-ctx設定を削除:シェルフック、すべてのエディタからのMCP設定、~/.lean-ctx/データディレクトリ。バイナリの削除手順を表示。

lean-ctx uninstall

アナリティクスとダッシュボード

スクリーンショットと解釈を含む詳細ガイドはアナリティクスガイドを参照してください。

lean-ctx gain [flags]

累計token節約量を表示するビジュアルターミナルダッシュボード。

GainEngine により駆動-圧縮メトリクス、コスト追跡、セッション分析を統合し、GainScore(0–100)に集約する統一オブザーバビリティ API。内蔵 ModelPricing(ネット不要)と 13 分類の TaskClassifier を使用。

フラグ出力
(none)フルダッシュボード:合計節約量、率、USD、上位コマンド、スパークライン
--scoreGainScore(0–100):圧縮率、コスト効率、品質、一貫性を統合
--cost内蔵価格でモデル別コスト内訳(--model=<name> フィルタ対応)
--tasks13 カテゴリのタスク分類内訳(file-ops / search / shell / memory など)
--agentsマルチエージェント統計(呼び出し数、トークン、コスト帰属)
--heatmapファイルアクセス・ヒートマップ-AI が最も読むファイル
--wrappedSpotify Wrapped 風のセッションサマリ(--period=week|month|all 対応)
--deep深掘り統合:report + tasks + cost + agents + heatmap を一括出力
--live自動更新モード(2秒ごとに更新)。qで終了。
--graph日別バーの30日間節約チャート
--dailytoken数とUSD付きの日別テーブル
--pipelinePipeline-view: shows compression stages and per-stage token savings
--jsonすべての統計の生JSONエクスポート(スクリプティング/自動化用)

修飾子

フラグ出力
--model=<name>特定モデルに絞る(例:--model=claude-4-sonnet
--period=<p>期間:today / week / month / all(デフォルト:all
--limit=<n>ランキング表の最大行数(デフォルト:10)
--reset統計を全てクリアして再開始
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

ctx_gain MCP ツールでも同じ分析をプログラムから取得できます。セッション中にトークン節約、コスト内訳、GainScore を直接問い合わせ可能。MCP ツールリファレンス を参照。

lean-ctx cep [--json]

CEP(Cognitive Efficiency Protocol)影響レポート。スコアの推移、cacheヒット率、モード分布を表示。

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] [--project=<path>]

http://localhost:3333でインタラクティブWebダッシュボードを起動。インタラクティブチャート、セッション履歴、アクティブエージェント、プロジェクトナレッジパネルを搭載。

FlagDescription
--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]

token節約の「Wrapped」シェア可能レポートカードを生成。

フラグ期間
(none)今週
--week今週(明示的)
--month今月
--all累計統計
lean-ctx wrapped
lean-ctx wrapped --month
lean-ctx wrapped --all

セッション管理

lean-ctx sessions [list|show|cleanup]

~/.lean-ctx/sessions/に保存されたCCP(Context Continuity Protocol)セッションを管理。

サブコマンドアクション
list保存されたすべてのセッションを一覧表示
show最新のセッション状態を表示
cleanup古い/無効なセッションを削除
lean-ctx sessions list
lean-ctx sessions show
lean-ctx sessions cleanup

lean-ctx session

導入統計を表示 - ワークフローのどれだけがlean-ctx圧縮を使用しているか。

lean-ctx session

ナレッジ管理

永続的プロジェクトナレッジストアへの完全なCLIアクセス。ファクト、パターン、規約はセッション間で維持され、累積的なプロジェクト理解を可能にします。

lean-ctx knowledge remember <value> --category <c> --key <k>

オプションの信頼度スコア付きでプロジェクトナレッジベースにファクトを保存します。

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]

クエリテキストまたはカテゴリでファクトを検索します。エンベディングが有効な場合はセマンティック検索をサポートします。

lean-ctx knowledge recall "authentication"
lean-ctx knowledge recall --category security
lean-ctx knowledge recall "auth" --mode semantic

すべてのプロジェクトとセッションにわたって一致するファクトを検索します。

lean-ctx knowledge search "database migration"

lean-ctx knowledge export [--format json|jsonl|simple] [--output <path>]

プロジェクトナレッジベースをエクスポートします。デフォルトでは stdout に出力(パイプ対応)。3つのフォーマット:json(完全ネイティブ、デフォルト)、jsonl(1行1ファクト)、simple(他ツールからの移行用コミュニティ互換配列)。

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]

JSON、JSONL、またはネイティブエクスポートファイルからファクトをインポートします。入力形式を自動検出。デフォルトのマージ戦略はskip-existing(安全—上書きしない)。

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>

ナレッジベースから特定のファクトを削除します。

lean-ctx knowledge remove --category auth --key token-type

lean-ctx knowledge status

ナレッジベースの概要を表示—ファクト数、カテゴリ、最終更新時刻。

lean-ctx knowledge status

lean-ctx knowledge health

品質メトリクス、古いファクトの検出、ルームバランスを含むヘルスレポート。

lean-ctx knowledge health

ベンチマーク

lean-ctx benchmark run [path] [--json]

tiktoken(o200k_base)を使用して、プロジェクトファイルでの実際のtokenベンチマークを実行。すべてのファイルにわたる各読み取りモードの正確な節約量を計測。

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]

ベンチマーク結果からシェア可能なMarkdownレポートを生成。

lean-ctx benchmark report             # generate report for current directory
lean-ctx benchmark report src/ > BENCHMARK.md

Teeとフィルター

lean-ctx tee [list|clear|show <file>|last]

~/.lean-ctx/tee/に保存された完全出力teeファイルを管理。lean-ctx tee lastで最新の保存出力を表示。tee_modeで設定:alwaysfailures、またはnever

lean-ctx filter [list|validate|init]

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

ユーティリティ

lean-ctx discover

シェル履歴をスキャンして、圧縮の恩恵を受けられるがインターセプトされていないコマンドを検出。コマンド別のtoken推定値とUSD節約予測を表示。

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

すべてのコマンドとワークフローのコンパクトなチートシートをターミナルに直接表示。

lean-ctx cheatsheet

lean-ctx tee [list|clear|show <file>]

~/.lean-ctx/tee/に保存されたエラーログファイルを管理。設定でtee_on_errorが有効な場合、失敗したコマンドの完全な出力がここに記録されます。

サブコマンドアクション
listすべてのエラーログファイルを一覧表示
clearすべてのエラーログを削除
show <file>特定のエラーログを表示
lean-ctx tee list
lean-ctx tee show 2026-03-29_10-30.log
lean-ctx tee clear

lean-ctx slow-log [list|clear]

~/.lean-ctx/slow-commands.logのスローコマンドログを表示またはクリア。予想より時間がかかったコマンドがデバッグ用にここに記録されます。

lean-ctx slow-log list
lean-ctx slow-log clear

プロジェクトGraph

プロジェクトのdependency graphを構築または検査します。Graphはファイル間の関係(imports、exports、シンボル)をインデックスし、heat-ranking、意図分析、スマートプリロードに使用されます。

lean-ctx graph build

プロジェクトディレクトリをスキャンし、dependency graphインデックスを構築します。MCPツール使用時にgraphは自動的にも構築されます。

lean-ctx graph build

コンテキストHeat Map

ファイルのtoken密度とdependency graphの接続性をカラーコード付きheat mapとして視覚化します。token数が多く接続の多いファイルはより熱く表示されます。

lean-ctx heatmap

現在のプロジェクトの全ファイルのターミナルheat mapを表示します。ヒートスコア(token数とgraph接続性の組み合わせ)でソートされます。

lean-ctx heatmap

安全レベル

LeanCTXはサポートされるすべてのコマンドを安全レベルに分類し、出力の圧縮の積極性を決定します。上位レベルは安全性に関する重要な情報(エラー、CVE、ヘルスステータス)を決して削除しません。

lean-ctx safety-levels

各コマンドタイプがどのように圧縮されるか、どのデータが保持されるか、どのグローバル安全機能がアクティブかを正確に示す詳細テーブルを表示します。

lean-ctx safety-levels
レベルコマンド動作
VERBATIMdf, git status, git stash, ls, find, wc, env圧縮なし。出力は完全に未変更のまま通過します。
MINIMALgit diff, git log, docker ps, grep, ruff, npm audit, pytest, pip, curl軽いフォーマットのみ。すべての安全性に関する重要なデータ(コードdiff、エラー詳細、CVE ID、ヘルスステータス)は完全に保持されます。
STANDARDcargo build, npm install, eslint, tsc, go build, maven, gradle, dotnet構造化された圧縮。エラー、警告、アクション可能な項目は常に保持されます。
AGGRESSIVEkubectl describe, aws, terraform, docker images冗長な出力に対する強力な圧縮。エラーメッセージと安全性に関する重要なキーワードは保持されます。

グローバル安全機能はすべてのレベルに適用されます:安全ニードルスキャン(CRITICAL、FATAL、panic、CVE-*、OOMKilledなどを保持)、セーフガード比率(>95%の圧縮をブロック)、認証検出(トークン/パスワードをマスク)、最小トークン閾値(50トークン未満では圧縮なし)。


シェルエイリアス

lean-ctx init --globalの実行後、シェルでこれらのエイリアスが利用可能になります。再起動なしで圧縮のオン/オフを切り替えられます:

エイリアスアクション
lean-ctx-onすべての圧縮エイリアスを有効化
lean-ctx-off圧縮を無効化(人間が読める出力)
lean-ctx-status圧縮が現在有効かどうかを表示
lean-ctx-raw <cmd>単一コマンドを圧縮なしで実行
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

無効にする場面:コマンド出力を自分で読みたい場合(デバッグ、ログ確認時)に圧縮をオフにしてください。AIコーディングセッションを開始する前に再度オンにしてください。


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.

FlagDefaultDescription
--port=<N>9119Port 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=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.

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 lean-ctx 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

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 lean-ctx content cache that accelerates repeated reads and avoids redundant compression.

lean-ctx cache <subcommand> [flags]

SubcommandDescription
statusShow cache size, hit rate, and entry count
clearClear 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]

SubcommandDescription
listShow all tracked gotchas for the current project
add "<description>"Add a new gotcha entry
remove <id>Remove a gotcha by its ID
clearRemove 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>]

SubcommandDescription
statusShow buddy status and current name
onEnable the buddy
offDisable 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

ポータブルなコンテキストパッケージの作成、管理、共有...

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

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 lean-ctx into CI/CD pipelines or custom agent frameworks that don't support the MCP instructions handshake natively.