TokenCap
Website · Docs · Downloads · Benchmarks · GitHub
AI coding agents waste tokens re-discovering your codebase. TokenCap stops that.
Run one command. Every AI session starts with full project context — ranked, budgeted, and ready.
npm install -g tokencap
tokencap make
The numbers
Measured on 100 real tasks from 9 open-source repositories in JavaScript, TypeScript, Vue,
Python, Go, Rust and Java. Each task is a real commit: the commit message is the task, the
files that commit changed are the answer key, and the repository is checked out at the
commit's parent, so the answer is not in the tree yet.
Tokenizer: js-tiktoken exact counts. Model: gpt-4o ($2.50/1M).
Naive grep-and-read: ████████████████████████ 382,258 tokens → $0.9556 / task
TokenCap task pack: █ 9,997 tokens → $0.0250 / task
Median task: 18.7× fewer tokens. Needed files present in the pack: 88%.
| Repo |
Language |
Tasks |
Naive avg |
TokenCap avg |
Median saving |
Needed files in pack |
| fastify-example-todo |
JavaScript (small) |
9 |
2,661 tok |
1,819 tok |
1.6× |
89% |
| full-stack-fastapi-template |
Python + TypeScript |
10 |
84,708 tok |
8,813 tok |
9.8× |
93% |
| flask |
Python |
12 |
120,974 tok |
11,301 tok |
11.6× |
87% |
| cobra |
Go |
12 |
149,229 tok |
9,373 tok |
14.4× |
92% |
| httpx |
Python |
12 |
203,638 tok |
11,180 tok |
19.4× |
96% |
| gin |
Go |
12 |
198,819 tok |
10,335 tok |
19.8× |
96% |
| gson |
Java |
12 |
389,410 tok |
12,142 tok |
35.0× |
75% |
| ripgrep |
Rust |
11 |
458,486 tok |
11,348 tok |
41.7× |
74% |
| hoppscotch |
TypeScript + Vue (large) |
10 |
1,956,661 tok |
11,842 tok |
184.6× |
82% |
What these numbers do and do not show:
- The saving grows with repository size. On a small repository a pack saves little; in 3 of
the 9 small-repository tasks it was larger than the naive read.
- Naive is every text file that matches at least one task keyword, read in full. It holds
the needed files 96% of the time. Against a stricter baseline, the 10 best-matching files,
the median saving is 7.5×, and that baseline holds the needed files 76% of the time.
- Needed files in the pack counts the files the real commit changed that are shown as code.
On average 73% of the exact lines the commit edited are in the pack.
- No model is called. This measures whether the context contains what the task needs, not
the quality of a model's answer.
benchmarks/fair/answer-eval.js runs that check with a
model of your choice; no result from it is published yet.
- Half the tasks were held out. 50 tasks were used while changing the code and 50 were not.
The held-out half scored 88% needed files and an 18.4× median saving.
- Scope. Measured on the task pack built by
tokencap ask "<task>" and the companion
bridge, at a 12,000-token budget.
Method, task list, and raw per-task results: benchmarks/fair/
Reproduce: node benchmarks/fair/fetch-repos.js <dir>, then node benchmarks/fair/run.js --repos <dir> --set all
These figures replace the earlier 12.2× claim; see Honest Numbers.
What it does
Run tokencap make --full in any repo. This is what you see:
$ tokencap make --full
TokenCap: Full build requested.
TokenCap snapshot written: ./.tokencap/snapshot.md
Included files: 47
Snapshot bytes: 198,432
Estimated tokens: 49,608
Profile: balanced
AI summary: .tokencap/graph/ai-graph-summary.md
Interactive graph: .tokencap/graph/graph.html
Knowledge graph written: .tokencap/graph/summary.md (47 nodes, 83 edges)
Memory layer written: .tokencap/memory/current.md
Security engine: active (redaction engine v1)
Agent pointers written: AGENTS.md, CLAUDE.md, .cursor/rules/tokencap.md,
.windsurf/rules/tokencap.md, .clinerules/tokencap.md,
.github/copilot-instructions.md, .kiro/steering/tokencap.md
── TokenCap Savings ─────────────────────────────────────
Profile: balanced
Naive: ████████████████████████ 146,702 tok $0.3668
TokenCap: ████████████████ 49,608 tok $0.1240
Saved: 97,094 tokens (66.2%) $0.2428
─────────────────────────────────────────────────────────
Every major AI host (AGENTS.md, CLAUDE.md, .cursor/rules/, and 4 more) now points to .tokencap/agent/START_HERE.md. The next session starts with full project context — no re-discovery, no wasted tokens.
How it works
Your repo
│
▼
tokencap make
│ ├─ Ranks every file by git recency, importance score, and in-degree
│ ├─ Enforces a token budget (default: 220 KB source)
│ └─ Writes .tokencap/savings.json ← exact before/after token counts
▼
`.tokencap/snapshot.md` ← the managed capsule
AGENTS.md ← short start point for hosts that discover it automatically
.tokencap/savings.json ← machine-readable savings data
The capsule is not a full dump. It's a graph-ranked selection of the files that matter most for the current state of the repo — so the model gets signal, not noise.
Features (v3.1.0)
1. Explicit Learning for Better Task Scope (v3.1.0)
Improve the next task pack using only feedback you deliberately record. TokenCap
never reads chat transcripts, sends telemetry, or silently changes retrieval or
Constitution rules.
# Record whether the selected scope helped, plus selected or missed files.
tokencap analyze --learning --outcome helped --task "fix auth retry" \
--files src/auth/retry.js,src/auth/service.js
# Review the local evidence and recurring selected-file pairs.
tokencap analyze --learning
tokencap analyze --patterns
# Opt into bounded re-ranking for one task. Baseline candidates are preserved.
tokencap ask "fix auth retry" --adaptive
- Inspectable local ledger: bounded task labels and workspace-relative
paths live only in
.tokencap/learning/; no notes or conversation text are
stored. Task labels are redacted before they are written: secrets are
removed and any absolute path outside the workspace becomes [path].
- Evidence from the same task only:
--adaptive uses feedback whose task
shares its subject with the current one; generic words such as "fix", "bug"
or "add" do not make two tasks related. Files from a helpful pack get +0.75
per record and a reported missed file +0.5, capped at +2. Boosts re-rank
files retrieval already found; they never add a file on their own.
- Explicit rule feedback, never auto-rulemaking: record rule feedback with
tokencap analyze --learning --rule <id> --outcome <...>. TokenCap does not
detect when you override a rule; it only knows what you record. Propose,
approve, activate, or deprecate local learning rules explicitly. Activation
never edits the Constitution by itself.
- Advisory patterns:
analyze --patterns lists file pairs that appeared
together in two or more packs you marked helpful or harmful. A pair is a
hint about how you work, not a dependency or a rule, and it changes nothing.
- Companion feedback: after injection, Useful and Missed file write
the same explicit local evidence through the paired loopback bridge, and
--adaptive uses both.
- Controlled quality gate:
npm run eval:adaptive verifies recall is not
reduced and measures selected-file-token efficiency on a versioned fixture.
It is a reproducible regression gate, not a claim about every repository.
npm run eval:ledger runs a held-out check on your own repository's
feedback once it has 20 or more records.
2. Browser Companion Context Transfer (v2.8.0)
Bring local repository intelligence into browser-based AI chats without sending
your code to a remote service:
- TokenCap Companion: Pair the Chrome companion with
tokencap serve, select
an indexed local project, and inject a bounded, redacted task pack into
ChatGPT, Claude, or Gemini.
- Draft-Safe Injection: Existing composer text stays intact; TokenCap marks
its inserted context and refuses duplicate injection. Every generated pack can
also be previewed, copied, or downloaded.
- Fast, Bounded Local Bridge:
tokencap serve pre-warms shared intelligence.
Companion task packs stay in memory, include the project primer in their total
budget, and do not create a context artifact for each browser request.
- Reviewable Capture Loop: Browser captures are validated, redacted, staged,
and explicitly approved before becoming durable project memory.
3. Conversation-to-Repository Loop & Session Capture v1 (v2.7.0)
Turn finished AI coding sessions into small, redacted, reviewable handoffs — closing the conversation → repository loop without raw transcripts or telemetry:
tokencap serve session save: Stage and review session summaries (--summary, --files, --decision, --next).
- Staged, Never Silent: Inbound captures land in
.tokencap/memory/inbound/ with full provenance. Nothing modifies durable memory or ADRs until reviewed and approved via tokencap serve session save --approve <session-id> (or --reject / --note). Approved sessions archive to .tokencap/memory/sessions/.
- Graph-Grounded Quality Scoring: Captures are validated, bounded, redacted, and scored against the repository graph for path validity, groundedness, specificity, and novelty → confidence tier + evidence. Grounding evaluates references, not the truth of the summary.
- Handoff Surfaces:
tokencap serve session handoff exports the latest approved session as Markdown. Approved sessions surface in .tokencap/memory/current.md, agent-pack.md, and via MCP tools.
- Honest Host Support: Registry of 7 AI coding hosts (
tokencap serve session save --hosts). No host is marked "auto" without a verified session-end hook. MCP process shutdown is never treated as a conversation-end signal.
4. Repository Build Health & Diagnostics (v2.7.0)
tokencap analyze health: Produces an explainable 0–100 repository health score evaluating intelligence freshness, git drift, symbol detection completeness, and test coverage.
- Actionable Remediation: Reports granular deduction factors and prints exact remediation commands (e.g.
tokencap make --rebuild).
- MCP Integration: Build health is continuously surfaced in
tokencap_overview and status diagnostics.
5. Evidence-Rich Risk Findings & Python Dependencies (v2.7.0)
tokencap analyze risk: Normalized risk findings (oversized-file, todo-density, possible-secret) with confidence tiers, structural evidence, scope, and recommended actions.
- Persistent Acknowledgment: Mark findings with
--ack <id> or --dismiss <id>. Persistent state retains evidence without hiding findings from audits.
- Python
pyproject.toml Parsing: Automatic dependency detection for PEP 621 standard declarations and Poetry dependencies.
6. Watcher Controls & Session ROI (v2.7.0)
tokencap analyze watch-config: Manage persistent file watching behavior (--enable, --disable, --debounce <ms>, --ignore <glob>).
- Session ROI Tracking: Computes observed per-session token savings and financial ROI aggregated across hosts in
tokencap serve session list and MCP status.
7. High-Speed Loopback Bridge & Cold-Start Primer (v2.7.0)
Connect browser-based coding environments securely to local project intelligence:
tokencap serve: Isolated loopback HTTP bridge (127.0.0.1) with pairing authentication (--token, --port, --daemon, --stop, --watch, --no-open).
- Project Primer (
GET /primer): Provides a rich, human-written ~1.5k token orientation so a cold AI chat immediately understands the architecture, stack, and guidelines.
- Session Capture Endpoints:
POST /capture stages captures from companions; POST /capture/approve and POST /capture/reject manage reviews over loopback.
- Warm Reuse (~3× Faster): Reuses query-independent graph, memory, and diff artifacts across queries within a short TTL, dropping repeat
/generate response times from ~2.6s to ~0.8s.
- Model-Aware Dynamic Budgeting: Automatically scales task context to the target model's window (clamped between 4k and 24k tokens).
- Registry Hygiene & Zero Egress: Automatically prunes deleted directories from
GET /projects. Strictly zero network egress.
8. Multi-Language Tier-1 AST Call Resolution
TokenCap parses code using pure Tree-sitter WebAssembly (zero native toolchain):
- Full Call Resolution: JavaScript, TypeScript, JSX/TSX, Python, Go, Rust, and Java.
- Go / Rust / Java Extraction: Resolves Go selector and method calls, Rust
macro!/field/path calls, and Java constructor/method invocations.
- Precision Call Resolution: Resolves calls via import bindings, method receivers, and records unresolved symbols explicitly rather than guessing.
9. Static Taint & Security Flow Analysis
tokencap analyze taint: Intra-procedural forward taint tracking from sources (req.body, query, params, cookies, process.argv, env) to sinks (db.query, exec, eval, fs.writeFile, etc.).
- Evidence-Based Risk: Clear HIGH/MEDIUM risk categorizations with sanitizer detection, without executing code.
10. Database & GraphQL Schema Graphs
tokencap analyze schema: Parses SQL CREATE TABLE and GraphQL type schemas into a queryable relational graph, linking database models and types back to referencing application code.
11. Multi-Framework Component & SFC Graphs
- React & Next.js: AST-extracted
RENDERS component trees, declared vs. passed props flow, App/Pages router maps.
- Vue & Svelte (
.vue, .svelte): Single-file component (SFC) graphs with declared props and component render hierarchies.
12. Impact & Blast Radius Analysis
Know exactly what breaks before modifying or deleting a symbol:
$ tokencap ask impact src/auth/token.js:validateToken
Direct callers 3 symbols · 2 files
Transitive impact 17 symbols · 9 files
Crosses boundary src/api -> src/billing ⚠
Risk HIGH — exported, 17 dependents
tokencap ask impact --dead-code — lists uncalled, non-exported functions.
tokencap ask impact --clusters — computes Louvain functional communities and cross-cluster coupling.
13. Guided Safe Refactoring
Modify code safely with deterministic, refuse-on-doubt transformations:
# Preview changes (dry-run by default)
tokencap analyze refactor rename src/auth/token.js:validateToken checkToken
tokencap analyze refactor rm-dead src/util/helpers.js:unusedHelper
# Apply atomically once verified
tokencap analyze refactor rename src/auth/token.js:validateToken checkToken --write
- Safety by construction: Byte-exact outside the target edit ranges.
- Refuse-on-doubt: Aliased imports, shadowing, collisions, and computed accesses automatically block the plan.
14. Static Test Mapping & Gap Analysis
tokencap analyze tests # map symbols to exercising tests
tokencap analyze tests --gaps # list called-but-untested symbols
tokencap analyze tests --coverage coverage/lcov.info # ingest test reports (read-only)
15. Change Review & Local Ownership Signals
tokencap analyze review # review working-tree changes
tokencap analyze review --base main # compare Git base ref against HEAD
tokencap analyze ownership --history # opt-in local Git churn & author signals
Review packets include base-ref symbol evidence, caller candidates, test associations, and local Constitution/ADR context.
16. Evidence-Backed Code Simplification & Debt Ledger
tokencap analyze simplify # find unreachable code & duplicate artifacts
tokencap analyze debt # update TODO/FIXME/HACK/DEBT ledger
tokencap analyze compress AGENTS.md --write # prose-only safe Markdown compression
Install & Quickstart
npm install -g tokencap
Requirements: Node.js 18+, Git.
tokencap make # build + print savings summary
tokencap make --full # full rebuild (graph + brain + agent + pointers)
Command Reference
7 Core Commands
TokenCap v3.1.0 keeps the seven canonical commands and expands them through
focused subcommands and flags:
| Command |
Description |
tokencap make |
Build or refresh repository intelligence (--full, --watch, --rebuild, --migrate, --package, --scope, --max-memory-mb) |
tokencap ask <query> |
Task-scoped context pack (--adaptive re-ranks with explicit local feedback), ask brain <topic>, or ask impact <file>:<symbol> |
tokencap analyze <tool> |
Audit and analyze: review, diff, ownership, team, plugins, compress, tests, taint, schema, components, constitution, agent, simplify, stats, debt, health, risk, security, debug, refactor, feedback, verify |
tokencap serve |
Local loopback HTTP bridge for browser companions (--port, --token, --daemon, --status, --stop), session capture (serve session save \| list \| handoff), or MCP server (--mcp) |
tokencap update |
Check for updates and upgrade TokenCap safely |
tokencap help |
Built-in CLI reference and command guides |
tokencap version |
Print current TokenCap version (-v, --version) |
[!NOTE]
v3 removes standalone compatibility aliases. Running a former command returns
its canonical replacement; run tokencap make --migrate once after upgrading a v2
workspace, then run tokencap make.
Model Context Protocol (MCP)
TokenCap includes a built-in MCP server exposing 19 specialized tools over stdio:
tokencap serve --mcp --init # configure the detected AI client
tokencap serve --mcp --init --client claude-code # configure for a specific host
tokencap serve --mcp --health # test server diagnostics and tools
tokencap_overview — High-level summary, tech stack, and risk clusters.
tokencap_files — Query-relevant files, ranked the same way as tokencap ask.
tokencap_cluster — Deep intelligence on a specific functional cluster.
tokencap_dependencies — Upstream/downstream dependency trees.
tokencap_constitution — Rule constraints and invariants before coding.
tokencap_impact — Blast radius and broken invariants for proposed changes.
tokencap_execution — Phase-by-phase execution contract guidance.
tokencap_delta — Incremental changes since last build.
tokencap_search — Cross-layer search across all intelligence files.
tokencap_verify — Cluster-specific test, build, and lint commands.
tokencap_mcp_status — Live server diagnostics: uptime, cache hit rate, and per-tool call counts.
tokencap_manage_adr — Manage Architecture Decision Records (.tokencap/constitution/adr.json).
tokencap_get_screen — UI Map screen details and components.
tokencap_get_diagram — Local architecture, impact, or diff SVGs.
tokencap_simplify — Evidence-backed simplification candidates.
tokencap_refactor_plan — Dry-run preview of guided refactoring plans.
tokencap_test_map — Static test-to-symbol mapping and untested gaps.
tokencap_review — Advisory change review packets.
tokencap_ownership — Opt-in local Git history ownership signals.
Agent Host Compatibility
tokencap serve --mcp --init --client <host> records your selected host. Builds maintain that host's pointer file without overwriting custom edits:
| File |
Host |
AGENTS.md |
Codex, Antigravity, OpenCode, VS Code Codex |
CLAUDE.md |
Claude Code |
.cursor/rules/tokencap.md |
Cursor |
.windsurf/rules/tokencap.md |
Windsurf |
.clinerules/tokencap.md |
Cline / Roo Code |
.github/copilot-instructions.md |
GitHub Copilot |
.kiro/steering/tokencap.md |
Kiro |
VS Code & IDE Extensions
The VS Code extension provides commands to refresh Agent, Brain, Graph, and Memory intelligence independently, with automatic debounced capture on save.
code --install-extension .\tokencap-3.1.0.vsix
Codex and Claude Code Plugins
.\scripts\install-plugins.ps1
Security & Sovereignty
- Zero network egress — No telemetry, analytics, or remote calls. Only
tokencap update touches the network. Enforced by test/local-only.test.js scanning all source files on every test run.
- Secret redaction — Every file read passes through a centralized redaction engine before becoming output. API keys, tokens, PEM blocks, high-entropy strings are replaced with
[REDACTED:*] markers.
- Atomic writes —
.tokencap/savings.json and all cache files use tmp-then-rename to prevent partial reads or corruptions.
- Zero native dependencies — Tree-sitter parsers are shipped as pure WebAssembly (WASM), keeping package size under 10 MB.
Further reading
| Document |
Contents |
| Setup & Quickstart |
Installation, IDE wiring, MCP server setup |
| Documentation |
Complete command manual, AST parsing, and frontend intelligence |
| Benchmarks |
Raw benchmark data, methodology, and reproduction steps |
| Changelog |
Full version history |
License
MIT — see LICENSE.
| |