db

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 8 Imported by: 0

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

View Source
const (
	ProjectStatusActive   = "active"
	ProjectStatusInactive = "inactive"
	ProjectStatusArchived = "archived"
)
View Source
const SessionDurationHours = 5

SessionDurationHours is Claude's rate limit reset window

Variables

This section is empty.

Functions

func AddProjectManually

func AddProjectManually(path string) error

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 CloseDB

func CloseDB()

func DeleteProject

func DeleteProject(path string) error

func GetAPICredentials

func GetAPICredentials() ([]string, error)

func GetDB

func GetDB() *sql.DB

GetDB returns the package-level database connection. Must call InitDB first.

func GetProjectsForOnboarding

func GetProjectsForOnboarding() (active []Project, inactive []Project, err error)

func GetRecentSessions

func GetRecentSessions(limit int) ([]map[string]interface{}, error)

func GetStats

func GetStats() (int, int, error)

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 GetUsageStats() (map[string]interface{}, error)

func GetUsageStatsByModel

func GetUsageStatsByModel() (map[string]map[string]interface{}, error)

func GetUsageStatsByTool

func GetUsageStatsByTool() (map[string]map[string]interface{}, error)

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 InsertMessage(msg Message) error

func InsertSession

func InsertSession(sess Session) error

func InsertSessionSimple

func InsertSessionSimple(id, project, firstQuery, filePath, tool string, msgCount int) error

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

func MergeProjects(oldPath, newPath string) (int, int, error)

MergeProjects moves all session/message history from oldPath to newPath. Used when a project directory is relocated on the filesystem.

func OpenReadOnlySQLite

func OpenReadOnlySQLite(path string) (*sql.DB, error)

func PruneStaleProjects

func PruneStaleProjects() (int, error)

func SetAPICredential

func SetAPICredential(provider string) error

func SetProjectUserEnabled

func SetProjectUserEnabled(path string, enabled bool) error

func UpdateSessionTokens

func UpdateSessionTokens(sessionID string, inputTokens, outputTokens, cacheRead, cacheWrite int, costUSD float64, model, provider string) error

func UpsertProject

func UpsertProject(path string, lastActivity time.Time) error

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 GetEnabledProjects() ([]Project, error)

func GetProjectByPath

func GetProjectByPath(path string) (*Project, error)

func GetProjects

func GetProjects() ([]Project, error)

func GetProjectsByStatus

func GetProjectsByStatus(status string) ([]Project, error)

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.

func Search(query string, limit int) ([]SearchResult, error)

Search performs a full-text search using FTS5 with BM25 ranking. Results include highlighted snippets with >>> <<< delimiters.

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 TokenUsage struct {
	SessionID        string
	Model            string
	InputTokens      int
	OutputTokens     int
	CacheReadTokens  int
	CacheWriteTokens int
	TotalTokens      int
	CostUSD          float64
	Provider         string
	Timestamp        time.Time
}

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.

Jump to

Keyboard shortcuts

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