store

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 19 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 (
	StatusActive = "active"
	StatusIdle   = "idle"
	StatusEnded  = "ended"
)

Session status values.

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.
	MetaToolLinkBackfilled = "tool_link_backfilled"
)

Meta keys.

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 TouchRule = "" /* 369-byte string literal not displayed */

TouchRule is the one-sentence statement of what counts as touching a directory, shown in the UI so the number is not a black box.

THE RULE: a tool that names a FILE touches that file's directory. Read, Edit and Write do; Bash, Grep and Glob do not.

Why reading counts. Reading a file to understand it is how most of a turn's tokens get spent — the file's contents enter the prompt and are billed. A rule that counted only writes would report a directory as free right up to the moment it was edited, which is the opposite of what a budget wants to know.

Why Bash does not, even when its command contains a path. A path inside a shell string is not a claim about what was touched: `grep -r foo /services` reads a tree, `cd /services/api && go build ./...` names one directory and touches many, and `rm /tmp/x` names a path that is not work at all. Parsing intent out of a command line would be inference presented as measurement. Bash is the biggest tool by volume on the owner's database (32581 of 65915 calls), so this is not a rounding decision — it is the reason a large share of spend lands in the unattributed bucket, and the UI says so rather than quietly redistributing it.

Why not Grep and Glob. They name a search pattern and a root, not a file that was read; the files they matched are not recorded. Neither appears at all on the owner's database, so including them would add no signal and one more assumption.

View Source
const UnattributedPath = "\x00unattributed"

UnattributedPath is the sentinel for spend that belongs to a repository but not to any single directory inside it.

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.

THE NAME IS INTERNAL ONLY. "Unattributed" describes this package's bookkeeping, not the user's work, and on real data this row is usually the largest — the tool calls behind it are overwhelmingly Bash (17382 of 27158 calls in the owner's `amarketer`, measured 2026-08-22): test runs, `git log`, tree-wide greps, builds. Showing a user that word next to two thirds of their spend says the tool failed, when in fact the work simply has no one home. The UI therefore names what the work IS; see REPO_WIDE_LABEL in Projects.tsx.

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.

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

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

AttributeDir decides which directory a turn's cost belongs to, given every directory its tool calls touched and the repository the turn's session sits in.

It returns the directory to charge and true, or false when the turn cannot be charged to exactly one. The three unattributable cases are deliberately not distinguished here — they are all "we do not know which one directory this was", and the UI states them as one honest bucket:

  • the turn touched several directories (do not split — see the file header)
  • the turn touched nothing that names a path (a pure Bash or thinking turn)
  • the turn touched a path OUTSIDE the repository

FILES OUTSIDE THE REPOSITORY. A turn that edits /tmp, or a file in an entirely different checkout, is not charged to the repository's directories — the touched directory is not one of them, so claiming it would put spend under a heading it does not belong to. Such a turn still counts toward the repository total (its session is in this repository and the money was really spent there), and lands in the unattributed bucket. That keeps the parts summing to the whole without inventing a row for a directory the repository does not contain.

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 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 CountThrottles

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

CountThrottles counts throttle observations since sinceMs (limit-forecast input).

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 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 GetOffset

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

Offset persistence for the transcript tailer.

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 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 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 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

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

MarkEndedSessions flips idle/active sessions silent since `before` (unix ms) to ended.

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 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 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 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 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

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 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 SessionFiles

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

SessionFiles lists paths a session touched, most recent first.

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 SetOffset

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

func SetSessionStatus

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

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

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 TouchesByTurn added in v0.14.0

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

TouchesByTurn reads every tool call in a time range and returns, per session, the set of directories each TURN touched — keyed by the message id that links the tool call to the turn whose cost paid for it.

The query reads only indexed columns (kind, ts, session_id, msg_id, touch_dir) and never parses JSON, which is the whole point of resolving touch_dir at ingest: on the owner's database json_extract over the tool.pre rows in a 30-day range costs ~215ms against a ~152ms budget for the entire summary.

A tool.pre row with no msg_id cannot be tied to a turn (the hook plane does not carry one). Those rows are counted per session so their sessions can be reported as partially unattributed rather than silently attributed on the evidence that happens to be linkable.

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 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.

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 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"`
}

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 ModelShare

type ModelShare struct {
	Model   string  `json:"model"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Turns   int64   `json:"turns"`
}

ModelShare is tokens/cost per model.

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 marks the one row that is a bucket rather than a directory,
	// so the UI does not have to know the sentinel's spelling.
	Unattributed bool `json:"unattributed,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". The one value that is NOT a path is UnattributedPath, the bucket for spend that belongs to the repository but to no single directory in it; callers must render it as its own thing and never as a directory (see Unattributed).

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 {
	Project  string      `json:"project"`
	Tokens   int64       `json:"tokens"`
	CostUSD  float64     `json:"cost_usd"`
	Sessions int64       `json:"sessions"`
	Paths    []PathShare `json:"paths,omitempty"`
	Spark    *Spark      `json:"spark,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 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

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 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"`
}

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.

type SessionPatch

type SessionPatch struct {
	Cwd, Project, Model, TranscriptPath, GitBranch, Version 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.

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 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 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"`
}

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)

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).

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 ToolCount

type ToolCount struct {
	Tool  string `json:"tool"`
	Count int64  `json:"count"`
}

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 TouchDirs added in v0.14.0

type TouchDirs struct {
	// Dirs are the distinct absolute directories touched, normalized.
	Dirs map[string]struct{}
	// Unlinkable records that at least one tool call could not be tied to a
	// turn (no message id — the hook plane never supplies one). Such a turn is
	// reported as unattributed rather than attributed on partial evidence.
	Unlinkable bool
}

TouchDirs is the set of directories one turn touched, and whether anything about that set is unknown.

Jump to

Keyboard shortcuts

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