lean-ctx README

The project's README from github.com/yvgude/lean-ctx. As one markdown file: README.md.

██╗     ███████╗ █████╗ ███╗   ██╗     ██████╗████████╗██╗  ██╗
██║     ██╔════╝██╔══██╗████╗  ██║    ██╔════╝╚══██╔══╝╚██╗██╔╝
██║     █████╗  ███████║██╔██╗ ██║    ██║        ██║    ╚███╔╝
██║     ██╔══╝  ██╔══██║██║╚██╗██║    ██║        ██║    ██╔██╗
███████╗███████╗██║  ██║██║ ╚████║    ╚██████╗   ██║   ██╔╝ ██╗
╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝     ╚═════╝   ╚═╝   ╚═╝  ╚═╝

Control what your AI can see.

LeanCTX — AI Value Gate for AI Coding Agents

LeanCTX — short for Lean Context — is an AI Value Gate and context engineering layer for AI coding agents. It runs locally alongside your coding agent, helping it read repositories, run development commands, and send focused context to the model: it understands the task, routes the right context, compresses what it sends, and tracks the cost and outcome of that work. Savings depend on the workload and enabled modes; the local savings ledger and Shadow Mode show the measured result against a comparable baseline. Zero config required. Local-first.

Problem With LeanCTX
Repeated file reads resend unchanged content Cached re-reads return a compact deterministic reference
Raw development commands include repetitive noise Command-specific compression preserves salient output
Every turn re-sends the whole history Proxy compresses each request, prompt-cache-safe
Context resets every chat Session memory persists across chats
No visibility into context usage Real-time dashboard + budget control

GitHub Stars   CI Security crates.io Downloads npm AUR License Discord X/Twitter Opt-in Telemetry

Website  ·  Docs  ·  Install  ·  Scenarios  ·  Demo  ·  Benchmarks  ·  Cookbook  ·  Security  ·  Changelog


Control what your AI can see — and what it costs. LeanCTX is an AI Value Gate for coding agents: it understands tasks, routes and compresses context, remembers what it learns, and measures cost against accepted outcomes.

Token savings are the receipt. Intelligence is the product. Works with Cursor, Claude Code, Copilot, Windsurf, Codex, Gemini and 30+ other agents — no config needed.

See it in action:

Map-mode file read + compressed git output demo
Read + Shell
Map-mode reads + compressed CLI output
lean-ctx gain live dashboard demo
Gain (live)
Tokens + USD savings in real time
lean-ctx benchmark report demo
Benchmark proof
Measure compression by language + mode

All GIFs are generated from reproducible VHS tapes in demo/.

Why developers use LeanCTX


Saves you tokens? Give it a star — it helps others discover LeanCTX.


Why now — own your context

Models are converging on commodity. The durable edge isn't which model you call — it's your context: what your agents read, what they remember, and what you can prove. And the layer that optimizes and owns that context can't come from the vendor that bills per token or keeps your memory in a black box — it has to sit on your side.

That's the shift behind "agent entities" that live in your chat and remember your company (Claude in Slack, ClickUp Brain): a context login, not a model login — you end up renting your own company knowledge back. LeanCTX is the opposite layer. It keeps the moat yours: local-first, portable (.ctxpkg), and model-agnostic — swap OpenAI, Anthropic or Gemini without losing context or cache. Own your context; don't rent it back.


What it does — five capabilities of an AI Value Gate

LeanCTX treats context and AI spend as managed resources, not afterthoughts. One binary covers the capabilities that decide how well an AI agent performs:

1. Context Compression — input efficiency

Your AI agent reads files and runs commands. LeanCTX compresses both automatically.

2. Intelligent Triage — task understanding

Not every task or file needs the same depth. LeanCTX classifies the task, then sends the signal rather than the noise.

3. Knowledge Routing — cross-source context

Relevant code, sessions, and connected sources become focused context instead of a larger prompt.

4. AI Value Gate — cost and outcome tracking

Performance is the cost of a useful result, not just speed. LeanCTX records costs and outcomes locally; CPAO (Cost per Accepted Outcome) is the north-star metric for comparing useful AI work.

5. Shadow Recommendations — savings proof

Shadow Mode compares LeanCTX treatment with a configured baseline without changing the active workflow. Its reports show cost, tokens, CPAO, and whether quality held, then recommend savings only when the comparison supports them.

Cost Intelligence

LeanCTX automatically tracks local cost and outcome signals; it does not add those reports to agent context. CPAO — cost per accepted outcome — is the north-star metric, while Shadow Mode provides a baseline comparison for savings.

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: value tracking

# Enable shadow mode for savings comparison
echo '[shadow]\nenabled = true' >> ~/.config/lean-ctx/config.toml

# After using LeanCTX for a while:
lean-ctx savings
lean-ctx shadow --latest
Full feature list (complete MCP tool set)
  • Web & Research (ctx_url_read): pull a public web page, PDF, or YouTube transcript into context as compressed, citation-backed text — facts/quotes return claims with a confidence score + source URL, relevance-ranked research-compression distils to a token budget, SSRF-guarded (http/https only)
  • Graph-Powered Intelligence: hybrid search (BM25 + embeddings + graph proximity via RRF), incremental git-diff updates
  • LSP Refactoring (ctx_refactor): language-server-powered rename, references, go-to-definition via rust-analyzer, typescript-language-server, pylsp, gopls
  • Multi-Agent (ctx_agent, ctx_handoff): agent handoff with context transfer bundles, diary system, synchronized shared state
  • Archive Full-Text Search (ctx_expand search_all): FTS5-powered cross-archive search over all previously archived tool outputs
  • PR Context Packs: lean-ctx pack --pr builds a PR-ready context pack (changed files, related tests, impact, artifacts)
  • Context Packages: lean-ctx pack create bundles Knowledge + Graph + Session into portable .ctxpkg files with SHA-256 integrity
  • Context Time Machine: lean-ctx snapshot create|list|show|verify|restore|publish|import — git-anchored, ed25519-signed snapshots of the layer state (lineage, ledger Φ, ROI, session) on an append-only timeline; replay them in the dashboard, restore to resume a session (and --git to check out the commit), or publish/import a signed snapshot to share it (concept →)
  • Observability: lean-ctx gain --live for real-time savings, lean-ctx wrapped for weekly/monthly summaries (gain --svg/--share for a shareable card or self-hostable page), lean-ctx watch for TUI monitoring
  • Verified savings: lean-ctx savings is an auditable, per-event ledger (tokenizer transparency, bounce-netting, tamper-evident SHA-256 chain) — local-only, on by default
  • HTTP mode: lean-ctx serve for Streamable HTTP MCP + /v1/tools/call (used by the Cookbook and external clients)

Addons — extend the engine, or run the ecosystem through one gateway

You don't have to choose between LeanCTX and the other context tools you already like. An addon is a signed package carrying either a sandboxed WASM module that runs inside the context pipeline, or an [mcp] declaration that wires an external MCP server into the gateway — after which LeanCTX treats what it returns like your own reads instead of just proxying it.

lean-ctx addon release ./my-addon   # build a signed .ctxpkg — no artifact host, no CI
lean-ctx addon add ./my-addon-1.0.0.ctxpkg   # verify, disclose, ask, install
lean-ctx addon list                 # what's installed, what loads, what's wired

There is deliberately no marketplace and no addon search: LeanCTX does not host, curate or rank addons. A package is a file you install, or one you fetch from a registry you name. See the addon guide for the full walkthrough.

Where it's going

LeanCTX is growing from a single context layer into a full cognitive context layer for whole teams: version-controlled context strategy, one unified graph, and a governance layer across many agents.

The full roadmap lives in VISION.md.

How it works (30 seconds)

LeanCTX works on two planes — what your agents read and what they send to the model:

read path:   AI tool  →  (MCP tools + shell)  →  lean-ctx  →  your repo + CLI
wire path:   AI tool  →  lean-ctx proxy        →  model provider   (every request, compressed)

Get started (30 seconds)

# 1) Install (pick one)
curl -fsSL https://leanctx.com/install.sh | sh      # universal (no Rust needed)
brew tap yvgude/lean-ctx && brew install lean-ctx    # macOS / Linux
npm install -g lean-ctx-bin                          # Node.js
cargo install lean-ctx                               # Rust

# 2) One-command setup for your agent
lean-ctx wrap cursor      # or: wrap claude / wrap codex

# Done. Savings appear after your AI's first lean-ctx call.
lean-ctx gain

lean-ctx wrap registers the MCP server and configures the supported local transport for that agent. Undo anytime with lean-ctx unwrap cursor.

Claude Pro/Max: subscription OAuth cannot use a custom ANTHROPIC_BASE_URL. lean-ctx wrap claude therefore adds no proxy redirect while enabling the ctx_* tools and shell-output compression; an existing custom endpoint remains untouched. Claude wire-level request compression requires ANTHROPIC_API_KEY. See advanced proxy setup.

Alternative: full control
lean-ctx onboard          # connect all detected AI tools (zero prompts)
lean-ctx setup            # interactive wizard with every option

**Building from so

lean-ctx (yvgude/lean-ctx)

Searching Database…

这是什么?LeanCTX 是一个「上下文网关」,它在本地与你的 AI 编程代理一同运行,决定模型实际能看到哪些上下文,对其进行压缩,并追踪这项工作的成本和效果。
这是命令行工具,还是作为后台服务运行?它是一个本地二进制文件和 MCP 服务器,带有 CLI 子命令(serve、gain、watch、pack、snapshot)以及浏览器仪表盘——它位于你的代理请求的中间环节,而不是一个供你导入的库。
怎么让 LeanCTX 和我的编程代理一起跑起来?运行 lean-ctx setup 命令——它会安装引擎并接入你现有的代理,无需任何配置更改。
它支持哪些编程代理?Cursor、Claude Code、Copilot、Windsurf、Codex、Gemini CLI 以及其他 30 多种代理——它以本地 MCP 服务器的形式接入,无需针对特定代理做集成。
Token 节省量有保证吗?没有——实际节省取决于工作负载以及启用了哪些模式。LeanCTX 自带本地节省账本和影子模式(Shadow Mode)对比,你可以自行验证实测的削减量,而不必相信一个固定的宣传数字。
我的代码或上下文会离开我的电脑吗?不会——LeanCTX 本地优先;你的上下文和记忆以可移植的 .ctxpkg 文件保存在你自己的电脑上,而且你可以在 OpenAI、Anthropic、Gemini 等模型提供商之间切换,不会丢失也不会暴露这些数据。
什么是影子模式(Shadow Mode)?它会在不改变你实际工作流程的情况下,让 LeanCTX 的处理与配置好的基线并行运行,然后报告成本、token 和 CPAO 的差异,以及输出质量是否保持——只有对比结果支持时,它才会推荐这些节省方案。
CPAO 是什么意思?即 Cost Per Accepted Outcome(每个已验收成果的成本)——这是 LeanCTX 的北极星指标,用来比较一项有用的 AI 工作实际花费多少,而不是只统计省下了多少原始 token。
我可以用第三方工具扩展 LeanCTX 吗?可以,通过签名的插件(addon):既可以是运行在流水线内部的沙箱化 WASM 模块,也可以是在清单中加入 [mcp] 条目来接入外部 MCP 服务器。项目刻意不设插件市场,而且每个插件的输出在到达模型之前都会被清理掉敏感信息并标记为不可信。
.ctxpkg 文件是什么?一种可移植的签名包,打包了代码知识、图谱和会话记忆,你可以在多台电脑之间迁移它,或在更换模型提供商时不丢失积累的上下文。
Creator
yvgude
Size
196.4 MB
Stars
3.9K
Age
6mo
Commits · 90 Days