diff --git a/agent/planner.go b/agent/planner.go index 8d9c78c68..708756bc3 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -23,6 +23,7 @@ import ( // into the frontier. It is the sole intent generator. type Planner struct { findingRecorder FindingRecorder + triage TriageClient // advisory decision-model client (agent/triage.go); nil = off prov llm.Provider model string tx *transcript.Store // raw LLM conversation persistence (nil = off) @@ -482,6 +483,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts p.compactor.OnPlannerRound(ctx, ts) tsx := NewToolSet(ts, "planner") tsx.SetFindingRecorder(p.findingRecorder) + tsx.SetTriageClient(p.triage) // The host's finding recorder owns the live capture; prove_goal checks bound // traffic_refs against it. No checker means finding proofs are refused. if c, ok := p.findingRecorder.(TrafficCaptureChecker); ok { diff --git a/agent/tools.go b/agent/tools.go index 5d35cbb7c..0aedcd706 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "log" "strconv" "strings" "time" @@ -139,6 +140,10 @@ func compactIntents(ns []*db.Node, parentsOf, yieldsOf map[int64][]int64) []map[ // One ToolSet is created per planner/worker run; per-run signals live here. type ToolSet struct { findingRecorder FindingRecorder + // triage, if set, is an advisory decision-model client used for closed-list + // judgements (currently the duplicate check in report_finding). nil = the + // judgement is left to the main model, exactly as before. See agent/triage.go. + triage TriageClient // trafficProofChecker verifies that a bound snapshot's source_traffic_id // exists in the live capture store during prove_goal. Planner.Plan wires it // from the finding recorder; nil or any error fails closed. @@ -1525,11 +1530,13 @@ func (t *ToolSet) addFinding() actool.CoreTool { "items": obj(map[string]any{"traffic_id": str("a real traffic ID returned by traffic_search"), "role": map[string]any{"type": "string", "enum": []string{"baseline", "proof", "verification", "supporting"}}, "note": str("how this traffic supports the finding's conclusion")}, "traffic_id")}, "counterevidence": str("optional: what you tested that did not work (variants, paths, or bypasses that were blocked or came back negative). Fill it when your confidence is not high; omitting it never blocks reporting."), "confidence_rationale": str("optional: why the conclusion holds (which observation rules out the benign explanation). Fill it when your confidence is not high; omitting it never blocks reporting."), + "force_register": map[string]any{"type": "boolean", "description": "optional: register even though the advisory duplicate check would suppress this finding. Use it only after a suppression when the new evidence is in fact a distinct defect (different endpoint, parameter or root cause); the suppression answer says so and names the finding it matched."}, }, "vulnclass", "severity", "summary"), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { var a struct { VulnClass, Name, Severity, Summary, Evidence string Counterevidence string `json:"counterevidence"` ConfidenceRationale string `json:"confidence_rationale"` + ForceRegister bool `json:"force_register"` IntentID json.RawMessage `json:"intent_id"` AssetIDs []json.RawMessage `json:"asset_ids"` TrafficRefs []db.TrafficRef `json:"traffic_refs"` @@ -1566,6 +1573,32 @@ func (t *ToolSet) addFinding() actool.CoreTool { } } input := db.RecordFindingInput{TaskID: t.taskID, ExplorationID: t.ts.ID(), IntentID: pid(a.IntentID), VulnClass: a.VulnClass, Name: a.Name, Severity: a.Severity, Summary: a.Summary, Evidence: a.Evidence, Worker: t.worker, AssetIDs: pidList(a.AssetIDs), Counterevidence: a.Counterevidence, ConfidenceRationale: a.ConfidenceRationale} + // Advisory dedup (agent/triage.go): a decision model answers "same defect as + // an already registered finding?" in one small request instead of a + // main-model turn. A confident duplicate is not registered a second time — + // the caller is told which finding to extend. Every failure path (no client, + // no existing findings, transport error, low confidence) falls through to + // the normal registration below. + // + // force_register is the way back out of a wrong suppression: without it the + // advice "register it again if it is distinct" is unactionable, because the + // retry hits the same check and is suppressed again. + if a.ForceRegister { + log.Printf("[triage] override: force_register set, registering %q without the duplicate check", a.Name) + } else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) { + res := map[string]any{ + "duplicate_of_finding_id": ans.DuplicateOf, + "duplicate_of_finding_node_id": ans.DuplicateOfNode, + "triage_confidence": ans.Confidence, + "evidence_status": "duplicate_not_registered", + "note": fmt.Sprintf("Triage matched this finding to already registered finding_id %d (exploration node %d), so no new finding was created. "+ + "To extend that finding, 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.", + ans.DuplicateOf, ans.DuplicateOfNode, ans.DuplicateOfNode), + } + raw, _ := json.Marshal(res) + return actool.Text(fmt.Sprintf("finding matched to existing finding_id %d (node %d, triage confidence %.2f) — not registered again\n%s", ans.DuplicateOf, ans.DuplicateOfNode, ans.Confidence, raw)), nil + } var recorded *db.RecordedFinding if t.findingRecorder != nil { recorded, err = t.findingRecorder.Record(ctx, input, refs) diff --git a/agent/triage.go b/agent/triage.go new file mode 100644 index 000000000..75ed0f437 --- /dev/null +++ b/agent/triage.go @@ -0,0 +1,500 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "math" + "net/http" + "regexp" + "sort" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode/utf8" + + "github.com/Autumn-27/artex/db" +) + +// Triage through a decision model (the llama.cpp /v1/systemone contract). +// +// A decision model answers a closed-list question with probabilities and generates +// no text, so a judgement that otherwise costs a main-model turn over a six-figure +// context costs one small request instead. Measured on our own findings (15 +// candidates, hand labels): picking the duplicate 8/8 on the 27B model and 7/8 on +// the flash one, against 7/15 for the constant "always distinct", at 0.66 s and +// ~1.7k input tokens per call with zero output tokens. +// +// It is ADVISORY by construction: every failure path falls back to today's +// behaviour, and only a confident answer changes an outcome. + +// Порог уверенности, выше которого ответ «дубль» гасит регистрацию. +// Переменная, а не константа: уверенность падает с шириной вопроса, и один +// фиксированный 0.5 не обслуживает оба конца. Снижать не страшно — результат +// подавления велит агенту перерегистрировать находку, если она различна. +// замер: калибровка stage3_calibrate.py 2026-11-22 — recall 1.00 при FP 0.47 на 75 +// жёстких негативах; на истинных дублях в живом прогоне 0.30-0.79. при превышении +// порога: находка не регистрируется, вызывающий получает finding_id. +const defaultTriageMinConfidence = 0.5 + +// triageDupMinConfidenceBits holds the threshold as float64 bits. It is written by the +// settings path (an HTTP goroutine) and read by the report_finding worker, so it is +// atomic: a plain float global is a data race under -race. +var triageDupMinConfidenceBits atomic.Uint64 + +func init() { + triageDupMinConfidenceBits.Store(math.Float64bits(defaultTriageMinConfidence)) +} + +// SetTriageMinConfidence overrides the suppression threshold. v <= 0 restores the default. +func SetTriageMinConfidence(v float64) { + if v <= 0 { + v = defaultTriageMinConfidence + } + triageDupMinConfidenceBits.Store(math.Float64bits(v)) +} + +// triageDupThreshold returns the current suppression threshold. +func triageDupThreshold() float64 { + return math.Float64frombits(triageDupMinConfidenceBits.Load()) +} + +const ( + // Потолок кандидатов в вопросе; отбор по релевантности, а не «новейшие N» — + // при широком графе верный партнёр выпадает из новейших по возрасту (triageRelevant). + // замер: ширина вопроса на реальном дубле, stage3_width.py 2026-11-22 — уверенность + // 0.81-0.91 до 11 кандидатов, 0.64 на 19, 0.56 на 29; латентность 0.44->1.29 с. + // при превышении: лишние кандидаты отбрасываются по релевантности. + triageMaxExisting = 10 + // Обрезка ОДНОЙ сводки; обрезка по записи, а не по состоянию целиком — иначе + // режется посреди строки и criteria остаётся с id, строки которого в состоянии нет. + // замер: распределение длин сводок в графе 2026-11-22 — p50 189, p90 334, max 564 + // (53 находки), то есть 400 сохраняет 90% сводок целиком. при превышении: сводка + // обрезается с «…», запись остаётся опознаваемой. + triageMaxSummaryChars = 400 + // Страховка на собранное состояние при потолке 10 записей. + // запас посчитан: 10*(400+60) + кандидат 480 ≈ 5.1 КБ против 6000, то есть 1.17x; + // при поштучной обрезке срабатывает только на патологических сводках. + // при превышении: состояние режется по границе записи. + triageMaxStateChars = 6000 +) + +// TriageCandidate is a finding reduced to what a dedup question needs. +type TriageCandidate struct { + FindingID int64 + // NodeID is the exploration node id of the same finding. The agent extends a + // finding through update_finding_report, which addresses the NODE, while the + // question and the suppression answer carry the findings-table id — both have + // to come back to the caller or it passes the wrong one. + NodeID int64 + Name string + VulnClass string + Severity string + Summary string + // RelatedTask is non-zero when the finding belongs to a directly related task + // (read-only here); it rides into the question so the model can weigh it. + RelatedTask int64 +} + +// DuplicateAnswer is the parsed verdict: DuplicateOf == 0 means "genuinely distinct". +type DuplicateAnswer struct { + DuplicateOf int64 + // DuplicateOfNode is the exploration node id of DuplicateOf (0 when unknown). + DuplicateOfNode int64 + Confidence float64 +} + +// TriageClient answers the closed-list questions the agent asks. +type TriageClient interface { + Duplicate(ctx context.Context, cand TriageCandidate, existing []TriageCandidate) (DuplicateAnswer, error) +} + +// SystemOneClient is a TriageClient over a decision-model endpoint. BaseURL is the +// OpenAI-style base ("https://host:8088/v1"); "/systemone" is appended. +type SystemOneClient struct { + BaseURL string + APIKey string + Model string + HTTP *http.Client +} + +// Таймаут запроса к decider. замер: латентность 0.26-0.57 с при ширине до 11 и 1.29 с на 29 +// (stage3_width.py 2026-11-22), 3.83-3.96 с на 27B-варианте (этап 0, 2026-11-21); у пула +// conc=2 и нет очереди, занятость добавляет ожидание. запас ~5x к худшему замеру. +// при превышении: ошибка -> fail open, находка регистрируется как раньше. +// Экспортирован, чтобы сервер, собирающий клиенту guarded-транспорт, брал тот же +// бюджет, а не заводил второй таймаут с другим числом. +const TriageHTTPTimeout = 20 * time.Second // замер: 0.26-3.96 с наблюдаемо; запас 5x + +func (c *SystemOneClient) http() *http.Client { + if c.HTTP != nil { + return c.HTTP + } + return &http.Client{Timeout: TriageHTTPTimeout} +} + +// Duplicate asks which existing finding, if any, is the same defect as cand. +func (c *SystemOneClient) Duplicate(ctx context.Context, cand TriageCandidate, existing []TriageCandidate) (DuplicateAnswer, error) { + if strings.TrimSpace(c.BaseURL) == "" || strings.TrimSpace(c.Model) == "" { + return DuplicateAnswer{}, fmt.Errorf("triage: base_url and model are required") + } + if len(existing) == 0 || strings.TrimSpace(cand.Summary) == "" { + return DuplicateAnswer{}, nil + } + body, err := json.Marshal(map[string]any{ + "model": c.Model, + "state": buildDuplicateState(cand, existing), + "questions": map[string]any{ + "duplicate_of": map[string]any{ + "type": "choice", + "instructions": duplicateInstructions, + "criteria": duplicateCriteria(existing), + }, + }, + }) + if err != nil { + return DuplicateAnswer{}, err + } + url := strings.TrimRight(c.BaseURL, "/") + "/systemone" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) + if err != nil { + return DuplicateAnswer{}, err + } + req.Header.Set("Content-Type", "application/json") + if c.APIKey != "" { + req.Header.Set("Authorization", "Bearer "+c.APIKey) + } + resp, err := c.http().Do(req) + if err != nil { + return DuplicateAnswer{}, err + } + defer resp.Body.Close() + // 1 MiB: ответ decider — это JSON вероятностей, замеренный 0.3-2 КБ (живые прогоны), + // то есть запас ~500x; потолок страхует от чатоподобного эндпоинта вместо decision. + // при превышении: тело читается частично, JSON может не распарситься -> fail open. + raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return DuplicateAnswer{}, err + } + if resp.StatusCode != http.StatusOK { + return DuplicateAnswer{}, fmt.Errorf("triage: status %d: %s", resp.StatusCode, triageFirstLine(raw)) + } + ids := make(map[int64]bool, len(existing)) + for _, e := range existing { + ids[e.FindingID] = true + } + return parseDuplicateAnswer(raw, ids) +} + +const duplicateInstructions = "The CANDIDATE finding is new. Decide whether it is the SAME defect as one of " + + "the REGISTERED findings (same endpoint, same parameter, same root cause) or a genuinely distinct finding. " + + "Answer 'none' when the candidate is distinct even if it shares the vulnerability class with a registered one." + +// buildDuplicateState renders the question's state. Deterministic: findings in the +// order given, candidate first. +func buildDuplicateState(cand TriageCandidate, existing []TriageCandidate) string { + var b strings.Builder + fmt.Fprintf(&b, "CANDIDATE FINDING\nclass: %s\nseverity: %s\nname: %s\nsummary: %s\n\nREGISTERED FINDINGS\n", + cand.VulnClass, cand.Severity, cand.Name, capText(cand.Summary, triageMaxSummaryChars)) + for _, e := range existing { + rel := "" + if e.RelatedTask > 0 { + rel = fmt.Sprintf(" (related task %d)", e.RelatedTask) + } + fmt.Fprintf(&b, "[%d]%s class=%s severity=%s name=%s | %s\n", + e.FindingID, rel, e.VulnClass, e.Severity, e.Name, capText(e.Summary, triageMaxSummaryChars)) + } + out := b.String() + if len(out) > triageMaxStateChars { + out = cutRunes(out, triageMaxStateChars) + } + return out +} + +// duplicateCriteria builds the closed list: "none" plus one key per finding id. +func duplicateCriteria(existing []TriageCandidate) map[string]any { + c := map[string]any{"none": "a genuinely distinct finding (different endpoint, parameter or root cause)"} + for _, e := range existing { + desc := strings.TrimSpace(e.Name) + if s := strings.TrimSpace(e.Summary); s != "" { + if desc != "" { + desc += " | " + } + desc += s + } + if desc == "" { + desc = "registered finding" + } + c[strconv.FormatInt(e.FindingID, 10)] = desc + } + return c +} + +// triageDuplicateHit reports whether an answer should suppress registration. +// Split out so the threshold is testable without an HTTP round trip. +func triageDuplicateHit(ans DuplicateAnswer) bool { + return ans.DuplicateOf > 0 && ans.Confidence >= triageDupThreshold() +} + +// parseDuplicateAnswer reads answers.duplicate_of. A choice that is not one of the +// offered ids is treated as "none" rather than as an error: the model naming an +// unknown id must not suppress a finding. +func parseDuplicateAnswer(raw []byte, existingIDs map[int64]bool) (DuplicateAnswer, error) { + var resp struct { + Answers map[string]struct { + Type string `json:"type"` + Choice string `json:"choice"` + Confidence float64 `json:"confidence"` + Probabilities map[string]float64 `json:"probabilities"` + } `json:"answers"` + } + if err := json.Unmarshal(raw, &resp); err != nil { + return DuplicateAnswer{}, fmt.Errorf("triage: bad answer json: %w", err) + } + a, ok := resp.Answers["duplicate_of"] + if !ok { + return DuplicateAnswer{}, fmt.Errorf("triage: answer has no duplicate_of") + } + conf := a.Confidence + if conf == 0 && a.Probabilities != nil { + conf = a.Probabilities[a.Choice] // some runtimes only fill probabilities + } + choice := strings.TrimSpace(a.Choice) + if choice == "" || choice == "none" { + return DuplicateAnswer{Confidence: conf}, nil + } + id, err := strconv.ParseInt(choice, 10, 64) + if err != nil || !existingIDs[id] { + return DuplicateAnswer{Confidence: conf}, nil + } + return DuplicateAnswer{DuplicateOf: id, Confidence: conf}, nil +} + +func capText(s string, n int) string { + if n > 0 && len(s) > n { + return cutRunes(s, n) + "…" + } + return s +} + +// cutRunes truncates s to at most n BYTES without splitting a multi-byte rune. +// The caps above are byte budgets (they bound a request), but a byte-index cut +// through a CJK or Cyrillic summary leaves a broken rune — the JSON encoder then +// sends U+FFFD and the question loses the tail of the evidence. +func cutRunes(s string, n int) string { + if n <= 0 || len(s) <= n { + return s + } + cut := n + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + return s[:cut] +} + +func triageFirstLine(b []byte) string { + s := strings.TrimSpace(string(b)) + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = s[:i] + } + if len(s) > 200 { + s = s[:200] + } + return s +} + +// --- wiring into report_finding --- + +// SetTriageClient installs (or, with nil, removes) the advisory triage client. +func (t *ToolSet) SetTriageClient(c TriageClient) { t.triage = c } + +// SetTriageClient mirrors ToolSet.SetTriageClient for the worker and planner: the +// per-run ToolSet is built inside their Plan/Run, so the client has to ride on the +// agent the same way the finding recorder does. +func (w *Worker) SetTriageClient(c TriageClient) { w.triage = c } +func (p *Planner) SetTriageClient(c TriageClient) { p.triage = c } + +// triageDuplicate asks the client about the finding being registered, against the +// task's already registered findings. Ordering and truncation keep the question +// bounded: newest findings first (a duplicate of a fresh finding is the common case). +func (t *ToolSet) triageDuplicate(ctx context.Context, in db.RecordFindingInput) (DuplicateAnswer, bool) { + if t.triage == nil || t.ts == nil { + log.Printf("[triage] skip: client=%v store=%v", t.triage != nil, t.ts != nil) + return DuplicateAnswer{}, false + } + nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500) + if err != nil || len(nodes) == 0 { + log.Printf("[triage] skip: nodes=%d err=%v", len(nodes), err) + return DuplicateAnswer{}, false + } + // Findings from independently created tasks on the same assets are NOT in the + // own-task pool (task_relations only links spawned tasks), yet they are exactly + // the duplicates a human would merge. The candidate's own asset ids are the join. + if len(in.AssetIDs) > 0 { + if cross, err := t.ts.FindingsSharingAssets(in.AssetIDs, t.taskID, triageMaxExisting); err == nil { + seen := make(map[int64]bool, len(nodes)) + for _, n := range nodes { + seen[n.ID] = true + } + for _, n := range cross { + if n != nil && !seen[n.ID] { + nodes = append(nodes, n) + } + } + } + } + // FindingID lives in the findings table, not on the node: without this the + // candidate list is built from nodes whose FindingID is still 0 and every + // entry is dropped (observed live: "nodes=6, no usable existing findings"). + if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil { + log.Printf("[triage] populate finding ids failed: %v", err) + } + existing := triageCandidates(nodes, in) + if len(existing) == 0 { + log.Printf("[triage] skip: no usable existing findings (nodes=%d)", len(nodes)) + return DuplicateAnswer{}, false + } + log.Printf("[triage] asking: existing=%d candidate=%q", len(existing), in.Name) + ans, err := t.triage.Duplicate(ctx, TriageCandidate{ + Name: in.Name, VulnClass: in.VulnClass, Severity: in.Severity, Summary: in.Summary, + }, existing) + if err != nil { + log.Printf("[triage] client error (fail open): %v", err) + return DuplicateAnswer{}, false + } + // Carry the node id of the matched finding alongside its findings-table id: + // the agent extends a finding through update_finding_report, which takes the + // node id, so an answer that names only the table id sends it to the wrong call. + ans = withNodeID(ans, existing) + log.Printf("[triage] answer: dup=%d node=%d conf=%.2f", ans.DuplicateOf, ans.DuplicateOfNode, ans.Confidence) + return ans, true +} + +// withNodeID resolves the exploration node id of the matched finding from the +// candidates the question offered. Pure, so the mapping is testable without a +// decision-model round trip. +func withNodeID(ans DuplicateAnswer, existing []TriageCandidate) DuplicateAnswer { + if ans.DuplicateOf <= 0 { + return ans + } + for _, e := range existing { + if e.FindingID == ans.DuplicateOf { + ans.DuplicateOfNode = e.NodeID + break + } + } + return ans +} + +// triageCandidates reduces finding nodes to question candidates: nodes without a +// finding row are skipped, the rest ranked by relevance to the candidate (see +// triageRelevant) and capped. Findings inherited from a directly related task are +// kept — the agent sees them in list_findings too — and marked so the model knows +// they are not this task's own. +func triageCandidates(nodes []*db.Node, in db.RecordFindingInput) []TriageCandidate { + usable := make([]*db.Node, 0, len(nodes)) + for _, n := range nodes { + if n != nil && n.FindingID > 0 { + usable = append(usable, n) + } + } + sort.SliceStable(usable, func(i, j int) bool { return usable[i].ID > usable[j].ID }) + out := make([]TriageCandidate, 0, triageMaxExisting) + for _, n := range triageRelevant(usable, in, triageMaxExisting) { + var p map[string]any + _ = json.Unmarshal(n.Payload, &p) + out = append(out, TriageCandidate{ + FindingID: n.FindingID, + NodeID: n.ID, + Name: strField(p, "name"), + VulnClass: strField(p, "vulnclass"), + Severity: strField(p, "severity"), + Summary: strField(p, "summary"), + RelatedTask: func() int64 { + if n.Inherited { + return n.SourceTaskID + } + return 0 + }(), + }) + } + return out +} + +// triageRelevant ranks candidate findings for the question and keeps the best cap. +// +// Ranking, strongest first: the same vulnerability class, an overlapping endpoint, +// membership in another task that shares an asset (those nodes arrive pre-filtered +// by asset, which is itself a signal), then newest. A flat "newest N" is arbitrary +// and drops the true partner on a wide graph; relevance keeps what the question is +// about. Falls back to the newest cap when nothing scores, so behaviour without +// assets (or on a first finding) is unchanged. +func triageRelevant(nodes []*db.Node, in db.RecordFindingInput, cap int) []*db.Node { + if cap <= 0 || len(nodes) <= cap { + return nodes + } + candEP := endpointTokens(in.Summary) + type scored struct { + n *db.Node + score int + } + ranked := make([]scored, 0, len(nodes)) + for _, n := range nodes { + var p map[string]any + _ = json.Unmarshal(n.Payload, &p) + s := 0 + if in.VulnClass != "" && strField(p, "vulnclass") == in.VulnClass { + s += 2 + } + if len(candEP) > 0 { + for ep := range endpointTokens(strField(p, "summary")) { + if candEP[ep] { + s += 2 + break + } + } + } + if n.Inherited { + s++ // another task on a shared asset: already a signal, not noise + } + ranked = append(ranked, scored{n, s}) + } + sort.SliceStable(ranked, func(i, j int) bool { + if ranked[i].score != ranked[j].score { + return ranked[i].score > ranked[j].score + } + return ranked[i].n.ID > ranked[j].n.ID + }) + out := make([]*db.Node, 0, cap) + for _, r := range ranked { + if len(out) >= cap { + break + } + out = append(out, r.n) + } + return out +} + +var endpointTokenRe = regexp.MustCompile(`/(?:rest|api|v[0-9])/[a-z0-9_{}./-]+`) + +func endpointTokens(s string) map[string]bool { + out := map[string]bool{} + for _, m := range endpointTokenRe.FindAllString(strings.ToLower(s), -1) { + out[strings.TrimRight(m, ".,;")] = true + } + return out +} + +func strField(p map[string]any, k string) string { + if p == nil { + return "" + } + if v, ok := p[k].(string); ok { + return v + } + return "" +} diff --git a/agent/triage_override_test.go b/agent/triage_override_test.go new file mode 100644 index 000000000..bd71f7b7d --- /dev/null +++ b/agent/triage_override_test.go @@ -0,0 +1,113 @@ +package agent + +import ( + "context" + "encoding/json" + "strconv" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +// dupTriageClient answers "the same defect" every time, so the suppression path +// runs without a decision-model server. +type dupTriageClient struct{ target int64 } + +func (c dupTriageClient) Duplicate(context.Context, TriageCandidate, []TriageCandidate) (DuplicateAnswer, error) { + return DuplicateAnswer{DuplicateOf: c.target, Confidence: 0.99}, nil +} + +func findingNodes(t *testing.T, ts *ToolSet) []*db.Node { + t.Helper() + nodes, err := ts.ts.ListByKindWithSources(db.KindFinding, 50) + if err != nil { + t.Fatal(err) + } + if err := ts.ts.PopulateFindingTrafficIDs(nodes); err != nil { + t.Fatal(err) + } + return nodes +} + +// The suppression answer tells the agent to register a genuinely distinct defect +// again — that advice is unactionable unless a retry can bypass the check. This +// walks the whole path: suppress, then override, and checks the answer names the +// NODE id update_finding_report needs, not only the findings-table id. +func TestReportFindingForceRegisterOverridesSuppression(t *testing.T) { + d := testDB(t) + t.Cleanup(func() { _ = d.Close() }) + task, err := d.CreateTaskWithOptions("triage override", "exercise the duplicate override", db.TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(task.ID) }) + + ts := NewToolSet(d.Exploration(task.ExplorationID), "worker-1") + ts.SetTaskID(task.ID) + body := `{"vulnclass":"sqli","severity":"high","summary":"GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."}` + + if res := callGuardTool(t, ts.addFinding(), body); res.IsError { + t.Fatalf("first report_finding failed: %s", res.Flatten()) + } + nodes := findingNodes(t, ts) + if len(nodes) != 1 { + t.Fatalf("findings after the first call = %d, want 1", len(nodes)) + } + fid, nid := nodes[0].FindingID, nodes[0].ID + if fid <= 0 || nid <= 0 { + t.Fatalf("fixture ids = finding %d / node %d", fid, nid) + } + + ts.SetTriageClient(dupTriageClient{target: fid}) + res := callGuardTool(t, ts.addFinding(), body) + if res.IsError { + t.Fatalf("suppressed report_finding returned an error: %s", res.Flatten()) + } + text := res.Flatten() + if !strings.Contains(text, "duplicate_not_registered") { + t.Fatalf("second call was not suppressed: %s", text) + } + // The caller must be able to act on the answer: both ids, and the node id is + // the one update_finding_report takes. + var ans struct { + DuplicateOfFindingID int64 `json:"duplicate_of_finding_id"` + DuplicateOfNodeID int64 `json:"duplicate_of_finding_node_id"` + } + payload := text[strings.Index(text, "{"):] + if err := json.Unmarshal([]byte(payload), &ans); err != nil { + t.Fatalf("suppression answer is not JSON: %v (%s)", err, text) + } + if ans.DuplicateOfFindingID != fid || ans.DuplicateOfNodeID != nid { + t.Fatalf("answer ids = finding %d / node %d, want %d / %d", ans.DuplicateOfFindingID, ans.DuplicateOfNodeID, fid, nid) + } + if !strings.Contains(text, "finding_id="+strconv.FormatInt(nid, 10)) { + t.Fatalf("answer does not point at the node id: %s", text) + } + if got := len(findingNodes(t, ts)); got != 1 { + t.Fatalf("findings after suppression = %d, want 1", got) + } + + // force_register is the way out: the same call now registers. + forced := `{"force_register":true,"vulnclass":"sqli","severity":"high","summary":"GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."}` + if res := callGuardTool(t, ts.addFinding(), forced); res.IsError { + t.Fatalf("forced report_finding failed: %s", res.Flatten()) + } else if strings.Contains(res.Flatten(), "duplicate_not_registered") { + t.Fatalf("force_register was ignored: %s", res.Flatten()) + } + if got := len(findingNodes(t, ts)); got != 2 { + t.Fatalf("findings after force_register = %d, want 2", got) + } +} + +// The parameter has to be advertised, or the model never learns the way out. +func TestReportFindingAdvertisesForceRegister(t *testing.T) { + schema := NewToolSet(nil, "").addFinding().InputSchema() + raw, err := json.Marshal(schema) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), "force_register") { + t.Fatalf("report_finding schema does not advertise force_register: %s", raw) + } +} diff --git a/agent/triage_review_test.go b/agent/triage_review_test.go new file mode 100644 index 000000000..20d650c5f --- /dev/null +++ b/agent/triage_review_test.go @@ -0,0 +1,92 @@ +package agent + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/Autumn-27/artex/db" +) + +// The caps bound a request in BYTES, but a byte-index cut through a multi-byte +// rune leaves a broken character: the JSON encoder sends U+FFFD and the decider +// reads garbage where the evidence tail was. Every cut must land on a boundary. +func TestCapTextCutsOnRuneBoundary(t *testing.T) { + for _, tc := range []struct { + name string + text string + cap int + }{ + {"cyrillic", strings.Repeat("уязвимость ", 80), 51}, + {"cjk", strings.Repeat("数据泄露", 100), 401}, + {"mixed", "SQLi: " + strings.Repeat("инъекция ", 90), 333}, + } { + t.Run(tc.name, func(t *testing.T) { + out := capText(tc.text, tc.cap) + if !utf8.ValidString(out) { + t.Fatalf("capText(%d) produced invalid UTF-8", tc.cap) + } + if !strings.HasSuffix(out, "…") { + t.Fatalf("capText(%d) dropped the ellipsis", tc.cap) + } + body := strings.TrimSuffix(out, "…") + if len(body) > tc.cap { + t.Fatalf("capText(%d) kept %d bytes", tc.cap, len(body)) + } + if !strings.HasPrefix(tc.text, body) { + t.Fatalf("capText(%d) is not a prefix of the input", tc.cap) + } + }) + } +} + +// The assembled state has its own byte ceiling; the same rule applies there, and +// the whole state must still parse as text. +func TestBuildDuplicateStateCutsOnRuneBoundary(t *testing.T) { + existing := make([]TriageCandidate, 0, 40) + for i := 0; i < 40; i++ { + existing = append(existing, TriageCandidate{ + FindingID: int64(i + 1), + Name: "数据泄露", + Summary: strings.Repeat("утечка данных через параметр ", 20), + }) + } + state := buildDuplicateState(TriageCandidate{Name: "SQLi", Summary: strings.Repeat("данные ", 200)}, existing) + if len(state) > triageMaxStateChars { + t.Fatalf("state is %d bytes, cap is %d", len(state), triageMaxStateChars) + } + if !utf8.ValidString(state) { + t.Fatal("state was cut mid-rune") + } +} + +// The question and the suppression answer carry the findings-table id, while +// update_finding_report addresses the exploration node — the candidate list has +// to keep both so the answer can name the one the agent needs to act on. +func TestTriageCandidatesCarryNodeID(t *testing.T) { + nodes := []*db.Node{ + {ID: 41, FindingID: 7, Payload: []byte(`{"name":"SQLi","vulnclass":"sqli","severity":"high","summary":"s"}`)}, + {ID: 42, FindingID: 0, Payload: []byte(`{"name":"no finding row"}`)}, + } + out := triageCandidates(nodes, db.RecordFindingInput{}) + if len(out) != 1 { + t.Fatalf("candidates = %d, want 1 (node without a finding row is skipped)", len(out)) + } + if out[0].NodeID != 41 || out[0].FindingID != 7 { + t.Fatalf("candidate ids = node %d / finding %d, want 41 / 7", out[0].NodeID, out[0].FindingID) + } +} + +func TestWithNodeIDMapsFindingToNode(t *testing.T) { + existing := []TriageCandidate{{FindingID: 7, NodeID: 41}, {FindingID: 9, NodeID: 55}} + if got := withNodeID(DuplicateAnswer{DuplicateOf: 9, Confidence: 0.8}, existing); got.DuplicateOfNode != 55 { + t.Fatalf("DuplicateOfNode = %d, want 55", got.DuplicateOfNode) + } + if got := withNodeID(DuplicateAnswer{}, existing); got.DuplicateOfNode != 0 { + t.Fatalf("distinct answer carried node %d", got.DuplicateOfNode) + } + // An id the question never offered must not invent a node. + if got := withNodeID(DuplicateAnswer{DuplicateOf: 999}, existing); got.DuplicateOfNode != 0 { + t.Fatalf("unoffered id mapped to node %d", got.DuplicateOfNode) + } +} diff --git a/agent/triage_test.go b/agent/triage_test.go new file mode 100644 index 000000000..f9243b29e --- /dev/null +++ b/agent/triage_test.go @@ -0,0 +1,310 @@ +package agent + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func triageCandidate() TriageCandidate { + return TriageCandidate{VulnClass: "sqli", Severity: "high", Name: "SQLi in search", + Summary: "GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."} +} + +func triageExisting() []TriageCandidate { + return []TriageCandidate{ + {FindingID: 98, VulnClass: "sqli", Severity: "high", Name: "SQL injection in search", Summary: "UNION SELECT dumps the Users table."}, + {FindingID: 102, VulnClass: "xss", Severity: "medium", Name: "DOM XSS", Summary: "q is bound via innerHTML."}, + } +} + +// newTriageServer returns a test server that captures the request body and replies +// with the given answers payload. +func newTriageServer(t *testing.T, answers map[string]any, status int) (*httptest.Server, *map[string]any) { + t.Helper() + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/systemone") { + t.Errorf("unexpected path %s", r.URL.Path) + } + if h := r.Header.Get("Authorization"); h != "Bearer testkey" { + t.Errorf("authorization header = %q", h) + } + body, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(body, &got) + if status != http.StatusOK { + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"error":{"message":"boom"}}`)) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"answers": answers}) + })) + t.Cleanup(srv.Close) + return srv, &got +} + +func TestSystemOneClient_DuplicateNamesExistingFinding(t *testing.T) { + srv, got := newTriageServer(t, map[string]any{ + "duplicate_of": map[string]any{"type": "choice", "choice": "98", "confidence": 0.91}, + }, http.StatusOK) + c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"} + + ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ans.DuplicateOf != 98 || ans.Confidence != 0.91 { + t.Fatalf("answer = %+v, want duplicate 98 @0.91", ans) + } + // The question must offer every existing finding plus "none", and carry the + // candidate so the model can compare. + if (*got)["model"] != "decider" { + t.Fatalf("model not sent: %v", (*got)["model"]) + } + state, _ := (*got)["state"].(string) + if !strings.Contains(state, "CANDIDATE FINDING") || !strings.Contains(state, "[98]") { + t.Fatalf("state does not carry candidate and existing findings:\n%s", state) + } + q := (*got)["questions"].(map[string]any)["duplicate_of"].(map[string]any) + if q["type"] != "choice" { + t.Fatalf("question type = %v", q["type"]) + } + crit := q["criteria"].(map[string]any) + for _, k := range []string{"none", "98", "102"} { + if _, ok := crit[k]; !ok { + t.Fatalf("criteria misses %q: %v", k, crit) + } + } +} + +func TestSystemOneClient_DistinctFinding(t *testing.T) { + srv, _ := newTriageServer(t, map[string]any{ + "duplicate_of": map[string]any{"type": "choice", "choice": "none", "confidence": 0.88}, + }, http.StatusOK) + c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"} + + ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ans.DuplicateOf != 0 { + t.Fatalf("want no duplicate, got %d", ans.DuplicateOf) + } +} + +// An id the question never offered must not suppress a finding. +func TestSystemOneClient_UnknownChoiceIsNotADuplicate(t *testing.T) { + srv, _ := newTriageServer(t, map[string]any{ + "duplicate_of": map[string]any{"choice": "777", "confidence": 0.99}, + }, http.StatusOK) + c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"} + + ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting()) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ans.DuplicateOf != 0 { + t.Fatalf("unknown id must read as distinct, got %d", ans.DuplicateOf) + } +} + +// Runtimes that fill only probabilities still yield a usable confidence. +func TestParseDuplicateAnswer_FallsBackToProbability(t *testing.T) { + raw := []byte(`{"answers":{"duplicate_of":{"type":"choice","choice":"98","probabilities":{"none":0.1,"98":0.8,"102":0.1}}}}`) + ans, err := parseDuplicateAnswer(raw, map[int64]bool{98: true, 102: true}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ans.DuplicateOf != 98 || ans.Confidence != 0.8 { + t.Fatalf("answer = %+v, want 98 @0.8", ans) + } +} + +func TestSystemOneClient_ErrorOnBadStatus(t *testing.T) { + srv, _ := newTriageServer(t, nil, http.StatusInternalServerError) + c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"} + if _, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting()); err == nil { + t.Fatal("want an error on 500 so the caller can fail open") + } +} + +// Nothing to judge: no existing findings or an empty summary must not cost a call. +func TestSystemOneClient_NoCallWithoutInput(t *testing.T) { + called := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + called++ + _ = json.NewEncoder(w).Encode(map[string]any{}) + })) + defer srv.Close() + c := &SystemOneClient{BaseURL: srv.URL + "/v1", Model: "decider"} + + if _, err := c.Duplicate(context.Background(), triageCandidate(), nil); err != nil { + t.Fatalf("no existing findings: %v", err) + } + empty := triageCandidate() + empty.Summary = "" + if _, err := c.Duplicate(context.Background(), empty, triageExisting()); err != nil { + t.Fatalf("empty summary: %v", err) + } + if called != 0 { + t.Fatalf("expected no HTTP call, got %d", called) + } +} + +// Regression: FindingID lives in the findings table, not on the node. Building +// candidates from nodes as they come out of the store dropped every entry +// ("nodes=6, no usable existing findings" on a live run) and triage never fired. +func TestTriageCandidates_SkipsNodesWithoutFindingRow(t *testing.T) { + payload := func(name string) []byte { + b, _ := json.Marshal(map[string]any{"name": name, "vulnclass": "sqli", "severity": "high", "summary": name + " summary"}) + return b + } + nodes := []*db.Node{ + {ID: 10, Kind: db.KindFinding, Payload: payload("no finding row"), FindingID: 0}, + {ID: 9, Kind: db.KindFinding, Payload: payload("own finding"), FindingID: 98}, + {ID: 11, Kind: db.KindFinding, Payload: payload("inherited finding"), FindingID: 55, Inherited: true, SourceTaskID: 7}, + } + got := triageCandidates(nodes, db.RecordFindingInput{}) + if len(got) != 2 { + t.Fatalf("want 2 candidates (the row-less node skipped), got %d: %+v", len(got), got) + } + if got[0].FindingID != 55 || got[0].RelatedTask != 7 { + t.Fatalf("newest first with its related task: %+v", got[0]) + } + if got[1].FindingID != 98 || got[1].RelatedTask != 0 { + t.Fatalf("own finding must carry no related task: %+v", got[1]) + } + st := buildDuplicateState(TriageCandidate{Summary: "cand"}, got) + if !strings.Contains(st, "(related task 7)") { + t.Fatalf("state must mark an inherited finding:\n%s", st) + } +} + +// The cap must be a SELECTION: with more candidates than fit, the ones matching the +// candidate's class or endpoint come first, newest only breaking ties. +func TestTriageRelevant_PrefersRelevanceOverRecency(t *testing.T) { + mk := func(id, findingID int64, class, summary string) *db.Node { + b, _ := json.Marshal(map[string]any{"vulnclass": class, "summary": summary}) + return &db.Node{ID: id, Kind: db.KindFinding, Payload: b, FindingID: findingID} + } + // The relevant finding is OLDER than the noise, so a newest-first cap would drop + // it — that is exactly the live defect this ranking fixes. + nodes := []*db.Node{mk(50, 50, "sqli", "GET /rest/user/login is injectable")} + for i := int64(100); i < 115; i++ { + nodes = append(nodes, mk(i, i, "xss", "GET /other/thing"+strconv.FormatInt(i, 10))) + } + got := triageCandidates(nodes, db.RecordFindingInput{VulnClass: "sqli", Summary: "POST /rest/user/login injectable"}) + if len(got) != triageMaxExisting { + t.Fatalf("cap = %d, want %d", len(got), triageMaxExisting) + } + if got[0].FindingID != 50 { + t.Fatalf("the relevant OLD finding must rank first, got %d (%+v)", got[0].FindingID, got[0]) + } +} + +func TestBuildDuplicateState_CapsPerEntry(t *testing.T) { + long := strings.Repeat("y", 500) + st := buildDuplicateState( + TriageCandidate{Summary: long}, + []TriageCandidate{{FindingID: 1, Summary: long}, {FindingID: 2, Summary: long}}) + // every offered finding stays present and its line is capped, not the whole state + for _, id := range []string{"[1]", "[2]"} { + if !strings.Contains(st, id) { + t.Fatalf("entry %s was cut out of the state:\n%s", id, st) + } + } + if strings.Count(st, "…") < 3 { + t.Fatalf("expected every summary to be capped, got %d caps", strings.Count(st, "…")) + } + if len(st) > triageMaxStateChars { + t.Fatalf("state over the safety cap: %d", len(st)) + } +} + +func TestBuildDuplicateState_Caps(t *testing.T) { + var many []TriageCandidate + for i := 0; i < 200; i++ { + many = append(many, TriageCandidate{FindingID: int64(i), Summary: strings.Repeat("x", 200)}) + } + st := buildDuplicateState(triageCandidate(), many) + if len(st) > triageMaxStateChars { + t.Fatalf("state not capped: %d", len(st)) + } + if !strings.Contains(st, "CANDIDATE FINDING") { + t.Fatal("state lost the candidate") + } +} + +func TestTriageDuplicateHit_Threshold(t *testing.T) { + defer SetTriageMinConfidence(defaultTriageMinConfidence) // restore the default for other tests + SetTriageMinConfidence(defaultTriageMinConfidence) + cases := []struct { + in DuplicateAnswer + want bool + }{ + {DuplicateAnswer{DuplicateOf: 5, Confidence: 0.9}, true}, + {DuplicateAnswer{DuplicateOf: 5, Confidence: defaultTriageMinConfidence}, true}, + {DuplicateAnswer{DuplicateOf: 5, Confidence: 0.4}, false}, // below the threshold: register as before + {DuplicateAnswer{DuplicateOf: 0, Confidence: 0.99}, false}, + } + for _, c := range cases { + if got := triageDuplicateHit(c.in); got != c.want { + t.Fatalf("hit(%+v) = %v, want %v", c.in, got, c.want) + } + } + // The live run produced true duplicates at 0.30 with the right partner named, so + // a lowered threshold must flip them to a hit — that is the point of the knob. + SetTriageMinConfidence(0.25) + if !triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.30}) { + t.Fatal("0.30 must hit at threshold 0.25") + } + SetTriageMinConfidence(0.9) + if triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.30}) { + t.Fatal("0.30 must miss at threshold 0.9") + } +} + +// The settings path writes the threshold from an HTTP goroutine while report_finding +// reads it on a worker. Run under -race: a plain float global fails here. +func TestTriageThresholdConcurrentSetAndRead(t *testing.T) { + defer SetTriageMinConfidence(0.5) + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 2000; i++ { + SetTriageMinConfidence(0.3 + 0.4*float64(i%2)) + } + }() + go func() { + defer wg.Done() + for i := 0; i < 2000; i++ { + _ = triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.6}) + } + }() + wg.Wait() +} + +func TestSetTriageMinConfidenceZeroRestoresDefault(t *testing.T) { + defer SetTriageMinConfidence(defaultTriageMinConfidence) + SetTriageMinConfidence(0.9) + SetTriageMinConfidence(0) + if got := triageDupThreshold(); got != defaultTriageMinConfidence { + t.Fatalf("threshold after Set(0) = %v, want %v", got, defaultTriageMinConfidence) + } + SetTriageMinConfidence(-1) + if got := triageDupThreshold(); got != defaultTriageMinConfidence { + t.Fatalf("threshold after Set(-1) = %v, want %v", got, defaultTriageMinConfidence) + } + if !triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.5}) { + t.Fatal("0.5 must hit at the restored default") + } +} diff --git a/agent/worker.go b/agent/worker.go index 9f1fff419..49284543e 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -62,17 +62,20 @@ type WebSearchOpts struct { type Worker struct { findingRecorder FindingRecorder - prov llm.Provider - model string - workDir string - proxyAddr string - proxyCACert string // recording proxy's CA cert path (for WebFetch HTTPS verify) - factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only) - webSearch WebSearchOpts // web_search tool backend selection (off by default) - tx *transcript.Store // raw LLM conversation persistence (nil = off) - window int // context window in tokens (for compaction) - windowFn func() int // optional dynamic task-chain minimum - maxTurns int // max agent turns per run (0 = unlimited) + // triage is the advisory decision-model client for closed-list judgements, + // handed to the per-run ToolSet (see agent/triage.go). nil = off. + triage TriageClient + prov llm.Provider + model string + workDir string + proxyAddr string + proxyCACert string // recording proxy's CA cert path (for WebFetch HTTPS verify) + factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only) + webSearch WebSearchOpts // web_search tool backend selection (off by default) + tx *transcript.Store // raw LLM conversation persistence (nil = off) + window int // context window in tokens (for compaction) + windowFn func() int // optional dynamic task-chain minimum + maxTurns int // max agent turns per run (0 = unlimited) // runTimeout is the wall-clock budget for the main exploration of one intent // (0 = unlimited). When it fires, the run is cut and a settlement round is // forced so already-identified facts get written back instead of being lost. @@ -532,6 +535,7 @@ func (w *Worker) ExecuteWithMessage(ctx context.Context, name string, taskID int func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, intent *db.Node, hooks harness.HookRunner, emit func(db.Activity), enr EnrichTrigger, notifyFinding func(int64, string), requestID, message string) (harness.TerminalReason, WriteCounts, error) { tsx := NewToolSet(ts, name) tsx.SetFindingRecorder(w.findingRecorder) + tsx.SetTriageClient(w.triage) tsx.SetFactTraffic(w.factTraffic) tsx.SetTaskID(taskID) coverageEnabled := coverageOn(as, taskID) diff --git a/db/finding_dedup_pool.go b/db/finding_dedup_pool.go new file mode 100644 index 000000000..f72f82736 --- /dev/null +++ b/db/finding_dedup_pool.go @@ -0,0 +1,71 @@ +package db + +import ( + "strings" +) + +// prefixedNodeCols mirrors nodeCols with an alias, for queries that join +// exploration_nodes with another table carrying an `id` of its own. +const prefixedNodeCols = `n.id, n.kind, n.payload, n.priority, n.state, ` + + `COALESCE(n.origin,''), COALESCE(n.owner,''), COALESCE(n.blocked_reason,''), ` + + `COALESCE(n.delete_reason,''), n.created_at` + +// FindingsSharingAssets returns finding nodes from OTHER tasks that are anchored to +// at least one of assetIDs. +// +// ListByKindWithSources covers the task's own findings plus its directly related +// tasks (task_relations). Two tasks run independently against the same target are +// NOT related, so a defect registered in one and re-registered in the other is +// invisible to a dedup check built only on that pool — measured live: three such +// duplicates across two tasks, all answered "distinct" because the question never +// offered them. Assets are the join that catches them. +// +// Returned nodes carry Inherited=true and SourceTaskID so callers can mark them as +// belonging to another task (read-only for extension). +func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask int64, limit int) ([]*Node, error) { + if len(assetIDs) == 0 { + return nil, nil + } + if limit <= 0 { + // 50: самый широкий наблюдённый пул по ассету — 31 находка на ассете [1] + // (53 находки в графе, 2026-11-22), запас 1.6x; вызывающий всё равно отбирает + // из результата не больше triageMaxExisting, так что 50 — верхняя граница запроса. + // при превышении: хвост по f.id DESC отбрасывается, вопрос всё равно ограничен. + limit = 50 + } + // One containment per asset, OR-joined: asset_ids is a jsonb array and the GIN + // index (jsonb_path_ops) serves @>, not a list-membership operator. + ors := make([]string, 0, len(assetIDs)) + args := []any{excludeTask} + for _, id := range assetIDs { + args = append(args, "["+itoa(id)+"]") + ors = append(ors, "f.asset_ids @> $"+itoa(int64(len(args)))+"::jsonb") + } + args = append(args, limit) + q := `SELECT ` + prefixedNodeCols + `, f.id, f.task_id + FROM findings f + JOIN exploration_nodes n ON n.id = f.node_id + WHERE f.task_id <> $1 AND (` + strings.Join(ors, " OR ") + `) + ORDER BY f.id DESC LIMIT $` + itoa(int64(len(args))) + rows, err := s.db.Query(q, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Node + for rows.Next() { + var n Node + var payload []byte + var findingID, taskID int64 + if err := rows.Scan(&n.ID, &n.Kind, &payload, &n.Priority, &n.State, &n.Origin, &n.Owner, + &n.BlockedReason, &n.DeleteReason, &n.CreatedAt, &findingID, &taskID); err != nil { + return nil, err + } + n.Payload = payload + n.FindingID = findingID + n.SourceTaskID = taskID + n.Inherited = true + out = append(out, &n) + } + return out, rows.Err() +} diff --git a/server/manager.go b/server/manager.go index d03525359..2da3ea942 100644 --- a/server/manager.go +++ b/server/manager.go @@ -334,6 +334,15 @@ const ( // Target noise profile (off|quiet|balanced|aggressive). When stored it wins over // ARTEX_NOISE_PROFILE, which stays the fallback; applied at startup and on PUT. settingNoiseProfile = "noise_profile" + // settingTriageProfile names an llm_profiles row that serves the decision-model + // (/v1/systemone) contract: the triage client for closed-list judgements such as + // the duplicate check in report_finding. Empty or 0 = triage off (main model + // decides, exactly as before). See server/triage.go. + settingTriageProfile = "triage_profile_id" + // settingTriageMinConfidence is the suppression threshold for a duplicate answer + // (0..1, empty = 0.5). Confidence on true duplicates moves with the question's + // width, so this is a knob rather than a constant. + settingTriageMinConfidence = "triage_min_confidence" // defaultWebSearchBackend is used when web search is on but no backend was picked. defaultWebSearchBackend = "ddgs" // deepSeekWebSearchBackend borrows the active LLM profile instead of its own diff --git a/server/server.go b/server/server.go index e6cc2b4c5..d2d85f579 100644 --- a/server/server.go +++ b/server/server.go @@ -3920,6 +3920,8 @@ func (s *Server) settingsPayload() map[string]any { return map[string]any{ "traffic_capture": s.m.TrafficEnabled(), "agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, false), + "triage_profile_id": s.triageProfileID(), + "triage_min_confidence": s.triageMinConfidence(), "llm_record": s.m.LLMRecordEnabled(), "web_search_enabled": on, "web_search_backend": backend, @@ -4021,6 +4023,14 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) { // operation-constraint injection scope switches (default both on); take effect immediately (planner/worker read them every round), no agent rebuild needed. ConstraintsInjectPlanner *bool `json:"constraints_inject_planner"` ConstraintsInjectWorker *bool `json:"constraints_inject_worker"` + // Triage profile: an llm_profiles row serving the decision-model (/v1/systemone) + // contract, used for closed-list judgements (report_finding dedup). 0/null-safe: + // omit = keep, 0 = off. Read per agent run, so it applies to runs started afterwards. + TriageProfileID *int64 `json:"triage_profile_id"` + // Suppression threshold for a duplicate answer (0..1). Lower catches more real + // duplicates and risks suppressing a distinct one; the caller is told to + // re-register in that case, which is what makes the low end affordable. + TriageMinConfidence *float64 `json:"triage_min_confidence"` // Experimental: noa context compaction switch (default off); read per run, applies to runs started afterwards, no agent rebuild needed. NoaCompaction *bool `json:"noa_compaction"` // Vulnerability IM push global settings. The delivery engine re-reads all three every round, so changes @@ -4052,6 +4062,26 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) { } egress.SetProfile(noise) } + // Triage settings are checked before either is stored. A profile id that does + // not exist resolves to "off" at run time, which reads as a broken dedup rather + // than as a rejected setting; a threshold outside 0..1 is silently ignored by + // the agent. Reject both here instead of storing them. + if req.TriageProfileID != nil { + if *req.TriageProfileID < 0 { + writeErr(w, 400, "triage_profile_id must be >= 0 (0 turns the duplicate check off)") + return + } + if *req.TriageProfileID > 0 { + if p, err := s.m.pg.ProfileByID(*req.TriageProfileID); err != nil || p == nil { + writeErr(w, 400, fmt.Sprintf("triage_profile_id %d does not match any LLM profile", *req.TriageProfileID)) + return + } + } + } + if req.TriageMinConfidence != nil && (*req.TriageMinConfidence < 0 || *req.TriageMinConfidence > 1) { + writeErr(w, 400, "triage_min_confidence must be between 0 and 1") + return + } // A masked placeholder echoed back keeps the stored secret, like null. req.BraveKey, req.TavilyKey, req.KeenableKey = keepIfMasked(req.BraveKey), keepIfMasked(req.TavilyKey), keepIfMasked(req.KeenableKey) req.WebSearchProxy, req.GlobalProxy = keepIfMasked(req.WebSearchProxy), keepIfMasked(req.GlobalProxy) @@ -4067,6 +4097,19 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) { return } } + if req.TriageMinConfidence != nil { + if err := s.m.pg.SetSetting(settingTriageMinConfidence, strconv.FormatFloat(*req.TriageMinConfidence, 'f', 3, 64)); err != nil { + writeErr(w, 500, err.Error()) + return + } + s.applyTriageThreshold() + } + if req.TriageProfileID != nil { + if err := s.m.pg.SetSetting(settingTriageProfile, strconv.FormatInt(*req.TriageProfileID, 10)); err != nil { + writeErr(w, 500, err.Error()) + return + } + } if req.NoaCompaction != nil { // The resolver is read per run; toggling takes effect immediately for runs started afterwards, no applyLLM rebuild needed. if err := s.m.SetNoaCompaction(*req.NoaCompaction); err != nil { diff --git a/server/task_llm.go b/server/task_llm.go index 29871f514..4e3968cf4 100644 --- a/server/task_llm.go +++ b/server/task_llm.go @@ -801,6 +801,8 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle { window := workerRuntime.CompactionWindow() wk := agent.NewWorker(workerRuntime, "task-router", s.m.dir, tx, window, s.agentMaxTurns("worker")) wk.SetFindingRecorder(s.evidenceStore()) + wk.SetTriageClient(s.triageClient()) // advisory dedup on report_finding (nil = off) + s.applyTriageThreshold() // stored suppression threshold (cheap, idempotent) wk.SetCompactionWindowResolver(workerRuntime.CompactionWindow) wk.SetNonStreaming(workerRuntime.nonStreaming) // per the task's currently active profile streaming switch (read every turn) wk.SetMaxTokens(workerRuntime.maxTokens) // as above, the output cap also follows the currently active profile @@ -812,6 +814,7 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle { wk.SetConstraintInject(s.constraintInjectWorker) // operation-constraint injection into the worker (configurable, on by default) pl := agent.NewPlanner(plannerRuntime, "task-router", s.m.dir, tx, plannerRuntime.CompactionWindow(), s.agentMaxTurns("planner")) pl.SetFindingRecorder(s.evidenceStore()) + pl.SetTriageClient(s.triageClient()) // the planner registers findings too (wrap-up paths) pl.SetCompactionWindowResolver(plannerRuntime.CompactionWindow) pl.SetNonStreaming(plannerRuntime.nonStreaming) pl.SetMaxTokens(plannerRuntime.maxTokens) diff --git a/server/triage.go b/server/triage.go new file mode 100644 index 000000000..4cb1da39e --- /dev/null +++ b/server/triage.go @@ -0,0 +1,121 @@ +package server + +import ( + "context" + "fmt" + "log" + "net" + "net/http" + "strconv" + "strings" + "time" + + "github.com/Autumn-27/artex/agent" +) + +// triageClient builds the advisory triage client from the configured profile, or +// nil when triage is off. The profile's base_url must serve the decision-model +// contract at /systemone; the model is the profile's model. Built per +// agent run (cheap: one settings read + one profile read), so toggling the setting +// takes effect on the next run without an agent rebuild. +// +// Fail-open by design: an unreadable setting, a missing profile or a profile with +// no base_url/model returns nil, and report_finding behaves exactly as before. +func (s *Server) triageClient() agent.TriageClient { + id := s.triageProfileID() + log.Printf("[triage] triageClient: profile_id=%d", id) + if id <= 0 { + return nil + } + p, err := s.m.pg.ProfileByID(id) + if err != nil || p == nil { + return nil + } + if strings.TrimSpace(p.BaseURL) == "" || strings.TrimSpace(p.Model) == "" { + return nil + } + client := s.triageHTTPClient(p.BaseURL) + if client == nil { + return nil + } + return &agent.SystemOneClient{BaseURL: p.BaseURL, APIKey: p.APIKey, Model: p.Model, HTTP: client} +} + +// triageHTTPClient builds the HTTP client for the decision endpoint under the same +// endpoint guard the model-list path uses (ARTEX_LLM_PRIVATE_ENDPOINTS, private and +// metadata addresses refused, redirects not followed). A triage profile is a stored +// base_url: without the guard, pointing it at an internal host makes the server dial +// that host on every report_finding. A refused base_url returns nil and triage stays +// off — the same fail-open path as every other triage failure. +func (s *Server) triageHTTPClient(baseURL string) *http.Client { + g := newModelURLGuard(s) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := g.validateURL(ctx, baseURL, "triage"); err != nil { + log.Printf("[triage] base_url refused (%v); dedup stays off", err) + return nil + } + var tr *http.Transport + if base, ok := http.DefaultTransport.(*http.Transport); ok { + tr = base.Clone() + } else { + tr = &http.Transport{} + } + tr.Proxy = nil // a proxy fetches the target itself and would bypass the dial guard + tr.DialContext = (&net.Dialer{Timeout: 10 * time.Second, Control: g.blockDial}).DialContext + return &http.Client{ + Transport: tr, + Timeout: agent.TriageHTTPTimeout, + CheckRedirect: func(*http.Request, []*http.Request) error { + return fmt.Errorf("triage: redirects are not followed") + }, + } +} + +// applyTriageThreshold pushes the stored threshold into the agent package. Called on +// boot and on a settings change; an unreadable or out-of-range value keeps the current +// threshold. 0 is in range and means "back to the default" (SetTriageMinConfidence). +func (s *Server) applyTriageThreshold() { + if s.m.pg == nil { + return + } + raw, ok, err := s.m.pg.GetSetting(settingTriageMinConfidence) + if err != nil || !ok { + return + } + if v, err := strconv.ParseFloat(strings.TrimSpace(raw), 64); err == nil && v >= 0 && v <= 1 { + agent.SetTriageMinConfidence(v) + } +} + +// triageMinConfidence reports the stored threshold for the settings API (0 = default). +func (s *Server) triageMinConfidence() float64 { + if s.m.pg == nil { + return 0 + } + raw, ok, err := s.m.pg.GetSetting(settingTriageMinConfidence) + if err != nil || !ok { + return 0 + } + v, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil { + return 0 + } + return v +} + +// triageProfileID returns the configured triage profile id, 0 when off or unreadable. +func (s *Server) triageProfileID() int64 { + if s.m.pg == nil { + return 0 + } + raw, ok, err := s.m.pg.GetSetting(settingTriageProfile) + if err != nil || !ok { + return 0 + } + id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) + if err != nil || id < 0 { + return 0 + } + return id +} diff --git a/server/triage_review_test.go b/server/triage_review_test.go new file mode 100644 index 000000000..05a0d267f --- /dev/null +++ b/server/triage_review_test.go @@ -0,0 +1,114 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +// A triage profile is a stored base_url, so the decision endpoint has to pass the +// same guard the model-list path uses: without it, pointing the profile at an +// internal host makes the server dial that host on every report_finding. +func TestTriageHTTPClientGuard(t *testing.T) { + s := &Server{} + t.Setenv(LLMPrivateEndpointsEnv, "") + if c := s.triageHTTPClient("http://127.0.0.1:8099/v1"); c != nil { + t.Fatal("private triage endpoint was accepted without an allow-list entry") + } + if c := s.triageHTTPClient("http://169.254.169.254/latest"); c != nil { + t.Fatal("metadata address was accepted as a triage endpoint") + } + t.Setenv(LLMPrivateEndpointsEnv, "127.0.0.1:8099") + if c := s.triageHTTPClient("http://127.0.0.1:8099/v1"); c == nil { + t.Fatal("allow-listed private triage endpoint was refused") + } +} + +// A stored profile id that matches nothing resolves to "off" at run time, which +// reads as a broken dedup instead of a rejected setting; out-of-range thresholds +// are silently ignored by the agent. Both are rejected at save time now. +func TestTriageSettingsValidation(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + defer m.Close() + clear := func() { + for _, k := range []string{settingTriageProfile, settingTriageMinConfidence} { + if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, k); err != nil { + t.Error(err) + } + } + } + clear() + defer clear() + + pid, err := m.pg.SaveProfile(&db.LLMProfile{Name: "triage-test", Format: "openai", + BaseURL: "http://127.0.0.1:8099/v1", Model: "pplx-decider", APIKey: "sk-test"}) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + defer stopTestServer(t, s, cancel) + token, err := signJWT(s.jwtKey) + if err != nil { + t.Fatal(err) + } + do := func(body string) int { + t.Helper() + req := httptest.NewRequest(http.MethodPut, "/api/settings", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + return rec.Code + } + + for _, bad := range []string{ + `{"triage_profile_id":-5}`, + `{"triage_profile_id":999888777}`, + `{"triage_min_confidence":-0.2}`, + `{"triage_min_confidence":1.7}`, + } { + if code := do(bad); code != 400 { + t.Errorf("PUT %s: %d, want 400", bad, code) + } + } + if v, ok, _ := m.pg.GetSetting(settingTriageProfile); ok { + t.Fatalf("rejected PUT stored triage_profile_id=%q", v) + } + + good := `{"triage_profile_id":` + strconv.FormatInt(pid, 10) + `,"triage_min_confidence":0.45}` + if code := do(good); code != 200 { + t.Fatalf("PUT %s: %d, want 200", good, code) + } + if v, _, _ := m.pg.GetSetting(settingTriageProfile); v != strconv.FormatInt(pid, 10) { + t.Fatalf("stored triage_profile_id = %q, want %d", v, pid) + } + if v, _, _ := m.pg.GetSetting(settingTriageMinConfidence); v != "0.450" { + t.Fatalf("stored triage_min_confidence = %q, want 0.450", v) + } + // 0 is the documented way to turn the check off and must stay accepted. + if code := do(`{"triage_profile_id":0}`); code != 200 { + t.Fatalf("PUT triage_profile_id=0: %d, want 200", code) + } + var got map[string]any + req := httptest.NewRequest(http.MethodGet, "/api/settings", nil) + req.Header.Set("Authorization", "Bearer "+token) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if v, _ := got["triage_profile_id"].(float64); int64(v) != 0 { + t.Fatalf("GET settings triage_profile_id = %v, want 0", got["triage_profile_id"]) + } +}