ドキュメント

自律インテリジェンスレイヤー

ctx_smart_read、ctx_delta、ctx_fill、ctx_intent、ctx_context、ctx_graph、ctx_discover、ctx_dedup、ctx_response - ワークフローとコード構造を理解する自律型ツール。

自律インテリジェンスレイヤーは、基本的な圧縮を超えたツールを提供します。ワークフローの理解、意図の検出、コンテキストの重複排除、token 予算のインテリジェントな管理を行います。v2.14.1 以降、これらのツールは自律的に動作します:セッション開始時のコンテキスト自動プリロード、読み取り後の関連ファイルヒント追加、インポートファイルの暗黙的 cache、cache 増大時の重複排除 - すべて明示的なコマンドなしに実行されます。

ctx_smart_read

Adaptive file read that automatically selects the optimal compression mode based on file size, type, cache state, and token budget.

パラメータ

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

パラメータ

  • 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).

パラメータ

  • paths (required) - array of file paths
  • budget (required) - maximum token budget
  • task (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.

パラメータ

  • query (required) - natural language description of what you want to do
  • project_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.

パラメータ

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.

パラメータ

パラメータ必須説明
actionstringYesbuild, related, symbol, impact, or status
pathstringFor related/symbol/impactFile path or symbol name to query
project_rootstringNoProject 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.

パラメータ

  • action (optional) - analyze (default, report-only) or apply (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.

パラメータ

  • text (required) - text to compress
Full reference →

ctx_discover

Analyzes shell history to find commands that could benefit from lean-ctx compression. Shows missed savings opportunities with estimated token/cost savings.

パラメータ

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

パラメータ

  • path (required) - file path to edit
  • old_string (optional) - exact text to find. Omit when creating a new file.
  • new_string (required) - replacement text
  • create (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.

パラメータ

  • task (required) - description of current task for relevance-based file selection
  • path (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 →

BM25 + 密な埋め込みによるハイブリッド意味検索。自動のインクリメンタル索引付き。埋め込みが利用できない場合は BM25 にフォールバックします。

パラメータ

  • query (required) - natural language search query
  • path (optional) - project root to search
  • top_k (optional) - number of results (default 10)
  • action (optional) - reindex to rebuild index
  • mode (optional) - hybrid (default), dense, bm25
  • languages (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

名前で特定のシンボル(関数/struct/クラス/メソッド)を読み、行番号付きで該当コード範囲のみ返します。

パラメータ

  • name (required) - symbol name
  • file (optional) - narrow by file path
  • kind (optional) - fn, struct, class, method, trait, enum
Full reference →

ctx_outline

ファイル全体を読まずに、ファイルのアウトライン(シンボル + シグネチャ)をコンパクトに生成します。

パラメータ

  • path (required) - file path
  • kind (optional) - filter by kind
Full reference →

ctx_callers

永続コールグラフ(インクリメンタル構築)を使って、関数/メソッドを呼ぶシンボルを見つけます。

パラメータ

  • symbol (required) - symbol name to find callers of
  • file (optional) - filter by caller file
Full reference →

ctx_callees

永続コールグラフ(インクリメンタル構築)を使って、シンボルが呼ぶ関数/メソッドを一覧します。

パラメータ

  • symbol (required) - symbol name to list callees for
  • file (optional) - filter by caller file
Full reference →

ctx_routes

一般的なフレームワークから HTTP ルート/エンドポイントを抽出し、ハンドラとファイル位置付きで一覧します。

パラメータ

  • method (optional) - HTTP method (GET, POST, ...)
  • path (optional) - path prefix (e.g. /api)
Full reference →

ctx_graph_diagram

依存グラフ(deps)またはコールグラフ(calls)の Mermaid 図を生成します。

パラメータ

  • kind (optional) - deps (default) or calls
  • file (optional) - focus filter
  • depth (optional) - max depth (default 2)
Full reference →

ctx_compress_memory

メモリ/設定 Markdown を圧縮(コードブロック・URL・パス保持)し、.original.md バックアップを作成します。

パラメータ

  • path (required) - file path to compress
Full reference →

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.

パラメータ

  • action (required) - analyze (default), chain (dependency chain), build (rebuild index), or status
  • root (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.

パラメータ

  • action (required) - overview (default), clusters, layers, cycles, entrypoints, or module
  • root (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.

ParamTypeReqDescription
actionstringNostatus (default), build, build-full