Compare commits

3 Commits

Author SHA1 Message Date
david 1fa9c46eb9 feat: remove peers from the CLI and the gossip API (#10)
build / test (push) Successful in 3m33s
build / image (push) Successful in 27s
Peers were only ever merged, so a retired node stayed in the table forever and
failed on every sweep — the laptop node retried a dead LAN peer every minute for
weeks, fixable only by editing SQLite.

Adds DeletePeer (by peer_id or exact address), DELETE /v1/peers/{id} and
DELETE /v1/peers?addr= behind the existing token middleware, and
`knox gossip peer list|rm`. The CLI warns when the removed address is still in
KNOX_PEERS, since a static seed is re-learned on the next sweep.
2026-11-04 18:19:58 -08:00
david e3bbeabb6b feat: always-on remote node — MCP over HTTP, TLS/token, Docker, CI, sqlc (#9)
build / test (push) Successful in 3m19s
build / image (push) Successful in 18s
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
david 8d6d73b747 fix: read opencode sessions from session_v2/session_message (#7)
Fixes #6.

opencode 2.0.24 migrated its session store on 2026-11-01 21:01:20 UTC. `session`, `message` and `part` stopped being written; sessions now live in `session_v2` and messages in `session_message`. The ingest kept querying the abandoned tables, so every sweep after the migration logged `0 new` — no error, no new sessions indexed.

## Changes

- **`internal/ingest/opencode_db.go`**
  - Read sessions from `session_v2` (title is nullable there, the existing COALESCE + fallback still apply).
  - Rebuild transcripts from both message shapes: user turns at `$.text`, assistant turns from `$.content[]` filtered to `type='text'` (reasoning and tool parts are not indexed). Ordered by `seq`, then part index.
  - Count messages from `session_message` instead of parts.
  - Drop `<system-reminder>` text — reminders now arrive as `synthetic` messages and would eat the 4000-byte summary budget.
  - Ingester version is now `opencode-db/v2`.
- **`internal/watch/watch.go`** — an entry is no longer skipped on `created_at` alone. Resuming a session appends messages without touching the creation time, so the summary is compared too.
- **`internal/ingest/opencode_db_test.go`** — new test builds the v2 schema in a temp SQLite database and asserts user text and assistant text parts are indexed while reasoning, tool and reminder content is not.

## Validation

- `go build ./...`, `go test ./internal/ingest/ ./internal/db/ ./internal/watch/` pass.
- Rebuilt the binary and restarted `knox.service` against the live store:
  ```
  [knox] opencode.db: 1 new, 387 unchanged
  ```
  The new entry is the session that had been invisible since the migration (`Knox OpenCode session adapter compatibility check`, observation version `opencode-db/v2`), and `knox query "knox opencode session adapter compatibility"` finds it.
- 59 pre-migration sessions re-recorded because their stored transcripts contained reminder text that the new filter drops; summaries still carry the conversation.

## Notes

The first commit on this branch is a checkpoint of pre-existing uncommitted work that the adapter fix sits on top of; the fix itself is the second commit (`e07ae8a`).

Reviewed-on: #7
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-02 01:16:50 +00:00
5 changed files with 211 additions and 0 deletions
+48
View File
@@ -54,6 +54,54 @@ func NewGossipCmd(kdb *db.KnoxDB) *cobra.Command {
return gossipDiff(kdb, args[0])
},
},
&cobra.Command{
Use: "peer <list|rm>",
Short: "List or forget known peers",
Args: cobra.RangeArgs(0, 2),
RunE: func(c *cobra.Command, args []string) error {
action := "list"
if len(args) > 0 {
action = args[0]
}
switch action {
case "list":
peers, err := kdb.ListPeers()
if err != nil {
return err
}
if len(peers) == 0 {
fmt.Println("no peers")
return nil
}
for _, p := range peers {
fmt.Printf("%s %-30s last=%s cursor=%d\n", p.PeerID, p.Addr, p.LastHandshake, p.Cursor)
}
return nil
case "rm":
if len(args) != 2 {
return fmt.Errorf("usage: knox gossip peer rm <peer-id|address>")
}
deleted, err := kdb.DeletePeer(args[1])
if err != nil {
return err
}
if deleted == 0 {
return fmt.Errorf("no peer matching %q", args[1])
}
fmt.Printf("forgot %s\n", args[1])
// A static seed would simply be re-learned on the next
// sweep, so say so rather than let the operator wonder.
for _, seeded := range watch.PeerAddrs() {
if seeded == args[1] {
fmt.Printf("warning: %s is still in KNOX_PEERS and will be re-learned\n", args[1])
}
}
return nil
default:
return fmt.Errorf("unknown peer action %q (use list or rm)", action)
}
},
},
&cobra.Command{
Use: "sync",
Short: "Run one anti-entropy sweep against configured peers",
+16
View File
@@ -4,6 +4,7 @@ import (
"database/sql"
"fmt"
"log"
"strings"
)
// GossipObservation is the serializable wire form of an observation exchanged
@@ -305,3 +306,18 @@ func (k *KnoxDB) ThreadStatusByCluster() (map[string]string, error) {
}
return out, rows.Err()
}
// DeletePeer removes a peer by exact peer_id or exact address and reports how
// many rows went. Without this, a peer learned once (or seeded from KNOX_PEERS
// and later retired) stays in the table forever and fails on every sweep.
func (k *KnoxDB) DeletePeer(identifier string) (int64, error) {
identifier = strings.TrimSpace(identifier)
if identifier == "" {
return 0, fmt.Errorf("peer id or address required")
}
res, err := k.db.Exec(`DELETE FROM peers WHERE peer_id=? OR addr=?`, identifier, identifier)
if err != nil {
return 0, fmt.Errorf("delete peer: %w", err)
}
return res.RowsAffected()
}
+73
View File
@@ -0,0 +1,73 @@
package db_test
import (
"path/filepath"
"testing"
"github.com/david/knox/internal/db"
)
// TestDeletePeer: peers are only ever merged, so a retired node used to linger
// forever and fail on every sweep. Deletion must work by id and by address, and
// must not touch unrelated peers.
func TestDeletePeer(t *testing.T) {
kdb, err := db.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { _ = kdb.Close() })
if err := kdb.MergePeer("aaaa", "http://10.0.0.1:8931", "old"); err != nil {
t.Fatalf("merge a: %v", err)
}
if err := kdb.MergePeer("bbbb", "https://10.0.0.2:8931", "new"); err != nil {
t.Fatalf("merge b: %v", err)
}
t.Run("by address", func(t *testing.T) {
n, err := kdb.DeletePeer("http://10.0.0.1:8931")
if err != nil {
t.Fatalf("delete: %v", err)
}
if n != 1 {
t.Errorf("deleted %d rows, want 1", n)
}
peers, err := kdb.ListPeers()
if err != nil {
t.Fatalf("list: %v", err)
}
if len(peers) != 1 || peers[0].PeerID != "bbbb" {
t.Fatalf("wrong survivor: %+v", peers)
}
})
t.Run("by id", func(t *testing.T) {
n, err := kdb.DeletePeer("bbbb")
if err != nil {
t.Fatalf("delete: %v", err)
}
if n != 1 {
t.Errorf("deleted %d rows, want 1", n)
}
peers, _ := kdb.ListPeers()
if len(peers) != 0 {
t.Fatalf("peers remain: %+v", peers)
}
})
t.Run("unknown is a no-op", func(t *testing.T) {
n, err := kdb.DeletePeer("nope")
if err != nil {
t.Fatalf("delete: %v", err)
}
if n != 0 {
t.Errorf("deleted %d rows for an unknown peer, want 0", n)
}
})
t.Run("empty identifier is rejected", func(t *testing.T) {
if _, err := kdb.DeletePeer(" "); err == nil {
t.Error("want error for empty identifier")
}
})
}
+29
View File
@@ -53,6 +53,10 @@ func (n *Node) Handler() http.Handler {
mux.HandleFunc("GET /v1/log", n.handleLog)
mux.HandleFunc("POST /v1/obs/batch", n.handleBatch)
mux.HandleFunc("GET /v1/diff", n.handleDiff)
mux.HandleFunc("DELETE /v1/peers/{id}", n.handleDeletePeer)
// Addresses contain slashes, so they travel as ?addr= rather than a path
// segment.
mux.HandleFunc("DELETE /v1/peers", n.handleDeletePeer)
return mux
}
@@ -183,6 +187,31 @@ func (n *Node) handleDiff(w http.ResponseWriter, r *http.Request) {
})
}
// handleDeletePeer forgets a peer, either by id in the path or by ?addr= for
// addresses that contain slashes. Deletion is not permanent against a static
// seed: KNOX_PEERS is re-merged on the next sweep, so a seeded peer must also
// be removed from the environment.
func (n *Node) handleDeletePeer(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("id")
if addr := r.URL.Query().Get("addr"); addr != "" {
key = addr
}
if key == "" {
http.Error(w, "peer id or address required", http.StatusBadRequest)
return
}
deleted, err := n.Kdb.DeletePeer(key)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if deleted == 0 {
http.Error(w, "no such peer: "+key, http.StatusNotFound)
return
}
writeJSON(w, map[string]any{"deleted": deleted})
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
+45
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
@@ -363,3 +364,47 @@ func TestClientPushSurfacesHTTPError(t *testing.T) {
t.Fatal("expected push error on HTTP 500, got nil")
}
}
// TestHandleDeletePeer: the peer list is otherwise append-only, so there must be
// a way to forget a node that moved or was decommissioned. Both addressing
// forms are accepted, and an unknown peer is a 404 rather than a silent success.
func TestHandleDeletePeer(t *testing.T) {
b := tmpKnoxDB(t)
node := &Node{Kdb: b, Name: "A"}
sv := httptest.NewServer(node.Handler())
defer sv.Close()
if err := b.MergePeer("0123456789abcdef0123456789abcdef", "http://10.0.0.9:8931", "old"); err != nil {
t.Fatalf("merge: %v", err)
}
del := func(path string) int {
req, _ := http.NewRequest(http.MethodDelete, sv.URL+path, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("delete %s: %v", path, err)
}
defer resp.Body.Close()
return resp.StatusCode
}
if code := del("/v1/peers/unknown-id"); code != http.StatusNotFound {
t.Errorf("unknown peer: got %d, want 404", code)
}
if code := del("/v1/peers/0123456789abcdef0123456789abcdef"); code != http.StatusOK {
t.Errorf("by id: got %d, want 200", code)
}
if peers, _ := b.ListPeers(); len(peers) != 0 {
t.Fatalf("peer not deleted: %+v", peers)
}
if err := b.MergePeer("ffff", "http://10.0.0.10:8931", "old2"); err != nil {
t.Fatalf("merge2: %v", err)
}
if code := del("/v1/peers?addr=" + url.QueryEscape("http://10.0.0.10:8931")); code != http.StatusOK {
t.Errorf("by addr: got %d, want 200", code)
}
if peers, _ := b.ListPeers(); len(peers) != 0 {
t.Fatalf("peer not deleted by addr: %+v", peers)
}
}