What's New in v4.0
TokenSafe 4.0 is a major architecture release designed for Zero Mid-Day Lockouts, 3-Second Turn Latency, Exact Code Context (Zero Loss), and Developer Flow:
- ⚡ SQLite FTS5 BM25 Code Indexer & Search (
scoped_search, tokensafe search): Native SQLite full-text search with trigram tokenization and BM25 relevance ranking (\<1ms) across the repository. Replaces raw terminal grep entirely with zero-token-waste search.
- 🔗 SQLite Graph Cache & Cross-Boundary Route Linking: Persistent SQLite caching (
.tokensafe/cache/graph.db) with bidirectional semantic linking between frontend client endpoints (fetch, axios, apiClient) and backend HTTP routes (FastAPI, Express, Flask, Next.js).
- 🖼️ Vision Image Downscaler (
optimize_image, tokensafe optimize-image): Automatically scales down oversized screenshots, architecture diagrams, and mockups (>1024px) via Pillow or macOS sips, saving 50–75% vision tokens while keeping original files intact.
- 🧠 Anti-Stuck Dead-Ends Ledger (
get_mistakes, tokensafe mistakes): Persistent project memory tracking failed hypotheses, loop guard trips, and git reverts to prevent agents from cycling through already-failed solutions.
- 🧹 Transcript Superseded Output Pruning (
prune_superseded, tokensafe prune-superseded): Prunes obsolete intermediate tool reads that were superseded by subsequent edits or re-reads in long agent transcripts (-30-40% context).
- 🧼 ANSI Escape Sequence Stripper: Cleans all ANSI/VT100 escape codes from tool outputs, test runners, and proxy streams before they enter model context.
- 👻 Ghost Tokens Auditor (
tokensafe doctor): Detects and cleans redundant multi-IDE configuration files (.cursorrules, CLAUDE.md, .windsurfrules, .clinerules) and oversized rule files, saving 2,000–5,000 wasted ghost tokens on every turn.
- 🛡️ Exact Code Context & Reversible Stash (
expand_ref): 100% byte-exact target symbol preservation with reversible 8-char hash anchors (#a1b2c3d4) to instantly recover any folded block.
- 🌲 C# Tree-sitter Support: Native AST slicing and God Nodes detection for C# (
tree-sitter-c-sharp) alongside TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, and PHP.
Install & Agents
Connect TokenSafe to the AI coding agents on your workstation in one command:
# Option 1: Zero-Install via npx (recommended)
npx tokensafe
# Option 2: Python / PyPI
pip install tokensafe && tokensafe
# Option 3: Direct shell script (macOS / Linux)
curl -fsSL https://tokensafe.dev/install.sh | bash
The installer detects which agents live on your machine, registers the TokenSafe MCP server, injects project rules, and wires lifecycle hooks where the agent supports them.
| Agent |
Integration |
| Google Antigravity |
Plugin symlink + hooks + skills + MCP (loaded automatically on startup) |
| Claude Code CLI |
MCP + SessionStart / UserPromptSubmit / PreToolUse hooks |
| Cursor |
MCP + beforeShellExecution / beforeReadFile hooks |
| Claude Desktop |
MCP registration (claude_desktop_config.json) |
| Windsurf |
MCP registration + global rules |
| OpenAI Codex |
MCP in ~/.codex/config.toml (stdio + cloud HTTP natively) |
| Cline / Roo Code |
MCP registration (VS Code) |
| GitHub Copilot |
MCP registration |
| Z.ai Code |
MCP registration |
| Kimi Code |
Native Plugin (kimi.plugin.json) + MCP + PreToolUse / SessionStart hooks |
| ChatGPT |
Cloud connector, nothing to install |
Claude Desktop / Cursor MCP config:
{
"mcpServers": {
"tokensafe": { "command": "npx", "args": ["-y", "tokensafe", "mcp"] }
}
}
Cloud features (team metrics, managed distillation, shared team cache, billing) run on the remote endpoint https://api.tokensafe.dev/mcp with Authorization: Bearer <TS2. license key>. Four public tools work without a key, so ChatGPT connects with authentication set to None.
Full per-agent configuration, hook details, and the Codex/ChatGPT setup live in docs/AGENT_SETUP.md.
CLI Quickstart
# View live savings dashboard in your terminal
tokensafe stats
⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD
Total Tokens Saved: 4,524,156 tokens
Efficiency Gain: [████████████████████████░░] 92.5%
Context Traffic: 4,889,255 raw → 370,574 optimized (2,132 events)
• Command Sanitizer (CLI) : 727,300 tokens saved (263 events)
• Architecture Graph : 758,256 tokens saved (13 events)
• Multi-turn History Fold : 2,897,897 tokens saved (471 events)
• Prompt Compactor (local+cache) : 43,502 tokens saved (1,255 events)
# Audit your environment: MCP tool overhead, skills tax, risky settings
tokensafe doctor
# Recursive security & hygiene audit of a repository
tokensafe guard audit
# Preview prompt compaction on custom input
tokensafe test "fix the validate_token method in src/auth.py to check jwt expiration"
# Map architectural hotspots before multi-file changes
tokensafe graph
# Disable a heavy MCP server without editing JSON
tokensafe mcp disable <server>
# Compile and preview the Friday team ROI digest
tokensafe digest
# Activate a Team or Solo license key
tokensafe activate TS2.eyJlbWFpbCI6...
The full command reference (24 commands) is in Reference.
Why TokenSafe
Giving coding agents raw access to entire repositories creates three daily costs:
- Senior hours burned on AI PRs: reading 2,000-line modules for a 10-line fix makes models forget imports, invent methods, and regress adjacent code.
- Secret leaks and unsafe shortcuts: static prompt rules in
.cursorrules wear off mid-session. Agents hardcode fallback credentials, disable TLS checks, or stage .env files with git add ..
- Mid-sprint quota stops and blind spend: bloated diffs, lockfiles, and verbose MCP schemas burn 5-hour limits while engineering leads lack per-seat ROI visibility.
| Outcome |
What changes for your team |
How it is enforced |
| Clean code on the first pass |
Agents read only target functions, design tokens, and 1-hop dependencies instead of 2,000 lines of noise. |
Sub-30ms local AST skeletonizer, architecture graph, predictive signature prefetch, lockfile-stripping diff slicer, loop guard. |
| Zero leaked secrets in git |
Hardcoded password fallbacks, TLS bypasses, raw SQL interpolation, and .env commits are stopped before reaching disk or staging. |
Deterministic TokenSafe Guard on every tool call, output guard on large writes, local PII/key redaction. |
| Predictable sprint velocity & ROI |
Teammates get warm cache hits, and CTOs receive a Friday ROI digest separating measured and estimated savings. |
Shared team cache, live context budget HUD, per-seat dashboard. |
A $29 seat pays for itself by saving one hour of senior code review or preventing one leaked key. Typical payback: 1 to 3 days of team usage.
Before and After
One contrast: an agent asked to change one helper in a 1,420-line file receives 94 lines of target logic and type contracts instead of the whole module. The same principle applies to terminal output, diffs, and session history.
| What breaks coding agents |
How TokenSafe fixes it |
The outcome |
| "Lost in the Middle" context fade: an agent reads a 2,000-line file to change one 10-line helper, forgets imports, and invents methods. |
AST skeletonizer folds inert bodies into typed signatures while keeping the target symbol and 1-hop callees intact. |
Focused signal: the model keeps full type contracts without drowning in unrelated logic. |
Terminal log flooding: npm test or pytest fails and dumps 4,000 lines of stack traces and lockfile diffs into context. |
Command sanitizer strips lockfile noise and trims output to the failing assertion and stack frame. |
Root-cause fixes instead of unrelated rewrites. |
Infinite wait on background tests: yarn test hangs in watch mode, or jest finishes but unclosed handles keep the process alive. |
Test-runner guard forces run-once mode (CI=true, --watch=false, --forceExit) and peeks at <cwd>/package.json to identify the runner behind opaque scripts. |
The test run terminates with an exit code and the agent moves on. |
| 5-attempt retry loops: an agent repeats the same broken edit until the context budget runs dry. |
Loop guard detects repeated identical tool calls and halts the cycle. |
Stuck loops stop before damaging working modules. |
Unsafe edits & secret leaks: fallback keys, verify=False, SQL string interpolation, or git add . with .env present. |
TokenSafe Guard audits writes and shell commands locally before execution. |
Credentials, SQLi patterns, and destructive commands are blocked locally. |
When an operation is blocked, the agent sees an explicit, constructive message:
🛡️ TokenSafe Guard: Blocked a hardcoded secret fallback in config.py.
Leave the default empty or read from os.environ at runtime.
10 Core Engine Capabilities
Why TokenSafe agents ship working code on the first pass without burning quotas or leaking keys:
| Capability |
What it solves |
How it works |
Impact |
1. Architecture Graphget_architecture_graph |
Agents open an unfamiliar repo and burn 45k tokens blindly crawling files. |
Analyzes dependency centrality, import hubs, and critical call paths in memory. |
< 250 tokens to map God Nodes (vs ~45k blind crawl) |
2. Smart Code Slicingsmart_read_file |
Feeding 3,000 lines into context causes models to hallucinate fake methods. |
Preserves target method logic while folding uncalled helpers into typed contracts. |
-95.0% tokens (192 vs 3,840) across 11 languages |
3. Pre-Git Security Guardguard_inspect |
Autonomous agents read .env secrets or hardcode fallback keys in edits. |
Sub-millisecond pre-flight interception blocks secrets, TLS bypasses, and dangerous commands. |
0 leaked keys in LLM logs or git history |
4. Lockfile & Noise Shieldschema_slicer |
Reading package-lock.json or uv.lock dumps 360k+ tokens in one turn. |
Intercepts lockfiles and massive schemas, returning a queryable dependency summary. |
-99.8% tokens (855 vs 367,410 tokens) |
5. Monorepo API Surface Mapget_api_surface |
Agents guess interfaces or crawl dozens of modules to find exported types. |
Extracts all exported types, interfaces, and contracts across the repo in one pass. |
1 tool call vs 50 separate file reads |
6. Subagent Pointer CacheSUBAGENT_DEDUP |
Multi-turn chats and swarms pay full price to re-read the same shared utilities. |
In-memory content hashes return 1-line pointer hits for unchanged files. |
0 tokens wasted on repeat file reads |
7. Shared Team Cacheteam_cache |
10 to 50 engineers repeatedly parse the same core libraries from scratch. |
L3 monorepo pool shares stripped signatures and package contracts across teammates. |
72% team hits with 0ms turnaround |
8. KV-Cache Prefix Lockingcache_normalizer |
Shifting timestamps and reordered tools break provider prompt cache hits. |
Locks prefix order, sorts schemas, and injects breakpoints for Anthropic, DeepSeek, and OpenAI. |
92% cache hit rate at 0.10x provider rates |
9. Compact Test Runnersanitize_command |
Test suites spew 1,000 lines of passing dots that crowd out instructions. |
Forces run-once mode (CI=true) and collapses passing runs to a single line. |
1 line vs 1,200 lines (traces kept on failure) |
10. Context Governor & Ledgercompact_conversation |
Models suffer needle-in-a-haystack amnesia after 70% context saturation. |
Monitors context thresholds and compacts chat sprawl into an actionable State Ledger. |
50+ turns without regression or amnesia |
Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in docs/ARCHITECTURE.md.
Benchmarks
Reference run across 10 production engineering scenarios (169,761 baseline tokens down to 8,173 tokens, -95.2% net context reduction, -99.4% peak single-scenario reduction, +30.6% turn latency speedup with 100% accuracy retention):
Prompt compaction, graph topology (SWE-06), dep_mode="signature" slicing (SWE-07), repeat-read pointer dedup (SWE-09), and parametric slot cache hits (SWE-10) are measured live (1,368 optimized tokens) while baselines (169,761), turn counts, and output estimates (6,805 tokens) are modeled constants. See METRICS.md and BENCHMARK_REPORT.md.