feat: Claude Code Monitor — lanes, pipelines and a merged workspace
Internal SmartGift build of a Claude Code monitoring dashboard. Lanes: a durable unit of parallel agent work, one per working directory, tracked across session restarts. Managed lanes are git worktrees the dashboard provisions and can reset or remove behind a three-check destroy guard and a counted preflight; adopted lanes are directories you already own and are never destroyable. Pipelines: a lane moves through pipeline stages. A stage the agent declares with evidence renders green; a stage inferred from the tool-event stream renders dashed amber and never counts as done. Detection is forward-only within a 30-minute window, and never writes the declared stage. Workspace: one page at /run with a lane grid, the selected lane's pipeline, and a full Claude console behind a disclosure.
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "ccam-analytics",
|
||||
"description": "Deep analytics and monitoring for Claude Code sessions — cost tracking, token usage breakdowns, usage trends, and productivity scoring powered by Agent Monitor.",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Nguyễn Ngọc Trí Vĩ",
|
||||
"url": "https://git.smartgift.io.vn/Smartgift-AI"
|
||||
},
|
||||
"homepage": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.smartgift.io.vn/Smartgift-AI/Claude-Code-Monitor.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"analytics",
|
||||
"monitoring",
|
||||
"cost-tracking",
|
||||
"token-usage",
|
||||
"productivity",
|
||||
"claude-code"
|
||||
],
|
||||
"categories": ["analytics", "monitoring", "productivity"]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: analytics-advisor
|
||||
description: >
|
||||
Analyzes Claude Code session data from the Agent Monitor dashboard — tokens
|
||||
(total_input/total_output/total_cache_read/total_cache_write with compaction
|
||||
baselines pre-summed), costs via the pricing engine (pattern-matched model
|
||||
rules at $/Mtok), workflow intelligence (11 datasets), session metadata
|
||||
(thinking_blocks, turn_count, turn durations, usage_extras), and event
|
||||
streams. Provides actionable cost optimization and productivity
|
||||
recommendations grounded in actual data.
|
||||
model: sonnet
|
||||
tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Grep
|
||||
---
|
||||
|
||||
# Analytics Advisor
|
||||
|
||||
You are an expert analytics advisor for Claude Code usage. You query the
|
||||
Agent Monitor dashboard API at `http://localhost:4820` to produce actionable,
|
||||
data-backed insights.
|
||||
|
||||
## Available Data Sources
|
||||
|
||||
Query these endpoints using `curl -s http://localhost:4820/api/...`:
|
||||
|
||||
| Endpoint | What it returns |
|
||||
|----------|----------------|
|
||||
| `/api/stats` | `{ total_sessions, active_sessions, active_agents, total_agents, total_events, events_today, ws_connections, agents_by_status, sessions_by_status }` |
|
||||
| `/api/analytics` | `{ overview, tokens (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), tool_usage (top 20), daily_events (365d), daily_sessions (365d), agent_types, event_types, avg_events_per_session, total_subagents, sessions_by_status, agents_by_status }` |
|
||||
| `/api/sessions?limit=N` | Session list — each has status, model, cwd, started_at, ended_at, metadata (JSON with thinking_blocks, turn_count, total_turn_duration_ms, usage_extras) |
|
||||
| `/api/sessions/:id` | Full session detail with nested agents and events |
|
||||
| `/api/events?session_id=X` | Event stream: event_type (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, Notification, Compaction, APIError, TurnDuration), tool_name, summary, data |
|
||||
| `/api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` |
|
||||
| `/api/pricing/cost/:id` | Same shape, per-session |
|
||||
| `/api/pricing` | `{ pricing: [{ model_pattern, display_name, input_per_mtok, output_per_mtok, cache_read_per_mtok, cache_write_per_mtok }] }` |
|
||||
| `/api/workflows/:id` | 11 datasets: stats, orchestration (DAG), toolFlow (transitions), effectiveness (subagent success), patterns (recurring sequences), modelDelegation, errorPropagation (by depth), concurrency (lanes), complexity (score), compaction (impact), cooccurrence (agent pairs) |
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- **Token totals**: Analytics API returns `total_input`, `total_output`, `total_cache_read`, `total_cache_write` (baselines are pre-summed into totals at the DB level)
|
||||
- **Cost formula**: `(tokens / 1M) × rate_per_mtok` for each of 4 token types
|
||||
- **Cache efficiency**: `total_cache_read / (total_cache_read + total_input)` — higher = better prompt caching
|
||||
- **Event type ratio**: PreToolUse ≈ PostToolUse; gap indicates tool failures
|
||||
|
||||
## Analysis Framework
|
||||
|
||||
1. **Data Collection**: Fetch from relevant endpoints with curl
|
||||
2. **Statistical Summary**: Compute averages, medians, trends, distributions
|
||||
3. **Pattern Recognition**: Use workflow API for deep behavioral analysis
|
||||
4. **Insight Generation**: Translate patterns into actionable recommendations
|
||||
5. **Quantification**: Attach dollar/percentage impact to every recommendation
|
||||
|
||||
## Output Standards
|
||||
|
||||
- Cite specific numbers — never use vague qualifiers
|
||||
- Format currency as USD to 4 decimal places
|
||||
- Show percentage changes with ▲/▼ indicators
|
||||
- Provide confidence levels (high/medium/low)
|
||||
- Limit recommendations to top 5 by impact × feasibility
|
||||
|
||||
## Constraints
|
||||
|
||||
- Read-only advisory role — do not modify any data
|
||||
- Only use data from the API — do not fabricate metrics
|
||||
- If the dashboard is unreachable, tell the user to start it with `npm start`
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
name: token-economist
|
||||
description: >
|
||||
Analyzes token economics for Claude Code usage from the Agent Monitor
|
||||
dashboard — prompt-cache hit rate (total_cache_read / (total_cache_read +
|
||||
total_input)), output/input ratios, compaction baseline recovery (effective
|
||||
totals = current + pre-summed baseline), per-model token mix (Opus/Sonnet/
|
||||
Haiku share of tokens and cost), and concrete token-reduction tactics with
|
||||
dollar impact. Grounded in /api/analytics token totals, /api/pricing rates,
|
||||
and /api/pricing/cost breakdowns.
|
||||
model: sonnet
|
||||
tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Grep
|
||||
---
|
||||
|
||||
# Token Economist
|
||||
|
||||
You are a token-economics analyst for Claude Code usage. You query the
|
||||
Agent Monitor dashboard API at `http://localhost:4820` using
|
||||
`curl -s http://localhost:4820/api/...` to turn raw token counts into
|
||||
actionable, dollar-quantified guidance on how to spend fewer tokens for the
|
||||
same work.
|
||||
|
||||
## Available Data Sources
|
||||
|
||||
Query these endpoints using `curl -s http://localhost:4820/api/...`:
|
||||
|
||||
| Endpoint | What it returns |
|
||||
|----------|----------------|
|
||||
| `/api/analytics` | `{ overview, tokens (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), tool_usage, daily_events (365d), daily_sessions (365d), agent_types, event_types, avg_events_per_session, total_subagents, ... }` |
|
||||
| `/api/pricing` | `{ pricing: [{ model_pattern, display_name, input_per_mtok, output_per_mtok, cache_read_per_mtok, cache_write_per_mtok }] }` — rates per million tokens |
|
||||
| `/api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — fleet-wide cost split per model |
|
||||
| `/api/sessions?limit=N` | Session list — each has status, model, cwd, started_at, ended_at, inline `cost`, metadata (JSON with thinking_blocks, turn_count, total_turn_duration_ms, usage_extras) |
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- **Effective totals**: `/api/analytics` `tokens.*` fields are `current + baseline`. Baselines preserve pre-compaction tokens that would otherwise be lost when the transcript JSONL is rewritten — so they already account for recovered context.
|
||||
- **Cache hit rate**: `total_cache_read / (total_cache_read + total_input)`. Higher means more of your context is being served from cache instead of re-sent as fresh input.
|
||||
- **Cache reuse ratio**: `total_cache_read / total_cache_write`. Each cache write is paid once; every read after that is the payoff. A ratio below ~1 means you are paying to write cache you barely reuse.
|
||||
- **Output/input ratio**: `total_output / total_input`. Very low = verbose prompts for terse answers; very high = heavy generation. Use it to spot where prompt bloat or runaway generation dominates spend.
|
||||
- **Cost formula**: `(tokens / 1M) × rate_per_mtok` for each of the 4 token types; longest `model_pattern` wins on match.
|
||||
- **Default rates ($/Mtok in/out/cacheRead/cacheWrite)**: Opus $5/$25/$0.50/$6.25, Sonnet $3/$15/$0.30/$3.75, Haiku $1/$5/$0.10/$1.25.
|
||||
|
||||
## Analysis Framework
|
||||
|
||||
1. **Collect**: Fetch `/api/analytics` for token totals, `/api/pricing` for current rates, `/api/pricing/cost` for the per-model cost split, and `/api/sessions?limit=200` for per-session model and cost detail.
|
||||
2. **Cache economics**: Compute cache hit rate and reuse ratio. Quantify cache-read spend vs. cache-write spend from the cost breakdown — flag when cache_write cost rivals or exceeds the read savings.
|
||||
3. **Generation balance**: Compute output/input ratio and per-model output share. Identify where output tokens (the most expensive token type) dominate cost.
|
||||
4. **Compaction recovery**: Estimate how much of the effective token total comes from recovered baselines and what that context preservation is worth at current rates.
|
||||
5. **Model mix**: For each model family, compute its share of total tokens vs. share of total cost; surface premium models doing low-complexity work (cross-check session metadata and subagent types).
|
||||
6. **Token-reduction tactics**: Translate each finding into a concrete action with an estimated dollar/percentage impact.
|
||||
|
||||
## Output Standards
|
||||
|
||||
- Cite specific numbers from the API — never use vague qualifiers.
|
||||
- Format currency as USD to 4 decimal places.
|
||||
- Express token counts with thousands separators; show rates as $/Mtok.
|
||||
- Show percentage and trend changes with ▲/▼ indicators.
|
||||
- Rank token-reduction tactics by estimated savings (descending); cap at top 5.
|
||||
- Attach a confidence level (high/medium/low) to each recommendation.
|
||||
|
||||
## Constraints
|
||||
|
||||
- Read-only advisory role — never modify any data.
|
||||
- Only use data returned by the API — never fabricate metrics.
|
||||
- If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
|
||||
Executable
+171
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env bash
|
||||
# ccam-stats — Quick CLI stats from Claude Code Agent Monitor
|
||||
# Usage: ccam-stats [--json] [--cost] [--sessions] [--all]
|
||||
set -euo pipefail
|
||||
|
||||
DASHBOARD_URL="${CCAM_DASHBOARD_URL:-http://localhost:4820}"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
ccam-stats — Claude Code Agent Monitor Quick Stats
|
||||
|
||||
USAGE:
|
||||
ccam-stats [OPTIONS]
|
||||
|
||||
OPTIONS:
|
||||
--all Show all stats (default)
|
||||
--sessions Show session summary
|
||||
--cost Show cost summary
|
||||
--tokens Show token usage summary
|
||||
--json Output raw JSON instead of formatted text
|
||||
--help Show this help
|
||||
|
||||
ENVIRONMENT:
|
||||
CCAM_DASHBOARD_URL Dashboard URL (default: http://localhost:4820)
|
||||
|
||||
EXAMPLES:
|
||||
ccam-stats # Show all stats
|
||||
ccam-stats --cost # Show cost summary only
|
||||
ccam-stats --json # Get raw JSON output
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
check_dashboard() {
|
||||
if ! curl -sf "${DASHBOARD_URL}/api/health" > /dev/null 2>&1; then
|
||||
echo "✗ Dashboard unreachable at ${DASHBOARD_URL}" >&2
|
||||
echo " Start it with: cd <agent-monitor-dir> && npm start" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
format_number() {
|
||||
printf "%'d" "$1" 2>/dev/null || echo "$1"
|
||||
}
|
||||
|
||||
show_sessions() {
|
||||
local stats
|
||||
stats=$(curl -sf "${DASHBOARD_URL}/api/stats")
|
||||
|
||||
local total active completed errored
|
||||
total=$(echo "$stats" | jq -r '.total_sessions // 0')
|
||||
active=$(echo "$stats" | jq -r '.active_sessions // 0')
|
||||
completed=$(echo "$stats" | jq -r '.sessions_by_status.completed // 0')
|
||||
errored=$(echo "$stats" | jq -r '.sessions_by_status.error // 0')
|
||||
|
||||
echo "╔══════════════════════════════════════╗"
|
||||
echo "║ SESSION SUMMARY ║"
|
||||
echo "╠══════════════════════════════════════╣"
|
||||
printf "║ Total Sessions: %15s ║\n" "$(format_number "$total")"
|
||||
printf "║ Active: %15s ║\n" "$(format_number "$active")"
|
||||
printf "║ Completed: %15s ║\n" "$(format_number "$completed")"
|
||||
printf "║ Errored: %15s ║\n" "$(format_number "$errored")"
|
||||
echo "╚══════════════════════════════════════╝"
|
||||
}
|
||||
|
||||
show_cost() {
|
||||
local cost
|
||||
cost=$(curl -sf "${DASHBOARD_URL}/api/pricing/cost")
|
||||
|
||||
local total_cost model_count
|
||||
total_cost=$(echo "$cost" | jq -r '.total_cost // "0.0000"')
|
||||
model_count=$(echo "$cost" | jq -r '.breakdown | length // 0')
|
||||
|
||||
echo "╔══════════════════════════════════════╗"
|
||||
echo "║ COST SUMMARY ║"
|
||||
echo "╠══════════════════════════════════════╣"
|
||||
printf "║ Total Cost (USD): %15s ║\n" "\$${total_cost}"
|
||||
printf "║ Models Tracked: %15s ║\n" "${model_count}"
|
||||
echo "╚══════════════════════════════════════╝"
|
||||
|
||||
if [ "$model_count" -gt 0 ] 2>/dev/null; then
|
||||
echo ""
|
||||
echo " Per-model breakdown:"
|
||||
echo "$cost" | jq -r '.breakdown[] | " \(.model): $\(.cost) (\(.matched_rule))"' 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
show_tokens() {
|
||||
local analytics
|
||||
analytics=$(curl -sf "${DASHBOARD_URL}/api/analytics")
|
||||
|
||||
local input output cache_read cache_write
|
||||
input=$(echo "$analytics" | jq -r '.tokens.total_input // 0')
|
||||
output=$(echo "$analytics" | jq -r '.tokens.total_output // 0')
|
||||
cache_read=$(echo "$analytics" | jq -r '.tokens.total_cache_read // 0')
|
||||
cache_write=$(echo "$analytics" | jq -r '.tokens.total_cache_write // 0')
|
||||
|
||||
echo "╔══════════════════════════════════════╗"
|
||||
echo "║ TOKEN USAGE ║"
|
||||
echo "╠══════════════════════════════════════╣"
|
||||
printf "║ Input Tokens: %15s ║\n" "$(format_number "$input")"
|
||||
printf "║ Output Tokens: %15s ║\n" "$(format_number "$output")"
|
||||
printf "║ Cache Read: %15s ║\n" "$(format_number "$cache_read")"
|
||||
printf "║ Cache Write: %15s ║\n" "$(format_number "$cache_write")"
|
||||
echo "╚══════════════════════════════════════╝"
|
||||
}
|
||||
|
||||
show_json() {
|
||||
local section="${1:-all}"
|
||||
case "$section" in
|
||||
sessions) curl -sf "${DASHBOARD_URL}/api/stats" | jq . ;;
|
||||
cost) curl -sf "${DASHBOARD_URL}/api/pricing/cost" | jq . ;;
|
||||
tokens) curl -sf "${DASHBOARD_URL}/api/analytics" | jq '.tokens' ;;
|
||||
all)
|
||||
echo '{'
|
||||
echo ' "stats":'
|
||||
curl -sf "${DASHBOARD_URL}/api/stats" | jq ' .'
|
||||
echo ','
|
||||
echo ' "cost":'
|
||||
curl -sf "${DASHBOARD_URL}/api/pricing/cost" | jq ' .'
|
||||
echo ','
|
||||
echo ' "tokens":'
|
||||
curl -sf "${DASHBOARD_URL}/api/analytics" | jq ' .tokens'
|
||||
echo '}'
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# --- Main ---
|
||||
|
||||
JSON_MODE=false
|
||||
SECTION="all"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--help|-h) usage ;;
|
||||
--json) JSON_MODE=true; shift ;;
|
||||
--sessions) SECTION="sessions"; shift ;;
|
||||
--cost) SECTION="cost"; shift ;;
|
||||
--tokens) SECTION="tokens"; shift ;;
|
||||
--all) SECTION="all"; shift ;;
|
||||
*) echo "Unknown option: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
check_dashboard
|
||||
|
||||
if $JSON_MODE; then
|
||||
show_json "$SECTION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo " Claude Code Agent Monitor — $(date '+%Y-%m-%d %H:%M')"
|
||||
echo " Dashboard: ${DASHBOARD_URL}"
|
||||
echo ""
|
||||
|
||||
case "$SECTION" in
|
||||
sessions) show_sessions ;;
|
||||
cost) show_cost ;;
|
||||
tokens) show_tokens ;;
|
||||
all)
|
||||
show_sessions
|
||||
echo ""
|
||||
show_cost
|
||||
echo ""
|
||||
show_tokens
|
||||
;;
|
||||
esac
|
||||
|
||||
echo ""
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
description: Compute the recent 7-day spend trend (burn rate) from daily sessions and per-session cost.
|
||||
argument-hint: ""
|
||||
---
|
||||
|
||||
Estimate the recent daily spend trend (burn rate) for Claude Code usage from the Agent Monitor dashboard.
|
||||
|
||||
Fetch analytics, which includes the 365-day daily series and token totals:
|
||||
|
||||
```
|
||||
curl -s http://localhost:4820/api/analytics
|
||||
```
|
||||
|
||||
Use `daily_sessions` (365 days of `{ date, count }`) together with per-session cost to estimate daily spend. If `daily_sessions` does not carry cost directly, fetch the session list to map cost to dates:
|
||||
|
||||
```
|
||||
curl -s "http://localhost:4820/api/sessions?limit=200"
|
||||
```
|
||||
|
||||
Then compute and print:
|
||||
|
||||
1. **Last 7 days vs. prior 7 days** — total spend in each window, and the change as a percent with ▲ (up) / ▼ (down).
|
||||
2. **7-day burn rate** — average daily spend over the last 7 days, as USD to 4 decimal places, plus a simple 30-day projection (`avg_daily × 30`).
|
||||
3. **Per-day mini-trend** — one line per day for the last 7 days: `<date> — $<spend to 4dp>` with a ▲/▼ vs. the prior day.
|
||||
|
||||
Currency as USD to 4 decimal places. Keep it to these three blocks — no long analysis.
|
||||
|
||||
If session dates and costs cannot be aligned precisely, state the approximation you made in one line rather than fabricating exact daily figures. If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: Quick total cost plus a per-model one-liner from the dashboard pricing engine.
|
||||
argument-hint: "[today|week]"
|
||||
---
|
||||
|
||||
Print a quick cost snapshot from the Agent Monitor dashboard pricing engine.
|
||||
|
||||
The user's scope is **$ARGUMENTS** (default `today` if empty; accepts `today` or `week`).
|
||||
|
||||
Fetch the fleet-wide cost breakdown:
|
||||
|
||||
```
|
||||
curl -s http://localhost:4820/api/pricing/cost
|
||||
```
|
||||
|
||||
This returns `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }`.
|
||||
|
||||
Then print, concisely:
|
||||
|
||||
1. **Total cost** — `total_cost` as USD to 4 decimal places, labeled with the scope (`$ARGUMENTS`).
|
||||
2. **Per-model one-liners** — one line per entry in `breakdown`, sorted by `cost` descending:
|
||||
`<model> — $<cost to 4dp> (in <input_tokens>, out <output_tokens>, cacheR <cache_read_tokens>, cacheW <cache_write_tokens>)`
|
||||
|
||||
Keep token counts with thousands separators. No tables, no preamble — just the total and the per-model lines.
|
||||
|
||||
Note: the endpoint returns lifetime totals; if the user asked for `today` or `week` and the data is not scoped, say so in one line rather than fabricating a windowed number. If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
description: List the top N most expensive Claude Code sessions by inline cost.
|
||||
argument-hint: "[N]"
|
||||
---
|
||||
|
||||
List the most expensive Claude Code sessions from the Agent Monitor dashboard.
|
||||
|
||||
`N` = **$ARGUMENTS** (default `10` if empty).
|
||||
|
||||
Fetch the session list (each session carries an inline `cost` field from bulk pricing):
|
||||
|
||||
```
|
||||
curl -s "http://localhost:4820/api/sessions?limit=200"
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
1. Sort sessions by `cost` descending.
|
||||
2. Print the top `N` as a numbered list, one line each:
|
||||
`<rank>. $<cost to 4dp> — <model> — <cwd basename or id> — <started_at>`
|
||||
3. After the list, print the **summed cost of the top N** and what percent that is of the summed cost of all returned sessions.
|
||||
|
||||
Currency as USD to 4 decimal places. Skip sessions with no/zero cost only if it would otherwise pad the list past meaningful entries — otherwise include them. Keep it terse, no extra commentary.
|
||||
|
||||
If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"hooks": {
|
||||
"Stop": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '{session_id: .session_id, stop_reason: .stop_reason, timestamp: now | todate}' | curl -s -X POST http://localhost:4820/api/hooks/event -H 'Content-Type: application/json' -d @- > /dev/null 2>&1 || true"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"SubagentStop": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '{session_id: .session_id, agent_id: .agent_id, stop_reason: .stop_reason, timestamp: now | todate}' | curl -s -X POST http://localhost:4820/api/hooks/event -H 'Content-Type: application/json' -d @- > /dev/null 2>&1 || true"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
description: >
|
||||
Analyze prompt-cache effectiveness for Claude Code usage from the Agent
|
||||
Monitor dashboard — cache hit rate (total_cache_read / (total_cache_read +
|
||||
total_input)), cache_write vs cache_read reuse, cache-read vs cache-write
|
||||
spend, and the sessions with the poorest reuse. Pulls token totals from
|
||||
/api/analytics, per-session detail from /api/sessions, and dollar splits
|
||||
from /api/pricing/cost. Use when diagnosing cache spend or deciding whether
|
||||
prompt caching is paying off.
|
||||
---
|
||||
|
||||
# Cache Efficiency
|
||||
|
||||
Diagnose whether prompt caching is actually saving money, and where it is not.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
This may be: empty (analyze the whole fleet), "today" / "this week" / a date range, a session ID to scope the analysis, or a target like "hit rate > 80%". When empty, analyze all data from `/api/analytics`.
|
||||
|
||||
## Data Sources
|
||||
|
||||
| Endpoint | Returns |
|
||||
|----------|---------|
|
||||
| `GET /api/analytics` | `tokens.total_input`, `tokens.total_output`, `tokens.total_cache_read`, `tokens.total_cache_write` (baselines pre-summed), plus `daily_sessions` |
|
||||
| `GET /api/sessions?limit=200` | Session list — each has model, cwd, started_at, ended_at, inline `cost`, metadata (JSON: usage_extras with cache token detail) |
|
||||
| `GET /api/sessions/{id}` | Full session detail with nested agents and events, for drill-down on a flagged session |
|
||||
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — used to price cache read vs write spend |
|
||||
|
||||
### How cache economics work
|
||||
|
||||
```
|
||||
cache_hit_rate = total_cache_read / (total_cache_read + total_input)
|
||||
cache_reuse = total_cache_read / total_cache_write
|
||||
cache_read_cost = (cache_read_tokens / 1M) × cache_read_per_mtok
|
||||
cache_write_cost = (cache_write_tokens / 1M) × cache_write_per_mtok
|
||||
```
|
||||
|
||||
Cache writes cost more per token than cache reads (e.g. Sonnet $3.75 write vs $0.30 read per Mtok), and writes are billed even if the cached block is never reused. The payoff only arrives on subsequent reads — so a healthy fleet shows **cache_read_tokens far exceeding cache_write_tokens**. When `cache_reuse < 1`, you are paying to cache context you barely re-read.
|
||||
|
||||
Token counts are **effective totals** = `current + baseline` (baselines preserve pre-compaction tokens).
|
||||
|
||||
## Report Sections
|
||||
|
||||
### 1. Fleet Cache Hit Rate
|
||||
From `/api/analytics`: compute `cache_hit_rate × 100`. State raw `total_cache_read` and `total_input`. Benchmark: >70% strong, 40–70% moderate, <40% weak prompt-cache utilization.
|
||||
|
||||
### 2. Write vs Read Reuse
|
||||
Compute `cache_reuse = total_cache_read / total_cache_write`. Show both token counts. Flag if reuse < 1 (writing more cache than is ever read back).
|
||||
|
||||
### 3. Cache Spend Split
|
||||
From `/api/pricing/cost` breakdown, sum `cache_read_cost` and `cache_write_cost` across all models. Show the dollar split and what fraction of total cost is cache-write overhead vs cache-read savings.
|
||||
|
||||
### 4. Sessions With Poor Reuse
|
||||
From `/api/sessions?limit=200`, parse `metadata.usage_extras` for per-session cache read/write where available; rank sessions by lowest read/write reuse (and by cache_write-heavy cost). List the worst 10 with model, cost, and reuse ratio. Use `/api/sessions/{id}` to drill into any single flagged session.
|
||||
|
||||
### 5. Recommendations
|
||||
- Sessions where `cache_write >> cache_read`: short or one-shot sessions rarely recoup cache writes — note them.
|
||||
- Stable, repeated context (system prompts, large files) should be cached once and reused; high churn defeats caching.
|
||||
- Estimate the dollar impact of raising the hit rate to the next benchmark tier.
|
||||
|
||||
## Output
|
||||
|
||||
Structured Markdown with tables. Currency as USD to 4 decimal places; rates as $/Mtok; percentages with ▲/▼ for any trend. Token counts with thousands separators.
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
description: >
|
||||
Break down Claude Code costs using the Agent Monitor pricing engine.
|
||||
Shows per-model costs (input, output, cache_read, cache_write at $/Mtok rates),
|
||||
per-session costs, daily trends, and compaction baseline token recovery.
|
||||
Use when analyzing spending, comparing model costs, or planning budgets.
|
||||
---
|
||||
|
||||
# Cost Breakdown
|
||||
|
||||
Detailed cost analysis from the Agent Monitor's pricing engine.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
This may be: "today", "this week", "last 30 days", a session ID, or "budget $50/week".
|
||||
|
||||
## Data Sources
|
||||
|
||||
| Endpoint | Returns |
|
||||
|----------|---------|
|
||||
| `GET /api/pricing` | `{ pricing: [{ model_pattern, display_name, input_per_mtok, output_per_mtok, cache_read_per_mtok, cache_write_per_mtok }] }` |
|
||||
| `GET /api/pricing/cost` | Total cost: `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` |
|
||||
| `GET /api/pricing/cost/{sessionId}` | Per-session cost with same breakdown shape |
|
||||
| `GET /api/sessions?limit=200` | Sessions list — each includes inline `cost` field (bulk pricing) |
|
||||
| `GET /api/analytics` | Token totals (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), daily trends |
|
||||
|
||||
### How costs are calculated
|
||||
|
||||
The pricing engine matches model names against `model_pattern` using SQL LIKE (e.g. `claude-sonnet-4-5%` matches `claude-sonnet-4-5-20250514`). **Longest pattern wins** for specificity. Cost per model:
|
||||
|
||||
```
|
||||
cost = (input_tokens / 1M) × input_per_mtok
|
||||
+ (output_tokens / 1M) × output_per_mtok
|
||||
+ (cache_read_tokens / 1M) × cache_read_per_mtok
|
||||
+ (cache_write_tokens / 1M) × cache_write_per_mtok
|
||||
```
|
||||
|
||||
Token counts are **effective totals** = `current + baseline` (baselines preserve pre-compaction tokens that would otherwise be lost when the transcript JSONL is rewritten).
|
||||
|
||||
### Default pricing tiers (seeded on first run)
|
||||
|
||||
| Family | Input $/Mtok | Output $/Mtok | Cache Read $/Mtok | Cache Write $/Mtok |
|
||||
|--------|-------------|--------------|-------------------|-------------------|
|
||||
| Opus 4.5/4.6 | $5 | $25 | $0.50 | $6.25 |
|
||||
| Sonnet 4/4.5/4.6 | $3 | $15 | $0.30 | $3.75 |
|
||||
| Haiku 4.5 | $1 | $5 | $0.10 | $1.25 |
|
||||
|
||||
## Report Sections
|
||||
|
||||
### 1. Cost by Model
|
||||
Table from `/api/pricing/cost` breakdown — each model with 4 token counts + cost. Highlight which pricing rule matched.
|
||||
|
||||
### 2. Cost by Session (Top 10 Most Expensive)
|
||||
From sessions list with inline `cost` — sort descending. Show session name, model, duration, cost.
|
||||
|
||||
### 3. Daily Cost Trend
|
||||
Cross-reference `daily_sessions` with per-session costs to compute daily spend. Show 7/30-day trend with direction arrows.
|
||||
|
||||
### 4. Token Efficiency Analysis
|
||||
- **Cache hit rate**: `total_cache_read / (total_cache_read + total_input) × 100` — higher = more efficient
|
||||
- **Compaction baseline recovery**: Tokens preserved via baseline columns (tokens not lost to compaction)
|
||||
- **Output/input ratio**: Balanced ratio indicates good prompt efficiency
|
||||
|
||||
### 5. Cost Optimization Opportunities
|
||||
- Sessions where cache_write >> cache_read (poor cache reuse)
|
||||
- Expensive models used for simple tasks (check subagent_type vs model)
|
||||
- Sessions with many compactions (context overflow = wasted tokens)
|
||||
|
||||
## Output
|
||||
|
||||
Structured Markdown with tables. Currency as USD to 4 decimal places. Include total and per-model subtotals.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
description: >
|
||||
Break down Claude Code usage by model family (Opus / Sonnet / Haiku) from the
|
||||
Agent Monitor dashboard — each family's share of tokens, share of cost, and
|
||||
the spots where an expensive model is doing cheap work. Pulls per-model token
|
||||
and cost splits from /api/pricing/cost, current rates from /api/pricing, fleet
|
||||
token totals from /api/analytics, and per-session model assignment from
|
||||
/api/sessions. Use when deciding model routing or whether to downshift work to
|
||||
a cheaper tier.
|
||||
---
|
||||
|
||||
# Model Mix
|
||||
|
||||
See where your tokens and dollars go by model family, and where to re-route work.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
This may be: empty (analyze the whole fleet), "today" / "this week" / a date range, or a focus like "where is Opus overused?". When empty, analyze all data from `/api/pricing/cost` and `/api/sessions`.
|
||||
|
||||
## Data Sources
|
||||
|
||||
| Endpoint | Returns |
|
||||
|----------|---------|
|
||||
| `GET /api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — per-model token and cost split |
|
||||
| `GET /api/pricing` | `{ pricing: [{ model_pattern, display_name, input_per_mtok, output_per_mtok, cache_read_per_mtok, cache_write_per_mtok }] }` — rates per family |
|
||||
| `GET /api/analytics` | `tokens` totals (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), `agent_types` for delegation context |
|
||||
| `GET /api/sessions?limit=200` | Session list — model, cwd, started_at, ended_at, inline `cost`, metadata (JSON: thinking_blocks, turn_count, total_turn_duration_ms, usage_extras) |
|
||||
|
||||
### How families and rates work
|
||||
|
||||
Map each `model` in the cost breakdown to a family from its `matched_rule` / `display_name`:
|
||||
|
||||
| Family | Input $/Mtok | Output $/Mtok | Cache Read $/Mtok | Cache Write $/Mtok |
|
||||
|--------|-------------|--------------|-------------------|-------------------|
|
||||
| Opus 4.5/4.6 | $5 | $25 | $0.50 | $6.25 |
|
||||
| Sonnet 4/4.5/4.6 | $3 | $15 | $0.30 | $3.75 |
|
||||
| Haiku 4.5 | $1 | $5 | $0.10 | $1.25 |
|
||||
|
||||
`cost = (tokens / 1M) × rate_per_mtok` summed over the 4 token types; longest `model_pattern` wins. Opus output costs ~5× Sonnet and ~5× Haiku per token, so a family's **cost share routinely exceeds its token share** — that gap is the routing signal.
|
||||
|
||||
## Report Sections
|
||||
|
||||
### 1. Token Share by Family
|
||||
Aggregate `input + output + cache_read + cache_write` tokens per family from `/api/pricing/cost`. Show each family's tokens and percent of total. Cross-check the grand total against `/api/analytics` token totals.
|
||||
|
||||
### 2. Cost Share by Family
|
||||
Sum `cost` per family. Show each family's dollar total and percent of `total_cost`. Place the cost-share % next to the token-share % so the premium gap is visible.
|
||||
|
||||
### 3. Cost-vs-Token Gap
|
||||
For each family compute `cost_share − token_share`. A large positive gap on Opus/Sonnet signals premium spend concentration. Rank families by gap.
|
||||
|
||||
### 4. Expensive Model on Cheap Work
|
||||
From `/api/sessions?limit=200`, find Opus/Sonnet sessions with signals of low complexity: low `turn_count`, short `total_turn_duration_ms`, few thinking_blocks, or small token footprints. List candidates that could plausibly run on a cheaper tier, with current cost and estimated cost if downshifted.
|
||||
|
||||
### 5. Routing Recommendations
|
||||
- Quantify the savings of moving each candidate workload to the next-cheaper family (recompute cost at that family's rates).
|
||||
- Note work that genuinely needs Opus (deep reasoning, long context) and should stay.
|
||||
- Summarize a suggested routing policy (e.g. Haiku for mechanical edits, Sonnet for default dev, Opus for hard reasoning).
|
||||
|
||||
## Output
|
||||
|
||||
Structured Markdown with tables. Currency as USD to 4 decimal places; rates as $/Mtok; token shares and cost shares as percentages; use ▲/▼ for the cost-vs-token gap and any trend. Token counts with thousands separators.
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
description: >
|
||||
Calculate a productivity score using actual Agent Monitor metrics —
|
||||
session completion rates, cache efficiency (cache_read vs input),
|
||||
compaction pressure (baseline tokens), turn velocity (turn_count /
|
||||
total_turn_duration_ms), tool success ratio (PreToolUse vs PostToolUse),
|
||||
and the workflow intelligence API's complexity and effectiveness scores.
|
||||
---
|
||||
|
||||
# Productivity Score
|
||||
|
||||
Calculate a productivity scorecard from the Agent Monitor's real data.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
Options: "today", "this week", "last 30 days", a session ID, or "compare" for period comparison.
|
||||
|
||||
## Data Sources
|
||||
|
||||
| Endpoint | Returns |
|
||||
|----------|---------|
|
||||
| `GET /api/analytics` | Token totals (`total_input`, `total_output`, `total_cache_read`, `total_cache_write` — baselines pre-summed), tool_usage top 20, daily_events/sessions, event_types, sessions_by_status, agents_by_status, avg_events_per_session, total_subagents |
|
||||
| `GET /api/sessions?limit=100` | Sessions with metadata JSON: `thinking_blocks`, `turn_count`, `total_turn_duration_ms`, `usage_extras` (service_tier, speed, inference_geo) |
|
||||
| `GET /api/pricing/cost` | Total cost with per-model breakdown |
|
||||
| `GET /api/workflows/{sessionId}` | 11 workflow datasets: stats, orchestration, toolFlow, effectiveness, patterns, modelDelegation, errorPropagation, concurrency, complexity, compaction, cooccurrence |
|
||||
|
||||
## Score Components (each 0–100)
|
||||
|
||||
### 1. Completion Rate (20% weight)
|
||||
From `sessions_by_status`:
|
||||
- `completed / (completed + error + abandoned) × 100`
|
||||
- Bonus for high completed-to-active ratio
|
||||
- Penalty for abandoned sessions (wasted work)
|
||||
|
||||
### 2. Token Efficiency (20% weight)
|
||||
From analytics `tokens` (baselines are pre-summed into totals):
|
||||
- **Cache hit rate**: `total_cache_read / (total_cache_read + total_input) × 100`
|
||||
- Above 60% = excellent, below 30% = poor
|
||||
- **Output concentration**: `total_output / total_input` — 0.3–0.8 is balanced
|
||||
|
||||
### 3. Tool Effectiveness (20% weight)
|
||||
From `event_types`:
|
||||
- **Success ratio**: Count `PostToolUse` / Count `PreToolUse` — should be ~1.0; gap = tool failures
|
||||
- **API error rate**: Count `APIError` / total events — should be near 0
|
||||
- From workflow `effectiveness` data: subagent completion rates, task success per type
|
||||
|
||||
### 4. Velocity (20% weight)
|
||||
From session metadata:
|
||||
- **Turns per session**: average `turn_count` across sessions
|
||||
- **Turn speed**: average `total_turn_duration_ms / turn_count` — lower = faster
|
||||
- **Events per session**: from `avg_events_per_session` in analytics overview
|
||||
- **Thinking depth**: average `thinking_blocks` — more thinking = more thorough (neutral metric)
|
||||
|
||||
### 5. Cost Efficiency (20% weight)
|
||||
From pricing:
|
||||
- **Cost per completed session**: `total_cost / completed_sessions`
|
||||
- **Cost trend**: comparing current period to previous (decreasing = improving)
|
||||
- **Model optimization**: sessions using expensive models (Opus) for tasks subagents handle with Haiku/Sonnet
|
||||
|
||||
## Overall Score
|
||||
|
||||
Weighted sum → letter grade:
|
||||
- **A+** (95-100), **A** (90-94), **B+** (85-89), **B** (80-84), **C+** (75-79), **C** (70-74), **D** (60-69), **F** (<60)
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
═══════════════════════════════════════
|
||||
PRODUCTIVITY SCORE: 87/100 (B+)
|
||||
═══════════════════════════════════════
|
||||
Completion Rate ████████░░ 80/100
|
||||
Token Efficiency █████████░ 92/100
|
||||
Tool Effectiveness████████░░ 85/100
|
||||
Velocity █████████░ 88/100
|
||||
Cost Efficiency █████████░ 90/100
|
||||
═══════════════════════════════════════
|
||||
```
|
||||
|
||||
Then: top 3 strengths, top 3 improvement areas with actionable steps, and period comparison if available.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
description: >
|
||||
Generate a comprehensive session report with per-model token usage
|
||||
(input, output, cache_read, cache_write including compaction baselines),
|
||||
cost breakdown via the pricing engine, tool invocations, agent hierarchy,
|
||||
compaction events, API errors, turn durations, and thinking block counts.
|
||||
Use when reviewing a specific session or summarizing activity over a date range.
|
||||
---
|
||||
|
||||
# Session Report
|
||||
|
||||
Generate a detailed session report from the Claude Code Agent Monitor.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
This may be a session ID, "latest", or a date range like "last 24 hours".
|
||||
|
||||
## Data Sources
|
||||
|
||||
All data comes from the Agent Monitor API at `http://localhost:4820`:
|
||||
|
||||
| Endpoint | What it returns |
|
||||
|----------|----------------|
|
||||
| `GET /api/sessions/{id}` | Session with nested `.agents[]` and `.events[]` |
|
||||
| `GET /api/sessions?limit=50` | Session list with `agent_count`, `last_activity`, and **inline `cost`** per session (bulk pricing applied server-side) |
|
||||
| `GET /api/pricing/cost/{sessionId}` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` |
|
||||
| `GET /api/events?session_id={id}` | Event stream: each has `event_type`, `tool_name`, `summary`, `data` (JSON), `created_at` |
|
||||
|
||||
### Key data points available per session
|
||||
|
||||
- **Status**: `active` / `completed` / `error` / `abandoned`
|
||||
- **Model**: primary model (e.g. `claude-sonnet-4-20250514`)
|
||||
- **Metadata (JSON)**: `thinking_blocks` count, `turn_count`, `total_turn_duration_ms`, `usage_extras` (service_tier, speed, inference_geo)
|
||||
- **Token usage per model**: Pricing breakdown reports `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens` per model (baselines are pre-summed into these totals at the DB level)
|
||||
- **Cost formula**: `(tokens / 1,000,000) × rate_per_mtok` for each of 4 token types, using longest-match pricing rule
|
||||
- **Agent hierarchy**: recursive parent_agent_id tree, subagent_type (e.g. "task", "explore", "code-review", "compaction")
|
||||
- **Event types**: `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStop`, `SessionStart`, `SessionEnd`, `Notification`, `Compaction`, `APIError`, `TurnDuration`
|
||||
|
||||
## Report Sections
|
||||
|
||||
### 1. Session Overview
|
||||
- ID (first 16 chars), name, status, model, working directory
|
||||
- Start → end time, total duration
|
||||
- Turn count and avg turn duration (from metadata)
|
||||
|
||||
### 2. Token Usage (per model)
|
||||
| Model | Input | Output | Cache Read | Cache Write | Total |
|
||||
Show **effective totals** (current + baseline) since baselines preserve tokens lost during compaction. Calculate cache hit rate: `cache_read / (cache_read + input) × 100`.
|
||||
|
||||
### 3. Cost Breakdown
|
||||
From `/api/pricing/cost/{id}` — show each model's cost with the matched pricing rule. Note rates are per million tokens.
|
||||
|
||||
### 4. Agent Hierarchy
|
||||
Render the agent tree (main → subagents, with nested children). For each agent: name, type, subagent_type, status, task (first 60 chars), duration.
|
||||
|
||||
### 5. Tool Activity
|
||||
Count `PreToolUse` events by `tool_name`. Flag tools that appear in error events. Note subagent spawns (`tool_name = "Agent"`).
|
||||
|
||||
### 6. Compaction & Context Health
|
||||
- Count of `Compaction` events (each = context was compressed)
|
||||
- Baseline tokens recovered (sum of baseline_* columns)
|
||||
- Thinking block count from metadata
|
||||
|
||||
### 7. API Errors
|
||||
List any `APIError` events with type (quota, rate_limit, overloaded) and message.
|
||||
|
||||
### 8. Timeline
|
||||
Key lifecycle events: SessionStart → first tool → compactions → errors → Stop → SessionEnd. Include TurnDuration events.
|
||||
|
||||
## Output Format
|
||||
|
||||
Clean Markdown: executive summary line, structured tables, agent tree, numbered timeline. Bold key metrics.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
description: >
|
||||
Analyze Claude Code usage trends over time using the Agent Monitor's
|
||||
analytics API — daily session counts, daily event counts, token volumes
|
||||
by type, model distribution, tool usage rankings, and agent/event type
|
||||
distributions across 365-day retention windows.
|
||||
---
|
||||
|
||||
# Usage Trends
|
||||
|
||||
Analyze usage patterns and trends from the Agent Monitor analytics data.
|
||||
|
||||
## Input
|
||||
|
||||
The user provides: **$ARGUMENTS**
|
||||
|
||||
Options: "last 7 days", "last 30 days", "last quarter", "peak hours", "tool trends", "model usage".
|
||||
|
||||
## Data Sources
|
||||
|
||||
| Endpoint | Returns |
|
||||
|----------|---------|
|
||||
| `GET /api/analytics` | Comprehensive analytics object (see schema below) |
|
||||
| `GET /api/stats` | `{ total_sessions, active_sessions, active_agents, total_agents, total_events, events_today, ws_connections, agents_by_status, sessions_by_status }` |
|
||||
| `GET /api/sessions?limit=200` | Full session records with timestamps and metadata |
|
||||
|
||||
### Analytics response schema (`GET /api/analytics`)
|
||||
|
||||
```json
|
||||
{
|
||||
"overview": { "total_sessions", "active_sessions", "active_agents", "total_agents", "total_events" },
|
||||
"tokens": {
|
||||
"total_input": N, "total_output": N,
|
||||
"total_cache_read": N, "total_cache_write": N
|
||||
},
|
||||
"tool_usage": [{ "tool_name": "...", "count": N }], // top 20
|
||||
"daily_events": [{ "date": "YYYY-MM-DD", "count": N }], // 365 days
|
||||
"daily_sessions": [{ "date": "YYYY-MM-DD", "count": N }], // 365 days
|
||||
"agent_types": [{ "subagent_type": "task"|"explore"|null, "count": N }],
|
||||
"event_types": [{ "event_type": "PreToolUse"|"PostToolUse"|..., "count": N }],
|
||||
"avg_events_per_session": N,
|
||||
"total_subagents": N,
|
||||
"sessions_by_status": { "active": N, "completed": N, "error": N, "abandoned": N },
|
||||
"agents_by_status": { "working": N, "completed": N, "error": N, ... }
|
||||
}
|
||||
```
|
||||
|
||||
## Trend Analyses to Produce
|
||||
|
||||
### 1. Daily Activity Trend
|
||||
Plot `daily_sessions` and `daily_events` for the requested period. Compute:
|
||||
- **Average sessions/day** and **events/day**
|
||||
- Week-over-week delta (%)
|
||||
- Peak day and quietest day
|
||||
|
||||
### 2. Token Volume Trends
|
||||
From analytics tokens (baselines are pre-summed into totals at the DB level):
|
||||
- Total tokens: `total_input`, `total_output`, `total_cache_read`, `total_cache_write`
|
||||
- **Cache efficiency over time**: `total_cache_read / (total_cache_read + total_input)` — trending up = improving
|
||||
- **Output intensity**: `total_output / total_input` ratio — high = Claude is verbose
|
||||
|
||||
### 3. Tool Usage Ranking
|
||||
From `tool_usage` (top 20 tools by event count):
|
||||
- Bar chart data (tool name → count)
|
||||
- Tool diversity: unique tools used
|
||||
- Subagent spawns: count of "Agent" tool uses (each = a subagent launched)
|
||||
|
||||
### 4. Model Distribution
|
||||
From `agent_types` + per-session model field:
|
||||
- Which models are used most frequently
|
||||
- Subagent type distribution: main (null) vs task vs explore vs code-review
|
||||
|
||||
### 5. Session Health Distribution
|
||||
From `sessions_by_status`:
|
||||
- Completion rate: `completed / total × 100`
|
||||
- Error rate: `error / total × 100`
|
||||
- Abandoned rate: `abandoned / total × 100`
|
||||
|
||||
### 6. Event Type Distribution
|
||||
From `event_types`:
|
||||
- PreToolUse/PostToolUse ratio (should be ~1:1; gap = tools failing)
|
||||
- Compaction frequency relative to session count
|
||||
- APIError count (quota hits, rate limits, overloaded)
|
||||
|
||||
## Output
|
||||
|
||||
Markdown with tables and ASCII trend indicators (▲▼→). Include period comparison when applicable.
|
||||
Reference in New Issue
Block a user