La couche d'intelligence autonome fournit des outils qui vont au-delà de la simple compression - ils comprennent votre flux de travail, détectent l'intention, dédupliquent le contexte et gèrent intelligemment les budgets de tokens. Depuis la v2.14.1, ces outils fonctionnent de manière autonome : préchargement automatique du contexte au démarrage de la session, ajout d'indices de fichiers liés après les lectures, mise en cache silencieuse des fichiers importés et déduplication lorsque le cache grossit - le tout sans commandes explicites.
ctx_smart_read
Adaptive file read that automatically selects the optimal compression mode based on file size, type, cache state, and token budget.
Paramètres
path(required) - file path to read
Example
ctx_smart_read src/auth.ts
→ [auto:map] Selected map mode (file cached, 915 tokens → 89 tokens) Full reference → ctx_delta
Incremental file update using Myers diff. Only sends changed lines (hunks with context) instead of full file content. Automatically updates the cache after computing the delta.
Paramètres
path(required) - file path to diff against cached version
Example
ctx_delta src/auth.ts
→ Δ auth.ts (3 hunks, 12 lines changed)
@@ -45,3 +45,5 @@
+ const token = generateJWT(user);
+ res.cookie('session', token); Full reference → ctx_fill
Priority-based context filling with a token budget. Given a list of files and a budget, automatically selects the best compression mode per file to maximize information within the budget. Higher-relevance files get more tokens (full mode); lower-relevance files get compressed (signatures).
Paramètres
paths(required) - array of file pathsbudget(required) - maximum token budgettask(optional) - task description for priority-based POP-Intent ordering
Example
ctx_fill ["src/auth.ts", "src/db.ts", "src/routes.ts"] budget=2000
→ Budget: 2000 tokens
auth.ts → full (915 tokens, priority 10)
db.ts → map (89 tokens, priority 5)
routes.ts → signatures (42 tokens, priority 3)
Total: 1046/2000 tokens used Full reference → ctx_intent
Semantic intent detection with multi-intent support. Analyzes natural language queries to determine intent (fix bug, add feature, refactor, understand, test, config, deploy, review), classifies complexity (mechanical/standard/architectural), and auto-loads relevant files ranked by heat score.
Paramètres
query(required) - natural language description of what you want to doproject_root(optional) - project root path (defaults to.)
Features (v2.18.0)
- Multi-intent - compound queries like "fix X and then test Y" are split into sub-intents
- Complexity - returns mechanical/standard/architectural classification
- Heat ranking - files ranked by token density + graph connectivity
Example
ctx_intent "fix the auth bug and then add tests for it"
→ Intent 1: fix_bug | Complexity: standard
Intent 2: test | Complexity: mechanical
Loaded 4 relevant files (heat-ranked):
F1=src/auth.ts (full, 915t) - heat: 0.92
F2=src/login.ts (full, 412t) - heat: 0.78
F3=src/__tests__/auth.test.ts (full, 340t) - heat: 0.65
F4=src/middleware.ts (map, 89t) - heat: 0.45 Full reference → ctx_context
Multi-turn context manager. Shows what files the LLM has already seen, which are cached, and provides a session overview to avoid redundant re-reads.
Paramètres
No parameters. Returns current context state.
Example
ctx_context
→ Turn 12 | Files: 8 cached | Reads: 24 | Cache hits: 16 (67%)
F1=auth.ts ✓cached [5 reads]
F2=db.ts ✓cached [3 reads]
F3=routes.ts ✓cached [2 reads, modified] Full reference → ctx_graph
Build and query a persistent project intelligence graph. Incrementally scans your codebase, extracts symbols and dependencies, and stores the index on disk for instant access across sessions. Supports 5 actions for structural understanding of any project.
Graph strategy: ctx_graph stores a lightweight JSON index for fast navigation
(symbols/related/quick impact). For deeper analysis, prefer ctx_impact and ctx_architecture,
which use the SQLite-backed property graph as the authoritative backend.
Paramètres
| Paramètre | Type | Requis | Description |
|---|---|---|---|
action | string | Yes | build, related, symbol, impact, or status |
path | string | For related/symbol/impact | File path or symbol name to query |
project_root | string | No | Project root path (defaults to cwd) |
Action: build
Incrementally scans the project, computing MD5 hashes to skip unchanged files.
Extracts symbols, dependencies, and edges. Persists to ~/.lean-ctx/graphs/<project-hash>/index.json.
Auto-build: The graph auto-builds when any query action (related, symbol, impact) is called and no index exists yet. Manual action=build is only needed to force a refresh of the index after significant code changes.
ctx_graph action=build
→ GRAPH BUILD - /Users/you/project
Scanned: 142 files (38 new, 104 cached)
Symbols: 847 exports across 12 languages
Edges: 1,203 import relationships
Index: ~/.lean-ctx/graphs/a3f8c1/index.json
Build: 340ms (incremental) Action: related
BFS traversal from a given file to find connected files via import/export relationships. Useful for understanding the blast radius of a change.
ctx_graph action=related path=src/auth.ts depth=2
→ Files related to auth.ts (depth 2):
src/middleware.ts - imports auth.ts
src/login.ts - imports auth.ts
src/lib/jwt.ts - imported by auth.ts
src/lib/session.ts - via middleware.ts Action: symbol
Reads a specific exported symbol by name from the graph index, returning the source code with line numbers. Avoids loading the entire file when you only need one function or type.
ctx_graph action=symbol path=createUser
→ SYMBOL: createUser
File: src/auth.ts:18-42
async function createUser(email: string, password: string): Promise<User> {
const hash = await bcrypt.hash(password, 12);
return db.users.create({ email, passwordHash: hash });
} Action: impact
Reverse dependency analysis - finds all files that depend on a given file. Essential for understanding what breaks when you change something.
ctx_graph action=impact path=src/lib/db.ts
→ IMPACT ANALYSIS: db.ts
Direct dependents (4):
src/auth.ts
src/users.ts
src/admin.ts
src/migration.ts
Transitive dependents (2):
src/routes.ts (via auth.ts)
src/middleware.ts (via auth.ts) Action: status
Shows index metadata: file count, symbol count, edge count, last build time, and freshness.
ctx_graph action=status
→ GRAPH STATUS
Project: /Users/you/project
Index: ~/.lean-ctx/graphs/a3f8c1/index.json
Files: 142 | Symbols: 847 | Edges: 1,203
Last build: 2026-03-27 14:30 (12 min ago)
Stale files: 3 (re-run build to update) Full reference → ctx_dedup
Cross-file deduplication analysis. Finds shared imports, boilerplate blocks, and repeated patterns across all cached files. Reports potential token savings.
Paramètres
action(optional) -analyze(default, report-only) orapply(apply dedup optimizations)
Example
ctx_dedup
→ Found 3 shared patterns across 8 cached files:
"import { db } from '../pages/docs/lib/db'" - 5 files (saving ~40 tokens)
"export default handler" - 4 files (saving ~25 tokens) Full reference → ctx_response
Bi-directional response compression. Compresses LLM response text by removing filler content and applying TDD shortcuts. Use to verify compression quality of responses.
Paramètres
text(required) - text to compress
ctx_discover
Analyzes shell history to find commands that could benefit from lean-ctx compression. Shows missed savings opportunities with estimated token/cost savings.
Paramètres
limit(optional) - number of results (default 15)
Example
ctx_discover
→ Shell commands that would benefit from lean-ctx:
docker ps -a - ran 12x, ~800 tokens each → ~9,600 tokens saveable
kubectl get pods - ran 8x, ~1,200 tokens each → ~9,600 tokens saveable Full reference → ctx_edit
Search-and-replace file editing that works without needing native Read or Edit tools. Reads the file, replaces the specified string, and writes the result - all in one MCP call.
Paramètres
path(required) - file path to editold_string(optional) - exact text to find. Omit when creating a new file.new_string(required) - replacement textcreate(optional, boolean) - create the file if it does not exist. Default:false.replace_all(optional, boolean) - replace all occurrences, not just the first. Default:false.
Example
ctx_edit path=src/config.ts old_string="timeout: 5000" new_string="timeout: 10000"
→ Replaced 1 occurrence in src/config.ts (cache updated) Full reference → ctx_preload
Proactive context loader. Given a task description, automatically identifies and caches
task-relevant files, returning a compact summary. Use at session start alongside ctx_overview.
Paramètres
task(required) - description of current task for relevance-based file selectionpath(optional) - project root path
Example
ctx_preload task="fix JWT token refresh"
→ Preloaded 5 files (2,340 tokens):
F1=src/auth.ts (full) F2=src/lib/jwt.ts (full) F3=src/middleware.ts (map)
F4=src/config.ts (signatures) F5=src/routes.ts (signatures) Full reference → ctx_semantic_search
Recherche sémantique hybride avec BM25 + embeddings denses et indexation incrémentale automatique. Revient à BM25 si les embeddings ne sont pas disponibles.
Paramètres
query(required) - natural language search querypath(optional) - project root to searchtop_k(optional) - number of results (default 10)action(optional) -reindexto rebuild indexmode(optional) -hybrid(default),dense,bm25languages(optional) - restrict to language/extension (e.g.["rust","ts"])path_glob(optional) - glob filter over relative paths (e.g."rust/src/**")
Example
ctx_semantic_search query="JWT token validation" top_k=5
→ 5 results:
1. src/auth.ts:18-42 - verifyJWT function (score: 0.89)
2. src/middleware.ts:5-20 - auth middleware (score: 0.76)
3. src/lib/jwt.ts:1-35 - JWT utilities (score: 0.71) Full reference → ctx_symbol
Lit un symbole spécifique (fonction/struct/classe/méthode) par nom et renvoie uniquement l'extrait pertinent avec numéros de ligne.
Paramètres
name(required) - symbol namefile(optional) - narrow by file pathkind(optional) -fn,struct,class,method,trait,enum
ctx_outline
Génère un plan compact d'un fichier (symboles + signatures) sans lire tout le contenu.
Paramètres
path(required) - file pathkind(optional) - filter by kind
ctx_callers
Trouve quels symboles appellent une fonction/méthode via le graphe d'appels persistant (construit incrémentalement).
Paramètres
symbol(required) - symbol name to find callers offile(optional) - filter by caller file
ctx_callees
Liste les fonctions/méthodes qu'un symbole appelle via le graphe d'appels persistant (construit incrémentalement).
Paramètres
symbol(required) - symbol name to list callees forfile(optional) - filter by caller file
ctx_routes
Extrait les routes/endpoints HTTP depuis des frameworks courants et les liste avec handler et emplacement du fichier.
Paramètres
method(optional) - HTTP method (GET, POST, ...)path(optional) - path prefix (e.g./api)
ctx_graph_diagram
Génère des diagrammes Mermaid pour les graphes de dépendances (deps) ou d'appels (calls).
Paramètres
kind(optional) -deps(default) orcallsfile(optional) - focus filterdepth(optional) - max depth (default 2)
ctx_compress_memory
Compresse des fichiers Markdown mémoire/config (préserve blocs de code, URLs, chemins) et crée une sauvegarde .original.md.
Paramètres
path(required) - file path to compress
ctx_impact - Reverse Dependency Analysis
Analyzes the impact of changing a file by tracing reverse dependencies through the project graph. Shows which files import or depend on the target, helping assess the blast radius of changes.
Paramètres
action(required) -analyze(default),chain(dependency chain),build(rebuild index), orstatusroot(required for analyze/chain) - file path to analyze impact for
Example
ctx_impact path=src/auth.ts
→ IMPACT ANALYSIS: src/auth.ts
Direct dependents (3):
src/routes.ts - imports: authenticate, createUser
src/middleware.ts - imports: verifyToken
src/api/users.ts - imports: AuthToken type
Transitive (depth 2): 7 more files
Blast radius: 10 files (7% of project) Full reference → ctx_architecture - Project Architecture Map
Generates a high-level architecture overview of the project using the dependency graph. Groups files into logical layers and shows inter-layer dependencies.
Paramètres
action(required) -overview(default),clusters,layers,cycles,entrypoints, ormoduleroot(optional) - project root or module path (defaults to cwd)
Example
ctx_architecture action=overview
→ ARCHITECTURE - /Users/you/project (142 files)
Layers:
API (12 files): routes.ts, controllers/*.ts
Service (8 files): services/*.ts
Data (5 files): models/*.ts, db.ts
Config (3 files): config.ts, env.ts
Dependencies:
API → Service → Data → Config
API → Config (direct) Full reference → Adaptive Compression (Wave 5)
Starting with v2.21, lean-ctx includes adaptive compression that learns from usage patterns and automatically optimizes compression strategies per project and language.
ACON Feedback Loop
The Adaptive Constraint Optimization Network (ACON) monitors compression outcomes for negative signals: retries, mode upgrades (e.g. map→full), errors after reads, and rapid re-reads. When a pattern of harmful compressions is detected (harm rate exceeds threshold), ACON automatically raises minimum quality constraints - e.g. increasing the entropy threshold or reducing maximum compression percentage.
Thompson Sampling Bandits
For each (file extension, file size) pair, a multi-armed bandit with Thompson Sampling learns the optimal compression parameters: BPE entropy threshold, Jaccard similarity threshold, and budget ratio. Arms with successful outcomes receive positive reinforcement; unsuccessful compressions penalize the selected arm. Over time, per-project and per-language optimal thresholds converge automatically.
Task-Aware KG Compression
The task read mode is task-conditioned: it runs an Information Bottleneck (IB) filter to keep only
task-relevant lines, and appends a compact Graph Context footer with the most relevant related files.
Graph context is best-effort and uses an existing project graph (prefers the SQLite property graph; falls back to the lightweight JSON index).
To enable it, build a graph once per project with ctx_graph action=build or ctx_impact action=build.
Storage
Bandit parameters: ~/.lean-ctx/projects/<hash>/bandits.json.
ACON constraints: Stored within the feedback store at ~/.lean-ctx/feedback.json.
ctx_index v3.4.5
ctx_index orchestrates project indexing - builds the property graph, symbol map, and dependency index used by ctx_graph, ctx_impact, and ctx_architecture.
| Param | Type | Req | Description |
|---|---|---|---|
action | string | No | status (default), build, build-full |