token-optimizer
Skill47 starsChanged 2 days agoApache-2.0View on GitHub
MANDATORY code inspection, architecture navigation, and live runtime verification skill. Activate whenever inspecting files, searching code, locating components/functions/classes, reading implementations, analyzing dependencies, navigating architecture, or interacting with live systems. Replaces wasteful terminal grep/find with zero-loss AST smart slicing (-90% tokens) and enables OUMV (Observe, Understand, Mutate, Verify) runtime verification across frontend and backend dev-servers.
- Reads credentials
27 other projects use a version of this.
Adopted by
Most recently taken up by
- mustafayilmazart/kesif-claude-skillstheir own version, first seen Nov 22, 2026
- aayushostwal/nexustheir own version, first seen Nov 20, 2026
- arturseo-geo/token-optimizer-skilltheir own version, first seen Nov 16, 2026
- tingyulu/MyR2D2their own version, first seen Nov 10, 2026
- blinkboxhq/Blinkboxtheir own version, first seen Nov 8, 2026
- ZhouYinLong-lab/Dog-Skillstheir own version, first seen Nov 8, 2026
Used with
Projects with it also use mcp-builder, webapp-testing and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
MicrosoftSkillmcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
Also in 4 projects that use this
JetBrainsSkillwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
Also in 3 projects that use this
SentrySkillskill-creator
Create new agent skills following the Agent Skills specification. Use when asked to "create a skill", "add a new skill", "write a skill", "make a skill", "build a skill", or scaffold a new skill with SKILL.md. Guides through requirements, writing, registration, and verification.
Also in 6 projects that use this
Other versions27 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 27
- alexgreensh/token-optimizer★ 3.2ksame name
- nitinjain999/platform-skills★ 71same name
- georgekhananaev/claude-skills-vault★ 32same name
- tingyulu/MyR2D2★ 20same name
- aayushostwal/nexus★ 19same name
- thesaifalitai/claude-setup★ 9same name
- GPire/claude-skills-swarm★ 8same name
- ZhouYinLong-lab/Dog-Skills★ 7same name
- samibajwaisking/Token-Optimizer-Skill★ 6same name
- amunozdev/token-optimizer★ 4same name
17 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository5 other files it gives its agents.
- AGENTS.mdAGENTS.md
- rules/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/tokensafe.mdcCursor rule
The file
Show its rules and text
We split this skill into the rules it gives an agent
17 rules. 0 are common, 3 are distinctive, and 14 are very specific to this project.
0
Common
Most of the 20 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 23
Mandatory Search Tool (
scoped_search): Call tokensafe:scoped_search(query, path=".", scope="code") for single searches … - Very specific: line 26
Call tokensafe:smart_read_file with path and symbol (dep_mode="signature" default, "full" for dependency bodies, "include_deps": false for …
- Very specific: line 33
Use view="api" for exported classes/types/interfaces, and view="tree" (depth=2) instead of ls -la.
- Very specific: line 36
Use tokensafe:apply_edits(edits=[...], verify="npm test") for >=2 hunks/files or edit + verify loops.
- Very specific: line 38
NEVER run sed -i, perl -i, awk -i on source code or suppress errors (2>/dev/null).
- Very specific: line 41
Never hardcode real private keys, API secrets, or credentials as fallback values in os.environ.get() or process.env.
- Very specific: line 61
Run unit tests via tokensafe tests [cmd] or tokensafe wrap '<cmd>' (1-line summary on pass, full traceback on failure).
- Distinctive: line 62
Never load raw screenshots into long (>150k) sessions.
- Very specific: line 90
Manual trigger: call tokensafe:compact_conversation with the session's transcript_path any time you need to shed context between subtasks — …
- Very specific: line 121
Call tokensafe:oumv(action="status") to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend …
- Distinctive: line 124
Never dump raw HTML or giant JSON payloads.
- Distinctive: line 132
Never guess state flows or assume dependencies.
- Very specific: line 133
Call tokensafe:oumv(action="understand", query="causality", target="POST /api/orders") to query live dependencies: Route ➔ Handler ➔ …
- Very specific: line 135
Call tokensafe:oumv(action="understand", query="impact", target="cart") before refactoring to know exactly what breaks.
- Very specific: line 139
For backend endpoints: call tokensafe:oumv(action="verify", target="POST /api/products", payload={...}) — executes in-memory with automatic …
- Very specific: line 140
For frontend UI: call tokensafe:oumv(action="verify", target="cart", verify_action="addItem", payload={...}) — executes synthetic …
- Very specific: line 151
When building greenfield applications with the TokenSafe ecosystem (tokensafe create or tokensafe init):
“Common” is measured: kept by at least 6 in 10 of the 20 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TokenSafe Optimization, Architecture & OUMV Runtime Skill
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 (UARP).
MANDATORY AGENT DIRECTIVES
- ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY
scoped_search):- Strictly NEVER run
grep,egrep,ripgrep, orfindinrun_commandon source code files (.ts,.tsx,.py,.js,src/,views/,components/). - Mandatory Search Tool (
scoped_search): Calltokensafe:scoped_search(query, path=".", scope="code")for single searches (mode="auto|text|regex|glob|fuzzy|git"), or passqueries=[{pattern, type, path, glob}]for up to 20 concurrent queries in <70ms.
- Strictly NEVER run
- SYMBOL, BUNDLE & EXTERNAL TYPE EXTRACTION (
smart_read_file):- Call
tokensafe:smart_read_filewithpathandsymbol(dep_mode="signature"default,"full"for dependency bodies,"include_deps": falsefor 0-hop isolation,"force_full": trueonly after compaction or as a fresh subagent). - Multi-Symbol Bundles: Pass
targets=[{path, symbol}](up to 8 targets) to merge skeletons and deduplicate shared imports in ONE call. - External
.d.tsTypes: Passpackage_name+symbolto slice 3rd-party TypeScript definitions fromnode_modules(-95% tokens). - Schema Auto-Slicing: OpenAPI/Prisma/GraphQL/SQL files auto-slice via
symbol(emptysymbolreturns an overview).
- Call
- ARCHITECTURE GRAPH, API SURFACE & DIRECTORY TREE (
repo_map):- First call
tokensafe:repo_map(view="graph", project_path=...)to inspect God Nodes and dependency hubs (<250 tokens) before reading files. - Use
view="api"for exported classes/types/interfaces, andview="tree"(depth=2) instead ofls -la.
- First call
- SURGICAL FILE EDITS (
apply_edits/edit_file) & STREAM GUARD (sed -iBLOCKED):- Use
tokensafe:apply_edits(edits=[...], verify="npm test")for >=2 hunks/files or edit + verify loops. - On existing files with >= 40 lines, wholesale rewrites via
write_fileare blocked by Output Guard. Useedit_fileorapply_edits. - NEVER run
sed -i,perl -i,awk -ion source code or suppress errors (2>/dev/null).
- Use
- SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS):
- Never hardcode real private keys, API secrets, or credentials as fallback values in
os.environ.get()orprocess.env.
- Never hardcode real private keys, API secrets, or credentials as fallback values in
- 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="metrics": cumulative savings analytics.
- UTILITIES (
run_helper):action="expand"(hash): restore full original text of a folded#hashblock.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:
- Run unit tests via
tokensafe tests [cmd]ortokensafe wrap '<cmd>'(1-line summary on pass, full traceback on failure). - Never load raw screenshots into long (>150k) sessions; delegate visual inspection to a subagent returning text-only findings.
- Run unit tests via
Core MCP Tools (tokensafe — 7 Consolidated Tools)
references/mcp-tools.md— Core MCP Tools table + JSON workflow examplesreferences/guard-checks.md— Security & Hygiene Guard check matrixreferences/cli-reference.md—tokensafeCLI command reference
Quick 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"|"metrics", ...)tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)tokensafe:run_helper(action="sanitize"|"guard"|"diff"|"deps"|"web"|"expand"|"image"|"compress", ...)
Context Governor & History Compactor
For long-running autonomous sessions, TokenSafe actively manages context bloat:
- Multi-Turn History Compaction & Post-Compaction Orientation Digest:
- At conversation turn >= 3, automatically compiles past turns into a lean Consolidated State Ledger paired with a deterministic 3-line Post-Compaction Orientation Digest (
1. Active Goal: ...,2. Last State: ...,3. Next Focus: ...). - Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise and preventing post-compaction amnesia.
- Manual trigger: call
tokensafe:compact_conversationwith the session'stranscript_pathany time you need to shed context between subtasks — it returns the ledger JSON, orientation digest, and exact token counts.
- At conversation turn >= 3, automatically compiles past turns into a lean Consolidated State Ledger paired with a deterministic 3-line Post-Compaction Orientation Digest (
- Subagent Deduplication Firewall:
- Caches file reads across subagents and sessions using SHA-256 content hashes. Interactive MCP clients receive self-healing pointer hits on unchanged repeat reads inside the same session; fresh subagents or post-compaction callers recover automatically with
force_full=true.
- Caches file reads across subagents and sessions using SHA-256 content hashes. Interactive MCP clients receive self-healing pointer hits on unchanged repeat reads inside the same session; fresh subagents or post-compaction callers recover automatically with
- Loop Guard:
- Detects repeated identical tool calls and triggers
force_askto prevent runaway infinite agent loops.
- Detects repeated identical tool calls and triggers
- Output Token Guard:
- Intercepts wholesale
write_filecalls on existing files with >= 40 lines to prevent expensive output token burn.
- Intercepts wholesale
LLM Prompt Cache Optimization
TokenSafe actively maximizes provider KV-cache hit rates alongside token compression:
- Append-Only Epoch Architecture: In proxy mode, past messages (
messages[0..N-2]) are never retroactively mutated within an epoch, preserving prefix cache hits. When cumulative context reaches 80% of the model's window, an atomic Epoch Rollover consolidates deep history into a State Ledger. - Multi-Breakpoint Cache Control:
PromptCacheNormalizersortstoolsdeterministically and places Anthropiccache_control: {"type": "ephemeral"}across tools, static system instructions, and the penultimate completed turn; OpenAI requests receive deterministicprompt_cache_key. - Deterministic Prefix Normalization: Ephemeral timestamps, hit counters, and session IDs are stripped from static prefixes, and
AgentFirewallheaders remain byte-deterministic across hits. - Parametric Prompt Template Caching:
DistillationCacheextracts file paths and symbols into positional slots (<FILE_0>,<SYM_0>) so structurally identical prompts hit L1/L2/L3 caches with 0 LLM roundtrips.
Universal OUMV Protocol (Runtime Introspection & Verification)
TokenSafe integrates the Universal Agent-Runtime Protocol (UARP / OUMV) to inspect, reason about, edit, and verify Frontend (tokensafe-ui, React 18/19 + Vite, Vue 3) and Backend (Go Gin/Chi/net-http, FastAPI) services without heavy headless browsers or unconstrained shell curls.
OUMV-First Policy, Zero-Footprint & Mixed Monorepos
- Mandatory When Supported (Even Without Dev/Build Running): If the workspace contains a supported profile (
frontend/react,frontend/vue,frontend/solid,backend/go,backend/fastapi,backend/node(Express/Fastify/Next.js),backend/elysia,backend/aspnetcore), prefertokensafe:oumv(status->observeL0/L1/L2 ->understandimpact ->mutate->verify) BEFORE brute-force reading components or runningcurl/browsers. Static OUMV works offline even when the agent only reads and edits files. - Zero-Footprint Vite+React (
tokensafe dev): Runningtokensafe dev(orvite/npm run devrewritten automatically byCommandSanitizer) starts the project's Vite+React DevServer withtokensafeReact()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. - Monorepo Capability Boundaries: In mixed monorepos (e.g.,
apps/webin React +apps/apiin Node.js/Express), checkoumv(action="status")or[TokenSafe OUMV Workspace Matrix]. Usetokensafe:oumv(runtime="frontend")for React, and userepo_map+smart_read_file+scoped_search+ normal tests for packagesoumv statusmarks unsupported (Nest/Hono/Koa, a Bun worker with no HTTP server).
- LIVE RUNTIME HEALTH (
oumv(action="status")):- Call
tokensafe:oumv(action="status")to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
- Call
- PROGRESSIVE CONTEXT OBSERVATION (
oumv(action="observe")):- Never dump raw HTML or giant JSON payloads. Observe progressively across native components, React, Vue, or backend APIs:
- L0 (Page Pulse ~20 tokens): Status, active route, mounted components/roots, error counts (
level="L0"). - L1 (Surface ~150 tokens): Interactive map of endpoints, models, buttons, and ARIA roles (
level="L1"). - L2 (Contract ~80 tokens): Targeted component state contract, props, Zod schema, or API DTO schemas (
level="L2", target="ModelName"). - L3 (Source): Targeted symbol source with line mapping and OCC version hash token.
- L4 (Traces): Event stream, signal mutations, store subscriptions (Zustand/Redux/Context updates), and state snapshot diffs.
- L0 (Page Pulse ~20 tokens): Status, active route, mounted components/roots, error counts (
- Never dump raw HTML or giant JSON payloads. Observe progressively across native components, React, Vue, or backend APIs:
- RUNTIME CAUSALITY & WHY-STATE (
oumv(action="understand")):- Never guess state flows or assume dependencies.
- Call
tokensafe:oumv(action="understand", query="causality", target="POST /api/orders")to query live dependencies:Route ➔ Handler ➔ ValidatesWith ➔ Model ➔ DB TableorSignal ➔ Computed ➔ Effect ➔ DOM Binding. - Call
tokensafe:oumv(action="understand", query="impact", target="cart")before refactoring to know exactly what breaks. Useaction="graph"for the cross-stack graph.
- SANDBOXED ACTION VERIFICATION (
oumv(action="verify")):- Sub-millisecond to low-millisecond local action verification inside transactional sandbox.
- For backend endpoints: call
tokensafe:oumv(action="verify", target="POST /api/products", payload={...})— executes in-memory with automatic DB rollback (rolledBack: true). - For frontend UI: call
tokensafe:oumv(action="verify", target="cart", verify_action="addItem", payload={...})— executes synthetic events/store actions in memory without browser automation.
- OPTIMISTIC CONCURRENCY MUTATIONS (
oumv(action="mutate")):- Submits surgical edits verified against
expectedVersionwith built-in Babel AST TSX/JSX syntax guards and security leak prevention. - Offline (no live runtime):
tokensafe:oumv(action="observe", level="L1", path="<file>")returns that file's symbols andfile.version; pass it asexpectedVersion. Asymboledit splices only that declaration (other declarations stay), an unknown symbol is refused, and a stale token returns-32001. - For a non-declaration range use
apply_editswithstart_line/end_line; for an unsupported stack (Bun/Elysia, worker, Node without an adapter)oumv(action="status")lists the package asoumvSupported: falseinstead of hiding it.
- Submits surgical edits verified against
Greenfield Ecosystem Architecture & Component Generation
When building greenfield applications with the TokenSafe ecosystem (tokensafe create or tokensafe init):
1. Frontend: tokensafe-ui
tokensafe-ui is a deterministic, token-efficient frontend framework designed for AI coding agents. It provides zero-bundle DOM parity, reactive state, and automatic OUMV introspection.
Component Anatomy (src/App.tsx / src/components/):
import { defineComponent, z, bind, h } from 'tokensafe-ui';
export const UserCard = defineComponent({
id: 'user-card',
// Zod-enforced reactive state (introspectable via oumv_observe L2)
state: {
username: z.string().default('Alice'),
active: z.boolean().default(true),
score: z.number().default(100),
},
// Pure actions for deterministic simulation in oumv_verify
actions: {
toggleActive: (s) => ({ ...s, active: !s.active }),
addScore: (s, delta: number) => ({ ...s, score: s.score + delta }),
setName: (s, username: string) => ({ ...s, username }),
},
// HyperScript rendering with required data-agent-id attributes for deterministic targeting
render: ({ state, emit }) =>
h('div', { class: 'card', 'data-agent-id': 'user-card:container' },
h('h2', { 'data-agent-id': 'user-card:title' }, state.username),
h('p', { 'data-agent-id': 'user-card:status' }, state.active ? 'Online' : 'Offline'),
h('button', {
'data-agent-id': 'user-card:btn-toggle',
onClick: () => emit.toggleActive()
}, 'Toggle Status'),
h('input', {
'data-agent-id': 'user-card:input-name',
...bind(emit.setName, state.username)
})
)
});2. Backend: tokensafe-python (FastAPI)
tokensafe-python instruments FastAPI services with UARP JSON-RPC 2.0 (/__oumv/rpc) and SQLAlchemy transactional sandboxes.
from fastapi import FastAPI
from pydantic import BaseModel, Field
from tokensafe_python.adapters.fastapi import mount_tokensafe
app = FastAPI(title="App API")
class TaskCreate(BaseModel):
title: str = Field(..., example="Implement feature")
done: bool = False
@app.post("/api/tasks", status_code=201)
def create_task(task: TaskCreate):
return {"id": 1, **task.model_dump()}
# 1-line UARP mounting: registers /__oumv/rpc, /__oumv/health, and writes .tokensafe/runtime.json
mount_tokensafe(app, port=8000)Proof-of-Savings Turn Footer (always in English)
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 Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)
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.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

