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,17 @@
{
"name": "ccam-devtools",
"description": "Developer tools for Claude Code Agent Monitor — session debugging, hook diagnostics, data export, and system health checks for maintaining a healthy monitoring setup.",
"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": ["devtools", "debugging", "diagnostics", "export", "health-check", "claude-code"],
"categories": ["devtools", "debugging", "diagnostics"]
}
@@ -0,0 +1,89 @@
---
name: db-inspector
description: >
Inspects Agent Monitor data integrity via the dashboard API (port 4820).
Detects orphaned events, sessions missing agents, PreToolUse/PostToolUse
imbalance, stale active sessions, and import freshness drift. Cross-checks
/api/stats counts against /api/sessions, /api/events, and /api/analytics to
surface ingestion gaps, then reports findings with severity and remediation.
model: sonnet
tools:
- Bash
- Read
- Grep
---
# Database Inspector
You are a data-integrity inspector for the Claude Code Agent Monitor. You query
the dashboard API at `http://localhost:4820` using `curl -s http://localhost:4820/api/...`
to verify that ingested data is internally consistent and fresh. You read only —
you never mutate data.
## Available Data Sources
| Endpoint | Returns |
|----------|---------|
| `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=N` | session list (id, status, model, cwd, started_at, ended_at, cost, metadata) |
| `GET /api/events?session_id=X` | events for a session (event_type, tool_name, summary, data, timestamp) |
| `GET /api/events` | recent events across all sessions |
| `GET /api/settings/info` | DB path/size, counts, last import time, hook config summary |
| `GET /api/analytics` | overview, tokens, tool_usage, daily_events(365d), daily_sessions(365d), agent_types, event_types, avg_events_per_session, total_subagents, sessions_by_status, agents_by_status |
## Analysis Framework
1. **Baseline the counts.** Read `/api/stats` and `/api/settings/info`. Record
total_sessions, total_agents, total_events, active_sessions, and the reported
DB size and last-import timestamp. These are the ground-truth totals.
2. **Orphaned events.** Pull `/api/events` (and per-session via
`/api/events?session_id=X` for suspect sessions). Flag any event whose
`session_id` does not resolve to a session in `/api/sessions?limit=1000`.
Orphaned events indicate ingestion that outran session creation, or deleted
sessions that left events behind.
3. **Sessions missing agents.** For each session, compare the session-level
subagent count against `/api/analytics` `total_subagents` and the
`agent_types` distribution. A session whose events contain `SubagentStop`
but which has zero agent records is a structural gap — report the session id.
4. **Event-type imbalance.** From `/api/analytics` `event_types` (or by tallying
`/api/events`), compute the PreToolUse vs PostToolUse ratio. In a healthy
feed these are near 1:1 (every started tool call should post a result). A
surplus of PreToolUse means tool calls without recorded completion (dropped
PostToolUse hooks); a surplus of PostToolUse means missing PreToolUse hooks.
Report the raw counts and the delta.
5. **Stale active sessions.** From `/api/stats` `active_sessions` and
`/api/sessions?limit=1000` filtered to `status=active`, find sessions marked
active whose most recent event (`/api/events?session_id=X`, last timestamp)
is older than 1 hour. These are likely sessions that ended without a clean
Stop/SessionEnd event.
6. **Import freshness.** Compare `/api/settings/info` last-import time and
`/api/stats` `events_today` against the newest `timestamp` in `/api/events`.
If the newest event is hours old or `events_today` is 0 on an otherwise busy
day, hook ingestion or import has stalled.
## Output Standards
- Cite real numbers pulled from the API — never fabricate counts or ratios.
- Format currency in USD to 4 decimals when cost appears.
- Use ▲/▼ to show deltas (e.g. PreToolUse ▲ 312 vs PostToolUse 287, ▲ 25).
- Lead with a one-line verdict (HEALTHY / DRIFT DETECTED / INTEGRITY ISSUES),
then a findings table: `Check | Result | Severity | Detail`.
- Severity scale: P0 (data loss/corruption), P1 (ingestion broken),
P2 (drift/staleness), P3 (cosmetic/expected).
- For each non-passing check, give a concrete remediation: e.g.
`POST /api/settings/reimport` to rebuild from transcripts,
`POST /api/settings/reinstall-hooks` to repair hook config, or
`POST /api/settings/cleanup` to prune orphans (confirm before suggesting any
destructive action).
## Constraints
- Read-only advisory role — never modify 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.
@@ -0,0 +1,97 @@
---
name: issue-triager
description: >
Triages Agent Monitor issues by systematically checking the Express API
(port 4820), SQLite database (better-sqlite3 with WAL mode), WebSocket
broadcast, hook handler (scripts/hook-handler.js processing 7 event types),
transcript cache (LRU max 200 with stat-based incremental reads), and
the MCP server. Classifies by severity and provides specific remediation.
model: sonnet
tools:
- Bash
- Read
- Grep
---
# Issue Triager
You are a technical issue triager for the Claude Code Agent Monitor system.
When users report problems, you systematically investigate, classify, and
provide resolution guidance.
## System Architecture
The Agent Monitor has these components:
- **Server** (`server/`): Express API on port 4820
- **Database** (`data/dashboard.db`): SQLite via better-sqlite3
- **WebSocket** (`server/websocket.js`): Real-time event broadcast
- **Hook Handler** (`scripts/hook-handler.js`): Receives Claude Code hook events
- **Hook Installer** (`scripts/install-hooks.js`): Configures hooks in `~/.claude/settings.json`
- **Client** (`client/`): React + Vite SPA on port 5173 (dev) or served by Express (prod)
- **MCP Server** (`mcp/`): Model Context Protocol integration
## Investigation Process
1. **Symptom Collection**: Understand what the user is experiencing
2. **Component Identification**: Determine which component(s) are involved
3. **Evidence Gathering**: Use API calls, file checks, and log inspection
4. **Root Cause Analysis**: Trace the issue to its source
5. **Resolution**: Provide specific fix instructions
## Diagnostic Commands
```bash
# API health
curl -sf http://localhost:4820/api/health
# Check if server is running
lsof -i :4820
# Database status
ls -la data/dashboard.db
# Hook configuration
cat ~/.claude/settings.json | jq '.hooks'
# Recent events
curl -sf 'http://localhost:4820/api/events?limit=10'
# Server logs (if running in foreground)
# Check process stderr/stdout
# Node.js version
node --version
```
## Severity Classification
- **P0 Critical**: System completely non-functional (server won't start, database corrupted)
- **P1 High**: Major feature broken (events not ingesting, WebSocket disconnected)
- **P2 Medium**: Feature degraded (slow queries, stale sessions, missing some events)
- **P3 Low**: Minor issue (UI glitch, cosmetic problem, documentation gap)
## Output Format
For each triaged issue, provide:
```
┌─────────────────────────────────────────┐
│ Issue: [Brief title] │
│ Severity: P[0-3] [Critical/High/Med/Low] │
│ Component: [server/client/hooks/db/mcp] │
│ Status: [investigating/identified/fixed] │
└─────────────────────────────────────────┘
Root Cause: [Concise explanation]
Evidence:
1. [Specific observation]
2. [Specific observation]
Resolution:
1. [Step-by-step fix]
2. [Verification step]
Prevention:
- [How to avoid in future]
```
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env bash
# ccam-doctor — Diagnostic tool for Claude Code Agent Monitor
# Usage: ccam-doctor [--quick] [--deep] [--fix]
set -euo pipefail
DASHBOARD_URL="${CCAM_DASHBOARD_URL:-http://localhost:4820}"
HOOK_HANDLER_NAME="hook-handler.js"
CLAUDE_SETTINGS="${HOME}/.claude/settings.json"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'
BOLD='\033[1m'
PASS=0
WARN=0
FAIL=0
usage() {
cat <<EOF
ccam-doctor — Claude Code Agent Monitor Diagnostic Tool
USAGE:
ccam-doctor [OPTIONS]
OPTIONS:
--quick Run basic connectivity checks only
--deep Run all checks including database integrity
--fix Attempt to auto-fix common issues
--json Output results as JSON
--help Show this help
ENVIRONMENT:
CCAM_DASHBOARD_URL Dashboard URL (default: http://localhost:4820)
EOF
exit 0
}
check_pass() { echo -e " ${GREEN}✅ $1${NC}"; ((PASS++)); }
check_warn() { echo -e " ${YELLOW}⚠️ $1${NC}"; ((WARN++)); }
check_fail() { echo -e " ${RED}❌ $1${NC}"; ((FAIL++)); }
header() {
echo ""
echo -e "${BOLD}${CYAN}╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${CYAN}║ AGENT MONITOR DIAGNOSTIC REPORT ║${NC}"
echo -e "${BOLD}${CYAN}║ $(date '+%Y-%m-%d %H:%M:%S %Z') ║${NC}"
echo -e "${BOLD}${CYAN}╠══════════════════════════════════════════════╣${NC}"
echo ""
}
check_api() {
echo -e "${BOLD}API Server${NC}"
local start_ms end_ms duration_ms
start_ms=$(date +%s%3N 2>/dev/null || python3 -c 'import time; print(int(time.time()*1000))')
if response=$(curl -sf --max-time 5 "${DASHBOARD_URL}/api/health" 2>/dev/null); then
end_ms=$(date +%s%3N 2>/dev/null || python3 -c 'import time; print(int(time.time()*1000))')
duration_ms=$((end_ms - start_ms))
if [ "$duration_ms" -lt 500 ]; then
check_pass "API responding (${duration_ms}ms)"
else
check_warn "API slow (${duration_ms}ms — expected <500ms)"
fi
else
check_fail "API unreachable at ${DASHBOARD_URL}"
echo " → Start the server: npm start (from the project directory)"
return 1
fi
}
check_endpoints() {
echo -e "${BOLD}API Endpoints${NC}"
local endpoints=("sessions?limit=1" "events?limit=1" "analytics" "pricing" "stats" "settings/info")
local pass_count=0
local total=${#endpoints[@]}
for ep in "${endpoints[@]}"; do
if curl -sf --max-time 5 "${DASHBOARD_URL}/api/${ep}" > /dev/null 2>&1; then
((pass_count++))
fi
done
if [ "$pass_count" -eq "$total" ]; then
check_pass "All ${total} endpoints responding"
elif [ "$pass_count" -gt 0 ]; then
check_warn "${pass_count}/${total} endpoints responding"
else
check_fail "No endpoints responding"
fi
}
check_database() {
echo -e "${BOLD}Database${NC}"
local stats
if stats=$(curl -sf --max-time 5 "${DASHBOARD_URL}/api/stats" 2>/dev/null); then
local sessions events
sessions=$(echo "$stats" | jq -r '.total_sessions // 0')
events=$(echo "$stats" | jq -r '.total_events // 0')
check_pass "Database OK (${sessions} sessions, ${events} events)"
else
check_fail "Database query failed"
fi
}
check_hooks() {
echo -e "${BOLD}Hook Configuration${NC}"
if [ ! -f "$CLAUDE_SETTINGS" ]; then
check_fail "Claude settings not found at ${CLAUDE_SETTINGS}"
echo " → Run: npm run install-hooks (from the project directory)"
return
fi
local hook_count
hook_count=$(jq '[.hooks // {} | to_entries[] | .value[] | .hooks[]? ] | length' "$CLAUDE_SETTINGS" 2>/dev/null || echo "0")
if [ "$hook_count" -ge 7 ]; then
check_pass "Hooks configured (${hook_count} hook entries)"
elif [ "$hook_count" -gt 0 ]; then
check_warn "Partial hook setup (${hook_count}/7+ expected)"
echo " → Run: npm run install-hooks"
else
check_fail "No hooks configured"
echo " → Run: npm run install-hooks (from the project directory)"
fi
}
check_data_freshness() {
echo -e "${BOLD}Data Freshness${NC}"
local events
if events=$(curl -sf --max-time 5 "${DASHBOARD_URL}/api/events?limit=1" 2>/dev/null); then
local last_event
last_event=$(echo "$events" | jq -r '.[0].created_at // empty' 2>/dev/null)
if [ -n "$last_event" ]; then
check_pass "Last event: ${last_event}"
else
check_warn "No events found — dashboard may be newly set up"
fi
else
check_warn "Could not check data freshness"
fi
}
summary() {
local total=$((PASS + WARN + FAIL))
echo ""
echo -e "${BOLD}${CYAN}╠══════════════════════════════════════════════╣${NC}"
if [ "$FAIL" -eq 0 ] && [ "$WARN" -eq 0 ]; then
echo -e "${BOLD}${GREEN}║ Overall: HEALTHY (${PASS}/${total} checks passed) ║${NC}"
elif [ "$FAIL" -eq 0 ]; then
echo -e "${BOLD}${YELLOW}║ Overall: DEGRADED (${WARN} warnings) ║${NC}"
else
echo -e "${BOLD}${RED}║ Overall: UNHEALTHY (${FAIL} failures) ║${NC}"
fi
echo -e "${BOLD}${CYAN}╚══════════════════════════════════════════════╝${NC}"
echo ""
}
# --- Main ---
MODE="standard"
while [[ $# -gt 0 ]]; do
case "$1" in
--help|-h) usage ;;
--quick) MODE="quick"; shift ;;
--deep) MODE="deep"; shift ;;
--fix) MODE="fix"; shift ;;
--json) MODE="json"; shift ;;
*) echo "Unknown option: $1" >&2; usage ;;
esac
done
header
check_api || { summary; exit 1; }
echo ""
if [ "$MODE" != "quick" ]; then
check_endpoints
echo ""
check_database
echo ""
fi
check_hooks
echo ""
check_data_freshness
summary
exit "$FAIL"
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
# ccam-export — Quick data export from Claude Code Agent Monitor
# Usage: ccam-export [sessions|events|analytics|costs|all] [--format json|csv] [--limit N]
set -euo pipefail
DASHBOARD_URL="${CCAM_DASHBOARD_URL:-http://localhost:4820}"
usage() {
cat <<EOF
ccam-export — Claude Code Agent Monitor Data Export
USAGE:
ccam-export <DATA_TYPE> [OPTIONS]
DATA TYPES:
sessions Export session data
events Export event data
analytics Export analytics summary
costs Export cost data
all Export everything (uses /api/settings/export)
OPTIONS:
--format FORMAT Output format: json (default), csv
--limit N Maximum records to export (default: 100)
--output FILE Write to file instead of stdout
--pretty Pretty-print JSON output
--help Show this help
ENVIRONMENT:
CCAM_DASHBOARD_URL Dashboard URL (default: http://localhost:4820)
EXAMPLES:
ccam-export sessions # Export sessions as JSON
ccam-export events --format csv --limit 500 # Export 500 events as CSV
ccam-export all --output backup.json # Full backup to file
ccam-export costs --pretty # Pretty-printed cost data
EOF
exit 0
}
check_dashboard() {
if ! curl -sf "${DASHBOARD_URL}/api/health" > /dev/null 2>&1; then
echo "Error: Dashboard unreachable at ${DASHBOARD_URL}" >&2
exit 1
fi
}
json_to_csv() {
local data_type="$1"
case "$data_type" in
sessions)
echo "id,name,status,model,cwd,started_at,ended_at,updated_at"
jq -r '.sessions[] | [.id, .name, .status, .model, .cwd, .started_at, .ended_at, .updated_at] | @csv'
;;
events)
echo "id,session_id,agent_id,event_type,tool_name,summary,created_at"
jq -r '.events[] | [.id, .session_id, .agent_id, .event_type, .tool_name, .summary, .created_at] | @csv'
;;
*)
echo "CSV format not supported for ${data_type}. Use JSON instead." >&2
exit 1
;;
esac
}
# --- Parse args ---
DATA_TYPE=""
FORMAT="json"
LIMIT=100
OUTPUT=""
PRETTY=false
while [[ $# -gt 0 ]]; do
case "$1" in
--help|-h) usage ;;
--format) FORMAT="$2"; shift 2 ;;
--limit) LIMIT="$2"; shift 2 ;;
--output) OUTPUT="$2"; shift 2 ;;
--pretty) PRETTY=true; shift ;;
sessions|events|analytics|costs|all)
DATA_TYPE="$1"; shift ;;
*)
echo "Unknown argument: $1" >&2; usage ;;
esac
done
if [ -z "$DATA_TYPE" ]; then
echo "Error: Data type required (sessions, events, analytics, costs, all)" >&2
echo ""
usage
fi
check_dashboard
# --- Fetch data ---
fetch_data() {
case "$DATA_TYPE" in
sessions) curl -sf "${DASHBOARD_URL}/api/sessions?limit=${LIMIT}" ;;
events) curl -sf "${DASHBOARD_URL}/api/events?limit=${LIMIT}" ;;
analytics) curl -sf "${DASHBOARD_URL}/api/analytics" ;;
costs) curl -sf "${DASHBOARD_URL}/api/pricing/cost" ;;
all) curl -sf "${DASHBOARD_URL}/api/settings/export" ;;
esac
}
format_output() {
if [ "$FORMAT" = "csv" ]; then
json_to_csv "$DATA_TYPE"
elif $PRETTY; then
jq .
else
cat
fi
}
# --- Export ---
RESULT=$(fetch_data)
if [ -z "$RESULT" ]; then
echo "Error: No data returned for ${DATA_TYPE}" >&2
exit 1
fi
if [ -n "$OUTPUT" ]; then
echo "$RESULT" | format_output > "$OUTPUT"
RECORD_COUNT=$(echo "$RESULT" | jq 'if .sessions then (.sessions | length) elif .events then (.events | length) elif type == "array" then length else 1 end' 2>/dev/null || echo "1")
echo "Exported ${RECORD_COUNT} record(s) to ${OUTPUT}" >&2
else
echo "$RESULT" | format_output
fi
+36
View File
@@ -0,0 +1,36 @@
---
description: Quick connectivity + health probe of the Agent Monitor dashboard.
---
Run a fast health probe against the Agent Monitor dashboard at
`http://localhost:4820`. Do two checks and print OK / FAIL for each.
1. **API + stats** — fetch core stats:
```bash
curl -s -o /dev/null -w '%{http_code}' http://localhost:4820/api/stats
curl -s http://localhost:4820/api/stats
```
PASS if HTTP 200 and the body is valid JSON. From the body, surface
`total_sessions`, `active_sessions`, `total_events`, and `events_today`.
2. **Self-update status** — confirm the update subsystem responds:
```bash
curl -s -o /dev/null -w '%{http_code}' http://localhost:4820/api/updates/status
curl -s http://localhost:4820/api/updates/status
```
PASS if HTTP 200 and valid JSON. Surface whether an update is available and
the current vs latest version if present.
Print a compact report, one line per check:
```
Agent Monitor Doctor
API /api/stats ............ OK (sessions=12 active=1 events=3480 today=57)
/api/updates/status ....... OK (up to date — v1.x.x)
Overall: OK (2/2)
```
Use ✅ OK / ❌ FAIL markers. If any curl fails to connect (non-200 or no
response), mark that check FAIL and end with: "Dashboard unreachable — start it
with `npm start` from the repo root." Keep it to the report only; no extra prose.
+30
View File
@@ -0,0 +1,30 @@
---
description: Export Agent Monitor data (sessions/events/analytics/costs/all) as json/csv/md.
argument-hint: "[sessions|events|analytics|costs|all] [json|csv|md]"
---
Export Agent Monitor data using the dashboard export endpoint. Arguments:
**$ARGUMENTS** — the first token is the data `type`, the second is the `format`.
- `type``sessions | events | analytics | costs | all` (default `all`)
- `format``json | csv | md` (default `json`)
Set `TYPE` and `FORMAT` from the args (apply the defaults if missing), then run:
```bash
TYPE="${1:-all}"; FORMAT="${2:-json}"
curl -s "http://localhost:4820/api/settings/export?type=${TYPE}&format=${FORMAT}" \
-o "ccam-export-${TYPE}.${FORMAT}"
```
Then:
1. Confirm the file was written and report its absolute path and byte size.
2. Preview the result: for `csv`/`md` print the first ~15 lines; for `json`
print a pretty-printed head (e.g. `head -c 1500` or the first array element
plus the record count).
3. Print a one-line summary: `Exported <type> as <format> → <path> (<N> records / <bytes>)`.
If the curl returns a non-200 or an error body, do not claim success — print the
error and remind the user to start the dashboard with `npm start` from the repo
root. Do not delete or overwrite any existing data; this command only reads via
the export endpoint and writes a new export file.
@@ -0,0 +1,33 @@
---
description: Show the latest N ingested events with timestamp, event_type, and tool_name.
argument-hint: "[N]"
---
Show the most recent events from the Agent Monitor dashboard. Argument:
**$ARGUMENTS** — `N`, the number of events to show (default 20).
Fetch recent events and take the newest N:
```bash
N="${1:-20}"
curl -s "http://localhost:4820/api/events?limit=${N}" | jq -r '.[] | "\(.timestamp)\t\(.event_type)\t\(.tool_name // "-")"'
```
The `/api/events` list is returned newest-first; show the most recent `N`.
Render a compact, aligned table — one row per event:
```
TIME EVENT_TYPE TOOL_NAME
2026-06-25T14:03:11Z PostToolUse Bash
2026-06-25T14:03:09Z PreToolUse Bash
2026-06-25T14:02:58Z Stop -
```
Include `event_type` (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart,
SessionEnd, Notification, Compaction, APIError, TurnDuration) and `tool_name`
when present (use `-` for events without a tool). End with a one-line count:
`Showing latest <N> events.`
If the request returns a non-200 or empty body, say so and tell the user to start
the dashboard with `npm start` from the repo root. Read-only — never POST or
modify events.
@@ -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.