Files
knox/internal/cmd/ingest.go
T
david 4dd1c2be09
build / test (push) Has been cancelled
build / image (push) Has been cancelled
feat: index reasoning and close the session freshness gap (#18)
Two changes that make the index reflect work as it happens.

Reasoning is now indexed. The model's own justification is where a decision is
explained, and it never appears in the text a reader sees. It is also enormous —
individual parts reach 175 KB — so each part is truncated to 1.2 KB and each
session is budgeted 4 KB. It lands in content (searchable) but stays out of the
summary, which is what search results and MCP output show.

Capturing it exposed a dedupe bug: sessions were skipped when created_at and
summary matched, so content that gained reasoning behind unchanged prose was
never recorded. IngestResult now carries a content hash and the sweep compares
it, which is what the observation layer already used internally.

Freshness: the watcher polls every two minutes, so a finished turn stayed
unsearchable that long. IngestSessionsNow shares the watcher's logic, sweeps
only sessions newer than a stored watermark, and runs in ~45 ms steady state
(a full sweep is ~21 s for 59k messages). The plugin calls it at prompt
admission, fire-and-forget.
2026-11-04 19:38:44 -08:00

158 lines
4.4 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)
}
} else {
log.Printf("[knox] obsidian ingest failed: %v", err)
}
}
log.Printf("[knox] ingesting browser-history...")
if results, err := ingest.NewBrowserHistoryIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
} else {
log.Printf("[knox] browser-history ingest failed: %v", err)
}
log.Printf("[knox] ingesting gitea...")
if results, err := ingest.NewGiteaIngester().IngestAll(); err == nil {
for _, r := range results {
record(r)
}
} else {
log.Printf("[knox] gitea ingest failed: %v", err)
}
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.AddCommand(&cobra.Command{
Use: "sessions",
Short: "Re-index opencode sessions only (fast; what the watcher timer does)",
Long: `Re-index opencode sessions only.
Reads opencode.db and records just the sessions whose content changed. Used by
the OpenCode plugin to close the gap between a finished turn and the knowledge
being searchable, without paying for a full sweep.`,
RunE: func(c *cobra.Command, args []string) error {
created, changed, unchanged, err := watch.IngestSessionsNow(kdb)
if err != nil {
return err
}
fmt.Printf("sessions: %d new, %d changed, %d unchanged\n", created, changed, unchanged)
return nil
},
})
cmd.Flags().StringSliceVarP(&dirs, "dir", "d", nil, "Directories to scan (default: opencode storage/log + skills)")
return cmd
}