Stats — usage and activity ledgers, run-outcome upserts, the stats folds, version diffs. A repository rule for apps/daemon/src/v1/stats/**, apps/daemon/src/v1/agents/**/usage-figures*, apps/daemon/src/v1/agents/**/tool-metric*, apps/daemon/src/v1/agents/**/tool-usage*, apps/daemon/src/v1/agents/**/chat-metrics*, apps/daemon/src/v1/agents/adapters/**/*tool-metric*, apps/daemon/src/v1/teams/**/team-version*, apps/daemon/src/v1/agents/**/run-outcome*; read it before editing a file there.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Rule Daemon Stats?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/geniro-io-rule-daemon-stats)
---
name: rule-daemon-stats
description: "Stats — usage and activity ledgers, run-outcome upserts, the stats folds, version diffs. A repository rule for apps/daemon/src/v1/stats/**, apps/daemon/src/v1/agents/**/usage-figures*, apps/daemon/src/v1/agents/**/tool-metric*, apps/daemon/src/v1/agents/**/tool-usage*, apps/daemon/src/v1/agents/**/chat-metrics*, apps/daemon/src/v1/agents/adapters/**/*tool-metric*, apps/daemon/src/v1/teams/**/team-version*, apps/daemon/src/v1/agents/**/run-outcome*; read it before editing a file there."
---
<!-- GENERATED by scripts/sync-agent-rules.mjs from .claude/rules/daemon-stats.md. DO NOT EDIT: edit the source, then run `pnpm sync:agent-rules`. -->
# Stats
- `usage_events` and `usage_activity`: ledgers that outlive teardown (`.claude/rules/storage-split.md`). Append-only, with two exceptions, both `usage_activity`:
- A `run_outcome` row (one per run and pull request, keyed `outcome:<runId>:<owner>/<repo>#<n>`) is UPDATED to a newer outcome, only ever forward by its source item's seq — or at the same seq only while it lacks the history figures — in one `INSERT … ON CONFLICT … DO UPDATE … WHERE` (`UsageActivityDao.upsertRunOutcome`). Each copy carries the pull request's history figures and the questions asked before it, read from the run's rows when the copy is made (`RunOutcomeHistoryService`). `RunOutcomeLedgerService` copies each `run_outcome` item off `bus.all()` and, behind the boot, sweeps every outcome row the ledger lacks, holds older, or holds without its figures; `UsageActivityDao.runOutcomes` is the read a per-team-version outcome fold will use; the versions table does not read it yet.
- A team run's `thread` row carries the team version ledger's version stamp, UPDATED in place (below).
- Team version ledger (`TeamLedgerService`): a team run's `thread` row is stamped with its team and team version (`teamVersionOf`, `teams/utils/team-version.ts`: a constant `mode: 'lead'` (so a version recorded with `mode: lead` keeps its hash), the members, trigger, instruction blocks and stages in their authored order, an empty stage list counting as none, and `maxActiveTurns`; never the team's name or description, nor a member's `avatar` — a version restore keeps each member's current face; a run snapshot written before members hashes as it always did, `legacyGraphVersionOf`) at `run_created`.
- Each version's team is recorded once in `team_versions`, keyed by (slug, version), teardown-exempt like the ledgers; `first_seen_at` keeps the earliest run, and versions are numbered by it.
- A run with no graph copy it can read is stamped with its team alone and stays so, even after a later read freezes the library's graph into it. A run created before `SNAPSHOT_AT_CREATION_SINCE` is `inferred` (its copy was frozen later) and its graph is never registered, so it gets no number and no change summary.
- The versions table (`GET /v1/stats/team-versions`) serves per version only the dates used, the run count, the cost and its average per priced run, and the graph's unified diff against the version numbered before it (`canonicalGraphYaml` of both, `utils/version-diff.ts` over jsdiff) with its added and removed line counts. A version's diff never changes, so `TeamVersionsService` keeps it in memory. Run status, failed nodes, turns, pull requests, lines and work time are deliberately not shown (user decision).
- `POST /v1/stats/team-versions/restore` (`TeamVersionsService.restore`) writes a recorded version back as the library file's graph: its nodes, edges, `maxActiveTurns` and stages, under the file's own name and description, the places of the nodes it still has and the labels of the edges it still has. It backs the file up first (`.backups/`, as an applied change does), refuses a `baseHash` the file has moved past (`TEAM_CHANGED`, checked before the backup and again by the store's save), and refuses a version with no recorded graph (`TEAM_VERSION_NOT_FOUND`: an inferred one never has one). Restoring writes no new version: the next run stamps the restored one. The graph it replaces is recorded, numbered as of the restore, when no run has stamped it (an edit not run yet), so the table keeps it and it can be restored back; one a run stamped already has its row.
- What is current is always the library file's graph (`currentVersion`), so a restore or an edit moves the current mark at once. When no version records that graph yet (edited since its last run, or never run), the table still shows it as its first row (`recorded: false`, unnumbered, no dates), diffed against the newest recorded version; its first run numbers it. A recorded version no run has stamped is a row with no dates.
- The archive sweep deletes archived TEAM runs too (`sweepArchived` → `purgeArchived`), so `TeamLedgerService.sweep()` is awaited in `main.ts` before listen — every boot, selecting only runs with no version stamp yet.
- Every read by `team_slug` filters `kind = 'thread'`: `run_outcome` rows carry the slug too.
- A team's own figures (`GET /v1/stats/teams/:slug`, `TeamStatsService` over `utils/team-stats-fold.ts`) are folded over every thread row stamped with the slug and every ledger row of those runs, deleted runs included: runs, cost and its estimated part, turns, worked time (the CLIs' own less what cards held, `durationMs − heldMs`, plus geniro's clock from `wall_turns` for a turn whose ledger row has no `durationMs`, matched by `(runId, seq)` and served apart as `measuredWorkedMs`, which a deleted run takes with it), pull-request outcomes, a local-day series of each, and a split by `usage_events.memberId`. Each member also carries its runs, its `work` (`utils/member-work-fold.ts`: calls answered and failed with their average open time, calls made, tool calls and errors, the goals it recorded by `run_goals.memberId`, and the completions of the stages it is responsible for in the team version that run ran (`team_versions` graph, never the member that moved the stage: the lead moves them all) with how many a later `reopen` of that stage in the same run undid — null when no run it took part in was measured) its `perRun` spread (lowest, median, highest cost and working time over the runs it took part in), `work.cleanRuns` (measured runs where no call to it failed, no stage it owns was reopened and no goal it recorded ended not achieved), its `changes` (`utils/member-change-fold.ts`: every move between the versions two consecutive runs ran, a restore included and each counted once, diffed member by member over the `team_versions` graphs — role, instructions, character, agent, model, effort, approval, pool, tools, owned stages, the blocks addressed to it, added, removed — with the member's figures over each version's runs, or the team's for a member added or removed, the change log entry that made it, and an `effect`: better or worse when every figure that moved by a tenth or more moved that way, mixed when they disagree, too-few-runs under two runs a side) and its `assessments` (`.claude/rules/daemon-thread-analysis.md` → member assessments). `GET /v1/stats/usage`'s `byTeam` buckets only runs with a team slug; a chat is in no bucket.
- `v1/stats` observes `AgentEventBus` and never drives; nothing in `v1/agents` imports it. `McpModule` imports it for one read, a team's history (`TeamHistoryService`, with the recommendation ledger it reads: `.claude/rules/daemon-thread-analysis.md` → team analysis).
- Thread metrics (`ThreadMetricsLedgerService` off `bus.all()`, `MetricLedgerDao`): one `tool_call_events` row per finished tool call of an agent (never a sub-agent's), paired with its call by member, conversation (`inCall`) and id, named through `utils/tool-metric.ts` `toolMetricOf` (the member's adapter's `toolCallMetric` first, then any adapter that reads an MCP server off the name, so a pool member on another CLI is read right; a name that is no tool's — a command or a path used as a title — is counted by its ACP kind and never stored; the run's own `geniro-<runId8>` filed as `geniro`), timed from its call row; a `usage_activity` `stage` row per stage change but nudges (a `complete` timed from the run's previous move, else the run's start), a `call` row per `call_result` (the callee's turns and cost inside it, from the rows carrying the call id) and one `thread_outcome` row per run, moved forward by seq. A run's `thread` row is marked `metricsLedger` when it is created live; the folds (`utils/thread-metrics-fold.ts`, `GET /v1/stats/teams/:slug` `metrics`, `GET /v1/stats/usage` `metrics`) read a figure no measured run could carry as null. Goals achieved is achieved over every goal not dropped. No backfill: runs from before the ledgers are not measured.
- Usage counters (`usage_counters`, `usage_subjects`, `usage_counter_backfill`; teardown-exempt): one increment-only row per subject (tool / capability / skill / command) × source (MCP server, `geniro` for geniro's own, `''` otherwise) × agent × origin (`direct` / `subagent`) × project — calls, errors, refused, time and result-size sums, offered sessions, first and last use; never per day and never windowed (user decision). Names and counts only: a tool's, skill's or command's arguments and results are never read past what identifies them.
- Counting never touches the database on the call's path: `UsageCounterService` merges deltas in memory and upserts them every `USAGE_COUNTER_FLUSH_MS` and at shutdown, `USAGE_COUNTER_ADD_BATCH` rows per statement with a turn of the event loop between batches; a failed batch goes back for the next flush. Reads flush first.
- Sources: `ThreadMetricsLedgerService` adds a delta for every finished call (a sub-agent's too, paired by `parentToolUseId`; only an agent's own goes into `tool_call_events`) and for `stage_move`, `agent_call` and the first `thread_outcome` of a run; `UsageObserverService` counts the rest of the catalog (`utils/capability-catalog.ts`) off `bus.all()`, `allRunCreated`, `allPromptCacheWarmups` and `allUsageSignals` — the signals `McpServerService` (tools listed per session, a geniro tool's refusal), `TaskRunsService` (card starts by starter) and `FlagBroker` (automatic flags) publish on `AgentEventBus`, so none of them imports this module. A denied permission request adds `refused` to its tool only when `toolMetricOf` names a real one; geniro's own cards are no permission request.
- "What exists" (`UsageRegistryService`): every name `McpTool.names()` serves, registered by `McpServerService` at boot, and the capability catalog; a subject not registered by this boot is retired and never listed as never called. CLI built-in and other MCP servers' tools appear only once called.
- `UsageCounterBackfillService` folds `tool_call_events` rows before the cutoff written at the first boot of this build into the counters once, off the ready path, in `(occurred_at, id)` windows whose counts and cursor commit in one transaction; live counting skips a journaled call before the cutoff.
- Journal retention, the one exception to "ledgers are never pruned": `ToolCallLogRetentionService` deletes `tool_call_events` rows older than `toolCallLogRetentionDays` (pushed by the desktop app, `PUT /v1/stats/tool-usage/config`, desktop only), at most `JOURNAL_DELETE_WINDOW_MAX` rows per statement with a yield between, 5 minutes after a start and daily — never before the first push nor before the backfill is done. Counters are never pruned. Stats' and team stats' tool tables, which read the journal, then cover only the retention.
- Reads (`GET /v1/stats/tool-usage`, `GET /v1/stats/tool-usage/subject`, open to paired devices) fold every counter row (`utils/usage-counter-fold.ts`); `removalEligible` holds only for a registered geniro tool known `TOOL_REMOVAL_MIN_AGE_DAYS`, offered in `TOOL_REMOVAL_MIN_OFFERED_SESSIONS` sessions, never called.
- Ledger writes are native inserts, not flushes (a flush re-stamps loaded runs' `updated_at`).
- Boot backfills must stay idempotent (`(runId, seq)` unique, `dedupKey`).
- Polled spend: Stats reads it only from the ledger rows (`PROMPT_CACHE_WARMUP_SEQ < seq ≤ POLLED_SPEND_SEQ`, `isPolledSpendRow`), never from `runs`. A team run's polled rows are split across the members the poll credited (`NodeState.polledCostCents`), each row naming its member and that member's billed CLI (`polledSpendRows`); a chat's, or a team run with no credited member, names none.
- Prompt-cache warm-ups (`PromptCacheKeepAliveService`): each one is a `usage_events` row of its own with `purpose: 'cache_warmup'` and a seq at or below `PROMPT_CACHE_WARMUP_SEQ`, appended below the run's lowest (`UsageEventDao.recordPromptCacheWarmup`) off `AgentEventBus.allPromptCacheWarmups`, never rewritten by the poll. Every reader that counts turns asks `isSpendWithoutTurn` first (polled rows and warm-ups alike: money, no turn); a polled-only reader asks `isPolledSpendRow`. The run's figure is `NodeState.promptCacheWarmupCostUsd` / `promptCacheWarmups`, added on top of a team run's thread totals (`addPromptCacheWarmupSpend`).
- The spend fold is `v1/agents/utils/usage-figures.ts`, shared; never copy it. No price means `costUsd: null`, never $0.
- Lines are measured by the desktop app per folder against one `line_baselines` commit. Day lines are growth past the series peak, never a client delta.
- `ClaudeSessionCostLedger` persists session totals to disk (`claude-session-costs.json`). A resume's seed is registered at spawn and read from the transcript's last `cost-state` at the new process's `system/init`, never at spawn (the replaced process writes its line as it exits). A read that finds no line keeps a known total, and leaves the process's first result untrusted.
- List prices come only from `ModelPriceCatalog` (models.dev, persisted to `model-prices.json`); never a hand-written price table. Provider is an adapter fact (`usage.listPrice` to price a turn; `modelVendor`, `modelIdVariant` and `modelIdSpellings` to show a model's price, `AgentAdapter.modelPriceOf`). `GET /v1/stats/usage`'s `byModel` rows carry the price of an agent that ran the model, a polled row's billed CLI included.