К основному содержанию
скилл CX Codex

cost-diff — скилл для Claude Code: сравнение расходов

Скилл cost-diff для Claude Code сравнивает два JSON-снимка расходов. Запускается, чтобы проверить, увеличила ли PR-ветка затраты относительно базового снимка.

MIT 248 установок ★ 82 234 обновлён 2026-10-25

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add ruvnet/ruflo --skill cost-diff -a claude-code
Открыть на GitHub

Что делает cost-diff

cost-diff сравнивает расходы и число сессий в двух JSON-снимках, созданных командой cost summary --format json. Он показывает изменения по моделям и уровням, помечает новые, удалённые и изменившиеся позиции, а таблицу сортирует по размеру разницы.

Пороговые флаги позволяют завершить команду с кодом 1, если выросли общие расходы в процентах или долларах либо расходы по классу токенов. Для сравнения нужны файлы снимков с полями total_cost_usd и sessionCount; некорректный JSON или неподходящая структура дают код 2. В автоматической проверке PR базовый снимок берут с основной ветки, текущий — с PR-ветки.

Какие задачи решает

  • сравнить расходы в базовом и текущем снимках
  • найти модели с наибольшим изменением стоимости
  • завершить проверку PR при превышении порога затрат
  • отследить рост расходов по классу токенов

Примеры запросов агенту

  • Сравни baseline.json и current.json и покажи, что изменилось.
  • Проверь baseline.json и current.json; заверши проверку с ошибкой при росте расходов больше чем на 10%.
  • Сравни снимки и сработай при росте cache_write больше чем на 50%.

Как установить cost-diff

1Через Skills CLI (Vercel)

npx skills add ruvnet/ruflo --skill cost-diff -a claude-code

2Вручную: положить файлы

~/.claude/skills/cost-diff/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/cost-diff/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о cost-diff

Как установить cost-diff в Claude Code?

Выполни npx skills add ruvnet/ruflo --skill cost-diff -a claude-code. Файл скилла находится в ~/.claude/skills/cost-diff/SKILL.md.

Что делает cost-diff?

Сравнивает два JSON-снимка расходов, показывает изменения по моделям и уровням и проверяет заданные пороги. Для PR можно сопоставить базовый снимок с текущим.

Что нужно для работы cost-diff?

Нужны два JSON-файла, созданных командой cost summary --format json. В каждом должны быть поля total_cost_usd и sessionCount.

Исходный текст

SKILL.md · MIT
---
name: cost-diff
description: Snapshot delta between two cost-summary JSON outputs. PR-level cost regression detection — answers "what changed between these two specific snapshots?". Pairs with cost-summary's stable JSON contract.
argument-hint: "--baseline <baseline.json> --current <current.json> [--alert-on-pct N] [--alert-on-usd N] [--alert-on-class-pct <class>:N[,<class>:N]] [--format table|json]"
allowed-tools: Bash
disable-model-invocation: true
---

PR-level cost regression detection. Where cost-counterfactual compares
to HYPOTHETICAL baselines (always-haiku/sonnet/opus) and cost-burn
compares latest bucket to PRIOR MEAN, cost-diff compares two SPECIFIC
known-good snapshots.

| Question | Skill |
|---|---|
| "What would we have spent at always-X?" | `cost-counterfactual` |
| "Is daily burn accelerating vs prior mean?" | `cost-burn` |
| "Did THIS PR add spend vs main?" | **`cost-diff`** ← this |

## Algorithm

Implementation: [`scripts/diff.mjs`](../../scripts/diff.mjs). Consumes the
stable JSON contract from `cost summary --format json`.

1. Load `--baseline` and `--current` JSON snapshots.
2. Sanity check: both must have `total_cost_usd` + `sessionCount` (cost-summary shape).
3. Per-key delta: `byTier` (haiku/sonnet/opus) and `byModel` (each model).
4. Each entry tagged `added` / `removed` / `changed` based on
   baseline / current zero-ness.
5. Sort table by `|delta|` descending so the biggest movers are at the top.
6. `--alert-on-pct N`: exit 1 when `total_pct > N`.
7. `--alert-on-usd N`: exit 1 when `total_delta_usd > N`.
   Both can be set; first to trigger wins.

## PR-gate workflow

```bash
# Capture baseline (e.g. on main, via the cost-tracker-smoke CI workflow)
cost summary --format json > baseline.json

# On the PR branch, capture current state
cost summary --format json > current.json

# Compare; fail the PR if total spend grew >10% OR >$5
cost diff --baseline baseline.json --current current.json \
          --alert-on-pct 10 --alert-on-usd 5.00
```

The combination of both flags catches:
- **Percent-only fires**: a small absolute change but a meaningful shift
  (e.g. doubling from $0.10 to $0.20 hits +100% but only +$0.10).
- **USD-only fires**: a large absolute change with a small percent
  (e.g. growing from $100 to $110 is only +10% but +$10).

Either signal can fail the PR independently — they're OR'd.

## --alert-on-class-pct (iter 86)

The two USD-level thresholds above miss a regression class: when ONE
token type grows disproportionately even though total spend grows
modestly. Example: a PR introduces a verbose context-cache pattern,
total spend grows only 10% (under --alert-on-pct 50), but `cache_write`
tokens grow 900%. The iter-82 driver hides inside the USD signal.

`--alert-on-class-pct cache_write:50` exits 1 when cache_write tokens
grow more than 50% baseline → current. Multiple classes can be checked
in one flag (comma-separated):

```bash
cost diff --baseline baseline.json --current current.json \
          --alert-on-class-pct cache_write:50,output:25
```

First class to breach wins. Valid classes: `input | output | cache_write | cache_read`.

Recommended PR-gate triad:

```bash
cost diff --baseline ... --current ... \
          --alert-on-pct 25 \
          --alert-on-usd 5.00 \
          --alert-on-class-pct cache_write:100
```

Three orthogonal signals — `pct` (total grew), `usd` (large absolute
jump), `class-pct` (composition shifted). Each catches what the others
miss; AND-of-OR semantics means any one firing fails the PR.

## Smoke transcript (synthetic baseline + current)

```
| Total spend       | $1.000000 | $1.500000 | +$0.500000 | 50.00% |
| Sessions          | 10        | 13        | +3         | 30.00% |

## By tier
| opus   | $0      | $0.60   | +$0.600000 | new      | added   |
| sonnet | $0.70   | $0.50   | -$0.200000 | -28.57%  | changed |
| haiku  | $0.30   | $0.40   | +$0.100000 | 33.33%   | changed |
```

Notice the table is **sorted by absolute delta**, not alphabetically —
the biggest mover (opus newly added) bubbles to the top. Operators
reading top-down see "what mattered" first.

## Exit codes

| Exit | Meaning |
|---|---|
| 0 | No alert, OR no thresholds set |
| 1 | --alert-on-pct or --alert-on-usd threshold exceeded |
| 2 | Config error (missing files, invalid JSON, malformed snapshot) |

## Status column

| Status | Meaning |
|---|---|
| `added` | This tier/model was $0 in baseline, >$0 in current |
| `removed` | This tier/model was >$0 in baseline, $0 in current |
| `changed` | Both baseline and current >$0; delta is the difference |

Entries with `baseline === 0 && current === 0` are dropped (nothing to
report).

## Composition with cost-summary

cost-diff is the SECOND HALF of a contract that cost-summary started:
the stable JSON shape from `cost summary --format json`. Both pieces
have been frozen — adding fields to summary is fine; renaming or
removing isn't.

If you're consuming snapshots elsewhere (dashboards, alerting), the
same shape works — `cost-diff` is just one consumer.

© ruvnet · MIT · ruvnet/ruflo

Похожие скиллы

Все скиллы по теме «DevOps и инфраструктура» →
Agent Cost Report thedotmack Скилл Agent Cost Report для Claude Code и Codex формирует отчёт о расходах агентов за выбранный период. Запускается при оценке затрат на сессии и поиске потерь от переделок или зацикливаний. CX Codex +1 816установок ccam-cost-guard Son Nguyen Хук ccam-cost-guard отслеживает расходы на Claude Code и отправляет данные о завершении сессий в дашборд Agent Monitor. CX Codex ★ 1 198звёзд репо agent-pulse Jane-o-O-o-O Скилл agent-pulse для Claude Code собирает статистику сессий, токенов, вызовов инструментов и затрат локальных ИИ-агентов. Показывает стоимость сессий и расход моделей. CX Codex +1 47 600установок cost-alert hoangsonww Скилл cost-alert для Claude Code показывает правила бюджета Agent Monitor, сработавшие алерты и причины их срабатывания. CX Codex +1 ★ 1 198звёзд репо cost-tracker Rohit Ghumare Команда cost-tracker оценивает стоимость текущей сессии, показывает главные источники расходов и предлагает способы оптимизации. Пригодится, чтобы сверить траты с бюджетом задачи. CX Codex +1 ★ 2 966звёзд репо cost-accrual-tracker curiositech Скилл cost-accrual-tracker для Claude Code и пяти других платформ, который считает расходы на API в режиме реального времени во время выполнения LLM-запросов. Фиксирует частичные затраты даже при прерванных запросах. CX Codex +1 175установок

Из того же набора155

Весь набор →
cost-session Скилл cost-session для Claude Code детализирует затраты на каждое сообщение внутри сессии, показывая дорогие запросы. CX Codex +1 249установок cost-projection Скилл cost-projection для Claude Code прогнозирует расходы по недавним сессиям. Показывает темп трат, суммы на заданные периоды и срок до достижения лимита. CX Codex +1 249установок cost-health Скилл cost-health гоняет четыре проверки расходов параллельно и отдаёт один статус: бюджет, ускорение трат, аномалии сессий и прогноз исчерпания. CX Codex +1 249установок cost-counterfactual Скилл cost-counterfactual сравнивает реальные траты на сессии с гипотетическими сценариями always-haiku, always-sonnet и always-opus. Помогает понять, окупается ли роутер моделей. CX Codex +1 249установок cost-burn Скилл cost-burn для Claude Code и других платформ, анализирующий ускорение трат на продакшене. Запускается в CI для проверки, не вышла ли скорость расходования средств за пределы среднего значения. CX Codex +1 248установок cost-anomaly Скилл cost-anomaly для Claude Code выявляет отдельные сессии с необычными расходами и показывает отклонение от типичных затрат. Запускается, когда нужно найти конкретную сессию-выброс, а не оценить общий тренд. CX Codex +1 248установок Ruflo MCP-сервер Ruflo для Claude Code и Codex координирует команды ИИ-агентов и хранит память между сессиями. После init хуки направляют задачи и запускают координацию в фоне. CX Codex +1 ★ 82 234звёзд репо claude-flow Подключает Claude Code к инструментам claude-flow для работы с агентами и координации задач. Для запуска через MCP понадобится ANTHROPIC_API_KEY. CX Codex +1 ★ 82 234звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой