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:
@@ -0,0 +1,261 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// KarakeepIngester indexes bookmarks from a self-hosted Karakeep instance via
|
||||
// its REST API. For link bookmarks it also pulls Karakeep's crawled article
|
||||
// text (the "content download" asset) so the full page is searchable in knox.
|
||||
//
|
||||
// Configured entirely by environment: KARAKEEP_URL (e.g.
|
||||
// https://keep.example.com) and KARAKEEP_API_KEY. When either is unset the
|
||||
// source is a no-op.
|
||||
type KarakeepIngester struct {
|
||||
Version string
|
||||
BaseURL string
|
||||
APIKey string
|
||||
MaxPages int
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewKarakeepIngester() *KarakeepIngester {
|
||||
return &KarakeepIngester{
|
||||
Version: "karakeep/v1",
|
||||
BaseURL: strings.TrimRight(os.Getenv("KARAKEEP_URL"), "/"),
|
||||
APIKey: os.Getenv("KARAKEEP_API_KEY"),
|
||||
MaxPages: 25, // 25 * 100 = up to 2500 bookmarks per sweep
|
||||
client: &http.Client{Timeout: 20 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (k *KarakeepIngester) SourceID() string { return "karakeep" }
|
||||
|
||||
// kaAssetCache caches downloaded content assets (assetID -> extracted text) so
|
||||
// unchanged bookmarks are not re-downloaded on every watch tick.
|
||||
var kaAssetCache = struct {
|
||||
sync.Mutex
|
||||
m map[string]string
|
||||
}{m: map[string]string{}}
|
||||
|
||||
func (k *KarakeepIngester) IngestAll() ([]*IngestResult, error) {
|
||||
if k.BaseURL == "" || k.APIKey == "" {
|
||||
return nil, nil // not configured
|
||||
}
|
||||
var results []*IngestResult
|
||||
cursor := ""
|
||||
for page := 0; page < k.MaxPages; page++ {
|
||||
bookmarks, next, err := k.fetchPage(cursor)
|
||||
if err != nil {
|
||||
return results, err
|
||||
}
|
||||
for _, b := range bookmarks {
|
||||
if r := k.toResult(b); r != nil {
|
||||
results = append(results, r)
|
||||
}
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
type kaTag struct {
|
||||
Name string `json:"name"`
|
||||
AttachedBy string `json:"attachedBy"`
|
||||
}
|
||||
|
||||
type kaContent struct {
|
||||
Type string `json:"type"`
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Content string `json:"content"` // inline text for type=text bookmarks
|
||||
ContentAssetID string `json:"contentAssetId"`
|
||||
Author string `json:"author"`
|
||||
Publisher string `json:"publisher"`
|
||||
CrawlStatus string `json:"crawlStatus"`
|
||||
}
|
||||
|
||||
type kaBookmark struct {
|
||||
ID string `json:"id"`
|
||||
Title *string `json:"title"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
ModifiedAt string `json:"modifiedAt"`
|
||||
Archived bool `json:"archived"`
|
||||
Favourited bool `json:"favourited"`
|
||||
Note *string `json:"note"`
|
||||
Summary *string `json:"summary"`
|
||||
Tags []kaTag `json:"tags"`
|
||||
Content kaContent `json:"content"`
|
||||
}
|
||||
|
||||
func (k *KarakeepIngester) fetchPage(cursor string) ([]kaBookmark, string, error) {
|
||||
u := k.BaseURL + "/api/v1/bookmarks?limit=100"
|
||||
if cursor != "" {
|
||||
u += "&cursor=" + cursor
|
||||
}
|
||||
body, err := k.get(u)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var payload struct {
|
||||
Bookmarks []kaBookmark `json:"bookmarks"`
|
||||
NextCursor string `json:"nextCursor"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil, "", fmt.Errorf("karakeep decode: %w", err)
|
||||
}
|
||||
return payload.Bookmarks, payload.NextCursor, nil
|
||||
}
|
||||
|
||||
func (k *KarakeepIngester) get(u string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+k.APIKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := k.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("karakeep GET %s: status %d", u, resp.StatusCode)
|
||||
}
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
}
|
||||
|
||||
// fetchAssetText downloads a content asset (readability-extracted HTML) and
|
||||
// returns plain text, caching by asset id.
|
||||
func (k *KarakeepIngester) fetchAssetText(assetID string) string {
|
||||
kaAssetCache.Lock()
|
||||
if t, ok := kaAssetCache.m[assetID]; ok {
|
||||
kaAssetCache.Unlock()
|
||||
return t
|
||||
}
|
||||
kaAssetCache.Unlock()
|
||||
|
||||
body, err := k.get(k.BaseURL + "/api/v1/assets/" + assetID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
text := htmlToText(string(body))
|
||||
|
||||
kaAssetCache.Lock()
|
||||
kaAssetCache.m[assetID] = text
|
||||
kaAssetCache.Unlock()
|
||||
return text
|
||||
}
|
||||
|
||||
func (k *KarakeepIngester) toResult(b kaBookmark) *IngestResult {
|
||||
url := strings.TrimSpace(b.Content.URL)
|
||||
title := firstNonEmpty(deref(b.Title), b.Content.Title, url, b.ID)
|
||||
if title == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Body text: prefer the crawled article, then inline text bookmark, then
|
||||
// description.
|
||||
var content string
|
||||
switch {
|
||||
case b.Content.ContentAssetID != "":
|
||||
content = k.fetchAssetText(b.Content.ContentAssetID)
|
||||
case b.Content.Type == "text" && b.Content.Content != "":
|
||||
content = htmlToText(b.Content.Content)
|
||||
}
|
||||
if content == "" {
|
||||
content = b.Content.Description
|
||||
}
|
||||
|
||||
summary := firstNonEmpty(deref(b.Note), deref(b.Summary), b.Content.Description, url)
|
||||
if r := []rune(summary); len(r) > 300 {
|
||||
summary = string(r[:300]) + "…"
|
||||
}
|
||||
|
||||
tagNames := make([]string, 0, len(b.Tags))
|
||||
for _, t := range b.Tags {
|
||||
tagNames = append(tagNames, t.Name)
|
||||
}
|
||||
|
||||
confidence := 0.8
|
||||
if b.Favourited {
|
||||
confidence = 0.9
|
||||
}
|
||||
|
||||
createdAt := b.CreatedAt
|
||||
if createdAt == "" {
|
||||
createdAt = b.ModifiedAt
|
||||
}
|
||||
|
||||
return &IngestResult{
|
||||
Fingerprint: FingerprintWithMeta([]byte("karakeep:"+b.ID), map[string]string{"source": "karakeep"}),
|
||||
SourceID: k.SourceID(),
|
||||
SourcePath: url,
|
||||
Project: "",
|
||||
ContentType: "bookmark/" + b.Content.Type,
|
||||
Title: title,
|
||||
Summary: summary,
|
||||
Content: content,
|
||||
CreatedAt: createdAt,
|
||||
Confidence: confidence,
|
||||
IngesterVersion: k.Version,
|
||||
ContentHash: Fingerprint([]byte(b.ModifiedAt + "|" + b.Content.ContentAssetID + "|" + fmt.Sprint(len(content)))),
|
||||
Provenance: map[string]any{
|
||||
"bookmark_id": b.ID,
|
||||
"url": url,
|
||||
"tags": tagNames,
|
||||
"archived": b.Archived,
|
||||
"favourited": b.Favourited,
|
||||
"author": b.Content.Author,
|
||||
"publisher": b.Content.Publisher,
|
||||
"content_len": len(content),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func deref(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(*s)
|
||||
}
|
||||
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if s := strings.TrimSpace(v); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var (
|
||||
htmlScriptStyleRE = regexp.MustCompile(`(?is)<(script|style|noscript|template)[^>]*>.*?</(script|style|noscript|template)>`)
|
||||
htmlTagRE = regexp.MustCompile(`(?s)<[^>]+>`)
|
||||
htmlWSRE = regexp.MustCompile(`\s+`)
|
||||
)
|
||||
|
||||
// htmlToText crudely reduces HTML to searchable text (tags/scripts stripped,
|
||||
// whitespace collapsed).
|
||||
func htmlToText(h string) string {
|
||||
h = htmlScriptStyleRE.ReplaceAllString(h, " ")
|
||||
h = htmlTagRE.ReplaceAllString(h, " ")
|
||||
replacer := strings.NewReplacer(
|
||||
" ", " ", "&", "&", "<", "<", ">", ">",
|
||||
"'", "'", """, `"`, "'", "'", "…", "…",
|
||||
)
|
||||
h = replacer.Replace(h)
|
||||
return strings.TrimSpace(htmlWSRE.ReplaceAllString(h, " "))
|
||||
}
|
||||
Reference in New Issue
Block a user