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

343 lines
8.5 KiB
Go

package ingest
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/david/knox/internal/noise"
_ "modernc.org/sqlite"
)
const minHistoryPath = ".config/Min/BrowserHistory.db"
// chromiumBases are Chromium-family browser config roots. Each may hold a
// "Default" and/or "Profile *" user profile containing a History database.
var chromiumBases = []string{
".config/chromium",
".config/google-chrome",
".config/google-chrome-beta",
".config/google-chrome-unstable",
".config/google-chrome-for-testing",
".config/brave-browser",
".config/BraveSoftware/Brave-Browser",
".config/microsoft-edge",
".config/microsoft-edge-dev",
".config/vivaldi",
".config/vivaldi-snapshot",
".config/net.imput.helium",
}
// firefoxBaseGlobs are directories whose immediate subdirectories are Firefox
// profiles holding places.sqlite (native, flatpak, and snap layouts).
var firefoxBaseGlobs = []string{
".mozilla/firefox",
"snap/firefox/common/.mozilla/firefox",
".var/app/org.mozilla.firefox/.mozilla/firefox",
}
type BrowserHistoryIngester struct {
Version string
}
func NewBrowserHistoryIngester() *BrowserHistoryIngester {
return &BrowserHistoryIngester{Version: "browser-history/v1"}
}
func (b *BrowserHistoryIngester) SourceID() string { return "browser-history" }
type historyRow struct {
URL string
Title string
VisitTime time.Time
VisitCount int
}
func (b *BrowserHistoryIngester) IngestAll() ([]*IngestResult, error) {
home, _ := os.UserHomeDir()
var results []*IngestResult
// Chromium-family (chromium, chrome*, brave, edge, vivaldi, helium), across
// every user profile.
for _, path := range chromiumHistoryPaths(home) {
cr, err := b.ingestChromium(path)
if err == nil {
results = append(results, cr...)
}
}
// Min
minResults, err := b.ingestMin(filepath.Join(home, minHistoryPath))
if err == nil {
results = append(results, minResults...)
}
// Firefox (places.sqlite), across every profile.
for _, path := range firefoxPlacesPaths(home) {
ff, err := b.ingestFirefox(path)
if err == nil {
results = append(results, ff...)
}
}
return results, nil
}
// chromiumHistoryPaths expands each Chromium-family base into its Default and
// Profile * History databases.
func chromiumHistoryPaths(home string) []string {
var paths []string
for _, base := range chromiumBases {
root := filepath.Join(home, base)
for _, pat := range []string{"Default/History", "Profile */History"} {
matches, _ := filepath.Glob(filepath.Join(root, pat))
paths = append(paths, matches...)
}
}
return paths
}
// firefoxPlacesPaths finds places.sqlite in every Firefox profile.
func firefoxPlacesPaths(home string) []string {
var paths []string
for _, base := range firefoxBaseGlobs {
matches, _ := filepath.Glob(filepath.Join(home, base, "*", "places.sqlite"))
paths = append(paths, matches...)
}
return paths
}
func (b *BrowserHistoryIngester) ingestChromium(path string) ([]*IngestResult, error) {
if !fileExists(path) {
return nil, nil
}
// Copy to avoid lock issues (Chromium uses WAL)
tmp := path + ".knox_tmp"
if err := copyFile(path, tmp); err != nil {
return nil, fmt.Errorf("copy chromium db: %w", err)
}
defer os.Remove(tmp)
db, err := sql.Open("sqlite", tmp)
if err != nil {
return nil, fmt.Errorf("open chromium copy: %w", err)
}
defer db.Close()
rows, err := db.Query(
`SELECT url, COALESCE(title,''), last_visit_time, visit_count
FROM urls
WHERE last_visit_time > 0
ORDER BY last_visit_time DESC
LIMIT 1000`,
)
if err != nil {
// Table might not exist or schema mismatch
return nil, fmt.Errorf("query chromium urls: %w", err)
}
defer rows.Close()
var results []*IngestResult
for rows.Next() {
var url, title string
var visitTimeMicro int64
var visitCount int
if err := rows.Scan(&url, &title, &visitTimeMicro, &visitCount); err != nil {
continue
}
// Chromium webkit time: microseconds since 1601-01-01 UTC
visitTime := webkitToTime(visitTimeMicro)
if result := b.makeResult(url, title, visitTime, visitCount); result != nil {
results = append(results, result)
}
}
return results, nil
}
func (b *BrowserHistoryIngester) ingestMin(path string) ([]*IngestResult, error) {
if !fileExists(path) {
return nil, nil
}
tmp := path + ".knox_tmp"
if err := copyFile(path, tmp); err != nil {
return nil, fmt.Errorf("copy min db: %w", err)
}
defer os.Remove(tmp)
db, err := sql.Open("sqlite", tmp)
if err != nil {
return nil, fmt.Errorf("open min copy: %w", err)
}
defer db.Close()
rows, err := db.Query(
`SELECT url, COALESCE(title,''), timestamp
FROM history
ORDER BY timestamp DESC
LIMIT 1000`,
)
if err != nil {
return nil, fmt.Errorf("query min history: %w", err)
}
defer rows.Close()
var results []*IngestResult
for rows.Next() {
var url, title string
var ts int64
if err := rows.Scan(&url, &title, &ts); err != nil {
continue
}
visitTime := time.Unix(ts, 0)
if result := b.makeResult(url, title, visitTime, 1); result != nil {
results = append(results, result)
}
}
return results, nil
}
// ingestFirefox reads a Firefox places.sqlite. Unlike Chromium, last_visit_date
// is a Unix (PRTime) microsecond value and visits can be hidden.
func (b *BrowserHistoryIngester) ingestFirefox(path string) ([]*IngestResult, error) {
if !fileExists(path) {
return nil, nil
}
tmp := path + ".knox_tmp"
if err := copyFile(path, tmp); err != nil {
return nil, fmt.Errorf("copy firefox db: %w", err)
}
defer os.Remove(tmp)
db, err := sql.Open("sqlite", tmp)
if err != nil {
return nil, fmt.Errorf("open firefox copy: %w", err)
}
defer db.Close()
rows, err := db.Query(
`SELECT url, COALESCE(title,''), last_visit_date, COALESCE(visit_count,0)
FROM moz_places
WHERE last_visit_date > 0 AND COALESCE(hidden,0) = 0
ORDER BY last_visit_date DESC
LIMIT 1000`,
)
if err != nil {
return nil, fmt.Errorf("query firefox places: %w", err)
}
defer rows.Close()
var results []*IngestResult
for rows.Next() {
var url, title string
var visitMicros int64
var visitCount int
if err := rows.Scan(&url, &title, &visitMicros, &visitCount); err != nil {
continue
}
visitTime := time.UnixMicro(visitMicros)
if result := b.makeResult(url, title, visitTime, visitCount); result != nil {
results = append(results, result)
}
}
return results, nil
}
func (b *BrowserHistoryIngester) makeResult(url, title string, visitTime time.Time, visitCount int) *IngestResult {
if url == "" {
return nil
}
// Skip chrome://, about://, file://, devtools and extension pages
if strings.HasPrefix(url, "chrome://") || strings.HasPrefix(url, "about:") ||
strings.HasPrefix(url, "file://") || strings.HasPrefix(url, "devtools://") ||
strings.HasPrefix(url, "chrome-extension://") || strings.HasPrefix(url, "moz-extension://") ||
strings.HasPrefix(url, "place:") {
return nil
}
if noise.IsNoisyURL(url) {
return nil
}
displayTitle := title
if displayTitle == "" {
displayTitle = extractDomain(url)
}
fp := Fingerprint([]byte(url))
confidence := 0.6
if visitCount > 5 {
confidence = 0.9
} else if visitCount > 1 {
confidence = 0.7
}
return &IngestResult{
Fingerprint: fp,
SourceID: b.SourceID(),
SourcePath: url,
ContentType: "url",
Title: displayTitle,
Summary: url,
CreatedAt: visitTime.Format(time.RFC3339),
Confidence: confidence,
IngesterVersion: b.Version,
// A URL is the same knowledge however many times it is visited, and the
// same URL recurs across browsers with different visit times — so dedup
// on the URL, not on the visit timestamp (which otherwise re-appends
// every tick).
ContentHash: fp,
Provenance: map[string]any{
"url": url,
"visit_count": visitCount,
"visited_at": visitTime.Format(time.RFC3339),
},
}
}
// webkitToTime converts Chromium webkit timestamp (µs since 1601-01-01) to time.Time
func webkitToTime(micros int64) time.Time {
// WebKit epoch: 1601-01-01 UTC
// Unix epoch: 1970-01-01 UTC
// Difference: 11644473600 seconds
secs := micros / 1_000_000
if secs < 11644473600 {
return time.Time{}
}
return time.Unix(secs-11644473600, 0)
}
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 url
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func copyFile(src, dst string) error {
data, err := os.ReadFile(src)
if err != nil {
return err
}
return os.WriteFile(dst, data, 0644)
}