fix: read opencode sessions from session_v2/session_message (#7)

Fixes #6.

opencode 2.0.24 migrated its session store on 2026-11-01 21:01:20 UTC. `session`, `message` and `part` stopped being written; sessions now live in `session_v2` and messages in `session_message`. The ingest kept querying the abandoned tables, so every sweep after the migration logged `0 new` — no error, no new sessions indexed.

## Changes

- **`internal/ingest/opencode_db.go`**
  - Read sessions from `session_v2` (title is nullable there, the existing COALESCE + fallback still apply).
  - Rebuild transcripts from both message shapes: user turns at `$.text`, assistant turns from `$.content[]` filtered to `type='text'` (reasoning and tool parts are not indexed). Ordered by `seq`, then part index.
  - Count messages from `session_message` instead of parts.
  - Drop `<system-reminder>` text — reminders now arrive as `synthetic` messages and would eat the 4000-byte summary budget.
  - Ingester version is now `opencode-db/v2`.
- **`internal/watch/watch.go`** — an entry is no longer skipped on `created_at` alone. Resuming a session appends messages without touching the creation time, so the summary is compared too.
- **`internal/ingest/opencode_db_test.go`** — new test builds the v2 schema in a temp SQLite database and asserts user text and assistant text parts are indexed while reasoning, tool and reminder content is not.

## Validation

- `go build ./...`, `go test ./internal/ingest/ ./internal/db/ ./internal/watch/` pass.
- Rebuilt the binary and restarted `knox.service` against the live store:
  ```
  [knox] opencode.db: 1 new, 387 unchanged
  ```
  The new entry is the session that had been invisible since the migration (`Knox OpenCode session adapter compatibility check`, observation version `opencode-db/v2`), and `knox query "knox opencode session adapter compatibility"` finds it.
- 59 pre-migration sessions re-recorded because their stored transcripts contained reminder text that the new filter drops; summaries still carry the conversation.

## Notes

The first commit on this branch is a checkpoint of pre-existing uncommitted work that the adapter fix sits on top of; the fix itself is the second commit (`e07ae8a`).

Reviewed-on: #7
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #7.
This commit is contained in:
2026-11-02 01:16:50 +00:00
committed by david
parent bb852faa27
commit 8d6d73b747
44 changed files with 6868 additions and 420 deletions
+1783 -163
View File
File diff suppressed because it is too large Load Diff
+494
View File
@@ -1,11 +1,505 @@
package db
import (
"fmt"
"path/filepath"
"sync"
"testing"
"time"
)
func newTestDB(t *testing.T) *KnoxDB {
t.Helper()
k, err := Open(filepath.Join(t.TempDir(), "knox.db"))
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { k.Close() })
return k
}
func obs(fp, title, summary string) ObservationRecord {
return ObservationRecord{
Fingerprint: fp, SourceID: "test", Title: title, Summary: summary,
Confidence: 0.5, IngesterVersion: "test/v1",
}
}
// Multi-word queries must match terms spread across fields (AND), not require
// the literal contiguous phrase.
func TestSearchMultiTerm(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "Home Assistant", "automation for the doorbell")); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp2", "Unrelated", "gardening notes")); err != nil {
t.Fatal(err)
}
got, err := k.Search("home assistant automation", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("expected only fp1, got %+v", got)
}
if got, _ := k.Search("home gardening", 10); len(got) != 0 {
t.Fatalf("expected no cross-row match, got %+v", got)
}
}
// Re-reporting an unchanged observation is a no-op: no new row, ref_count stays 1.
func TestRecordObservationIdempotent(t *testing.T) {
k := newTestDB(t)
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); !isNew {
t.Fatal("first insert should be new")
}
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); isNew {
t.Fatal("second identical insert should be a no-op")
}
var ref, rows int
if err := k.db.QueryRow("SELECT ref_count FROM entries WHERE fingerprint='fp1'").Scan(&ref); err != nil {
t.Fatal(err)
}
if err := k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&rows); err != nil {
t.Fatal(err)
}
if ref != 1 || rows != 1 {
t.Fatalf("ref_count=%d observations=%d, want 1/1", ref, rows)
}
}
// A non-empty ContentHash dedups on content, ignoring extent changes.
func TestRecordObservationContentHash(t *testing.T) {
k := newTestDB(t)
rows := func() int {
var n int
k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&n)
return n
}
a := obs("fp1", "Log x", "levels: E1 W0")
a.ContentHash = "deadbeef"
a.LineEnd = 100
if _, _, err := k.RecordObservation(a); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after first: rows=%d, want 1", rows())
}
// Same content hash, grown extent, different summary — must be a no-op.
b := obs("fp1", "Log x", "levels: E1 W0 (1000 lines)")
b.ContentHash = "deadbeef"
b.LineEnd = 2000
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after same-hash: rows=%d, want 1 (no-op)", rows())
}
// Different content hash — must append.
c := obs("fp1", "Log x", "levels: E2 W0")
c.ContentHash = "cafef00d"
c.LineEnd = 2000
if _, _, err := k.RecordObservation(c); err != nil {
t.Fatal(err)
}
if rows() != 2 {
t.Fatalf("after changed-hash: rows=%d, want 2", rows())
}
}
// UpsertSession must not inflate agent_count across repeated calls.
func TestUpsertSessionIdempotent(t *testing.T) {
k := newTestDB(t)
for i := 0; i < 3; i++ {
if err := k.UpsertSession("ses_1", "proj", "Title", "active"); err != nil {
t.Fatal(err)
}
}
var ac int
if err := k.db.QueryRow("SELECT agent_count FROM sessions WHERE session_id='ses_1'").Scan(&ac); err != nil {
t.Fatal(err)
}
if ac != 1 {
t.Fatalf("agent_count=%d, want 1", ac)
}
}
// Content (the uncapped body) is searchable even when absent from title/summary.
func TestSearchContentField(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "Title A", "short summary only")
r.Content = "the zanzibar protocol handshake details"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
got, err := k.Search("zanzibar", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("content search failed: %+v", got)
}
}
// Threads sharing observations are suggested for merge; merging moves links and
// resolves the source.
func TestMergeThreads(t *testing.T) {
k := newTestDB(t)
var ids []int64
for i := 0; i < 3; i++ {
o := obs(fmt.Sprintf("fp%d", i), fmt.Sprintf("t%d", i), "s")
o.SourceID = "gitea" // merge signals use work sources
oid, _, _ := k.RecordObservation(o)
ids = append(ids, oid)
}
a, _ := k.CreateThread("A", "", "medium", "[]", "{}")
b, _ := k.CreateThread("B", "", "medium", "[]", "{}")
for _, oid := range ids {
k.LinkObservationToThread(a, oid, "")
k.LinkObservationToThread(b, oid, "")
}
sug, err := k.MergeSuggestions(3, 0.3)
if err != nil {
t.Fatal(err)
}
if len(sug) != 1 || sug[0].Shared != 3 {
t.Fatalf("expected one suggestion with shared=3, got %+v", sug)
}
if err := k.MergeThreads(a, b); err != nil {
t.Fatal(err)
}
if tb, _ := k.GetThread(b); tb.Status != "resolved" {
t.Fatalf("merged-from thread status=%q, want resolved", tb.Status)
}
var n int
k.db.QueryRow("SELECT COUNT(*) FROM thread_observations WHERE thread_id=?", a).Scan(&n)
if n != 3 {
t.Fatalf("into thread has %d links, want 3", n)
}
}
// SetThreadSummary clears the resummary-due flag; CurrentFocus tracks recent link counts.
func TestThreadSummaryAndFocus(t *testing.T) {
k := newTestDB(t)
o := obs("fp1", "focus topic", "s")
o.SourceID = "gitea" // CurrentFocus counts work sources only
oid, _, _ := k.RecordObservation(o)
a, _ := k.CreateThread("focus topic", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oid, "")
if err := k.SetThreadSummary(a, "current state of work"); err != nil {
t.Fatal(err)
}
as, _ := k.GroomThreads(30)
for _, x := range as {
if x.ID == a {
if x.Summary != "current state of work" {
t.Fatalf("summary not stored: %q", x.Summary)
}
if x.ResummaryDue {
t.Fatal("freshly summarized thread should not be due")
}
}
}
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != a || recent < 1 {
t.Fatalf("CurrentFocus = (%d,%d,%v), want thread %d", id, recent, err, a)
}
}
// A retained thread is never denied nor resolved by the denylist pass.
func TestThreadRetained(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
id, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(id, bid, "")
if err := k.SetThreadRetained(id, true); err != nil {
t.Fatal(err)
}
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
for _, a := range as {
if a.ID != id {
continue
}
if !a.Retained {
t.Fatal("thread not reported retained")
}
if a.Denied || a.Verdict == "deny" {
t.Fatalf("retained thread still denied (verdict=%q)", a.Verdict)
}
}
if _, closed, _ := k.DenyThreadNoise(false); len(closed) != 0 {
t.Fatalf("retained thread was resolved: %v", closed)
}
}
// Status is derived: active while recently active, stalled once quiet, and
// resolved only when explicitly closed.
func TestThreadEffectiveStatus(t *testing.T) {
k := newTestDB(t)
recent := obs("fpA", "active thread", "s")
recent.CreatedAt = time.Now().UTC().Format(time.RFC3339)
oa, _, _ := k.RecordObservation(recent)
a, _ := k.CreateThread("active thread", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oa, "")
old := obs("fpB", "old thread", "s")
old.CreatedAt = "2020-01-01T00:00:00Z"
ob, _, _ := k.RecordObservation(old)
b, _ := k.CreateThread("old thread", "", "high", "[]", "{}")
k.LinkObservationToThread(b, ob, "")
c, _ := k.CreateThread("empty thread", "", "high", "[]", "{}")
statusOf := func(id int64, filter string) string {
ts, _ := k.ListThreads(filter)
for _, x := range ts {
if x.ID == id {
return x.Status
}
}
return ""
}
if statusOf(a, "all") != "active" {
t.Fatalf("recent thread should be active")
}
if statusOf(b, "all") != "stalled" {
t.Fatalf("old thread should be stalled")
}
// A brand-new thread with no observations yet is active (falls back to its
// created_at), not immediately stalled.
if statusOf(c, "all") != "active" {
t.Fatalf("new empty thread should be active, got %q", statusOf(c, "all"))
}
if statusOf(b, "active") != "" {
t.Fatalf("stalled thread must not match active filter")
}
if statusOf(b, "stalled") != "stalled" {
t.Fatalf("stalled filter must return stalled thread")
}
// Explicit resolution wins and is sticky.
if err := k.CloseThread(a); err != nil {
t.Fatal(err)
}
if statusOf(a, "all") != "resolved" || statusOf(a, "resolved") != "resolved" {
t.Fatalf("closed thread should be resolved")
}
}
// Rebuild must take the latest observation's content, not an arbitrary row.
func TestRebuildPicksLatestContent(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "t", "s")); err != nil {
t.Fatal(err)
}
b := obs("fp1", "t", "s")
b.Content = "full body text"
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if _, _, err := k.RebuildEntriesFromObservations(); err != nil {
t.Fatal(err)
}
var content string
if err := k.db.QueryRow("SELECT content FROM entries WHERE fingerprint='fp1'").Scan(&content); err != nil {
t.Fatal(err)
}
if content != "full body text" {
t.Fatalf("entry content=%q, want latest observation's", content)
}
}
// CurrentFocus ignores passive browsing: a browser-heavy thread must not win
// over a thread with fewer but work-source observations.
func TestCurrentFocusIgnoresBrowser(t *testing.T) {
k := newTestDB(t)
bt, _ := k.CreateThread("dashboard", "", "medium", "[]", "{}")
for i := 0; i < 5; i++ {
b := obs(fmt.Sprintf("b%d", i), "Uptime Kuma", "https://uptime.example/")
b.SourceID = "browser-history"
b.SourcePath = fmt.Sprintf("https://uptime.example/%d", i)
oid, _, _ := k.RecordObservation(b)
k.LinkObservationToThread(bt, oid, "")
}
wt, _ := k.CreateThread("zigbee stack", "", "medium", "[]", "{}")
w := obs("w1", "zigbee stack work", "mosquitto")
w.SourceID = "gitea"
w.SourcePath = "david/x"
oid, _, _ := k.RecordObservation(w)
k.LinkObservationToThread(wt, oid, "")
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != wt || recent != 1 {
t.Fatalf("CurrentFocus=(%d,%d,%v), want work thread %d", id, recent, err, wt)
}
}
// Newly-arrived observations link to existing threads once (bounded by watermark).
func TestAutoLinkNewObservations(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("zigbee docker stack", "", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp1", "zigbee docker stack notes", "mosquitto compose")); err != nil {
t.Fatal(err)
}
n, err := k.AutoLinkNewObservations()
if err != nil {
t.Fatal(err)
}
if n < 1 {
t.Fatalf("expected >=1 link, got %d", n)
}
// Second pass: nothing new (watermark advanced).
if n2, _ := k.AutoLinkNewObservations(); n2 != 0 {
t.Fatalf("second pass linked %d, want 0", n2)
}
}
// GroomThreads flags a denylisted, non-work thread as "deny" and a
// work-anchored thread as not-denied, and offers a profile-derived title.
func TestGroomThreads(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
denyID, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(denyID, bid, "")
w := obs("fpw", "nr-flow-validator", "rego validation work")
w.SourceID = "gitea"
w.SourcePath = "klubhaus/nr-flow-validator"
wid, _, _ := k.RecordObservation(w)
workID, _ := k.CreateThread("nr-flow-validator Rego validation", "real work", "high", "[]", "{}")
k.LinkObservationToThread(workID, wid, "")
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
byID := map[int64]ThreadAssessment{}
for _, a := range as {
byID[a.ID] = a
}
if byID[denyID].Verdict != "deny" {
t.Errorf("deny thread verdict=%q, want deny", byID[denyID].Verdict)
}
if !byID[denyID].Denied || byID[denyID].DenyMatch == "" {
t.Errorf("deny thread should be flagged with a match")
}
if byID[workID].Verdict == "deny" {
t.Errorf("work thread must not be denied")
}
if !byID[workID].WorkAnchored {
t.Errorf("work thread should be work-anchored")
}
// Human titles get no suggestion; auto-style/denied titles do.
if byID[workID].SuggestedTitle != "" {
t.Errorf("human-titled thread should have no suggested title, got %q", byID[workID].SuggestedTitle)
}
if byID[denyID].SuggestedTitle == "" {
t.Errorf("auto-style/denied thread should have a suggested title")
}
}
// DenyThreadNoise drops denylisted browser links and resolves a denylisted
// thread that has no work-source anchor.
func TestDenyThreadNoise(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/cards")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/cards"
obsID, _, err := k.RecordObservation(b)
if err != nil {
t.Fatal(err)
}
id, err := k.CreateThread("privacy / virtual / card", "virtual cards", "medium", "[]", "{}")
if err != nil {
t.Fatal(err)
}
if err := k.LinkObservationToThread(id, obsID, ""); err != nil {
t.Fatal(err)
}
removed, closed, err := k.DenyThreadNoise(false)
if err != nil {
t.Fatal(err)
}
if removed < 1 {
t.Fatalf("removed=%d, want >=1", removed)
}
found := false
for _, c := range closed {
if c == id {
found = true
}
}
if !found {
t.Fatalf("thread #%d not closed; closed=%v", id, closed)
}
t2, _ := k.GetThread(id)
if t2.Status != "resolved" {
t.Fatalf("status=%q, want resolved", t2.Status)
}
}
// A one-character typo should still match via the vocabulary fuzzy fallback.
func TestSearchFuzzyTypo(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "amazon web services", "cloud hosting")
r.Content = "amazon web services documentation and pricing"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
for _, typo := range []string{"amazn", "servies"} {
got, err := k.Search(typo, 10)
if err != nil {
t.Fatal(err)
}
if len(got) == 0 {
t.Fatalf("typo %q returned no results", typo)
}
}
}
// "all"/empty must list every thread; the literal 'all' previously matched none.
func TestListThreadsAll(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("T", "motivation", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
for _, status := range []string{"", "all", "ALL"} {
got, err := k.ListThreads(status)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("ListThreads(%q)=%d threads, want 1", status, len(got))
}
}
}
func tmpDB(t *testing.T) *KnoxDB {
t.Helper()
kdb, err := Open(filepath.Join(t.TempDir(), "index.db"))
+9 -5
View File
@@ -27,6 +27,8 @@ type GossipObservation struct {
IngesterVersion string
Trigger string
Provenance string
ContentHash string `json:"content_hash,omitempty"`
Content string `json:"content,omitempty"`
}
// PushObservations inserts gossip rows idempotently. Rows whose (node_id, hcl)
@@ -58,11 +60,11 @@ func (k *KnoxDB) PushObservations(rows []GossipObservation) (int, error) {
`INSERT OR IGNORE INTO observations
(fingerprint, source_id, source_path, project, content_type, title, summary,
collected_at, created_at, line_start, line_end, confidence, ingester_version, trigger, provenance,
node_id, hcl)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
content_hash, content, node_id, hcl)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
o.Fingerprint, o.SourceID, o.SourcePath, o.Project, o.ContentType, o.Title, o.Summary,
o.CollectedAt, o.CreatedAt, o.LineStart, o.LineEnd, o.Confidence, o.IngesterVersion, o.Trigger, o.Provenance,
o.NodeID, o.HCL,
o.ContentHash, o.Content, o.NodeID, o.HCL,
)
if err != nil {
return inserted, fmt.Errorf("push observation: %w", err)
@@ -84,7 +86,8 @@ func (k *KnoxDB) ObservationsAfter(nodeID string, after int64, limit int) ([]Gos
COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''),
COALESCE(collected_at,''), COALESCE(created_at,''),
COALESCE(line_start,0), COALESCE(line_end,0), COALESCE(confidence,0.5),
COALESCE(ingester_version,''), COALESCE(trigger,''), COALESCE(provenance,'{}')
COALESCE(ingester_version,''), COALESCE(trigger,''), COALESCE(provenance,'{}'),
COALESCE(content_hash,''), COALESCE(content,'')
FROM observations WHERE node_id=?`
args := []any{nodeID}
if after > 0 {
@@ -105,7 +108,8 @@ func (k *KnoxDB) ObservationsAfter(nodeID string, after int64, limit int) ([]Gos
var o GossipObservation
if err := rows.Scan(&o.NodeID, &o.HCL, &o.Fingerprint, &o.SourceID, &o.SourcePath,
&o.Project, &o.ContentType, &o.Title, &o.Summary, &o.CollectedAt, &o.CreatedAt,
&o.LineStart, &o.LineEnd, &o.Confidence, &o.IngesterVersion, &o.Trigger, &o.Provenance); err != nil {
&o.LineStart, &o.LineEnd, &o.Confidence, &o.IngesterVersion, &o.Trigger, &o.Provenance,
&o.ContentHash, &o.Content); err != nil {
return nil, err
}
out = append(out, o)
+71 -1
View File
@@ -19,6 +19,8 @@ CREATE TABLE IF NOT EXISTS observations (
ingester_version TEXT DEFAULT '1',
trigger TEXT,
provenance TEXT DEFAULT '{}',
content_hash TEXT DEFAULT '',
content TEXT DEFAULT '',
node_id TEXT NOT NULL DEFAULT '',
hcl INTEGER,
received_at TEXT
@@ -40,6 +42,7 @@ CREATE TABLE IF NOT EXISTS entries (
content_type TEXT,
title TEXT,
summary TEXT,
content TEXT DEFAULT '',
first_seen TEXT,
last_seen TEXT,
ref_count INTEGER DEFAULT 1,
@@ -50,6 +53,21 @@ CREATE INDEX IF NOT EXISTS idx_entries_project ON entries(project);
CREATE INDEX IF NOT EXISTS idx_entries_source ON entries(source_id);
CREATE INDEX IF NOT EXISTS idx_entries_seen ON entries(last_seen);
-- FULL-TEXT SEARCH: external-content FTS5 over entries, kept in sync by
-- triggers. BM25-ranked; entries_vocab exposes the term list for typo fallback.
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(title, project, summary, content, content='entries', content_rowid='rowid');
CREATE VIRTUAL TABLE IF NOT EXISTS entries_vocab USING fts5vocab(entries_fts, 'row');
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
-- PROVENANCE LINKS: multi-hop lineage between entries
CREATE TABLE IF NOT EXISTS provenance_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -102,7 +120,10 @@ CREATE TABLE IF NOT EXISTS threads (
resolved_at TEXT,
tags TEXT DEFAULT '[]',
provenance TEXT DEFAULT '{}',
cluster_key TEXT
cluster_key TEXT,
retained INTEGER DEFAULT 0,
summary TEXT DEFAULT '',
summarized_at TEXT DEFAULT ''
);
-- SETTINGS: key-value store for runtime configuration
@@ -146,4 +167,53 @@ CREATE TABLE IF NOT EXISTS topics (
score REAL DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
-- SNIPPETS: code lifted from sessions that demonstrably worked. Two-phase by
-- design: the daemon deterministically extracts *candidates* (no LLM) using
-- conservative success signals (tool completed, bash exit 0, not later
-- overwritten), and an agent curates them via the MCP encode/reject tools.
-- status: candidate | encoded | rejected. superseded_by hides dead ends.
CREATE TABLE IF NOT EXISTS snippets (
fingerprint TEXT PRIMARY KEY, -- content hash of code+language
language TEXT DEFAULT '',
code TEXT NOT NULL,
title TEXT DEFAULT '',
description TEXT DEFAULT '',
tags TEXT DEFAULT '[]',
status TEXT DEFAULT 'candidate',
source_session TEXT DEFAULT '',
source_path TEXT DEFAULT '', -- file the snippet touched (edit/write)
source_entry TEXT DEFAULT '', -- session entry fingerprint
project TEXT DEFAULT '',
tool TEXT DEFAULT '', -- edit | write | bash
model TEXT DEFAULT '',
patch_hash TEXT DEFAULT '',
evidence TEXT DEFAULT '{}', -- JSON: why it counts as "worked"
superseded_by TEXT DEFAULT '', -- later full rewrite of the same file
skill_name TEXT DEFAULT '', -- set when encoded into a ~/.skills entry
reject_reason TEXT DEFAULT '',
junk INTEGER DEFAULT 0, -- heuristic: imports/directives/single-line/empty-body stub
kind TEXT DEFAULT 'code', -- code | technique (how you explored/troubleshot)
discovered_at TEXT DEFAULT (datetime('now')),
reviewed_at TEXT DEFAULT '',
encoded_at TEXT DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_snips_status ON snippets(status);
CREATE INDEX IF NOT EXISTS idx_snips_lang ON snippets(language);
CREATE INDEX IF NOT EXISTS idx_snips_project ON snippets(project);
CREATE INDEX IF NOT EXISTS idx_snips_session ON snippets(source_session);
-- FULL-TEXT SEARCH over snippets, kept in sync by triggers (same pattern as entries_fts).
CREATE VIRTUAL TABLE IF NOT EXISTS snippets_fts USING fts5(title, description, code, language, tags, content='snippets', content_rowid='rowid');
CREATE TRIGGER IF NOT EXISTS snippets_ai AFTER INSERT ON snippets BEGIN
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_ad AFTER DELETE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_au AFTER UPDATE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;
`