diff --git a/agent/compaction.go b/agent/compaction.go index e3c6fcb0..8052135a 100644 --- a/agent/compaction.go +++ b/agent/compaction.go @@ -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 } diff --git a/agent/compaction_thinking_test.go b/agent/compaction_thinking_test.go new file mode 100644 index 00000000..18ca13eb --- /dev/null +++ b/agent/compaction_thinking_test.go @@ -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) + } +} diff --git a/agent/finding_hint_degrade_test.go b/agent/finding_hint_degrade_test.go index 0ecf7242..a8270dbc 100644 --- a/agent/finding_hint_degrade_test.go +++ b/agent/finding_hint_degrade_test.go @@ -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) + } + }) + } +} diff --git a/agent/finding_workflow.go b/agent/finding_workflow.go index a44a689d..50fa8461 100644 --- a/agent/finding_workflow.go +++ b/agent/finding_workflow.go @@ -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"` diff --git a/agent/tools.go b/agent/tools.go index 1f7d7eb8..52dd7c0f 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -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 }) diff --git a/server/task_llm.go b/server/task_llm.go index 4e3968cf..322e7cea 100644 --- a/server/task_llm.go +++ b/server/task_llm.go @@ -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 {