/tokensafe:token-optimizerfrom tokensafe
Replaces terminal grep/find with AST-based code search, symbol extraction, and architecture navigation. Enables OUMV runtime verification across dev-servers.
Ships in tokensafe. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
TokenSafe is the zero-loss token economy, context governor, security engine, and runtime verification layer for autonomous AI coding agents.
It replaces brute-force terminal crawls (grep, find, cat) with deterministic AST symbol extraction,
folds multi-turn conversation history, guards against secret leaks, and standardizes live runtime interaction via the Universal OUMV Protocol.
ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY scoped_search):
grep, egrep, ripgrep, or find in run_command on source code files (.ts, .tsx, .py, .js, src/, views/, components/).scoped_search): Call tokensafe:scoped_search(query, path=".", scope="code") for single searches (mode="auto|text|regex|glob|fuzzy|git"), or pass queries=[{pattern, type, path, glob}] for up to 20 concurrent queries in <70ms.SYMBOL, BUNDLE & EXTERNAL TYPE EXTRACTION (smart_read_file):
tokensafe:smart_read_file with path and symbol (dep_mode="signature" default, "full" for dependency bodies, "include_deps": false for 0-hop isolation, "force_full": true only after compaction or as a fresh subagent).targets=[{path, symbol}] (up to 8 targets) to merge skeletons and deduplicate shared imports in ONE call..d.ts Types: Pass package_name + symbol to slice 3rd-party TypeScript definitions from node_modules (-95% tokens).symbol (empty symbol returns an overview).ARCHITECTURE GRAPH, API SURFACE & DIRECTORY TREE (repo_map):
tokensafe:repo_map(view="graph", project_path=...) to inspect God Nodes and dependency hubs (<250 tokens) before reading files.view="api" for exported classes/types/interfaces, and view="tree" (depth=2) instead of ls -la.SURGICAL FILE EDITS (apply_edits / edit_file) & STREAM GUARD (sed -i BLOCKED):
tokensafe:apply_edits(edits=[...], verify="npm test") for >=2 hunks/files or edit + verify loops.edit_file/apply_edits over a wholesale write_file: the Output Guard meters the re-emitted output and only blocks under TOKENSAFE_OUTPUT_GUARD=enforce.sed -i, perl -i, awk -i on source code or suppress errors (2>/dev/null).SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS):
os.environ.get() or process.env.SESSION & CONTEXT HYGIENE (session_context):
action="budget" (model=..., transcript_path=...): check window usage and Context Quality Score (Grade S–F).action="compact" (transcript_path=...): fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest.action="prune" (transcript_path=...): drop superseded intermediate file reads.action="mistakes" (project_root=...): query anti-stuck memory of prior dead-ends and reverts.action="recall_transcript" (query=... or id="<session>:<index>", scope="project"): BM25F search or turn drill-down over prior sessions.action="remember" / "recall" / "forget" (kind="decision"|"note"|"preference", text=..., files=[...]): machine-local project memory across sessions.action="metrics": cumulative savings analytics.UTILITIES (run_helper):
action="expand" (hash): restore the original text of a folded #hash block; a large block comes back paged — follow the offset in its footer.action="web" (url): fetch docs/pages as clean Markdown (L1/L2/L3 cached).action="deps" (package_name, lockfile_path): point lockfile lookup in <50 tokens.action="sanitize" (command, cwd): rewrite noisy shell/test commands.action="guard" (command/code, file_path): pre-flight security/hygiene audit.action="diff" (diff): slice unified diffs.action="image" (image_path, max_edge=1024): downscale oversized screenshots (-50-75% vision tokens).action="compress" (prompt): TOCP S-expression prompt compression.COMPACT TEST EXECUTION & MULTIMODAL ISOLATION:
tokensafe tests [cmd] (auto-detects the project runner) or tokensafe wrap '<cmd>' (1-line summary on pass, full traceback on failure).STRING CATALOGS / i18n (dict):
messages/<locale>/*.ts (or locales/*.json) catalog to review or edit translations: it is 100% payload, and one subagent per locale that each re-reads the English oracle is the single most expensive workflow we know.tokensafe dict lint --locale <l> --base en --json (MCP: run_helper(action="dict", command="lint --locale <l>")). Reasons: identical, missing, orphan, placeholder_mismatch, contains_english, glossary:<term>, length_ratio, duplicate, calque.tokensafe dict apply --locale <l> --patch patch.json --dry-run, then without --dry-run. Edits are byte-preserving: formatting, comments and key order stay untouched.smart_read_file on a catalog returns a digest on purpose; tokensafe dict show --locale <l> --keys a.b,c.d returns exact values, and expand_ref restores the raw file. Pass root="<project>" to run_helper when the server cwd is not the project.tokensafe — 8 Consolidated Tools)references/mcp-tools.md — Core MCP Tools table + JSON workflow examplesreferences/guard-checks.md — Security & Hygiene Guard check matrixreferences/cli-reference.md — tokensafe CLI command referenceQuick reference:
tokensafe:smart_read_file(path, symbol) / (targets=[...]) / (package_name, symbol)tokensafe:scoped_search(query, path=".", scope="code") / (queries=[...])tokensafe:apply_edits(edits=[...], verify="...")tokensafe:repo_map(view="graph"|"api"|"tree", project_path=".")tokensafe:session_context(action="budget"|"compact"|"prune"|"mistakes"|"remember"|"recall"|"forget"|"recall_transcript"|"metrics"|"turn", ...)tokensafe:oumv(action="status"|"brief"|"observe"|"understand"|"index"|"graph"|"mutate"|"preview"|"verify"|"build"|"cancel", ...) (full protocol: the oumv-protocol skill)tokensafe:run_helper(action="sanitize"|"guard"|"diff"|"deps"|"web"|"expand"|"image"|"compress"|"dict", ...)tokensafe:session_context(action="budget", model=...); act only on measurement: "measured" — estimated is a cumulative floor and never justifies compaction.tokensafe:session_context(action="compact", transcript_path=...) returns the ledger JSON, a 3-line orientation digest and exact token counts. Use it between subtasks, and action="prune" for superseded reads.force_full=true.write_file over an existing ≥40-line file is metered as re-emitted output — edit with apply_edits instead.TokenSafe integrates the OUMV protocol to inspect, reason about, edit, and verify Frontend (React/Vue/Solid/Angular + Vite via tokensafe-ui) and Backend (Go Gin/Chi/net-http, FastAPI/Starlette/Flask/Django, Express/Fastify/Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core) services without heavy headless browsers or unconstrained shell curls.
frontend/react, frontend/vue, frontend/solid, frontend/angular, backend/go, backend/fastapi, backend/node (Express/Fastify/Next.js), backend/elysia, backend/aspnetcore), prefer tokensafe:oumv (status -> observe L0/L1/L2 -> understand impact -> mutate -> verify) BEFORE brute-force reading components or running curl/browsers. Static OUMV works offline even when the agent only reads and edits files.tokensafe dev): Running tokensafe dev (or vite / npm run dev rewritten automatically by CommandSanitizer) starts the project's Vite+React DevServer with tokensafeReact() injected in memory and runtime state stored under ~/.tokensafe/runtimes/<hash>.json (sidecar L2 contracts in ~/.tokensafe/contracts/<hash>.json) — leaving 0 modified/untracked files in the repository.apps/web in React + apps/api in Node.js/Express), check oumv(action="status") or [TokenSafe OUMV Workspace Matrix]. Use tokensafe:oumv(runtime="frontend") for React, and use repo_map + smart_read_file + scoped_search + normal tests for packages oumv status marks unsupported (Nest/Hono/Koa, a Bun worker with no HTTP server).LIVE RUNTIME HEALTH (oumv(action="status")):
tokensafe:oumv(action="status") to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).PROGRESSIVE CONTEXT OBSERVATION (oumv(action="observe")):
level="L0").level="L1").level="L2", target="ModelName").RUNTIME CAUSALITY & WHY-STATE (oumv(action="understand")):
tokensafe:oumv(action="understand", query="causality", target="POST /api/orders") to query live dependencies:
Route ➔ Handler ➔ ValidatesWith ➔ Model ➔ DB Table or Signal ➔ Computed ➔ Effect ➔ DOM Binding.tokensafe:oumv(action="understand", query="impact", target="cart") before refactoring to know exactly what breaks. Use action="graph" for the cross-stack graph.SANDBOXED ACTION VERIFICATION (oumv(action="verify")):
tokensafe:oumv(action="verify", target="POST /api/products", payload={...}) — executes in-memory with automatic DB rollback (rolledBack: true).tokensafe:oumv(action="verify", target="cart", verify_action="invoke"|"click"|"submit", payload={...}) (verify_action is the action kind; the store action/handler name goes in target/payload) — executes synthetic events/store actions in memory without browser automation.OPTIMISTIC CONCURRENCY MUTATIONS (oumv(action="mutate")):
expectedVersion with built-in Babel AST TSX/JSX syntax guards and security leak prevention.tokensafe:oumv(action="observe", level="L1", path="<file>") returns that file's symbols and file.version; pass it as expectedVersion. A symbol edit splices only that declaration (other declarations stay), an unknown symbol is refused, and a stale token returns -32001.apply_edits with start_line/end_line; for an unsupported stack (Bun/Elysia, worker, Node without an adapter) oumv(action="status") lists the package as oumvSupported: false instead of hiding it.tokensafe create / tokensafe initScaffolds a tokensafe-ui frontend (Zod state, data-agent-id targets, OUMV introspection) and a tokensafe-python FastAPI service where mount_tokensafe(app) registers /__oumv/rpc + /__oumv/health and writes .tokensafe/runtime.json. Component and state conventions live in the tokensafe-ui package README — read it there instead of restating it in a prompt.
At the end of any response where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:
⚡ **TokenSafe**: +<tokens> tokens / <steps> steps | Total <total> tokens
Call session_context(action='turn') once at the end of a tool-using turn and quote its saved_tokens, steps and total_measured_tokens; write n/a for the turn fields only when basis is unknown — never estimate.
The USD figure is derived (tokens × $1.5/M blended rate) — an approximation for planning, never a bill. Cumulative analytics distinguish measured (metered I/O delta) from estimated (counterfactual baseline) savings — see METRICS.md.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub tokensafe-dev/tokensafe --plugin tokensafe2 skills in this plugin
Other plugins' skills for the same job