Documentation

Changelog

lean-ctx version history - new features, improvements, and bug fixes for every release.

Complete version history for lean-ctx. Each release includes new features, improvements, and bug fixes. lean-ctx follows semantic versioning.

3.6.12 (2026-05-20)

Context Cortex architecture, config-based data source providers, shell hook fix, Windows updater fix.

Added

  • Context Cortex — Multi-source intelligence layer connecting code, issues, and external APIs. BM25 indexing, cross-source edge detection, saliency ranking, and active inference prefetching. Read more.
  • Config-based data source providers — Connect any REST API by dropping a .toml or .json file into ~/.config/lean-ctx/providers/. Supports Bearer, API-Key, Basic, Header, and no-auth methods. JSON response extraction via dot-notation paths. Read more.
  • Built-in GitHub, Jira, PostgreSQL providers — Activate with environment variables. Your AI agent can query issues, tickets, and database schemas through ctx_provider.
  • ctx_call meta-tool — Invoke any of 62 registered tools by name through a single dispatch interface.
  • Cross-source hints in ctx_read — When reading a file, the Cortex appends related context from providers (e.g., relevant GitHub issues or Jira tickets).
  • Provider Bandit (Thompson sampling) — Automatically deprioritizes noisy providers and promotes ones that consistently deliver relevant context.
  • Active inference in ctx_preload — Predicts what context you'll need next based on recent tool call patterns and prefetches in the background.

Fixed

  • _lc: command not found in non-interactive subshells (#255) — Passthrough stubs for _lc and _lc_compress defined in .zshenv/.bashenv before the exec guard. Also added to env.sh for container scenarios.
  • Windows update hangs with locked binary (#254) — Pre-update process stop, blocking PID visibility, 60s timeout with progress indicators, and manual recovery instructions.

Security

  • MCP config credential protection.vscode/mcp.json and .github/mcp.json added to .gitignore to prevent accidental credential commits.
  • GitHub provider hardened — Parses GITHUB_REPOSITORY=owner/repo format correctly; improved remote fallback logic.

3.6.11 (2026-05-20)

Critical Linux restart loop fix, Windows hang prevention, manifest SSOT, performance hardening.

Fixed

  • Linux proxy restart loop (11258+ restarts) — When the binary is replaced during runtime, Linux marks /proc/self/exe with (deleted) suffix. The systemd unit generator wrote this corrupted path into ExecStart, causing (deleted) to appear as a CLI argument on every restart. Now uses resolve_portable_binary() which strips the suffix. CLI dispatch also defensively removes (deleted) from args for existing units.
  • Windows ctx_read hangs — Session lock acquire and path canonicalization now have bounded timeouts (5s for RwLock, 2s for canonicalize()) preventing indefinite hangs on Windows reparse points and network paths.
  • Manifest generator uses stale tool_defsgen_mcp_manifest now reads from ToolRegistry (61 tools) instead of static granular_tool_defs() (56 tools).

Changed

  • Context budget auto-escalationpressure_downgrade() applies more aggressive mode downgrades based on ContextPressure.
  • Cache-stable LITM output — Dynamic session statistics moved from output prefix to suffix for LLM prefix-caching compatibility.
  • ToolRegistry as SSOT for list_tools — Eliminates schema drift between exposed schemas and handler implementations.
  • OnceLock for project rootfind_project_root() cached via std::sync::OnceLock, eliminating repeated git rev-parse calls.
  • Compaction sync tail-seek — Reads only the last 4KB of context_radar.jsonl instead of the entire file.

Removed

  • Dead code cleanup: removed unused functions, #[allow(dead_code)] attributes replaced with _ prefixes across 8 files.

3.6.10 (2026-05-20)

Critical performance fix for knowledge recall, start_line no-op, git write-command safety.

Fixed

  • Knowledge recall blocks all agents for 58s — Embedding engine loading no longer blocks recall. Non-blocking try_shared_engine() used for auto/hybrid mode; retrieval signal persistence moved to background thread.
  • start_line=1 forces unnecessary disk re-reads (#253) — Clients that always send start_line=1 no longer trigger mode override. Now correctly treated as a no-op.
  • Git write-commands incorrectly compressedgit commit, git push, git pull, git merge, git rebase, git cherry-pick, git tag, git reset are now classified as verbatim (zero compression).
  • PowerShell command wrapping — Single full-command strings no longer incorrectly wrapped in & '...' quotes on PowerShell.
  • Terse dictionary safety — Removed git subcommand abbreviations (commit→cmt, branch→br, etc.) from the GIT dictionary to prevent output corruption.

3.6.9 (2026-05-19)

Workflow staleness auto-clear, cache message fix, Context IR hot-path, plugin-ready traits, pytest compression.

Added

  • Context IR hot-path lineage — Every tool call now records source kind, tokens, duration, and content excerpt into the Context Intermediate Representation for full lineage tracking.
  • Plugin-ready traits — Extracted CompressionPattern trait and ContextProvider trait for future plugin extensibility.
  • Pytest verbose compression — Dedicated pattern for pytest -v output: consolidates per-test lines, strips fixtures/collection/metadata, preserves tracebacks and test identifiers.
  • Active Context Gate — Pressure-based auto-downgrade: when context utilization exceeds 75%, reads are automatically downgraded (full→map, map→signatures).

Fixed

  • Workflow persistence blocking reads after crash — Workflows inactive >30 minutes are now auto-expired. Read-only tools (ctx_read, ctx_multi_read, ctx_smart_read, ctx_search, ctx_tree) always pass through the workflow gate regardless of state.
  • Misleading cache-hit message — Changed "Already in your context window" to neutral [unchanged, use cached context] with hint about fresh=true for forced re-read.
  • Unable to clear context pressure (#244)ctx_ledger(action=reset) now correctly clears all ledger state.
  • Flaky CI tests — Serialized environment-variable tests, fixed anomaly persistence debounce race, relaxed stress thresholds for shared runners.

3.6.8 (2026-05-18)

Post-RRF reranking pipeline, BM25 path enrichment, find_related search, workflow done-state fix.

Added

  • Post-RRF Reranking Pipeline — 5 scientifically-grounded signals: Query-Type Classifier, Definition Boost, File Coherence Boost, Noise Penalties, MMR Diversity.
  • BM25 Path-Enrichment — File stem and parent directory doubled into BM25 content for path-aware queries.
  • find_related action in ctx_semantic_search — Chunk-based similarity search given a file path + line.

Fixed

  • Workflow "done" state blocks all tools permanentlyhandle_complete now clears the workflow file. Gate auto-clears stale "done" workflows.
  • ctx_read lines:N-M mode hangs on large files — Line-range reads no longer trigger expensive hint computations.

3.6.7 (2026-05-18)

Model registry, PathJail container bypass, ctx_shell env forwarding, Copilot CLI support, benchmark honesty fixes.

Added

  • 3-Layer Model Registry — Data-driven model context window registry replaces hardcoded substring matching. Supports bundled defaults, auto-updated local registry, and user overrides via [model_context_windows] in config.toml. Covers 40+ models including GPT-5.5, GPT-4.1, Gemini, Claude.
  • ctx_shell env parameter — New optional object parameter lets agents explicitly pass environment variables to shell commands. Auto-forwards CODEX_*, CLAUDE_*, OPENCODE_*, HERMES_* from the MCP server process.
  • PathJail container bypass — Auto-disables in Docker/Podman containers. Manual opt-out via path_jail = false in config.toml or LEAN_CTX_NO_JAIL=1.
  • Copilot CLI support — Separate CopilotCli config type writes to ~/.copilot/mcp-config.json with correct format (mcpServers, "type": "local", "tools": ["*"]).

Fixed

  • Benchmark honesty — Structural modes (map, signatures) excluded from "best mode" for non-code files. Previous reports showed misleading 100% savings for JSON; corrected to accurate values.
  • Copilot CLI config path — Now writes to ~/.copilot/mcp-config.json instead of VS Code's Application Support path.
  • PathJail CWD fallback — Guarded fallback with unsafe-root protection and differentiated error messages.
  • Invalid JSON config handling — Text-based injection preserves invalid files instead of destructive overwrite.

Changed

  • VS Code / Copilot split — Two separate targets: "VS Code" and "Copilot CLI" with distinct config paths and formats.

3.6.6 (2026-05-17)

ABC-inspired agent hardening, bypass detection, strict enforcement mode, knowledge export, and git compression fix.

Added

  • Bypass Hints — Detects when agents use native Read/Grep instead of lean-ctx tools and emits a reminder. Configurable via bypass_hints config or LEAN_CTX_BYPASS_HINTS env (modes: gentle, firm, off).
  • Tool Description Enhancement — All core tool descriptions now explicitly state "replaces native X" to guide AI agents directly from the MCP schema.
  • Rules Deduplication — Removed redundant tool mapping tables from injected rules. Tool descriptions carry the mapping; rules focus on mode selection and anti-patterns.
  • lean-ctx harden — Activates strict enforcement mode (LEAN_CTX_HARDEN=1 in MCP configs). Optionally denies Bash in Claude Code's permissions.deny.
  • lean-ctx export-rules — Exports high-confidence knowledge facts as editor-native rules (MDC for Cursor, AGENTS.md, CLAUDE.md).

Fixed

  • git status --porcelain truncation — Shell compression no longer truncates git status output when it doesn't match section parsing. Developers always see full status.
  • init --agent rules injection — Global rules and skill file now correctly injected. Fixed data dir split causing empty gain field. (#238, #239)

3.6.5 (2026-05-17)

Bug fixes for CLAUDE_CONFIG_DIR, OpenCode rules location, Linux CI warnings, and MCP resource notifications.

Fixed

  • CLAUDE_CONFIG_DIR support — MCP instructions and rules file paths now respect CLAUDE_CONFIG_DIR env var instead of hardcoding ~/.claude. (#235)
  • OpenCode rules location — Rules written to ~/.config/opencode/AGENTS.md instead of path OpenCode never loads. (#237)
  • Linux CI warnings — Fixed unreachable_pub, borrow_as_ptr, unnecessary_wraps, and unused_variables for platform-gated items.
  • MCP Resource Notificationsnotifications/resources/updated sent to subscribed clients after ledger changes.
  • ctx_load_tools — New tool for explicit category management with notifications/tools/list_changed support.

3.6.4 (2026-05-17)

Hebbian knowledge enhancement, auto-update UX, agent runtime hardening, multi-agent production features, governance & compliance, and full OWASP Agentic Top 10 alignment.

Agent Runtime Hardening

  • Capability-based tool access control — Fine-grained permissions per agent with declarative capability ACLs. Agents can only invoke tools they are explicitly granted access to.
  • OS-level sandboxing — macOS Seatbelt and Linux Landlock integration at sandbox_level=1. Agent file system and network access is restricted at the kernel level.
  • SHA-256 chained audit trail — Append-only JSONL audit log with hash-chained entries. Every tool call, policy decision, and agent action is cryptographically linked.
  • Secret detection — 8+ regex patterns detect secrets (API keys, tokens, passwords) in tool inputs/outputs with optional redaction.
  • Shell allowlist modectx_shell can be restricted to a configurable set of allowed commands, blocking all others.
  • Auto-reroot protectionallow_auto_reroot=false by default prevents agents from escaping their project root.

Multi-Agent Production

  • Per-agent context ledger isolation — Each agent gets its own isolated context ledger, preventing cross-agent data leakage in multi-agent setups.
  • Agent token budgets — Configurable per-agent token limits with enforcement. Budget overruns are logged and can trigger policy actions.
  • Remote Agent Bus — HTTP-based agent registration with heartbeat monitoring and SSE event streaming for distributed multi-agent orchestration.
  • Signed handoff bundles — Agent-to-agent handoffs are signed with Ed25519, ensuring bundle integrity and provenance.

Governance & Compliance

  • Enhanced policy engine — Declarative rules with agent, content, and time-based conditions. Policies can allow, deny, or require approval for specific operations.
  • Compliance reports via lean-ctx audit — Generate compliance reports from the audit trail. Supports filtering by time range, agent, and event type.
  • OWASP Agentic Top 10 alignment — 8 out of 10 categories have full coverage: Prompt Injection, Tool Misuse, Excessive Agency, Insecure Output, SSRF, Over-Reliance, Data Exfiltration, and Insufficient Logging.

Security Hardening

  • PathJail expanded — 16 path-typed argument keys are now validated and jailed, preventing path traversal in all tool parameters.
  • TOCTOU fixO_NOFOLLOW on Unix prevents symlink race conditions during file operations.
  • Atomic writes for all JSON stores — Crash-safe writes for config, sessions, knowledge base, and audit trail.
  • Timing-safe authentication — All token and password comparisons use constant-time algorithms.
  • Proxy header allowlist — Only explicitly allowed headers are forwarded through the LLM proxy.
  • FILE_LOCKS LRU eviction — Prevents unbounded memory growth from accumulated file locks.
  • Tool execution timeout — 120-second hard timeout for all tool executions, preventing runaway operations.
  • TaskStore advisory file locks — Concurrent access to task stores is serialized via advisory locks.

MCP Alignment

  • MCP Server Card.well-known/mcp-server.json discovery endpoint for standardized server metadata.
  • Reference results for large outputs — Tool responses exceeding size thresholds return references instead of inline data.
  • Context gateway metrics — New metrics endpoint for monitoring context gateway throughput and latency.
  • Dashboard audit events endpoint/api/audit exposes audit trail events for the web dashboard.

Hebbian Knowledge Enhancement

  • Cognition Loop — 8-step background knowledge reorganization: seed promote, structural repair, fidelity check, lateral synthesis, contradiction resolution, Hebbian strengthening, decay, and compaction.
  • Knowledge Archetypes — 10 typed node categories (Architecture, Decision, Gotcha, Convention, Dependency, Pattern, Workflow, Preference, Observation, Fact) with salience-based ranking.
  • Fidelity Scoring — Two-tier quality metric (structural + semantic) influencing recall ranking.
  • Hebbian Edge Strengthening — Co-retrieved facts strengthen edges via saturating formula; exponential decay + pruning keep the graph lean.
  • Cross-Agent Knowledge Bridge — Controlled sharing of high-confidence facts between agents with provenance tracking and trust penalties.

Auto-Update UX

  • lean-ctx update --schedule — OS-native schedulers (macOS LaunchAgent, Linux systemd/cron, Windows Task Scheduler). Default OFF, explicit opt-in required.
  • Setup opt-in — Interactive setup asks about auto-updates (Step 9/11). Always changeable via CLI or config.
  • --quiet flag — Suppress output when already current (for background schedulers).
  • Session notifications — One-shot per-session update hint when a newer version is available.
  • [updates] config — New config section with auto_update, check_interval_hours, notify_only with env var overrides.

3.5.25 (May 2026)

Current stable release — CPU hotspot fixes, canonical rules policy, full registry migration.

Added

  • Process concurrency guard — Limits concurrent lean-ctx processes to 4 via flock slot locks, preventing CPU saturation when multiple agents trigger simultaneous operations.
  • Terse pipeline input cap & timeout — Skips inputs >64KB and enforces a 500ms deadline, preventing runaway CPU on large outputs (#210).
  • Canonical rules policy — New rules_canonical.rs module provides a single source of truth for all rule generation (MUST USE / NEVER USE tables) across Hybrid and MCP modes.
  • Contract tests for rules consistency — 11 cross-IDE contract tests verify generated rules contain correct MUST/NEVER language with no contradictions.
  • Property-based compression testsproptest invariant tests for safeguard_ratio, entropy_compress, and compress_output.
  • MCP JSON instructions field — Editor MCP configs now include tool policy instructions where clients support it.

Changed

  • Rules language strengthened — All rule templates now use CRITICAL: ALWAYS, MUST USE, and NEVER USE instead of PREFER.
  • Background index throttled — Index builds run with nice -n 19 and ionice -c 3 to prevent CPU contention during setup.
  • Dictionary and quality gate optimized — Case-insensitive early-exit in apply_dictionaries, HashSet lookup in quality gate, identifier cap at 200.
  • Entropy compression safeguard — Falls back to original content when compression would inflate token count.

Fixed

  • 100% CPU on terse with large inputs (#210) — Combination of input cap, timeout budget, trigram cap, and process guard eliminates all known CPU hotspot scenarios.
  • env.sh self-heal loop — Container self-heal now includes 60-second cooldown and PID-lock check (max 4 concurrent).

3.5.24 (May 2026)

Unified Hybrid mode, CliRedirect elimination, LEAN_CTX_QUIET production mode.

Changed

  • Eliminate CliRedirect hook mode — All agents now use Hybrid (MCP for reads/search + shell hooks for command compression) or Mcp only. Cursor, Gemini CLI, and 18 more agents get automatic MCP installation with cached reads.
  • All agents default to Hybridrecommend_hook_mode() returns Hybrid for all agents with shell access. MCP reads + shell compression = best of both worlds.
  • Cursor: automatic MCP installationlean-ctx init --agent cursor and lean-ctx setup now install the MCP server config automatically.
  • Hybrid rules template v2 — Updated rule templates to clearly instruct ctx_read + ctx_search (MCP) for reads/search, lean-ctx -c (CLI) for shell.

Added

  • LEAN_CTX_QUIET=1 production mode — Suppresses all informational output: savings footers, session-start messages, tee-log hints. Shell compression still runs — only annotations are hidden.
  • Redirect subprocess timeout increased — Hook redirect timeout increased from 3s to 10s for reliable operation on slow filesystems.

Removed

  • HookMode::CliRedirect — Enum variant, CLI_REDIRECT_RULES constant, build_cli_redirect_instructions(), and the lean-ctx-cli-redirect.mdc template.
  • DedicatedCliRedirect / CursorMdcCliRedirect — Rules injection variants removed.

Fixed

  • Cursor reads/search not using MCP — CliRedirect mode prevented MCP installation. Now all rule files consistently instruct Hybrid mode.
  • Inconsistent rule files.cursorrules, AGENTS.md, and .mdc templates now all instruct Hybrid mode.
  • macOS CI: rustup-init in PATH — Added explicit rustup default stable step to ensure toolchain is active.

3.5.23 (May 2026)

RAM Guardian with jemalloc, zstd cache compression, configurable savings footer suppression.

Added

  • RAM Guardian — adaptive memory management — RSS-based memory monitoring with adaptive tiered eviction. Uses jemalloc as global allocator on Unix for aggressive memory return. Configurable via max_ram_percent (default 5%). New /api/memory dashboard endpoint and lean-ctx doctor diagnostics.
  • zstd-compressed session cache — Cache entries now stored as zstd-compressed data, reducing in-memory footprint by ~60–80%.
  • Configurable savings footer suppression — New savings_footer config option (auto / always / never) and LEAN_CTX_SAVINGS_FOOTER env var. In auto mode (default), token savings footers are shown in CLI but suppressed in MCP/agent context.
  • Memory estimation and unload for indexes — BM25 and embedding indexes expose memory usage and can be unloaded by the RAM Guardian under pressure.

Fixed

  • CLI savings footer bypass — CLI footer formatting now delegates to the central format_savings() function, respecting the savings_footer configuration.
  • Daemon-delegated output footer leakage — Client-side filtering ensures footers are stripped when LEAN_CTX_SAVINGS_FOOTER=never, even when output comes from the daemon.
  • Shared session store cap — Reduced from 64 to 8 cached sessions to prevent unbounded memory growth.

3.5.22 (May 2026)

Native Windows daemon, IPC abstraction, overlay/FUSE read fix, CPU hotfix, dashboard improvements.

Fixed

  • Read: overlay/FUSE stat() raceread_file_lossy now opens the file first and uses fstat() on the file descriptor instead of a separate stat() syscall. Fixes sporadic "No such file or directory" errors in Docker overlay/FUSE filesystems (e.g. Codex sandboxes). Adds a single retry with 50ms backoff on NotFound.
  • 100% CPU after lean-ctx setup on Ubuntu — Two root causes: (1) env.sh self-heal script could recursively spawn lean-ctx init via BASH_ENV. Now guarded with container detection, recursion guard, and LEAN_CTX_ACTIVE propagation. (2) Graph index scanning could scan entire $HOME. Now guarded with is_safe_scan_root(), cross-process lock, 50k entry limit, and 2-minute timeout. LEAN_CTX_NO_INDEX env var skips indexing entirely. (#210)
  • Daemon modules now platform-independent — Removed all #[cfg(unix)] gates from daemon modules. daemon_client.rs auto-start works on all platforms.
  • Dashboard call graph timeout — Increased from 15s/30s to 60s for larger projects during initial build.

Added

  • Native Windows daemon support — IPC abstraction layer — New ipc/ module provides platform-independent daemon transport. Unix uses UDS (unchanged), Windows uses Named Pipes (\\.\pipe\lean-ctx-{hash}). All OS-specific code isolated in ipc/unix.rs and ipc/windows.rs. (#209)
  • HTTP-based daemon shutdown — New POST /v1/shutdown endpoint for cross-platform graceful shutdown. Falls back to SIGTERM/TerminateProcess, then force kill.
  • Parallel call graph build with progress trackingCallGraph::build_parallel() uses rayon for concurrent file analysis with live progress. Dashboard polls via /api/call-graph/status.
  • Dashboard: call graph progress bar — Live progress bar during call graph builds with auto-polling every 2s.
  • Dashboard: project file browser in Compression Lab — Two tabs: "Recent" and "Project" (all indexed files). Includes search, file count, and token count per file.

Changed

  • serve_uds() replaced by serve_ipc() — Takes a DaemonAddr enum instead of a PathBuf.
  • daemon_socket_path() removed — Replaced by daemon::daemon_addr() returning a DaemonAddr enum.

3.5.21 (May 2026)

Graph data directory fix, graph index UX, config schema validation, dashboard expandable events.

Fixed

  • graph.db and graph.meta.json now honor LEAN_CTX_DATA_DIR — Property graph files stored in $DATA_DIR/graphs/<project_hash>/. Transparent migration moves existing files from <project>/.lean-ctx/ on first access. (#205)
  • Graph index UX: correct labels and configurable caplean-ctx gain shows "files" instead of "nodes". New config key graph_index_max_files (default: 5000). (#206)
  • Config documentation accuracy — Removed phantom sections and corrected wrong defaults across website docs. (#208)

Added

  • Dashboard expandable event details — Event cards in the Live Observatory are now clickable with accordion pattern and lazy-loaded full metrics. (#207)
  • lean-ctx config schema — Outputs complete JSON schema of all configuration keys.
  • lean-ctx config validate — Validates config.toml against the schema with "did you mean?" suggestions.

3.5.20 (May 2026)

Codex installer fixes, Windows path normalization, and CLI flag validation.

Fixed

  • Codex installer respects CODEX_HOMElean-ctx init --agent codex now reads the CODEX_HOME environment variable. All Codex config files are written to $CODEX_HOME instead of always using ~/.codex. (#202)
  • Codex feature flag migrated to hooks — The installer now writes hooks = true instead of the deprecated codex_hooks = true. Existing entries are auto-migrated. (#203)
  • lean-ctx ls rejects unsupported flags — Flags like -la, -l, -R now return a clear error with usage hints. Supported: --all/-a, --depth N. The shell hook continues passing ls flags to the system ls. (#201)
  • Windows path format for inline rewriteshandle_rewrite_inline() returns native OS paths on Windows instead of MSYS format (/c/Users/...). New from_bash_to_native_path() function provides symmetrical conversion. (#204)

Added

  • Path normalization tests — 11 new normalize_tool_path() tests, 6 new from_bash_to_native_path() tests including Windows/Unix roundtrips.

3.5.19 (May 2026)

Shell hook drop-in install, output policy classification, dashboard audit, and agent-aware non-interactive tracking.

Added

  • Shell hook drop-in install — Users with .d/-style dotfiles (chezmoi, yadm, stow, oh-my-zsh custom/) now get hook fragments installed as numbered drop-in files (e.g. ~/.zshenv.d/00-lean-ctx.zsh) instead of inline fenced blocks. Detection is automatic (Style::Auto); override with --style=inline or --style=dropin. Transparent migration between styles preserves hand-edits via timestamped backups.
  • Output policy classification — New OutputPolicy enum (Passthrough, Verbatim, Compressible) provides centralized command classification for the compression pipeline. Commands like gh api, az login, docker ps, kubectl get pods are now correctly classified and never compressed.

Fixed

  • Dashboard: 7 frontend data mismatch bugs — Complete attribute-by-attribute audit of all 17 dashboard pages. Fixed field name mismatches, falsy checks hiding zero values, incorrect API field mapping in Overview, Health, Agents, Memory, Live, Compression Lab, and Graph components.
  • Token Pressure accuracy — Context field temperature now uses pressure.utilization (weighted decay) instead of raw ratio for consistency with the Token Pressure card.
  • Truncation bug (#199) — Removed aggressive 8000-byte fallback truncation that caused AI models to retry commands. Large outputs now flow through the safety-aware compress_if_beneficial pipeline.
  • Shell hook: ls and find added — Both commands are now included in the generated shell hook alias list, so directory listings are tracked and compressed. (#200)
  • Shell hook: agent-aware TTY bypass — The TTY guard ([ ! -t 1 ]) now checks for agent environment variables (LEAN_CTX_AGENT, CODEX_CLI_SESSION, CLAUDECODE, GEMINI_SESSION). Non-interactive agent commands in Docker/Codex are now tracked. (#200)

3.5.18 (May 2026)

Fixed

  • gh api output no longer compressed — Commands like gh api repos/.../actions/jobs/.../logs are now passthrough (no compression, no truncation). Previously, large API responses were silently truncated by the generic 8000-byte fallback.

3.5.17 (May 2026)

Security

  • [Critical] LLM Proxy bearer token auth — The proxy server now supports optional bearer token authentication via LEAN_CTX_PROXY_TOKEN.
  • [Critical] Symlink hijack protectionwrite_atomic() and context package atomic_write() now reject writes through symlinks.
  • [High] Claude binary path validationclaude mcp add-json validates that the resolved claude binary comes from a trusted directory.
  • [High] TOCTOU mitigation — New write_atomic_with_backup_checked() validates file mtime between read and write.
  • [High] Auto-approve transparencylean-ctx setup now displays a banner listing all auto-approved MCP tools. New --no-auto-approve flag.
  • [High] Full integrity verificationverify_integrity() now validates content_hash, sha256, and byte_size.

3.5.16 (May 2026)

Major security hardening, structural output protection, and context runtime research modules.

Security (32 fixes)

  • [Critical] Path traversal fixes - tee show and dashboard compression-demo no longer accept path separators or ..
  • [Critical] Injection prevention - ctx_execute intent parameter sanitized to alphanumeric only; CSPRNG failures now panic
  • [Critical] MCP stdio overflow guard - Content-Length headers validated with checked_add and size cap
  • [High] Dashboard auth hardened - loopback token exposure fixed, nonce-based CSP replaces unsafe-inline
  • [High] Data isolation - ctx_share scoped per project hash, ctx_execute output redacted, panic payloads no longer leaked
  • [High] Resource exhaustion - SSE subscriber cap enforced (64/channel), Rust sandbox environment isolated
  • [Medium] Crypto upgrade - Argon2id password hashing, SQLite busy_timeout, ReDoS mitigation for filter rules
  • [Medium] Error sanitization - A2A handoff, cloud server, and context summary errors no longer leak OS details

Fixed

  • Structural output protection - git diff, git show, git blame, git log -p, git stash show, diff, colordiff, icdiff, and delta output is no longer mangled by compression. Dedicated fast path preserves all +/- lines, hunk headers, and blame annotations verbatim.
  • Zsh completion fixcompinit sourcing in the shell hook no longer blocks interactive shells when completion dirs are missing. #193

Changed

  • Security hardening test strengthened — the security_resolve_path_guard test suite now covers additional traversal vectors (encoded slashes, null bytes, overlong UTF-8) and asserts stricter deny semantics for symlink-to-outside-project scenarios.

Added

  • 13 context runtime research modules - adaptive chunking (Rabin-Karp), attention placement, cognitive load estimation (Halstead), cyclomatic complexity, gamma cover sets, graph features, information bottleneck (Blahut-Arimoto), MDL selector, memory consolidation, progressive compression, SPLADE retrieval, structural diff, structural tokenizer (18 languages)
  • Louvain community detection O(m) - rewrote from O(n²) to edge-list-based with modularity optimization
  • Enhanced PageRank - configurable damping, convergence detection, seed biasing
  • SPLADE-enhanced BM25 - sparse expansion terms for improved recall
  • memory_cleanup config option - aggressive (default, 5 min TTL) or shared (30 min TTL) for multi-IDE setups
  • Shell activation mode — new shell_activation config option with three modes: always (default, all shells), agents-only (only when AI agent env vars detected), off (manual activation via lean-ctx-on). Override via LEAN_CTX_SHELL_ACTIVATION env var.
  • Explicit project identity (.lean-ctx-id) — new highest-priority identity marker file for Docker environments. Place a .lean-ctx-id file in your project root with a unique project name to prevent hash collisions when different projects share the same /workspace mount path.
  • Docker project isolation fix — graph index, semantic cache, bandit, and embedding index now use a composite project hash (path + identity) instead of path-only hash. Existing data is automatically migrated from old hash directories. No user action required.

3.5.15 (May 2026)

Critical bug fixes for dashboard auth and large file handling.

Fixed

  • Dashboard "unauthorized" on localhost - auto-injects auth token for loopback connections so the dashboard works without manual token setup
  • Large file crash / MCP hang - reading multi-GB files no longer causes unbounded memory allocation; 4-layer protection: binary detection, metadata check, stat guard, MCP error semantics

Added

  • Binary file detection - 100+ binary file extensions recognized with human-readable labels
  • Live Observatory help - every dashboard event now has an inline explanation with actionable guidance
  • memory_cleanup setting - aggressive (5 min idle TTL) or shared (30 min TTL) via config or LEAN_CTX_MEMORY_CLEANUP

3.5.14 (May 2026)

Performance overhaul and new analysis tools.

Performance

  • BLAKE3 hashing - 3x faster content hashing across all file operations
  • Tree-sitter query cache - repeated structural queries skip re-parsing
  • SQLite Property Graph optimization - faster graph traversal for architecture and impact analysis
  • Token cache upgrade - capacity increased from 256 to 2048 entries
  • Parallel indexing with rayon - multi-threaded project indexing
  • Compact JSON serialization - reduced wire size for MCP responses

Improved

  • Rules mode selection decision tree - improved heuristics for auto-selecting read modes (community contribution)
  • Flaky test fixes - stabilized intermittent CI failures

Added

  • core::hasher module - BLAKE3-based content hashing abstraction
  • core::community - Louvain clustering for dependency graph analysis
  • core::pagerank - PageRank scoring for file importance
  • core::smells - code smell detection engine
  • ctx_smells tool - code smell detection with graph-enriched scoring
  • 58 MCP tools (up from 57)

3.5.13 (May 2026)

Instruction file handling fix and formal verification expansion.

Fixed

  • Instruction files always delivered in full mode - SKILL.md, AGENTS.md, and RULES.md are no longer compressed, ensuring agent instructions are never mangled
  • Markdown files exempt from aggressive compression - prevents loss of formatting in documentation files
  • Windows Claude Code PowerShell compatibility - resolved shell detection issues when running under Claude Code on Windows

Added

  • is_instruction_file() API - programmatic check for instruction file detection
  • Lean4 formal proofs - Theorems 12-13 added to the formal verification suite
  • 7 regression tests - covering instruction file handling and compression exemptions

3.4.2 (April 2026)

Bug fixes for Unicode paths and Windows shell detection.

Fixed

  • Unicode SIGABRT in ctx_overview - directory path truncation used byte-index slicing which panicked on multi-byte UTF-8 characters (Chinese, Japanese, Korean, emoji paths). Replaced with char-boundary-safe truncation. #154
  • Windows shell detection in Git Bash / MSYS2 - find_real_shell() now checks MSYSTEM/MINGW_PREFIX env vars before PSModulePath, preventing incorrect PowerShell detection when running inside Git Bash. #156

Added

  • Shell hint in MCP instructions (Windows) - on Windows, instructions now include the detected shell type with explicit guidance, helping LLMs generate correct commands for the active shell environment
  • Shell mismatch hint in ctx_shell responses (Windows) - when a command fails and contains PowerShell cmdlets while the detected shell is POSIX, a correction hint is appended

3.4.1 (April 2026)

Performance & token optimization release.

Highlights

  • Up to 64% lower per-session token overhead - best-case overhead reduced from ~6,600 to ~2,400 tokens through lazy tools + minimal_overhead mode
  • Async I/O on hot paths - session saves and cost attribution no longer block tool responses, reducing latency for every tool call
  • New minimal_overhead mode - set minimal_overhead = true or LEAN_CTX_MINIMAL=1 to suppress auto-checkpoints, meta-strings, and session blocks in instructions. Ideal for Codex and cost-sensitive environments

Performance

  • Session.save() split into prepare_save() (CPU under lock) + write_to_disk() (background thread) - serialization stays fast, disk I/O no longer blocks responses
  • CostStore writes deferred to background via tokio::task::spawn_blocking
  • mcp-live.json writes debounced to every 5th tool call (80% fewer disk writes)
  • count_tokens called once per tool response instead of up to 4 times - cached result reused for hints, cost attribution, and logging
  • compress_output skipped entirely for Normal density (no string copy)
  • md5_hex_fast - 8x faster fingerprinting for large outputs (>16 KB) by hashing prefix + suffix + length

Token Savings

  • Auto-checkpoint injection disabled under minimal_overhead - eliminates the largest per-call token overhead source
  • Meta-strings (stale_note, savings_note, shell efficiency hints, archive hints) suppressed under minimal_overhead
  • Session/knowledge/gotcha blocks removed from MCP instructions under minimal_overhead

Bug Fixes

  • Fixed integer overflow crash in shell_efficiency_hint when output tokens exceeded input tokens (e.g. shell commands that expand output) - now uses saturating_sub
  • Synchronous save() restores retry counter on disk write failure, preserving auto-save retry behavior

3.4.0 (April 2026)

Highlights

  • Lazy tools now the default - only 9 core tools exposed by default instead of 46, reducing per-turn input overhead by ~80%. Use LEAN_CTX_FULL_TOOLS=1 to opt back in. ctx_discover_tools lets agents load additional tools on demand
  • XDG Base Directory compliance - new installs use $XDG_CONFIG_HOME/lean-ctx. Existing ~/.lean-ctx directories auto-detected
  • JSONC comment support - config writers now parse JSON with // and /* */ comments
  • Shell hook disable - --no-shell-hook flag, shell_hook_disabled = true config, LEAN_CTX_NO_HOOK=1 env var

3.3.3 (April 2026)

Highlights

  • Official release tag: lean-ctx 3.3.3 was marked as the stable build at time of release
  • Stability improvements across all MCP tools
  • Refined CEP v1 (Context Efficiency Protocol) instruction codes

Improvements

  • Improved CRP mode density - budget enforcement at ≤150 tokens per response
  • Enhanced ctx_knowledge with rooms, search, and wakeup actions
  • Better session resume flow with ctx_session resume action
  • Polished Observatory TUI dashboard layout

Bug Fixes

  • Fixed edge case where ctx_dedup could skip entries with identical hashes but different paths
  • Corrected cache-hit stub token count reporting in ctx_gain
  • Fixed ctx_tree depth parameter not respecting symlink boundaries

3.3.2 (March 2026)

Highlights

  • Composite project hash: New project_hash combines content hash, structure hash, and config hash into a single deterministic fingerprint for change detection
  • Codex hooks integration: Native hook support for OpenAI Codex CLI - PreToolCall, PostToolCall, and SessionStart events

New Features

  • project_hash - composite hash for CI caching and drift detection across branches
  • Codex hook scripts auto-installed via lean-ctx install --codex
  • ctx_knowledge action="timeline" - chronological view of knowledge base entries

Improvements

  • Faster ctx_preload with parallel file reads (up to 4x speedup on large projects)
  • Reduced memory footprint for sessions with 50+ cached files

Bug Fixes

  • Fixed project_hash inconsistency when .gitignore patterns changed between runs
  • Resolved Codex hook permission errors on Windows WSL environments

3.3.1 (February 2026)

Highlights

  • 85+ new passthrough entries: Massive expansion of the shell passthrough table - commands that are passed through uncompressed when compression would lose critical information

New Features

  • 85+ new passthrough patterns for debugging tools (strace, ltrace, perf), database CLIs (psql, mysql, redis-cli), and cloud CLIs (aws, gcloud, az)
  • ctx_shell raw=true - explicit bypass for any command, returning uncompressed output

Improvements

  • Better error messages when passthrough entries conflict with custom compression patterns
  • Shell pattern matching now supports glob wildcards in command prefixes

Bug Fixes

  • Fixed passthrough not triggering for commands with leading whitespace
  • Resolved ctx_shell timeout not resetting between chained commands

3.3.0 (January 2026)

Major release - expanded tool surface and protocol overhaul.

Highlights

  • 46 MCP tools: Expanded from 38 to 46 tools, adding analysis, graph, and workflow categories
  • CEP v1 protocol: New Context Efficiency Protocol with 5-rule framework and instruction codes
  • 18 tree-sitter grammars: Full language coverage for structural analysis

New Tools

ToolCategoryDescription
ctx_architectureAnalysisProject architecture overview with dependency graph
ctx_graphAnalysisBuild and query code dependency graphs
ctx_graph_diagramAnalysisVisual Mermaid diagrams from dependency data
ctx_heatmapAnalysisFile complexity and change-frequency heatmaps
ctx_impactAnalysisChange impact analysis - what breaks if you modify X
ctx_workflowWorkflowMulti-step workflow orchestration
ctx_wrappedWorkflowWrapped tool calls with pre/post hooks
ctx_executeWorkflowExecute workflow steps with rollback

Improvements

  • Rewritten instruction system with ACT1, BRIEF, FULL, DELTA, NOREPEAT, STRUCT, 1LINE codes
  • Auto-checkpoint every 15 tool calls (configurable)
  • Tree-sitter grammars now cover TypeScript, Python, Rust, Go, Java, C, C++, C#, Ruby, PHP, Swift, Kotlin, Scala, Lua, Zig, Elixir, Haskell, OCaml

Breaking Changes

  • CRP mode output format changed - agents using hard-coded parsers should update
  • ctx_agent action="handoff" renamed to ctx_handoff (old form still accepted with deprecation warning)

3.2.9 (December 2025)

Highlights

  • LEAN_CTX_SHELL_TIMEOUT_MS: New environment variable to control shell command timeout globally - prevents runaway processes from blocking sessions

New Features

  • LEAN_CTX_SHELL_TIMEOUT_MS - configurable shell timeout (default: 30000ms), applied to all ctx_shell invocations
  • ctx_shell now reports timeout kills with exit code and partial output

Improvements

  • Graceful SIGTERM → SIGKILL escalation for timed-out processes (500ms grace period)
  • Timeout duration shown in ctx_metrics per-command breakdown

Bug Fixes

  • Fixed zombie process accumulation when timeout killed a process group
  • Resolved ctx_shell not cleaning up temp files after timeout

3.2.8 (November 2025)

Highlights

  • Gemini path change: Gemini CLI MCP configuration moved from ~/.gemini/config.json to VS Code settings.json - lean-ctx auto-detects the new path

New Features

  • Auto-detection of Gemini MCP config in settings.json during lean-ctx install --gemini
  • lean-ctx doctor now checks both legacy and new Gemini config locations

Improvements

  • Installer shows migration instructions when legacy Gemini config is detected
  • Updated Getting Started guide with new Gemini setup steps

Bug Fixes

  • Fixed installer creating duplicate MCP entries when both config locations existed
  • Resolved Gemini config validation failing on Windows backslash paths

3.2.6 (October 2025)

Highlights

  • rules_scope: New config option to control which rule files lean-ctx injects - filter by project, user, or global scope

New Features

  • rules_scope config option - restrict injected rules to specific scopes ("project", "user", "global", or combinations)
  • ctx_read mode="reference" - compact reference-only output for documentation files

Improvements

  • Rule injection now respects .cursorignore patterns
  • Faster startup when many rule files are present (lazy loading)

Bug Fixes

  • Fixed rules_scope="project" accidentally including workspace-level rules
  • Resolved rules not reloading after config change without server restart

3.2.0 (August 2025)

Major feature release - HTTP server mode.

Highlights

  • lean-ctx serve: HTTP server mode for running lean-ctx as a standalone service - enables remote agents, web integrations, and custom toolchains to use lean-ctx over HTTP

New Features

  • lean-ctx serve - starts an HTTP server with REST API endpoints mirroring all MCP tools
  • lean-ctx serve --stdio - stdio mode for container and pipe-based integrations
  • lean-ctx serve --port 9315 - configurable port (default: 9315)
  • Health check endpoint at /health with session and cache stats

Improvements

  • All 38 tools (at the time) accessible via POST /tool/:name with JSON body
  • Session management via X-Session-ID header - enables multi-tenant usage
  • CORS support for browser-based integrations

Bug Fixes

  • Fixed stdio mode not flushing output buffers on slow connections
  • Resolved session cleanup not triggering for HTTP sessions after idle timeout

3.0.1 (June 2025)

First stable release of the v3 series.

Highlights

  • lean-ctx watch (Observatory TUI): Real-time terminal dashboard showing active sessions, tool calls, token savings, cache status, and agent activity

New Features

  • lean-ctx watch - interactive terminal UI with live session monitoring
  • Dashboard panels: active agents, recent tool calls, token savings graph, cache hit rate, file reference table
  • Keyboard shortcuts: q quit, r refresh, t toggle tool detail, f filter by agent

Improvements

  • Complete rewrite from Node.js to Rust - 10x faster startup, 5x lower memory
  • Single binary distribution - no runtime dependencies
  • Tree-sitter integration for structural code analysis (initial 12 grammars)

Bug Fixes

  • Fixed file watcher not detecting changes on NFS-mounted directories
  • Resolved TUI rendering artifacts on terminals with non-standard color support
  • Fixed ctx_read returning stale content when file was replaced (not modified in-place)