Files
knox/internal/watch/watch.go
T
david 39d970a7ea
build / test (push) Successful in 3m2s
build / image (push) Successful in 2m10s
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 17:09:04 -08:00

921 lines
27 KiB
Go

package watch
import (
"context"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/httpauth"
"github.com/david/knox/internal/ingest"
"github.com/david/knox/internal/metrics"
"github.com/david/knox/internal/skillsrepo"
"github.com/fsnotify/fsnotify"
)
const (
browserInterval = 5 * time.Minute
opencodeInterval = 2 * time.Minute
gossipInterval = 1 * time.Minute
// logDebounce coalesces the rapid writes of an actively-appended log so it
// is not fully re-parsed every couple of seconds.
logDebounce = 30 * time.Second
karakeepInterval = 30 * time.Minute
healthInterval = 15 * time.Minute
snippetInterval = 10 * time.Minute
)
// fileState is a cheap identity for a file: an unchanged size+mtime means the
// content is unchanged, so the expensive Ingest (full read) can be skipped.
type fileState struct {
size int64
mtime int64
}
type Watcher struct {
knoxDB *db.KnoxDB
dirs []string
vault string
debounce time.Duration
fileIngesters []ingest.Ingester
metrics *metrics.Metrics
lastIngest map[string]fileState
gossipSrv *http.Server
metricsSrv *http.Server
quit chan struct{}
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
// relevant event (trailing edge): writers that emit bursts (multi-write appends,
// atomic save = temp-write + rename) settle before anything is read, so a
// partial file is never recorded as final state. Timers are removed once they
// fire, keeping the map bounded by recently-active paths.
type fileDebouncer struct {
mu sync.Mutex
timers map[string]*time.Timer
}
func newFileDebouncer() *fileDebouncer {
return &fileDebouncer{timers: make(map[string]*time.Timer)}
}
func (d *fileDebouncer) schedule(path string, delay time.Duration, fn func(string)) {
d.mu.Lock()
defer d.mu.Unlock()
if t, ok := d.timers[path]; ok {
t.Stop()
}
d.timers[path] = time.AfterFunc(delay, func() {
d.mu.Lock()
delete(d.timers, path)
d.mu.Unlock()
fn(path)
})
}
// cancel drops any pending ingest for path (e.g. the file was deleted).
func (d *fileDebouncer) cancel(path string) {
d.mu.Lock()
defer d.mu.Unlock()
if t, ok := d.timers[path]; ok {
t.Stop()
delete(d.timers, path)
}
}
func New(kdb *db.KnoxDB, dirs []string) *Watcher {
// Detect Obsidian vault. A gossip-only node has no local sources to read,
// so it must not adopt whatever vault happens to exist on its filesystem.
var vault string
if LocalSourcesEnabled() {
vault, _ = ingest.DetectObsidianVault()
}
return &Watcher{
knoxDB: kdb,
dirs: dirs,
vault: vault,
debounce: 2 * time.Second,
fileIngesters: []ingest.Ingester{
ingest.NewLogIngester(),
ingest.NewSkillsIngester(),
},
metrics: metrics.New(kdb, "knox"),
lastIngest: make(map[string]fileState),
quit: make(chan struct{}),
}
}
// Shutdown asks Start to return after closing the gossip and metrics servers.
// It is safe to call more than once.
func (w *Watcher) Shutdown() {
w.quitOnce.Do(func() { close(w.quit) })
}
// LocalSourcesEnabled reports whether this node ingests local sources
// (opencode sessions, browser history, git, Gitea, Karakeep, Obsidian).
// Set KNOX_LOCAL_SOURCES=none on a node that only replicates peers.
func LocalSourcesEnabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("KNOX_LOCAL_SOURCES"))) {
case "none", "0", "false", "off":
return false
default:
return true
}
}
// unchanged reports whether path's size+mtime match the last ingest, and
// records the current state. A false read (stat error) never skips.
func (w *Watcher) unchanged(path string) bool {
fi, err := os.Stat(path)
if err != nil {
return false
}
st := fileState{size: fi.Size(), mtime: fi.ModTime().UnixNano()}
if prev, ok := w.lastIngest[path]; ok && prev == st {
return true
}
w.lastIngest[path] = st
return false
}
func (w *Watcher) Start() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// 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.
gossipAddr := ListenAddr()
node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: AdvertiseAddr(), Metrics: w.metrics}
node.OnIngest = func(int) { w.pendingReconcile.Store(true) }
srv := &http.Server{
Addr: gossipAddr,
Handler: httpauth.Middleware(node.Handler()),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
w.gossipSrv = srv
go func() {
log.Printf("[knox] gossip listening on %s (tls=%t auth=%t)", gossipAddr, httpauth.TLSAvailable(), httpauth.Enabled())
if !httpauth.Enabled() && !isLoopbackAddr(gossipAddr) {
log.Printf("[knox] WARNING: %s is reachable beyond this host with no KNOX_AUTH_TOKEN", gossipAddr)
}
if err := httpauth.Serve(srv); err != nil && err != http.ErrServerClosed {
log.Printf("[knox] gossip server: %v", err)
}
}()
// Prometheus scraping on a dedicated port (KNOX_METRICS_ADDR).
metricsAddr := MetricsAddr()
metricsSrv := &http.Server{
Addr: metricsAddr,
Handler: node.Metrics.Handler(),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
w.metricsSrv = metricsSrv
go func() {
log.Printf("[knox] metrics listening on %s", metricsAddr)
if !isLoopbackAddr(metricsAddr) {
log.Printf("[knox] WARNING: %s exposes metrics unauthenticated; scrape it over a private network", metricsAddr)
}
if err := metricsSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[knox] metrics server: %v", err)
}
}()
if peers := PeerAddrs(); len(peers) > 0 {
log.Printf("[knox] gossip peers: %v", peers)
}
w.seed(watcher)
log.Printf("[knox] watching %d directories", len(w.dirs))
if w.vault != "" {
log.Printf("[knox] obsidian vault: %s", w.vault)
}
debounce := newFileDebouncer()
browserTicker := time.NewTicker(browserInterval)
giteaTicker := time.NewTicker(10 * time.Minute)
gitTicker := time.NewTicker(10 * time.Minute)
opencodeTicker := time.NewTicker(opencodeInterval)
karakeepTicker := time.NewTicker(karakeepInterval)
healthTicker := time.NewTicker(healthInterval)
threadTicker := time.NewTicker(10 * time.Minute)
snippetTicker := time.NewTicker(snippetInterval)
gossipTicker := time.NewTicker(gossipInterval)
// A node that only replicates peers (a server with none of the local
// sources) skips the ingest/derive tickers entirely. Nil channels block
// forever, so the select simply never fires for them.
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC, threadC, snippetC <-chan time.Time
if LocalSourcesEnabled() {
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C
threadC, snippetC = threadTicker.C, snippetTicker.C
} else {
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: gossip-only mode, local ingest disabled")
}
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return nil
}
// fsnotify is non-recursive: files appearing inside newly created
// subdirectories would otherwise be invisible to the daemon.
isDir := false
if event.Has(fsnotify.Create) {
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
isDir = true
if err := watcher.Add(event.Name); err != nil {
log.Printf("[knox] cannot watch new dir %s: %v", event.Name, err)
} else {
log.Printf("[knox] watching new dir %s", event.Name)
}
}
}
if event.Has(fsnotify.Remove) {
// Drop any pending ingest for a deleted file. (No tombstone is
// written yet — the entry lingers until reconcile/prune.)
debounce.cancel(event.Name)
continue
}
if isDir || !w.isRelevantEvent(event) {
continue
}
trigger := eventOpName(event.Op)
log.Printf("[knox] %s %s", trigger, filepath.Base(event.Name))
name := event.Name
// An actively-appended log writes every couple of seconds; settle
// longer than the default so it is not fully re-parsed each time.
delay := w.debounce
if strings.HasSuffix(name, ".log") {
delay = logDebounce
}
debounce.schedule(name, delay, func(path string) {
w.ingestFile(path, trigger)
})
case <-browserC:
if !browserRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer browserRunning.Store(false)
w.ingestBrowserHistory()
}()
case <-giteaC:
if !giteaRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer giteaRunning.Store(false)
w.ingestGitea()
}()
case <-gitC:
if !gitRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer gitRunning.Store(false)
w.ingestGit()
}()
case <-opencodeC:
if !opencodeRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer opencodeRunning.Store(false)
w.ingestOpenCodeDB()
}()
case <-karakeepC:
if !karakeepRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer karakeepRunning.Store(false)
w.ingestKarakeep()
}()
case <-healthC:
if !healthRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer healthRunning.Store(false)
w.checkSkillsHealth()
}()
case <-threadC:
if !threadRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer threadRunning.Store(false)
w.autoThread()
}()
case <-snippetC:
if !snippetRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer snippetRunning.Store(false)
w.extractSnippets()
}()
case <-gossipTicker.C:
if !gossipRunning.CompareAndSwap(false, true) {
continue
}
go func() {
defer gossipRunning.Store(false)
w.syncGossip()
}()
case <-w.quit:
log.Printf("[knox] shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if w.gossipSrv != nil {
_ = w.gossipSrv.Shutdown(ctx)
}
if w.metricsSrv != nil {
_ = w.metricsSrv.Shutdown(ctx)
}
return nil
case err, ok := <-watcher.Errors:
if !ok {
return nil
}
log.Printf("[knox] watch error: %v", err)
}
}
}
func (w *Watcher) seed(watcher *fsnotify.Watcher) {
for _, dir := range w.dirs {
if err := w.watchTree(watcher, dir); err != nil {
log.Printf("[knox] cannot watch %s: %v", dir, err)
}
}
// Watch Obsidian vault (every subdirectory, non-recursively mirrored)
if w.vault != "" {
if err := w.watchTree(watcher, w.vault); err != nil {
log.Printf("[knox] cannot watch obsidian vault %s: %v", w.vault, err)
}
}
// Seed existing files anywhere under the watched dirs. fsnotify watches the
// whole tree, so live events cover any depth; this walk covers startup so
// pre-existing nested files (e.g. skills at two+ levels) are indexed too.
for _, dir := range w.dirs {
_ = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil // skip unreadable entries; dirs are handled by the watch
}
for _, ing := range w.fileIngesters {
if MatchesIngester(path, ing.SourceID()) {
w.ingestFileWith(path, ing, "seed")
return nil
}
}
return nil
})
}
// Seed Obsidian notes via the full walk: skips dot-dirs (.trash, .obsidian)
// and covers all depths.
if w.vault != "" {
if notes, err := ingest.NewObsidianIngester(w.vault).IngestAll(); err == nil {
for _, r := range notes {
w.recordResult(r, "seed")
}
}
}
}
// watchTree adds a directory and every non-hidden subdirectory to the watcher,
// mirroring fsnotify's non-recursive API with an explicit walk. Hidden
// directories (.git, .obsidian, .trash) are skipped so their churn doesn't burn
// inotify watches.
func (w *Watcher) watchTree(watcher *fsnotify.Watcher, root string) error {
rootAbs, err := filepath.Abs(root)
if err != nil {
return err
}
if err := watcher.Add(rootAbs); err != nil {
return err
}
log.Printf("[knox] watching %s", rootAbs)
return filepath.WalkDir(rootAbs, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if !d.IsDir() {
return nil
}
if path != rootAbs && strings.HasPrefix(d.Name(), ".") {
return filepath.SkipDir
}
if path == rootAbs {
return nil
}
if err := watcher.Add(path); err != nil {
log.Printf("[knox] cannot watch %s: %v", path, err)
}
return nil
})
}
func (w *Watcher) ingestFile(path, trigger string) {
for _, ing := range w.fileIngesters {
if MatchesIngester(path, ing.SourceID()) {
w.ingestFileWith(path, ing, trigger)
return
}
}
// Obsidian: any .md file in the vault
if w.vault != "" && strings.HasSuffix(path, ".md") && !strings.Contains(path, ".obsidian") {
obs := ingest.NewObsidianFileIngester(w.vault)
w.ingestFileWith(path, obs, trigger)
}
}
func (w *Watcher) ingestFileWith(path string, ing ingest.Ingester, trigger string) {
// Skip before the (expensive) full read when the file is byte-identical to
// the last ingest.
if w.unchanged(path) {
return
}
result, err := ing.Ingest(path)
if err != nil {
log.Printf("[knox] ingest error %s: %v", path, err)
return
}
if result == nil {
return
}
// Staleness check: skip when the signal time is known and unchanged.
// Empty CreatedAt must NOT skip — it would suppress everything.
if result.CreatedAt != "" {
if existing, _ := w.knoxDB.FindEntry(result.Fingerprint); existing != nil && existing.CreatedAt == result.CreatedAt {
return
}
}
w.recordResult(result, trigger)
}
// recordResult persists one ingest result and fires side effects (session
// tracking, golden-thread linking happens inside RecordObservation).
func (w *Watcher) recordResult(result *ingest.IngestResult, trigger string) {
obsID, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
Project: result.Project,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
CreatedAt: result.CreatedAt,
LineStart: result.LineStart,
LineEnd: result.LineEnd,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: trigger,
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
log.Printf("[knox] db error: %v", err)
return
}
if isNew {
log.Printf("[knox] new entry #%d: %s", obsID, result.Title)
} else {
log.Printf("[knox] updated entry #%d: %s", obsID, result.Title)
}
if result.SourceID == "opencode-session" {
sessionID, _ := result.Provenance["session_id"].(string)
if sessionID != "" {
if err := w.knoxDB.UpsertSession(sessionID, result.Project, result.Title, "active"); err != nil {
log.Printf("[knox] session upsert error: %v", err)
}
}
}
}
func (w *Watcher) ingestBrowserHistory() {
log.Printf("[knox] periodic browser history ingest...")
ing := ingest.NewBrowserHistoryIngester()
results, err := ing.IngestAll()
if err != nil {
log.Printf("[knox] browser ingest error: %v", err)
return
}
var newCount, skipped int
for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
if existing != nil && existing.CreatedAt == result.CreatedAt {
skipped++
continue
}
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
CreatedAt: result.CreatedAt,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: "browser_timer",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
continue
}
if isNew {
newCount++
}
}
if newCount > 0 || skipped > 0 {
log.Printf("[knox] browser history: %d new, %d unchanged", newCount, skipped)
}
}
func (w *Watcher) ingestGitea() {
log.Printf("[knox] periodic gitea ingest...")
ing := ingest.NewGiteaIngester()
results, err := ing.IngestAll()
if err != nil {
log.Printf("[knox] gitea ingest error: %v", err)
return
}
var newCount, skipped int
for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
if existing != nil && existing.CreatedAt == result.CreatedAt {
skipped++
continue
}
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
Project: result.Project,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
CreatedAt: result.CreatedAt,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: "gitea_timer",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
continue
}
if isNew {
newCount++
}
}
if newCount > 0 || skipped > 0 {
log.Printf("[knox] gitea: %d new, %d unchanged", newCount, skipped)
}
}
func (w *Watcher) ingestGit() {
log.Printf("[knox] periodic git status ingest...")
ing := ingest.NewGitIngester()
ing.Recursive = true
if v := os.Getenv("KNOX_GIT_ROOTS"); v != "" {
for _, part := range strings.Split(v, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
ing.Roots = append(ing.Roots, part)
}
}
results, err := ing.IngestAll()
if err != nil {
log.Printf("[knox] git ingest error: %v", err)
return
}
var newCount, skipped int
for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
if existing != nil && existing.CreatedAt == result.CreatedAt {
skipped++
continue
}
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
Project: result.Project,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
CreatedAt: result.CreatedAt,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: "git_timer",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
continue
}
if isNew {
newCount++
}
}
if newCount > 0 || skipped > 0 {
log.Printf("[knox] git: %d new, %d unchanged", newCount, skipped)
}
}
// ingestOpenCodeDB sweeps opencode.db, indexing one entry per session. The
// sweep is full every time; RecordObservation collapses unchanged sessions, so
// no watermark is needed and repeated runs are idempotent.
func (w *Watcher) ingestOpenCodeDB() {
results, err := ingest.NewOpenCodeDBIngester().IngestAll()
if err != nil {
log.Printf("[knox] opencode.db ingest error: %v", err)
return
}
var newCount, skipped int
for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
// created_at alone cannot detect a resumed session: resuming appends
// messages without touching the creation time, so compare the summary
// (which carries the transcript) as well.
if existing != nil && existing.CreatedAt == result.CreatedAt && existing.Summary == result.Summary {
skipped++
continue
}
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
Project: result.Project,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
CreatedAt: result.CreatedAt,
LineEnd: result.LineEnd,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: "opencode_db_timer",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
continue
}
if isNew {
newCount++
}
}
if newCount > 0 || skipped > 0 {
log.Printf("[knox] opencode.db: %d new, %d unchanged", newCount, skipped)
}
}
// ingestKarakeep pulls bookmarks (and their crawled article text) from a
// self-hosted Karakeep instance configured via KARAKEEP_URL/KARAKEEP_API_KEY.
func (w *Watcher) ingestKarakeep() {
results, err := ingest.NewKarakeepIngester().IngestAll()
if err != nil {
log.Printf("[knox] karakeep ingest error: %v", err)
return
}
if len(results) == 0 {
return
}
var newCount, skipped int
for _, result := range results {
existing, _ := w.knoxDB.FindEntry(result.Fingerprint)
if existing != nil && existing.CreatedAt == result.CreatedAt {
skipped++
continue
}
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
Fingerprint: result.Fingerprint,
SourceID: result.SourceID,
SourcePath: result.SourcePath,
Project: result.Project,
ContentType: result.ContentType,
Title: result.Title,
Summary: result.Summary,
Content: result.Content,
CreatedAt: result.CreatedAt,
Confidence: result.Confidence,
IngesterVersion: result.IngesterVersion,
Trigger: "karakeep_timer",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
})
if err != nil {
continue
}
if isNew {
newCount++
}
}
if newCount > 0 || skipped > 0 {
log.Printf("[knox] karakeep: %d new, %d unchanged", newCount, skipped)
}
}
// checkSkillsHealth warns when the skills git repo looks broken — the skills
// MCP auto-commits/pushes but hides git errors, so silent breakage (corrupt
// objects, unpushed commits, low disk) would otherwise go unnoticed.
func (w *Watcher) checkSkillsHealth() {
h := skillsrepo.Default()
if h.Healthy() {
return
}
log.Printf("[knox] WARN skills repo unhealthy: %s (head=%s branch=%s ahead=%d behind=%d dirty=%d fsck_ok=%v free=%d) problems=%v",
h.Dir, h.Head, h.Branch, h.Ahead, h.Behind, h.Dirty, h.FsckOK, h.FreeBytes, h.Problems)
}
// autoThread runs the heuristic auto-threader. Disabled entirely when
// KNOX_THREAD_DISABLE is non-empty.
func (w *Watcher) autoThread() {
if os.Getenv("KNOX_THREAD_DISABLE") != "" {
return
}
threader := NewAutoThreader(w.knoxDB)
created, linked, err := threader.AutoThread()
if err != nil {
log.Printf("[knox] auto-thread error: %v", err)
return
}
if created > 0 || linked > 0 {
log.Printf("[knox] auto-thread: %d created, %d linked", created, linked)
}
// Link newly-arrived observations to existing threads (bounded to new obs),
// so sources ingested after a thread was created still get represented.
n, err := w.knoxDB.AutoLinkNewObservations()
if err != nil {
log.Printf("[knox] thread auto-link error: %v", err)
return
}
if n > 0 {
log.Printf("[knox] thread auto-link: %d observation(s) linked", n)
}
}
// extractSnippets runs the LLM-free candidate extractor over opencode sessions.
// It only ever writes *candidates*; curation (encode/reject) is agent-driven via
// MCP. Disabled entirely when KNOX_SNIPPET_DISABLE is non-empty.
func (w *Watcher) extractSnippets() {
if os.Getenv("KNOX_SNIPPET_DISABLE") != "" {
return
}
cands, err := ingest.NewSnippetExtractor().ExtractAll()
if err != nil {
log.Printf("[knox] snippet extract error: %v", err)
return
}
recs := make([]db.SnippetRecord, 0, len(cands))
for _, c := range cands {
recs = append(recs, db.SnippetRecord{
Fingerprint: c.Fingerprint,
Language: c.Language,
Code: c.Code,
Title: c.Title,
Description: c.Description,
Tags: c.Tags,
SourceSession: c.SourceSession,
SourcePath: c.SourcePath,
SourceEntry: c.SourceEntry,
Project: c.Project,
Tool: c.Tool,
Model: c.Model,
PatchHash: c.PatchHash,
Evidence: c.Evidence,
SupersededBy: c.SupersededBy,
Junk: c.Junk,
Kind: c.Kind,
})
}
newCount, err := w.knoxDB.UpsertSnippets(recs)
if err != nil {
log.Printf("[knox] snippet upsert error: %v", err)
return
}
if newCount > 0 {
log.Printf("[knox] snippets: %d new candidate(s) (%d scanned)", newCount, len(cands))
}
}
// syncGossip runs one anti-entropy sweep against configured peers and rebuilds
// derived state if anything new arrived.
func (w *Watcher) syncGossip() {
peers := PeerAddrs()
if len(peers) == 0 {
return
}
pulled := Run(w.knoxDB, w.metrics, peers)
// A pull only appends to the observation log; the entries cache and
// auto-threads are derived state that reconcile rebuilds. Comparing entry
// counts can never trigger this (pushes/pulls never touch entries directly),
// so reconcile fires on the sweep's newly-inserted observation count.
// 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.
pushedIn := w.pendingReconcile.Swap(false)
if pulled > 0 || pushedIn {
created, linked, err := Reconcile(w.knoxDB)
if err != nil {
log.Printf("[knox] gossip reconcile: %v", err)
return
}
log.Printf("[knox] gossip reconcile done: %d created, %d linked after pulling %d obs", created, linked, pulled)
}
}
func (w *Watcher) isRelevantEvent(event fsnotify.Event) bool {
name := filepath.Base(event.Name)
// Opencode session diffs and logs
if strings.HasPrefix(name, "ses_") || strings.HasSuffix(name, ".log") {
return true
}
// Obsidian markdown files
if w.vault != "" && strings.HasSuffix(name, ".md") && !strings.Contains(event.Name, ".obsidian") {
return true
}
return false
}
func MatchesIngester(path, sourceID string) bool {
base := filepath.Base(path)
switch sourceID {
case "opencode-session":
return strings.HasPrefix(base, "ses_") && strings.HasSuffix(base, ".json")
case "opencode-log":
return strings.HasSuffix(base, ".log")
case "skills-catalog":
return base == "SKILL.md"
}
return false
}
func eventOpName(op fsnotify.Op) string {
switch {
case op.Has(fsnotify.Create):
return "inotify:CREATE"
case op.Has(fsnotify.Write):
return "inotify:WRITE"
case op.Has(fsnotify.Chmod):
return "inotify:CHMOD"
case op.Has(fsnotify.Rename):
return "inotify:RENAME"
default:
return "inotify:UNKNOWN"
}
}