feat: always-on remote node — MCP over HTTP, TLS/token, Docker, CI, sqlc (#9)
Deploys knox as a headless, always-on replica so agents keep their memory when the laptop is off. Closes #8. **Supersedes #5** (its hardening commit is merged in here; close #5 after this lands). ## What changed **MCP transport + SDK** - Moves from `mark3labs/mcp-go` v0.17 (stdio only, five releases behind) to the official `modelcontextprotocol/go-sdk` v1.8. Tool inputs are typed structs, so schemas are generated instead of hand-built. - Adds `knox mcp --http` (Streamable HTTP). stdio remains the default. **Transport security without a public name** - `KNOX_AUTH_TOKEN` guards gossip and MCP HTTP; `KNOX_TLS_CERT/KEY` serve TLS; `knox tls init` mints a self-signed cert whose SANs are whatever addresses clients dial. Verified: 401 without the token, 200 with, cert valid for the overlay IP. **Daemon hygiene** - SIGTERM shuts down the gossip and metrics servers. - `--version` reports the VCS revision. - `KNOX_LOCAL_SOURCES=none` makes a node ingest nothing but still derive. - Default watch dirs skip paths that do not exist. **Deployment topology fixes** (all found by actually running a replica) - `KNOX_LISTEN_ADDR` split from `KNOX_PEER_ADDR`: a container cannot bind the host's overlay IP, and previously the gossip server silently failed to start. - Reconcile now fires on push and on startup, not only on pull. Three separate bugs left `entries` empty on a push-only node. - Pushes batch by byte budget, not just row count — 500 content-heavy rows exceeded the 4 MiB body limit and the log stalled permanently at 3,000 observations. - Threads and snippets derive on replicas: gating them with the ingesters left the server holding 11.5k observations and 4.9k entries but 2 of 28 threads. **Packaging + CI** - Multi-stage Dockerfile (static, non-root, `/data` volume). - Gitea workflow builds on the dhg.lol daemon through the runner socket, tags `:latest` + `:<sha>`, and restarts the stack when installed. BuildKit cache mounts keep module downloads warm. **sqlc pilot** - Schema extracted to `internal/db/schema.sql` (embedded); read paths behind the MCP tools are generated. - The pilot found real drift: `entries.created_at` existed only as a runtime `ALTER`. It is now declared in the schema, and `sqlcdb_pilot_test.go` fails if generated code disagrees with `db.Open`. - FTS5 stays hand-written: sqlc ignores `CREATE VIRTUAL TABLE`, so `MATCH`/`bm25` cannot be generated. ## Verification - `go vet ./...`, `go test ./...`, `gofmt` clean - `scripts/conformance.sh` — official MCP suite, exit 0 against `conformance-baseline.yml` (documents the capabilities knox does not implement: resources, prompts, completions, fixture tools) - Live: both containers healthy on dhg.lol, ports bound only to the ZeroTier address, 11,553 observations / 4,943 entries replicated and reconciled ## Deploy Infrastructure lives in `tf-net/apps/knox` (separate repo); this branch is what is currently running in production. Reviewed-on: #9 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #9.
This commit is contained in:
+192
-63
@@ -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
|
||||
}
|
||||
|
||||
@@ -886,36 +952,56 @@ func (k *KnoxDB) MarkSessionIndexed(sessionID string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// DerivedStateCounts returns the number of observations in the append-only log
|
||||
// and the number of materialized entries. Callers use it to decide whether the
|
||||
// derived cache needs rebuilding (e.g. a replica that starts with a log but no
|
||||
// entries because it never saw a push or pull since the cache was wiped).
|
||||
func (k *KnoxDB) DerivedStateCounts() (observations, entries int, err error) {
|
||||
if err = k.db.QueryRow("SELECT COUNT(*) FROM observations").Scan(&observations); err != nil {
|
||||
return 0, 0, fmt.Errorf("count observations: %w", err)
|
||||
}
|
||||
if err = k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&entries); err != nil {
|
||||
return 0, 0, fmt.Errorf("count entries: %w", err)
|
||||
}
|
||||
return observations, entries, nil
|
||||
}
|
||||
|
||||
func (k *KnoxDB) Stats() (map[string]any, error) {
|
||||
stats := make(map[string]any)
|
||||
|
||||
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 +1014,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 +1613,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 +1740,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 +1769,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 +1778,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 +1790,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 +1805,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 +1877,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 {
|
||||
|
||||
Reference in New Issue
Block a user