██╗ ███████╗ █████╗ ███╗ ██╗ ██████╗████████╗██╗ ██╗ ██║ ██╔════╝██╔══██╗████╗ ██║ ██╔════╝╚══██╔══╝╚██╗██╔╝ ██║ █████╗ ███████║██╔██╗ ██║ ██║ ██║ ╚███╔╝ ██║ ██╔══╝ ██╔══██║██║╚██╗██║ ██║ ██║ ██╔██╗ ███████╗███████╗██║ ██║██║ ╚████║ ╚██████╗ ██║ ██╔╝ ██╗ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝## LeanCTX **Context Gateway for AI Systems.** ### **Control what your AI can see.** LeanCTX sits between AI tools and the information they read. It selects task-relevant context, applies supported access and content controls before delivery, and records the context operations and delivery evidence it can observe. Your application, agent loop and model stay yours. The open-source **LeanCTX Engine** runs locally through CLI, MCP, hooks and proxy paths. The **LeanCTX SDK** embeds supported Engine capabilities in your application. ---
Website · Docs · Install · Scenarios · Demo · Benchmarks · Cookbook · Security · Changelog
See it in action:
Read + Shell Map-mode reads + compressed CLI output |
Gain (live) Token usage + estimated cost differences |
Benchmark measurement Measure compression by language + mode |
All GIFs are generated from reproducible VHS tapes in demo/.
Find LeanCTX useful? Give it a star — it helps others find the Context Gateway for AI systems.
--- ## Inside the LeanCTX Engine The Engine puts Select, Control, Learn and Prove into the context paths of your existing AI tools. Your host keeps control of the task, agent loop and model. ### 1. Select — the context each task needs Search and structural views help an agent find relevant information before reading entire files. Supported read and shell paths can return focused views of files and command output, with references for recovering detail. - **File reads**: 16 read modes (`full`, `map`, `signatures`, `diff`, `lines:N-M`, `density:X`, …) — eligible cached re-reads return a compact reference instead of repeating content - **Target density** (`density:0.4`): SDE-style budget compression — keeps the highest-entropy lines until ~40% of the original tokens remain, deterministic - **JIT disclosure**: `signatures` carries line spans and points at `lines:N-M` for targeted expansion — outline first, bodies on demand - **Shell output**: 85+ shell-output patterns compress git, npm, cargo, docker, kubectl, terraform and more (250+ passthrough rules) - **Tree-sitter AST**: structural understanding for 27 languages — not just text compression - **Source recovery (CCR)**: supported compact views retain source or archive references for expansion through `ctx_expand`, `ctx_retrieve` or the reference API. Recovery depends on permissions, retention and the source remaining available. [Read modes and detail →](docs/reference/02-daily-use.md#1-reading-files) ### 2. Control — configured rules on supported paths - **PathJail and roles:** constrain tool filesystem access to the configured scope. - **Content filters:** configured detectors can warn, redact or block on supported paths. Detection coverage and enforcement depend on the integration and settings. - **Context budgets:** bound selected input and supported tool output. - **Host-owned model choice:** the host chooses the model and performs any model calls outside the Engine's observed path. Review [the security policy](SECURITY.md) for defaults, supported controls and coverage limits. A filesystem boundary is not an operating-system sandbox. ### 3. Learn — connect work across sessions Keep useful task records and discover relationships between code and local knowledge. Learning here means context continuity; it does not train your model. - **Session memory (CCP)**: persist task/facts/decisions across chats — structured recovery queries survive compaction - **Knowledge graph**: temporal facts with validity windows, episodic + procedural memory - **Property Graph**: multi-edge code graph (imports, calls, exports, type_ref) powers impact analysis and search ranking - **Permission-bound reuse:** access and retention rules still apply when stored context is retrieved. Experimental `.ctxpkg` export is described under Research below. ### 4. Prove — inspect what the Engine recorded Inspect source references, recorded policy decisions and delivery evidence from supported paths. `lean-ctx inspect` explains observed context operations. A context-only integration records its prepared result; it cannot prove a later model call made by the host. - **Context Manager**: browser dashboard with real-time token tracking, compression stats, utilization gauge - **Audit export:** retain the recorded evidence for review within its stated scope. - **Context Proof** (`ctx_proof`, `ctx_verify`): exportable audit trail (verifier, SLO, pipeline and provenance records) plus runtime-checked policy claims (PathJail per touched file, budget) ## Usage and cost — measure the result Context controls and evidence come first. Usage estimates and calculated costs help you assess their operational effect; they do not prove answer quality. ### Shadow Mode — a simulated baseline Shadow Mode estimates what the same work would have cost without LeanCTX, without changing the active workflow. The baseline is **simulated** from the uncompressed token counts and the same outcome signals, not a second measured run, so its reports estimate cost, tokens and CPAO deltas; they do not measure answer quality. LeanCTX records local cost and outcome signals without adding those reports to agent context. CPAO (cost per accepted outcome) is one comparison metric; Shadow Mode provides simulated savings estimates. Keep estimates, provider-measured usage and outcome quality separate. ```bash lean-ctx savings --period week # costs, token savings, and CPAO lean-ctx value-report --format markdown --last 20 # recent outcome quality lean-ctx shadow --latest # latest baseline comparison ``` ### Quick start: usage tracking ```bash # Enable shadow mode for savings comparison lean-ctx config set shadow.enabled true # After using LeanCTX for a while: lean-ctx savings lean-ctx shadow --latest ```| ### 🟢 Your first setup *"I just installed it — now what?"* ```bash lean-ctx wrap cursor # one-command setup for your agent lean-ctx doctor # confirm you're wired up ``` `wrap` configures the supported integration; `doctor` checks the resulting setup. → **[Journey 1 — Setup & Onboarding](docs/reference/01-setup-and-onboarding.md)** | ### 📖 Coding every day *"Stop re-reading the same files."* ```bash lean-ctx read src/server.rs -m map # API surface, ~13 tok on re-read lean-ctx -c "git status" # compressed shell output ``` Your agent reads less and searches smarter — automatically. → **[Journey 2 — Daily Use](docs/reference/02-daily-use.md)** |
| ### 🧠 Resume where you left off *"My new chat forgot everything."* ```bash lean-ctx overview # task-aware project recap lean-ctx knowledge recall "auth" # facts that survive resets lean-ctx knowledge consolidate # import session + compact lifecycle lean-ctx knowledge consolidate --all # compact every project store ``` Session memory + a project knowledge graph persist across chats. → **[Journey 3 — Memory & Knowledge](docs/reference/03-memory-and-knowledge.md)** | ### 🗺️ Understand a new codebase *"Where does this function ripple to?"* ```bash lean-ctx graph impact src/auth.rs # blast radius lean-ctx smells scan # code-smell hotspots ``` A multi-edge property graph powers impact analysis + ranked search. → **[Journey 4 — Code Intelligence](docs/reference/04-code-intelligence.md)** |
| ### 🔌 Providers & multi-repo *"Pull in GitHub issues and our Postgres schema."* ```bash lean-ctx provider list lean-ctx serve --root ./api --root ./web # multi-repo ``` External data flows through the same consolidation pipeline. → **[Journey 5 — Advanced & Integrations](docs/reference/05-advanced.md)** | ### 🛠️ Keep it healthy *"Update, fix, or cleanly remove."* ```bash lean-ctx doctor --fix lean-ctx update ``` Self-healing diagnostics; surgical uninstall that only removes its own blocks. → **[Journey 6 — Lifecycle & Troubleshooting](docs/reference/06-lifecycle.md)** |
| ### 🎛️ Take control of the window *"Budget my context like a pro."* ```bash lean-ctx plan "refactor billing" --budget 8000 lean-ctx compile --mode balanced ``` Phi-scored planning + knapsack compilation + a context ledger. → **[Journey 7 — Context Engineering](docs/reference/07-context-engineering.md)** | ### 🤝 Run a team of agents *"Planner + coder + reviewer on one repo."* ```text ctx_agent action=register role=dev ctx_handoff action=create # baton-pass with full context ``` Shared message bus, diaries, knowledge, and deterministic handoffs. → **[Journey 8 — Multi-Agent Collaboration](docs/reference/08-multi-agent.md)** |
| ### 🏢 Explore team and CI context — Research *"One shared index, headless in pipelines."* ```bash lean-ctx team serve --config team.toml lean-ctx bootstrap # zero-prompt CI setup ``` Experimental local team-server path with scoped tokens and verifiable context gates; no hosted team or cloud service is publicly available. → **[Journey 9 — Team, Cloud & CI](docs/reference/09-team-cloud-ci.md)** | ### 🎚️ Tune & govern *"Make it behave exactly how we want."* ```bash lean-ctx compression standard lean-ctx harden # enforce token discipline ``` Compression levels, tool profiles, themes, and rules governance. → **[Journey 10 — Customization & Governance](docs/reference/10-customization-and-governance.md)** |
| ### 📊 Measure usage and cost *"Show me the numbers."* ```bash lean-ctx gain --deep # savings, cost, per-agent, heatmap lean-ctx wrapped # shareable recap (also: gain --svg / gain --share) lean-ctx savings # verified per-event ledger (auditable; savings verify) ``` All analytics live in the CLI/dashboard — never burning agent tokens. → **[Journey 11 — Analytics & Insights](docs/reference/11-analytics-and-insights.md)** | ### 📚 The full reference *"I want to read everything."* Every command and the generated MCP registry, organized as user journeys, plus appendices for the [CLI map](docs/reference/appendix-cli-map.md), [MCP tools](docs/reference/appendix-mcp-tools.md), and [paths & config](docs/reference/appendix-paths-and-config.md). → **[Reference index](docs/reference/README.md)** |