store

package
v0.111.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store owns the SQLite database: opening, migrating, and every query. Nothing else in Caprock issues SQL. Pure Go driver (modernc.org/sqlite), no CGO — see ADR-012.

Index

Constants

View Source
const (
	ProjectKindRepo   = "repo"
	ProjectKindFolder = "folder"

	ProjectSourceSeed    = "seed"
	ProjectSourceSession = "session"
	ProjectSourceFolder  = "folder"
	ProjectSourceNew     = "new"
	ProjectSourceClone   = "clone"
)

Project kinds and sources, as the CHECK constraints spell them.

View Source
const (
	StatusActive = "active"
	StatusIdle   = "idle"
	StatusEnded  = "ended"
)

Session status values.

View Source
const (
	HandoffNone     = 0 // nothing was there to hand over
	HandoffServed   = 1 // it was handed what the last session left
	HandoffWithheld = 2 // something was there and was held back, as the control
)

Handoff states on sessions.handoff.

View Source
const (
	SavedKindPrompt  = "prompt"
	SavedKindCommand = "command"
)

Saved prompt kinds, as the CHECK constraint spells them.

View Source
const (
	MetaSchemaVersion = "schema_version"
	// MetaTranscriptSchema records the parser version that wrote the events, so
	// a bump can trigger a one-time re-derivation of affected payloads.
	MetaTranscriptSchema = "transcript_schema_version"
	MetaPricingVersion   = "pricing_version"
	// MetaToolLinkBackfilled marks the one-time recovery of the tool→turn
	// linkage from the transcripts (ingest.BackfillToolMessageIDs). It lives in
	// the daemon rather than the store because it needs the transcript files.
	//
	// It is the marker for the ORIGINAL, path-only pass and is now only read as
	// history: a database that finished that pass still has every pathless call
	// unlinked, so it must not be taken to mean the linkage is complete.
	MetaToolLinkBackfilled = "tool_link_backfilled"
	// MetaToolLinkCursor is the resume point of the widened backfill (OQ-10):
	// the highest event id already examined. A separate key from
	// MetaToolLinkBackfilled because the narrow pass set that one to "1" on
	// databases where 53293 pathless rows were never even looked at — reusing
	// it would skip exactly the machines the widening is for. Absent ⇒ start at
	// 0; the sentinel below ⇒ finished.
	MetaToolLinkCursor = "tool_link_cursor"
	// MetaCodexDailyRebuilt marks that daily_stats' Codex rows were rebuilt
	// from events once — migrations 0022 and 0023 re-imported every Codex
	// event without taking the first import back out of daily_stats.
	MetaCodexDailyRebuilt = "codex_daily_rebuilt"
	// MetaCodexSeen remembers which Codex transcripts have been read (path,
	// modification time, size, session), so a restart reads only what changed.
	MetaCodexSeen = "codex_seen"
	// MetaCodexTextBackfilled marks that the Codex turns imported before the
	// importer read assistant prose have been given it from their transcripts
	// once (codex.Ingester.backfillText).
	MetaCodexTextBackfilled = "codex_text_backfilled"
	// MetaCodexChatBackfilled marks that the Codex transcripts read before
	// prompts and tool results were stored have been read once more for both
	// (codex.backfillChat).
	MetaCodexChatBackfilled = "codex_chat_backfilled"
	// MetaCodexSplitRepaired marks that the Codex rows earlier versions stored
	// wrongly have been repaired from the transcripts once: threads imported
	// from another agent removed, and subagent turns moved off the parent's
	// line-number keys (codex.Ingester.repairSplit).
	MetaCodexSplitRepaired = "codex_split_repaired"
	// MetaSessionModelRepaired marks that sessions.model was recomputed once
	// from each session's latest main-thread turn: earlier versions let a
	// subagent's turn overwrite it (rollup.RepairSessionModels).
	MetaSessionModelRepaired = "session_model_repaired"
	// MetaForkedTurnsRepaired marks that the assistant turns a fork's
	// transcript copied from its parent have had their usage and cost taken
	// back out once: earlier versions priced every copy again
	// (rollup.RepairForkedTurns).
	MetaForkedTurnsRepaired = "forked_turns_repaired"
	// MetaDeepseekInjectedRemoved marks that the prompts earlier versions
	// stored for DeepSeek Harness's own `user/message` records (instructions,
	// runtime context) have been deleted once, verified against the
	// transcripts (deepseek.Ingester.removeInjected).
	MetaDeepseekInjectedRemoved = "deepseek_injected_removed"
	// MetaReportWeek is the ISO week of the last weekly report that was sent,
	// as "2026-W36". It lives here rather than in memory because an in-memory
	// marker sends a second copy of the message after every restart — the bug
	// cap.Guard.firedOn has, tolerable for a cap and not for a message someone
	// receives on their phone.
	MetaReportWeek = "report_week"
	// MetaReportLastError is why the last weekly send failed, empty when it did
	// not. Stored rather than held in memory for the same reason the week is:
	// the person who configured a bot is waiting for a message, not watching a
	// settings screen, and an error that vanishes on the next restart takes the
	// only evidence of a silent failure with it. "chat not found" a week later
	// is still the answer.
	MetaReportLastError = "report_last_error"
	// MetaAliveAt is the daemon's heartbeat, unix ms as a string, written every
	// minute. Read once at start, before the first write, it is when the
	// previous run stopped — to the minute, whether it stopped cleanly or the
	// machine went down under it.
	MetaAliveAt = "daemon_alive_at"
	// MetaInterrupted is the sessions that were still running when the daemon
	// last stopped and were gone when it started again, as JSON
	// {"stopped_at": ms, "ids": [...]} (FB-038).
	MetaInterrupted = "interrupted"
	// MetaReportLastSent is when a report last went out, unix ms as a string.
	MetaReportLastSent = "report_last_sent"
	// MetaEmptyTextRepairPending is "1" while assistant turns stored before
	// parser v4 still wait to have their prose read back from the transcripts
	// (ingest.RepairEmptyAssistantText). Set when a start finds an older
	// parser version, cleared when the repair has run, so a daemon stopped
	// mid-repair runs it again.
	MetaEmptyTextRepairPending = "empty_text_repair_pending"
	// MetaPRsBackfilled is "1" once session_prs holds the pull requests of the
	// events stored before migration 0035.
	MetaPRsBackfilled = "session_prs_backfilled"
	// ToolLinkDone is the MetaToolLinkCursor value meaning "no rows left".
	// A cursor alone cannot say so: the pass ends by reading a short batch, and
	// new unlinked rows never appear behind the cursor.
	ToolLinkDone = "done"
)

Meta keys.

View Source
const CodexRateLimitPrefix = "codex_"

CodexRateLimitPrefix namespaces Codex's windows in rate_limit_latest, so they sit beside Claude Code's `five_hour` / `seven_day` rows without replacing them: `codex_five_hour`, `codex_seven_day`.

View Source
const LiveSubagentWindow = 30 * time.Minute

LiveSubagentWindow bounds how long a silent subagent is believed to be working: one whose SubagentStop never arrived must not count forever.

View Source
const MainThreadWhere = `COALESCE(e.agent_id, '') = '' AND json_extract(e.payload, '$.sidechain') IS NOT 1`

MainThreadWhere keeps the events of a session's main thread and drops its subagents', for a query over `events e`. It is the SQL twin of event.Event.Subagent and must say the same thing.

View Source
const MaxEventPage = 5000

MaxEventPage is the most events one ListEvents call will return. Callers that need more must paginate with `after`.

View Source
const MaxSessionCalls = 20000

MaxSessionCalls bounds GET /v1/sessions/{id}/calls. A long session makes a few thousand model calls; this is several times that, and still a page the cockpit draws in one pass.

View Source
const MaxSessionsPage = 2000

MaxSessionsPage caps one page of the session list. The Now screen asks for more in steps; a caller asking for everything gets this many and the total in X-Total-Count, not a response the size of the database.

View Source
const MetaProjectsSeeded = "projects_seeded"

MetaProjectsSeeded is "1" once the projects list has been seeded from the repositories sessions ran in.

View Source
const OutsidePath = "\x00outside"

OutsidePath is the sentinel for turns whose carried directory is real but sits outside the repository — Claude's notes about the project, subagent scratchpads, test-output directories, or another checkout entirely.

It is a row of its own, sibling to the directory rows and to UnattributedPath, because it is neither: the work has a known location and that location is simply not in this tree. Merging it into repository-wide work would mislabel a quarter of the bill as "no single home" when its home is known and named; folding it into the repository root would claim work happened in the checkout that did not. See AttributeDir for the measured shares and for why "another checkout" is not split out separately.

View Source
const TouchRule = "" /* 454-byte string literal not displayed */

TouchRule is the statement of how a turn is placed, shown in the UI so the number is not a black box. It is the sentence that makes this honest rather than a guess, so it says exactly what the rule does and claims nothing more.

THE RULE, in the user's words: a turn counts toward the directory of the most recent file it touched, and work keeps counting there until it touches a file somewhere else.

Why a stretch and not a single call. Work happens in stretches: after "finish /app", Claude edits, runs the tests, reads the output, greps, edits again. Charging only the calls that name a file would count the edit and discard the hour around it.

What counts as touching. A tool that names a FILE — Read, Edit, Write, NotebookEdit. Bash does not, even when its command contains a path: `grep -r foo /services` reads a tree and `cd /services/api && go build ./...` names one directory while touching many, so parsing intent out of a command line would be inference presented as measurement. Under carry-forward that costs nothing, because a Bash turn is placed by the file touched before it rather than dropped.

Why reading counts. Reading a file to understand it is how most of a turn's tokens get spent — the contents enter the prompt and are billed.

View Source
const UnattributedPath = "\x00unattributed"

UnattributedPath is the sentinel for the turns carry-forward cannot place: those that ran before any file was touched in their session.

It is a sentinel, not a path, and it must never reach a user as one: the UI renders it as "repository-wide work" in its own style with the reason attached. It starts with a character no path segment does so that a hypothetical directory of the same name could not collide with it.

WHAT NOW LANDS HERE, AND WHY THE ROW IS SMALL. Under the previous strict rule this bucket was most of the money — 87.6% of the owner's `amarketer` — and the UI had to work hard to explain that it was not a failure. Under carry-forward it means one narrow, honest thing: a session's opening turns, before Claude has touched any file. On the owner's database that is $2.39 of $3426 in `amarketer` and $11.45 of $1729 in `caprock` (measured 2026-08-22). It is usually zero, and the UI must not render an empty row.

View Source
const WorkKindRule = "" /* 456-byte string literal not displayed */

WorkKindRule is the statement of how a turn is placed, shown in the UI so the number is not a black box — the same contract TouchRule holds for the per-directory breakdown.

The precedence is ordered by what the turn most concretely DID, strongest evidence first: writing a file is a stronger statement about a turn than running a command, which is stronger than reading. It is not ordered by cost, which would let the ranking rewrite itself as the data changed.

View Source
const WorktreeDir = ".caprock-worktrees"

WorktreeDir is where Caprock checks out a worktree for one of its own agents, relative to the repository root. Kept here so the resolver and the code that creates them agree on the name (see internal/agents.WorktreeDir).

Variables

View Source
var ErrDuplicate = errors.New("duplicate event")

ErrDuplicate is returned by InsertEvent when (session_id, key) already exists.

View Source
var ErrNotMultiRepo = errors.New("this project is not a multi-repo project")

ErrNotMultiRepo is returned when a multi-repo action meets a project with no member repositories.

View Source
var ErrProjectNotFound = errors.New("no such project")

ErrProjectNotFound is returned for an id no row has.

View Source
var ErrQueuedNotFound = errors.New("no such queued message")

ErrQueuedNotFound is returned for an id the session's queue does not hold.

View Source
var ErrRemovedSession = errors.New("session was removed from Caprock")

ErrRemovedSession is returned by the recorder for an event of a session the owner removed; it is not a failure, the event is simply not recorded.

View Source
var ErrSavedNotFound = errors.New("no such saved prompt")

ErrSavedNotFound is returned for an id no row has.

Functions

func ActivityBuckets added in v0.108.0

func ActivityBuckets(ctx context.Context, q Querier, from, bucket int64, n int) (map[string][]int, error)

ActivityBuckets is how many turns and tool calls each session recorded in each bucket of [from, from+n*bucket): the sidebar's per-project sparkline. One range scan on idx_events_ts over a short window — the last hour by default — and only two kinds, so a busy machine reads a few thousand rows. Sessions with nothing in the window are absent.

func AddDaily

func AddDaily(ctx context.Context, q Querier, day, project, model string, tokens int64, cost float64, newSession bool) error

AddDaily increments daily_stats for (day, project, model). newSession bumps the sessions count, and is true only for the row that carries it — see MarkDailySession.

func ArchiveProject added in v0.75.0

func ArchiveProject(ctx context.Context, q Querier, id int64, at int64) error

ArchiveProject takes a project off the list. Nothing on disk is touched.

func AttributeDir added in v0.14.0

func AttributeDir(t TouchDirs, repoRoot string) (string, bool)

AttributeDir decides which row a turn's cost belongs to, given the directory carried into it and the repository the turn's session sits in.

It always returns a row, because every turn's cost belongs somewhere and the rows must sum to the repository total. There are exactly three outcomes:

  • a directory inside the repository, written relative to its root
  • OutsidePath, when the carried directory is real but not in this repository
  • UnattributedPath, when no touch preceded this turn in its session

PATHS OUTSIDE THE REPOSITORY get their own row rather than being folded into the repository root or dropped. Folding them into "/" would claim work happened in the checkout when it did not; dropping them would stop the parts reconciling with the total. On the owner's database this is not a rounding error — it is 25.8% of `amarketer` and 28.7% of `caprock` (measured 2026-08-22) — and it is overwhelmingly work ON this project whose files live elsewhere: Claude's own notes under ~/.claude/projects/<project>/memory, subagent scratchpads under the per-session temp directory, and test output directories. A share that large must be named, not hidden.

It deliberately does NOT try to tell "another checkout" from "scratch space". The only way to do so would be to ask whether the path sits under some OTHER repository root the database happens to know, and that answer is unstable: `caprock-web` is a real git repository on disk that no session was ever launched from, so it is invisible here — the same path would classify one way today and another tomorrow, silently moving money between rows. One structural question ("is it inside THIS repository?") is answerable from the two paths alone and always gives the same answer.

TURNS BEFORE ANY TOUCH land in UnattributedPath rather than carrying BACKWARD from the session's first touch. Measured both ways on the owner's database (2026-08-22, all time): carrying backward moves $2.39 of $3426 in `amarketer` and $11.45 of $1729 in `caprock` — 0.1% and 0.7%. That is far too little to justify a second rule pointing the opposite way, which would make the one-sentence explanation two sentences and let a session's opening question charge a directory it had not reached yet.

func AttributeTaskCost

func AttributeTaskCost(ctx context.Context, q Querier, taskID string) (float64, error)

AttributeTaskCost sums event cost within a task's assignment windows and writes it to tasks.cost_usd (T24).

func BootTime added in v0.60.0

func BootTime() time.Time

BootTime is when the machine last started, or the zero time when the platform cannot say.

It closes the one hole in ProcessAlive that is not rare: a reboot. The pid space starts again from the bottom, so the small numbers Claude Code sessions held yesterday are handed straight back out to whatever starts first, and a session from before the reboot was called alive for as long as that stranger ran. No process from before a boot can be running after it, so a session last heard from before the boot is over whatever its pid says.

func BranchAt added in v0.95.0

func BranchAt(dir string) (string, bool)

BranchAt is the branch checked out in the git checkout holding dir, read from its HEAD file — no git process — and ok=false when there is no checkout, HEAD cannot be read, or it is detached.

It exists because Claude Code's own `gitBranch` cannot be trusted for the main thread: with a background agent working in a linked worktree, the parent's transcript lines kept their cwd and reported the worktree's branch, and the owner's session on master read `feat/cockpit-scrub` (2026-10-09, 0.94.2). A linked worktree has its own HEAD, under the `gitdir:` its `.git` file names.

func CleanRepoPaths added in v0.111.0

func CleanRepoPaths(paths []string) []string

CleanRepoPaths normalises paths, drops empties and duplicates, and sorts them: the form project_repos keeps.

func ClearPendingPermission added in v0.73.0

func ClearPendingPermission(ctx context.Context, q Querier, sessionID string) error

ClearPendingPermission forgets every prompt a session waited on.

func ClearQueued added in v0.104.0

func ClearQueued(ctx context.Context, q Querier, sessionID string) (int64, error)

ClearQueued empties a session's queue and says how many it dropped.

func CloseTaskAssignments added in v0.12.0

func CloseTaskAssignments(ctx context.Context, q Querier, taskID string, toTs int64) error

CloseTaskAssignments closes every open window on a task at to_ts. Windows are keyed by *session* id (AttributeTaskCost joins events.session_id), and the board — which finishes a task — only knows the hive *agent* id, not the session the router spawned for it. Closing by task is the identifier both sides already agree on, and it is correct when a task was worked by more than one session (a reassignment, or a worker respawned after a crash).

func CountEvents

func CountEvents(ctx context.Context, q Querier) (int64, error)

CountEvents returns the total number of stored events (for status/metrics).

func CountSavedPrompts added in v0.102.0

func CountSavedPrompts(ctx context.Context, q Querier) (int, error)

CountSavedPrompts is how many rows there are, for the cap.

func CountSessions added in v0.49.0

func CountSessions(ctx context.Context, q Querier, activeOnly bool) (int, error)

CountSessions returns how many sessions exist under the same filter ListSessions pages through — so a caller can say "200 of 431" rather than presenting a truncated page as the whole set.

func CountSessionsMatching added in v0.59.0

func CountSessionsMatching(ctx context.Context, q Querier, activeOnly bool, search string) (int, error)

CountSessionsMatching counts what ListSessionsMatching would return without a limit.

func CountThrottles

func CountThrottles(ctx context.Context, q Querier, sinceMs int64, agent AgentFilter) (int64, error)

CountThrottles counts throttle observations since sinceMs (limit-forecast input). CountThrottles counts rate-limit and overloaded events since sinceMs, through the same agent filter as the figures they are shown beside. The table carries a session id, so the scope is answerable; the empty filter counts every agent.

func DefaultTempDirs added in v0.70.0

func DefaultTempDirs() []string

DefaultTempDirs are the scratch locations on this platform.

func DeleteQueued added in v0.104.0

func DeleteQueued(ctx context.Context, q Querier, sessionID string, id int64) error

DeleteQueued takes one message out of a session's queue.

func DeleteSavedPrompt added in v0.102.0

func DeleteSavedPrompt(ctx context.Context, q Querier, id int64) error

DeleteSavedPrompt removes a row; ErrSavedNotFound when there was none.

func DirWithin added in v0.75.0

func DirWithin(dir, root string) bool

DirWithin reports whether dir is root or below it, on segment boundaries. Both are normalised first.

func DisambiguateLabels added in v0.12.2

func DisambiguateLabels(roots map[string]string) map[string]string

DisambiguateLabels resolves collisions among repository labels within one result set: two distinct roots whose basename is the same each grow parent segments until they read differently (`livegraph/repo`, `orch-live/repo`).

This runs over a summary's rows rather than at ingest, because whether a label is ambiguous is a property of the set it is displayed in, not of the repository. A label that is unique — the overwhelming majority — is left exactly as the user would say it.

roots maps each row's label to its repository root; the returned map gives the label to display for each root.

func EndSupersededSiblings added in v0.52.1

func EndSupersededSiblings(ctx context.Context, q Querier, pid int, keep string) (int64, error)

func EventsAfter

func EventsAfter(ctx context.Context, q Querier, after int64, limit int) ([]event.Event, error)

Cursor is a stable timeline of events across all sessions (for the live feed catch-up).

func EventsBefore added in v0.40.0

func EventsBefore(ctx context.Context, q Querier, sessionID string, before int64, n int) ([]event.Event, error)

EventsBefore returns the n events immediately preceding `before` (exclusive), oldest-first. before <= 0 means "from the end", which is what LastEvents is.

Paging backwards needs its own query: the timeline used to walk back by asking for the first 1000 events of the session and discarding everything it already had, which on a session with sixteen thousand events fetched the wrong end of the history and threw nearly all of it away.

func EventsVersion added in v0.105.0

func EventsVersion(ctx context.Context, q Querier) (int64, error)

EventsVersion is the newest event's id: it moves on every event written, and an answer counted at one version is still right at the same version unless rows were removed. Read off the primary key, so it costs one lookup.

func FirstEventTs added in v0.70.0

func FirstEventTs(ctx context.Context, q Querier) (int64, error)

FirstEventTs is when the first event was recorded (unix ms), or 0 with none: where "all time" starts.

func FirstPrompts added in v0.59.0

func FirstPrompts(ctx context.Context, q Querier, id string, limit int) ([]string, error)

FirstPrompts returns up to limit of a session's earliest user prompts, oldest first. Claude Code carries the text as `prompt`, DeepSeek Harness as `text`.

Pinned to idx_events_user_turn (migration 0033). Left to itself SQLite picked idx_events_kind_ts, which walks every turn.user row in the database and reads each one to test its session: 6ms a session on the owner's 1 GB database, run once per untitled row of /v1/sessions — 330ms of a 50-row list. The partial index holds only user turns, keyed by session and time, with the implicit rowid tail giving (ts, id) order and no sort.

func GetOffset

func GetOffset(ctx context.Context, q Querier, path string) (int64, error)

Offset persistence for the transcript tailer.

func HandoffCoverage added in v0.51.0

func HandoffCoverage(ctx context.Context, q Querier, since int64, minLen int) (repos int, oldest int64, err error)

HandoffCoverage counts the repositories that hold a passage recent and long enough to hand a new session, and dates the oldest of them.

For the status screen. A feature that acts before anyone types is one nobody can see working — this is how a person checks that it can, without opening a session to find out.

func IncForcedContinue

func IncForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) (int, error)

IncForcedContinue bumps and returns the forced-continue count for (session, task).

func InsertAttempt added in v0.102.0

func InsertAttempt(ctx context.Context, q Querier, a Attempt) error

InsertAttempt records that a session is attempt n of total in a group.

func InsertEvent

func InsertEvent(ctx context.Context, q Querier, ev *event.Event) (int64, error)

InsertEvent appends an event. Returns ErrDuplicate (and leaves the row alone) when the same (session_id, key) was already stored — the idempotency guarantee that lets ingest re-read a transcript after restart.

func IsBusy added in v0.70.0

func IsBusy(err error) bool

IsBusy reports whether err is SQLite saying the database was locked by another connection — a write that would succeed if tried again, as opposed to one that is wrong. Callers that would otherwise drop the record they were writing use it to keep it for a later attempt instead.

func IsRemoved added in v0.73.0

func IsRemoved(ctx context.Context, q Querier, sessionID string) (bool, error)

IsRemoved reports whether the owner removed this session (migration 0040).

func LastEvents

func LastEvents(ctx context.Context, q Querier, sessionID string, n int) ([]event.Event, error)

LastEvents returns the newest n events for a session, oldest first.

func LastEventsFiltered added in v0.92.0

func LastEventsFiltered(ctx context.Context, q Querier, sessionID string, n int, f EventFilter) ([]event.Event, error)

LastEventsFiltered is LastEvents with a filter applied before the limit: the n newest events that pass it, oldest first.

func LastMainTurn added in v0.65.0

func LastMainTurn(ctx context.Context, q Querier, sessionID string) (ev event.Event, found bool, err error)

LastMainTurn returns the newest turn.assistant of a session's main thread that carried usage, among its newest mainTurnScan events. found is false when there is none — a session whose every turn is a subagent's, such as an OpenCode child session, or one that has not answered yet.

It exists for the context-fill badge: a subagent starts with a fresh, small prompt, so measuring the session by its subagent's last turn showed an almost full context as almost empty.

func LastPermissionMode added in v0.78.2

func LastPermissionMode(ctx context.Context, q Querier, sessionID string) (string, error)

LastPermissionMode is the permission mode a session was last running in, as Claude Code's own hook payloads state it (`permission_mode`, common to every hook event), or "" when no stored hook carries one — a session observed from its transcript alone, or an agent without hooks.

It reads the stored payloads rather than a column, because every hook payload is already stored verbatim and the mode changes mid-session (⇧Tab cycles it), so the newest event is the answer and a column would be one more thing to keep in step. PostToolUse is skipped: its payload carries the tool's whole output, and it states the same mode as the PreToolUse before it. The value is Claude Code's word for the mode, unvalidated; the caller decides which words it passes on.

func LatestPRByDir added in v0.70.0

func LatestPRByDir(ctx context.Context, q Querier) (map[string]SessionPR, error)

LatestPRByDir is the most recent pull request of any session whose repository (or, outside one, directory) is each of the given keys — the directory a Projects row is keyed on.

func LinkToolCall added in v0.71.0

func LinkToolCall(ctx context.Context, q Querier, sessionID, key, msgID string) (bool, error)

LinkToolCall writes the message id onto a stored tool call that has none.

The same call usually reaches the store twice: from the PreToolUse hook, which knows no message id, and moments later from the transcript, which does. Both carry the key `pre:<tool_use_id>`, so the first write wins and the transcript's copy is a duplicate — and with hooks installed the hook is first nearly every time. Without this, the transcript's message id was dropped with the duplicate and the call was never attached to the turn that paid for it: on the owner's database every hook-plane call stored after the one-time backfill of 2026-08-23 had no msg_id (25,924 rows by 2026-10-04).

Only a NULL msg_id is filled: a tool_use id belongs to exactly one message, so an existing link is already right. Returns whether a row changed.

func ListEvents

func ListEvents(ctx context.Context, q Querier, sessionID string, after int64, limit int) ([]event.Event, error)

ListEvents returns events for a session with id > after, oldest first.

func LiveSubagents added in v0.70.0

func LiveSubagents(ctx context.Context, q Querier, sessionID string, since int64) (int, error)

LiveSubagents counts the subagents working in a session now: each agent id heard from since `since` whose latest event is not its SubagentStop.

Claude Code sends no event when a subagent starts, only hooks from inside it (they carry its agent_id) and a SubagentStop when it finishes. So a subagent is live from its first event until its stop, and `since` bounds how long a silent one is believed: one whose stop never arrived must not count forever.

func MarkDailySession added in v0.49.1

func MarkDailySession(ctx context.Context, q Querier, day, project, sessionID string) (bool, error)

MarkDailySession records that a session was seen on a day, and reports whether this was the first time.

The caller used to answer "is this a new session" with "is this its first turn ever", so a session that started yesterday added nothing to today — four of eight days on the owner's database read zero sessions beside real spend.

Keyed by day and project, deliberately not by model. daily_stats *is* keyed by model and the dashboard sums a day's rows, so the count has to live in exactly one place: keyed by model as well, a session that switched from Opus to Haiku mid-day would be counted twice, which measured as 3 against a true 2 on 27 August.

func MarkEndedSessions

func MarkEndedSessions(ctx context.Context, q Querier, before int64) ([]string, error)

MarkEndedSessions ends sessions whose process is gone, and — only for sessions whose process was never known — sessions silent since `before`.

A session is over when its process exits, not when it goes quiet. Every number picked for "quiet enough" was wrong for somebody: twelve hours left the day's work marked live at midnight, one hour closed a session while its owner was at lunch. Both are guesses about a person's day standing in for a fact about a process, and the fact is available — the shim reports the pid of the Claude Code that ran it, and Caprock records the pid of every session it spawns itself.

So a session with a pid is judged only by whether that pid is alive, and may sit quiet for a week without being touched. `before` applies solely to sessions with no pid: rows written by an older shim, or read from a transcript with no live process behind them, where there is nothing to ask and a backstop is all there is.

func MarkIdleSessions

func MarkIdleSessions(ctx context.Context, q Querier, before int64) ([]string, error)

MarkIdleSessions flips active sessions with no event since `before` (unix ms) to idle. Returns the ids that changed.

func MarkOwned

func MarkOwned(ctx context.Context, q Querier, id, worktree, spawnCommand string, pid int) error

MarkOwned records that Caprock spawned this session (Phase 1).

func MergeAssistantText added in v0.70.0

func MergeAssistantText(ctx context.Context, q Querier, sessionID, key string, payload json.RawMessage) (bool, error)

MergeAssistantText folds the prose and tool names of a later line of one API response into the turn row that response is stored as.

Claude Code writes one response as several transcript lines — thinking, then text, then each tool_use — every one carrying the same message id and usage. The store keys turns on `msg:<id>` so usage is counted once, which keeps the FIRST line and dropped the rest. While the first line was usually the text that did not matter; once Claude Code began writing a thinking line first on every response, the stored turn kept an empty `text` and the prose that followed it never reached the database. On the owner's machine 93% of the assistant turns stored after 2026-09-29 had no text, against 10-28% in every earlier week (measured 2026-10-04), and the Answers tab of a session full of long replies showed one line.

Only the payload changes: usage, cost and id stay as the first line set them. It is idempotent — a transcript re-read after a restart offers the same lines again, and text already in the row is not appended twice. Returns whether the row changed.

func MovedOnSince added in v0.73.0

func MovedOnSince(ctx context.Context, q Querier, sessionID string, sinceMs int64) (bool, error)

MovedOnSince reports whether a session recorded anything after sinceMs that means a permission dialog drawn then is no longer on screen: a tool finishing, a prompt or reply, a turn ending, or the session ending. Another permission.prompt does not count: Claude Code queues dialogs, so a later one leaves the earlier on screen.

func NormalizeDir added in v0.75.0

func NormalizeDir(dir string) string

NormalizeDir puts a directory into the one form the store keeps paths in: forward slashes, no trailing separator (sessions.repo_root, projects.root).

func NotAProject added in v0.72.0

func NotAProject(cwd string) bool

NotAProject reports whether cwd is a place nobody works in as a project: a filesystem root, the home directory itself, or a temp directory itself.

Sessions do start there — on the owner's Mac a background `claude` opens in "/" every ten minutes and exits seconds later — but such a directory is no project to offer in the New session picker, and no repository whose last passage a new session should be handed. Subdirectories are unaffected.

func OpenAssignment

func OpenAssignment(ctx context.Context, q Querier, taskID, sessionID string, fromTs int64) error

OpenAssignment records that a session started working a task at from_ts. It is a no-op when an open window already exists for that (task, session), so a caller may invoke it every tick without stacking duplicate windows.

func PRToolPosts added in v0.70.0

func PRToolPosts(ctx context.Context, q Querier, fn func(sessionID string, ts int64, payload []byte) error) error

PRToolPosts streams the Bash PostToolUse rows that recorded a `gh pr` operation or ran `gh pr create`, for the one-off history backfill. A LIKE on the payload: this runs once, after the port opens.

func PreviousOnPID added in v0.60.0

func PreviousOnPID(ctx context.Context, q Querier, pid int, id string) (string, error)

updateStatusByID sets one status on a known set of sessions, in chunks that stay well inside SQLite's variable limit. EndSupersededSiblings retires the other sessions running under `pid`, leaving `keep` alone. It exists for /clear, which starts a fresh session id inside a process that is already running one.

The staleness sweep cannot do this. It judges a session by whether its process is alive (ADR-028), and after a /clear the old session's process is not merely alive — it is the very process now serving the new session. So the old row stayed `active` forever, and the dashboard showed one Claude Code as two live sessions, one of them frozen at the moment it was cleared, its six-day cost and 95%-full context still presented as current.

A process runs exactly one Claude Code conversation at a time, so a sibling on the same pid is finished by definition. pid 0 means "unknown" and is never matched: it would sweep together every session whose pid was never recorded. PreviousOnPID is the session that most recently started in the same process before id — the one a /clear replaced. Empty when there is none.

func ProcessAlive added in v0.45.0

func ProcessAlive(pid int) bool

ProcessAlive reports whether a process is still running.

This is what replaced a timer. Caprock used to decide a session was over because it had been quiet for a while, and every number chosen for "a while" was wrong for somebody: twelve hours left the day's sessions live at midnight, and one hour closed a session while its owner was at lunch. A session is over when its process is gone, which is a fact rather than a guess, and the only reason the staleness sweep still exists at all is sessions whose pid was never learned.

On unix, signal 0 is the "does this pid exist and may I signal it" test: it performs the permission and existence checks and delivers nothing. A pid belonging to another user answers EPERM, which is still proof the process is there — Caprock is single-user, but a session left by `sudo` should not be declared dead because of a permission error.

The known unsoundness is pid reuse: a dead process's number can be handed to a new one, and this would call that session alive. Detecting it means comparing process start times, which is three platforms of code for a case that requires a wrap of the pid space between two sweeps. The failure it would prevent is a stale row in a list; the failure of not doing this at all was a session vanishing while somebody worked in it.

A reboot is the exception, because it resets the pid space and makes reuse the common case rather than a wrap: MarkEndedSessions checks BootTime first.

func ProjectActivityByDir added in v0.75.0

func ProjectActivityByDir(ctx context.Context, q Querier, sinceMs int64) (map[string]*ProjectActivity, error)

ProjectActivityByDir aggregates sessions and today's spend by directory key (the repository root, else the cwd), the same key RecentDirs groups by. The caller attributes each key to the project that contains it.

Live is a session not ended; waiting is a live one whose newest event is a permission prompt, or a main-thread Stop with no subagent still working (LiveSubagents) — what narrate calls waiting-on-you. Spend is events at or after sinceMs, internal ones left out as every total leaves them out.

func ProjectFromCwd

func ProjectFromCwd(cwd string) string

ProjectFromCwd derives the project label for a working directory: the repository it belongs to, not the basename of the directory.

This is the ingest-time label written to sessions.project, so a session in caprock/ui is `caprock`. Kept as the same name and signature the callers already use.

func ProjectRepos added in v0.111.0

func ProjectRepos(ctx context.Context, q Querier) (map[int64][]string, error)

ProjectRepos lists the member repositories of every multi-repo project (migration 0050, ADR-055), keyed by project id, each list sorted by path.

func ProjectWorthListing added in v0.75.0

func ProjectWorthListing(root string) bool

ProjectWorthListing reports whether a repository root found from sessions should be on the projects list without anyone adding it: still on disk with a `.git` directory of its own (not a linked worktree, not a Caprock agent worktree), and not a place nobody works in (NotAProject) or a temp directory's scratch repository.

func PromptTexts added in v0.110.0

func PromptTexts(ctx context.Context, q Querier, ids []int64, limit int) (map[int64]string, error)

PromptTexts returns the prompt of each turn.user event by id, as typed (payload.prompt, else payload.text), clipped to limit runes.

func ProseSince added in v0.52.0

func ProseSince(ctx context.Context, q Querier) (int64, error)

ProseSince is when the oldest passage Caprock still holds was written.

Distinct from HandoffCoverage's date, which is bounded by how far back a handoff will reach (a fortnight). The search screen spans everything, and showing the shorter date there would understate the corpus by a month.

func PruneEventsBefore

func PruneEventsBefore(ctx context.Context, q Querier, beforeMs int64) (int64, error)

PruneEventsBefore deletes events older than beforeMs, keeping session rows and their rollups (session_stats/daily_stats stay — the totals are already materialized). Returns the number of events removed. This is the data-growth safety valve; it never touches sessions the user might still be looking at (callers pass a cutoff well in the past).

func PrunePendingPermissions added in v0.73.0

func PrunePendingPermissions(ctx context.Context, q Querier, keep map[string]bool) error

PrunePendingPermissions deletes every stored prompt whose session is not in keep: a session that ended while no daemon was running is waiting on nothing.

func QueuedSessions added in v0.104.0

func QueuedSessions(ctx context.Context, q Querier) ([]string, error)

QueuedSessions returns every session that has a message waiting.

func RateLimitPace added in v0.4.0

func RateLimitPace(ctx context.Context, q Querier, window string, resetsAt int64) (pctPerHour float64, ok bool, err error)

RateLimitPace returns the observed usage slope (percentage points per hour) for a window's CURRENT reset cycle. ok is false unless there are ≥2 same-window (same resets_at) history samples spanning ≥60s with a strictly rising usage — the honesty gate for the "at current pace" forecast. It never extrapolates across a reset boundary and never reports a flat/declining slope.

func RecentOwnedSessions added in v0.110.0

func RecentOwnedSessions(ctx context.Context, q Querier, since time.Time) ([]string, error)

RecentOwnedSessions returns the sessions Caprock started that recorded anything at or after since.

func RecordPR added in v0.70.0

func RecordPR(ctx context.Context, q Querier, a PRAction) error

RecordPR folds one `gh pr` command into session_prs. Only created, merged and closed are recorded; an edit or a comment is not a PR the session opened. An action that came without a URL is matched by number within the session, and dropped when the session has no such PR. Idempotent: replaying the same action leaves the row as it was.

func RecordRateLimit added in v0.4.0

func RecordRateLimit(ctx context.Context, q Querier, s RateLimitSnapshot, sessionID string) error

RecordRateLimit upserts the latest state for a window and, throttled, appends a history row for the "at current pace" slope. The latest row is always current; history rows are sampled (≥30s apart) to avoid write amplification.

func RecordThrottle

func RecordThrottle(ctx context.Context, q Querier, ts int64, sessionID, kind string, payload []byte) error

RecordThrottle appends a throttle observation (Phase 1: capture now, model later).

func RecordVerification

func RecordVerification(ctx context.Context, q Querier, taskID string, round int, command string, exitCode int, outputPath string) error

RecordVerification stores one verification-command result.

func RelayLinks(ctx context.Context, q Querier, sess Session) (*RelayLink, []RelayLink, error)

RelayLinks returns the session this one was relayed from (nil when none or unknown) and the sessions relayed from it, oldest first.

func ReleaseOwned added in v0.70.1

func ReleaseOwned(ctx context.Context, q Querier, id string) error

ReleaseOwned records that a session is no longer Caprock's: its process was stopped so the user could carry it on in their own terminal. Without this, the resumed session would read as one Caprock started and then lost the terminal of.

func RemoveSession added in v0.73.0

func RemoveSession(ctx context.Context, q Querier, c RemovalCandidate, loc *time.Location, nowMs int64) (float64, error)

RemoveSession deletes a session, its events and everything built from them, and records it in removed_sessions so the recorder never stores it again (ADR-037). Run it inside one transaction.

daily_stats is shared with every other session of the same day, project and model, so the session's turns are taken back out of it rather than the rows deleted — the inverse of what rollup.Record added, as codex.removeRows does. It returns the cost it could not find a row to take out of, which is zero unless a turn's day row was rebuilt under another project name since.

func ReplacePendingPermissions added in v0.78.2

func ReplacePendingPermissions(ctx context.Context, q Querier, sessionID string, ps []PendingPermission) error

ReplacePendingPermissions makes the stored queue of a session exactly ps, in that order.

func ReplaceRateLimits added in v0.63.0

func ReplaceRateLimits(ctx context.Context, q Querier, prefix string, sessionID string, snaps []RateLimitSnapshot) (bool, error)

ReplaceRateLimits swaps every window under prefix for those in one newer sample, and reports whether it did.

Replaced as a set rather than upserted per window, because a sample that omits a window is a statement about the plan: on the owner's machine a Codex account moved from `plus` (5-hour and weekly windows) to `prolite` (weekly only), and an upsert would have kept showing the five-hour figure from the old plan forever. A sample no newer than the stored one is ignored — transcripts are imported newest-modified first and out of order, and the latest observation is the only one shown.

Unlike RecordRateLimit this writes no history: the Codex rows are shown as last observed, with no forecast built on them. Run it in a transaction.

func RepoPathFromCwd added in v0.12.2

func RepoPathFromCwd(cwd string) string

RepoPathFromCwd returns the path within the repository for a cwd — the second level of the grouping, stored so the breakdown needs no filesystem access on read.

func ResetForcedContinue

func ResetForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) error

ResetForcedContinue clears the counter (task moved on).

func ResolveRepoRoot added in v0.75.0

func ResolveRepoRoot(dir string) string

ResolveRepoRoot is the repository root dir belongs to, read from disk now rather than from RepoFromCwd's memo (which keeps a folder's answer for the daemon's life, so a `git init` after the first look would be missed), or "" when dir is in no repository.

func RunningAt added in v0.60.0

func RunningAt(ctx context.Context, q Querier, stoppedAt int64, limit int) ([]string, error)

RunningAt lists the sessions that look as if they were running at stoppedAt, when the daemon last stopped: not ended yet, or ended by that very stop — a close recorded within a couple of minutes of it. Only sessions somebody worked in on the day of the stop count, and only agents whose process Caprock watches, so imported history and long-abandoned rows stay out. Newest work first, at most limit.

func SavePendingPermission added in v0.73.0

func SavePendingPermission(ctx context.Context, q Querier, p PendingPermission) error

SavePendingPermission records one more prompt a session waits on, behind the ones already stored: Claude Code queues its dialogs and shows the oldest. Saving a prompt id again updates its row in place.

func SeedProject added in v0.75.0

func SeedProject(ctx context.Context, q Querier, p Project) (bool, error)

SeedProject adds a project found from sessions, unless its root is already a row — listed or unlisted, so an unlisted project stays off the list. Reports whether a row was added.

func SessionFiles

func SessionFiles(ctx context.Context, q Querier, sessionID string, limit int) ([]string, error)

SessionFiles lists paths a session touched, most recent first.

func SessionForNative added in v0.70.0

func SessionForNative(ctx context.Context, q Querier, agent, nativeID string) (string, error)

SessionForNative returns the Caprock session linked to an agent's own id, or "" when none is.

func SetAttemptTotal added in v0.102.0

func SetAttemptTotal(ctx context.Context, q Querier, group string, total int) error

SetAttemptTotal says how many of a group started, when fewer did than asked.

func SetExit

func SetExit(ctx context.Context, q Querier, id string, code int) error

SetExit records an owned session's exit code and marks it ended.

func SetHandoff added in v0.61.0

func SetHandoff(ctx context.Context, q Querier, id string, state int) error

SetHandoff records what a new session was given when it opened.

func SetNativeID added in v0.70.0

func SetNativeID(ctx context.Context, q Querier, id, nativeID string) (bool, error)

SetNativeID links a session Caprock started to the agent's own id for it (migration 0032). Written once: a link already made is never moved to a different thread, because the events stored under it came from the first. Reports whether the link was made.

func SetOffset

func SetOffset(ctx context.Context, q Querier, path, sessionID string, off int64) error

func SetParent added in v0.60.0

func SetParent(ctx context.Context, q Querier, id, parent string) error

SetParent records the session id continues. It never replaces one already known.

func SetProjectGit added in v0.75.0

func SetProjectGit(ctx context.Context, q Querier, id int64, remoteURL, defaultBranch string) error

SetProjectGit records what git says a project's remote and default branch are, when they changed.

func SetProjectRepos added in v0.111.0

func SetProjectRepos(ctx context.Context, q Querier, id int64, paths []string, at int64) ([]string, error)

SetProjectRepos replaces project id's member repositories with paths (CleanRepoPaths). A repository is a member of one project at a time: a path another project held moves here. An empty list makes the project an ordinary one again. Nothing on disk is touched. Run it inside a transaction (Store.WithTx) so a move is never half done.

func SetPrompt added in v0.59.0

func SetPrompt(ctx context.Context, q Querier, id, prompt string) error

SetPrompt records the first thing the user typed, for an agent whose prompts are not events. Same rules as SetTitle: empty is a no-op, a missing session is not created.

func SetRelayFrom added in v0.70.0

func SetRelayFrom(ctx context.Context, q Querier, id, from string) error

SetRelayFrom records that a session was started to carry on another's work (migration 0036).

func SetSessionStatus

func SetSessionStatus(ctx context.Context, q Querier, id, status string) error

SetSessionStatus forces a status (idle/ended/active).

func SetTitle added in v0.59.0

func SetTitle(ctx context.Context, q Querier, id, title string) error

SetTitle records the agent's own name for a session. An empty title is a no-op, so a line that names nothing cannot erase a name already known; a session that does not exist yet is left alone rather than created.

func SpendByBranch added in v0.111.0

func SpendByBranch(ctx context.Context, q Querier, repoRoot string) (map[string]BranchSpend, error)

SpendByBranch sums the sessions of repository repoRoot (sessions.repo_root, as ingest resolved it) per branch, read through idx_sessions_repo_branch (migration 0051). A session with no branch recorded is left out.

func SpendSince added in v0.39.0

func SpendSince(ctx context.Context, q Querier, fromMs int64) (float64, error)

SpendSince is the total priced cost of events at or after fromMs.

The daily spend cap's only question, asked after every priced turn, so it is one indexed sum and nothing else. Unpriced turns contribute nothing: a model missing from the pricing table leaves cost_usd NULL, and COALESCE flattens it — the cap therefore under-counts rather than inventing a figure, which is the safe direction for something that stops work.

func TimedCalls added in v0.70.0

func TimedCalls(calls []TaxCall) []contexttax.TimedCall

TimedCalls converts calls for contexttax.PriceSeries.

func TouchDir added in v0.14.0

func TouchDir(payload []byte) string

TouchDir extracts the directory a tool call touched from its stored payload.

It returns "" when the tool named no path, which is the common case: on the owner's 65915 tool.pre rows, only Read, Edit, Write and Artifact carry a path at all. That is deliberate — see TouchRule.

func TouchFile

func TouchFile(ctx context.Context, q Querier, sessionID, path string, ts int64) (bool, error)

TouchFile records that a session touched a path. Returns true when the path is new for the session.

func TurnPaidElsewhere added in v0.68.0

func TurnPaidElsewhere(ctx context.Context, q Querier, msgID, sessionID string) (bool, error)

TurnPaidElsewhere reports whether a session other than sessionID already holds an assistant turn for msgID that carries usage.

A message id names one API response, and one response is billed once. Claude Code nevertheless writes the same response into more than one transcript: a fork (`--resume <id> --fork-session`) copies the parent's history since its last compaction into the new session's file, ids and usage included. The store dedupes on (session_id, key), which cannot see that, so the copy was priced a second time.

Only a row with usage counts as the payer. Claude Code zeroes the usage scalars of the first messages it preserves across a compaction, so a copy can arrive with nothing on it — and if that copy happened to be stored first, the original must still be priced when it arrives.

func UnderTempDir added in v0.75.0

func UnderTempDir(dir string) bool

UnderTempDir reports whether dir is inside a temp directory: the scratch repositories tests and agents make there are not projects.

func UpdateProject added in v0.75.0

func UpdateProject(ctx context.Context, q Querier, id int64, patch ProjectPatch) error

UpdateProject applies patch to project id.

func UpdateQueued added in v0.104.0

func UpdateQueued(ctx context.Context, q Querier, sessionID string, id int64, text string, now time.Time) error

UpdateQueued replaces a waiting message's text, keeping its place.

func UpsertSession

func UpsertSession(ctx context.Context, q Querier, id string, p SessionPatch) error

UpsertSession creates or updates a session from a patch.

func UpsertTask

func UpsertTask(ctx context.Context, q Querier, t TaskRow) error

UpsertTask mirrors a hive task into SQLite.

Types

type AgentFilter added in v0.22.0

type AgentFilter string

AgentFilter restricts a summary to one coding agent. Empty means every agent, which is what every caller wanted before OpenCode existed.

The predicate is a subquery on sessions rather than a join, for two reasons: events carries no agent of its own (it belongs to the session), and a join would change the row multiplicity of five separate aggregate queries — a silent way to double a cost. A subquery leaves each query's shape alone.

type AssistantNote added in v0.9.0

type AssistantNote struct {
	EventID   int64  `json:"event_id"`
	SessionID string `json:"session_id"`
	Project   string `json:"project"`
	Ts        int64  `json:"ts"`
	Model     string `json:"model"`
	Text      string `json:"text"`
	// Fragment marks a note that reads as mid-thought rather than a conclusion
	// ("Let me check that"), so a caller can avoid presenting it as a summary.
	Fragment bool `json:"fragment"`
}

AssistantNote is one thing Claude actually said, in prose — the reasoning and the closing "here is what changed, here is what I still need from you" that people otherwise copy into a notepad or lose to terminal scrollback.

func SearchNotes added in v0.9.0

func SearchNotes(ctx context.Context, q Querier, query string, limit int, before int64) ([]AssistantNote, error)

SearchNotes finds prose across every session — the question people actually ask is "which session was it where Claude explained the SSO thing?", not "show me session 17". An empty query returns the most recent notes. SearchNotes returns Claude's prose, newest first. `before` pages backwards: pass the lowest event_id already shown to get the next page, or 0 to start.

Paging is not an optimisation here, it is the feature working at all. The screen used to load a fixed 500 and stop, which on a busy machine is half a day — one reporter saw an entry from 22 hours ago followed immediately by one from 30 days ago, and reasonably read it as data loss. Nothing was lost; the middle was never fetched.

func SessionNotes added in v0.9.0

func SessionNotes(ctx context.Context, q Querier, sessionID string, limit int) ([]AssistantNote, error)

SessionNotes returns what Claude said in a session, newest first. Sidechains are excluded; the caller gets main-thread prose only.

func WhereWeLeftOff added in v0.51.0

func WhereWeLeftOff(ctx context.Context, q Querier, project string, before int64, minLen int) (AssistantNote, error)

WhereWeLeftOff is the last substantial thing an agent said in a repository, for handing back to the next session that opens there.

The question a person asks on returning is not "find something similar" — it is "what were we doing". Measured on the owner's database: searching prior prose by the terms of the opening prompt found something useful in 4 of 15 resumed sessions, and missed the clearest case of all ("remind me what we were looking into last time", 384 candidate passages, nothing matched) because an opening question shares no words with its own answer. Taking the last substantial passage instead answers 12 of 19. Recency beats retrieval here.

`before` excludes the session now starting, so a session cannot be handed its own output; `minLen` skips one-liners like "Done." that say nothing about where the work stood.

The project is tested on the covering index, before any payload is read. As a join on sessions, every assistant turn in the database had its payload fetched and parsed before the project was checked, so a project with no passage long enough — every session from "/" — walked all of history: 4-6 s on the owner's 1.2 GB database (2026-10-05), longer than the SessionStart hook waits, and the lookup died cancelled every time. The session ids are on idx_events_cost_cover, so rows of other projects are skipped without touching their payloads: under 0.1 s for any project, same answers.

type Attempt added in v0.102.0

type Attempt struct {
	SessionID string `json:"session_id"`
	GroupID   string `json:"group_id"`
	N         int    `json:"n"`
	Total     int    `json:"total"`
	// Base is the branch the copies started from; BaseCommit the commit it
	// pointed at, which each attempt's changes are measured from.
	Base       string `json:"base,omitempty"`
	BaseCommit string `json:"base_commit,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

Attempt is one of several sessions started on the same first message, each in a new copy of the same branch (migration 0046, ADR-052).

func AttemptGroup added in v0.102.0

func AttemptGroup(ctx context.Context, q Querier, group string) ([]Attempt, error)

AttemptGroup returns a group's attempts in order; empty for an unknown one.

type BackgroundUsage added in v0.57.0

type BackgroundUsage struct {
	Turns  int64    `json:"turns"`
	Tokens int64    `json:"tokens"`
	Models []string `json:"models"`
}

BackgroundUsage is known internal work observed in real transcripts. The raw events remain available, but these calls are not sessions or turns the user started and therefore do not belong in user-work totals.

type BranchSpend added in v0.111.0

type BranchSpend struct {
	Branch   string   `json:"branch"`
	Sessions int      `json:"sessions"`
	Agents   []string `json:"agents"`
	CostUSD  float64  `json:"cost_usd"`
	LastAt   int64    `json:"last_at"`
}

BranchSpend is what Caprock's sessions on one branch of a repository cost: the sessions recorded on it (sessions.git_branch, the branch the session was on when Caprock saw it), the agents among them, the sum of their session_stats.cost_usd and the newest event of any of them.

type CallTool added in v0.95.0

type CallTool struct {
	Tool  string
	Input json.RawMessage
}

CallTool is one tool request of a model call, with its raw input.

type DailyStat

type DailyStat struct {
	Day         string  `json:"day"`
	Project     string  `json:"project"`
	Model       string  `json:"model"`
	TokensTotal int64   `json:"tokens_total"`
	CostUSD     float64 `json:"cost_usd"`
	Sessions    int64   `json:"sessions"`
}

DailyStat mirrors daily_stats.

func Daily

func Daily(ctx context.Context, q Querier, from string) ([]DailyStat, error)

Daily returns daily_stats for the last `days` days (day >= from), oldest first.

type DrillHint added in v0.70.0

type DrillHint struct {
	Kind   string  `json:"kind"` // failures, output, repeats
	Key    string  `json:"key"`
	Text   string  `json:"text"`
	Weight float64 `json:"-"`
}

DrillHint is one fact and the row it is about. Weight orders hints: the share of the tool's calls, output or failures the fact accounts for.

type DrillOptions added in v0.70.0

type DrillOptions struct {
	Tool   string
	FromMs int64
	ToMs   int64 // the trend's end; 0 means now as the caller sees it
	Agent  AgentFilter
	Home   string
	Rows   int
	Trend  int
}

DrillOptions bounds a drill.

type DrillRow added in v0.70.0

type DrillRow struct {
	Key      string  `json:"key"`
	Calls    int64   `json:"calls"`
	Results  int64   `json:"results,omitempty"`
	Failures int64   `json:"failures,omitempty"`
	Bytes    int64   `json:"bytes,omitempty"`
	Trend    []int64 `json:"trend,omitempty"`
}

DrillRow is one group of calls.

type EventFilter added in v0.92.0

type EventFilter struct {
	// MainOnly keeps the main thread's events: no subagent's (agent_id set)
	// and no transcript sidechain line. A parent running subagents in parallel
	// logs hundreds of their events an hour, and a window of its newest few
	// hundred events held none of the parent's own calls.
	MainOnly bool
	// Kinds keeps only these kinds; empty keeps every kind.
	Kinds []string
}

EventFilter narrows a page of a session's events.

type HandoffGroup added in v0.61.0

type HandoffGroup struct {
	Sessions   int     `json:"sessions"`
	Reached    int     `json:"reached"`
	MedianMin  float64 `json:"median_min"`
	MedianCall float64 `json:"median_calls"`
}

HandoffGroup is how one arm of the handoff comparison got on: of the sessions in it, how many reached a first edit, and how long and how many tool calls that took.

func HandoffEffect added in v0.61.0

func HandoffEffect(ctx context.Context, q Querier) (served, withheld HandoffGroup, err error)

HandoffEffect compares sessions that were handed the last session's note with sessions that could have been and were not. The measure is the first edit: how long, and how many tool calls, a session spends finding its footing before it changes anything. A handoff that works should shorten it.

type HistoryTotals

type HistoryTotals struct {
	Sessions      int64   `json:"sessions"`
	OwnedSessions int64   `json:"owned_sessions"`
	Turns         int64   `json:"turns"`
	ToolCalls     int64   `json:"tool_calls"`
	FilesTouched  int64   `json:"files_touched"`
	CostUSD       float64 `json:"cost_usd"`
	AvgSessionSec float64 `json:"avg_session_sec"`
	Days          int64   `json:"days"`
	// Unpriced is the volume in range with no pricing row, so CostUSD excludes
	// it. Omitted when everything was priced. History's headline claims the
	// numbers are "measured, not estimated", which a silently incomplete total
	// would make false.
	Unpriced *Unpriced `json:"unpriced,omitempty"`
	// Background is known internal model usage, reported separately rather than
	// counted as sessions or turns the user started.
	Background *BackgroundUsage `json:"background,omitempty"`
}

HistoryTotals is the all-time (or ranged) cross-session summary for the History screen.

func History

func History(ctx context.Context, q Querier, fromMs int64) (HistoryTotals, error)

History computes cross-session totals since fromMs.

type LivePID added in v0.101.0

type LivePID struct {
	SessionID string
	PID       int
}

LivePID is a session that has not ended and the process it runs in.

func LivePIDs added in v0.101.0

func LivePIDs(ctx context.Context, q Querier) ([]LivePID, error)

LivePIDs lists the sessions not ended that have a process id: the ones the resource meter can measure. Sessions without one (an older shim's rows, a transcript with no process behind it) are left out.

type ModelShare

type ModelShare struct {
	Model   string  `json:"model"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Turns   int64   `json:"turns"`
	// Output is what the model generated, which is the part of a token total
	// that is entirely this model's work and entirely at the top rate. The
	// combined figure is ~99% cache read on this workload — a number that is
	// real, is nearly free, and swamps everything it is added to.
	Output int64 `json:"output"`
	// CacheRead is the context this model re-read: the conversation being
	// re-sent on every turn. It is the base of the context tax, kept per model
	// because cache-read rates differ by more than the table's usual 0.1x --
	// Fable 5.1 and Mythos 5.1 read at 0.025x, so one blended rate would be
	// wrong for any mixed workload.
	CacheRead int64 `json:"cache_read"`
}

ModelShare is tokens/cost per model.

type ModelTokens added in v0.70.0

type ModelTokens struct {
	Model        string
	In, Out      int64
	CacheRead    int64
	CacheWrite   int64
	CacheWrite1h int64
}

ModelTokens is one model's tokens by type, which the pricing table turns into what each type of token cost.

func TokensByModel added in v0.70.0

func TokensByModel(ctx context.Context, q Querier, from int64) ([]ModelTokens, error)

TokensByModel sums each model's tokens by type since from.

type PRAction added in v0.70.0

type PRAction struct {
	SessionID string
	URL       string // empty for an action recorded without one ("closed")
	Number    int
	Title     string
	Action    string // created | merged | closed | edited | commented
	Ts        int64
}

PRAction is one recorded `gh pr` command: what it did to which PR, and when.

type PathShare added in v0.12.2

type PathShare struct {
	Path    string  `json:"path"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Turns   int64   `json:"turns"`
	// Unattributed and Outside mark the two rows that are buckets rather than
	// directories, so the UI does not have to know the sentinels' spelling.
	// Unattributed is the turns that ran before their session touched any file;
	// Outside is the turns whose most recent touch was not in this repository.
	// Both are rendered as their own thing and never as a path.
	Unattributed bool `json:"unattributed,omitempty"`
	Outside      bool `json:"outside,omitempty"`
	// TokensPct and CostPct are this row's share of the REPOSITORY's total,
	// including the unattributed bucket — so each column sums to 100% and the
	// unattributed share is visible as its own number instead of being hidden
	// in a denominator.
	//
	// Both are sent because they genuinely differ: cost per token varies by
	// model, so a directory worked on by a cheap model is a larger share of the
	// tokens than of the money. Sending one would leave the reader to assume it
	// described both.
	//
	// They are computed here rather than in the panel because the denominator
	// is the repository total, which the panel only has after summing rows it
	// may be truncating. Values are floored to one decimal on the client
	// (fmtPct), never rounded up.
	TokensPct float64 `json:"tokens_pct"`
	CostPct   float64 `json:"cost_pct"`
}

PathShare is tokens/cost for one directory inside a repository, charged by what the repository's TURNS touched rather than by where a session was launched (see touch.go).

Path is the directory relative to the repository root, written from it so it reads as a path — "/", "/services/api". Two values are NOT paths: UnattributedPath (turns that ran before their session touched any file) and OutsidePath (turns whose most recent touch was outside the repository). Callers must render both as their own thing and never as a directory — see Unattributed and Outside.

Turns replaces the old Sessions count. A session touches many directories, so it cannot be counted once per directory row without the column summing to more than the repository's own session count; a TURN is charged to exactly one row by construction, so turns partition and add up.

type PendingPermission added in v0.73.0

type PendingPermission struct {
	SessionID string
	PromptID  string
	Tool      string
	Detail    string
	Always    string
	SinceMs   int64
	Input     string
	ToolUseID string
	AgentID   string
	AgentType string
}

PendingPermission is the stored half of one permission prompt an owned session is waiting on (migrations 0039, 0042, 0043). The agents package owns its meaning; the store only keeps it across a daemon restart.

func ListPendingPermissions added in v0.78.2

func ListPendingPermissions(ctx context.Context, q Querier, sessionID string) ([]PendingPermission, error)

ListPendingPermissions returns the prompts a session waits on, oldest first.

type Project added in v0.75.0

type Project struct {
	ID            int64  `json:"id"`
	Root          string `json:"root"`
	Name          string `json:"name"`
	Kind          string `json:"kind"`   // repo | folder
	Source        string `json:"source"` // seed | session | folder | new | clone
	RemoteURL     string `json:"remote_url,omitempty"`
	DefaultBranch string `json:"default_branch,omitempty"`
	AddedAt       int64  `json:"added_at"`
	Pinned        bool   `json:"pinned"`
	Sort          int64  `json:"sort"`
	Defaults      string `json:"-"` // raw JSON; the API decodes it
	ArchivedAt    int64  `json:"archived_at,omitempty"`
}

Project is one row of the projects list (migration 0041).

func GetProject added in v0.75.0

func GetProject(ctx context.Context, q Querier, id int64) (Project, error)

GetProject returns one project by id, archived or not.

func GetProjectByRoot added in v0.75.0

func GetProjectByRoot(ctx context.Context, q Querier, root string) (Project, error)

GetProjectByRoot returns the project whose root is root, archived or not.

func InsertProject added in v0.75.0

func InsertProject(ctx context.Context, q Querier, p Project) (Project, bool, error)

InsertProject adds p, or — when its root is already a row — lists that row again (an add of an unlisted project brings it back) and returns it. The existing row's name and settings are kept.

func ListProjects added in v0.75.0

func ListProjects(ctx context.Context, q Querier, withArchived bool) ([]Project, error)

ListProjects returns the listed projects (archived ones too when withArchived), pinned first, then by sort, then by name.

type ProjectActivity added in v0.75.0

type ProjectActivity struct {
	Dir          string
	Total        int64
	Live         int64
	Waiting      int64
	LastActivity int64
	CostToday    float64
}

ProjectActivity is what sessions say about one directory key — a repository root, or the cwd of a session outside any repository.

type ProjectPatch added in v0.75.0

type ProjectPatch struct {
	Name     *string
	Pinned   *bool
	Sort     *int64
	Defaults *string
}

ProjectPatch is what PATCH /v1/projects/{id} may change; nil leaves a field.

type ProjectShare

type ProjectShare struct {
	Project string `json:"project"`
	// Agent is set when every session in this row came from one agent, so the
	// dashboard can say which. Empty when a repository was worked on with
	// both — labelling it either way would be wrong, and the per-session
	// labels below still answer it.
	Agent    string  `json:"agent,omitempty"`
	Tokens   int64   `json:"tokens"`
	CostUSD  float64 `json:"cost_usd"`
	Sessions int64   `json:"sessions"`
	// Dir is the directory the row is keyed on — the repository root, or the
	// session's own directory when it is outside any repository. It is what
	// GET /v1/sessions?dir= takes to list this row's sessions, so the
	// dashboard can open a terminal in the project. Empty for the row of
	// spend whose session was deleted, which has no directory to open.
	Dir   string      `json:"dir,omitempty"`
	Paths []PathShare `json:"paths,omitempty"`
	Spark *Spark      `json:"spark,omitempty"`
	// RepoURL is the repository's web address, from its git remote; set by
	// the API, empty when there is no remote it can link to.
	RepoURL string `json:"repo_url,omitempty"`
	// LastPR is the latest pull request a session in this row opened or
	// merged; set by the API.
	LastPR *SessionPR `json:"last_pr,omitempty"`
}

ProjectShare is tokens/cost per REPOSITORY. Sessions is how many distinct sessions touched it in the range — the "who is working in this repo" half of the question; cost alone does not answer it.

Paths is the breakdown one level down: what each top-level directory inside the repository cost. On a monorepo that is the difference between "caprock cost $1,662" and "ui was $400 of it", which is the question a budget actually asks. It is present only when the repository has more than one such directory — a single-directory repo would just repeat its own total. Spark is the per-bucket series behind the row's sparkline, present only when the caller asked for one. It is deliberately NOT repeated on PathShare: a sparkline per directory would multiply the payload of a polled endpoint for a picture nobody sees until they expand the row.

type Querier

type Querier interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Querier is satisfied by *sql.DB and *sql.Tx.

type QueuedMessage added in v0.104.0

type QueuedMessage struct {
	ID        int64  `json:"id"`
	SessionID string `json:"session_id"`
	Text      string `json:"text"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

QueuedMessage is one message waiting for a session's turn to end (migration 0047, ADR-053).

func AddQueued added in v0.104.0

func AddQueued(ctx context.Context, q Querier, sessionID, text string, now time.Time) (QueuedMessage, error)

AddQueued puts text at the end of a session's queue.

func GetQueued added in v0.104.0

func GetQueued(ctx context.Context, q Querier, sessionID string, id int64) (QueuedMessage, error)

GetQueued returns one message of a session's queue; ErrQueuedNotFound when the session holds no such id.

func ListQueued added in v0.104.0

func ListQueued(ctx context.Context, q Querier, sessionID string) ([]QueuedMessage, error)

ListQueued returns a session's queue, oldest first: the order it is sent in.

type RateLimitSnapshot added in v0.4.0

type RateLimitSnapshot struct {
	Window         string  `json:"window"`
	Ts             int64   `json:"ts"` // unix ms received
	UsedPercentage float64 `json:"used_percentage"`
	ResetsAt       int64   `json:"resets_at"` // unix seconds
}

RateLimitSnapshot is one window's rate-limit state (from Claude Code's statusline `rate_limits`).

func LatestRateLimit added in v0.4.0

func LatestRateLimit(ctx context.Context, q Querier, window string) (RateLimitSnapshot, bool, error)

LatestRateLimit returns the current state for a window, or ok=false when none.

func RateLimitsWithPrefix added in v0.63.0

func RateLimitsWithPrefix(ctx context.Context, q Querier, prefix string) ([]RateLimitSnapshot, error)

RateLimitsWithPrefix returns every window stored under prefix, with the prefix stripped from Window.

type RecentDirDetail added in v0.38.0

type RecentDirDetail struct {
	Dir         string
	Sessions    int64
	LastEventAt int64
}

RecentDirDetail is a directory sessions have run in, for the folder picker.

func RecentDirs added in v0.38.0

func RecentDirs(ctx context.Context, q Querier, limit int) ([]RecentDirDetail, error)

RecentDirs lists the directories sessions have run in, most recently active first.

The repository someone wants to start in next is almost always one they were in yesterday, so this is the half of the folder picker that needs no browsing at all. Grouped by repository root where one is known and by working directory otherwise: two sessions started from different subdirectories of one repository are one entry, because they are one project to the person choosing.

"/", the home directory and a temp directory are left out (NotAProject): something on the machine running `claude` from "/" every few minutes would otherwise hold the top of the list for good.

func SessionRepoRoots added in v0.75.0

func SessionRepoRoots(ctx context.Context, q Querier) ([]RecentDirDetail, error)

SessionRepoRoots lists the repository roots sessions ran in, most recently active first — the candidates for seeding the projects list. The caller decides which are worth listing (ProjectWorthListing).

type RelayLink struct {
	SessionID string `json:"session_id"`
	Agent     string `json:"agent"`
	Title     string `json:"title,omitempty"`
	StartedAt int64  `json:"started_at"`
}

RelayLink is one end of a relay, as a session page names it.

type RemovalCandidate added in v0.73.0

type RemovalCandidate struct {
	SessionID   string  `json:"session_id"`
	Cwd         string  `json:"cwd"`
	Project     string  `json:"project"`
	Agent       string  `json:"agent"`
	Status      string  `json:"status"`
	Owned       bool    `json:"owned"`
	LastEventAt int64   `json:"last_event_at"`
	Turns       int64   `json:"turns"`
	CostUSD     float64 `json:"cost_usd"`
}

RemovalCandidate is a session as the remove commands list it: enough to tell a test run's leftovers from real work before anything is deleted.

func FindRemovalCandidates added in v0.73.0

func FindRemovalCandidates(ctx context.Context, q Querier, ids []string, cwdPrefix string) ([]RemovalCandidate, error)

FindRemovalCandidates lists the sessions named by ids, or every session whose working directory is cwdPrefix or lies under it. One of the two must be given: an empty filter matching everything is never what anyone meant.

type RepoInfo added in v0.12.2

type RepoInfo struct {
	// Root is the absolute repository root, or "" when the cwd is not inside a
	// repository.
	Root string
	// Repo is the display label for the repository row.
	Repo string
	// Path is the location within the repository, "" for the repository root
	// itself. Always slash-separated, whatever the host's separator.
	Path string
}

RepoInfo is the two-level project identity of a working directory.

func RepoFromCwd added in v0.12.2

func RepoFromCwd(cwd string) RepoInfo

RepoFromCwd resolves the repository a working directory belongs to.

It walks up from cwd looking for `.git`. A `.git` DIRECTORY is an ordinary clone. A `.git` FILE is a linked worktree — including the `.caprock-worktrees/ worker-N` trees Caprock creates for its own agents — and its `gitdir:` line points into `<parent>/.git/worktrees/<name>`, so the parent repository is recovered from it and the worker's spend lands on the repository it is actually working on, which is the whole point of a worktree.

A cwd with no repository above it (/tmp, a scratchpad) is labelled from the path itself, never given a fabricated repository name.

func (RepoInfo) Segment added in v0.12.2

func (r RepoInfo) Segment() string

Segment returns the row label for the breakdown inside a repository: the directory path under the root, written from the root so it reads as a path rather than a name — "/", "/ui", "/ui/src". Collapsing to the first segment was the first version and hid the distinction the breakdown exists to show: in a monorepo, "/services/api" and "/services/web" are the two rows anyone opening this actually wants.

type Run added in v0.74.0

type Run struct {
	// PromptAt is the last main-thread prompt at or before the end, unix ms;
	// 0 when the session has none, and then the run is the whole session.
	PromptAt  int64
	CostUSD   float64
	ToolCalls int
	// Files are the paths edited in the run, first edited first.
	Files []string
}

Run is what a session did since its owner's last prompt, up to a moment: what a "finished" phone alert reports (ADR-036).

func LastRun added in v0.74.0

func LastRun(ctx context.Context, q Querier, sessionID string, until int64) (Run, error)

LastRun reads the run of a session that ended at until (unix ms). Subagents' turns and tool calls are counted with the session's: they are work the run paid for.

type SavedPrompt added in v0.102.0

type SavedPrompt struct {
	ID   int64  `json:"id"`
	Kind string `json:"kind"` // prompt | command
	Name string `json:"name"`
	Text string `json:"text"`
	// ProjectID is the project it belongs to; 0 means every project.
	ProjectID int64 `json:"project_id,omitempty"`
	// ProjectRoot and ProjectName are the project's, joined in when listed,
	// so a client can scope it to a folder without a second request.
	ProjectRoot string `json:"project_root,omitempty"`
	ProjectName string `json:"project_name,omitempty"`
	Sort        int64  `json:"sort"`
	CreatedAt   int64  `json:"created_at"`
	UpdatedAt   int64  `json:"updated_at"`
}

SavedPrompt is one saved prompt or command (migration 0045, ADR-051).

func GetSavedPrompt added in v0.102.0

func GetSavedPrompt(ctx context.Context, q Querier, id int64) (SavedPrompt, error)

GetSavedPrompt returns one row; ErrSavedNotFound when unknown.

func InsertSavedPrompt added in v0.102.0

func InsertSavedPrompt(ctx context.Context, q Querier, v SavedPrompt, now int64) (SavedPrompt, error)

InsertSavedPrompt adds a row and returns it as listed.

func ListSavedPrompts added in v0.102.0

func ListSavedPrompts(ctx context.Context, q Querier) ([]SavedPrompt, error)

ListSavedPrompts returns every saved prompt and command: the ones for every project first, then by project, then by sort and name.

func UpdateSavedPrompt added in v0.102.0

func UpdateSavedPrompt(ctx context.Context, q Querier, v SavedPrompt, now int64) (SavedPrompt, error)

UpdateSavedPrompt replaces a row's kind, name, text, project and sort.

type Session

type Session struct {
	SessionID      string `json:"session_id"`
	Cwd            string `json:"cwd"`
	Project        string `json:"project"`
	Model          string `json:"model"`
	StartedAt      int64  `json:"started_at"`
	LastEventAt    int64  `json:"last_event_at"`
	Status         string `json:"status"` // active|idle|ended
	TranscriptPath string `json:"transcript_path"`
	HasHooks       bool   `json:"has_hooks"`
	HasTranscript  bool   `json:"has_transcript"`
	GitBranch      string `json:"git_branch"`
	Version        string `json:"version"`
	RepoRoot       string `json:"repo_root,omitempty"`
	RepoPath       string `json:"repo_path,omitempty"`
	Owned          bool   `json:"owned"`
	Worktree       string `json:"worktree,omitempty"`
	SpawnCommand   string `json:"spawn_command,omitempty"`
	PID            int    `json:"pid,omitempty"`
	ExitCode       *int   `json:"exit_code,omitempty"`
	// Agent is which coding agent produced this session. Every session was
	// Claude Code until OpenCode support, so "claude" is the default and the
	// UI treats an empty value as such.
	Agent string `json:"agent,omitempty"`
	// Title is the agent's own name for the session — Claude Code's ai-title,
	// OpenCode's title — or empty when it has not named one.
	Title string `json:"title,omitempty"`
	// Prompt is the first thing the user typed, stored only for agents whose
	// prompts are not events (Codex). The API folds it into the description.
	Prompt string `json:"-"`
	// WorkedAt is the last prompt, reply or tool call — not the exit, /clear or
	// shutdown that may have followed it (FB-037).
	WorkedAt int64 `json:"worked_at,omitempty"`
	// ParentSession is the session this one continues: the one a /clear
	// replaced, or the one it was forked from (FB-039).
	ParentSession string `json:"parent_session,omitempty"`
	// NativeID is the agent's own id for a Codex or OpenCode session Caprock
	// started under an id of its own (migration 0032); empty otherwise.
	NativeID string `json:"native_id,omitempty"`
	// RelayFrom is the session whose work this one was started to carry on,
	// with a brief rather than the conversation (migration 0036); empty
	// otherwise.
	RelayFrom string `json:"relay_from,omitempty"`
	// Subscription is the sign-in the session ran on (migration 0044,
	// ADR-048): a subscription id from Settings → Subscriptions, or empty for
	// the user's normal sign-in.
	Subscription string `json:"subscription,omitempty"`
	// AttemptGroup, Attempt and Attempts say the session is attempt Attempt
	// of Attempts started together on one first message (migration 0046,
	// ADR-052); empty and zero otherwise.
	AttemptGroup string `json:"attempt_group,omitempty"`
	Attempt      int    `json:"attempt,omitempty"`
	Attempts     int    `json:"attempts,omitempty"`
}

Session mirrors the sessions table.

func GetSession

func GetSession(ctx context.Context, q Querier, id string) (Session, error)

GetSession returns one session; sql.ErrNoRows when unknown.

func ListOwnedActive

func ListOwnedActive(ctx context.Context, q Querier) ([]Session, error)

ListOwnedActive returns owned sessions that are not ended (for restart bookkeeping).

func ListSessions

func ListSessions(ctx context.Context, q Querier, activeOnly bool, limit int) ([]Session, error)

ListSessions returns sessions newest-first. activeOnly filters out ended.

func ListSessionsInDir added in v0.66.0

func ListSessionsInDir(ctx context.Context, q Querier, dir string, limit int) ([]Session, error)

ListSessionsInDir returns the sessions of one project row, newest-first: those whose repository root is dir, and those outside any repository whose directory is dir. It is the same grouping the Projects panel uses (see Summary: rows are keyed by repo_root, else by cwd), so "the sessions of this row" means exactly the sessions that were summed into it. Exact match, not the session search: a search also reads prompts, and "acme-api" would match every session that ever mentioned it.

func ListSessionsMatching added in v0.59.0

func ListSessionsMatching(ctx context.Context, q Querier, activeOnly bool, search string, limit int) ([]Session, error)

ListSessionsMatching returns sessions newest-first, optionally only those matching a search — see sessionFilter for what a search looks at.

type SessionCall added in v0.95.0

type SessionCall struct {
	ID      int64
	Ts      int64
	Model   string
	CostUSD float64
	Tokens  *event.TokenDelta
	// Tools are the tool calls this model call asked for, joined by msg_id —
	// exact, the tool_use block and the usage billed for it share the
	// message id. Empty when it asked for none or its agent records no id.
	Tools []CallTool
	// ToolCount is how many it asked for, which Tools may hold fewer of.
	ToolCount int
}

SessionCall is one priced model call of a session's main thread: what the cockpit's spend scrubber reads bar by bar.

func SessionCalls added in v0.95.0

func SessionCalls(ctx context.Context, q Querier, sessionID string, n int) ([]SessionCall, error)

SessionCalls returns the newest n priced main-thread model calls of a session, oldest first, each with the tool calls it requested. Internal model calls and unpriced turns are left out, as the cockpit's spark leaves them out; a subagent's calls are its own. Both queries pin the session's index (`+kind`), as the subagent queries do.

type SessionPR added in v0.70.0

type SessionPR struct {
	SessionID string `json:"session_id"`
	URL       string `json:"url"`
	Number    int    `json:"number"`
	Title     string `json:"title,omitempty"`
	OpenedAt  int64  `json:"opened_at,omitempty"`
	// MergedAt is set only when a merge was recorded; a PR without it is not
	// known to be merged, which is not the same as known to be open.
	MergedAt int64 `json:"merged_at,omitempty"`
	ClosedAt int64 `json:"closed_at,omitempty"`
	LastAt   int64 `json:"last_at"`
}

SessionPR is a pull request a session opened or merged (migration 0035).

func SessionPRs added in v0.70.0

func SessionPRs(ctx context.Context, q Querier, sessionID string) ([]SessionPR, error)

SessionPRs lists a session's pull requests, the latest first.

type SessionPatch

type SessionPatch struct {
	Cwd, Project, Model, TranscriptPath, GitBranch, Version string
	// SubagentModel is the model of a subagent's turn inside this session. It
	// names the session only while nothing else has: a session run on Opus
	// whose Explore subagent ran on Haiku is an Opus session, and its card,
	// its list row and its context window all read this column. Model, the
	// main thread's, always wins over it.
	SubagentModel string
	// FromSubagent says Cwd, GitBranch and TranscriptPath were reported by a
	// subagent of this session. A subagent works where it was put — often a
	// git worktree of its own, on its own branch — so its place only fills a
	// session that has none yet and never overwrites the main thread's: the
	// owner's session in ~/dev/caprock on master read as a background agent's
	// `feat/…` worktree (2026-10-09).
	FromSubagent bool
	// Agent is the coding agent that produced the session ("claude",
	// "opencode"). Empty leaves the column at its default rather than
	// overwriting a value already stored.
	Agent                    string
	StartedAt, LastEventAt   int64
	FromHook, FromTranscript bool
	Status                   string // set only to force a status
	// PID is the process the session belongs to, reported by the shim. Zero
	// leaves whatever is stored alone: most events do not carry one, and an
	// event that does not know the pid must not erase one that did.
	PID int
	// Title is the agent's own name for the session. Empty leaves the stored
	// one alone.
	Title string
	// WorkedAt is set by work events only (a prompt, a reply, a tool call);
	// zero leaves the stored value. See migration 0027.
	WorkedAt int64
	// ParentSession names the session this one continues, when known; empty
	// leaves the stored one alone.
	ParentSession string
	// Subscription is the sign-in the session runs on (ADR-048). The first
	// non-empty value is kept: the spawn knows it before any event does, and
	// a session cannot move from one sign-in to another.
	Subscription string
}

SessionPatch carries the fields an event may reveal about its session. Empty strings mean "no information" and are never written over existing values.

type SliceSize added in v0.64.0

type SliceSize struct {
	Name         string `json:"name"`
	Events       int64  `json:"events"`
	PayloadBytes int64  `json:"payload_bytes"`
}

SliceSize is one group of events.

type Spark added in v0.13.0

type Spark struct {
	FromMs  int64     `json:"from_ms"`
	WidthMs int64     `json:"width_ms"`
	Cost    []float64 `json:"cost"`
	Tokens  []int64   `json:"tokens"`
}

Spark is a project's spend over time, as one value per fixed-width bucket — the series behind the sparkline on the Projects panel. It answers "when did this repo cost that" without shipping the events themselves.

Cost and tokens travel together, as two parallel arrays over the SAME buckets, because which of the two the panel plots stays a display choice on the client. Sending only one of them would make re-basing the picture a network round trip — on a polled endpoint, a control that stalls — and sending events so the client could bucket them itself would be orders of magnitude more payload for a picture 120px wide.

Bucket i covers [FromMs + i*WidthMs, FromMs + (i+1)*WidthMs). The last bucket is the one containing "now" and is therefore still filling; it is not extrapolated to a full bucket's worth (rule 6).

type SparkSpec added in v0.13.0

type SparkSpec struct {
	// Buckets is how many columns the panel will paint.
	Buckets int
	// WidthMs is one column's width. Callers derive it from the selected range
	// (a day for 30d/7d, an hour for today) so the picture and the number beside
	// it always describe the same period.
	WidthMs int64
	// FromMs is the first bucket's left edge. It is passed separately from
	// Summarize's own fromMs because a range is calendar-aligned: "30d" starts
	// at local midnight 29 days ago, and bucketing from an arbitrary instant
	// would smear each day across two columns.
	FromMs int64
}

SparkSpec asks Summarize for per-project time series. Buckets <= 0 disables them entirely, which is the default: /v1/stats/summary computes a second summary for the 10-minute burn figure, and that one has no sparkline to draw.

type Stats

type Stats struct {
	SessionID    string  `json:"session_id"`
	Turns        int64   `json:"turns"`
	ToolCalls    int64   `json:"tool_calls"`
	FilesTouched int64   `json:"files_touched"`
	TokensIn     int64   `json:"tokens_in"`
	TokensOut    int64   `json:"tokens_out"`
	CacheRead    int64   `json:"cache_read"`
	CacheWrite   int64   `json:"cache_write"`
	CostUSD      float64 `json:"cost_usd"`
}

Stats mirrors session_stats.

func AddStats

func AddStats(ctx context.Context, q Querier, d Stats) (Stats, error)

AddStats increments session_stats by the delta and returns the new totals.

func GetStats

func GetStats(ctx context.Context, q Querier, sessionID string) (Stats, error)

GetStats returns session_stats for a session (zeros when absent).

type Storage added in v0.64.0

type Storage struct {
	PageSize  int64 `json:"page_size"`
	PageCount int64 `json:"page_count"`
	// FreePages is the freelist: pages the file holds but no table uses. They
	// are reused by new rows before the file grows, and only VACUUM returns
	// them to the disk.
	FreePages int64 `json:"free_pages"`
	// Tables is every table with its own pages and its indexes' pages, largest
	// first. Absent when this SQLite build has no dbstat.
	Tables []TableSize `json:"tables,omitempty"`
	// Events and PayloadBytes count the events table: rows, and the bytes of
	// the raw JSON each row keeps.
	Events       int64 `json:"events"`
	PayloadBytes int64 `json:"payload_bytes"`
	// OldestTs is the oldest event's time, unix ms; 0 when there are none.
	OldestTs int64 `json:"oldest_ts"`
	// Agents and Kinds split the events by who produced them and what they
	// are, largest payload first.
	Agents []SliceSize `json:"agents"`
	Kinds  []SliceSize `json:"kinds"`
	// Recent is what the last 7 and 30 days added; Older is what is older than
	// 30 and 90 days — what a retention setting of that length would delete.
	Recent []WindowSize `json:"recent"`
	Older  []WindowSize `json:"older"`
}

Storage is what the database is made of: how many pages it has, how many of them are free, which tables and indexes hold the rest, and what the events table — nearly all of it — records.

Every figure is counted, not modelled. The one derived number, the growth estimate, is labelled as such by the caller.

Expensive by design: dbstat walks every page of the file and the events breakdown reads every row. On an 857 MB database the two took seconds, so the daemon computes this in the background and serves a cached copy; nothing on a request path may call it.

func MeasureStorage added in v0.64.0

func MeasureStorage(ctx context.Context, db *sql.DB, now time.Time) (Storage, error)

MeasureStorage reads the database's composition. See Storage for its cost.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store wraps the database handle.

func Open

func Open(ctx context.Context, path string, log *slog.Logger) (*Store, error)

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB exposes the raw handle for packages that need transactions (rollup).

func (*Store) GetMeta

func (s *Store) GetMeta(ctx context.Context, key string) (string, error)

GetMeta reads a meta value; "" when absent.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion returns the applied schema version (0 = empty database).

func (*Store) SetMeta

func (s *Store) SetMeta(ctx context.Context, key, value string) error

SetMeta upserts a meta value.

func (*Store) WithTx

func (s *Store) WithTx(ctx context.Context, fn func(q Querier) error) error

WithTx runs fn inside a transaction, committing on nil error.

type SubagentActivity added in v0.92.0

type SubagentActivity struct {
	AgentID string
	// AgentType is the hook's agent_type ("general-purpose", "Explore"); empty
	// when no hook named one.
	AgentType string
	// Description is what the parent asked it to do, from the Agent call
	// that launched it, when its result names the agent (a background launch
	// does at once; a foreground one only when it finishes).
	Description string
	// ToolCalls is how many tool calls it has made in all.
	ToolCalls int
	// StartedAt and LastAt are its first and newest events in the window, unix ms.
	StartedAt, LastAt int64
	// Tool, Input and ToolAt are its newest call; empty when it made none.
	Tool   string
	Input  json.RawMessage
	ToolAt int64
	// Running is true while that call has no result.
	Running bool
	// StoppedAt is its SubagentStop (unix ms), for one that finished.
	StoppedAt int64
	// Asking is true when its newest event is a permission prompt: a
	// subagent waiting on a dialog records nothing else.
	Asking bool
}

SubagentActivity is one subagent working in a session now: who it is and what it is doing, read from the hooks fired inside it (they carry its agent_id) — Claude Code sends no event when a subagent starts.

func SubagentsDone added in v0.94.0

func SubagentsDone(ctx context.Context, q Querier, sessionID string, since int64, limit int) ([]SubagentActivity, error)

SubagentsDone returns up to limit subagents of a session that stopped since `since` after making at least one tool call, newest stop first: the ones SubagentsNow counts as finished. StoppedAt is their SubagentStop.

func SubagentsNow added in v0.92.0

func SubagentsNow(ctx context.Context, q Querier, sessionID string, since int64) ([]SubagentActivity, int, error)

SubagentsNow returns the subagents working in a session — each agent id heard from since `since` whose newest event is not its SubagentStop, the rule LiveSubagents counts by — newest activity first, and how many stopped within the window after making at least one tool call. Claude Code also fires SubagentStop for small internal agents that run no tools; they are not counted.

type SubagentCall added in v0.110.0

type SubagentCall struct {
	// ID is the call's tool.pre event id: the cursor "show earlier" pages by.
	ID        int64
	ToolUseID string
	Tool      string
	Input     json.RawMessage
	StartedAt int64
	// EndedAt is its result's time; 0 while it has none.
	EndedAt int64
	// Error is true when the result came back as an error.
	Error bool
}

SubagentCall is one tool call a subagent made, joined to its result.

type SubagentSpend added in v0.94.0

type SubagentSpend struct {
	// Model is its newest turn's model; empty when it has none yet.
	Model string
	// CostUSD sums its turns' costs. Known is false when it has no turn, or
	// a turn the pricing table could not price: a partial sum would
	// understate it, and no figure is better than a wrong one (rule 6).
	CostUSD float64
	Known   bool
}

SubagentSpend is what a subagent's own model calls cost, from its transcript's turns (each carries its model and usage, and is priced like any other turn).

func SubagentsSpend added in v0.94.0

func SubagentsSpend(ctx context.Context, q Querier, sessionID string) (map[string]SubagentSpend, SubagentSpend, error)

SubagentsSpend returns each subagent's spend in a session, keyed by agent id, and the total over all of them, Known only when every one is. Internal model calls are left out, as every total leaves them out.

type SubagentToolSpend added in v0.110.0

type SubagentToolSpend struct {
	Tool    string
	Calls   int
	CostUSD float64
	Known   bool
}

SubagentToolSpend is what one kind of tool cost inside a subagent: the turns that called it, each turn's cost split evenly over the tools it called. Calls counts the calls; Known is false when any of those turns could not be priced.

type SubagentTrail added in v0.110.0

type SubagentTrail struct {
	AgentID   string
	AgentType string
	// Description, Prompt and SubagentType are the parent's Agent/Task call
	// input; ParentToolUseID that call's id. Empty when no call is linked.
	Description     string
	Prompt          string
	SubagentType    string
	ParentToolUseID string
	// Background is true when the parent launched it in the background.
	Background bool
	// StartedAt and LastAt are its first and newest events, StoppedAt its
	// newest SubagentStop when that is its newest event (unix ms).
	StartedAt, LastAt, StoppedAt int64
	// Result is the text it returned: its SubagentStop's last message, else
	// the parent call's result.
	Result string
	// Calls is every call, oldest first.
	Calls []SubagentCall
	// Asking is true while its newest event is a permission prompt.
	Asking bool
	// Turn figures: its own model calls, internal ones left out.
	Turns                                      int
	TokensIn, TokensOut, CacheRead, CacheWrite int64
	CostUSD                                    float64
	CostKnown                                  bool
	Model                                      string
	ByTool                                     []SubagentToolSpend
}

SubagentTrail is everything Caprock holds about one subagent of a session: the task its parent gave it, its calls in order, what it answered, and its numbers. Read in two scans of the session's rows (idx_events_session_ts), so a parent with thousands of events is not paged through.

func SubagentTrailOf added in v0.110.0

func SubagentTrailOf(ctx context.Context, q Querier, sessionID, agentID string) (tr SubagentTrail, found bool, err error)

SubagentTrailOf reads one subagent of a session. found is false when the session holds no event of that agent.

type SubscriptionSpend added in v0.101.0

type SubscriptionSpend struct {
	Agent        string
	Subscription string // "" is the Default sign-in
	Sessions     int64
	CostUSD      float64
}

SubscriptionSpend is one subscription's work since a moment (ADR-048).

func SpendBySubscription added in v0.101.0

func SpendBySubscription(ctx context.Context, q Querier, since int64) ([]SubscriptionSpend, error)

SpendBySubscription sums the priced turns since `since` (unix ms) per agent and subscription, for Settings → Subscriptions. Only agents that have subscriptions are asked for; internal turns (the agent's own housekeeping calls) are left out, as everywhere else a cost is shown.

type Summary

type Summary struct {
	Range      string         `json:"range"`
	FromMs     int64          `json:"from_ms"`
	Sessions   int64          `json:"sessions"`
	Active     int64          `json:"active_sessions"`
	Turns      int64          `json:"turns"`
	ToolCalls  int64          `json:"tool_calls"`
	TokensIn   int64          `json:"tokens_in"`
	TokensOut  int64          `json:"tokens_out"`
	CacheRead  int64          `json:"cache_read"`
	CacheWrite int64          `json:"cache_write"`
	CostUSD    float64        `json:"cost_usd"`
	Models     []ModelShare   `json:"models"`
	Projects   []ProjectShare `json:"projects"`
	// Work is what the money was spent ON — the breakdown by the KIND of work
	// each turn did, beside the cuts by model and by project. Rows sum exactly
	// to CostUSD and Tokens; see workkind.go for the rule.
	Work []WorkShare `json:"work"`
	// WorkUnlinkedCalls is how many tool calls in the range could not be
	// attached to any turn, so their cost was counted in the "no tool" row
	// rather than in the row for the work they actually did.
	//
	// It exists because the failure is INVISIBLE otherwise: an unlinked call
	// leaves its turn looking exactly like a turn that genuinely called
	// nothing, so a broken linkage quietly inflates "no tool" and understates
	// every other row. Publishing the breakdown without publishing this would
	// be publishing a number we know might be wrong (rule 6). The UI says so
	// whenever it is non-zero, and `caprock report` withholds the breakdown
	// entirely when the share is large enough to change the ranking.
	WorkUnlinkedCalls int64 `json:"work_unlinked_calls"`
	// Unpriced is the volume in this range whose model is not in the pricing
	// table, so it contributes nothing to CostUSD. Omitted when everything was
	// priced. Without it the aggregates flattened unknown models into the
	// COALESCE(SUM(cost_usd),0) total and 61k tokens of a model shipped after
	// the pricing table rendered as a confident "$0.00" — indistinguishable
	// from free, and an invented number under rule 6.
	Unpriced *Unpriced `json:"unpriced,omitempty"`
	// Background is measured token usage from known internal product machinery,
	// kept outside user session/turn/cost totals. It is not an error and carries
	// no invented dollar value when its vendor publishes none.
	Background *BackgroundUsage `json:"background,omitempty"`
}

Summary is the aggregate for /v1/stats/summary.

func Summarize

func Summarize(ctx context.Context, q Querier, fromMs int64) (Summary, error)

Summarize aggregates events since fromMs (0 = all time).

func SummarizeSpark added in v0.13.0

func SummarizeSpark(ctx context.Context, q Querier, fromMs int64, spark SparkSpec) (Summary, error)

func SummarizeSparkFor added in v0.22.0

func SummarizeSparkFor(ctx context.Context, q Querier, fromMs int64, spark SparkSpec, agent AgentFilter) (Summary, error)

SummarizeSparkFor is SummarizeSpark restricted to one agent.

type TableSize added in v0.64.0

type TableSize struct {
	Name       string `json:"name"`
	DataBytes  int64  `json:"data_bytes"`
	IndexBytes int64  `json:"index_bytes"`
}

TableSize is one table's footprint on disk.

type TaskRow

type TaskRow struct {
	ID           string  `json:"id"`
	Title        string  `json:"title"`
	Status       string  `json:"status"`
	Assignee     string  `json:"assignee"`
	BudgetUSD    float64 `json:"budget_usd"`
	VerifyRounds int     `json:"verify_rounds"`
	CostUSD      float64 `json:"cost_usd"`
	CreatedAt    int64   `json:"created_at"`
	UpdatedAt    int64   `json:"updated_at"`
}

TaskRow mirrors the tasks table (a query cache over the hive's task files).

func GetTask

func GetTask(ctx context.Context, q Querier, id string) (TaskRow, error)

GetTask returns one task row.

func ListTasks

func ListTasks(ctx context.Context, q Querier) ([]TaskRow, error)

ListTasks returns all task rows ordered by creation.

type TaskSession added in v0.15.0

type TaskSession struct {
	SessionID string `json:"session_id"`
	Cwd       string `json:"cwd"`
	FromTs    int64  `json:"from_ts"`
	ToTs      int64  `json:"to_ts,omitempty"`
}

TaskSession is one session that worked a task, newest window first. It is how the UI gets from a task card to the diff endpoint: the diff is keyed on a session id, and the board only ever knew the hive agent id.

func TaskSessions added in v0.15.0

func TaskSessions(ctx context.Context, q Querier, taskID string) ([]TaskSession, error)

TaskSessions returns the sessions attributed to a task, newest window first.

type TaxCall added in v0.56.0

type TaxCall struct {
	Ts      time.Time
	Tool    string
	Context int64
	Result  int64
	Model   string
}

TaxCall is one tool call priced against the turn that issued it: the context that turn re-read, and what the turn produced.

The link is exact, not reconstructed. A tool.pre event carries the msg_id of the assistant message whose usage was billed, so a call's context is that turn's own reading. Nearest-preceding-turn guessing recovers 38.7% of these correctly (see internal/ingest/parser.go), which is why it is not attempted.

func LoopTaxCalls added in v0.56.0

func LoopTaxCalls(ctx context.Context, q Querier, sessionID string, from, to time.Time) ([]TaxCall, int, error)

LoopTaxCalls returns the tool calls of one session in a time window, each carrying the context of the turn that issued it.

It exists to price a loop alert: the detector knows which calls repeated but stores no tokens, and the tax of a series is the sum of exactly these contexts. Calls whose turn carried no usage come back with Context 0 and are the caller's to drop -- a call that cannot be priced must not be priced as free. It also returns how many calls in the window carried no message id and so could not be attached to any turn. They are not a defect: a tool call arriving on the hook plane has no message id to carry, and 13% of all calls on the owner's archive are of that kind. But a tax summed over 87% of a loop's calls is an understatement, and an understatement nobody is told about is an invented number (rule 6). The caller reports the shortfall rather than presenting a partial figure as complete.

type TodoItem added in v0.108.0

type TodoItem struct {
	ID         string `json:"id"`
	Text       string `json:"text"`
	Status     string `json:"status"` // pending | in_progress | completed | cancelled
	ActiveForm string `json:"active_form,omitempty"`
}

TodoItem is one entry of the task list an agent keeps for itself: Claude Code's TodoWrite and TaskCreate/TaskUpdate, OpenCode's todowrite (stored as TodoWrite) and Codex's update_plan.

type TodoList added in v0.108.0

type TodoList struct {
	Items     []TodoItem `json:"items"`
	UpdatedAt int64      `json:"updated_at"`
}

TodoList is a session's current task list and when it last changed (unix ms; 0 when the session never kept one).

func SessionTodos added in v0.108.0

func SessionTodos(ctx context.Context, q Querier, sessionID string) (TodoList, error)

SessionTodos rebuilds a session's task list from its own task tool calls. A TodoWrite or update_plan call carries the whole list, so the newest one is the list. TaskCreate adds one task and TaskUpdate changes one by id; Claude Code numbers tasks 1, 2, 3 in the order they were created within the session ("Task #3 created successfully"), so the fold numbers them the same way. Whichever of the two kinds changed last is the answer. Only the main thread counts: a subagent keeps its own list. A call recorded on both the hook and the transcript plane is folded once, by tool_use_id.

The query pins idx_events_attr_work, which holds session_id, ts, kind and tool, so only the matching rows are read from the table. On a copy of the owner's database (2026-10-11, sqlite3) the largest session, 56k events, answered in 10 ms against 37 ms on idx_events_session_id; SQLite's own choice, idx_events_kind_id, walks every tool.pre in the database.

type ToolCount

type ToolCount struct {
	Tool  string `json:"tool"`
	Count int64  `json:"count"`
	// Bytes is how much this tool handed back, summed. Not tokens: a tool
	// spends none — the turn that reads its output does — and splitting a
	// turn's tokens between its calls would put a figure on screen that looks
	// measured and is not. This is the size of what came back, which is
	// measured exactly and answers what the call count cannot: on one machine
	// Bash was called 22x more often than Read and returned a quarter as much.
	Bytes int64 `json:"bytes"`
}

ToolCount is one row of the tool-usage distribution.

func ToolDistribution

func ToolDistribution(ctx context.Context, q Querier, fromMs int64, limit int) ([]ToolCount, error)

ToolDistribution counts tool.pre events by tool since fromMs (0 = all time).

type ToolDrill added in v0.70.0

type ToolDrill struct {
	Tool string `json:"tool"`
	// Kind is how the calls are grouped: shell, files, web, mcp or other.
	Kind string `json:"kind"`
	// GroupBy names a row's key in words: command, file, domain, query,
	// action, pattern, subagent, or call.
	GroupBy string `json:"group_by"`
	// Calls is every call of the tool in the window; rows hold the top ones.
	Calls int64 `json:"calls"`
	// Results is how many of them have a recorded result, the denominator of
	// every failure rate.
	Results  int64      `json:"results,omitempty"`
	Failures int64      `json:"failures,omitempty"`
	Bytes    int64      `json:"bytes,omitempty"`
	Rows     []DrillRow `json:"rows"`
	// Other is the calls in groups below the top rows.
	Other int64 `json:"other"`
	// TrendFromMs and TrendWidthMs place each row's Trend buckets.
	TrendFromMs  int64 `json:"trend_from_ms,omitempty"`
	TrendWidthMs int64 `json:"trend_width_ms,omitempty"`
	// Hints are measured facts worth acting on, strongest first.
	Hints []DrillHint `json:"hints,omitempty"`
}

ToolDrill is what one tool did in a window: its calls grouped by what they were about (the command a shell call ran, the file a Read or Edit touched, the domain a fetch reached), with what came back and how often it failed.

Every figure is counted from stored events. Nothing is estimated: a call whose result was never recorded counts as a call and is left out of the failure rate rather than guessed at.

func ToolDrillStats added in v0.70.0

func ToolDrillStats(ctx context.Context, q Querier, o DrillOptions) (ToolDrill, error)

ToolDrillStats groups one tool's calls. The pre carries the input; its post (same session, key post:<id>) carries the result, read through the unique (session_id, key) index rather than by scanning results.

type TouchDirs added in v0.14.0

type TouchDirs struct {
	// Dir is the absolute, normalized directory carried into this turn — the
	// directory of the most recent touch at or before it in the same session.
	// It is "" when no touch preceded the turn in its session (the session's
	// opening turns), which is the one case carry-forward cannot place.
	Dir string
	// HasDir distinguishes "no touch preceded this turn" from a directory that
	// normalized to the empty string, so the caller never treats the two alike.
	HasDir bool
}

TouchDirs is what one turn's attribution is decided from: the directory carried into it by the most recent file touch in its session.

type Turn added in v0.110.0

type Turn struct {
	SessionID string
	// PromptID is the turn.user event's id, to read its prompt.
	PromptID int64
	Start    int64 // unix ms
	End      int64 // unix ms; 0 while it runs
	// Failed: it ended on a StopFailure.
	Failed bool
}

Turn is one finished turn, or the open one (End 0).

func ProjectTurns added in v0.110.0

func ProjectTurns(ctx context.Context, q Querier, dir string, since time.Time, limit int) ([]Turn, error)

ProjectTurns returns the newest limit finished turns of the Claude Code sessions in one project — the repository root, else the folder, as Cost groups them — that ended at or after since, oldest first.

func SessionTurns added in v0.110.0

func SessionTurns(ctx context.Context, q Querier, ids []string, since time.Time, lookback time.Duration) ([]Turn, map[string]Turn, error)

SessionTurns returns the given sessions' turns that ended at or after since, oldest first, and each one's open turn, read from lookback before since so a turn that started earlier is whole.

func (Turn) Duration added in v0.110.0

func (t Turn) Duration() time.Duration

Duration is the finished turn's length.

type Unpriced added in v0.16.0

type Unpriced struct {
	Turns  int64 `json:"turns"`
	Tokens int64 `json:"tokens"`
	// Models are the distinct model ids with no pricing row, most volume first.
	// An empty model id (a turn recorded before its model was known) is
	// reported as "" and rendered by the UI as "unknown".
	Models []string `json:"models"`
}

Unpriced is the volume that could not be priced, and which models caused it. Naming the models matters: a user who sees an unknown model id can report it (or add a pricing override); "some tokens are unpriced" is not actionable.

type VerificationRow added in v0.15.0

type VerificationRow struct {
	Round      int    `json:"round"`
	Command    string `json:"command"`
	ExitCode   int    `json:"exit_code"`
	OutputPath string `json:"output_path,omitempty"`
	Ts         int64  `json:"ts"`
}

VerificationRow is one recorded done_criteria run. Reading these back is what lets the UI show *why* a task is green: which commands ran, and that they exited zero. A pass with no visible evidence is indistinguishable from a pass that never ran.

func Verifications added in v0.15.0

func Verifications(ctx context.Context, q Querier, taskID string) ([]VerificationRow, error)

Verifications returns a task's recorded command runs, latest round first.

type Week added in v0.70.0

type Week struct {
	FromMs int64 `json:"from_ms"`
	ToMs   int64 `json:"to_ms"`
	// Days are the seven days in order, each with what it opened and cost.
	Days []WeekDay `json:"days"`
	// Sessions is every session with a non-internal event in the window.
	Sessions   int64 `json:"sessions"`
	ActiveDays int   `json:"active_days"`
	Turns      int64 `json:"turns"`
	// CostUSD is the stored list-price cost of the window's turns: priced once
	// per message id and never twice across forks (TurnPaidElsewhere).
	CostUSD float64 `json:"cost_usd"`
	// UnpricedTurns carry tokens and no price, so CostUSD leaves them out.
	UnpricedTurns int64 `json:"unpriced_turns,omitempty"`
	// Models is each model's cost and re-read volume, for the context tax.
	Models []WeekModel `json:"models"`

	PRsOpened int `json:"prs_opened"`
	// PRsMerged is distinct pull requests a successful `gh pr merge` named,
	// by URL, by number, or -- for the current-branch form -- by the one URL
	// the command printed. MergesUnresolved ran but named nothing readable and
	// are not in PRsMerged.
	PRsMerged        int   `json:"prs_merged"`
	MergesUnresolved int   `json:"merges_unresolved"`
	Commits          int   `json:"commits"`
	FilesEdited      int   `json:"files_edited"`
	LinesAdded       int64 `json:"lines_added"`   // estimate: a Write counts its whole file
	LinesRemoved     int64 `json:"lines_removed"` // estimate: as above
	// CIWaitMs is tool time spent in commands that wait on CI; ToolMs is all
	// measured tool time. Only Claude Code's hook plane carries a duration, and
	// parallel calls overlap, so neither is wall-clock time.
	CIWaitMs int64 `json:"ci_wait_ms"`
	ToolMs   int64 `json:"tool_ms"`

	Agents  []WeekAgent  `json:"agents"`
	Loop    *WeekLoop    `json:"loop,omitempty"`
	Biggest *WeekSession `json:"biggest,omitempty"`
}

Week is the measured week. Estimates are named as such in their comments and in the API's `estimates` list; everything else is a count or a sum.

func WeekStats added in v0.70.0

func WeekStats(ctx context.Context, q Querier, o WeekOptions) (Week, error)

WeekStats measures one window. See Week for what each figure means.

type WeekAgent added in v0.70.0

type WeekAgent struct {
	Agent    string  `json:"agent"`
	Subagent bool    `json:"subagent"`
	Turns    int64   `json:"turns"`
	CostUSD  float64 `json:"cost_usd"`
	Sessions int64   `json:"sessions"`
	// Threads is how many distinct subagents ran; 0 for main threads.
	Threads int64 `json:"threads,omitempty"`
}

WeekAgent is one agent's main threads, or its subagents.

func AgentSplit added in v0.70.0

func AgentSplit(ctx context.Context, q Querier, from, to int64) ([]WeekAgent, error)

AgentSplit is the turns and cost of each agent's main threads and of its subagents in [from, to). to <= 0 means no upper bound.

It reads in two steps so the big one is covered (idx_events_turn_agent, migration 0031): turns grouped by session and by whether they carry an agent id, without touching a payload; then, for each session with main-thread turns, one payload asks whether the session is a sidechain. That is the one mark MainThreadWhere reads besides agent_id, and OpenCode writes it on every turn of a child session, so one turn answers for the session. Reading it per event cost 3.5 s on the owner's database (2026-10-04).

type WeekDay added in v0.70.0

type WeekDay struct {
	Day       string  `json:"day"`
	PRsOpened int     `json:"prs_opened"`
	CostUSD   float64 `json:"cost_usd"`
	Active    bool    `json:"active"`
}

WeekDay is one local day of the window.

type WeekLoop added in v0.70.0

type WeekLoop struct {
	SessionID string `json:"-"` // for pricing; never shown
	Agent     string `json:"agent"`
	Tool      string `json:"tool"`
	// Kind is what the repeated call did, in words a card can use without
	// quoting the command: poll, command, edit, fetch, subagent, other.
	Kind    string `json:"kind"`
	Calls   int    `json:"calls"`
	FirstMs int64  `json:"first_ms"`
	LastMs  int64  `json:"last_ms"`
	// TaxUSD is what the loop paid to re-read the conversation, priced the way
	// the live alert prices it (contexttax.PriceSeries) -- an estimate, and
	// absent when none of its calls could be priced (Codex calls carry no
	// message id). TaxPricedCalls says how many calls it covers.
	TaxUSD         float64 `json:"tax_usd,omitempty"`
	TaxPricedCalls int     `json:"tax_priced_calls,omitempty"`
}

WeekLoop is the longest episode the loop detector would have alerted on.

type WeekModel added in v0.70.0

type WeekModel struct {
	Model     string  `json:"model"`
	CacheRead int64   `json:"cache_read"`
	CostUSD   float64 `json:"cost_usd"`
}

WeekModel is one model's share of the week, the input to the context tax.

type WeekOptions added in v0.70.0

type WeekOptions struct {
	// From and To bound the window, [From, To). The caller computes them from
	// local midnights, the same days the Cost screen uses.
	From, To time.Time
	// Loc decides which day an event falls on.
	Loc *time.Location
	// LoopK and LoopWindow are the loop detector's own settings (K calls of
	// one signature within the window), so the card's loop is the alert's loop.
	LoopK      int
	LoopWindow time.Duration
	// Home is the user's home directory: notes an agent writes under
	// ~/.claude are memory, not code, and are not counted as files edited.
	Home string
	// TempDirs are scratch locations whose files are not counted either.
	TempDirs []string
}

WeekOptions say which seven days, and how the product detects a loop.

type WeekSession added in v0.70.0

type WeekSession struct {
	SessionID  string  `json:"-"`
	Agent      string  `json:"agent"`
	CostUSD    float64 `json:"cost_usd"`
	Turns      int64   `json:"turns"`
	ActiveDays int     `json:"active_days"`
}

WeekSession is the week's most expensive session, without its name.

type WindowSize added in v0.64.0

type WindowSize struct {
	Days         int   `json:"days"`
	Events       int64 `json:"events"`
	PayloadBytes int64 `json:"payload_bytes"`
}

WindowSize is the events on one side of a day boundary.

type WorkKind added in v0.19.0

type WorkKind string

WorkKind is the kind of work one turn did. It is a closed set: every turn lands in exactly one of these, and they sum to the total.

const (
	// WorkNone is a turn that called no tool at all. Named for what is
	// observable (no tool call), never for what it might have been doing.
	WorkNone WorkKind = "none"
	// WorkEdit is a turn that wrote to a file.
	WorkEdit WorkKind = "edit"
	// WorkCommand is a turn that ran a shell command.
	WorkCommand WorkKind = "command"
	// WorkRead is a turn that read or searched the codebase.
	WorkRead WorkKind = "read"
	// WorkWeb is a turn that fetched or searched the web.
	WorkWeb WorkKind = "web"
	// WorkMCP is a turn that called an MCP tool — the user's own integrations.
	WorkMCP WorkKind = "mcp"
	// WorkOther is a turn that called a tool belonging to none of the above:
	// agent and task control, skills, structured output. It is deliberately
	// last and deliberately vague-sounding, because its members genuinely have
	// nothing in common but "not one of the named kinds".
	WorkOther WorkKind = "other"
)

The categories.

WHY THESE, AND WHAT WAS REJECTED. The cut has to survive the question "is that label true?" for every turn it puts in a row, because a flattering label is an invented number in words (rule 6).

  • Edits and commands are separated because they are the two halves of writing software that cost differently and are acted on differently: an edit-heavy bill and a command-heavy bill suggest opposite things about where the time goes.
  • Reading and searching are ONE row, not two. Read, Grep and Glob are the same activity from the model's side — pulling context into the prompt so it can be reasoned about — and the cost driver is identical: the contents enter the prompt and are billed. Splitting them would invite the reader to compare two numbers that mean the same thing.
  • Web research is its own row rather than folded into "other". Fetching and searching the web is a distinct, recognisable activity whose cost a user can act on (it pulls large pages into the prompt), and on the owner's database it is a real 1.8% rather than a rounding error.
  • MCP tools are their own row because they are the user's OWN integrations. Folding a browser-automation or scraping tool into "other" would hide the cost of the thing the user added themselves, which is exactly the cost they are most able to change.
  • "No tool" is called what it is. It is NOT labelled "conversation", "thinking" or "planning": a turn that called no tool may be answering a question, reasoning, planning, or simply writing prose, and picking one of those as the label would assert something the data does not say. The honest statement is the mechanical one — this turn called no tool — and the UI says exactly that.

func WorkKindOfTurn added in v0.19.0

func WorkKindOfTurn(tools []string) WorkKind

WorkKindOfTurn decides the single kind a turn belongs to from the tools it called. An empty set is WorkNone — the turn called nothing.

It is exported so the classification has exactly one definition, testable on its own and shared by the summary and any future caller. The precedence is applied here and nowhere else.

type WorkShare added in v0.19.0

type WorkShare struct {
	// Kind is one of the WorkKind constants — a stable key the UI maps to a
	// label, never a display string.
	Kind      WorkKind `json:"kind"`
	Turns     int64    `json:"turns"`
	Tokens    int64    `json:"tokens"`
	CostUSD   float64  `json:"cost_usd"`
	TokensPct float64  `json:"tokens_pct"`
	CostPct   float64  `json:"cost_pct"`
}

WorkShare is tokens/cost for one KIND of work — what the money was spent on, beside the existing cuts by model and by project.

Turns, not sessions: a session does many kinds of work, so it cannot be counted once per kind without the column summing to more than the total, while a TURN is charged to exactly one kind by construction (see workkind.go), so turns partition and add up.

CostPct and TokensPct are shares of the range total, computed here rather than in the panel because the denominator is the whole range — a percentage whose base the reader has to guess is what rule 6 exists to prevent. Both are sent because they genuinely differ: cost per token varies by model, so a kind of work done by a cheap model is a larger share of the tokens than of the money.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL