ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
fix(agent,db): counter for intents that proved facts and registered no finding
Николай Гусев8e1c88e803f8
diff --git a/agent/fact_only_block_test.go b/agent/fact_only_block_test.gonew file mode 100644index 0000000..297bfb5--- /dev/null+++ b/agent/fact_only_block_test.go@@ -0,0 +1,25 @@+package agent++import (+ "strings"+ "testing"+)++// Блок «доказал — не зарегистрировал» обязан попадать в ситуационный блок планировщика:+// без него счётчик есть, а планировщик его не видит. Второй случай — тесты и вызовы без+// factOnly (nil) не должны падать и не должны печатать блок.+func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) {+ with := plannerSituational(nil, triggerLookup{+ factOnly: func() string {+ return "\n\n[Proved but not registered: 2 finished intent(s) produced facts and NO finding.]\n"+ },+ }, nil, newDataEnvelope())+ if !strings.Contains(with, "Proved but not registered") {+ t.Fatalf("situational block lost the fact-only nudge:\n%s", with)+ }++ without := plannerSituational(nil, triggerLookup{}, nil, newDataEnvelope())+ if strings.Contains(without, "Proved but not registered") {+ t.Fatalf("empty lookup should not print the block:\n%s", without)+ }+}diff --git a/agent/planner.go b/agent/planner.goindex 708756b..99ed172 100644--- a/agent/planner.go+++ b/agent/planner.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "strconv""strings""sync"@@ -395,6 +396,9 @@ type triggerLookup struct {intentSummary func(int64) stringworkerOutput func(int64) stringfactIDs func(int64) string+ // factOnly renders the «proved but not registered» block: intents that produced+ // facts and no finding. Nil in tests that do not care about it.+ factOnly func() string}func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {@@ -402,13 +406,46 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {intentSummary: func(id int64) string { return intentSummary(ts, id) },workerOutput: func(id int64) string { return workerOutput(ts, id) },factIDs: func(id int64) string { return factIDsYielded(ts, id) },+ factOnly: func() string { return factOnlyBlock(ts) },}}+// factOnlyBlock names the intents whose work proved something and registered no+// finding — the defect the run record shows plainly (three runs in twelve had every+// fact-producing intent register nothing). A fact carries no "this is a defect"+// flag, so the planner is the only place that can turn one into a finding; without+// the counter it has to notice by reading every fact again.+func factOnlyBlock(ts *db.ExplorationStore) string {+ if ts == nil {+ return ""+ }+ rows, err := ts.FactOnlyIntents(0)+ if err != nil || len(rows) == 0 {+ return ""+ }+ var b strings.Builder+ b.WriteString("\n\n[Proved but not registered: ")+ b.WriteString(strconv.Itoa(len(rows)))+ b.WriteString(" finished intent(s) produced facts and NO finding. For each, decide explicitly: " ++ "either register the defect as a finding (report_finding, with the executed request as evidence) " ++ "or state why the fact is not a defect. Facts carry no defect flag — only you can turn one into a finding.]\n")+ for _, r := range rows {+ // 140: сводка интента — одно предложение; 140 символов хватает, чтобы отличить+ // направления друг от друга (полный текст в одной node_detail). Обрезка общая+ // с триггерами, чтобы блок не стал вторым источником контекста.+ b.WriteString(fmt.Sprintf(" #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140)))+ }+ return b.String()+}+// plannerSituational is the planner's situational block for one round: the// envelope intro, the triggers, then the overview, all framed with env.func plannerSituational(evs []TriggerEvent, look triggerLookup, data map[string]any, env dataEnvelope) string {- return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env)+ block := ""+ if look.factOnly != nil {+ block = look.factOnly()+ }+ return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block}// plannerDefaultTmpl is the built-in EDITABLE body (section [A]) of the plannerdiff --git a/db/exploration.go b/db/exploration.goindex aa63910..662c83d 100644--- a/db/exploration.go+++ b/db/exploration.go@@ -1211,6 +1211,59 @@ WHERE e.exploration_id=$1 AND e.rel=$2 AND n.kind='finding'`, s.expID, RelYieldsreturn out, rows.Err()}+// FactOnlyIntent is one intent that yielded facts and no finding — the measurable+// form of «proved but not registered».+type FactOnlyIntent struct {+ IntentID int64+ Summary string+ Facts int+}++// FactOnlyIntents returns the intents of this exploration that yielded at least one+// fact node and zero finding nodes, newest first, capped at limit.+//+// Why it exists: on the run record, three runs out of twelve had EVERY+// fact-producing intent register nothing (3/3, 3/3, 2/2 — llm/agent logs of the+// 2026-11-22 stand). Facts were proven, findings never reached the registry, and+// nothing in the graph connected the two, so the planner could not notice.+// The counter is deliberately about the intent, not the fact: a fact carries no+// "this is a defect" flag, while an intent that produced facts has finished work+// whose result the planner can judge.+//+// limit<=0 falls back to 10: a planner round acts on a handful, and the whole+// point is a nudge, not an inventory.+func (s *ExplorationStore) FactOnlyIntents(limit int) ([]FactOnlyIntent, error) {+ if limit <= 0 {+ limit = 10+ }+ rows, err := s.db.Query(`SELECT i.id, COALESCE(i.payload->>'summary',''), count(*)+FROM exploration_edges e+JOIN exploration_nodes i ON i.id=e.src_id AND i.exploration_id=e.exploration_id+JOIN exploration_nodes d ON d.id=e.dst_id AND d.exploration_id=e.exploration_id+WHERE e.exploration_id=$1 AND e.rel=$2 AND d.kind=$3+ AND NOT EXISTS (+ SELECT 1 FROM exploration_edges e2+ JOIN exploration_nodes f ON f.id=e2.dst_id AND f.exploration_id=e2.exploration_id+ WHERE e2.exploration_id=e.exploration_id AND e2.src_id=e.src_id+ AND e2.rel=$2 AND f.kind='finding')+GROUP BY i.id, 2+ORDER BY i.id DESC+LIMIT $4`, s.expID, RelYields, KindFact, limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []FactOnlyIntent+ for rows.Next() {+ var r FactOnlyIntent+ if err := rows.Scan(&r.IntentID, &r.Summary, &r.Facts); err != nil {+ return nil, err+ }+ out = append(out, r)+ }+ return out, rows.Err()+}+// FindingIntentsTerminal is the inherited-history variant: it returns finding// lineage only when the producing intent has reached an immutable terminal// state. This keeps a source task's live worker topology private.diff --git a/db/fact_only_intents_test.go b/db/fact_only_intents_test.gonew file mode 100644index 0000000..c0c6552--- /dev/null+++ b/db/fact_only_intents_test.go@@ -0,0 +1,83 @@+package db++import "testing"++// «Доказал — не зарегистрировал» в измеримой форме: интент, который дал факты и не+// дал ни одной находки. Тест держит оба случая сразу, иначе гейт зелёный на пустом+// множестве: интент А (факт, находки нет) должен попасть, интент Б (факт + находка) — нет.+func TestFactOnlyIntents(t *testing.T) {+ d, err := Open(testDSN(t))+ if err != nil {+ SkipPGUnavailable(t, err)+ }+ t.Cleanup(func() { d.Close() })++ expID, err := d.CreateExploration("fact only intents", "fact only intents")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) })+ store := d.Exploration(expID)++ // А: факт есть, находки нет — «доказал, не зарегистрировал».+ intentA, err := store.AddIntent(map[string]any{"summary": "proved X, never registered"}, 1, nil, "planner")+ if err != nil {+ t.Fatal(err)+ }+ factA, err := store.AddNode(KindFact, map[string]any{"summary": "X is injectable"}, 1, "confirmed", "worker", nil)+ if err != nil {+ t.Fatal(err)+ }+ if err := store.Link(intentA, RelYields, factA); err != nil {+ t.Fatal(err)+ }++ // Б: факт и находка — не должен попасть.+ intentB, err := store.AddIntent(map[string]any{"summary": "proved Y and registered"}, 1, nil, "planner")+ if err != nil {+ t.Fatal(err)+ }+ factB, err := store.AddNode(KindFact, map[string]any{"summary": "Y is injectable"}, 1, "confirmed", "worker", nil)+ if err != nil {+ t.Fatal(err)+ }+ findingB, err := store.AddNode(KindFinding, map[string]any{"summary": "Y finding"}, 1, "confirmed", "worker", nil)+ if err != nil {+ t.Fatal(err)+ }+ if err := store.Link(intentB, RelYields, factB); err != nil {+ t.Fatal(err)+ }+ if err := store.Link(intentB, RelYields, findingB); err != nil {+ t.Fatal(err)+ }++ // В: интент вообще без фактов — тоже не должен попасть.+ intentC, err := store.AddIntent(map[string]any{"summary": "nothing yet"}, 1, nil, "planner")+ if err != nil {+ t.Fatal(err)+ }+ _ = intentC++ got, err := store.FactOnlyIntents(10)+ if err != nil {+ t.Fatal(err)+ }+ if len(got) != 1 {+ t.Fatalf("FactOnlyIntents returned %d intents, want 1 (only the fact-without-finding one): %+v", len(got), got)+ }+ if got[0].IntentID != intentA {+ t.Fatalf("FactOnlyIntents picked intent %d, want %d", got[0].IntentID, intentA)+ }+ if got[0].Facts != 1 {+ t.Fatalf("FactOnlyIntents facts = %d, want 1", got[0].Facts)+ }+ if got[0].Summary == "" {+ t.Fatal("FactOnlyIntents lost the intent summary — the planner cannot act on an id alone")+ }++ // Порог по умолчанию: limit<=0 не должен возвращать пусто.+ if many, err := store.FactOnlyIntents(0); err != nil || len(many) != 1 {+ t.Fatalf("FactOnlyIntents(0) = (%d, %v), want 1 row via the default cap", len(many), err)+ }+}