Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ab9066486a |
@@ -119,39 +119,3 @@ func Unsourced(findings []Finding) []Finding {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scored is a finding with the verdict for a specific evidence window.
|
|
||||||
type Scored struct {
|
|
||||||
Finding
|
|
||||||
Status Status
|
|
||||||
}
|
|
||||||
|
|
||||||
// Classify tags findings against this turn's tool output and the claims this
|
|
||||||
// session already made in earlier turns. It is the single place that decides
|
|
||||||
// sourced/stale/unsupported, so the CLI and the live plugin cannot disagree.
|
|
||||||
//
|
|
||||||
// Staleness is measured against *earlier prose*, not earlier tool output, and
|
|
||||||
// that distinction matters: a tool printed "6884 deletions" while the prose
|
|
||||||
// said "6,884 lines", so matching tool output by number+unit called the real
|
|
||||||
// incident "unsupported" — silent. Comparing prose to prose catches the actual
|
|
||||||
// failure, which is restating a figure the session already asserted.
|
|
||||||
func Classify(findings []Finding, turnOutputs []string, priorProse string) []Scored {
|
|
||||||
prior := make(map[claimKey]struct{})
|
|
||||||
for _, c := range Extract(priorProse) {
|
|
||||||
prior[claimKey{c.Value, normUnit(c.Unit)}] = struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
out := make([]Scored, 0, len(findings))
|
|
||||||
for _, orig := range findings {
|
|
||||||
f := Mark([]Finding{orig}, turnOutputs)[0]
|
|
||||||
status := Sourced
|
|
||||||
if !f.Sourced {
|
|
||||||
status = Unsupported
|
|
||||||
if _, repeated := prior[claimKey{f.Value, normUnit(f.Unit)}]; repeated {
|
|
||||||
status = Stale
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out = append(out, Scored{Finding: f, Status: status})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -205,10 +205,10 @@ type LintRun struct {
|
|||||||
// quoted from an earlier turn count as unsourced.
|
// quoted from an earlier turn count as unsourced.
|
||||||
func Lint(s *Session) []LintRun {
|
func Lint(s *Session) []LintRun {
|
||||||
var out []LintRun
|
var out []LintRun
|
||||||
var turnOutputs []string
|
var turnOutputs, earlierOutputs []string
|
||||||
var priorProse strings.Builder
|
|
||||||
for _, m := range s.Messages {
|
for _, m := range s.Messages {
|
||||||
if m.Role == "user" {
|
if m.Role == "user" {
|
||||||
|
earlierOutputs = append(earlierOutputs, turnOutputs...)
|
||||||
turnOutputs = nil
|
turnOutputs = nil
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -217,11 +217,16 @@ func Lint(s *Session) []LintRun {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
prose := strings.Join(m.Text, "\n")
|
prose := strings.Join(m.Text, "\n")
|
||||||
for _, sc := range Classify(Extract(prose), turnOutputs, priorProse.String()) {
|
for _, f := range Mark(Extract(prose), turnOutputs) {
|
||||||
out = append(out, LintRun{MessageID: m.ID, Seq: m.Seq, Finding: sc.Finding, Status: sc.Status})
|
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)
|
||||||
}
|
}
|
||||||
priorProse.WriteString(prose)
|
|
||||||
priorProse.WriteString("\n")
|
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-41
@@ -3,7 +3,6 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/david/knox/internal/claims"
|
"github.com/david/knox/internal/claims"
|
||||||
@@ -99,45 +98,6 @@ exactly what this flags: repetition should lower confidence, not raise it.`,
|
|||||||
lintCmd.Flags().StringVar(&dbPath, "db", "", "opencode database path (default: ~/.local/share/opencode/opencode.db)")
|
lintCmd.Flags().StringVar(&dbPath, "db", "", "opencode database path (default: ~/.local/share/opencode/opencode.db)")
|
||||||
lintCmd.Flags().BoolVar(&jsonOut, "json", false, "Machine-readable output")
|
lintCmd.Flags().BoolVar(&jsonOut, "json", false, "Machine-readable output")
|
||||||
|
|
||||||
// check is the live contract used by the opencode plugin: it takes the
|
cmd.AddCommand(lintCmd)
|
||||||
// assembled turn from stdin and reports verdicts, so all the classification
|
|
||||||
// logic stays in one tested place instead of being reimplemented in TS.
|
|
||||||
checkCmd := &cobra.Command{
|
|
||||||
Use: "check",
|
|
||||||
Short: "Classify claims from a JSON turn on stdin (plugin interface)",
|
|
||||||
Long: `Read {"prose": "...", "outputs": [...], "prior_prose": "..."} on stdin and
|
|
||||||
report each numeric claim as sourced, stale or unsupported.
|
|
||||||
|
|
||||||
"outputs" are tool results from the current turn. "prior_prose" is everything
|
|
||||||
the assistant asserted in earlier turns of the same session: a figure repeated
|
|
||||||
from there without fresh evidence is what "stale" means.`,
|
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
|
||||||
var in struct {
|
|
||||||
Prose string `json:"prose"`
|
|
||||||
Outputs []string `json:"outputs"`
|
|
||||||
PriorProse string `json:"prior_prose"`
|
|
||||||
}
|
|
||||||
if err := json.NewDecoder(os.Stdin).Decode(&in); err != nil {
|
|
||||||
return fmt.Errorf("read stdin: %w", err)
|
|
||||||
}
|
|
||||||
scored := claims.Classify(claims.Extract(in.Prose), in.Outputs, in.PriorProse)
|
|
||||||
out := struct {
|
|
||||||
Findings []map[string]any `json:"findings"`
|
|
||||||
}{}
|
|
||||||
for _, s := range scored {
|
|
||||||
out.Findings = append(out.Findings, map[string]any{
|
|
||||||
"assertion": s.Assertion,
|
|
||||||
"value": s.Value,
|
|
||||||
"unit": s.Unit,
|
|
||||||
"status": s.Status.String(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
enc := json.NewEncoder(os.Stdout)
|
|
||||||
enc.SetIndent("", " ")
|
|
||||||
return enc.Encode(out)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd.AddCommand(lintCmd, checkCmd)
|
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
# knox.claims — OpenCode plugin
|
|
||||||
|
|
||||||
Warns when a request restates a figure that an earlier turn measured but the
|
|
||||||
current turn did not.
|
|
||||||
|
|
||||||
## Why
|
|
||||||
|
|
||||||
The failure mode is drift, not ignorance: a number is derived once — sometimes
|
|
||||||
against the wrong reference — then quoted in later turns, and each restatement
|
|
||||||
makes it feel more established. In this repo that produced "6,884 lines behind
|
|
||||||
main" from a diff measured against `bb852fa`, repeated across five turns, which
|
|
||||||
drove a branch decision that had to be undone.
|
|
||||||
|
|
||||||
## How it works
|
|
||||||
|
|
||||||
The `context` session hook runs immediately before a request is dispatched,
|
|
||||||
including tool-driven continuations. It gets the assembled messages, splits them
|
|
||||||
at the last user message, and passes:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "prose": "<last assistant text>", "outputs": ["<this turn's tool output>"], "earlier": ["<previous turns'>"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
to `knox claims check`, which replies with each numeric claim tagged
|
|
||||||
`sourced` / `stale` / `unsupported`. Only `stale` claims produce a warning, which
|
|
||||||
is appended as a system part for that request.
|
|
||||||
|
|
||||||
All classification lives in the Go binary, so the plugin cannot drift from the
|
|
||||||
tested implementation.
|
|
||||||
|
|
||||||
## Why there is no `@opencode/plugin` import
|
|
||||||
|
|
||||||
The docs show `import { Plugin } from "@opencode/plugin"`, but a local plugin
|
|
||||||
loaded by path cannot resolve that bare specifier. Verified by experiment:
|
|
||||||
|
|
||||||
| File | Imports | Result |
|
|
||||||
|---|---|---|
|
|
||||||
| `index.js` | none | active |
|
|
||||||
| `index.ts` | none | active |
|
|
||||||
| `index.ts` | `@opencode/plugin` | failed to load |
|
|
||||||
| `index.ts` | `@opencode-ai/plugin` | failed to load |
|
|
||||||
|
|
||||||
`Plugin.define` is an identity function in the runtime, so exporting the
|
|
||||||
definition object directly is exactly equivalent. Only `node:` builtins resolve.
|
|
||||||
|
|
||||||
## Enable
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
// ~/.config/opencode/opencode.json
|
|
||||||
{
|
|
||||||
"plugins": ["/home/david/assistant/knox/plugins/claims"]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Takes effect on the next `opencode service restart`.
|
|
||||||
|
|
||||||
## Configure
|
|
||||||
|
|
||||||
| Env | Default | Meaning |
|
|
||||||
|---|---|---|
|
|
||||||
| `KNOX_BIN` | `knox` (on `PATH`) | Binary to invoke. Set an absolute path when the daemon's PATH does not include it. |
|
|
||||||
|
|
||||||
## Failure behaviour
|
|
||||||
|
|
||||||
Every failure path is swallowed: a missing binary, a timeout (2 s), or malformed
|
|
||||||
JSON results in no warning and an unmodified request. A guardrail must never
|
|
||||||
break the thing it guards.
|
|
||||||
|
|
||||||
## Not implemented
|
|
||||||
|
|
||||||
- It cannot *force* a re-check; it appears in the system prompt as guidance.
|
|
||||||
- It only sees numeric claims in prose, not comparatives ("the trees are
|
|
||||||
identical") — those need a different signal and would be far noisier.
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
// 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
|
|
||||||
|
|
||||||
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,
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export default {
|
|
||||||
id: "knox.claims",
|
|
||||||
async setup(ctx: any) {
|
|
||||||
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)
|
|
||||||
// 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.
|
|
||||||
}
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user