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 CloseAssignment(ctx context.Context, q Querier, taskID, sessionID 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 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 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 ProjectShare
- type Querier
- type RateLimitSnapshot
- 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`.
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 CloseAssignment ¶
CloseAssignment closes the open window for a task/session at to_ts.
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 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 from a working directory (its basename).
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 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
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.
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 ProjectShare ¶
type ProjectShare struct {
}
ProjectShare is tokens/cost per project (cwd basename). Sessions is how many distinct sessions touched the project in the range — the "who is working in this repo" half of the question; cost alone does not answer it.
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 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"`
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 Open ¶
Open opens (creating if needed) the SQLite database at path and applies pending migrations. Use ":memory:" for tests.
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).