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

analytics · yonatangross — скилл для Claude Code: что делает и как установить

Скилл analytics собирает локальную аналитику вызовов агентов, хуков и токенов из файлов Claude Code. Запускается при проверке расходов и производительности сессий.

MIT 210 установок ★ 305 обновлён 2026-11-07

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

Что делает analytics

Скилл читает локальные логи в директории ~/.claude/analytics/ и кэш ~/.claude/stats-cache.json. Анализ выполняется через утилиту jq, а результаты возвращаются в виде таблиц Markdown. Все идентификаторы проектов хэшируются, внешние сервисы для сбора метрик не задействуются.

Внутри доступны подкоманды под конкретные срезы: статистика использования субагентов, задержки хуков, повтор сессий и расчёт расходов на токены с учётом кэша подсказок. Скилл также может разбирать файлы OpenTelemetry при наличии свежих версий окружения.

Для работы утилите нужны jq и Bash. В исходных логах agent-usage.jsonl около 38% строк содержат значение unknown, поэтому скилл отсекает их перед подсчётом долей, иначе рейтинг агентов искажается.

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

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

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

  • Покажи общую сводку использования агентов и скиллов через analytics summary
  • Оцени расходы на токены по всем моделям с помощью analytics cost
  • Найди самые медленные хуки командой analytics hooks

Как установить analytics

1Через Skills CLI (Vercel)

npx skills add yonatangross/orchestkit --skill analytics -a claude-code

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

~/.claude/skills/analytics/SKILL.md

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

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

Вопросы об analytics

Как установить analytics в Claude Code?

Выполните команду npx skills add yonatangross/orchestkit --skill analytics -a claude-code в терминале.

Что делает скилл analytics?

Он читает локальные JSONL-логи и кэш статистики Claude Code, формируя отчёты по токенам, времени работы хуков и вызовам агентов без отправки данных наружу.

Какие системные утилиты нужны для работы скилла?

Потребуется установленная утилита jq, так как скилл выполняет прямые поисковые запросы по локальным файлам через Bash.

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

SKILL.md · MIT
---
name: analytics
license: MIT
compatibility: "Claude Code 2.1.277+."
description: "Local OrchestKit usage analytics: agent and skill frequency, hook timing, session replay, cost estimates, model delegation trends. Use when reviewing usage, performance or costs."
argument-hint: "[agents|models|skills|hooks|teams|session|cost|trends|summary]"
context: inherit
user-invocable: false
allowed-tools: "Bash Read Grep Glob AskUserQuestion"
effort: low
model: haiku
metadata:
  category: document-asset-creation
  version: "2.1.0"
  author: "OrchestKit"
  complexity: "low"
  tags: "analytics, metrics, usage, teams, agents, skills, hooks, data-visualization, dashboard, recharts, charts, widgets, session, cost, tokens, model-delegation"
---

# Cross-Project Analytics

Query local analytics data from `~/.claude/analytics/`. All data is local-only, privacy-safe (hashed project IDs, no PII).

Answer usage questions from the local files, never from guesswork: agent usage (which agents and how often — not which model, see the caveats) lives in `~/.claude/analytics/agent-usage.jsonl`; hook performance and failures live in `~/.claude/analytics/hook-timing.jsonl`; token and cost totals live in `~/.claude/stats-cache.json`. Query them with `jq` one-liners (below) and present real counts, not pointers to dashboards.

## Subcommands

Parse the user's argument to determine which report to show. If no argument provided, use AskUserQuestion to let them pick.

| Subcommand | Description | Data Source | Reference |
|------------|-------------|-------------|-----------|
| `agents` | Top agents by frequency and success rate (duration/model unavailable — #3034) | `agent-usage.jsonl` | `references/jq-queries.md` |
| `models` | Model delegation from **token totals** in `stats-cache.json`. Per-spawn attribution is unavailable (#3034) | `stats-cache.json` | `references/jq-queries.md` |
| `skills` | Top skills by invocation count | `skill-usage.jsonl` | `references/jq-queries.md` |
| `hooks` | Slowest hooks and failure rates | `hook-timing.jsonl` | `references/jq-queries.md` |
| `teams` | Team spawn counts, idle time, task completions | `team-activity.jsonl` | `references/jq-queries.md` |
| `session` | Replay a session timeline with tools, tokens, timing | CC session JSONL | `references/session-replay.md` |
| `cost` | Token cost estimation with cache savings | `stats-cache.json` | `references/cost-estimation.md` |
| `trends` | Daily activity, model delegation, peak hours | `stats-cache.json` | `references/trends-analysis.md` |
| `summary` | Unified view of all categories | All files | `references/jq-queries.md` |
| `otel` | CC 2.1.117 + 2.1.122 + 2.1.126 OTEL enrichments: top slash commands (user vs model), per-effort cost, effort-vs-success correlation, skill activation by trigger type, most-mentioned `@` targets | `~/.claude/otel/*.jsonl`, or user-named Loki + Prometheus endpoints after schema discovery | `references/otel-fields.md`, `references/otel-gateway-source.md` |

### Quick Start Example

```bash
# Top agents by spawn frequency. Excludes phantom rows (see caveat below).
jq -s 'map(select(.agent != "unknown")) | group_by(.agent) | map({agent: .[0].agent, count: length}) | sort_by(-.count)' ~/.claude/analytics/agent-usage.jsonl

# Cost per model: input + output token counts (multiply by per-model pricing;
# count cache-read tokens separately — prompt-cache hits are ~90% cheaper, so
# cache savings materially lower the real total)
jq '.modelUsage | to_entries | map({model: .key, input: .value.inputTokens, output: .value.outputTokens, cacheRead: .value.cacheReadInputTokens})' ~/.claude/stats-cache.json

# Slowest hooks by average duration, and failure rate as a percentage
jq -s 'group_by(.hook) | map({hook: .[0].hook, avg_ms: (map(.duration_ms) | add / length), fail_pct: (100 * (map(select(.ok != true)) | length) / length)}) | sort_by(-.avg_ms)' ~/.claude/analytics/hook-timing.jsonl
```

### Quick Subcommand Guide

**`agents`, `models`, `skills`, `hooks`, `teams`, `summary`** — Run the jq query from `Read("references/jq-queries.md")` for the matching subcommand. Present results as a markdown table.

**`session`** — Follow the 4-step process in `Read("references/session-replay.md")`: locate session file, resolve reference (latest/partial/full ID), parse JSONL, present timeline.

**`cost`** — Apply model-specific pricing from `Read("references/cost-estimation.md")` to CC's stats-cache.json. Show per-model breakdown, totals, and cache savings. On CC >= 2.1.174, cross-check against CC-native `/usage` per-component attribution (see 'CC-Native /usage Attribution' below).

**`trends`** — Follow the 4-step process in `Read("references/trends-analysis.md")`: daily activity, model delegation, peak hours, all-time stats.

**`summary`** — Run all subcommands and present a unified view: total sessions, top 5 agents, top 5 skills, team activity, unique projects. If `~/.claude/otel/*.jsonl` exists with non-empty content, append the three OTEL panels from `otel-fields.md`; otherwise omit them (do not render empty panels).

**`otel`** — Render the OTEL panels: 3 from CC 2.1.117 (top slash commands user-vs-model, per-effort cost, effort-vs-success correlation), 3 from CC 2.1.119 (oversized inputs, pre/post latency, see `otel-fields.md`), 1 from CC 2.1.122 (most-mentioned `@` targets), and 1 from CC 2.1.126 (skill activation by trigger type). See `Read("references/otel-fields.md")` for queries, graceful-fallback rules, and panel semantics. Each panel falls back cleanly to "no OTEL data available (upgrade to CC ≥ X)" when its specific file is absent or empty — render only the panels with data.

## Data-Quality Caveats — read before reporting any number

Two measured defects in `agent-usage.jsonl` change what this file can honestly answer. Verified against 11,249 real rows on 2026-07-20.

**1. Four of eight fields are dead for 100% of rows (#3034).** `model` is the literal string `"unknown"` on every row, `agent_name` is null on every row, `output_len` is 0 on every row, and `duration_ms` is absent entirely. Only `ts`, `pid`, `agent`, and `success` carry signal. Do NOT report model delegation, agent duration, or output size from this file — grouping by `.model` returns one `unknown` bucket, not a breakdown. If asked, say the data is unavailable and cite #3034 rather than presenting a single-bucket result as if it were an answer.

**2. ~38% of rows are phantom events, not spawns (#3035).** Rows with `agent == "unknown"` have no SubagentStart, no readable transcript, and their agent ids appear nowhere in Claude Code's own session data. They are an inflated denominator: any activation ratio computed over the full file is wrong. **Filter `select(.agent != "unknown")` before computing any share, percentage, or ranking.** A specialist-vs-generic split over the raw file understates specialists by roughly a third.

Both are writer-side defects, not query bugs — a better jq expression cannot recover the missing signal.

## Data Files

Load `Read("references/data-locations.md")` for complete data source documentation.

| File | Contents |
|------|----------|
| `agent-usage.jsonl` | Agent spawns — usable fields are `ts`, `pid`, `agent`, `success` only. `model`/`agent_name`/`output_len`/`duration_ms` are dead (#3034) and ~38% of rows are phantoms (#3035) |
| `skill-usage.jsonl` | Skill invocations |
| `hook-timing.jsonl` | Hook execution timing and failure rates |
| `session-summary.jsonl` | Session end summaries |
| `task-usage.jsonl` | Task completions |
| `team-activity.jsonl` | Team spawns and idle events |

## Rules

Each category has individual rule files in `rules/` loaded on-demand:

| Category | Rule | Impact | Key Pattern |
|----------|------|--------|-------------|
| Data Integrity | `rules/data-privacy.md` | CRITICAL | Hash project IDs, never log PII, local-only |
| Cost & Tokens | `rules/cost-calculation.md` | HIGH | Separate pricing per token type, cache savings |
| Performance | `rules/large-file-streaming.md` | HIGH | Streaming jq for >50MB, rotation-aware queries |
| Visualization | `rules/visualization-recharts.md` | HIGH | Recharts charts, ResponsiveContainer, tooltips |
| Visualization | `rules/visualization-dashboards.md` | HIGH | Dashboard grids, stat cards, widget registry |

**Total: 5 rules across 4 categories**

## References

| Reference | Contents |
|-----------|----------|
| `references/jq-queries.md` | Ready-to-run jq queries for all JSONL subcommands |
| `references/session-replay.md` | Session JSONL parsing, timeline extraction, presentation |
| `references/cost-estimation.md` | Pricing table, cost formula, daily cost queries |
| `references/trends-analysis.md` | Daily activity, model delegation, peak hours queries |
| `references/data-locations.md` | All data sources, file formats, CC session structure |
| `references/otel-fields.md` | CC 2.1.117 OTEL fields (command_name, command_source, effort), queries, and dashboard panels |

## Important Notes

- All files are JSONL (newline-delimited JSON) format
- For large files (>50MB), use streaming `jq` without `-s` — load `Read("rules/large-file-streaming.md")`
- Rotated files: `<name>.<YYYY-MM>.jsonl` — include for historical queries
- `team` field only present during team/swarm sessions
- `pid` is a 12-char SHA256 hash — irreversible, for grouping only

## CC-Native /usage Attribution (2.1.174+)

CC 2.1.174 added per-component attribution to `/usage`: cache misses, long-context usage, subagent costs, and per-skill / per-agent / per-plugin / per-MCP cost breakdowns over the last 24h / 7d. It currently surfaces in the VSCode "Account & usage" dialog; in the terminal, run `/usage`.

When the user asks "which skill/agent actually costs the most" or questions ork's local estimates, direct them to `/usage` as the authoritative source — CC's own attribution supersedes ork's heuristic `cost` estimates for the windows it covers. Use ork's `cost`/`otel` views for history beyond CC's 7-day window and for cross-project slicing; use `/usage` for ground truth on the last 24h/7d.

## Output Format

Present results as clean markdown tables. Include counts, percentages, and averages. If a file doesn't exist, note that no data has been collected yet for that category.

## Related Skills

- `ork:explore` - Codebase exploration and analysis
- `ork:remember` - Store project knowledge
- `ork:doctor` - Health check diagnostics
- `ork:prompt-focus` - Where the user's own attention went, from their prompts (the user's own prompts, not tool telemetry)

© OrchestKit · MIT · yonatangross/orchestkit

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →

Сначала — analytics от других авторов.

analytics coreyhaines31 Скилл analytics для Claude Code и Codex помогает спроектировать план трекинга и проверить формулы метрик. Настраивает события в GA4, GTM, PostHog и Mixpanel без искажения когорт. CX Codex +1 97 200установок analytics apolloio Скилл analytics для Claude Code и других AI-редакторов отвечает на вопросы о продажах данными из Apollo. Спрашиваешь про письма, звонки, встречи или сделки — получаешь таблицу с цифрами, а не сырой API-ответ. CX Codex +1 636установок analytics Microsoft Скилл analytics маршрутизирует запросы к Process Mining: показывает обзор процесса, метрики событий и вариантов, загружает нужный специализированный скилл для глубокого анализа. CX Codex +1 ★ 1 167звёзд репо analytics-advisor Son Nguyen Субагент analytics-advisor для Claude, который собирает цифры с дашборда Agent Monitor и объясняет, за что вы платите в сессиях. CX Codex ★ 1 198звёзд репо ccam-analytics Son Nguyen Плагин ccam-analytics отслеживает сессии Claude Code через Agent Monitor: собирает статистику расходов, детализирует расход токенов и оценивает продуктивность работы. CX Codex ★ 1 198звёзд репо google-analytics acedatacloud Скилл для Claude и других агентов: тянет отчёты Google Analytics 4 и список свойств через Analytics API, работая из оболочки на curl и jq. CX Codex +1 177установок lean-analytics wondelai Помогает выбрать ключевую метрику проекта и очистить дашборды от метрик тщеславия по методологии Lean Analytics. Аудирует показатели под стадию и бизнес-модель стартапа. CX Codex +1 3 500установок cargo-analytics getcargo Скилл cargo-analytics для Claude Code измеряет результаты запусков Cargo и выгружает данные в CSV или JSON. С его помощью можно посчитать ошибки и получить выходные данные запуска. CX Codex +1 11 600установок openrouter-analytics-query OpenRouterTeam Скилл openrouter-analytics-query для построения и выполнения запросов к аналитике OpenRouter. Нужен, чтобы извлекать метрики по использованию моделей, группировать их по размерностям и фильтровать по времени и параметрам. CX Codex +1 355установок

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

Весь набор →
api-design Скилл api-design задаёт правила проектирования контрактов REST, GraphQL и gRPC при редактировании эндпоинтов и схем OpenAPI. Включается автоматически при работе с файлами в routes/ и спецификациями. CX Codex +1 211установок assess Скилл assess выставляет оценки от 0 до 10 по семи измерениям: правильность, читаемость, сложность, производительность, безопасность, поддерживаемость и соответствие стандартам. CX Codex +1 211установок verify Скилл verify проверяет готовность работы к слиянию: запускает тесты, проверки безопасности и типов, затем даёт оценку от 0 до 10. CX Codex +1 210установок commit Создаёт коммиты в формате Conventional Commits с автоопределением скоупа, строками Co-Authored-By и проверкой хуков; блокирует секреты и сгенерированные файлы. Запускается по команде commit или фразе «сохрани изменения». CX Codex +1 210установок create-pr Скилл create-pr создаёт pull request в GitHub после прогона тестов, линтера, типов и проверки безопасности. Срабатывает по явному вызову, обычная команда gh pr create остаётся командой. CX Codex +1 209установок audit-full Скилл audit-full проверяет весь код проекта за один проход: ищет проблемы безопасности, архитектуры и зависимостей, сортируя находки по серьёзности. Запускается перед релизом или проверкой безопасности. CX Codex +1 208установок implement Скилл implement собирает новую фичу параллельно: бэкенд, фронтенд, тесты и проверка безопасности в отдельных воркдеревьях. CX Codex +1 206установок demo-producer Скилл demo-producer для Claude Code автоматизирует создание демонстрационных и промо-видео по коду, CLI и плагинам. Запускает связку из VHS и Remotion для подготовки роликов в разных форматах. CX Codex +1 196установок

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

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