Files
knox/internal/claims/opencode.go
T
david c559f4ab03
build / test (push) Has been cancelled
build / image (push) Has been cancelled
fix: read tool calls and prose from the v2 session store (#30)
Snippet extraction and claim lint were still on the frozen v1 part table.
opencode 2.0.24 moved tool calls into session_message.data $.content and
stopped writing part at 2026-11-01, so every later session produced no
snippet candidates and no lint evidence: 1,475 completed write/edit/shell
calls are in v2 that v1 never saw.

Both readers now prefer v2 and fall back to v1 only where v2 has nothing,
so a migrated session is never counted twice.

Shape differences handled: the tool name moved from $.tool to $.name,
write/edit input carries 'path' as well as 'filePath', completed output
is $.state.content[] rather than a flat $.state.output, and the shell
tool is emitted as both 'bash' and 'shell'. v2 has no patch parts, so
PatchHash stays empty for v2 candidates; supersession already derives
from the last full write, so nothing depends on it.
2026-11-04 20:31:20 -08:00

298 lines
8.0 KiB
Go

package claims
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
_ "modernc.org/sqlite"
)
// DefaultDBPath is opencode's session store. knox already reads this database
// for session ingestion, so the claim check needs no extra plumbing.
func DefaultDBPath() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".local/share/opencode/opencode.db")
}
// Message is one turn of a session with the text it wrote and the output of
// the tools it called. The lint needs them separated: prose makes claims, tool
// output is the only thing that can back them.
type Message struct {
ID string
Seq int64
Role string // user | assistant
Text []string
Outputs []string
}
// Session is an ordered conversation.
type Session struct {
ID string
Title string
Messages []Message
}
// Open connects to an opencode database read-only.
func Open(path string) (*sql.DB, error) {
if path == "" {
path = DefaultDBPath()
}
if path == "" {
return nil, fmt.Errorf("cannot locate opencode database")
}
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf("opencode database: %w", err)
}
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
if err != nil {
return nil, err
}
db.SetMaxOpenConns(1)
return db, nil
}
// RecentSessions lists sessions, most recently updated first.
func RecentSessions(db *sql.DB, limit int) ([]struct{ ID, Title string }, error) {
if limit <= 0 {
limit = 10
}
rows, err := db.Query(
`SELECT id, COALESCE(title,'') FROM session_v2 ORDER BY time_updated DESC LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []struct{ ID, Title string }
for rows.Next() {
var id, title string
if err := rows.Scan(&id, &title); err != nil {
return nil, err
}
out = append(out, struct{ ID, Title string }{id, title})
}
return out, rows.Err()
}
// LatestSession returns the id of the most recently updated session.
func LatestSession(db *sql.DB) (string, error) {
var id string
err := db.QueryRow(`SELECT id FROM session_v2 ORDER BY time_updated DESC LIMIT 1`).Scan(&id)
return id, err
}
// LoadSession reads a session's messages and their parts in order.
//
// opencode 2.0.24 keeps a message's prose and tool calls inside
// session_message.data ($.content for assistant turns, $.text for user turns)
// and stopped writing the v1 part table. v2 is read first; part rows are used
// only for messages v2 does not describe, so a migrated session is not read
// twice.
func LoadSession(db *sql.DB, sessionID string) (*Session, error) {
s := &Session{ID: sessionID}
_ = db.QueryRow(`SELECT COALESCE(title,'') FROM session_v2 WHERE id=?`, sessionID).Scan(&s.Title)
rows, err := db.Query(
`SELECT id, seq, type, data FROM session_message WHERE session_id=? ORDER BY seq`, sessionID)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id, typ, data string
var seq int64
if err := rows.Scan(&id, &seq, &typ, &data); err != nil {
return nil, err
}
m := &Message{ID: id, Seq: seq, Role: typ}
appendMessage(m, data)
s.Messages = append(s.Messages, *m)
}
if err := rows.Err(); err != nil {
return nil, err
}
if err := appendLegacyParts(db, sessionID, s); err != nil {
return nil, err
}
return s, nil
}
// appendMessage decodes one session_message row. Assistant turns carry a typed
// part list at $.content; user turns carry their prose at $.text.
func appendMessage(m *Message, data string) {
var msg map[string]any
if err := json.Unmarshal([]byte(data), &msg); err != nil {
return
}
if parts, ok := msg["content"].([]any); ok {
for _, p := range parts {
if pm, ok := p.(map[string]any); ok {
appendPart(m, pm)
}
}
}
if len(m.Text) == 0 && len(m.Outputs) == 0 {
if t := asString(msg["text"]); t != "" {
m.Text = append(m.Text, t)
}
}
}
// appendLegacyParts fills in messages that v2 left empty from the pre-migration
// part table, when that table still exists.
func appendLegacyParts(db *sql.DB, sessionID string, s *Session) error {
need := make(map[string]*Message)
for i := range s.Messages {
if len(s.Messages[i].Text) == 0 && len(s.Messages[i].Outputs) == 0 {
need[s.Messages[i].ID] = &s.Messages[i]
}
}
if len(need) == 0 {
return nil
}
var n int
if err := db.QueryRow(
`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='part'`).Scan(&n); err != nil || n == 0 {
return nil // no v1 table: nothing to fall back to
}
rows, err := db.Query(
`SELECT message_id, data FROM part WHERE session_id=? ORDER BY time_created, id`, sessionID)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id, data string
if err := rows.Scan(&id, &data); err != nil {
return err
}
m, ok := need[id]
if !ok {
continue
}
var p map[string]any
if err := json.Unmarshal([]byte(data), &p); err != nil {
continue
}
appendPart(m, p)
}
return rows.Err()
}
// appendPart decodes one part, keeping prose and tool output apart. The decode
// is map-based because part payloads are heterogeneous: a tool part carries a
// typed state object, a text part carries a string.
func appendPart(m *Message, p map[string]any) {
switch asString(p["type"]) {
case "text":
if t := asString(p["text"]); t != "" {
m.Text = append(m.Text, t)
}
case "tool":
state, ok := p["state"].(map[string]any)
if !ok {
return
}
// Only completed tools produced a result worth trusting; an error or a
// running call proves nothing about a number.
if status := asString(state["status"]); status != "" && status != "completed" {
return
}
// v1 stored a flat output string; v2 keeps a {type,text} content list.
if out := asString(state["output"]); out != "" {
m.Outputs = append(m.Outputs, out)
}
if parts, ok := state["content"].([]any); ok {
var b strings.Builder
for _, raw := range parts {
pm, ok := raw.(map[string]any)
if !ok || asString(pm["type"]) != "text" {
continue
}
b.WriteString(asString(pm["text"]))
}
if b.Len() > 0 {
m.Outputs = append(m.Outputs, b.String())
}
}
}
}
func asString(v any) string {
s, _ := v.(string)
return s
}
// Status classifies where a claim's evidence sits relative to the message.
type Status int
const (
// Sourced: a tool call in this turn printed the number.
Sourced Status = iota
// Stale: the number appeared in an *earlier* turn's tool output and is
// being restated without being re-checked. This is the failure mode —
// repetition raising confidence instead of prompting a fresh look.
Stale
// Unsupported: the number has never appeared in any tool output. Usually
// a hypothetical or an illustrative figure rather than a claim about data.
Unsupported
)
func (s Status) String() string {
switch s {
case Sourced:
return "sourced"
case Stale:
return "stale"
default:
return "unsupported"
}
}
// LintRun is a finding together with the message it came from.
type LintRun struct {
MessageID string
Seq int64
Finding Finding
Status Status
}
// Lint checks every assistant message in the session.
//
// The evidence window is the turn, not the message: a tool call and the prose
// citing it land in consecutive messages (opencode emits one message per step),
// so requiring the output in the same message would flag every legitimate
// result. The window resets at each user message, which is what makes a figure
// quoted from an earlier turn count as unsourced.
func Lint(s *Session) []LintRun {
var out []LintRun
var turnOutputs []string
var priorProse strings.Builder
for _, m := range s.Messages {
if m.Role == "user" {
turnOutputs = nil
continue
}
turnOutputs = append(turnOutputs, m.Outputs...)
if m.Role != "assistant" || len(m.Text) == 0 {
continue
}
prose := strings.Join(m.Text, "\n")
for _, sc := range Classify(Extract(prose), turnOutputs, priorProse.String()) {
out = append(out, LintRun{MessageID: m.ID, Seq: m.Seq, Finding: sc.Finding, Status: sc.Status})
}
priorProse.WriteString(prose)
priorProse.WriteString("\n")
}
return out
}