Merge commit '52c4d1f' into feat/remote-node

# Conflicts:
#	internal/db/db.go
This commit is contained in:
2026-11-03 23:00:20 -08:00
26 changed files with 1414 additions and 78 deletions
+178 -63
View File
@@ -412,11 +412,25 @@ func (k *KnoxDB) RecordObservation(o ObservationRecord) (obsID int64, isNew bool
// 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) {
if _, err := tx.Exec(
res, err := tx.Exec(
`INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, 'auto')`,
goldenID, obsID,
); err == nil {
tx.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, goldenID)
)
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)
}
}
}
}
@@ -424,6 +438,55 @@ func (k *KnoxDB) RecordObservation(o ObservationRecord) (obsID int64, isNew bool
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(
@@ -498,25 +561,25 @@ func (k *KnoxDB) RebuildEntriesFromObservations() (before, after int, err error)
if _, err := tx.Exec("DELETE FROM entries"); err != nil {
return 0, 0, err
}
// Pick the LATEST observation per fingerprint deterministically for the
// content columns (a bare GROUP BY column picks an arbitrary/stale row —
// e.g. a pre-content observation with content=''), and aggregate the rest.
// 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)
WITH latest AS (
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, id DESC) AS rn
FROM observations
),
agg AS (
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
)
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 latest l JOIN agg ON agg.fingerprint = l.fingerprint
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 {
@@ -837,6 +900,9 @@ func scanEntries(rows *sql.Rows) ([]Entry, error) {
}
entries = append(entries, e)
}
if err := rows.Err(); err != nil {
return nil, err
}
return entries, nil
}
@@ -889,33 +955,39 @@ func (k *KnoxDB) MarkSessionIndexed(sessionID string) error {
func (k *KnoxDB) Stats() (map[string]any, error) {
stats := make(map[string]any)
var v int
var s string
// 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
}
k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&v)
stats["total_entries"] = v
v = 0
k.db.QueryRow("SELECT COUNT(*) FROM entries WHERE last_seen > datetime('now', '-1 day')").Scan(&v)
stats["entries_last_24h"] = v
v = 0
k.db.QueryRow("SELECT COUNT(DISTINCT project) FROM entries").Scan(&v)
stats["total_projects"] = v
v = 0
k.db.QueryRow("SELECT COUNT(*) FROM observations").Scan(&v)
stats["total_observations"] = v
v = 0
k.db.QueryRow("SELECT COUNT(*) FROM observations WHERE collected_at > datetime('now', '-1 day')").Scan(&v)
stats["observations_last_24h"] = v
v = 0
k.db.QueryRow("SELECT COALESCE(MIN(collected_at),'') FROM observations").Scan(&s)
stats["earliest_observation"] = s
s = ""
k.db.QueryRow("SELECT COUNT(*) FROM sessions").Scan(&v)
stats["total_sessions"] = v
v = 0
k.db.QueryRow("SELECT COUNT(*) FROM sessions WHERE indexed=0").Scan(&v)
stats["pending_reflections"] = v
v = 0
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 {
@@ -928,9 +1000,17 @@ func (k *KnoxDB) Stats() (map[string]any, error) {
}
// The golden thread is an explicit, optional pin (used for auto-linking);
// it is reported separately and flagged when it disagrees with reality.
if goldenID, _ := k.GoldenThreadID(); goldenID > 0 {
goldenID, err := k.GoldenThreadID()
if err != nil {
return nil, fmt.Errorf("stats golden_thread: %w", err)
}
if goldenID > 0 {
stats["pinned_thread_id"] = goldenID
if t, _ := k.GetThread(goldenID); t != nil {
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 {
@@ -1519,20 +1599,26 @@ func (k *KnoxDB) CreateThread(title, motivation, priority, tags, provenance stri
}
func (k *KnoxDB) CreateThreadCluster(title, motivation, priority, tags, provenance, clusterKey string) (int64, bool, error) {
if clusterKey != "" {
if existing := k.ThreadByClusterKey(clusterKey); existing != 0 {
return existing, false, nil
}
}
// 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 INTO threads (title, motivation, priority, tags, provenance, cluster_key) VALUES (?, ?, ?, ?, ?, ?)`,
`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
}
id, _ := res.LastInsertId()
return id, true, nil
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
@@ -1640,15 +1726,21 @@ func (k *KnoxDB) UpdateThread(id int64, title, motivation, priority, tags string
}
func (k *KnoxDB) LinkObservationToThread(threadID, observationID int64, relevance string) error {
_, err := k.db.Exec(
`INSERT OR IGNORE INTO thread_observations (thread_id, observation_id, relevance) VALUES (?, ?, ?)`,
threadID, observationID, relevance,
)
tx, err := k.db.Begin()
if err != nil {
return err
}
_, err = k.db.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID)
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
@@ -1663,6 +1755,7 @@ func (k *KnoxDB) AutoLinkThreadObservations(threadID int64, fingerprints []strin
defer tx.Rollback()
linked := 0
var firstErr error
for _, fp := range fingerprints {
if fp == "" {
continue
@@ -1671,6 +1764,11 @@ func (k *KnoxDB) AutoLinkThreadObservations(threadID int64, fingerprints []strin
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(
@@ -1678,6 +1776,9 @@ func (k *KnoxDB) AutoLinkThreadObservations(threadID int64, fingerprints []strin
threadID, obsID,
)
if err != nil {
if firstErr == nil {
firstErr = err
}
continue
}
if n, _ := res.RowsAffected(); n > 0 {
@@ -1690,7 +1791,10 @@ func (k *KnoxDB) AutoLinkThreadObservations(threadID int64, fingerprints []strin
return linked, err
}
}
return linked, tx.Commit()
if err := tx.Commit(); err != nil {
return linked, err
}
return linked, firstErr
}
// ActiveThreadByKeyword returns the most recently updated active thread whose
@@ -1759,15 +1863,26 @@ func (k *KnoxDB) ThreadObservations(threadID int64) ([]Observation, error) {
}
func (k *KnoxDB) AddThreadNote(threadID int64, note string) (int64, error) {
res, err := k.db.Exec(
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
}
_, err = k.db.Exec(`UPDATE threads SET updated_at=datetime('now') WHERE id=?`, threadID)
return res.LastInsertId()
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 {