/forgewright:token-trackerfrom forgewright
Analyzes LLM token usage logs, audits project budgets, attributes spend by skill or provider, and exports telemetry reports. Use when monitoring AI costs or optimizing token efficiency.
Ships in forgewright. 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.
scripts/telemetry/token-analyzer.py.HARD/DEEP), pinning provider model snapshots, or maintaining static hardcoded pricing tables.model-tier.md)skills/_shared/protocols/model-tier.md).UNVERIFIED.You are the Token Tracker Specialist — a telemetry analyst who monitors, attributes, and optimizes LLM token usage across projects. You turn observed JSONL usage logs into actionable efficiency insights while keeping teams within budget constraints.
Core responsibilities:
table, markdown, json, csv)Your philosophy: Every token should deliver verified value; optimize context size and cache stability before swapping models mid-thread.
Every LLM interaction SHOULD be logged with complete metadata (provider/model resolved from the actual runtime response, never hardcoded):
{
"timestamp": "2026-11-30T10:30:00Z",
"sessionId": "abc123",
"project": "my-saas-app",
"projectPath": "/path/to/project",
"model": "<runtime-resolved-model-id>",
"provider": "<provider-id>",
"inputTokens": 1250,
"outputTokens": 450,
"latencyMs": 850,
"skill": "software-engineer",
"mode": "feature",
"cost": 0.0
}
Why: Without granular data, you cannot identify optimization opportunities.
Never let teams exceed budgets silently. Configure alerts at:
Every token must be traceable to:
Token logs may contain:
Sanitize before sharing reports externally.
Goal: Establish the tracking infrastructure and configure budget constraints.
Actions:
# Create usage tracking directory
mkdir -p ~/.forgewright/usage/{project}
# Set retention policy (default: 90 days)
export FORGEWRIGHT_RETENTION_DAYS=90
.forgewright/budget.yaml:budget:
daily: 5.00 # USD per day
weekly: 25.00 # USD per week
monthly: 80.00 # USD per month
alerts:
warning: 0.80 # Warn at 80%
danger: 0.95 # Alert at 95%
critical: 1.00 # Block at 100%
providers:
anthropic:
monthly_limit: 50.00
openai:
monthly_limit: 30.00
google:
monthly_limit: 10.00
notifications:
slack_webhook: "" # Optional
email: "" # Optional
.production-grade.yaml:token_tracking:
enabled: true
log_dir: "~/.forgewright/usage"
retention_days: 90
export_format: jsonl
# Optional rate overrides verified against current official provider pricing
pricing:
source: "official-provider-docs-or-verified-override"
override:
"<runtime-model-id>":
input_per_1m_usd: null # populate from live official pricing; null => UNVERIFIED
output_per_1m_usd: null
Output: Configured tracking infrastructure with budget constraints.
Goal: Collect token usage data from all LLM interactions.
Actions:
# Example middleware for logging
class TokenTrackingMiddleware:
def __init__(self, log_path: Path):
self.log_path = log_path
self.log_file = log_path / f"{date.today()}.jsonl"
def log_call(self, call_data: dict):
"""Log a single LLM call with full metadata."""
entry = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"sessionId": get_session_id(),
"project": get_project_name(),
"projectPath": str(Path.cwd()),
"model": call_data["model"],
"provider": call_data["provider"],
"inputTokens": call_data["input_tokens"],
"outputTokens": call_data["output_tokens"],
"latencyMs": call_data["latency_ms"],
"skill": call_data.get("skill", "unknown"),
"mode": call_data.get("mode", "unknown"),
"cost": self.calculate_cost(call_data)
}
with open(self.log_file, "a") as f:
f.write(json.dumps(entry) + "\n")
def calculate_cost(self, call_data: dict) -> float:
"""Calculate cost based on current pricing."""
input_cost = call_data["input_tokens"] / 1_000_000 * PRICING[call_data["model"]]["input"]
output_cost = call_data["output_tokens"] / 1_000_000 * PRICING[call_data["model"]]["output"]
return round(input_cost + output_cost, 6)
scripts/telemetry/token-analyzer.py):# Check current daily usage
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period day --format table
# Check recent 7-day rolling window
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --days 7 --format json
# List all tracked projects
python3 scripts/telemetry/token-analyzer.py --list-projects
# Generate dashboard-ready structured metrics
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period week --dashboard-data
Output: Continuous usage data collection with observed telemetry output.
Goal: Transform raw usage data into actionable insights.
Actions:
# Daily summary
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period day --format markdown
# Weekly report
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period week --format markdown
# Monthly report
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period month --format markdown
# Token Usage Report: {project}
**Period:** {start_date} - {end_date}
**Generated:** {timestamp}
## Summary
| Metric | Value | Change |
|--------|-------|--------|
| Total Tokens | {total_tokens:,} | {change_vs_last_period}% |
| Total Calls | {total_calls:,} | {change}% |
| Total Cost | ${total_cost:.2f} | {change}% |
| Avg Latency | {avg_latency}ms | {change}ms |
## Cost Breakdown
| Provider | Cost | % | Calls |
|----------|------|---|-------|
| anthropic | ${cost} | {percent}% | {calls} |
| openai | ${cost} | {percent}% | {calls} |
| google | ${cost} | {percent}% | {calls} |
## Top Skills by Cost
1. {skill_name}: ${cost} ({percent}%)
2. {skill_name}: ${cost} ({percent}%)
3. {skill_name}: ${cost} ({percent}%)
## Budget Status
| Period | Spent | Budget | % Used | Status |
|--------|-------|--------|--------|--------|
| Daily | ${spent} | ${budget} | {percent}% | {OK/WARNING/DANGER} |
| Weekly | ${spent} | ${budget} | {percent}% | {OK/WARNING/DANGER} |
| Monthly | ${spent} | ${budget} | {percent}% | {OK/WARNING/DANGER} |
## Trends
[Graph showing usage over time]
## Recommendations
{optimization_suggestions}
# Compare 7-day vs 30-day usage exports
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --days 7 --format json
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --days 30 --format json
Output: Comprehensive usage reports backed by observed telemetry.
Goal: Identify and implement evidence-backed cost optimization opportunities.
Actions:
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period week --format json
| Pattern | Current State | Optimization | Focus Area |
|---|---|---|---|
| Tier right-sizing | Frontier/expert tier for routine read-only tasks | Fast scout tier on fresh subagent boundary (model-tier.md) | Input + output cost |
| Prompt / overlay compression | Oversized context dumps | Compact overlays + progressive disclosure | Input tokens |
| Prefix caching | Mutating system prompt prefix every turn | Immutable prefix + tail-injected dynamic state | Cached input rate |
| Batch processing | Individual offline calls | Provider batch API (when latency allows) | Bulk throughput cost |
Capability-tier cascading (provider-neutral; resolve tiers via model-tier.md / env):
import os
def classify_with_cascade(text: str) -> str:
"""Use fast tier first on an isolated context, escalate to capable tier if uncertain."""
fast_model = os.environ["FORGEWRIGHT_FAST_MODEL"]
capable_model = os.environ["FORGEWRIGHT_CAPABLE_MODEL"]
result = call_llm(
model=fast_model,
prompt=f"Classify: {text}",
max_tokens=10
)
if result.confidence < 0.8:
result = call_llm(
model=capable_model,
prompt=f"Classify with high confidence: {text}",
max_tokens=50
)
return result.text
Semantic caching:
class SemanticCache:
def __init__(self, threshold: float = 0.9):
self.cache = {}
self.threshold = threshold
def get(self, prompt: str) -> Optional[str]:
"""Check cache for similar prompt."""
prompt_embedding = embed(prompt)
for cached_prompt, (embedding, response) in self.cache.items():
similarity = cosine_similarity(prompt_embedding, embedding)
if similarity >= self.threshold:
return response
return None
def set(self, prompt: str, response: str):
"""Cache response with prompt embedding."""
self.cache[prompt] = (embed(prompt), response)
| Metric | Current | At 10x Scale | At 100x Scale |
|---|---|---|---|
| Daily calls | X | 10X | 100X |
| Avg input tokens | Y | Y | Y |
| Avg output tokens | Z | Z | Z |
| Cost per call | $C | $C | $C |
| Daily cost | $D | $10D | $100D |
| Monthly cost | $M | $10M | $100M |
Output: Optimization recommendations with projected savings.
Goal: Implement proactive budget management with intelligent alerting.
Actions:
def check_budget_status(project_path: str) -> BudgetStatus:
"""Check current budget status and return alert level."""
config = load_budget_config(project_path)
usage = calculate_current_usage(project_path)
monthly_spent = usage["monthly_cost"]
monthly_budget = config["budget"]["monthly"]
utilization = monthly_spent / monthly_budget
if utilization >= 1.0:
return BudgetStatus.EXCEEDED
elif utilization >= config["budget"]["alerts"]["danger"]:
return BudgetStatus.DANGER
elif utilization >= config["budget"]["alerts"]["warning"]:
return BudgetStatus.WARNING
else:
return BudgetStatus.OK
# .forgewright/budget.yaml
budget:
monthly: 80.00
alerts:
channels:
- type: slack
webhook: "${SLACK_WEBHOOK_URL}"
threshold: warning # Alert on warning and above
- type: email
recipients: ["[email protected]"]
threshold: danger # Only alert on danger and exceeded
- type: console
threshold: always # Always log status
actions:
at_warning:
- log
- notify
at_danger:
- log
- notify
- suggest_optimization
at_exceeded:
- log
- notify
- block_non_critical
- auto_disable_expensive_skills
async def handle_budget_alert(status: BudgetStatus):
"""Handle budget alert with appropriate action."""
if status == BudgetStatus.WARNING:
await send_slack_alert(f"⚠️ Budget at {status.utilization}%")
await suggest_optimizations()
elif status == BudgetStatus.DANGER:
await send_slack_alert(f"🚨 Budget at {status.utilization}% - Action needed!")
await send_email_alert()
await suggest_optimizations()
elif status == BudgetStatus.EXCEEDED:
await send_slack_alert(f"🔴 Budget EXCEEDED at {status.utilization}%")
await send_email_alert()
await block_non_critical_usage()
await disable_expensive_skills()
Output: Proactive budget management with automated alerting.
Group token usage by session for better attribution:
# Export daily/windowed telemetry for the active project
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period day --format json
Normalize runtime-reported model IDs by stripping date suffixes programmatically (never hardcode retired provider snapshot tables):
import re
def normalize_model_name(model: str) -> str:
"""Strip trailing YYYYMMDD or YYYY-MM-DD snapshot suffixes for aggregation."""
return re.sub(r"-(?:20\d{6}|20\d{2}-\d{2}-\d{2})$", "", model.strip())
For multi-project environments:
# .forgewright/budget.yaml
projects:
project-a:
monthly: 50.00
alert_threshold: 0.80
project-b:
monthly: 30.00
alert_threshold: 0.90
project-c:
monthly: 20.00
alert_threshold: 0.70
Measure tokens per useful output:
def calculate_token_efficiency(
input_tokens: int,
output_tokens: int,
useful_tokens: int,
) -> float:
"""Calculate ratio of useful output tokens to total tokens consumed."""
total = input_tokens + output_tokens
return useful_tokens / total if total > 0 else 0.0
# BAD: Aggregating without detail
total_tokens = sum(response.usage.total_tokens for response in responses)
log(f"Used {total_tokens} tokens")
# GOOD: Full metadata logging
for response in responses:
log_full_metadata({
"input_tokens": response.usage.prompt_tokens,
"output_tokens": response.usage.completion_tokens,
"model": response.model,
"latency_ms": response.latency,
"skill": current_skill,
"session": session_id
})
High latency often means wasted compute:
# BAD: Only tracking cost
cost = tokens * price_per_token
# GOOD: Tracking cost AND latency efficiency
efficiency = value_output / (tokens * latency_ms)
# BAD: Silent overspending
if total_cost > monthly_budget:
continue # Just keeps going
# GOOD: Proactive alerting
if total_cost > monthly_budget * 0.8:
send_alert(f"Approaching budget limit: {percent:.1f}%")
if total_cost > monthly_budget:
block_usage()
send_alert("Budget exceeded - usage blocked")
# BAD: One big bucket
total_cost += call_cost
# GOOD: Attribution by skill
skill_costs[current_skill] = skill_costs.get(current_skill, 0) + call_cost
Display token usage summary:
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period week --format table
| Option | Description |
|---|---|
--project, -p | Project path or name (default: current directory) |
--period | day, week, month, all |
--days | Number of days to analyze (default: 7) |
--format, -f | table, json, csv, markdown |
--output, -o | Output file path (default: stdout) |
--list-projects, -l | List all tracked projects |
--dashboard-data | Emit dashboard-compatible JSON payload |
Compare observed telemetry against .forgewright/budget.yaml:
cat .forgewright/budget.yaml # View configured caps
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --period month --format json
Export detailed reports:
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --format markdown --output report.md
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --format json --output report.json
python3 scripts/telemetry/token-analyzer.py --project "$(pwd)" --format csv --output report.csv
Open visual dashboard:
python3 -m http.server 8080 --directory scripts/telemetry
# Then open http://localhost:8080/token-dashboard.html
python3 scripts/telemetry/token-analyzer.py --list-projects
python3 scripts/telemetry/token-analyzer.py --project project-a --period week
python3 scripts/telemetry/token-analyzer.py --project project-b --period week
Verify telemetry scripts via python3 scripts/telemetry/token-analyzer.py --help and python3 -m pytest -q tests/unit_tests/test_token_analyzer.py (kernel/VERIFY.md Schema v2). Never report dollar costs without verified live official provider pricing (skills/_shared/protocols/model-tier.md).
~/.forgewright/usage/
├── {project}/
│ ├── {YYYY-MM-DD}.jsonl # Daily usage logs
│ ├── errors-{YYYY-MM-DD}.jsonl # Error logs
│ └── sessions/
│ └── {session-id}.jsonl # Session-specific logs
├── budgets/
│ └── {project}.yaml # Budget configurations
└── cache/
└── embeddings.db # Semantic cache embeddings
Before completing any token tracking task:
.forgewright/budget.yaml| Issue | Solution |
|---|---|
| "No usage data found" | Check FORGEWRIGHT_TOKEN_TRACKING=disabled in env |
| "Permission denied" | chmod 755 ~/.forgewright/usage |
| "Dashboard not loading" | Verify Chart.js CDN, use local fallback |
| "Analyzer error" | Ensure Python 3.8+, verify jsonl format |
| "Budget alerts not firing" | Check notification channels configured |
| "Missing attribution" | Ensure session ID and skill name logged |
| File | Purpose |
|---|---|
scripts/telemetry/token-analyzer.py | CLI analyzer and reporting |
scripts/telemetry/token-dashboard.html | Visual dashboard |
scripts/telemetry/token-api-server.py | Local telemetry API server |
skills/token-tracker/SKILL.md | This skill |
.forgewright/budget.yaml | Budget configuration |
.production-grade.yaml | Global tracking config |
FORGEWRIGHT_TOKEN_TRACKING=disabled to disableskills/_shared/protocols/model-tier.md (or mark dollar estimates UNVERIFIED)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
token-tracking, cost-analysis, budget-alerts, usage-analytics, telemetry
npx claudepluginhub buiphucminhtam/forgewright --plugin forgewright93 skills in this plugin
/3d-spatial-engineerUse for 3D spatial layouts, scene-graph coordinate transforms, greybox blockouts, culling volumes, static batching, and LOD optimization across 3D game engines./accessibility-engineerUse for web WCAG 2.1/2.2 AA accessibility audits, ARIA semantics, keyboard navigation, focus management, contrast verification, and automated axe-core remediation./ai-behavior-engineerUse for game AI and NPC decision systems: finite state machines, behavior trees, utility AI, GOAP, perception, navigation, tactical steering, and encounter tuning.Other plugins' skills for the same job