hermes-trace/AGENTS.md

161 lines
7.2 KiB
Markdown

# hermes-trace — Hermes Plugin Development Guide
## Overview
hermes-trace is a Hermes Agent plugin that captures every LLM API call (main session, background review forks, subagents) to a local SQLite store with a Granian-powered query frontend.
**Lang:** Python 3.13+
**Server:** Granian (`--interface asgi`), FastAPI, Jinja2 templates
**Frontend:** HTMX + Alpine.js (zero build step)
## Quick Start
```bash
cd ~/.hermes/plugins/hermes-trace
uv sync --dev # Install all deps (incl. ruff, pyright)
source .venv/bin/activate
```
## Adding Dependencies
```bash
uv add <package> # Production dependency
uv add --dev <package> # Dev dependency (ruff, pyright, etc.)
```
## Verification Gates
Run after every code change before committing:
```bash
just verify # lint + format check + typecheck + tests, in one command
```
Or run individual gates via the Justfile:
```bash
just lint # ruff check .
just fmt # ruff format . (auto-fix)
just fmt-check # ruff format --check .
just typecheck # pyright
just test # python -m unittest discover -s tests -v
```
## Project Conventions
- **Type hints:** Required on every function signature (public and private). Use `from __future__ import annotations` for forward references.
- **Docstrings:** Google style (`"""Summary.\n\nArgs:\n ...\nReturns:\n ...\n"""`) for public APIs; private functions can have inline comments.
- **Imports:** `ruff format` handles ordering; just group by stdlib → third-party → local with blank lines.
- **Error handling:** Don't silence exceptions. If a hook fails, log and return (don't crash Hermes).
- **SQLite:** Always use `with sqlite3.connect(...)` context manager; no raw string concatenation in queries (use `?` params).
## Plugin Contract
`register(ctx)` is called once at Hermes startup. The function must:
1. Register hooks via `ctx.register_hook("hook_name", handler)`
2. Spawn daemon threads for background work (cleanup, frontend server)
3. Not block startup
Hook handlers receive keyword-only arguments (`**kwargs` contract). Use `**_` to accept extra params Hermes may add in future versions.
## Frontend Architecture
Flat table + right-side overlay panel for session trace view:
| Pane | Role | Interaction |
|------|------|-------------|
| **Table** | Turn timeline (LLM calls + nested tool calls) | Click a row to open detail |
| **Overlay** | Right-side resizable panel | HTMX-loads turn detail into `#detail-body` |
### Key patterns
- **Large JSON safety:** Use `<textarea readonly>` not `<pre>` for Full Request/Response. Browser virtualizes textarea rendering — only visible lines are laid out.
- **JSON display:** Full payloads are server-formatted once and rendered as a single valid JSON copy.
- **Lazy loading:** Full Request/Response loaded via HTMX when the JSON tab is activated (Alpine `loadJson()` → two `htmx.ajax` GETs; `htmx:beforeSwap` race guard discards stale payloads).
- **Token tooltip:** Hover on the Tokens pill shows a Langfuse-style Usage Breakdown popup (Input usage / Output usage / Total usage with cache read breakdown).
- **CSS:** All styles live in `static/hermes-trace.css` (extracted from layout.html; legacy waterfall/three-pane styles removed).
## Routes
| Route | Type | Content |
|-------|------|---------|
| `GET /` | Full page | Session list, sorted by recency |
| `GET /session/{id}` | Full page | Flat turn timeline table; clicking a row opens the right-side detail overlay |
| `GET /session/{id}/waterfall/{turn_id}` | HTMX fragment | Legacy waterfall tree fragment — no live navigation path in the UI |
| `GET /turn/{id}` | HTMX fragment | Full turn detail with metadata badges + technical details (overlay panel) |
| `GET /turn/{id}?focus_tc=N` | HTMX fragment | Same as above, auto-scrolls to tool call #N |
| `GET /turn/{id}/payload?type=request\|response` | HTMX fragment | Lazy-loaded, server-formatted JSON content (single textarea) |
## File Layout
```
~/.hermes/plugins/hermes-trace/
├── .gitignore
├── plugin.yaml # Hermes plugin manifest
├── AGENTS.md # This file — development guide
├── PLAN.md # Design document
├── HERMES_PLUGIN_RESEARCH.md # Research notes on Hermes plugin hooks
├── __init__.py # register(ctx): wire hooks + spawn daemons; re-exports package surface
├── _state.py # Shared state and utility functions
├── hooks.py # Hook handlers
├── launcher.py # Daemon targets and launcher helpers
├── db.py # SQLite schema + write/read abstraction
├── app.py # Granian + FastAPI + Jinja2 frontend
├── static/
│ ├── hermes-trace.js # Alpine component + HTMX guards/listeners (no inline scripts)
│ └── hermes-trace.css # All frontend CSS (extracted from layout.html)
├── templates/
│ ├── layout.html # Base layout + HTMX/Alpine CDN
│ ├── index.html # Session list page
│ ├── session.html # Flat timeline table + right-side overlay
│ ├── waterfall.html # Legacy unlinked waterfall tree fragment
│ ├── turn_detail.html # Turn detail fragment (overlay panel)
│ └── payload.html # Lazy-loaded JSON textarea fragment
```
## Template Data Flow
```
Session list (/) → click session → Session detail (/session/{id})
└── Flat turn timeline table (server-rendered)
└── Click row → right-side detail overlay (HTMX /turn/{id})
└── Full Request/Response (HTMX /turn/{id}/payload)
```
The waterfall fragment (`/session/{id}/waterfall/{turn_id}`) is legacy and has no live navigation path in the UI.
## Subagent Instructions
When delegating code changes to subagents:
1. First read `docs/architecture.md`, `docs/frontend.md`, `docs/hooks.md`, `docs/database.md`, and the relevant source files
2. After changing any `.py` file, run the verification gates:
```bash
uv run ruff check .
uv run ruff format .
uv run pyright
```
Or activate the venv first: `source .venv/bin/activate` then run the commands directly.
3. After changing any `.html` file: no linter available, but visually verify in browser.
4. Fix ALL findings — zero lint/type errors before considering done.
5. If adding a new route or template, update the routes table and file layout in this file.
## Agent skills
### Domain docs
Single-context repo. See `docs/agents/domain.md`.
## Quick Reference
See the `docs/` directory for detailed documentation:
| Document | Contents |
|----------|----------|
| `docs/architecture.md` | System overview, data flow, component diagram |
| `docs/frontend.md` | Flat-table + overlay layout, Alpine patterns, JSON display, token tooltip |
| `docs/hooks.md` | Hook callbacks, daemon threads, plugin configuration |
| `docs/database.md` | SQLite schema, indexes, key queries, retention |
| `PLAN.md` | Design decisions, status, implementation order |
| `HERMES_PLUGIN_RESEARCH.md` | Research notes on Hermes plugin system and Langfuse reference |