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): finish the fact-only counter
BaaRaideba1d1c7a11
diff --git a/agent/fact_only_block_test.go b/agent/fact_only_block_test.goindex 297bfb5..101f547 100644--- a/agent/fact_only_block_test.go+++ b/agent/fact_only_block_test.go@@ -5,12 +5,12 @@ import ("testing")-// Блок «доказал — не зарегистрировал» обязан попадать в ситуационный блок планировщика:-// без него счётчик есть, а планировщик его не видит. Второй случай — тесты и вызовы без-// factOnly (nil) не должны падать и не должны печатать блок.+// The «proved but not registered» block must reach the planner's situational block.+// Without it the counter exists and the planner never sees it. Calls without a+// lookup (nil factOnly) must not panic and must not print the block.func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) {with := plannerSituational(nil, triggerLookup{- factOnly: func() string {+ factOnly: func(dataEnvelope) string {return "\n\n[Proved but not registered: 2 finished intent(s) produced facts and NO finding.]\n"},}, nil, newDataEnvelope())@@ -23,3 +23,17 @@ func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) {t.Fatalf("empty lookup should not print the block:\n%s", without)}}++// The lookup receives the round's envelope, so the block can frame its data with it.+func TestFactOnlyLookupReceivesRoundEnvelope(t *testing.T) {+ env := newDataEnvelope()+ var got dataEnvelope+ look := triggerLookup{factOnly: func(e dataEnvelope) string {+ got = e+ return ""+ }}+ _ = plannerSituational(nil, look, nil, env)+ if got.nonce != env.nonce {+ t.Fatalf("lookup got nonce %q, want the round nonce %q", got.nonce, env.nonce)+ }+}diff --git a/agent/planner.go b/agent/planner.goindex 99ed172..5c6e4bf 100644--- a/agent/planner.go+++ b/agent/planner.go@@ -398,7 +398,7 @@ type triggerLookup struct {factIDs 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+ factOnly func(dataEnvelope) string}func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {@@ -406,7 +406,7 @@ 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) },+ factOnly: func(env dataEnvelope) string { return factOnlyBlock(ts, env) },}}@@ -415,7 +415,7 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {// 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 {+func factOnlyBlock(ts *db.ExplorationStore, env dataEnvelope) string {if ts == nil {return ""}@@ -424,17 +424,21 @@ func factOnlyBlock(ts *db.ExplorationStore) string {return ""}var b strings.Builder+ var list strings.Builderb.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)))- }+ // 140: one sentence of intent summary; 140 characters is enough to tell the+ // directions apart (the full text is in one node_detail). The cut is shared+ // with the triggers so the block does not become a second context source.+ fmt.Fprintf(&list, " #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140))+ }+ // The summaries come from agent output: they are data and go inside the envelope.+ b.WriteString(env.wrap("fact_only_intents", strings.TrimRight(list.String(), "\n")))+ b.WriteString("\n")return b.String()}@@ -443,7 +447,7 @@ func factOnlyBlock(ts *db.ExplorationStore) string {func plannerSituational(evs []TriggerEvent, look triggerLookup, data map[string]any, env dataEnvelope) string {block := ""if look.factOnly != nil {- block = look.factOnly()+ block = look.factOnly(env)}return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block}diff --git a/db/exploration.go b/db/exploration.goindex 662c83d..688f39f 100644--- a/db/exploration.go+++ b/db/exploration.go@@ -1241,6 +1241,7 @@ FROM exploration_edges eJOIN exploration_nodes i ON i.id=e.src_id AND i.exploration_id=e.exploration_idJOIN exploration_nodes d ON d.id=e.dst_id AND d.exploration_id=e.exploration_idWHERE e.exploration_id=$1 AND e.rel=$2 AND d.kind=$3+ AND i.state IN ('done','blocked','exhausted','stopped')AND NOT EXISTS (SELECT 1 FROM exploration_edges e2JOIN exploration_nodes f ON f.id=e2.dst_id AND f.exploration_id=e2.exploration_iddiff --git a/db/fact_only_intents_test.go b/db/fact_only_intents_test.goindex c0c6552..66f938f 100644--- a/db/fact_only_intents_test.go+++ b/db/fact_only_intents_test.go@@ -2,9 +2,10 @@ package dbimport "testing"-// «Доказал — не зарегистрировал» в измеримой форме: интент, который дал факты и не-// дал ни одной находки. Тест держит оба случая сразу, иначе гейт зелёный на пустом-// множестве: интент А (факт, находки нет) должен попасть, интент Б (факт + находка) — нет.+// "Proved but not registered", in measurable form: an intent that yielded facts and+// no finding. The test holds both cases at once, otherwise the gate is green on an+// empty set: intent A (fact, no finding) must be returned, intent B (fact + finding)+// must not.func TestFactOnlyIntents(t *testing.T) {d, err := Open(testDSN(t))if err != nil {@@ -19,11 +20,15 @@ func TestFactOnlyIntents(t *testing.T) {t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) })store := d.Exploration(expID)- // А: факт есть, находки нет — «доказал, не зарегистрировал».+ // A: fact present, no finding — "proved, not registered".intentA, err := store.AddIntent(map[string]any{"summary": "proved X, never registered"}, 1, nil, "planner")if err != nil {t.Fatal(err)}+ // Only finished intents count: the state filter keeps A (done) and drops open ones.+ if err := store.SetIntentState(intentA, "done"); 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)@@ -32,7 +37,7 @@ func TestFactOnlyIntents(t *testing.T) {t.Fatal(err)}- // Б: факт и находка — не должен попасть.+ // B: fact and finding — must not be returned.intentB, err := store.AddIntent(map[string]any{"summary": "proved Y and registered"}, 1, nil, "planner")if err != nil {t.Fatal(err)@@ -52,7 +57,7 @@ func TestFactOnlyIntents(t *testing.T) {t.Fatal(err)}- // В: интент вообще без фактов — тоже не должен попасть.+ // C: intent with no facts at all — must not be returned either.intentC, err := store.AddIntent(map[string]any{"summary": "nothing yet"}, 1, nil, "planner")if err != nil {t.Fatal(err)@@ -76,8 +81,60 @@ func TestFactOnlyIntents(t *testing.T) {t.Fatal("FactOnlyIntents lost the intent summary — the planner cannot act on an id alone")}- // Порог по умолчанию: limit<=0 не должен возвращать пусто.+ // Default cap: limit<=0 must not return nothing.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)}}++// Only finished intents (done, blocked, exhausted, stopped) count. An intent that is+// still open or running with a fact and no finding must not be reported as finished.+func TestFactOnlyIntentsStates(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 states", "fact only states")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) })+ store := d.Exploration(expID)++ states := []string{"open", "running", "done", "blocked", "exhausted", "stopped"}+ want := map[int64]bool{}+ for _, st := range states {+ id, err := store.AddIntent(map[string]any{"summary": "state " + st}, 1, nil, "planner")+ if err != nil {+ t.Fatal(err)+ }+ if err := store.SetIntentState(id, st); err != nil {+ t.Fatal(err)+ }+ fact, err := store.AddNode(KindFact, map[string]any{"summary": "fact for " + st}, 1, "confirmed", "worker", nil)+ if err != nil {+ t.Fatal(err)+ }+ if err := store.Link(id, RelYields, fact); err != nil {+ t.Fatal(err)+ }+ if st == "done" || st == "blocked" || st == "exhausted" || st == "stopped" {+ want[id] = true+ }+ }++ got, err := store.FactOnlyIntents(0)+ if err != nil {+ t.Fatal(err)+ }+ if len(got) != len(want) {+ t.Fatalf("FactOnlyIntents returned %d intents, want %d (terminal states only): %+v", len(got), len(want), got)+ }+ for _, g := range got {+ if !want[g.IntentID] {+ t.Fatalf("FactOnlyIntents returned intent %d in a non-terminal state", g.IntentID)+ }+ }+}diff --git a/db/llm_context.go b/db/llm_context.goindex ce4951d..7b1fede 100644--- a/db/llm_context.go+++ b/db/llm_context.go@@ -5,8 +5,9 @@ import ("strings")-// LLMContext is one opt-in context-size telemetry row written when-// ARTEX_CONTEXT_TELEMETRY=1. It records only byte sizes, counts, token usage,+// LLMContext is one context-size telemetry row, written on every model call while+// telemetry is on (the default; ARTEX_CONTEXT_TELEMETRY=0|false|off|no turns it off).+// It records only byte sizes, counts, token usage,// and call metadata — never any prompt, tool, or message content.type LLMContext struct {TaskID string `json:"task_id"`diff --git a/docs/context-telemetry.md b/docs/context-telemetry.mdindex 6d8f2e3..86974e5 100644--- a/docs/context-telemetry.md+++ b/docs/context-telemetry.md@@ -1,6 +1,6 @@# LLM Context Size Telemetry (P3.5 Phase A)-`ARTEX_CONTEXT_TELEMETRY=1` enables opt-in, size-only per-call telemetry for every `llmrec` `Stream` and `Complete` call. It is **disabled by default**: when off, no request sizing runs and no rows are written to PostgreSQL.+Size-only per-call telemetry runs for every `llmrec` `Stream` and `Complete` call. It is **on by default**; `ARTEX_CONTEXT_TELEMETRY=0|false|off|no` disables it explicitly, and then no request sizing runs and no rows are written to PostgreSQL.This phase measures context composition without changing any prompt, compaction policy, or model behavior, so Phases B (`ARTEX_BOUNDED_CONTEXT`) and C (`ARTEX_CACHE_PREFIX` / `ARTEX_COMPACTION_MEMO`) can be evaluated against real numbers first.@@ -10,13 +10,13 @@ This phase measures context composition without changing any prompt, compaction| Environment variable | Values | Default ||---|---|---|-| `ARTEX_CONTEXT_TELEMETRY` | `1`, `true`, `on`, `yes` (case-insensitive) | off |+| `ARTEX_CONTEXT_TELEMETRY` | `0`, `false`, `off`, `no` disable it (case-insensitive); anything else, or unset, keeps it on | on |-Telemetry runs independently of `llm_record` (`recordBodies`): enabling `ARTEX_CONTEXT_TELEMETRY=1` works even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata.+Telemetry runs independently of `llm_record` (`recordBodies`): it stays on even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata.### Stopping, retention, and write cost-When `ARTEX_CONTEXT_TELEMETRY=1` is active, each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Unset `ARTEX_CONTEXT_TELEMETRY` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically:+While telemetry is on (the default), each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Set `ARTEX_CONTEXT_TELEMETRY=0` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically:```sqlDELETE FROM llm_context WHERE ts < now() - interval '30 days';diff --git a/llmrec/context_telemetry.go b/llmrec/context_telemetry.goindex 1d067d0..edfc1ac 100644--- a/llmrec/context_telemetry.go+++ b/llmrec/context_telemetry.go@@ -12,12 +12,12 @@ import (// ContextTelemetryEnv switches per-call context size telemetry into llm_context.//-// ON by default. Замер: на стенде, где прошло 15 прогонов, таблица llm_context была-// ПУСТА (0 строк), потому что флаг выключен по умолчанию — то есть размер контекста-// воркера обсуждали по суммарным токенам задачи, а не по разбивке (2026-11-22).-// Стоимость: одна строка на вызов модели и подсчёт длин, содержимое не сохраняется-// (по логам стенда — до ~300 вызовов на прогон, то есть до ~300 строк).-// Выключение явное: ARTEX_CONTEXT_TELEMETRY=0|false|off|no.+// ON by default. Measurement: on the test bench, 15 runs left llm_context EMPTY+// (0 rows) because the flag was off by default, so the worker's context size was+// discussed from the task's total tokens, not from a breakdown (2026-11-22).+// Cost: one row per model call plus length counts; no content is stored (up to about+// 300 calls per run in the bench logs, so up to about 300 rows).+// Explicit off switch: ARTEX_CONTEXT_TELEMETRY=0|false|off|no.const ContextTelemetryEnv = "ARTEX_CONTEXT_TELEMETRY"// ContextTelemetryEnabled reports whether context telemetry is on. Default true;diff --git a/llmrec/llmrec.go b/llmrec/llmrec.goindex 8d15f8c..0eb75da 100644--- a/llmrec/llmrec.go+++ b/llmrec/llmrec.go@@ -211,7 +211,7 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S}// Lightweight metering row — always written.r.recordUsage(ctx, taskID, expID, worker, usage, int(time.Since(start).Milliseconds()), status)- // Opt-in context size telemetry — independent of recordBodies.+ // Context size telemetry (on by default) — independent of recordBodies.if collectContext {r.recordContext(taskID, worker, ctxMetrics, usage, status)}