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 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 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 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 ToolCount
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" )
Meta keys.
const MaxEventPage = 5000
MaxEventPage is the most events one ListEvents call will return. Callers that need more must paginate with `after`.
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 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 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"`
}
HistoryTotals is the all-time (or ranged) cross-session summary for the History screen.
type PathShare ¶ added in v0.12.2
type PathShare struct {
}
PathShare is tokens/cost for one directory inside a repository. Path is the first segment under the repository root; "." is work in the root itself.
type ProjectShare ¶
type ProjectShare struct {
}
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.
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"`
}
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
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 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"`
}
Summary is the aggregate for /v1/stats/summary.
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).