Compare commits

..

15 Commits

Author SHA1 Message Date
david 24d28c4cc5 fix: derive threads and snippets on replicate-only nodes (#8)
KNOX_LOCAL_SOURCES=none disabled the auto-threader and snippet extractor along
with the ingesters. Both derive from rows already in the log, so a replica has
everything they need: the dhg.lol node held 11.5k observations and 4.9k entries
but only 2 of the origin's 28 threads, quietly degrading half the MCP surface.

Ingestion stays gated; derivation always runs.
2026-11-04 18:13:21 -08:00
david 2ef8782869 fix: rebuild derived state on startup when the log has data but entries do not (#8)
A replica that restarts with a populated observation log and an empty entries
cache had no trigger to reconcile: pushes and pulls only fire on *new* rows,
and the node is already in sync. It now rebuilds once at startup.
2026-11-04 18:13:21 -08:00
david 120f64c3db perf: cache go modules and build output in CI (#8)
The Dockerfile uses BuildKit cache mounts so module downloads and compiled
packages survive a go.sum bump, and the test job restores the runner-local
cache server that act_runner already exposes.
2026-11-04 18:13:21 -08:00
david b02271f033 fix: batch pushes by size, not just row count (#8)
A 500-row batch of content-heavy observations exceeded the receiver's 4 MiB
body limit and returned 400, so the sender retried the same batch on every
sweep and the log stalled. Pushes now trim to a 2 MiB budget (rows are ordered
by HCL, so the tail simply arrives next time) and the receiver accepts up to
8 MiB.
2026-11-04 18:13:21 -08:00
david 906712cf9a fix: reconcile pushes even when this node has no seed peers (#8)
The sweep returned early on an empty peer list, which is precisely the
replica case: dhg.lol configures no peers, receives pushes, and never rebuilt
entries. Check for pending pushes before bailing out.
2026-11-04 18:13:21 -08:00
david 201a49208a ci: mount the real CasaOS app dir so the restart step can find knox (#8) 2026-11-04 18:13:21 -08:00
david 7b92b411a5 fix: reconcile after a peer push, not only after a pull (#8)
A push-only node — a replica with no peers of its own, which is exactly the
dhg.lol deployment — received observations but never rebuilt entries, so search
returned nothing while the log filled up. The batch handler now signals the
sweep, and reconcile runs when either direction changed the log.
2026-11-04 18:13:21 -08:00
david cbe42b7900 fix: separate the gossip listen address from the advertised one (#8)
KNOX_PEER_ADDR doubled as the bind address, so a container tried to bind the
host's overlay IP and the gossip server never started. KNOX_LISTEN_ADDR now
controls the bind (defaulting to KNOX_PEER_ADDR for compatibility) and the
advertised address stays what peers dial.
2026-11-04 18:13:21 -08:00
david 31fd0d8957 ci: drop the explicit docker socket mount (runner already injects it) (#8) 2026-11-04 18:13:21 -08:00
david 2421efe706 ci: install node in the job containers so actions/checkout can run (#8) 2026-11-04 18:13:21 -08:00
david 4c207fe2b3 ci: use debian-based job images so act_runner can inject node (#8) 2026-11-04 18:13:21 -08:00
david 089355708f ci: build the image on the host daemon via the runner socket (#8)
Builds on dhg.lol's daemon (the runner whitelists /var/run/docker.sock and
/apps), tags :latest plus the commit SHA, and restarts the compose stack only
when apps/knox is already installed. No registry credentials: the registry
requires htpasswd auth and self-built apps are consumed with pull_policy never.
2026-11-04 18:13:21 -08:00
david c13ac12d97 feat: mcp over http on the official sdk, tls/token transport, docker, sqlc (#8)
MCP moves from mark3labs/mcp-go v0.17 (stdio only, 5 releases behind) to the
official modelcontextprotocol/go-sdk with typed tool inputs, and gains a
Streamable HTTP transport so a remote node can serve agents.

Transport security works without a public DNS name: KNOX_AUTH_TOKEN guards
every endpoint, KNOX_TLS_CERT/KEY serve TLS from a self-signed cert, and
`knox tls init` mints one whose SANs are whatever addresses clients dial.

Daemon hygiene for an always-on host: SIGTERM shutdown of the gossip and
metrics servers, --version reporting the VCS revision, KNOX_LOCAL_SOURCES=none
for a replicate-only node (no ingest tickers, no Obsidian vault adoption), and
default watch dirs that skip paths which do not exist.

Packaging: multi-stage Dockerfile (static, non-root, /data volume).

sqlc pilot: schema moved to internal/db/schema.sql (embedded) and the read
paths behind the MCP tools are now generated. The pilot found real drift —
entries.created_at existed only as a runtime ALTER — so the column is declared
in schema.sql and a parity test fails if generated code disagrees with db.Open.

Conformance: scripts/conformance.sh runs the official suite against a throwaway
node; conformance-baseline.yml records the capabilities knox deliberately does
not implement (resources, prompts, completions, fixture tools).

Refs #8
2026-11-04 18:13:21 -08:00
david 1f35b7eea4 Merge commit '52c4d1f' into feat/remote-node
# Conflicts:
#	internal/db/db.go
2026-11-04 18:13:14 -08: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
7 changed files with 142 additions and 32 deletions
+25 -8
View File
@@ -8,6 +8,9 @@ name: build
# daemon keeps that contract and means a knox change needs no registry # daemon keeps that contract and means a knox change needs no registry
# credentials at all. # credentials at all.
# #
# act_runner runs JS actions (actions/checkout) with whatever `node` is on the
# job container's PATH, so each job installs one before checkout.
#
# Deployment stays with tf-net: this workflow only makes the new image available # Deployment stays with tf-net: this workflow only makes the new image available
# and restarts the stack when the app is already installed. # and restarts the stack when the app is already installed.
@@ -32,7 +35,18 @@ jobs:
container: container:
image: golang:1.27-alpine image: golang:1.27-alpine
steps: steps:
- name: Install node for JS actions
run: apk add --no-cache nodejs
- uses: actions/checkout@v4 - uses: actions/checkout@v4
# act_runner injects ACTIONS_CACHE_URL, so this hits the runner-local
# cache server (config: cache.dir) instead of re-downloading modules.
- uses: actions/cache@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: go-${{ hashFiles('go.sum') }}
restore-keys: go-
- run: go vet ./... && go test ./... - run: go vet ./... && go test ./...
image: image:
@@ -40,19 +54,26 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: docker:27-cli image: docker:27-cli
# Whitelisted in the runner config (valid_volumes): the host daemon and # The runner already injects /var/run/docker.sock (declaring it again is a
# the CasaOS app directory where compose files live. # duplicate mount error). CasaOS keeps app definitions under
# /var/lib/casaos/apps, which is whitelisted in the runner's valid_volumes;
# mount it at /apps so the restart step sees the installed compose file.
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock - /var/lib/casaos/apps:/apps
- /apps:/apps
env: env:
IMAGE: docker.notsosm.art/knox IMAGE: docker.notsosm.art/knox
steps: steps:
- name: Install node for JS actions
run: apk add --no-cache nodejs git
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Check the daemon
run: docker version --format '{{.Server.Version}}'
- name: Build image on the host daemon - name: Build image on the host daemon
run: | run: |
set -eu set -eu
git config --global --add safe.directory "$GITHUB_WORKSPACE" || true
# .git is present in the checkout, so the binary records the commit # .git is present in the checkout, so the binary records the commit
# it was built from (`knox --version`). # it was built from (`knox --version`).
docker build \ docker build \
@@ -69,10 +90,6 @@ jobs:
echo "apps/knox is not installed yet; image built, skipping restart" echo "apps/knox is not installed yet; image built, skipping restart"
exit 0 exit 0
fi fi
if ! docker compose version >/dev/null 2>&1; then
echo "compose plugin unavailable in this image; restart deferred to tf-net"
exit 0
fi
cd /apps/knox cd /apps/knox
docker compose up -d docker compose up -d
docker compose ps docker compose ps
+10 -3
View File
@@ -1,3 +1,4 @@
# syntax=docker/dockerfile:1
# Headless knox node: CLI + MCP stdio + gossip sync, one static binary. # Headless knox node: CLI + MCP stdio + gossip sync, one static binary.
# #
# docker build -t docker.notsosm.art/knox:latest . # docker build -t docker.notsosm.art/knox:latest .
@@ -9,12 +10,18 @@
FROM golang:1.27-alpine AS build FROM golang:1.27-alpine AS build
WORKDIR /src WORKDIR /src
# Dependencies first so source edits do not invalidate the module cache. # Dependencies first so source edits do not invalidate the module layer.
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go mod download
COPY . . COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/knox . # Cache mounts persist on the build daemon across builds, so a go.sum change no
# longer forces a full re-download and rebuild of every dependency.
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/knox .
FROM alpine:3.22 FROM alpine:3.22
RUN apk add --no-cache ca-certificates \ RUN apk add --no-cache ca-certificates \
+1
View File
@@ -31,6 +31,7 @@ DNS name: a self-signed certificate and a shared bearer token are enough.
| `KNOX_TLS_CERT` / `KNOX_TLS_KEY` | Serve TLS. Generate with `knox tls init`. | | `KNOX_TLS_CERT` / `KNOX_TLS_KEY` | Serve TLS. Generate with `knox tls init`. |
| `KNOX_TLS_CA` | Client side: trust a peer's self-signed cert. | | `KNOX_TLS_CA` | Client side: trust a peer's self-signed cert. |
| `KNOX_INSECURE_TLS=1` | Client side: skip verification (trusted overlay only). | | `KNOX_INSECURE_TLS=1` | Client side: skip verification (trusted overlay only). |
| `KNOX_LISTEN_ADDR` | Address the gossip server binds (use `0.0.0.0:8931` in a container). |
| `KNOX_PEER_ADDR` | Address this node advertises to peers. | | `KNOX_PEER_ADDR` | Address this node advertises to peers. |
| `KNOX_PEERS` | Comma-separated seed peers, e.g. `https://172.30.170.155:8931`. | | `KNOX_PEERS` | Comma-separated seed peers, e.g. `https://172.30.170.155:8931`. |
| `KNOX_LOCAL_SOURCES=none` | Replicate only: skip ingest of local files/sessions. | | `KNOX_LOCAL_SOURCES=none` | Replicate only: skip ingest of local files/sessions. |
+14
View File
@@ -952,6 +952,20 @@ func (k *KnoxDB) MarkSessionIndexed(sessionID string) error {
return err 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) { func (k *KnoxDB) Stats() (map[string]any, error) {
stats := make(map[string]any) stats := make(map[string]any)
+49 -2
View File
@@ -31,6 +31,11 @@ type Node struct {
Name string Name string
Addr string // advertised base URL, e.g. http://192.168.1.20:8931 Addr string // advertised base URL, e.g. http://192.168.1.20:8931
Metrics *metrics.Metrics Metrics *metrics.Metrics
// OnIngest runs when a peer's push added observations. Receiving a push
// changes the log just like pulling does, so the caller needs to rebuild
// derived state — otherwise a push-only node (a replica with no peers of
// its own) keeps an empty entries cache.
OnIngest func(inserted int)
} }
// pingResponse is the anti-entropy summary returned by /v1/ping. // pingResponse is the anti-entropy summary returned by /v1/ping.
@@ -100,13 +105,22 @@ func nextCursor(rows []db.GossipObservation) int64 {
return rows[len(rows)-1].HCL return rows[len(rows)-1].HCL
} }
// maxPushBytes is the payload budget for one push: observations carry the full
// source text, so a row-count limit alone can still produce a batch larger than
// the receiver accepts, which then fails on every sweep.
const maxPushBytes = 2 << 20
// maxBatchBody is the largest body a node accepts from a peer. Comfortably
// above maxPushBytes so a sender using a different batching rule still lands.
const maxBatchBody = 8 << 20
// maxBatchRows bounds the number of observations a peer may push in one POST. // maxBatchRows bounds the number of observations a peer may push in one POST.
// Pull already pages at 500 rows, so any larger batch is at best redundant and // Pull already pages at 500 rows, so any larger batch is at best redundant and
// at worst a flood; capping keeps memory and insert work bounded. // at worst a flood; capping keeps memory and insert work bounded.
const maxBatchRows = 1000 const maxBatchRows = 1000
func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) { func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4<<20) // 4 MiB r.Body = http.MaxBytesReader(w, r.Body, maxBatchBody)
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, "batch too large or unreadable", http.StatusBadRequest) http.Error(w, "batch too large or unreadable", http.StatusBadRequest)
@@ -126,6 +140,9 @@ func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
if inserted > 0 && n.OnIngest != nil {
n.OnIngest(inserted)
}
writeJSON(w, map[string]any{ writeJSON(w, map[string]any{
"accepted": inserted, "accepted": inserted,
"conflict": len(rows) - inserted, "conflict": len(rows) - inserted,
@@ -233,6 +250,21 @@ func (c *Client) Push(kdb *db.KnoxDB, peerVector map[string]int64) (int, error)
if len(rows) == 0 { if len(rows) == 0 {
return 0, nil return 0, nil
} }
// Trim to a byte budget. Rows are ordered by HCL, so dropping the tail
// keeps the cursor monotonic and the remainder arrives on the next push.
budget, n := maxPushBytes, 0
for _, r := range rows {
b, err := json.Marshal(r)
if err != nil {
break
}
if n > 0 && len(b) > budget {
break
}
budget -= len(b)
n++
}
rows = rows[:n]
body, _ := json.Marshal(rows) body, _ := json.Marshal(rows)
req, err := http.NewRequest(http.MethodPost, c.Addr+"/v1/obs/batch", bytes.NewReader(body)) req, err := http.NewRequest(http.MethodPost, c.Addr+"/v1/obs/batch", bytes.NewReader(body))
if err != nil { if err != nil {
@@ -416,14 +448,29 @@ func isLoopbackAddr(addr string) bool {
return host == "localhost" return host == "localhost"
} }
// ListenAddr returns the advertised HTTP address (KNOX_PEER_ADDR or default). // ListenAddr is the address the gossip server binds. It is separate from the
// advertised address because a container cannot bind the host's public or
// overlay IP: inside the netns it listens on all interfaces while advertising
// something peers can dial (KNOX_PEER_ADDR).
func ListenAddr() (addr string) { func ListenAddr() (addr string) {
if addr = os.Getenv("KNOX_LISTEN_ADDR"); addr != "" {
return addr
}
if addr = os.Getenv("KNOX_PEER_ADDR"); addr != "" { if addr = os.Getenv("KNOX_PEER_ADDR"); addr != "" {
return addr return addr
} }
return "localhost:" + defaultPort return "localhost:" + defaultPort
} }
// AdvertiseAddr is the base URL this node publishes to peers (/v1/ping), which
// is what they store and dial. Falls back to the listen address.
func AdvertiseAddr() string {
if addr := os.Getenv("KNOX_PEER_ADDR"); addr != "" {
return addr
}
return ListenAddr()
}
const defaultMetricsPort = "8932" const defaultMetricsPort = "8932"
// MetricsAddr returns the Prometheus scrape address (KNOX_METRICS_ADDR or // MetricsAddr returns the Prometheus scrape address (KNOX_METRICS_ADDR or
+2 -2
View File
@@ -289,7 +289,7 @@ func TestHandleBatchRejectsOversizedBatch(t *testing.T) {
} }
} }
// TestHandleBatchRejectsHugeBody: an oversized body (beyond the 4 MiB cap) // TestHandleBatchRejectsHugeBody: an oversized body (beyond maxBatchBody)
// must be refused even when the row count is small. // must be refused even when the row count is small.
func TestHandleBatchRejectsHugeBody(t *testing.T) { func TestHandleBatchRejectsHugeBody(t *testing.T) {
b := tmpKnoxDB(t) b := tmpKnoxDB(t)
@@ -300,7 +300,7 @@ func TestHandleBatchRejectsHugeBody(t *testing.T) {
rows := []db.GossipObservation{{ rows := []db.GossipObservation{{
NodeID: "0123456789abcdef0123456789abcdef", HCL: 1, NodeID: "0123456789abcdef0123456789abcdef", HCL: 1,
Fingerprint: "fp:huge", SourceID: "test", Title: "t", Fingerprint: "fp:huge", SourceID: "test", Title: "t",
Summary: strings.Repeat("x", 5<<20), // 5 MiB summary Summary: strings.Repeat("x", 9<<20), // 9 MiB, past maxBatchBody
CollectedAt: "2026-08-29T00:00:00Z", CollectedAt: "2026-08-29T00:00:00Z",
}} }}
body, _ := json.Marshal(rows) body, _ := json.Marshal(rows)
+41 -17
View File
@@ -51,6 +51,9 @@ type Watcher struct {
metricsSrv *http.Server metricsSrv *http.Server
quit chan struct{} quit chan struct{}
quitOnce sync.Once quitOnce sync.Once
// pendingReconcile is set when a peer's push added observations, so the
// next sweep rebuilds derived state without reconciling per HTTP request.
pendingReconcile atomic.Bool
} }
// fileDebouncer schedules one ingest per path a settle-window after the last // fileDebouncer schedules one ingest per path a settle-window after the last
@@ -157,7 +160,8 @@ func (w *Watcher) Start() error {
// Start the gossip server first so peers can reach us while the initial // Start the gossip server first so peers can reach us while the initial
// seed is still ingesting. Vault/dirs are logged after the seed below. // seed is still ingesting. Vault/dirs are logged after the seed below.
gossipAddr := ListenAddr() gossipAddr := ListenAddr()
node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: gossipAddr, Metrics: w.metrics} node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: AdvertiseAddr(), Metrics: w.metrics}
node.OnIngest = func(int) { w.pendingReconcile.Store(true) }
srv := &http.Server{ srv := &http.Server{
Addr: gossipAddr, Addr: gossipAddr,
Handler: httpauth.Middleware(node.Handler()), Handler: httpauth.Middleware(node.Handler()),
@@ -205,6 +209,19 @@ func (w *Watcher) Start() error {
log.Printf("[knox] obsidian vault: %s", w.vault) log.Printf("[knox] obsidian vault: %s", w.vault)
} }
// A node that starts with a populated log but an empty entries cache — a
// freshly deployed replica, or any node whose derived state was wiped — has
// nothing to trigger a reconcile, so build it once at startup. Reconcile is
// only cheap-ish, not free, hence the guard.
if obs, entries, err := w.knoxDB.DerivedStateCounts(); err == nil && obs > 0 && entries == 0 {
log.Printf("[knox] derived state empty with %d observations: rebuilding", obs)
if created, linked, err := Reconcile(w.knoxDB); err != nil {
log.Printf("[knox] startup reconcile: %v", err)
} else {
log.Printf("[knox] startup reconcile done: %d created, %d linked", created, linked)
}
}
debounce := newFileDebouncer() debounce := newFileDebouncer()
browserTicker := time.NewTicker(browserInterval) browserTicker := time.NewTicker(browserInterval)
giteaTicker := time.NewTicker(10 * time.Minute) giteaTicker := time.NewTicker(10 * time.Minute)
@@ -216,16 +233,21 @@ func (w *Watcher) Start() error {
snippetTicker := time.NewTicker(snippetInterval) snippetTicker := time.NewTicker(snippetInterval)
gossipTicker := time.NewTicker(gossipInterval) gossipTicker := time.NewTicker(gossipInterval)
// A node that only replicates peers (a server with none of the local // Derivation always runs. Threads and snippets are computed from rows that
// sources) skips the ingest/derive tickers entirely. Nil channels block // are already in the log, so a replica needs them exactly as much as the
// forever, so the select simply never fires for them. // origin does — gating them with the ingesters left a replica with an
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC, threadC, snippetC <-chan time.Time // almost empty thread list while the data sat right there.
threadC, snippetC := threadTicker.C, snippetTicker.C
// Ingestion only runs where the sources exist. A node with no local
// sources (KNOX_LOCAL_SOURCES=none) leaves these nil: nil channels block
// forever, so the select never fires for them.
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC <-chan time.Time
if LocalSourcesEnabled() { if LocalSourcesEnabled() {
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C
threadC, snippetC = threadTicker.C, snippetTicker.C
} else { } else {
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: gossip-only mode, local ingest disabled") log.Printf("[knox] KNOX_LOCAL_SOURCES=none: local ingest disabled, derivation still active")
} }
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool
@@ -850,18 +872,20 @@ func (w *Watcher) extractSnippets() {
// syncGossip runs one anti-entropy sweep against configured peers and rebuilds // syncGossip runs one anti-entropy sweep against configured peers and rebuilds
// derived state if anything new arrived. // derived state if anything new arrived.
func (w *Watcher) syncGossip() { func (w *Watcher) syncGossip() {
peers := PeerAddrs() // Taken before the peer check: a replica with no seed peers still receives
if len(peers) == 0 { // pushes, and that is the only thing that ever changes its log. Returning
return // early on an empty peer list would leave its entries cache empty forever.
pushedIn := w.pendingReconcile.Swap(false)
pulled := 0
if peers := PeerAddrs(); len(peers) > 0 {
pulled = Run(w.knoxDB, w.metrics, peers)
} }
pulled := Run(w.knoxDB, w.metrics, peers) // Reconcile when this sweep changed the log, in either direction: a pull
// inserts rows here, a peer's push inserted them in the HTTP handler. The
// A pull only appends to the observation log; the entries cache and // entries cache and auto-threads are derived state that reconcile rebuilds.
// auto-threads are derived state that reconcile rebuilds. Comparing entry if pulled > 0 || pushedIn {
// counts can never trigger this (pushes/pulls never touch entries directly),
// so reconcile fires on the sweep's newly-inserted observation count.
if pulled > 0 {
created, linked, err := Reconcile(w.knoxDB) created, linked, err := Reconcile(w.knoxDB)
if err != nil { if err != nil {
log.Printf("[knox] gossip reconcile: %v", err) log.Printf("[knox] gossip reconcile: %v", err)