Compare commits

...
Author SHA1 Message Date
BaaRai 478bdcae82 fix(tools): degrade stale or invalid evidence_hint_id cleanly in report_finding (#550) 2026-11-27 01:08:45 +01:00
BaaRai efe588a526 fix(compaction): omit hardcoded thinking=disabled to avoid Anthropic 400 (#550) 2026-11-27 01:08:45 +01:00
4851aeea5a fix(db): check rows.Err after iterating query results (#539)
ListLogs, ListLogsBefore and the two task_relations reads in the task
archive code never checked rows.Err(). When a result set fails partway
(connection drop, statement timeout), Next returns false and closes the
rows, so the later Close returns nil and the caller got a silently
truncated list: missing log lines, or an archive whose source tasks
are incomplete.


Claude-Session: https://claude.ai/code/session_01JNRiKGwr3P1LP1njD8FbR4

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-27 00:15:26 +01:00
BaaRai f76810aa04 Merge pull request #522 from BaaRai/feat/knowledge-pack
feat(agent): add versioned knowledge pack and knowledge_lookup tool
2026-11-27 00:15:05 +01:00
9 changed files with 397 additions and 13 deletions
+18 -2
View File
@@ -537,16 +537,32 @@ func buildCompressionInput(g *coldGraph, b block, nodeByID map[int64]*db.Node) s
return sb.String()
}
// isThinkingBetweenToolsError reports an Anthropic 400 telling the caller that
// the model rejects thinking.type="disabled" and requires "between_tools" instead
// (e.g. Claude Sonnet 5.5, #550).
func isThinkingBetweenToolsError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "between_tools") && strings.Contains(msg, "thinking")
}
// compress runs the §4 body LLM call on one block. Uses the same model the agent
// runs on; thinking disabled (a pure summarization step).
// runs on without forcing thinking.type="disabled" (models such as Claude Sonnet
// 5.5 reject {"type":"disabled"} with HTTP 400; inheriting the profile's working
// thinking setting avoids sending an unsupported parameter, #550).
func (c *Compactor) compress(ctx context.Context, g *coldGraph, b block, nodeByID map[int64]*db.Node) (string, error) {
req := llm.CompletionRequest{
System: []string{compressionSystem},
Messages: []llm.Message{llm.UserText(buildCompressionInput(g, b, nodeByID))},
MaxTokens: 1500,
Thinking: "disabled",
}
msg, _, _, err := c.prov.Complete(ctx, req)
if err != nil && isThinkingBetweenToolsError(err) {
req.Thinking = "between_tools"
msg, _, _, err = c.prov.Complete(ctx, req)
}
if err != nil {
return "", err
}
+146
View File
@@ -0,0 +1,146 @@
package agent
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/norma/llm"
)
func sampleCompactionInputs() (*coldGraph, block, map[int64]*db.Node) {
n1 := &db.Node{ID: 10, Kind: db.KindIntent, State: "done", Payload: json.RawMessage(`{"summary":"Scan /api/login"}`)}
n2 := &db.Node{ID: 11, Kind: db.KindFact, State: "confirmed", Payload: json.RawMessage(`{"summary":"Login returns 401"}`)}
g := newColdGraph(
[]cgNode{
{ID: 10, Kind: db.KindIntent, State: "done"},
{ID: 11, Kind: db.KindFact, State: "confirmed"},
},
[]cgEdge{
{From: 10, Rel: db.RelYields, To: 11},
},
)
b := block{Members: []int64{10, 11}}
return g, b, map[int64]*db.Node{10: n1, 11: n2}
}
// Regression for #550: compaction must not hardcode thinking={"type":"disabled"},
// which Claude Sonnet 5.5 rejects with HTTP 400 invalid_request_error.
func TestCompactorCompressDoesNotSendThinkingDisabled(t *testing.T) {
var (
mu sync.Mutex
bodies []map[string]any
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
mu.Lock()
bodies = append(bodies, m)
mu.Unlock()
if th, ok := m["thinking"].(map[string]any); ok && th["type"] == "disabled" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"To turn thinking off on this model, send \"thinking\": {\"type\": \"between_tools\"} instead of {\"type\": \"disabled\"}. The model does not think before responding."}}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"Consolidated summary (#10,#11)."}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":6}}`))
}))
defer srv.Close()
prov, err := llm.NewProvider(llm.Config{
Format: llm.FormatAnthropic,
BaseURL: srv.URL,
APIKey: "test-key",
Model: "claude-sonnet-5-5",
})
if err != nil {
t.Fatal(err)
}
c := NewCompactor(prov, "claude-sonnet-5-5")
g, b, nodes := sampleCompactionInputs()
got, err := c.compress(context.Background(), g, b, nodes)
if err != nil {
t.Fatalf("compress failed: %v", err)
}
if got != "Consolidated summary (#10,#11)." {
t.Fatalf("unexpected compressed body: %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(bodies) != 1 {
t.Fatalf("expected 1 request, got %d", len(bodies))
}
if _, hasThinking := bodies[0]["thinking"]; hasThinking {
t.Fatalf("compaction request must not send rejected thinking parameter when profile has none: %+v", bodies[0]["thinking"])
}
}
// Regression for #550: if a profile itself sets ThinkingType="disabled" and the
// provider returns the Anthropic 400 requesting thinking.type="between_tools",
// compaction retries once with "between_tools" and succeeds.
func TestCompactorCompressRetriesWithBetweenToolsOnAnthropic400(t *testing.T) {
var (
mu sync.Mutex
thinkingTypes []string
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
tt := ""
if th, ok := m["thinking"].(map[string]any); ok {
tt, _ = th["type"].(string)
}
mu.Lock()
thinkingTypes = append(thinkingTypes, tt)
mu.Unlock()
if tt == "disabled" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"To turn thinking off on this model, send \"thinking\": {\"type\": \"between_tools\"} instead of {\"type\": \"disabled\"}."}}`))
return
}
if tt != "between_tools" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"unexpected thinking mode"}}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"msg_2","type":"message","role":"assistant","content":[{"type":"text","text":"Summary via between_tools (#10,#11)."}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":6}}`))
}))
defer srv.Close()
prov, err := llm.NewProvider(llm.Config{
Format: llm.FormatAnthropic,
BaseURL: srv.URL,
APIKey: "test-key",
Model: "claude-sonnet-5-5",
ThinkingType: "disabled",
})
if err != nil {
t.Fatal(err)
}
c := NewCompactor(prov, "claude-sonnet-5-5")
g, b, nodes := sampleCompactionInputs()
got, err := c.compress(context.Background(), g, b, nodes)
if err != nil {
t.Fatalf("compress failed on between_tools fallback: %v", err)
}
if got != "Summary via between_tools (#10,#11)." {
t.Fatalf("unexpected compressed body: %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(thinkingTypes) != 2 || thinkingTypes[0] != "disabled" || thinkingTypes[1] != "between_tools" {
t.Fatalf("expected thinking sequence [disabled between_tools], got %v", thinkingTypes)
}
}
+112
View File
@@ -107,3 +107,115 @@ func TestReportFindingNonHintNodeDegradesToExplicitRefs(t *testing.T) {
t.Fatalf("explicit proof ref did not survive: %+v", rec.got)
}
}
// Regression for #550: absent, null, empty, zero, or negative evidence_hint_id
// must succeed even when no explicit traffic_refs are supplied (the default
// workflow where the report agent binds traffic afterward).
func TestReportFindingAbsentOrZeroHintIDWithoutTrafficRefs(t *testing.T) {
prev := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(prev) })
SetFindingTrafficBindingEnabled(func() bool { return true })
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("absent hint id", "fixture", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
}()
cases := []struct {
name string
body string
}{
{"omitted", `{"vulnclass":"SQLI","severity":"high","summary":"omitted hint","evidence":"UNION rows"}`},
{"zero", `{"vulnclass":"SQLI","severity":"high","summary":"zero hint","evidence":"UNION rows","evidence_hint_id":0}`},
{"null", `{"vulnclass":"SQLI","severity":"high","summary":"null hint","evidence":"UNION rows","evidence_hint_id":null}`},
{"empty_string", `{"vulnclass":"SQLI","severity":"high","summary":"empty hint","evidence":"UNION rows","evidence_hint_id":""}`},
{"negative", `{"vulnclass":"SQLI","severity":"high","summary":"negative hint","evidence":"UNION rows","evidence_hint_id":-5}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ts := NewToolSet(nil, "")
ts.ts, ts.taskID = d.Exploration(task.ExplorationID), task.ID
rec := &capturingRecorder{}
ts.SetFindingRecorder(rec)
res, err := ts.addFinding().Call(t.Context(), json.RawMessage(tc.body), nil)
if err != nil {
t.Fatalf("report_finding returned error: %v", err)
}
if got := res.Flatten(); !strings.HasPrefix(got, "finding recorded: ") {
t.Fatalf("%s rejected: %q", tc.name, got)
}
if len(rec.got) != 0 {
t.Fatalf("%s unexpectedly bound refs: %+v", tc.name, rec.got)
}
})
}
}
// Regression for #550: a stale/deleted or non-hint evidence_hint_id passed
// without explicit traffic_refs must degrade cleanly (record the finding as
// not_bound with an explanatory evidence_note) instead of discarding it.
func TestReportFindingStaleOrNonHintIDWithoutTrafficRefsDegradesCleanly(t *testing.T) {
prev := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(prev) })
SetFindingTrafficBindingEnabled(func() bool { return true })
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("stale hint id", "fixture", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
}()
exp := d.Exploration(task.ExplorationID)
factID, err := exp.AddNode(db.KindFact, map[string]any{"summary": "not a hint"}, 0, "confirmed", "worker", nil)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
hintID int64
}{
{"stale_nonexistent", 999999},
{"non_hint_fact_node", factID},
} {
t.Run(tc.name, func(t *testing.T) {
rec := &capturingRecorder{}
ts := NewToolSet(nil, "")
ts.ts, ts.taskID = exp, task.ID
ts.SetFindingRecorder(rec)
body, _ := json.Marshal(map[string]any{
"vulnclass": "XSS",
"severity": "medium",
"summary": "stale hint finding",
"evidence": "reflected payload",
"evidence_hint_id": tc.hintID,
})
res, err := ts.addFinding().Call(t.Context(), json.RawMessage(body), nil)
if err != nil {
t.Fatalf("report_finding returned error: %v", err)
}
got := res.Flatten()
if !strings.HasPrefix(got, "finding recorded: ") {
t.Fatalf("stale/non-hint evidence_hint_id discarded finding: %q", got)
}
if !strings.Contains(got, "Ignored stale or non-local evidence_hint_id=") {
t.Fatalf("expected explanatory evidence_note, got: %q", got)
}
if len(rec.got) != 0 {
t.Fatalf("expected 0 refs on degraded stale hint, got %+v", rec.got)
}
})
}
}
+8 -1
View File
@@ -2,6 +2,7 @@ package agent
import (
"encoding/json"
"errors"
"fmt"
"sync"
@@ -227,6 +228,12 @@ func HintTrafficSchema() map[string]any {
return map[string]any{"type": "array", "description": "Optional: verified traffic references corresponding to the specific vulnerability in this hint, order preserved; after handoff, report_finding can carry these references via evidence_hint_id.", "items": obj(map[string]any{"traffic_id": str("real traffic ID"), "role": str("baseline / proof / verification / supporting"), "note": str("which conclusion this traffic supports")}, "traffic_id")}
}
// errEvidenceHintNotFound marks an evidence_hint_id that does not resolve to a
// local hint node of the current task (e.g. stale/deleted ID, inherited hint, or
// non-hint node ID). report_finding degrades cleanly instead of discarding the
// finding (#550).
var errEvidenceHintNotFound = errors.New("evidence_hint_id is not a local hint node")
func (t *ToolSet) findingRefsFromHint(hintID int64, explicit []db.TrafficRef) ([]db.TrafficRef, error) {
if hintID <= 0 {
return db.NormalizeTrafficRefs(explicit)
@@ -236,7 +243,7 @@ func (t *ToolSet) findingRefsFromHint(hintID int64, explicit []db.TrafficRef) ([
return nil, err
}
if n == nil || n.Kind != db.KindHint {
return nil, fmt.Errorf("evidence_hint_id=%d must be a hint node of this task (inherited hints cannot be bound directly)", hintID)
return nil, fmt.Errorf("%w: evidence_hint_id=%d must be a hint node of this task (inherited hints cannot be bound directly)", errEvidenceHintNotFound, hintID)
}
var payload struct {
Refs []db.TrafficRef `json:"traffic_refs"`
+24 -9
View File
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strconv"
@@ -1602,16 +1603,23 @@ func (t *ToolSet) addFinding() actool.CoreTool {
if !findingTrafficBindingEnabled() {
a.TrafficRefs, a.EvidenceHintID = nil, nil
}
// A model routinely emits "evidence_hint_id": 0 meaning "absent" — the field
// is optional, so 0 must mean "no hint", not an error. A hint id that does
// not resolve to a local hint node (passing a fact node number is the common
// case) must not sink an otherwise complete finding either: when explicit
// traffic_refs are present they are sufficient on their own, so degrade to
// them and keep the finding. Only a call with neither usable hint nor usable
// refs fails.
refs, err := t.findingRefsFromHint(pid(a.EvidenceHintID), a.TrafficRefs)
// A model routinely emits "evidence_hint_id": 0 (or null/"") meaning "absent",
// or passes a stale/non-hint node ID. Because evidence_hint_id is optional and
// findings without bound traffic are valid (the report agent binds traffic later),
// a stale or non-local hint ID must degrade cleanly to whatever valid explicit
// traffic_refs were passed (including none) instead of discarding the finding (#550).
hintID := pid(a.EvidenceHintID)
var ignoredHintNote string
refs, err := t.findingRefsFromHint(hintID, a.TrafficRefs)
if err != nil {
if degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs); derr == nil && len(degraded) > 0 {
if errors.Is(err, errEvidenceHintNotFound) {
degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs)
if derr != nil {
return actool.Errorf(derr.Error()), nil
}
refs = degraded
ignoredHintNote = fmt.Sprintf("Ignored stale or non-local evidence_hint_id=%d; finding recorded without hint references.", hintID)
} else if degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs); derr == nil && len(degraded) > 0 {
refs = degraded
} else {
return actool.Errorf(err.Error()), nil
@@ -1682,6 +1690,13 @@ func (t *ToolSet) addFinding() actool.CoreTool {
result.EvidenceNote = "Finding saved without bound traffic. Automatic agent traffic binding is off: this finding remains visible but cannot close a goal unless traffic is bound manually later (or a non-HTTP goal is proven with an observed tool_output fact)."
}
}
if ignoredHintNote != "" {
if result.EvidenceNote != "" {
result.EvidenceNote = ignoredHintNote + " " + result.EvidenceNote
} else {
result.EvidenceNote = ignoredHintNote
}
}
raw, _ := json.Marshal(result)
return actool.Text(fmt.Sprintf("finding recorded: %d\n%s", recorded.NodeID, raw)), nil
})
+6
View File
@@ -43,6 +43,9 @@ func (d *DB) RecentLogs(limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
@@ -70,6 +73,9 @@ func (d *DB) ListLogsBefore(beforeID int64, limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
+66
View File
@@ -0,0 +1,66 @@
package db
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"sync"
"testing"
"time"
)
type midStreamErrDriver struct{}
type midStreamErrConn struct{}
type midStreamErrRows struct{ n int }
func (midStreamErrDriver) Open(string) (driver.Conn, error) { return midStreamErrConn{}, nil }
func (midStreamErrConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unused") }
func (midStreamErrConn) Close() error { return nil }
func (midStreamErrConn) Begin() (driver.Tx, error) { return nil, errors.New("unused") }
func (midStreamErrConn) QueryContext(_ context.Context, _ string, _ []driver.NamedValue) (driver.Rows, error) {
return &midStreamErrRows{}, nil
}
func (r *midStreamErrRows) Columns() []string {
return []string{"id", "created_at", "level", "tag", "text"}
}
func (r *midStreamErrRows) Close() error { return nil }
func (r *midStreamErrRows) Next(dest []driver.Value) error {
if r.n == 0 {
r.n++
dest[0] = int64(1)
dest[1] = time.Now()
dest[2] = "info"
dest[3] = "test"
dest[4] = "first row"
return nil
}
if r.n == 1 {
r.n++
return errors.New("simulated mid-stream connection drop")
}
return io.EOF
}
var registerMidStreamErrDriverOnce sync.Once
func TestLogsMethodsReturnRowsErr(t *testing.T) {
registerMidStreamErrDriverOnce.Do(func() {
sql.Register("artex_test_mid_stream_err", midStreamErrDriver{})
})
raw, err := sql.Open("artex_test_mid_stream_err", "")
if err != nil {
t.Fatal(err)
}
defer raw.Close()
d := &DB{DB: raw}
if _, err := d.RecentLogs(10); err == nil {
t.Fatal("RecentLogs returned nil error on mid-stream rows.Next failure")
}
if _, err := d.ListLogsBefore(100, 10); err == nil {
t.Fatal("ListLogsBefore returned nil error on mid-stream rows.Next failure")
}
}
+12
View File
@@ -295,6 +295,12 @@ LIMIT 1`, taskID).Scan(&dependent)
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
@@ -664,6 +670,12 @@ func (d *DB) snapshotTaskArchive(taskID int64, llmRecords io.Writer) (*TaskArchi
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
+5 -1
View File
@@ -873,7 +873,11 @@ func (s *Server) emitTaskLLMTransition(t *Task, transition db.TaskLLMTransition,
}
mode := "automatic"
kind := "llm_switch"
summary := fmt.Sprintf("%s quota exhausted", llmAuditProfileLabel(previous))
reasonLabel := "failed consecutive calls"
if isQuotaExhaustedError(cause) {
reasonLabel = "quota exhausted"
}
summary := fmt.Sprintf("%s %s", llmAuditProfileLabel(previous), reasonLabel)
if transition.NextProfileID != nil {
summary += fmt.Sprintf(", subsequent calls switched to %s", llmAuditProfileLabel(next))
} else {