Commit Graph

13 Commits

Author SHA1 Message Date
david a5430b7d25 feat: remove peers (CLI + HTTP) so retired nodes stop being retried (#11)
build / test (push) Successful in 3m33s
build / image (push) Successful in 18s
Closes #10.

Peers were append-only: `UpsertPeer`/`MergePeer` existed, nothing could remove a row. A retired node therefore stayed in the table forever and failed on every anti-entropy sweep — the laptop node has been retrying a dead LAN peer (`http://192.168.8.240:8931`) every minute for weeks, with no fix short of hand-editing SQLite.

## Changes

- `KnoxDB.DeletePeer(identifier)` — exact match on `peer_id` **or** `addr`; empty identifier rejected.
- `DELETE /v1/peers/{peer_id}` and `DELETE /v1/peers?addr=<url>` — the query form exists because addresses contain slashes. Both sit behind the same bearer-token middleware as the rest of the gossip API, so they inherit TLS + `KNOX_AUTH_TOKEN`.
- `knox gossip peer list` / `knox gossip peer rm <peer-id|address>`.
- The CLI warns when the removed address is still in `KNOX_PEERS`, because a static seed is re-merged on the next sweep and would silently come back.

## Caveat worth knowing
Deletion only sticks for peers learned through membership gossip. Anything still listed in `KNOX_PEERS` will be re-learned; remove it from the environment too.

## Verification
- `internal/db/gossip_test.go` — delete by id, by address, unknown peer is a no-op, empty identifier rejected
- `internal/watch/gossip_test.go` — 404 for unknown, 200 by id, 200 by `?addr=`
- `go vet ./...`, `go test ./...` green
- Used live: removed the stale `192.168.8.240` peer on the laptop node; the every-minute `no route to host` errors stopped on the next sweep

Reviewed-on: #11
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 02:27:52 +00: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
david bb852faa27 fix: harden gossip, HLC restarts, watcher races, MCP args, pagination (#3)
Implements the top findings from the codebase review, verified with tests and live CLI/MCP checks.

**Gossip integrity**
- Push validation: 4 MiB body cap, 1000-row batch cap; rows claiming the local node id (vector-poisoning), empty node ids, and negative HCLs rejected (internal/watch/gossip.go, internal/db/gossip.go)
- Reconcile-on-pull: Run returns the pulled count, syncGossip rebuilds derived state when > 0 — entry-count comparison could never fire, so synced observations never materialized into searchable entries

**Data-layer safety**
- HLC resumed from MAX(hcl) at Open (hlc.SeekTo): a restart with a regressed wall clock cannot reissue values the (node_id, hcl) locator and pull cursors depend on
- Writer serialization: _txlock=immediate DSN + SetMaxOpenConns(1) + per-KnoxDB mutex around RecordObservation's check-then-insert dedup (closes duplicate-row race)

**Watch daemon**
- Ticker guard flags now atomic.Bool (was a cross-goroutine data race)
- Trailing-edge per-path debounce (timer-based, pruned on fire/delete)
- Recursive watches (startup tree walk + watcher.Add on dir Create); Rename re-ingests, Remove cancels pending ingests

**MCP + CLI**
- Strict arg validation, no silent clamping: thread_id 0 errors instead of renaming thread #1; empty knox_thread_link {} errors instead of false success; thread existence checked before writes; golden-thread tool nil-safe
- --page 0 errors instead of panicking; query/recent pagination actually pages (page x limit)

**Tests** (new internal/hlc and internal/db packages): SeekTo monotonicity, concurrent dedup race, push validation, reopen HCL monotonicity, batch caps, self-spoof rejection, idempotency on observation counts.

Verified: go build, go vet, full suite with -race, live MCP stdio transcripts against a scratch DB.
Reviewed-on: #3
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-09-17 09:06:08 +00:00
david d6d2a24ddc style: gofmt all packages (#4)
Applies gofmt to the 18 files that were already unformatted at HEAD (pre-existing debt — 122 insertions / 122 deletions, whitespace plus import-block reorderings only; `git diff -w` confirms no semantic changes).

Kept on its own branch so the functional change set (see the review-hardening PR) stays reviewable without formatting noise.

Verified: go build, go vet, go test ./... pass on this branch; a merge simulation with the functional branch produces a clean 3-way merge with all tests green.
Reviewed-on: #4
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-09-17 09:05:57 +00:00
david 876d2aa45f feat: Prometheus metrics endpoint for knox nodes
Refs #2

- /metrics served on a dedicated port (KNOX_METRICS_ADDR, default
  localhost:8932) via prometheus/client_golang, with Go runtime +
  process collectors
- DB-derived gauges refreshed per scrape: observations by source,
  last-24h observations, entries, projects, sessions, pending
  reflections, threads by status, peers, observations by origin node,
  knowledge vector (max hcl per node)
- live gossip counters (pulls/pushes, observations pulled/pushed,
  errors) incremented during the anti-entropy sweep; Run accepts an
  optional metrics handle (nil for one-shot CLI)
- knox_node_info{node_id,name} for scrape identification
- internal/metrics package + db MetricsSnapshot; tests for snapshot,
  scrape output, and counter increments
2026-08-29 06:06:49 -07:00
david 25a7112d8a feat: swarm membership discovery via peer-list gossip
Refs #1

- /v1/ping now advertises the node's known peers (peer_id, addr, name)
- Run sweeps static KNOX_PEERS + persisted discovered peers, enqueueing
  newly-learned addresses for direct sweeps (membership-only relay; no
  observation relay)
- db: ShareablePeers, SwarmPeerAddrs, MergePeer (cursor-preserving
  discovery upsert), MaxHCLForNode
- integration test: a node configured with a single seed discovers and
  pulls from other swarm members without direct configuration
2026-08-29 05:41:52 -07:00
david 48e9c39d7b feat: M4 gossip ops and UX
Refs #1

- /v1/diff endpoint returns each node's fingerprint set + tombstoned
  auto-thread status
- knox gossip diff <peer-url>: shows peer-only/local-only fingerprints
  (pull/keep preview) and tombstone divergence (resolved-on-peer vs
  would-resurrect)
- knox gossip sync: one-shot anti-entropy sweep + reconcile
- gossip server starts before initial seed so peers can reach a booting
  node; KNOX_PEER_ADDR alone now serves without KNOX_PEERS
- integration tests for diff + tombstone reporting
- e2e verified: two live daemons, diff previewed 1655 peer-only fps,
  sync converged second node to 1655 observations
2026-08-29 05:08:45 -07:00
david 8c054094a1 feat: M3 peer gossip protocol
Refs #1

- peers table (peer_id, addr, cursor, last_handshake)
- watch serves HTTP API: GET /v1/ping (knowledge vector),
  GET /v1/log?node=&after= (cursor-paged pull), POST /v1/obs/batch
- anti-entropy sweep (Run): ping, pull what we lack, push own obs;
  echo suppressed by node_id ownership; reconcile-on-pull
- config via KNOX_PEERS / KNOX_PEER_ADDR; knox gossip status
- db: GossipObservation wire type, PushObservations, ObservationsAfter,
  KnowledgeVector, peer upsert/list
- integration tests: bidirectional convergence + idempotency
2026-08-29 04:53:26 -07:00
david aa0dec68c1 feat: M2 composite locator + idle reconcile
Refs #1

- observations: hcl backfilled from local rowid; (node_id, hcl) UNIQUE
  locator index becomes the gossip merge key
- threads: cluster_key column + partial UNIQUE index; CreateThreadCluster
  is idempotent, threader folds into exact cluster_key before heuristic
- AutoLinkThreadObservations dedup re-expressed on hcl DESC
- new `knox reconcile [--dry-run]` rebuilds entries from the observation
  log and re-links threads idempotently (entry count, thread cluster_key
  verified bit-identical from log-only DB)
2026-08-29 04:47:15 -07:00
david 2c0f8fa257 feat: M1 determinism fixes for gossip
Refs #1

- F1: canonical fingerprints (git identity by remote URL, log by
  basename, obsidian by relative vault path) so identical facts get
  identical ids across machines
- F2: node_id (persisted in settings) + Hybrid Logical Clock in all
  observation "when" columns; removed time.Now() fact-time fallbacks
- F3: stable TF-IDF tie-break sort (score desc, term asc)
- F4: observations carry (node_id, hcl) locator; dedup ordered by hcl
2026-08-29 03:51:02 -07:00
david f5766aa6d8 docs: gossip protocol design for cross-machine sharing
Tracks issue #1. Audits knox determinism (path-based fingerprints,
wall-clock fact times, TF-IDF tie-breaks, autoincrement IDs) and
specifies schema changes, HLC clocks, merge rules, reconcile, and
M1-M4 milestones.
2026-08-29 03:40:53 -07:00
david 8eecde18b4 Initial commit: knox knowledge index 2026-08-29 02:52:32 -07:00