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>
This commit was merged in pull request #7.
This commit is contained in:
@@ -299,7 +299,7 @@ func TestHandleBatchRejectsHugeBody(t *testing.T) {
|
||||
rows := []db.GossipObservation{{
|
||||
NodeID: "0123456789abcdef0123456789abcdef", HCL: 1,
|
||||
Fingerprint: "fp:huge", SourceID: "test", Title: "t",
|
||||
Summary: strings.Repeat("x", 5<<20), // 5 MiB summary
|
||||
Summary: strings.Repeat("x", 5<<20), // 5 MiB summary
|
||||
CollectedAt: "2026-08-29T00:00:00Z",
|
||||
}}
|
||||
body, _ := json.Marshal(rows)
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/david/knox/internal/db"
|
||||
"github.com/david/knox/internal/index"
|
||||
"github.com/david/knox/internal/noise"
|
||||
)
|
||||
|
||||
// AutoThreader promotes high-intent topic clusters into knowledge threads.
|
||||
@@ -39,6 +40,7 @@ var workSources = map[string]bool{
|
||||
"opencode-session": true,
|
||||
"obsidian": true,
|
||||
"filesystem": true,
|
||||
"karakeep": true,
|
||||
}
|
||||
|
||||
// NewAutoThreader reads the tuning knobs from the environment. All have
|
||||
@@ -68,6 +70,9 @@ func (t *AutoThreader) AutoThread() (created, linked int, err error) {
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
// Refocus: denylisted webapp browsing is not a knowledge signal, so it must
|
||||
// not seed clusters.
|
||||
entries = dropNoisyBrowser(entries)
|
||||
if len(entries) == 0 {
|
||||
return 0, 0, nil
|
||||
}
|
||||
@@ -81,6 +86,10 @@ func (t *AutoThreader) AutoThread() (created, linked int, err error) {
|
||||
if len(fps) == 0 || !t.crossesBar(c, fps, now) {
|
||||
continue
|
||||
}
|
||||
// Deny: never create/extend a thread whose topic is a denylisted webapp.
|
||||
if noise.IsDeniedTopic(c.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Fold into the exact thread this cluster keyed to (idempotent across
|
||||
// nodes/reconciles); otherwise fall back to the keyword heuristic which
|
||||
@@ -279,6 +288,19 @@ func (t *AutoThreader) motivation(c index.TopicCluster, fps []string) string {
|
||||
|
||||
// --- small helpers ---------------------------------------------------------
|
||||
|
||||
// dropNoisyBrowser removes browser-history entries: browsing is context, not
|
||||
// thread membership, so it must not seed clusters either.
|
||||
func dropNoisyBrowser(entries []db.Entry) []db.Entry {
|
||||
out := make([]db.Entry, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if e.SourceID == "browser-history" {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func fingerprints(entries []db.Entry) []string {
|
||||
seen := make(map[string]bool)
|
||||
var out []string
|
||||
|
||||
+255
-5
@@ -14,14 +14,29 @@ import (
|
||||
"github.com/david/knox/internal/db"
|
||||
"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
|
||||
gossipInterval = 1 * time.Minute
|
||||
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
|
||||
@@ -29,6 +44,7 @@ type Watcher struct {
|
||||
debounce time.Duration
|
||||
fileIngesters []ingest.Ingester
|
||||
metrics *metrics.Metrics
|
||||
lastIngest map[string]fileState
|
||||
}
|
||||
|
||||
// fileDebouncer schedules one ingest per path a settle-window after the last
|
||||
@@ -79,14 +95,29 @@ func New(kdb *db.KnoxDB, dirs []string) *Watcher {
|
||||
vault: vault,
|
||||
debounce: 2 * time.Second,
|
||||
fileIngesters: []ingest.Ingester{
|
||||
ingest.NewSessionDiffIngester(),
|
||||
ingest.NewLogIngester(),
|
||||
ingest.NewSkillsIngester(),
|
||||
},
|
||||
metrics: metrics.New(kdb, "knox"),
|
||||
metrics: metrics.New(kdb, "knox"),
|
||||
lastIngest: make(map[string]fileState),
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -131,9 +162,14 @@ func (w *Watcher) Start() error {
|
||||
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)
|
||||
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
|
||||
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -169,7 +205,13 @@ func (w *Watcher) Start() error {
|
||||
trigger := eventOpName(event.Op)
|
||||
log.Printf("[knox] %s %s", trigger, filepath.Base(event.Name))
|
||||
name := event.Name
|
||||
debounce.schedule(name, w.debounce, func(path string) {
|
||||
// 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)
|
||||
})
|
||||
|
||||
@@ -197,6 +239,30 @@ func (w *Watcher) Start() error {
|
||||
defer gitRunning.Store(false)
|
||||
w.ingestGit()
|
||||
}()
|
||||
case <-opencodeTicker.C:
|
||||
if !opencodeRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer opencodeRunning.Store(false)
|
||||
w.ingestOpenCodeDB()
|
||||
}()
|
||||
case <-karakeepTicker.C:
|
||||
if !karakeepRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer karakeepRunning.Store(false)
|
||||
w.ingestKarakeep()
|
||||
}()
|
||||
case <-healthTicker.C:
|
||||
if !healthRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer healthRunning.Store(false)
|
||||
w.checkSkillsHealth()
|
||||
}()
|
||||
case <-threadTicker.C:
|
||||
if !threadRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
@@ -205,6 +271,14 @@ func (w *Watcher) Start() error {
|
||||
defer threadRunning.Store(false)
|
||||
w.autoThread()
|
||||
}()
|
||||
case <-snippetTicker.C:
|
||||
if !snippetRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
defer snippetRunning.Store(false)
|
||||
w.extractSnippets()
|
||||
}()
|
||||
case <-gossipTicker.C:
|
||||
if !gossipRunning.CompareAndSwap(false, true) {
|
||||
continue
|
||||
@@ -314,6 +388,12 @@ func (w *Watcher) ingestFile(path, trigger string) {
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -352,6 +432,8 @@ func (w *Watcher) recordResult(result *ingest.IngestResult, trigger string) {
|
||||
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)
|
||||
@@ -401,6 +483,8 @@ func (w *Watcher) ingestBrowserHistory() {
|
||||
IngesterVersion: result.IngesterVersion,
|
||||
Trigger: "browser_timer",
|
||||
Provenance: ingest.ProvenanceJSON(result.Provenance),
|
||||
ContentHash: result.ContentHash,
|
||||
Content: result.Content,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -443,6 +527,8 @@ func (w *Watcher) ingestGitea() {
|
||||
IngesterVersion: result.IngesterVersion,
|
||||
Trigger: "gitea_timer",
|
||||
Provenance: ingest.ProvenanceJSON(result.Provenance),
|
||||
ContentHash: result.ContentHash,
|
||||
Content: result.Content,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -495,6 +581,8 @@ func (w *Watcher) ingestGit() {
|
||||
IngesterVersion: result.IngesterVersion,
|
||||
Trigger: "git_timer",
|
||||
Provenance: ingest.ProvenanceJSON(result.Provenance),
|
||||
ContentHash: result.ContentHash,
|
||||
Content: result.Content,
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -508,6 +596,113 @@ func (w *Watcher) ingestGit() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
@@ -523,6 +718,61 @@ func (w *Watcher) autoThread() {
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user