edf6c03a7c
Pre-existing work-in-progress in the tree: karakeep, snippets, skills-health and redaction ingesters, the opencode.db session sweep, gossip and metrics changes. Checkpointed as-is so the adapter fix in the next commit stays reviewable on its own.
501 lines
14 KiB
Go
501 lines
14 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"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))
|
|
}
|
|
}
|
|
}
|