xonecas.io
6119
My

mysis / commit 894507d

feat: add SQLite persistence for conversation history

- Add store package with SQLite database layer
- Session management (create/resume/list sessions)
- Persistent message history per session
- Multi-instance support with WAL mode (no conflicts)
- Session flags: --session <name> to resume/create named session
- List sessions: --list-sessions shows recent conversations
- Auto-save all messages (user, assistant, tool) to database
- Database stored at ~/.config/mysis/mysis.db

Schema:
- sessions table: id, name, provider, model, timestamps
- messages table: session_id, role, content, tool_calls, reasoning
- Unique session names (anonymous sessions allowed)

Dependencies added:
- github.com/mattn/go-sqlite3 v1.14.33
- github.com/google/uuid v1.6.0

Updated PROJECT_STRUCTURE.md with store documentation

xonecas2026-02-10 894507d0734e2dc841b2051cf9f75256bb05856a parent b4cfbef

5 files changed

cmd/mysis/main.go+163−17
@@ -8,12 +8,15 @@ import (
88 "fmt"
99 "os"
1010 "strings"
11+ "time"
1112
13+ "github.com/google/uuid"
1214 "github.com/rs/zerolog"
1315 "github.com/rs/zerolog/log"
1416 "github.com/xonecas/mysis/internal/config"
1517 "github.com/xonecas/mysis/internal/mcp"
1618 "github.com/xonecas/mysis/internal/provider"
19+ "github.com/xonecas/mysis/internal/store"
1720 "github.com/xonecas/mysis/internal/styles"
1821 )
1922
@@ -27,6 +30,8 @@ func main() {
2730 configPath = flag.String("config", "", "Path to config file")
2831 debug = flag.Bool("debug", false, "Enable debug logging")
2932 providerName = flag.String("p", "", "Provider name (overrides default from config)")
33+ sessionName = flag.String("session", "", "Session name (resume or create named session)")
34+ listSessions = flag.Bool("list-sessions", false, "List recent sessions and exit")
3035 )
3136 flag.Parse()
3237
@@ -75,6 +80,23 @@ func main() {
7580 os.Exit(1)
7681 }
7782
83+ // Open database
84+ db, err := store.Open()
85+ if err != nil {
86+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to open database: "+err.Error()))
87+ os.Exit(1)
88+ }
89+ defer db.Close()
90+
91+ // Handle --list-sessions flag
92+ if *listSessions {
93+ if err := listSessionsCmd(db); err != nil {
94+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
95+ os.Exit(1)
96+ }
97+ return
98+ }
99+
78100 // Load credentials
79101 creds, err := config.LoadCredentials()
80102 if err != nil {
@@ -139,21 +161,69 @@ func main() {
139161 log.Info().Int("count", len(tools)).Msg("Tools available")
140162 }
141163
164+ // Initialize or resume session
165+ var sessionID string
166+ var sessionInfo string
167+ if *sessionName != "" {
168+ // Try to resume by name
169+ sess, err := db.GetSessionByName(*sessionName)
170+ if err != nil {
171+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load session: "+err.Error()))
172+ os.Exit(1)
173+ }
174+ if sess != nil {
175+ sessionID = sess.ID
176+ sessionInfo = fmt.Sprintf("Resumed session: %s", *sessionName)
177+ log.Info().Str("session_id", sessionID).Str("name", *sessionName).Msg("Resumed session")
178+ } else {
179+ // Create new named session
180+ sessionID = uuid.New().String()
181+ if err := db.CreateSession(sessionID, selectedProvider, providerCfg.Model, sessionName); err != nil {
182+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
183+ os.Exit(1)
184+ }
185+ sessionInfo = fmt.Sprintf("New session: %s", *sessionName)
186+ log.Info().Str("session_id", sessionID).Str("name", *sessionName).Msg("Created named session")
187+ }
188+ } else {
189+ // Create anonymous session
190+ sessionID = uuid.New().String()
191+ if err := db.CreateSession(sessionID, selectedProvider, providerCfg.Model, nil); err != nil {
192+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
193+ os.Exit(1)
194+ }
195+ sessionInfo = fmt.Sprintf("Session: %s", sessionID[:8])
196+ log.Info().Str("session_id", sessionID).Msg("Created anonymous session")
197+ }
198+
199+ // Load message history
200+ history, err := db.LoadMessages(sessionID)
201+ if err != nil {
202+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load history: "+err.Error()))
203+ os.Exit(1)
204+ }
205+ if len(history) > 0 {
206+ log.Info().Int("count", len(history)).Msg("Loaded message history")
207+ }
208+
142209 // Print welcome message
143210 fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗"))
144- fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
211+ fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
145212 fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝"))
146213 fmt.Println()
147214 fmt.Println(styles.Muted.Render(fmt.Sprintf("Provider: %s (%s)", selectedProvider, providerCfg.Model)))
148215 fmt.Println(styles.Muted.Render(fmt.Sprintf("Tools: %d available", len(tools))))
216+ fmt.Println(styles.Muted.Render(sessionInfo))
149217 fmt.Println()
150218
151219 // Start conversation loop
152220 app := &App{
153- provider: prov,
154- proxy: proxy,
155- tools: tools,
156- history: []provider.Message{},
221+ provider: prov,
222+ proxy: proxy,
223+ tools: tools,
224+ history: history,
225+ db: db,
226+ sessionID: sessionID,
157227 }
158228
159229 if err := app.Run(ctx); err != nil {
@@ -164,10 +234,12 @@ func main() {
164234
165235 // App holds the application state
166236 type App struct {
167- provider provider.Provider
168- proxy *mcp.Proxy
169- tools []mcp.Tool
170- history []provider.Message
237+ provider provider.Provider
238+ proxy *mcp.Proxy
239+ tools []mcp.Tool
240+ history []provider.Message
241+ db *store.Store
242+ sessionID string
171243 }
172244
173245 // Run starts the conversation loop
@@ -195,10 +267,16 @@ func (app *App) Run(ctx context.Context) error {
195267 }
196268
197269 // Add user message to history
198- app.history = append(app.history, provider.Message{
270+ userMsg := provider.Message{
199271 Role: "user",
200272 Content: input,
201- })
273+ }
274+ app.history = append(app.history, userMsg)
275+
276+ // Save user message
277+ if err := app.db.SaveMessage(app.sessionID, userMsg); err != nil {
278+ log.Warn().Err(err).Msg("Failed to save user message")
279+ }
202280
203281 // Process turn (may involve multiple LLM calls if tools are used)
204282 if err := app.processTurn(ctx); err != nil {
@@ -214,7 +292,7 @@ func (app *App) Run(ctx context.Context) error {
214292
215293 // processTurn handles one conversation turn, which may involve tool calls
216294 func (app *App) processTurn(ctx context.Context) error {
217- maxToolRounds := 10 // Prevent infinite loops
295+ maxToolRounds := 20 // Prevent infinite loops
218296
219297 for round := 0; round < maxToolRounds; round++ {
220298 // Convert MCP tools to provider format
@@ -245,7 +323,7 @@ func (app *App) processTurn(ctx context.Context) error {
245323 }
246324
247325 // Add assistant response to history
248- app.history = append(app.history, provider.Message{
326+ app.addMessage(provider.Message{
249327 Role: "assistant",
250328 Content: resp.Content,
251329 })
@@ -254,7 +332,7 @@ func (app *App) processTurn(ctx context.Context) error {
254332 }
255333
256334 // Tool calls present - add assistant message with tool calls to history
257- app.history = append(app.history, provider.Message{
335+ app.addMessage(provider.Message{
258336 Role: "assistant",
259337 Content: resp.Content,
260338 ToolCalls: resp.ToolCalls,
@@ -283,7 +361,7 @@ func (app *App) processTurn(ctx context.Context) error {
283361 fmt.Println(styles.Error.Render(" Error: " + err.Error()))
284362
285363 // Add error result to history
286- app.history = append(app.history, provider.Message{
364+ app.addMessage(provider.Message{
287365 Role: "tool",
288366 Content: fmt.Sprintf("Error: %v", err),
289367 ToolCallID: toolCall.ID,
@@ -306,7 +384,7 @@ func (app *App) processTurn(ctx context.Context) error {
306384 }
307385
308386 // Add error result to history
309- app.history = append(app.history, provider.Message{
387+ app.addMessage(provider.Message{
310388 Role: "tool",
311389 Content: errText,
312390 ToolCallID: toolCall.ID,
@@ -334,7 +412,7 @@ func (app *App) processTurn(ctx context.Context) error {
334412 }
335413
336414 // Add tool result to history
337- app.history = append(app.history, provider.Message{
415+ app.addMessage(provider.Message{
338416 Role: "tool",
339417 Content: resultText,
340418 ToolCallID: toolCall.ID,
@@ -347,6 +425,74 @@ func (app *App) processTurn(ctx context.Context) error {
347425 return fmt.Errorf("too many tool call rounds (limit: %d)", maxToolRounds)
348426 }
349427
428+// addMessage adds a message to history and saves it to the database.
429+func (app *App) addMessage(msg provider.Message) {
430+ app.history = append(app.history, msg)
431+ if err := app.db.SaveMessage(app.sessionID, msg); err != nil {
432+ log.Warn().Err(err).Msg("Failed to save message to database")
433+ }
434+}
435+
436+// listSessionsCmd lists recent sessions.
437+func listSessionsCmd(db *store.Store) error {
438+ sessions, err := db.ListSessions(20)
439+ if err != nil {
440+ return fmt.Errorf("list sessions: %w", err)
441+ }
442+
443+ if len(sessions) == 0 {
444+ fmt.Println("No sessions found")
445+ return nil
446+ }
447+
448+ fmt.Println(styles.Brand.Render("Recent Sessions:"))
449+ fmt.Println()
450+
451+ for _, sess := range sessions {
452+ fmt.Printf("%s ", styles.Muted.Render(sess.ID[:8]))
453+
454+ if sess.Name != nil {
455+ fmt.Print(styles.BrandBold.Render(*sess.Name))
456+ } else {
457+ fmt.Print(styles.Muted.Render("(anonymous)"))
458+ }
459+
460+ fmt.Printf(" - %s (%s)\n", sess.Provider, sess.Model)
461+
462+ elapsed := time.Since(sess.LastActiveAt)
463+ fmt.Printf(" %s\n", styles.Muted.Render(formatDuration(elapsed)+" ago"))
464+ fmt.Println()
465+ }
466+
467+ return nil
468+}
469+
470+// formatDuration formats a duration in human-readable form.
471+func formatDuration(d time.Duration) string {
472+ if d < time.Minute {
473+ return "just now"
474+ }
475+ if d < time.Hour {
476+ mins := int(d.Minutes())
477+ if mins == 1 {
478+ return "1 minute"
479+ }
480+ return fmt.Sprintf("%d minutes", mins)
481+ }
482+ if d < 24*time.Hour {
483+ hours := int(d.Hours())
484+ if hours == 1 {
485+ return "1 hour"
486+ }
487+ return fmt.Sprintf("%d hours", hours)
488+ }
489+ days := int(d.Hours() / 24)
490+ if days == 1 {
491+ return "1 day"
492+ }
493+ return fmt.Sprintf("%d days", days)
494+}
495+
350496 // initializeProviders creates and registers all configured providers
351497 func initializeProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry {
352498 registry := provider.NewRegistry()
documentation/architecture/PROJECT_STRUCTURE.md+47−8
@@ -13,6 +13,7 @@ mysis/
1313 │ ├── constants/ # Application constants
1414 │ ├── mcp/ # MCP client and proxy (from zoea-nova)
1515 │ ├── provider/ # LLM provider abstraction (from zoea-nova)
16+│ ├── store/ # SQLite persistence for conversation history
1617 │ └── styles/ # UI styling with brand colors
1718 ├── assets/
1819 │ └── logos/ # Branding assets (from zoea-nova)
@@ -64,7 +65,7 @@ LLM provider abstraction with:
6465 Configuration management with:
6566 - TOML config file parsing
6667 - Credentials handling
67-- Data directory management
68+- Data directory management (`~/.config/mysis`)
6869 - Provider configuration
6970
7071 **Files:**
@@ -72,25 +73,41 @@ Configuration management with:
7273 - `credentials.go` - Secure credential handling
7374 - Tests
7475
75-### 4. Brand Assets
76+### 4. Store Package (`internal/store/`)
77+SQLite persistence layer for conversation history:
78+- Session management (create, resume, list)
79+- Message storage with tool calls and reasoning
80+- Multi-instance support (no locking conflicts)
81+- WAL mode for concurrent access
82+
83+**Database Schema:**
84+- `sessions` - Conversation sessions with provider info
85+- `messages` - Message history per session
86+- Stored at `~/.config/mysis/mysis.db`
87+
88+**Files:**
89+- `store.go` - Database operations and schema
90+
91+### 5. Brand Assets
7692 - Logo files (SVG format)
7793 - Brand colors: #9D00FF (electric purple), #00FFCC (bright teal)
7894 - Style definitions in `internal/styles/styles.go`
7995
80-### 5. Configuration
96+### 6. Configuration
8197 - `config.toml` with provider definitions
8298 - Support for Ollama (local) and OpenCode Zen (cloud)
8399 - MCP upstream configuration
84100
85101 ## Technology Stack
86102
87-Inherited from zoea-nova:
88-- **Go 1.24.2** - Programming language
89-- **Bubble Tea** - TUI framework (dependency ready)
103+Core dependencies:
104+- **Go 1.25.6** - Programming language
105+- **SQLite 3** - Conversation persistence (`github.com/mattn/go-sqlite3`)
106+- **UUID** - Session IDs (`github.com/google/uuid`)
90107 - **Lipgloss** - Terminal styling
91-- **go-openai** - OpenAI-compatible API client
108+- **go-openai** - OpenAI-compatible API client (`github.com/sashabaranov/go-openai`)
92109 - **zerolog** - Structured logging
93-- **TOML** - Configuration format
110+- **TOML** - Configuration format (`github.com/BurntSushi/toml`)
94111
95112 ## Brand Colors
96113
@@ -112,9 +129,31 @@ This is a scaffold with reusable infrastructure. Implementation of application-s
112129 4. Build TUI components using the established brand styling
113130 5. Add tests following the patterns from zoea-nova
114131
132+## Data Storage
133+
134+**Config Directory:** `~/.config/mysis/`
135+- `config.toml` - Configuration file (optional, falls back to `./config.toml`)
136+- `credentials.json` - API keys (mode 0600)
137+- `mysis.db` - SQLite database for conversation history
138+- `account-backup.md` - Backup of SpaceMolt test accounts
139+
140+**Session Management:**
141+- Each CLI instance creates a unique session (UUID)
142+- Sessions can be named for easy resumption: `--session my-session`
143+- Anonymous sessions get auto-generated IDs
144+- Multiple instances can run concurrently without conflicts
145+
146+**Database Features:**
147+- WAL mode for concurrent read/write
148+- Automatic schema initialization
149+- Full conversation history (user, assistant, tool messages)
150+- Tool calls stored as JSON
151+- Session metadata (provider, model, timestamps)
152+
115153 ## Notes
116154
117155 - All import paths updated from `github.com/xonecas/zoea-nova` to `github.com/xonecas/mysis`
118156 - The MCP client is configured to connect to `https://game.spacemolt.com/mcp`
119157 - Provider configurations support both local (Ollama) and cloud (OpenCode Zen) models
120158 - The project maintains the retro-futuristic aesthetic from zoea-nova
159+- Config directory changed from `~/.mysis` to `~/.config/mysis` (XDG Base Directory standard)
go.mod+2−0
@@ -5,6 +5,8 @@ go 1.25.6
55 require (
66 github.com/BurntSushi/toml v1.6.0
77 github.com/charmbracelet/lipgloss v1.1.0
8+ github.com/google/uuid v1.6.0
9+ github.com/mattn/go-sqlite3 v1.14.33
810 github.com/rs/zerolog v1.34.0
911 github.com/sashabaranov/go-openai v1.41.2
1012 )
go.sum+4−0
@@ -14,6 +14,8 @@ github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQ
1414 github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
1515 github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
1616 github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
17+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
18+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
1719 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
1820 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
1921 github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
@@ -24,6 +26,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
2426 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
2527 github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
2628 github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
29+github.com/mattn/go-sqlite3 v1.14.33 h1:A5blZ5ulQo2AtayQ9/limgHEkFreKj1Dv226a1K73s0=
30+github.com/mattn/go-sqlite3 v1.14.33/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
2731 github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
2832 github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
2933 github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
internal/store/store.go+304−0
@@ -0,0 +1,304 @@
1+// Package store provides SQLite persistence for conversation history.
2+package store
3+
4+import (
5+ "database/sql"
6+ "encoding/json"
7+ "fmt"
8+ "path/filepath"
9+ "time"
10+
11+ _ "github.com/mattn/go-sqlite3"
12+ "github.com/xonecas/mysis/internal/config"
13+ "github.com/xonecas/mysis/internal/provider"
14+)
15+
16+// Store handles database operations.
17+type Store struct {
18+ db *sql.DB
19+}
20+
21+// Session represents a conversation session.
22+type Session struct {
23+ ID string
24+ Name *string
25+ Provider string
26+ Model string
27+ CreatedAt time.Time
28+ LastActiveAt time.Time
29+}
30+
31+// Message represents a stored message.
32+type Message struct {
33+ ID int64
34+ SessionID string
35+ Role string
36+ Content string
37+ ToolCallID *string
38+ ToolCalls []provider.ToolCall
39+ Reasoning *string
40+ CreatedAt time.Time
41+}
42+
43+// Open opens the database connection and ensures schema exists.
44+func Open() (*Store, error) {
45+ dataDir, err := config.EnsureDataDir()
46+ if err != nil {
47+ return nil, fmt.Errorf("ensure data dir: %w", err)
48+ }
49+
50+ dbPath := filepath.Join(dataDir, "mysis.db")
51+ db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL")
52+ if err != nil {
53+ return nil, fmt.Errorf("open database: %w", err)
54+ }
55+
56+ store := &Store{db: db}
57+ if err := store.initSchema(); err != nil {
58+ db.Close()
59+ return nil, fmt.Errorf("init schema: %w", err)
60+ }
61+
62+ return store, nil
63+}
64+
65+// Close closes the database connection.
66+func (s *Store) Close() error {
67+ return s.db.Close()
68+}
69+
70+// initSchema creates tables if they don't exist.
71+func (s *Store) initSchema() error {
72+ // Create tables
73+ _, err := s.db.Exec(`
74+ CREATE TABLE IF NOT EXISTS sessions (
75+ id TEXT PRIMARY KEY,
76+ name TEXT UNIQUE,
77+ provider TEXT NOT NULL,
78+ model TEXT NOT NULL,
79+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
80+ last_active_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
81+ );
82+
83+ CREATE TABLE IF NOT EXISTS messages (
84+ id INTEGER PRIMARY KEY AUTOINCREMENT,
85+ session_id TEXT NOT NULL,
86+ role TEXT NOT NULL,
87+ content TEXT NOT NULL,
88+ tool_call_id TEXT,
89+ tool_calls TEXT,
90+ reasoning TEXT,
91+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
92+ FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
93+ );
94+
95+ CREATE INDEX IF NOT EXISTS idx_messages_session
96+ ON messages(session_id, created_at);
97+ `)
98+ return err
99+}
100+
101+// CreateSession creates a new session.
102+func (s *Store) CreateSession(id, provider, model string, name *string) error {
103+ query := `
104+ INSERT INTO sessions (id, name, provider, model, created_at, last_active_at)
105+ VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
106+ `
107+ _, err := s.db.Exec(query, id, name, provider, model)
108+ if err != nil {
109+ return fmt.Errorf("create session: %w", err)
110+ }
111+ return nil
112+}
113+
114+// GetSession retrieves a session by ID.
115+func (s *Store) GetSession(id string) (*Session, error) {
116+ query := `
117+ SELECT id, name, provider, model, created_at, last_active_at
118+ FROM sessions
119+ WHERE id = ?
120+ `
121+
122+ var sess Session
123+ var name sql.NullString
124+ err := s.db.QueryRow(query, id).Scan(
125+ &sess.ID,
126+ &name,
127+ &sess.Provider,
128+ &sess.Model,
129+ &sess.CreatedAt,
130+ &sess.LastActiveAt,
131+ )
132+ if err == sql.ErrNoRows {
133+ return nil, nil
134+ }
135+ if err != nil {
136+ return nil, fmt.Errorf("get session: %w", err)
137+ }
138+
139+ if name.Valid {
140+ sess.Name = &name.String
141+ }
142+
143+ return &sess, nil
144+}
145+
146+// GetSessionByName retrieves a session by name.
147+func (s *Store) GetSessionByName(name string) (*Session, error) {
148+ query := `
149+ SELECT id, name, provider, model, created_at, last_active_at
150+ FROM sessions
151+ WHERE name = ?
152+ `
153+
154+ var sess Session
155+ var nameVal sql.NullString
156+ err := s.db.QueryRow(query, name).Scan(
157+ &sess.ID,
158+ &nameVal,
159+ &sess.Provider,
160+ &sess.Model,
161+ &sess.CreatedAt,
162+ &sess.LastActiveAt,
163+ )
164+ if err == sql.ErrNoRows {
165+ return nil, nil
166+ }
167+ if err != nil {
168+ return nil, fmt.Errorf("get session by name: %w", err)
169+ }
170+
171+ if nameVal.Valid {
172+ sess.Name = &nameVal.String
173+ }
174+
175+ return &sess, nil
176+}
177+
178+// ListSessions returns all sessions ordered by most recent.
179+func (s *Store) ListSessions(limit int) ([]Session, error) {
180+ query := `
181+ SELECT id, name, provider, model, created_at, last_active_at
182+ FROM sessions
183+ ORDER BY last_active_at DESC
184+ LIMIT ?
185+ `
186+
187+ rows, err := s.db.Query(query, limit)
188+ if err != nil {
189+ return nil, fmt.Errorf("list sessions: %w", err)
190+ }
191+ defer rows.Close()
192+
193+ var sessions []Session
194+ for rows.Next() {
195+ var sess Session
196+ var name sql.NullString
197+ if err := rows.Scan(
198+ &sess.ID,
199+ &name,
200+ &sess.Provider,
201+ &sess.Model,
202+ &sess.CreatedAt,
203+ &sess.LastActiveAt,
204+ ); err != nil {
205+ return nil, fmt.Errorf("scan session: %w", err)
206+ }
207+
208+ if name.Valid {
209+ sess.Name = &name.String
210+ }
211+
212+ sessions = append(sessions, sess)
213+ }
214+
215+ return sessions, rows.Err()
216+}
217+
218+// TouchSession updates the last_active_at timestamp.
219+func (s *Store) TouchSession(id string) error {
220+ query := `UPDATE sessions SET last_active_at = CURRENT_TIMESTAMP WHERE id = ?`
221+ _, err := s.db.Exec(query, id)
222+ return err
223+}
224+
225+// SaveMessage stores a message in the database.
226+func (s *Store) SaveMessage(sessionID string, msg provider.Message) error {
227+ // Marshal tool calls to JSON if present
228+ var toolCallsJSON *string
229+ if len(msg.ToolCalls) > 0 {
230+ data, err := json.Marshal(msg.ToolCalls)
231+ if err != nil {
232+ return fmt.Errorf("marshal tool calls: %w", err)
233+ }
234+ jsonStr := string(data)
235+ toolCallsJSON = &jsonStr
236+ }
237+
238+ // Handle optional fields
239+ var toolCallID *string
240+ if msg.ToolCallID != "" {
241+ toolCallID = &msg.ToolCallID
242+ }
243+
244+ query := `
245+ INSERT INTO messages (session_id, role, content, tool_call_id, tool_calls, reasoning)
246+ VALUES (?, ?, ?, ?, ?, NULL)
247+ `
248+ _, err := s.db.Exec(query, sessionID, msg.Role, msg.Content, toolCallID, toolCallsJSON)
249+ if err != nil {
250+ return fmt.Errorf("save message: %w", err)
251+ }
252+
253+ // Touch session to update last_active_at
254+ return s.TouchSession(sessionID)
255+}
256+
257+// LoadMessages retrieves all messages for a session.
258+func (s *Store) LoadMessages(sessionID string) ([]provider.Message, error) {
259+ query := `
260+ SELECT role, content, tool_call_id, tool_calls, reasoning
261+ FROM messages
262+ WHERE session_id = ?
263+ ORDER BY created_at ASC
264+ `
265+
266+ rows, err := s.db.Query(query, sessionID)
267+ if err != nil {
268+ return nil, fmt.Errorf("load messages: %w", err)
269+ }
270+ defer rows.Close()
271+
272+ var messages []provider.Message
273+ for rows.Next() {
274+ var msg provider.Message
275+ var toolCallID sql.NullString
276+ var toolCallsJSON sql.NullString
277+ var reasoning sql.NullString
278+
279+ if err := rows.Scan(&msg.Role, &msg.Content, &toolCallID, &toolCallsJSON, &reasoning); err != nil {
280+ return nil, fmt.Errorf("scan message: %w", err)
281+ }
282+
283+ if toolCallID.Valid {
284+ msg.ToolCallID = toolCallID.String
285+ }
286+
287+ if toolCallsJSON.Valid {
288+ if err := json.Unmarshal([]byte(toolCallsJSON.String), &msg.ToolCalls); err != nil {
289+ return nil, fmt.Errorf("unmarshal tool calls: %w", err)
290+ }
291+ }
292+
293+ messages = append(messages, msg)
294+ }
295+
296+ return messages, rows.Err()
297+}
298+
299+// DeleteSession deletes a session and all its messages.
300+func (s *Store) DeleteSession(id string) error {
301+ query := `DELETE FROM sessions WHERE id = ?`
302+ _, err := s.db.Exec(query, id)
303+ return err
304+}