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

217 lines
5.3 KiB
Go

package ingest
import (
"bufio"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
var _ Ingester = (*LogIngester)(nil)
type LogIngester struct {
Version string
}
func NewLogIngester() *LogIngester {
return &LogIngester{Version: "log-parser/v2"}
}
func (l *LogIngester) SourceID() string { return "opencode-log" }
var (
sessionIDRE = regexp.MustCompile(`session[=_ ]?([a-zA-Z0-9_-]+)`)
modelRE = regexp.MustCompile(`model[=_ ]?([a-zA-Z0-9_.-]+)`)
agentRE = regexp.MustCompile(`agent[=_ ]?([a-zA-Z0-9_.-]+)`)
levelRE = regexp.MustCompile(`\blevel=([A-Za-z]+)`)
)
// Log lines are structured as `timestamp=... level=... run=... message=...`.
// Only real WARN/ERROR/FATAL lines are "errors"; the previous substring match
// flagged INFO permission lines that merely contained the word "timeout".
var seriousLevels = map[string]bool{"ERROR": true, "WARN": true, "FATAL": true}
func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open log: %w", err)
}
defer f.Close()
var (
sessionIDs []string
models []string
agents []string
signatures []string
totalLines int
errCount int
warnCount int
)
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
totalLines++
if m := sessionIDRE.FindStringSubmatch(line); len(m) > 1 {
sessionIDs = append(sessionIDs, m[1])
}
if m := modelRE.FindStringSubmatch(line); len(m) > 1 {
models = append(models, m[1])
}
if m := agentRE.FindStringSubmatch(line); len(m) > 1 {
agents = append(agents, m[1])
}
m := levelRE.FindStringSubmatch(line)
if len(m) < 2 {
continue
}
level := strings.ToUpper(m[1])
if !seriousLevels[level] {
continue
}
if level == "WARN" {
warnCount++
} else {
errCount++
}
signatures = append(signatures, normalizeLogLine(line))
}
base := filepath.Base(path)
fp := Fingerprint([]byte("log:" + base))
createdAt := ""
if fi, err := os.Stat(path); err == nil {
createdAt = fi.ModTime().UTC().Format(time.RFC3339)
}
uniq := uniqueSorted(signatures)
contentHash := hashSignatures(uniq, errCount, warnCount)
summary := buildLogSummary(uniq, errCount, warnCount)
confidence := 0.6
if errCount > 0 || warnCount > 0 {
confidence = 0.8
}
return &IngestResult{
Fingerprint: fp,
SourceID: l.SourceID(),
SourcePath: base,
ContentType: ".log",
Title: "Log " + base,
Summary: summary,
Content: strings.Join(uniq, "\n"),
CreatedAt: createdAt,
Confidence: confidence,
IngesterVersion: l.Version,
LineEnd: totalLines,
ContentHash: contentHash,
Provenance: map[string]any{
"session_ids": uniqueSlice(sessionIDs),
"models": uniqueSlice(models),
"agents": uniqueSlice(agents),
"error_count": errCount,
"warn_count": warnCount,
"errors_sample": firstN(uniq, 5),
"file_size": fmt.Sprintf("%d lines", totalLines),
},
}, nil
}
// Normalization patterns strip values that change between identical log events
// so the same error yields the same signature.
var (
tsPrefixRE = regexp.MustCompile(`^timestamp=\S+\s*`)
runRE = regexp.MustCompile(`run=[0-9a-fA-F]+`)
sesRE = regexp.MustCompile(`ses_[A-Za-z0-9]+`)
msgRE = regexp.MustCompile(`msg_[A-Za-z0-9]+`)
hexRE = regexp.MustCompile(`\b[0-9a-fA-F]{6,}\b`)
numRE = regexp.MustCompile(`[0-9]+`)
)
func normalizeLogLine(line string) string {
s := tsPrefixRE.ReplaceAllString(line, "")
s = runRE.ReplaceAllString(s, "run=<RUN>")
s = sesRE.ReplaceAllString(s, "<SES>")
s = msgRE.ReplaceAllString(s, "<MSG>")
s = hexRE.ReplaceAllString(s, "<HEX>")
s = numRE.ReplaceAllString(s, "<N>")
s = strings.Join(strings.Fields(s), " ")
return truncate(s, 160)
}
// hashSignatures is the change signal: it depends only on the set of distinct
// error signatures and the level counts — not on total line count or ordering.
func hashSignatures(sigs []string, errCount, warnCount int) string {
h := sha256.New()
for _, s := range sigs {
h.Write([]byte(s))
h.Write([]byte{'\n'})
}
fmt.Fprintf(h, "E=%d W=%d", errCount, warnCount)
return fmt.Sprintf("%x", h.Sum(nil)[:8])
}
func buildLogSummary(sigs []string, errCount, warnCount int) string {
if errCount == 0 && warnCount == 0 {
return "no errors"
}
var b strings.Builder
fmt.Fprintf(&b, "levels: E%d W%d", errCount, warnCount)
if len(sigs) > 0 {
b.WriteString(" | err: ")
b.WriteString(strings.Join(firstN(sigs, 5), " ;; "))
}
return b.String()
}
// uniqueSorted returns de-duplicated, lexicographically sorted signatures.
func uniqueSorted(items []string) []string {
seen := make(map[string]bool)
var out []string
for _, s := range items {
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
sort.Strings(out)
return out
}
func firstN(items []string, n int) []string {
if len(items) > n {
return items[:n]
}
return items
}
func uniqueJoin(items []string, max int) string {
uniq := uniqueSlice(items)
if len(uniq) > max {
uniq = uniq[:max]
}
return strings.Join(uniq, ", ")
}
func uniqueSlice(items []string) []string {
seen := make(map[string]bool)
var uniq []string
for _, s := range items {
if !seen[s] {
seen[s] = true
uniq = append(uniq, s)
}
}
return uniq
}