Compare commits

..

2 Commits

Author SHA1 Message Date
david e07ae8aa27 fix: read opencode sessions from session_v2/session_message
opencode 2.0.24 migrated its session store: the session, message and
part tables stopped being written, and sessions now live in session_v2
with messages in session_message. The ingest kept querying the abandoned
tables, so every sweep after the migration logged "0 new" and no error.

Session titles are nullable in session_v2, so keep the COALESCE and the
"Session <short id>" fallback.

Transcripts are rebuilt from both message shapes the new store uses:
user turns carry text at $.text, assistant turns carry a typed part list
at $.content of which only "text" parts are conversation (reasoning and
tool parts are not indexed). Rows are ordered by seq, then part index,
so a session reads in order.

Harness reminders arrive as synthetic messages now; drop <system-reminder>
text so it does not consume the 4000-byte summary budget.

Also stop skipping an entry purely on created_at: resuming a session
appends messages without touching the creation time, so the summary is
compared too and the entry refreshes.

Bump the ingester to opencode-db/v2 and cover both message shapes with a
test that builds the new schema in a temp database.

Fixes #6
2026-11-01 13:33:56 -08:00
david edf6c03a7c chore: checkpoint uncommitted work before session store fix
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.
2026-11-01 13:33:36 -08:00
21 changed files with 195 additions and 828 deletions
+5 -5
View File
@@ -5,9 +5,9 @@ import (
"log" "log"
"strings" "strings"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest" "github.com/david/knox/internal/ingest"
"github.com/spf13/cobra"
) )
func NewBrowserCmd(kdb *db.KnoxDB) *cobra.Command { func NewBrowserCmd(kdb *db.KnoxDB) *cobra.Command {
@@ -67,10 +67,10 @@ Run periodically to capture browsing exhaust.`,
for _, r := range results { for _, r := range results {
domains[extractDomain(r.Summary)]++ domains[extractDomain(r.Summary)]++
} }
fmt.Println("\nTop domains:") fmt.Println("\nTop domains:")
for _, d := range topDomains(domains, 10) { for _, d := range topDomains(domains, 10) {
fmt.Printf(" %-40s %d\n", d.Name, d.Count) fmt.Printf(" %-40s %d\n", d.Name, d.Count)
} }
return nil return nil
}, },
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"fmt" "fmt"
"log" "log"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest" "github.com/david/knox/internal/ingest"
"github.com/spf13/cobra"
) )
func NewGiteaCmd(kdb *db.KnoxDB) *cobra.Command { func NewGiteaCmd(kdb *db.KnoxDB) *cobra.Command {
+2 -2
View File
@@ -3,9 +3,9 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch" "github.com/david/knox/internal/watch"
"github.com/spf13/cobra"
) )
// NewGossipCmd exposes peer status/diff for the gossip protocol. // NewGossipCmd exposes peer status/diff for the gossip protocol.
@@ -154,4 +154,4 @@ func min(a, b int) int {
return a return a
} }
return b return b
} }
+48 -215
View File
@@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -54,14 +53,8 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(searchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(searchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
query, err := requiredStringArg(req, "query") query, _ := req.Params.Arguments["query"].(string)
if err != nil { limit := clampInt(req, "limit", 10, 1, 50)
return errorResult(err.Error()), nil
}
limit, err := optionalIntArg(req, "limit", 10, 1, 50)
if err != nil {
return errorResult(err.Error()), nil
}
detail := parseDetail(getString(req, "detail", "normal")) detail := parseDetail(getString(req, "detail", "normal"))
scope := getString(req, "scope", "all") scope := getString(req, "scope", "all")
@@ -107,10 +100,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(recentTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(recentTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
limit, err := optionalIntArg(req, "limit", 10, 1, 50) limit := clampInt(req, "limit", 10, 1, 50)
if err != nil {
return errorResult(err.Error()), nil
}
detail := parseDetail(getString(req, "detail", "normal")) detail := parseDetail(getString(req, "detail", "normal"))
scope := getString(req, "scope", "all") scope := getString(req, "scope", "all")
@@ -133,10 +123,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(getTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(getTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
fp, err := requiredStringArg(req, "fingerprint") fp := getString(req, "fingerprint", "")
if err != nil {
return errorResult(err.Error()), nil
}
entry, err := kdb.FindEntry(fp) entry, err := kdb.FindEntry(fp)
if err != nil { if err != nil {
@@ -202,10 +189,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(countTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(countTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
query, err := requiredStringArg(req, "query") query, _ := req.Params.Arguments["query"].(string)
if err != nil {
return errorResult(err.Error()), nil
}
results, err := kdb.Search(query, 500) results, err := kdb.Search(query, 500)
if err != nil { if err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
@@ -275,10 +259,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadCreateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadCreateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
title, err := requiredStringArg(req, "title") title := getString(req, "title", "")
if err != nil {
return errorResult(err.Error()), nil
}
motivation := getString(req, "motivation", "") motivation := getString(req, "motivation", "")
priority := getString(req, "priority", "medium") priority := getString(req, "priority", "medium")
provenance := getString(req, "provenance", "{}") provenance := getString(req, "provenance", "{}")
@@ -300,10 +281,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadUpdateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadUpdateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
id, err := requiredIntArg(req, "thread_id", 1, 999999) id := int64(clampInt(req, "thread_id", 0, 1, 999999))
if err != nil {
return errorResult(err.Error()), nil
}
title := getString(req, "title", "") title := getString(req, "title", "")
motivation := getString(req, "motivation", "") motivation := getString(req, "motivation", "")
priority := getString(req, "priority", "") priority := getString(req, "priority", "")
@@ -327,10 +305,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadDraftTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadDraftTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
limit, err := optionalIntArg(req, "limit", 20, 1, 200) limit := clampInt(req, "limit", 20, 1, 200)
if err != nil {
return errorResult(err.Error()), nil
}
threads, err := kdb.ListThreads("") threads, err := kdb.ListThreads("")
if err != nil { if err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
@@ -378,18 +353,9 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadLinkTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadLinkTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
threadID, err := requiredIntArg(req, "thread_id", 1, 999999) threadID := int64(clampInt(req, "thread_id", 0, 1, 999999))
if err != nil { obsID := int64(clampInt(req, "observation_id", 0, 1, 999999))
return errorResult(err.Error()), nil
}
obsID, err := requiredIntArg(req, "observation_id", 1, 999999)
if err != nil {
return errorResult(err.Error()), nil
}
relevance := getString(req, "relevance", "") relevance := getString(req, "relevance", "")
if err := threadExists(kdb, threadID); err != nil {
return errorResult(err.Error()), nil
}
if err := kdb.LinkObservationToThread(threadID, obsID, relevance); err != nil { if err := kdb.LinkObservationToThread(threadID, obsID, relevance); err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
} }
@@ -403,10 +369,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadSearchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadSearchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
query, err := requiredStringArg(req, "query") query := getString(req, "query", "")
if err != nil {
return errorResult(err.Error()), nil
}
threads, err := kdb.SearchThreadsByMotivation(query) threads, err := kdb.SearchThreadsByMotivation(query)
if err != nil { if err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
@@ -433,18 +396,9 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadLinkEntryTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadLinkEntryTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
threadID, err := requiredIntArg(req, "thread_id", 1, 999999) threadID := int64(clampInt(req, "thread_id", 0, 1, 999999))
if err != nil { fp := getString(req, "fingerprint", "")
return errorResult(err.Error()), nil
}
fp, err := requiredStringArg(req, "fingerprint")
if err != nil {
return errorResult(err.Error()), nil
}
relation := getString(req, "relation", "produced") relation := getString(req, "relation", "produced")
if err := threadExists(kdb, threadID); err != nil {
return errorResult(err.Error()), nil
}
if err := kdb.LinkEntryToThread(threadID, fp, relation); err != nil { if err := kdb.LinkEntryToThread(threadID, fp, relation); err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
} }
@@ -460,21 +414,9 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadRelateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadRelateTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
parentID, err := requiredIntArg(req, "parent_id", 1, 999999) parentID := int64(clampInt(req, "parent_id", 0, 1, 999999))
if err != nil { childID := int64(clampInt(req, "child_id", 0, 1, 999999))
return errorResult(err.Error()), nil
}
childID, err := requiredIntArg(req, "child_id", 1, 999999)
if err != nil {
return errorResult(err.Error()), nil
}
relation := getString(req, "relation", "spawned") relation := getString(req, "relation", "spawned")
if err := threadExists(kdb, parentID); err != nil {
return errorResult(err.Error()), nil
}
if err := threadExists(kdb, childID); err != nil {
return errorResult(err.Error()), nil
}
if err := kdb.LinkEntryToThread(childID, db.ThreadFP(parentID), relation); err != nil { if err := kdb.LinkEntryToThread(childID, db.ThreadFP(parentID), relation); err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
} }
@@ -488,67 +430,29 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(goldenTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(goldenTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
// Absent thread_id: query the current golden thread. threadID := int64(clampInt(req, "thread_id", 0, 0, 999999))
if _, ok := req.Params.Arguments["thread_id"]; !ok {
current, err := kdb.GoldenThreadID() if threadID == 0 {
if err != nil { // Query or clear
return errorResult(err.Error()), nil current, _ := kdb.GoldenThreadID()
}
if current == 0 { if current == 0 {
return mcp.NewToolResultText("No golden thread set."), nil return mcp.NewToolResultText("No golden thread set."), nil
} }
t, err := kdb.GetThread(current) // If thread_id was explicitly 0 and a golden exists, clear it
if err != nil { if _, ok := req.Params.Arguments["thread_id"]; ok {
return errorResult(err.Error()), nil kdb.SetGoldenThread(0)
} t, _ := kdb.GetThread(current)
if t == nil { return mcp.NewToolResultText(fmt.Sprintf("Golden thread cleared (was #%d: %s)", current, t.Title)), nil
return errorResult(fmt.Sprintf("Golden thread #%d no longer exists", current)), nil
} }
t, _ := kdb.GetThread(current)
return mcp.NewToolResultText(fmt.Sprintf("Golden thread: #%d %s [%s]\n %s", t.ID, t.Title, t.Status, t.Motivation)), nil return mcp.NewToolResultText(fmt.Sprintf("Golden thread: #%d %s [%s]\n %s", t.ID, t.Title, t.Status, t.Motivation)), nil
} }
threadID, err := requiredIntArg(req, "thread_id", 0, 999999)
if err != nil {
return errorResult(err.Error()), nil
}
if threadID == 0 {
// Explicit 0 clears the golden thread.
current, err := kdb.GoldenThreadID()
if err != nil {
return errorResult(err.Error()), nil
}
if current == 0 {
return mcp.NewToolResultText("No golden thread set."), nil
}
if err := kdb.SetGoldenThread(0); err != nil {
return errorResult(err.Error()), nil
}
t, err := kdb.GetThread(current)
if err != nil {
return errorResult(err.Error()), nil
}
name := "?"
if t != nil {
name = t.Title
}
return mcp.NewToolResultText(fmt.Sprintf("Golden thread cleared (was #%d: %s)", current, name)), nil
}
if err := threadExists(kdb, threadID); err != nil {
return errorResult(err.Error()), nil
}
if err := kdb.SetGoldenThread(threadID); err != nil { if err := kdb.SetGoldenThread(threadID); err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
} }
t, err := kdb.GetThread(threadID) t, _ := kdb.GetThread(threadID)
if err != nil { return mcp.NewToolResultText(fmt.Sprintf("Golden thread set to #%d: %s", threadID, t.Title)), nil
return errorResult(err.Error()), nil
}
name := "?"
if t != nil {
name = t.Title
}
return mcp.NewToolResultText(fmt.Sprintf("Golden thread set to #%d: %s", threadID, name)), nil
}) })
// ─── knox_thread_deny ─────────────────────────────────────── // ─── knox_thread_deny ───────────────────────────────────────
@@ -700,10 +604,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
fmt.Fprintf(&b, "Merged %d/%d thread pairs.\n", n, len(ms)) fmt.Fprintf(&b, "Merged %d/%d thread pairs.\n", n, len(ms))
} }
staleDays, err := optionalIntArg(req, "stale_days", 30, 1, 3650) staleDays := clampInt(req, "stale_days", 30, 1, 3650)
if err != nil {
return errorResult(err.Error()), nil
}
dueOnly, _ := req.Params.Arguments["due_only"].(bool) dueOnly, _ := req.Params.Arguments["due_only"].(bool)
assessments, err := kdb.GroomThreads(staleDays) assessments, err := kdb.GroomThreads(staleDays)
if err != nil { if err != nil {
@@ -711,10 +612,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
} }
wantVerdict := strings.ToLower(strings.TrimSpace(getString(req, "verdict", ""))) wantVerdict := strings.ToLower(strings.TrimSpace(getString(req, "verdict", "")))
minLinked, err := optionalIntArg(req, "min_linked", 0, 0, 999999) minLinked := clampInt(req, "min_linked", 0, 0, 999999)
if err != nil {
return errorResult(err.Error()), nil
}
counts := map[string]int{} counts := map[string]int{}
dueCount := 0 dueCount := 0
@@ -789,15 +687,8 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(threadTextTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(threadTextTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
threadID, err := optionalIntArg(req, "thread_id", 0, 1, 999999) id := int64(clampInt(req, "thread_id", 0, 1, 999999))
if err != nil { maxBytes := clampInt(req, "max_bytes", 16000, 500, 200000)
return errorResult(err.Error()), nil
}
maxBytes, err := optionalIntArg(req, "max_bytes", 16000, 500, 200000)
if err != nil {
return errorResult(err.Error()), nil
}
id := int64(threadID)
text, err := kdb.ThreadText(id, maxBytes) text, err := kdb.ThreadText(id, maxBytes)
if err != nil { if err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
@@ -824,10 +715,7 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(topicsTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(topicsTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
limit, err := optionalIntArg(req, "limit", 10, 1, 30) limit := clampInt(req, "limit", 10, 1, 30)
if err != nil {
return errorResult(err.Error()), nil
}
entries, _ := kdb.RecentEntries(2000) entries, _ := kdb.RecentEntries(2000)
tfidf := index.BuildTFIDF(entries) tfidf := index.BuildTFIDF(entries)
clusters := tfidf.Cluster(2, limit) clusters := tfidf.Cluster(2, limit)
@@ -932,20 +820,12 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
) )
s.AddTool(snippetCandTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(snippetCandTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
described, _ := req.Params.Arguments["described"].(bool) described, _ := req.Params.Arguments["described"].(bool)
limit, err := optionalIntArg(req, "limit", 10, 1, 100)
if err != nil {
return errorResult(err.Error()), nil
}
minBytes, err := optionalIntArg(req, "min_bytes", 0, 0, 1000000)
if err != nil {
return errorResult(err.Error()), nil
}
items, err := kdb.SnippetCandidates(db.SnippetFilter{ items, err := kdb.SnippetCandidates(db.SnippetFilter{
Limit: limit, Limit: clampInt(req, "limit", 10, 1, 100),
Language: getString(req, "language", ""), Language: getString(req, "language", ""),
Project: getString(req, "project", ""), Project: getString(req, "project", ""),
Tool: getString(req, "tool", ""), Tool: getString(req, "tool", ""),
MinBytes: minBytes, MinBytes: clampInt(req, "min_bytes", 0, 0, 1000000),
Config: getString(req, "config", "hide"), Config: getString(req, "config", "hide"),
Junk: getString(req, "junk", "hide"), Junk: getString(req, "junk", "hide"),
Kind: getString(req, "kind", ""), Kind: getString(req, "kind", ""),
@@ -1086,14 +966,8 @@ func NewMCPServer(kdb *db.KnoxDB) *server.MCPServer {
mcp.WithNumber("limit", mcp.Description("Max results (default 10)")), mcp.WithNumber("limit", mcp.Description("Max results (default 10)")),
) )
s.AddTool(snippetSearchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { s.AddTool(snippetSearchTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
query, err := requiredStringArg(req, "query") query := getString(req, "query", "")
if err != nil { limit := clampInt(req, "limit", 10, 1, 50)
return errorResult(err.Error()), nil
}
limit, err := optionalIntArg(req, "limit", 10, 1, 50)
if err != nil {
return errorResult(err.Error()), nil
}
items, err := kdb.SearchSnippets(query, limit) items, err := kdb.SearchSnippets(query, limit)
if err != nil { if err != nil {
return errorResult(err.Error()), nil return errorResult(err.Error()), nil
@@ -1259,59 +1133,18 @@ func getString(req mcp.CallToolRequest, key, def string) string {
return def return def
} }
// requiredStringArg returns a non-empty string argument or a descriptive error. func clampInt(req mcp.CallToolRequest, key string, def, min, max int) int {
// Empty/missing/wrong-type values are rejected rather than silently defaulted: if v, ok := req.Params.Arguments[key].(float64); ok {
// LLM clients routinely omit or zero value params, and a silent default writes n := int(v)
// to the wrong thread or reports false success. if n < min {
func requiredStringArg(req mcp.CallToolRequest, key string) (string, error) { return min
v, _ := req.Params.Arguments[key].(string) }
v = strings.TrimSpace(v) if n > max {
if v == "" { return max
return "", fmt.Errorf("%s is required and must be a non-empty string", key) }
return n
} }
return v, nil return def
}
// requiredIntArg returns an integer argument validated against [min, max].
func requiredIntArg(req mcp.CallToolRequest, key string, min, max int64) (int64, error) {
v, ok := req.Params.Arguments[key].(float64)
if !ok || v != math.Trunc(v) {
return 0, fmt.Errorf("%s is required and must be an integer", key)
}
n := int64(v)
if n < min || n > max {
return 0, fmt.Errorf("%s must be in [%d..%d], got %d", key, min, max, n)
}
return n, nil
}
// optionalIntArg validates a present numeric argument, defaulting when absent.
func optionalIntArg(req mcp.CallToolRequest, key string, def, min, max int) (int, error) {
v, ok := req.Params.Arguments[key].(float64)
if !ok {
return def, nil
}
if v != math.Trunc(v) {
return 0, fmt.Errorf("%s must be an integer", key)
}
n := int(v)
if n < min || n > max {
return 0, fmt.Errorf("%s must be in [%d..%d], got %d", key, min, max, n)
}
return n, nil
}
// threadExists is a guard for write tools: link/relate/set-golden must not
// silently accept ids with no matching thread.
func threadExists(kdb *db.KnoxDB, id int64) error {
t, err := kdb.GetThread(id)
if err != nil {
return err
}
if t == nil {
return fmt.Errorf("thread #%d not found", id)
}
return nil
} }
// formatSkillsHealth renders the skills-repo health report. // formatSkillsHealth renders the skills-repo health report.
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"fmt" "fmt"
"log" "log"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest" "github.com/david/knox/internal/ingest"
"github.com/spf13/cobra"
) )
func NewObsidianCmd(kdb *db.KnoxDB) *cobra.Command { func NewObsidianCmd(kdb *db.KnoxDB) *cobra.Command {
+2 -2
View File
@@ -3,9 +3,9 @@ package cmd
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch" "github.com/david/knox/internal/watch"
"github.com/spf13/cobra"
) )
// NewReconcileCmd rebuilds all derived state (entries cache, threads) from the // NewReconcileCmd rebuilds all derived state (entries cache, threads) from the
@@ -51,4 +51,4 @@ func dryRunReconcile(kdb *db.KnoxDB) error {
fmt.Printf("drift: %d entries current, %d from log (%+d), %d threads would be created, %d obs would be linked\n", fmt.Printf("drift: %d entries current, %d from log (%+d), %d threads would be created, %d obs would be linked\n",
current, logCount, logCount-current, created, linked) current, logCount, logCount-current, created, linked)
return nil return nil
} }
+7 -20
View File
@@ -6,14 +6,14 @@ import (
"os" "os"
"strings" "strings"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/index" "github.com/david/knox/internal/index"
"github.com/spf13/cobra"
) )
func paginate(entries []db.Entry, page, limit int) []db.Entry { func paginate(entries []db.Entry, page, limit int) []db.Entry {
start := (page - 1) * limit start := (page - 1) * limit
if start < 0 || start >= len(entries) { if start >= len(entries) {
return nil return nil
} }
end := start + limit end := start + limit
@@ -74,22 +74,16 @@ func NewQueryCmd(kdb *db.KnoxDB) *cobra.Command {
if query == "" { if query == "" {
return fmt.Errorf("search query required (positional arg or stdin pipe)") return fmt.Errorf("search query required (positional arg or stdin pipe)")
} }
if page < 1 || limit < 1 { results, err := kdb.Search(query, limit)
return fmt.Errorf("page and limit must be >= 1 (got page=%d limit=%d)", page, limit)
}
// Fetch enough rows to cover the requested page: Search caps at its
// limit argument, so slicing a limit-sized result set could never
// reach page 2+.
all, err := kdb.Search(query, page*limit)
if err != nil { if err != nil {
return err return err
} }
results := paginate(all, page, limit) results = paginate(results, page, limit)
if len(results) == 0 { if len(results) == 0 {
fmt.Println("No results found.") fmt.Println("No results found.")
return nil return nil
} }
fmt.Printf("Found %d results for %q — showing %d (page %d, %d per page):\n\n", len(all), query, len(results), page, limit) fmt.Printf("Found %d results for %q (page %d, %d per page):\n\n", len(results), query, page, limit)
for _, r := range results { for _, r := range results {
fmt.Printf(" %-8s %-30s [%s] %s\n", shortFP(r.Fingerprint), truncateStr(r.Title, 30), r.Project, r.SourceID) fmt.Printf(" %-8s %-30s [%s] %s\n", shortFP(r.Fingerprint), truncateStr(r.Title, 30), r.Project, r.SourceID)
if r.Summary != "" { if r.Summary != "" {
@@ -111,20 +105,13 @@ func NewRecentCmd(kdb *db.KnoxDB) *cobra.Command {
Use: "recent", Use: "recent",
Short: "Show recent knowledge entries", Short: "Show recent knowledge entries",
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
if page < 1 || limit < 1 { all, err := kdb.RecentEntries(limit * 10)
return fmt.Errorf("page and limit must be >= 1 (got page=%d limit=%d)", page, limit)
}
all, err := kdb.RecentEntries(page * limit)
if err != nil { if err != nil {
return err return err
} }
entries := paginate(all, page, limit) entries := paginate(all, page, limit)
if len(entries) == 0 { if len(entries) == 0 {
if page > 1 { fmt.Println("No entries yet. Run `knox watch` to start ingesting.")
fmt.Printf("No more entries on page %d (page %d of %d).\n", page, page, (len(all)+limit-1)/limit)
} else {
fmt.Println("No entries yet. Run `knox watch` to start ingesting.")
}
return nil return nil
} }
fmt.Printf("Recent %d entries (page %d, %d per page):\n\n", len(entries), page, limit) fmt.Printf("Recent %d entries (page %d, %d per page):\n\n", len(entries), page, limit)
+1 -1
View File
@@ -5,9 +5,9 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/index" "github.com/david/knox/internal/index"
"github.com/spf13/cobra"
) )
func NewTopicsCmd(kdb *db.KnoxDB) *cobra.Command { func NewTopicsCmd(kdb *db.KnoxDB) *cobra.Command {
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"io" "io"
"log" "log"
"github.com/spf13/cobra"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch" "github.com/david/knox/internal/watch"
"github.com/spf13/cobra"
) )
func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command { func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command {
+1 -20
View File
@@ -27,12 +27,6 @@ type KnoxDB struct {
db *sql.DB db *sql.DB
nodeID string nodeID string
clock *hlc.Clock 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 { type Observation struct {
@@ -160,13 +154,10 @@ func Open(path string) (*KnoxDB, error) {
return nil, fmt.Errorf("create db dir: %w", err) 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") db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
if err != nil { if err != nil {
return nil, fmt.Errorf("open db: %w", err) 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 { if _, err := db.Exec(Schema); err != nil {
return nil, fmt.Errorf("init schema: %w", err) return nil, fmt.Errorf("init schema: %w", err)
@@ -213,13 +204,6 @@ func Open(path string) (*KnoxDB, error) {
if _, err := db.Exec("UPDATE observations SET hcl=id WHERE hcl IS NULL"); err != nil { if _, err := db.Exec("UPDATE observations SET hcl=id WHERE hcl IS NULL"); err != nil {
return nil, fmt.Errorf("backfill hcl: %w", err) 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 // 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. // node's HCL is strictly monotonic so this never throws a false conflict.
@@ -316,9 +300,6 @@ func (k *KnoxDB) ObservationEntryEstimate() int {
// Idempotent: if the latest observation for this fingerprint has an identical // Idempotent: if the latest observation for this fingerprint has an identical
// content signature, nothing is recorded — re-ingesting unchanged content is a no-op. // 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) { func (k *KnoxDB) RecordObservation(o ObservationRecord) (obsID int64, isNew bool, err error) {
k.writeMu.Lock()
defer k.writeMu.Unlock()
tx, err := k.db.Begin() tx, err := k.db.Begin()
if err != nil { if err != nil {
return 0, false, fmt.Errorf("begin tx: %w", err) return 0, false, fmt.Errorf("begin tx: %w", err)
-150
View File
@@ -3,7 +3,6 @@ package db
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"sync"
"testing" "testing"
"time" "time"
) )
@@ -499,152 +498,3 @@ func TestListThreadsAll(t *testing.T) {
} }
} }
} }
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)
}
}
+1 -15
View File
@@ -3,7 +3,6 @@ package db
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"log"
) )
// GossipObservation is the serializable wire form of an observation exchanged // GossipObservation is the serializable wire form of an observation exchanged
@@ -43,19 +42,6 @@ func (k *KnoxDB) PushObservations(rows []GossipObservation) (int, error) {
inserted := 0 inserted := 0
for _, o := range rows { for _, o := range rows {
// Reject malformed or forged rows. Nodes only ever push their own
// observations, so a row claiming this node's id cannot be legitimate:
// accepting it would let a peer poison our knowledge vector (a forged
// max-HCL makes peers believe they have our whole history and stop
// pulling). Empty node ids and negative HCLs are likewise never produced
// by a real node.
if o.NodeID == "" || o.HCL < 0 {
continue
}
if o.NodeID == k.nodeID {
log.Printf("[gossip] dropped pushed row claiming local node_id (spoof?)")
continue
}
res, err := tx.Exec( res, err := tx.Exec(
`INSERT OR IGNORE INTO observations `INSERT OR IGNORE INTO observations
(fingerprint, source_id, source_path, project, content_type, title, summary, (fingerprint, source_id, source_path, project, content_type, title, summary,
@@ -304,4 +290,4 @@ func (k *KnoxDB) ThreadStatusByCluster() (map[string]string, error) {
out[key] = status out[key] = status
} }
return out, rows.Err() return out, rows.Err()
} }
+2 -2
View File
@@ -11,7 +11,7 @@ type MetricsSnapshot struct {
PendingReflections int PendingReflections int
ThreadsByStatus map[string]int ThreadsByStatus map[string]int
Peers int Peers int
ByOriginNode map[string]int // node_id → observation count ByOriginNode map[string]int // node_id → observation count
KnowledgeVector map[string]int64 // node_id → max hcl KnowledgeVector map[string]int64 // node_id → max hcl
EarliestObservation string EarliestObservation string
} }
@@ -105,4 +105,4 @@ func (k *KnoxDB) MetricsSnapshot() (*MetricsSnapshot, error) {
return nil, err return nil, err
} }
return s, nil return s, nil
} }
+1 -18
View File
@@ -27,23 +27,6 @@ type Clock struct {
func New() *Clock { return &Clock{} } func New() *Clock { return &Clock{} }
// SeekTo adopts the given packed HLC value when it is ahead of the clock's current
// position, so the next Now is still strictly increasing. Used to resume a node's
// clock from its persisted MAX(hcl) at startup — without it, a restart with a
// regressed wall clock would reissue already-used values and break the
// monotonicity the (node_id, hcl) locator uniqueness and gossip cursors rely on.
func (c *Clock) SeekTo(v int64) {
c.mu.Lock()
defer c.mu.Unlock()
wall := v >> wallShift
seq := v & seqMask
if wall > c.wallMS || (wall == c.wallMS && seq > c.seq) {
c.wallMS = wall
c.seq = seq
}
}
// Now returns the next monotonic HLC value and the wall-clock time embedded in // Now returns the next monotonic HLC value and the wall-clock time embedded in
// it. The returned time is the HLC's wall component — never ahead of the local // it. The returned time is the HLC's wall component — never ahead of the local
// clock beyond the current call and never rewinding across calls. // clock beyond the current call and never rewinding across calls.
@@ -74,4 +57,4 @@ func (c *Clock) Now() (int64, time.Time) {
// WallTime extracts the wall-clock component embedded in a packed HLC value. // WallTime extracts the wall-clock component embedded in a packed HLC value.
func WallTime(v int64) time.Time { func WallTime(v int64) time.Time {
return time.UnixMilli(v >> wallShift).UTC() return time.UnixMilli(v >> wallShift).UTC()
} }
-68
View File
@@ -1,68 +0,0 @@
package hlc
import "testing"
// TestSeekToFutureValueKeepsMonotonic: after resuming from a persisted value
// ahead of the wall clock (clock regression), every subsequent Now must still
// be strictly greater than the resumed position.
func TestSeekToFutureValueKeepsMonotonic(t *testing.T) {
c := New()
resumed := int64(1) << 62 // packed value far ahead of any real wall clock
c.SeekTo(resumed)
prev, _ := c.Now()
if prev <= resumed {
t.Fatalf("first Now after SeekTo = %d, want > resumed %d", prev, resumed)
}
for i := 0; i < 100; i++ {
next, _ := c.Now()
if next <= prev {
t.Fatalf("HLC regressed: %d then %d", prev, next)
}
prev = next
}
}
// TestSeekToLowerValueIgnored: resuming from a value behind the current clock
// (or a fresh 0-padded DB) must not rewind it.
func TestSeekToLowerValueIgnored(t *testing.T) {
c := New()
first, _ := c.Now()
c.SeekTo(0)
second, _ := c.Now()
if second <= first {
t.Fatalf("SeekTo(0) rewound the clock: %d then %d", first, second)
}
// Seek to exactly the last emitted value: the next value must exceed it.
c.SeekTo(second)
third, _ := c.Now()
if third <= second {
t.Fatalf("SeekTo(last) did not preserve monotonicity: %d then %d", second, third)
}
}
// TestSeekToAcrossRestart mirrors Open's reopen path: a fresh clock resumed
// from the persisted max keeps issuing strictly increasing values.
func TestSeekToAcrossRestart(t *testing.T) {
c1 := New()
var last int64
for i := 0; i < 50; i++ {
last, _ = c1.Now()
}
c2 := New() // fresh process clock
c2.SeekTo(last)
prev, _ := c2.Now()
if prev <= last {
t.Fatalf("reopened clock reissued a value: %d <= %d", prev, last)
}
for i := 0; i < 50; i++ {
next, _ := c2.Now()
if next <= prev {
t.Fatalf("reopened clock regressed: %d then %d", prev, next)
}
prev = next
}
}
+16 -16
View File
@@ -19,23 +19,23 @@ import (
// scrape-time gauges derived from the database (refreshed on each scrape). // scrape-time gauges derived from the database (refreshed on each scrape).
type Metrics struct { type Metrics struct {
// Gossip counters (live). // Gossip counters (live).
pullsTotal prometheus.Counter pullsTotal prometheus.Counter
pushesTotal prometheus.Counter pushesTotal prometheus.Counter
obsPulledTotal prometheus.Counter obsPulledTotal prometheus.Counter
obsPushedTotal prometheus.Counter obsPushedTotal prometheus.Counter
errorsTotal prometheus.Counter errorsTotal prometheus.Counter
// Snapshot gauges (updated per scrape). // Snapshot gauges (updated per scrape).
observationsGauge *prometheus.GaugeVec observationsGauge *prometheus.GaugeVec
entriesGauge prometheus.Gauge entriesGauge prometheus.Gauge
projectsGauge prometheus.Gauge projectsGauge prometheus.Gauge
sessionsGauge prometheus.Gauge sessionsGauge prometheus.Gauge
pendingReflections prometheus.Gauge pendingReflections prometheus.Gauge
peersGauge prometheus.Gauge peersGauge prometheus.Gauge
threadsByStatus *prometheus.GaugeVec threadsByStatus *prometheus.GaugeVec
byOriginNode *prometheus.GaugeVec byOriginNode *prometheus.GaugeVec
knowledgeVector *prometheus.GaugeVec knowledgeVector *prometheus.GaugeVec
observationsLast24h prometheus.Gauge observationsLast24h prometheus.Gauge
registry *prometheus.Registry registry *prometheus.Registry
kdb *db.KnoxDB kdb *db.KnoxDB
@@ -161,4 +161,4 @@ func (m *Metrics) Handler() http.Handler {
} }
h.ServeHTTP(w, r) h.ServeHTTP(w, r)
}) })
} }
+1 -1
View File
@@ -111,4 +111,4 @@ func TestMetricsCounters(t *testing.T) {
if got := testutil.ToFloat64(m.errorsTotal); got != 1 { if got := testutil.ToFloat64(m.errorsTotal); got != 1 {
t.Errorf("errorsTotal = %v, want 1", got) t.Errorf("errorsTotal = %v, want 1", got)
} }
} }
+16 -29
View File
@@ -33,11 +33,11 @@ type Node struct {
// pingResponse is the anti-entropy summary returned by /v1/ping. // pingResponse is the anti-entropy summary returned by /v1/ping.
type pingResponse struct { type pingResponse struct {
NodeID string `json:"node_id"` NodeID string `json:"node_id"`
Name string `json:"name"` Name string `json:"name"`
Vector map[string]int64 `json:"vector"` // node_id → max hcl Vector map[string]int64 `json:"vector"` // node_id → max hcl
Peers []db.PeerInfo `json:"peers"` // swarm membership this node knows Peers []db.PeerInfo `json:"peers"` // swarm membership this node knows
MaxHCL *int64 `json:"max_hcl,omitempty"` MaxHCL *int64 `json:"max_hcl,omitempty"`
} }
func (n *Node) Handler() http.Handler { func (n *Node) Handler() http.Handler {
@@ -98,16 +98,10 @@ func nextCursor(rows []db.GossipObservation) int64 {
return rows[len(rows)-1].HCL return rows[len(rows)-1].HCL
} }
// maxBatchRows bounds the number of observations a peer may push in one POST.
// Pull already pages at 500 rows, so any larger batch is at best redundant and
// at worst a flood; capping keeps memory and insert work bounded.
const maxBatchRows = 1000
func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) { func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4<<20) // 4 MiB
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, "batch too large or unreadable", http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
var rows []db.GossipObservation var rows []db.GossipObservation
@@ -115,10 +109,6 @@ func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest) http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
return return
} }
if len(rows) > maxBatchRows {
http.Error(w, fmt.Sprintf("batch too large: %d rows (max %d)", len(rows), maxBatchRows), http.StatusBadRequest)
return
}
inserted, err := n.Kdb.PushObservations(rows) inserted, err := n.Kdb.PushObservations(rows)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
@@ -133,11 +123,11 @@ func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
// DiffSummary is the divergence snapshot served at /v1/diff: everything this // DiffSummary is the divergence snapshot served at /v1/diff: everything this
// node observes, plus the status of auto-threaded threads (for tombstones). // node observes, plus the status of auto-threaded threads (for tombstones).
type DiffSummary struct { type DiffSummary struct {
NodeID string `json:"node_id"` NodeID string `json:"node_id"`
Name string `json:"name"` Name string `json:"name"`
Fingerprints []string `json:"fingerprints"` Fingerprints []string `json:"fingerprints"`
ThreadStatus map[string]string `json:"thread_status"` ThreadStatus map[string]string `json:"thread_status"`
ObsCount int `json:"obs_count"` ObsCount int `json:"obs_count"`
} }
func (n *Node) handleDiff(w http.ResponseWriter, r *http.Request) { func (n *Node) handleDiff(w http.ResponseWriter, r *http.Request) {
@@ -173,9 +163,9 @@ func writeJSON(w http.ResponseWriter, v any) {
// Client is the pull/push half used by the exchange loop. // Client is the pull/push half used by the exchange loop.
type Client struct { type Client struct {
NodeID string NodeID string
Addr string Addr string
Timeout time.Duration Timeout time.Duration
} }
func (c *Client) Ping() (*pingResponse, error) { func (c *Client) Ping() (*pingResponse, error) {
@@ -283,7 +273,7 @@ func (c *Client) Diff() (*DiffSummary, error) {
// node pulls/pushes directly with every other node it learns about. // node pulls/pushes directly with every other node it learns about.
// //
// m, when non-nil, receives gossip event counters (nil for one-shot CLI runs). // m, when non-nil, receives gossip event counters (nil for one-shot CLI runs).
func Run(kdb *db.KnoxDB, m *metrics.Metrics, static []string) int { func Run(kdb *db.KnoxDB, m *metrics.Metrics, static []string) {
myID := kdb.NodeID() myID := kdb.NodeID()
// Seed the work queue with static config plus persisted discoveries. // Seed the work queue with static config plus persisted discoveries.
@@ -294,7 +284,6 @@ func Run(kdb *db.KnoxDB, m *metrics.Metrics, static []string) int {
seen := make(map[string]bool) // addr → handled (also suppresses self) seen := make(map[string]bool) // addr → handled (also suppresses self)
queue := 0 queue := 0
pulledTotal := 0
for queue < len(work) { for queue < len(work) {
addr := strings.TrimSpace(work[queue]) addr := strings.TrimSpace(work[queue])
queue++ queue++
@@ -349,7 +338,6 @@ func Run(kdb *db.KnoxDB, m *metrics.Metrics, static []string) int {
pulled += n pulled += n
} }
} }
pulledTotal += pulled
if m != nil { if m != nil {
m.IncrementPull(pulled) m.IncrementPull(pulled)
} }
@@ -368,7 +356,6 @@ func Run(kdb *db.KnoxDB, m *metrics.Metrics, static []string) int {
log.Printf("[gossip] synced with %s (%s): in sync (pushed %d)", p.NodeID, addr, pushed) log.Printf("[gossip] synced with %s (%s): in sync (pushed %d)", p.NodeID, addr, pushed)
} }
} }
return pulledTotal
} }
func kdbVectorGet(kdb *db.KnoxDB, nodeID string) int64 { func kdbVectorGet(kdb *db.KnoxDB, nodeID string) int64 {
@@ -423,4 +410,4 @@ func PeerAddrs() []string {
} }
} }
return out return out
} }
+5 -109
View File
@@ -1,12 +1,8 @@
package watch package watch
import ( import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest" "net/http/httptest"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
@@ -232,116 +228,16 @@ func TestGossipIdempotent(t *testing.T) {
defer sb.Close() defer sb.Close()
Run(b, nil, []string{sa.URL}) Run(b, nil, []string{sa.URL})
entryBefore, err := b.EntryCount() before, err := b.EntryCount()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
stats, err := b.Stats()
if err != nil {
t.Fatal(err)
}
obsBefore, _ := stats["total_observations"].(int)
Run(b, nil, []string{sa.URL}) Run(b, nil, []string{sa.URL})
after, err := b.EntryCount()
entryAfter, err := b.EntryCount()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if entryBefore != entryAfter { if before != after {
t.Errorf("second sweep changed entry count: %d -> %d", entryBefore, entryAfter) t.Errorf("second sweep changed entry count: %d -> %d", before, after)
} }
stats, err = b.Stats() }
if err != nil {
t.Fatal(err)
}
obsAfter, _ := stats["total_observations"].(int)
if obsBefore != obsAfter {
t.Errorf("second sweep duplicated observations: %d -> %d", obsBefore, obsAfter)
}
}
// TestHandleBatchRejectsOversizedBatch: more than maxBatchRows in one POST
// must be refused up front, before any insert work.
func TestHandleBatchRejectsOversizedBatch(t *testing.T) {
b := tmpKnoxDB(t)
node := &Node{Kdb: b, Name: "B"}
sv := httptest.NewServer(node.Handler())
defer sv.Close()
rows := make([]db.GossipObservation, maxBatchRows+1)
for i := range rows {
rows[i] = db.GossipObservation{
NodeID: "0123456789abcdef0123456789abcdef", HCL: int64(i + 1),
Fingerprint: "fp:oversized", SourceID: "test", Title: "t", Summary: "s",
CollectedAt: "2026-08-29T00:00:00Z",
}
}
body, _ := json.Marshal(rows)
resp, err := http.Post(sv.URL+"/v1/obs/batch", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("oversized batch: want 400, got %d", resp.StatusCode)
}
}
// TestHandleBatchRejectsHugeBody: an oversized body (beyond the 4 MiB cap)
// must be refused even when the row count is small.
func TestHandleBatchRejectsHugeBody(t *testing.T) {
b := tmpKnoxDB(t)
node := &Node{Kdb: b, Name: "B"}
sv := httptest.NewServer(node.Handler())
defer sv.Close()
rows := []db.GossipObservation{{
NodeID: "0123456789abcdef0123456789abcdef", HCL: 1,
Fingerprint: "fp:huge", SourceID: "test", Title: "t",
Summary: strings.Repeat("x", 5<<20), // 5 MiB summary
CollectedAt: "2026-08-29T00:00:00Z",
}}
body, _ := json.Marshal(rows)
resp, err := http.Post(sv.URL+"/v1/obs/batch", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("huge body: want 400, got %d", resp.StatusCode)
}
}
// TestHandleBatchSkipsSelfRows: rows claiming the receiver's own node_id are
// dropped at the HTTP layer too (the poisoning vector), reported as conflicts.
func TestHandleBatchSkipsSelfRows(t *testing.T) {
b := tmpKnoxDB(t)
node := &Node{Kdb: b, Name: "B"}
sv := httptest.NewServer(node.Handler())
defer sv.Close()
rows := []db.GossipObservation{
{NodeID: b.NodeID(), HCL: 1, Fingerprint: "fp:self1", SourceID: "test", Title: "t", Summary: "s", CollectedAt: "2026-08-29T00:00:00Z"},
{NodeID: b.NodeID(), HCL: 2, Fingerprint: "fp:self2", SourceID: "test", Title: "t", Summary: "s", CollectedAt: "2026-08-29T00:00:00Z"},
}
body, _ := json.Marshal(rows)
resp, err := http.Post(sv.URL+"/v1/obs/batch", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("want 200, got %d", resp.StatusCode)
}
var out struct {
Accepted int `json:"accepted"`
Conflict int `json:"conflict"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
t.Fatalf("decode: %v", err)
}
if out.Accepted != 0 || out.Conflict != 2 {
t.Errorf("self rows: want accepted=0 conflict=2, got accepted=%d conflict=%d", out.Accepted, out.Conflict)
}
}
+1 -1
View File
@@ -20,4 +20,4 @@ func Reconcile(kdb *db.KnoxDB) (int, int, error) {
return 0, 0, fmt.Errorf("auto-thread: %w", err) return 0, 0, fmt.Errorf("auto-thread: %w", err)
} }
return created, linked, nil return created, linked, nil
} }
+83 -151
View File
@@ -1,14 +1,11 @@
package watch package watch
import ( import (
"io/fs"
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"sync/atomic"
"time" "time"
"github.com/david/knox/internal/db" "github.com/david/knox/internal/db"
@@ -47,44 +44,6 @@ type Watcher struct {
lastIngest map[string]fileState lastIngest map[string]fileState
} }
// fileDebouncer schedules one ingest per path a settle-window after the last
// relevant event (trailing edge): writers that emit bursts (multi-write appends,
// atomic save = temp-write + rename) settle before anything is read, so a
// partial file is never recorded as final state. Timers are removed once they
// fire, keeping the map bounded by recently-active paths.
type fileDebouncer struct {
mu sync.Mutex
timers map[string]*time.Timer
}
func newFileDebouncer() *fileDebouncer {
return &fileDebouncer{timers: make(map[string]*time.Timer)}
}
func (d *fileDebouncer) schedule(path string, delay time.Duration, fn func(string)) {
d.mu.Lock()
defer d.mu.Unlock()
if t, ok := d.timers[path]; ok {
t.Stop()
}
d.timers[path] = time.AfterFunc(delay, func() {
d.mu.Lock()
delete(d.timers, path)
d.mu.Unlock()
fn(path)
})
}
// cancel drops any pending ingest for path (e.g. the file was deleted).
func (d *fileDebouncer) cancel(path string) {
d.mu.Lock()
defer d.mu.Unlock()
if t, ok := d.timers[path]; ok {
t.Stop()
delete(d.timers, path)
}
}
func New(kdb *db.KnoxDB, dirs []string) *Watcher { func New(kdb *db.KnoxDB, dirs []string) *Watcher {
// Detect Obsidian vault // Detect Obsidian vault
vault, _ := ingest.DetectObsidianVault() vault, _ := ingest.DetectObsidianVault()
@@ -158,7 +117,7 @@ func (w *Watcher) Start() error {
log.Printf("[knox] obsidian vault: %s", w.vault) log.Printf("[knox] obsidian vault: %s", w.vault)
} }
debounce := newFileDebouncer() debounceMap := make(map[string]time.Time)
browserTicker := time.NewTicker(browserInterval) browserTicker := time.NewTicker(browserInterval)
giteaTicker := time.NewTicker(10 * time.Minute) giteaTicker := time.NewTicker(10 * time.Minute)
gitTicker := time.NewTicker(10 * time.Minute) gitTicker := time.NewTicker(10 * time.Minute)
@@ -168,8 +127,15 @@ func (w *Watcher) Start() error {
threadTicker := time.NewTicker(10 * time.Minute) threadTicker := time.NewTicker(10 * time.Minute)
snippetTicker := time.NewTicker(snippetInterval) snippetTicker := time.NewTicker(snippetInterval)
gossipTicker := time.NewTicker(gossipInterval) gossipTicker := time.NewTicker(gossipInterval)
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool browserRunning := false
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool giteaRunning := false
gitRunning := false
opencodeRunning := false
karakeepRunning := false
healthRunning := false
threadRunning := false
snippetRunning := false
gossipRunning := false
for { for {
select { select {
@@ -177,114 +143,103 @@ func (w *Watcher) Start() error {
if !ok { if !ok {
return nil return nil
} }
if !w.isRelevantEvent(event) {
// fsnotify is non-recursive: files appearing inside newly created
// subdirectories would otherwise be invisible to the daemon.
isDir := false
if event.Has(fsnotify.Create) {
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
isDir = true
if err := watcher.Add(event.Name); err != nil {
log.Printf("[knox] cannot watch new dir %s: %v", event.Name, err)
} else {
log.Printf("[knox] watching new dir %s", event.Name)
}
}
}
if event.Has(fsnotify.Remove) {
// Drop any pending ingest for a deleted file. (No tombstone is
// written yet — the entry lingers until reconcile/prune.)
debounce.cancel(event.Name)
continue continue
} }
if isDir || !w.isRelevantEvent(event) {
now := time.Now()
dd := w.debounce
if strings.HasSuffix(event.Name, ".log") {
dd = logDebounce
}
if last, ok := debounceMap[event.Name]; ok && now.Sub(last) < dd {
continue continue
} }
debounceMap[event.Name] = now
trigger := eventOpName(event.Op) trigger := eventOpName(event.Op)
log.Printf("[knox] %s %s", trigger, filepath.Base(event.Name)) log.Printf("[knox] %s %s", trigger, filepath.Base(event.Name))
name := event.Name w.ingestFile(event.Name, trigger)
// An actively-appended log writes every couple of seconds; settle
// longer than the default so it is not fully re-parsed each time.
delay := w.debounce
if strings.HasSuffix(name, ".log") {
delay = logDebounce
}
debounce.schedule(name, delay, func(path string) {
w.ingestFile(path, trigger)
})
case <-browserTicker.C: case <-browserTicker.C:
if !browserRunning.CompareAndSwap(false, true) { if browserRunning {
continue continue
} }
browserRunning = true
go func() { go func() {
defer browserRunning.Store(false) defer func() { browserRunning = false }()
w.ingestBrowserHistory() w.ingestBrowserHistory()
}() }()
case <-giteaTicker.C: case <-giteaTicker.C:
if !giteaRunning.CompareAndSwap(false, true) { if giteaRunning {
continue continue
} }
giteaRunning = true
go func() { go func() {
defer giteaRunning.Store(false) defer func() { giteaRunning = false }()
w.ingestGitea() w.ingestGitea()
}() }()
case <-gitTicker.C: case <-gitTicker.C:
if !gitRunning.CompareAndSwap(false, true) { if gitRunning {
continue continue
} }
gitRunning = true
go func() { go func() {
defer gitRunning.Store(false) defer func() { gitRunning = false }()
w.ingestGit() w.ingestGit()
}() }()
case <-opencodeTicker.C: case <-opencodeTicker.C:
if !opencodeRunning.CompareAndSwap(false, true) { if opencodeRunning {
continue continue
} }
opencodeRunning = true
go func() { go func() {
defer opencodeRunning.Store(false) defer func() { opencodeRunning = false }()
w.ingestOpenCodeDB() w.ingestOpenCodeDB()
}() }()
case <-karakeepTicker.C: case <-karakeepTicker.C:
if !karakeepRunning.CompareAndSwap(false, true) { if karakeepRunning {
continue continue
} }
karakeepRunning = true
go func() { go func() {
defer karakeepRunning.Store(false) defer func() { karakeepRunning = false }()
w.ingestKarakeep() w.ingestKarakeep()
}() }()
case <-healthTicker.C: case <-healthTicker.C:
if !healthRunning.CompareAndSwap(false, true) { if healthRunning {
continue continue
} }
healthRunning = true
go func() { go func() {
defer healthRunning.Store(false) defer func() { healthRunning = false }()
w.checkSkillsHealth() w.checkSkillsHealth()
}() }()
case <-threadTicker.C: case <-threadTicker.C:
if !threadRunning.CompareAndSwap(false, true) { if threadRunning {
continue continue
} }
threadRunning = true
go func() { go func() {
defer threadRunning.Store(false) defer func() { threadRunning = false }()
w.autoThread() w.autoThread()
}() }()
case <-snippetTicker.C: case <-snippetTicker.C:
if !snippetRunning.CompareAndSwap(false, true) { if snippetRunning {
continue continue
} }
snippetRunning = true
go func() { go func() {
defer snippetRunning.Store(false) defer func() { snippetRunning = false }()
w.extractSnippets() w.extractSnippets()
}() }()
case <-gossipTicker.C: case <-gossipTicker.C:
if !gossipRunning.CompareAndSwap(false, true) { if gossipRunning {
continue continue
} }
gossipRunning = true
go func() { go func() {
defer gossipRunning.Store(false) defer func() { gossipRunning = false }()
w.syncGossip() w.syncGossip()
}() }()
@@ -299,38 +254,44 @@ func (w *Watcher) Start() error {
func (w *Watcher) seed(watcher *fsnotify.Watcher) { func (w *Watcher) seed(watcher *fsnotify.Watcher) {
for _, dir := range w.dirs { for _, dir := range w.dirs {
if err := w.watchTree(watcher, dir); err != nil { abs, _ := filepath.Abs(dir)
log.Printf("[knox] cannot watch %s: %v", dir, err) if err := watcher.Add(abs); err != nil {
log.Printf("[knox] cannot watch %s: %v", abs, err)
continue
} }
log.Printf("[knox] watching %s", abs)
} }
// Watch Obsidian vault (every subdirectory, non-recursively mirrored) // Watch Obsidian vault
if w.vault != "" { if w.vault != "" {
if err := w.watchTree(watcher, w.vault); err != nil { if err := watcher.Add(w.vault); err != nil {
log.Printf("[knox] cannot watch obsidian vault %s: %v", w.vault, err) log.Printf("[knox] cannot watch obsidian vault %s: %v", w.vault, err)
} else {
log.Printf("[knox] watching %s (obsidian)", w.vault)
} }
} }
// Seed existing files anywhere under the watched dirs. fsnotify watches the // Seed existing files
// whole tree, so live events cover any depth; this walk covers startup so for _, ing := range w.fileIngesters {
// pre-existing nested files (e.g. skills at two+ levels) are indexed too. for _, dir := range w.dirs {
for _, dir := range w.dirs { patterns := []string{
_ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { filepath.Join(dir, "*"),
if err != nil || d.IsDir() { filepath.Join(dir, "*", "SKILL.md"),
return nil // skip unreadable entries; dirs are handled by the watch
} }
for _, ing := range w.fileIngesters { for _, pattern := range patterns {
if MatchesIngester(path, ing.SourceID()) { entries, _ := filepath.Glob(pattern)
for _, path := range entries {
if !MatchesIngester(path, ing.SourceID()) {
continue
}
w.ingestFileWith(path, ing, "seed") w.ingestFileWith(path, ing, "seed")
return nil
} }
} }
return nil }
})
} }
// Seed Obsidian notes via the full walk: skips dot-dirs (.trash, .obsidian) // Seed Obsidian notes via the full walk: skips dot-dirs (.trash, .obsidian)
// and covers all depths. // and covers all depths — glob patterns would match dot-dirs and miss depth >2.
if w.vault != "" { if w.vault != "" {
if notes, err := ingest.NewObsidianIngester(w.vault).IngestAll(); err == nil { if notes, err := ingest.NewObsidianIngester(w.vault).IngestAll(); err == nil {
for _, r := range notes { for _, r := range notes {
@@ -340,39 +301,6 @@ func (w *Watcher) seed(watcher *fsnotify.Watcher) {
} }
} }
// watchTree adds a directory and every non-hidden subdirectory to the watcher,
// mirroring fsnotify's non-recursive API with an explicit walk. Hidden
// directories (.git, .obsidian, .trash) are skipped so their churn doesn't burn
// inotify watches.
func (w *Watcher) watchTree(watcher *fsnotify.Watcher, root string) error {
rootAbs, err := filepath.Abs(root)
if err != nil {
return err
}
if err := watcher.Add(rootAbs); err != nil {
return err
}
log.Printf("[knox] watching %s", rootAbs)
return filepath.WalkDir(rootAbs, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if !d.IsDir() {
return nil
}
if path != rootAbs && strings.HasPrefix(d.Name(), ".") {
return filepath.SkipDir
}
if path == rootAbs {
return nil
}
if err := watcher.Add(path); err != nil {
log.Printf("[knox] cannot watch %s: %v", path, err)
}
return nil
})
}
func (w *Watcher) ingestFile(path, trigger string) { func (w *Watcher) ingestFile(path, trigger string) {
for _, ing := range w.fileIngesters { for _, ing := range w.fileIngesters {
if MatchesIngester(path, ing.SourceID()) { if MatchesIngester(path, ing.SourceID()) {
@@ -783,23 +711,29 @@ func (w *Watcher) syncGossip() {
return return
} }
pulled := Run(w.knoxDB, w.metrics, peers) before := 0
if n, err := w.knoxDB.EntryCount(); err == nil {
before = n
}
// A pull only appends to the observation log; the entries cache and Run(w.knoxDB, w.metrics, peers)
// auto-threads are derived state that reconcile rebuilds. Comparing entry
// counts can never trigger this (pushes/pulls never touch entries directly), // If new observations arrived, reconcile to pick up entries/threads they
// so reconcile fires on the sweep's newly-inserted observation count. // imply (deterministic log → derived rebuild).
if pulled > 0 { if after, err := w.knoxDB.EntryCount(); err == nil && after > before {
created, linked, err := Reconcile(w.knoxDB) created, linked, err := Reconcile(w.knoxDB)
if err != nil { if err != nil {
log.Printf("[knox] gossip reconcile: %v", err) log.Printf("[knox] gossip reconcile: %v", err)
return return
} }
log.Printf("[knox] gossip reconcile done: %d created, %d linked after pulling %d obs", created, linked, pulled) log.Printf("[knox] gossip reconcile done: %d created, %d linked", created, linked)
} }
} }
func (w *Watcher) isRelevantEvent(event fsnotify.Event) bool { func (w *Watcher) isRelevantEvent(event fsnotify.Event) bool {
if event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) {
return false
}
name := filepath.Base(event.Name) name := filepath.Base(event.Name)
// Opencode session diffs and logs // Opencode session diffs and logs
if strings.HasPrefix(name, "ses_") || strings.HasSuffix(name, ".log") { if strings.HasPrefix(name, "ses_") || strings.HasSuffix(name, ".log") {
@@ -833,8 +767,6 @@ func eventOpName(op fsnotify.Op) string {
return "inotify:WRITE" return "inotify:WRITE"
case op.Has(fsnotify.Chmod): case op.Has(fsnotify.Chmod):
return "inotify:CHMOD" return "inotify:CHMOD"
case op.Has(fsnotify.Rename):
return "inotify:RENAME"
default: default:
return "inotify:UNKNOWN" return "inotify:UNKNOWN"
} }