# Code Context (cctx) documentation Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/architecture/ # Architecture, Adaptive Memory & Privacy **How does Code Context index source code locally?**: Code Context architecture: Rust trigram indexing, regex planning, incremental file watching, adaptive memory, and local source-code privacy boundaries. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). Code Context is engineered as a single-binary Rust daemon (`cctx`) that keeps hot repository metadata and trigram postings in bounded local RAM while respecting operating-system memory pressure and workspace access rules. ## System architecture [Section titled “System architecture”](https://dotnetpower.github.io/code-context/architecture/#system-architecture) ``` VS Code 1.140+ Extension MCP Clients (Claude, Cursor, CLI) (#cctxNativeContext, Read, ...) (cctx shared-mcp -> code_context, ...) \ / \--- Persistent CCTXJ1 Framing RPC ---/ (Unix Domain Socket or Authenticated Win32 Loopback) | +---------------v---------------+ | Shared Rust Daemon | | - Workspace Catalog & Policy | | - Case-Folded Trigram Index | | - HIR Regex Query Planner | | - Polyglot AST Block Clamper | | - Incremental File Watcher | | - Adaptive Memory Controller | +-------------------------------+ ``` ## 1. Case-folded trigram posting index & HIR planner [Section titled “1. Case-folded trigram posting index & HIR planner”](https://dotnetpower.github.io/code-context/architecture/#1-case-folded-trigram-posting-index--hir-planner) - Resident posting index (`src/resident.rs`): Indexes eligible text source files into compact 3-byte ASCII/UTF-8 case-folded trigrams. Both exact and `ignore_case: true` queries intersect sorted posting lists in microseconds before touching file bytes. - HIR regex planner (`src/planner.rs`, `src/query.rs`): Parses regular expressions with `regex-syntax` High-Level Intermediate Representation (HIR) to extract mandatory literals, prefixes, suffixes, and alternations (`a|b`). Only candidate files surviving trigram intersection are scanned with `grep-regex`. - Zero-allocation wire serialization: Hot responses use borrowed snippet slices, `RawJson` framing, and persistent `CCTXJ1` socket connections to hold warm RPC latency at ~`0.232 ms`. ## 2. Incremental file watcher reconciliation [Section titled “2. Incremental file watcher reconciliation”](https://dotnetpower.github.io/code-context/architecture/#2-incremental-file-watcher-reconciliation) Saved edits never require manual re-indexing: - `notify`-backed filesystem watchers (`src/watched.rs`, `src/incremental.rs`) detect file creates, edits, renames, and deletions in real time and patch only affected posting entries. - If an agent calls `code_read` microseconds after editing a file—before the OS watcher event lands—`code_read` verifies file metadata/hashes and recovers transparently from live disk so stale lines are never returned. ## 3. Adaptive memory controller & eviction [Section titled “3. Adaptive memory controller & eviction”](https://dotnetpower.github.io/code-context/architecture/#3-adaptive-memory-controller--eviction) A resident cache on a developer workstation or WSL2 VM must never starve compilers, browsers, or Docker containers: - Linux & WSL2 cgroup v2 awareness (`src/memory.rs`): Continuously inspects host RAM reserve and parent cgroup v2 limits, shrinking index budgets automatically under memory pressure. - Windows physical-memory reporting: Native clients report fresh host RAM availability; on WSL without a fresh host report, the daemon conservatively caps itself at a `4 GiB` ceiling unless configured otherwise. - TTL & LRU eviction: Idle roots evict automatically after `15` minutes (`TTL`) or under Least-Recently-Used (`LRU`) pressure when capacity is reached (up to `256` registered workspace roots). ## 4. Security, exclusions & 100% local privacy [Section titled “4. Security, exclusions & 100% local privacy”](https://dotnetpower.github.io/code-context/architecture/#4-security-exclusions--100-local-privacy) - Zero network egress for indexing: Source code, trigram indexes, continuity journals, and usage telemetry stay strictly on your local filesystem (`~/.local/state/code-context` on Linux/WSL or `%LOCALAPPDATA%\code-context` on Windows). - Strict exclusion boundaries (`src/exclusion_policy.rs`, `src/policy.rs`): Automatically respects `.gitignore`, build outputs (`target/`, `node_modules/`, `.venv*/`, `dist/`), secret files (`.env`, `.env.*`), and sensitive agent/editor configuration directories (`.github`, `.vscode`). - No policy bypass across transports: Neither Native tools, MCP, nor shared CLI will serve files excluded by workspace trust or repository ignore policies. - Authenticated Windows loopback: On native Windows, local TCP loopback RPC requires a per-user secret token stored with restricted user permissions under `%LOCALAPPDATA%\code-context`. Have more questions? Check the [FAQ](https://dotnetpower.github.io/code-context/faq/). ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/benchmarks/ # Benchmarks: 17.22× Warm Retrieval **How were Code Context performance results measured?**: Code Context benchmarks: 17.22× warm retrieval on the published fixture, token suites, and agent A/B trials. Reproduce the results and read the limitations. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). Code Context publishes paired, correctness-checked retrieval measurements alongside multi-language token-reduction suites and controlled end-to-end coding-agent A/B trials. Every benchmark explicitly states what was measured, what was excluded, and where Code Context is slower. ## 1. Retrieval latency benchmark (AKS Store Demo, 8,960 pairs) [Section titled “1. Retrieval latency benchmark (AKS Store Demo, 8,960 pairs)”](https://dotnetpower.github.io/code-context/benchmarks/#1-retrieval-latency-benchmark-aks-store-demo-8960-pairs) Across 8 fresh daemon sessions × 40 rounds × 28 tasks (`8,960` correctness-checked off/on pairs) on the polyglot [AKS Store Demo](https://github.com/dotnetpower/aks-store-demo) corpus (`68` files, `172,244 B` across Go, Rust, JavaScript, Vue, TypeScript, and Python; pinned revision `3c3ba3bd999d0b2d78eece1adac84b712b7d9c4f`): - Mixed suite mean: `3.996 ms` without CCTX → `0.232 ms` with warm CCTX (`17.22×` faster, 95% session-bootstrap CI `17.04–17.40×`, `94.2%` less retrieval wall time; up from `6.83×` / `0.557 ms` in v0.14). - Mixed suite p95: `6.334 ms` off → `0.355 ms` on. - Cold sync median: `19.735 ms` (down from `98.813 ms` in v0.14 — `5.01×` faster). ![Warm retrieval latency means, 95% bootstrap confidence intervals, Rust and Python lookup token reductions, and Copilot A/B speedup](https://dotnetpower.github.io/code-context/benchmarks/latency-speedup.svg) Figure 1. Paired-session retrieval latency, log-scale speedup ratios (dashed parity = 1.0×), lookup token savings, and Copilot CLI A/B trials. | Retrieval Task | Checked Pairs | CCTX Off Mean | CCTX On Mean (Warm) | Speedup [95% CI] | | --- | --- | --- | --- | --- | | Filename discovery (`code_files`) | 1,920 | 4.466 ms | 0.254 ms | 17.57× [17.29, 17.89] | | Literal search (`code_grep`) | 2,560 | 5.234 ms | 0.230 ms | 22.77× [22.52, 23.07] | | Search + context (`code_context`) | 2,560 | 5.343 ms | 0.250 ms | 21.39× [21.18, 21.61] | | Known small read + SHA-256 (`code_read`) | 1,920 | 0.081 ms | 0.190 ms | 0.425× [0.415, 0.438] — slower | | Fixed mixed suite (all tasks) | 8,960 | 3.996 ms | 0.232 ms | 17.22× [17.04, 17.40] | - Small known-file reads are 2.4× slower (`0.43×`) over daemon IPC than direct in-process buffered reads (`0.081 ms` vs `0.190 ms`) because socket transport, policy checks, and JSON framing add fixed overhead. Known reads are intentionally kept inside the mixed suite rather than cherry-picked out. - Cold cache: A cold `CACHE_MISS` plus host fallback had a `4.409 ms` median—not a cold-cache speedup. Ordinary callers never block on cold sync. - Hardware disclosure: Measurements run on a nonexclusive Linux host without CPU pinning; hardware specifics are omitted for host privacy, so exact millisecond figures vary by machine. ![Cold-start CACHE_MISS fallback latency and explicit cold synchronization duration](https://dotnetpower.github.io/code-context/benchmarks/cold-start.svg) Figure 2. Descriptive cold-control lookup, nonblocking CACHE_MISS + fallback, and explicit cold synchronization (`19.735 ms` median). ## 2. Lookup payload token suites (Rust & Python) [Section titled “2. Lookup payload token suites (Rust & Python)”](https://dotnetpower.github.io/code-context/benchmarks/#2-lookup-payload-token-suites-rust--python) Replacing traditional two-step `rg -n` + 100-line or 200-line `view` reads with a single AST block-clamped `code_context` call (`radius=8..12`, `max_matches_per_file=5` with definition priority): | Corpus & 6-Symbol Suite | Tool Calls (`rg+view` → `cctx`) | `rg` + 200L `view` | `rg` + 100L `view` | `cctx code_context` | Payload Token Reduction | Retrieval Time | | --- | --- | --- | --- | --- | --- | --- | | Rust (`src/`, 20 files) | 20 → 6 (-70.0%) | 25,133 tok | 15,028 tok | 4,031 tok | -73.2% to -84.0% | 26.24 ms → 2.56 ms (10.3×) | | Python (506 files, 17.3k lines) | 15 → 6 (-60.0%) | 24,609 tok | 13,997 tok | 2,141 tok | -84.7% to -91.3% | 5.33 ms → 0.40 ms (13.16×) | ## 3. End-to-end Copilot CLI agent A/B trials [Section titled “3. End-to-end Copilot CLI agent A/B trials”](https://dotnetpower.github.io/code-context/benchmarks/#3-end-to-end-copilot-cli-agent-ab-trials) Measured with `scripts/agent_ab.py` on a 6,000-file Rust workspace across identical multi-file questions, identical model configuration, alternating trial order, and 100% answer accuracy in both arms: | Metric (Mean per Trial) | Baseline (`rg` / `glob` / `view`) | With `cctx` (`code_context`) | Measured Delta | | --- | --- | --- | --- | | Tool invocations | 7.00 | 2.67 | -61.9% tool calls | | LLM round-trip turns | 5.00 | 3.67 | -26.7% turns | | Tool result payload tokens | 6,360 tok | 3,177 tok | -50.0% payload tokens | | Total session billing (`totalNanoAiu`) | 4.76B nanoAIU | 3.55B nanoAIU | -25.4% net AIU cost | | End-to-end completion wall time | 20.31 s | 15.30 s | -24.7% faster | ## 4. Rich documents, `pctx` probes & `cctx journal` [Section titled “4. Rich documents, pctx probes & cctx journal”](https://dotnetpower.github.io/code-context/benchmarks/#4-rich-documents-pctx-probes--cctx-journal) | Workload | Raw Payload | Delivered to Context | Reduction | Median Latency | | --- | --- | --- | --- | --- | | Rich documents (`.pptx`/`.docx`/`.md` `#toc` & `#slide-N`) | Full document | Virtual `#toc` + `#slide-N-M` | -86.3% to -98.9% | 5.4× faster DEFLATE | | `pctx json` (5,000 API records, `--where` + `--count-by`) | 1,021,281 B | 662 B | -99.94% | 7.82 ms | | `pctx batch` (2,400-line log, 2 RRF queries + digest) | 226,918 B | 4,079 B | -98.20% | 21.81 ms | | `pctx log @latest` (follow-up BM25 + Trigram RRF) | 226,918 B | 2,273 B | -99.00% | 11.00 ms (0 re-exec) | | `cctx journal resume` (40-step session state) | 434,271 B | 1,829 B (`<=2 KiB`) | -99.58% | 5.51 ms | | BPE-aligned formula instructions (`cctx prompt`) | 2,048 tok | 756 tok | -63.1% | Static / per-turn | ## 5. Net LLM cost analysis (`24h` production trace replay) [Section titled “5. Net LLM cost analysis (24h production trace replay)”](https://dotnetpower.github.io/code-context/benchmarks/#5-net-llm-cost-analysis-24h-production-trace-replay) Shrinking a single tool output by 99% via large MCP tool catalogs or `PreToolUse` hook denials often increases total session billing because model output tokens and extra uncached turns cost 10× to 100× more than cached history reads. Replaying 159 live multi-model coding sessions (`7,578` turns, `2.86B` total tokens, `95.5%` warm cache hit rate, `90.3%` eligible source adoption) via `cctx usage --hours 24 --details` models `$48.88 USD` (`-26.6%`) lower spend (`~$183.78 → $134.90` @ `$0.001/AIC`; `~$488.82` @ `$0.01` API list reference): | Savings Driver (`cctx usage --hours 24 --details`) | Tokens Avoided | Share | Why It Lowers the Actual Bill | | --- | --- | --- | --- | | 1. Avoided LLM round-trip turns (`~2,290` turns) | 851.76M tok | 54.0% | Combining search + block-clamped read in 1 turn eliminates extra model invocations, reasoning/output tokens, and full-history re-submissions. | | 2. Compounded prompt-cache re-reads (`98.7×` mult.) | 701.82M tok | 44.5% | Keeping noisy lines out on turn k avoids re-reading those tokens across turns k+1 … T before compaction. | | 3. Standing BPE formula compression (`4/4` surfaces) | 16.09M tok | 1.0% | Saves `~2,123 tok` on every turn (`0` extra MCP schemas for `pctx` & `journal`). | | 4. First-turn tool payload byte delta | 7.11M tok | 0.5% | Immediate single-call byte trimming alone is `<0.5%` of total session token exposure. | | Total modeled 24h impact | ~1.58B tok | 100.0% | `~$183.78 → $134.90` (`-$48.88 USD` / `-26.6%` @ `$0.001/AIC`) | ## 6. Reproduce on your own machine [Section titled “6. Reproduce on your own machine”](https://dotnetpower.github.io/code-context/benchmarks/#6-reproduce-on-your-own-machine) Terminal window ``` git clone https://github.com/dotnetpower/code-context.gitcd code-contextgit clone https://github.com/dotnetpower/aks-store-demo.git ../aks-store-demogit -C ../aks-store-demo checkout 3c3ba3bd999d0b2d78eece1adac84b712b7d9c4f cargo build --locked --releasepython3 -m venv .venv-benchmark.venv-benchmark/bin/pip install -r benchmarks/requirements.txt.venv-benchmark/bin/python benchmarks/benchmark.py \ --root ../aks-store-demo --cctx target/release/cctx \ --sessions 8 --rounds 40 --seed 20261023 \ --output /tmp/cctx-benchmark-run ``` Raw observations and summary CSVs are published in the repository under [`benchmarks/results/aks-store-demo/`](https://github.com/dotnetpower/code-context/tree/main/benchmarks/results/aks-store-demo). ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/faq/ # Frequently Asked Questions (FAQ) **What should I know before using Code Context?**: Code Context FAQ: ripgrep and vector RAG comparisons, native VS Code tools versus MCP, Windows support, privacy, and benchmark limitations. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). ## How is Code Context (`cctx`) different from `ripgrep` (`rg`)? [Section titled “How is Code Context (cctx) different from ripgrep (rg)?”](https://dotnetpower.github.io/code-context/faq/#how-is-code-context-cctx-different-from-ripgrep-rg) `ripgrep` is a fast stateless CLI scanner—Code Context actually uses `rg` during initial authorized workspace discovery. However, in multi-turn coding agents, raw `rg` forces a costly two-step loop (`rg` match lines → multiple 100–200 line `view` calls) and re-scans files on every turn. `cctx` keeps a warm in-memory trigram index (`17.22×` faster mixed retrieval) and returns AST block-clamped definitions in one call (`#cctxNativeContext` / `code_context`), cutting lookup payload tokens by 73.2% to 91.3% and agent round-trip tool calls by 61.9%. ## How does `cctx` compare to vector embeddings / semantic RAG? [Section titled “How does cctx compare to vector embeddings / semantic RAG?”](https://dotnetpower.github.io/code-context/faq/#how-does-cctx-compare-to-vector-embeddings--semantic-rag) Vector RAG requires chunking, embedding models (often cloud APIs or heavy local GPUs), approximate nearest-neighbor indexes that lag behind rapid branch switches, and fuzzy similarity matches that frequently miss exact symbol names, error codes, or regex patterns. `cctx` is 100% deterministic, exact, local, and SHA-256 verified: zero API keys, zero GPU overhead, sub-millisecond warm queries, and instant incremental updates on file save. ## Do I need MCP if I install the VS Code extension? [Section titled “Do I need MCP if I install the VS Code extension?”](https://dotnetpower.github.io/code-context/faq/#do-i-need-mcp-if-i-install-the-vs-code-extension) For foreground VS Code Copilot sessions (VS Code 1.140+), no MCP configuration is required—the Marketplace extension (`dotnetpower.code-context-native`) registers native Language Model Tools directly. Adding `cctx shared-mcp` is recommended when you also run background/unattended subagents without UI extension-host dispatch, or external MCP clients such as Claude Code, Cursor, or custom CLI agents. Both surfaces share the exact same background Rust daemon and warm cache. ## Does `cctx` upload my code or telemetry anywhere? [Section titled “Does cctx upload my code or telemetry anywhere?”](https://dotnetpower.github.io/code-context/faq/#does-cctx-upload-my-code-or-telemetry-anywhere) Indexing, trigram postings, document extraction, `cctx journal`, and `cctx usage` analytics run locally; the index is not automatically uploaded. Explicit `pctx http` probes contact the URLs you supply. Any AI client receiving tool output follows its own data policy. This public documentation website cannot access your local workspace. ## Why does `code_read` show `0.43×` (slower) on small known-file reads in the benchmark? [Section titled “Why does code_read show 0.43× (slower) on small known-file reads in the benchmark?”](https://dotnetpower.github.io/code-context/faq/#why-does-code_read-show-043-slower-on-small-known-file-reads-in-the-benchmark) Because direct in-process buffered reads of a tiny file already in the OS page cache take ~`0.081 ms`, whereas sending a request over a Unix socket / loopback RPC with policy validation, SHA-256 verification, and JSON serialization takes ~`0.190 ms`. We keep small known reads in the benchmark suite deliberately so our reported `17.22×` mixed speedup reflects realistic agent workloads rather than cherry-picked search-only numbers. ## What happens when `cctx` returns `CACHE_MISS`? [Section titled “What happens when cctx returns CACHE_MISS?”](https://dotnetpower.github.io/code-context/faq/#what-happens-when-cctx-returns-cache_miss) `CACHE_MISS` means the workspace root was cold and has just been queued for bounded background indexing—never that the symbol or file is absent. The agent performs a single normal host read/search for that immediate turn without waiting, and automatically gets warm `0.23 ms` hits on subsequent turns. ## Does `cctx` run natively on Windows without WSL? [Section titled “Does cctx run natively on Windows without WSL?”](https://dotnetpower.github.io/code-context/faq/#does-cctx-run-natively-on-windows-without-wsl) Yes. Build `cctx.exe` with `cargo build --locked --release` and place it at `%USERPROFILE%\.local\bin\cctx.exe`. The VS Code extension starts `cctx.exe daemon` automatically on demand and uses `rg` on `PATH` or VS Code’s bundled `rg.exe`. WSL2 and Windows Agent Sessions are also fully supported—see [Installation & Platform Setup](https://dotnetpower.github.io/code-context/installation/). ## How does `cctx` relate to `agent-tokenomics` and `tokprof`? [Section titled “How does cctx relate to agent-tokenomics and tokprof?”](https://dotnetpower.github.io/code-context/faq/#how-does-cctx-relate-to-agent-tokenomics-and-tokprof) [`agent-tokenomics`](https://dotnetpower.github.io/agent-tokenomics/) is our companion engineering playbook and zero-code LLM request profiler (`tokprof`). Use `cctx` inside your IDE and MCP clients to cut lookup tokens, clamp context, and accelerate coding tasks; use `tokprof` when building or operating custom agents to attribute every input token across system prompts, tool schemas, and conversation history. ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/ LOCAL RUST CONTEXT ENGINE · NATIVE VS CODE TOOLS & MCP # Code Context (cctx) for AI Coding Agents Find the signal. Clamp the noise in 0.23 ms. Stop feeding coding agents 200-line `grep` dumps. Code Context (cctx) pairs native VS Code Language Model Tools (`#cctxNativeContext`) and an MCP server over one shared Rust trigram index—cutting lookup tokens by 73.2–91.3%, accelerating warm retrieval 17.22× in the published retrieval fixture. Linux, native Windows (`cctx.exe`), WSL, and SSH are supported. **What is Code Context?**: A local Rust source index shared by 7 native VS Code and MCP tools. **What does the 17.22× result mean?**: A warm mixed-retrieval measurement on the published fixture, not a guarantee for other hardware, workloads, or bills. [Methodology and limitations](https://dotnetpower.github.io/code-context/benchmarks/). Can this website search my source code? No. Install the [local backend](https://dotnetpower.github.io/code-context/installation/) and follow the [quickstart](https://dotnetpower.github.io/code-context/quickstart/). The website only publishes documentation. ``` git clone https://github.com/dotnetpower/code-context.git && cd code-context && bash scripts/install.sh ``` [Install in 60s →](https://dotnetpower.github.io/code-context/installation/) [VS Code Marketplace ↗](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) [7 Native & MCP Tools →](https://dotnetpower.github.io/code-context/tools/) [Verified Benchmarks →](https://dotnetpower.github.io/code-context/benchmarks/) SCENE 03 · AST CLAMP LOCKED t = 06.80s Comparison of traditional multi-turn ripgrep plus 200-line view windows (25,133 tokens, 20 tool calls, 3.996 ms mean retrieval) versus a single Code Context #cctxNativeContext call on plan_query in src/planner.rs:142-146 (4,031 tokens, -84.0% payload reduction, 6 calls, 0.232 ms warm retrieval, SHA-256 verified under 8 KiB). Drag wipe · 10.0s ONE SHARED RUST DAEMON · ZERO STARTUP STALLS ## One resident index powers both VS Code Native Tools and MCP. Scroll or toggle between Warm Hit and Cold `CACHE_MISS`. Code Context never blocks an agent on index warmup: cold workspaces return immediately so host tools proceed without delay while bounded background indexing finishes in ~19.7 ms. PIPELINE CHOREOGRAPHY · CLICK ANY STAGE OR TOGGLE CACHE STATE STAGE 01 ### Native & MCP Ingress Foreground VS Code agents call `#cctxNativeContext`; CLI and subagents call `code_context` over `cctx shared-mcp`. Both hit the same socket/loopback RPC. STAGE 02 ### Trigram + HIR Planner ASCII/UTF-8 case-folded trigram postings narrow regex and literal candidates in microseconds before touching line buffers, prioritizing symbol definitions. STAGE 03 ### Polyglot Block Clamper Expands matches to clean Rust, Python, TS/React, Go, SQL, and Markdown/Office boundaries under a strict `<8 KiB` inline guard with SHA-256 verification. STAGE 04 ### Watcher & Adaptive Memory Incremental filesystem watchers reconcile edits live while the memory controller respects Linux cgroup v2 headroom, Windows physical RAM reports, and 15m TTL eviction. BEYOND SOURCE GREP · FULL CONTEXT HYGIENE SUITE ## Rich document anchors, zero-schema probes, and compaction journals. Every high-volume token leak in real agent sessions—Office decks, 1 MB JSON responses, multi-command build logs, and context compactions—is handled natively in Rust with 0 standing MCP schema bloat. 01 · Virtual #toc & #slide-N-M ### Rich Document Slicing (-86.3% to -98.9%) Inspect `.pptx`, `.docx`, `.xlsx`, `.pdf`, `.epub`, Jupyter notebooks, and Markdown by virtual table-of-contents or slide/section anchors—backed by 5.4× faster 9-bit O(1) DEFLATE decoding. #cctxNativeRead `architecture.pptx#toc` → `architecture.pptx#slide-3-5` Full deck dump100.0% #toc + #slide-3-51.1% – 13.7% 02 · pctx {http|json|table|image|log|batch} ### Zero-Schema Probes & BM25+RRF Log Spools Replace fragile ad-hoc `python3 -c`, `jq`, and `sqlite3` one-liners. Filter 1 MB JSON payloads to 662 B in 7.82 ms and query spooled batch logs (`@s1`) without re-running commands. `$ pctx json api.json --where status=500 --count-by route` `$ pctx log @latest "panic|deadlock"` # 0 re-exec Raw JSON (1,021,281 B)7.82 ms Redacted digest (662 B)-99.94% 03 · cctx journal & cctx usage ### <=2 KiB Continuity & Live Cost Telemetry Preserve architectural decisions across compactions in strictly `<= 2,048 B` with fail-open hooks (`0` `PreToolUse` denials), and track live AIC/USD savings in VS Code or `cctx usage --hours 24`. `$ cctx usage --hours 24` 💰 $48.88 saved · 26.6% less (~$183.78 → $134.90) ⚡ Avoided ~1.58B tok · Warm hits 95.5% 40-step journal resume (1,829 B)-99.58% 8,960 CORRECTNESS-CHECKED PAIRS · REPRODUCIBLE EVIDENCE ## Measured retrieval speedups, token reductions, and honest limits. Evaluated across 8 daemon sessions × 40 rounds × 28 tasks on [AKS Store Demo](https://github.com/dotnetpower/aks-store-demo), 506-file Python and 6,000-file Rust suites, and controlled end-to-end Copilot CLI A/B trials. ![Measured retrieval latency, paired-session speedup confidence intervals, Rust and Python lookup token savings, and Copilot A/B task completion speedup](https://dotnetpower.github.io/code-context/benchmarks/latency-speedup.svg) Transparent engineering boundaries: Small known-file reads are 0.43× (2.4× slower: 0.081 ms → 0.190 ms) over daemon IPC than direct buffered reads because IPC adds socket and JSON framing overhead. A cold `CACHE_MISS` plus host fallback had a 4.409 ms median—no cold-cache speedup is claimed. See the [full methodology, confidence intervals, and reproduction commands](https://dotnetpower.github.io/code-context/benchmarks/). 17.22× Mixed retrieval speedup (95% CI 17.04–17.40×, 3.996 → 0.232 ms) -73% to -91% Rust & Python 6-symbol lookup payload token reduction -24.7% Faster Copilot A/B task wall time (20.31 s → 15.30 s, 100% accuracy) -25.4% Lower net session AIU billing cost (-61.9% tool calls) | Benchmark Workload | Baseline | With cctx | Impact | | --- | --- | --- | --- | | Literal search (AKS Store Demo) | 5.234 ms | 0.230 ms | 22.77× faster | | Search + context | 5.343 ms | 0.250 ms | 21.39× faster | | Filename discovery | 4.466 ms | 0.254 ms | 17.57× faster | | Known small read + SHA-256 | 0.081 ms | 0.190 ms | 0.43× (IPC overhead) | | Rust 6-symbol lookup tokens | 15,028 – 25,133 tok | 4,031 tok | -73.2% to -84.0% | | Python 6-symbol lookup tokens | 13,997 – 24,609 tok | 2,141 tok | -84.7% to -91.3% | | BPE formula instructions | 2,048 tok | 756 tok | -63.1% per turn | FREQUENTLY ASKED QUESTIONS · TECHNICAL EVALUATION ## Common questions from engineers & agent builders How is Code Context (cctx) different from ripgrep or vector embeddings? `ripgrep` spawns a fresh scan per call and returns raw lines without block boundaries, forcing agents into multi-turn `rg` + `view` loops. Vector RAG requires cloud or GPU embedding indexes that drift on edits and blur exact identifiers. `cctx` keeps an exact, deterministic in-memory trigram posting index in Rust with live file-watcher updates and polyglot AST block clamping—100% local and SHA-256 verified. Does cctx upload source code or require an external API key? Indexing, trigram queries, document extraction, and continuity journals run locally. Explicit `pctx http` probes contact the URLs you supply. AI clients receiving tool output follow their own data policies; review the [privacy boundaries](https://dotnetpower.github.io/code-context/architecture/). Should I use the VS Code Native Extension or the MCP server? In VS Code 1.140+, install `dotnetpower.code-context-native` from the Marketplace for foreground native tool dispatch and automatic BPE-aligned agent instructions, and optionally configure `cctx shared-mcp` for background subagents or MCP-only clients (Claude Code, Cursor, CLI agents). Both surfaces share the exact same resident Rust daemon and cache. Does it work on native Windows without WSL? Yes. Build or copy `cctx.exe` to `%USERPROFILE%\.local\bin\cctx.exe`. The VS Code extension automatically starts `cctx.exe daemon` in the background on first use and falls back to VS Code’s bundled `rg.exe` if ripgrep is not on `PATH`. WSL and Windows Agent Sessions are also first-class supported. Looking for broader LLM & Copilot token-cost playbooks and zero-code request profiling? Explore our companion guide [agent-tokenomics & tokprof ↗](https://dotnetpower.github.io/agent-tokenomics/) or browse the machine-readable [`llms.txt`](https://dotnetpower.github.io/code-context/llms.txt) and [`llms-full.txt`](https://dotnetpower.github.io/code-context/llms-full.txt) indexes. ## Check your lookup payload reduction Enter token counts from your own tool outputs. This arithmetic is not a forecast of billing or performance. The calculator requires JavaScript. Formula: (baseline − clamped) ÷ baseline × 100%. ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/installation/ # Installation & Platform Setup **How do I install Code Context on my platform?**: Install Code Context and its native VS Code extension or MCP server on Linux, Windows, WSL, and SSH. Includes platform setup and troubleshooting. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). For a machine-readable index of all documentation, see [`llms.txt`](https://dotnetpower.github.io/code-context/llms.txt) and [`llms-full.txt`](https://dotnetpower.github.io/code-context/llms-full.txt). Code Context (`cctx`) consists of two lightweight local components: - The `cctx` Rust backend — a single native executable (`cctx` on Linux/WSL/SSH or `cctx.exe` on Windows) that maintains the shared in-memory trigram index, incremental file watchers, adaptive memory controller, declarative probes (`pctx`), and compaction journal. - Your agent client surface — either the [Code Context VS Code Marketplace extension](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) (`dotnetpower.code-context-native`, VS Code 1.140+) for foreground native tools, `cctx shared-mcp` for Model Context Protocol (MCP) clients, or both simultaneously. The VS Code extension package contains the native Language Model Tools adapter and BPE-aligned agent instructions—not a precompiled backend binary. Install the `cctx` executable first so the extension can connect immediately. ## Platform requirements matrix [Section titled “Platform requirements matrix”](https://dotnetpower.github.io/code-context/installation/#platform-requirements-matrix) | Platform | Transport & Daemon Lifecycle | Requirements | | --- | --- | --- | | Linux (local or SSH) | Unix domain socket (`~/.local/state/code-context/daemon.sock`) + `systemd --user` service | Stable Rust/Cargo, `rg` (ripgrep) on `PATH`, `systemd` user session, cgroup v2 | | WSL2 (Linux workspace) | Unix domain socket inside WSL distribution | Stable Rust/Cargo and `rg` inside WSL | | Native Windows (no WSL) | Authenticated loopback RPC (`%LOCALAPPDATA%\code-context`), auto-started in background | Stable Rust/Cargo (MSVC) to build `cctx.exe`; uses `rg` on `PATH` or falls back to VS Code’s bundled `rg.exe` | | Windows Agent Sessions | Windows UI extension host bridging to WSL `cctx` | Extension installed on Windows + `codeContextNative.wslDistribution` & `wslExecutablePath` configured | ## 1. Install the Rust backend (`cctx`) [Section titled “1. Install the Rust backend (cctx)”](https://dotnetpower.github.io/code-context/installation/#1-install-the-rust-backend-cctx) ### Linux, WSL, and Linux SSH [Section titled “Linux, WSL, and Linux SSH”](https://dotnetpower.github.io/code-context/installation/#linux-wsl-and-linux-ssh) Clone the repository and run the managed installer, which builds a `--locked --release` binary, installs `cctx` (and `pctx` alias) into `~/.local/bin`, and configures the user service: Terminal window ``` git clone https://github.com/dotnetpower/code-context.gitcd code-contextbash scripts/install.sh~/.local/bin/cctx pingexport PATH="$HOME/.local/bin:$PATH" ``` ### Native Windows (`cctx.exe`, without WSL) [Section titled “Native Windows (cctx.exe, without WSL)”](https://dotnetpower.github.io/code-context/installation/#native-windows-cctxexe-without-wsl) Build `--locked --release` in PowerShell and copy `cctx.exe` into `%USERPROFILE%\.local\bin\cctx.exe`: Terminal window ``` git clone https://github.com/dotnetpower/code-context.gitSet-Location code-contextcargo build --locked --releaseNew-Item -ItemType Directory -Force "$HOME\.local\bin" | Out-NullCopy-Item target\release\cctx.exe "$HOME\.local\bin\cctx.exe" -Force& "$HOME\.local\bin\cctx.exe" --version ``` When you open a trusted Windows folder (`C:\...`) in VS Code without `codeContextNative.wslDistribution` set, the extension automatically launches `cctx.exe daemon` in the background on first tool call and stores index metadata under `%LOCALAPPDATA%\code-context`. ## 2. Install the VS Code Native Extension [Section titled “2. Install the VS Code Native Extension”](https://dotnetpower.github.io/code-context/installation/#2-install-the-vs-code-native-extension) Install [Code Context by dotnetpower](https://marketplace.visualstudio.com/items?itemName=dotnetpower.code-context-native) from the VS Code Extensions view, or run from your terminal: Terminal window ``` code --install-extension dotnetpower.code-context-native ``` Alternatively, download `code-context-native.vsix` from [GitHub Releases](https://github.com/dotnetpower/code-context/releases/latest) and install via Extensions: Install from VSIX…. Marketplace and GitHub VSIX builds share the exact same `dotnetpower.code-context-native` identity and require no proposed API flags. Open a trusted project and run Code Context: Getting Started from the Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`). ## 3. Configure MCP Clients (Claude Code, Cursor, CLI & Subagents) [Section titled “3. Configure MCP Clients (Claude Code, Cursor, CLI & Subagents)”](https://dotnetpower.github.io/code-context/installation/#3-configure-mcp-clients-claude-code-cursor-cli--subagents) Any MCP-compatible coding agent can connect to the exact same shared daemon through `cctx shared-mcp`: ``` { "mcpServers": { "code-context": { "command": "cctx", "args": ["shared-mcp"] } }} ``` If `~/.local/bin` is not inherited by GUI launchers, specify the full executable path (for example `/opt/cctx/bin/cctx` or `$HOME/.local/bin/cctx` on Linux, or `%USERPROFILE%\\.local\\bin\\cctx.exe` on Windows). ## 4. Windows Agent Sessions (Windows UI + WSL Workspace) [Section titled “4. Windows Agent Sessions (Windows UI + WSL Workspace)”](https://dotnetpower.github.io/code-context/installation/#4-windows-agent-sessions-windows-ui--wsl-workspace) A WSL-only extension installation cannot expose client tools inside a separate Windows Agents window. Install `dotnetpower.code-context-native` on the Windows host as well, then configure these workspace settings for the Agents window: ``` { "remote.extensionKind": { "dotnetpower.code-context-native": ["ui"] }, "codeContextNative.wslDistribution": "", "codeContextNative.wslExecutablePath": "/path/to/user-state/.local/bin/cctx"} ``` Discover your distribution name with `wsl --list --quiet` and your Linux binary path inside WSL with `realpath ~/.local/bin/cctx`. Leave `codeContextNative.socketPath` empty in this mode. ## 5. Verify the installation & troubleshoot [Section titled “5. Verify the installation & troubleshoot”](https://dotnetpower.github.io/code-context/installation/#5-verify-the-installation--troubleshoot) Run the built-in health and telemetry checks: Terminal window ``` cctx pingcctx --root /path/to/project doctorcctx usage --hours 24 ``` ### Common setup issues [Section titled “Common setup issues”](https://dotnetpower.github.io/code-context/installation/#common-setup-issues) | Symptom | Cause | Fix | | --- | --- | --- | | `CACHE_MISS` on first lookup | Expected cold-root contract: root was queued for background indexing | Do not treat as zero matches or run `code_sync`; continue that single lookup with normal host tools and resume `cctx` on the next turn (~1s). | | Legacy publisher conflict | Older `moonchoi.code-context-native` VSIX installed alongside `dotnetpower` | Uninstall the legacy extension first, then reload VS Code. | | Connection error in Linux workspace | User daemon stopped or `~/.local/bin` missing from `PATH` | Run `~/.local/bin/cctx ping` or verify `codeContextNative.autoStartService` is `true` (default). | | `TARGET_NOT_INDEXED` | Requested path is outside registered scopes/globs or excluded by `.gitignore` | Register explicit coverage with `cctx --root /path/to/project register` or use host tools for intentionally excluded files (`.github`, `.vscode`, `.env`). | Next, walk through a real agent session in the [Quickstart & Agent Workflow](https://dotnetpower.github.io/code-context/quickstart/). ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/probes-and-journal/ # Zero-Schema Probes (pctx), Journal & Formula Prompts **When should I use pctx probes and the continuity journal?**: Use pctx to inspect JSON, APIs, tables, images, and logs; preserve compact continuity with cctx journal and compile formula prompts. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). Coding agents lose tens of thousands of tokens per session on tasks outside source code: inspecting 1 MB API payloads, writing throwaway `python3 -c` or `jq` scripts, re-running noisy test suites, and losing architectural state after context compaction. Code Context solves all three in native Rust CLI subcommands (`pctx` / `cctx probe`, `cctx journal`, and `cctx prompt`) with `0` standing MCP tool-schema tokens and `0` LLM script-authoring turns. ## 1. Declarative Probes (`pctx` / `cctx probe`) [Section titled “1. Declarative Probes (pctx / cctx probe)”](https://dotnetpower.github.io/code-context/probes-and-journal/#1-declarative-probes-pctx--cctx-probe) `pctx` (installed alongside `cctx` as a direct alias for `cctx probe`) gives agents six deterministic inspection primitives with automatic secret/token scrubbing and ANSI stripping: | Command | Replaces | Example Usage | | --- | --- | --- | | `pctx json` | `jq`, `python3 -c "import json..."` | `pctx json response.json --where status=500 --count-by service` | | `pctx http` | Multi-curl loops & OpenAPI/STAC scripts | `pctx http "https://api.example.com/{svc}/health" --var svc=auth,billing` | | `pctx table` | Ad-hoc `sqlite3` / Parquet / CSV Python scripts | `pctx table metrics.db --sql "SELECT model, AVG(ms) FROM runs GROUP BY 1"` | | `pctx image` | Blindly attaching multi-megabyte PNGs | `pctx image ui-after.png --expect 1440x900` (dimensions, channels, exposure check) | | `pctx batch` | Raw multi-command log dumps | `pctx batch --cmd "cargo test --locked" --query "FAILED\|panicked"` | | `pctx log` | Re-running slow builds to grep a different error | `pctx log @latest "deadlock\|timeout"` (queries saved `@sN` spool in ~`11 ms`) | ### Measured `pctx` payload reductions [Section titled “Measured pctx payload reductions”](https://dotnetpower.github.io/code-context/probes-and-journal/#measured-pctx-payload-reductions) - `pctx json` on `5,000` API records (`1,021,281 B`): emits a `662 B` structured schema + filtered count digest in `7.82 ms` (`-99.94%` payload bytes). - `pctx batch` + `pctx log @latest` on a `2,400`-line cluster log (`226,918 B`): spools output once as `@s1`, preserves code fences and stack traces intact, and answers follow-up Okapi BM25 + Trigram Reciprocal Rank Fusion (RRF) queries in `11.00 ms` (`2,273 B`, `-99.00%`) with zero command re-execution. ## 2. Compaction Continuity Journal (`cctx journal`) [Section titled “2. Compaction Continuity Journal (cctx journal)”](https://dotnetpower.github.io/code-context/probes-and-journal/#2-compaction-continuity-journal-cctx-journal) Long coding sessions inevitably hit context-window compaction, causing agents to forget subtle invariants, rejected approaches, or verified root paths. `cctx journal` maintains a project-scoped continuity log that resumes into strictly `<= 2,048 B` (`2 KiB`): Terminal window ``` # Record a verified architectural decision or milestonecctx --root /path/to/project journal record \ --summary "Switched planner literal extraction to ASCII case-folded trigrams" # Emit <= 2 KiB block + top BM25/RRF recall after compactioncctx --root /path/to/project journal resume # Search historical session decisionscctx --root /path/to/project journal search "cgroup memory reserve" # Print fail-open hook configuration for agent harnessescctx --root /path/to/project journal hook-config ``` - Measured compression: Compresses a `40`-step (`434,271 B`) engineering session into `1,829 B` (`-99.58%`) in `5.51 ms`. - Fail-open safety: Hook integration never blocks tool execution (`0` `PreToolUse` denials). ## 3. BPE-Aligned Formula Prompts (`cctx prompt`) [Section titled “3. BPE-Aligned Formula Prompts (cctx prompt)”](https://dotnetpower.github.io/code-context/probes-and-journal/#3-bpe-aligned-formula-prompts-cctx-prompt) Verbose prose instructions in `AGENTS.md`, `CLAUDE.md`, MCP descriptions, and subagent definitions get re-tokenized on every single turn. `cctx prompt` compiles agent instructions and user task prompts into compact, BPE-aligned symbolic specs while preserving domain nouns and safety invariants: Terminal window ``` # Render BPE-aligned formula instructions (-63.1% tokens: 2,048 -> 756 tok)cctx --root /path/to/project prompt --style formula --target instructions # Compress an English or Korean task prompt while preserving technical identifierscctx prompt --compress "Analyze planner.rs and fix case-insensitive regex fallback" --json ``` Supported `--target` outputs include `instructions`, `mcp`, `subagent-yaml`, `subagent-md`, and `claude-md`. Continue to [Benchmarks & Token Suites](https://dotnetpower.github.io/code-context/benchmarks/) for the full experimental methodology and confidence intervals. ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/quickstart/ # Quickstart & Agent Workflow **How do I run my first Code Context lookup?**: Run your first block-clamped symbol lookup with #cctxNativeContext, handle cold-cache responses cleanly, configure subagents, and inspect live AIC/USD savings. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). Once [installed](https://dotnetpower.github.io/code-context/installation/), Code Context works automatically in trusted VS Code workspaces: the extension contributes seven native Language Model Tools and injects compact BPE-aligned agent instructions (`applyTo: "**"`) so Copilot prefers fast, bounded lookups without manual prompting. ## 1. Try your first prompt in VS Code Chat [Section titled “1. Try your first prompt in VS Code Chat”](https://dotnetpower.github.io/code-context/quickstart/#1-try-your-first-prompt-in-vs-code-chat) Open a trusted repository and ask your coding agent: ``` Use #cctxNativeFiles to find *planner* files, then #cctxNativeContext to inspect plan_query and summarize how trigram candidates are intersected. ``` Instead of spawning multiple `rg` subprocesses and reading arbitrary 200-line file slices, the agent executes: - `#cctxNativeFiles` (`glob: "*planner*"`) — returns matching relative paths from the resident catalog in ~`0.25 ms`. - `#cctxNativeContext` (`pattern: "plan_query"`, `radius: 12`) — intersects trigram postings, locates the symbol definition, clamps the snippet cleanly to the enclosing function boundary within `<8 KiB`, and verifies the whole-file SHA-256 hash. ## 2. Recommended tool dispatch priority [Section titled “2. Recommended tool dispatch priority”](https://dotnetpower.github.io/code-context/quickstart/#2-recommended-tool-dispatch-priority) Code Context is an optional nonblocking accelerator, never a fragile gate. Agents follow a deterministic priority hierarchy: ``` VS Code Native (#cctxNative*) > MCP (code_*) > CLI (cctx --backend shared) > Host (rg, view, glob) ``` | Lookup Intent | First-Choice Tool | Key Guardrails | | --- | --- | --- | | Symbol or literal + nearby code | `#cctxNativeContext` / `code_context` | Prefer 1 call (`radius: 8..50`, `limit: 1..64`) over separate `grep` + `read` turns. | | Filename or path discovery | `#cctxNativeFiles` / `code_files` | Pass `glob` (`*.rs`, `src/**/*.ts`); does not scan file contents. | | Exact, case-folded, or regex lines | `#cctxNativeGrep` / `code_grep` | Set `regex: true` for alternation (`a\|b`); set `max_matches_per_file` to prioritize definitions. | | Known line ranges or doc anchors | `#cctxNativeRead` / `code_read` | Batch multiple edits into one `ranges` array (`<=150` lines total, `<8 KiB`); supports `doc.pptx#toc` and `#slide-3-5`. | ## 3. Understanding cold-cache `CACHE_MISS` [Section titled “3. Understanding cold-cache CACHE_MISS”](https://dotnetpower.github.io/code-context/quickstart/#3-understanding-cold-cache-cache_miss) When an agent queries an unindexed workspace root for the very first time, Code Context returns `CACHE_MISS` in ~`0.2 ms` and schedules bounded background indexing: - `CACHE_MISS` does NOT mean zero matches or a missing file. - The agent performs one normal host lookup (`rg` or `view`) for that immediate turn—never stalling the user—and automatically resumes `#cctxNative*` / `code_*` on the next turn once warm (~`19.7 ms` median sync on a 68-file polyglot repo). - Never poll `#cctxNativeStatus` or call `#cctxNativeSync` merely to wait for warmup; `code_sync` is reserved strictly for exhaustive absence proofs. ## 4. Delegating to subagents [Section titled “4. Delegating to subagents”](https://dotnetpower.github.io/code-context/quickstart/#4-delegating-to-subagents) Built-in subagents (`explore`, `general-purpose`, `code-review`, `research`, `security-review`) may run in separate sessions or model families without workspace prompt files. For maximum cache hits: - Always pass the explicit absolute `root` path in your subagent prompt. - If tools are deferred in the subagent harness, have it discover `cctxNative*` or `code-context-code_*` via `tool_search` first. - Optional: patch local subagent definitions into compact BPE-aligned formula specs so every subagent turn saves ~`63.1%` of instruction overhead: Terminal window ``` cctx --root /path/to/project prompt --style formula --target instructions ``` ## 5. Inspect live token & cost savings (`cctx usage`) [Section titled “5. Inspect live token & cost savings (cctx usage)”](https://dotnetpower.github.io/code-context/quickstart/#5-inspect-live-token--cost-savings-cctx-usage) Monitor real multi-session telemetry—modeled AI Credit (`@ $0.001/AIC`) spend with versus without `cctx`, avoided tokens across turns/cache/BPE, warm cache hit rate, per-model breakdown, and actionable optimization advisories—directly from your terminal or the VS Code status bar: Terminal window ``` cctx usage --hours 24# Full 4-driver cost anatomy & session advisories:cctx usage --hours 24 --details# Machine-readable JSON output:cctx usage --hours 24 --json ``` Example `24h` multi-session summary (`159` sessions · `7,578` turns): ``` ⚡ CCTX USAGE · Last 24 hours 💰 $48.88 saved · 26.6% less (estimated) Without cctx ~$183.78 → With cctx $134.90 USD equivalent @ $0.001/AIC; not a bill. EFFICIENCY Tokens avoided ~1.58B Warm hits 95.5% · Source adoption 90.3% 💡 OPTIMIZATION ADVISORIES No optimization issues detected. MODELS · USD equivalent┌───────────────────────┬─────────┬───────────┐│ Model │ Used │ Est.saved │├───────────────────────┼─────────┼───────────┤│ Claude Opus (high) │ $78.40 │ $29.10 ││ GPT-6.1 (medium) │ $41.25 │ $14.85 ││ Claude Sonnet (med) │ $15.25 │ $4.93 ││ Total │ $134.90 │ $48.88 │└───────────────────────┴─────────┴───────────┘ Full report: cctx usage --hours 24 --details ``` Running `--details` decomposes why net dollar spend drops—showing that 54.0% (`851.8M tok`) comes from avoided LLM round-trip turns and 44.5% (`701.8M tok`, `98.7×`) comes from avoided prompt-cache re-reads, rather than single-output byte trimming (`0.5%`). See [Benchmarks & Net LLM Cost Analysis](https://dotnetpower.github.io/code-context/benchmarks/#5-net-llm-cost-analysis-24h-production-trace-replay) for the full cost equation. Continue to [Native VS Code & MCP Tools](https://dotnetpower.github.io/code-context/tools/) for full parameter schemas and rich document anchor syntax. ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs. --- Canonical: https://dotnetpower.github.io/code-context/tools/ # 7 Native VS Code & MCP Tools **Which native VS Code and MCP tools are available?**: Reference for 7 native VS Code and MCP tools: context, grep, read, files, status, sync, and workspaces, with inline budgets and document anchors. **Scope and evidence**: Local developer tooling, not a hosted source-search service. Benchmark results are workload-specific, not guarantees. Where can I verify the results and limitations? Read the [benchmark methodology](https://dotnetpower.github.io/code-context/benchmarks/), [architecture and privacy boundaries](https://dotnetpower.github.io/code-context/architecture/), and [technical FAQ](https://dotnetpower.github.io/code-context/faq/). Code Context exposes seven identical capabilities across three local transports: VS Code Native Language Model Tools (`dotnetpower.code-context-native`), Model Context Protocol (`cctx shared-mcp`), and the `cctx` CLI. ## Tool mapping overview [Section titled “Tool mapping overview”](https://dotnetpower.github.io/code-context/tools/#tool-mapping-overview) | VS Code `toolReferenceName` | Internal Native ID | MCP Tool | CLI Subcommand | Mutates Index? | | --- | --- | --- | --- | --- | | `#cctxNativeContext` | `code-context-native_codeContext` | `code_context` | `cctx --backend shared context` | Queues cold root nonblockingly | | `#cctxNativeGrep` | `code-context-native_codeGrep` | `code_grep` | `cctx --backend shared grep` | Queues cold root nonblockingly | | `#cctxNativeFiles` | `code-context-native_codeFiles` | `code_files` | `cctx --backend shared files` | Queues cold root nonblockingly | | `#cctxNativeRead` | `code-context-native_codeRead` | `code_read` | `cctx --backend shared read` | Live disk fallback + hash check | | `#cctxNativeStatus` | `code-context-native_codeStatus` | `code_status` | `cctx --backend shared status` | Never (purely observational) | | `#cctxNativeSync` | `code-context-native_codeSync` | `code_sync` | `cctx --backend shared sync` | Blocking full-source barrier | | `#cctxNativeWorkspaces` | `code-context-native_codeWorkspaces` | `code_workspaces` | `cctx workspaces` | Never (lists catalog) | ## 1. `#cctxNativeContext` / `code_context` (Primary Tool) [Section titled “1. #cctxNativeContext / code_context (Primary Tool)”](https://dotnetpower.github.io/code-context/tools/#1-cctxnativecontext--code_context-primary-tool) Searches saved source for a literal substring or regular expression and returns block-clamped surrounding code in a single round trip. - Key parameters: - `pattern` (required): Literal string by default; set `regex: true` for alternation (`foo|bar`) or regex patterns. - `root`: Explicit absolute workspace or Git worktree root. - `radius` (`0..100`): Requested context radius around matches, automatically clamped to clean function, struct, class, or heading boundaries so unrelated neighboring functions are excluded. - `limit` (`1..64`): Total match cap across the response. - `max_matches_per_file` (`1..64`): Caps noisy files and prioritizes symbol definitions (`fn`, `pub struct`, `class`, `def`, `interface`, `export function`, etc.) ahead of call-site noise. - `paths` / `glob` / `ignore_case`: Narrow scope to relative directory prefixes or file patterns. ### Supported polyglot block clamping [Section titled “Supported polyglot block clamping”](https://dotnetpower.github.io/code-context/tools/#supported-polyglot-block-clamping) Boundary clamping understands declarations and structural blocks across Rust, Python, TypeScript/JavaScript/JSX/TSX (React 19), Vue, Svelte, Go, Kotlin, Swift, Elixir, Ruby, SQL, Protobuf, Terraform, Makefile, Dockerfile, and Markdown. ## 2. `#cctxNativeGrep` / `code_grep` [Section titled “2. #cctxNativeGrep / code_grep”](https://dotnetpower.github.io/code-context/tools/#2-cctxnativegrep--code_grep) Fast trigram-indexed line search when you only need matching line numbers and text rather than surrounding code blocks. - Uses ASCII and UTF-8 case-folded trigram postings (`src/resident.rs`) plus an HIR literal extractor (`src/planner.rs`) to eliminate >99% of non-matching files before running `grep-regex`. - Pass `max_matches_per_file` (for example `5` or `10`) so generated or test fixtures cannot starve results from core modules, while keeping total output strictly below the `<8 KiB` host offload threshold. ## 3. `#cctxNativeFiles` / `code_files` [Section titled “3. #cctxNativeFiles / code_files”](https://dotnetpower.github.io/code-context/tools/#3-cctxnativefiles--code_files) Sub-millisecond filename and relative-path discovery against the in-memory workspace catalog. - Pass `glob` such as `"*.rs"`, `"*Service*.ts"`, `"**/*.test.tsx"`, or a bare stem. - Combine with `paths: ["src", "crates"]` and `limit` (`1..1000`). ## 4. `#cctxNativeRead` / `code_read` & Rich Document Anchors [Section titled “4. #cctxNativeRead / code_read & Rich Document Anchors”](https://dotnetpower.github.io/code-context/tools/#4-cctxnativeread--code_read--rich-document-anchors) Batched, SHA-256-verified 1-based inclusive line reads with transparent live-disk recovery if a file was just edited moments before watcher reconciliation. ### `<8 KiB` inline budget & pagination [Section titled “<8 KiB inline budget & pagination”](https://dotnetpower.github.io/code-context/tools/#8-kib-inline-budget--pagination) Host agent harnesses often offload tool outputs larger than `8 KiB` into temporary `/tmp` files, costing extra tool calls to inspect. Keep batched `ranges` to `<= 150` total lines for instant inline delivery, or pass `page: true` (and follow `next_ranges` until `complete: true`) for structured streaming pagination. ### Rich document virtual `#toc` & `#slide-N-M` anchors [Section titled “Rich document virtual #toc & #slide-N-M anchors”](https://dotnetpower.github.io/code-context/tools/#rich-document-virtual-toc--slide-n-m-anchors) `code_read` extracts clean, token-compact Markdown/text from binary and structured documents with zero external runtime dependencies (powered by an internal 9-bit $O(1)$ DEFLATE decoder that runs 5.4× faster): | Document Format | Supported Virtual Anchors | Token Savings | | --- | --- | --- | | Markdown (`.md`, `.mdx`) | `docs/REFERENCE.md#native-tools`, `#toc` | Reads exact section slug without loading whole file | | PowerPoint (`.pptx`) & ODP | `deck.pptx#toc`, `deck.pptx#slide-3`, `deck.pptx#slide-3-5` | -86.3% to -98.9% (hoists repeated slide headers/footers & compresses charts) | | Word (`.docx`), ODT & RTF | `spec.docx#toc`, `spec.docx#outline`, `spec.docx#architecture`, `{#bookmark}` | Jumps straight to heading or bookmark span | | Excel (`.xlsx`) & ODS | `metrics.xlsx#toc`, sheet & bounded table ranges | Prunes empty columns/rows automatically | | PDF, EPUB, Jupyter (`.ipynb`), SRT/VTT, XLIFF | `#toc`, page/cell/cue ranges | Clean text projection without raw JSON/XML markup tax | ## 5. `#cctxNativeStatus`, `#cctxNativeSync` & `#cctxNativeWorkspaces` [Section titled “5. #cctxNativeStatus, #cctxNativeSync & #cctxNativeWorkspaces”](https://dotnetpower.github.io/code-context/tools/#5-cctxnativestatus-cctxnativesync--cctxnativeworkspaces) - `#cctxNativeStatus` / `code_status`: Returns index state (`warm`, `loading`, `cold`), memory ceiling, cgroup v2 reserve, file counts, and latency telemetry without triggering background indexing. - `#cctxNativeSync` / `code_sync`: Waits for a full source synchronization barrier. Use only when proving exhaustive symbol absence across an entire workspace—never call `code_sync` before ordinary lookups. - `#cctxNativeWorkspaces` / `code_workspaces`: Lists registered roots, allowed directory scopes, globs, and active exclusion profiles. Next, see how [`pctx` probes, `cctx journal`, and `cctx prompt`](https://dotnetpower.github.io/code-context/probes-and-journal/) eliminate non-code token waste. ## Sources and limitations Measurements are from the repository's published benchmark fixtures, not a performance or billing guarantee. Hardware, workload, cache state and model pricing change results. This documentation site cannot search or read a visitor's local source code. Indexing is local; explicitly requested HTTP probes contact their supplied URLs.