Sub-millisecond polyglot AST dependency graph, speculative background test runner, pre-flight linter, and Merkle test cache for GitHub Copilot & AI coding agents.
Test Context (tctx) is a local Rust accelerator for Python (pytest + ruff), Rust (cargo test + clippy), Frontend (React, Vite, TypeScript/JavaScript, Vue/Svelte, CSS/SCSS, Vitest/Jest/Node test, ESLint/Biome), and Polyglot (C/C++, C#, Protobuf, GraphQL) workflows — built as the companion to code-context (cctx) for VS Code, GitHub Copilot, and CLI agents.
Live Documentation & Interactive Benchmarks: https://dotnetpower.github.io/test-context/
Instead of re-running entire test suites or paying interpreter/compiler startup costs on every edit, tctx maintains an in-memory polyglot AST reverse dependency graph, computes comment/whitespace-normalized Merkle dependency hashes (dep_hash), pre-checks modified files with Ruff / ESLint / Biome / Clippy, adapts concurrency to live CPU/memory/I/O pressure, and runs affected tests speculatively in the background as files are saved.
| Mode | Trigger | Typical Latency | Behavior |
|---|---|---|---|
instant_cache_hit |
All targeted/affected tests match live Merkle dep_hash |
< 1 ms (median 0.81 ms) |
Returns verified cached results immediately without spawning a runner |
hybrid_delta |
Subset of tests uncached or modified (0 ms post-edit) | ~108 ms median (leaf delta) |
Reuses cached passes, joins in-flight background work (Singleflight), prioritizes prior failures (Fail-First), and executes only the uncached delta |
affected_graph |
Reverse impact analysis + cached pre-flight lints | ~0.65 ms median |
Traverses compact u32 reverse adjacency lists with hop-ranked chains & file:row:col diagnostics |
ruff_fix: true |
Pre-flight auto-remediation (--ruff-fix) |
Inline before delta | Auto-fixes safe Ruff / ESLint / Biome lint & import issues before executing tests |
VS Code Native LM Tools (#tctxNative*) · MCP (tctx shared-mcp) · Drop-In CLI (tctx pytest / cargo-test / vitest / jest)
│
Unix Socket / WSL Native Bridge
▼
┌─────────────────────────────────────── tctx daemon (Rust) ───────────────────────────────────────┐
│ Adaptive Pressure Controller (PSI / loadavg / meminfo / cgroup v2 → 4 tiers, dynamic cargo -j) │
│ ┌──────────────────────────┐ ┌───────────────────────────┐ ┌───────────────────────────────┐ │
│ │ Polyglot AST Graph (u32) │ │ Speculative Worker & Pool │ │ WAL-Backed Merkle Cache │ │
│ │ • Py / Rs / TS / CSS / C │ │ • Singleflight + Fail-1st │ │ • SHA-256 dep_hash history │ │
│ │ • 2-hop barrel shake │ │ • Warm Pytest Zygote │ │ • Flaky-test quarantine │ │
│ │ • Streaming AST snapshot │ │ • Ruff/Clippy/ESLint/Biome│ │ • Portable CI cache bundles │ │
│ └──────────────────────────┘ └───────────────────────────┘ └───────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘
- Python (
pytest): Extractsimport x,from x import y, relative imports, multi-line parenthesized imports, in-function lazy imports,conftest.pyfixture hierarchies (connecting only tests that actually use a defined@pytest.fixtureorautouse/hook), andpyproject.toml/pytest.iniconfigs while excludingif TYPE_CHECKING:-only imports from false test invalidation. Uses zero-allocationPyAliasSetalias tracking and bounded nested f-string lexing (fail-closedpy_dynamic_importon extreme nesting). - Rust (
cargo test): Parsesmod foo;,#[path = "..."] mod, nesteduse crate::{...}trees,#[test]/#[tokio::test]/#[rstest]/#[test_case]symbols,#[ignore]/#[serial]attributes,tests/common/mod.rshelpers,build.rs, andinclude_str!/include_bytes!compile-time data dependencies. Decouples non-barrellib.rs/mod.rsmodule mounts (pub mod <child>;) and performs 2-hoppub usebarrel tree-shaking so shared types (use crate::Result) never couple unrelated sibling modules. - Frontend (
React/Vite/TS/JS/CSS/SCSS): Resolves ES/CJS/dynamicimport(...), excludesimport type/export type, tree-shakes nested barrel (index.ts/index.tsx) named and wildcard re-exports via zero-clone nestedHashMaplookups, and supportstsconfig.json(paths&extends),package.json(imports#subpath&exports), Vite asset queries (?raw,?url,?worker),import.meta.glob(...), Web Workers, SIMD-scanned CSS/SCSS@import/@use/@forward/partials (_tokens.scss), Next.js App Router (app/**/layout.tsx -> page.tsx), and Storybook*.stories.tsxplay interaction tests. - C/C++ / C# / Protobuf / GraphQL: Tracks C/C++
#include "..."/<...>across source-relative, workspace-root, andinclude//inc//src/directories (including nonstandard.incheaders, header-to-implementation linking,CMakeLists.txtscoping, and GoogleTestTEST/TEST_F), C#namespace/using/global using/using static/ aliases,[Fact]/[Theory]/[Test]/[TestMethod], and.sln/.csproj/Directory.Build.propsconfig isolation, plus.proto(import,import public,import weak) definitions and.graphql#importedges. - Cross-Language & Full-Stack Bridges (
O(1)BridgeProviderIndex):- PyO3 / Maturin: Links Rust
cdylib/[tool.maturin]/#[pymodule]crates to Python importers so editing a.rskernel marks dependent Pythonpytestfiles as affected alongside Rust unit tests. - Full-Stack API Routes: Links backend route definitions (
@app.get('/api/v1/orders')) to frontend tests callingfetch('/api/v1/orders')oraxios. - WebAssembly & Protobuf & React Context: Links Rust
#[wasm_bindgen]exports to frontend Wasm imports,.protoschemas to generated_pb2.py/_pb.tsconsumers, and ReactcreateContextproviders touseContextconsumers.
- PyO3 / Maturin: Links Rust
- Semantic AST Hashing (
semantic_sha256): Strips ordinary comments and non-semantic blank lines via SIMDmemchrfast paths so comment/formatting edits preservedep_hashand never invalidate cached test passes, while preserving directive comments (noqa,type:,pragma,eslint,@ts-,biome-, and Rust doctest fences). - Environment Variable & Data File Tracking: Tracks referenced
os.getenv,os.environ,env!,env::var,import.meta.env, andprocess.envkeys (including multi-line wrapped calls and scoped.envfiles) plus.json,.yaml,.toml,.sql,.snap,.golden,.csv, and.protodata files in each test's Merkledep_hash.
- 4-Tier Adaptive Resource Pressure Control (
pressure.rs): Reads Linux PSI (cpu/io/memory),/proc/loadavg,/proc/meminfo, and cgroup v2 limits via singleflight caching to dynamically scaleCARGO_BUILD_JOBS, parallel worker counts, child process niceness, watcher debounce intervals, and background pausing (Normal→Elevated→High→Critical) without penalizing single-file interactive saves. - Multi-Core Parallel Indexing & Streaming AST Snapshots: Parallelizes file reading, SHA-256 hashing, AST parsing, direct dependency resolution, and per-test Merkle BFS across worker threads (
std::thread::scope), persisting graphs via bounded 64 KiB streamingbincodesnapshots with fullu32edge bounds validation on load. - Zero-Clone Parent-Pointer BFS: Reverse impact analysis (
affected_tests,affected_modules,untested_modified_files) traverses contiguousu32adjacency arrays with flatparent_idpointers, reconstructing dependency chains only for matched test files. - Rust Multi-Target Precompilation & Indexed Demux: Pre-compiles
--liband--test <integration>targets in a single multi-corecargo test --no-runpass, filters with-- <mod_filters...>, and attributes test cases back to source modules inO(cases)via first-segment prefix indexing. - Hardened Warm Pytest Zygote: Materializes its content-addressed
0600worker script in a per-UID private directory (eliminating Linux128 KiBMAX_ARG_STRLENE2BIGerrors), pre-imports safe third-party packages (fastapi,pydantic,numpy,pandas,sqlalchemy, etc.) in a single-threaded fork-verified (/proc/self/statusfail-closed) parent process with reusableselect.poll(),PR_SET_PDEATHSIG,pid > 1process-group reaping, non-finite/circular JSON sanitization, and POSIX 8-bit exit-code preservation. - Hardened WAL, Security & Fault Tolerance:
O_NOFOLLOW+ regular-file verification across WAL, snapshots, metrics, and.gitignore; stack-encoded SHA-256 WAL checksums;import_bundlepath-traversal & orphan-quarantine guards; per-root singleflight load/worktree gates; automaticPoisonErrorrecovery andcatch_unwindisolation;O(1)incremental cache memory accounting; and automatic idle Zygote reclamation. - Watch Lifecycle Cleanup: Deleted or moved-out directory subtrees are unwatched and removed from the dependency graph, freeing watch capacity for recreated paths. Overflow recovery, periodic safety reconciliation, and explicit sync also prune missing watch directories.
- 7 Native VS Code Language Model Tools:
| Tool | Purpose |
|---|---|
#tctxNativeRun |
Run pytest, cargo test, vitest, jest, and node --test incrementally (< 1 ms cache hits, hybrid_delta, language_filter, ruff_fix) |
#tctxNativeAffected |
Discover tests transitively impacted by modified files or git diff, ranked by hop distance with cached lints |
#tctxNativeGraph |
Inspect imports, reverse importers, transitive dependencies, setup/conftest chains, cross-language bridges, and dep_hash |
#tctxNativeStatus |
Non-blocking daemon health, pressure tier, indexed counts, cache hit stats, background queue, and Zygote metrics |
#tctxNativeSync |
Synchronize the polyglot AST dependency graph with disk and schedule speculative background verification |
#tctxNativeInvalidate |
Invalidate cached results for specific files or the entire workspace |
#tctxNativeWorkspaces |
List explicitly registered workspace roots, scopes, globs, and detected runners |
- Rich Status Bar Hover Tooltip & Revision Caching: Live daemon polling with a Markdown dashboard tooltip (time saved, cache hit rate, ecosystem breakdown, adaptive pressure tier, Zygote RSS, and per-tool breakdown) cached by monotonic revision counter.
- Agent-Friendly Path & Root Resolution: Automatically strips workspace-root prefixes from absolute target paths (
/path/to/repo/src/daemon/tests.rs::test_fn -> src/daemon/tests.rs::test_fn), enforces strict../ NUL / control-character containment, and infers the active workspace root from target path hints,vscode-remote://URIs, Windows WSL UNC paths (\\wsl.localhost\...), and session history. - Smart Git-Dirty Delta Scoping: In large repositories (
> 64test files), omittingtargetsin#tctxNativeRunautomatically scopes execution to tests affected by uncommittedgit statuschanges rather than running thousands of unrelated tests. - Context Window Token Optimization (92.7% Reduction): Strips passing test boilerplate (
test ... ok, compiler progress lines) while preserving 100% of warnings, failures, and skips, and bounds large#tctxNativeAffected/#tctxNativeGraphoutputs to stay inline (< 8 KB) without/tmpfile offloading. - Culprit Attribution & CI Cache Sharing: Extracts workspace-local stack frames (
structured_failures), cross-referencesgit diffwith transitive dependencies to identifysuspected_culprit_files, exports JUnit XML / SARIF v2.1.0 reports, and supports portable CI cache bundles (cache-export/cache-import).
tctx learns invocation patterns routed through its Native, MCP, or CLI surfaces. Use tctx pytest, tctx cargo-test, tctx vitest, or tctx jest (or their symlinks tctx-pytest, tctx-cargo-test, tctx-vitest, tctx-jest) for drop-in CLI acceleration.
Across 8 independent daemon sessions (320 paired observations) on AKS Store Demo (src/ai-service) measured against the current release build:
| Task | TCTX off (pytest) |
TCTX on | Speedup [95% CI] |
|---|---|---|---|
Warm suite (warm_suite) |
1,125.77 ms | 1.18 ms (median 0.81 ms) | 957.44× [613.12, 1362.80] |
Post-edit background pre-run (bg_speculative) |
1,168.57 ms | 1.19 ms (median 0.86 ms) | 980.98× [812.85, 1171.15] |
Reverted edit Merkle hit (merkle_revert) |
1,141.21 ms | 4.27 ms (median 1.04 ms) | 267.21× [141.37, 627.02] |
Immediate 0ms-delay leaf edit (leaf_delta) |
1,156.31 ms | 135.45 ms (median 108.38 ms) | 8.54× [6.88, 9.89] |
Impact query + Ruff pre-check (affected_graph) |
1,096.90 ms | 0.86 ms (median 0.65 ms) | 1,274.04× [1054.57, 1506.24] |
Fixed mixed suite (all, 320 pairs) |
1,137.75 ms | 28.59 ms (median 0.89 ms) | 39.80× [32.22, 45.46] (1,132.71× median) |
| Scenario | Baseline / Unoptimized | With tctx |
Speedup / Improvement |
|---|---|---|---|
Enterprise monorepo (9,042 files, 3,434 tests) cold AST load |
6,047.38 ms | 670.33 ms (parallel multi-core build) | 9.0× faster cold load (-88.9%) |
Enterprise monorepo core module test_affected (67 affected tests) |
256.80 ms | 5.17 ms (u32 reverse_adj parent-pointer BFS) |
49.7× faster impact query |
Enterprise monorepo test_affected (2,363 affected tests) payload |
1,400,000 B (/tmp offloaded) |
5,320 B (hop-ranked inline < 8 KB) |
263× smaller inline payload |
4 Rust modules (25 unit tests) cold batch |
~5,800 ms (4× cargo test) |
1,254.64 ms (cargo test --lib demux) |
4.6× faster cold batch |
2 Rust modules (27 unit tests) targeted harness filter |
1,110.00 ms (full crate 53 tests) | 90.00 ms (-- <mod_filters...>) |
12.3× faster module run |
6 Rust files (53 unit tests) warm cache hit |
6,606.00 ms | 0.87 ms (instant_cache_hit) |
7,593× speedup |
Single Rust test node (src/runner.rs::demux_...) |
1,254.64 ms | 0.23 ms (cached_node) |
5,455× speedup |
See docs/BENCHMARKS.md or the GitHub Pages benchmark gallery for methodology, cold-start measurements, raw samples, and reproduction instructions.
# 1. Build and install tctx + user systemd service (or macOS LaunchAgent)
./scripts/install.sh
# 2. Register a Python, Rust, Frontend, or Polyglot workspace
tctx --root /path/to/repo register
# 3. Inspect daemon health, AST dependency graph, affected tests, or lint diagnostics
tctx --root /path/to/repo doctor
tctx --root /path/to/repo status
tctx --root /path/to/repo affected --file src/my_pkg/core.py
tctx --root /path/to/repo graph src/my_pkg/core.py
tctx --root /path/to/repo ruff --fix
# 4. Run tests incrementally across Python, Rust, and Frontend
tctx --root /path/to/repo run --ruff-fix
tctx --root /path/to/repo pytest -q
tctx --root /path/to/repo cargo-test
tctx --root /path/to/repo vitest
tctx --root /path/to/repo jest
# 5. Diagnose failures, export JUnit/SARIF reports, or share cache bundles in CI/CD
tctx --root /path/to/repo explain
tctx --root /path/to/repo run --report-format=sarif --report-out=results.sarif
tctx --root /path/to/repo cache-export --out=tctx-cache.json
tctx --root /path/to/repo cache-import --input=tctx-cache.json
# 6. Install Git pre-commit/pre-push hooks or authorize Git worktrees
tctx --root /path/to/repo hook-install
tctx --root /path/to/repo authorize-worktrees
# 7. Package and install the VS Code Native Extension (Linux & Windows WSL)
./scripts/install-vscode-extension.sh# Rust unit, integration, safety/cancellation tests & strict clippy
cargo clippy --all-targets --locked -- -D warnings
cargo test --locked
# Python benchmark parity & subagent configuration tests
python3 -m unittest discover -s tests -p 'test_*.py'
# VS Code extension lint, typecheck, unit tests & VSIX integrity verification
npm --prefix vscode-extension run lint
npm --prefix vscode-extension run check
npm --prefix vscode-extension test
npm --prefix vscode-extension run package
python3 scripts/verify_vsix.py vscode-extension/dist/test-context-native.vsix- Website & Docs: https://dotnetpower.github.io/test-context/
- Companion (
code-context/cctx): https://github.com/dotnetpower/code-context - Benchmarks Report: docs/BENCHMARKS.md
- VS Code Extension: vscode-extension/README.md
- License: LICENSE

