fix: read opencode sessions from session_v2/session_message

opencode 2.0.24 migrated its session store: the session, message and
part tables stopped being written, and sessions now live in session_v2
with messages in session_message. The ingest kept querying the abandoned
tables, so every sweep after the migration logged "0 new" and no error.

Session titles are nullable in session_v2, so keep the COALESCE and the
"Session <short id>" fallback.

Transcripts are rebuilt from both message shapes the new store uses:
user turns carry text at $.text, assistant turns carry a typed part list
at $.content of which only "text" parts are conversation (reasoning and
tool parts are not indexed). Rows are ordered by seq, then part index,
so a session reads in order.

Harness reminders arrive as synthetic messages now; drop <system-reminder>
text so it does not consume the 4000-byte summary budget.

Also stop skipping an entry purely on created_at: resuming a session
appends messages without touching the creation time, so the summary is
compared too and the entry refreshes.

Bump the ingester to opencode-db/v2 and cover both message shapes with a
test that builds the new schema in a temp database.

Fixes #6
This commit is contained in:
2026-11-01 13:33:56 -08:00
parent 0b8ac34aee
commit e4f3618424
3 changed files with 117 additions and 21 deletions
+35 -20
View File
@@ -12,8 +12,10 @@ import (
) )
// opencodeDBPath is the current opencode storage: a single SQLite database // opencodeDBPath is the current opencode storage: a single SQLite database
// holding sessions, messages and their parts. The legacy // holding sessions, messages and their parts. Sessions live in session_v2 and
// storage/session_diff/*.json files are mostly empty and are no longer read. // messages in session_message; the v1 session/message/part tables stopped
// being written when opencode 2.0.24 migrated the store, and the legacy
// storage/session_diff/*.json files are mostly empty. Neither is read here.
const opencodeDBPath = ".local/share/opencode/opencode.db" const opencodeDBPath = ".local/share/opencode/opencode.db"
// transcriptCap bounds how much conversation text is folded into one session // transcriptCap bounds how much conversation text is folded into one session
@@ -23,14 +25,14 @@ const transcriptCap = 4000
// OpenCodeDBIngester indexes opencode sessions from opencode.db. One session // OpenCodeDBIngester indexes opencode sessions from opencode.db. One session
// becomes one entry; the summary carries a capped transcript of the session's // becomes one entry; the summary carries a capped transcript of the session's
// text parts so conversation content is searchable. // text messages so conversation content is searchable.
type OpenCodeDBIngester struct { type OpenCodeDBIngester struct {
Version string Version string
Path string // defaults to ~/.local/share/opencode/opencode.db Path string // defaults to ~/.local/share/opencode/opencode.db
} }
func NewOpenCodeDBIngester() *OpenCodeDBIngester { func NewOpenCodeDBIngester() *OpenCodeDBIngester {
return &OpenCodeDBIngester{Version: "opencode-db/v1"} return &OpenCodeDBIngester{Version: "opencode-db/v2"}
} }
func (o *OpenCodeDBIngester) SourceID() string { return "opencode-session" } func (o *OpenCodeDBIngester) SourceID() string { return "opencode-session" }
@@ -95,7 +97,7 @@ func loadOCSessions(db *sql.DB) ([]ocSession, error) {
rows, err := db.Query( rows, err := db.Query(
`SELECT id, COALESCE(title,''), COALESCE(directory,''), `SELECT id, COALESCE(title,''), COALESCE(directory,''),
COALESCE(time_created,0), COALESCE(time_updated,0) COALESCE(time_created,0), COALESCE(time_updated,0)
FROM session ORDER BY time_updated`) FROM session_v2 ORDER BY time_updated`)
if err != nil { if err != nil {
return nil, fmt.Errorf("query sessions: %w", err) return nil, fmt.Errorf("query sessions: %w", err)
} }
@@ -113,13 +115,23 @@ func loadOCSessions(db *sql.DB) ([]ocSession, error) {
} }
// loadOCTranscripts returns session_id -> ordered text lines ("role: text"). // loadOCTranscripts returns session_id -> ordered text lines ("role: text").
//
// session_message.type is the role. User turns keep their text at $.text;
// assistant turns keep a typed part list at $.content, of which only "text"
// parts are conversation — reasoning and tool parts are not indexed.
func loadOCTranscripts(db *sql.DB) (map[string][]string, error) { func loadOCTranscripts(db *sql.DB) (map[string][]string, error) {
rows, err := db.Query( rows, err := db.Query(
`SELECT p.session_id, json_extract(m.data,'$.role'), json_extract(p.data,'$.text') `SELECT session_id, role, text, seq, ord FROM (
FROM part p SELECT session_id, type AS role, json_extract(data,'$.text') AS text,
JOIN message m ON m.id = p.message_id seq AS seq, -1 AS ord
WHERE json_extract(p.data,'$.type')='text' FROM session_message
ORDER BY p.session_id, p.time_created`) WHERE type='user'
UNION ALL
SELECT sm.session_id, sm.type, json_extract(je.value,'$.text'),
sm.seq, je.key
FROM session_message sm, json_each(json_extract(sm.data,'$.content')) je
WHERE sm.type='assistant' AND json_extract(je.value,'$.type')='text'
) ORDER BY session_id, seq, ord`)
if err != nil { if err != nil {
return nil, fmt.Errorf("query transcripts: %w", err) return nil, fmt.Errorf("query transcripts: %w", err)
} }
@@ -127,24 +139,25 @@ func loadOCTranscripts(db *sql.DB) (map[string][]string, error) {
out := make(map[string][]string) out := make(map[string][]string)
for rows.Next() { for rows.Next() {
var sessionID, text string var sessionID string
var role sql.NullString var role, text sql.NullString
if err := rows.Scan(&sessionID, &role, &text); err != nil { var seq, ord int64
if err := rows.Scan(&sessionID, &role, &text, &seq, &ord); err != nil {
return nil, err return nil, err
} }
text = strings.TrimSpace(text) t := strings.TrimSpace(text.String)
if text == "" || isToolEcho(text) { if t == "" || isToolEcho(t) {
continue continue
} }
out[sessionID] = append(out[sessionID], roleLabel(role.String)+": "+text) out[sessionID] = append(out[sessionID], roleLabel(role.String)+": "+t)
} }
return out, rows.Err() return out, rows.Err()
} }
func loadOCPartCounts(db *sql.DB) (map[string]int, error) { func loadOCPartCounts(db *sql.DB) (map[string]int, error) {
rows, err := db.Query(`SELECT session_id, COUNT(*) FROM part GROUP BY session_id`) rows, err := db.Query(`SELECT session_id, COUNT(*) FROM session_message GROUP BY session_id`)
if err != nil { if err != nil {
return nil, fmt.Errorf("query part counts: %w", err) return nil, fmt.Errorf("query message counts: %w", err)
} }
defer rows.Close() defer rows.Close()
@@ -230,9 +243,11 @@ func roleLabel(role string) string {
} }
// isToolEcho drops the user-role echoes opencode stores for tool invocations // isToolEcho drops the user-role echoes opencode stores for tool invocations
// and file reads; they are noise in a knowledge summary. // and file reads, and harness reminders, which are noise in a knowledge
// summary.
func isToolEcho(text string) bool { func isToolEcho(text string) bool {
return strings.HasPrefix(text, "Called the ") || strings.HasPrefix(text, "<path>") return strings.HasPrefix(text, "Called the ") || strings.HasPrefix(text, "<path>") ||
strings.HasPrefix(text, "<system-reminder>")
} }
func shortID(id string) string { func shortID(id string) string {
+78
View File
@@ -1,10 +1,88 @@
package ingest package ingest
import ( import (
"database/sql"
"fmt"
"path/filepath"
"strings" "strings"
"testing" "testing"
) )
// opencode 2.0.24 moved sessions to session_v2/session_message and stopped
// writing the v1 session/message/part tables. The adapter must read the new
// store and pull conversation out of both message shapes: user text at
// $.text, assistant text parts under $.content.
func TestOpenCodeDBIngestSessionV2(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode.db")
db, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatalf("open: %v", err)
}
for _, stmt := range []string{
`CREATE TABLE session_v2 (id TEXT PRIMARY KEY, title TEXT, directory TEXT,
time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)`,
`CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL, data TEXT NOT NULL)`,
} {
if _, err := db.Exec(stmt); err != nil {
t.Fatalf("schema: %v", err)
}
}
msgs := []struct {
typ string
data string
}{
{"user", `{"text":"check the kitchen light"}`},
{"assistant", `{"content":[{"type":"reasoning","text":"thinking hard"},` +
`{"type":"text","text":"it is excluded from the kelvin path"},{"type":"tool","id":"call_1"}]}`},
{"synthetic", `{"text":"<system-reminder>plan mode</system-reminder>"}`},
}
for i, m := range msgs {
_, err := db.Exec(
`INSERT INTO session_message VALUES (?,?,?,?,0,0,?)`,
fmt.Sprintf("msg_%d", i), "ses_upgrade", m.typ, i+1, m.data)
if err != nil {
t.Fatalf("insert message: %v", err)
}
}
if _, err := db.Exec(
`INSERT INTO session_v2 VALUES ('ses_upgrade','Kitchen light','/home/david/assistant',1700000000000,1700000001000)`,
); err != nil {
t.Fatalf("insert session: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
results, err := (&OpenCodeDBIngester{Path: path}).IngestAll()
if err != nil {
t.Fatalf("IngestAll: %v", err)
}
if len(results) != 1 {
t.Fatalf("results=%d, want 1", len(results))
}
r := results[0]
if r.Title != "Kitchen light" || r.Project != "assistant" {
t.Fatalf("title=%q project=%q", r.Title, r.Project)
}
if !strings.Contains(r.Summary, "check the kitchen light") ||
!strings.Contains(r.Summary, "excluded from the kelvin path") {
t.Fatalf("summary missing conversation: %q", r.Summary)
}
for _, unwanted := range []string{"thinking hard", "system-reminder", "call_1"} {
if strings.Contains(r.Content, unwanted) {
t.Fatalf("content leaked %q: %q", unwanted, r.Content)
}
}
if got := len(strings.Split(strings.TrimSpace(r.Content), "\n")); got != 2 {
t.Fatalf("content lines=%d, want 2 (%q)", got, r.Content)
}
}
func TestBuildSummary(t *testing.T) { func TestBuildSummary(t *testing.T) {
if got := buildSummary(nil); got != "" { if got := buildSummary(nil); got != "" {
t.Fatalf("empty summary=%q", got) t.Fatalf("empty summary=%q", got)
+4 -1
View File
@@ -609,7 +609,10 @@ func (w *Watcher) ingestOpenCodeDB() {
var newCount, skipped int var newCount, skipped int
for _, result := range results { for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint) existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
if existing != nil && existing.CreatedAt == result.CreatedAt { // created_at alone cannot detect a resumed session: resuming appends
// messages without touching the creation time, so compare the summary
// (which carries the transcript) as well.
if existing != nil && existing.CreatedAt == result.CreatedAt && existing.Summary == result.Summary {
skipped++ skipped++
continue continue
} }