Documentation
¶
Overview ¶
Package db provides the SQLite persistence layer for mnemo.
All indexed sessions and messages are stored in ~/.mnemo/mnemo.db using pure-Go SQLite (modernc.org/sqlite, no CGO required). The schema includes:
- messages table with FTS5 virtual table for full-text search
- sessions table linking messages to projects and tools
- token_usage table for per-request cost tracking
- projects table for directory-based project management
FTS5 triggers automatically keep the search index in sync with inserts, updates, and deletes on the messages table.
Index ¶
- Constants
- func AddProjectManually(path string) error
- func ClassifyProjects() error
- func ClearIndex() error
- func CloseDB()
- func DeleteProject(path string) error
- func GetAPICredentials() ([]string, error)
- func GetDB() *sql.DB
- func GetProjectsForOnboarding() (active []Project, inactive []Project, err error)
- func GetRecentSessions(limit int) ([]map[string]interface{}, error)
- func GetStats() (int, int, error)
- func GetTokenStatsByProvider(days int) (map[string]TokenStats, error)
- func GetUsageByToolForActiveBlock(provider string) ([]ToolUsageStats, *SessionBlock, error)
- func GetUsageStats() (map[string]interface{}, error)
- func GetUsageStatsByModel() (map[string]map[string]interface{}, error)
- func GetUsageStatsByTool() (map[string]map[string]interface{}, error)
- func InitDB() error
- func InsertMessage(msg Message) error
- func InsertSession(sess Session) error
- func InsertSessionSimple(id, project, firstQuery, filePath, tool string, msgCount int) error
- func InsertTokenUsage(usage TokenUsage) error
- func MergeProjects(oldPath, newPath string) (int, int, error)
- func OpenReadOnlySQLite(path string) (*sql.DB, error)
- func PruneStaleProjects() (int, error)
- func SetAPICredential(provider string) error
- func SetProjectUserEnabled(path string, enabled bool) error
- func UpdateSessionTokens(sessionID string, inputTokens, outputTokens, cacheRead, cacheWrite int, ...) error
- func UpsertProject(path string, lastActivity time.Time) error
- type Message
- type Project
- type SearchResult
- type Session
- type SessionBlock
- func (b SessionBlock) CostPerHour() float64
- func (b SessionBlock) DurationMinutes() float64
- func (b SessionBlock) ProjectedCost() float64
- func (b SessionBlock) ProjectedTokens() int
- func (b SessionBlock) RemainingTime() time.Duration
- func (b SessionBlock) TokensPerMinute() float64
- func (b SessionBlock) TotalTokens() int
- type SessionMatch
- type TokenStats
- type TokenUsage
- type ToolUsageStats
- type UsageEntry
Constants ¶
const ( ProjectStatusActive = "active" ProjectStatusInactive = "inactive" ProjectStatusArchived = "archived" )
const SessionDurationHours = 5
SessionDurationHours is Claude's rate limit reset window
Variables ¶
This section is empty.
Functions ¶
func AddProjectManually ¶
func ClassifyProjects ¶
func ClassifyProjects() error
ClassifyProjects updates project status based on last_activity recency: active (<60 days), inactive (60-90 days), archived (>90 days).
func ClearIndex ¶
func ClearIndex() error
func DeleteProject ¶
func GetAPICredentials ¶
func GetRecentSessions ¶
func GetTokenStatsByProvider ¶
func GetTokenStatsByProvider(days int) (map[string]TokenStats, error)
func GetUsageByToolForActiveBlock ¶
func GetUsageByToolForActiveBlock(provider string) ([]ToolUsageStats, *SessionBlock, error)
GetUsageByToolForActiveBlock returns per-tool usage for the current 5-hour block
func GetUsageStats ¶
func GetUsageStatsByModel ¶
func GetUsageStatsByTool ¶
func InitDB ¶
func InitDB() error
InitDB opens (or creates) the mnemo database at ~/.mnemo/mnemo.db and applies the schema and any pending migrations. Uses WAL mode for concurrent read access.
func InsertMessage ¶
func InsertSession ¶
func InsertSessionSimple ¶
func InsertTokenUsage ¶
func InsertTokenUsage(usage TokenUsage) error
InsertTokenUsage records a single API request's token usage and updates the parent session's aggregate totals.
func MergeProjects ¶
MergeProjects moves all session/message history from oldPath to newPath. Used when a project directory is relocated on the filesystem.
func PruneStaleProjects ¶
func SetAPICredential ¶
func SetProjectUserEnabled ¶
func UpdateSessionTokens ¶
Types ¶
type Message ¶
type Message struct {
ID int64
SessionID string
Project string
Role string
Content string
Timestamp time.Time
Tool string
Model string
Provider string
InputTokens int
OutputTokens int
CacheReadTokens int
CacheWriteTokens int
ReasoningTokens int
CostUSD float64
MessageUUID string
ParentUUID string
WorkingDirectory string
Agent string
Date string
}
Message represents a single message within an AI coding session.
type Project ¶
type Project struct {
ID int64
Path string
Name string
LastActivity time.Time
Status string
UserEnabled bool
CreatedAt time.Time
}
Project represents a tracked development directory. Projects are auto-discovered from working_directory fields in indexed sessions and classified by recency: active (<60 days), inactive (60-90 days), or archived (>90 days).
func GetEnabledProjects ¶
func GetProjectByPath ¶
func GetProjects ¶
func GetProjectsByStatus ¶
type SearchResult ¶
type SearchResult struct {
SessionID string
Project string
Role string
Content string
Snippet string
Rank float64
Tool string
Model string
Provider string
}
SearchResult holds a single FTS5 search match with BM25 ranking. Snippet contains the matched text with >>> and <<< delimiters for highlighting.
type Session ¶
type Session struct {
ID string
Project string
FirstQuery string
MessageCount int
Tool string
FilePath string
IndexedAt time.Time
Model string
Provider string
TotalInputTokens int
TotalOutputTokens int
TotalCacheRead int
TotalCacheWrite int
TotalReasoningTokens int
TotalCostUSD float64
CLIVersion string
GitBranch string
WorkingDirectory string
StartTime time.Time
EndTime time.Time
Agent string
Date string
}
Session aggregates all messages from a single AI coding conversation. The ID is typically derived from the source tool's session identifier.
type SessionBlock ¶
type SessionBlock struct {
ID string
StartTime time.Time
EndTime time.Time // StartTime + 5 hours
ActualEndTime time.Time // Last activity within block
IsActive bool // Currently within this block's time window
IsGap bool // No activity during this period
InputTokens int
OutputTokens int
CacheRead int
CacheWrite int
CostUSD float64
Models []string
Providers []string
SessionCount int
MessageCount int
ResetTime *time.Time // From Claude error messages (if available)
}
SessionBlock represents a 5-hour usage window (matching Claude's rate limit reset)
func GetActiveBlock ¶
func GetActiveBlock() (*SessionBlock, error)
GetActiveBlock returns the current 5-hour block (if any activity exists)
func GetRecentBlocks ¶
func GetRecentBlocks(count int) ([]SessionBlock, error)
GetRecentBlocks returns the last N blocks
func GetSessionBlocks ¶
func GetSessionBlocks(days int) ([]SessionBlock, error)
GetSessionBlocks returns identified 5-hour blocks for a time range
func IdentifySessionBlocks ¶
func IdentifySessionBlocks(entries []UsageEntry) []SessionBlock
IdentifySessionBlocks groups usage entries into 5-hour windows This mirrors ccusage's _session-blocks.ts logic
func (SessionBlock) CostPerHour ¶
func (b SessionBlock) CostPerHour() float64
CostPerHour calculates hourly burn rate
func (SessionBlock) DurationMinutes ¶
func (b SessionBlock) DurationMinutes() float64
DurationMinutes returns minutes of actual activity
func (SessionBlock) ProjectedCost ¶
func (b SessionBlock) ProjectedCost() float64
ProjectedCost estimates cost at end of 5-hour window
func (SessionBlock) ProjectedTokens ¶
func (b SessionBlock) ProjectedTokens() int
ProjectedTokens estimates tokens at end of 5-hour window
func (SessionBlock) RemainingTime ¶
func (b SessionBlock) RemainingTime() time.Duration
RemainingTime returns time left in block
func (SessionBlock) TokensPerMinute ¶
func (b SessionBlock) TokensPerMinute() float64
TokensPerMinute calculates burn rate
func (SessionBlock) TotalTokens ¶
func (b SessionBlock) TotalTokens() int
TotalTokens returns sum of all token types
type SessionMatch ¶
type SessionMatch struct {
SessionID string
Project string
FirstQuery string
MessageCount int
Tool string
StartTime time.Time
MatchCount int
BestRank float64
FinalScore float64
Snippet string
SnippetRole string
}
SessionMatch holds a session-level search result with aggregated scoring. This is the primary return type for the redesigned search system.
func SearchGrouped ¶
func SearchGrouped(query string, limit int) ([]SessionMatch, error)
SearchGrouped performs a session-level search with intelligent ranking. Fetches message-level FTS5 results, groups by session in Go, then enriches with session metadata. Ranked by BM25 * temporal_decay * density_bonus.
type TokenStats ¶
type TokenStats struct {
TotalInputTokens int
TotalOutputTokens int
TotalCacheRead int
TotalCacheWrite int
TotalTokens int
TotalCostUSD float64
SessionCount int
}
func GetTokenStats ¶
func GetTokenStats(days int) (TokenStats, error)
type TokenUsage ¶
type ToolUsageStats ¶
type ToolUsageStats struct {
Tool string
Provider string
InputTokens int
OutputTokens int
CacheRead int
CacheWrite int
TotalTokens int
SessionCount int
}
ToolUsageStats represents token usage from a specific tool
func GetUsageByToolInWindow ¶
func GetUsageByToolInWindow(provider string, windowStart, windowEnd time.Time) ([]ToolUsageStats, error)
GetUsageByToolInWindow returns token usage grouped by tool for a provider within a specific time window (e.g., current 5-hour block)
type UsageEntry ¶
type UsageEntry struct {
SessionID string
Timestamp time.Time
Model string
Provider string
InputTokens int
OutputTokens int
CacheReadTokens int
CacheWriteTokens int
CostUSD float64
}
UsageEntry represents a single token usage record for block identification
func GetUsageEntries ¶
func GetUsageEntries(days int) ([]UsageEntry, error)
GetUsageEntries fetches token usage records for block identification. Falls back to the sessions table if the token_usage table is empty, which happens when data was indexed from session history rather than live-tracked via the proxy.