Files
knox/plugins/claims/index.ts
T
david c8fd031f6c
build / test (push) Has been cancelled
build / image (push) Has been cancelled
feat: persist the claim ledger with an inverted SM-2 interval (#26)
The plugin could already warn about a restated figure within one transcript.
This makes it remember across turns and sessions.

A claim is keyed by unit+value, so '6,884 lines' and '6884 lines' are the same
claim. Interval arithmetic is SM-2 with the sign flipped: verification expands
the interval and restores ease, while restating a claim without new evidence
contracts ease and falls due immediately — repetition is the failure signal,
not the achievement.

Adds 'knox claims record' (fold check verdicts into the ledger) and 'knox claims
due' (what needs re-checking). The plugin records once per distinct prose (the
context hook fires for every model call, so naive recording would inflate the
reuse count) and injects a capped digest at turn start.

Two bugs caught by the tests: a new claim defaulted to EF=0 and contracted
straight to the 1.3 floor, and my first test encoded the wrong policy — a
single restatement is already due, which is the behaviour worth having.
2026-11-04 19:52:52 -08:00

261 lines
8.8 KiB
TypeScript

// NOTE: no import from "@opencode/plugin". A local plugin loaded by path cannot
// resolve that bare specifier — verified by experiment: identical code without
// the import loads, with it the plugin fails with "Plugin failed to load".
// `Plugin.define` is an identity function in the runtime, so exporting the
// definition object directly is equivalent.
import { execFile } from "node:child_process"
import { existsSync } from "node:fs"
/**
* knox.claims — warn when a model request restates a figure that an earlier
* turn measured but this turn did not.
*
* The failure it targets is not ignorance, it is drift: a number derived once
* (sometimes against the wrong reference) gets quoted in later turns, and each
* restatement makes it feel more established. The check is deterministic — no
* model calls — and rides the `context` hook, which runs immediately before a
* request is dispatched, including tool-driven continuations.
*
* Classification lives in the knox binary (`knox claims check`, JSON on stdin)
* so there is exactly one implementation, and it is the tested one.
*/
// The OpenCode server does not inherit the service's PATH, so prefer the
// checkout binary when it exists and fall back to PATH lookup.
const DEFAULT_BIN = `${process.env.HOME ?? ""}/assistant/knox/knox`
const BIN = process.env.KNOX_BIN ?? (existsSync(DEFAULT_BIN) ? DEFAULT_BIN : "knox")
const TIMEOUT_MS = 2000
const INGEST_TIMEOUT_MS = 60_000
type Finding = { assertion: string; value: number; unit: string; status: string }
type Turn = {
/** Assistant prose in the current turn (since the last user message). */
prose: string
/** Tool output in the current turn. */
outputs: string[]
/** Everything the assistant asserted in earlier turns. */
priorProse: string
}
function roleOf(msg: any): string {
return String(msg?.role ?? msg?.info?.role ?? "").toLowerCase()
}
/** Text the assistant wrote, ignoring tool payloads. */
function proseOf(msg: any): string {
const content = msg?.content ?? msg?.parts
if (typeof content === "string") return content
if (!Array.isArray(content)) return ""
return content
.filter((p: any) => p?.type === "text" && typeof p?.text === "string")
.map((p: any) => p.text as string)
.join("\n")
}
/** Anything a tool printed, in whatever shape the SDK used. */
function outputsOf(msg: any): string[] {
const out: string[] = []
const push = (v: any) => {
if (typeof v === "string") out.push(v)
else if (v && typeof v === "object") {
try {
out.push(JSON.stringify(v))
} catch {
/* unrepresentable: skip it */
}
}
}
const content = msg?.content ?? msg?.parts
if (Array.isArray(content)) {
for (const part of content) {
const type = String(part?.type ?? "")
if (type.includes("tool")) {
push(part?.output)
push(part?.result)
push(part?.content)
}
}
}
// Some transports emit tool results as their own message role.
if (roleOf(msg) === "tool") push(msg?.content)
return out
}
/**
* Split the assembled messages into the current turn (since the last user
* message) and everything before it. The boundary matters: a figure quoted
* from an earlier turn is exactly what we want to flag.
*/
function splitTurns(messages: any[]): Turn {
const prior: string[] = []
let currentOutputs: string[] = []
let currentProse = ""
let priorProse = ""
for (const msg of messages) {
const role = roleOf(msg)
if (role === "user") {
// The turn just ended: its prose becomes prior context, its tool output
// is no longer evidence for anything the next turn claims.
if (currentProse) prior.push(currentProse)
currentProse = ""
currentOutputs = []
continue
}
if (role === "assistant") {
const text = proseOf(msg)
if (text) currentProse = text
currentOutputs.push(...outputsOf(msg))
continue
}
currentOutputs.push(...outputsOf(msg))
}
priorProse = prior.join("\n")
return { prose: currentProse, outputs: currentOutputs, priorProse }
}
function check(turn: Turn): Promise<Finding[]> {
return new Promise((resolve) => {
const child = execFile(
BIN,
["claims", "check"],
{ timeout: TIMEOUT_MS, maxBuffer: 1 << 20 },
(err, stdout) => {
// A missing binary, a timeout, or bad JSON must never break a request.
if (err) return resolve([])
try {
const parsed = JSON.parse(stdout)
resolve(Array.isArray(parsed.findings) ? parsed.findings : [])
} catch {
resolve([])
}
},
)
child.stdin?.end(JSON.stringify({
prose: turn.prose,
outputs: turn.outputs,
prior_prose: turn.priorProse,
}))
})
}
// Guard against overlapping sweeps when prompts arrive quickly.
let refreshing = false
// The context hook fires for every model call, including tool continuations, so
// the same prose would be recorded again and again and inflate reuse_count.
// Remember what was last recorded per session and only record on change.
const recordedProse = new Map<string, string>()
/** Persist verdicts into the ledger (fire-and-forget). */
function record(sessionID: string, prose: string, findings: Finding[]): void {
if (findings.length === 0) return
const seen = recordedProse.get(sessionID)
if (seen === prose) return
recordedProse.set(sessionID, prose)
const child = execFile(BIN, ["claims", "record"], { timeout: INGEST_TIMEOUT_MS }, () => {})
child.stdin?.end(JSON.stringify({ findings }))
}
type DueClaim = { Assertion: string; ReuseCount: number; VerifyCount: number }
/** Claims the ledger says are overdue for a re-check. */
function dueClaims(): Promise<DueClaim[]> {
return new Promise((resolve) => {
execFile(
BIN,
["claims", "due", "--json", "--limit", "3"],
{ timeout: TIMEOUT_MS, maxBuffer: 1 << 20 },
(err, stdout) => {
if (err) return resolve([])
try {
const parsed = JSON.parse(stdout)
resolve(Array.isArray(parsed) ? parsed : [])
} catch {
resolve([])
}
},
)
})
}
/**
* Re-index opencode sessions in the background.
*
* knox's watcher polls opencode.db every two minutes, so a finished turn is not
* searchable for up to that long. Running the scoped sweep at prompt admission
* closes the gap: it is fire-and-forget (~45 ms steady state thanks to the
* watermark), so it never delays the turn it is triggered by.
*/
function refreshSessions(): void {
if (refreshing) return
refreshing = true
execFile(BIN, ["ingest", "sessions"], { timeout: INGEST_TIMEOUT_MS }, () => {
refreshing = false
})
}
export default {
id: "knox.claims",
async setup(ctx: any) {
// Ahead of the guardrail: fresher index, and this is the natural place for
// recall to read from once it exists.
await ctx.session.hook("prompt", () => {
refreshSessions()
})
// Turn-start digest from the ledger: claims this machine keeps restating
// without ever re-checking. Cross-session, which the per-message warning
// cannot be.
await ctx.session.hook("context", async (event: any) => {
try {
const messages = (event.messages ?? []) as any[]
const last = messages[messages.length - 1]
if (roleOf(last) !== "user") return
const due = await dueClaims()
if (due.length === 0) return
const list = due
.map((d) => `"${d.Assertion}" (restated ${d.ReuseCount}x since last check)`)
.join("; ")
event.system.push({
type: "text",
text:
`Claims in the ledger that need re-checking before reuse: ${list}. ` +
`Re-measure or state where the figure came from.`,
})
} catch {
/* a digest must never break the turn */
}
})
await ctx.session.hook("context", async (event: any) => {
try {
const turn = splitTurns(event.messages as any[])
if (!turn.prose) return
const findings = await check(turn)
record(String(event.sessionID ?? "unknown"), turn.prose, findings)
// Only stale claims: "unsupported" is usually a hypothetical, and
// warning on those trains the reader to ignore the warning.
const stale = findings.filter((f) => f.status === "stale")
if (stale.length === 0) return
const list = stale.map((f) => f.assertion).join(", ")
event.system.push({
type: "text",
text:
`Unsourced figures in the previous turn: ${list}. ` +
`They were measured earlier in this session but no tool in the current turn produced them. ` +
`Re-run the check, or state the reference the figure came from, before relying on it.`,
})
} catch {
// Never let the guardrail break the request it is guarding.
}
})
},
}