Skip to content
Back to skills

Token Optimizer

ASecurity

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.

  • 47 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 11, 2026
ai-agentstypescriptpythongoshellsqlreactvueangularnextjsnode

Works with

  • terminal
  • cli
  • api
  • mcp

Security analysis

A100/100

Pro scans all 4 files and shows the line behind each finding

Scanned December 5, 2026

npx -y skills add tokensafe-dev/tokensafe --skill token-optimizer --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Token Optimizer?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Token Optimizer
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/tokensafe-dev-token-optimizer/badge)](https://www.skillsdirectory.com/skills/tokensafe-dev-token-optimizer)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: token-optimizer
description: >-
  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.
---

# 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**.

---

## MANDATORY AGENT DIRECTIVES

1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY `scoped_search`)**:
   - Strictly NEVER run `grep`, `egrep`, `ripgrep`, or `find` in `run_command` on source code files (`.ts`, `.tsx`, `.py`, `.js`, `src/`, `views/`, `components/`).
   - **Mandatory Search Tool (`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.

2. **SYMBOL, BUNDLE & EXTERNAL TYPE EXTRACTION (`smart_read_file`)**:
   - Call `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).
   - **Multi-Symbol Bundles**: Pass `targets=[{path, symbol}]` (up to 8 targets) to merge skeletons and deduplicate shared imports in ONE call.
   - **External `.d.ts` Types**: Pass `package_name` + `symbol` to slice 3rd-party TypeScript definitions from `node_modules` (-95% tokens).
   - **Schema Auto-Slicing**: OpenAPI/Prisma/GraphQL/SQL files auto-slice via `symbol` (empty `symbol` returns an overview).

3. **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, and `view="tree"` (depth=2) instead of `ls -la`.

4. **SURGICAL FILE EDITS (`apply_edits` / `edit_file`) & STREAM GUARD (`sed -i` BLOCKED)**:
   - Use `tokensafe:apply_edits(edits=[...], verify="npm test")` for >=2 hunks/files or edit + verify loops.
   - On existing files with >= 40 lines, prefer `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`.
   - NEVER run `sed -i`, `perl -i`, `awk -i` on source code or suppress errors (`2>/dev/null`).

5. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
   - Never hardcode real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`.

6. **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.

7. **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.

8. **COMPACT TEST EXECUTION & MULTIMODAL ISOLATION**:
   - Run tests via `tokensafe tests [cmd]` (auto-detects the project runner) or `tokensafe 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.

9. **STRING CATALOGS / i18n (`dict`)**:
   - NEVER read a whole `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.
   - Get only the suspect keys: `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`.
   - Write back with `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.

---

## Core MCP Tools (`tokensafe` — 8 Consolidated Tools)

- [`references/mcp-tools.md`](references/mcp-tools.md) — Core MCP Tools table + JSON workflow examples
- [`references/guard-checks.md`](references/guard-checks.md) — Security & Hygiene Guard check matrix
- [`references/cli-reference.md`](references/cli-reference.md) — `tokensafe` CLI 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"|"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", ...)`

---

## Context Governor & Compaction

- **Headroom first**: `tokensafe:session_context(action="budget", model=...)`; act only on `measurement: "measured"` — `estimated` is a cumulative floor and never justifies compaction.
- **Fold history**: `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.
- Repeat reads of unchanged files return a pointer hit; a fresh subagent or a compacted context recovers with `force_full=true`.
- Repeated identical tool calls trip a loop guard; a wholesale `write_file` over an existing ≥40-line file is metered as re-emitted output — edit with `apply_edits` instead.

---

## Universal OUMV Protocol (Runtime Introspection & Verification)

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.

### 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`, `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.
- **Zero-Footprint Vite+React (`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.
- **Monorepo Capability Boundaries**: In mixed monorepos (e.g., `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).

1. **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).

2. **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.

3. **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 Table` or `Signal ➔ Computed ➔ Effect ➔ DOM Binding`.
   - Call `tokensafe:oumv(action="understand", query="impact", target="cart")` before refactoring to know exactly what breaks. Use `action="graph"` for the cross-stack graph.

4. **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="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.

5. **OPTIMISTIC CONCURRENCY MUTATIONS (`oumv(action="mutate")`)**:
   - Submits surgical edits verified against `expectedVersion` with 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 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`.
   - For a non-declaration range use `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.

---

## Greenfield: `tokensafe create` / `tokensafe init`

Scaffolds 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.

## 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**: +<tokens> tokens / <steps> steps | Total <total> tokens`

Call `session_context(action='turn')` once at the end of a tool-using turn and quote its `footer` field verbatim (it carries `saved_tokens`, `steps` and `total_measured_tokens`); write `n/a` for the turn fields only when `basis` is `unknown` — never estimate. If `session_context` is not attached in this session's tool list, never invent or carry over a `Total` or dollar figure; say "MCP not attached — run `tokensafe doctor --fix`" instead. There is no USD figure in the footer: cost is a dashboard/`savings` concern, never something the model derives per turn. Cumulative analytics distinguish `measured` (metered I/O delta) from `estimated` (counterfactual baseline) savings — see METRICS.md.

Files in this skill

  • SKILL.md5.5 KB
  • references/cli-reference.md1.6 KB
  • references/guard-checks.md2 KB
  • references/mcp-tools.md5.1 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.