Files
knox/internal/ingest/snippets_test.go
T
david f410d3b46c
build / image (push) Successful in 31s
build / test (push) Successful in 5m51s
fix: make the snippet queue reviewable (#35) (#36)
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
2026-11-05 05:20:39 +00:00

205 lines
7.5 KiB
Go

package ingest
import (
"database/sql"
"path/filepath"
"strings"
"testing"
)
// v2Schema installs the opencode 2.0.24 tables (and, optionally, the frozen v1
// ones) so the extractor can be pointed at a fixture.
func v2Schema(t *testing.T, db *sql.DB, withV1 bool) {
t.Helper()
stmts := []string{
`CREATE TABLE session_v2 (id TEXT PRIMARY KEY, title TEXT, directory TEXT,
time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)`,
`CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL,
time_updated INTEGER NOT NULL, data TEXT NOT NULL)`,
}
if withV1 {
stmts = append(stmts,
`CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, data TEXT NOT NULL)`,
`CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT,
time_created INTEGER, data TEXT NOT NULL)`,
)
}
for _, s := range stmts {
if _, err := db.Exec(s); err != nil {
t.Fatalf("schema: %v", err)
}
}
}
func mustExec(t *testing.T, db *sql.DB, q string, args ...any) {
t.Helper()
if _, err := db.Exec(q, args...); err != nil {
t.Fatalf("exec: %v", err)
}
}
// opencode 2.0.24 keeps tool calls in session_message.data $.content and
// stopped writing the v1 part table. Extraction has to follow it, or nothing
// written after the migration ever becomes a candidate.
func TestSnippetExtractorReadsSessionV2(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode.db")
db, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatalf("open: %v", err)
}
v2Schema(t, db, false)
mustExec(t, db,
`INSERT INTO session_v2 VALUES ('ses_v2','Demo','/home/david/src/demo',1,2)`)
mustExec(t, db,
`INSERT INTO session_message VALUES ('msg_1','ses_v2','assistant',1,1,1,?)`,
`{"model":{"providerID":"p","id":"m1"},"content":[`+
`{"type":"text","text":"writing the entry point"},`+
`{"type":"tool","id":"call_1","name":"write","state":{"status":"completed",`+
`"input":{"path":"/home/david/src/demo/main.go","content":"package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n"}}}]}`)
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
ex := NewSnippetExtractor()
ex.Path = path
cands, err := ex.ExtractAll()
if err != nil {
t.Fatalf("ExtractAll: %v", err)
}
if len(cands) != 1 {
t.Fatalf("candidates=%d, want 1: %+v", len(cands), cands)
}
c := cands[0]
if c.Tool != "write" || c.Language != "go" || c.Project != "demo" {
t.Fatalf("tool=%q lang=%q project=%q", c.Tool, c.Language, c.Project)
}
if !strings.HasSuffix(c.SourcePath, "main.go") {
t.Fatalf("source path = %q", c.SourcePath)
}
if c.Model != "m1" {
t.Fatalf("model = %q, want m1", c.Model)
}
}
// v2 renamed the shell tool and moved its result to state.content; a heredoc is
// still code written by hand and should land as a technique, not a dead probe.
func TestSnippetExtractorShellV2(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode.db")
db, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatalf("open: %v", err)
}
v2Schema(t, db, false)
mustExec(t, db, `INSERT INTO session_v2 VALUES ('ses_v2','Demo','/home/david/src/demo',1,2)`)
mustExec(t, db,
`INSERT INTO session_message VALUES ('msg_1','ses_v2','assistant',1,1,1,?)`,
`{"content":[{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed",`+
`"input":{"command":"python3 - <<'PY'\nimport json\nprint(json.dumps({}))\nPY"},`+
`"metadata":{"exit":0},"content":[{"type":"text","text":"{}"}]}}]}`)
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
ex := NewSnippetExtractor()
ex.Path = path
cands, err := ex.ExtractAll()
if err != nil {
t.Fatalf("ExtractAll: %v", err)
}
if len(cands) != 1 {
t.Fatalf("candidates=%d, want 1", len(cands))
}
if cands[0].Kind != "technique" || cands[0].Language != "python" {
t.Fatalf("kind=%q lang=%q", cands[0].Kind, cands[0].Language)
}
}
// A session present in both shapes must be read once: v2 wins, and the frozen
// v1 part rows are only a fallback for sessions v2 does not cover.
func TestSnippetExtractorDoesNotDoubleCountV1AndV2(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode.db")
db, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatalf("open: %v", err)
}
v2Schema(t, db, true)
mustExec(t, db, `INSERT INTO session_v2 VALUES ('ses_v2','Demo','/home/david/src/demo',1,2)`)
body := `{"type":"tool","id":"call_1","name":"write","state":{"status":"completed",` +
`"input":{"path":"/home/david/src/demo/main.go","content":"package main\n\nfunc main() {\n\tprintln(\"hi\")\n}\n"}}}`
mustExec(t, db, `INSERT INTO session_message VALUES ('msg_1','ses_v2','assistant',1,1,1,?)`,
`{"content":[`+body+`]}`)
// Same call, as the backfill left it in v1.
mustExec(t, db, `INSERT INTO message VALUES ('msg_1','ses_v2','{"modelID":"m1"}')`)
mustExec(t, db, `INSERT INTO part VALUES ('prt_1','msg_1','ses_v2',1,?)`, body)
// A session only v1 knows about still gets mined.
mustExec(t, db, `INSERT INTO session_v2 VALUES ('ses_v1','Old','/home/david/src/old',1,2)`)
mustExec(t, db, `INSERT INTO message VALUES ('msg_2','ses_v1','{"modelID":"m0"}')`)
mustExec(t, db, `INSERT INTO part VALUES ('prt_2','msg_2','ses_v1',1,?)`,
`{"type":"tool","id":"call_2","tool":"write","state":{"status":"completed",`+
`"input":{"filePath":"/home/david/src/old/lib.go","content":"package old\n\nfunc Lib() string {\n\treturn \"x\"\n}\n"}}}`)
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
ex := NewSnippetExtractor()
ex.Path = path
cands, err := ex.ExtractAll()
if err != nil {
t.Fatalf("ExtractAll: %v", err)
}
if len(cands) != 2 {
t.Fatalf("candidates=%d, want 2 (one per session): %+v", len(cands), cands)
}
seen := map[string]bool{}
for _, c := range cands {
if seen[c.Project] {
t.Fatalf("duplicate candidate for project %q", c.Project)
}
seen[c.Project] = true
}
if !seen["demo"] || !seen["old"] {
t.Fatalf("projects = %v, want demo and old", seen)
}
}
// trivialProbe decides what a "technique" candidate is: an inspection chore
// (hidden) versus transferable method (kept). Multi-line commands used to be
// exempted wholesale, which kept every transcript of `cd … && cat …` chores.
func TestTrivialProbe(t *testing.T) {
cases := []struct {
name string
cmd string
want bool
}{
{"single read", "ls -la /tmp", true},
{"chained reads", "cd /repo && sed -n '60,200p' tools/deploy.py", true},
{"multi-line reads", "ls -la\nsed -n '1,20p' main.go\nwc -l main.go", true},
{"git chores", "git status --short && git log --oneline -3", true},
{"show file", "git show 1d244cf:engine/scroll.py | head -n 100", true},
{"pwd", "pwd && git rev-parse --show-toplevel", true},
{"test run", "go test ./... 2>&1 | tail -6", false},
{"archaeology", `git log --all -p --since="3 months ago" -- engine/app.py | grep -B 50 "class Camera"`, false},
{"context grep", `grep -A 5 "def main" engine/app.py`, false},
{"ssh diagnostic", "ssh host 'dmesg | grep dwc3'", false},
{"ssh read", "ssh host 'ls /usr/src'", true},
{"heredoc script", "python3 - <<'PY'\nprint(1)\nPY", false},
{"in-place edit", "sed -i 's/a/b/' main.go", false},
{"write", "git push origin main", false},
{"redirect", "cat > out.txt <<EOF\nx\nEOF", false},
{"substitution", "echo $(date)", false},
{"compose up", "docker compose up -d", false},
{"empty", "", false},
}
for _, c := range cases {
if got := trivialProbe(c.cmd); got != c.want {
t.Errorf("%s: trivialProbe(%q)=%v, want %v", c.name, c.cmd, got, c.want)
}
}
}