Architecture

Thearchitecture.

One Rust binary. Five subsystems. Zero cloud dependencies. Every box below maps to a real module, port, or file on disk.

System topology.

The process topology of the shipped binary: seven entry points, one runtime, one set of local stores. Every box below maps to a real module, port or file on disk.

One binary. Five subsystems. No cloud required.

Data Flow Stage by stage.

Sheet 2 traces one request through the runtime, stage by stage, including the cache short-circuit that makes repeated reads nearly free. The shell path runs in parallel with the same accounting.

Compression engine.

Tree-sitter parses 27 languages into ASTs. 10 read modes select the right abstraction level — from full source to aggressive entropy filtering. 95+ shell patterns compress git, cargo, npm, docker, and kubectl output into compact evidence.

Explore read modes
ctx_read — mode selectionauto
Available modes
full entire file, no compression
signatures fn signatures + type defs
map structural overview
diff uncommitted changes only
task query-conditioned extract
aggressive maximum compression
entropy information-dense lines
reference symbols + doc comments
lines:N-M specific line range
Selected: signatures (420 lines → 18 lines)
27 languages · tree-sitter−95.7%

Memory, agents, security.

Content-addressed caching collapses re-reads to ~13 tokens. A knowledge graph persists decisions across sessions. The agent bus coordinates multiple agents without duplicating context. PathJail, shell allowlists, and TOCTOU checks enforce deny-by-default boundaries on every call.

Security model
lean-ctx doctorall passed
Cache 47 entries · 73% hit rate
Knowledge 342 nodes · 1,205 edges
Agent bus 3 agents registered
PathJail root: /Users/dev/project
Allowlist 14 allow, 6 deny
Redaction .env, credentials.*
TOCTOU open-handle verify active
Ledger Ed25519-signed · 0 violations
8/8 subsystems healthydeny-by-default

Engineering data sheet.

The reference tables behind the drawings: every surface with its transport and lifecycle, the on-disk layout, the adaptive-learning layers, and the security boundaries the runtime enforces.

AProcess model

All surfaces are the same binary in different roles. Nothing requires a cloud connection; everything binds local-first.

REFSURFACETRANSPORTENDPOINTLIFECYCLECOMMAND
01MCP server (stdio)JSON-RPC over stdin/stdoutspawned per editor sessionchild process of the editorlean-ctx
02MCP server (HTTP)MCP Streamable HTTPlocalhost, configurable --host/--portforeground or servicelean-ctx serve
03IPC daemonUnix Domain SocketOS data dir, e.g. ~/Library/Application Support/lean-ctx/daemon.socklaunchd / systemd autostartlean-ctx serve --daemon
04Shell hookprocess exec, compressed stdoutwraps IDE bash calls + interactive shellsper commandlean-ctx -c "<cmd>"
05API proxyHTTP (LLM API pass-through)localhost:4444 (default)on demandlean-ctx proxy start
06Web dashboardHTTP + bearer tokenlocalhost:3333 (default, --port)on demandlean-ctx dashboard
07Terminal UITTY (in-place redraw)live event stream / 1 s refreshinteractivelean-ctx watch · gain --live

BStorage layout — local XDG dirs

Persistent state is plain files under the XDG base directories: inspectable, exportable, deletable. No hidden databases beyond these local folders.

ARTIFACTFORMPURPOSE
config.tomlTOMLSingle config file — integration mode, compression, providers, opt-outs (config dir)
cache/content-addressedSession file cache; unchanged re-reads collapse to ~13-token stubs (cache dir)
bm25 indexinverted indexLexical search over code chunks + provider documents (data dir)
context_graph/property graphImports, calls, types across files and repos — powers map mode + deep queries (data dir)
knowledgeSQLitePersistent facts, decisions, rooms — recalled across sessions, CCP (data dir)
savings ledgerappend-only JSONLEvery compression event; Ed25519-signable for audit (data dir)
litm_calibration.jsonJSONLearned context-position hit rates (lost-in-the-middle calibration) (cache dir)
events.jsonlevent streamLive feed consumed by watch, dashboard and efficacy reports (state dir)

CAdaptive-learning layers

Seven online-learning mechanisms tune compression to your real usage, locally, from quality signals like bounces and edit failures. Deep dive: Adaptive Learning →

  • L1
    Adaptive thresholdsOnline-learned compression aggressiveness from quality signals (bounces, edit failures, clean runs)
  • L2
    LITM calibrationEmpirical placement of critical context at positions the model actually attends to
  • L3
    Stigmergic scent fieldMulti-agent coordination via decaying markers: claimed, done, stuck, hot, avoid
  • L4
    Delta playbookIncremental checkpoint snapshots that survive context compaction
  • L5
    Query-conditioned IBInformation-Bottleneck compression fused with query relevance
  • L6
    Theta-gamma chunkingWakeup facts grouped in attention-friendly bursts
  • L7
    Semantic dedupLikelihood-scored redundancy filtering across the session

DSecurity boundaries

Hard guarantees enforced in the runtime. Security model →

  • PathJailEvery file access is canonicalised and confined to the workspace root
  • IDE config-dir jailHome-level IDE/agent config dirs (~/.claude, ~/.codex, ~/.codebuddy, …) are writable only when allow_ide_config_dirs is opted in; otherwise PathJail blocks them
  • Shell allowlistDeny-by-default command policy for agent-issued shell executions
  • Local-firstAll processing on-device; dashboard binds to localhost and requires a bearer token
  • Signed evidenceSavings ledger entries are Ed25519-signable and batch-verifiable

Explore thesource.

LeanCTX is open source. Read the code, understand the design, contribute.

Support this project