Files
knox/internal/db/schema.sql
david e3bbeabb6b
build / test (push) Successful in 3m19s
build / image (push) Successful in 18s
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>
2026-11-05 02:14:33 +00:00

219 lines
9.9 KiB
SQL

-- IMMUTABLE LOG: every observation is append-only, never mutated
CREATE TABLE IF NOT EXISTS observations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fingerprint TEXT NOT NULL,
source_id TEXT NOT NULL,
source_path TEXT,
project TEXT,
content_type TEXT,
title TEXT,
summary TEXT,
collected_at TEXT NOT NULL DEFAULT (datetime('now')),
created_at TEXT,
line_start INTEGER,
line_end INTEGER,
confidence REAL DEFAULT 0.5,
ingester_version TEXT DEFAULT '1',
trigger TEXT,
provenance TEXT DEFAULT '{}',
content_hash TEXT DEFAULT '',
content TEXT DEFAULT '',
node_id TEXT NOT NULL DEFAULT '',
hcl INTEGER,
received_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_obs_fingerprint ON observations(fingerprint);
CREATE INDEX IF NOT EXISTS idx_obs_collected ON observations(collected_at);
CREATE INDEX IF NOT EXISTS idx_obs_created ON observations(created_at);
CREATE INDEX IF NOT EXISTS idx_obs_source ON observations(source_id, source_path);
CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project);
CREATE INDEX IF NOT EXISTS idx_obs_trigger ON observations(trigger);
-- MATERIALIZED CACHE: current state, reconstructable from observations
CREATE TABLE IF NOT EXISTS entries (
fingerprint TEXT PRIMARY KEY,
source_id TEXT NOT NULL,
source_path TEXT,
project TEXT,
content_type TEXT,
title TEXT,
summary TEXT,
content TEXT DEFAULT '',
first_seen TEXT,
last_seen TEXT,
ref_count INTEGER DEFAULT 1,
last_confidence REAL DEFAULT 0.5,
-- Added by the ALTER TABLE migrations in db.go; declared here so the file
-- is the single description of the current schema (sqlc reads this file).
created_at TEXT DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_entries_project ON entries(project);
CREATE INDEX IF NOT EXISTS idx_entries_source ON entries(source_id);
CREATE INDEX IF NOT EXISTS idx_entries_seen ON entries(last_seen);
-- FULL-TEXT SEARCH: external-content FTS5 over entries, kept in sync by
-- triggers. BM25-ranked; entries_vocab exposes the term list for typo fallback.
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(title, project, summary, content, content='entries', content_rowid='rowid');
CREATE VIRTUAL TABLE IF NOT EXISTS entries_vocab USING fts5vocab(entries_fts, 'row');
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, title, project, summary, content) VALUES ('delete', old.rowid, old.title, old.project, old.summary, old.content);
INSERT INTO entries_fts(rowid, title, project, summary, content) VALUES (new.rowid, new.title, new.project, new.summary, new.content);
END;
-- PROVENANCE LINKS: multi-hop lineage between entries
CREATE TABLE IF NOT EXISTS provenance_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
descendant_fp TEXT NOT NULL,
ancestor_fp TEXT NOT NULL,
hop_distance INTEGER NOT NULL,
relation TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_pl_descendant ON provenance_links(descendant_fp);
CREATE INDEX IF NOT EXISTS idx_pl_ancestor ON provenance_links(ancestor_fp);
-- REFLECTION STATE: per-session tracking
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
project TEXT,
title TEXT,
status TEXT DEFAULT 'active',
agent_count INTEGER DEFAULT 0,
started_at TEXT,
ended_at TEXT,
last_seen TEXT DEFAULT (datetime('now')),
indexed INTEGER DEFAULT 0
);
-- SOURCE REGISTRY
CREATE TABLE IF NOT EXISTS sources (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
enabled INTEGER DEFAULT 1,
last_event TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
INSERT OR IGNORE INTO sources (id, name) VALUES ('opencode-session', 'Opencode Session Diffs');
INSERT OR IGNORE INTO sources (id, name) VALUES ('opencode-log', 'Opencode Log Files');
INSERT OR IGNORE INTO sources (id, name) VALUES ('git', 'Git History');
INSERT OR IGNORE INTO sources (id, name) VALUES ('filesystem', 'File System Watcher');
-- KNOWLEDGE THREADS: why observations exist, what questions they answer
CREATE TABLE IF NOT EXISTS threads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
motivation TEXT,
status TEXT DEFAULT 'active',
priority TEXT DEFAULT 'medium',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
resolved_at TEXT,
tags TEXT DEFAULT '[]',
provenance TEXT DEFAULT '{}',
cluster_key TEXT,
retained INTEGER DEFAULT 0,
summary TEXT DEFAULT '',
summarized_at TEXT DEFAULT ''
);
-- SETTINGS: key-value store for runtime configuration
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
);
-- PEERS: other knox nodes known to this one (gossip ring)
CREATE TABLE IF NOT EXISTS peers (
peer_id TEXT PRIMARY KEY, -- remote node_id
addr TEXT, -- e.g. http://192.168.1.20:8931
name TEXT,
last_handshake TEXT,
cursor INTEGER DEFAULT 0, -- remote's max_hcl we've seen (knowledge)
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_threads_status ON threads(status);
CREATE TABLE IF NOT EXISTS thread_observations (
thread_id INTEGER NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
observation_id INTEGER NOT NULL REFERENCES observations(id) ON DELETE CASCADE,
relevance TEXT,
added_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (thread_id, observation_id)
);
CREATE TABLE IF NOT EXISTS thread_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id INTEGER NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
note TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
-- TOPICS: TF-IDF clustered groups of related observations
CREATE TABLE IF NOT EXISTS topics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
keywords TEXT,
score REAL DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
-- SNIPPETS: code lifted from sessions that demonstrably worked. Two-phase by
-- design: the daemon deterministically extracts *candidates* (no LLM) using
-- conservative success signals (tool completed, bash exit 0, not later
-- overwritten), and an agent curates them via the MCP encode/reject tools.
-- status: candidate | encoded | rejected. superseded_by hides dead ends.
CREATE TABLE IF NOT EXISTS snippets (
fingerprint TEXT PRIMARY KEY, -- content hash of code+language
language TEXT DEFAULT '',
code TEXT NOT NULL,
title TEXT DEFAULT '',
description TEXT DEFAULT '',
tags TEXT DEFAULT '[]',
status TEXT DEFAULT 'candidate',
source_session TEXT DEFAULT '',
source_path TEXT DEFAULT '', -- file the snippet touched (edit/write)
source_entry TEXT DEFAULT '', -- session entry fingerprint
project TEXT DEFAULT '',
tool TEXT DEFAULT '', -- edit | write | bash
model TEXT DEFAULT '',
patch_hash TEXT DEFAULT '',
evidence TEXT DEFAULT '{}', -- JSON: why it counts as "worked"
superseded_by TEXT DEFAULT '', -- later full rewrite of the same file
skill_name TEXT DEFAULT '', -- set when encoded into a ~/.skills entry
reject_reason TEXT DEFAULT '',
junk INTEGER DEFAULT 0, -- heuristic: imports/directives/single-line/empty-body stub
kind TEXT DEFAULT 'code', -- code | technique (how you explored/troubleshot)
discovered_at TEXT DEFAULT (datetime('now')),
reviewed_at TEXT DEFAULT '',
encoded_at TEXT DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_snips_status ON snippets(status);
CREATE INDEX IF NOT EXISTS idx_snips_lang ON snippets(language);
CREATE INDEX IF NOT EXISTS idx_snips_project ON snippets(project);
CREATE INDEX IF NOT EXISTS idx_snips_session ON snippets(source_session);
-- FULL-TEXT SEARCH over snippets, kept in sync by triggers (same pattern as entries_fts).
CREATE VIRTUAL TABLE IF NOT EXISTS snippets_fts USING fts5(title, description, code, language, tags, content='snippets', content_rowid='rowid');
CREATE TRIGGER IF NOT EXISTS snippets_ai AFTER INSERT ON snippets BEGIN
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_ad AFTER DELETE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
END;
CREATE TRIGGER IF NOT EXISTS snippets_au AFTER UPDATE ON snippets BEGIN
INSERT INTO snippets_fts(snippets_fts, rowid, title, description, code, language, tags) VALUES ('delete', old.rowid, old.title, old.description, old.code, old.language, old.tags);
INSERT INTO snippets_fts(rowid, title, description, code, language, tags) VALUES (new.rowid, new.title, new.description, new.code, new.language, new.tags);
END;