Skip to content

Add SQLite-backed persistent session storage - #64

Merged
pavelanni merged 11 commits into
mainfrom
feature/sqlite-session-persistence
May 8, 2026
Merged

pavelanni merged 11 commits into
mainfrom
feature/sqlite-session-persistence

Conversation

@pavelanni

@pavelanni pavelanni commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Extract SessionStore interface from concrete in-memory store, enabling pluggable backends
  • Add SQLiteStore implementation using modernc.org/sqlite (pure Go, no CGo)
  • Sessions survive server restarts when backed by SQLite (default behavior)
  • Add --session-db flag and DOCSCLAW_SESSION_DB env var for store selection
  • Default path follows XDG spec ($XDG_DATA_HOME/docsclaw/sessions.db), works with K8s PVCs
  • Add --session-id flag to chat command for resuming previous sessions
  • Display session ID on chat exit for easy reconnection
  • Use --session-db memory to preserve previous in-memory behavior

Test plan

  • 21 unit tests pass (11 SQLiteStore + 10 MemoryStore)
  • Tool call/result JSON serialization roundtrip verified
  • Persistence across close/reopen verified
  • TTL-based reaper with CASCADE delete verified
  • Manual test: chat, kill server, restart, resume with --session-id — agent remembers context
  • Code review (Kimi)

Closes #5 (Phase 2)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added session resumption capability via --session-id flag, allowing users to resume previous chat sessions
    • Introduced SQLite-backed persistent session storage alongside existing in-memory storage
    • Added --session-db flag to configure session storage backend (memory or SQLite database path)
  • Documentation

    • Added design specification and implementation plan for session persistence feature

@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 49 minutes and 56 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 528566df-426c-4e6e-b7d8-58fb3968c612

📥 Commits

Reviewing files that changed from the base of the PR and between abb3f96 and 8e7ae92.

📒 Files selected for processing (3)
  • internal/cmd/chat.go
  • internal/cmd/serve.go
  • internal/session/sqlite_store.go
📝 Walkthrough

Walkthrough

This PR implements persistent session storage with a new SessionStore interface. It adds a SQLite-backed session store alongside a refactored in-memory implementation, updates dependencies, and wires session resumption into the chat and serve commands. Session state (messages, tool calls) is now persisted across restarts with configurable TTL-based cleanup.

Changes

Session Storage Layer

Layer / File(s) Summary
Interface Definition
internal/session/store.go
SessionStore interface introduced with methods for GetOrCreate, Get, Append, AppendAndSnapshot, Len, StartReaper, and Close. All mutating/lookup operations now return errors. Store renamed to MemoryStore and implements the interface.
Session Store Tests
internal/session/store_test.go
Tests updated to use NewMemoryStore and handle error returns from GetOrCreate, Get, and AppendAndSnapshot. Concurrency, reaper/TTL, and snapshot copy semantics verified.
SQLite Implementation
internal/session/sqlite_store.go
New SQLiteStore with schema for sessions and messages tables. Implements GetOrCreate, Get, Append, AppendAndSnapshot with transaction safety, mutex-guarded access, JSON marshaling for tool call/result fields, and a background TTL reaper (StartReaper/reap).
SQLite Store Tests
internal/session/sqlite_store_test.go
Comprehensive test suite covering store initialization, session CRUD, idempotency, TTL expiry, tool call roundtrip serialization, and persistence across store close/reopen.
Dependencies
go.mod
Added modernc.org/sqlite v1.50.0, modernc.org/libc v1.72.0, modernc.org/mathutil v1.7.1, modernc.org/memory v1.11.0. Updated golang.org/x/sync to v0.20.0.
Chat Model Updates
internal/chat/model.go
NewModel constructor now accepts explicit sessionID parameter; added SessionID() method for retrieval. Refactored ID generation into pickSessionID() helper.
Chat Command
internal/cmd/chat.go
Added --session-id flag. runChat passes session ID into chat.NewModel(...) and on completion prints resumable session info if the result is a chat.Model.
Serve Command
internal/cmd/serve.go
Added --session-db flag (defaults to XDG-based path; supports memory keyword). defaultSessionDBPath() derives the default SQLite location. Phase-2 initialization conditionally selects between in-memory and SQLite stores with logging.
Executor Adapter
internal/bridge/executor.go
AgentExecutor.Sessions type changed from *session.Store to session.SessionStore. Session operations (GetOrCreate, Append) now include explicit error checking and logged failures.
Documentation
CLAUDE.md, docs/superpowers/specs/2026-05-08-sqlite-session-persistence-design.md, docs/superpowers/plans/2026-05-08-sqlite-session-persistence.md
Updated project structure doc; added design specification and implementation plan for SQLite session persistence.

Sequence Diagram

sequenceDiagram
    actor User
    participant CLI as docsclaw chat
    participant Model as Chat Model
    participant Store as Session Store<br/>(Memory/SQLite)
    participant Executor as Agent Executor
    participant LLM as LLM Backend

    User->>CLI: --session-id=abc123
    CLI->>Model: NewModel(..., sessionID="abc123")
    Model->>Store: GetOrCreate(sessionID, systemPrompt)
    
    alt Session Exists
        Store-->>Model: return existing session & messages
    else New Session
        Store->>Store: create session, insert system message
        Store-->>Model: return new session
    end
    
    Model-->>CLI: model ready with session

    User->>CLI: send message
    CLI->>Model: handle user input
    Model->>Executor: call with session context
    Executor->>LLM: process request
    LLM-->>Executor: assistant response
    Executor->>Store: Append(sessionID, assistantMessage)
    Store->>Store: compute seq, JSON-marshal tool fields, insert, update last_active
    Store-->>Executor: ack
    Executor-->>Model: result
    Model-->>CLI: display response

    User->>CLI: exit
    CLI->>Model: return
    User->>User: note session ID for next time
    
    User->>CLI: --session-id=abc123 (later)
    CLI->>Model: NewModel(..., sessionID="abc123")
    Model->>Store: GetOrCreate(sessionID, systemPrompt)
    Store-->>Model: return session with full message history
    Note over Model,Store: Conversation resumes with all prior context restored
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements session persistence but diverges significantly from issue #5's acceptance criteria, which require evaluating external memory frameworks (Letta, Mem0, Graphiti) and exposing memory via agent tools with agent-config.yaml configuration. Either address issue #5's specific requirements (evaluate external frameworks, tool integration, agent-config.yaml support) or document why this PR's session persistence approach satisfies those criteria differently.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.68% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive The PR introduces changes beyond session persistence scope, including chat command enhancements (--session-id flag, session resumption UI), Model API changes, and go.mod updates for SQLite dependencies, which extend beyond the core backend infrastructure. Clarify whether chat command enhancements and Model API modifications are necessary dependencies for the session persistence feature or could be deferred to a separate PR.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding SQLite-backed persistent session storage, which is the primary feature of this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/sqlite-session-persistence

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pavelanni
pavelanni marked this pull request as ready for review May 8, 2026 18:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/bridge/executor.go (1)

97-99: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject oversized session IDs instead of truncating them.

Silently slicing the client-provided ID can merge two distinct sessions that share the same 64-byte prefix, which is especially risky now that history is persisted across requests. Fail the request for invalid IDs, or map them to a fixed-length derived key.

Suggested fix
-			if len(sessionID) > 64 {
-				sessionID = sessionID[:64]
-			}
+			if len(sessionID) > 64 {
+				yield(e.failedEvent(execCtx, "Invalid session ID"), nil)
+				return
+			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/bridge/executor.go` around lines 97 - 99, Replace the silent
truncation of sessionID in executor.go with explicit validation and handling: in
the function/method that currently contains the sessionID truncation (look for
the sessionID variable near the block with "if len(sessionID) > 64 { sessionID =
sessionID[:64] }"), either return a clear error response when the
client-provided sessionID length exceeds 64 bytes (e.g., reject the request with
a validation error) or deterministically map the long ID to a fixed-length
derived key (e.g., compute a stable hash and use that as the stored session key)
and document which approach you choose; ensure the error path sets an
appropriate status/error message and that any derived-key approach uses a
collision-resistant method and records both original and derived IDs where
needed for traceability.
🧹 Nitpick comments (7)
internal/session/sqlite_store_test.go (1)

11-326: 💤 Low value

Comprehensive test coverage; the timing-based reaper test is the only fragile spot.

TestSQLiteStoreReaper relies on time.Sleep(20 * time.Millisecond) being long enough for the 10ms TTL. The Append("keep-me", ...) call on line 198 refreshes last_active so the "keep" path is robust, but if you ever see flakes on slow CI runners, consider an injectable clock or a nowFunc field in SQLiteStore so the test can advance time deterministically. Not blocking — the suite as written exercises the right behaviors (TTL expiry, cascade cleanup of messages, JSON roundtrip, persistence across reopen).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store_test.go` around lines 11 - 326,
TestSQLiteStoreReaper is timing-flaky because it relies on real time; modify
SQLiteStore to accept an injectable clock (e.g., add a nowFunc field or clock
interface used by NewSQLiteStore and by reap()/TTL checks) and update the test
TestSQLiteStoreReaper to use a deterministic nowFunc that you can advance
instead of time.Sleep, ensuring calls to store.GetOrCreate, store.Append and
store.reap use the injected nowFunc so the test can simulate expiry reliably.
internal/session/sqlite_store.go (5)

134-134: ⚡ Quick win

Use errors.Is(err, sql.ErrNoRows) instead of direct comparison.

Direct equality with sql.ErrNoRows breaks if the error gets wrapped anywhere in the future and is not the idiomatic Go 1.13+ pattern. Cheap to fix today.

♻️ Proposed fix
-	if err == sql.ErrNoRows {
+	if errors.Is(err, sql.ErrNoRows) {
 		return nil, nil
 	}

(Add "errors" to imports.)

Also applies to: 219-219

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` at line 134, Replace direct equality checks
against sql.ErrNoRows with errors.Is(err, sql.ErrNoRows) to correctly handle
wrapped errors: update the conditional(s) that currently use "if err ==
sql.ErrNoRows" (seen in the function(s) handling query results in
sqlite_store.go) to use errors.Is, and add "errors" to the import list; apply
the same change to the second occurrence around the code that currently compares
err == sql.ErrNoRows (the one referenced at the other occurrence).

216-232: ⚖️ Poor tradeoff

Race window between existence check and seq computation.

The session existence check (line 218), MAX(seq) query (line 227), and the actual INSERT (line 258) are three separate operations against s.db. The instance-level s.mu mutex makes this safe within a single process, but if the same SQLite file is ever opened by a second SQLiteStore (or another process — e.g., during a rolling pod restart with shared PVC), two concurrent appendMessage calls could compute the same seq and one would fail the UNIQUE(session_id, seq) constraint. Folding the existence check and seq computation into the same transaction (and relying on the unique constraint as the safety net) would make this multi-writer-safe.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` around lines 216 - 232, The appendMessage
function has a race between checking session existence, computing seq, and
inserting; fix it by running the existence check, seq computation, and INSERT
inside a single DB transaction using s.db.BeginTx (or Begin) so those
reads/writes are atomic; in appendMessage, start a transaction, perform SELECT 1
FROM sessions WHERE id = ? and SELECT COALESCE(MAX(seq), -1) + 1 FROM messages
WHERE session_id = ? within that same tx, then perform the INSERT and commit;
also handle UNIQUE(session_id, seq) constraint errors from the INSERT (return or
retry as appropriate) instead of relying on s.mu so multi-process writers are
safe.

217-218: 💤 Low value

Verify Scan(&exists) works with a bool destination on modernc.org/sqlite.

SELECT 1 FROM sessions WHERE id = ? returns an integer column, and database/sql.convertAssign is conservative about integer→bool conversions on some drivers. The PR description says all 21 tests pass (which includes TestSQLiteStoreAppend), so this likely works with the modernc driver, but it's worth a quick sanity check. If you ever swap drivers, switching var exists bool to var exists int (or var dummy int since the value isn't actually used) avoids the dependency on driver-specific conversion behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` around lines 217 - 218, The current
QueryRow call uses Scan(&exists) with exists declared as a bool which can be
driver-dependent; change the destination to an integer (e.g., declare var dummy
int and call Scan(&dummy)) and keep the same error handling (treat sql.ErrNoRows
as "not found" and any other error as a failure). Locate the
s.db.QueryRow("SELECT 1 FROM sessions WHERE id = ?", id) call in sqlite_store.go
and replace the bool target with an int/dummy variable to avoid relying on
driver-specific int→bool conversion behavior.

22-61: ⚡ Quick win

Consider limiting the SQLite connection pool to 1 writer.

database/sql opens a pool of connections, but SQLite serializes writers at the file level. Under concurrent writes (multiple sessions appending in parallel) you can hit SQLITE_BUSY / "database is locked" errors despite WAL mode. A common, simple mitigation is db.SetMaxOpenConns(1) for write-heavy SQLite, or use a separate read pool. Given each Append does BEGIN ... COMMIT, and appendMessage already serializes via s.mu, the practical effect today is small — but once any caller bypasses s.mu (e.g., a future read path) the issue surfaces.

♻️ Suggested addition in `NewSQLiteStore` after schema init
 	if _, err := db.Exec(schema); err != nil {
 		_ = db.Close()
 		return nil, fmt.Errorf("create schema: %w", err)
 	}
+	// SQLite serializes writers at the file level; cap the pool to avoid
+	// SQLITE_BUSY under concurrent writes.
+	db.SetMaxOpenConns(1)
 
 	return &SQLiteStore{db: db, ttl: ttl}, nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` around lines 22 - 61, The SQLite store
should limit concurrent open connections to avoid SQLITE_BUSY under concurrent
writers: in NewSQLiteStore, after the schema is created and before returning the
SQLiteStore, call db.SetMaxOpenConns(1) so the database uses a single writer
connection; reference NewSQLiteStore and SQLiteStore to locate where to add
this, and note Append and appendMessage / s.mu currently serialize writes but
this db.SetMaxOpenConns(1) provides a safety net if future callers bypass s.mu.

67-71: ⚡ Quick win

Len() silently swallows query errors.

_ = s.db.QueryRow(...).Scan(&count) discards any error and returns 0, which is indistinguishable from an empty store. Either return (int, error) (interface change) or at minimum log the error so a corrupted/locked DB doesn't go unnoticed.

♻️ Minimal fix without changing the interface
 func (s *SQLiteStore) Len() int {
 	var count int
-	_ = s.db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&count)
+	if err := s.db.QueryRowContext(context.Background(),
+		"SELECT COUNT(*) FROM sessions").Scan(&count); err != nil {
+		slog.Error("session count query failed", "error", err)
+	}
 	return count
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` around lines 67 - 71, Len() currently
ignores errors from s.db.QueryRow(...).Scan(&count) causing silent failures;
update SQLiteStore.Len() to check the error returned by Scan, log the error
(using SQLiteStore's logger field if present, otherwise a package logger like
log.Printf) and still return the count (or 0) to avoid changing the function
signature, e.g., capture err := s.db.QueryRow(...).Scan(&count) and if err !=
nil log the error with context ("SQLiteStore.Len: failed to count sessions")
before returning count; keep the function name SQLiteStore.Len() and signature
unchanged.
internal/cmd/chat.go (1)

67-71: 💤 Low value

Optional: also surface session ID when p.Run errors.

If p.Run returns a non-nil error (e.g., terminal issue mid-conversation) the user loses the session ID and cannot resume. Consider attempting the type-assert/print before returning the error, so the resume hint is always available when a chat.Model was produced.

♻️ Proposed tweak
 	result, err := p.Run()
+	if finalModel, ok := result.(chat.Model); ok && finalModel.SessionID() != "" {
+		_, _ = fmt.Fprintf(cmd.ErrOrStderr(),
+			"\nSession ID: %s\nTo resume: docsclaw chat --agent-url %s --session-id %s\n",
+			finalModel.SessionID(), agentURL, finalModel.SessionID())
+	}
 	if err != nil {
 		return err
 	}
-	if finalModel, ok := result.(chat.Model); ok {
-		_, _ = fmt.Fprintf(cmd.ErrOrStderr(),
-			"\nSession ID: %s\nTo resume: docsclaw chat --agent-url %s --session-id %s\n",
-			finalModel.SessionID(), agentURL, finalModel.SessionID())
-	}
 	return nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cmd/chat.go` around lines 67 - 71, When p.Run returns an error, the
resume hint is currently only printed when result is a chat.Model and no error
is returned; change the flow so you attempt the type assertion on result (e.g.,
if finalModel, ok := result.(chat.Model)) and print the SessionID/resume hint to
cmd.ErrOrStderr() using finalModel.SessionID() and agentURL before returning the
error from p.Run, ensuring the session ID is surfaced even when p.Run fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/bridge/executor.go`:
- Around line 135-140: The Append call on e.Sessions
(e.Sessions.Append(sessionID, llm.Message{Role: "assistant", Content: result}))
can fail but the code currently only logs and lets the caller proceed; change
this so that when Append returns an error you both log it (retain e.Log.Error)
and propagate it to the caller by returning/wrapping the error from the
surrounding function (or otherwise signaling failure) so the caller does not
treat the turn as successfully persisted; ensure no subsequent success path
(sending/acknowledging the assistant response) runs if Append fails.

In `@internal/cmd/serve.go`:
- Around line 465-474: The directory for the persistent session DB is created
with overly permissive 0755; change the os.MkdirAll call to use 0700 to restrict
traversal to the user, and after creating/opening the database with
session.NewSQLiteStore (symbol sqliteStore), explicitly set the file permissions
to 0600 (e.g., os.Chmod(sessionDB, 0600)) and handle any error (returning a
wrapped fmt.Errorf) before deferring sqliteStore.Close(); keep assignments to
sessions and the log.Info call as-is.

In `@internal/session/sqlite_store.go`:
- Line 32: Update the SQLite store to use context-aware DB calls: replace
db.Exec, db.QueryRow, db.Begin and tx.Exec usages with their context-aware
counterparts (ExecContext, QueryRowContext, BeginTx/Tx.ExecContext) and thread a
context.Context through all affected methods; specifically change the
SessionStore interface method signatures for GetOrCreate, Get, Append,
AppendAndSnapshot, Len and the internal reap method to accept ctx, update
MemoryStore and any executor callers to pass the incoming ctx, and use
db.BeginTx with a context when starting transactions so long-running DB ops can
be cancelled by the request context.

---

Outside diff comments:
In `@internal/bridge/executor.go`:
- Around line 97-99: Replace the silent truncation of sessionID in executor.go
with explicit validation and handling: in the function/method that currently
contains the sessionID truncation (look for the sessionID variable near the
block with "if len(sessionID) > 64 { sessionID = sessionID[:64] }"), either
return a clear error response when the client-provided sessionID length exceeds
64 bytes (e.g., reject the request with a validation error) or deterministically
map the long ID to a fixed-length derived key (e.g., compute a stable hash and
use that as the stored session key) and document which approach you choose;
ensure the error path sets an appropriate status/error message and that any
derived-key approach uses a collision-resistant method and records both original
and derived IDs where needed for traceability.

---

Nitpick comments:
In `@internal/cmd/chat.go`:
- Around line 67-71: When p.Run returns an error, the resume hint is currently
only printed when result is a chat.Model and no error is returned; change the
flow so you attempt the type assertion on result (e.g., if finalModel, ok :=
result.(chat.Model)) and print the SessionID/resume hint to cmd.ErrOrStderr()
using finalModel.SessionID() and agentURL before returning the error from p.Run,
ensuring the session ID is surfaced even when p.Run fails.

In `@internal/session/sqlite_store_test.go`:
- Around line 11-326: TestSQLiteStoreReaper is timing-flaky because it relies on
real time; modify SQLiteStore to accept an injectable clock (e.g., add a nowFunc
field or clock interface used by NewSQLiteStore and by reap()/TTL checks) and
update the test TestSQLiteStoreReaper to use a deterministic nowFunc that you
can advance instead of time.Sleep, ensuring calls to store.GetOrCreate,
store.Append and store.reap use the injected nowFunc so the test can simulate
expiry reliably.

In `@internal/session/sqlite_store.go`:
- Line 134: Replace direct equality checks against sql.ErrNoRows with
errors.Is(err, sql.ErrNoRows) to correctly handle wrapped errors: update the
conditional(s) that currently use "if err == sql.ErrNoRows" (seen in the
function(s) handling query results in sqlite_store.go) to use errors.Is, and add
"errors" to the import list; apply the same change to the second occurrence
around the code that currently compares err == sql.ErrNoRows (the one referenced
at the other occurrence).
- Around line 216-232: The appendMessage function has a race between checking
session existence, computing seq, and inserting; fix it by running the existence
check, seq computation, and INSERT inside a single DB transaction using
s.db.BeginTx (or Begin) so those reads/writes are atomic; in appendMessage,
start a transaction, perform SELECT 1 FROM sessions WHERE id = ? and SELECT
COALESCE(MAX(seq), -1) + 1 FROM messages WHERE session_id = ? within that same
tx, then perform the INSERT and commit; also handle UNIQUE(session_id, seq)
constraint errors from the INSERT (return or retry as appropriate) instead of
relying on s.mu so multi-process writers are safe.
- Around line 217-218: The current QueryRow call uses Scan(&exists) with exists
declared as a bool which can be driver-dependent; change the destination to an
integer (e.g., declare var dummy int and call Scan(&dummy)) and keep the same
error handling (treat sql.ErrNoRows as "not found" and any other error as a
failure). Locate the s.db.QueryRow("SELECT 1 FROM sessions WHERE id = ?", id)
call in sqlite_store.go and replace the bool target with an int/dummy variable
to avoid relying on driver-specific int→bool conversion behavior.
- Around line 22-61: The SQLite store should limit concurrent open connections
to avoid SQLITE_BUSY under concurrent writers: in NewSQLiteStore, after the
schema is created and before returning the SQLiteStore, call
db.SetMaxOpenConns(1) so the database uses a single writer connection; reference
NewSQLiteStore and SQLiteStore to locate where to add this, and note Append and
appendMessage / s.mu currently serialize writes but this db.SetMaxOpenConns(1)
provides a safety net if future callers bypass s.mu.
- Around line 67-71: Len() currently ignores errors from
s.db.QueryRow(...).Scan(&count) causing silent failures; update
SQLiteStore.Len() to check the error returned by Scan, log the error (using
SQLiteStore's logger field if present, otherwise a package logger like
log.Printf) and still return the count (or 0) to avoid changing the function
signature, e.g., capture err := s.db.QueryRow(...).Scan(&count) and if err !=
nil log the error with context ("SQLiteStore.Len: failed to count sessions")
before returning count; keep the function name SQLiteStore.Len() and signature
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: c01d146d-87dd-47df-a22f-b4fb8aff0025

📥 Commits

Reviewing files that changed from the base of the PR and between e73b558 and abb3f96.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • CLAUDE.md
  • docs/superpowers/plans/2026-05-08-sqlite-session-persistence.md
  • docs/superpowers/specs/2026-05-08-sqlite-session-persistence-design.md
  • go.mod
  • internal/bridge/executor.go
  • internal/chat/model.go
  • internal/cmd/chat.go
  • internal/cmd/serve.go
  • internal/session/sqlite_store.go
  • internal/session/sqlite_store_test.go
  • internal/session/store.go
  • internal/session/store_test.go

Comment on lines 135 to +140
if e.Sessions != nil && sessionID != "" {
e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result})
if err := e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result}); err != nil {
e.Log.Error("Failed to save assistant response to session",
"session_id", sessionID, "error", err)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't complete the task after the assistant turn fails to persist.

If this append fails, the caller still gets a successful response, but the stored conversation is now missing the assistant reply. The next resumed turn will run against corrupted history.

Suggested fix
 			if e.Sessions != nil && sessionID != "" {
 				if err := e.Sessions.Append(sessionID,
 					llm.Message{Role: "assistant", Content: result}); err != nil {
 					e.Log.Error("Failed to save assistant response to session",
 						"session_id", sessionID, "error", err)
+					yield(e.failedEvent(execCtx, "Session error: "+err.Error()), nil)
+					return
 				}
 			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if e.Sessions != nil && sessionID != "" {
e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result})
if err := e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result}); err != nil {
e.Log.Error("Failed to save assistant response to session",
"session_id", sessionID, "error", err)
}
if e.Sessions != nil && sessionID != "" {
if err := e.Sessions.Append(sessionID,
llm.Message{Role: "assistant", Content: result}); err != nil {
e.Log.Error("Failed to save assistant response to session",
"session_id", sessionID, "error", err)
yield(e.failedEvent(execCtx, "Session error: "+err.Error()), nil)
return
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/bridge/executor.go` around lines 135 - 140, The Append call on
e.Sessions (e.Sessions.Append(sessionID, llm.Message{Role: "assistant", Content:
result})) can fail but the code currently only logs and lets the caller proceed;
change this so that when Append returns an error you both log it (retain
e.Log.Error) and propagate it to the caller by returning/wrapping the error from
the surrounding function (or otherwise signaling failure) so the caller does not
treat the turn as successfully persisted; ensure no subsequent success path
(sending/acknowledging the assistant response) runs if Append fails.

Comment thread internal/cmd/serve.go Resolved
"PRAGMA journal_mode=WAL",
"PRAGMA foreign_keys=ON",
} {
if _, err := db.Exec(pragma); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

noctx lint failures will block make lint.

Static analysis flags six call sites that use the non-context variants of database/sql operations: db.Exec (lines 32, 55), db.QueryRow (lines 69, 218, 227), and db.Begin/tx.Exec (lines 88, 94, 102, 252, 258, 266). Per the project's lint policy these need to use the *Context variants. Plumbing a context.Context through GetOrCreate, Get, Append, AppendAndSnapshot, Len, and reap would also let the executor cancel long-running DB ops along with the request.

♻️ Sketch of the change
-func (s *SQLiteStore) GetOrCreate(id, systemPrompt string) (*Session, error) {
+func (s *SQLiteStore) GetOrCreate(ctx context.Context, id, systemPrompt string) (*Session, error) {
 	s.mu.Lock()
 	defer s.mu.Unlock()
 
-	sess, err := s.loadSession(id)
+	sess, err := s.loadSession(ctx, id)
 	...
-	tx, err := s.db.Begin()
+	tx, err := s.db.BeginTx(ctx, nil)
 	...
-	_, err = tx.Exec(
+	_, err = tx.ExecContext(ctx,
 		"INSERT INTO sessions ...",
 		...,
 	)

The SessionStore interface in store.go would also need its method signatures updated, and MemoryStore + the executor callers would need to thread through ctx.

As per coding guidelines: "Focus on major issues impacting performance, readability, maintainability and security."

Also applies to: 55-55, 69-69, 88-88, 94-94, 102-102

🧰 Tools
🪛 golangci-lint (2.12.1)

[error] 32-32: (*database/sql.DB).Exec must not be called. use (*database/sql.DB).ExecContext

(noctx)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/session/sqlite_store.go` at line 32, Update the SQLite store to use
context-aware DB calls: replace db.Exec, db.QueryRow, db.Begin and tx.Exec
usages with their context-aware counterparts (ExecContext, QueryRowContext,
BeginTx/Tx.ExecContext) and thread a context.Context through all affected
methods; specifically change the SessionStore interface method signatures for
GetOrCreate, Get, Append, AppendAndSnapshot, Len and the internal reap method to
accept ctx, update MemoryStore and any executor callers to pass the incoming
ctx, and use db.BeginTx with a context when starting transactions so
long-running DB ops can be cancelled by the request context.

- Use errors.Is for sql.ErrNoRows checks
- Move exists check and seq query into transaction in appendMessage
- Use int instead of bool for EXISTS scan target
- Set db.SetMaxOpenConns(1) for SQLite safety
- Log errors in Len() instead of silently ignoring
- Tighten directory (0700) and file (0600) permissions for session DB
- Print session ID on chat exit even when p.Run returns error

Skipped (with reasons):
- Append error propagation: response already computed, log+continue is
  correct UX
- Context-aware DB calls: significant interface refactor, follow-up
- Session ID truncation: pre-existing code outside this PR
- Injectable clock for tests: over-engineering for 20ms sleep

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni merged commit c1ef6fa into main May 8, 2026
3 checks passed
@pavelanni
pavelanni deleted the feature/sqlite-session-persistence branch May 8, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory and context persistence

1 participant