Files
knox/internal/cmd/browser.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

118 lines
2.9 KiB
Go

package cmd
import (
"fmt"
"log"
"strings"
"github.com/david/knox/internal/db"
"github.com/david/knox/internal/ingest"
"github.com/spf13/cobra"
)
func NewBrowserCmd(kdb *db.KnoxDB) *cobra.Command {
cmd := &cobra.Command{
Use: "browser",
Short: "Ingest browser history from Chromium and Min into the knowledge index",
Long: `Reads browser history databases (Chromium and Min), fingerprints URLs,
and stores them as observations. Tracks what you've searched for and read.
Run periodically to capture browsing exhaust.`,
RunE: func(c *cobra.Command, args []string) error {
ing := ingest.NewBrowserHistoryIngester()
log.Printf("[knox] ingesting browser history...")
results, err := ing.IngestAll()
if err != nil {
return fmt.Errorf("browser ingest: %w", err)
}
if len(results) == 0 {
fmt.Println("No browser history found (Chromium/Min not detected or empty).")
return nil
}
var newCount, dupCount int
for _, result := range results {
_, isNew, err := kdb.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_ingest",
Provenance: ingest.ProvenanceJSON(result.Provenance),
ContentHash: result.ContentHash,
Content: result.Content,
})
if err != nil {
log.Printf("[knox] db error: %v", err)
continue
}
if isNew {
newCount++
} else {
dupCount++
}
}
fmt.Printf("Browser history: %d new, %d already seen\n", newCount, dupCount)
// Show top domains
domains := make(map[string]int)
for _, r := range results {
domains[extractDomain(r.Summary)]++
}
fmt.Println("\nTop domains:")
for _, d := range topDomains(domains, 10) {
fmt.Printf(" %-40s %d\n", d.Name, d.Count)
}
return nil
},
}
return cmd
}
func topDomains(domains map[string]int, n int) []struct {
Name string
Count int
} {
var sorted []struct {
Name string
Count int
}
for name, count := range domains {
sorted = append(sorted, struct {
Name string
Count int
}{name, count})
}
// Simple bubble sort for small n
for i := 0; i < len(sorted)-1; i++ {
for j := 0; j < len(sorted)-1-i; j++ {
if sorted[j].Count < sorted[j+1].Count {
sorted[j], sorted[j+1] = sorted[j+1], sorted[j]
}
}
}
if len(sorted) > n {
sorted = sorted[:n]
}
return sorted
}
func extractDomain(url string) string {
url = strings.TrimPrefix(url, "https://")
url = strings.TrimPrefix(url, "http://")
parts := strings.Split(url, "/")
if len(parts) > 0 {
return parts[0]
}
return ""
}