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:
2026-07-29 17:07:45 +07:00
commit 57dc91585d
783 changed files with 221743 additions and 0 deletions
@@ -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, 4070% 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 0100)
### 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.30.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.