开源项目 GitHub Topic ai-coding 2026-07-06T12:02 正文 ok 3643 words

📦 yvgude/lean-ctx:为 AI Agent 打造本地优先的上下文智能层,节省 60–90% 令牌

英文标题:📦 yvgude/lean-ctx

LeanCTX 是一个用 Rust 编写的本地二进制上下文工程层,可控制 AI Agent 读取、记忆、保护和验证的内容,并与 Cursor、Claude Code 等 30 多种 Agent 零配置集成。它通过 10 种读取模式、Shell 输出压缩和 Tree-sitter AST 理解等手段,将读取与 Shell 输出的令牌消耗降低 60–90%,并提供会话记忆、知识图谱与验证仪表板。对开发者而言,这意味着更长的有效编码会话、更低的 API 成本以及完全本地化、可移植且不受模型供应商绑定的上下文所有权。
打开原文相关 4.9 · 机会 5
media2.7 KB media2.2 KB media2.2 KB media1.3 KB media1.3 KB media1.2 KB media1.2 KB media1.6 KB media1.3 KB media3.1 KB media1.7 KB media1.3 KB media733.8 KB media302.1 KB media162.2 KB media63.0 KB media63.0 KB media6.3 KB media63.8 KB

中文


控制你的 AI 能看见什么。 LeanCTX — 全称 Lean Context — 是面向 AI Agent 的上下文工程层:一个本地 Rust 二进制文件,它决定你的 Agent 读什么,压缩它们发给模型的内容,记住它们学到的东西,守护它们接触的一切——并证明它们保存了什么。

令牌节省是收据。智能才是产品。可与 Cursor、Claude Code、Copilot、Windsurf、Codex、Gemini 以及 30 多种其他 Agent 协同工作——无需任何配置。

运行效果演示:

Map 模式文件读取 + 压缩的 git 输出演示
读取 + Shell
Map 模式读取 + 压缩后的 CLI 输出 | lean-ctx 实时收益仪表板演示
收益(实时)
实时令牌与美元节省 | lean-ctx 基准测试报告演示
基准验证
按语言和模式衡量压缩效果
---|---|---

所有 GIF 均由 demo/ 中可复现的 VHS 录制生成。

开发者为什么使用 LeanCTX

  • 更长的有效编码会话 — 更少的上下文浪费 = 为真正的代码推理留出更多空间
  • 更低的 API 成本 — 读取和 Shell 输出减少 60–90% 令牌,缓存重读仅消耗约 13 个令牌
  • 告别“我已经给你看过这个文件” — 会话记忆跨聊天保持
  • 适配你现有的配置 — 只需一条 lean-ctx setup 命令,无需更改配置
  • 完全可见 — 精确了解你的上下文窗口预算去向
  • 模型无关且属于你 — 自由切换 OpenAI/Anthropic/Gemini;你的上下文和记忆保持本地化、可移植,永远不会被锁在供应商的黑盒里

帮你省令牌了吗? 给它一颗星 — 能帮助更多人发现 LeanCTX。


为什么是现在 —— 拥有你的上下文

模型正在趋同于商品。持久的优势不在于你调用哪个模型——而在于你的上下文:你的 Agent 读什么、记住什么、以及你能证明什么。而优化并拥有这一上下文的层,不可能来自按令牌计费或将你的记忆锁在黑盒里的供应商——它必须坐在你这一边。

这就是“Agent 实体”背后的转变:它们存在于你的聊天中并记住你的公司(如 Slack 中的 Claude、ClickUp Brain):一种上下文登录,而非模型登录——你最终会把自己的公司知识租回来。LeanCTX 则是相反的层。它让护城河属于你:本地优先、可移植(.ctxpkg),且模型无关——随意切换 OpenAI、Anthropic 或 Gemini,不会丢失上下文或缓存。拥有你的上下文,而非租回它。


它能做什么 —— 上下文的四个维度

LeanCTX 将上下文视为受管理资源,而不仅仅是事后的想法。一个二进制文件覆盖了决定 AI Agent 实际表现的四个维度:

1. 压缩 —— 输入效率

你的 AI Agent 读取文件并运行命令。LeanCTX 自动压缩这两者。

  • 文件读取:10 种读取模式(full、map、signatures、diff、lines:N-M、density:X 等)——缓存重读仅消耗约 13 个令牌
  • 目标密度(density:0.4):SDE 风格的预算压缩——保留最高熵的行,直到约占原始令牌的 40%,确定性
  • 按需披露:signatures 携带行范围并指向 lines:N-M 以进行定向扩展——先看大纲,按需请求正文
  • Shell 输出:95 种以上的 Shell 输出模式,压缩 git、npm、cargo、docker、kubectl、terraform 等(270 条直通规则)
  • Tree-sitter AST:对 27 种语言的结构化理解——不仅仅是文本压缩
  • 设计上可逆(CCR):压缩从不丢弃内容——被修剪或截断的负载移动到内容寻址存储中,并带有确定性句柄,因此模型可通过 ctx_expand、ctx_retrieve、带内标记或 GET /v1/references/{id} 按需取回原始字节。五条恢复路径 →

2. 路由 —— 每次读取的通真度

不是每个文件都需要相同的深度。LeanCTX 发送信号,而非噪声。

  • 10 种读取模式:从完整内容到 AST 签名和熵过滤视图
  • 自适应 ModePredictor:从过往会话中学习每个文件类型的最优读取模式
  • IntentEngine:分类查询复杂度,让简单查询保持低成本

3. 记忆 —— 持久的上下文

上下文不再在聊天之间消失。

  • 会话记忆(CCP):跨聊天持久化任务/事实/决策——结构化恢复查询可在压缩后存活
  • 知识图谱:带有效期窗口的时间事实、情节记忆和程序性记忆
  • 属性图:多边代码图(导入、调用、导出、类型引用)支持影响分析和搜索排名
  • 你的,而非供应商的:记忆保持本地且可移植——将其导出为 .ctxpkg 包,跨机器或模型移动,而不是锁在供应商的黑盒里

4. 验证 —— 控制到达模型的内容

性能不仅是速度,更是准确性。你始终掌控上下文窗口。

  • 上下文管理器:带有实时令牌跟踪、压缩统计、利用率仪表盘的浏览器控制台
  • 预算与 SLO:配置文件、角色、每个 Agent 的预算和节流策略
  • 上下文证明(ctx_proof、ctx_verify):带 CI 漂移门的四层验证引擎

完整功能列表(81 个 MCP 工具)

  • Web 与研究(ctx_url_read):将公共网页、PDF 或 YouTube 转录拉入上下文,作为压缩的、带引用的文本——facts/quotes 返回带有置信度分数 + 来源 URL 的声明,相关性排序的研究压缩将内容提炼到令牌预算内,SSRF 防护(仅 http/https)
  • 图谱驱动智能:混合搜索(BM25 + 嵌入 + 基于 RRF 的图谱邻近度),增量 git-diff 更新
  • LSP 重构(ctx_refactor):通过 rust-analyzer、typescript-language-server、pylsp、gopls 支持语言服务器的重命名、引用、跳转到定义
  • 多 Agent(ctx_agent、ctx_handoff):带上下文传输包、日记系统、同步共享状态的 Agent 交接
  • 归档全文搜索(ctx_expand search_all):基于 FTS5 的跨归档搜索,覆盖所有先前归档的工具输出
  • PR 上下文包:lean-ctx pack --pr 构建一个准备就绪的 PR 上下文包(变更文件、相关测试、影响范围、制品)
  • 上下文包:lean-ctx pack create 将知识 + 图谱 + 会话打包为带有 SHA-256 完整性的便携 .ctxpkg 文件
  • 上下文时光机:lean-ctx snapshot create|list|show|verify|restore|publish|import —— 基于 git 锚定、ed25519 签名的层状态快照(谱系、分类账 Φ、ROI、会话),记录在追加时间线上;在仪表板中回放,restore 以恢复会话(--git 可检出提交),或 publish/import 一个签名快照进行分享(概念 →)
  • 可观测性:lean-ctx gain --live 实时节省,lean-ctx wrapped 周/月摘要(gain --svg/--share 生成可分享卡片或自托管页面),lean-ctx watch 提供 TUI 监控
  • 已验证的节省:lean-ctx savings 是一个可审计的、每事件分类账(分词器透明度、反弹网、防篡改 SHA-256 链)——仅本地,默认开启
  • HTTP 模式:lean-ctx serve 用于 Streamable HTTP MCP + /v1/tools/call(用于 Cookbook + SDK)

插件 —— 通过一个网关运行整个生态

你不必在 LeanCTX 和你已经喜欢的其他上下文工具之间做选择。一个插件用一个微小的 lean-ctx-addon.toml 清单包裹任何 MCP 服务器;LeanCTX 用一条命令在其网关后运行它,然后将其返回的内容当作你自己的读取一样处理,而不是仅仅代理它。

lean-ctx addon search memory # 按类别浏览注册表 lean-ctx addon add headroom # 安装上游包,并在添加时连接 MCP 服务器 lean-ctx addon list # 列出已接入你网关的插件

  • 一条命令添加 — addon add <name> 通过其本机管理器(uv、pip、cargo、npm、brew、dotnet)安装上游包,并将 MCP 服务器接入你的网关。无需 fork,无需重新编译。
  • 融入,而不仅仅是代理 — 可选择的后处理将插件输出通过与你的代码相同的管道:压缩到预算、将超大块溢出到 ctx_expand 句柄、索引到 BM25 / 图谱 / 知识库。类型化适配器将特定工具直接路由到 ctx_expand、ctx_callgraph 和 ctx_knowledge。
  • 默认不信任 — 每个插件的输出在到达模型之前都会被擦除秘密并标记为不可信。始终开启,而非一个标志。
  • 你保持控制 — 通过一个 [addons] 策略,将一台机器或整个集群固定为仅验证项、白名单或完全关闭,单个仓库无法覆盖。

注册表涵盖压缩(Headroom、Sophon)、代码智能(Repomix、Serena)、记忆(Mem0、Cognee、Letta)和推理(Sequential Thinking)。查看**插件指南** 或浏览全部。

LeanCTX 正从单一上下文层成长为整个团队的完整认知上下文层:版本控制的上下文策略、一个统一图谱,以及跨多个 Agent 的治理层。

  • 上下文时光机 → 托管历史 — 快照引擎、仪表板回放、恢复以及基于签名文件的共享/导入已发布(见上文);下一步是 ctxpkg.com 注册表,用于托管、版本化的上下文历史以及并排的模型视图 | git-diff 回放。这贯穿 LeanCTX 所做的一切的时间轴——它决策、记忆、守护、证明和回放。(概念 →)
  • 上下文即代码 — TOML 中的声明式管道、配置文件和策略,像基础设施一样进行版本控制
  • 统一上下文图谱 — 将代码、测试、提交、CI 运行和知识条目放在单一语义图谱中
  • Agent 工具框架 — 用于多 Agent 治理的角色、预算和工具权限
  • 上下文可观测性 — 上下文消耗上的 SLO、异常检测、OpenTelemetry / Prometheus 导出

完整路线图在 VISION.md 中。

它是如何工作的(30 秒)

LeanCTX 运作在两个平面上——你的 Agent 读取什么以及它们向模型发送什么:

read path: AI 工具 → (MCP 工具 + shell) → lean-ctx → 你的仓库 + CLI wire path: AI 工具 → lean-ctx 代理 → 模型供应商 (每个请求,均被压缩)

  • MCP 服务器 (读取路径):暴露 ctx_* 工具(读取模式、缓存、增量、搜索、记忆、多 Agent)
  • Shell 钩子 (读取路径):透明地压缩常见命令,让 LLM 看到更少的噪声
  • 请求代理 (线路路径,可选):lean-ctx proxy enable 在你的 Agent 和模型之间放置一个本地代理,压缩每个请求——系统提示、完整历史记录和工具结果——缓存友好,并测量美元花费。它还可以跨 OpenAI、Anthropic 和 Gemini 固定一个推理努力级别(proxy.effort),而不会破坏缓存,通过缓存友好的简洁引导和可衡量的保留组削减输出令牌,并将可变字段(日期、UUID、提交 SHA)重新定位到可缓存前缀之外,让稳定的系统提示最终得以缓存。每次重写都是可逆的(内容寻址恢复),并按契约保持字节稳定。与独立的请求压缩代理(例如 Headroom)处于同一层——你无需在其上层叠一个。
  • 属性图:多边代码图支持影响分析、关联文件发现和搜索排名
  • 会话记忆:持久化状态并结构化恢复,让长时间工作永不“冷启动”
  • 上下文管理器:浏览器仪表板,实时查看上下文窗口中的内容

1) 安装 (任选其一)

curl -fsSL https://leanctx.com/install.sh | sh # 通用 (无需 Rust) brew tap yvgude/lean-ctx && brew install lean-ctx # macOS / Linux npm install -g lean-ctx-bin # Node.js cargo install lean-ctx # Rust pi install npm:pi-lean-ctx # Pi Coding Agent

2) 连接你的 AI 工具 (零提示,合理默认值)

lean-ctx onboard # 或: lean-ctx setup (引导式,完全控制)

3) 验证

lean-ctx doctor

4) 重启你的 shell + AI 工具,正常使用,然后查看回报

lean-ctx gain # 你的 AI 首次 lean-ctx 调用后,节省才会出现

登录后,重启你的 shell 和编辑器/AI 工具一次,使 MCP + 钩子生效。lean-ctx gain 在你的 AI 工具进行首次 lean-ctx 调用之前是空的——这是正常现象,不是配置错误。

在 Windows 上从源代码构建? 克隆仓库并在 PowerShell 中运行 ./install.ps1——它将构建 release 二进制文件并安装到 Cargo 的 bin 目录(传递 -BuildOnly 则仅构建不安装)。

故障排除 / 安全

  • 立即禁用(当前 shell):lean-ctx-off
  • 以原始方式运行单个命令:lean-ctx -c --raw "git status"
  • 仅在 AI Agent 会话中激活:在 ~/.config/lean-ctx/config.toml 中设置 shell_activation = "agents-only"
  • 每个项目的配置覆盖:在项目根目录中创建 .lean-ctx.toml(自动与全局配置合并)
  • 共享 /workspace 的 Docker 项目:创建 .lean-ctx-id 并使用唯一名称来标识

English / 原文


Control what your AI can see. LeanCTX — short for Lean Context — is the context engineering layer for AI agents: one local Rust binary that decides what your agents read, compresses what they send to the model, remembers what they learn, guards what they touch — and proves what they save.

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

  • Longer useful coding sessions — less context waste = more room for actual code reasoning
  • Lower API costs — 60–90% fewer tokens on reads and shell output, cached re-reads cost ~13 tokens
  • No more "I already showed you this file" — session memory persists across chats
  • Works with your existing setup — one lean-ctx setup command, no config changes needed
  • Full visibility — see exactly where your context window budget goes
  • Model-agnostic & yours — swap OpenAI/Anthropic/Gemini freely; your context and memory stay local and portable, never locked in a vendor's black box

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 — the four dimensions of context

LeanCTX treats context as a managed resource, not an afterthought. One binary covers the four dimensions that decide how well an AI agent actually performs:

1. Compression — input efficiency

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

  • File reads : 10 read modes (full, map, signatures, diff, lines:N-M, density:X, …) — cached re-reads cost ~13 tokens
  • 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 : 95+ shell-output patterns compress git, npm, cargo, docker, kubectl, terraform and more (270 passthrough rules)
  • Tree-sitter AST : structural understanding for 27 languages — not just text compression
  • Reversible by design (CCR) : compression never discards content — pruned or truncated payloads move to a content-addressed store with a deterministic handle, so the model can pull the original bytes back on demand via ctx_expand, ctx_retrieve, an in-band marker, or GET /v1/references/{id}. Five recovery paths →

2. Routing — the right fidelity per read

Not every file needs the same depth. LeanCTX sends the signal, not the noise.

  • 10 read modes : from full content down to AST signatures and entropy-filtered views
  • AdaptiveModePredictor: learns the optimal read mode per file type from past sessions
  • IntentEngine : classifies query complexity so simple lookups stay cheap

3. Memory — context that persists

Context doesn't disappear between chats anymore.

  • 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
  • Yours, not the vendor's : memory stays local and portable — export it as a .ctxpkg package and move it across machines or models, instead of locking it in a vendor's black box

4. Verification — control what reaches the model

Performance is accuracy, not just speed. You stay in control of the window.

  • Context Manager : browser dashboard with real-time token tracking, compression stats, utilization gauge
  • Budgets & SLOs: profiles, roles, per-agent budgets, and throttling policies
  • Context Proof (ctx_proof, ctx_verify): 4-layer verification engine with CI drift gates

Full feature list (81 MCP tools)

  • 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 + SDK)

Addons — run the ecosystem through one gateway

You don't have to choose between LeanCTX and the other context tools you already like. An addon wraps any MCP server in a tiny lean-ctx-addon.toml manifest; LeanCTX runs it behind its gateway with one command, then treats what it returns like your own reads instead of just proxying it.

lean-ctx addon search memory   # browse the registry by category
lean-ctx addon add headroom    # installs the upstream package + wires the MCP server, on add
lean-ctx addon list            # what's wired into your gateway
  • One command to add — addon add <name> installs the upstream package via its native manager (uv, pip, cargo, npm, brew, dotnet) and wires the MCP server into your gateway. No fork, no recompile.
  • Folded in, not just proxied — opt-in post-processing runs addon output through the same pipeline as your code: compress to a budget, spill oversized blobs to a ctx_expand handle, index into BM25 / graph / knowledge. Typed adapters route specific tools straight into ctx_expand, ctx_callgraph and ctx_knowledge.
  • Untrusted by default — every addon's output is scrubbed for secrets and tagged untrusted before it reaches the model. Always on, not a flag.
  • You stay in control — pin a machine or fleet to verified-only, an allowlist, or off entirely via one [addons] policy a single repo can't override.

The registry spans compression (Headroom, Sophon), code intelligence (Repomix, Serena), memory (Mem0, Cognee, Letta) and reasoning (Sequential Thinking). See the addon guide or browse them all.

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.

  • Context Time Machine → hosted history — the snapshot engine, dashboard replay, restore, and signed file-based share/import have shipped (see above); next is a ctxpkg.com registry for hosted, versioned context history and a side-by-side model-view | git-diff replay. The temporal axis through everything LeanCTX does — it decides, remembers, guards, proves, and replays. (concept →)
  • Context as Code — declarative pipelines, profiles, and policies in TOML, versioned like infrastructure
  • Unified Context Graph — code, tests, commits, CI runs, and knowledge entries in a single semantic graph
  • Agent Harness — roles, budgets, and tool permissions for multi-agent governance
  • Context Observability — SLOs on context consumption, anomaly detection, OpenTelemetry / Prometheus export

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)
  • MCP server (read path) : exposes ctx_* tools (read modes, caching, deltas, search, memory, multi-agent)

  • Shell hook (read path) : transparently compresses common commands so the LLM sees less noise

  • Request proxy (wire path, opt-in) : lean-ctx proxy enable puts a local proxy between your agent and the model that compresses every request — system prompt, full history and tool results — prompt-cache-safe, with measured USD spend. It can also pin one reasoning-effort level across OpenAI, Anthropic & Gemini (proxy.effort) without breaking that cache, cut output tokens with a cache-safe verbosity steer plus a measured holdout, and relocate volatile fields (dates, UUIDs, commit SHAs) out of the cacheable prefix so a stable system prompt finally caches. Every rewrite is reversible (content-addressed recovery) and byte-stable by contract. Same layer as a standalone request-compression proxy (e.g. Headroom) — you don't need one on top.

  • Property Graph : multi-edge code graph powers impact analysis, related file discovery, and search ranking

  • Session memory : persists state with structured recovery so long-running work never "cold starts"

  • Context Manager : browser dashboard for real-time visibility into what's in your context window

    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 pi install npm:pi-lean-ctx # Pi Coding Agent

    2) Connect your AI tools (zero prompts, sensible defaults)

    lean-ctx onboard # or: lean-ctx setup (guided, full control)

    3) Verify

    lean-ctx doctor

    4) Restart your shell + AI tool, use it normally, then see the payoff

    lean-ctx gain # savings appear after your AI's first lean-ctx call

After onboarding, restart your shell and your editor/AI tool once so the MCP + hooks are active. lean-ctx gain is empty until your AI tool makes its first lean-ctx call — that's expected, not a misconfiguration.

Building from source on Windows? Clone the repo and run ./install.ps1 in PowerShell — it builds the release binary and installs it into Cargo's bin directory (pass -BuildOnly to build without installing).

Troubleshooting / Safety

  • Disable immediately (current shell): lean-ctx-off
  • Run a single command uncompressed: lean-ctx -c --raw "git status"
  • Only activate in AI agent sessions: set shell_activation = "agents-only" in ~/.config/lean-ctx/config.toml
  • Per-project config override: create .lean-ctx.toml in your project root (auto-merged with global config)
  • Docker projects sharing /workspace: create .lean-ctx-id with a unique name to prevent context collisions
  • Update: lean-ctx update
  • Diagnose (shareable): lean-ctx doctor --json

Use it from your own code (SDKs)

Beyond the CLI, lean-ctx ships published libraries so you can call it directly from your app.

Drop-in prompt compression —lean-ctx-sdk (npm). Compress a chat-style messages array before it reaches any model — deterministic and prompt-cache friendly; images, tool-calls and ids pass through untouched.

# pip install lean-ctx-sdk
from lean_ctx import compress
messages = compress(messages, model="claude-sonnet-4")


// npm install lean-ctx-sdk
import { compress } from "lean-ctx-sdk";
messages = await compress(messages, { model: "gpt-4o" });

Framework adapters included (LiteLLM, LangChain, Vercel AI SDK). → compress() cookbook

Thin/v1 contract clients — lean-ctx-client (npm · crates.io). Wrap the full /v1 tool, event and session API over the process boundary — never links the engine, so it stays stable as lean-ctx evolves.

pip install lean-ctx-client     # Python (imports as `leanctx`)
npm install lean-ctx-client     # TypeScript / Node
cargo add lean-ctx-client       # Rust

Start the server with lean-ctx serve, then point a client at it. → API reference

LeanCTX grows with you. Below are the journeys most people actually take — each links to a complete, function-by-function walkthrough in the Reference (every CLI command and all 79 MCP tools are documented there).

"I just installed it — now what?"

lean-ctx onboard      # connect every detected AI tool
lean-ctx doctor       # confirm you're wired up

One command auto-detects Cursor/Claude/Codex/… and configures MCP + hooks. → Journey 1 — Setup& Onboarding | "Stop re-reading the same files."

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

🧠 Resume where you left off

"My new chat forgot everything."

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 |

🗺️ Understand a new codebase

"Where does this function ripple to?"

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
"Pull in GitHub issues and our Postgres schema."

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 | "Update, fix, or cleanly remove."

lean-ctx doctor --fix
lean-ctx update

Self-healing diagnostics; surgical uninstall that only removes its own blocks. → Journey 6 — Lifecycle& Troubleshooting

🎛️ Take control of the window

"Budget my context like a pro."

lean-ctx plan "refactor billing" --budget 8000
lean-ctx compile --mode balanced

Phi-scored planning + knapsack compilation + a context ledger. → Journey 7 — Context Engineering | "Planner + coder + reviewer on one repo."

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

🏢 Share across a team / CI

"One shared index, headless in pipelines."

lean-ctx team serve --config team.toml
lean-ctx bootstrap            # zero-prompt CI setup

Scoped tokens, optional cloud sync, verifiable context gates. → Journey 9 — Team, Cloud& CI | "Make it behave exactly how we want."

lean-ctx compression standard
lean-ctx harden               # enforce token discipline

Compression levels, tool profiles, themes, and rules governance. → Journey 10 — Customization& Governance
"Show me the numbers."

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 | "I want to read everything." Every command and all 81 MCP tools, organized as user journeys, plus appendices for the CLI map, MCP tools, and paths & config. → Reference index

Supported IDEs & AI tools

LeanCTX is a standard MCP server , so it works with any MCP-compatible client. Two integration modes are auto-selected per agent:

Mode How it works Best for
Hybrid MCP for cached reads (~13 tokens) + shell hooks for command compression Agents with shell access (Cursor, Claude Code, Codex, ...)
MCP All 80 tools via MCP protocol, no shell hooks Protocol-only agents (JetBrains, VS Code, Zed, ...)

Agent compatibility matrix

Agent Hybrid MCP Setup
Cursor ● lean-ctx init --agent cursor
Claude Code ● lean-ctx init --agent claude
CodeBuddy ● lean-ctx init --agent codebuddy
Augment CLI / VS Code ● lean-ctx init --agent augment
Codex CLI ● lean-ctx init --agent codex
Gemini CLI ● lean-ctx init --agent gemini
Windsurf ● lean-ctx init --agent windsurf
GitHub Copilot ● lean-ctx init --agent copilot
CRUSH ● lean-ctx init --agent crush
Hermes ● lean-ctx init --agent hermes
OpenCode ● lean-ctx init --agent opencode
Pi ● lean-ctx init --agent pi
Qoder ● lean-ctx init --agent qoder
Amp ● lean-ctx init --agent amp
Cline ● lean-ctx init --agent cline
Roo Code ● lean-ctx init --agent roo
Kiro ● lean-ctx init --agent kiro
Antigravity ● lean-ctx init --agent antigravity
Amazon Q ● lean-ctx init --agent amazonq
Qwen ● lean-ctx init --agent qwen
Trae ● lean-ctx init --agent trae
Verdent ● lean-ctx init --agent verdent
Aider ● lean-ctx init --agent aider
Continue ● lean-ctx init --agent continue
JetBrains IDEs ● lean-ctx init --agent jetbrains
QoderWork ● lean-ctx init --agent qoderwork
VS Code ● lean-ctx init --agent vscode
Zed ● lean-ctx init --agent zed
Neovim ● lean-ctx init --agent neovim
Emacs ● lean-ctx init --agent emacs
Sublime Text ● lean-ctx init --agent sublime

Any MCP-compatible client works out of the box — the table above shows agents with first-class auto-setup.

When to use (and when not to)

Great fit if you...

  • use AI coding tools daily and your sessions are shell-heavy (git/tests/builds)
  • work in medium/large repos (50+ files / monorepos)
  • want a local-first layer with no telemetry by default

Skip it if you...

  • mostly work in tiny repos and rarely call the shell from your AI tool
  • always need raw/unfiltered logs (you can still use --raw, but ROI is lower)

The honest fine print: the payoff depends on three levers — reach (own the window via the proxy/engine, not just the ctx_* tool layer), context lifetime (one long-lived session vs. a fresh process per phase), and provider pricing (prompt-cache-priced vs. re-billed every turn). They stack into a clear win where they line up and net to break-even where they don't. See the win vs. break-even matrix for the full breakdown and how to tune for each case.

Try these in any repo:

lean-ctx read rust/src/server/mod.rs -m map
lean-ctx -c "git log -n 5 --oneline"
lean-ctx gain --live
lean-ctx dashboard                              # Context Manager (browser)
lean-ctx watch                                  # TUI monitor
lean-ctx benchmark report .
  • The repo ships the exact tapes used to render the GIFs in demo/

  • Regenerate locally:

    vhs demo/leanctx.tape vhs demo/gain.tape vhs demo/benchmark.tape

Real, reproduced numbers — never estimated. Measured on this repo with the GPT-4o tokenizer (o200k_base); a tool that isn't installed is reported as such, never guessed.

Read mode Compression Tokens (50 files) Quality
Raw read 0% 533.2K 100%
map 98.1% 8.0K 78%
signatures 96.7% 14.0K 96%
Cached re-read ~99.99% ~13 tok 100%

lean-ctx's own cost is measured too : the fixed per-session footprint it injects (advertised tool schemas + MCP instructions) is ~2.1K tokens and CI-gated via lean-ctx doctor overhead --gate, so it can only shrink. And the long-lived proxy rail has a deterministic self-verify — lean-ctx benchmark dual-arm --json replays a 15-turn session and prices it per model (digest f5ed145e61ce3689, 99.4% input-side saving on cache-priced rails; methodology: bench/agent-task/r2).

Accuracy isn't a vibe: the lossy stages are CI-gated. A model-free A/B gate proves the JSON crusher keeps every gold answer while cutting tokens, and proxy rewrites are byte-stable by contract, so Anthropic (90%) / OpenAI (50%) prompt-cache discounts survive compression. A deterministic off-vs-on testbench (lean-ctx eval testbench) extends the proof to answers : it runs pinned real repos through a raw-dump baseline and through lean-ctx at an identical token budget, grades free-form QA with an LLM judge and code with each repo's own tests, and emits FINDINGS.md (tokens / turns / walltime / quality) plus a regressions file — with a committed recorded subset that blocks CI on any regression.

  • Latest snapshot : BENCHMARKS.md

  • Reproduce : lean-ctx benchmark report .

  • 3,000+ GitHub stars — and counting

  • 280+ forks — active community contributions

  • 200+ releases — shipped near-daily since launch

  • 30+ supported AI coding agents — broadest MCP compatibility

  • 81 MCP tools — from simple file reads to multi-agent orchestration

  • Used in production by teams running Claude Code, Cursor, and Codex daily

  • Live adoption metrics : leanctx.com/metrics — installs, stars and savings, updated continuously

  • No telemetry by default

  • Optional anonymous stats sharing (opt-in during setup)

  • Disableable update check (config update_check_disabled = true or LEAN_CTX_NO_UPDATE_CHECK=1)

  • 40+ security hardening fixes in v3.5.16 (path traversal, injection, CSPRNG, CSP, resource limits — details)

  • Context Governance Benchmark self-assessment : graded C2 — Managed against the 32-control CGB v1.0-draft spec, gaps declared — docs/compliance/cgb-self-assessment.md

  • Runs locally; your code never leaves your machine unless you explicitly enable cloud sync

See SECURITY.md.

One command removes everything — it stops all processes, then deletes hooks, editor configs, rules, autostart (LaunchAgent/systemd), the data dir, and the binary itself :

lean-ctx uninstall                 # full clean removal
lean-ctx uninstall --dry-run       # preview every change, write nothing
lean-ctx uninstall --keep-config   # keep MCP configs + rules (for reinstall)
lean-ctx-off                       # or just disable for the current shell session

No binary on PATH (or you used the curl installer)? Run the same removal from the installer:

curl -fsSL https://leanctx.com/install.sh | sh -s -- --uninstall

If you installed via a package manager, uninstall removes everything it wrote and tells you the one command to finish removing the binary:

brew uninstall lean-ctx        # Homebrew
cargo uninstall lean-ctx       # cargo install
npm uninstall -g lean-ctx-bin  # npm
pi uninstall npm:pi-lean-ctx   # Pi Coding Agent

Star History Chart

Start with CONTRIBUTING.md. Easy first PR: propose a new CLI compression pattern via the issue template.

Apache License 2.0 — see LICENSE.