# sessions/ — Agent Session Tracking

See @../../CLAUDE.md for project-wide patterns.

## What This Is
Records agent execution sessions: who ran, when, what model, tokens/cost, and a stream of events per session.

## Status Lifecycle
`running → completed | failed | timeout`

## Key Endpoints
- `POST /api/sessions` — create session (loop startup)
- `PUT /api/sessions/{id}` — update (mark done, record tokens/cost, set ended_at)
- `POST /api/sessions/{id}/events` — append event (tool_call, error, checkpoint, etc.)
- `GET /api/sessions/{id}` — detail with full events array + joined task_title
- `GET /api/sessions/stats?project_id=` — aggregates: total, success_rate, avg_duration, tokens, cost by model
- `POST /api/sessions/cleanup-stale` — marks all running sessions as failed (crash recovery on startup)

## MCP Tools (5)
`create_session`, `update_session`, `add_session_event`, `list_sessions`, `get_session`, `session_stats`

## Gotchas
- Duration is computed as `ROUND(EXTRACT(EPOCH FROM (ended_at - started_at))::numeric, 2)` — NULL until ended_at is set
- `get_session` returns full event array (no pagination) — can be large for long sessions
- Event types are schema-validated but NOT constrained at DB level
- `cleanup-stale` requires `project_id` parameter — scoped per project
- Cost is float (USD), tokens are int — both default to 0
- Loop integration: loop.py calls create_session at start, add_session_event throughout, update_session at end
