cost-tracking
affaan-m/ECC
ローカルのECCコストトラッカーのメトリクスログから、Claude Codeのトークン使用状況、支出、予算を分析します。サマリー、モデル別・セッション別・日付別の内訳、およびCSVエクスポート機能を提供します。
...すべて拡張しますコスト追跡
このスキルを使用して、ECCの`stop:cost-tracker`フックが書き込むメトリクスログから、
Claude Codeのコストおよび使用履歴を分析します。
データの保存場所
トラッカーは、セッションの停止ごとに1つのJSONオブジェクトを
~/.claude/metrics/costs.jsonl に追加します。各行はその
セッションの累積スナップショットであるため、総支出を算出するには、 session_idごとに最新の行を取り出し、
セッション間で合計します(すべての行を合計すると重複計上されます)。
行のスキーマ:
| フィールド | 意味 |
|---|---|
timestamp |
スナップショットのISOタイムスタンプ |
session_id |
Claude Code セッション識別子 |
transcript_path |
セッションのトランスクリプトへのパス |
model |
使用されたモデル |
入力トークン/出力トークン |
トークン数 |
cache_write_tokens/cache_read_tokens |
プロンプトキャッシュのトークン数 |
推定コスト(USD) |
セッションの事前計算済み累積コスト(USD) |
手計算による価格算出よりもestimated_cost_usdを使用することを推奨します。モデルやキャッシュの
価格は変動するため、トラッカーが信頼できる情報源となります。
使用すべき場面
- ユーザーが「これまでにいくら使ったか?」「このセッションの費用はいくらか?」「トークンの使用量はどれくらいか?」と 尋ねる場合
- ユーザーが予算、支出上限、超過、またはコスト管理について言及する場合。
- ユーザーが、モデル別、セッション別、または日付別のコスト内訳、あるいは CSV 形式でのエクスポートを希望する場合。
仕組み
まず、ログが存在することを確認します(sqlite3ではなくnode を使用してください。トラッカーは
JSONL を書き込むため、nodeの方がクロスプラットフォームに対応しています):
node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"コストログが見つかりました":"コストログが見つかりません: "+f)'
ログが見つからない場合は、使用状況データをでっち上げないでください。stop:cost-tracker
フックが有効な状態で最初のセッションが終了した後、コスト
追跡データが反映されることをユーザーに伝えてください。
例 — モデル別、過去7日間のサマリー
node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("コストログが見つかりません: "+f);process.exit(0);}
const rows=fs.readFileSync(f,"utf8").split(/\r?\n/).filter(Boolean).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean);
const bySession = new Map();
for (const r of rows) { const k = r.session_id || r.transcript_path || r.timestamp; const p = bySession.get(k); if (!p || String(r.timestamp)>String(p.timestamp)) bySession.set(k, r); }
const latest = [...bySession.values()];
const cost = r => Number(r.estimated_cost_usd) || 0, day = r => String(r.timestamp || "").slice(0, 10), sum = a => a.reduce((s, r) => s + cost(r), 0), f4=n=>"$"+n.toFixed(4);
const today=new Date().toISOString().slice(0,10), yest=new Date(Date.now()-864e5).toISOString().slice(0,10);
console.log("今日: "+f4(sum(latest.filter(r=>day(r)===today)))+" | 昨日: " + f4(sum(latest.filter(r => day(r) === yest))) + " | 合計: " + f4(sum(latest)) + " (" + latest.length + " セッション)");
const m=new Map();for(const r of latest){const k=r.model||"(unknown)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("モデル別:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log(" "+f4(v)+" "+k));
'
セッションの詳細表示やCSVエクスポートを行う場合は、同じ最新セット(またはCSV用の生
行データ)を反復処理し、必要なフィールドを出力します。
レポート作成の指針
コストデータを提示する際は、本日の支出と昨日の比較、全 セッションの合計、モデル別の内訳、およびセッション数を必ず含めてください。1ドル未満の金額は 小数点以下4桁、それ以上の金額は小数点以下2桁で表示してください。
アンチパターン
- すべての行を合計しないでください。これらはセッションごとの累積値であるため、まず
session_idごとに最新の 行に絞り込んでください。 estimated_cost_usdが存在する場合は、生のトークン数からコストを推定しないでください。- 確認せずにログが存在すると仮定しないでください。
- ユーザー向けの回答に、現在のモデル価格をハードコーディングしないでください。
- 審査されていないフックや、任意のコードを実行するプラグインのインストールを推奨しないでください。
関連
/cost-report- 同じメトリクスログに基づくコマンド形式のレポート。cost-aware-llm-pipeline- モデルルーティングおよび予算設計パターン。token-budget-advisor- コンテキストおよびトークン予算の計画。strategic-compact- トークンの重複消費を削減するためのコンテキストの圧縮。
---
name: cost-tracking
description: Analyze Claude Code token usage, spending, and budgets from the local ECC cost-tracker metrics log. Provides summaries, breakdowns by model, session, or date, and CSV export.
---
# Cost Tracking
Use this skill to analyze Claude Code cost and usage history from the metrics log
that ECC's `stop:cost-tracker` hook writes.
## Where the data lives
The tracker appends one JSON object per session-stop to
`~/.claude/metrics/costs.jsonl`. Each row is a **cumulative snapshot for that
session**, so to total spend you take the **latest row per `session_id`** and
sum across sessions — summing every row multiply-counts.
Row schema:
| Field | Meaning |
| --- | --- |
| `timestamp` | ISO timestamp of the snapshot |
| `session_id` | Claude Code session identifier |
| `transcript_path` | Path to the session transcript |
| `model` | Model used |
| `input_tokens` / `output_tokens` | Token counts |
| `cache_write_tokens` / `cache_read_tokens` | Prompt-cache token counts |
| `estimated_cost_usd` | Precomputed cumulative cost in USD for the session |
Prefer `estimated_cost_usd` over hand-calculating pricing — model and cache
prices change, and the tracker is the source of truth.
## When to Use
- The user asks "how much have I spent?", "what did this session cost?", or
"what is my token usage?"
- The user mentions budgets, spending limits, overruns, or cost controls.
- The user wants a cost breakdown by model, session, or date, or a CSV export.
## How It Works
First verify the log exists (use `node`, not `sqlite3` — the tracker writes
JSONL, and `node` is cross-platform):
```bash
node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"cost log found":"cost log not found: "+f)'
```
If the log is missing, do not fabricate usage data. Tell the user that cost
tracking populates after the first session ends with the `stop:cost-tracker`
hook enabled.
## Example — summary, by model, last 7 days
```bash
node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("cost log not found: "+f);process.exit(0);}
const rows=fs.readFileSync(f,"utf8").split(/\r?\n/).filter(Boolean).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean);
const bySession=new Map();
for(const r of rows){const k=r.session_id||r.transcript_path||r.timestamp;const p=bySession.get(k);if(!p||String(r.timestamp)>String(p.timestamp))bySession.set(k,r);}
const latest=[...bySession.values()];
const cost=r=>Number(r.estimated_cost_usd)||0, day=r=>String(r.timestamp||"").slice(0,10), sum=a=>a.reduce((s,r)=>s+cost(r),0), f4=n=>"$"+n.toFixed(4);
const today=new Date().toISOString().slice(0,10), yest=new Date(Date.now()-864e5).toISOString().slice(0,10);
console.log("today: "+f4(sum(latest.filter(r=>day(r)===today)))+" | yesterday: "+f4(sum(latest.filter(r=>day(r)===yest)))+" | total: "+f4(sum(latest))+" ("+latest.length+" sessions)");
const m=new Map();for(const r of latest){const k=r.model||"(unknown)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("by model:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log(" "+f4(v)+" "+k));
'
```
For a session drilldown or CSV export, iterate the same `latest` set (or the raw
rows for CSV) and print the fields you need.
## Reporting Guidance
When presenting cost data, include today's spend vs yesterday, total across all
sessions, a by-model breakdown, and session count. Format sub-dollar amounts
with four decimals, larger amounts with two.
## Anti-Patterns
- Do not sum every row — they are cumulative per session; reduce to the latest
row per `session_id` first.
- Do not estimate costs from raw token counts when `estimated_cost_usd` is present.
- Do not assume the log exists without checking.
- Do not hard-code current model pricing in user-facing answers.
- Do not recommend installing unreviewed hooks or plugins that execute arbitrary code.
## Related
- `/cost-report` - Command-form report over the same metrics log.
- `cost-aware-llm-pipeline` - Model-routing and budget-design patterns.
- `token-budget-advisor` - Context and token-budget planning.
- `strategic-compact` - Context compaction to reduce repeated token spend.
すべてのファイル
1件のファイルcost-trackingをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/affaan-m/ECC/tree/main/skills/cost-tracking # Copy SKILL.md to your .claude/skills/ directory
コピー





家
