Files
knox/internal/ingest/opencode_db.go
T
david edf6c03a7c chore: checkpoint uncommitted work before session store fix
Pre-existing work-in-progress in the tree: karakeep, snippets,
skills-health and redaction ingesters, the opencode.db session sweep,
gossip and metrics changes. Checkpointed as-is so the adapter fix in the
next commit stays reviewable on its own.
2026-11-01 13:33:36 -08:00

245 lines
6.4 KiB
Go

package ingest
import (
"database/sql"
"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. The legacy
// storage/session_diff/*.json files are mostly empty and are no longer read.
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
// OpenCodeDBIngester indexes opencode sessions from opencode.db. One session
// becomes one entry; the summary carries a capped transcript of the session's
// text parts 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/v1"}
}
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) {
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)
if err != nil {
return nil, err
}
transcripts, err := loadOCTranscripts(db)
if err != nil {
return nil, err
}
partCounts, err := loadOCPartCounts(db)
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) ([]ocSession, error) {
rows, err := db.Query(
`SELECT id, COALESCE(title,''), COALESCE(directory,''),
COALESCE(time_created,0), COALESCE(time_updated,0)
FROM session ORDER BY time_updated`)
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").
func loadOCTranscripts(db *sql.DB) (map[string][]string, error) {
rows, err := db.Query(
`SELECT p.session_id, json_extract(m.data,'$.role'), json_extract(p.data,'$.text')
FROM part p
JOIN message m ON m.id = p.message_id
WHERE json_extract(p.data,'$.type')='text'
ORDER BY p.session_id, p.time_created`)
if err != nil {
return nil, fmt.Errorf("query transcripts: %w", err)
}
defer rows.Close()
out := make(map[string][]string)
for rows.Next() {
var sessionID, text string
var role sql.NullString
if err := rows.Scan(&sessionID, &role, &text); err != nil {
return nil, err
}
text = strings.TrimSpace(text)
if text == "" || isToolEcho(text) {
continue
}
out[sessionID] = append(out[sessionID], roleLabel(role.String)+": "+text)
}
return out, rows.Err()
}
func loadOCPartCounts(db *sql.DB) (map[string]int, error) {
rows, err := db.Query(`SELECT session_id, COUNT(*) FROM part GROUP BY session_id`)
if err != nil {
return nil, fmt.Errorf("query part 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,
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:] {
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; they are noise in a knowledge summary.
func isToolEcho(text string) bool {
return strings.HasPrefix(text, "Called the ") || strings.HasPrefix(text, "<path>")
}
func shortID(id string) string {
id = strings.TrimPrefix(id, "ses_")
if len(id) > 8 {
return id[:8]
}
return id
}