store

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: Apache-2.0 Imports: 14 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"
	MetaPricingVersion = "pricing_version"
)

Meta keys.

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

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

CloseAssignment closes the open window for a task/session at to_ts.

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

func ProjectFromCwd

func ProjectFromCwd(cwd string) string

ProjectFromCwd derives the project label from a working directory (its basename).

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 RecentToolPre

func RecentToolPre(ctx context.Context, q Querier, sessionID string, since int64) ([]event.Event, error)

RecentToolPre returns tool.pre events for a session since `since` (unix ms), oldest first — the loop detector's window.

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

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

type ProjectShare struct {
	Project string  `json:"project"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
}

ProjectShare is tokens/cost per project (cwd basename).

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

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

Open opens (creating if needed) the SQLite database at path and applies pending migrations. Use ":memory:" for tests.

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

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

Jump to

Keyboard shortcuts

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