Documentation
¶
Index ¶
- Constants
- Variables
- func EncodeCursor(cursor *Cursor) (string, error)
- func GenerateAPITokenValue() (string, error)
- type APICall
- type APIToken
- type ApprovalAllowRule
- type ApprovalPolicy
- type AuthSession
- type BatchWriter
- type CLITicket
- type Cursor
- type Event
- type EventType
- type FileRecord
- type ImportRecord
- type Message
- type MessageSearchResult
- type Migration
- type Observer
- type ObserverFunc
- type PendingApproval
- type PreparedStatements
- type PushSubscription
- type ScratchpadEntry
- type Session
- type SessionSkill
- type SessionStats
- type Store
- func (s *Store) AddApprovalAllowRule(rule *ApprovalAllowRule) error
- func (s *Store) AddObserver(observer Observer)
- func (s *Store) AnalyzeDatabase() error
- func (s *Store) ApproveCLITicket(id string, principal, scope, tokenID, sessionToken string) error
- func (s *Store) CleanupExpiredAuthSessions(now time.Time) (int64, error)
- func (s *Store) CleanupExpiredCLITickets(now time.Time) (int64, error)
- func (s *Store) Close() error
- func (s *Store) ConsumeCLITicket(id string) error
- func (s *Store) CountActiveAuthSessions(now time.Time) (int, error)
- func (s *Store) CountPendingApprovals(sessionID string) (int, error)
- func (s *Store) CountPendingCLITickets(now time.Time) (int, error)
- func (s *Store) CreateAPIToken(name, owner, scope, secret string) (*APIToken, error)
- func (s *Store) CreateAuthSession(id, principal, scope, tokenID string, expires time.Time) error
- func (s *Store) CreateCLITicket(id, secret, label string, expires time.Time) error
- func (s *Store) CreateCheckpoint(checkpoint *TodoCheckpoint) error
- func (s *Store) CreatePendingApproval(approval *PendingApproval) error
- func (s *Store) CreatePushSubscription(principal, endpoint, p256dh, auth, userAgent string) (string, error)
- func (s *Store) CreateSession(session *Session) error
- func (s *Store) CreateTodo(todo *Todo) error
- func (s *Store) DB() *sql.DB
- func (s *Store) DeactivateAllSessionSkills(sessionID string) error
- func (s *Store) DeactivateSessionSkill(sessionID, skillName string) error
- func (s *Store) DeleteAuthSession(id string) error
- func (s *Store) DeleteFileRecord(ctx context.Context, filePath string) error
- func (s *Store) DeletePushSubscription(id string) error
- func (s *Store) DeletePushSubscriptionByEndpoint(endpoint string) error
- func (s *Store) DeleteSession(sessionID string) error
- func (s *Store) DeleteSessionToken(sessionID string) error
- func (s *Store) DeleteTodos(sessionID string) error
- func (s *Store) EnsureSession(sessionID string) error
- func (s *Store) ExpirePendingApprovals() (int, error)
- func (s *Store) ExportAPITokens() ([]byte, error)
- func (s *Store) GetActivePolicy() (*ApprovalPolicy, error)
- func (s *Store) GetActiveSessionSkills(sessionID string) ([]SessionSkill, error)
- func (s *Store) GetActiveTodo(sessionID string) (*Todo, error)
- func (s *Store) GetAllFileChecksums(ctx context.Context) (map[string]string, error)
- func (s *Store) GetAllMessages(sessionID string) ([]Message, error)
- func (s *Store) GetAuditLog(sessionID string, limit int) ([]*ToolAuditEntry, error)
- func (s *Store) GetAuthSession(id string) (*AuthSession, error)
- func (s *Store) GetCLITicket(id string) (*CLITicket, error)
- func (s *Store) GetDailyCost() (float64, error)
- func (s *Store) GetDatabaseStats() (map[string]any, error)
- func (s *Store) GetLatestCheckpoint(sessionID string) (*TodoCheckpoint, error)
- func (s *Store) GetLatestMessageByRole(sessionID, role string) (*Message, error)
- func (s *Store) GetMessages(sessionID string, limit int, offset int) ([]Message, error)
- func (s *Store) GetMessagesMissingEmbeddings(ctx context.Context, sessionID string, limit int) ([]Message, error)
- func (s *Store) GetMessagesWithCursor(sessionID string, cursor *Cursor, limit int) ([]Message, *Cursor, error)
- func (s *Store) GetMessagesWithEmbeddings(ctx context.Context, sessionID string) ([]Message, error)
- func (s *Store) GetMessagesWithSessions(sessionIDs []string) (map[string][]Message, error)
- func (s *Store) GetMigrationHistory() ([]struct{ ... }, error)
- func (s *Store) GetMonthlyCost() (float64, error)
- func (s *Store) GetPendingApproval(id string) (*PendingApproval, error)
- func (s *Store) GetPolicy(id int64) (*ApprovalPolicy, error)
- func (s *Store) GetPushSubscription(id string) (*PushSubscription, error)
- func (s *Store) GetPushSubscriptionByEndpoint(endpoint string) (*PushSubscription, error)
- func (s *Store) GetPushSubscriptionsByPrincipal(principal string) ([]*PushSubscription, error)
- func (s *Store) GetRecentMessagesByRole(role string, limit int) ([]Message, error)
- func (s *Store) GetSchemaVersion() (int, error)
- func (s *Store) GetScratchpadEntry(ctx context.Context, key string) (*ScratchpadEntry, error)
- func (s *Store) GetSession(sessionID string) (*Session, error)
- func (s *Store) GetSessionPlanID(sessionID string) (string, error)
- func (s *Store) GetSessionSkillHistory(sessionID string) ([]SessionSkill, error)
- func (s *Store) GetSessionStats(sessionID string) (*SessionStats, error)
- func (s *Store) GetSessionSummary(sessionID string) (string, error)
- func (s *Store) GetSettings(keys []string) (map[string]string, error)
- func (s *Store) GetTodoByID(id int64) (*Todo, error)
- func (s *Store) GetTodoSummary(sessionID string) (*TodoSummary, error)
- func (s *Store) GetTodos(sessionID string) ([]Todo, error)
- func (s *Store) GetVAPIDKeys() (*VAPIDKeys, error)
- func (s *Store) GetVAPIDPublicKey() (string, error)
- func (s *Store) LinkSessionToPlan(sessionID, planID string) error
- func (s *Store) ListAPITokens() ([]APIToken, error)
- func (s *Store) ListApprovalAllowRules(projectPath string) ([]*ApprovalAllowRule, error)
- func (s *Store) ListAuditLogs(limit int) ([]map[string]any, error)
- func (s *Store) ListPendingApprovals(sessionID string) ([]*PendingApproval, error)
- func (s *Store) ListPlanIDsForPrincipal(principal string) (map[string]struct{}, error)
- func (s *Store) ListPolicies() ([]*ApprovalPolicy, error)
- func (s *Store) ListPushSubscriptions() ([]*PushSubscription, error)
- func (s *Store) ListScratchpadEntries(ctx context.Context, limit int) ([]ScratchpadEntry, error)
- func (s *Store) ListScratchpadEntriesByType(ctx context.Context, entryType string, limit int) ([]ScratchpadEntry, error)
- func (s *Store) ListSessionSummaries() (map[string]string, error)
- func (s *Store) ListSessions(limit int) ([]Session, error)
- func (s *Store) ListSessionsByRepo(repoPath string) ([]Session, error)
- func (s *Store) LogToolExecution(entry *ToolAuditEntry) error
- func (s *Store) NewBatchWriter(maxSize int, maxWait time.Duration) *BatchWriter
- func (s *Store) OptimizeDatabase() error
- func (s *Store) PrepareStatements() (*PreparedStatements, error)
- func (s *Store) PrincipalHasPlan(principal, planID string) (bool, error)
- func (s *Store) RecordAuditLog(actor, scope, action string, payload any) error
- func (s *Store) ReplaceImports(ctx context.Context, filePath string, imports []ImportRecord) error
- func (s *Store) ReplaceMessages(sessionID string, messages []Message) error
- func (s *Store) ReplaceSymbols(ctx context.Context, filePath string, symbols []SymbolRecord) error
- func (s *Store) RevokeAPIToken(id string) error
- func (s *Store) SaveAPICall(call *APICall) error
- func (s *Store) SaveMessage(msg *Message) error
- func (s *Store) SaveMessageEmbedding(ctx context.Context, messageID int64, embedding []byte) error
- func (s *Store) SaveMessagesBatch(messages []*Message) error
- func (s *Store) SavePolicy(policy *ApprovalPolicy) error
- func (s *Store) SavePushSubscription(sub *PushSubscription) error
- func (s *Store) SaveSessionSkill(sessionID, skillName, activatedBy, scope string) error
- func (s *Store) SaveSessionSummary(sessionID, summary string) error
- func (s *Store) SaveSessionToken(sessionID, token string) error
- func (s *Store) SaveVAPIDKeys(publicKey, privateKey string) error
- func (s *Store) SearchFiles(ctx context.Context, query, pathGlob string, limit int) ([]FileRecord, error)
- func (s *Store) SearchMessagesFTS(ctx context.Context, query, sessionID string, limit int) ([]MessageSearchResult, error)
- func (s *Store) SearchSymbols(ctx context.Context, symbol, pathGlob string, limit int) ([]SymbolRecord, error)
- func (s *Store) SetSessionStatus(sessionID string, status string) error
- func (s *Store) SetSetting(key, value string) error
- func (s *Store) TouchAuthSession(id string) error
- func (s *Store) UpdatePendingApproval(approval *PendingApproval) error
- func (s *Store) UpdateSessionActivity(sessionID string) error
- func (s *Store) UpdateSessionPauseState(sessionID string, reason, question string, pausedAt *time.Time) error
- func (s *Store) UpdateSessionProjectPath(sessionID, projectPath string) error
- func (s *Store) UpdateSessionStats(sessionID string, messageCount, totalTokens int, totalCost float64) error
- func (s *Store) UpdateTodoStatus(id int64, status string, errorMessage string) error
- func (s *Store) UpsertFileRecord(ctx context.Context, rec *FileRecord) error
- func (s *Store) UpsertScratchpadEntry(ctx context.Context, entry ScratchpadEntry) (ScratchpadEntry, error)
- func (s *Store) VacuumDatabase() error
- func (s *Store) ValidateAPIToken(secret string) (*APIToken, error)
- func (s *Store) ValidateSessionToken(sessionID, token string) (bool, error)
- type SymbolRecord
- type Todo
- type TodoCheckpoint
- type TodoSummary
- type ToolAuditEntry
- type VAPIDKeys
Constants ¶
const ( TokenScopeOperator = "operator" TokenScopeMember = "member" TokenScopeViewer = "viewer" )
const ( SessionStatusActive = "active" SessionStatusPaused = "paused" SessionStatusCompleted = "completed" )
Session status constants.
Variables ¶
var ErrStoreClosed = errors.New("storage: closed")
ErrStoreClosed indicates the underlying database connection is unavailable.
Functions ¶
func EncodeCursor ¶
EncodeCursor encodes a cursor to a base64 string for API use.
func GenerateAPITokenValue ¶
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 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 ¶
type Cursor ¶
Cursor represents a pagination cursor for efficient message retrieval. Uses ID and Timestamp for stable pagination even with concurrent writes.
func DecodeCursor ¶
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 ¶
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 ¶
MessageSearchResult captures a full-text search hit.
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 ¶
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 ¶
AddObserver registers a new observer that will receive storage events.
func (*Store) AnalyzeDatabase ¶
AnalyzeDatabase updates query planner statistics
func (*Store) ApproveCLITicket ¶
func (*Store) CleanupExpiredAuthSessions ¶
func (*Store) CleanupExpiredCLITickets ¶
func (*Store) ConsumeCLITicket ¶
func (*Store) CountActiveAuthSessions ¶
func (*Store) CountPendingApprovals ¶
CountPendingApprovals returns the count of pending approvals for a session
func (*Store) CountPendingCLITickets ¶
func (*Store) CreateAPIToken ¶
CreateAPIToken stores a new API token record, hashing the provided secret.
func (*Store) CreateAuthSession ¶
func (*Store) CreateCLITicket ¶
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 ¶
CreateSession creates a new session with retry logic for database locks.
func (*Store) CreateTodo ¶
CreateTodo creates a new TODO item
func (*Store) DeactivateAllSessionSkills ¶
DeactivateAllSessionSkills marks all skills as inactive for a session
func (*Store) DeactivateSessionSkill ¶
DeactivateSessionSkill marks a skill as inactive for a session
func (*Store) DeleteAuthSession ¶
func (*Store) DeleteFileRecord ¶
DeleteFileRecord removes a file and its associated symbols/imports from the index.
func (*Store) DeletePushSubscription ¶
DeletePushSubscription removes a subscription by ID.
func (*Store) DeletePushSubscriptionByEndpoint ¶
DeletePushSubscriptionByEndpoint removes a subscription by endpoint.
func (*Store) DeleteSession ¶
DeleteSession deletes a session and all related data (cascades to messages, api_calls).
func (*Store) DeleteSessionToken ¶
DeleteSessionToken removes any stored token for the session.
func (*Store) DeleteTodos ¶
DeleteTodos deletes all TODOs for a session
func (*Store) EnsureSession ¶
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 ¶
ExpirePendingApprovals marks expired approvals as expired
func (*Store) ExportAPITokens ¶
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 ¶
GetActiveTodo returns the currently in_progress TODO
func (*Store) GetAllFileChecksums ¶
GetAllFileChecksums returns a map of file path to checksum for all indexed files.
func (*Store) GetAllMessages ¶
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) GetDailyCost ¶
GetDailyCost returns the total API cost accrued today.
func (*Store) GetDatabaseStats ¶
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 ¶
GetLatestMessageByRole returns the most recent message for a role in a session.
func (*Store) GetMessages ¶
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 ¶
GetMessagesWithEmbeddings returns messages with stored embeddings.
func (*Store) GetMessagesWithSessions ¶
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 ¶
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 ¶
GetRecentMessagesByRole returns the most recent messages for a role across sessions.
func (*Store) GetSchemaVersion ¶
GetSchemaVersion returns the current schema version for external use
func (*Store) GetScratchpadEntry ¶
GetScratchpadEntry retrieves a scratchpad entry by key.
func (*Store) GetSession ¶
GetSession retrieves a session by ID.
func (*Store) GetSessionPlanID ¶
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 ¶
GetSessionSummary retrieves the last stored summary for a session.
func (*Store) GetSettings ¶
GetSettings loads settings for the provided keys.
func (*Store) GetTodoByID ¶
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) GetVAPIDKeys ¶
GetVAPIDKeys retrieves the VAPID keys.
func (*Store) GetVAPIDPublicKey ¶
GetVAPIDPublicKey returns only the public key for sharing with clients.
func (*Store) LinkSessionToPlan ¶
LinkSessionToPlan associates a session with the latest active plan so dashboards can hydrate plan state without waiting for telemetry events.
func (*Store) ListAPITokens ¶
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 ¶
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 (*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 ¶
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 ¶
ListSessionSummaries returns summaries for all sessions with stored summaries.
func (*Store) ListSessions ¶
ListSessions returns all sessions ordered by last active time.
func (*Store) ListSessionsByRepo ¶
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 ¶
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 (*Store) RecordAuditLog ¶
RecordAuditLog stores an operator action for later review.
func (*Store) ReplaceImports ¶
ReplaceImports replaces all imports for a given file.
func (*Store) ReplaceMessages ¶
ReplaceMessages replaces all messages for a session with the provided set.
func (*Store) ReplaceSymbols ¶
ReplaceSymbols replaces all symbols for a given file.
func (*Store) RevokeAPIToken ¶
RevokeAPIToken marks the token as revoked.
func (*Store) SaveAPICall ¶
SaveAPICall records an API call and updates the owning session's total cost.
func (*Store) SaveMessage ¶
SaveMessage persists a message and updates aggregate session stats.
func (*Store) SaveMessageEmbedding ¶
SaveMessageEmbedding updates a message row with its embedding bytes.
func (*Store) SaveMessagesBatch ¶
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 ¶
SaveSessionSkill saves or updates a skill activation in the database
func (*Store) SaveSessionSummary ¶
SaveSessionSummary stores a compacted session summary for cross-instance awareness.
func (*Store) SaveSessionToken ¶
SaveSessionToken stores or replaces the hashed session token for a session ID.
func (*Store) SaveVAPIDKeys ¶
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 ¶
SetSessionStatus updates the session status (active/paused/completed) and tracks completion timestamps.
func (*Store) SetSetting ¶
SetSetting upserts a setting value. Empty value deletes the row.
func (*Store) TouchAuthSession ¶
func (*Store) UpdatePendingApproval ¶
func (s *Store) UpdatePendingApproval(approval *PendingApproval) error
UpdatePendingApproval updates a pending approval's status
func (*Store) UpdateSessionActivity ¶
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 ¶
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 ¶
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 ¶
VacuumDatabase performs maintenance to reclaim space and optimize
func (*Store) ValidateAPIToken ¶
ValidateAPIToken verifies a token secret and updates last_used_at.
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
Source Files
¶
- api_call_store.go
- api_tokens.go
- approvals.go
- batch_writer.go
- cli_tickets.go
- embeddings_store.go
- events.go
- feature_sessions.go
- hash.go
- index.go
- memories_store.go
- message_embeddings.go
- message_store.go
- messages_search_store.go
- optimize.go
- push_subscriptions.go
- scratchpad_store.go
- session_store.go
- session_tokens.go
- settings.go
- skills.go
- sqlite.go
- summaries.go
- todo_store.go
- web_sessions.go