store

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 15 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 Smif's SQLite database: messages, runs, presence, cursors, budgets, blobs, threads and the audit table (RFC 8.1).

Every message state change goes through Tx.Transition, which checks the state machine (RFC 5.2) and appends an audit row in the same transaction.

Index

Constants

View Source
const (
	RunRunning    = "running"
	RunSucceeded  = "succeeded"
	RunNeedsHuman = "needs_human"
	RunFailed     = "failed"
	RunTimeout    = "timeout"
	RunKilled     = "killed"
	RunOrphaned   = "orphaned"
	RunCancelled  = "cancelled"
)

Run states.

Variables

AllStates lists every state.

View Source
var ErrIllegal = errors.New("illegal state transition")

ErrIllegal is returned for a transition the state machine forbids.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when a row does not exist.

View Source
var SchemaVersion = func() int {
	n := 0
	ents, _ := fs.ReadDir(migrationFS, "migrations")
	for _, e := range ents {
		v, _ := strconv.Atoi(strings.SplitN(e.Name(), "_", 2)[0])
		if v > n {
			n = v
		}
	}
	return n
}()

SchemaVersion is the highest migration number shipped in this binary.

Functions

func Allowed

func Allowed(from, to State) bool

Allowed reports whether from -> to is a legal transition.

func Int

func Int(i int) *int

func Str

func Str(s string) *string

Str and friends make Fields literals short.

func Time

func Time(t time.Time) *time.Time

Types

type AuditRow

type AuditRow struct {
	Seq       int64          `json:"seq"`
	TS        time.Time      `json:"ts"`
	Event     string         `json:"event"`
	Agent     string         `json:"agent,omitempty"`
	MessageID string         `json:"message_id,omitempty"`
	RunID     string         `json:"run_id,omitempty"`
	ThreadID  string         `json:"thread_id,omitempty"`
	Detail    map[string]any `json:"detail,omitempty"`
}

AuditRow is one audit record.

type Fields

type Fields struct {
	RuleID, Handler, Profile *string
	Attempt, ExtraAttempts   *int
	NotBefore                *time.Time
	HoldReason, Reason       *string
	Summary, HumanQuestion   *string
	AnsweredBy               *string
}

Fields are optional column updates applied with a transition.

type Message

type Message struct {
	Env           envelope.Envelope
	State         State
	RuleID        string
	Handler       string
	Profile       string
	Attempt       int
	ExtraAttempts int
	NotBefore     time.Time
	HoldReason    string
	Reason        string
	Summary       string
	HumanQuestion string
	Coalesced     int
	Recurrence    bool
	AnsweredBy    string
	Seen          bool
	HandledSeq    int64
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

Message is a stored message with its routing and lifecycle columns.

type Presence

type Presence struct {
	Repo, SessionID, State string
	LastSeen               time.Time
	Turn                   string // "busy" (a prompt is running), "idle" (waits for input) or ""
	TurnAt                 time.Time
	TTY                    string
	PID                    int
	Term                   string
	Title                  string // claude --name or /rename
	LastPrompt             string // the human's last prompt, shortened
	Harness                string // the agent's provider: "claude" (ADR-0019)
	Cwd                    string // the session's folder (from discovery; not stored)
	// Level is "" for a session a provider or a hook reports, else the
	// support level of a scanned session: herdr or listed (ADR-0019; not
	// stored, so a scanned session never gets a presence row).
	Level string
}

Presence is one interactive session seen in a repo. Turn, TTY, PID and Term come from the hooks (ADR-0012); they are empty for a session first seen by the status line.

type PresenceUpdate

type PresenceUpdate struct {
	Turn, TTY, Term   string
	PID               int
	Title, LastPrompt string
	Harness           string // "" = claude on a new row, keep on an old one
}

PresenceUpdate is one hook or status-line report. Empty fields keep the stored value; Turn "" keeps the turn.

type Run

type Run struct {
	ID, MessageID, Agent, Handler, Profile string
	Attempt                                int
	State                                  string
	PID, PGID                              int
	SessionID, ArchivedSession             string
	Workspace, Branch, BaseSHA, HeadSHA    string
	Diffstat                               string
	ResultJSON, UsageJSON                  string
	CostUSD                                float64
	InputTokens, OutputTokens              int64
	Error, Transcript, Stderr              string
	StartedAt                              time.Time
	EndedAt                                time.Time
}

Run is one handler execution.

type RunEnd

type RunEnd struct {
	State                     string
	SessionID                 string
	ArchivedSession           string
	HeadSHA, Diffstat, Branch string
	ResultJSON, UsageJSON     string
	CostUSD                   float64
	InputTokens, OutputTokens int64
	Error, Transcript, Stderr string
}

RunEnd carries the final columns of a run.

type SessionAsk

type SessionAsk struct {
	MessageID, SessionID, Cwd string
	CreatedAt                 time.Time
}

SessionAsk ties a message to the interactive session whose fork answers it (ADR-0013): the worker resumes SessionID with --fork-session in Cwd.

type State

type State string

State is a message lifecycle state (RFC 5.2).

const (
	Accepted   State = "accepted"
	Queued     State = "queued"
	Running    State = "running"
	RetryWait  State = "retry_wait"
	NeedsHuman State = "needs_human"
	Done       State = "done"
	Rejected   State = "rejected"
	Expired    State = "expired"
	DeadLetter State = "dead_letter"
)

The nine states. Four are terminal: done, rejected, expired, dead_letter.

func (State) Open

func (s State) Open() bool

Open reports whether a message in s still counts as open for dedupe.

func (State) Terminal

func (s State) Terminal() bool

Terminal reports whether s is one of the four terminal states.

type Store

type Store struct {

	// OnAudit is called after commit with the audit rows the transaction wrote.
	OnAudit func([]AuditRow)
	// contains filtered or unexported fields
}

Store wraps the database.

func Open

func Open(dir string) (*Store, error)

Open opens (and migrates) the database at dir/smif.db.

func (*Store) ActivePresence

func (s *Store) ActivePresence(repo string, ttl time.Duration) ([]Presence, error)

ActivePresence returns live sessions for repo newer than ttl.

func (*Store) AllPresence

func (s *Store) AllPresence() ([]Presence, error)

AllPresence returns every stored session, newest first.

func (*Store) AuditFor

func (s *Store) AuditFor(msgID string) ([]AuditRow, error)

AuditFor returns audit rows for a message.

func (*Store) AuditHead

func (s *Store) AuditHead() (int64, error)

AuditHead returns the newest audit seq, or 0 for an empty table.

func (*Store) AuditSince

func (s *Store) AuditSince(seq int64, limit int) ([]AuditRow, error)

AuditSince returns audit rows after seq (for tail).

func (*Store) AuditTail

func (s *Store) AuditTail(n int) ([]AuditRow, error)

AuditTail returns the newest n audit rows, oldest first.

func (*Store) AuditWhere

func (s *Store) AuditWhere(where string, args ...any) ([]AuditRow, error)

AuditWhere returns audit rows matching a condition.

func (*Store) BlobInfo

func (s *Store) BlobInfo(sha string) (size int64, mime string, err error)

BlobInfo returns size and mime for a blob.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB exposes the handle for read-only queries in other packages.

func (*Store) DigestCursor

func (s *Store) DigestCursor(agent string) int64

DigestCursor returns an agent's digest cursor.

func (*Store) ExpiredBlobs

func (s *Store) ExpiredBlobs(cutoff time.Time) ([]string, error)

ExpiredBlobs returns blobs unreferenced since before cutoff.

func (*Store) FindMessage

func (s *Store) FindMessage(ref string) (*Message, error)

FindMessage resolves an id or a unique suffix of one.

func (*Store) GetKV

func (s *Store) GetKV(k string) string

GetKV reads a kv entry.

func (*Store) GetMessage

func (s *Store) GetMessage(id string) (*Message, error)

GetMessage reads a message.

func (*Store) GetRun

func (s *Store) GetRun(id string) (*Run, error)

GetRun reads a run.

func (*Store) Messages

func (s *Store) Messages(where string, args ...any) ([]*Message, error)

Messages runs a query returning message rows. where is appended after WHERE.

func (*Store) Now

func (s *Store) Now() time.Time

Now returns the store clock's time.

func (*Store) Runs

func (s *Store) Runs(where string, args ...any) ([]*Run, error)

Runs queries runs.

func (*Store) SessionAsk

func (s *Store) SessionAsk(messageID string) (*SessionAsk, error)

SessionAsk returns the session ask of a message, or nil.

func (*Store) SessionAsks

func (s *Store) SessionAsks(sessionID string, limit int) ([]SessionAsk, error)

SessionAsks returns the newest limit asks answered by forks of a session, oldest first.

func (*Store) SetClock

func (s *Store) SetClock(f func() time.Time)

SetClock overrides the clock (tests).

func (*Store) SetRunProcess

func (s *Store) SetRunProcess(id string, pid, pgid int, transcript string) error

SetRunProcess records the pid and pgid once the process started, and the transcript path (empty for none) so a running run's transcript can be tailed.

func (*Store) SetRunSession

func (s *Store) SetRunSession(id, session string) error

SetRunSession records the claude session id as soon as it is known.

func (*Store) ThreadBranch

func (s *Store) ThreadBranch(thread, agent string) string

ThreadBranch returns the branch recorded for (thread, agent).

func (*Store) Update

func (s *Store) Update(f func(*Tx) error) error

Update runs f in a serialised write transaction.

func (*Store) Usage

func (s *Store) Usage(agent, day string) (cost float64, tokens int64)

Usage returns an agent's spend for a day.

func (*Store) Version

func (s *Store) Version() int

Version returns the applied schema version.

type Thread

type Thread struct {
	ID           string
	Frozen       bool
	FrozenReason string
	Branch       string
}

Thread is a thread's guard state.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx is a write transaction.

func (*Tx) AddUsage

func (t *Tx) AddUsage(agent, day string, cost float64, tokens int64) error

AddUsage accumulates a run's usage into the agent's day.

func (*Tx) Audit

func (t *Tx) Audit(event, agent, msgID, runID, threadID string, detail map[string]any) error

Audit appends an audit row inside the transaction.

func (*Tx) Coalesce

func (t *Tx) Coalesce(m *Message, dup *envelope.Envelope) error

Coalesce bumps coalesced_count on an open message and audits it.

func (*Tx) CountPair

func (t *Tx) CountPair(thread, a, b string, since time.Time) (int, error)

CountPair counts messages in a thread between two agents (either direction) created at or after since.

func (*Tx) CountThread

func (t *Tx) CountThread(id string) (int, error)

CountThread returns how many messages a thread has.

func (*Tx) DeleteBlob

func (t *Tx) DeleteBlob(sha string) error

DeleteBlob removes a blob row.

func (*Tx) Exec

func (t *Tx) Exec(q string, args ...any) (sql.Result, error)

Exec runs a statement inside the transaction.

func (*Tx) FinishRun

func (t *Tx) FinishRun(id string, e RunEnd) error

FinishRun closes a run and audits it.

func (*Tx) FreezeThread

func (t *Tx) FreezeThread(id, reason string) error

FreezeThread marks a thread frozen.

func (*Tx) GetMessage

func (t *Tx) GetMessage(id string) (*Message, error)

GetMessage reads a message inside the transaction.

func (*Tx) GetRun

func (t *Tx) GetRun(id string) (*Run, error)

GetRun reads a run in the transaction.

func (*Tx) GetThread

func (t *Tx) GetThread(id string) (*Thread, error)

GetThread returns the thread row.

func (*Tx) InsertMessage

func (t *Tx) InsertMessage(e *envelope.Envelope, recurrence bool) error

InsertMessage stores a new message in state accepted and audits it.

func (*Tx) InsertRun

func (t *Tx) InsertRun(r *Run) error

InsertRun creates a run in state running.

func (*Tx) InsertSessionAsk

func (t *Tx) InsertSessionAsk(messageID, sessionID, cwd string) error

InsertSessionAsk records that message id is answered by a fork of session.

func (*Tx) LastDoneByDedupe

func (t *Tx) LastDoneByDedupe(to, key string, since time.Time) (*Message, error)

LastDoneByDedupe returns the newest done message to `to` with the key that finished after `since`.

func (*Tx) MarkSeen

func (t *Tx) MarkSeen(id string) error

MarkSeen marks a reply as fetched by its asker.

func (*Tx) Messages

func (t *Tx) Messages(where string, args ...any) ([]*Message, error)

Messages inside a transaction.

func (*Tx) Now

func (t *Tx) Now() time.Time

Now is the transaction timestamp.

func (*Tx) OpenByDedupe

func (t *Tx) OpenByDedupe(to, key string) (*Message, error)

OpenByDedupe returns a non-terminal (and not needs_human) message to `to` with the dedupe key.

func (*Tx) PutBlob

func (t *Tx) PutBlob(sha string, size int64, mime string) error

PutBlob records a blob row (refcount 0 until a message references it).

func (*Tx) QueryRow

func (t *Tx) QueryRow(q string, args ...any) *sql.Row

QueryRow runs a query inside the transaction.

func (*Tx) ResetCoalesced

func (t *Tx) ResetCoalesced(id string) error

ResetCoalesced zeroes the counter (used after a recurrence is created).

func (*Tx) Runs

func (t *Tx) Runs(where string, args ...any) ([]*Run, error)

Runs in a transaction.

func (*Tx) SessionAskTx

func (t *Tx) SessionAskTx(messageID string) (*SessionAsk, error)

SessionAskTx returns the session ask of a message, or nil.

func (*Tx) SetDigestCursor

func (t *Tx) SetDigestCursor(agent string, c int64) error

SetDigestCursor advances the cursor.

func (*Tx) SetFields

func (t *Tx) SetFields(id string, f Fields) error

SetFields updates columns without a state change (holds, not_before).

func (*Tx) SetKV

func (t *Tx) SetKV(k, v string) error

KV helpers for small daemon state.

func (*Tx) SetPresenceTurn

func (t *Tx) SetPresenceTurn(session, turn string) error

SetPresenceTurn sets one session's turn (after Smif typed a prompt).

func (*Tx) SetThreadBranch

func (t *Tx) SetThreadBranch(id, agent, branch string) error

SetThreadBranch records the worktree branch used by a thread.

func (*Tx) Transition

func (t *Tx) Transition(id string, to State, f Fields, detail map[string]any, from ...State) (*Message, error)

Transition moves a message from its current state to `to`, applying fields, and appends an audit row. It fails with ErrIllegal if the state machine forbids the move, and with a mismatch error if the current state is not one of `from` (when given).

func (*Tx) UpsertPresence

func (t *Tx) UpsertPresence(repo, session, state string, u PresenceUpdate) error

UpsertPresence records a hook or status-line heartbeat.

Jump to

Keyboard shortcuts

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