mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-25 09:20:53 +08:00
agent: advisory duplicate check on report_finding via a decision model
Duplicates are the cheapest way to lose reviewer trust, and the only guard today is
a prompt instruction: the worker is told to check list_findings before registering.
It does not hold — in one run against a deliberately vulnerable app three defect
classes were registered twice each (two SQLi, two IDOR, two admin-endpoint
findings), and one of the pairs differed only in wording.
A decision model answers exactly this kind of closed-list question (same defect as
one of these N findings, or not?) with probabilities and no generated text, so the
judgement costs one small request instead of a main-model turn over a six-figure
context. Measured on our own findings before writing any of this (15 candidates,
hand labels): the correct partner 8/8 on a 27B decider 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. Repeated calls were stable (30/30 identical).
Changes
- agent/triage.go: TriageClient interface, a /v1/systemone HTTP client, and the pure
pieces (state builder, criteria builder, answer parser, threshold) so the logic is
testable without a server.
- report_finding: consults the client before registering. On a duplicate above the
confidence threshold the finding is not registered again; the caller is told which
finding_id it matched and to extend it with update_finding_report.
- Wiring: agent.SetTriageClient on the worker/planner ToolSets, a triage_profile_id
setting (any llm_profiles row whose base_url serves the decision contract; 0 = off),
exposed through the settings API.
Fail-open, by construction
Triage changes an outcome only when it is confident; every other path behaves exactly
as today: no client, no existing findings, empty summary, transport error, non-200,
malformed body, an id the question never offered, or confidence below the threshold
all fall through to normal registration. A wrong suppression loses evidence, a wrong
registration only costs a row — hence the threshold, and hence "advisory".
Verification
- go test ./agent/ passes, including new tests: request shape (model/state/criteria
carry every candidate), distinct answer, unknown id reads as distinct, probability
fallback when confidence is absent, error on 500, no HTTP call without input, state
cap, threshold boundaries.
- red/green on two independent breakages: forcing the threshold false and accepting
an unoffered id both fail the suite; restored, it passes.
- go test ./server/ shows one failure,
TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (bind 127.0.0.2 —
environment), reproduced on clean main in a separate worktree.
- gofmt -l agent/ server/ clean.
Notes
- The profile must serve /v1/systemone. A chat-only decider endpoint (one that refuses
/v1/chat/completions) needs a thin adapter; a decision endpoint works directly.
- Off by default: with no triage_profile_id the platform behaves as before.
The cap on offered findings is a SELECTION, not "the newest N": with a wide graph
the true partner falls out of a newest-first list, so candidates are ranked by
relevance (same class, overlapping endpoint, another task on a shared asset) with
recency only breaking ties. Per-entry summary capping replaces the whole-state
truncation, which used to cut mid-line and leave criteria ids whose state line had
been dropped.
Threshold is a knob, not a constant (live acceptance): on a run with the wider
cross-task pool the model named the right partner in 8 of 9 questions, but its
confidence moved with the question's width — 0.73-0.79 on a small pool, 0.30-0.53
with twenty candidates. Six duplicates were suppressed, and exactly the two that
slipped were the 0.30 and 0.47 ones, both with the correct partner named. A fixed
0.5 cannot fit both ends, so the threshold is a setting (triage_min_confidence,
default 0.5); the low end is affordable because the suppression result tells the
agent to re-register explicitly when the finding is in fact distinct.
Cross-task pool (found by re-measuring the live miss): task_relations only links
spawned tasks, so two tasks created independently against the same target never see
each other's findings and a defect registered in both is invisible to the dedup
question. FindingsSharingAssets joins on the candidate's own asset ids (jsonb
containment, GIN-served) and adds those findings to the question, marked with their
task. On three real cross-task duplicates the wider question names the right partner
in all three (confidence 0.58-0.73, above the threshold), where the own-task pool
could only answer "none".
Regression note (found on a live run, not in CI): FindingID is filled from the findings table, so building the candidate list straight from the nodes dropped every entry and triage never fired ("nodes=6, no usable existing findings"). Covered by TestTriageCandidates_SkipsNodesWithoutFindingRow; findings inherited from a directly related task are kept and marked in the question.
---
Found while running the platform against a live target.
limits: triageDupMinConfidence 0.5 - калибровка 538 пар одной цели (stage3_calibrate.py, 2026-11-22): recall 1.00 при FP 0.47 на 75 жёстких негативах; на истинных дублях в живом прогоне 0.30-0.79
limits: triageMaxExisting 10 - ширина вопроса на реальном дубле (stage3_width.py, 2026-11-22): уверенность 0.81-0.91 до 11 кандидатов, 0.64 на 19, 0.56 на 29; латентность 0.44->1.29 с
limits: triageMaxSummaryChars 400 - p90 длины сводки 334, максимум 564 по 53 находкам графа (2026-11-22)
limits: triageMaxStateChars 6000 - арифметика при потолке 10 записей: 10*(400+60)+480 ~= 5.1 КБ, запас 1.17x
limits: triageHTTPTimeout 20s - наблюдаемая латентность decider 0.26-1.29 с, 3.83-3.96 с на 27B; запас ~5x к худшему
limits: findings pool query limit 50 - самый широкий пул по ассету 31 находка (53 в графе, 2026-11-22), запас 1.6x
limits: ответ decider 1 MiB - наблюдаемый ответ 0.3-2 КБ, запас ~500x
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -139,6 +139,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.
|
||||
@@ -1566,6 +1570,24 @@ 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.
|
||||
if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
|
||||
res := map[string]any{
|
||||
"duplicate_of_finding_id": ans.DuplicateOf,
|
||||
"triage_confidence": ans.Confidence,
|
||||
"evidence_status": "duplicate_not_registered",
|
||||
"note": "Triage matched this finding to an already registered one, so no new finding was created. " +
|
||||
"If the new evidence adds detail, extend that finding with update_finding_report; if it is in fact a " +
|
||||
"distinct defect (different endpoint, parameter or root cause), register it again explicitly.",
|
||||
}
|
||||
raw, _ := json.Marshal(res)
|
||||
return actool.Text(fmt.Sprintf("finding matched to existing finding_id %d (triage confidence %.2f) — not registered again\n%s", ans.DuplicateOf, ans.Confidence, raw)), nil
|
||||
}
|
||||
var recorded *db.RecordedFinding
|
||||
if t.findingRecorder != nil {
|
||||
recorded, err = t.findingRecorder.Record(ctx, input, refs)
|
||||
|
||||
+437
@@ -0,0 +1,437 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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.
|
||||
var triageDupMinConfidence = 0.5
|
||||
|
||||
// SetTriageMinConfidence overrides the suppression threshold (<=0 keeps the default).
|
||||
func SetTriageMinConfidence(v float64) {
|
||||
if v > 0 {
|
||||
triageDupMinConfidence = v
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
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
|
||||
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, находка регистрируется как раньше.
|
||||
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 = 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 >= triageDupMinConfidence
|
||||
}
|
||||
|
||||
// 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 s[:n] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
log.Printf("[triage] answer: dup=%d conf=%.2f", ans.DuplicateOf, ans.Confidence)
|
||||
return ans, true
|
||||
}
|
||||
|
||||
// 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,
|
||||
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 ""
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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(0.5) // restore the default for other tests
|
||||
SetTriageMinConfidence(0.5)
|
||||
cases := []struct {
|
||||
in DuplicateAnswer
|
||||
want bool
|
||||
}{
|
||||
{DuplicateAnswer{DuplicateOf: 5, Confidence: 0.9}, true},
|
||||
{DuplicateAnswer{DuplicateOf: 5, Confidence: triageDupMinConfidence}, 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")
|
||||
}
|
||||
}
|
||||
+15
-11
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -3897,6 +3897,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,
|
||||
@@ -3998,6 +4000,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
|
||||
@@ -4044,6 +4054,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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"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 <base_url>/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
|
||||
}
|
||||
return &agent.SystemOneClient{BaseURL: p.BaseURL, APIKey: p.APIKey, Model: p.Model}
|
||||
}
|
||||
|
||||
// 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 default.
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user