chore: checkpoint uncommitted work before session store fix

Pre-existing work-in-progress in the tree: karakeep, snippets,
skills-health and redaction ingesters, the opencode.db session sweep,
gossip and metrics changes. Checkpointed as-is so the adapter fix in the
next commit stays reviewable on its own.
This commit is contained in:
2026-11-01 13:33:36 -08:00
parent 876d2aa45f
commit edf6c03a7c
43 changed files with 6828 additions and 492 deletions
+120 -35
View File
@@ -8,37 +8,35 @@ import (
"strings"
"time"
"github.com/david/knox/internal/noise"
_ "modernc.org/sqlite"
)
const (
chromiumHistoryPath = ".config/chromium/Default/History"
minHistoryPath = ".config/Min/BrowserHistory.db"
)
const minHistoryPath = ".config/Min/BrowserHistory.db"
// noiseURLPatterns are URLs that represent navigation noise rather than knowledge.
var noiseURLPatterns = []string{
"opencode.ai",
"auth.opencode.ai",
"github.com/login/oauth/authorize",
"accounts.google.com",
"google.com/accounts",
"kagi.com",
"chatgpt.com",
// knox indexing its own web UI is self-referential noise
"localhost:8924",
"localhost:18925",
"127.0.0.1:8924",
"127.0.0.1:18925",
// 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",
}
func noiseURL(url string) bool {
for _, p := range noiseURLPatterns {
if strings.Contains(url, p) {
return true
}
}
return false
// 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 {
@@ -62,23 +60,56 @@ func (b *BrowserHistoryIngester) IngestAll() ([]*IngestResult, error) {
home, _ := os.UserHomeDir()
var results []*IngestResult
// Chromium
chromiumDB := filepath.Join(home, chromiumHistoryPath)
cr, err := b.ingestChromium(chromiumDB)
if err == nil {
results = append(results, cr...)
// 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
minDB := filepath.Join(home, minHistoryPath)
minResults, err := b.ingestMin(minDB)
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
@@ -173,19 +204,68 @@ func (b *BrowserHistoryIngester) ingestMin(path string) ([]*IngestResult, error)
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
// 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, "chrome-extension://") || strings.HasPrefix(url, "moz-extension://") ||
strings.HasPrefix(url, "place:") {
return nil
}
if noiseURL(url) {
if noise.IsNoisyURL(url) {
return nil
}
@@ -213,6 +293,11 @@ func (b *BrowserHistoryIngester) makeResult(url, title string, visitTime time.Ti
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,
+40
View File
@@ -0,0 +1,40 @@
package ingest
import (
"os"
"path/filepath"
"testing"
)
func touch(t *testing.T, path string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
}
func TestChromiumHistoryPaths(t *testing.T) {
home := t.TempDir()
touch(t, filepath.Join(home, ".config/net.imput.helium/Default/History"))
touch(t, filepath.Join(home, ".config/google-chrome/Profile 1/History"))
touch(t, filepath.Join(home, ".config/BraveSoftware/Brave-Browser/Default/History"))
got := chromiumHistoryPaths(home)
if len(got) != 3 {
t.Fatalf("got %d paths, want 3: %v", len(got), got)
}
}
func TestFirefoxPlacesPaths(t *testing.T) {
home := t.TempDir()
touch(t, filepath.Join(home, ".mozilla/firefox/wuuvr9ed.default-release/places.sqlite"))
touch(t, filepath.Join(home, "snap/firefox/common/.mozilla/firefox/abc.default/places.sqlite"))
got := firefoxPlacesPaths(home)
if len(got) != 2 {
t.Fatalf("got %d paths, want 2: %v", len(got), got)
}
}
+59
View File
@@ -157,6 +157,10 @@ func (g *GitIngester) repoToResult(repoPath string) *IngestResult {
createdAt := status.LastCommit
// Carry the repo's README + config source so an agent can see what the repo
// actually contains, not just its last commit.
content := repoContent(repoPath)
return &IngestResult{
Fingerprint: fp,
SourceID: g.SourceID(),
@@ -165,9 +169,13 @@ func (g *GitIngester) repoToResult(repoPath string) *IngestResult {
ContentType: "git-status",
Title: name,
Summary: summary,
Content: content,
CreatedAt: createdAt,
Confidence: 0.9,
IngesterVersion: g.Version,
// Change signal covers status AND content, so status flips (dirty,
// ahead/behind) and code changes both refresh; unchanged repos no-op.
ContentHash: Fingerprint([]byte(fmt.Sprintf("git|%s|%s|%d|%d|%d", status.Head, content, status.Dirty, status.Ahead, status.Behind))),
Provenance: map[string]any{
"type": "git_status",
"path": repoPath,
@@ -178,10 +186,61 @@ func (g *GitIngester) repoToResult(repoPath string) *IngestResult {
"behind": status.Behind,
"last_commit": status.LastCommit,
"subject": status.Subject,
"content_len": len(content),
},
}
}
// Bounded repo content limits (kept small so a 10-minute sweep over many repos
// stays cheap).
const (
maxRepoContentBytes = 64 * 1024
maxRepoFileBytes = 16 * 1024
)
// repoContent assembles a bounded digest of a repository: its README, a
// tracked-file listing, and the contents of infrastructure/config files
// (Terraform, and common homelab formats). Empty when nothing is readable.
func repoContent(repoPath string) string {
var b strings.Builder
for _, name := range []string{"README.md", "README.rst", "README.txt", "README", "readme.md"} {
if data, err := os.ReadFile(filepath.Join(repoPath, name)); err == nil {
b.WriteString("## " + name + "\n")
b.WriteString(truncate(string(data), maxRepoFileBytes))
b.WriteString("\n\n")
break
}
}
if out, err := gitOut(repoPath, "ls-files"); err == nil && out != "" {
b.WriteString("## files\n")
b.WriteString(truncate(out, 4096))
b.WriteString("\n\n")
}
// Contents of infra/config files, newest-relevant first (git order).
files, _ := gitOut(repoPath, "ls-files", "--", "*.tf", "*.tfvars", "*.hcl", "*.yaml", "*.yml", "*.toml")
for _, f := range strings.Split(files, "\n") {
f = strings.TrimSpace(f)
if f == "" {
continue
}
if b.Len() >= maxRepoContentBytes {
break
}
data, err := os.ReadFile(filepath.Join(repoPath, f))
if err != nil {
continue
}
b.WriteString("## " + f + "\n")
b.WriteString(truncate(string(data), maxRepoFileBytes))
b.WriteString("\n\n")
}
return strings.TrimSpace(b.String())
}
func gitStatus(repoPath string) GitStatus {
out, err := gitOut(repoPath, "status", "--porcelain")
if err != nil {
+7
View File
@@ -20,6 +20,13 @@ type IngestResult struct {
Confidence float64
IngesterVersion string
Provenance map[string]any
// ContentHash is an optional stable hash of the result's *meaningful*
// content. When set, the index treats an unchanged hash as "same knowledge"
// even if the source grew (e.g. a log with the same error set).
ContentHash string
// Content is the full searchable body. Summary stays a short preview; this
// is what full-text search matches against.
Content string
}
type Ingester interface {
+261
View File
@@ -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(
"&nbsp;", " ", "&amp;", "&", "&lt;", "<", "&gt;", ">",
"&#39;", "'", "&quot;", `"`, "&#x27;", "'", "&hellip;", "…",
)
h = replacer.Replace(h)
return strings.TrimSpace(htmlWSRE.ReplaceAllString(h, " "))
}
+56
View File
@@ -0,0 +1,56 @@
package ingest
import (
"strings"
"testing"
)
func TestHTMLToText(t *testing.T) {
in := `<div id="readability-page-1"><article><h1>Hello</h1>` +
`<script>evil()</script><style>.x{}</style>` +
`<p>A &amp; B &#39;quoted&#39;</p></article></div>`
out := htmlToText(in)
if strings.Contains(out, "evil()") || strings.Contains(out, ".x{}") {
t.Fatalf("script/style not stripped: %q", out)
}
for _, want := range []string{"Hello", "A & B", "'quoted'"} {
if !strings.Contains(out, want) {
t.Fatalf("missing %q in %q", want, out)
}
}
}
func TestKarakeepToResult(t *testing.T) {
title := "My Link"
k := &KarakeepIngester{Version: "test"}
b := kaBookmark{
ID: "bm1",
CreatedAt: "2026-01-02T03:04:05Z",
ModifiedAt: "2026-01-02T03:04:05Z",
Title: &title,
Tags: []kaTag{{Name: "zigbee"}},
Content: kaContent{Type: "link", URL: "https://example.com/a", Description: "short desc"},
}
r := k.toResult(b)
if r == nil {
t.Fatal("nil result")
}
if r.SourceID != "karakeep" || r.Title != "My Link" || r.SourcePath != "https://example.com/a" {
t.Fatalf("unexpected mapping: %+v", r)
}
// No asset and no inline text -> content falls back to description.
if r.Content != "short desc" {
t.Fatalf("content=%q, want description fallback", r.Content)
}
if r.Fingerprint == "" || r.ContentHash == "" {
t.Fatal("fingerprint/content hash must be set")
}
}
func TestKarakeepUnconfigured(t *testing.T) {
k := &KarakeepIngester{Version: "test"} // no BaseURL/APIKey
got, err := k.IngestAll()
if err != nil || got != nil {
t.Fatalf("unconfigured ingester should no-op, got %v %v", got, err)
}
}
+110 -32
View File
@@ -2,10 +2,12 @@ package ingest
import (
"bufio"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
@@ -17,19 +19,23 @@ type LogIngester struct {
}
func NewLogIngester() *LogIngester {
return &LogIngester{Version: "log-parser/v1"}
return &LogIngester{Version: "log-parser/v2"}
}
func (l *LogIngester) SourceID() string { return "opencode-log" }
var (
sessionIDRE = regexp.MustCompile(`session[=_ ]?([a-zA-Z0-9_-]+)`)
projectIDRE = regexp.MustCompile(`project[=_ ]?([a-zA-Z0-9_.-]+)`)
modelRE = regexp.MustCompile(`model[=_ ]?([a-zA-Z0-9_.-]+)`)
agentRE = regexp.MustCompile(`agent[=_ ]?([a-zA-Z0-9_.-]+)`)
errorRE = regexp.MustCompile(`(?i)(error|fail|exception|panic|timeout)`)
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 {
@@ -41,12 +47,14 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
sessionIDs []string
models []string
agents []string
errors []string
signatures []string
totalLines int
firstError 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++
@@ -60,39 +68,37 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
if m := agentRE.FindStringSubmatch(line); len(m) > 1 {
agents = append(agents, m[1])
}
if errorRE.MatchString(line) {
if len(errors) == 0 {
firstError = totalLines
}
errors = append(errors, truncate(line, 120))
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))
title := fmt.Sprintf("Log %s (%d lines)", base, totalLines)
createdAt := ""
if fi, err := os.Stat(path); err == nil {
createdAt = fi.ModTime().UTC().Format(time.RFC3339)
}
var summaryParts []string
if len(sessionIDs) > 0 {
summaryParts = append(summaryParts, fmt.Sprintf("sessions: %s", uniqueJoin(sessionIDs, 5)))
}
if len(models) > 0 {
summaryParts = append(summaryParts, fmt.Sprintf("models: %s", uniqueJoin(models, 3)))
}
if len(errors) > 0 {
summaryParts = append(summaryParts, fmt.Sprintf("%d errors (line %d)", len(errors), firstError))
}
summary := strings.Join(summaryParts, " | ")
if summary == "" {
summary = fmt.Sprintf("%d lines", totalLines)
}
uniq := uniqueSorted(signatures)
contentHash := hashSignatures(uniq, errCount, warnCount)
summary := buildLogSummary(uniq, errCount, warnCount)
confidence := 0.6
if len(errors) > 0 {
if errCount > 0 || warnCount > 0 {
confidence = 0.8
}
@@ -101,22 +107,94 @@ func (l *LogIngester) Ingest(path string) (*IngestResult, error) {
SourceID: l.SourceID(),
SourcePath: base,
ContentType: ".log",
Title: title,
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": len(errors),
"file_size": fmt.Sprintf("%d lines", totalLines),
"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 {
+70
View File
@@ -0,0 +1,70 @@
package ingest
import (
"os"
"path/filepath"
"testing"
)
func writeTempLog(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "test.log")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
return path
}
// INFO lines that merely contain the substring "timeout" must not be counted as
// errors (the old substring matcher flagged them) and must not appear in the
// content hash.
func TestLogIgnoresInfoTimeoutSubstring(t *testing.T) {
content := "" +
`timestamp=2026-10-01T00:00:00.000Z level=INFO run=aaaa message=evaluated permission=bash pattern="timeout 120 ssh foo"` + "\n" +
`timestamp=2026-10-01T00:00:01.000Z level=INFO run=bbbb message=evaluated permission=bash pattern="timeout 5 curl bar"` + "\n"
r, err := NewLogIngester().Ingest(writeTempLog(t, content))
if err != nil {
t.Fatal(err)
}
if r.Summary != "no errors" {
t.Fatalf("summary=%q, want 'no errors'", r.Summary)
}
if r.Provenance["error_count"].(int) != 0 {
t.Fatalf("error_count=%v, want 0", r.Provenance["error_count"])
}
}
// The content hash must be stable across volatile differences (timestamps, run
// ids, session/message ids, line numbers, extra INFO) and change only when the
// distinct error set changes.
func TestLogContentHashStability(t *testing.T) {
base := `[] level=ERROR run=aaaa session.id=ses_abc123 messageID=msg_zzz999 error="Not Found"` + "\n"
a := `timestamp=2026-10-01T00:00:00.000Z ` + base
// Same error, different volatile values, plus unrelated INFO noise.
b := `timestamp=2026-10-02T12:34:56.789Z ` + base +
`timestamp=2026-10-02T12:34:57.000Z level=INFO run=cccc message="resolved path" arg=timeout` + "\n"
l := NewLogIngester()
ra, err := l.Ingest(writeTempLog(t, a))
if err != nil {
t.Fatal(err)
}
rb, err := l.Ingest(writeTempLog(t, b))
if err != nil {
t.Fatal(err)
}
if ra.ContentHash != rb.ContentHash {
t.Fatalf("hash should be stable: %s != %s", ra.ContentHash, rb.ContentHash)
}
// A genuinely new distinct error changes the hash.
c := a + `timestamp=2026-10-01T00:00:05.000Z level=WARN run=dddd message="server unavailable" key=docker status=failed` + "\n"
rc, err := l.Ingest(writeTempLog(t, c))
if err != nil {
t.Fatal(err)
}
if rc.ContentHash == ra.ContentHash {
t.Fatal("hash should change when a new distinct error appears")
}
}
+1
View File
@@ -102,6 +102,7 @@ func (o *ObsidianIngester) ingestNote(path, vault string) (*IngestResult, error)
ContentType: ".md",
Title: title,
Summary: summary,
Content: content,
CreatedAt: created,
LineStart: 0,
LineEnd: len(strings.Split(content, "\n")),
+1
View File
@@ -56,6 +56,7 @@ func (o *ObsidianFileIngester) Ingest(path string) (*IngestResult, error) {
ContentType: ".md",
Title: title,
Summary: summary,
Content: content,
CreatedAt: created,
LineEnd: len(strings.Split(content, "\n")),
Confidence: 0.85,
+244
View File
@@ -0,0 +1,244 @@
package ingest
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"time"
_ "modernc.org/sqlite"
)
// opencodeDBPath is the current opencode storage: a single SQLite database
// holding sessions, messages and their parts. The legacy
// storage/session_diff/*.json files are mostly empty and are no longer read.
const opencodeDBPath = ".local/share/opencode/opencode.db"
// transcriptCap bounds how much conversation text is folded into one session
// entry's summary. It keeps the entry searchable without storing the whole
// (often tool-heavy) transcript.
const transcriptCap = 4000
// OpenCodeDBIngester indexes opencode sessions from opencode.db. One session
// becomes one entry; the summary carries a capped transcript of the session's
// text parts so conversation content is searchable.
type OpenCodeDBIngester struct {
Version string
Path string // defaults to ~/.local/share/opencode/opencode.db
}
func NewOpenCodeDBIngester() *OpenCodeDBIngester {
return &OpenCodeDBIngester{Version: "opencode-db/v1"}
}
func (o *OpenCodeDBIngester) SourceID() string { return "opencode-session" }
// Ingest satisfies Ingester but is unused: this source is DB-backed, not
// per-file. Callers use IngestAll.
func (o *OpenCodeDBIngester) Ingest(path string) (*IngestResult, error) { return nil, nil }
type ocSession struct {
ID string
Title string
Directory string
TimeCreated int64
TimeUpdated int64
}
// IngestAll reads every session and produces one result per session. It is a
// full sweep: unchanged sessions are collapsed by RecordObservation's dedup, so
// repeated sweeps are idempotent and need no watermark.
func (o *OpenCodeDBIngester) IngestAll() ([]*IngestResult, error) {
path := o.Path
if path == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("home dir: %w", err)
}
path = filepath.Join(home, opencodeDBPath)
}
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("opencode db: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, fmt.Errorf("open opencode db: %w", err)
}
defer db.Close()
sessions, err := loadOCSessions(db)
if err != nil {
return nil, err
}
transcripts, err := loadOCTranscripts(db)
if err != nil {
return nil, err
}
partCounts, err := loadOCPartCounts(db)
if err != nil {
return nil, err
}
results := make([]*IngestResult, 0, len(sessions))
for _, s := range sessions {
results = append(results, o.buildResult(s, transcripts[s.ID], partCounts[s.ID]))
}
return results, nil
}
func loadOCSessions(db *sql.DB) ([]ocSession, error) {
rows, err := db.Query(
`SELECT id, COALESCE(title,''), COALESCE(directory,''),
COALESCE(time_created,0), COALESCE(time_updated,0)
FROM session ORDER BY time_updated`)
if err != nil {
return nil, fmt.Errorf("query sessions: %w", err)
}
defer rows.Close()
var out []ocSession
for rows.Next() {
var s ocSession
if err := rows.Scan(&s.ID, &s.Title, &s.Directory, &s.TimeCreated, &s.TimeUpdated); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
// loadOCTranscripts returns session_id -> ordered text lines ("role: text").
func loadOCTranscripts(db *sql.DB) (map[string][]string, error) {
rows, err := db.Query(
`SELECT p.session_id, json_extract(m.data,'$.role'), json_extract(p.data,'$.text')
FROM part p
JOIN message m ON m.id = p.message_id
WHERE json_extract(p.data,'$.type')='text'
ORDER BY p.session_id, p.time_created`)
if err != nil {
return nil, fmt.Errorf("query transcripts: %w", err)
}
defer rows.Close()
out := make(map[string][]string)
for rows.Next() {
var sessionID, text string
var role sql.NullString
if err := rows.Scan(&sessionID, &role, &text); err != nil {
return nil, err
}
text = strings.TrimSpace(text)
if text == "" || isToolEcho(text) {
continue
}
out[sessionID] = append(out[sessionID], roleLabel(role.String)+": "+text)
}
return out, rows.Err()
}
func loadOCPartCounts(db *sql.DB) (map[string]int, error) {
rows, err := db.Query(`SELECT session_id, COUNT(*) FROM part GROUP BY session_id`)
if err != nil {
return nil, fmt.Errorf("query part counts: %w", err)
}
defer rows.Close()
out := make(map[string]int)
for rows.Next() {
var sessionID string
var n int
if err := rows.Scan(&sessionID, &n); err != nil {
return nil, err
}
out[sessionID] = n
}
return out, rows.Err()
}
func (o *OpenCodeDBIngester) buildResult(s ocSession, lines []string, partCount int) *IngestResult {
title := strings.TrimSpace(s.Title)
if title == "" {
title = "Session " + shortID(s.ID)
}
summary := buildSummary(lines)
createdAt := ""
if s.TimeCreated > 0 {
createdAt = time.UnixMilli(s.TimeCreated).UTC().Format(time.RFC3339)
}
project := ""
if s.Directory != "" {
project = filepath.Base(s.Directory)
}
return &IngestResult{
Fingerprint: FingerprintWithMeta([]byte(s.ID), map[string]string{"source": "opencode-db"}),
SourceID: o.SourceID(),
SourcePath: s.ID,
Project: project,
ContentType: ".session",
Title: title,
Summary: summary,
Content: strings.Join(lines, "\n"),
CreatedAt: createdAt,
LineEnd: partCount,
Confidence: 0.8,
IngesterVersion: o.Version,
Provenance: map[string]any{
"session_id": s.ID,
"directory": s.Directory,
"parts": partCount,
"prompts": len(lines),
},
}
}
// buildSummary folds a session's text lines into a bounded, searchable string:
// the first line (usually the opening prompt) followed by the transcript up to
// the cap.
func buildSummary(lines []string) string {
if len(lines) == 0 {
return ""
}
var b strings.Builder
b.WriteString(truncate(lines[0], 200))
if len(lines) > 1 {
b.WriteString(" || ")
for _, l := range lines[1:] {
if b.Len()+len(l) > transcriptCap {
break
}
b.WriteString(l)
b.WriteString(" ")
}
}
return strings.TrimSpace(b.String())
}
func roleLabel(role string) string {
if role == "" {
return "msg"
}
return role
}
// isToolEcho drops the user-role echoes opencode stores for tool invocations
// and file reads; they are noise in a knowledge summary.
func isToolEcho(text string) bool {
return strings.HasPrefix(text, "Called the ") || strings.HasPrefix(text, "<path>")
}
func shortID(id string) string {
id = strings.TrimPrefix(id, "ses_")
if len(id) > 8 {
return id[:8]
}
return id
}
+42
View File
@@ -0,0 +1,42 @@
package ingest
import (
"strings"
"testing"
)
func TestBuildSummary(t *testing.T) {
if got := buildSummary(nil); got != "" {
t.Fatalf("empty summary=%q", got)
}
got := buildSummary([]string{"first prompt", "assistant: reply"})
if !strings.HasPrefix(got, "first prompt") || !strings.Contains(got, "reply") {
t.Fatalf("unexpected summary: %q", got)
}
// Transcript is bounded well under the cap plus the leading prompt.
long := strings.Repeat("x", transcriptCap*2)
got = buildSummary([]string{"p", long})
if len(got) > transcriptCap+300 {
t.Fatalf("summary not capped: %d bytes", len(got))
}
}
func TestToolEchoFiltered(t *testing.T) {
if !isToolEcho("Called the Read tool with the following input: {}") {
t.Fatal("tool echo not detected")
}
if !isToolEcho("<path>/tmp/x</path>") {
t.Fatal("path echo not detected")
}
if isToolEcho("review repo, start with @AGENTS.md") {
t.Fatal("real prompt wrongly filtered")
}
}
func TestShortID(t *testing.T) {
if got := shortID("ses_38703c295ffeIjbbaYM2Xh6GvK"); got != "38703c29" {
t.Fatalf("shortID=%q", got)
}
}
+58
View File
@@ -0,0 +1,58 @@
package ingest
import "regexp"
// Redact masks credentials in text lifted from sessions: DB URLs, NAME=literal
// secrets, cloud token shapes, private keys, JWTs, bearer tokens. It is
// deliberately broad on *literal* values but never touches a value that is a
// reference or substitution (`$(…)`, `${…}`, `$VAR`) — masking those would
// corrupt code without hiding anything. Idempotent, so re-running is safe.
func Redact(s string) string {
for _, r := range redactRules {
s = r.re.ReplaceAllString(s, r.repl)
}
return s
}
type redactRule struct {
re *regexp.Regexp
repl string
}
// secretName matches a variable name that implies a credential. Deliberately
// excludes the bare words PASS/PWD, which falsely match PASSED, BYPASS, etc.
const secretName = `(?:PASSWORD|PASSWD|PASSPHRASE|SECRET|TOKEN|APIKEY|API_KEY|ACCESS_KEY|SECRET_KEY|PRIVATE_KEY|CREDENTIAL|AUTH|PSK|CLIENT_SECRET|SESSION_KEY)`
// litValue is a quoted-literal value: not a $reference, $(...) or ${...}.
const litValue = `[A-Za-z0-9_\-./+=]{4,}`
// litStrong is an UNQUOTED value that must contain at least one digit or symbol
// (- / + =) — i.e. it looks like a secret, not an identifier or a property access
// like `formData.get`. This keeps the bare rules from corrupting
// `password = read_secret(...)`, `password = formData.get(...)`,
// `password: string`, or `C1_PASSED=true`.
const litStrong = `[A-Za-z0-9_\-/+=]*[0-9\-/+=][A-Za-z0-9_\-/+=]*`
var redactRules = []redactRule{
// PEM private key blocks (multiline).
{regexp.MustCompile(`(?s)-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----`), "[REDACTED PRIVATE KEY]"},
// userinfo in a URL: scheme://user:password@host (structure preserved).
{regexp.MustCompile(`(?i)([a-z][a-z0-9+.\-]*://)([^/\s:@]+):([^@\s/]+)@`), "${1}${2}:****@"},
// NAME="literal" / NAME='literal' (quoted values are unambiguous).
{regexp.MustCompile(`(?i)\b([A-Z0-9_]*` + secretName + `[A-Z0-9_]*)="(` + litValue + `)"`), `${1}="****"`},
{regexp.MustCompile(`(?i)\b([A-Z0-9_]*` + secretName + `[A-Z0-9_]*)='(` + litValue + `)'`), `${1}='****'`},
// NAME=literal (unquoted, must look secret-like).
{regexp.MustCompile(`(?i)\b([A-Z0-9_]*` + secretName + `[A-Z0-9_]*)=(` + litStrong + `)`), `${1}=****`},
// password[:=]literal in JSON-ish text (quoted, or secret-like unquoted).
{regexp.MustCompile(`(?i)("?password"?\s*[:=]\s*)"(` + litValue + `)"`), `${1}"****"`},
{regexp.MustCompile(`(?i)("?password"?\s*[:=]\s*)'(` + litValue + `)'`), `${1}'****'`},
{regexp.MustCompile(`(?i)("?password"?\s*[:=]\s*)(` + litStrong + `)`), `${1}****`},
// Cloud / SaaS token shapes.
{regexp.MustCompile(`AKIA[0-9A-Z]{16}`), "AKIA****************"},
{regexp.MustCompile(`gh[pousr]_[A-Za-z0-9]{20,}`), "gh*_****"},
{regexp.MustCompile(`xox[baprs]-[A-Za-z0-9-]{10,}`), "xox*-****"},
{regexp.MustCompile(`eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+`), "****.****.****"},
{regexp.MustCompile(`(?i)bearer\s+[A-Za-z0-9._\-]{8,}`), "Bearer ****"},
// curl -u user:password
{regexp.MustCompile(`(?i)((?:^|\s)(?:-u|--user)\s+)([^\s:]+):([^\s]+)`), "${1}${2}:****"},
}
-157
View File
@@ -1,157 +0,0 @@
package ingest
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
type jsonKind int
const (
jsonObject jsonKind = iota
jsonArray
)
var _ Ingester = (*SessionDiffIngester)(nil)
type SessionDiffIngester struct {
Version string
}
func NewSessionDiffIngester() *SessionDiffIngester {
return &SessionDiffIngester{Version: "session-diff/v1"}
}
func (s *SessionDiffIngester) SourceID() string { return "opencode-session" }
func (s *SessionDiffIngester) Ingest(path string) (*IngestResult, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read session diff: %w", err)
}
if len(data) < 10 {
return nil, nil
}
raw, kind := parseJSON(data)
if raw == nil {
return nil, nil
}
sessionID := guessString(raw, "session_id", "id", "sessionId")
project := guessString(raw, "project", "project_id", "projectPath", "projectId")
title := guessString(raw, "title", "name", "label")
createdAt := guessString(raw, "created_at", "timestamp", "date", "started_at")
if createdAt == "" {
if fi, err := os.Stat(path); err == nil {
createdAt = fi.ModTime().UTC().Format(time.RFC3339)
}
}
if sessionID == "" {
base := filepath.Base(path)
sessionID = strings.TrimSuffix(base, filepath.Ext(base))
sessionID = strings.TrimPrefix(sessionID, "ses_")
}
if title == "" {
title = fmt.Sprintf("Session %s", sessionID[:min(8, len(sessionID))])
}
summary := extractSummary(raw, kind)
fp := FingerprintWithMeta(data, map[string]string{
"session_id": sessionID,
"source": "session_diff",
})
confidence := 0.7
if kind == jsonArray {
confidence = 0.4
}
return &IngestResult{
Fingerprint: fp,
SourceID: s.SourceID(),
SourcePath: path,
Project: project,
ContentType: ".json",
Title: title,
Summary: summary,
CreatedAt: createdAt,
LineStart: 0,
LineEnd: 0,
Confidence: confidence,
IngesterVersion: s.Version,
Provenance: map[string]any{
"session_id": sessionID,
"kind": kindName(kind),
"field_count": len(raw),
},
}, nil
}
func parseJSON(data []byte) (map[string]any, jsonKind) {
var obj map[string]any
if err := json.Unmarshal(data, &obj); err == nil {
return obj, jsonObject
}
var arr []any
if err := json.Unmarshal(data, &arr); err == nil {
m := make(map[string]any)
m["_count"] = float64(len(arr))
m["_kind"] = "array"
if len(arr) > 0 {
if first, ok := arr[0].(map[string]any); ok {
for k, v := range first {
if str, ok := v.(string); ok && len(str) < 200 {
m["_sample_"+k] = str
break
}
}
}
}
return m, jsonArray
}
return nil, jsonObject
}
func extractSummary(raw map[string]any, kind jsonKind) string {
if msg, ok := raw["message"].(string); ok && len(msg) > 0 {
return truncate(msg, 200)
}
if msgs, ok := raw["messages"].([]any); ok && len(msgs) > 0 {
parts := make([]string, 0, len(msgs))
for _, m := range msgs {
if mm, ok := m.(map[string]any); ok {
if c, ok := mm["content"].(string); ok {
parts = append(parts, truncate(c, 100))
}
}
}
return strings.Join(parts, " | ")
}
if count, ok := raw["_count"].(float64); ok && kind == jsonArray {
return fmt.Sprintf("Array with %.0f entries", count)
}
b, _ := json.Marshal(raw)
return truncate(string(b), 200)
}
func guessString(m map[string]any, keys ...string) string {
for _, k := range keys {
if v, ok := m[k].(string); ok && v != "" {
return v
}
}
return ""
}
func kindName(k jsonKind) string {
if k == jsonArray {
return "array"
}
return "object"
}
+1
View File
@@ -48,6 +48,7 @@ func (s *SkillsIngester) Ingest(path string) (*IngestResult, error) {
ContentType: ".md",
Title: title,
Summary: summary,
Content: content,
CreatedAt: createdAt,
LineStart: 0,
LineEnd: len(strings.Split(content, "\n")),
+883
View File
@@ -0,0 +1,883 @@
package ingest
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
_ "modernc.org/sqlite"
)
// SnippetExtractor mines opencode sessions for code that *demonstrably worked*.
//
// It is deliberately LLM-free and conservative: only tool calls that completed
// successfully become candidates, and a file that was later fully rewritten
// (a later `write` to the same path) marks its earlier snippets superseded —
// a dead end. Bash calls are mined (set KNOX_SNIPPET_BASH=0 to disable) because
// code is often written by hand there as a heredoc body; plain throwaway shell
// one-liners are dropped. Judgment about what is worth keeping is left to the
// agent that calls the MCP encode/reject tools.
//
// The output is candidate *raw material*; it is not curated until an agent
// encodes it. Identical code dedups by content hash, so the same snippet reused
// across sessions collapses to one row.
type SnippetExtractor struct {
Version string
Path string // defaults to ~/.local/share/opencode/opencode.db
IncludeBash bool
}
const (
snippetMinCode = 30
snippetMaxCode = 32000
snippetCodeCap = 200 // candidates kept per session
)
// SnippetCandidate is one extracted code snippet with its provenance.
type SnippetCandidate struct {
Fingerprint string
Language string
Code string
Title string
Description string
Tags string
SourceSession string
SourcePath string
SourceEntry string
Project string
Tool string
Model string
PatchHash string
Evidence string
SupersededBy string
Junk bool
Kind string
}
func NewSnippetExtractor() *SnippetExtractor {
return &SnippetExtractor{
Version: "snippet-extract/v1",
IncludeBash: os.Getenv("KNOX_SNIPPET_BASH") != "0",
}
}
type ocPart struct {
Session string
Message string
Model string
Time int64
Kind string // tool | patch | other
Tool string
Status string
Input string
Metadata string
Err string
PatchHash string
}
type toolInput struct {
FilePath string `json:"filePath"`
Content string `json:"content"`
NewString string `json:"newString"`
Command string `json:"command"`
Description string `json:"description"`
}
type toolMeta struct {
Exit *int `json:"exit"`
Output string `json:"output"`
Diagnostics map[string][]diagEntry `json:"diagnostics"`
}
type diagEntry struct {
Code string `json:"code"`
Message string `json:"message"`
}
// ExtractAll sweeps opencode.db and returns one candidate per successful,
// not-superseded code-producing tool call.
func (e *SnippetExtractor) ExtractAll() ([]SnippetCandidate, error) {
path := e.Path
if path == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("home dir: %w", err)
}
path = filepath.Join(home, opencodeDBPath)
}
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("opencode db: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, fmt.Errorf("open opencode db: %w", err)
}
defer db.Close()
sessions, err := loadOCSessions(db)
if err != nil {
return nil, err
}
dirOf := make(map[string]string, len(sessions))
for _, s := range sessions {
dirOf[s.ID] = s.Directory
}
rows, err := db.Query(
`SELECT p.session_id,
COALESCE(p.message_id,''),
COALESCE(json_extract(m.data,'$.modelID'),''),
COALESCE(p.time_created,0),
COALESCE(json_extract(p.data,'$.type'),''),
COALESCE(json_extract(p.data,'$.tool'),''),
COALESCE(json_extract(p.data,'$.state.status'),''),
COALESCE(json_extract(p.data,'$.state.input'),''),
COALESCE(json_extract(p.data,'$.state.metadata'),''),
COALESCE(json_extract(p.data,'$.state.error'),''),
COALESCE(json_extract(p.data,'$.hash'),'')
FROM part p JOIN message m ON m.id = p.message_id
WHERE json_extract(p.data,'$.type') IN ('tool','patch')
ORDER BY p.session_id, p.time_created`)
if err != nil {
return nil, fmt.Errorf("query parts: %w", err)
}
defer rows.Close()
var (
out []SnippetCandidate
curSession string
events []ocPart
)
flush := func() {
if curSession == "" || len(events) == 0 {
return
}
out = append(out, e.processSession(curSession, dirOf[curSession], events)...)
events = events[:0]
}
for rows.Next() {
var p ocPart
if err := rows.Scan(&p.Session, &p.Message, &p.Model, &p.Time, &p.Kind,
&p.Tool, &p.Status, &p.Input, &p.Metadata, &p.Err, &p.PatchHash); err != nil {
return nil, err
}
if p.Session != curSession {
flush()
curSession = p.Session
}
events = append(events, p)
}
if err := rows.Err(); err != nil {
return nil, err
}
flush()
return dedupPrimaries(out), nil
}
func (e *SnippetExtractor) processSession(sessionID, directory string, events []ocPart) []SnippetCandidate {
project := ""
if directory != "" {
project = filepath.Base(directory)
}
entryFP := FingerprintWithMeta([]byte(sessionID), map[string]string{"source": "opencode-db"})
// Patch hashes are stamped onto the message they belong to.
patchHash := map[string]string{}
for _, ev := range events {
if ev.Kind == "patch" && ev.PatchHash != "" {
patchHash[ev.Message] = ev.PatchHash
}
}
type cand struct {
fp string
filePath string
idx int
isWrite bool
c SnippetCandidate
}
var cands []cand
for i, ev := range events {
if ev.Kind != "tool" || ev.Status != "completed" {
continue
}
if ev.Tool != "write" && ev.Tool != "edit" && ev.Tool != "bash" {
continue
}
if ev.Tool == "bash" && !e.IncludeBash {
continue
}
if len(cands) >= snippetCodeCap {
break
}
var in toolInput
if err := json.Unmarshal([]byte(ev.Input), &in); err != nil {
continue
}
var meta toolMeta
_ = json.Unmarshal([]byte(ev.Metadata), &meta)
var code, filePath, language, desc string
switch ev.Tool {
case "write":
code, filePath = in.Content, in.FilePath
case "edit":
code, filePath = in.NewString, in.FilePath
case "bash":
if meta.Exit == nil || *meta.Exit != 0 {
continue
}
// A bash call is often how code is written by hand: a heredoc body
// (`python3 - <<'PY' … PY`, `cat > x.py <<EOF`) is the real code.
bcode, blang, ok := extractBashSnippet(in.Command)
if !ok {
continue
}
code, language, desc = bcode, blang, in.Description
}
code = strings.TrimRight(code, "\n")
if len(code) < snippetMinCode || len(code) > snippetMaxCode {
continue
}
// Keep the raw code for the identity hash (so re-extraction is stable),
// but store a redacted copy and never index a leaked credential.
rawCode := code
code = Redact(code)
desc = Redact(desc)
if language == "" {
language = languageForPath(filePath)
}
if filePath == "" {
filePath = "(bash)"
}
evidence := map[string]any{
"tool": ev.Tool,
"status": "completed",
"bytes": len(code),
"lines": strings.Count(code, "\n") + 1,
"diagnostics": len(meta.Diagnostics),
"signal_version": e.Version,
}
if meta.Exit != nil {
evidence["exit"] = *meta.Exit
}
evJSON, _ := json.Marshal(evidence)
// bash calls are how exploration and troubleshooting happen: a diagnostic
// command is a *technique*, not junk, even when it's a one-liner tied to
// a specific host. Only code files get the import/stub junk verdict.
kind, junk := "code", classifyJunk(code, language)
if ev.Tool == "bash" {
kind, junk = "technique", trivialProbe(in.Command)
}
title := snippetTitle(ev.Tool, filePath)
if ev.Tool == "bash" {
switch {
case desc != "":
title = truncate(desc, 60)
case language != "" && language != "bash":
title = "script (" + language + ")"
default:
title = "shell command"
}
}
fp := Fingerprint([]byte(language + "\x00" + rawCode))
cands = append(cands, cand{
fp: fp,
filePath: filePath,
idx: i,
isWrite: ev.Tool == "write",
c: SnippetCandidate{
Fingerprint: fp,
Language: language,
Code: code,
Title: title,
Description: desc,
Tags: "[]",
SourceSession: sessionID,
SourcePath: filePath,
SourceEntry: entryFP,
Project: project,
Tool: ev.Tool,
Model: ev.Model,
PatchHash: patchHash[ev.Message],
Evidence: string(evJSON),
Junk: junk,
Kind: kind,
},
})
}
// Supersession: the last surviving full `write` to a file means every
// earlier candidate for that file (write or edit) may no longer be present.
lastWrite := map[string]int{} // filePath -> index of last write candidate
for _, c := range cands {
if c.isWrite {
if prev, ok := lastWrite[c.filePath]; !ok || c.idx > prev {
lastWrite[c.filePath] = c.idx
}
}
}
fpAtIdx := map[int]string{}
for _, c := range cands {
fpAtIdx[c.idx] = c.fp
}
out := make([]SnippetCandidate, 0, len(cands))
for _, c := range cands {
if lw, ok := lastWrite[c.filePath]; ok && c.idx < lw {
c.c.SupersededBy = fpAtIdx[lw]
}
out = append(out, c.c)
}
return out
}
// dedupPrimaries collapses identical fingerprints and clears the superseded
// marker for any fingerprint that also occurs as a primary elsewhere.
func dedupPrimaries(in []SnippetCandidate) []SnippetCandidate {
primary := map[string]bool{}
for _, c := range in {
if c.SupersededBy == "" {
primary[c.Fingerprint] = true
}
}
seen := map[string]bool{}
out := make([]SnippetCandidate, 0, len(in))
for _, c := range in {
if primary[c.Fingerprint] {
c.SupersededBy = ""
}
if seen[c.Fingerprint] {
continue
}
seen[c.Fingerprint] = true
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Fingerprint < out[j].Fingerprint })
return out
}
func snippetTitle(tool, filePath string) string {
base := filepath.Base(filePath)
switch tool {
case "bash":
return "command"
case "write":
return "new file: " + base
default:
return "edit " + base
}
}
func languageForPath(path string) string {
base := strings.ToLower(filepath.Base(path))
switch base {
case "dockerfile", "containerfile":
return "dockerfile"
case "makefile", "gnumakefile":
return "makefile"
case "cmakelists.txt":
return "cmake"
}
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".go":
return "go"
case ".py":
return "python"
case ".js", ".mjs", ".cjs":
return "javascript"
case ".ts", ".mts", ".cts":
return "typescript"
case ".tsx":
return "tsx"
case ".jsx":
return "jsx"
case ".rs":
return "rust"
case ".c":
return "c"
case ".h":
return "c"
case ".cpp", ".cc", ".cxx", ".hpp", ".hh":
return "cpp"
case ".ino":
return "cpp"
case ".java":
return "java"
case ".rb":
return "ruby"
case ".erb":
return "erb"
case ".sh", ".bash", ".zsh", ".bashrc":
return "bash"
case ".fish":
return "fish"
case ".ps1":
return "powershell"
case ".sql":
return "sql"
case ".html", ".htm":
return "html"
case ".css":
return "css"
case ".scss", ".sass":
return "scss"
case ".json", ".jsonc":
return "json"
case ".yaml", ".yml":
return "yaml"
case ".toml":
return "toml"
case ".ini", ".cfg", ".conf":
return "ini"
case ".md", ".mdx":
return "markdown"
case ".nix":
return "nix"
case ".lua":
return "lua"
case ".tf", ".tfvars", ".hcl":
return "hcl"
case ".php":
return "php"
case ".cs":
return "csharp"
case ".swift":
return "swift"
case ".kt", ".kts":
return "kotlin"
case ".scala":
return "scala"
case ".pl", ".pm":
return "perl"
case ".r":
return "r"
case ".vue":
return "vue"
case ".svelte":
return "svelte"
case ".graphql", ".gql":
return "graphql"
case ".proto":
return "protobuf"
case ".xml":
return "xml"
case ".tex":
return "latex"
case ".rst":
return "rst"
case ".asm", ".s":
return "assembly"
case ".v", ".sv":
return "verilog"
case ".vhd", ".vhdl":
return "vhdl"
case ".gradle":
return "groovy"
case ".cmake":
return "cmake"
case ".bat", ".cmd":
return "batch"
case ".txt":
return "text"
default:
return ""
}
}
// classifyJunk flags low-reuse snippets: import/directive-only blocks,
// single-statement one-liners, and empty-body stubs. It is deliberately narrow —
// anything with real control flow or multiple statements is kept. The flag is a
// heuristic, not a verdict: the agent can still encode a junk row, and
// knox_snippet_reopen undoes a bulk rejection.
func classifyJunk(code, language string) bool {
lines := meaningfulLines(code)
if len(lines) == 0 {
return true
}
if allDirective(lines) {
return true
}
if len(lines) == 1 {
return len(code) < 160
}
if len(lines) <= 2 && isStub(lines) {
return true
}
return false
}
func meaningfulLines(code string) []string {
var out []string
for _, ln := range strings.Split(code, "\n") {
t := strings.TrimSpace(ln)
if t == "" || isCommentLine(t) {
continue
}
out = append(out, t)
}
return out
}
func isCommentLine(t string) bool {
for _, p := range []string{"//", "/*", "*/", "*", "<!--", "-->", "--"} {
if strings.HasPrefix(t, p) {
return true
}
}
return false
}
var directivePrefixes = []string{
"import ", "import\t", "from ", "require", "require_relative",
"use ", "using ", "package ", "option ", "#include", "#import",
"#pragma", "#!", "export ", "\"use strict\"", "'use strict'",
"//go:build", "// +build", "# frozen_string_literal", "module ",
"@import", "extern crate", "pub use", "mod ", "pub mod ",
}
func allDirective(lines []string) bool {
for _, ln := range lines {
if !isDirective(ln) {
return false
}
}
return true
}
func isDirective(ln string) bool {
l := strings.ToLower(ln)
for _, p := range directivePrefixes {
if strings.HasPrefix(l, p) {
return true
}
}
if strings.HasPrefix(l, "export ") && strings.Contains(l, " from ") {
return true
}
return false
}
func isStub(lines []string) bool {
joined := strings.TrimSpace(strings.Join(lines, " "))
if strings.HasSuffix(joined, "{}") || strings.HasSuffix(joined, "{ }") {
return true
}
switch strings.ToLower(strings.TrimSpace(lines[len(lines)-1])) {
case "pass", "...", "return", "return null", "return nil", "return none":
return true
}
return false
}
// ─── bash mining ─────────────────────────────────────────────
var (
heredocRe = regexp.MustCompile(`<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)`)
interpRe = regexp.MustCompile(`(?i)\b(python3|python|node|deno|bun|ruby|irb|perl|php|lua|fish|bash|zsh|sh|rscript)\b`)
redirRe = regexp.MustCompile(`>>?\s*([^\s;|&]+)`)
pythonCRe = regexp.MustCompile(`(?is)^\s*python3?\s+-c\s+(.*)$`)
)
// extractBashSnippet turns a completed bash command into code worth keeping:
// the body of a heredoc (the common way code is written by hand in a shell),
// the argument of `python -c`, or a genuine multi-line / control-flow shell
// script. Trivial one-liners return ok=false.
func extractBashSnippet(cmd string) (code, language string, ok bool) {
if body, lang, found := extractHeredoc(cmd); found {
if len(strings.TrimSpace(body)) >= snippetMinCode {
return strings.TrimRight(body, "\n"), lang, true
}
return "", "", false
}
if m := pythonCRe.FindStringSubmatch(cmd); m != nil {
if body := trimQuotes(m[1]); len(strings.TrimSpace(body)) >= snippetMinCode {
return strings.TrimRight(body, "\n"), "python", true
}
return "", "", false
}
if len(cmd) < snippetMinCode || (!strings.Contains(cmd, "\n") && !hasShellControl(cmd)) {
return "", "", false
}
return strings.TrimRight(cmd, "\n"), "bash", true
}
// extractHeredoc returns the body between a "<<WORD" marker and a line equal to
// WORD, plus the language inferred from the invoking interpreter or a `> file`
// redirection target.
func extractHeredoc(cmd string) (body, language string, ok bool) {
lines := strings.Split(cmd, "\n")
for i, ln := range lines {
m := heredocRe.FindStringSubmatch(ln)
if m == nil {
continue
}
marker := m[1]
for j := i + 1; j < len(lines); j++ {
if strings.TrimSpace(lines[j]) == marker {
return strings.Join(lines[i+1:j], "\n"), heredocLanguage(ln), true
}
}
return "", "", false // unterminated heredoc
}
return "", "", false
}
func heredocLanguage(opLine string) string {
if m := interpRe.FindStringSubmatch(opLine); m != nil {
return interpreterLanguage(strings.ToLower(m[1]))
}
if m := redirRe.FindStringSubmatch(opLine); m != nil {
if l := languageForPath(m[1]); l != "" {
return l
}
}
return ""
}
func interpreterLanguage(cmd string) string {
switch cmd {
case "python", "python3":
return "python"
case "node", "deno", "bun":
return "javascript"
case "ruby", "irb":
return "ruby"
case "perl":
return "perl"
case "php":
return "php"
case "lua":
return "lua"
case "fish":
return "fish"
case "bash", "sh", "zsh":
return "bash"
case "rscript":
return "r"
}
return ""
}
func hasShellControl(cmd string) bool {
return strings.ContainsAny(cmd, "|&;$(){}") ||
strings.Contains(cmd, " && ") || strings.Contains(cmd, " || ") ||
strings.Contains(cmd, "for ") || strings.Contains(cmd, "while ") || strings.Contains(cmd, "if ")
}
func trimQuotes(s string) string {
s = strings.TrimSpace(s)
if len(s) >= 2 {
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
return s[1 : len(s)-1]
}
}
return s
}
// trivialProbe flags a technique command that is just a one-shot read of a
// file or system state (ls/cat/head/…, or a non-recursive grep) with no
// pipeline, redirection, or diagnostic tooling. These carry no transferable
// method, so they are junk (hidden by default) while real diagnostics — an ssh
// probe, a dmesg/journalctl check, a recursive search, a test run — are kept.
// Deliberately conservative: when in doubt, keep it.
func trivialProbe(cmd string) bool {
cmd = strings.TrimSpace(cmd)
if cmd == "" || strings.Contains(cmd, "\n") {
return false
}
if strings.Contains(cmd, "$(") || strings.Contains(cmd, "`") {
return false // command substitution runs something
}
return trivialTokens(shellTokens(scrubRedirects(cmd)))
}
func scrubRedirects(s string) string {
return strings.NewReplacer(
"2>&1", "", "2>/dev/null", "", "&>/dev/null", "", ">/dev/null", "",
).Replace(s)
}
// trivialTokens reports whether every segment of a tokenized command is a
// read-only inspection. A write redirection or background job makes it real work.
func trivialTokens(toks []string) bool {
seg := make([]string, 0, len(toks))
for _, t := range toks {
switch t {
case "|", "||", "&&", ";", "&":
if !trivialWordSeq(seg) {
return false
}
seg = seg[:0]
case ">", ">>":
return false // writes a file
case "<":
// input redirection: harmless
default:
seg = append(seg, t)
}
}
return trivialWordSeq(seg)
}
func trivialWordSeq(seg []string) bool {
i := 0
for i < len(seg) && strings.Contains(seg[i], "=") && !strings.HasPrefix(seg[i], "-") {
i++ // skip leading VAR=value assignments
}
if i >= len(seg) {
return true
}
base := filepath.Base(seg[i])
if base == "ssh" {
return trivialSSH(seg[i+1:])
}
return trivialReader(base, seg[i:])
}
// trivialSSH classifies an ssh call by its remote command: `ssh host ls` and
// `ssh host 'docker ps'` are trivial reads, while `ssh host 'dmesg | grep dwc'`
// is a diagnostic method.
func trivialSSH(args []string) bool {
takesArg := map[string]bool{
"-i": true, "-o": true, "-p": true, "-l": true, "-b": true, "-c": true,
"-D": true, "-e": true, "-E": true, "-F": true, "-I": true, "-J": true,
"-L": true, "-m": true, "-O": true, "-Q": true, "-R": true, "-S": true,
"-W": true, "-w": true,
}
i := 0
for i < len(args) && strings.HasPrefix(args[i], "-") {
if takesArg[args[i]] {
i += 2
} else {
i++
}
}
if i >= len(args) {
return true // `ssh host` with no remote command
}
remote := strings.TrimSpace(strings.Join(args[i+1:], " "))
if remote == "" {
return true
}
return trivialTokens(shellTokens(scrubRedirects(remote)))
}
// trivialReader reports whether a single command is a read-only local inspection.
// grep/rg count only when non-recursive; docker/podman read subcommands count.
func trivialReader(base string, args []string) bool {
switch base {
case "ls", "cat", "head", "tail", "pwd", "which", "whoami", "echo", "printf",
"wc", "file", "stat", "du", "df", "readlink", "realpath", "env", "printenv",
"id", "true", "cd", "basename", "dirname", "sort", "uniq", "cut", "tr",
"nl", "column", "xxd", "strings", "cksum":
return true
case "grep", "rg", "egrep", "fgrep":
for _, tok := range args[1:] {
if strings.HasPrefix(tok, "--") {
if tok == "--recursive" || strings.HasPrefix(tok, "--include") || strings.HasPrefix(tok, "--exclude") {
return false
}
continue
}
if strings.HasPrefix(tok, "-") && strings.ContainsAny(tok, "rR") {
return false
}
}
return true
case "docker", "podman":
if len(args) >= 2 {
switch args[1] {
case "ps", "images", "inspect", "version", "info", "port", "history":
return true
}
}
return false
}
return false
}
// shellTokens splits a shell command into words and operator tokens. Quoted runs
// become one token (quotes stripped); operators |, ||, &&, ;, &, <, >, >> are
// emitted as their own tokens.
func shellTokens(s string) []string {
var toks []string
var cur strings.Builder
flush := func() {
if cur.Len() > 0 {
toks = append(toks, cur.String())
cur.Reset()
}
}
for i := 0; i < len(s); i++ {
switch s[i] {
case ' ', '\t':
flush()
case '\'':
i++
for i < len(s) && s[i] != '\'' {
cur.WriteByte(s[i])
i++
}
case '"':
i++
for i < len(s) && s[i] != '"' {
if s[i] == '\\' && i+1 < len(s) {
i++
}
cur.WriteByte(s[i])
i++
}
case '|':
flush()
if i+1 < len(s) && s[i+1] == '|' {
toks = append(toks, "||")
i++
} else {
toks = append(toks, "|")
}
case '&':
flush()
if i+1 < len(s) && s[i+1] == '&' {
toks = append(toks, "&&")
i++
} else {
toks = append(toks, "&")
}
case ';':
flush()
toks = append(toks, ";")
case '>':
flush()
if i+1 < len(s) && s[i+1] == '>' {
toks = append(toks, ">>")
i++
} else {
toks = append(toks, ">")
}
case '<':
flush()
toks = append(toks, "<")
default:
cur.WriteByte(s[i])
}
}
flush()
return toks
}