cost-counterfactual — скилл для Claude Code: обзор и установка
Скилл cost-counterfactual сравнивает реальные траты на сессии с гипотетическими сценариями always-haiku, always-sonnet и always-opus. Помогает понять, окупается ли роутер моделей.
MIT 249 установок ★ 82 234 обновлён 2026-11-01
npx skills add ruvnet/ruflo --skill cost-counterfactual -a claude-codeЧто делает cost-counterfactual
Скилл анализирует записи session-* из пространства имён cost-tracking. Он суммирует объёмы токенов по сессиям, а затем пересчитывает траты по фиксированным тарифам базовых моделей. Разница между гипотетической суммой и фактическим счётом показывает чистый выигрыш маршрутизатора.
Инструмент запускается через Bash. Аргумент --since задаёт временное окно, а флаг --format json готовит вывод для парсинга через jq. Такой скрипт подходит для шагов CI, где нужно проверять минимальную долю экономии перед выкаткой новых правил.
Отрицательная экономия относительно Haiku указывает на завышение планки качества. Расчёт игнорирует успешность выполнения задачи и возможные повторные вызовы дешёвых моделей, поэтому итоговые показатели задают лишь теоретический предел выгоды.
Какие задачи решает
- оценить финансовую отдачу от маршрутизации запросов
- выявить избыточные переключения на дорогие модели
- отслеживать регресс экономии в пайплайне CI
- сопоставить реальный расход с единым тарифом Sonnet
Примеры запросов агенту
- Запусти анализ cost-counterfactual за последние 7 дней в виде таблицы
- Проверь эффективность маршрутизации через cost-counterfactual против baseline always-sonnet
- Выведи метрики cost-counterfactual в формате json за прошлую неделю
Как установить cost-counterfactual
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill cost-counterfactual -a claude-code2Вручную: положить файлы
~/.claude/skills/cost-counterfactual/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/cost-counterfactual/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill cost-counterfactual -a codex2Вручную: положить файлы
.agents/skills/cost-counterfactual/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill cost-counterfactual -a cursor2Вручную: положить файлы
.cursor/skills/cost-counterfactual/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install ruvnet/ruflo plugins/ruflo-cost-tracker/skills/cost-counterfactual2Вручную: положить файлы
.github/skills/cost-counterfactual/SKILL.md1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill cost-counterfactual -a gemini-cli2Командой платформы
gemini skills install https://github.com/ruvnet/ruflo --path plugins/ruflo-cost-tracker/skills/cost-counterfactualВручную: положить файлы
.devin/skills/cost-counterfactual/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill cost-counterfactual -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о cost-counterfactual
Как установить cost-counterfactual в Claude Code?
Выполните команду npx skills add ruvnet/ruflo --skill cost-counterfactual -a claude-code.
Что показывает анализ в cost-counterfactual?
Скилл рассчитывает, сколько стоили бы прошедшие сессии при отправке всех запросов только в Haiku, Sonnet или Opus. Разница с реальными затратами показывает точный процент экономии от маршрутизатора.
Что означает отрицательная экономия в отчёте?
Отрицательный результат по строке always-haiku означает, что роутер переключался на более дорогие модели в задачах, с которыми справился бы Haiku. Это признак избыточной эскалации или завышенной планки качества.
Исходный текст
SKILL.md · MIT
--- name: cost-counterfactual description: Multi-baseline counterfactual cost analysis. Compares actual session spend to hypothetical always-haiku / always-sonnet / always-opus routing baselines. Answers "is the routing earning its keep?" Negative savings flag over-escalation; positive savings quantify the router's win. argument-hint: "[--since 7d] [--baseline always-haiku|always-sonnet|always-opus|all] [--format table|json]" allowed-tools: Bash disable-model-invocation: true --- Multi-baseline counterfactual cost analysis. Pairs with the existing observability surface: - **`cost-budget-check`** — "have we crossed a threshold?" (reactive) - **`cost-projection`** — "when will we cross a threshold?" (predictive) - **`cost-counterfactual`** — "is the routing earning its keep?" (comparative) ← this one ## Algorithm 1. Read all `session-*` records from the `cost-tracking` namespace. 2. Apply `--since` window filter (default all-time). 3. Sum tokens across `byModel[*]` entries for each session. 4. For each requested baseline (default: all three): - `counterfactualUsd = (input × tier.input + output × tier.output + cache_write × tier.cache_write + cache_read × tier.cache_read) / 1M` 5. Compute `savings = counterfactualUsd − actualUsd`. 6. Emit per-baseline totals + savings % across the comparison set. ## Smoke transcript (2 sessions: 50K haiku tokens + 50K sonnet tokens) ``` | Sessions considered | 2 | | Total input tokens | 100,000 | | Actual spend | $0.162500 | | Baseline | Hypothetical | Actual | Savings | % | | `always-haiku` | $0.025000 | $0.162500 | -$0.137500 | -550.00% | | `always-sonnet` | $0.300000 | $0.162500 | +$0.137500 | 45.83% | | `always-opus` | $1.500000 | $0.162500 | +$1.337500 | 89.17% | ``` ## How to read negative savings A negative `always-haiku` result means **the router chose more-expensive models than haiku** on tasks haiku could have handled. That's an over-escalation signal: - Maybe qualityBar is set too high - Maybe the sonnet/opus session was warranted by complexity but the baseline doesn't know that - Run `cost optimize` (or inspect specific sessions via `cost conversation`) to investigate Positive savings quantify the router's win against that baseline. The most informative number is usually `always-sonnet` — it's the standard "safe default" baseline most teams would pick if they didn't have routing. ## When to use - **Quarterly cost review**: "We saved $X vs always-Sonnet — here's the proof." - **CI gate**: `cost counterfactual --format json | jq '.baselines[1].savingsPct > 30'` — fail builds if routing isn't saving ≥30% vs sonnet baseline (workload-shift detector). - **Routing-config validation**: When introducing a new qualityBar or cost-ceiling, re-run counterfactual to confirm savings didn't regress. ## Stationarity caveat Like all counterfactual analyses, this assumes the same tokens at the same complexity would have produced the same outcome from the baseline model. That's an upper bound — the baseline might have failed and required retries, which the math doesn't capture. Treat the numbers as a quality-blind ceiling.
© ruvnet · MIT · ruvnet/ruflo