Документация

Сессия и мониторинг

ctx_session, ctx_metrics, ctx_cache, ctx_compress, ctx_analyze, ctx_benchmark, ctx_wrapped - инструменты для управления сессиями, мониторинга и анализа сжатия.

Эти инструменты обеспечивают сохранение сессий, мониторинг производительности, анализ сжатия и бенчмаркинг - всё необходимое для измерения и оптимизации экономии token.

ctx_session

Session state manager for cross-chat continuity. Persists task context, findings, decisions, and file state across chat sessions and context compactions.

Параметры

  • action (required) - one of: status, load, save, task, finding, decision, list, cleanup, snapshot, restore, resume, profile
  • value (optional) - value for task, finding, decision, or profile actions
  • session_id (optional) - specific session ID to load

Actions

ActionОписание
statusShow current session state
loadRestore most recent or specified session
saveForce persist session to disk
taskSet current task description
findingRecord a key finding (e.g. "auth.ts:45 - JWT expiry not checked")
decisionRecord an architectural decision
listList all saved sessions
cleanupRemove old sessions (keeps recent ones)
snapshotBuild a priority-tiered 2KB XML snapshot for context window recovery
restoreLoad the most recent compaction snapshot
resumeBuild a compact resume block for a fresh chat
profileShow or switch the active Context Profile at runtime

Example: Recording Context

ctx_session task "Implement OAuth2 login flow"
ctx_session finding "auth.ts:45 - missing token refresh logic"
ctx_session decision "Use refresh tokens with 7-day expiry"
ctx_session save

Example: Restoring Context

ctx_session load
→ Restored session (2026-03-25 14:30)
  Task: Implement OAuth2 login flow
  Findings: 3 recorded
  Decisions: 1 recorded
  Files touched: auth.ts, login.ts, middleware.ts
  (~400 tokens vs ~50K cold start)

LITM-Aware Positioning

Session state is positioned using attention-aware placement based on Liu et al., 2023: task and findings go to the beginning of the context window (high primacy attention), while the lossy middle zone carries only compressed metadata.

Compaction Recovery (v2.20.0)

When the context window is compacted (common with long conversations), critical session state can be lost. snapshot builds a compact XML summary (~2KB) with priority tiers:

  • P1 (always included): Current task, touched files with cache state
  • P2: Decisions, findings, progress entries
  • P3: Test results, next steps
  • P4: Session statistics

The snapshot is automatically saved to ~/.lean-ctx/sessions/<id>_snapshot.txt. After compaction, use restore to reload the most recent snapshot and resume seamlessly.

ctx_session action=snapshot
→ Snapshot saved (1847 bytes) - ~/.lean-ctx/sessions/abc123_snapshot.txt

ctx_session action=restore
→ <session task="Implement OAuth2 login">
    <files>
      <f id="F1" path="auth.ts" lines="123" cached="true"/>
      <f id="F2" path="db.ts" lines="89" cached="true"/>
    </files>
    <decisions>
      <d>Use refresh tokens with 7-day expiry</d>
    </decisions>
  </session>

Storage

Sessions are stored as JSON in ~/.lean-ctx/sessions/. Each session captures: task description, findings, decisions, files touched with their cache state, and a timestamp for ordering.

Full reference →

ctx_compress

ctx_compress creates a compact snapshot of all files currently in the session cache. Use it as a memory checkpoint during long coding sessions - paste the output into a fresh chat to carry over project understanding at minimal token cost.

Параметры

ПараметрТипОбязательныйОписание
include_signaturesbooleanNoInclude top-5 function signatures per file (default: true)

Example

$ ctx_compress

CTX CHECKPOINT (12 files)

F1 auth.ts [123L]: λ+createUser(email:s,pwd:s)→User, λ+authenticate(email:s,pwd:s)→Session
F2 db.ts [89L]: §+Database, λ+query(sql:s)→R, λ+migrate()→∅
F3 routes.ts [234L]: λ+setupRoutes(app:Express), λ+authMiddleware(req,res,next)
F4 config.ts [45L]: ν+DB_URL:s, ν+JWT_SECRET:s
...

STATS: 34 reads, 22 hits (65%)
COMPRESSION: 28450 → 890 tok
[27560 tok saved (97%)]

Token Savings

Typical savings are 90-99%. A 12-file project context that normally takes ~28,000 tokens can be represented in under 900 tokens.

Auto-Checkpoint

LeanCTX can automatically generate checkpoints after every N tool calls. Configure with the LEAN_CTX_CHECKPOINT_INTERVAL environment variable:

# Auto-checkpoint every 15 tool calls (default: 15)
LEAN_CTX_CHECKPOINT_INTERVAL=15

# Disable auto-checkpoints
LEAN_CTX_CHECKPOINT_INTERVAL=0
Full reference →

ctx_analyze

ctx_analyze performs deep information-theoretic analysis on a file using Shannon entropy and Jaccard similarity. It tells you exactly how much real information the file contains and recommends the best compression strategy.

Параметры

ПараметрТипОбязательныйОписание
pathstringYesPath to the file to analyze

Example

$ ctx_analyze middleware.ts

ANALYSIS: middleware.ts (78L, 1856 tok)

Entropy Distribution:
  H̄ = 3.2 bits/char
  Low-entropy (H<2.0): 14 lines (18%)
  High-entropy (H>4.0): 22 lines (28%)

Strategy Comparison:
  raw                      1856 tok  -
  aggressive               1420 tok  -23%
  signatures (tdd)          312 tok  -83%
  entropy                   298 tok  -84%
  aggressive + §MAP        1380 tok  -26%
  cache hit                  13 tok  -99%

Recommendation: signatures (best first-read savings)
Full reference →

ctx_benchmark

ctx_benchmark measures real token counts using tiktoken (o200k_base - the same tokenizer used by GPT-4 and Claude). It supports two modes: single-file benchmarks and project-wide scans.

Project Benchmark (v2.7.0)

Scans your project directory, selects up to 50 representative files across all languages, and measures every compression mode with real data.

CLI Usage

# Terminal output (ANSI)
lean-ctx benchmark run [path]

# Machine-readable JSON
lean-ctx benchmark run [path] --json

# Shareable Markdown report
lean-ctx benchmark report [path]

Tool Usage

ctx_benchmark path="." action="project" format="terminal"
ctx_benchmark path="." action="project" format="markdown"
ctx_benchmark path="." action="project" format="json"

Example Output

══════════════════════════════════════════════════════════════
  lean-ctx Benchmark - .
══════════════════════════════════════════════════════════════
  Scanned: 50 files (10 ts, 10 rs, 8 py, 6 go, ...)
  Total raw tokens: 145.2K

  Mode Performance:
  Mode               Tokens    Savings    Latency    Quality
  ──────────────────────────────────────────────────────────
  map                  7.5K      98.5%      2.3ms      93.4%
  signatures           9.3K      98.2%      2.1ms      96.3%
  aggressive         130.1K      10.4%       81μs     100.0%
  entropy            108.3K      25.4%     26.0ms     100.0%
  cache_hit             650      99.6%        0μs        N/A

  Session Simulation (30-min coding):
  Approach                     Tokens       Cost    Savings
  ──────────────────────────────────────────────────────────
  Raw (no compression)         290.4K     $0.726          -
  lean-ctx (no CCP)             38.2K     $0.096      86.8%
  lean-ctx + CCP                12.4K     $0.031      95.7%
══════════════════════════════════════════════════════════════

Single-File Benchmark

Benchmarks a single file against all compression strategies with exact token counts.

Parameters

ПараметрТипОбязательныйОписание
pathstringYesFile path (single file) or directory (project mode)
actionstringNofile (default) or project
formatstringNoterminal (default), markdown, or json (project mode only)

Example (Single File)

ctx_benchmark auth.ts

Benchmark: auth.ts (123L)

Strategy                     Tokens   Savings
──────────────────────────────────────────────
raw                             915  -
aggressive                      412  -503 (55%)
signatures (compact)            121  -794 (87%)
signatures (tdd)                 98  -817 (89%)
entropy                         348  -567 (62%)
cache hit                        13  -902 (99%)
──────────────────────────────────────────────
Best: "cache hit" saves 902 tokens (99%)
Full reference →

ctx_metrics

ctx_metrics displays comprehensive session statistics including token savings, USD cost estimates, per-tool and per-mode breakdowns, and file reference mappings.

Параметры

No parameters. Returns current session statistics.

Example Output

ctx_metrics

LeanCTX session metrics
══════════════════════════════════════════════════
Files tracked: 12 | Reads: 34 | Cache hits: 22 (65%)
Input tokens:  28.5K original → 4.1K sent | 24.3K saved (85.5%)
Cost estimate: $0.0713 without → $0.0103 with lean-ctx | $0.0610 saved

By Tool:
Tool           Calls  Original     Saved   Avg%
──────────────────────────────────────────────────
ctx_read          18     22.4K    19.2K    91%
ctx_shell          8      4.8K     3.1K    74%
ctx_tree           4      1.8K     1.2K    40%

By Mode:
Mode           Calls     Saved
──────────────────────────────
map                6    12.1K
signatures         4     5.2K
full               8     1.9K

File Refs:
  F1=auth.ts [123L 915t reads:5]
  F2=db.ts [89L 412t reads:3]

Projected session savings (incl. thinking): $0.085
Full reference →

ctx_wrapped

Generates a savings report card showing tokens saved, cost avoided, top commands, and cache efficiency over a time period.

Параметры

  • period (optional) - week (default), month, or all

Example

ctx_wrapped period=week

╔══════════════════════════════════════════╗
║         lean-ctx WRAPPED 2026           ║
╠══════════════════════════════════════════╣
║  24.3K tokens saved      $0.06 avoided  ║
║  12 sessions              47 commands   ║
║                                         ║
║  Top Commands:                          ║
║    ctx_read ▓▓▓▓▓▓▓▓▓▓▓ 18             ║
║    git      ▓▓▓▓▓▓▓ 12                 ║
║    ctx_shell ▓▓▓▓▓ 8                   ║
║                                         ║
║  Cache Hit Rate: 65%                    ║
╚══════════════════════════════════════════╝
Full reference →

ctx_cache

ctx_cache gives you explicit control over LeanCTX's in-memory session cache. Use it when the LLM's context no longer matches what the server has cached - for example after context compaction, session resets, or when running as a subagent.

Параметры

ПараметрТипОбязательныйОписание
actionstringYesstatus, clear, or invalidate
pathstringOnly for invalidateFile path to remove from cache

Actions

status

Lists all files currently in the session cache with line counts, token counts, and read counts.

ctx_cache action=status

Cache: 3 file(s)
  F1=auth.ts [123L, 915t, read 4x]
  F2=db.ts [89L, 678t, read 2x]
  F3=routes.ts [234L, 1856t, read 1x]

clear

Removes all entries from the session cache. The next ctx_read call for any file will return full content.

ctx_cache action=clear

Cache cleared - 3 file(s) removed. Next ctx_read will return full content.

invalidate

Removes a single file from the cache. Useful when you know a specific file has changed externally.

ctx_cache action=invalidate path=/src/auth.ts

Invalidated cache for auth.ts. Next ctx_read will return full content.

Automatic Cache Expiry (Idle TTL)

Since v1.5.4, the cache auto-clears after 5 minutes of inactivity. This is a server-side safety net that handles new chats, context compaction, and session resets without relying on the LLM. Configure via the LEAN_CTX_CACHE_TTL environment variable (seconds, 0 to disable).

Full reference →

ctx_heatmap - File Access Heatmap

Tracks and displays file access patterns across sessions. Shows which files are accessed most frequently, their average compression ratios, and access patterns over time. Helps identify hot files that could benefit from pre-loading or different compression strategies.

Параметры

  • action (optional) - status (default), directory (per-dir breakdown), dirs (top directories), cold (least-accessed files), or json (raw data)
  • path (optional) - filter to a specific directory

Example

ctx_heatmap
→ FILE ACCESS HEATMAP

  HOT FILES (top 10):
    src/auth.ts          ████████████ 24 reads  avg 87% compression
    src/routes.ts        ██████████   18 reads  avg 91% compression
    src/middleware.ts     ████████     14 reads  avg 82% compression
    src/db.ts            ██████       10 reads  avg 94% compression

  COLD FILES (accessed once):
    src/config.ts, src/types.ts, src/utils.ts

  Total: 142 accesses across 23 files

Storage

Heatmap data is stored at ~/.lean-ctx/heatmap.json and persists across sessions.

Full reference →

ctx_gain - Token Savings Report

Reports token savings for the current session or across all sessions. Shows per-tool breakdowns, estimated cost savings, and compression effectiveness. Also available via CLI: lean-ctx gain.

Параметры

  • action (optional) - report (default), score (CEP score), live (real-time), json (machine-readable), reset
  • period (optional) - time range: session (default), day, week, month, all
  • model (optional) - pricing model for cost estimates (default: claude-sonnet)

Example

ctx_gain
→ TOKEN SAVINGS REPORT (session)
  Total input:     234,500 tokens
  After lean-ctx:   28,140 tokens
  Saved:           206,360 tokens (88%)
  Est. cost saved: $0.62

  By mechanism:
    Read caching:    112,400 tok (54%)
    Shell compress:   58,200 tok (28%)
    Deduplication:    35,760 tok (17%)
Full reference →

ctx_artifacts v3.4.5

ctx_artifacts manages the context artifact registry with BM25 indexing. Artifacts include proofs, packs, and bundles generated during sessions.

ParamTypeReqDescription
actionstringYeslist, status, index, reindex, search, remove
querystringNoSearch query (for action=search)

ctx_verify v3.4.5

ctx_verify returns a verification observability snapshot - versioned JSON or compact summary of verifier stats, warnings, and SLO compliance.

ParamTypeReqDescription
actionstringNostats (default) - returns versioned verification snapshot