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
- Variables
- func Allowed(from, to State) bool
- func Int(i int) *int
- func Str(s string) *string
- func Time(t time.Time) *time.Time
- type AuditRow
- type Fields
- type Message
- type Presence
- type PresenceUpdate
- type QueueItem
- type Run
- type RunEnd
- type SessionAsk
- type State
- type Store
- func (s *Store) ActivePresence(repo string, ttl time.Duration) ([]Presence, error)
- func (s *Store) AllPresence() ([]Presence, error)
- func (s *Store) AuditFor(msgID string) ([]AuditRow, error)
- func (s *Store) AuditHead() (int64, error)
- func (s *Store) AuditSince(seq int64, limit int) ([]AuditRow, error)
- func (s *Store) AuditTail(n int) ([]AuditRow, error)
- func (s *Store) AuditWhere(where string, args ...any) ([]AuditRow, error)
- func (s *Store) BlobInfo(sha string) (size int64, mime string, err error)
- func (s *Store) Close() error
- func (s *Store) DB() *sql.DB
- func (s *Store) DigestCursor(agent string) int64
- func (s *Store) ExpiredBlobs(cutoff time.Time) ([]string, error)
- func (s *Store) FindMessage(ref string) (*Message, error)
- func (s *Store) GetKV(k string) string
- func (s *Store) GetMessage(id string) (*Message, error)
- func (s *Store) GetRun(id string) (*Run, error)
- func (s *Store) Messages(where string, args ...any) ([]*Message, error)
- func (s *Store) Now() time.Time
- func (s *Store) QueueItem(id int64) (*QueueItem, error)
- func (s *Store) QueueItems(sessionID string) ([]QueueItem, error)
- func (s *Store) QueuedItems() ([]QueueItem, error)
- func (s *Store) Runs(where string, args ...any) ([]*Run, error)
- func (s *Store) SessionAsk(messageID string) (*SessionAsk, error)
- func (s *Store) SessionAsks(sessionID string, limit int) ([]SessionAsk, error)
- func (s *Store) SetClock(f func() time.Time)
- func (s *Store) SetRunProcess(id string, pid, pgid int, transcript string) error
- func (s *Store) SetRunSession(id, session string) error
- func (s *Store) ThreadBranch(thread, agent string) string
- func (s *Store) Update(f func(*Tx) error) error
- func (s *Store) Usage(agent, day string) (cost float64, tokens int64)
- func (s *Store) Version() int
- type Thread
- type Tx
- func (t *Tx) AddQueued(i QueueItem) (int64, error)
- func (t *Tx) AddUsage(agent, day string, cost float64, tokens int64) error
- func (t *Tx) Audit(event, agent, msgID, runID, threadID string, detail map[string]any) error
- func (t *Tx) Coalesce(m *Message, dup *envelope.Envelope) error
- func (t *Tx) CountPair(thread, a, b string, since time.Time) (int, error)
- func (t *Tx) CountThread(id string) (int, error)
- func (t *Tx) DeleteBlob(sha string) error
- func (t *Tx) Exec(q string, args ...any) (sql.Result, error)
- func (t *Tx) FinishRun(id string, e RunEnd) error
- func (t *Tx) FreezeThread(id, reason string) error
- func (t *Tx) GetMessage(id string) (*Message, error)
- func (t *Tx) GetRun(id string) (*Run, error)
- func (t *Tx) GetThread(id string) (*Thread, error)
- func (t *Tx) InsertMessage(e *envelope.Envelope, recurrence bool) error
- func (t *Tx) InsertRun(r *Run) error
- func (t *Tx) InsertSessionAsk(messageID, sessionID, cwd string) error
- func (t *Tx) LastDoneByDedupe(to, key string, since time.Time) (*Message, error)
- func (t *Tx) MarkSeen(id string) error
- func (t *Tx) Messages(where string, args ...any) ([]*Message, error)
- func (t *Tx) Now() time.Time
- func (t *Tx) OpenByDedupe(to, key string) (*Message, error)
- func (t *Tx) PutBlob(sha string, size int64, mime string) error
- func (t *Tx) QueryRow(q string, args ...any) *sql.Row
- func (t *Tx) QueueMove(i QueueItem, from, to, why string) (bool, error)
- func (t *Tx) QueueNote(id int64, why string) error
- func (t *Tx) QueueRefused(i QueueItem, why string) error
- func (t *Tx) ResetCoalesced(id string) error
- func (t *Tx) Runs(where string, args ...any) ([]*Run, error)
- func (t *Tx) SessionAskTx(messageID string) (*SessionAsk, error)
- func (t *Tx) SetDigestCursor(agent string, c int64) error
- func (t *Tx) SetFields(id string, f Fields) error
- func (t *Tx) SetKV(k, v string) error
- func (t *Tx) SetPresenceTurn(session, turn string) error
- func (t *Tx) SetThreadBranch(id, agent, branch string) error
- func (t *Tx) Transition(id string, to State, f Fields, detail map[string]any, from ...State) (*Message, error)
- func (t *Tx) UpsertPresence(repo, session, state string, u PresenceUpdate) error
Constants ¶
const ( RunRunning = "running" RunSucceeded = "succeeded" RunNeedsHuman = "needs_human" RunFailed = "failed" RunTimeout = "timeout" RunKilled = "killed" RunOrphaned = "orphaned" RunCancelled = "cancelled" )
Run states.
const ( QueueQueued = "queued" QueueSent = "sent" QueueCancelled = "cancelled" QueueExpired = "expired" QueueGone = "gone" )
States of a queue item.
Variables ¶
var AllStates = []State{Accepted, Queued, Running, RetryWait, NeedsHuman, Done, Rejected, Expired, DeadLetter}
AllStates lists every state.
var ErrIllegal = errors.New("illegal state transition")
ErrIllegal is returned for a transition the state machine forbids.
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a row does not exist.
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 ¶
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
// AttachID is the id for `claude attach`, set only on a background
// session, which has no tab (ADR-0021; from discovery, not stored).
AttachID 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 QueueItem ¶ added in v0.2.0
type QueueItem struct {
ID int64
SessionID, Agent, Name, Text string
CreatedAt time.Time
State, Error string
}
QueueItem is one prompt in the queue.
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 ¶
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.
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 (*Store) ActivePresence ¶
ActivePresence returns live sessions for repo newer than ttl.
func (*Store) AllPresence ¶
AllPresence returns every stored session, newest first.
func (*Store) AuditSince ¶
AuditSince returns audit rows after seq (for tail).
func (*Store) AuditWhere ¶
AuditWhere returns audit rows matching a condition.
func (*Store) DigestCursor ¶
DigestCursor returns an agent's digest cursor.
func (*Store) ExpiredBlobs ¶
ExpiredBlobs returns blobs unreferenced since before cutoff.
func (*Store) FindMessage ¶
FindMessage resolves an id or a unique suffix of one.
func (*Store) GetMessage ¶
GetMessage reads a message.
func (*Store) Messages ¶
Messages runs a query returning message rows. where is appended after WHERE.
func (*Store) QueueItems ¶ added in v0.2.0
QueueItems returns the items of a session in every state, oldest first.
func (*Store) QueuedItems ¶ added in v0.2.0
QueuedItems returns the items still queued, oldest first.
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) SetRunProcess ¶
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 ¶
SetRunSession records the claude session id as soon as it is known.
func (*Store) ThreadBranch ¶
ThreadBranch returns the branch recorded for (thread, agent).
type Tx ¶
type Tx struct {
// contains filtered or unexported fields
}
Tx is a write transaction.
func (*Tx) AddQueued ¶ added in v0.2.0
AddQueued writes a queued item and its audit row. The audit keeps the length, never the text.
func (*Tx) CountPair ¶
CountPair counts messages in a thread between two agents (either direction) created at or after since.
func (*Tx) CountThread ¶
CountThread returns how many messages a thread has.
func (*Tx) FreezeThread ¶
FreezeThread marks a thread frozen.
func (*Tx) GetMessage ¶
GetMessage reads a message inside the transaction.
func (*Tx) InsertMessage ¶
InsertMessage stores a new message in state accepted and audits it.
func (*Tx) InsertSessionAsk ¶
InsertSessionAsk records that message id is answered by a fork of session.
func (*Tx) LastDoneByDedupe ¶
LastDoneByDedupe returns the newest done message to `to` with the key that finished after `since`.
func (*Tx) OpenByDedupe ¶
OpenByDedupe returns a non-terminal (and not needs_human) message to `to` with the dedupe key.
func (*Tx) QueueMove ¶ added in v0.2.0
QueueMove changes the state of an item and writes the audit row in the same transaction. It reports false, and changes nothing, when the item is no longer in state from. A move that queueMoves does not allow is an error.
func (*Tx) QueueNote ¶ added in v0.2.0
QueueNote keeps why a sent item started no turn. The sent audit row exists already, and deliverPrompt audits session.prompt_unsent.
func (*Tx) QueueRefused ¶ added in v0.2.0
QueueRefused keeps why an item did not go. The state stays, so the audit row comes only when the reason changes (a refusal can repeat every 30 s for a day).
func (*Tx) ResetCoalesced ¶
ResetCoalesced zeroes the counter (used after a recurrence is created).
func (*Tx) SessionAskTx ¶
func (t *Tx) SessionAskTx(messageID string) (*SessionAsk, error)
SessionAskTx returns the session ask of a message, or nil.
func (*Tx) SetDigestCursor ¶
SetDigestCursor advances the cursor.
func (*Tx) SetPresenceTurn ¶
SetPresenceTurn sets one session's turn (after Smif typed a prompt).
func (*Tx) SetThreadBranch ¶
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.