> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Statistics

> Endpoints for analytics, growth metrics, daily activity journals, and AI-powered daily wrap summaries.

# Statistics API

Endpoints for querying agent activity analytics, growth metrics, daily work journals, and AI-generated daily summaries.

## Daily Journal

Retrieve a consolidated view of all agent activity for a specific day.

```
GET /api/v1/statistics/daily-journal?date=YYYY-MM-DD&agent_id=optional
```

### Parameters

| Parameter  | Type   | Required | Description                 |
| ---------- | ------ | -------- | --------------------------- |
| `date`     | string | Yes      | Date in `YYYY-MM-DD` format |
| `agent_id` | string | No       | Filter by specific agent ID |

### Response

```json theme={null}
{
  "code": 0,
  "data": {
    "date": "2026-05-31",
    "overview": {
      "total_sessions": 5,
      "total_tokens": 42000,
      "total_cost": 0.35,
      "tool_call_count": 28,
      "approval_count": 2,
      "cron_run_count": 1,
      "kanban_event_count": 3,
      "sessions_by_source": {
        "web": 3,
        "telegram": 1,
        "api": 1
      }
    },
    "sessions": [
      {
        "id": "abc-123",
        "title": "Code review session",
        "source": "web",
        "started_at": "2026-05-31T09:15:00Z",
        "total_tokens": 12000,
        "total_cost": 0.10
      }
    ],
    "approvals": [],
    "cron_runs": [],
    "kanban_events": [],
    "timeline": [
      {
        "type": "session",
        "time": "2026-05-31T09:15:00Z",
        "title": "Code review session",
        "detail": { "source": "web", "tokens": 12000 }
      }
    ]
  }
}
```

### Data Sources

The journal aggregates data from 6 existing sources without any additional storage:

| Source               | Data                                         |
| -------------------- | -------------------------------------------- |
| Chat                 | Session metadata (title, source, timestamps) |
| Message              | Token counts and cost per session            |
| ApprovalRecord       | Human approval events                        |
| CronRunModel         | Scheduled task executions                    |
| KanbanTaskEventModel | Kanban board events                          |
| EventLog             | Tool call counts (file-based)                |

### Error Responses

| Code | Description                                |
| ---- | ------------------------------------------ |
| 400  | Invalid date format (must be `YYYY-MM-DD`) |
| 400  | Missing `date` parameter                   |

## Daily Wrap (AI Summary)

Get an AI-generated natural-language summary of a day's activity, including keywords and next-day suggestions. Results are cached in SQLite to minimize LLM costs.

```
GET /api/v1/statistics/daily-wrap?date=YYYY-MM-DD
```

### Parameters

| Parameter | Type   | Required | Description                 |
| --------- | ------ | -------- | --------------------------- |
| `date`    | string | Yes      | Date in `YYYY-MM-DD` format |

### Response

```json theme={null}
{
  "code": 0,
  "data": {
    "date": "2026-06-27",
    "summary": "Productive day focused on code review and bug fixes. Completed 5 sessions across web and Telegram channels.",
    "keywords": ["code review", "bug fix", "telegram"],
    "suggestions": ["Continue the refactoring started in session #3", "Review pending approvals"],
    "generated_at": "2026-06-27T23:05:00Z",
    "cached": true
  }
}
```

### Regenerate

Force a fresh AI summary, bypassing the cache:

```
POST /api/v1/statistics/daily-wrap/regenerate?date=YYYY-MM-DD
```

Returns the same response structure as the GET endpoint with `cached: false`.

### Requirements

* A **Lite Model** must be configured in Settings (used for low-cost summary generation)
* If no activity exists for the date, returns `reason: "no_activity"` with `summary: null`
* If no Lite Model is configured, returns `reason: "lite_model_not_configured"` with `summary: null`

### How It Works

1. Aggregates data from the same 6 sources as Daily Journal (sessions, tokens, approvals, cron runs, kanban events, cost)
2. Builds a structured prompt and sends it to the configured Lite Model
3. Parses the LLM response (supports JSON and plain-text fallback)
4. Caches the result in a dedicated `daily_wrap_cache` SQLite table (one row per date)

## Per-Agent Usage Analytics

Break down token consumption and cost by individual agent — see which agents consume the most resources, with 7-day trend sparklines.

```
GET /api/v1/statistics/usage/by-agent?days=7
```

### Parameters

| Parameter | Type    | Required | Description                                             |
| --------- | ------- | -------- | ------------------------------------------------------- |
| `days`    | integer | No       | Number of days for sparkline data (default: 7, max: 30) |

### Response

```json theme={null}
{
  "success": true,
  "data": {
    "agents": [
      {
        "agentId": "builtin-general",
        "name": "General Assistant",
        "avatar": "icon:general",
        "totalTokens": 125000,
        "totalUsd": 1.25,
        "totalCalls": 42,
        "sessions": 15,
        "percentTokens": 65,
        "percentUsd": 72,
        "sparkline": [
          { "date": "2026-06-03", "tokens": 18000, "usd": 0.18 },
          { "date": "2026-06-04", "tokens": 22000, "usd": 0.22 }
        ]
      }
    ],
    "total_agents": 3,
    "grand_total_tokens": 192000,
    "grand_total_usd": 1.74
  }
}
```

### Key Features

* Results sorted by total USD cost (highest first)
* Percentage breakdown shows each agent's share of total consumption
* Sparkline data enables 7-day SVG trend visualization in the UI
* Automatically resolves agent names and avatars from the Agent registry
* The `AgentUsageCard` component auto-hides when there is only 1 agent (no comparison value)

## Session Execution Trace

Retrieve the complete execution trace for a session — tool calls, LLM invocations, errors, human feedback events, and memory operations — structured for timeline replay.

```
GET /api/v1/statistics/session/{session_id}/trace
```

### Response

```json theme={null}
{
  "code": 0,
  "data": {
    "session_id": "sess-abc123",
    "metadata": {
      "user_id": "user-1",
      "agent_id": "builtin-general",
      "task_type": "chat",
      "trace_id": "trace-xyz"
    },
    "outcome": "success",
    "start_time": 1720000000.0,
    "end_time": 1720000030.0,
    "duration_ms": 30000,
    "task_input": "Help me refactor this module",
    "output": "Done! I've refactored the module into 3 files.",
    "tool_calls": [
      {
        "sequence": 1,
        "tool_name": "read_file",
        "start_time": 1720000002.0,
        "end_time": 1720000003.5,
        "duration_ms": 1500,
        "success": true,
        "error": null,
        "input_data": { "path": "/src/module.py" },
        "output_summary": "Read 200 lines"
      }
    ],
    "llm_calls": [
      {
        "sequence": 1,
        "start_time": 1720000001.0,
        "end_time": 1720000005.0,
        "model_name": "claude-sonnet-4-20250514",
        "prompt_preview": "[user] Help me refactor...",
        "message_count": 3,
        "duration_ms": 4000,
        "ttft_ms": 180,
        "prompt_tokens": 1200,
        "completion_tokens": 800,
        "total_tokens": 2000
      }
    ],
    "errors": [],
    "human_feedback": [],
    "memory_events": [
      {
        "id": "mem-1",
        "phase": "extraction",
        "status": "completed",
        "timestamp": 1720000028.0,
        "title": "Working Memory Extract",
        "summary": "Learned user prefers small focused modules",
        "target_kind": "memory",
        "target_id": "mem-target-1",
        "influence_count": 2
      }
    ],
    "total_events": 12,
    "total_tokens": 2000
  }
}
```

### Key Features

* **Zero-storage replay**: Traces are reconstructed on-demand from the append-only event log — no extra database or video files needed
* **Seven event types**: tool\_start, tool\_end, llm\_call, human\_feedback, memory, error, message
* **Frontend Session Replay Player**: The WebUI provides a three-pane interactive player (Chat View / Mind View / Inspector) with scrubber, playback speed control, keyboard navigation, and jump-to-error
* **Dataset export**: Traces can be batch-exported to ShareGPT/Alpaca/OpenAI JSONL format for fine-tuning via the `dataset_export` pipeline

## Growth Statistics

Growth dashboard metrics are available through the unified **Learning Journey** page (`/journey`, former `/growth` auto-redirects) and provide:

* Skill KPI summary (total, success rate, evolution count)
* Smart savings summary (cost reduction through caching and routing)
* 84-day activity heatmaps and multi-dimensional health radar charts
* Weekly trend analysis and AI-powered daily wrap summaries
* Evolution timeline with skill lifecycle events
* **Knowledge Graph** — interactive Claim/Evidence 2D force-directed visualization with namespace filtering
* **Skill Usage Efficiency Trends** — per-skill success rate, average duration, and call frequency over time (daily granularity)

## Harness Observability Metrics (Prometheus)

The Myrm Engine exposes underlying Prometheus telemetry metrics for deep DevOps & SRE monitoring. These metrics run on the `/metrics` endpoint and incur zero operational overhead.

### Advanced Agent Metrics

* `myrm_time_to_first_action_seconds` (Histogram): Captures the precise Time-To-First-Action (TTFA), calculating the exact time from receiving a user's instruction until the agent invokes its first tool.
* `myrm_policy_denial_total` (Counter): Tracks the number of times agent actions were blocked, redacted, or denied by the Security Guardrails and Path Policies.
* `myrm_tool_execution_total` & `myrm_tool_execution_failed_total` (Counters): Monitors execution results for all individual skills, providing real-time data for calculating the overall "Tool Effectiveness Ratio" on Grafana dashboards.

### Production Alerting Rules (Cloud Deployment)

For cloud-hosted deployments, Myrm ships with 12 production-grade Prometheus alerting rules covering sandbox health and reliability:

| Alert                      | Severity | Trigger                        |
| -------------------------- | -------- | ------------------------------ |
| ContainerPoolExhausted     | Critical | Pool available = 0 for 5 min   |
| ContainerPoolLow           | Warning  | Pool available \< 2 for 10 min |
| HealthCheckFailureRateHigh | Critical | Failure rate > 20% for 5 min   |
| ContainerCreationSlow      | Warning  | P99 creation > 10s for 5 min   |
| ContainerOOMKills          | Critical | Any OOM kill detected          |
| HotPoolExhausted           | Critical | Hot pool = 0 for 5 min         |

Each alert includes a `runbook_url` linking to the Enterprise Runbook for remediation steps.

### Grafana Dashboard

A ready-to-import Grafana dashboard (`grafana-dashboard-sandbox.json`) provides real-time visualization of container pool status, hit rates, health check success rates, creation latency, and hot pool availability. Import via Grafana UI or provisioning directory mount.

### Smart Enable/Disable

Metrics collection is automatically enabled or disabled based on deployment mode — local and desktop deployments run with zero overhead, while cloud deployments expose the full `/metrics` endpoint for Prometheus scraping.

## Agent Liveness SSOT

A single aggregated endpoint that tells you whether your agent is busy, idle, or degraded — no need to poll multiple APIs.

```
GET /api/v1/health/liveness
```

### Response

```json theme={null}
{
  "state": "busy",
  "agents": {
    "activeCount": 2,
    "maxConcurrent": 3,
    "availableSlots": 1,
    "sessions": [
      {
        "sessionId": "abc-123",
        "chatId": "chat-456",
        "agentType": "general",
        "elapsedSeconds": 12.5
      }
    ]
  },
  "channels": {
    "wechat": { "status": "connected" },
    "telegram": { "status": "connected" }
  },
  "memory": {
    "level": "NORMAL",
    "percent": 42.3
  },
  "uptimeSeconds": 3600.5
}
```

### State Logic

| State      | Condition                                                                        |
| ---------- | -------------------------------------------------------------------------------- |
| `busy`     | At least one agent session is actively running                                   |
| `degraded` | No active sessions, but a channel is disconnected or memory pressure is elevated |
| `idle`     | No active sessions, all channels healthy, memory normal                          |

### Use Cases

* **Frontend tray / pet indicator**: Poll this endpoint to show a tri-state icon (spinning = busy, green = idle, amber = degraded)
* **Cloud monitoring**: `curl /api/v1/health/liveness | jq .state` integrates with Prometheus/Grafana alerting
* **Multi-pane workspace**: Show agent availability across browser tabs without opening settings

### Key Properties

* **Pure read-only aggregation**: Zero I/O, zero database queries — all data comes from in-memory gateway state
* **Sub-millisecond response time**: Suitable for frequent polling (every 2-5 seconds)
* **Works across all deployment modes**: Local WebUI, Tauri desktop, and cloud-hosted
