Files
knox/internal/ingest/opencode_db.go
T
david 84f30f293b
build / test (push) Has been cancelled
build / image (push) Has been cancelled
feat: index reasoning, and close the two-minute freshness gap (#19)
feat: index reasoning, and close the session freshness gap (#19)

Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 03:39:16 +00:00

347 lines
10 KiB
Go

package ingest
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"
"time"
_ "modernc.org/sqlite"
)
// opencodeDBPath is the current opencode storage: a single SQLite database
// holding sessions, messages and their parts. Sessions live in session_v2 and
// 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"
// transcriptCap bounds how much conversation text is folded into one session
// entry's summary. It keeps the entry searchable without storing the whole
// (often tool-heavy) transcript.
const transcriptCap = 4000
// Reasoning is the model's own "why", which never appears in the text parts a
// user sees. It is worth indexing — it is where decisions are justified — but
// it is enormous (individual parts reach 175 KB), so it is truncated per part
// and budgeted per session. The budget bounds index growth; the truncation
// keeps the opening of each thought, which is where the claim usually is.
const (
reasoningPartCap = 1200
reasoningSessionCap = 4000
reasoningLinePrefix = "reasoning: "
)
// OpenCodeDBIngester indexes opencode sessions from opencode.db. One session
// becomes one entry; the summary carries a capped transcript of the session's
// text messages so conversation content is searchable.
type OpenCodeDBIngester struct {
Version string
Path string // defaults to ~/.local/share/opencode/opencode.db
}
func NewOpenCodeDBIngester() *OpenCodeDBIngester {
return &OpenCodeDBIngester{Version: "opencode-db/v3"}
}
func (o *OpenCodeDBIngester) SourceID() string { return "opencode-session" }
// Ingest satisfies Ingester but is unused: this source is DB-backed, not
// per-file. Callers use IngestAll.
func (o *OpenCodeDBIngester) Ingest(path string) (*IngestResult, error) { return nil, nil }
type ocSession struct {
ID string
Title string
Directory string
TimeCreated int64
TimeUpdated int64
}
// IngestAll reads every session and produces one result per session. It is a
// full sweep: unchanged sessions are collapsed by RecordObservation's dedup, so
// repeated sweeps are idempotent and need no watermark.
func (o *OpenCodeDBIngester) IngestAll() ([]*IngestResult, error) {
return o.IngestSince(0)
}
// IngestSince sweeps only sessions updated after sinceMillis (0 = all), and
// loads transcripts for just those. A full sweep reads every session's messages
// — ~20s on a 59k-message store — which is far too slow to run per turn. With a
// watermark the steady-state cost tracks the number of changed sessions.
func (o *OpenCodeDBIngester) IngestSince(sinceMillis int64) ([]*IngestResult, error) {
path := o.Path
if path == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("home dir: %w", err)
}
path = filepath.Join(home, opencodeDBPath)
}
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("opencode db: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, fmt.Errorf("open opencode db: %w", err)
}
defer db.Close()
sessions, err := loadOCSessions(db, sinceMillis)
if err != nil {
return nil, err
}
if len(sessions) == 0 {
return nil, nil
}
ids := make([]string, 0, len(sessions))
for _, s := range sessions {
ids = append(ids, s.ID)
}
transcripts, err := loadOCTranscripts(db, ids)
if err != nil {
return nil, err
}
partCounts, err := loadOCPartCounts(db, ids)
if err != nil {
return nil, err
}
results := make([]*IngestResult, 0, len(sessions))
for _, s := range sessions {
results = append(results, o.buildResult(s, transcripts[s.ID], partCounts[s.ID]))
}
return results, nil
}
func loadOCSessions(db *sql.DB, sinceMillis int64) ([]ocSession, error) {
rows, err := db.Query(
`SELECT id, COALESCE(title,''), COALESCE(directory,''),
COALESCE(time_created,0), COALESCE(time_updated,0)
FROM session_v2
WHERE time_updated > ?
ORDER BY time_updated`, sinceMillis)
if err != nil {
return nil, fmt.Errorf("query sessions: %w", err)
}
defer rows.Close()
var out []ocSession
for rows.Next() {
var s ocSession
if err := rows.Scan(&s.ID, &s.Title, &s.Directory, &s.TimeCreated, &s.TimeUpdated); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
// 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, sessionIDs []string) (map[string][]string, error) {
in, args := inClause(sessionIDs)
rows, err := db.Query(
`SELECT session_id, role, text, seq, ord FROM (
SELECT session_id, type AS role, json_extract(data,'$.text') AS text,
seq AS seq, -1 AS ord
FROM session_message
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'
UNION ALL
SELECT sm.session_id, 'reasoning', 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')='reasoning'
) WHERE session_id IN `+in+`
ORDER BY session_id, seq, ord`, args...)
if err != nil {
return nil, fmt.Errorf("query transcripts: %w", err)
}
defer rows.Close()
out := make(map[string][]string)
reasoningBudget := make(map[string]int)
for rows.Next() {
var sessionID string
var role, text sql.NullString
var seq, ord int64
if err := rows.Scan(&sessionID, &role, &text, &seq, &ord); err != nil {
return nil, err
}
t := strings.TrimSpace(text.String)
if t == "" || isToolEcho(t) {
continue
}
if role.String == "reasoning" {
// Keep the opening of each thought, within a per-session budget.
remaining := reasoningSessionCap - reasoningBudget[sessionID]
if remaining <= 0 {
continue
}
if len(t) > reasoningPartCap {
t = truncate(t, reasoningPartCap)
}
if len(t) > remaining {
t = truncate(t, remaining)
}
reasoningBudget[sessionID] += len(t)
out[sessionID] = append(out[sessionID], reasoningLinePrefix+t)
continue
}
out[sessionID] = append(out[sessionID], roleLabel(role.String)+": "+t)
}
return out, rows.Err()
}
func loadOCPartCounts(db *sql.DB, sessionIDs []string) (map[string]int, error) {
in, args := inClause(sessionIDs)
rows, err := db.Query(`SELECT session_id, COUNT(*) FROM session_message WHERE session_id IN `+in+` GROUP BY session_id`, args...)
if err != nil {
return nil, fmt.Errorf("query message counts: %w", err)
}
defer rows.Close()
out := make(map[string]int)
for rows.Next() {
var sessionID string
var n int
if err := rows.Scan(&sessionID, &n); err != nil {
return nil, err
}
out[sessionID] = n
}
return out, rows.Err()
}
func (o *OpenCodeDBIngester) buildResult(s ocSession, lines []string, partCount int) *IngestResult {
title := strings.TrimSpace(s.Title)
if title == "" {
title = "Session " + shortID(s.ID)
}
summary := buildSummary(lines)
createdAt := ""
if s.TimeCreated > 0 {
createdAt = time.UnixMilli(s.TimeCreated).UTC().Format(time.RFC3339)
}
project := ""
if s.Directory != "" {
project = filepath.Base(s.Directory)
}
return &IngestResult{
Fingerprint: FingerprintWithMeta([]byte(s.ID), map[string]string{"source": "opencode-db"}),
SourceID: o.SourceID(),
SourcePath: s.ID,
Project: project,
ContentType: ".session",
Title: title,
Summary: summary,
Content: strings.Join(lines, "\n"),
CreatedAt: createdAt,
LineEnd: partCount,
Confidence: 0.8,
ContentHash: contentHash(strings.Join(lines, "\n")),
SourceUpdated: s.TimeUpdated,
IngesterVersion: o.Version,
Provenance: map[string]any{
"session_id": s.ID,
"directory": s.Directory,
"parts": partCount,
"prompts": len(lines),
},
}
}
// buildSummary folds a session's text lines into a bounded, searchable string:
// the first line (usually the opening prompt) followed by the transcript up to
// the cap.
func buildSummary(lines []string) string {
if len(lines) == 0 {
return ""
}
var b strings.Builder
b.WriteString(truncate(lines[0], 200))
if len(lines) > 1 {
b.WriteString(" || ")
for _, l := range lines[1:] {
// Reasoning is indexed in content but kept out of the summary: it
// is long, and the summary is what search results and MCP output
// show a reader.
if strings.HasPrefix(l, reasoningLinePrefix) {
continue
}
if b.Len()+len(l) > transcriptCap {
break
}
b.WriteString(l)
b.WriteString(" ")
}
}
return strings.TrimSpace(b.String())
}
func roleLabel(role string) string {
if role == "" {
return "msg"
}
return role
}
// isToolEcho drops the user-role echoes opencode stores for tool invocations
// and file reads, and harness reminders, which are noise in a knowledge
// summary.
func isToolEcho(text string) bool {
return strings.HasPrefix(text, "Called the ") || strings.HasPrefix(text, "<path>") ||
strings.HasPrefix(text, "<system-reminder>")
}
// contentHash is the change signal for a session observation. Two sweeps that
// produce the same bytes are the same fact; a sweep that only gained reasoning
// behind unchanged prose must still be recorded, which a summary comparison
// alone would miss.
func contentHash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
// inClause builds "?,?,?" plus its arguments for a session-id filter.
func inClause(ids []string) (string, []any) {
args := make([]any, len(ids))
marks := make([]byte, 0, len(ids)*2)
for i, id := range ids {
args[i] = id
if i > 0 {
marks = append(marks, ',')
}
marks = append(marks, '?')
}
return "(" + string(marks) + ")", args
}
func shortID(id string) string {
id = strings.TrimPrefix(id, "ses_")
if len(id) > 8 {
return id[:8]
}
return id
}