feat: audit session transcripts for numeric claims with no tool evidence (#13)
build / test (push) Successful in 5m29s
build / image (push) Successful in 45s

feat: audit session transcripts for numeric claims with no tool evidence (#13)

Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #13.
This commit is contained in:
2026-11-05 02:42:43 +00:00
committed by david
parent a5430b7d25
commit 029c5078ba
5 changed files with 537 additions and 0 deletions
+121
View File
@@ -0,0 +1,121 @@
// Package claims implements the sourced-claim check.
//
// The rule it enforces is narrow on purpose: a number asserted in assistant
// prose must appear in the output of a tool call in the same message. If it
// does not, the number was either remembered from an earlier turn or derived
// without being shown — the shape of error that produced "6,884 lines" from a
// diff that had been run against the wrong ref, and then repeated five times
// without re-checking.
//
// It is fully deterministic: no model calls, no tokens. That is what makes it
// affordable to run on every message.
package claims
import (
"regexp"
"strconv"
"strings"
)
// Finding is one numeric assertion and whether this message backed it.
type Finding struct {
Assertion string // as written, e.g. "6,884 lines"
Value int64 // normalized numeric value, e.g. 6884
Unit string // e.g. "lines"
Sourced bool
}
// claimRe matches a number followed by a unit we care about. The unit list is
// deliberately small: every entry is something a tool can be expected to have
// printed, so "unsourced" is a fair verdict rather than a style opinion.
var claimRe = regexp.MustCompile(
`(?i)\b(\d[\d,_.]*)\s*(lines?|commits?|files?|rows?|bytes?|observations?|entries|threads?|peers?|nodes?|ms|%|[KMGT]i?B)\b`)
// Extract returns the numeric assertions in a piece of prose.
func Extract(text string) []Finding {
matches := claimRe.FindAllStringSubmatch(text, -1)
if len(matches) == 0 {
return nil
}
findings := make([]Finding, 0, len(matches))
for _, m := range matches {
value, ok := parseNumber(m[1])
if !ok || value < 10 {
// Single digits and small counts collide with everything a tool
// prints; flagging them would train the reader to ignore output.
continue
}
findings = append(findings, Finding{
Assertion: strings.TrimSpace(m[0]),
Value: value,
Unit: strings.ToLower(m[2]),
})
}
return findings
}
// claimKey identifies a measurement: the number and its unit together. Matching
// the number alone is far too loose — "200MB" would be "backed" by any output
// containing 200 — so the unit has to agree too.
type claimKey struct {
value int64
unit string
}
// normUnit folds plurals so "1 line" and "3 lines" share a unit, without
// mangling unit symbols.
func normUnit(u string) string {
u = strings.ToLower(strings.TrimSpace(u))
switch u {
case "%", "ms", "kb", "kib", "mb", "mib", "gb", "gib", "tb", "tib":
return u
}
return strings.TrimSuffix(u, "s")
}
// Mark records whether each finding is backed by one of the tool outputs.
func Mark(findings []Finding, toolOutputs []string) []Finding {
if len(findings) == 0 {
return findings
}
seen := make(map[claimKey]struct{})
for _, out := range toolOutputs {
for _, c := range Extract(out) {
seen[claimKey{c.Value, normUnit(c.Unit)}] = struct{}{}
}
}
for i := range findings {
_, findings[i].Sourced = seen[claimKey{findings[i].Value, normUnit(findings[i].Unit)}]
}
return findings
}
// parseNumber converts "6,884" / "6_884" / "6884.0" to 6884. Decimals are
// truncated to their integer part: prose usually rounds anyway, and the point
// is to find the magnitude a tool printed.
func parseNumber(s string) (int64, bool) {
s = strings.TrimSpace(s)
s = strings.NewReplacer(",", "", "_", "").Replace(s)
if i := strings.IndexByte(s, '.'); i >= 0 {
s = s[:i]
}
if s == "" {
return 0, false
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, false
}
return v, true
}
// Unsourced filters to the findings that no tool call backed.
func Unsourced(findings []Finding) []Finding {
var out []Finding
for _, f := range findings {
if !f.Sourced {
out = append(out, f)
}
}
return out
}
+80
View File
@@ -0,0 +1,80 @@
package claims
import "testing"
func TestExtract(t *testing.T) {
cases := []struct {
in string
want []int64
units []string
skipped string
}{
{in: "that file is 6,884 lines long", want: []int64{6884}, units: []string{"lines"}},
{in: "took 200ms over the wire", want: []int64{200}, units: []string{"ms"}},
{in: "11 files changed and 3 commits", want: []int64{11}, units: []string{"files"}, skipped: "3 commits is below the noise floor"},
{in: "no numbers to see here", want: nil},
{in: "version 2.31 of the thing", want: nil, skipped: "no unit"},
}
for _, c := range cases {
got := Extract(c.in)
if len(got) != len(c.want) {
t.Errorf("%q: got %d findings (%v), want %d", c.in, len(got), got, len(c.want))
continue
}
for i := range got {
if got[i].Value != c.want[i] || got[i].Unit != c.units[i] {
t.Errorf("%q: finding %d = (%d,%q), want (%d,%q)", c.in, i, got[i].Value, got[i].Unit, c.want[i], c.units[i])
}
}
}
}
// TestMarkRequiresUnit: the failure this guards against is subtle — matching a
// bare number is so loose that "200MB" counts as backed by any output
// containing 200. The unit has to agree.
func TestMarkRequiresUnit(t *testing.T) {
f := Extract("6884 lines")
if got := Mark(append([]Finding(nil), f...), []string{"44 files changed, 6884 deletions(-)"}); got[0].Sourced {
t.Error("6884 lines must not be backed by '6884 deletions'")
}
if got := Mark(append([]Finding(nil), f...), []string{"6884 lines (12%)"}); !got[0].Sourced {
t.Error("6884 lines should be backed by an output saying 6884 lines")
}
if got := Mark(append([]Finding(nil), f...), []string{"6,884 lines"}); !got[0].Sourced {
t.Error("thousands separators must not defeat the match")
}
}
// TestLintClassification walks the three outcomes the CLI reports.
func TestLintClassification(t *testing.T) {
s := &Session{
ID: "s1",
Messages: []Message{
{Role: "user", Seq: 1, Text: []string{"how many files?"}},
{Role: "assistant", Seq: 2, Outputs: []string{"44 files changed"}},
// Same turn as the tool result: legitimately sourced.
{Role: "assistant", Seq: 3, Text: []string{"that is 44 files"}},
{Role: "user", Seq: 4, Text: []string{"thanks"}},
// New turn, no tool call: restating the earlier figure.
{Role: "assistant", Seq: 5, Text: []string{"as I said, 44 files"}},
// Never observed anywhere.
{Role: "assistant", Seq: 6, Text: []string{"probably 999 files"}},
},
}
got := map[int64]Status{}
for _, r := range Lint(s) {
got[r.Seq] = r.Status
}
if got[3] != Sourced {
t.Errorf("seq 3: got %v, want sourced (tool result in the same turn)", got[3])
}
if got[5] != Stale {
t.Errorf("seq 5: got %v, want stale (restated from an earlier turn without re-checking)", got[5])
}
if got[6] != Unsupported {
t.Errorf("seq 6: got %v, want unsupported (never printed by a tool)", got[6])
}
}
+232
View File
@@ -0,0 +1,232 @@
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.
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 m.id, m.seq, m.type, p.data
FROM session_message m
JOIN part p ON p.message_id = m.id
WHERE m.session_id = ?
ORDER BY m.seq, p.time_created, p.id`, sessionID)
if err != nil {
return nil, err
}
defer rows.Close()
byID := make(map[string]*Message)
var order []string
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, ok := byID[id]
if !ok {
m = &Message{ID: id, Seq: seq, Role: typ}
byID[id] = m
order = append(order, id)
}
appendPart(m, data)
}
if err := rows.Err(); err != nil {
return nil, err
}
for _, id := range order {
s.Messages = append(s.Messages, *byID[id])
}
return s, nil
}
// appendPart decodes one part row, 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, data string) {
var p map[string]any
if err := json.Unmarshal([]byte(data), &p); err != nil {
return
}
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
}
if out := asString(state["output"]); out != "" {
m.Outputs = append(m.Outputs, out)
}
}
}
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, earlierOutputs []string
for _, m := range s.Messages {
if m.Role == "user" {
earlierOutputs = append(earlierOutputs, turnOutputs...)
turnOutputs = nil
continue
}
turnOutputs = append(turnOutputs, m.Outputs...)
if m.Role != "assistant" || len(m.Text) == 0 {
continue
}
prose := strings.Join(m.Text, "\n")
for _, f := range Mark(Extract(prose), turnOutputs) {
run := LintRun{MessageID: m.ID, Seq: m.Seq, Finding: f, Status: Sourced}
if !f.Sourced {
run.Status = Unsupported
if len(Mark([]Finding{f}, earlierOutputs)) == 1 && Mark([]Finding{f}, earlierOutputs)[0].Sourced {
run.Status = Stale
}
}
out = append(out, run)
}
}
return out
}
+103
View File
@@ -0,0 +1,103 @@
package cmd
import (
"encoding/json"
"fmt"
"strings"
"github.com/david/knox/internal/claims"
"github.com/spf13/cobra"
)
// NewClaimsCmd exposes the sourced-claim check: numeric assertions in assistant
// prose that no tool call in the same message backed.
func NewClaimsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "claims",
Short: "Audit numeric claims in session transcripts for missing evidence",
}
var (
sessionID string
dbPath string
jsonOut bool
)
lintCmd := &cobra.Command{
Use: "lint",
Short: "Report numeric assertions that no tool result in the same message supports",
Long: `Report numeric assertions that no tool result in the same message supports.
A claim is "sourced" when a tool call in the same assistant message printed the
same number. Restating a figure from an earlier turn without re-checking it is
exactly what this flags: repetition should lower confidence, not raise it.`,
RunE: func(c *cobra.Command, args []string) error {
db, err := claims.Open(dbPath)
if err != nil {
return err
}
defer db.Close()
if sessionID == "" {
sessionID, err = claims.LatestSession(db)
if err != nil {
return fmt.Errorf("no sessions found: %w", err)
}
}
s, err := claims.LoadSession(db, sessionID)
if err != nil {
return err
}
runs := claims.Lint(s)
var stale, unsupported, sourced int
var flagged []claims.LintRun
for _, r := range runs {
switch r.Status {
case claims.Stale:
stale++
flagged = append(flagged, r)
case claims.Unsupported:
unsupported++
flagged = append(flagged, r)
default:
sourced++
}
}
if jsonOut {
b, _ := json.MarshalIndent(map[string]any{
"session": s.ID,
"title": s.Title,
"claims": len(runs),
"sourced": sourced,
"stale": stale,
"unsupported": unsupported,
"findings": flagged,
}, "", " ")
fmt.Println(string(b))
return nil
}
fmt.Printf("session %s (%s)\n", s.ID, strings.TrimSpace(s.Title))
fmt.Printf("claims: %d checked — %d sourced, %d stale, %d unsupported\n",
len(runs), sourced, stale, unsupported)
for _, r := range flagged {
mark := "✗"
if r.Status == claims.Sourced {
mark = "✓"
}
fmt.Printf(" %s %-11s msg %-4d %s\n", mark, r.Status, r.Seq, r.Finding.Assertion)
}
if len(flagged) == 0 {
fmt.Println("every numeric claim was backed by a tool result in its own turn")
}
return nil
},
}
lintCmd.Flags().StringVar(&sessionID, "session", "", "Session id (default: most recently updated)")
lintCmd.Flags().StringVar(&dbPath, "db", "", "opencode database path (default: ~/.local/share/opencode/opencode.db)")
lintCmd.Flags().BoolVar(&jsonOut, "json", false, "Machine-readable output")
cmd.AddCommand(lintCmd)
return cmd
}