Files
knox/internal/cmd/ingest.go
T
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

134 lines
3.6 KiB
Go

package cmd
import (
"fmt"
"log"
"path/filepath"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest"
"github.com/david/knox/internal/watch"
"github.com/spf13/cobra"
)
func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command {
var dirs []string
cmd := &cobra.Command{
Use: "ingest",
Short: "One-time full sweep of all sources into the knowledge index",
Run: func(cmd *cobra.Command, args []string) {
if len(dirs) == 0 {
dirs = defaultWatchDirs()
}
ingesters := []ingest.Ingester{
ingest.NewLogIngester(),
ingest.NewSkillsIngester(),
}
var totalNew, totalUpdated int
record := func(result *ingest.IngestResult) {
_, isNew, err := kdb.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: "ingest",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
log.Printf("[knox] db error: %v", err)
return
}
if isNew {
totalNew++
} else {
totalUpdated++
}
if result.SourceID == "opencode-session" {
sessionID, _ := result.Provenance["session_id"].(string)
if sessionID != "" {
kdb.UpsertSession(sessionID, result.Project, result.Title, "active")
}
}
}
for _, ing := range ingesters {
sid := ing.SourceID()
log.Printf("[knox] ingesting %s...", sid)
for _, dir := range dirs {
patterns := []string{
dir + "/*",
dir + "/*/SKILL.md",
}
for _, pattern := range patterns {
entries, _ := filepath.Glob(pattern)
for _, path := range entries {
if !watch.MatchesIngester(path, sid) {
continue
}
result, err := ing.Ingest(path)
if err != nil || result == nil {
continue
}
record(result)
}
}
}
}
// Non-file sources: obsidian vault, browser history, gitea, opencode.db
if vault, err := ingest.DetectObsidianVault(); err == nil {
log.Printf("[knox] ingesting obsidian...")
if results, err := ingest.NewObsidianIngester(vault).IngestAll(); err == nil {
for _, r := range results {
record(r)
}
}
}
log.Printf("[knox] ingesting browser-history...")
if results, err := ingest.NewBrowserHistoryIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
}
log.Printf("[knox] ingesting gitea...")
if results, err := ingest.NewGiteaIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
}
log.Printf("[knox] ingesting karakeep...")
if results, err := ingest.NewKarakeepIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
}
log.Printf("[knox] ingesting opencode.db...")
if results, err := ingest.NewOpenCodeDBIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
}
fmt.Printf("\nIngest complete: %d new entries, %d updated\n", totalNew, totalUpdated)
},
}
cmd.Flags().StringSliceVarP(&dirs, "dir", "d", nil, "Directories to scan (default: opencode storage/log + skills)")
return cmd
}