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
- Variables
- func AddDaily(ctx context.Context, q Querier, day, project, model string, tokens int64, ...) error
- func AttributeDir(t TouchDirs, repoRoot string) (string, bool)
- func AttributeTaskCost(ctx context.Context, q Querier, taskID string) (float64, error)
- func CloseTaskAssignments(ctx context.Context, q Querier, taskID string, toTs int64) error
- func CountEvents(ctx context.Context, q Querier) (int64, error)
- func CountThrottles(ctx context.Context, q Querier, sinceMs int64) (int64, error)
- func DisambiguateLabels(roots map[string]string) map[string]string
- func EventsAfter(ctx context.Context, q Querier, after int64, limit int) ([]event.Event, error)
- func GetOffset(ctx context.Context, q Querier, path string) (int64, error)
- func IncForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) (int, error)
- func InsertEvent(ctx context.Context, q Querier, ev *event.Event) (int64, error)
- func LastEvents(ctx context.Context, q Querier, sessionID string, n int) ([]event.Event, error)
- func ListEvents(ctx context.Context, q Querier, sessionID string, after int64, limit int) ([]event.Event, error)
- func MarkEndedSessions(ctx context.Context, q Querier, before int64) ([]string, error)
- func MarkIdleSessions(ctx context.Context, q Querier, before int64) ([]string, error)
- func MarkOwned(ctx context.Context, q Querier, id, worktree, spawnCommand string, pid int) error
- func OpenAssignment(ctx context.Context, q Querier, taskID, sessionID string, fromTs int64) error
- func ProjectFromCwd(cwd string) string
- func PruneEventsBefore(ctx context.Context, q Querier, beforeMs int64) (int64, error)
- func RateLimitPace(ctx context.Context, q Querier, window string, resetsAt int64) (pctPerHour float64, ok bool, err error)
- func RecordRateLimit(ctx context.Context, q Querier, s RateLimitSnapshot, sessionID string) error
- func RecordThrottle(ctx context.Context, q Querier, ts int64, sessionID, kind string, ...) error
- func RecordVerification(ctx context.Context, q Querier, taskID string, round int, command string, ...) error
- func RepoPathFromCwd(cwd string) string
- func ResetForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) error
- func SessionFiles(ctx context.Context, q Querier, sessionID string, limit int) ([]string, error)
- func SetExit(ctx context.Context, q Querier, id string, code int) error
- func SetOffset(ctx context.Context, q Querier, path, sessionID string, off int64) error
- func SetSessionStatus(ctx context.Context, q Querier, id, status string) error
- func TouchDir(payload []byte) string
- func TouchFile(ctx context.Context, q Querier, sessionID, path string, ts int64) (bool, error)
- func UpsertSession(ctx context.Context, q Querier, id string, p SessionPatch) error
- func UpsertTask(ctx context.Context, q Querier, t TaskRow) error
- type AssistantNote
- type DailyStat
- type HistoryTotals
- type ModelShare
- type PathShare
- type ProjectShare
- type Querier
- type RateLimitSnapshot
- type RepoInfo
- type Session
- type SessionPatch
- type Spark
- type SparkSpec
- type Stats
- type Store
- func (s *Store) Close() error
- func (s *Store) DB() *sql.DB
- func (s *Store) GetMeta(ctx context.Context, key string) (string, error)
- func (s *Store) SchemaVersion(ctx context.Context) (int, error)
- func (s *Store) SetMeta(ctx context.Context, key, value string) error
- func (s *Store) WithTx(ctx context.Context, fn func(q Querier) error) error
- type Summary
- type TaskRow
- type TaskSession
- type ToolCount
- type TouchDirs
- type Unpriced
- type VerificationRow
- type WorkKind
- type WorkShare
Constants ¶
const ( StatusActive = "active" StatusIdle = "idle" StatusEnded = "ended" )
Session status values.
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" // 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.
const MaxEventPage = 5000
MaxEventPage is the most events one ListEvents call will return. Callers that need more must paginate with `after`.
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.
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.
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.
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.
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 ¶
var ErrDuplicate = errors.New("duplicate event")
ErrDuplicate is returned by InsertEvent when (session_id, key) already exists.
Functions ¶
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.
func AttributeDir ¶ added in v0.14.0
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 ¶
AttributeTaskCost sums event cost within a task's assignment windows and writes it to tasks.cost_usd (T24).
func CloseTaskAssignments ¶ added in v0.12.0
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 ¶
CountEvents returns the total number of stored events (for status/metrics).
func CountThrottles ¶
CountThrottles counts throttle observations since sinceMs (limit-forecast input).
func DisambiguateLabels ¶ added in v0.12.2
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 EventsAfter ¶
Cursor is a stable timeline of events across all sessions (for the live feed catch-up).
func IncForcedContinue ¶
IncForcedContinue bumps and returns the forced-continue count for (session, task).
func InsertEvent ¶
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 LastEvents ¶
LastEvents returns the newest n events for a session, oldest first.
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 MarkEndedSessions ¶
MarkEndedSessions flips idle/active sessions silent since `before` (unix ms) to ended.
func MarkIdleSessions ¶
MarkIdleSessions flips active sessions with no event since `before` (unix ms) to idle. Returns the ids that changed.
func OpenAssignment ¶
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 ProjectFromCwd ¶
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 PruneEventsBefore ¶
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 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 RecordRateLimit ¶ added in v0.4.0
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 RepoPathFromCwd ¶ added in v0.12.2
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 ¶
ResetForcedContinue clears the counter (task moved on).
func SessionFiles ¶
SessionFiles lists paths a session touched, most recent first.
func SetSessionStatus ¶
SetSessionStatus forces a status (idle/ended/active).
func TouchDir ¶ added in v0.14.0
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 ¶
TouchFile records that a session touched a path. Returns true when the path is new for the session.
func UpsertSession ¶
UpsertSession creates or updates a session from a patch.
Types ¶
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.
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.
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"`
}
HistoryTotals is the all-time (or ranged) cross-session summary for the History screen.
type PathShare ¶ added in v0.12.2
type PathShare struct {
// 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.
// 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.
}
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 ProjectShare ¶
type ProjectShare struct {
// 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.
}
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 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.
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
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
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 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"`
}
Session mirrors the sessions table.
func GetSession ¶
GetSession returns one session; sql.ErrNoRows when unknown.
func ListOwnedActive ¶
ListOwnedActive returns owned sessions that are not ended (for restart bookkeeping).
type SessionPatch ¶
type SessionPatch struct {
Cwd, Project, Model, TranscriptPath, GitBranch, Version string
// 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
}
SessionPatch carries the fields an event may reveal about its session. Empty strings mean "no information" and are never written over existing values.
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.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store wraps the database handle.
func (*Store) SchemaVersion ¶
SchemaVersion returns the applied schema version (0 = empty database).
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"`
}
Summary is the aggregate for /v1/stats/summary.
func SummarizeSpark ¶ added in v0.13.0
SummarizeSpark is Summarize with an optional per-project time series. The series costs one extra GROUP BY column on a scan the summary already makes, so it is nearly free; see the measurement note on the query below.
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).
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
TaskSessions returns the sessions attributed to a task, newest window first.
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 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
Verifications returns a task's recorded command runs, latest round first.
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
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.
}
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.