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,77 @@
---
description: >
Export Claude Code session and analytics data in JSON, CSV, or Markdown
formats. Supports exporting sessions, events, costs, and analytics
for external analysis or reporting. Use for data backup or integration.
---
# Data Export
Export Agent Monitor data in various formats.
## Input
The user provides: **$ARGUMENTS**
This may be:
- A data type: "sessions", "events", "analytics", "costs", "all"
- A format: "json", "csv", "markdown" (default: json)
- A filter: "last 7 days", "session {id}", "completed only"
- Combined: "sessions csv last 30 days"
## Procedure
1. **Parse the request** to determine:
- Data scope: which data to export
- Format: output format
- Filters: time range, status, session ID
2. **Fetch data** from `http://localhost:4820`:
- Sessions: `GET /api/sessions?limit=1000`
- Events: `GET /api/events?limit=5000`
- Analytics: `GET /api/analytics`
- Costs: `GET /api/pricing/cost`
- Full export: `GET /api/settings/export`
3. **Transform to requested format**:
### JSON Format
Pretty-printed JSON with metadata header:
```json
{
"export": {
"source": "Claude Code Agent Monitor",
"exported_at": "2025-04-11T12:00:00Z",
"filters": { "type": "sessions", "range": "last 7 days" },
"count": 42
},
"data": [...]
}
```
### CSV Format
Standard CSV with headers, proper quoting, and ISO timestamps:
```
id,name,status,model,started_at,ended_at,duration_minutes,cost_usd
```
### Markdown Format
Human-readable tables with summary statistics:
```markdown
# Agent Monitor Export — Sessions (Last 7 Days)
| ID | Name | Status | Model | Duration | Cost |
|...
**Total: 42 sessions, $12.34 cost**
```
4. **Output the data**:
- For small exports (<100 rows): output directly
- For large exports: save to file and report the path
- Include row count and any filter notes
## Output Format
Deliver the exported data in the requested format. Always include:
- Export metadata (when, what, filters applied)
- Row/record count
- Suggested filename for saving
@@ -0,0 +1,72 @@
---
description: >
Trace the full event chain for one Claude Code session into an ordered
timeline of every event type with tool_name and summary, highlighting gaps,
out-of-order events, and failures. Reads /api/events?session_id= and
/api/sessions/:id from the Agent Monitor dashboard. Use when debugging what a
session actually did, step by step.
---
# Event Trace
Build a chronological, annotated event timeline for a single session.
## Input
The user provides: **$ARGUMENTS**
This is a session ID. It may also be:
- `latest` / `last` — trace the most recently updated session
- `errors` — trace the most recent session whose status is `error`
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/sessions?limit=N` | session list (used to resolve `latest`/`errors` and the target id) |
| `GET /api/sessions/:id` | full session detail (status, model, cwd, started_at, ended_at, cost, nested agents + events) |
| `GET /api/events?session_id=X` | the ordered event stream: event_type, tool_name, summary, data, timestamp |
## Report Sections
### 1. Resolve the session
If `$ARGUMENTS` is a raw id, use it. If `latest`/`last`, call
`GET /api/sessions?limit=1`. If `errors`, call
`GET /api/sessions?limit=10&status=error` and pick the newest. Confirm the id
resolves via `GET /api/sessions/:id`; if not, report it as missing and stop.
### 2. Session header
From `GET /api/sessions/:id`: id, status, model, cwd, started_at → ended_at,
total duration, cost (USD to 4 decimals), and counts (events, agents).
### 3. Ordered timeline
From `GET /api/events?session_id=X`, list every event in timestamp order. One row
per event:
`| # | time | Δ since prev | event_type | tool_name | summary |`
Cover all event types present: SessionStart, PreToolUse, PostToolUse, Stop,
SubagentStop, Compaction, APIError, TurnDuration, Notification, SessionEnd.
### 4. Gap & failure highlights
Annotate the timeline:
- **Gaps**: any Δ > 30s between consecutive events — mark ⏳ and note the wait.
- **Unpaired tool calls**: a PreToolUse with no matching PostToolUse (same
tool_name, next in stream) — mark ⚠️ "no completion recorded".
- **Failures**: APIError events and PostToolUse whose `summary`/`data` indicates
an error — mark ❌ with the error text.
- **Compaction**: mark ♻️ and note it resets the visible token baseline.
- **Missing bookends**: no SessionStart at the head or no Stop/SessionEnd at the
tail of an ended session — mark 🚩.
### 5. Verdict
One line: CLEAN, GAPS DETECTED, or FAILURES PRESENT — with the count of each
flag type and the single most likely thing to investigate next.
## Output
- Markdown timeline table, events in strict timestamp order.
- Status glyphs inline: ✅ ok, ❌ error, ⚠️ warning/unpaired, ⏳ gap, ♻️ compaction, 🚩 missing bookend.
- Currency in USD to 4 decimals.
- Cite only event data returned by the API — do not invent timestamps or summaries.
- If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.
@@ -0,0 +1,93 @@
---
description: >
Run comprehensive health checks on the Claude Code Agent Monitor system.
Validates dashboard API, database, WebSocket, hooks, and disk usage.
Use to verify the monitoring setup is working correctly.
---
# Health Check
Run a comprehensive health check on the Agent Monitor system.
## Input
The user provides: **$ARGUMENTS**
This may be:
- "full" or empty (default: run all checks)
- "quick" for a fast connectivity check
- "deep" for extended checks including database integrity
## Procedure
Run health checks in this order:
### 1. API Health
```bash
curl -sf http://localhost:4820/api/health
```
- Verify HTTP 200 response
- Check response time (<500ms expected, <1000ms acceptable)
- Confirm JSON response body
### 2. Database Health
```bash
curl -sf http://localhost:4820/api/stats
```
- Verify stats endpoint returns valid data
- Check that counts are non-negative integers
- Verify database file exists and has reasonable size
### 3. WebSocket Health
- Check that the WebSocket server is listening
- Verify WebSocket upgrade is supported on the dashboard port
### 4. API Endpoint Validation
Test each major endpoint:
```bash
curl -sf http://localhost:4820/api/sessions?limit=1
curl -sf http://localhost:4820/api/events?limit=1
curl -sf http://localhost:4820/api/analytics
curl -sf http://localhost:4820/api/pricing
curl -sf http://localhost:4820/api/settings/info
```
### 5. Hook Integration
- Verify hook handler script exists
- Check hooks are configured in `~/.claude/settings.json`
- Verify the handler script targets the correct dashboard URL
### 6. Disk & Resource Usage (deep mode only)
- Database file size
- Log file sizes (if any)
- Available disk space
- Node.js process memory usage (if accessible)
### 7. Data Freshness
- Time since last event ingested
- Time since last session created
- Check for stale active sessions (active but no events in >1 hour)
## Output Format
Present as a system health dashboard:
```
╔══════════════════════════════════════════════╗
║ AGENT MONITOR HEALTH CHECK ║
║ Timestamp: 2025-04-11 12:00:00 UTC ║
╠══════════════════════════════════════════════╣
║ ║
║ API Server ............ ✅ OK (45ms) ║
║ Database .............. ✅ OK (2.4 MB) ║
║ WebSocket ............. ✅ OK ║
║ API Endpoints ......... ✅ 6/6 passing ║
║ Hook Integration ...... ⚠️ 5/7 hooks ║
║ Data Freshness ........ ✅ 3m ago ║
║ ║
║ Overall: HEALTHY (5/6 checks passed) ║
║ ║
╚══════════════════════════════════════════════╝
```
For any non-passing check, include detailed explanation and remediation steps below the dashboard.
@@ -0,0 +1,103 @@
---
description: >
Diagnose Claude Code hook installation, delivery, and ingestion issues.
Checks hook configuration, connectivity, event flow, and identifies
common problems. Use when events are not appearing in the dashboard.
---
# Hook Diagnostics
Diagnose hook integration issues between Claude Code and the Agent Monitor.
## Input
The user provides: **$ARGUMENTS**
This may be:
- "full" or empty (default: run all diagnostics)
- "install" to check hook installation only
- "connectivity" to check dashboard connectivity only
- "events" to check event delivery only
## Procedure
Run diagnostic checks in this order:
### 1. Hook Installation Check
Verify hooks are installed in Claude Code settings:
```bash
# Check if hooks exist in Claude Code settings
cat ~/.claude/settings.json | jq '.hooks // empty'
```
Verify:
- All 7 expected hook types are registered: `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStop`, `Notification`, `SessionStart`, `SessionEnd`
- Hook commands point to the correct handler script path
- Handler script exists and is readable at the configured path
### 2. Dashboard Connectivity
Test that the dashboard API is reachable:
```bash
curl -sf http://localhost:4820/api/health
```
Verify:
- Dashboard responds with 200 OK
- Response includes expected health fields
- WebSocket endpoint is accessible
### 3. Hook Handler Validation
Check the hook handler script:
```bash
# Verify handler exists and is executable
ls -la <handler-path>
# Syntax check
node --check <handler-path>
```
### 4. Event Delivery Test
Send a test event and verify it arrives:
```bash
echo '{"hook_type":"test","session_id":"diag-test","data":{}}' | \
curl -sf -X POST http://localhost:4820/api/hooks/event \
-H 'Content-Type: application/json' -d @-
```
### 5. Database Check
Verify the database is writable and events are persisted:
```bash
curl -sf http://localhost:4820/api/stats
curl -sf http://localhost:4820/api/events?limit=5
```
### 6. Recent Event Flow
Check if events are flowing:
- Time since last event received
- Events received in last hour
- Any gaps in event delivery
## Output Format
Present as a diagnostic report with:
```
Hook Diagnostics Report
━━━━━━━━━━━━━━━━━━━━━━
✅ Hook Installation .............. PASS
✅ Dashboard Connectivity ......... PASS
✅ Handler Script ................. PASS
⚠️ Event Delivery ................ WARN (slow)
✅ Database ....................... PASS
❌ Recent Event Flow .............. FAIL (no events in 2h)
━━━━━━━━━━━━━━━━━━━━━━
Overall: 5/6 checks passed
```
For each failed or warning check, include:
- What was expected vs what was found
- Specific remediation steps
- Commands to fix the issue
@@ -0,0 +1,78 @@
---
description: >
Debug a specific session by inspecting its full event chain (PreToolUse,
PostToolUse, Stop, SubagentStop, Compaction, APIError, TurnDuration,
Notification events), agent hierarchy (recursive parent/child tree with
subagent_type and depth), token usage with compaction baselines, workflow
intelligence data (orchestration DAG, error propagation by depth), and
session metadata (thinking_blocks, turn_count, total_turn_duration_ms).
---
# Session Debug
Debug and inspect a Claude Code session from Agent Monitor data.
## Input
The user provides: **$ARGUMENTS**
This may be:
- A session ID to debug
- "latest" or "last" for the most recent session
- "errors" to find and debug the most recent errored session
## Procedure
1. **Identify the target session**:
- If session ID given: `GET /api/sessions/{id}` from `http://localhost:4820`
- If "latest": `GET /api/sessions?limit=1` (default sort: most recently updated first)
- If "errors": `GET /api/sessions?limit=10&status=error`
2. **Collect full session data**:
- Session metadata: status, model, cwd, timestamps, duration
- Events: `GET /api/events?session_id={session_id}` — full event timeline
- Agents: `GET /api/agents?session_id={session_id}` — all agents in session
- Cost: `GET /api/pricing/cost/{session_id}`
3. **Analyze the session**:
### Session Lifecycle
- Start time → first event → last event → end time
- Status transitions (active → working → completed/error)
- Total duration and active-vs-idle time
### Event Chain Analysis
- Chronological event list with timestamps and durations
- Identify the **critical path** (longest chain of dependent events)
- Flag events that took unusually long
- Highlight error events with full error context
### Agent Inspection
- List all agents: type, task, status, duration
- Subagent tree visualization (parent → children)
- Agents that failed and their last known state
- Agent switching patterns (when and why new agents spawned)
### Tool Execution Trace
- Every tool invocation in order with: tool name, duration, success/failure
- Failed tool calls with error messages
- Tool retry patterns (same tool called multiple times)
### Anomaly Detection
- Events out of expected order
- Gaps in event timeline (>30s with no events)
- Duplicate events or agent states
- Token usage spikes (compaction indicators)
4. **Diagnosis**:
- Root cause hypothesis (if errors present)
- Contributing factors
- Remediation suggestions
## Output Format
Present as a debug report with:
- Session summary header (ID, status, model, duration, cost)
- Color-coded timeline (✅ success, ❌ error, ⚠️ warning, info)
- Agent tree diagram
- Diagnosis section with numbered findings
@@ -0,0 +1,69 @@
---
description: >
Search a Claude Code session transcript for a string or regex pattern and show
every matching message with surrounding context. Reads
/api/sessions/:id/transcript and resolves sessions via /api/sessions?limit=
from the Agent Monitor dashboard. Use when hunting for a specific message,
prompt, tool call, or error inside a session's conversation.
---
# Transcript Grep
Find where a pattern appears in a session transcript and show the matches in context.
## Input
The user provides: **$ARGUMENTS**
Interpreted as a session reference plus a search pattern, e.g.
`<session-id> "rate limit"` or `latest TypeError`. Parsing rules:
- The session reference is the first token if it looks like an id, or the words
`latest`/`last` (most recently updated session).
- The remainder is the search pattern (string or regex, quoted if it contains spaces).
- If no session is given, default to the most recent session.
## Data Sources
| Endpoint | Returns |
|----------|---------|
| `GET /api/sessions?limit=N` | session list to resolve `latest`/`last` and to confirm the id exists |
| `GET /api/sessions/:id/transcript` | the ordered transcript messages (role, content, tool calls/results, timestamps) for the session |
## Report Sections
### 1. Resolve the session
If `latest`/`last` (or no id), call `GET /api/sessions?limit=1`. Otherwise verify
the id with `GET /api/sessions?limit=1000` (or `GET /api/sessions/:id`). Report
the resolved id, status, and model before searching.
### 2. Fetch and search
Call `GET /api/sessions/:id/transcript`. Walk the messages in order and match the
pattern against message text, tool_name, and tool input/output content.
Case-insensitive by default; treat the pattern as a regex if it contains regex
metacharacters, otherwise as a literal substring.
### 3. Matches with context
For each match show:
```
[#N HH:MM:SS role(:tool_name)]
… preceding line of context …
> matching line with the **pattern** emphasized
… following line of context …
```
Number matches sequentially. Include ±12 messages (or lines) of context so the
match is interpretable. If a tool call matches, show the tool_name and a trimmed
view of its arguments/result.
### 4. Summary
Report: total matches, how many distinct messages matched, the roles involved
(user / assistant / tool), and the timestamp span of the matches. If there are
zero matches, say so plainly and suggest a looser pattern.
## Output
- Lead with the match count and session header, then the contextual snippets.
- Keep snippets trimmed — truncate long tool payloads with `…` rather than dumping them.
- Cite only transcript content returned by the API — never fabricate messages.
- If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.