package db import ( "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "fmt" "math" "os" "path/filepath" "regexp" "sort" "strconv" "strings" "sync" "time" "unicode" "github.com/david/knox/internal/hlc" "github.com/david/knox/internal/noise" _ "modernc.org/sqlite" ) const goldenMinConfidence = 0.7 type KnoxDB struct { db *sql.DB nodeID string clock *hlc.Clock // writeMu serializes the check-then-insert dedup in RecordObservation within // this process. Cross-process serialization comes from _txlock=immediate (the // write lock is taken at BEGIN, before the dedup read) plus a single // connection per pool. writeMu sync.Mutex } type Observation struct { ID int64 Fingerprint string SourceID string SourcePath string Project string ContentType string Title string Summary string CollectedAt string CreatedAt string LineStart int LineEnd int Confidence float64 IngesterVersion string Trigger string Count int // duplicates collapsed by ObservationsByFingerprint } type Entry struct { Fingerprint string SourceID string SourcePath string Project string ContentType string Title string Summary string FirstSeen string LastSeen string CreatedAt string RefCount int LastConfidence float64 } type SessionRow struct { SessionID string Project string Title string Status string AgentCount int StartedAt string EndedAt string LastSeen string Indexed bool } type ObservationRecord struct { Fingerprint string SourceID string SourcePath string Project string ContentType string Title string Summary string CreatedAt string LineStart int LineEnd int Confidence float64 IngesterVersion string Trigger string Provenance string // ContentHash, when non-empty, is the change signal: two observations with // the same hash are the same knowledge even if their extent grew. ContentHash string // Content is the full searchable body (transcript, note text, log errors). // Distinct from Summary, which is a short human preview. Content string } // Snippet is a code extract that demonstrably worked in a session. Candidates // are produced deterministically by the ingest extractor; an agent curates // them (encode/reject) via the MCP tools. type Snippet struct { Fingerprint string Language string Code string Title string Description string Tags string Status string SourceSession string SourcePath string SourceEntry string Project string Tool string Model string PatchHash string Evidence string SupersededBy string SkillName string RejectReason string Junk bool Kind string DiscoveredAt string ReviewedAt string EncodedAt string } // SnippetRecord is the insert payload for a candidate snippet. type SnippetRecord struct { Fingerprint string Language string Code string Title string Description string Tags string SourceSession string SourcePath string SourceEntry string Project string Tool string Model string PatchHash string Evidence string SupersededBy string Junk bool Kind string } func Open(path string) (*KnoxDB, error) { dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0755); err != nil { return nil, fmt.Errorf("create db dir: %w", err) } db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_txlock=immediate") if err != nil { return nil, fmt.Errorf("open db: %w", err) } // One connection per process: WAL has a single writer; serializing on one // connection avoids pool contention surfacing as busy_timeout errors. db.SetMaxOpenConns(1) if _, err := db.Exec(Schema); err != nil { return nil, fmt.Errorf("init schema: %w", err) } // Migrations: safe ALTER TABLE for existing databases migrations := []string{ "ALTER TABLE threads ADD COLUMN provenance TEXT DEFAULT '{}'", "ALTER TABLE entries ADD COLUMN created_at TEXT DEFAULT ''", "ALTER TABLE observations ADD COLUMN node_id TEXT NOT NULL DEFAULT ''", "ALTER TABLE observations ADD COLUMN hcl INTEGER", "ALTER TABLE observations ADD COLUMN received_at TEXT", "ALTER TABLE observations ADD COLUMN content_hash TEXT DEFAULT ''", "ALTER TABLE observations ADD COLUMN content TEXT DEFAULT ''", "ALTER TABLE entries ADD COLUMN content TEXT DEFAULT ''", "ALTER TABLE threads ADD COLUMN cluster_key TEXT", "ALTER TABLE threads ADD COLUMN retained INTEGER DEFAULT 0", "ALTER TABLE threads ADD COLUMN summary TEXT DEFAULT ''", "ALTER TABLE threads ADD COLUMN summarized_at TEXT DEFAULT ''", "ALTER TABLE snippets ADD COLUMN junk INTEGER DEFAULT 0", "ALTER TABLE snippets ADD COLUMN kind TEXT DEFAULT 'code'", } for _, m := range migrations { if _, err := db.Exec(m); err != nil && !strings.Contains(err.Error(), "duplicate column") { return nil, fmt.Errorf("migration failed: %w", err) } } kdb := &KnoxDB{db: db, clock: hlc.New()} // Node identity: generated once, persisted in settings. Stable across // restarts so gossip cursors and locator IDs survive. nodeID, err := kdb.loadNodeID() if err != nil { return nil, err } kdb.nodeID = nodeID // Backfill: rows added before node_id existed belong to this node, and // their HCL is their local rowid (monotonic, so ordering is preserved). if _, err := db.Exec("UPDATE observations SET node_id=? WHERE node_id=''", nodeID); err != nil { return nil, fmt.Errorf("backfill node_id: %w", err) } if _, err := db.Exec("UPDATE observations SET hcl=id WHERE hcl IS NULL"); err != nil { return nil, fmt.Errorf("backfill hcl: %w", err) } // Resume this node's HLC from its persisted max: a restart with a regressed // wall clock must not reissue already-persisted values (see hlc.SeekTo). var maxHCL int64 if err := db.QueryRow(`SELECT COALESCE(MAX(hcl), 0) FROM observations WHERE node_id=?`, nodeID).Scan(&maxHCL); err != nil { return nil, fmt.Errorf("seed hlc: %w", err) } kdb.clock.SeekTo(maxHCL) // Locator uniqueness: (node_id, hcl) is the merge key for gossip; a given // node's HCL is strictly monotonic so this never throws a false conflict. if _, err := db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_obs_locator ON observations(node_id, hcl)`); err != nil { return nil, fmt.Errorf("create locator index: %w", err) } // Thread idempotency index must come after the cluster_key migration (a // fresh DB has the column from Schema; an existing DB gets it above). if _, err := db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_threads_cluster ON threads(cluster_key) WHERE cluster_key IS NOT NULL AND cluster_key != ''`); err != nil { return nil, fmt.Errorf("create cluster_key index: %w", err) } // One-time full-text index build for databases that predate the FTS5 // tables (triggers keep it current afterwards). if kdb.getSetting("fts_ready") != "1" { if _, err := db.Exec(`INSERT INTO entries_fts(entries_fts) VALUES('rebuild')`); err != nil { return nil, fmt.Errorf("build fts index: %w", err) } if err := kdb.setSetting("fts_ready", "1"); err != nil { return nil, err } } return kdb, nil } // Setting reads a value from the settings table ("" when absent). func (k *KnoxDB) Setting(key string) string { return k.getSetting(key) } // SetSetting writes a value into the settings table. func (k *KnoxDB) SetSetting(key, val string) error { return k.setSetting(key, val) } func (k *KnoxDB) getSetting(key string) string { var v string if err := k.db.QueryRow(`SELECT value FROM settings WHERE key=?`, key).Scan(&v); err != nil { return "" } return v } func (k *KnoxDB) setSetting(key, val string) error { _, err := k.db.Exec( `INSERT INTO settings (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=?`, key, val, val, ) return err } const nodeIDKey = "node_id" // loadNodeID reads the persisted node identity, creating one if absent. func (k *KnoxDB) loadNodeID() (string, error) { var id string err := k.db.QueryRow(`SELECT value FROM settings WHERE key=?`, nodeIDKey).Scan(&id) if err == nil && id != "" { return id, nil } if err != nil && err != sql.ErrNoRows { return "", fmt.Errorf("read node_id: %w", err) } buf := make([]byte, 16) if _, err := rand.Read(buf); err != nil { return "", fmt.Errorf("generate node_id: %w", err) } id = hex.EncodeToString(buf) if _, err := k.db.Exec( `INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=?`, nodeIDKey, id, id, ); err != nil { return "", fmt.Errorf("persist node_id: %w", err) } return id, nil } // NodeID returns this node's stable identity. func (k *KnoxDB) NodeID() string { return k.nodeID } func (k *KnoxDB) Close() error { return k.db.Close() } // EntryCount returns the number of entries in the materialized cache. func (k *KnoxDB) EntryCount() (int, error) { var n int err := k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&n) return n, err } // ObservationEntryEstimate is the number of distinct fingerprints in the // observation log — the ground-truth size reconcile's rebuild would produce. func (k *KnoxDB) ObservationEntryEstimate() int { var n int if err := k.db.QueryRow("SELECT COUNT(DISTINCT fingerprint) FROM observations").Scan(&n); err != nil { return -1 } return n } // RecordObservation appends an immutable observation and updates the entries cache. // Idempotent: if the latest observation for this fingerprint has an identical // content signature, nothing is recorded — re-ingesting unchanged content is a no-op. func (k *KnoxDB) RecordObservation(o ObservationRecord) (obsID int64, isNew bool, err error) { k.writeMu.Lock() defer k.writeMu.Unlock() tx, err := k.db.Begin() if err != nil { return 0, false, fmt.Errorf("begin tx: %w", err) } defer tx.Rollback() hclVal, hclWall := k.clock.Now() now := hclWall.Format(time.RFC3339) // Dedup: compare against the latest observation of the same fingerprint. // A non-empty content_hash is the change signal when present — sources like // logs hash their meaningful content, so a grown file with the same error // set collapses to a no-op. Otherwise fall back to field comparison: for // content sources (LineEnd > 0) the extent/summary IS the change signal — // created_at is just the file mtime, which can twitch without content change // (live log files). For extent-less sources (browser, gitea), created_at is // the only change signal (revisit, issue update) so it must match. var prevID int64 var pTitle, pSummary, pProject, pCreated, pContent string var pStart, pEnd int var pContentLen int64 err = tx.QueryRow( `SELECT id, COALESCE(title,''), COALESCE(summary,''), COALESCE(project,''), COALESCE(created_at,''), COALESCE(line_start,0), COALESCE(line_end,0), COALESCE(content_hash,''), COALESCE(LENGTH(content),0) FROM observations WHERE fingerprint=? ORDER BY hcl DESC, id DESC LIMIT 1`, o.Fingerprint, ).Scan(&prevID, &pTitle, &pSummary, &pProject, &pCreated, &pStart, &pEnd, &pContent, &pContentLen) sameContent := int64(len(o.Content)) == pContentLen switch err { case nil: if o.ContentHash != "" && o.ContentHash == pContent && sameContent { return prevID, false, tx.Commit() // same content, no change } if o.ContentHash == "" && sameContent && pTitle == o.Title && pSummary == o.Summary && pProject == o.Project && pStart == o.LineStart && pEnd == o.LineEnd && (o.LineEnd > 0 || pCreated == o.CreatedAt) { return prevID, false, tx.Commit() // unchanged } case sql.ErrNoRows: // first observation of this fingerprint — proceed default: return 0, false, fmt.Errorf("check previous observation: %w", err) } res, err := tx.Exec( `INSERT 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, content_hash, content, node_id, hcl, received_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, o.Fingerprint, o.SourceID, o.SourcePath, o.Project, o.ContentType, o.Title, o.Summary, now, o.CreatedAt, o.LineStart, o.LineEnd, o.Confidence, o.IngesterVersion, o.Trigger, o.Provenance, o.ContentHash, o.Content, k.nodeID, hclVal, time.Now().UTC().Format(time.RFC3339), ) if err != nil { return 0, false, fmt.Errorf("insert observation: %w", err) } obsID, _ = res.LastInsertId() // Update materialized entries cache var existingFirstSeen string err = tx.QueryRow("SELECT first_seen FROM entries WHERE fingerprint=?", o.Fingerprint).Scan(&existingFirstSeen) isNew = false if err == sql.ErrNoRows { isNew = true _, err = tx.Exec( `INSERT INTO entries (fingerprint, source_id, source_path, project, content_type, title, summary, content, first_seen, last_seen, created_at, ref_count, last_confidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`, o.Fingerprint, o.SourceID, o.SourcePath, o.Project, o.ContentType, o.Title, o.Summary, o.Content, now, now, coalesceCreatedAt(o.CreatedAt), o.Confidence, ) } else if err == nil { _, err = tx.Exec( `UPDATE entries SET last_seen=?, ref_count=ref_count+1, last_confidence=?, source_path=COALESCE(NULLIF(?,''), source_path), title=COALESCE(NULLIF(?,''), title), summary=COALESCE(NULLIF(?,''), summary), content=COALESCE(NULLIF(?,''), content), created_at=COALESCE(NULLIF(?,''), created_at) WHERE fingerprint=?`, now, o.Confidence, o.SourcePath, o.Title, o.Summary, o.Content, o.CreatedAt, o.Fingerprint, ) } if err != nil { return 0, false, fmt.Errorf("update entries cache: %w", err) } // Auto-link to golden thread (only if relevant). Browsing is context, not // thread membership, so browser observations never link. if goldenID, keywords, bigrams := k.goldenThreadKeywords(tx); goldenID > 0 && len(keywords) > 0 { if o.SourceID != "browser-history" && o.Confidence >= goldenMinConfidence && isRelevant(o.Title, o.Summary, o.Project, o.Content, keywords, bigrams) { res, err := tx.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'auto')`, goldenID, obsID, ) if err != nil { return 0, false, fmt.Errorf("auto-link golden thread: %w", err) } affected, _ := res.RowsAffected() linked := affected > 0 if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, goldenID); err != nil { return 0, false, fmt.Errorf("bump golden thread updated_at: %w", err) } // Temporal cross-reference: when a high-signal non-browser event links, // nearby browser history (±1h) becomes thread context too. if linked && o.SourceID != "browser-history" && o.CreatedAt != "" { if err := k.linkTemporalNeighbors(tx, goldenID, o.CreatedAt, keywords, bigrams); err != nil { return 0, false, fmt.Errorf("link temporal neighbors: %w", err) } } } } return obsID, isNew, tx.Commit() } // linkTemporalNeighbors links browser-history observations within ±1h of a // signal timestamp to the thread. A weak keyword check still applies so // unrelated browsing (lunch news) doesn't pollute the thread. func (k *KnoxDB) linkTemporalNeighbors(tx *sql.Tx, threadID int64, createdAt string, keywords []string, bigrams [][2]string) error { rows, err := tx.Query( `SELECT o.id, COALESCE(o.title,''), COALESCE(o.summary,'') FROM observations o WHERE o.source_id='browser-history' AND o.created_at != '' AND ABS(strftime('%s', o.created_at) - strftime('%s', ?)) <= 3600 GROUP BY o.fingerprint`, createdAt, ) if err != nil { return err } defer rows.Close() for rows.Next() { var obsID int64 var title, summary string if err := rows.Scan(&obsID, &title, &summary); err != nil { return err } if isRelevant(title, summary, "", "", keywords, bigrams) || weakRelevant(title, summary, keywords) { if _, err := tx.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'temporal')`, threadID, obsID, ); err != nil { return err } } } return rows.Err() } // weakRelevant is a lower bar for temporal neighbors: any single keyword match. func weakRelevant(title, summary string, keywords []string) bool { text := strings.ToLower(title + " " + summary) for _, t := range wordBoundaryRE.FindAllString(text, -1) { for _, kw := range keywords { if t == kw { return true } } } return false } // FindEntry returns current entry from materialized cache. func (k *KnoxDB) FindEntry(fingerprint string) (*Entry, error) { row := k.db.QueryRow( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE fingerprint=?`, fingerprint, ) e := &Entry{} err := row.Scan(&e.Fingerprint, &e.SourceID, &e.SourcePath, &e.Project, &e.ContentType, &e.Title, &e.Summary, &e.FirstSeen, &e.LastSeen, &e.CreatedAt, &e.RefCount, &e.LastConfidence) if err == sql.ErrNoRows { return nil, nil } return e, err } // ObservationsByFingerprint returns the observation history for a fingerprint, // collapsing exact duplicates (same summary/signal-time/extent) into one row // with a Count — re-observations of unchanged content are noise, not signal. // LatestContentHash returns the content hash of the most recent observation for // a fingerprint, or "" when none carries one. Ingesters use it to detect a // content-only change, which a summary comparison misses. func (k *KnoxDB) LatestContentHash(fp string) (string, error) { var h string err := k.db.QueryRow( `SELECT COALESCE(content_hash,'') FROM observations WHERE fingerprint=? ORDER BY id DESC LIMIT 1`, fp, ).Scan(&h) if err == sql.ErrNoRows { return "", nil } return h, err } func (k *KnoxDB) ObservationsByFingerprint(fp string, limit int) ([]Observation, error) { if limit <= 0 { limit = 50 } rows, err := k.db.Query( `SELECT MAX(id), fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), MAX(collected_at), COALESCE(created_at,''), COALESCE(line_start,0), COALESCE(line_end,0), confidence, ingester_version, COALESCE(trigger,''), COUNT(*) FROM observations WHERE fingerprint=? GROUP BY COALESCE(summary,''), COALESCE(created_at,''), COALESCE(line_end,0) ORDER BY MAX(collected_at) DESC LIMIT ?`, fp, limit, ) if err != nil { return nil, err } defer rows.Close() var obs []Observation for rows.Next() { var o Observation if err := rows.Scan(&o.ID, &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.Count); err != nil { return nil, err } obs = append(obs, o) } return obs, nil } // RebuildEntriesFromObservations drops and rebuilds the entries cache from observations. // coalesceCreatedAt prefers the observation's signal time, falling back to ingestion time. func coalesceCreatedAt(s string) string { if s != "" { return s } return time.Now().UTC().Format(time.RFC3339) } func (k *KnoxDB) RebuildEntriesFromObservations() (before, after int, err error) { tx, err := k.db.Begin() if err != nil { return 0, 0, err } defer tx.Rollback() var b int if err := tx.QueryRow("SELECT COUNT(*) FROM entries").Scan(&b); err != nil { return 0, 0, err } if _, err := tx.Exec("DELETE FROM entries"); err != nil { return 0, 0, err } // Content fields come from the latest observation per fingerprint, folded in // a total order (hcl DESC, node_id DESC, id DESC) — deterministic for any two // nodes holding identical logs, per the gossip spec (a bare GROUP BY column // picks an arbitrary, merge-order-dependent row). _, err = tx.Exec( `INSERT INTO entries (fingerprint, source_id, source_path, project, content_type, title, summary, content, first_seen, last_seen, created_at, ref_count, last_confidence) SELECT l.fingerprint, l.source_id, l.source_path, l.project, l.content_type, l.title, l.summary, l.content, agg.first_seen, agg.last_seen, COALESCE(NULLIF(l.created_at,''), agg.first_seen), agg.cnt, agg.conf FROM ( SELECT fingerprint, source_id, source_path, project, content_type, title, summary, content, created_at, ROW_NUMBER() OVER (PARTITION BY fingerprint ORDER BY COALESCE(hcl,0) DESC, node_id DESC, id DESC) AS rn FROM observations ) l JOIN ( SELECT fingerprint, MIN(collected_at) AS first_seen, MAX(collected_at) AS last_seen, COUNT(*) AS cnt, MAX(confidence) AS conf FROM observations GROUP BY fingerprint ) agg ON agg.fingerprint = l.fingerprint WHERE l.rn = 1`, ) if err != nil { return 0, 0, fmt.Errorf("rebuild entries: %w", err) } var a int if err := tx.QueryRow("SELECT COUNT(*) FROM entries").Scan(&a); err != nil { return 0, 0, err } if err := tx.Commit(); err != nil { return 0, 0, err } return b, a, nil } // EntriesByProject returns entries from the materialized cache. func (k *KnoxDB) EntriesByProject(project string, limit int) ([]Entry, error) { if limit <= 0 { limit = 50 } rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE project=? ORDER BY last_seen DESC LIMIT ?`, project, limit, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } func (k *KnoxDB) RecentEntriesBySource(sourceID string, limit int) ([]Entry, error) { if limit <= 0 { limit = 10 } rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE source_id=? ORDER BY last_seen DESC LIMIT ?`, sourceID, limit, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } // EntriesBySource returns all entries for a source ordered by title (for // stable project-status listings like git repo snapshots). func (k *KnoxDB) EntriesBySource(sourceID string) ([]Entry, error) { rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE source_id=? ORDER BY title COLLATE NOCASE`, sourceID, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } func (k *KnoxDB) RecentEntries(limit int) ([]Entry, error) { if limit <= 0 { limit = 20 } rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries ORDER BY COALESCE(NULLIF(created_at,''), last_seen) DESC LIMIT ?`, limit, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } // escapeLike escapes LIKE wildcards so user input is matched literally. func escapeLike(s string) string { s = strings.ReplaceAll(s, `\`, `\\`) s = strings.ReplaceAll(s, `%`, `\%`) s = strings.ReplaceAll(s, `_`, `\_`) return s } // searchTerms splits a query into lowercase alphanumeric terms. Multi-word // queries become an AND of terms, each of which may match any indexed field, // so "home assistant automation" finds rows containing all three anywhere // rather than requiring the literal contiguous phrase. func searchTerms(query string) []string { fields := strings.FieldsFunc(strings.ToLower(query), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) terms := make([]string, 0, len(fields)) for _, f := range fields { if len([]rune(f)) >= 2 { terms = append(terms, f) } } // Single-rune queries carry no useful signal once split; keep the raw // trimmed query so a one-character search still matches literally. if len(terms) == 0 { if t := strings.TrimSpace(strings.ToLower(query)); t != "" { terms = append(terms, t) } } return terms } // Search returns entries ranked by relevance. Tier 1 is the FTS5/BM25 index // with prefix matching; tier 2 is a typo-tolerant expansion of each term over // the FTS vocabulary; tier 3 is the original substring match. func (k *KnoxDB) Search(query string, limit int) ([]Entry, error) { if limit <= 0 { limit = 20 } terms := searchTerms(query) if len(terms) == 0 { return nil, nil } if res, err := k.searchFTS(matchAllTerms(terms), limit); err == nil && len(res) > 0 { return res, nil } if fuzzy := k.expandFuzzy(terms); fuzzy != "" { if res, err := k.searchFTS(fuzzy, limit); err == nil && len(res) > 0 { return res, nil } } return k.searchSubstring(terms, limit) } // ftsTerm renders a term as a quoted prefix query, safe for any FTS5 operator // characters the term might contain. func ftsTerm(t string) string { return `"` + strings.ReplaceAll(t, `"`, "") + `"*` } func matchAllTerms(terms []string) string { parts := make([]string, len(terms)) for i, t := range terms { parts[i] = ftsTerm(t) } return strings.Join(parts, " AND ") } // searchFTS runs a ranked BM25 query against the FTS index. func (k *KnoxDB) searchFTS(match string, limit int) ([]Entry, error) { if match == "" { return nil, nil } rows, err := k.db.Query( `SELECT e.fingerprint, e.source_id, COALESCE(e.source_path,''), COALESCE(e.project,''), COALESCE(e.content_type,''), COALESCE(e.title,''), COALESCE(e.summary,''), COALESCE(e.first_seen,''), COALESCE(e.last_seen,''), COALESCE(e.created_at,''), e.ref_count, COALESCE(e.last_confidence,0.5) FROM entries_fts f JOIN entries e ON e.rowid = f.rowid WHERE entries_fts MATCH ? ORDER BY bm25(entries_fts) LIMIT ?`, match, limit, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } // expandFuzzy maps each query term to nearby vocabulary terms (edit distance // 1, or 2 for longer terms) so typos still match. Vocabulary is bounded to the // most frequent terms to cap cost. func (k *KnoxDB) expandFuzzy(terms []string) string { rows, err := k.db.Query(`SELECT term FROM entries_vocab ORDER BY doc DESC LIMIT 4000`) if err != nil { return "" } defer rows.Close() var vocab []string for rows.Next() { var t string if rows.Scan(&t) == nil { vocab = append(vocab, t) } } if len(vocab) == 0 { return "" } groups := make([]string, 0, len(terms)) for _, term := range terms { maxDist := 1 if len(term) >= 6 { maxDist = 2 } ors := []string{ftsTerm(term)} seen := map[string]bool{term: true} for _, v := range vocab { if seen[v] || absInt(len(v)-len(term)) > maxDist { continue } if levenshtein(term, v) <= maxDist { seen[v] = true ors = append(ors, ftsTerm(v)) if len(ors) >= 8 { break } } } groups = append(groups, "("+strings.Join(ors, " OR ")+")") } return strings.Join(groups, " AND ") } // searchSubstring is the tier-3 fallback: every term must appear as a substring // in one of the indexed text fields. func (k *KnoxDB) searchSubstring(terms []string, limit int) ([]Entry, error) { conds := make([]string, 0, len(terms)) args := make([]any, 0, len(terms)*4+1) for _, term := range terms { like := "%" + escapeLike(term) + "%" conds = append(conds, `(title LIKE ? ESCAPE '\' OR summary LIKE ? ESCAPE '\' OR project LIKE ? ESCAPE '\' OR source_path LIKE ? ESCAPE '\')`) args = append(args, like, like, like, like) } args = append(args, limit) rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE `+strings.Join(conds, " AND ")+` ORDER BY last_seen DESC LIMIT ?`, args..., ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } func absInt(n int) int { if n < 0 { return -n } return n } // levenshtein is the edit distance between two (short) tokens. func levenshtein(a, b string) int { ar, br := []rune(a), []rune(b) if len(ar) == 0 { return len(br) } if len(br) == 0 { return len(ar) } prev := make([]int, len(br)+1) cur := make([]int, len(br)+1) for j := range prev { prev[j] = j } for i := 1; i <= len(ar); i++ { cur[0] = i for j := 1; j <= len(br); j++ { cost := 1 if ar[i-1] == br[j-1] { cost = 0 } cur[j] = min3(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) } prev, cur = cur, prev } return prev[len(br)] } func min3(a, b, c int) int { if b < a { a = b } if c < a { a = c } return a } // FindEntryByPrefix returns entries whose fingerprint starts with the given prefix. func (k *KnoxDB) FindEntryByPrefix(fp string, limit int) ([]Entry, error) { if limit <= 0 { limit = 5 } rows, err := k.db.Query( `SELECT fingerprint, source_id, COALESCE(source_path,''), COALESCE(project,''), COALESCE(content_type,''), COALESCE(title,''), COALESCE(summary,''), COALESCE(first_seen,''), COALESCE(last_seen,''), COALESCE(created_at,''), ref_count, COALESCE(last_confidence,0.5) FROM entries WHERE fingerprint LIKE ? || '%' LIMIT ?`, fp, limit, ) if err != nil { return nil, err } defer rows.Close() return scanEntries(rows) } func scanEntries(rows *sql.Rows) ([]Entry, error) { var entries []Entry for rows.Next() { var e Entry if err := rows.Scan(&e.Fingerprint, &e.SourceID, &e.SourcePath, &e.Project, &e.ContentType, &e.Title, &e.Summary, &e.FirstSeen, &e.LastSeen, &e.CreatedAt, &e.RefCount, &e.LastConfidence); err != nil { return nil, err } entries = append(entries, e) } if err := rows.Err(); err != nil { return nil, err } return entries, nil } // UpsertSession tracks session state. Idempotent: re-reporting the same session // updates its title/status/last_seen but does not inflate agent_count, which is // set once on first sight. func (k *KnoxDB) UpsertSession(sessionID, project, title, status string) error { now := time.Now().UTC().Format(time.RFC3339) _, err := k.db.Exec( `INSERT INTO sessions (session_id, project, title, status, started_at, last_seen, agent_count) VALUES (?, ?, ?, ?, ?, ?, 1) ON CONFLICT(session_id) DO UPDATE SET title=COALESCE(NULLIF(?,''), title), status=?, last_seen=?`, sessionID, project, title, status, now, now, title, status, now, ) return err } func (k *KnoxDB) PendingSessions() ([]SessionRow, error) { rows, err := k.db.Query( `SELECT session_id, COALESCE(project,''), COALESCE(title,''), status, agent_count, COALESCE(started_at,''), COALESCE(ended_at,''), last_seen, indexed FROM sessions WHERE indexed=0 ORDER BY last_seen DESC`, ) if err != nil { return nil, err } defer rows.Close() var sessions []SessionRow for rows.Next() { var s SessionRow if err := rows.Scan(&s.SessionID, &s.Project, &s.Title, &s.Status, &s.AgentCount, &s.StartedAt, &s.EndedAt, &s.LastSeen, &s.Indexed); err != nil { return nil, err } sessions = append(sessions, s) } return sessions, nil } func (k *KnoxDB) MarkSessionIndexed(sessionID string) error { _, err := k.db.Exec("UPDATE sessions SET indexed=1 WHERE session_id=?", sessionID) return err } // DerivedStateCounts returns the number of observations in the append-only log // and the number of materialized entries. Callers use it to decide whether the // derived cache needs rebuilding (e.g. a replica that starts with a log but no // entries because it never saw a push or pull since the cache was wiped). func (k *KnoxDB) DerivedStateCounts() (observations, entries int, err error) { if err = k.db.QueryRow("SELECT COUNT(*) FROM observations").Scan(&observations); err != nil { return 0, 0, fmt.Errorf("count observations: %w", err) } if err = k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&entries); err != nil { return 0, 0, fmt.Errorf("count entries: %w", err) } return observations, entries, nil } func (k *KnoxDB) Stats() (map[string]any, error) { stats := make(map[string]any) // A broken DB reports an error, not zeros: every aggregate is checked. countInt := func(query string) (int, error) { var v int if err := k.db.QueryRow(query).Scan(&v); err != nil { return 0, err } return v, nil } ints := []struct { key string query string }{ {"total_entries", "SELECT COUNT(*) FROM entries"}, {"entries_last_24h", "SELECT COUNT(*) FROM entries WHERE last_seen > datetime('now', '-1 day')"}, {"total_projects", "SELECT COUNT(DISTINCT project) FROM entries"}, {"total_observations", "SELECT COUNT(*) FROM observations"}, {"observations_last_24h", "SELECT COUNT(*) FROM observations WHERE collected_at > datetime('now', '-1 day')"}, {"total_sessions", "SELECT COUNT(*) FROM sessions"}, {"pending_reflections", "SELECT COUNT(*) FROM sessions WHERE indexed=0"}, } for _, it := range ints { v, err := countInt(it.query) if err != nil { return nil, fmt.Errorf("stats %s: %w", it.key, err) } stats[it.key] = v } var earliest string if err := k.db.QueryRow("SELECT COALESCE(MIN(collected_at),'') FROM observations").Scan(&earliest); err != nil { return nil, fmt.Errorf("stats earliest_observation: %w", err) } stats["earliest_observation"] = earliest // Current focus is DERIVED from normalized, source-balanced activity. if focus, err := k.ThreadFocus(focusWindowDays); err == nil && len(focus) > 0 { top := focus[0] stats["current_focus"] = top.Title stats["current_focus_id"] = top.ID stats["current_focus_recent"] = top.WorkRecent stats["current_focus_score"] = top.Score stats["current_focus_z"] = top.ZScore } // The golden thread is an explicit, optional pin (used for auto-linking); // it is reported separately and flagged when it disagrees with reality. goldenID, err := k.GoldenThreadID() if err != nil { return nil, fmt.Errorf("stats golden_thread: %w", err) } if goldenID > 0 { stats["pinned_thread_id"] = goldenID t, err := k.GetThread(goldenID) if err != nil { return nil, fmt.Errorf("stats golden_thread: %w", err) } if t != nil { stats["pinned_thread"] = t.Title } if cf, _ := stats["current_focus_id"].(int64); cf != goldenID { stats["pinned_is_stale"] = true } } return stats, nil } // ThreadFocus is a thread's normalized focus score. Rather than compare raw // counts across sources (browser history has thousands, Karakeep dozens), each // source's per-thread counts are standardized (z-score within that source), // clipped to [0, cap] and summed — so a high-volume source still contributes, // but its outlier can't dominate. ZScore positions the thread against the // "standard" (mean/std of all thread scores). type ThreadFocus struct { ID int64 Title string Score float64 ZScore float64 Total int // observations across all sources in window WorkRecent int // work-source observations in window Sources map[string]int // raw per-source counts Contrib map[string]float64 // clipped per-source z contribution } const ( focusRelCap = 3.0 // max multiples-of-the-source-mean any single source may contribute focusHalfLifeDays = 3.0 // recency decay half-life (days) // focusWindowDays is the horizon for "current focus": recent enough to be // current, long enough to survive a quiet day. focusWindowDays = 3 ) // sourceWeight scales each source's contribution to focus. Active work you do // (sessions, notes, bookmarks) counts fully; ambient/auto-collected sources // (browsing, git/gitea pulls, the skills catalog) still count, but lower. var sourceWeight = map[string]float64{ "opencode-session": 1.0, "obsidian": 1.0, "karakeep": 1.0, "git": 0.35, "gitea": 0.35, "browser-history": 0.35, "skills-catalog": 0.35, "filesystem": 0.5, } func weightFor(src string) float64 { if w, ok := sourceWeight[src]; ok { return w } return 0.5 } // ThreadFocus ranks active threads by normalized, source-balanced activity over // the last windowDays. func (k *KnoxDB) ThreadFocus(windowDays int) ([]ThreadFocus, error) { if windowDays <= 0 { windowDays = 14 } rows, err := k.db.Query( `SELECT t.id, t.title, o.source_id, COALESCE(NULLIF(o.created_at,''), o.collected_at) FROM threads t JOIN thread_observations tos ON tos.thread_id = t.id JOIN observations o ON o.id = tos.observation_id WHERE t.status='active'`) if err != nil { return nil, err } now := time.Now().UTC() type key struct { id int64 src string } wsum := map[key]float64{} byThread := map[int64]*ThreadFocus{} var order []*ThreadFocus for rows.Next() { var id int64 var title, src, tsRaw string if err := rows.Scan(&id, &title, &src, &tsRaw); err != nil { rows.Close() return nil, err } // Age from the observation's signal time (created_at) — when the work // actually happened — not ingestion time (collected_at), which is // uniform across a re-ingest and would defeat the decay. ts, perr := parseTime(tsRaw) if perr != nil { continue } ageDays := now.Sub(ts).Hours() / 24 if ageDays < 0 { ageDays = 0 } if ageDays > float64(windowDays) { continue } f := byThread[id] if f == nil { f = &ThreadFocus{ID: id, Title: title, Sources: map[string]int{}} byThread[id] = f order = append(order, f) } f.Sources[src]++ f.Total++ if workSources[src] { f.WorkRecent++ } w := math.Pow(0.5, ageDays/focusHalfLifeDays) kk := key{id, src} wsum[kk] += w } rows.Close() if len(order) == 0 { return nil, nil } // Per-source mean weighted count = the "standard" for that source. srcMean := map[string]float64{} srcN := map[string]int{} for _, f := range order { for src := range f.Sources { srcMean[src] += wsum[key{f.ID, src}] srcN[src]++ } } for src, sum := range srcMean { if srcN[src] > 0 { srcMean[src] = sum / float64(srcN[src]) } } // Score = sum over sources of the thread's relative magnitude (its weighted // count ÷ that source's mean), capped so one source can't dominate. This is // magnitude-aware (steady work counts) and scale-free per source (a sparse // source can't hand a lone thread a big score, nor can a huge one swamp). scores := make([]float64, 0, len(order)) for _, f := range order { f.Contrib = make(map[string]float64, len(f.Sources)) for src := range f.Sources { rel := 0.0 if m := srcMean[src]; m > 0 { rel = wsum[key{f.ID, src}] / m } c := weightFor(src) * rel if c > focusRelCap { c = focusRelCap } f.Contrib[src] = math.Round(c*1000) / 1000 f.Score += c } scores = append(scores, f.Score) } // Z-score of each thread's score against the population ("the standard"). smean, sstd := meanStdF(scores) for _, f := range order { if sstd > 0 { f.ZScore = math.Round(((f.Score-smean)/sstd)*100) / 100 } } sort.Slice(order, func(i, j int) bool { if order[i].Score != order[j].Score { return order[i].Score > order[j].Score } if order[i].WorkRecent != order[j].WorkRecent { return order[i].WorkRecent > order[j].WorkRecent } return order[i].Total > order[j].Total }) out := make([]ThreadFocus, len(order)) for i, f := range order { out[i] = *f } return out, nil } // parseTime parses a stored timestamp (RFC3339 from ingestion, or SQLite // datetime) and is tolerant of both. func parseTime(s string) (time.Time, error) { if t, err := time.Parse(time.RFC3339, s); err == nil { return t, nil } return time.Parse("2006-01-02 15:04:05", s) } // meanStd returns the population mean and standard deviation. func meanStd(vals []int) (float64, float64) { if len(vals) == 0 { return 0, 0 } sum := 0.0 for _, v := range vals { sum += float64(v) } mean := sum / float64(len(vals)) var ss float64 for _, v := range vals { d := float64(v) - mean ss += d * d } return mean, math.Sqrt(ss / float64(len(vals))) } // meanStdF is meanStd for float64 samples. func meanStdF(vals []float64) (float64, float64) { if len(vals) == 0 { return 0, 0 } sum := 0.0 for _, v := range vals { sum += v } mean := sum / float64(len(vals)) var ss float64 for _, v := range vals { d := v - mean ss += d * d } return mean, math.Sqrt(ss / float64(len(vals))) } // CurrentFocus derives the current focus from the normalized ThreadFocus model. // recent is the top thread's work-source observation count. func (k *KnoxDB) CurrentFocus(windowDays int) (id int64, title string, recent int, err error) { focus, err := k.ThreadFocus(windowDays) if err != nil { return 0, "", 0, err } if len(focus) == 0 { return 0, "", 0, nil } return focus[0].ID, focus[0].Title, focus[0].WorkRecent, nil } // ProvenanceChain returns the provenance link graph for a fingerprint. func (k *KnoxDB) ProvenanceChain(fp string, maxHops int) ([]struct { Fingerprint string Relation string HopDistance int }, error) { if maxHops <= 0 { maxHops = 3 } rows, err := k.db.Query( `SELECT ancestor_fp, relation, hop_distance FROM provenance_links WHERE descendant_fp=? AND hop_distance <= ? UNION SELECT descendant_fp, relation, hop_distance FROM provenance_links WHERE ancestor_fp=? AND hop_distance <= ? ORDER BY hop_distance`, fp, maxHops, fp, maxHops, ) if err != nil { return nil, err } defer rows.Close() var results []struct { Fingerprint string Relation string HopDistance int } for rows.Next() { var r struct { Fingerprint string Relation string HopDistance int } if err := rows.Scan(&r.Fingerprint, &r.Relation, &r.HopDistance); err != nil { return nil, err } results = append(results, r) } return results, nil } // ─── Golden Thread ─────────────────────────────────────────── func (k *KnoxDB) goldenThreadID(tx *sql.Tx) int64 { var id int64 err := tx.QueryRow("SELECT value FROM settings WHERE key='golden_thread_id'").Scan(&id) if err != nil { return 0 } return id } func (k *KnoxDB) GoldenThreadID() (int64, error) { var id int64 err := k.db.QueryRow("SELECT value FROM settings WHERE key='golden_thread_id'").Scan(&id) if err == sql.ErrNoRows { return 0, nil } return id, err } func (k *KnoxDB) SetGoldenThread(id int64) error { if id == 0 { _, err := k.db.Exec("DELETE FROM settings WHERE key='golden_thread_id'") return err } // Verify thread exists t, err := k.GetThread(id) if err != nil || t == nil { return fmt.Errorf("thread #%d not found", id) } _, err = k.db.Exec( "INSERT INTO settings (key, value) VALUES ('golden_thread_id', ?) ON CONFLICT(key) DO UPDATE SET value=?", id, id, ) return err } // kwCache caches DF-filtered golden-thread keywords, keyed by thread update time. var kwCache = struct { sync.Mutex threadID int64 updatedAt string keywords []string bigrams [][2]string }{threadID: -1} // maxDocFreq is the fraction of entries a keyword may match before it's // considered too generic to discriminate (e.g. "board"). const maxDocFreq = 0.02 func (k *KnoxDB) goldenThreadKeywords(tx *sql.Tx) (int64, []string, [][2]string) { var id int64 var title, motivation, tags, updatedAt string err := tx.QueryRow( `SELECT t.id, t.title, COALESCE(t.motivation,''), COALESCE(t.tags,'[]'), COALESCE(t.updated_at,'') FROM threads t JOIN settings s ON s.value = CAST(t.id AS TEXT) WHERE s.key='golden_thread_id'`, ).Scan(&id, &title, &motivation, &tags, &updatedAt) if err != nil { return 0, nil, nil } kwCache.Lock() if kwCache.threadID == id && kwCache.updatedAt == updatedAt { kws, bgs := kwCache.keywords, kwCache.bigrams kwCache.Unlock() return id, kws, bgs } kwCache.Unlock() raw := extractKeywords(title + " " + motivation + " " + tags) filtered := k.filterByDocFreq(tx, raw) // Keep only bigrams where both words survived DF filtering. survived := make(map[string]bool, len(filtered)) for _, kw := range filtered { survived[kw] = true } var bigrams [][2]string for _, bg := range extractBigrams(title + " " + motivation + " " + tags) { if survived[bg[0]] && survived[bg[1]] { bigrams = append(bigrams, bg) } } kwCache.Lock() kwCache.threadID, kwCache.updatedAt = id, updatedAt kwCache.keywords, kwCache.bigrams = filtered, bigrams kwCache.Unlock() return id, filtered, bigrams } // filterByDocFreq drops keywords that match more than maxDocFreq of all entries. // Rare keywords (klubhaus, doorbell) are discriminative; common ones (board, // current) just link noise. func (k *KnoxDB) filterByDocFreq(tx *sql.Tx, keywords []string) []string { var total int if err := tx.QueryRow("SELECT COUNT(*) FROM entries").Scan(&total); err != nil || total == 0 { return keywords } limit := int(float64(total) * maxDocFreq) if limit < 5 { limit = 5 } var out []string for _, kw := range keywords { var df int like := "%" + escapeLike(kw) + "%" err := tx.QueryRow( `SELECT COUNT(*) FROM entries WHERE title LIKE ? ESCAPE '\' OR summary LIKE ? ESCAPE '\' OR project LIKE ? ESCAPE '\'`, like, like, like, ).Scan(&df) if err != nil || df <= limit { out = append(out, kw) } } return out } var wordRE = regexp.MustCompile(`[^a-z0-9]+`) // wordBoundaryRE extracts maximal alphanumeric runs. No \b anchors — Go treats // underscore as a word char, so \b would swallow snake_case tokens entirely // ("ALERT_klubhaus_topic" would yield nothing). var wordBoundaryRE = regexp.MustCompile(`[a-z0-9]+`) var stopWords = map[string]bool{ "with": true, "this": true, "that": true, "from": true, "they": true, "have": true, "were": true, "what": true, "when": true, "where": true, "which": true, "their": true, "them": true, "been": true, "also": true, "than": true, "into": true, "over": true, "such": true, "each": true, "about": true, "most": true, "some": true, "more": true, "other": true, "then": true, "will": true, "just": true, "like": true, "only": true, "very": true, "even": true, "much": true, "still": true, "well": true, "here": true, "there": true, "does": true, "done": true, "system": true, "page": true, "site": true, "user": true, "data": true, "file": true, "type": true, "home": true, "mode": true, "show": true, "name": true, "back": true, "open": true, } func ExtractKeywords(s string) []string { return extractKeywords(s) } func extractKeywords(s string) []string { s = strings.ToLower(s) words := wordRE.Split(s, -1) seen := make(map[string]bool) var keywords []string for _, w := range words { if len(w) > 3 && !seen[w] && !stopWords[w] { seen[w] = true keywords = append(keywords, w) } } return keywords } // extractBigrams returns ordered consecutive keyword pairs from the text, // preserving phrase structure ("multi board" from "multi-board"). func extractBigrams(s string) [][2]string { s = strings.ToLower(s) words := wordRE.Split(s, -1) var kept []string for _, w := range words { if len(w) > 3 && !stopWords[w] { kept = append(kept, w) } } seen := make(map[[2]string]bool) var out [][2]string for i := 0; i+1 < len(kept); i++ { pair := [2]string{kept[i], kept[i+1]} if !seen[pair] { seen[pair] = true out = append(out, pair) } } return out } // isRelevant scores phrase and keyword overlap. Title/summary/project matches // ("hard" signal) can link on their own. The full content body only // *corroborates*: its total contribution is capped below the link threshold, so // a long transcript — which mentions many keywords — cannot flood a thread on // its own, but it can tip a borderline observation over the line. func isRelevant(title, summary, project, content string, keywords []string, bigrams [][2]string) bool { titleTokens := wordBoundaryRE.FindAllString(strings.ToLower(title), -1) bodyTokens := wordBoundaryRE.FindAllString(strings.ToLower(summary+" "+project), -1) contentTokens := wordBoundaryRE.FindAllString(strings.ToLower(content), -1) titleSet := make(map[string]bool, len(titleTokens)) for _, t := range titleTokens { titleSet[t] = true } bodySet := make(map[string]bool, len(bodyTokens)) for _, t := range bodyTokens { bodySet[t] = true } contentSet := make(map[string]bool, len(contentTokens)) for _, t := range contentTokens { contentSet[t] = true } // Hard signal from title/summary/project. hard := 0 for _, kw := range keywords { if titleSet[kw] { hard += 2 } else if bodySet[kw] { hard += 1 } } for _, bg := range bigrams { if containsBigram(titleTokens, bg) || containsBigram(bodyTokens, bg) { hard += 3 } } if hard >= 3 { return true } // Content corroboration, capped so it can never link alone. const contentCap = 2 contentScore := 0 for _, kw := range keywords { if titleSet[kw] || bodySet[kw] { continue } if contentSet[kw] { contentScore++ if contentScore >= contentCap { break } } } if contentScore < contentCap { for _, bg := range bigrams { if containsBigram(titleTokens, bg) || containsBigram(bodyTokens, bg) { continue } if containsBigram(contentTokens, bg) { contentScore = contentCap break } } } return hard+contentScore >= 3 } func containsBigram(tokens []string, bg [2]string) bool { for i := 0; i+1 < len(tokens); i++ { if tokens[i] == bg[0] && tokens[i+1] == bg[1] { return true } } return false } // ─── Thread (Motivation/Intent) Operations ───────────────────── type Thread struct { ID int64 Title string Motivation string Status string // effective: active | stalled | resolved Priority string CreatedAt string UpdatedAt string ResolvedAt string Tags string Provenance string EntryCount int LastActivity string // newest linked observation's signal time (created_at) } // IsDraft reports whether a thread still carries the heuristic auto-threader's // editorial copy and is worth offering for polish. Merged clusters are resolved // and left with no observations, so they are excluded: there is nothing to // rewrite and the queue could never drain. func (t Thread) IsDraft() bool { if t.Status == "resolved" || t.EntryCount == 0 { return false } return strings.Contains(t.Provenance, "auto_thread") || strings.HasPrefix(t.Motivation, "Auto-detected") } // stallAfterDays is how long a thread may go without activity before it is // considered stalled (derived, reversible — not a stored state). const stallAfterDays = 14 // effectiveThreadStatus derives a thread's status from its stored state and its // last activity. "resolved" is explicit and sticky; otherwise a thread is // "active" while it has recent activity and "stalled" once it goes quiet. func effectiveThreadStatus(stored, lastActivity string) string { if stored == "resolved" { return "resolved" } ts, err := parseTime(lastActivity) if err != nil { return "stalled" // never had activity } if time.Since(ts) <= time.Duration(stallAfterDays)*24*time.Hour { return "active" } return "stalled" } func ThreadFP(id int64) string { return fmt.Sprintf("thread:%d", id) } // CreateThread inserts a thread. clusterKey, when non-empty, provides // idempotency: if a thread with that cluster key already exists no new row is // created. The existing id is returned with created=false. func (k *KnoxDB) CreateThread(title, motivation, priority, tags, provenance string) (int64, error) { id, _, err := k.CreateThreadCluster(title, motivation, priority, tags, provenance, "") return id, err } func (k *KnoxDB) CreateThreadCluster(title, motivation, priority, tags, provenance, clusterKey string) (int64, bool, error) { // INSERT OR IGNORE makes creation atomic under the partial unique index: // concurrent creators (thread ticker + post-pull reconcile, or two gossip // nodes converging on the same cluster) lose the race into a no-op instead // of a UNIQUE error, then pick up the winner's id. res, err := k.db.Exec( `INSERT OR IGNORE INTO threads (title, motivation, priority, tags, provenance, cluster_key) VALUES (?, ?, ?, ?, ?, ?)`, title, motivation, priority, tags, provenance, clusterKey, ) if err != nil { return 0, false, err } if n, _ := res.RowsAffected(); n > 0 { id, _ := res.LastInsertId() return id, true, nil } // Ignored insert: a thread with this cluster key already exists. if existing := k.ThreadByClusterKey(clusterKey); existing != 0 { return existing, false, nil } return 0, false, fmt.Errorf("insert ignored but no thread with cluster key %q", clusterKey) } // ThreadByClusterKey returns the id of the thread auto-created for a given // cluster, or 0 when none exists. func (k *KnoxDB) ThreadByClusterKey(clusterKey string) int64 { if clusterKey == "" { return 0 } var id int64 err := k.db.QueryRow(`SELECT id FROM threads WHERE cluster_key=?`, clusterKey).Scan(&id) if err != nil { return 0 } return id } func (k *KnoxDB) ListThreads(status string) ([]Thread, error) { rows, err := k.db.Query( `SELECT t.id, t.title, COALESCE(t.motivation,''), t.status, t.priority, t.created_at, t.updated_at, COALESCE(t.resolved_at,''), COALESCE(t.tags,'[]'), COALESCE(t.provenance,'{}'), (SELECT COUNT(*) FROM thread_observations WHERE thread_id=t.id), COALESCE((SELECT MAX(o.created_at) FROM thread_observations tos JOIN observations o ON o.id = tos.observation_id WHERE tos.thread_id = t.id), t.created_at) FROM threads t ORDER BY t.updated_at DESC`) if err != nil { return nil, err } defer rows.Close() // status filters on the EFFECTIVE status (active | stalled | resolved); the // stored flag only records explicit resolution. want := strings.ToLower(strings.TrimSpace(status)) var threads []Thread for rows.Next() { var t Thread if err := rows.Scan(&t.ID, &t.Title, &t.Motivation, &t.Status, &t.Priority, &t.CreatedAt, &t.UpdatedAt, &t.ResolvedAt, &t.Tags, &t.Provenance, &t.EntryCount, &t.LastActivity); err != nil { return nil, err } t.Status = effectiveThreadStatus(t.Status, t.LastActivity) if want != "" && want != "all" && strings.ToLower(t.Status) != want { continue } threads = append(threads, t) } return threads, rows.Err() } func (k *KnoxDB) GetThread(id int64) (*Thread, error) { row := k.db.QueryRow( `SELECT t.id, t.title, COALESCE(t.motivation,''), t.status, t.priority, t.created_at, t.updated_at, COALESCE(t.resolved_at,''), COALESCE(t.tags,'[]'), COALESCE(t.provenance,'{}'), (SELECT COUNT(*) FROM thread_observations WHERE thread_id=t.id) FROM threads t WHERE t.id=?`, id, ) t := &Thread{} err := row.Scan(&t.ID, &t.Title, &t.Motivation, &t.Status, &t.Priority, &t.CreatedAt, &t.UpdatedAt, &t.ResolvedAt, &t.Tags, &t.Provenance, &t.EntryCount) if err == sql.ErrNoRows { return nil, nil } return t, err } func (k *KnoxDB) CloseThread(id int64) error { _, err := k.db.Exec( `UPDATE threads SET status='resolved', resolved_at=datetime('now'), updated_at=datetime('now') WHERE id=?`, id, ) return err } // UpdateThread rewrites the editorial fields of a thread (used by the LLM // draft/polish pass to replace auto-generated titles/motivations). Empty // strings leave the corresponding field unchanged; omitting them all is a no-op. // // A rewritten title or motivation counts as editorial: the auto_thread // provenance marker is dropped so the thread stops reporting as a draft. The // rest of the provenance (cluster, score, sources) is kept. func (k *KnoxDB) UpdateThread(id int64, title, motivation, priority, tags string) (bool, error) { t, err := k.GetThread(id) if err != nil || t == nil { return false, fmt.Errorf("thread #%d not found", id) } if title == "" { title = t.Title } if motivation == "" { motivation = t.Motivation } if priority == "" { priority = t.Priority } if tags == "" { tags = t.Tags } provenance := t.Provenance if title != t.Title || motivation != t.Motivation { provenance = clearAutoThreadMarker(provenance) } changed := title != t.Title || motivation != t.Motivation || priority != t.Priority || tags != t.Tags || provenance != t.Provenance if !changed { return false, nil } _, err = k.db.Exec( `UPDATE threads SET title=?, motivation=?, priority=?, tags=?, provenance=?, updated_at=datetime('now') WHERE id=?`, title, motivation, priority, tags, provenance, id, ) return true, err } // clearAutoThreadMarker removes the auto_thread trigger from a thread's // provenance JSON, recording that a human or agent has since rewritten it. // Unparseable or unrelated provenance is returned unchanged. func clearAutoThreadMarker(provenance string) string { if !strings.Contains(provenance, "auto_thread") { return provenance } var meta map[string]any if err := json.Unmarshal([]byte(provenance), &meta); err != nil { return provenance } if trigger, _ := meta["trigger"].(string); trigger != "auto_thread" { return provenance } delete(meta, "trigger") meta["groomed"] = true out, err := json.Marshal(meta) if err != nil { return provenance } return string(out) } func (k *KnoxDB) LinkObservationToThread(threadID, observationID int64, relevance string) error { tx, err := k.db.Begin() if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, ?)`, threadID, observationID, relevance, ); err != nil { return err } if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID); err != nil { return err } return tx.Commit() } // AutoLinkThreadObservations resolves each entry fingerprint to its most recent // observation and links it to the thread ('auto_cluster' relevance). Idempotent: // INSERT OR IGNORE means re-linking an already-linked fingerprint is a no-op. // Returns the number of newly linked observations. func (k *KnoxDB) AutoLinkThreadObservations(threadID int64, fingerprints []string) (int, error) { tx, err := k.db.Begin() if err != nil { return 0, err } defer tx.Rollback() linked := 0 var firstErr error for _, fp := range fingerprints { if fp == "" { continue } var obsID int64 if err := tx.QueryRow( `SELECT id FROM observations WHERE fingerprint=? ORDER BY hcl DESC, id DESC LIMIT 1`, fp, ).Scan(&obsID); err != nil { // A fingerprint without observations is expected (provenance links); // a real query failure is not — remember the first one. if err != sql.ErrNoRows && firstErr == nil { firstErr = err } continue } res, err := tx.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'auto_cluster')`, threadID, obsID, ) if err != nil { if firstErr == nil { firstErr = err } continue } if n, _ := res.RowsAffected(); n > 0 { linked++ } } if linked > 0 { if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID); err != nil { return linked, err } } if err := tx.Commit(); err != nil { return linked, err } return linked, firstErr } // ActiveThreadByKeyword returns the most recently updated active thread whose // title/motivation/tags contains the given keyword, or 0 if none exists. Used // to fold new clusters into an existing thread instead of spawning duplicates. func (k *KnoxDB) ActiveThreadByKeyword(keyword string) (int64, error) { if keyword == "" { return 0, nil } like := "%" + escapeLike(keyword) + "%" rows, err := k.db.Query( `SELECT id FROM threads WHERE status='active' AND (title LIKE ? ESCAPE '\' OR motivation LIKE ? ESCAPE '\' OR tags LIKE ? ESCAPE '\') ORDER BY updated_at DESC LIMIT 1`, like, like, like, ) if err != nil { return 0, err } defer rows.Close() if rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return 0, err } return id, nil } return 0, rows.Err() } // ThreadObservations returns linked observations, deduplicated by fingerprint // (re-observed entries appear once, with the latest observation's data). func (k *KnoxDB) ThreadObservations(threadID int64) ([]Observation, error) { rows, err := k.db.Query( `SELECT o.id, o.fingerprint, o.source_id, COALESCE(o.source_path,''), COALESCE(o.project,''), COALESCE(o.content_type,''), COALESCE(o.title,''), COALESCE(o.summary,''), o.collected_at, COALESCE(o.created_at,''), COALESCE(o.line_start,0), COALESCE(o.line_end,0), o.confidence, o.ingester_version, COALESCE(o.trigger,'') FROM observations o JOIN thread_observations to2 ON to2.observation_id = o.id WHERE to2.thread_id=? AND o.id IN ( SELECT MAX(to3.observation_id) FROM thread_observations to3 JOIN observations o2 ON o2.id = to3.observation_id WHERE to3.thread_id=? GROUP BY o2.fingerprint ) ORDER BY COALESCE(NULLIF(o.created_at,''), o.collected_at) DESC`, threadID, threadID, ) if err != nil { return nil, err } defer rows.Close() var obs []Observation for rows.Next() { var o Observation if err := rows.Scan(&o.ID, &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); err != nil { return nil, err } obs = append(obs, o) } return obs, nil } func (k *KnoxDB) AddThreadNote(threadID int64, note string) (int64, error) { tx, err := k.db.Begin() if err != nil { return 0, err } defer tx.Rollback() res, err := tx.Exec( `INSERT INTO thread_notes (thread_id, note) VALUES (?, ?)`, threadID, note, ) if err != nil { return 0, err } if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID); err != nil { return 0, err } id, err := res.LastInsertId() if err != nil { return 0, err } return id, tx.Commit() } func (k *KnoxDB) ThreadNotes(threadID int64) ([]struct { ID int64 Note string CreatedAt string }, error) { rows, err := k.db.Query( `SELECT id, note, created_at FROM thread_notes WHERE thread_id=? ORDER BY created_at`, threadID, ) if err != nil { return nil, err } defer rows.Close() var notes []struct { ID int64 Note string CreatedAt string } for rows.Next() { var n struct { ID int64 Note string CreatedAt string } if err := rows.Scan(&n.ID, &n.Note, &n.CreatedAt); err != nil { return nil, err } notes = append(notes, n) } return notes, nil } func (k *KnoxDB) SearchThreadsByMotivation(query string) ([]Thread, error) { like := "%" + escapeLike(query) + "%" rows, err := k.db.Query( `SELECT t.id, t.title, COALESCE(t.motivation,''), t.status, t.priority, t.created_at, t.updated_at, COALESCE(t.resolved_at,''), COALESCE(t.tags,'[]'), COALESCE(t.provenance,'{}'), (SELECT COUNT(*) FROM thread_observations WHERE thread_id=t.id) FROM threads t WHERE t.title LIKE ? ESCAPE '\' OR t.motivation LIKE ? ESCAPE '\' OR t.tags LIKE ? ESCAPE '\' ORDER BY t.updated_at DESC LIMIT 20`, like, like, like, ) if err != nil { return nil, err } defer rows.Close() var threads []Thread for rows.Next() { var t Thread if err := rows.Scan(&t.ID, &t.Title, &t.Motivation, &t.Status, &t.Priority, &t.CreatedAt, &t.UpdatedAt, &t.ResolvedAt, &t.Tags, &t.Provenance, &t.EntryCount); err != nil { return nil, err } threads = append(threads, t) } return threads, nil } // LinkEntryToThread links an entry to a thread via provenance_links. func (k *KnoxDB) LinkEntryToThread(threadID int64, entryFP, relation string) error { if entryFP == "" { return fmt.Errorf("entry fingerprint must not be empty") } tfp := ThreadFP(threadID) _, err := k.db.Exec( `INSERT OR IGNORE INTO provenance_links (descendant_fp, ancestor_fp, hop_distance, relation) VALUES (?, ?, 1, ?)`, entryFP, tfp, relation, ) return err } // profileText is the text a thread's relevance keywords are mined from: the // title and tags only. The motivation is human prose and leaks generic words // ("sessions", "browsing", "administration") that turn a thread into a // catch-all, so it is excluded. func profileText(title, tags string) string { return title + " " + tags } // ThreadRelevanceProfile returns the DF-filtered keywords and bigrams for any thread. func (k *KnoxDB) ThreadRelevanceProfile(threadID int64) ([]string, [][2]string, error) { var title, tags string err := k.db.QueryRow( `SELECT title, COALESCE(tags,'[]') FROM threads WHERE id=?`, threadID, ).Scan(&title, &tags) if err != nil { return nil, nil, err } text := profileText(title, tags) raw := extractKeywords(text) var total int if err := k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&total); err != nil || total == 0 { return raw, nil, nil } limit := int(float64(total) * maxDocFreq) if limit < 5 { limit = 5 } // A thread's own title terms are its identity and must never be discarded // as "too common" — e.g. #knox must still match sessions about knox. titleSet := map[string]bool{} for _, w := range wordBoundaryRE.FindAllString(strings.ToLower(title), -1) { if len(w) >= 2 { titleSet[w] = true } } survived := make(map[string]bool) var keywords []string for _, kw := range raw { var df int like := "%" + escapeLike(kw) + "%" if err := k.db.QueryRow( `SELECT COUNT(*) FROM entries WHERE title LIKE ? ESCAPE '\' OR summary LIKE ? ESCAPE '\' OR project LIKE ? ESCAPE '\'`, like, like, like, ).Scan(&df); err != nil || df <= limit || titleSet[kw] { keywords = append(keywords, kw) survived[kw] = true } } var bigrams [][2]string for _, bg := range extractBigrams(text) { if survived[bg[0]] && survived[bg[1]] { bigrams = append(bigrams, bg) } } return keywords, bigrams, nil } // PruneThread removes machine-linked observations ('auto' and legacy 'regroom') // that fail the (stricter) relevance scoring, using the thread's DF-filtered // keyword profile. Temporal links and manual links (descriptive relevance // strings) are evidence of a different kind and are left intact. func (k *KnoxDB) PruneThread(threadID int64) (int, error) { keywords, bigrams, err := k.ThreadRelevanceProfile(threadID) if err != nil { return 0, err } if len(keywords) == 0 { return 0, nil } rows, err := k.db.Query( `SELECT to2.observation_id, COALESCE(o.title,''), COALESCE(o.summary,''), COALESCE(o.project,''), COALESCE(o.content,'') FROM thread_observations to2 JOIN observations o ON o.id = to2.observation_id WHERE to2.thread_id = ? AND to2.relevance IN ('auto', 'regroom')`, threadID, ) if err != nil { return 0, err } var staleIDs []int64 for rows.Next() { var id int64 var title, summary, project, content string if err := rows.Scan(&id, &title, &summary, &project, &content); err != nil { rows.Close() return 0, err } if !isRelevant(title, summary, project, content, keywords, bigrams) { staleIDs = append(staleIDs, id) } } rows.Close() if len(staleIDs) == 0 { return 0, nil } placeholders := strings.TrimSuffix(strings.Repeat("?,", len(staleIDs)), ",") args := make([]any, 0, len(staleIDs)+1) args = append(args, threadID) for _, id := range staleIDs { args = append(args, id) } res, err := k.db.Exec( fmt.Sprintf(`DELETE FROM thread_observations WHERE thread_id=? AND observation_id IN (%s)`, placeholders), args..., ) if err != nil { return 0, err } n, _ := res.RowsAffected() return int(n), nil } // AutoLinkNewObservations links newly-arrived observations to existing active // threads. It is bounded to observations newer than a persisted watermark, so // the periodic pass stays cheap even as the index grows. func (k *KnoxDB) AutoLinkNewObservations() (int, error) { var wmStr string _ = k.db.QueryRow(`SELECT value FROM settings WHERE key='thread_link_watermark'`).Scan(&wmStr) var wm int64 if wmStr != "" { wm, _ = strconv.ParseInt(wmStr, 10, 64) } type obsRow struct { id int64 title, summary, project string content, sourceID, fp string } rows, err := k.db.Query( `SELECT o.id, COALESCE(o.title,''), COALESCE(o.summary,''), COALESCE(o.project,''), COALESCE(o.content,''), COALESCE(o.source_id,''), COALESCE(o.fingerprint,'') FROM observations o WHERE o.id > ? AND o.id IN (SELECT MAX(id) FROM observations GROUP BY fingerprint)`, wm) if err != nil { return 0, err } var fresh []obsRow maxID := wm for rows.Next() { var o obsRow if err := rows.Scan(&o.id, &o.title, &o.summary, &o.project, &o.content, &o.sourceID, &o.fp); err != nil { rows.Close() return 0, err } fresh = append(fresh, o) if o.id > maxID { maxID = o.id } } rows.Close() if len(fresh) == 0 { return 0, nil } // Link to any non-resolved thread, including stalled ones — new activity // should revive a stalled thread, not be ignored. all, err := k.ListThreads("") if err != nil { return 0, err } var threads []Thread for _, t := range all { if t.Status != "resolved" { threads = append(threads, t) } } total := 0 for _, t := range threads { keywords, bigrams, err := k.ThreadRelevanceProfile(t.ID) if err != nil || len(keywords) == 0 { continue } for _, o := range fresh { if o.sourceID == "browser-history" { continue // browsing is context, not thread membership } if !isRelevant(o.title, o.summary, o.project, o.content, keywords, bigrams) { continue } res, err := k.db.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'auto')`, t.ID, o.id, ) if err == nil { if n, _ := res.RowsAffected(); n > 0 { total++ } } } } if err := k.setSetting("thread_link_watermark", strconv.FormatInt(maxID, 10)); err != nil { return total, err } return total, nil } // RescanThread links existing observations that pass the thread's relevance // profile but were never linked — the inverse of PruneThread. One link row per // fingerprint (latest observation), relevance 'auto'. func (k *KnoxDB) RescanThread(threadID int64) (int, error) { keywords, bigrams, err := k.ThreadRelevanceProfile(threadID) if err != nil { return 0, err } if len(keywords) == 0 { return 0, nil } rows, err := k.db.Query( `SELECT o.id, o.source_id, COALESCE(o.title,''), COALESCE(o.summary,''), COALESCE(o.project,''), COALESCE(o.content,'') FROM observations o WHERE o.id IN (SELECT MAX(id) FROM observations GROUP BY fingerprint) AND o.fingerprint NOT IN ( SELECT o2.fingerprint FROM thread_observations t JOIN observations o2 ON o2.id = t.observation_id WHERE t.thread_id = ? )`, threadID, ) if err != nil { return 0, err } var linkIDs []int64 for rows.Next() { var id int64 var sourceID, title, summary, project, content string if err := rows.Scan(&id, &sourceID, &title, &summary, &project, &content); err != nil { rows.Close() return 0, err } if sourceID == "browser-history" { continue // browsing is context, not thread membership } if isRelevant(title, summary, project, content, keywords, bigrams) { linkIDs = append(linkIDs, id) } } rows.Close() linked := 0 for _, id := range linkIDs { res, err := k.db.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'auto')`, threadID, id, ) if err == nil { if n, _ := res.RowsAffected(); n > 0 { linked++ } } } return linked, nil } // workSources imply active intent (vs passive browsing) when judging whether a // thread has a real anchor. var workSources = map[string]bool{ "git": true, "gitea": true, "opencode-session": true, "obsidian": true, "filesystem": true, "karakeep": true, } // ThreadAssessment is a per-thread snapshot for agent-driven grooming: value, // coherence, denylist status, and the material needed to retitle it. type ThreadAssessment struct { ID int64 Title string Status string Priority string Tags string Linked int Sources map[string]int WorkAnchored bool BrowserFrac float64 Denied bool DenyMatch string Keywords []string Bigrams [][2]string Sample []string SampleContent []string // short excerpts from linked content, for assessment Summary string // agent-written thread summary SummarizedAt string ResummaryDue bool Retained bool // explicitly allowlisted: never denied/resolved by the denylist Verdict string // deny | low-signal | ok | high-snr SuggestedTitle string } // GroomThreads assesses every active thread so an agent can decide which to // keep, retitle, summarize, or deny. staleDays is the age (in days) after which // a thread's summary is considered due for a refresh (<=0 uses 30). func (k *KnoxDB) GroomThreads(staleDays int) ([]ThreadAssessment, error) { if staleDays <= 0 { staleDays = 30 } rows, err := k.db.Query( `SELECT id, title, COALESCE(status,''), COALESCE(priority,''), COALESCE(motivation,''), COALESCE(tags,''), COALESCE(retained,0), COALESCE(summary,''), COALESCE(summarized_at,'') FROM threads WHERE status='active' ORDER BY id`) if err != nil { return nil, err } type meta struct { a ThreadAssessment motivation string } var metas []meta for rows.Next() { var m meta if err := rows.Scan(&m.a.ID, &m.a.Title, &m.a.Status, &m.a.Priority, &m.motivation, &m.a.Tags, &m.a.Retained, &m.a.Summary, &m.a.SummarizedAt); err != nil { rows.Close() return nil, err } metas = append(metas, m) } rows.Close() var out []ThreadAssessment for _, m := range metas { a := m.a a.Sources = map[string]int{} srows, err := k.db.Query( `SELECT o.source_id, COUNT(*) FROM thread_observations t JOIN observations o ON o.id = t.observation_id WHERE t.thread_id = ? GROUP BY o.source_id`, a.ID) if err != nil { return nil, err } for srows.Next() { var s string var n int if err := srows.Scan(&s, &n); err == nil { a.Sources[s] = n a.Linked += n if workSources[s] { a.WorkAnchored = true } } } srows.Close() if a.Linked > 0 { a.BrowserFrac = float64(a.Sources["browser-history"]) / float64(a.Linked) } a.DenyMatch = noise.MatchDeniedTopic(a.Title + " " + m.motivation + " " + a.Tags) a.Denied = a.DenyMatch != "" if a.Retained { // Explicitly allowlisted: the denylist must not flag or resolve it. a.Denied = false a.DenyMatch = "" } a.Keywords, a.Bigrams, _ = k.ThreadRelevanceProfile(a.ID) obrows, err := k.db.Query( `SELECT COALESCE(o.title,'') FROM thread_observations t JOIN observations o ON o.id = t.observation_id WHERE t.thread_id = ? AND COALESCE(o.title,'') != '' ORDER BY o.confidence DESC, t.observation_id DESC LIMIT 5`, a.ID) if err == nil { for obrows.Next() { var s string if obrows.Scan(&s) == nil { a.Sample = append(a.Sample, s) } } obrows.Close() } // Short content excerpts so an agent can judge the thread and draft a // summary without a separate full-text call. crows, err := k.db.Query( `SELECT COALESCE(NULLIF(o.content,''), o.summary) FROM thread_observations t JOIN observations o ON o.id = t.observation_id WHERE t.thread_id = ? AND COALESCE(NULLIF(o.content,''), o.summary) != '' ORDER BY LENGTH(COALESCE(o.content,'')) DESC LIMIT 3`, a.ID) if err == nil { for crows.Next() { var s string if crows.Scan(&s) == nil { a.SampleContent = append(a.SampleContent, excerptText(s, 280)) } } crows.Close() } if a.SummarizedAt == "" { a.ResummaryDue = true } else if t, perr := time.Parse(time.RFC3339, a.SummarizedAt); perr == nil { a.ResummaryDue = time.Since(t) > time.Duration(staleDays)*24*time.Hour } else { a.ResummaryDue = true } switch { case a.Denied && !a.WorkAnchored: a.Verdict = "deny" case !a.WorkAnchored || a.Linked < 3: a.Verdict = "low-signal" case len(a.Sources) >= 2 && a.Linked >= 10 && a.BrowserFrac < 0.5: a.Verdict = "high-snr" default: a.Verdict = "ok" } // Only offer a retitle where the current title is auto-generated // ("a / b / c" keyword triple) or denylisted; human titles are left to // the agent to keep or improve. autoTitle := strings.Count(a.Title, " / ") >= 2 if (autoTitle || a.Denied) && len(a.Keywords) > 0 { top := a.Keywords if len(top) > 3 { top = top[:3] } a.SuggestedTitle = strings.Join(top, " · ") } out = append(out, a) } return out, nil } // retainedThreadIDs returns the set of threads explicitly allowlisted. func (k *KnoxDB) retainedThreadIDs() (map[int64]bool, error) { rows, err := k.db.Query(`SELECT id FROM threads WHERE COALESCE(retained,0)=1`) if err != nil { return nil, err } defer rows.Close() out := map[int64]bool{} for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return nil, err } out[id] = true } return out, rows.Err() } // SetThreadRetained allowlists a thread: the denylist never flags or resolves // it, and grooming reports it as retained. func (k *KnoxDB) SetThreadRetained(id int64, retained bool) error { v := 0 if retained { v = 1 } _, err := k.db.Exec(`UPDATE threads SET retained=?, updated_at=datetime('now') WHERE id=?`, v, id) return err } // SetThreadSummary stores an agent-written summary and stamps the time, which // drives the monthly resummary cadence. func (k *KnoxDB) SetThreadSummary(id int64, summary string) error { _, err := k.db.Exec( `UPDATE threads SET summary=?, summarized_at=?, updated_at=datetime('now') WHERE id=?`, summary, time.Now().UTC().Format(time.RFC3339), id, ) return err } // ThreadText returns a bounded, de-duplicated digest of a thread's linked // content (header + excerpts), for an agent to summarize. func (k *KnoxDB) ThreadText(threadID int64, maxBytes int) (string, error) { if maxBytes <= 0 { maxBytes = 16000 } var title, motivation, summary string err := k.db.QueryRow( `SELECT title, COALESCE(motivation,''), COALESCE(summary,'') FROM threads WHERE id=?`, threadID, ).Scan(&title, &motivation, &summary) if err != nil { return "", err } var b strings.Builder fmt.Fprintf(&b, "Thread #%d: %s\nMotivation: %s\nSummary: %s\n\n", threadID, title, motivation, summary) rows, err := k.db.Query( `SELECT COALESCE(o.title,''), COALESCE(NULLIF(o.content,''), o.summary) FROM thread_observations t JOIN observations o ON o.id = t.observation_id WHERE t.thread_id = ? ORDER BY o.confidence DESC, t.observation_id DESC`, threadID) if err != nil { return "", err } defer rows.Close() seen := map[string]bool{} for rows.Next() { var otitle, text string if err := rows.Scan(&otitle, &text); err != nil { continue } text = strings.Join(strings.Fields(text), " ") if text == "" { continue } key := text if len(key) > 160 { key = key[:160] } if seen[key] { continue } seen[key] = true block := "--- " + otitle + "\n" + text + "\n\n" if b.Len()+len(block) > maxBytes { if remaining := maxBytes - b.Len(); remaining > 0 { b.WriteString(block[:min(remaining, len(block))]) } b.WriteString("\n[truncated]\n") break } b.WriteString(block) } return b.String(), rows.Err() } // excerptText collapses whitespace and truncates to n runes for display. func excerptText(s string, n int) string { s = strings.Join(strings.Fields(s), " ") r := []rune(s) if len(r) > n { return string(r[:n]) + "…" } return s } // ThreadMergeSuggestion is a pair of threads whose linked observations overlap // enough that they likely describe the same work. type ThreadMergeSuggestion struct { A, B int64 // A = larger thread, B = smaller (merge B into A) ATitle, BTitle string Shared int AOnly, BOnly int Containment float64 // shared / |smaller set| Examples []string } // MergeSuggestions finds thread pairs where one thread is largely subsumed by // another. Containment (shared / smaller set) is the signal — not absolute // overlap, which is inflated because observations get linked to several // threads. A pair is suggested when it shares >= minShared observations and the // smaller thread is at least minRatio contained in the larger. func (k *KnoxDB) MergeSuggestions(minShared int, minRatio float64) ([]ThreadMergeSuggestion, error) { if minShared <= 0 { minShared = 3 } if minRatio <= 0 { minRatio = 0.7 } rows, err := k.db.Query( `SELECT t.id, COALESCE(o.fingerprint,'') FROM threads t JOIN thread_observations tos ON tos.thread_id = t.id JOIN observations o ON o.id = tos.observation_id WHERE t.status='active' AND COALESCE(o.fingerprint,'') != '' AND o.source_id IN ('git','gitea','opencode-session','obsidian','karakeep','filesystem')`) if err != nil { return nil, err } sets := map[int64]map[string]bool{} titles := map[int64]string{} for rows.Next() { var id int64 var fp string if err := rows.Scan(&id, &fp); err != nil { rows.Close() return nil, err } if sets[id] == nil { sets[id] = map[string]bool{} } sets[id][fp] = true } rows.Close() ids := make([]int64, 0, len(sets)) for id := range sets { ids = append(ids, id) t, _ := k.GetThread(id) if t != nil { titles[id] = t.Title } } sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) var out []ThreadMergeSuggestion for i := 0; i < len(ids); i++ { for j := i + 1; j < len(ids); j++ { a, b := ids[i], ids[j] shared := 0 var examples []string for fp := range sets[a] { if sets[b][fp] { shared++ if len(examples) < 3 { examples = append(examples, fp) } } } smaller := len(sets[a]) if len(sets[b]) < smaller { smaller = len(sets[b]) } containment := float64(shared) / float64(smaller) if shared < minShared || containment < minRatio { continue } // Order larger-first so the suggested merge is B(-> smaller) into A. aBig, bSmall := a, b if len(sets[b]) > len(sets[a]) { aBig, bSmall = b, a } out = append(out, ThreadMergeSuggestion{ A: aBig, B: bSmall, ATitle: titles[aBig], BTitle: titles[bSmall], Shared: shared, AOnly: len(sets[aBig]) - shared, BOnly: len(sets[bSmall]) - shared, Containment: containment, Examples: examples, }) } } sort.Slice(out, func(i, j int) bool { return out[i].Shared > out[j].Shared }) return out, nil } // MergeThreads folds thread `from` into `into`: its observations move to // `into`, and `from` is resolved (kept as a tombstone, not deleted). func (k *KnoxDB) MergeThreads(into, from int64) error { if into == from || into <= 0 || from <= 0 { return fmt.Errorf("invalid merge: into=%d from=%d", into, from) } tx, err := k.db.Begin() if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec( `INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) SELECT ?, observation_id, COALESCE(relevance,'auto') FROM thread_observations WHERE thread_id = ?`, into, from, ); err != nil { return err } if _, err := tx.Exec(`DELETE FROM thread_observations WHERE thread_id = ?`, from); err != nil { return err } if _, err := tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, into); err != nil { return err } if _, err := tx.Exec( `UPDATE threads SET status='resolved', resolved_at=datetime('now'), updated_at=datetime('now') WHERE id=?`, from, ); err != nil { return err } return tx.Commit() } // DenyThreadNoise refocuses existing threads against the shared denylist: // 1. removes denylisted webapp browsing links from every thread, then // 2. resolves threads whose topic is denylisted and which retain no // work-source observation. // // Returns links removed and the ids of threads closed. With dryRun it reports // without writing. func (k *KnoxDB) DenyThreadNoise(dryRun bool) (removed int, closed []int64, err error) { retained, err := k.retainedThreadIDs() if err != nil { return 0, nil, err } rows, err := k.db.Query( `SELECT to2.thread_id, to2.observation_id, COALESCE(o.source_path,''), COALESCE(o.summary,'') FROM thread_observations to2 JOIN observations o ON o.id = to2.observation_id WHERE o.source_id = 'browser-history'`) if err != nil { return 0, nil, err } type link struct { threadID, obsID int64 } var links []link for rows.Next() { var l link var path, summary string if err := rows.Scan(&l.threadID, &l.obsID, &path, &summary); err != nil { rows.Close() return 0, nil, err } if retained[l.threadID] { continue // allowlisted thread: leave entirely intact } if noise.IsNoisyURL(path) || noise.IsNoisyURL(summary) { links = append(links, l) } } rows.Close() removed = len(links) if !dryRun { for _, l := range links { if _, err := k.db.Exec( `DELETE FROM thread_observations WHERE thread_id=? AND observation_id=?`, l.threadID, l.obsID, ); err != nil { return removed, nil, err } } } // Resolve denylisted-topic threads that lost (or never had) a work anchor. trows, err := k.db.Query(`SELECT id, title, COALESCE(motivation,''), COALESCE(tags,'') FROM threads WHERE status='active' AND COALESCE(retained,0)=0`) if err != nil { return removed, nil, err } type tt struct { id int64 title, motivation, tag string } var candidates []tt for trows.Next() { var t tt if err := trows.Scan(&t.id, &t.title, &t.motivation, &t.tag); err != nil { trows.Close() return removed, nil, err } if noise.IsDeniedTopic(t.title + " " + t.motivation + " " + t.tag) { candidates = append(candidates, t) } } trows.Close() for _, t := range candidates { var workLinks int if err := k.db.QueryRow( `SELECT COUNT(*) FROM thread_observations to2 JOIN observations o ON o.id = to2.observation_id WHERE to2.thread_id = ? AND o.source_id IN ('git','gitea','opencode-session','obsidian','filesystem','karakeep')`, t.id, ).Scan(&workLinks); err != nil { return removed, nil, err } if workLinks > 0 { continue } closed = append(closed, t.id) if !dryRun { if err := k.CloseThread(t.id); err != nil { return removed, nil, err } } } return removed, closed, nil } // ThreadProvenance returns the provenance graph for a thread. func (k *KnoxDB) ThreadProvenance(threadID int64) ([]struct { Fingerprint string Relation string HopDistance int }, error) { return k.ProvenanceChain(ThreadFP(threadID), 3) } // ─── Snippets ──────────────────────────────────────────────── const snippetCols = `s.fingerprint, COALESCE(s.language,''), s.code, COALESCE(s.title,''), COALESCE(s.description,''), COALESCE(s.tags,'[]'), COALESCE(s.status,'candidate'), COALESCE(s.source_session,''), COALESCE(s.source_path,''), COALESCE(s.source_entry,''), COALESCE(s.project,''), COALESCE(s.tool,''), COALESCE(s.model,''), COALESCE(s.patch_hash,''), COALESCE(s.evidence,'{}'), COALESCE(s.superseded_by,''), COALESCE(s.skill_name,''), COALESCE(s.reject_reason,''), COALESCE(s.discovered_at,''), COALESCE(s.reviewed_at,''), COALESCE(s.encoded_at,''), COALESCE(s.junk,0), COALESCE(s.kind,'code')` func scanSnippet(sc interface{ Scan(...any) error }) (Snippet, error) { var s Snippet err := sc.Scan(&s.Fingerprint, &s.Language, &s.Code, &s.Title, &s.Description, &s.Tags, &s.Status, &s.SourceSession, &s.SourcePath, &s.SourceEntry, &s.Project, &s.Tool, &s.Model, &s.PatchHash, &s.Evidence, &s.SupersededBy, &s.SkillName, &s.RejectReason, &s.DiscoveredAt, &s.ReviewedAt, &s.EncodedAt, &s.Junk, &s.Kind) return s, err } // UpsertSnippet records a candidate snippet. Dedup is by content fingerprint: // an already-known snippet is never overwritten (curation is preserved). A // non-empty SupersededBy stamps the dead-end marker on the earlier snippet. func (k *KnoxDB) UpsertSnippet(rec SnippetRecord) (inserted bool, err error) { junk := 0 if rec.Junk { junk = 1 } kind := rec.Kind if kind == "" { kind = "code" } res, err := k.db.Exec( `INSERT OR IGNORE INTO snippets (fingerprint, language, code, title, description, tags, status, source_session, source_path, source_entry, project, tool, model, patch_hash, evidence, superseded_by, junk, kind) VALUES (?, ?, ?, ?, ?, ?, 'candidate', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, rec.Fingerprint, rec.Language, rec.Code, rec.Title, rec.Description, rec.Tags, rec.SourceSession, rec.SourcePath, rec.SourceEntry, rec.Project, rec.Tool, rec.Model, rec.PatchHash, rec.Evidence, rec.SupersededBy, junk, kind, ) if err != nil { return false, fmt.Errorf("insert snippet: %w", err) } n, _ := res.RowsAffected() // Refresh derived metadata on an existing row (classification and redaction // may improve); curated fields (status, title, description, tags) are kept. if n == 0 { if _, err := k.db.Exec(`UPDATE snippets SET junk=?, kind=?, code=? WHERE fingerprint=? AND (junk!=? OR kind!=? OR code!=?)`, junk, kind, rec.Code, rec.Fingerprint, junk, kind, rec.Code); err != nil { return false, fmt.Errorf("refresh snippet meta: %w", err) } } if rec.SupersededBy != "" { if _, err := k.db.Exec( `UPDATE snippets SET superseded_by=? WHERE fingerprint=? AND superseded_by=''`, rec.SupersededBy, rec.Fingerprint, ); err != nil { return n > 0, fmt.Errorf("mark superseded: %w", err) } } return n > 0, nil } // UpsertSnippets records many candidates in one transaction. Semantics match // UpsertSnippet, but batching avoids a fsync per row (and per-FTS-trigger // churn), which matters for a full extraction sweep of tens of thousands of // candidates. Returns the number of newly inserted rows. func (k *KnoxDB) UpsertSnippets(recs []SnippetRecord) (inserted int, err error) { tx, err := k.db.Begin() if err != nil { return 0, fmt.Errorf("begin: %w", err) } defer tx.Rollback() ins, err := tx.Prepare(`INSERT OR IGNORE INTO snippets (fingerprint, language, code, title, description, tags, status, source_session, source_path, source_entry, project, tool, model, patch_hash, evidence, superseded_by, junk, kind) VALUES (?, ?, ?, ?, ?, ?, 'candidate', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) if err != nil { return 0, fmt.Errorf("prepare insert: %w", err) } defer ins.Close() updMeta, err := tx.Prepare(`UPDATE snippets SET junk=?, kind=?, code=? WHERE fingerprint=? AND (junk!=? OR kind!=? OR code!=?)`) if err != nil { return 0, fmt.Errorf("prepare meta: %w", err) } defer updMeta.Close() updSup, err := tx.Prepare(`UPDATE snippets SET superseded_by=? WHERE fingerprint=? AND superseded_by=''`) if err != nil { return 0, fmt.Errorf("prepare superseded: %w", err) } defer updSup.Close() for _, r := range recs { junk := 0 if r.Junk { junk = 1 } kind := r.Kind if kind == "" { kind = "code" } res, err := ins.Exec(r.Fingerprint, r.Language, r.Code, r.Title, r.Description, r.Tags, r.SourceSession, r.SourcePath, r.SourceEntry, r.Project, r.Tool, r.Model, r.PatchHash, r.Evidence, r.SupersededBy, junk, kind) if err != nil { return inserted, fmt.Errorf("insert snippet: %w", err) } if n, _ := res.RowsAffected(); n > 0 { inserted++ } else if _, err := updMeta.Exec(junk, kind, r.Code, r.Fingerprint, junk, kind, r.Code); err != nil { return inserted, fmt.Errorf("refresh snippet meta: %w", err) } if r.SupersededBy != "" { if _, err := updSup.Exec(r.SupersededBy, r.Fingerprint); err != nil { return inserted, fmt.Errorf("mark superseded: %w", err) } } } return inserted, tx.Commit() } // SnippetFilter selects and orders candidate snippets. Config selects how // config/doc snippets (json/yaml/toml/markdown/lua) are treated: "demote" // (default) ranks them below code, "hide" excludes them, "only" returns only // them. Snippet extraction is conservative about *applied*, not about *value*, // so filters carry the judgment the agent asks for. type SnippetFilter struct { Limit int Language string Project string Tool string MinBytes int Config string Junk string Kind string Described bool } // configLangExpr is a SQL boolean that is 1 for config/doc languages. const configLangExpr = `(s.language IN ('json','yaml','toml','markdown','lua'))` // SnippetCandidates lists un-superseded, not-yet-curated snippets. func (k *KnoxDB) SnippetCandidates(f SnippetFilter) ([]Snippet, error) { if f.Limit <= 0 { f.Limit = 20 } query := `SELECT ` + snippetCols + ` FROM snippets s WHERE s.status='candidate' AND s.superseded_by=''` var args []any if f.Language != "" { query += ` AND s.language=?` args = append(args, f.Language) } if f.Project != "" { query += ` AND s.project=?` args = append(args, f.Project) } if f.Tool != "" { query += ` AND s.tool=?` args = append(args, f.Tool) } if f.Kind != "" && f.Kind != "all" { query += ` AND s.kind=?` args = append(args, f.Kind) } if f.Described { query += ` AND COALESCE(s.description,'') != ''` } if f.MinBytes > 0 { query += ` AND length(s.code) >= ?` args = append(args, f.MinBytes) } switch f.Junk { case "hide": query += ` AND s.junk=0` case "only": query += ` AND s.junk=1` } switch f.Config { case "hide": query += ` AND ` + configLangExpr + ` = 0` case "only": query += ` AND ` + configLangExpr + ` = 1` } order := `s.discovered_at DESC, s.rowid DESC` if f.Config != "hide" && f.Config != "only" { order = configLangExpr + ` ASC, ` + order } if f.Junk != "hide" && f.Junk != "only" { order = `s.junk ASC, ` + order } query += ` ORDER BY ` + order + ` LIMIT ?` args = append(args, f.Limit) return k.querySnippets(query, args...) } // ListSnippets lists snippets, optionally filtered by status. func (k *KnoxDB) ListSnippets(status string, limit int) ([]Snippet, error) { if limit <= 0 { limit = 50 } if status == "" { return k.querySnippets(`SELECT `+snippetCols+` FROM snippets s ORDER BY s.discovered_at DESC, s.rowid DESC LIMIT ?`, limit) } return k.querySnippets(`SELECT `+snippetCols+` FROM snippets s WHERE s.status=? ORDER BY s.discovered_at DESC, s.rowid DESC LIMIT ?`, status, limit) } // SnippetByFingerprint resolves a full or prefixed fingerprint. func (k *KnoxDB) SnippetByFingerprint(fp string) (*Snippet, error) { s, err := k.querySnippets(`SELECT `+snippetCols+` FROM snippets s WHERE s.fingerprint=?`, fp) if err != nil { return nil, err } if len(s) == 1 { return &s[0], nil } if len(s) == 0 && len(fp) >= 4 { s, err = k.querySnippets(`SELECT `+snippetCols+` FROM snippets s WHERE s.fingerprint LIKE ? LIMIT 5`, fp+"%") if err != nil { return nil, err } if len(s) == 1 { return &s[0], nil } } return nil, nil } // SearchSnippets runs an FTS query over encoded and candidate snippets, ranked // by bm25 with encoded (curated) snippets preferred, and excluding junk and // superseded rows. bm25 in SQLite is lower-is-better, so it sorts ascending. func (k *KnoxDB) SearchSnippets(query string, limit int) ([]Snippet, error) { if limit <= 0 { limit = 20 } terms := searchTerms(query) if len(terms) == 0 { return nil, nil } match := matchAllTerms(terms) rows, err := k.db.Query( `SELECT `+snippetCols+` FROM snippets s JOIN snippets_fts f ON f.rowid = s.rowid WHERE snippets_fts MATCH ? AND s.superseded_by='' AND s.junk=0 ORDER BY (s.status='encoded') DESC, bm25(snippets_fts) LIMIT ?`, match, limit, ) if err != nil { return nil, err } defer rows.Close() var out []Snippet for rows.Next() { s, err := scanSnippet(rows) if err != nil { return nil, err } out = append(out, s) } return out, rows.Err() } // EncodeSnippet marks a candidate as curated knowledge. Only candidates (not // rejected) can be encoded; skill_name links it to a written ~/.skills entry. func (k *KnoxDB) EncodeSnippet(fp, title, description, tags, language, skillName string) (bool, error) { now := time.Now().UTC().Format(time.RFC3339) res, err := k.db.Exec( `UPDATE snippets SET status='encoded', title=COALESCE(NULLIF(?,''), title), description=COALESCE(NULLIF(?,''), description), tags=COALESCE(NULLIF(?,''), tags), language=COALESCE(NULLIF(?,''), language), skill_name=COALESCE(NULLIF(?,''), skill_name), reviewed_at=?, encoded_at=? WHERE (fingerprint=? OR (length(?)>=4 AND fingerprint LIKE ?||'%')) AND status!='rejected'`, title, description, tags, language, skillName, now, now, fp, fp, fp, ) if err != nil { return false, fmt.Errorf("encode snippet: %w", err) } n, _ := res.RowsAffected() return n > 0, nil } // RejectSnippet records a dead end so it is not proposed again. func (k *KnoxDB) RejectSnippet(fp, reason string) (bool, error) { now := time.Now().UTC().Format(time.RFC3339) res, err := k.db.Exec( `UPDATE snippets SET status='rejected', reject_reason=?, reviewed_at=? WHERE (fingerprint=? OR (length(?)>=4 AND fingerprint LIKE ?||'%')) AND status='candidate'`, reason, now, fp, fp, fp, ) if err != nil { return false, fmt.Errorf("reject snippet: %w", err) } n, _ := res.RowsAffected() return n > 0, nil } // ReopenSnippet returns a curated snippet to the candidate queue — the undo for // encode/reject. It clears the curation fields but does NOT delete a ~/.skills // entry a prior encode may have written; that file is left on disk. func (k *KnoxDB) ReopenSnippet(fp string) (bool, error) { res, err := k.db.Exec( `UPDATE snippets SET status='candidate', reject_reason='', reviewed_at='', encoded_at='', skill_name='' WHERE (fingerprint=? OR (length(?)>=4 AND fingerprint LIKE ?||'%')) AND status!='candidate'`, fp, fp, fp, ) if err != nil { return false, fmt.Errorf("reopen snippet: %w", err) } n, _ := res.RowsAffected() return n > 0, nil } // RejectJunkSnippets bulk-rejects every candidate the extractor classified as // junk (imports/directives, single-line, empty-body stubs). Reversible via // ReopenSnippet. Returns the number rejected. func (k *KnoxDB) RejectJunkSnippets(reason string) (int, error) { if strings.TrimSpace(reason) == "" { reason = "Auto-classified junk (imports/directives/single-line/empty-body stub)." } now := time.Now().UTC().Format(time.RFC3339) res, err := k.db.Exec( `UPDATE snippets SET status='rejected', reject_reason=?, reviewed_at=? WHERE status='candidate' AND junk=1 AND superseded_by=''`, reason, now, ) if err != nil { return 0, fmt.Errorf("reject junk snippets: %w", err) } n, _ := res.RowsAffected() return int(n), nil } // CountJunkCandidates is the actionable junk count (candidates, not superseded). func (k *KnoxDB) CountJunkCandidates() (int, error) { var n int err := k.db.QueryRow(`SELECT COUNT(*) FROM snippets WHERE status='candidate' AND junk=1 AND superseded_by=''`).Scan(&n) return n, err } // ExpireSnippets rejects uncurated candidates discovered before the cutoff. // This is retention, not judgement: the code did not change, the review window // moved past it. Encoded and already-rejected rows are untouched, and the // decision is reversible with knox snippets reopen. func (k *KnoxDB) ExpireSnippets(cutoff time.Time, reason string) (int, error) { if strings.TrimSpace(reason) == "" { reason = "Expired: never curated within the retention window." } now := time.Now().UTC().Format(time.RFC3339) res, err := k.db.Exec( `UPDATE snippets SET status='rejected', reject_reason=?, reviewed_at=? WHERE status='candidate' AND superseded_by='' AND datetime(discovered_at) < datetime(?)`, reason, now, cutoff.UTC().Format(time.RFC3339), ) if err != nil { return 0, fmt.Errorf("expire snippets: %w", err) } n, _ := res.RowsAffected() return int(n), nil } // CountExpiredCandidates is the actionable expiry count for a cutoff. func (k *KnoxDB) CountExpiredCandidates(cutoff time.Time) (int, error) { var n int err := k.db.QueryRow( `SELECT COUNT(*) FROM snippets WHERE status='candidate' AND superseded_by='' AND datetime(discovered_at) < datetime(?)`, cutoff.UTC().Format(time.RFC3339), ).Scan(&n) return n, err } // snippetsExpireRunKey records when retention last ran, so a sweep can be // driven by any caller (plugin, cron, a human) without a timer of its own. const snippetsExpireRunKey = "snippets_expire_last_run" // ExpireSnippetsDue runs the retention sweep only when the previous one is at // least interval old, and reports whether it ran. The clock lives in settings // rather than in the caller, so an agent hook, a cron job and a manual run share // one schedule and a restarted caller cannot cause a storm. func (k *KnoxDB) ExpireSnippetsDue(cutoff time.Time, interval time.Duration, reason string, now time.Time) (int, bool, error) { if interval > 0 { if last := k.Setting(snippetsExpireRunKey); last != "" { if ts, err := time.Parse(time.RFC3339, last); err == nil && now.Sub(ts) < interval { return 0, false, nil } } } n, err := k.ExpireSnippets(cutoff, reason) if err != nil { return 0, false, err } // Record the run even when nothing expired: the window was checked, and // re-checking it on every caller would defeat the point. if err := k.SetSetting(snippetsExpireRunKey, now.UTC().Format(time.RFC3339)); err != nil { return n, true, err } return n, true, nil } // NextSnippetExpiry is when the retention sweep is next due, or zero when it // has never run. func (k *KnoxDB) NextSnippetExpiry(interval time.Duration) time.Time { last := k.Setting(snippetsExpireRunKey) if last == "" { return time.Time{} } ts, err := time.Parse(time.RFC3339, last) if err != nil { return time.Time{} } return ts.Add(interval) } // ReopenRejectedTechniques returns every rejected technique (bash-sourced) to the // candidate queue — undoing the earlier junk sweep that discarded exploration // and troubleshooting commands. Returns the number reopened. func (k *KnoxDB) ReopenRejectedTechniques() (int, error) { res, err := k.db.Exec( `UPDATE snippets SET status='candidate', reject_reason='', reviewed_at='' WHERE status='rejected' AND tool='bash'`) if err != nil { return 0, fmt.Errorf("reopen techniques: %w", err) } n, _ := res.RowsAffected() return int(n), nil } // RedactSnippets applies fn to each snippet's code/description/title, updating // rows in place where the result differs. Fingerprints are deliberately left // untouched, so re-extraction remains idempotent (the extractor hashes the raw // code). Returns the number of rows that changed (or would, when dryRun). func (k *KnoxDB) RedactSnippets(fn func(string) string, dryRun bool) (int, error) { type row struct{ fp, code, desc, title string } rows, err := k.db.Query(`SELECT fingerprint, code, COALESCE(description,''), COALESCE(title,'') FROM snippets`) if err != nil { return 0, fmt.Errorf("scan snippets: %w", err) } var rs []row for rows.Next() { var r row if err := rows.Scan(&r.fp, &r.code, &r.desc, &r.title); err != nil { rows.Close() return 0, err } rs = append(rs, r) } rows.Close() if err := rows.Err(); err != nil { return 0, err } tx, err := k.db.Begin() if err != nil { return 0, err } defer tx.Rollback() upd, err := tx.Prepare(`UPDATE snippets SET code=?, description=?, title=? WHERE fingerprint=?`) if err != nil { return 0, err } defer upd.Close() n := 0 for _, r := range rs { nc, nd, nt := fn(r.code), fn(r.desc), fn(r.title) if nc == r.code && nd == r.desc && nt == r.title { continue } n++ if dryRun { continue } if _, err := upd.Exec(nc, nd, nt, r.fp); err != nil { return n, fmt.Errorf("redact snippet: %w", err) } } if dryRun { return n, nil } if err := tx.Commit(); err != nil { return n, err } return n, nil } // SnippetStats returns counts by status and the distinct-language tally. func (k *KnoxDB) SnippetStats() (map[string]any, error) { out := map[string]any{} rows, err := k.db.Query(`SELECT COALESCE(status,'candidate'), COUNT(*) FROM snippets GROUP BY status`) if err != nil { return nil, err } defer rows.Close() byStatus := map[string]int{} for rows.Next() { var st string var n int if err := rows.Scan(&st, &n); err != nil { return nil, err } byStatus[st] = n } out["by_status"] = byStatus lrows, err := k.db.Query(`SELECT COALESCE(language,''), COUNT(*) FROM snippets GROUP BY language ORDER BY COUNT(*) DESC LIMIT 20`) if err != nil { return nil, err } defer lrows.Close() byLang := map[string]int{} for lrows.Next() { var l string var n int if err := lrows.Scan(&l, &n); err != nil { return nil, err } if l == "" { l = "(unknown)" } byLang[l] = n } out["by_language"] = byLang var junk int _ = k.db.QueryRow(`SELECT COUNT(*) FROM snippets WHERE status='candidate' AND junk=1`).Scan(&junk) out["junk_candidates"] = junk byKind := map[string]int{} if krows, err := k.db.Query(`SELECT COALESCE(kind,'code'), COUNT(*) FROM snippets WHERE status='candidate' AND superseded_by='' GROUP BY kind`); err == nil { for krows.Next() { var kd string var n int if err := krows.Scan(&kd, &n); err != nil { break } byKind[kd] = n } krows.Close() } out["by_kind"] = byKind return out, nil } func (k *KnoxDB) querySnippets(query string, args ...any) ([]Snippet, error) { rows, err := k.db.Query(query, args...) if err != nil { return nil, err } defer rows.Close() var out []Snippet for rows.Next() { s, err := scanSnippet(rows) if err != nil { return nil, err } out = append(out, s) } return out, rows.Err() }