Files
knox/internal/db/db_test.go
david 3b24e3b8be
build / image (push) Successful in 51s
build / test (push) Successful in 4m48s
fix: make the snippet queue reviewable (#35)
Two causes, both fixed here.

Classification: trivialProbe bailed out on any newline, so multi-line
chores were never judged — 'cd X && sed -n 60,200p f' and 'git status &&
git log --oneline -3' all became technique candidates. Newlines are now
segment separators like ';', sed (without -i) and read-only git
subcommands count as inspections, and context flags (-A/-B/-C, git log -p,
--since, --graph, --all) keep a command because selecting history is
method, not a chore.

Over the live corpus the trivial verdicts go from 307 to 1,081 of 11,552
techniques, and the archaeology that matters (git log -p | grep -B 50)
still survives.

Retention: nothing ever aged a candidate out, so 16,149 of them sat in the
queue. knox snippets expire --days N rejects uncurated candidates older
than the window. It is reversible and never touches encoded rows: the code
did not change, the review window moved past it.
2026-11-04 21:20:24 -08:00

903 lines
28 KiB
Go

package db
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
func newTestDB(t *testing.T) *KnoxDB {
t.Helper()
k, err := Open(filepath.Join(t.TempDir(), "knox.db"))
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { k.Close() })
return k
}
func obs(fp, title, summary string) ObservationRecord {
return ObservationRecord{
Fingerprint: fp, SourceID: "test", Title: title, Summary: summary,
Confidence: 0.5, IngesterVersion: "test/v1",
}
}
// Multi-word queries must match terms spread across fields (AND), not require
// the literal contiguous phrase.
func TestSearchMultiTerm(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "Home Assistant", "automation for the doorbell")); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp2", "Unrelated", "gardening notes")); err != nil {
t.Fatal(err)
}
got, err := k.Search("home assistant automation", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("expected only fp1, got %+v", got)
}
if got, _ := k.Search("home gardening", 10); len(got) != 0 {
t.Fatalf("expected no cross-row match, got %+v", got)
}
}
// Re-reporting an unchanged observation is a no-op: no new row, ref_count stays 1.
func TestRecordObservationIdempotent(t *testing.T) {
k := newTestDB(t)
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); !isNew {
t.Fatal("first insert should be new")
}
if _, isNew, _ := k.RecordObservation(obs("fp1", "t", "s")); isNew {
t.Fatal("second identical insert should be a no-op")
}
var ref, rows int
if err := k.db.QueryRow("SELECT ref_count FROM entries WHERE fingerprint='fp1'").Scan(&ref); err != nil {
t.Fatal(err)
}
if err := k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&rows); err != nil {
t.Fatal(err)
}
if ref != 1 || rows != 1 {
t.Fatalf("ref_count=%d observations=%d, want 1/1", ref, rows)
}
}
// A non-empty ContentHash dedups on content, ignoring extent changes.
func TestRecordObservationContentHash(t *testing.T) {
k := newTestDB(t)
rows := func() int {
var n int
k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE fingerprint='fp1'").Scan(&n)
return n
}
a := obs("fp1", "Log x", "levels: E1 W0")
a.ContentHash = "deadbeef"
a.LineEnd = 100
if _, _, err := k.RecordObservation(a); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after first: rows=%d, want 1", rows())
}
// Same content hash, grown extent, different summary — must be a no-op.
b := obs("fp1", "Log x", "levels: E1 W0 (1000 lines)")
b.ContentHash = "deadbeef"
b.LineEnd = 2000
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if rows() != 1 {
t.Fatalf("after same-hash: rows=%d, want 1 (no-op)", rows())
}
// Different content hash — must append.
c := obs("fp1", "Log x", "levels: E2 W0")
c.ContentHash = "cafef00d"
c.LineEnd = 2000
if _, _, err := k.RecordObservation(c); err != nil {
t.Fatal(err)
}
if rows() != 2 {
t.Fatalf("after changed-hash: rows=%d, want 2", rows())
}
}
// UpsertSession must not inflate agent_count across repeated calls.
func TestUpsertSessionIdempotent(t *testing.T) {
k := newTestDB(t)
for i := 0; i < 3; i++ {
if err := k.UpsertSession("ses_1", "proj", "Title", "active"); err != nil {
t.Fatal(err)
}
}
var ac int
if err := k.db.QueryRow("SELECT agent_count FROM sessions WHERE session_id='ses_1'").Scan(&ac); err != nil {
t.Fatal(err)
}
if ac != 1 {
t.Fatalf("agent_count=%d, want 1", ac)
}
}
// Content (the uncapped body) is searchable even when absent from title/summary.
func TestSearchContentField(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "Title A", "short summary only")
r.Content = "the zanzibar protocol handshake details"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
got, err := k.Search("zanzibar", 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Fingerprint != "fp1" {
t.Fatalf("content search failed: %+v", got)
}
}
// Threads sharing observations are suggested for merge; merging moves links and
// resolves the source.
func TestMergeThreads(t *testing.T) {
k := newTestDB(t)
var ids []int64
for i := 0; i < 3; i++ {
o := obs(fmt.Sprintf("fp%d", i), fmt.Sprintf("t%d", i), "s")
o.SourceID = "gitea" // merge signals use work sources
oid, _, _ := k.RecordObservation(o)
ids = append(ids, oid)
}
a, _ := k.CreateThread("A", "", "medium", "[]", "{}")
b, _ := k.CreateThread("B", "", "medium", "[]", "{}")
for _, oid := range ids {
k.LinkObservationToThread(a, oid, "")
k.LinkObservationToThread(b, oid, "")
}
sug, err := k.MergeSuggestions(3, 0.3)
if err != nil {
t.Fatal(err)
}
if len(sug) != 1 || sug[0].Shared != 3 {
t.Fatalf("expected one suggestion with shared=3, got %+v", sug)
}
if err := k.MergeThreads(a, b); err != nil {
t.Fatal(err)
}
if tb, _ := k.GetThread(b); tb.Status != "resolved" {
t.Fatalf("merged-from thread status=%q, want resolved", tb.Status)
}
var n int
k.db.QueryRow("SELECT COUNT(*) FROM thread_observations WHERE thread_id=?", a).Scan(&n)
if n != 3 {
t.Fatalf("into thread has %d links, want 3", n)
}
}
// SetThreadSummary clears the resummary-due flag; CurrentFocus tracks recent link counts.
func TestThreadSummaryAndFocus(t *testing.T) {
k := newTestDB(t)
o := obs("fp1", "focus topic", "s")
o.SourceID = "gitea" // CurrentFocus counts work sources only
oid, _, _ := k.RecordObservation(o)
a, _ := k.CreateThread("focus topic", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oid, "")
if err := k.SetThreadSummary(a, "current state of work"); err != nil {
t.Fatal(err)
}
as, _ := k.GroomThreads(30)
for _, x := range as {
if x.ID == a {
if x.Summary != "current state of work" {
t.Fatalf("summary not stored: %q", x.Summary)
}
if x.ResummaryDue {
t.Fatal("freshly summarized thread should not be due")
}
}
}
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != a || recent < 1 {
t.Fatalf("CurrentFocus = (%d,%d,%v), want thread %d", id, recent, err, a)
}
}
// A retained thread is never denied nor resolved by the denylist pass.
func TestThreadRetained(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
id, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(id, bid, "")
if err := k.SetThreadRetained(id, true); err != nil {
t.Fatal(err)
}
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
for _, a := range as {
if a.ID != id {
continue
}
if !a.Retained {
t.Fatal("thread not reported retained")
}
if a.Denied || a.Verdict == "deny" {
t.Fatalf("retained thread still denied (verdict=%q)", a.Verdict)
}
}
if _, closed, _ := k.DenyThreadNoise(false); len(closed) != 0 {
t.Fatalf("retained thread was resolved: %v", closed)
}
}
// Status is derived: active while recently active, stalled once quiet, and
// resolved only when explicitly closed.
func TestThreadEffectiveStatus(t *testing.T) {
k := newTestDB(t)
recent := obs("fpA", "active thread", "s")
recent.CreatedAt = time.Now().UTC().Format(time.RFC3339)
oa, _, _ := k.RecordObservation(recent)
a, _ := k.CreateThread("active thread", "", "high", "[]", "{}")
k.LinkObservationToThread(a, oa, "")
old := obs("fpB", "old thread", "s")
old.CreatedAt = "2020-01-01T00:00:00Z"
ob, _, _ := k.RecordObservation(old)
b, _ := k.CreateThread("old thread", "", "high", "[]", "{}")
k.LinkObservationToThread(b, ob, "")
c, _ := k.CreateThread("empty thread", "", "high", "[]", "{}")
statusOf := func(id int64, filter string) string {
ts, _ := k.ListThreads(filter)
for _, x := range ts {
if x.ID == id {
return x.Status
}
}
return ""
}
if statusOf(a, "all") != "active" {
t.Fatalf("recent thread should be active")
}
if statusOf(b, "all") != "stalled" {
t.Fatalf("old thread should be stalled")
}
// A brand-new thread with no observations yet is active (falls back to its
// created_at), not immediately stalled.
if statusOf(c, "all") != "active" {
t.Fatalf("new empty thread should be active, got %q", statusOf(c, "all"))
}
if statusOf(b, "active") != "" {
t.Fatalf("stalled thread must not match active filter")
}
if statusOf(b, "stalled") != "stalled" {
t.Fatalf("stalled filter must return stalled thread")
}
// Explicit resolution wins and is sticky.
if err := k.CloseThread(a); err != nil {
t.Fatal(err)
}
if statusOf(a, "all") != "resolved" || statusOf(a, "resolved") != "resolved" {
t.Fatalf("closed thread should be resolved")
}
}
// Rebuild must take the latest observation's content, not an arbitrary row.
func TestRebuildPicksLatestContent(t *testing.T) {
k := newTestDB(t)
if _, _, err := k.RecordObservation(obs("fp1", "t", "s")); err != nil {
t.Fatal(err)
}
b := obs("fp1", "t", "s")
b.Content = "full body text"
if _, _, err := k.RecordObservation(b); err != nil {
t.Fatal(err)
}
if _, _, err := k.RebuildEntriesFromObservations(); err != nil {
t.Fatal(err)
}
var content string
if err := k.db.QueryRow("SELECT content FROM entries WHERE fingerprint='fp1'").Scan(&content); err != nil {
t.Fatal(err)
}
if content != "full body text" {
t.Fatalf("entry content=%q, want latest observation's", content)
}
}
// CurrentFocus ignores passive browsing: a browser-heavy thread must not win
// over a thread with fewer but work-source observations.
func TestCurrentFocusIgnoresBrowser(t *testing.T) {
k := newTestDB(t)
bt, _ := k.CreateThread("dashboard", "", "medium", "[]", "{}")
for i := 0; i < 5; i++ {
b := obs(fmt.Sprintf("b%d", i), "Uptime Kuma", "https://uptime.example/")
b.SourceID = "browser-history"
b.SourcePath = fmt.Sprintf("https://uptime.example/%d", i)
oid, _, _ := k.RecordObservation(b)
k.LinkObservationToThread(bt, oid, "")
}
wt, _ := k.CreateThread("zigbee stack", "", "medium", "[]", "{}")
w := obs("w1", "zigbee stack work", "mosquitto")
w.SourceID = "gitea"
w.SourcePath = "david/x"
oid, _, _ := k.RecordObservation(w)
k.LinkObservationToThread(wt, oid, "")
id, _, recent, err := k.CurrentFocus(14)
if err != nil || id != wt || recent != 1 {
t.Fatalf("CurrentFocus=(%d,%d,%v), want work thread %d", id, recent, err, wt)
}
}
// Newly-arrived observations link to existing threads once (bounded by watermark).
func TestAutoLinkNewObservations(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("zigbee docker stack", "", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
if _, _, err := k.RecordObservation(obs("fp1", "zigbee docker stack notes", "mosquitto compose")); err != nil {
t.Fatal(err)
}
n, err := k.AutoLinkNewObservations()
if err != nil {
t.Fatal(err)
}
if n < 1 {
t.Fatalf("expected >=1 link, got %d", n)
}
// Second pass: nothing new (watermark advanced).
if n2, _ := k.AutoLinkNewObservations(); n2 != 0 {
t.Fatalf("second pass linked %d, want 0", n2)
}
}
// GroomThreads flags a denylisted, non-work thread as "deny" and a
// work-anchored thread as not-denied, and offers a profile-derived title.
func TestGroomThreads(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/"
bid, _, _ := k.RecordObservation(b)
denyID, _ := k.CreateThread("privacy / virtual / card", "cards", "medium", "[]", "{}")
k.LinkObservationToThread(denyID, bid, "")
w := obs("fpw", "nr-flow-validator", "rego validation work")
w.SourceID = "gitea"
w.SourcePath = "klubhaus/nr-flow-validator"
wid, _, _ := k.RecordObservation(w)
workID, _ := k.CreateThread("nr-flow-validator Rego validation", "real work", "high", "[]", "{}")
k.LinkObservationToThread(workID, wid, "")
as, err := k.GroomThreads(30)
if err != nil {
t.Fatal(err)
}
byID := map[int64]ThreadAssessment{}
for _, a := range as {
byID[a.ID] = a
}
if byID[denyID].Verdict != "deny" {
t.Errorf("deny thread verdict=%q, want deny", byID[denyID].Verdict)
}
if !byID[denyID].Denied || byID[denyID].DenyMatch == "" {
t.Errorf("deny thread should be flagged with a match")
}
if byID[workID].Verdict == "deny" {
t.Errorf("work thread must not be denied")
}
if !byID[workID].WorkAnchored {
t.Errorf("work thread should be work-anchored")
}
// Human titles get no suggestion; auto-style/denied titles do.
if byID[workID].SuggestedTitle != "" {
t.Errorf("human-titled thread should have no suggested title, got %q", byID[workID].SuggestedTitle)
}
if byID[denyID].SuggestedTitle == "" {
t.Errorf("auto-style/denied thread should have a suggested title")
}
}
// DenyThreadNoise drops denylisted browser links and resolves a denylisted
// thread that has no work-source anchor.
func TestDenyThreadNoise(t *testing.T) {
k := newTestDB(t)
b := obs("fpb", "Privacy.com", "https://app.privacy.com/cards")
b.SourceID = "browser-history"
b.SourcePath = "https://app.privacy.com/cards"
obsID, _, err := k.RecordObservation(b)
if err != nil {
t.Fatal(err)
}
id, err := k.CreateThread("privacy / virtual / card", "virtual cards", "medium", "[]", "{}")
if err != nil {
t.Fatal(err)
}
if err := k.LinkObservationToThread(id, obsID, ""); err != nil {
t.Fatal(err)
}
removed, closed, err := k.DenyThreadNoise(false)
if err != nil {
t.Fatal(err)
}
if removed < 1 {
t.Fatalf("removed=%d, want >=1", removed)
}
found := false
for _, c := range closed {
if c == id {
found = true
}
}
if !found {
t.Fatalf("thread #%d not closed; closed=%v", id, closed)
}
t2, _ := k.GetThread(id)
if t2.Status != "resolved" {
t.Fatalf("status=%q, want resolved", t2.Status)
}
}
// A one-character typo should still match via the vocabulary fuzzy fallback.
func TestSearchFuzzyTypo(t *testing.T) {
k := newTestDB(t)
r := obs("fp1", "amazon web services", "cloud hosting")
r.Content = "amazon web services documentation and pricing"
if _, _, err := k.RecordObservation(r); err != nil {
t.Fatal(err)
}
for _, typo := range []string{"amazn", "servies"} {
got, err := k.Search(typo, 10)
if err != nil {
t.Fatal(err)
}
if len(got) == 0 {
t.Fatalf("typo %q returned no results", typo)
}
}
}
// "all"/empty must list every thread; the literal 'all' previously matched none.
func TestListThreadsAll(t *testing.T) {
k := newTestDB(t)
if _, err := k.CreateThread("T", "motivation", "high", "[]", "{}"); err != nil {
t.Fatal(err)
}
for _, status := range []string{"", "all", "ALL"} {
got, err := k.ListThreads(status)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("ListThreads(%q)=%d threads, want 1", status, len(got))
}
}
}
func tmpDB(t *testing.T) *KnoxDB {
t.Helper()
kdb, err := Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { kdb.Close() })
return kdb
}
func record(t *testing.T, k *KnoxDB, fp, title string) {
t.Helper()
_, _, err := k.RecordObservation(ObservationRecord{
Fingerprint: fp,
SourceID: "test",
SourcePath: fp,
Project: "itest",
ContentType: "test",
Title: title,
Summary: "summary",
CreatedAt: "2026-08-29T00:00:00Z",
LineEnd: 0,
Confidence: 0.9,
IngesterVersion: "test/v1",
})
if err != nil {
t.Errorf("record %s: %v", fp, err)
}
}
func obsCount(t *testing.T, k *KnoxDB) int {
t.Helper()
stats, err := k.Stats()
if err != nil {
t.Fatalf("stats: %v", err)
}
n, _ := stats["total_observations"].(int)
return n
}
// TestRecordObservationConcurrentDedup: N goroutines ingesting identical
// content must produce exactly one observation row. This exercises the
// check-then-insert dedup under the writeMu + BEGIN IMMEDIATE serialization.
func TestRecordObservationConcurrentDedup(t *testing.T) {
k := tmpDB(t)
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
record(t, k, "fp:concurrent", "same title")
}()
}
wg.Wait()
if n := obsCount(t, k); n != 1 {
t.Fatalf("expected exactly 1 observation after concurrent identical ingests, got %d", n)
}
}
// TestRecordObservationDistinctFingerprints: different content must never be
// deduped away (the constraint is per-fingerprint signature, not global).
func TestRecordObservationDistinctFingerprints(t *testing.T) {
k := tmpDB(t)
record(t, k, "fp:a", "alpha")
record(t, k, "fp:b", "beta")
record(t, k, "fp:a", "alpha changed")
if n := obsCount(t, k); n != 3 {
t.Fatalf("expected 3 observations, got %d", n)
}
}
// TestPushObservationsValidation: forged/malformed rows are rejected without
// error — self node_id (poisoning vector), empty node_id, negative HCL.
func TestPushObservationsValidation(t *testing.T) {
k := tmpDB(t)
foreign := GossipObservation{
NodeID: "0123456789abcdef0123456789abcdef", HCL: 42,
Fingerprint: "fp:foreign", SourceID: "test", Title: "t", Summary: "s",
CollectedAt: "2026-08-29T00:00:00Z",
}
rows := []GossipObservation{
foreign,
{NodeID: k.NodeID(), HCL: 100, Fingerprint: "fp:self"}, // spoof poisoning attempt
{NodeID: "", HCL: 1, Fingerprint: "fp:empty"},
{NodeID: "other", HCL: -5, Fingerprint: "fp:neg"},
}
n, err := k.PushObservations(rows)
if err != nil {
t.Fatalf("push: %v", err)
}
if n != 1 {
t.Fatalf("expected exactly the one valid row inserted, got %d", n)
}
if got := obsCount(t, k); got != 1 {
t.Fatalf("expected 1 observation in the log, got %d", got)
}
}
// TestOpenReopenHCLMonotonicAcrossRestart: reopening a DB must resume the HLC
// from its persisted max (clock seeding), keep the node identity, and order the
// new observation above every previous one.
func TestOpenReopenHCLMonotonicAcrossRestart(t *testing.T) {
path := filepath.Join(t.TempDir(), "index.db")
k1, err := Open(path)
if err != nil {
t.Fatalf("open: %v", err)
}
record(t, k1, "fp:r1", "one")
record(t, k1, "fp:r2", "two")
record(t, k1, "fp:r3", "three")
nodeID1 := k1.NodeID()
maxBefore := int64(0)
rows, err := k1.ObservationsAfter(nodeID1, 0, 100)
if err != nil {
t.Fatalf("obs after: %v", err)
}
for _, r := range rows {
if r.HCL > maxBefore {
maxBefore = r.HCL
}
}
if err := k1.Close(); err != nil {
t.Fatalf("close: %v", err)
}
k2, err := Open(path)
if err != nil {
t.Fatalf("reopen: %v", err)
}
defer k2.Close()
if k2.NodeID() != nodeID1 {
t.Errorf("node id changed across reopen: %q -> %q", nodeID1, k2.NodeID())
}
record(t, k2, "fp:r4", "four")
after, err := k2.ObservationsAfter(nodeID1, maxBefore, 100)
if err != nil {
t.Fatalf("obs after (reopened): %v", err)
}
if len(after) != 1 {
t.Fatalf("expected exactly the new observation above the pre-restart max, got %d rows", len(after))
}
if after[0].Fingerprint != "fp:r4" {
t.Errorf("unexpected row above max: %s", after[0].Fingerprint)
}
}
// TestCreateThreadClusterConcurrentIdempotent: two concurrent creators of the
// same cluster key must converge on one thread (one created=true, one false)
// with no UNIQUE constraint error — the INSERT OR IGNORE path.
func TestCreateThreadClusterConcurrentIdempotent(t *testing.T) {
k := tmpDB(t)
const key = "cluster:race"
var wg sync.WaitGroup
ids := make([]int64, 2)
created := make([]bool, 2)
errs := make([]error, 2)
for i := 0; i < 2; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
ids[i], created[i], errs[i] = k.CreateThreadCluster("Race thread", "m", "medium", "[]", `{}`, key)
}(i)
}
wg.Wait()
for i := range errs {
if errs[i] != nil {
t.Fatalf("creator %d: %v", i, errs[i])
}
}
if ids[0] != ids[1] {
t.Errorf("concurrent creators got different ids: %d vs %d", ids[0], ids[1])
}
if created[0] == created[1] {
t.Errorf("exactly one creator should report created=true, got %v %v", created[0], created[1])
}
threads, err := k.ListThreads("")
if err != nil {
t.Fatal(err)
}
n := 0
for _, th := range threads {
if th.Title == "Race thread" {
n++
}
}
if n != 1 {
t.Errorf("want exactly 1 race thread, got %d", n)
}
}
// TestRebuildEntriesDeterministicFold: two nodes holding the same observations
// in different merge orders must rebuild identical derived state — content
// fields come from the highest-HCL observation per fingerprint (spec 6.2),
// never from an arbitrary (merge-order-dependent) row.
func TestRebuildEntriesDeterministicFold(t *testing.T) {
const foreign = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
rows := []GossipObservation{
{NodeID: foreign, HCL: 10, Fingerprint: "fp:fold", SourceID: "test", Title: "old title", Summary: "old", CollectedAt: "2026-08-29T00:00:00Z", Confidence: 0.5},
{NodeID: foreign, HCL: 20, Fingerprint: "fp:fold", SourceID: "test", Title: "new title", Summary: "new", CollectedAt: "2026-08-29T01:00:00Z", Confidence: 0.9},
}
results := make([]Entry, 2)
for i, order := range [][]GossipObservation{{rows[0], rows[1]}, {rows[1], rows[0]}} {
k := tmpDB(t)
if _, err := k.PushObservations(order); err != nil {
t.Fatalf("push: %v", err)
}
if _, _, err := k.RebuildEntriesFromObservations(); err != nil {
t.Fatalf("rebuild: %v", err)
}
e, err := k.FindEntry("fp:fold")
if err != nil || e == nil {
t.Fatalf("find entry: %v", err)
}
results[i] = *e
}
if results[0].Title != "new title" {
t.Errorf("order [old,new]: title = %q, want %q", results[0].Title, "new title")
}
if results[1].Title != "new title" {
t.Errorf("order [new,old]: title = %q, want %q", results[1].Title, "new title")
}
if results[0] != results[1] {
t.Errorf("derived state diverged between merge orders:\n%+v\n%+v", results[0], results[1])
}
if results[0].RefCount != 2 {
t.Errorf("ref_count = %d, want 2", results[0].RefCount)
}
if results[0].FirstSeen != "2026-08-29T00:00:00Z" || results[0].LastSeen != "2026-08-29T01:00:00Z" {
t.Errorf("first/last seen = %q/%q", results[0].FirstSeen, results[0].LastSeen)
}
}
// A polished auto-thread has to leave the draft queue. Drafts are detected by
// the auto_thread provenance marker (or an "Auto-detected" motivation), and
// nothing cleared either of them before: an edited thread was a draft forever.
func TestUpdateThreadClearsAutoThreadMarker(t *testing.T) {
k := newTestDB(t)
prov := `{"cluster":"plant / care / dashboard","score":3.9,"sources":["git","gitea"],"trigger":"auto_thread"}`
id, err := k.CreateThread("plant / care / dashboard", "Auto-detected cluster of 4 observations",
"medium", "[]", prov)
if err != nil {
t.Fatalf("create: %v", err)
}
changed, err := k.UpdateThread(id, "plant-care: watering analytics", "", "", "")
if err != nil {
t.Fatalf("update: %v", err)
}
if !changed {
t.Fatal("update reported no change")
}
got, err := k.GetThread(id)
if err != nil || got == nil {
t.Fatalf("get: %v", err)
}
if strings.Contains(got.Provenance, "auto_thread") {
t.Fatalf("auto_thread marker survived a retitle: %s", got.Provenance)
}
var meta map[string]any
if err := json.Unmarshal([]byte(got.Provenance), &meta); err != nil {
t.Fatalf("provenance is not JSON: %v (%s)", err, got.Provenance)
}
if meta["cluster"] != "plant / care / dashboard" {
t.Fatalf("cluster dropped from provenance: %v", meta)
}
if meta["groomed"] != true {
t.Fatalf("groomed flag not recorded: %v", meta)
}
// A motivation rewrite alone is also an editorial pass.
other, _ := k.CreateThread("zigbee / docker / stack", "Auto-detected cluster", "medium", "[]",
`{"trigger":"auto_thread","cluster":"zigbee"}`)
if _, err := k.UpdateThread(other, "", "Build the klubhaus Zigbee stack", "", ""); err != nil {
t.Fatalf("update motivation: %v", err)
}
if got, _ := k.GetThread(other); strings.Contains(got.Provenance, "auto_thread") {
t.Fatalf("auto_thread marker survived a motivation rewrite: %s", got.Provenance)
}
// Tag-only edits are not editorial: the thread is still a draft.
third, _ := k.CreateThread("kuma / uptime", "Auto-detected cluster", "medium", "[]",
`{"trigger":"auto_thread"}`)
if _, err := k.UpdateThread(third, "", "", "", "uptime monitoring"); err != nil {
t.Fatalf("update tags: %v", err)
}
if got, _ := k.GetThread(third); !strings.Contains(got.Provenance, "auto_thread") {
t.Fatalf("a tag-only edit cleared the draft marker: %s", got.Provenance)
}
// Provenance that was never auto-generated is left alone.
own, _ := k.CreateThread("manual thread", "by hand", "high", "[]", `{"trigger":"display-watch","host":"surf"}`)
if _, err := k.UpdateThread(own, "manual thread, renamed", "", "", ""); err != nil {
t.Fatalf("update manual: %v", err)
}
if got, _ := k.GetThread(own); got.Provenance != `{"trigger":"display-watch","host":"surf"}` {
t.Fatalf("unrelated provenance was rewritten: %s", got.Provenance)
}
}
// The draft queue is "auto-threaded clusters still worth polishing". A merged
// cluster is resolved and empty, so it must not come back as a candidate.
func TestThreadIsDraft(t *testing.T) {
cases := []struct {
name string
t Thread
draft bool
}{
{"marker", Thread{Status: "active", EntryCount: 12, Provenance: `{"trigger":"auto_thread"}`}, true},
{"prefix", Thread{Status: "stalled", EntryCount: 3, Motivation: "Auto-detected cluster of 4"}, true},
{"groomed", Thread{Status: "active", EntryCount: 12,
Provenance: `{"groomed":true,"cluster":"plant"}`, Motivation: "Plant watering"}, false},
{"merged", Thread{Status: "resolved", EntryCount: 0, Provenance: `{"trigger":"auto_thread"}`}, false},
{"resolved with work", Thread{Status: "resolved", EntryCount: 9, Provenance: `{"trigger":"auto_thread"}`}, false},
{"empty cluster", Thread{Status: "active", EntryCount: 0, Motivation: "Auto-detected cluster"}, false},
{"manual", Thread{Status: "active", EntryCount: 4,
Provenance: `{"trigger":"display-watch"}`, Motivation: "By hand"}, false},
}
for _, c := range cases {
if got := c.t.IsDraft(); got != c.draft {
t.Errorf("%s: IsDraft()=%v, want %v", c.name, got, c.draft)
}
}
}
// Retention is not judgement: an old uncurated candidate is rejected so the
// review queue tracks recent work, while curated rows are never touched.
func TestExpireSnippets(t *testing.T) {
k := newTestDB(t)
add := func(fp, code string) {
t.Helper()
if _, err := k.UpsertSnippet(SnippetRecord{
Fingerprint: fp, Language: "go", Code: code, Title: fp, Tags: "[]",
SourceSession: "ses_1", Project: "demo", Tool: "write", Kind: "code",
}); err != nil {
t.Fatalf("upsert: %v", err)
}
}
setSeen := func(fp, when string) {
t.Helper()
if _, err := k.db.Exec(`UPDATE snippets SET discovered_at=? WHERE fingerprint=?`, when, fp); err != nil {
t.Fatalf("set discovered_at: %v", err)
}
}
old := "2026-01-01T00:00:00Z"
recent := time.Now().UTC().Format(time.RFC3339)
add("fp_old", "package demo\n\nfunc Old() {}\n")
add("fp_recent", "package demo\n\nfunc Recent() {}\n")
add("fp_encoded", "package demo\n\nfunc Encoded() {}\n")
setSeen("fp_old", old)
setSeen("fp_recent", recent)
setSeen("fp_encoded", old)
if _, err := k.db.Exec(`UPDATE snippets SET status='encoded' WHERE fingerprint='fp_encoded'`); err != nil {
t.Fatalf("encode: %v", err)
}
cutoff := time.Now().UTC().AddDate(0, 0, -30)
n, err := k.CountExpiredCandidates(cutoff)
if err != nil {
t.Fatalf("count: %v", err)
}
if n != 1 {
t.Fatalf("expirable=%d, want 1", n)
}
expired, err := k.ExpireSnippets(cutoff, "")
if err != nil {
t.Fatalf("expire: %v", err)
}
if expired != 1 {
t.Fatalf("expired=%d, want 1", expired)
}
status := func(fp string) (string, string) {
t.Helper()
var s, reason string
if err := k.db.QueryRow(`SELECT status, COALESCE(reject_reason,'') FROM snippets WHERE fingerprint=?`, fp).
Scan(&s, &reason); err != nil {
t.Fatalf("status %s: %v", fp, err)
}
return s, reason
}
if s, reason := status("fp_old"); s != "rejected" || !strings.Contains(reason, "retention") {
t.Fatalf("old candidate = %q / %q", s, reason)
}
if s, _ := status("fp_recent"); s != "candidate" {
t.Fatalf("recent candidate = %q, want candidate", s)
}
if s, _ := status("fp_encoded"); s != "encoded" {
t.Fatalf("encoded snippet = %q, want encoded", s)
}
}