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,64 @@
---
description: >
Generate a daily standup summary from recent Claude Code sessions — completed
work grouped by project (cwd), session costs from the pricing engine,
tool invocations, error/compaction/APIError events, and turn velocity
metrics from session metadata (turn_count, total_turn_duration_ms).
---
# Daily Standup
Generate a daily standup report from Claude Code Agent Monitor data.
## Input
The user provides: **$ARGUMENTS**
This may be:
- "today" or empty (default: last 24 hours)
- "yesterday" for the previous day
- A specific date: "2025-04-10"
## Procedure
1. **Fetch recent session data** from `http://localhost:4820`:
- `GET /api/sessions?limit=50` (default sort: most recently updated first)
- Filter sessions that started within the target day
- For each matching session: `GET /api/events?session_id={session_id}`
2. **Compile standup sections**:
### ✅ What I accomplished
- List each completed session with:
- Brief description (from session name or first tool's context)
- Working directory (project context)
- Key tools used and outcomes
- Duration and model used
- Group by project/working directory if multiple
### ⚠️ Issues encountered
- Sessions that ended in `error` or `abandoned` status
- Tools that failed (from error events)
- Compaction events (hit context limits)
- Unusually long sessions (>2x average duration)
### 📋 Key metrics
- Total sessions: N
- Total time spent: X hours Y minutes
- Tools invoked: N (top 3 listed)
- Estimated cost: $X.XX
- Completion rate: N%
### 🔮 Suggested focus areas
- Based on incomplete/error sessions, suggest what to revisit
- Based on tool patterns, suggest workflow improvements
3. **Format for standup**:
- Keep it concise — aim for a 2-minute read
- Lead with accomplishments
- Be honest about blockers
- Make metrics scannable
## Output Format
Present as a clean standup report with emoji section headers, bullet points for items, and a compact metrics table. Add a one-line summary at the top suitable for pasting into Slack or a team channel.
@@ -0,0 +1,77 @@
---
description: >
Compile a month-over-month retrospective from Agent Monitor data — sessions,
cost, token volumes, completion rate, top projects by working directory, and
notable shifts versus the prior month. Uses daily_sessions/daily_events (365d)
from analytics, the session list, and the pricing cost breakdown. Use when
doing a monthly retrospective or planning the month ahead.
---
# Monthly Review
Generate a month-over-month productivity retrospective from Agent Monitor data.
## Input
The user provides: **$ARGUMENTS**
This may be:
- "this month" or empty (default: the current calendar month to date)
- "last month" for the previous full calendar month
- A specific month: "2026-02" or "February 2026"
The comparison period is always the immediately preceding calendar month.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/analytics` | `daily_sessions` and `daily_events` (365d) for monthly bucketing and trends; `tokens` (total_input/output/cache_read/cache_write — baselines pre-summed); `tool_usage` (top 20); `sessions_by_status` |
| `GET /api/sessions?limit=500` | Sessions with `started_at`, `ended_at`, `status`, `model`, `cwd`, `cost`, and `metadata` (turn_count, thinking_blocks) — for per-project (cwd) grouping and completion rate |
| `GET /api/pricing/cost` | `total_cost` and per-model `breakdown` (input/output/cache tokens, cost, matched_rule) |
## Report Sections
### 1. Month at a Glance
Compare the target month to the prior month in a table:
| Metric | This Month | Last Month | Change |
|--------|-----------|------------|--------|
| Sessions | N | N | ▲/▼ N% |
| Total Cost | $X.XXXX | $X.XXXX | ▲/▼ N% |
| Tokens (in/out/cache) | N | N | ▲/▼ N% |
| Completion Rate | N% | N% | ▲/▼ N pts |
| Active Days | N | N | ▲/▼ |
Derive monthly buckets from `daily_sessions` / `daily_events`. Completion rate =
`completed sessions / total sessions` for the month (from `sessions_by_status` and
the filtered session list).
### 2. Top Projects (by cwd)
Group the month's sessions by `cwd`. For the top 58 projects, list session count,
total cost, completion rate, and dominant model. Note any project that newly
appeared or dropped off versus last month.
### 3. Cost & Token Breakdown
From `/api/pricing/cost`, show cost per model and the dominant token type. Compute
cache hit rate = `total_cache_read / (total_cache_read + total_input)` and compare
to last month. Currency to 4 decimals.
### 4. Tool & Workflow Shifts
From `tool_usage`, highlight the tools that rose or fell most month-over-month, and
any new tool adopted. Flag rising error/Compaction activity if present.
### 5. Notable Shifts & Narrative
Three to five plain-language observations: what changed, why it likely changed, and
what it implies (e.g., "cost up 22% but sessions flat → heavier per-session work").
### 6. Focus for Next Month
Two to four prioritized, actionable goals grounded in the numbers above.
## Output
- Markdown report with emoji-light, scannable section headers.
- Tables for all month-over-month comparisons; ▲ / ▼ for deltas.
- Currency in USD to 4 decimals; tokens with thousands separators.
- Lead with a 23 sentence executive summary, then the sections in order.
- Cite only numbers returned by the API; if a month has no data, say so explicitly.
@@ -0,0 +1,77 @@
---
description: >
Summarize a sprint's worth of Claude Code activity — sessions grouped by
project (cwd), per-model cost breakdown, token efficiency (cache hit rate,
compaction baselines), subagent effectiveness from workflow API, velocity
metrics (turn_count, turn_duration_ms), and tool diversity across the sprint.
---
# Sprint Summary
Generate a sprint summary from Claude Code Agent Monitor data.
## Input
The user provides: **$ARGUMENTS**
This may be:
- A sprint duration: "last 2 weeks", "last 10 days"
- A date range: "2025-03-31 to 2025-04-13"
- "current sprint" (default: last 14 days)
## Procedure
1. **Fetch sprint data** from `http://localhost:4820`:
- `GET /api/sessions?limit=500` — all sessions in range (default sort: most recently updated first)
- `GET /api/analytics` — aggregated metrics
- `GET /api/pricing/cost` — total costs
- For high-value sessions: `GET /api/events?session_id={id}` — event details
2. **Compile sprint summary**:
### 🎯 Sprint Overview
- Sprint period: [start] to [end]
- Total sessions: N (completed: N, errored: N, abandoned: N)
- Total development hours with Claude Code: N
- Total cost: $X.XX
- Overall completion rate: N%
### 📦 Deliverables
Group sessions by working directory (project):
- **Project A** (`/path/to/project`)
- N sessions, N hours, key activities
- **Project B** (`/path/to/other`)
- N sessions, N hours, key activities
### 📊 Velocity Metrics
| Metric | Sprint | Previous Sprint | Trend |
|--------|--------|-----------------|-------|
| Sessions/day | N | N | ↑/↓ |
| Avg session duration | Nm | Nm | ↑/↓ |
| Cost/session | $N | $N | ↑/↓ |
| Tokens/session | N | N | ↑/↓ |
| Completion rate | N% | N% | ↑/↓ |
### 🛠 Technology Breakdown
- Models used with distribution percentages
- Top 15 tools by usage with category grouping
- Subagent utilization rate
### ⚡ Efficiency Analysis
- Token efficiency: cache hit rate, compaction frequency
- Cost per completed task
- Time-to-first-output (avg across sessions)
- Error recovery rate (sessions that recovered from errors)
### 🔄 Retrospective Data Points
- **What went well**: Highest-efficiency sessions, best completion rates
- **What could improve**: Most expensive sessions, highest error rates
- **Action items**: Data-driven suggestions for next sprint
## Output Format
Professional sprint report suitable for sharing with team leads or managers:
- Executive summary paragraph (5 sentences max)
- Structured data tables with trend indicators
- Grouped deliverables by project
- Numbered action items at the end
@@ -0,0 +1,65 @@
---
description: >
Discover when you are most active and most productive with Claude Code by
bucketing sessions and events into hour-of-day and day-of-week bins from their
timestamps, then flagging peak versus low-output windows. Uses the session
list, per-session events, and analytics daily trends. Use when planning a
schedule or deciding when to do deep work versus lighter tasks.
---
# Time of Day
Profile activity and productivity across the hours of the day and days of the week.
## Input
The user provides: **$ARGUMENTS**
This may be:
- empty or "all" (default: all available sessions)
- a window like "last 30 days" or "last 90 days" to limit the analysis
- a project path to scope the analysis to one `cwd`
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/sessions?limit=500` | Sessions with `started_at`, `ended_at`, `status`, `cwd`, `cost`, and `metadata` (turn_count, total_turn_duration_ms) — primary source for hour/weekday bucketing |
| `GET /api/events?session_id=X` | Events with `timestamp` and `event_type` (PreToolUse, PostToolUse, Stop, Compaction, APIError, etc.) — finer-grained activity within sessions and error timing |
| `GET /api/analytics` | `daily_sessions` / `daily_events` (365d) and `sessions_by_status` for trend context and completion baselines |
## Report Sections
### 1. Activity by Hour of Day
Bucket sessions (by `started_at`) and events (by `timestamp`) into 24 hourly bins.
Show a text bar chart of session and event counts per hour. Identify the busiest
hours by raw volume.
### 2. Productivity by Hour of Day
For each hour bin, compute completion rate (`completed / total` sessions started in
that hour) and average sustained turn time
(`total_turn_duration_ms / turn_count`, ms → minutes). Distinguish "active" hours
(high volume) from "productive" hours (high completion + sustained turns).
### 3. Day-of-Week Pattern
Bucket the same metrics into 7 weekday bins. Table: weekday, sessions, completion
rate, avg cost, dominant model.
### 4. Peak vs. Low-Output Windows
- **Peak windows:** hours/days with high completion rate and long sustained turns.
- **Low-output windows:** hours/days with high abandonment/error/Compaction rates
or fragmented short turns. Pull error timing from `/api/events` event types
(APIError, Compaction) to corroborate.
### 5. Schedule Recommendation
Suggest which hour/weekday blocks to reserve for deep work and which to use for
lighter or shallower tasks, grounded in the buckets above.
## Output
- Markdown with text-based bar charts (e.g., `09:00 ████████ 24`) for the hourly
and weekday distributions.
- Tables for the hour and weekday metrics; ▲ / ▼ for above/below the overall mean.
- Currency in USD to 4 decimals; durations in minutes (convert from ms).
- Cite only numbers from the API. State how many sessions/events were bucketed and
exclude sessions missing `started_at` or the focus metadata, noting the count.
@@ -0,0 +1,73 @@
---
description: >
Compile a weekly productivity report using Agent Monitor data — daily_sessions
and daily_events trends, per-session costs from pricing engine, token volumes
(input/output/cache_read/cache_write + baselines), tool usage top 20,
session completion rates by status, and workflow intelligence metrics.
---
# Weekly Report
Generate a comprehensive weekly productivity report from Agent Monitor data.
## Input
The user provides: **$ARGUMENTS**
This may be:
- "this week" or empty (default: current week Mon-Sun)
- "last week" for the previous week
- A date range: "2025-04-07 to 2025-04-13"
## Procedure
1. **Fetch weekly data** from `http://localhost:4820`:
- `GET /api/sessions?limit=200` — filter to target week (default sort: most recently updated first)
- `GET /api/analytics` — aggregated analytics
- `GET /api/pricing/cost` — cost data
2. **Build the weekly report**:
### 📊 Week at a Glance
| Metric | This Week | Last Week | Change |
|--------|-----------|-----------|--------|
| Sessions | N | N | ↑/↓ N% |
| Total Hours | N | N | ↑/↓ N% |
| Tokens Used | N | N | ↑/↓ N% |
| Total Cost | $X.XX | $X.XX | ↑/↓ N% |
| Completion Rate | N% | N% | ↑/↓ |
### 🏆 Highlights
- Most productive day (by sessions completed)
- Longest session and what it accomplished
- Most used tools and any new tools adopted
- Notable achievements (complex tasks completed, errors resolved)
### 📈 Daily Breakdown
| Day | Sessions | Hours | Cost | Completion |
|-----|----------|-------|------|------------|
For each day of the week with activity.
### 🔧 Tool Usage Report
- Top 10 tools by invocation count
- Tools with highest error rate
- Tool usage distribution chart (text-based)
### 💡 Productivity Insights
- Peak productivity hours
- Average session duration and trend
- Cost efficiency trend
- Model usage distribution
### 🎯 Recommendations for Next Week
- Based on error patterns: what to improve
- Based on cost trends: optimization opportunities
- Based on tool usage: workflow suggestions
## Output Format
Professional report format with:
- Executive summary (3 sentences max)
- Structured tables with week-over-week comparisons
- Emoji-prefixed section headers for scannability
- Actionable recommendations in priority order
@@ -0,0 +1,96 @@
---
description: >
Analyze workflow patterns using the Agent Monitor's workflow intelligence
API — orchestration DAGs, tool flow transitions, subagent effectiveness,
model delegation patterns, error propagation by depth, concurrency lanes,
compaction impact, and agent co-occurrence. Produces prioritized optimization
recommendations with quantified impact.
---
# Workflow Optimizer
Analyze Claude Code workflows using the Agent Monitor's workflow intelligence engine.
## Input
The user provides: **$ARGUMENTS**
Options: "analyze", a session ID for single-session analysis, or a focus: "tools", "subagents", "cost", "errors".
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/sessions?limit=100` | Session list with metadata |
| `GET /api/workflows/{sessionId}` | **11 workflow datasets** (see below) |
| `GET /api/analytics` | Tool usage top 20, event types, agent types |
| `GET /api/pricing` | Model pricing rules for cost comparison |
### Workflow Intelligence API (`GET /api/workflows/{sessionId}`)
Returns these 11 datasets per session:
| Dataset | Content |
|---------|---------|
| `stats` | Aggregate session stats: tool count, agent depth, event count |
| `orchestration` | **DAG**: agent nodes with parent/child edges, depths, types |
| `toolFlow` | **Transition matrix**: tool A → tool B with counts (common sequences) |
| `effectiveness` | **Subagent success**: per-type completion rates, avg duration, task success |
| `patterns` | **Recurring sequences**: detected workflow patterns with frequency |
| `modelDelegation` | **Model choices**: which models are delegated which tasks |
| `errorPropagation` | **Error flow by depth**: where in the agent tree errors originate and propagate |
| `concurrency` | **Concurrency lanes**: overlapping agent execution timelines |
| `complexity` | **Complexity score**: numerical score based on depth, breadth, tool diversity |
| `compaction` | **Compaction impact**: token savings, frequency, context health |
| `cooccurrence` | **Agent pairs**: which agents frequently run together |
## Optimization Analyses
### 1. Tool Flow Optimization
From `toolFlow` transition data:
- Identify the most common tool sequences (e.g., Read → Edit → Bash)
- Find redundant transitions (same tool called repeatedly = retries)
- Detect anti-patterns: high-frequency failure loops
- Recommend tool chain shortcuts
### 2. Subagent Strategy
From `effectiveness` + `orchestration`:
- Which subagent types (task, explore, code-review) have highest completion rates
- Average duration per subagent type — are subagents taking too long?
- Underutilized types: tasks that could benefit from delegation
- Over-spawning: too many subagents for simple tasks
### 3. Model Delegation Analysis
From `modelDelegation`:
- Which models handle which task types
- Cost-per-task comparison across models
- Opportunities to delegate simple tasks to cheaper models (Haiku/Sonnet instead of Opus)
- Calculate estimated savings from model rebalancing
### 4. Error Prevention
From `errorPropagation`:
- Where errors originate (agent depth level)
- How errors cascade to parent agents
- Error types (APIError, tool failure) by frequency
- Defensive strategies: which patterns lead to fewer errors
### 5. Concurrency Optimization
From `concurrency`:
- Which agents run in parallel vs sequential
- Bottlenecks: sequential agents that could be parallelized
- Resource contention: overlapping heavy tasks
### 6. Context Health
From `compaction`:
- How often compaction occurs per session
- Token recovery from compaction baselines
- Sessions that hit context limits — suggest breaking into smaller tasks
## Output
Prioritized recommendations table:
| # | Recommendation | Source Data | Impact | Effort | Est. Savings |
|---|---------------|-------------|--------|--------|-------------|
Top 5 recommendations with detailed explanation, supporting data from the workflow API, and implementation steps.