mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-27 10:20:54 +08:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5c7bfcbdd | ||
|
|
3d79ec9528 | ||
|
|
10fb8d389d | ||
|
|
066b978687 | ||
|
|
cc25ad55c4 | ||
|
|
30d5b96a51 | ||
|
|
01424b685e | ||
|
|
478bdcae82 | ||
|
|
efe588a526 |
+18
-2
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
|
||||
+107
-26
@@ -3,7 +3,9 @@ package agent
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -72,10 +74,30 @@ type GoalSpec struct {
|
||||
VulnClass string `json:"vulnclass,omitempty"`
|
||||
}
|
||||
|
||||
// ErrGoalDecompositionContract reports that the Goal Decomposer did not submit
|
||||
// at least one non-empty goal through a structured set_goals tool call even
|
||||
// after the single strict retry.
|
||||
var ErrGoalDecompositionContract = errors.New("goal decomposition did not produce a structured set_goals tool call")
|
||||
|
||||
// ErrGoalDecompositionEmptyInput reports that goal decomposition was invoked
|
||||
// with an empty task goal.
|
||||
var ErrGoalDecompositionEmptyInput = errors.New("goal decomposition requires a non-empty task goal")
|
||||
|
||||
// ErrGoalDecompositionNoProvider reports that goal decomposition cannot run
|
||||
// because no LLM provider is configured. Callers distinguish this from a
|
||||
// structured tool-call contract failure (ErrGoalDecompositionContract).
|
||||
var ErrGoalDecompositionNoProvider = errors.New("goal decomposition failed: no LLM provider configured")
|
||||
|
||||
// goalsStrictRetryPrompt is sent once when the initial goal decomposition run
|
||||
// finishes without persisting any non-empty goal via a structured set_goals
|
||||
// tool call (e.g. the model emitted set_goals in plain text instead).
|
||||
const goalsStrictRetryPrompt = "You did not submit any goals through a structured tool call. Do not write set_goals or JSON as plain text. Invoke the structured set_goals tool now with at least one non-empty goal."
|
||||
|
||||
// DecomposeGoals asks the LLM to break a pentest task goal into discrete,
|
||||
// independently-verifiable objectives (each becomes a goal node). Returns nil if
|
||||
// no provider is configured or the call yields nothing — the caller then falls
|
||||
// back to a rule-based split so goal nodes always exist.
|
||||
// independently-verifiable objectives (each becomes a goal node). It enforces
|
||||
// the structured set_goals tool-call contract: if no non-empty goal is
|
||||
// submitted on the first pass, it retries once with a stricter instruction and
|
||||
// then returns an explicit error instead of materializing empty goals.
|
||||
//
|
||||
// prov is supplied by the caller (rather than built here from a Config) so goal
|
||||
// decomposition rides the SAME provider instance as the rest of the engine — it
|
||||
@@ -94,12 +116,8 @@ type GoalSpec struct {
|
||||
//
|
||||
// ts is the task's exploration store: set_goals writes the decomposed goal nodes
|
||||
// straight into it (the same managed tool the main agent uses to add goals at
|
||||
// runtime). The returned specs are read back from the store so callers can emit
|
||||
// per-goal activity and detect the "LLM produced nothing" case for their fallback.
|
||||
func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, emit func(db.Activity)) []GoalSpec {
|
||||
if prov == nil {
|
||||
return nil
|
||||
}
|
||||
// runtime).
|
||||
func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, emit func(db.Activity)) ([]GoalSpec, error) {
|
||||
return DecomposeGoalsWithProvider(ctx, prov, dataDir, goalText, desc, as, ts, taskID, false, 0, emit)
|
||||
}
|
||||
|
||||
@@ -107,9 +125,16 @@ func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, d
|
||||
// ordered provider chain. It preserves the same tools and write behavior while
|
||||
// letting the caller own provider selection/failover. maxTokens is the profile's
|
||||
// per-reply output cap (0 = send none).
|
||||
func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, nonStreaming bool, maxTokens int, emit func(db.Activity)) []GoalSpec {
|
||||
func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, nonStreaming bool, maxTokens int, emit func(db.Activity)) ([]GoalSpec, error) {
|
||||
if prov == nil {
|
||||
return nil
|
||||
return nil, ErrGoalDecompositionNoProvider
|
||||
}
|
||||
if ts == nil {
|
||||
return nil, errors.New("goal decomposition failed: exploration store is not initialized")
|
||||
}
|
||||
trimmedGoal := strings.TrimSpace(goalText)
|
||||
if trimmedGoal == "" {
|
||||
return nil, ErrGoalDecompositionEmptyInput
|
||||
}
|
||||
// Goal decomposition is a one-shot call: it does not attach a transcript store, so
|
||||
// agentcore does not put a session id on the ctx (it only does when there is a
|
||||
@@ -120,8 +145,10 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
|
||||
// explicitly: decomposition requests of the same exploration share it (good for
|
||||
// cache hits), the naming does not collide with planner/worker, and
|
||||
// llmrec.parseSession can attribute it correctly.
|
||||
if ts != nil {
|
||||
ctx = transcript.WithSessionID(ctx, fmt.Sprintf("exp%d-goals", ts.ID()))
|
||||
ctx = transcript.WithSessionID(ctx, fmt.Sprintf("exp%d-goals", ts.ID()))
|
||||
beforeIDs, err := existingGoalIDs(ts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("goal decomposition failed to read existing goals: %w", err)
|
||||
}
|
||||
// worker="goals" tags the goal nodes' provenance; ts/taskID let set_goals link
|
||||
// each goal under the task root. This is the catalog's real set_goals tool, so a
|
||||
@@ -142,19 +169,19 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
|
||||
tools = append(tools, tsx.addTaskScope())
|
||||
sys += goalsScopeTail
|
||||
}
|
||||
userMsg := "Task goal:\n" + goalText
|
||||
userMsg := "Task goal:\n" + trimmedGoal
|
||||
if d := strings.TrimSpace(desc); d != "" {
|
||||
userMsg += "\n\nTask description (background information, may include target scope / flag count / engagement notes; for reference only — do not invent anything it does not mention):\n" + d
|
||||
}
|
||||
// Use captureRun so every LLM step is emitted as an activity record (visible in
|
||||
// the plan tab under the round-0 marker). Falls back gracefully when emit is nil.
|
||||
// Use captureRunSession on one session so a single strict retry keeps any
|
||||
// prior tool results (constraints/scope) and shows the model its prior output.
|
||||
captureEmit := func(r db.Activity) {
|
||||
if emit != nil {
|
||||
r.Worker = "planner"
|
||||
emit(r)
|
||||
}
|
||||
}
|
||||
captureRun(ctx, agentcore.Options{
|
||||
session := agentcore.NewSession(agentcore.Options{
|
||||
Provider: prov,
|
||||
SystemPrompt: []string{sys},
|
||||
Tools: tools,
|
||||
@@ -164,23 +191,77 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
|
||||
MaxTurns: 8,
|
||||
NonStreaming: nonStreaming, // when this profile selects non-streaming, use Provider.Complete
|
||||
MaxTokens: maxTokens, // 0 = send no cap, the server's default decides
|
||||
}, userMsg, captureEmit)
|
||||
// set_goals persisted the goals directly; read them back so the caller sees what
|
||||
// was written (empty slice ⇒ the LLM produced nothing ⇒ caller falls back).
|
||||
if ts == nil {
|
||||
return nil
|
||||
})
|
||||
defer session.Close()
|
||||
|
||||
finalText, _, runErr := captureRunSession(ctx, session, userMsg, captureEmit)
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("goal decomposition failed: %w", runErr)
|
||||
}
|
||||
out, err := readNewGoals(ts, beforeIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("goal decomposition failed to read persisted goals: %w", err)
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// No valid structured set_goals call succeeded on the first pass: allow
|
||||
// exactly one strict retry before failing explicitly.
|
||||
log.Printf("[goals] task %d: goal decomposer produced no structured set_goals tool call; retrying once with stricter instruction", taskID)
|
||||
finalText, _, runErr = captureRunSession(ctx, session, goalsStrictRetryPrompt, captureEmit)
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("goal decomposition retry failed: %w", runErr)
|
||||
}
|
||||
out, err = readNewGoals(ts, beforeIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("goal decomposition failed to read persisted goals after retry: %w", err)
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out, nil
|
||||
}
|
||||
if strings.TrimSpace(finalText) != "" {
|
||||
return nil, fmt.Errorf("%w after retry (model returned plain text instead of a structured tool call)", ErrGoalDecompositionContract)
|
||||
}
|
||||
return nil, fmt.Errorf("%w after retry", ErrGoalDecompositionContract)
|
||||
}
|
||||
|
||||
func existingGoalIDs(ts *db.ExplorationStore) (map[int64]struct{}, error) {
|
||||
nodes, err := ts.ListByKind(db.KindGoal, 10000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make(map[int64]struct{}, len(nodes))
|
||||
for _, n := range nodes {
|
||||
ids[n.ID] = struct{}{}
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func readNewGoals(ts *db.ExplorationStore, before map[int64]struct{}) ([]GoalSpec, error) {
|
||||
nodes, err := ts.ListByKind(db.KindGoal, 10000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, _ := ts.ListByKind(db.KindGoal, 10000)
|
||||
var out []GoalSpec
|
||||
for _, n := range nodes {
|
||||
if _, existed := before[n.ID]; existed {
|
||||
continue
|
||||
}
|
||||
var p struct {
|
||||
Text string `json:"text"`
|
||||
VulnClass string `json:"vulnclass"`
|
||||
}
|
||||
_ = json.Unmarshal(n.Payload, &p)
|
||||
if strings.TrimSpace(p.Text) != "" {
|
||||
out = append(out, GoalSpec{Text: p.Text, VulnClass: p.VulnClass})
|
||||
if text := strings.TrimSpace(p.Text); text != "" {
|
||||
out = append(out, GoalSpec{Text: text, VulnClass: strings.TrimSpace(p.VulnClass)})
|
||||
}
|
||||
}
|
||||
return out
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"iter"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// scriptedDecomposerProvider replays a sequence of scripted stream turns and
|
||||
// records every CompletionRequest it receives.
|
||||
type scriptedDecomposerProvider struct {
|
||||
mu sync.Mutex
|
||||
turns [][]llm.StreamEvent
|
||||
reqs []llm.CompletionRequest
|
||||
}
|
||||
|
||||
func (p *scriptedDecomposerProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
|
||||
p.mu.Lock()
|
||||
idx := len(p.reqs)
|
||||
p.reqs = append(p.reqs, req)
|
||||
var evs []llm.StreamEvent
|
||||
if idx < len(p.turns) {
|
||||
evs = p.turns[idx]
|
||||
} else if len(p.turns) > 0 {
|
||||
evs = p.turns[len(p.turns)-1]
|
||||
}
|
||||
p.mu.Unlock()
|
||||
return func(yield func(llm.StreamEvent, error) bool) {
|
||||
for _, ev := range evs {
|
||||
if !yield(ev, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *scriptedDecomposerProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
|
||||
acc := llm.NewAccumulator()
|
||||
for ev, err := range p.Stream(ctx, req) {
|
||||
if err != nil {
|
||||
return llm.Message{}, "", llm.Usage{}, err
|
||||
}
|
||||
acc.Add(ev)
|
||||
}
|
||||
return acc.Message(), acc.StopReason, acc.Usage, nil
|
||||
}
|
||||
|
||||
func (p *scriptedDecomposerProvider) calls() int {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return len(p.reqs)
|
||||
}
|
||||
|
||||
func plainTextTurn(text string) []llm.StreamEvent {
|
||||
return []llm.StreamEvent{
|
||||
{Type: llm.SETextDelta, Text: text},
|
||||
{Type: llm.SEMessageDelta, StopReason: "end_turn"},
|
||||
}
|
||||
}
|
||||
|
||||
func toolCallTurn(id, name, inputJSON string) []llm.StreamEvent {
|
||||
return []llm.StreamEvent{
|
||||
{Type: llm.SEToolUseStart, ToolID: id, ToolName: name},
|
||||
{Type: llm.SEToolInputJSON, Text: inputJSON},
|
||||
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecomposeGoalsPlainTextToolCallFailsAfterSingleRetry(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
prov := &scriptedDecomposerProvider{
|
||||
turns: [][]llm.StreamEvent{
|
||||
plainTextTurn(`set_goals({"goals":[{"text":"Audit auth on lab.local"}]})`),
|
||||
plainTextTurn(`set_goals({"goals":[{"text":"Audit auth on lab.local"}]})`),
|
||||
plainTextTurn(`should never be reached`),
|
||||
},
|
||||
}
|
||||
|
||||
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit auth on lab.local", "planning only", nil, ts, 0, nil)
|
||||
if !errors.Is(err, ErrGoalDecompositionContract) {
|
||||
t.Fatalf("expected ErrGoalDecompositionContract, got goals=%+v err=%v", got, err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("expected no returned goals, got %+v", got)
|
||||
}
|
||||
if prov.calls() != 2 {
|
||||
t.Fatalf("expected exactly 2 LLM calls (initial + 1 retry), got %d", prov.calls())
|
||||
}
|
||||
// Verify the second call received the stricter retry prompt.
|
||||
second := prov.reqs[1]
|
||||
foundRetry := false
|
||||
for _, msg := range second.Messages {
|
||||
for _, blk := range msg.Content {
|
||||
if strings.Contains(blk.Text, "structured set_goals tool") {
|
||||
foundRetry = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !foundRetry {
|
||||
t.Fatalf("second request did not include the stricter retry instruction: %+v", second.Messages)
|
||||
}
|
||||
nodes, lerr := ts.ListByKind(db.KindGoal, 100)
|
||||
if lerr != nil {
|
||||
t.Fatal(lerr)
|
||||
}
|
||||
if len(nodes) != 0 {
|
||||
t.Fatalf("expected 0 materialized goal nodes in DB, got %d", len(nodes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecomposeGoalsSingleRetrySucceeds(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
prov := &scriptedDecomposerProvider{
|
||||
turns: [][]llm.StreamEvent{
|
||||
plainTextTurn(`set_goals({"goals":[{"text":"Identify SQLi on /login"}]})`),
|
||||
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":"Identify SQLi on /login","vulnclass":"SQLi"}]}`),
|
||||
plainTextTurn("Goals submitted."),
|
||||
},
|
||||
}
|
||||
|
||||
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Test /login for SQLi", "scope: lab.local", nil, ts, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("expected single retry to succeed, got err=%v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Text != "Identify SQLi on /login" || got[0].VulnClass != "SQLi" {
|
||||
t.Fatalf("unexpected goals: %+v", got)
|
||||
}
|
||||
// Turn 1: plain text; Turn 2: retry tool call; Turn 3: post-tool completion.
|
||||
if prov.calls() != 3 {
|
||||
t.Fatalf("expected 3 provider turns (plain text, retry tool_use, final), got %d", prov.calls())
|
||||
}
|
||||
nodes, lerr := ts.ListByKind(db.KindGoal, 100)
|
||||
if lerr != nil {
|
||||
t.Fatal(lerr)
|
||||
}
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("expected 1 persisted goal node, got %d", len(nodes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecomposeGoalsValidStructuredToolCallAccepted(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
prov := &scriptedDecomposerProvider{
|
||||
turns: [][]llm.StreamEvent{
|
||||
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":"Confirm auth bypass on admin panel","vulnclass":"AuthBypass"},{"text":"Verify IDOR on /api/users","vulnclass":"IDOR"}]}`),
|
||||
plainTextTurn("Done."),
|
||||
},
|
||||
}
|
||||
|
||||
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit admin panel and /api/users", "", nil, ts, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 goals, got %+v", got)
|
||||
}
|
||||
// Only 2 turns (tool_use + final end_turn) — no retry was needed.
|
||||
if prov.calls() != 2 {
|
||||
t.Fatalf("expected 2 turns with no retry, got %d", prov.calls())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecomposeGoalsRejectsEmptyTaskGoalAndEmptyToolArgs(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
prov := &scriptedDecomposerProvider{
|
||||
turns: [][]llm.StreamEvent{
|
||||
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":" "}]}`),
|
||||
plainTextTurn("ok"),
|
||||
toolCallTurn("tc_2", "set_goals", `{"goals":[{"text":""}]}`),
|
||||
plainTextTurn("ok"),
|
||||
},
|
||||
}
|
||||
|
||||
if got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), " ", "desc", nil, ts, 0, nil); !errors.Is(err, ErrGoalDecompositionEmptyInput) || len(got) != 0 {
|
||||
t.Fatalf("empty goalText: got goals=%+v err=%v", got, err)
|
||||
}
|
||||
if prov.calls() != 0 {
|
||||
t.Fatalf("empty goalText must not call LLM, got %d calls", prov.calls())
|
||||
}
|
||||
|
||||
if got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Real task goal", "", nil, ts, 0, nil); !errors.Is(err, ErrGoalDecompositionContract) || len(got) != 0 {
|
||||
t.Fatalf("blank tool args: expected ErrGoalDecompositionContract, got goals=%+v err=%v", got, err)
|
||||
}
|
||||
nodes, err := ts.ListByKind(db.KindGoal, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(nodes) != 0 {
|
||||
t.Fatalf("blank tool args must not materialize empty goal nodes, got %d", len(nodes))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlannerRefusesEmptyContextAndOverviewOmitsEmptyFields(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
task, err := d.CreateTaskWithOptions("", "", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
|
||||
ts := d.Exploration(task.ExplorationID)
|
||||
|
||||
// Even if a blank goal node exists in the graph, overview must drop it and
|
||||
// omit empty task description/goal, and Planner.Plan must refuse to plan.
|
||||
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": " "}, 0, "open", "system", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tsx := NewToolSet(ts, "planner")
|
||||
overview := tsx.graphOverviewData()
|
||||
if goals, _ := overview["goals"].([]map[string]any); len(goals) != 0 {
|
||||
t.Fatalf("graphOverviewData materialized empty goals: %+v", goals)
|
||||
}
|
||||
if _, hasTask := overview["task"]; hasTask {
|
||||
t.Fatalf("graphOverviewData materialized empty task block: %+v", overview["task"])
|
||||
}
|
||||
|
||||
prov := &scriptedDecomposerProvider{
|
||||
turns: [][]llm.StreamEvent{plainTextTurn("should not run")},
|
||||
}
|
||||
planner := NewPlanner(prov, "test-model", t.TempDir(), nil, 0, 2)
|
||||
|
||||
var logBuf bytes.Buffer
|
||||
prevOut := log.Writer()
|
||||
log.SetOutput(&logBuf)
|
||||
t.Cleanup(func() { log.SetOutput(prevOut) })
|
||||
|
||||
if _, _, err := planner.Plan(t.Context(), task.ID, nil, nil, "", nil, nil, nil); !errors.Is(err, ErrPlannerEmptyContext) {
|
||||
t.Fatalf("nil store: expected ErrPlannerEmptyContext, got %v", err)
|
||||
}
|
||||
if _, _, err := planner.Plan(t.Context(), task.ID, nil, ts, " ", nil, nil, nil); !errors.Is(err, ErrPlannerEmptyContext) {
|
||||
t.Fatalf("empty context: expected ErrPlannerEmptyContext, got %v", err)
|
||||
}
|
||||
if prov.calls() != 0 {
|
||||
t.Fatalf("planner must not call LLM on empty context, got %d calls", prov.calls())
|
||||
}
|
||||
if !strings.Contains(logBuf.String(), "refusing to plan on empty context") {
|
||||
t.Fatalf("expected clear refusal log, got: %q", logBuf.String())
|
||||
}
|
||||
|
||||
// Verify graphOverviewData includes non-empty goal and task fields normally.
|
||||
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Audit /admin"}, 0, "open", "goals", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
overview = tsx.graphOverviewData()
|
||||
goals, _ := overview["goals"].([]map[string]any)
|
||||
if len(goals) != 1 || goals[0]["text"] != "Audit /admin" {
|
||||
t.Fatalf("expected 1 non-empty goal in overview, got %+v", overview["goals"])
|
||||
}
|
||||
// With a valid goal node present, Planner.Plan proceeds even if the explicit
|
||||
// goal arg was empty.
|
||||
if _, _, err := planner.Plan(t.Context(), task.ID, nil, ts, "", nil, nil, nil); err != nil {
|
||||
t.Fatalf("planner with valid goal node should proceed, got err=%v", err)
|
||||
}
|
||||
if prov.calls() != 1 {
|
||||
t.Fatalf("expected 1 LLM call when context is valid, got %d", prov.calls())
|
||||
}
|
||||
}
|
||||
func TestDecomposeGoalsNoProviderReturnsSentinel(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
got, err := DecomposeGoals(t.Context(), nil, t.TempDir(), "Audit target", "desc", nil, ts, 0, nil)
|
||||
if !errors.Is(err, ErrGoalDecompositionNoProvider) {
|
||||
t.Fatalf("expected ErrGoalDecompositionNoProvider, got goals=%+v err=%v", got, err)
|
||||
}
|
||||
if errors.Is(err, ErrGoalDecompositionContract) {
|
||||
t.Fatalf("no-provider error must not match ErrGoalDecompositionContract: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("expected no goals returned, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package agent
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -516,7 +518,53 @@ func plannerSystem(goal, dataDir, workDir string) string {
|
||||
// for time/heartbeat wakes). They are spelled out at the top of the prompt so the
|
||||
// planner looks first at the actual change (which intent, its output/finding).
|
||||
// hooks (the task's target-only Guard) sees every tool call; may be nil.
|
||||
// ErrPlannerEmptyContext reports that Planner.Plan was called without usable
|
||||
// planning context (missing exploration store, or both task goal and goal nodes
|
||||
// are empty).
|
||||
var ErrPlannerEmptyContext = errors.New("planner refused to plan on empty context")
|
||||
|
||||
func hasNonEmptyGoalNodes(ts *db.ExplorationStore) bool {
|
||||
if ts == nil {
|
||||
return false
|
||||
}
|
||||
nodes, err := ts.ListByKind(db.KindGoal, 100)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, n := range nodes {
|
||||
var payload struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if json.Unmarshal(n.Payload, &payload) == nil && strings.TrimSpace(payload.Text) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, goal string, triggers []TriggerEvent, hooks harness.HookRunner, emit func(db.Activity)) (met bool, reason string, err error) {
|
||||
if ts == nil {
|
||||
msg := fmt.Sprintf("task %d: refusing to plan on empty context (exploration store is nil)", taskID)
|
||||
log.Printf("[planner] %s", msg)
|
||||
if emit != nil {
|
||||
emit(db.Activity{Worker: "planner", Kind: "result", IsError: true, Summary: msg, Detail: msg})
|
||||
}
|
||||
return false, "", fmt.Errorf("%w: exploration store is nil", ErrPlannerEmptyContext)
|
||||
}
|
||||
rootDesc, rootGoal, _ := ts.Root()
|
||||
effectiveGoal := strings.TrimSpace(goal)
|
||||
if effectiveGoal == "" {
|
||||
effectiveGoal = strings.TrimSpace(rootGoal)
|
||||
}
|
||||
if effectiveGoal == "" && !hasNonEmptyGoalNodes(ts) {
|
||||
msg := fmt.Sprintf("task %d: refusing to plan on empty context (empty task goal and no goals; description=%q)", taskID, strings.TrimSpace(rootDesc))
|
||||
log.Printf("[planner] %s", msg)
|
||||
if emit != nil {
|
||||
emit(db.Activity{Worker: "planner", Kind: "result", IsError: true, Summary: msg, Detail: msg})
|
||||
}
|
||||
return false, "", fmt.Errorf("%w: empty task goal and no goals", ErrPlannerEmptyContext)
|
||||
}
|
||||
goal = effectiveGoal
|
||||
// cold-digest §2.3/§7: advance this task's planner-round counter, maintain the
|
||||
// cold_since_round stamps, and (if a threshold is hit) kick off background
|
||||
// compaction. Synchronous part is cheap (a few queries); the LLM compaction
|
||||
|
||||
+54
-11
@@ -3,6 +3,7 @@ package agent
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
@@ -500,7 +501,12 @@ func (t *ToolSet) graphOverviewData() map[string]any {
|
||||
for _, g := range goals {
|
||||
var p map[string]any
|
||||
_ = json.Unmarshal(g.Payload, &p)
|
||||
gsum = append(gsum, map[string]any{"id": g.ID, "state": g.State, "text": p["text"]})
|
||||
text, _ := p["text"].(string)
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
gsum = append(gsum, map[string]any{"id": g.ID, "state": g.State, "text": text})
|
||||
}
|
||||
out["goals"] = gsum
|
||||
// hints: strategic hints attached to the graph by the human/main agent via
|
||||
@@ -680,7 +686,16 @@ func (t *ToolSet) graphOverviewData() map[string]any {
|
||||
// the original task (root) so the planner always has it, not just the
|
||||
// decomposed goals.
|
||||
if description, goal, err := t.ts.Root(); err == nil {
|
||||
out["task"] = map[string]any{"description": description, "goal": goal}
|
||||
task := map[string]any{}
|
||||
if d := strings.TrimSpace(description); d != "" {
|
||||
task["description"] = d
|
||||
}
|
||||
if g := strings.TrimSpace(goal); g != "" {
|
||||
task["goal"] = g
|
||||
}
|
||||
if len(task) > 0 {
|
||||
out["task"] = task
|
||||
}
|
||||
}
|
||||
// Direct source tasks are a live, read-only blackboard view. Keep their
|
||||
// summaries in a separate field so their intents never enter this task's
|
||||
@@ -1602,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
|
||||
@@ -1630,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,
|
||||
@@ -1682,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
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
+54
-28
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sort"
|
||||
@@ -46,12 +47,28 @@ func (s *Server) startTaskEngine(t *Task) {
|
||||
}
|
||||
s.engine.emitActivity(t, db.Activity{Worker: "planner", Kind: "round",
|
||||
Summary: "round 0 goal decomposition"})
|
||||
goals := s.createGoals(ctx, t, func(r db.Activity) {
|
||||
goals, err := s.createGoals(ctx, t, func(r db.Activity) {
|
||||
s.engine.emitActivity(t, r)
|
||||
})
|
||||
if ctx.Err() != nil || s.engine.IsDeleting(t.ID) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[goals] task %s goal decomposition failed: %v", t.ID, err)
|
||||
s.engine.emitActivity(t, db.Activity{
|
||||
Worker: "planner",
|
||||
Kind: "result",
|
||||
IsError: true,
|
||||
Summary: "Goal decomposition failed: " + err.Error(),
|
||||
Detail: err.Error(),
|
||||
})
|
||||
if won, ferr := s.m.SetTaskStatusGuarded(t.ID, "failed", ""); ferr != nil {
|
||||
log.Printf("[goals] task %s failed to persist failed status: %v", t.ID, ferr)
|
||||
} else if won {
|
||||
go s.reconcileConcurrency()
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, g := range goals {
|
||||
summary := g.Text
|
||||
if g.VulnClass != "" {
|
||||
@@ -365,22 +382,21 @@ func (s *Server) reviveTask(t *Task) {
|
||||
}
|
||||
}
|
||||
|
||||
// createGoals materializes the goal node(s) under the task root (rel objective).
|
||||
// Decomposition is done ENTIRELY by the LLM (the project requires an LLM). There is
|
||||
// no rule-based fallback splitter — it only ever produced garbage (shredded URLs,
|
||||
// meaningless 2-way splits). If the LLM yields nothing (an error), the raw task goal
|
||||
// is used verbatim as a single goal so the task still has something to judge against.
|
||||
// Returns the seeded specs so callers can emit activity records for them.
|
||||
// createGoals materializes the goal node(s) under the task root (rel objective)
|
||||
// through the LLM Goal Decomposer's structured set_goals tool call. It returns an
|
||||
// explicit error if the task has no goal or if the decomposer fails to submit at
|
||||
// least one non-empty goal via a structured tool call (including after its single
|
||||
// strict retry) — empty goals or raw fallbacks are never materialized.
|
||||
// emit, when non-nil, is forwarded to DecomposeGoals so LLM steps are visible in the UI.
|
||||
func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity)) []goalSpec {
|
||||
func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity)) ([]goalSpec, error) {
|
||||
if t == nil {
|
||||
return nil
|
||||
return nil, fmt.Errorf("task is nil")
|
||||
}
|
||||
if strings.TrimSpace(t.Goal) == "" {
|
||||
return nil, fmt.Errorf("task %s has empty goal", t.ID)
|
||||
}
|
||||
// Use the SAME LLM the task runs on (its pinned profile, else the active profile),
|
||||
// NOT agent.FromEnv() — the LLM is configured via the UI (DB profile), not env vars,
|
||||
// so FromEnv returned empty and every task silently fell back to the crude rule
|
||||
// splitter (which shredded URLs / made meaningless 2-way splits).
|
||||
var specs []goalSpec
|
||||
// NOT agent.FromEnv() — the LLM is configured via the UI (DB profile), not env vars.
|
||||
var as *db.AssetStore
|
||||
if s.m != nil {
|
||||
as = s.m.Assets()
|
||||
@@ -388,26 +404,36 @@ func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity
|
||||
taskID, _ := strconv.ParseInt(t.ID, 10, 64)
|
||||
s.engine.BeginLLMCall(t.ID)
|
||||
goalRuntime := s.agentsForTask(t).runtime
|
||||
decomposed := agent.DecomposeGoalsWithProvider(ctx, goalRuntime, s.m.dir, t.Goal, t.Description, as, t.Store, taskID, goalRuntime.nonStreaming(), goalRuntime.maxTokens(), emit)
|
||||
decomposed, err := agent.DecomposeGoalsWithProvider(ctx, goalRuntime, s.m.dir, t.Goal, t.Description, as, t.Store, taskID, goalRuntime.nonStreaming(), goalRuntime.maxTokens(), emit)
|
||||
s.engine.EndLLMCall(t.ID)
|
||||
for _, g := range decomposed {
|
||||
if strings.TrimSpace(g.Text) != "" {
|
||||
specs = append(specs, goalSpec{Text: g.Text, VulnClass: g.VulnClass})
|
||||
}
|
||||
}
|
||||
if len(specs) == 0 {
|
||||
// No decomposed goals (LLM error / no provider): use the raw task goal verbatim
|
||||
// as a single goal so the task still has something to judge against. This is the
|
||||
// only path that writes here — decomposed goals are already persisted by the tool.
|
||||
if g := strings.TrimSpace(t.Goal); g != "" {
|
||||
log.Printf("[goals] task %s: LLM goal decomposition produced nothing, falling back to the raw goal as a single goal", t.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, agent.ErrGoalDecompositionNoProvider) {
|
||||
// No LLM provider is configured yet: preserve the pre-existing fallback
|
||||
// so the task gets a single raw goal node linked to its origin fact and
|
||||
// stays alive until an LLM is configured. Structured contract failures
|
||||
// from an actual model remain strict and fail the task.
|
||||
g := strings.TrimSpace(t.Goal)
|
||||
log.Printf("[goals] task %s: no LLM provider configured, seeding raw goal as a single goal", t.ID)
|
||||
origin, _ := t.Store.OriginFactID()
|
||||
id, _ := t.Store.AddNode(db.KindGoal, map[string]any{"text": g}, 0, "open", "system", nil)
|
||||
id, addErr := t.Store.AddNode(db.KindGoal, map[string]any{"text": g}, 0, "open", "system", nil)
|
||||
if addErr != nil {
|
||||
return nil, fmt.Errorf("seed raw goal: %w", addErr)
|
||||
}
|
||||
if origin > 0 && id > 0 {
|
||||
_ = t.Store.Link(origin, db.RelSpawns, id) // goal descends from the task root (origin fact)
|
||||
}
|
||||
specs = []goalSpec{{Text: g}}
|
||||
return []goalSpec{{Text: g}}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var specs []goalSpec
|
||||
for _, g := range decomposed {
|
||||
if text := strings.TrimSpace(g.Text); text != "" {
|
||||
specs = append(specs, goalSpec{Text: text, VulnClass: strings.TrimSpace(g.VulnClass)})
|
||||
}
|
||||
}
|
||||
return specs
|
||||
if len(specs) == 0 {
|
||||
return nil, fmt.Errorf("goal decomposition produced no valid goals")
|
||||
}
|
||||
return specs, nil
|
||||
}
|
||||
|
||||
+197
-2
@@ -2,11 +2,206 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func TestCreateGoalsNilTask(t *testing.T) {
|
||||
if got := (&Server{}).createGoals(context.Background(), nil, nil); len(got) != 0 {
|
||||
t.Fatalf("nil task produced goals: %+v", got)
|
||||
got, err := (&Server{}).createGoals(context.Background(), nil, nil)
|
||||
if err == nil || len(got) != 0 {
|
||||
t.Fatalf("nil task must return an error and no goals: got=%+v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartTaskEngineFailsTaskOnPlainTextDecomposer verifies end-to-end that
|
||||
// when the Goal Decomposer returns set_goals as plain text instead of a
|
||||
// structured tool call, startTaskEngine retries once, never materializes empty
|
||||
// or fallback goals, never starts the planner, and explicitly fails the task.
|
||||
func TestStartTaskEngineFailsTaskOnPlainTextDecomposer(t *testing.T) {
|
||||
skipWithoutDSN(t)
|
||||
var (
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
)
|
||||
mockOpenAI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": "chatcmpl-test",
|
||||
"object": "chat.completion",
|
||||
"model": "mock-local",
|
||||
"choices": []map[string]any{
|
||||
{
|
||||
"index": 0,
|
||||
"message": map[string]any{
|
||||
"role": "assistant",
|
||||
"content": `set_goals({"goals":[{"text":"Audit lab target"}]})`,
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
},
|
||||
},
|
||||
"usage": map[string]any{"prompt_tokens": 20, "completion_tokens": 12, "total_tokens": 32},
|
||||
})
|
||||
}))
|
||||
defer mockOpenAI.Close()
|
||||
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = m.Close() })
|
||||
if m.pg == nil {
|
||||
db.SkipNoPG(t)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := New(ctx, m, "", m.dir, m.dir)
|
||||
t.Cleanup(func() { stopTestServer(t, s, cancel) })
|
||||
|
||||
pid, err := m.pg.SaveProfile(&db.LLMProfile{
|
||||
Name: "mock-plaintext-decomposer",
|
||||
Format: "openai",
|
||||
BaseURL: mockOpenAI.URL + "/v1",
|
||||
Model: "mock-local",
|
||||
APIKey: "test-key",
|
||||
Streaming: false,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = m.pg.DeleteProfile(pid) })
|
||||
|
||||
task, err := m.CreateTaskWithOptions("planning-only lab check", "Audit lab target 10.10.52.1", db.TaskCreateOptions{
|
||||
LLMProfileIDs: []int64{pid},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
|
||||
|
||||
s.startTaskEngine(task)
|
||||
|
||||
mu.Lock()
|
||||
gotCalls := calls
|
||||
mu.Unlock()
|
||||
if gotCalls != 2 {
|
||||
t.Fatalf("expected exactly 2 decomposer calls (initial + 1 retry), got %d", gotCalls)
|
||||
}
|
||||
|
||||
if st := task.lifecycleSnapshot().Status; st != "failed" {
|
||||
t.Fatalf("expected in-memory task status failed, got %q", st)
|
||||
}
|
||||
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("GetTask: %v %v", stored, err)
|
||||
}
|
||||
if stored.Status != "failed" {
|
||||
t.Fatalf("expected persisted task status failed, got %q", stored.Status)
|
||||
}
|
||||
|
||||
goals, err := task.Store.ListByKind(db.KindGoal, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(goals) != 0 {
|
||||
t.Fatalf("expected 0 goal nodes materialized after contract failure, got %d", len(goals))
|
||||
}
|
||||
|
||||
acts, _, err := task.Store.ActivityList(nil, 0, 200)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foundErrAct := false
|
||||
for _, a := range acts {
|
||||
if a.Kind == "result" && a.IsError && strings.Contains(a.Summary, "Goal decomposition failed") {
|
||||
foundErrAct = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !foundErrAct {
|
||||
t.Fatalf("expected error activity describing goal decomposition failure, got %+v", acts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateGoalsNoProviderSeedsRawGoalAndKeepsTaskAlive verifies that when no
|
||||
// LLM provider is configured, createGoals falls back to seeding the raw task
|
||||
// goal as a single goal node linked from the origin fact, keeping the task
|
||||
// alive instead of marking it failed.
|
||||
func TestCreateGoalsNoProviderSeedsRawGoalAndKeepsTaskAlive(t *testing.T) {
|
||||
skipWithoutDSN(t)
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = m.Close() })
|
||||
if m.pg == nil {
|
||||
db.SkipNoPG(t)
|
||||
}
|
||||
// Ensure no global LLM profile is configured in this test DB.
|
||||
profiles, err := m.pg.ListProfiles()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(profiles) > 0 {
|
||||
t.Skip("test database already has configured LLM profiles")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s := New(ctx, m, "", m.dir, m.dir)
|
||||
t.Cleanup(func() { stopTestServer(t, s, cancel) })
|
||||
|
||||
const rawGoal = "Probe http://127.0.0.1:9/v1 for unauthenticated exposure"
|
||||
task, err := m.CreateTaskWithOptions("no-provider fallback", rawGoal, db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
|
||||
|
||||
// Seed origin fact as launchTask does so the spawns link is exercised.
|
||||
s.seed(task, rawGoal)
|
||||
originID, err := task.Store.OriginFactID()
|
||||
if err != nil || originID <= 0 {
|
||||
t.Fatalf("expected origin fact seeded, got id=%d err=%v", originID, err)
|
||||
}
|
||||
|
||||
goals, err := s.createGoals(ctx, task, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("createGoals without provider must fall back cleanly, got err=%v", err)
|
||||
}
|
||||
if len(goals) != 1 || goals[0].Text != rawGoal {
|
||||
t.Fatalf("unexpected fallback goals: %+v", goals)
|
||||
}
|
||||
|
||||
nodes, err := task.Store.ListByKind(db.KindGoal, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("expected 1 persisted goal node, got %d", len(nodes))
|
||||
}
|
||||
edges, err := task.Store.Edges(100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
linked := false
|
||||
for _, e := range edges {
|
||||
if e.From == originID && e.Rel == db.RelSpawns && e.To == nodes[0].ID {
|
||||
linked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !linked {
|
||||
t.Fatalf("fallback goal node #%d not linked from origin fact #%d via %q (edges=%+v)", nodes[0].ID, originID, db.RelSpawns, edges)
|
||||
}
|
||||
if st := task.lifecycleSnapshot().Status; st == "failed" {
|
||||
t.Fatalf("task without provider must stay alive, got status=%q", st)
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -248,7 +248,7 @@ func (r *taskLLMRuntime) currentFor(ctx context.Context) (taskLLMSelection, erro
|
||||
}
|
||||
prov, cfg, id, ok := r.s.globalProviderWithProfile()
|
||||
if !ok {
|
||||
return sel, fmt.Errorf("task %s has no available fallback LLM provider", r.taskID)
|
||||
return sel, fmt.Errorf("task %s has no available fallback LLM provider: %w", r.taskID, agent.ErrGoalDecompositionNoProvider)
|
||||
}
|
||||
sel.provider, sel.retry = prov, cfg.Retry
|
||||
sel.healthProfileID = healthIDFor(prov, id)
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user