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

audit-session-metrics — скилл для Claude Code: аудит расхода токенов

Скилл для Claude Code читает JSON-экспорт session-metrics и выдаёт отчёт о нерациональном расходе токенов. Запускается командой /audit-session-metrics quick или detailed над готовым файлом экспорта.

MIT ★ 2 744 обновлён 2026-10-08

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

Что делает audit-session-metrics

Скилл работает в двух режимах. «Quick» проверяет соотношения токенов, здоровье кэша и самые дорогие ходы или сессии. «Detailed» делает то же самое плюс сканирует CLAUDE.md, файлы настроек и повторные чтения — этот режим только для session-скоупа.

Поддерживаются три скоупа JSON: session_*.json — поанализ по ходам, project_*.json — по сессиям, instance/*/index.json — по проектам. Скоуп определяется автоматически из поля digest.scope. Сам скилл запускает python3 scripts/audit-extract.py, получает дайджест и дальше работает с ним, не читая исходный .jsonl.

По итогам создаются три артефакта: JSON-файл с находками, Markdown-копия и вывод прямо в чат. Оба файла сохраняются в exports/session-metrics/. Перед запуском на длинных сессиях автор советует переключиться на /model haiku — на API Anthropic это Haiku 5.5 с окном 1M токенов, на Bedrock и Google Cloud это Haiku 4.5 с окном 200k.

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

  • найти ходы и сессии с наибольшим расходом токенов
  • проверить эффективность кэша в экспорте session-metrics
  • выявить повторные чтения файлов настроек и CLAUDE.md
  • сравнить расход токенов по всем сессиям проекта
  • получить структурированный JSON-отчёт по аудиту токенов

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

  • Запусти быстрый аудит: /audit-session-metrics quick exports/session-metrics/session_abc12345_20250601.json
  • Запусти детальный аудит: /audit-session-metrics detailed exports/session-metrics/project_20250601.json
  • Проверь расход токенов по всем проектам: /audit-session-metrics quick exports/session-metrics/instance/2025-06-01/index.json

Как установить audit-session-metrics

1Через Skills CLI (Vercel)

npx skills add centminmod/my-claude-code-setup --skill audit-session-metrics -a claude-code

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

~/.claude/skills/audit-session-metrics/SKILL.md

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

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

Вопросы об audit-session-metrics

Как установить audit-session-metrics в Claude Code?

Выполните npx skills add centminmod/my-claude-code-setup --skill audit-session-metrics -a claude-code, затем скилл будет доступен по пути ~/.claude/skills/audit-session-metrics/SKILL.md.

Что делает audit-session-metrics?

Скилл читает JSON-файл экспорта session-metrics и формирует отчёт о нерациональном расходе токенов: соотношения, состояние кэша, дорогие ходы. В режиме detailed дополнительно проверяет файлы конфигурации.

Чем отличается режим quick от detailed?

quick выдаёт соотношения токенов, статус кэша и топ дорогих ходов. detailed добавляет сканирование CLAUDE.md, settings.json и .claudeignore — только для session-скоупа; файлы больше 500 строк сами по себе попадают в находки.

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

SKILL.md · MIT
---
name: audit-session-metrics
effort: low
description: >
  Audit a session-metrics JSON export for token-usage waste and produce a
  plain-English findings report. Trigger when the user runs
  /audit-session-metrics, when session-metrics suggests an audit after an
  HTML export, or when the user asks to audit / review / find waste in a
  saved session-metrics JSON. Two modes: "quick" (ratios + cache health +
  top expensive turns/sessions) and "detailed" (adds CLAUDE.md / settings /
  re-read scan). Supports session, project, and instance JSON scopes.
  Args: $ARGUMENTS[0] = quick|detailed,
  $ARGUMENTS[1] = path to a session-metrics JSON export.
---

# Audit Session-Metrics

Reads a session-metrics JSON export and produces a prioritised, plain-English
audit of token-usage waste. It runs on the session's current model (it no
longer pins one — a hard model pin capped the usable context at that model's
window and broke invocation on long sessions). The work is mostly
summarisation over a small disk-read export, so for a much cheaper run
`/model haiku` before invoking. On the Anthropic API `haiku` is Haiku 5.5
(1M window, so long sessions fit; prompts over 100K tokens bill at its higher
rate). On Bedrock, Google Cloud, Microsoft Foundry, and Claude Platform on AWS
it is still Haiku 4.5 with a 200k window — short/early sessions only there.

Supports three JSON scopes auto-detected from `digest.scope`:
- **session** — single session (`session_*.json`) — per-turn analysis
- **project** — all sessions for one project (`project_*.json`) — per-session analysis
- **instance** — all projects (`instance/*/index.json`) — per-project analysis

## Dispatch — how to route this invocation

**First positional argument received:** `$ARGUMENTS[0]`
**Second positional argument received:** `$ARGUMENTS[1]`

Read `$ARGUMENTS[0]` and match by **literal equality**:

| `$ARGUMENTS[0]` | Route                    | Then read (session scope) | Then read (project/instance scope) |
|-----------------|--------------------------|---------------------------|------------------------------------|
| `quick`         | Quick audit              | [`references/quick-audit.md`](references/quick-audit.md) | see Scope routing below |
| `detailed`      | Detailed audit           | [`references/detailed-audit.md`](references/detailed-audit.md) | see Scope routing below |
| *(empty / other)* | Print usage and stop   | this file's "Usage" block below | — |

`$ARGUMENTS[1]` must be the path to a JSON export written by session-metrics.
Accepted patterns:
- `exports/session-metrics/session_<id8>_<ts>.json` — session scope
- `exports/session-metrics/project_<ts>.json` — project scope
- `exports/session-metrics/instance/<datedir>/index.json` — instance scope

If `$ARGUMENTS[1]` is missing, empty, or the file does not exist, print:

> Usage: /audit-session-metrics {quick|detailed} <path-to-session-metrics.json>
>
> Accepted JSON types:
>   session:  exports/session-metrics/session_*.json
>   project:  exports/session-metrics/project_*.json
>   instance: exports/session-metrics/instance/*/index.json

…and stop without further work.

## Steps

1. Run the extract helper once with the input path:

   ```
   python3 scripts/audit-extract.py $ARGUMENTS[1] --mode $ARGUMENTS[0]
   ```

   The helper emits a single JSON digest to stdout. Read `digest.scope`
   from the output — it will be `"session"`, `"project"`, or `"instance"`.
   **Do not** read the raw `.jsonl`, and **do not** re-derive numbers the
   digest already carries.

2. **Scope routing — read the matching reference file:**

   | `digest.scope` | `$ARGUMENTS[0]` | Reference file |
   |----------------|-----------------|----------------|
   | `session`      | `quick`         | [`references/quick-audit.md`](references/quick-audit.md) |
   | `session`      | `detailed`      | [`references/detailed-audit.md`](references/detailed-audit.md) |
   | `project`      | `quick`         | [`references/project-quick-audit.md`](references/project-quick-audit.md) |
   | `project`      | `detailed`      | [`references/project-detailed-audit.md`](references/project-detailed-audit.md) |
   | `instance`     | `quick` or `detailed` | [`references/instance-quick-audit.md`](references/instance-quick-audit.md) |

   Follow the playbook step-by-step. Do not improvise additional phases.

3. For `detailed` mode **on session scope only**, the playbook also asks
   you to read the user's config files (`~/.claude/CLAUDE.md`,
   `./CLAUDE.md`, `~/.claude/settings.json`, `./.claude/settings.json`,
   `./.claudeignore`). Each is capped at ≤500 lines — if a file is
   bigger, that itself is a finding.

4. **Output contract — three artefacts.** All playbooks specify the
   same three-artefact contract:
   - **JSON sidecar** at `<project>/exports/session-metrics/audit_<id8>_<ts>_<mode>.json` — structured findings (versioned schema, enum'd metrics).
   - **Markdown copy** at `<project>/exports/session-metrics/audit_<id8>_<ts>_<mode>.md` — same content rendered for humans.
   - **Inline chat output** — the markdown content printed in your reply.

   `<id8>` and `<ts>` come from `digest.session_id_short` and
   `digest.ts_str` (the helper parses the input filename and
   normalises all three filename patterns).

5. **Write order.** Populate the JSON object first using the digest
   values, write the JSON sidecar, render the markdown using the
   template in the playbook, write the markdown copy, then print the
   markdown inline (without the H1 heading — the chat client already
   shows context above the audit). Finish with two stderr-style lines
   on their own:
   `[audit] saved → <json-path>`
   `[audit] saved → <md-path>`

   **IMPORTANT:** Use the **Write tool** directly for steps 3 and 5.
   Do NOT generate a Python script (e.g. writing to `/tmp/audit_synthesis.py`
   and executing it) — this adds unnecessary failure modes (syntax errors,
   f-string escaping) and is never required. Build the JSON in the AI's own
   context; call Write. Render the markdown in context; call Write again.

## Tone

- **Direct and specific.** Cite the exact ratio, dollar figure, or turn
  index. No motivational language, no LLM-theory padding.
- **Prioritise by impact.** Sort findings so the costliest fix is first.
- **Quote sparingly.** Snippets capped at 5 lines each.
- **Honour the playbook.** If quick-audit.md asks for 5 rows, produce 5
  rows — don't invent a 6th to look thorough.

## Why this is a separate skill

The audit is a distinct, user-initiated analysis step over a finished
export, not part of generating one. It reads only the on-disk JSON — never
the conversation — so it stands alone as its own turn, which is why
session-metrics *suggests* `/audit-session-metrics` rather than invoking it
programmatically. Running it as a fresh slash command keeps the turn focused
and lets the user decide when to spend on it. The work is summarisation-heavy
and the input is tiny, so the cost path is `/model haiku` before invoking
(Haiku 5.5 with a 1M window on the Anthropic API; on other providers
`haiku` is Haiku 4.5 with a 200k window, so short/early sessions only) — far
cheaper than a frontier model, with identical output (every dollar figure is
pre-computed by `audit-extract.py`, not guessed by the model).

## Reference files

### Session scope
- [`references/quick-audit.md`](references/quick-audit.md) — Distilled
  ratios + cache health + top expensive turns. Read when scope=session,
  mode=quick.
- [`references/detailed-audit.md`](references/detailed-audit.md) — Quick
  audit findings plus config + re-read scans. Read when scope=session,
  mode=detailed.

### Project scope
- [`references/project-quick-audit.md`](references/project-quick-audit.md) —
  Per-session cost outliers, cache health, breaks, weekly trend. Read when
  scope=project, mode=quick.
- [`references/project-detailed-audit.md`](references/project-detailed-audit.md) —
  Project quick findings plus per-session turn-level drilldown on the most
  expensive sessions. Read when scope=project, mode=detailed.

### Instance scope
- [`references/instance-quick-audit.md`](references/instance-quick-audit.md) —
  Per-project cost breakdown, cache health, weekly cost trend. Used for both
  quick and detailed modes (no per-turn data available at instance scope).

© centminmod · MIT · centminmod/my-claude-code-setup

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
context-tax-audit Ronny (MiniMax Code team) Скилл context-tax-audit для Claude Code проводит аудит данных, которые агент добавляет в каждый запрос, для сокращения затрат на токены. Он выявляет лишние блоки в системном промпте и настройки, мешающие кэшированию запросов. CX Codex +1 ★ 741звёзд репо session-tax CraniusMaximus LLC Плагин session-tax замеряет стартовый вес контекста в Claude Code до первого введённого слова. Он показывает, сколько токенов сжигают забытые скиллы, серверы и хуки. ★ 1 013звёзд репо session-compare hoangsonww Скилл session-compare сопоставляет две сессии по затратам, токенам, событиям и работе агентов. Пригодится, чтобы выяснить, почему один запуск завершился лучше другого. CX Codex +1 ★ 1 198звёзд репо session-debug hoangsonww Скилл session-debug для Claude Code, который разбирает сессию из данных Agent Monitor по цепочке событий. Вытаскивает ошибки, дерево субагентов и расход токенов по конкретному session ID. CX Codex +1 ★ 1 198звёзд репо cost-session ruvnet Скилл cost-session для Claude Code детализирует затраты на каждое сообщение внутри сессии, показывая дорогие запросы. CX Codex +1 249установок learn-codebase thedotmack Скилл learn-codebase для Claude Code, Codex, Cursor и других платформ ИИ-кодинга, который читает все исходные файлы проекта целиком. Запускается по команде пользователя в начале работы с незнакомым репозиторием. CX Codex +1 5 800установок

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

Весь набор →
memory-bank-synchronizer memory-bank-synchronizer — субагент Claude Code, который сверяет memory bank с текущим кодом и обновляет документацию при расхождениях. CX Codex ★ 2 744звёзд репо ux-design-expert Субагент ux-design-expert для Claude Code разбирает пользовательские сценарии, собирает дизайн-систему на Tailwind и настраивает графики Highcharts. Разбирает путаницу пользователей в готовом интерфейсе. CX Codex ★ 2 744звёзд репо code-searcher Субагент code-searcher ищет функции, классы и уязвимости в кодовой базе и возвращает ссылки на строки файл:номер. CX Codex ★ 2 744звёзд репо cleanup-context Команда cleanup-context для Claude Code анализирует и сокращает объём файлов документации проекта, удаляя дубли, устаревшие материалы и консолидируя перекрывающийся контент. CX Codex +1 ★ 2 744звёзд репо task-breakdown Скилл task-breakdown группирует запросы из сессии Claude Code в осмысленные задачи и оценивает их пользу по метрикам. CX Codex +1 ★ 2 744звёзд репо apply-thinking-to Команда apply-thinking-to для Claude Code преобразует файл промпта по схемам расширенного мышления Anthropic. Помогает анализировать задачи, проверять выводы и разбирать компромиссы. CX Codex +1 ★ 2 744звёзд репо create-release-note Команда create-release-note для автоматического создания двух версий документации релиза: покупательской и технической. Анализирует коммиты за последнее время и структурирует изменения по темам. CX Codex +1 ★ 2 744звёзд репо consult-zai Скилл consult-zai запускает параллельный анализ кода двумя моделями: z.ai GLM 5.2 и Claude code-searcher. Помогает получить второе мнение при поиске багов. CX Codex +1 ★ 2 744звёзд репо

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

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