Esta es la referencia exhaustiva de cada comando de lean-ctx. Para una hoja de referencia rápida, consulta Referencia rápida. Para detalles de analíticas y paneles, consulta Guía de analíticas.
Compresión de shell
Estos comandos ejecutan comandos de shell a través de los más de 95 patrones de compresión de lean-ctx. La salida se limpia automáticamente de ruido, código repetitivo y redundancia antes de llegar al LLM.
lean-ctx -c "<command>"
Ejecuta cualquier comando de shell y comprime su salida. 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" El shell hook (instalado vía lean-ctx init) hace esto automáticamente para comandos comunes - no necesitas prefijarlos con -c. Usa -c explícitamente para comandos no cubiertos por el shell hook.
lean-ctx shell
Inicia una sesión de shell interactiva donde toda la salida de comandos se comprime. Envuelve tu shell predeterminado (zsh, bash o fish).
lean-ctx shell
# Now every command output is compressed automatically
git log --oneline -20
docker compose logs
# Exit with Ctrl+D or 'exit' Modo sin procesar
Omite la compresión por completo cuando necesitas salida completa sin modificar. Tres formas de activarlo:
# 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>"
Ejecuta cualquier comando con cero compresión garantizada. Internamente establece LEAN_CTX_RAW=1 antes de ejecutar el comando. Úsalo cuando necesites certeza absoluta de que la salida no está modificada.
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 Consejo: bypass es equivalente a LEAN_CTX_RAW=1 lean-ctx -c "command" pero más conveniente. La cadena de comando se pasa directamente al shell.
Operaciones de archivos
Acceso directo por CLI a las herramientas de lectura, búsqueda y navegación de archivos de lean-ctx. Estas son las mismas operaciones que el servidor MCP proporciona a las herramientas de IA.
lean-ctx read <file> [-m <mode>]
Lee un archivo con modo de compresión opcional. El modo predeterminado es 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>
Diff comprimido entre dos archivos con resúmenes de cambios estructurados.
lean-ctx diff old.rs new.rs lean-ctx grep <pattern> [path]
Busca contenido en archivos con resultados comprimidos y agrupados. Usa ripgrep internamente.
lean-ctx grep "pub fn" src/
lean-ctx grep "TODO" .
lean-ctx grep "async fn.*Result" rust/src/ lean-ctx find <pattern> [path]
Busca archivos por patrón de nombre. Respeta .gitignore y produce un árbol de archivos compacto.
lean-ctx find "*.rs" src/
lean-ctx find "test_*" . lean-ctx ls [path]
Listado compacto de directorio como mapa de árbol con conteo de archivos.
lean-ctx ls
lean-ctx ls src/components/ lean-ctx deps [path]
Muestra el grafo de dependencias del proyecto. Detecta el gestor de paquetes y extrae las dependencias.
lean-ctx deps .
lean-ctx deps frontend/ Modos de lectura
Los modos de lectura controlan cómo lean-ctx read y la herramienta MCP ctx_read comprimen el contenido de archivos. Elige el modo adecuado para tu caso de uso:
| Modo | Salida | Caso de uso | Savings |
|---|---|---|---|
auto | Mejor modo para contexto | Predeterminado si no se especifica modo: lean-ctx elige la estrategia optima | 60–95% |
full | Contenido completo del archivo | Archivos que vas a editar. Las relecturas cuestan ~13 tokens (en cache). | 0% (primera lectura), ~99% (en cache) |
map | Grafo de dependencias + exports + firmas clave | Archivos solo de contexto - entiende la estructura sin leer todo. | 90–98% |
signatures | Extracción de AST por tree-sitter (18 lenguajes) | Solo superficie de API - firmas de funciones/métodos/clases. | 92–99% |
aggressive | Contenido sin sintaxis | Compresión máxima preservando la lógica. | 85–95% |
entropy | Filtrado por entropía Shannon + Jaccard | Conservar solo líneas con alta densidad de información. | 70–90% |
diff | Solo líneas modificadas (vs. última lectura) | Después de editar - ver solo lo que cambió. | 90–99% |
task | Contenido filtrado por tarea | Extraccion con puntuacion IB segun la intencion actual: solo codigo relevante para la tarea activa | 70–90% |
reference | Contexto de referencia cruzada | Tipos relacionados, llamadas y dependencias del simbolo o funcion objetivo | 60–85% |
lines:N-M | Rangos específicos de líneas | Lee solo la sección que necesitas. Soporta múltiples rangos: lines:10-50,80-100 | varies |
Lenguajes soportados para el modo signatures: TypeScript, JavaScript, Rust, Python, Go, Java, C, C++, Ruby, C#, Kotlin, Swift, PHP (14 en total vía tree-sitter).
Configuración inicial
lean-ctx setup
Configuración con un solo comando. Detecta automáticamente tu shell (zsh/bash/fish/PowerShell), encuentra herramientas de IA instaladas y configura el servidor MCP + shell hooks. Ejecuta una vez después de instalar lean-ctx.
lean-ctx setup Esto ejecuta tres pasos internamente:
- Instala alias de shell (
init --global) - Configura MCP para cada herramienta de IA detectada
- Verifica que todo funcione (
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>]
Instala los alias de compresión de shell en tu perfil de 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 Esto escribe un bloque en ~/.zshrc, ~/.bashrc, ~/.config/fish/config.fish, o tu perfil de PowerShell. El bloque incluye alias para git, docker, npm, cargo y más de 95 comandos adicionales.
Patrón eval: El método eval imprime código de hook en stdout, asegurando que siempre coincida con la versión del binario instalado. Es el mismo patrón usado por starship, zoxide y atuin. Los hooks nunca quedan desactualizados después de una actualización.
lean-ctx init --agent <name>
Configura MCP para una herramienta de IA específica sin ejecutar la configuración completa.
| 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>]
Muestra o edita la configuración almacenada en ~/.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 doctor
Ejecuta 8 diagnósticos de instalación y entorno:
- Binario instalado y en el PATH
- Shell hook activo
- Configuración MCP para editores detectados
- Persistencia del archivo de estadísticas
- Directorio de cache
- Shell compatible detectado
- Detección de herramientas de IA
- Verificación de versión
- Rules injection status
- Claude Code instructions (rules + skill installed)
- Build integrity verification
lean-ctx doctor lean-ctx update [--check]
Auto-actualiza el binario de lean-ctx desde 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
Elimina toda la configuración de lean-ctx: shell hooks, configuraciones MCP de todos los editores, y el directorio de datos ~/.lean-ctx/. Imprime instrucciones para eliminar el binario.
lean-ctx uninstall Analíticas y paneles
Para una guía detallada con capturas de pantalla e interpretaciones, consulta Guía de analíticas.
lean-ctx gain [flags]
Panel visual en terminal que muestra ahorros de tokens de por vida.
Impulsado por GainEngine: una API de observabilidad unificada que combina metricas de compresion, seguimiento de costos y analiticas de sesion en un solo GainScore (0–100). Usa ModelPricing embebido (sin red) y un TaskClassifier con 13 categorias.
| Flag | Salida |
|---|---|
(none) | Panel completo: total ahorrado, tasa, USD, comandos principales, sparklines |
--score | GainScore (0–100) que combina ratio de compresion, eficiencia de costo, calidad y consistencia |
--cost | Desglose de costos por modelo con precios embebidos (soporta filtro --model=<name>) |
--tasks | Desglose de tareas en 13 categorias (file-ops, search, shell, memory, etc.) |
--agents | Estadisticas por agente en sesiones multi-agente (llamadas, tokens, atribucion de costos) |
--heatmap | Mapa de calor de acceso a archivos: que archivos lee mas a menudo la IA |
--wrapped | Resumen estilo Spotify Wrapped (soporta --period=week|month|all) |
--deep | Deep-dive combinado: reporte + tareas + costos + agentes + heatmap en una sola salida |
--live | Modo con actualización automática (se actualiza cada 2s). Presiona q para salir. |
--graph | Gráfico de ahorros de 30 días con barras diarias |
--daily | Tabla diaria con bordes con conteos de tokens y USD |
--pipeline | Pipeline-view: shows compression stages and per-stage token savings |
--json | Exportación JSON sin procesar de todas las estadísticas (para scripting/automatización) |
Modificadores
| Flag | Salida |
|---|---|
--model=<name> | Filtra costo/score a un modelo especifico (p. ej. --model=claude-4-sonnet) |
--period=<p> | Ventana de tiempo: today, week, month, all (predeterminado: all) |
--limit=<n> | Maximo de filas en tablas rankeadas (predeterminado: 10) |
--reset | Borra todas las estadisticas y reinicia |
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 La herramienta MCP ctx_gain ofrece las mismas analiticas por API: los agentes pueden consultar ahorro de tokens, costos y GainScore durante la sesion. Ver Referencia de herramientas MCP.
lean-ctx cep [--json]
Reporte de impacto del CEP (Cognitive Efficiency Protocol) que muestra tendencias de puntuación, tasas de acierto del cache y distribución de modos.
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>]
Abre el panel web interactivo en http://localhost:3333. Incluye gráficos interactivos, historial de sesiones, agentes activos y paneles de conocimiento del proyecto.
| 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]
Genera una tarjeta de reporte "Wrapped" compartible de tus ahorros de tokens.
| Flag | Período |
|---|---|
(none) | Semana actual |
--week | Semana actual (explícito) |
--month | Mes actual |
--all | Estadísticas de por vida |
lean-ctx wrapped
lean-ctx wrapped --month
lean-ctx wrapped --all Gestión de sesiones
lean-ctx sessions [list|show|cleanup]
Administra sesiones CCP (Context Continuity Protocol) almacenadas en ~/.lean-ctx/sessions/.
| Subcomando | Acción |
|---|---|
list | Listar todas las sesiones guardadas |
show | Mostrar el estado más reciente de la sesión |
cleanup | Eliminar sesiones antiguas/obsoletas |
lean-ctx sessions list
lean-ctx sessions show
lean-ctx sessions cleanup lean-ctx session
Muestra estadísticas de adopción - qué proporción de tu flujo de trabajo usa la compresión de lean-ctx.
lean-ctx session Gestión del conocimiento
Acceso completo por CLI al almacén de conocimiento persistente del proyecto. Los hechos, patrones y convenciones sobreviven entre sesiones y permiten una comprensión acumulativa del proyecto.
lean-ctx knowledge remember <value> --category <c> --key <k>
Almacena un hecho en la base de conocimiento del proyecto con una puntuación de confianza opcional.
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]
Recupera hechos por texto de consulta o categoría. Soporta recuperación semántica cuando los embeddings están habilitados.
lean-ctx knowledge recall "authentication"
lean-ctx knowledge recall --category security
lean-ctx knowledge recall "auth" --mode semantic lean-ctx knowledge search <query>
Busca en todos los proyectos y sesiones hechos coincidentes.
lean-ctx knowledge search "database migration" lean-ctx knowledge export [--format json|jsonl|simple] [--output <path>]
Exporta la base de conocimiento del proyecto. Salida a stdout por defecto (compatible con pipes). Tres formatos: json (nativo completo, por defecto), jsonl (un hecho por línea), simple (array compatible con la comunidad para migración desde otras herramientas).
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]
Importa hechos desde un archivo JSON, JSONL o de exportación nativa. Detecta automáticamente el formato de entrada. La estrategia de fusión por defecto es skip-existing (segura — nunca sobrescribe).
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>
Elimina un hecho específico de la base de conocimiento.
lean-ctx knowledge remove --category auth --key token-type lean-ctx knowledge status
Muestra resumen de la base de conocimiento — conteo de hechos, categorías y última actualización.
lean-ctx knowledge status lean-ctx knowledge health
Informe de salud con métricas de calidad, detección de hechos obsoletos y equilibrio de espacio.
lean-ctx knowledge health Benchmarking
lean-ctx benchmark run [path] [--json]
Ejecuta benchmarks reales de tokens en los archivos de tu proyecto usando tiktoken (o200k_base). Mide los ahorros exactos para cada modo de lectura en cada archivo.
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]
Genera un reporte en Markdown compartible a partir de los resultados del benchmark.
lean-ctx benchmark report # generate report for current directory
lean-ctx benchmark report src/ > BENCHMARK.md Tee y filtros
lean-ctx tee [list|clear|show <file>|last]
Administra archivos tee de salida completa guardados en ~/.lean-ctx/tee/. Usa lean-ctx tee last para ver la salida más reciente guardada. Configura vía tee_mode: always, failures, o never.
lean-ctx filter [list|validate|init]
Administra filtros de compresión personalizados en ~/.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 Utilidades
lean-ctx discover
Escanea tu historial de shell en busca de comandos que podrían beneficiarse de la compresión pero que no están siendo interceptados. Muestra estimaciones de tokens por comando y proyección de ahorro en 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
Imprime una hoja de referencia rápida compacta de todos los comandos y flujos de trabajo directamente en tu terminal.
lean-ctx cheatsheet lean-ctx tee [list|clear|show <file>]
Administra archivos de registro de errores almacenados en ~/.lean-ctx/tee/. Cuando tee_on_error está habilitado en la configuración, los comandos fallidos guardan su salida completa aquí.
| Subcomando | Acción |
|---|---|
list | Listar todos los archivos de registro de errores |
clear | Eliminar todos los registros de errores |
show <file> | Mostrar un registro de error específico |
lean-ctx tee list
lean-ctx tee show 2026-03-29_10-30.log
lean-ctx tee clear lean-ctx slow-log [list|clear]
Muestra o limpia el registro de comandos lentos en ~/.lean-ctx/slow-commands.log. Los comandos que tardan más de lo esperado se registran aquí para depuración.
lean-ctx slow-log list
lean-ctx slow-log clear Graph del proyecto
Construir o inspeccionar el dependency graph del proyecto. El graph indexa las relaciones entre archivos (imports, exports, símbolos) y se utiliza para heat-ranking, análisis de intención y precarga inteligente.
lean-ctx graph build
Escanear el directorio del proyecto y construir el índice del dependency graph. El graph también se construye automáticamente cuando se usan herramientas MCP.
lean-ctx graph build Heat Map de contexto
Visualizar la densidad de token de archivos y la conectividad del dependency graph como una heat map con código de colores. Los archivos con alto número de token y muchas conexiones aparecen más calientes.
lean-ctx heatmap
Mostrar una heat map en terminal de todos los archivos del proyecto actual, ordenados por puntuación de calor (combinación de cantidad de token y conectividad del graph).
lean-ctx heatmap Niveles de Seguridad
LeanCTX categoriza cada comando soportado en un nivel de seguridad que determina cuán agresivamente se comprime la salida. Los niveles más altos nunca eliminan información crítica de seguridad (errores, CVEs, estado de salud).
lean-ctx safety-levels
Muestra una tabla detallada que indica exactamente cómo se comprime cada tipo de comando, qué datos se preservan y qué funciones globales de seguridad están activas.
lean-ctx safety-levels | Nivel | Comandos | Comportamiento |
|---|---|---|
VERBATIM | df, git status, git stash, ls, find, wc, env | Cero compresión. La salida pasa completamente sin modificar. |
MINIMAL | git diff, git log, docker ps, grep, ruff, npm audit, pytest, pip, curl | Solo formato ligero. Todos los datos críticos de seguridad (diffs de código, detalles de errores, IDs de CVE, estado de salud) se preservan completamente. |
STANDARD | cargo build, npm install, eslint, tsc, go build, maven, gradle, dotnet | Compresión estructurada. Errores, advertencias y elementos accionables siempre preservados. |
AGGRESSIVE | kubectl describe, aws, terraform, docker images | Compresión fuerte para salida detallada. Aún preserva mensajes de error y palabras clave de seguridad crítica. |
Funciones globales de seguridad se aplican a TODOS los niveles: escaneo de agujas de seguridad (preserva CRITICAL, FATAL, panic, CVE-*, OOMKilled, etc.), ratio de protección (bloquea compresión >95%), detección de autenticación (enmascara tokens/contraseñas) y umbral mínimo de tokens (sin compresión por debajo de 50 tokens).
Alias de shell
Después de ejecutar lean-ctx init --global, estos alias están disponibles en tu shell. Te permiten activar y desactivar la compresión sin reiniciar:
| Alias | Acción |
|---|---|
lean-ctx-on | Activar todos los alias de compresión |
lean-ctx-off | Desactivar compresión (salida legible para humanos) |
lean-ctx-status | Mostrar si la compresión está actualmente activa |
lean-ctx-raw <cmd> | Ejecutar un solo comando sin compresión |
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 Cuándo desactivar: Desactiva la compresión cuando quieras leer la salida de comandos tú mismo (depuración, revisión de logs). Vuelve a activarla antes de iniciar una sesión de programación con IA.
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
Crear, gestionar y compartir paquetes de contexto portables que agrupan conocimiento, datos de grafos, hallazgos de sesión y trampas en archivos versionados.
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.