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>
This commit was merged in pull request #9.
This commit is contained in:
2026-11-05 02:14:33 +00:00
committed by david
parent 8d6d73b747
commit e3bbeabb6b
31 changed files with 2883 additions and 1334 deletions
+2 -1
View File
@@ -2,6 +2,7 @@ package cmd
import (
"fmt"
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch"
@@ -77,7 +78,7 @@ func NewGossipCmd(kdb *db.KnoxDB) *cobra.Command {
// gossipDiff compares this node's observation log + auto-threads with a peer's
// via /v1/diff. Never writes; it is the preview for what a sync would adopt.
func gossipDiff(kdb *db.KnoxDB, peerAddr string) error {
c := &watch.Client{Addr: peerAddr}
c := &watch.Client{Addr: peerAddr, Timeout: 10 * time.Second}
remote, err := c.Diff()
if err != nil {
return err
+6
View File
@@ -98,6 +98,8 @@ func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command {
for _, r := range results {
record(r)
}
} else {
log.Printf("[knox] obsidian ingest failed: %v", err)
}
}
log.Printf("[knox] ingesting browser-history...")
@@ -105,12 +107,16 @@ func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command {
for _, r := range results {
record(r)
}
} else {
log.Printf("[knox] browser-history ingest failed: %v", err)
}
log.Printf("[knox] ingesting gitea...")
if results, err := ingest.NewGiteaIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
} else {
log.Printf("[knox] gitea ingest failed: %v", err)
}
log.Printf("[knox] ingesting karakeep...")
if results, err := ingest.NewKarakeepIngester().IngestAll(); err == nil {
+1024 -1004
View File
File diff suppressed because it is too large Load Diff
+60
View File
@@ -0,0 +1,60 @@
package cmd
import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/david/knox/internal/httpauth"
"github.com/spf13/cobra"
)
// NewTLSCmd exposes certificate management for nodes that must serve TLS
// without a public DNS name or a CA-issued certificate.
func NewTLSCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "tls",
Short: "Manage TLS material for a remote knox node",
}
var (
hosts []string
out string
days int
)
initCmd := &cobra.Command{
Use: "init",
Short: "Generate a self-signed certificate usable without a public name",
Long: `Generate a self-signed certificate and key for this node.
The certificate is its own CA, so peers (and MCP clients) trust it by pointing
KNOX_TLS_CA at the certificate file. No public DNS name or external certificate
authority is involved: pass the addresses clients actually dial, e.g.
knox tls init --host 172.30.170.155 --host knox.dhg.lol --out /data/tls`,
RunE: func(c *cobra.Command, args []string) error {
certPath := filepath.Join(out, "cert.pem")
keyPath := filepath.Join(out, "key.pem")
if err := httpauth.GenerateSelfSigned(certPath, keyPath, hosts, time.Duration(days)*24*time.Hour); err != nil {
return err
}
fmt.Printf("wrote %s\nwrote %s\n\n", certPath, keyPath)
fmt.Println("serve with:")
fmt.Printf(" %s=%s\n %s=%s\n %s=<shared-secret>\n",
httpauth.CertEnv, certPath, httpauth.KeyEnv, keyPath, httpauth.TokenEnv)
fmt.Println("\npeers trust it with:")
fmt.Printf(" %s=%s\n %s=<same-secret>\n", httpauth.CAEnv, certPath, httpauth.TokenEnv)
if len(hosts) > 0 {
fmt.Printf("\ncertificate covers: %s\n", strings.Join(hosts, ", "))
}
return nil
},
}
initCmd.Flags().StringSliceVar(&hosts, "host", nil, "DNS names and/or IP addresses clients dial (repeatable)")
initCmd.Flags().StringVar(&out, "out", "./tls", "Directory to write cert.pem and key.pem into")
initCmd.Flags().IntVar(&days, "days", 825, "Validity in days")
cmd.AddCommand(initCmd)
return cmd
}
+29 -2
View File
@@ -1,8 +1,13 @@
package cmd
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"syscall"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/watch"
@@ -24,8 +29,21 @@ func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command {
}
log.Printf("[knox] starting watcher, scanning %d directories", len(dirs))
w := watch.New(kdb, dirs)
// A container sends SIGTERM on stop; shut down the HTTP servers so
// restarts are clean instead of dropping the listeners abruptly.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
w.Shutdown()
}()
if err := w.Start(); err != nil {
log.Fatalf("watcher error: %v", err)
// Not log.Fatalf: --quiet redirects the logger to io.Discard,
// so a fatal exit must reach the user on stderr directly.
fmt.Fprintf(os.Stderr, "watcher error: %v\n", err)
os.Exit(1)
}
},
}
@@ -36,8 +54,17 @@ func NewWatchCmd(kdb *db.KnoxDB) *cobra.Command {
func defaultWatchDirs() []string {
home, _ := getHomeDir()
return []string{
candidates := []string{
home + "/.local/share/opencode/log",
home + "/.skills",
}
// A headless node has none of these; watch nothing rather than logging a
// failed watch for every missing path.
dirs := make([]string, 0, len(candidates))
for _, d := range candidates {
if info, err := os.Stat(d); err == nil && info.IsDir() {
dirs = append(dirs, d)
}
}
return dirs
}