storage

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenScopeOperator = "operator"
	TokenScopeMember   = "member"
	TokenScopeViewer   = "viewer"
)
View Source
const (
	SessionStatusActive    = "active"
	SessionStatusPaused    = "paused"
	SessionStatusCompleted = "completed"
)

Session status constants.

Variables

View Source
var ErrStoreClosed = errors.New("storage: closed")

ErrStoreClosed indicates the underlying database connection is unavailable.

Functions

func EncodeCursor

func EncodeCursor(cursor *Cursor) (string, error)

EncodeCursor encodes a cursor to a base64 string for API use.

func GenerateAPITokenValue

func GenerateAPITokenValue() (string, error)

GenerateAPITokenValue creates a random token string suitable for CLI clients.

Types

type APICall

type APICall struct {
	ID               int64     `json:"id"`
	SessionID        string    `json:"sessionId"`
	Model            string    `json:"model"`
	PromptTokens     int       `json:"promptTokens"`
	CompletionTokens int       `json:"completionTokens"`
	Cost             float64   `json:"cost"`
	Timestamp        time.Time `json:"timestamp"`
}

APICall represents an API cost tracking record.

type APIToken

type APIToken struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	Owner      string     `json:"owner,omitempty"`
	Scope      string     `json:"scope"`
	Prefix     string     `json:"prefix"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
	Revoked    bool       `json:"revoked"`
}

APIToken represents an operator-managed API token.

type ApprovalAllowRule

type ApprovalAllowRule struct {
	ID          int64     `json:"id"`
	ProjectPath string    `json:"project_path"`
	ToolName    string    `json:"tool_name"`
	Operation   string    `json:"operation"`
	Command     string    `json:"command"`
	FilePath    string    `json:"file_path"`
	CreatedAt   time.Time `json:"created_at"`
}

ApprovalAllowRule represents a persisted rule for auto-approving tool calls.

type ApprovalPolicy

type ApprovalPolicy struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	IsActive  bool      `json:"is_active"`
	Config    string    `json:"config"` // JSON encoded policy config
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

ApprovalPolicy represents a stored approval policy

type AuthSession

type AuthSession struct {
	ID        string
	Principal string
	Scope     string
	TokenID   string
	ExpiresAt time.Time
	CreatedAt time.Time
}

type BatchWriter

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

BatchWriter provides asynchronous batching of message writes with automatic flushing based on batch size or timeout. This reduces transaction overhead when saving multiple messages in rapid succession.

Usage:

writer := store.NewBatchWriter(100, 100*time.Millisecond) defer writer.Close() writer.Add(msg) // messages are batched and flushed automatically

The writer is safe for concurrent use and handles errors by logging them and continuing to accept new messages.

func (*BatchWriter) Add

func (bw *BatchWriter) Add(msg *Message) error

Add adds a message to the batch. If the batch reaches maxSize, it is flushed immediately. Otherwise, a timer is started to flush after maxWait.

func (*BatchWriter) BatchSize

func (bw *BatchWriter) BatchSize() int

BatchSize returns the current number of messages in the batch.

func (*BatchWriter) Close

func (bw *BatchWriter) Close() error

Close stops the batch writer and flushes any remaining messages.

func (*BatchWriter) Flush

func (bw *BatchWriter) Flush() error

Flush manually flushes the current batch.

type CLITicket

type CLITicket struct {
	ID           string
	SecretHash   string
	Label        string
	Approved     bool
	Principal    string
	Scope        string
	TokenID      string
	SessionToken string
	CreatedAt    time.Time
	ExpiresAt    time.Time
	Consumed     bool
}

func (*CLITicket) MatchesSecret

func (t *CLITicket) MatchesSecret(secret string) bool

type Cursor

type Cursor struct {
	ID        int64     `json:"id"`
	Timestamp time.Time `json:"timestamp"`
}

Cursor represents a pagination cursor for efficient message retrieval. Uses ID and Timestamp for stable pagination even with concurrent writes.

func DecodeCursor

func DecodeCursor(encoded string) (*Cursor, error)

DecodeCursor decodes a base64 string to a cursor.

type Event

type Event struct {
	Type      EventType `json:"type"`
	SessionID string    `json:"sessionId,omitempty"`
	EntityID  string    `json:"entityId,omitempty"`
	Data      any       `json:"data,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

Event represents a change inside the storage layer that other subsystems can react to.

type EventType

type EventType string

EventType represents the type of storage event emitted.

const (
	EventSessionCreated EventType = "session.created"
	EventSessionUpdated EventType = "session.updated"
	EventSessionDeleted EventType = "session.deleted"

	EventMessageCreated EventType = "message.created"

	EventTodoCreated EventType = "todo.created"
	EventTodoUpdated EventType = "todo.updated"
	EventTodoDeleted EventType = "todo.deleted"
	EventTodoCleared EventType = "todo.cleared"

	EventSkillActivated   EventType = "skill.activated"
	EventSkillDeactivated EventType = "skill.deactivated"

	EventApprovalCreated EventType = "approval.created"
	EventApprovalDecided EventType = "approval.decided"
	EventApprovalExpired EventType = "approval.expired"
)

Storage event type constants.

type FileRecord

type FileRecord struct {
	Path      string
	Checksum  string
	Language  string
	SizeBytes int64
	Summary   string
	UpdatedAt time.Time
}

FileRecord represents indexed file metadata.

type ImportRecord

type ImportRecord struct {
	FilePath   string
	ImportPath string
}

ImportRecord represents an import discovered in a file.

type Message

type Message struct {
	ID          int64     `json:"id"`
	SessionID   string    `json:"sessionId"`
	Role        string    `json:"role"`
	Content     string    `json:"content"`
	ContentJSON string    `json:"contentJson,omitempty"`
	ContentType string    `json:"contentType,omitempty"`
	Reasoning   string    `json:"reasoning,omitempty"` // Reasoning/thinking content for reasoning models
	Embedding   []byte    `json:"embedding,omitempty"`
	Timestamp   time.Time `json:"timestamp"`
	Tokens      int       `json:"tokens"`
	IsSummary   bool      `json:"isSummary"`
	IsTruncated bool      `json:"isTruncated"` // True if message was interrupted/incomplete
}

Message represents a conversation message stored for a session.

type MessageSearchResult

type MessageSearchResult struct {
	Message Message
	Snippet string
	Score   float64
}

MessageSearchResult captures a full-text search hit.

type Migration

type Migration struct {
	Version int
	Name    string
	Apply   func(db *sql.DB) error
}

Migration represents a database schema migration

type Observer

type Observer interface {
	HandleStorageEvent(Event)
}

Observer reacts to storage events.

type ObserverFunc

type ObserverFunc func(Event)

ObserverFunc is a helper to turn a function into an Observer.

func (ObserverFunc) HandleStorageEvent

func (f ObserverFunc) HandleStorageEvent(e Event)

HandleStorageEvent implements the Observer interface.

type PendingApproval

type PendingApproval struct {
	ID             string    `json:"id"`
	SessionID      string    `json:"session_id"`
	ToolName       string    `json:"tool_name"`
	ToolInput      string    `json:"tool_input"` // JSON encoded
	RiskScore      int       `json:"risk_score"`
	RiskReasons    []string  `json:"risk_reasons"`
	Status         string    `json:"status"` // pending, approved, rejected, expired, auto
	DecidedBy      string    `json:"decided_by,omitempty"`
	DecidedAt      time.Time `json:"decided_at,omitempty"`
	DecisionReason string    `json:"decision_reason,omitempty"`
	ExpiresAt      time.Time `json:"expires_at"`
	CreatedAt      time.Time `json:"created_at"`
}

PendingApproval represents a tool call awaiting approval

type PreparedStatements

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

PreparedStatements holds pre-compiled SQL statements for performance

func (*PreparedStatements) Close

func (ps *PreparedStatements) Close() error

Close closes all prepared statements

type PushSubscription

type PushSubscription struct {
	ID        string    `json:"id"`
	Endpoint  string    `json:"endpoint"`
	P256dh    string    `json:"p256dh"`
	Auth      string    `json:"auth"`
	Principal string    `json:"principal"`
	UserAgent string    `json:"userAgent,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
}

PushSubscription represents a Web Push subscription.

type ScratchpadEntry

type ScratchpadEntry struct {
	Key       string
	EntryType string
	Raw       []byte
	Summary   string
	Metadata  string
	CreatedBy string
	CreatedAt time.Time
	UpdatedAt time.Time
}

ScratchpadEntry represents a persisted RLM scratchpad entry.

type Session

type Session struct {
	ID           string     `json:"id"`
	Principal    string     `json:"principal,omitempty"`
	ProjectPath  string     `json:"projectPath,omitempty"`
	GitRepo      string     `json:"gitRepo,omitempty"`
	GitBranch    string     `json:"gitBranch,omitempty"`
	CreatedAt    time.Time  `json:"createdAt"`
	LastActive   time.Time  `json:"lastActive"`
	MessageCount int        `json:"messageCount"`
	TotalTokens  int        `json:"totalTokens"`
	TotalCost    float64    `json:"totalCost"`
	Status       string     `json:"status"`
	CompletedAt  *time.Time `json:"completedAt,omitempty"`
	// Pause state for workflow continuity
	PauseReason   string     `json:"pauseReason,omitempty"`
	PauseQuestion string     `json:"pauseQuestion,omitempty"`
	PausedAt      *time.Time `json:"pausedAt,omitempty"`
}

Session represents a conversation session persisted in SQLite.

type SessionSkill

type SessionSkill struct {
	ID            int64      `json:"id"`
	SessionID     string     `json:"sessionId"`
	SkillName     string     `json:"skillName"`
	ActivatedAt   time.Time  `json:"activatedAt"`
	ActivatedBy   string     `json:"activatedBy"` // "model"|"user"|"phase"
	Scope         string     `json:"scope"`
	IsActive      bool       `json:"isActive"`
	DeactivatedAt *time.Time `json:"deactivatedAt,omitempty"`
}

SessionSkill represents an active skill in a session

type SessionStats

type SessionStats struct {
	SessionID    string         `json:"sessionId"`
	MessageCount int            `json:"messageCount"`
	TotalTokens  int            `json:"totalTokens"`
	FirstMessage time.Time      `json:"firstMessage"`
	LastMessage  time.Time      `json:"lastMessage"`
	RoleCounts   map[string]int `json:"roleCounts,omitempty"`
}

SessionStats contains aggregated statistics for a session without loading all messages.

type Store

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

Store manages SQLite database operations

func New

func New(dbPath string) (*Store, error)

New creates a new Store backed by SQLite at the given path, initializing WAL mode, foreign keys, and all required tables.

func (*Store) AddApprovalAllowRule

func (s *Store) AddApprovalAllowRule(rule *ApprovalAllowRule) error

AddApprovalAllowRule persists an auto-approval rule (duplicates are ignored).

func (*Store) AddObserver

func (s *Store) AddObserver(observer Observer)

AddObserver registers a new observer that will receive storage events.

func (*Store) AnalyzeDatabase

func (s *Store) AnalyzeDatabase() error

AnalyzeDatabase updates query planner statistics

func (*Store) ApproveCLITicket

func (s *Store) ApproveCLITicket(id string, principal, scope, tokenID, sessionToken string) error

func (*Store) CleanupExpiredAuthSessions

func (s *Store) CleanupExpiredAuthSessions(now time.Time) (int64, error)

func (*Store) CleanupExpiredCLITickets

func (s *Store) CleanupExpiredCLITickets(now time.Time) (int64, error)

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection

func (*Store) ConsumeCLITicket

func (s *Store) ConsumeCLITicket(id string) error

func (*Store) CountActiveAuthSessions

func (s *Store) CountActiveAuthSessions(now time.Time) (int, error)

func (*Store) CountPendingApprovals

func (s *Store) CountPendingApprovals(sessionID string) (int, error)

CountPendingApprovals returns the count of pending approvals for a session

func (*Store) CountPendingCLITickets

func (s *Store) CountPendingCLITickets(now time.Time) (int, error)

func (*Store) CreateAPIToken

func (s *Store) CreateAPIToken(name, owner, scope, secret string) (*APIToken, error)

CreateAPIToken stores a new API token record, hashing the provided secret.

func (*Store) CreateAuthSession

func (s *Store) CreateAuthSession(id, principal, scope, tokenID string, expires time.Time) error

func (*Store) CreateCLITicket

func (s *Store) CreateCLITicket(id, secret, label string, expires time.Time) error

func (*Store) CreateCheckpoint

func (s *Store) CreateCheckpoint(checkpoint *TodoCheckpoint) error

CreateCheckpoint creates a checkpoint snapshot

func (*Store) CreatePendingApproval

func (s *Store) CreatePendingApproval(approval *PendingApproval) error

CreatePendingApproval creates a new pending approval

func (*Store) CreatePushSubscription

func (s *Store) CreatePushSubscription(principal, endpoint, p256dh, auth, userAgent string) (string, error)

CreatePushSubscription creates a new push subscription and returns the ID.

func (*Store) CreateSession

func (s *Store) CreateSession(session *Session) error

CreateSession creates a new session with retry logic for database locks.

func (*Store) CreateTodo

func (s *Store) CreateTodo(todo *Todo) error

CreateTodo creates a new TODO item

func (*Store) DB

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

DB returns the underlying database connection

func (*Store) DeactivateAllSessionSkills

func (s *Store) DeactivateAllSessionSkills(sessionID string) error

DeactivateAllSessionSkills marks all skills as inactive for a session

func (*Store) DeactivateSessionSkill

func (s *Store) DeactivateSessionSkill(sessionID, skillName string) error

DeactivateSessionSkill marks a skill as inactive for a session

func (*Store) DeleteAuthSession

func (s *Store) DeleteAuthSession(id string) error

func (*Store) DeleteFileRecord

func (s *Store) DeleteFileRecord(ctx context.Context, filePath string) error

DeleteFileRecord removes a file and its associated symbols/imports from the index.

func (*Store) DeletePushSubscription

func (s *Store) DeletePushSubscription(id string) error

DeletePushSubscription removes a subscription by ID.

func (*Store) DeletePushSubscriptionByEndpoint

func (s *Store) DeletePushSubscriptionByEndpoint(endpoint string) error

DeletePushSubscriptionByEndpoint removes a subscription by endpoint.

func (*Store) DeleteSession

func (s *Store) DeleteSession(sessionID string) error

DeleteSession deletes a session and all related data (cascades to messages, api_calls).

func (*Store) DeleteSessionToken

func (s *Store) DeleteSessionToken(sessionID string) error

DeleteSessionToken removes any stored token for the session.

func (*Store) DeleteTodos

func (s *Store) DeleteTodos(sessionID string) error

DeleteTodos deletes all TODOs for a session

func (*Store) EnsureSession

func (s *Store) EnsureSession(sessionID string) error

EnsureSession creates a minimal session record if it doesn't exist. This is used by the TODO tool to satisfy foreign key constraints.

func (*Store) ExpirePendingApprovals

func (s *Store) ExpirePendingApprovals() (int, error)

ExpirePendingApprovals marks expired approvals as expired

func (*Store) ExportAPITokens

func (s *Store) ExportAPITokens() ([]byte, error)

ExportAPITokens encodes token metadata for backups.

func (*Store) GetActivePolicy

func (s *Store) GetActivePolicy() (*ApprovalPolicy, error)

GetActivePolicy returns the currently active approval policy

func (*Store) GetActiveSessionSkills

func (s *Store) GetActiveSessionSkills(sessionID string) ([]SessionSkill, error)

GetActiveSessionSkills retrieves all active skills for a session

func (*Store) GetActiveTodo

func (s *Store) GetActiveTodo(sessionID string) (*Todo, error)

GetActiveTodo returns the currently in_progress TODO

func (*Store) GetAllFileChecksums

func (s *Store) GetAllFileChecksums(ctx context.Context) (map[string]string, error)

GetAllFileChecksums returns a map of file path to checksum for all indexed files.

func (*Store) GetAllMessages

func (s *Store) GetAllMessages(sessionID string) ([]Message, error)

GetAllMessages retrieves all messages for a session.

func (*Store) GetAuditLog

func (s *Store) GetAuditLog(sessionID string, limit int) ([]*ToolAuditEntry, error)

GetAuditLog returns the audit log for a session

func (*Store) GetAuthSession

func (s *Store) GetAuthSession(id string) (*AuthSession, error)

func (*Store) GetCLITicket

func (s *Store) GetCLITicket(id string) (*CLITicket, error)

func (*Store) GetDailyCost

func (s *Store) GetDailyCost() (float64, error)

GetDailyCost returns the total API cost accrued today.

func (*Store) GetDatabaseStats

func (s *Store) GetDatabaseStats() (map[string]any, error)

GetDatabaseStats returns database statistics

func (*Store) GetLatestCheckpoint

func (s *Store) GetLatestCheckpoint(sessionID string) (*TodoCheckpoint, error)

GetLatestCheckpoint retrieves the most recent checkpoint for a session

func (*Store) GetLatestMessageByRole

func (s *Store) GetLatestMessageByRole(sessionID, role string) (*Message, error)

GetLatestMessageByRole returns the most recent message for a role in a session.

func (*Store) GetMessages

func (s *Store) GetMessages(sessionID string, limit int, offset int) ([]Message, error)

GetMessages retrieves messages for a session using limit/offset pagination.

Recommended indexes for optimal performance:

CREATE INDEX idx_messages_session_time ON messages(session_id, timestamp);
CREATE INDEX idx_messages_session_role ON messages(session_id, role);

func (*Store) GetMessagesMissingEmbeddings

func (s *Store) GetMessagesMissingEmbeddings(ctx context.Context, sessionID string, limit int) ([]Message, error)

GetMessagesMissingEmbeddings returns messages without embeddings for a session.

func (*Store) GetMessagesWithCursor

func (s *Store) GetMessagesWithCursor(sessionID string, cursor *Cursor, limit int) ([]Message, *Cursor, error)

GetMessagesWithCursor retrieves messages for a session using cursor-based pagination. More efficient than offset pagination for large datasets as it uses index seek. Pass nil cursor to get the first page.

Recommended indexes for optimal performance:

CREATE INDEX idx_messages_session_time ON messages(session_id, timestamp);

func (*Store) GetMessagesWithEmbeddings

func (s *Store) GetMessagesWithEmbeddings(ctx context.Context, sessionID string) ([]Message, error)

GetMessagesWithEmbeddings returns messages with stored embeddings.

func (*Store) GetMessagesWithSessions

func (s *Store) GetMessagesWithSessions(sessionIDs []string) (map[string][]Message, error)

GetMessagesWithSessions retrieves messages for multiple sessions in a single query. This eliminates N+1 query problems when loading sessions with their messages. Returns a map of sessionID -> messages for that session.

Recommended indexes for optimal performance:

CREATE INDEX idx_messages_session_time ON messages(session_id, timestamp);

func (*Store) GetMigrationHistory

func (s *Store) GetMigrationHistory() ([]struct {
	Version   int
	Name      string
	AppliedAt string
}, error)

GetMigrationHistory returns the list of applied migrations

func (*Store) GetMonthlyCost

func (s *Store) GetMonthlyCost() (float64, error)

GetMonthlyCost returns the total API cost for the current month.

func (*Store) GetPendingApproval

func (s *Store) GetPendingApproval(id string) (*PendingApproval, error)

GetPendingApproval returns a pending approval by ID

func (*Store) GetPolicy

func (s *Store) GetPolicy(id int64) (*ApprovalPolicy, error)

GetPolicy returns a policy by ID

func (*Store) GetPushSubscription

func (s *Store) GetPushSubscription(id string) (*PushSubscription, error)

GetPushSubscription retrieves a subscription by ID.

func (*Store) GetPushSubscriptionByEndpoint

func (s *Store) GetPushSubscriptionByEndpoint(endpoint string) (*PushSubscription, error)

GetPushSubscriptionByEndpoint retrieves a subscription by endpoint.

func (*Store) GetPushSubscriptionsByPrincipal

func (s *Store) GetPushSubscriptionsByPrincipal(principal string) ([]*PushSubscription, error)

GetPushSubscriptionsByPrincipal retrieves all subscriptions for a principal.

func (*Store) GetRecentMessagesByRole

func (s *Store) GetRecentMessagesByRole(role string, limit int) ([]Message, error)

GetRecentMessagesByRole returns the most recent messages for a role across sessions.

func (*Store) GetSchemaVersion

func (s *Store) GetSchemaVersion() (int, error)

GetSchemaVersion returns the current schema version for external use

func (*Store) GetScratchpadEntry

func (s *Store) GetScratchpadEntry(ctx context.Context, key string) (*ScratchpadEntry, error)

GetScratchpadEntry retrieves a scratchpad entry by key.

func (*Store) GetSession

func (s *Store) GetSession(sessionID string) (*Session, error)

GetSession retrieves a session by ID.

func (*Store) GetSessionPlanID

func (s *Store) GetSessionPlanID(sessionID string) (string, error)

GetSessionPlanID returns the most recent plan attached to the session, or empty string if none.

func (*Store) GetSessionSkillHistory

func (s *Store) GetSessionSkillHistory(sessionID string) ([]SessionSkill, error)

GetSessionSkillHistory retrieves all skills (active and inactive) for a session

func (*Store) GetSessionStats

func (s *Store) GetSessionStats(sessionID string) (*SessionStats, error)

GetSessionStats retrieves aggregated statistics for a session without loading all messages. This is useful for displaying session metadata in list views.

Recommended indexes for optimal performance:

CREATE INDEX idx_messages_session_time ON messages(session_id, timestamp);
CREATE INDEX idx_messages_session_role ON messages(session_id, role);

func (*Store) GetSessionSummary

func (s *Store) GetSessionSummary(sessionID string) (string, error)

GetSessionSummary retrieves the last stored summary for a session.

func (*Store) GetSettings

func (s *Store) GetSettings(keys []string) (map[string]string, error)

GetSettings loads settings for the provided keys.

func (*Store) GetTodoByID

func (s *Store) GetTodoByID(id int64) (*Todo, error)

GetTodoByID returns a single TODO item by ID.

func (*Store) GetTodoSummary

func (s *Store) GetTodoSummary(sessionID string) (*TodoSummary, error)

GetTodoSummary returns aggregate todo counts for a session

func (*Store) GetTodos

func (s *Store) GetTodos(sessionID string) ([]Todo, error)

GetTodos retrieves all TODOs for a session ordered by order_index

func (*Store) GetVAPIDKeys

func (s *Store) GetVAPIDKeys() (*VAPIDKeys, error)

GetVAPIDKeys retrieves the VAPID keys.

func (*Store) GetVAPIDPublicKey

func (s *Store) GetVAPIDPublicKey() (string, error)

GetVAPIDPublicKey returns only the public key for sharing with clients.

func (*Store) LinkSessionToPlan

func (s *Store) LinkSessionToPlan(sessionID, planID string) error

LinkSessionToPlan associates a session with the latest active plan so dashboards can hydrate plan state without waiting for telemetry events.

func (*Store) ListAPITokens

func (s *Store) ListAPITokens() ([]APIToken, error)

ListAPITokens returns active and revoked tokens for operator review.

func (*Store) ListApprovalAllowRules

func (s *Store) ListApprovalAllowRules(projectPath string) ([]*ApprovalAllowRule, error)

ListApprovalAllowRules returns persisted allowlist rules for a project.

func (*Store) ListAuditLogs

func (s *Store) ListAuditLogs(limit int) ([]map[string]any, error)

ListAuditLogs returns recent audit entries.

func (*Store) ListPendingApprovals

func (s *Store) ListPendingApprovals(sessionID string) ([]*PendingApproval, error)

ListPendingApprovals returns pending approvals for a session

func (*Store) ListPlanIDsForPrincipal

func (s *Store) ListPlanIDsForPrincipal(principal string) (map[string]struct{}, error)

func (*Store) ListPolicies

func (s *Store) ListPolicies() ([]*ApprovalPolicy, error)

ListPolicies returns all approval policies

func (*Store) ListPushSubscriptions

func (s *Store) ListPushSubscriptions() ([]*PushSubscription, error)

ListPushSubscriptions retrieves all push subscriptions.

func (*Store) ListScratchpadEntries

func (s *Store) ListScratchpadEntries(ctx context.Context, limit int) ([]ScratchpadEntry, error)

ListScratchpadEntries returns scratchpad entries ordered by creation time (descending).

func (*Store) ListScratchpadEntriesByType

func (s *Store) ListScratchpadEntriesByType(ctx context.Context, entryType string, limit int) ([]ScratchpadEntry, error)

ListScratchpadEntriesByType returns scratchpad entries filtered by type, ordered by creation time (descending).

func (*Store) ListSessionSummaries

func (s *Store) ListSessionSummaries() (map[string]string, error)

ListSessionSummaries returns summaries for all sessions with stored summaries.

func (*Store) ListSessions

func (s *Store) ListSessions(limit int) ([]Session, error)

ListSessions returns all sessions ordered by last active time.

func (*Store) ListSessionsByRepo

func (s *Store) ListSessionsByRepo(repoPath string) ([]Session, error)

ListSessionsByRepo returns all sessions tied to a specific git repository/project path.

func (*Store) LogToolExecution

func (s *Store) LogToolExecution(entry *ToolAuditEntry) error

LogToolExecution logs a tool execution to the audit log

func (*Store) NewBatchWriter

func (s *Store) NewBatchWriter(maxSize int, maxWait time.Duration) *BatchWriter

NewBatchWriter creates a new batch writer with the specified batch size and maximum wait time. Messages are flushed when either maxSize messages have been accumulated or maxWait time has elapsed since the first message.

For a store-configured batch writer, use store.NewMessageBatchWriter().

func (*Store) OptimizeDatabase

func (s *Store) OptimizeDatabase() error

OptimizeDatabase adds indices and optimizes database settings

func (*Store) PrepareStatements

func (s *Store) PrepareStatements() (*PreparedStatements, error)

PrepareStatements pre-compiles common SQL statements

func (*Store) PrincipalHasPlan

func (s *Store) PrincipalHasPlan(principal, planID string) (bool, error)

func (*Store) RecordAuditLog

func (s *Store) RecordAuditLog(actor, scope, action string, payload any) error

RecordAuditLog stores an operator action for later review.

func (*Store) ReplaceImports

func (s *Store) ReplaceImports(ctx context.Context, filePath string, imports []ImportRecord) error

ReplaceImports replaces all imports for a given file.

func (*Store) ReplaceMessages

func (s *Store) ReplaceMessages(sessionID string, messages []Message) error

ReplaceMessages replaces all messages for a session with the provided set.

func (*Store) ReplaceSymbols

func (s *Store) ReplaceSymbols(ctx context.Context, filePath string, symbols []SymbolRecord) error

ReplaceSymbols replaces all symbols for a given file.

func (*Store) RevokeAPIToken

func (s *Store) RevokeAPIToken(id string) error

RevokeAPIToken marks the token as revoked.

func (*Store) SaveAPICall

func (s *Store) SaveAPICall(call *APICall) error

SaveAPICall records an API call and updates the owning session's total cost.

func (*Store) SaveMessage

func (s *Store) SaveMessage(msg *Message) error

SaveMessage persists a message and updates aggregate session stats.

func (*Store) SaveMessageEmbedding

func (s *Store) SaveMessageEmbedding(ctx context.Context, messageID int64, embedding []byte) error

SaveMessageEmbedding updates a message row with its embedding bytes.

func (*Store) SaveMessagesBatch

func (s *Store) SaveMessagesBatch(messages []*Message) error

SaveMessagesBatch efficiently saves multiple messages in a single transaction. This reduces database round-trips compared to calling SaveMessage for each message.

func (*Store) SavePolicy

func (s *Store) SavePolicy(policy *ApprovalPolicy) error

SavePolicy creates or updates an approval policy

func (*Store) SavePushSubscription

func (s *Store) SavePushSubscription(sub *PushSubscription) error

SavePushSubscription creates or updates a push subscription.

func (*Store) SaveSessionSkill

func (s *Store) SaveSessionSkill(sessionID, skillName, activatedBy, scope string) error

SaveSessionSkill saves or updates a skill activation in the database

func (*Store) SaveSessionSummary

func (s *Store) SaveSessionSummary(sessionID, summary string) error

SaveSessionSummary stores a compacted session summary for cross-instance awareness.

func (*Store) SaveSessionToken

func (s *Store) SaveSessionToken(sessionID, token string) error

SaveSessionToken stores or replaces the hashed session token for a session ID.

func (*Store) SaveVAPIDKeys

func (s *Store) SaveVAPIDKeys(publicKey, privateKey string) error

SaveVAPIDKeys saves the VAPID keys (single row, replaces if exists).

func (*Store) SearchFiles

func (s *Store) SearchFiles(ctx context.Context, query, pathGlob string, limit int) ([]FileRecord, error)

SearchFiles performs a basic LIKE search across file metadata.

func (*Store) SearchMessagesFTS

func (s *Store) SearchMessagesFTS(ctx context.Context, query, sessionID string, limit int) ([]MessageSearchResult, error)

SearchMessagesFTS runs a full-text search query against messages.

func (*Store) SearchSymbols

func (s *Store) SearchSymbols(ctx context.Context, symbol, pathGlob string, limit int) ([]SymbolRecord, error)

SearchSymbols finds symbols by name/path.

func (*Store) SetSessionStatus

func (s *Store) SetSessionStatus(sessionID string, status string) error

SetSessionStatus updates the session status (active/paused/completed) and tracks completion timestamps.

func (*Store) SetSetting

func (s *Store) SetSetting(key, value string) error

SetSetting upserts a setting value. Empty value deletes the row.

func (*Store) TouchAuthSession

func (s *Store) TouchAuthSession(id string) error

func (*Store) UpdatePendingApproval

func (s *Store) UpdatePendingApproval(approval *PendingApproval) error

UpdatePendingApproval updates a pending approval's status

func (*Store) UpdateSessionActivity

func (s *Store) UpdateSessionActivity(sessionID string) error

UpdateSessionActivity updates the last active timestamp.

func (*Store) UpdateSessionPauseState

func (s *Store) UpdateSessionPauseState(sessionID string, reason, question string, pausedAt *time.Time) error

UpdateSessionPauseState updates the pause state for a session. Pass empty strings for reason/question and nil for pausedAt to clear pause state.

func (*Store) UpdateSessionProjectPath

func (s *Store) UpdateSessionProjectPath(sessionID, projectPath string) error

UpdateSessionProjectPath updates the project path for a session.

func (*Store) UpdateSessionStats

func (s *Store) UpdateSessionStats(sessionID string, messageCount, totalTokens int, totalCost float64) error

UpdateSessionStats updates message count, tokens, and cost.

func (*Store) UpdateTodoStatus

func (s *Store) UpdateTodoStatus(id int64, status string, errorMessage string) error

UpdateTodoStatus updates the status of a TODO

func (*Store) UpsertFileRecord

func (s *Store) UpsertFileRecord(ctx context.Context, rec *FileRecord) error

UpsertFileRecord stores or updates metadata for a file.

func (*Store) UpsertScratchpadEntry

func (s *Store) UpsertScratchpadEntry(ctx context.Context, entry ScratchpadEntry) (ScratchpadEntry, error)

UpsertScratchpadEntry writes or updates a scratchpad entry.

func (*Store) VacuumDatabase

func (s *Store) VacuumDatabase() error

VacuumDatabase performs maintenance to reclaim space and optimize

func (*Store) ValidateAPIToken

func (s *Store) ValidateAPIToken(secret string) (*APIToken, error)

ValidateAPIToken verifies a token secret and updates last_used_at.

func (*Store) ValidateSessionToken

func (s *Store) ValidateSessionToken(sessionID, token string) (bool, error)

ValidateSessionToken compares the provided token against the stored hash.

type SymbolRecord

type SymbolRecord struct {
	FilePath  string
	Name      string
	Kind      string
	Signature string
	StartLine int
	EndLine   int
}

SymbolRecord represents a code symbol in a file.

type Todo

type Todo struct {
	ID           int64      `json:"id"`
	SessionID    string     `json:"sessionId"`
	Content      string     `json:"content"`
	ActiveForm   string     `json:"activeForm"`
	Status       string     `json:"status"`
	OrderIndex   int        `json:"orderIndex"`
	ParentID     *int64     `json:"parentId,omitempty"`
	CreatedAt    time.Time  `json:"createdAt"`
	UpdatedAt    time.Time  `json:"updatedAt"`
	CompletedAt  *time.Time `json:"completedAt,omitempty"`
	ErrorMessage string     `json:"errorMessage,omitempty"`
	Metadata     string     `json:"metadata,omitempty"`
}

Todo represents a task item

type TodoCheckpoint

type TodoCheckpoint struct {
	ID                  int64     `json:"id"`
	SessionID           string    `json:"sessionId"`
	CheckpointType      string    `json:"checkpointType"`
	TodoCount           int       `json:"todoCount"`
	CompletedCount      int       `json:"completedCount"`
	ConversationSummary string    `json:"conversationSummary"`
	ConversationTokens  int       `json:"conversationTokens"`
	CreatedAt           time.Time `json:"createdAt"`
	Metadata            string    `json:"metadata"`
}

TodoCheckpoint represents a checkpoint snapshot

type TodoSummary

type TodoSummary struct {
	Total     int `json:"total"`
	Completed int `json:"completed"`
	Pending   int `json:"pending"`
	Failed    int `json:"failed"`
}

TodoSummary contains aggregate counts for a session's todos

type ToolAuditEntry

type ToolAuditEntry struct {
	ID         int64     `json:"id"`
	SessionID  string    `json:"session_id"`
	ApprovalID string    `json:"approval_id,omitempty"`
	ToolName   string    `json:"tool_name"`
	ToolInput  string    `json:"tool_input"`
	ToolOutput string    `json:"tool_output,omitempty"`
	RiskScore  int       `json:"risk_score"`
	Decision   string    `json:"decision"`
	DecidedBy  string    `json:"decided_by,omitempty"`
	ExecutedAt time.Time `json:"executed_at"`
	DurationMs int64     `json:"duration_ms"`
}

ToolAuditEntry represents a logged tool execution

type VAPIDKeys

type VAPIDKeys struct {
	PublicKey  string    `json:"publicKey"`
	PrivateKey string    `json:"privateKey"`
	CreatedAt  time.Time `json:"createdAt"`
}

VAPIDKeys represents the VAPID key pair for Web Push.

Jump to

Keyboard shortcuts

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