Compare commits

...
Author SHA1 Message Date
BaaRai e5c7bfcbdd Merge pull request #586 from BaaRai/fix/585-decomposer-contract
fix(goals,planner): enforce structured set_goals and refuse empty planning context
2026-11-27 01:50:56 +01:00
BaaRai 10fb8d389d Merge pull request #589 from BaaRai/fix/473-finding-fingerprint-dedup
feat(agent): deterministic finding fingerprint dedup
2026-11-27 01:27:59 +01:00
BaaRai 066b978687 Merge pull request #588 from BaaRai/fix/526-conntest-reject-tool-calls
fix(agent): reject tool-call replies in the LLM connection test
2026-11-27 01:27:53 +01:00
BaaRai cc25ad55c4 Merge pull request #587 from BaaRai/fix/550-compaction-thinking-and-evidence-hint
fix(compaction,tools): stop forcing thinking=disabled and degrade stale evidence_hint_id
2026-11-27 01:27:49 +01:00
BaaRai 30d5b96a51 feat(agent): add deterministic finding fingerprint deduplication complementing LLM triage (#473) 2026-11-27 01:08:46 +01:00
BaaRai 1f558d8681 fix(agent): reject tool calls and tool_calls finish_reason in TestConnection (#526) 2026-11-27 01:08:46 +01:00
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
11 changed files with 996 additions and 14 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)
}
}
+74
View File
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -36,3 +37,76 @@ func TestConnectionSendsNoTools(t *testing.T) {
t.Fatalf("connection test sent %d tools, want none:\n%s", len(req.Tools), body)
}
}
// Regression for #526: Ollama returning a tool call (with or without accompanying
// text) or finish_reason="tool_calls", or whitespace-only content, must fail
// TestConnection instead of reporting Connected.
func TestConnectionRejectsToolCallsAndWhitespaceReplies(t *testing.T) {
cases := []struct {
name string
stream bool
statusBody string
wantErrSub string
}{
{
name: "ollama_nonstream_tool_call_with_text",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_tool_call_only",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_finish_reason_tool_calls_without_array",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}}`,
wantErrSub: "tool call",
},
{
name: "ollama_stream_tool_call_with_text",
stream: true,
statusBody: strings.Join([]string{
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"role":"assistant","content":"OK"}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`data: [DONE]`,
``,
}, "\n\n"),
wantErrSub: "tool call",
},
{
name: "ollama_whitespace_only_content",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":" \n\t "},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":3,"total_tokens":23}}`,
wantErrSub: "no content",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
} else {
w.Header().Set("Content-Type", "application/json")
}
_, _ = w.Write([]byte(tc.statusBody))
}))
defer srv.Close()
cfg := ConfigFrom("ollama", "baronllm", srv.URL+"/v1", "", "")
cfg.Stream = tc.stream
_, reply, err := TestConnection(context.Background(), cfg)
if err == nil {
t.Fatalf("expected TestConnection to reject %s, got Connected with reply=%q", tc.name, reply)
}
if !strings.Contains(strings.ToLower(err.Error()), tc.wantErrSub) {
t.Fatalf("unexpected error for %s: %v (want substring %q)", tc.name, err, tc.wantErrSub)
}
})
}
}
+317
View File
@@ -0,0 +1,317 @@
package agent
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log/slog"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"github.com/Autumn-27/artex/db"
)
// findingFingerprintMatch is a deterministic duplicate hit against an already
// registered finding (#473), complementing the advisory LLM triage pass.
type findingFingerprintMatch struct {
FindingID int64
NodeID int64
Fingerprint string
}
var (
fpURLRe = regexp.MustCompile(`(?i)\bhttps?://[^\s"'<>\]\)]+`)
fpMethodPathRe = regexp.MustCompile(`(?i)\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(/[^\s"'<>\]\)]+)`)
fpBarePathRe = regexp.MustCompile(`(?:^|[\s(\["'])(/[a-zA-Z0-9._~/%{}:-]+(?:\?[a-zA-Z0-9._~=&%-]+)?)`)
fpParamRe = regexp.MustCompile(`(?i)\b(?:param(?:eter)?|field|query\s+param(?:eter)?)\s*(?:=|:|\s+)\s*["'\x60]?([a-zA-Z_][a-zA-Z0-9_.-]{0,63})["'\x60]?`)
fpNonAlnumRe = regexp.MustCompile(`[^a-z0-9]+`)
)
// FindingFingerprint returns a deterministic SHA-256 fingerprint for a finding
// from three required axes (#473):
// 1. normalized vulnerability class / CWE,
// 2. canonical asset IDs (sorted/deduplicated) or URL host,
// 3. normalized affected endpoint path and/or parameter name.
//
// If any of the three axes cannot be extracted unambiguously, it returns "" so
// callers fall through to LLM triage / normal registration without false
// collisions.
func FindingFingerprint(in db.RecordFindingInput) string {
vulnClass := normalizeFingerprintToken(in.VulnClass)
if vulnClass == "" {
return ""
}
corpus := strings.Join([]string{in.Name, in.Summary, in.Evidence}, "\n")
assetKey := canonicalFindingAssetKey(in.AssetIDs, corpus)
if assetKey == "" {
return ""
}
endpointKey := canonicalFindingEndpointKey(corpus)
if endpointKey == "" {
return ""
}
h := sha256.Sum256([]byte(vulnClass + "\x00" + assetKey + "\x00" + endpointKey))
return "fp:" + hex.EncodeToString(h[:16])
}
func normalizeFingerprintToken(s string) string {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" {
return ""
}
s = fpNonAlnumRe.ReplaceAllString(s, "_")
return strings.Trim(s, "_")
}
func canonicalFindingAssetKey(assetIDs []int64, corpus string) string {
if len(assetIDs) > 0 {
seen := make(map[int64]struct{}, len(assetIDs))
ids := make([]int64, 0, len(assetIDs))
for _, id := range assetIDs {
if id > 0 {
if _, ok := seen[id]; !ok {
seen[id] = struct{}{}
ids = append(ids, id)
}
}
}
if len(ids) > 0 {
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
parts := make([]string, len(ids))
for i, id := range ids {
parts[i] = strconv.FormatInt(id, 10)
}
return "ids:" + strings.Join(parts, ",")
}
}
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
raw = strings.TrimRight(raw, ".,;:!?)")
u, err := url.Parse(raw)
if err != nil || strings.TrimSpace(u.Host) == "" {
continue
}
return "host:" + strings.ToLower(strings.TrimSuffix(u.Host, "."))
}
return ""
}
func canonicalFindingEndpointKey(corpus string) string {
var pathSig string
var paramNames []string
// Prefer explicit URLs first so scheme/host are stripped cleanly.
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
raw = strings.TrimRight(raw, ".,;:!?)")
u, err := url.Parse(raw)
if err != nil {
continue
}
p := normalizeEndpointPath(u.Path)
if p != "" {
pathSig = p
paramNames = append(paramNames, sortedQueryParamNames(u.RawQuery)...)
break
}
}
if pathSig == "" {
if m := fpMethodPathRe.FindStringSubmatch(corpus); len(m) == 2 {
pathSig, paramNames = splitPathAndQuery(m[1])
}
}
if pathSig == "" {
for _, m := range fpBarePathRe.FindAllStringSubmatch(corpus, 8) {
if len(m) != 2 {
continue
}
candidate := strings.TrimRight(m[1], ".,;:!?)")
// Ignore common filesystem/OS paths unless nothing else; require
// at least one route character after '/'.
if len(candidate) <= 1 || strings.HasPrefix(candidate, "//") {
continue
}
pathSig, paramNames = splitPathAndQuery(candidate)
if pathSig != "" {
break
}
}
}
for _, m := range fpParamRe.FindAllStringSubmatch(corpus, 4) {
if len(m) == 2 {
if name := strings.ToLower(strings.TrimSpace(m[1])); name != "" {
paramNames = append(paramNames, name)
}
}
}
paramNames = dedupSortedStrings(paramNames)
if pathSig == "" && len(paramNames) == 0 {
return ""
}
if len(paramNames) == 0 {
return "path:" + pathSig
}
return "path:" + pathSig + "|params:" + strings.Join(paramNames, ",")
}
func splitPathAndQuery(raw string) (string, []string) {
raw = strings.TrimRight(strings.TrimSpace(raw), ".,;:!?)")
pathPart, queryPart, _ := strings.Cut(raw, "?")
return normalizeEndpointPath(pathPart), sortedQueryParamNames(queryPart)
}
func normalizeEndpointPath(p string) string {
p = strings.TrimSpace(p)
if p == "" || p == "/" {
return ""
}
p = strings.ToLower(p)
for strings.Contains(p, "//") {
p = strings.ReplaceAll(p, "//", "/")
}
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
return p
}
func sortedQueryParamNames(rawQuery string) []string {
if strings.TrimSpace(rawQuery) == "" {
return nil
}
var names []string
for _, pair := range strings.Split(rawQuery, "&") {
if pair == "" {
continue
}
k, _, _ := strings.Cut(pair, "=")
if k = strings.ToLower(strings.TrimSpace(k)); k != "" {
names = append(names, k)
}
}
return dedupSortedStrings(names)
}
func dedupSortedStrings(in []string) []string {
if len(in) == 0 {
return nil
}
seen := make(map[string]struct{}, len(in))
out := make([]string, 0, len(in))
for _, s := range in {
if _, ok := seen[s]; !ok {
seen[s] = struct{}{}
out = append(out, s)
}
}
sort.Strings(out)
return out
}
func isDismissedFindingStatus(status string) bool {
switch strings.ToLower(strings.TrimSpace(status)) {
case "false_positive", "ignored", "duplicate":
return true
default:
return false
}
}
// fingerprintDuplicate checks already registered active findings in this task,
// its directly related tasks, and tasks sharing the same assets for an exact
// deterministic fingerprint match (#473).
func (t *ToolSet) fingerprintDuplicate(in db.RecordFindingInput) (findingFingerprintMatch, bool) {
if t.ts == nil {
return findingFingerprintMatch{}, false
}
candFP := FindingFingerprint(in)
if candFP == "" {
return findingFingerprintMatch{}, false
}
nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500)
if err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: failed to list findings", "err", err)
return findingFingerprintMatch{}, false
}
if len(in.AssetIDs) > 0 {
if cross, err := t.ts.FindingsSharingAssets(in.AssetIDs, t.taskID, 100); err == nil {
seen := make(map[int64]bool, len(nodes))
for _, n := range nodes {
if n != nil {
seen[n.ID] = true
}
}
for _, n := range cross {
if n != nil && !seen[n.ID] {
nodes = append(nodes, n)
}
}
}
}
if len(nodes) == 0 {
return findingFingerprintMatch{}, false
}
if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: populate finding ids failed", "err", err)
return findingFingerprintMatch{}, false
}
findingIDs := make([]int64, 0, len(nodes))
for _, n := range nodes {
if n != nil && n.FindingID > 0 {
findingIDs = append(findingIDs, n.FindingID)
}
}
if len(findingIDs) == 0 {
return findingFingerprintMatch{}, false
}
meta, err := t.ts.FindingDedupMetadata(findingIDs)
if err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: load finding metadata failed", "err", err)
return findingFingerprintMatch{}, false
}
// Check newest first for deterministic match selection.
sort.SliceStable(nodes, func(i, j int) bool { return nodes[i].ID > nodes[j].ID })
for _, n := range nodes {
if n == nil || n.FindingID <= 0 {
continue
}
m := meta[n.FindingID]
if isDismissedFindingStatus(m.Status) {
continue
}
var payload struct {
VulnClass string `json:"vulnclass"`
Name string `json:"name"`
Summary string `json:"summary"`
Status string `json:"status"`
Evidence struct {
PoC string `json:"poc"`
} `json:"evidence"`
}
if json.Unmarshal(n.Payload, &payload) != nil {
continue
}
if isDismissedFindingStatus(payload.Status) {
continue
}
existingFP := FindingFingerprint(db.RecordFindingInput{
VulnClass: payload.VulnClass,
Name: payload.Name,
Summary: payload.Summary,
Evidence: payload.Evidence.PoC,
AssetIDs: m.AssetIDs,
})
if existingFP != "" && existingFP == candFP {
slog.Info("[dedup] deterministic fingerprint matched existing finding",
"finding_id", n.FindingID, "node_id", n.ID, "fingerprint", candFP)
return findingFingerprintMatch{
FindingID: n.FindingID,
NodeID: n.ID,
Fingerprint: candFP,
}, true
}
}
return findingFingerprintMatch{}, false
}
+168
View File
@@ -0,0 +1,168 @@
package agent
import (
"context"
"encoding/json"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestFindingFingerprintDeterminismAndDistinctness(t *testing.T) {
base := db.RecordFindingInput{
VulnClass: "SQLi",
Name: "SQL Injection on search",
Summary: "GET https://app.example.test/api/v1/products/search?q=1&sort=asc is injectable",
AssetIDs: []int64{42, 10},
}
sameReordered := db.RecordFindingInput{
VulnClass: "sqli",
Name: "Re-verified SQLi",
Summary: "Confirmed again on https://APP.EXAMPLE.TEST/api/v1/products/search/?sort=desc&q=2",
AssetIDs: []int64{10, 42, 10},
}
fp1 := FindingFingerprint(base)
fp2 := FindingFingerprint(sameReordered)
if fp1 == "" || fp1 != fp2 {
t.Fatalf("equivalent findings must yield identical non-empty fingerprint: fp1=%q fp2=%q", fp1, fp2)
}
// Distinct endpoint on same host/asset must produce a different fingerprint.
diffEndpoint := base
diffEndpoint.Summary = "GET https://app.example.test/api/v1/users/search?q=1 is injectable"
if fp3 := FindingFingerprint(diffEndpoint); fp3 == "" || fp3 == fp1 {
t.Fatalf("different endpoint must yield different fingerprint: fp1=%q fp3=%q", fp1, fp3)
}
// Distinct parameter on same path must produce a different fingerprint.
diffParam := base
diffParam.Summary = "GET https://app.example.test/api/v1/products/search?category=1 is injectable"
if fp4 := FindingFingerprint(diffParam); fp4 == "" || fp4 == fp1 {
t.Fatalf("different parameter must yield different fingerprint: fp1=%q fp4=%q", fp1, fp4)
}
// Distinct vulnerability class on same endpoint must produce a different fingerprint.
diffClass := base
diffClass.VulnClass = "XSS"
if fp5 := FindingFingerprint(diffClass); fp5 == "" || fp5 == fp1 {
t.Fatalf("different vulnclass must yield different fingerprint: fp1=%q fp5=%q", fp1, fp5)
}
// Missing endpoint or missing asset/host returns "" (no false collision).
noEndpoint := db.RecordFindingInput{VulnClass: "SQLi", Summary: "generic database error", AssetIDs: []int64{10}}
if fp := FindingFingerprint(noEndpoint); fp != "" {
t.Fatalf("missing endpoint must return empty fingerprint, got %q", fp)
}
noAssetOrHost := db.RecordFindingInput{VulnClass: "SQLi", Summary: "GET /login?user=a is injectable"}
if fp := FindingFingerprint(noAssetOrHost); fp != "" {
t.Fatalf("missing asset/host must return empty fingerprint, got %q", fp)
}
}
type countingTriageClient struct {
calls atomic.Int64
ans DuplicateAnswer
}
func (c *countingTriageClient) Duplicate(_ context.Context, _ TriageCandidate, _ []TriageCandidate) (DuplicateAnswer, error) {
c.calls.Add(1)
return c.ans, nil
}
func TestReportFindingFingerprintDedupWithoutTriageClientAndComplementsTriage(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTaskWithOptions("fingerprint dedup", "verify deterministic dedup", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
})
ts := NewToolSet(d.Exploration(task.ExplorationID), "worker-1")
ts.SetTaskID(task.ID)
// 1. First registration with URL host + vulnclass + endpoint succeeds.
first := `{"vulnclass":"SQLi","severity":"high","name":"Login SQLi","summary":"POST https://target.lab.local/api/login?user=admin vulnerable to boolean SQLi"}`
if res := callGuardTool(t, ts.addFinding(), first); res.IsError {
t.Fatalf("first report_finding failed: %s", res.Flatten())
}
nodes := findingNodes(t, ts)
if len(nodes) != 1 {
t.Fatalf("expected 1 finding after first report, got %d", len(nodes))
}
origFID, origNID := nodes[0].FindingID, nodes[0].ID
// 2. Re-verification with reworded summary on the same host+endpoint+param+class
// is suppressed deterministically even with NO triage client configured.
triageMock := &countingTriageClient{}
ts.SetTriageClient(triageMock)
dup := `{"vulnclass":"sqli","severity":"high","name":"Re-verified login SQLi","summary":"Re-confirmed SQL injection on https://TARGET.LAB.LOCAL/api/login/?user=test"}`
res := callGuardTool(t, ts.addFinding(), dup)
if res.IsError {
t.Fatalf("duplicate suppression returned error: %s", res.Flatten())
}
text := res.Flatten()
if !strings.Contains(text, "duplicate_not_registered") || !strings.Contains(text, `"dedup_source":"fingerprint"`) {
t.Fatalf("expected deterministic fingerprint suppression, got: %s", text)
}
if triageMock.calls.Load() != 0 {
t.Fatalf("fingerprint hit must short-circuit before LLM triage, got %d triage calls", triageMock.calls.Load())
}
var ans struct {
DuplicateOfFindingID int64 `json:"duplicate_of_finding_id"`
DuplicateOfNodeID int64 `json:"duplicate_of_finding_node_id"`
Fingerprint string `json:"fingerprint"`
}
if err := json.Unmarshal([]byte(text[strings.Index(text, "{"):]), &ans); err != nil {
t.Fatalf("parse suppression json: %v (%s)", err, text)
}
if ans.DuplicateOfFindingID != origFID || ans.DuplicateOfNodeID != origNID || !strings.HasPrefix(ans.Fingerprint, "fp:") {
t.Fatalf("unexpected suppression payload: %+v (want finding=%d node=%d)", ans, origFID, origNID)
}
if !strings.Contains(text, "finding_id="+strconv.FormatInt(origNID, 10)) {
t.Fatalf("suppression note must reference node id %d: %s", origNID, text)
}
if got := len(findingNodes(t, ts)); got != 1 {
t.Fatalf("expected still 1 finding after suppression, got %d", got)
}
// 3. A distinct endpoint on the same host is NOT suppressed by fingerprint and
// falls through to LLM triage (which returns distinct -> registers).
distinct := `{"vulnclass":"sqli","severity":"high","name":"Search SQLi","summary":"GET https://target.lab.local/api/search?q=abc vulnerable to UNION SQLi"}`
if res := callGuardTool(t, ts.addFinding(), distinct); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("distinct endpoint should register, got: %s", res.Flatten())
}
if triageMock.calls.Load() != 1 {
t.Fatalf("non-matching fingerprint must fall through to LLM triage, got %d calls", triageMock.calls.Load())
}
if got := len(findingNodes(t, ts)); got != 2 {
t.Fatalf("expected 2 findings after distinct endpoint, got %d", got)
}
// 4. force_register=true overrides deterministic fingerprint suppression.
forced := `{"force_register":true,"vulnclass":"sqli","severity":"high","name":"Distinct root cause on login","summary":"POST https://target.lab.local/api/login?user=admin second bug"}`
if res := callGuardTool(t, ts.addFinding(), forced); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("force_register must override fingerprint suppression, got: %s", res.Flatten())
}
if got := len(findingNodes(t, ts)); got != 3 {
t.Fatalf("expected 3 findings after force_register, got %d", got)
}
// 5. Dismissed (false_positive) findings must not suppress a new registration.
if _, err := d.Exec(`UPDATE findings SET status='false_positive' WHERE task_id=$1`, task.ID); err != nil {
t.Fatal(err)
}
ts.SetTriageClient(nil)
if res := callGuardTool(t, ts.addFinding(), dup); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("false_positive finding must not suppress re-discovery, got: %s", res.Flatten())
}
if got := len(findingNodes(t, ts)); got != 4 {
t.Fatalf("expected 4 findings after false_positive re-discovery, got %d", got)
}
}
+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"`
+57 -1
View File
@@ -14,6 +14,7 @@ import (
"context"
"fmt"
"io"
"iter"
"log/slog"
"net/http"
"net/url"
@@ -689,8 +690,9 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
// budget to emit OK cleanly (finish=stop).
// EscalateMaxTokens stays false: don't raise the cap and retry on truncation, to
// avoid burning tokens in a resume loop.
probe := &connTestProvider{inner: prov}
reply, err := agentcore.Run(ctx, agentcore.Options{
Provider: prov,
Provider: probe,
SystemPrompt: []string{"You are a connection test. Just output the two characters OK — no thinking, no explanation, nothing else."},
Tools: []actool.CoreTool{}, // not nil: nil means the SDK's unconfined file and shell tools
PermissionMode: acperm.ModeBypass,
@@ -712,6 +714,12 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, "", err
}
// Reject tool-call replies (#526): the connection test asks for plain text
// with no tools; a model answering with a tool call or tool_calls/tool_use
// finish reason must not be reported as Connected even if it also emitted text.
if probe.sawToolCall || isToolCallStopReason(probe.stopReason) {
return lat, "", fmt.Errorf("the model returned a tool call instead of a text reply (finish_reason=%q)", probe.stopReason)
}
// err==nil is not enough: requests that go through while the model emits nothing
// at all really happen (thinking burned the whole budget, the body got swallowed
// by a safety policy, a compatibility layer dropped the content). Such a config
@@ -723,3 +731,51 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, reply, nil
}
// connTestProvider observes the raw provider response during TestConnection so
// tool-call replies and tool_calls/tool_use stop reasons are rejected (#526).
type connTestProvider struct {
inner llm.Provider
sawToolCall bool
stopReason string
}
func (p *connTestProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
for ev, err := range p.inner.Stream(ctx, req) {
if err == nil {
if ev.Type == llm.SEToolUseStart {
p.sawToolCall = true
}
if ev.StopReason != "" {
p.stopReason = ev.StopReason
}
}
if !yield(ev, err) {
return
}
}
}
}
func (p *connTestProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
msg, stopReason, usage, err := p.inner.Complete(ctx, req)
if err == nil {
if len(msg.ToolUses()) > 0 {
p.sawToolCall = true
}
if stopReason != "" {
p.stopReason = stopReason
}
}
return msg, stopReason, usage, err
}
func isToolCallStopReason(stopReason string) bool {
switch strings.ToLower(strings.TrimSpace(stopReason)) {
case "tool_use", "tool_calls":
return true
default:
return false
}
}
+38 -9
View File
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strconv"
@@ -1616,16 +1617,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
@@ -1644,6 +1652,20 @@ func (t *ToolSet) addFinding() actool.CoreTool {
// retry hits the same check and is suppressed again.
if a.ForceRegister {
slog.Info("[triage] override: force_register set, registering without duplicate check", "candidate", a.Name)
} else if dup, ok := t.fingerprintDuplicate(input); ok {
res := map[string]any{
"duplicate_of_finding_id": dup.FindingID,
"duplicate_of_finding_node_id": dup.NodeID,
"dedup_source": "fingerprint",
"fingerprint": dup.Fingerprint,
"evidence_status": "duplicate_not_registered",
"note": fmt.Sprintf("Deterministic fingerprint (%s) matched already registered finding_id %d (exploration node %d), so no new finding was created. "+
"To extend that finding with new evidence, call update_finding_report with finding_id=%d (it addresses the NODE id, not the findings-table id). "+
"If the new evidence is in fact a distinct defect (different endpoint, parameter or root cause), call report_finding again with force_register=true.",
dup.Fingerprint, dup.FindingID, dup.NodeID, dup.NodeID),
}
raw, _ := json.Marshal(res)
return actool.Text(fmt.Sprintf("finding matched existing finding_id %d (node %d, fingerprint %s) — not registered again\n%s", dup.FindingID, dup.NodeID, dup.Fingerprint, raw)), nil
} else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
res := map[string]any{
"duplicate_of_finding_id": ans.DuplicateOf,
@@ -1696,6 +1718,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
})
+53
View File
@@ -1,6 +1,7 @@
package db
import (
"encoding/json"
"strings"
)
@@ -69,3 +70,55 @@ func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask i
}
return out, rows.Err()
}
// FindingDedupMeta carries the finding metadata needed by deterministic
// fingerprint deduplication (#473) without requiring any schema migration.
type FindingDedupMeta struct {
AssetIDs []int64
Status string
}
// FindingDedupMetadata returns asset_ids and status keyed by finding id.
func (s *ExplorationStore) FindingDedupMetadata(findingIDs []int64) (map[int64]FindingDedupMeta, error) {
out := make(map[int64]FindingDedupMeta, len(findingIDs))
if len(findingIDs) == 0 {
return out, nil
}
placeholders := make([]string, 0, len(findingIDs))
args := make([]any, 0, len(findingIDs))
seen := make(map[int64]struct{}, len(findingIDs))
for _, id := range findingIDs {
if id <= 0 {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
args = append(args, id)
placeholders = append(placeholders, "$"+itoa(int64(len(args))))
}
if len(args) == 0 {
return out, nil
}
rows, err := s.db.Query(
`SELECT id, COALESCE(asset_ids, '[]'::jsonb), COALESCE(status, 'pending') FROM findings WHERE id IN (`+strings.Join(placeholders, ",")+`)`,
args...,
)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id int64
var rawAssets []byte
var status string
if err := rows.Scan(&id, &rawAssets, &status); err != nil {
return nil, err
}
var aids []int64
_ = json.Unmarshal(rawAssets, &aids)
out[id] = FindingDedupMeta{AssetIDs: aids, Status: status}
}
return out, rows.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 {