Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(agents): stop auto-closing alerts on reasoning the evidence contradicts (#666)

Beenu Arora65c4c5925ce7
diff --git a/services/agents/app/models/state.py b/services/agents/app/models/state.py
index da6380a2e..e165c302a 100644
--- a/services/agents/app/models/state.py
+++ b/services/agents/app/models/state.py
@@ -84,6 +84,12 @@ class InvestigationState(BaseModel):
confidence_basis: list[str] = Field(default_factory=list)
verdict: str | None = None
+ # Fraction of the concrete indicators cited in the reasoning that actually
+ # appear in the evidence (see app/confidence/groundedness.py). None means
+ # the verdict was not scored. Recorded alongside the verdict so an
+ # ungrounded auto-closure is visible after the fact, not just at the time.
+ groundedness: float | None = None
+
# Metadata
iteration_count: int = 0
max_iterations: int = 10
diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.py
index 3e7110c4e..4d7224131 100644
--- a/services/agents/app/workers/fused_alert_consumer.py
+++ b/services/agents/app/workers/fused_alert_consumer.py
@@ -42,8 +42,9 @@ from typing import Any
import structlog
from app.agents.auto_triage_agent import run_auto_triage
-from app.agents.dispositions import NEEDS_REVIEW, normalize_disposition
+from app.agents.dispositions import AUTO_CLOSEABLE_DISPOSITIONS, NEEDS_REVIEW, normalize_disposition
from app.agents.triage_agent import run_triage
+from app.confidence.groundedness import score_groundedness
from app.core.cost_governor import Decision, get_governor
from app.core.cost_telemetry import CostTracker
from app.graph.runner import default_budget, run_escalation
@@ -80,6 +81,7 @@ _METRICS = {
"escalated": 0,
"outcome_written": 0,
"outcome_suppressed": 0,
+ "ungrounded_demoted": 0,
"persist_retries": 0,
"dead_lettered": 0,
"errors": 0,
@@ -109,6 +111,22 @@ def _memory_writeback_enabled() -> bool:
return _truthy("AISOC_AGENT_MEMORY_WRITEBACK")
+def _groundedness_gate_enabled() -> bool:
+ """Demote a verdict whose reasoning cites indicators the evidence lacks.
+
+ On by default; disable with AISOC_AGENT_GROUNDEDNESS_GATE=0.
+ """
+ return _truthy("AISOC_AGENT_GROUNDEDNESS_GATE")
+
+
+def _groundedness_floor() -> float:
+ """Minimum grounded fraction for a verdict to be trusted to auto-close."""
+ try:
+ return float(os.getenv("AISOC_AGENT_GROUNDEDNESS_FLOOR", "0.75"))
+ except ValueError:
+ return 0.75
+
+
def _coerce_uuid(value: Any, *, fallback: str) -> uuid.UUID:
try:
return uuid.UUID(str(value))
@@ -415,6 +433,13 @@ class FusedAlertTriageWorker:
except Exception as exc: # noqa: BLE001 — governance accounting is best-effort
logger.debug("auto_triage_worker.governor_record_failed", error=str(exc))
+ # Groundedness gate: does the verdict's reasoning cite indicators the
+ # evidence actually contained? `score_groundedness` existed as an eval
+ # axis with no caller in the service, so a confident verdict citing an
+ # IP or hash that appeared nowhere in the alert was persisted, acted on
+ # and auto-closed with no signal that it was invented.
+ verdict, confidence = self._apply_groundedness_gate(state, verdict, confidence)
+
_METRICS["triaged"] += 1
await self._record(state, tier=tier, verdict=verdict, confidence=confidence, tokens=tokens, cost_usd=cost_usd)
@@ -564,6 +589,64 @@ class FusedAlertTriageWorker:
_METRICS["deterministic"] += 1
return state, "deterministic"
+ def _apply_groundedness_gate(
+ self,
+ state: InvestigationState,
+ verdict: Any,
+ confidence: float,
+ ) -> tuple[Any, float]:
+ """Refuse to auto-close on reasoning the evidence does not support.
+
+ `score_groundedness` measures what fraction of the concrete indicators
+ an output asserts — IPs, hashes, CVEs, MITRE techniques, domains —
+ actually appear in the evidence the agent was given. It shipped as an
+ eval axis and had no caller in the service, so a confident verdict
+ citing an IP that appeared nowhere in the alert was persisted, acted on
+ and auto-closed with nothing recording that it was invented.
+
+ Only auto-closing verdicts are gated. Demoting an escalation because
+ its prose mentioned an extra indicator would add review load without
+ reducing risk, and a verdict that already routes to a human is not
+ making an unsupervised decision.
+ """
+ if not _groundedness_gate_enabled() or not verdict:
+ return verdict, confidence
+ if normalize_disposition(str(verdict), default=NEEDS_REVIEW) not in AUTO_CLOSEABLE_DISPOSITIONS:
+ return verdict, confidence
+
+ reasoning = " ".join(str(part) for part in [*(state.findings or []), *(state.confidence_basis or [])])
+ if not reasoning.strip():
+ return verdict, confidence
+
+ try:
+ evidence = json.dumps(state.raw_alert or {}, default=str)
+ result = score_groundedness(reasoning, f"{evidence}\n{state.alert_summary or ''}")
+ except Exception as exc: # noqa: BLE001 — a scoring failure must not change the verdict
+ logger.debug("auto_triage_worker.groundedness_failed", error=str(exc))
+ return verdict, confidence
+
+ state.groundedness = result.score
+ if result.score >= _groundedness_floor():
+ return verdict, confidence
+
+ _METRICS["ungrounded_demoted"] += 1
+ logger.warning(
+ "auto_triage_worker.ungrounded_verdict_demoted",
+ run_id=str(state.run_id),
+ original_verdict=str(verdict),
+ groundedness=result.score,
+ hallucinated=result.hallucinated[:10],
+ )
+ state.add_finding(
+ f"Verdict demoted to needs_review: only {result.score:.0%} of the indicators cited in "
+ f"the reasoning appear in the evidence (unsupported: {', '.join(result.hallucinated[:5])})."
+ )
+ if state.status is AgentStatus.COMPLETED:
+ state.status = AgentStatus.RUNNING
+ state.verdict = NEEDS_REVIEW
+ # Confidence describes the demoted verdict now, not the discarded one.
+ return NEEDS_REVIEW, min(float(confidence or 0.0), result.score)
+
async def _record(
self,
state: InvestigationState,
diff --git a/services/agents/tests/test_groundedness_gate.py b/services/agents/tests/test_groundedness_gate.py
new file mode 100644
index 000000000..4407e1bda
--- /dev/null
+++ b/services/agents/tests/test_groundedness_gate.py
@@ -0,0 +1,159 @@
+"""A verdict must not auto-close on reasoning the evidence does not support.
+
+`score_groundedness` measures what fraction of the concrete indicators an
+agent's output asserts — IPs, hashes, CVEs, MITRE techniques, domains — appear
+in the evidence it was given. It shipped as an eval axis and had no caller
+anywhere in the service.
+
+So a confident "false positive" whose reasoning cited an IP that appeared
+nowhere in the alert was persisted, written back as an institutional-memory
+prior, and auto-closed, with nothing recording that the reasoning was invented.
+That is the exact failure the honesty bar exists to prevent, and it was
+measured only against synthetic eval fixtures.
+
+These tests drive the gate through the triage worker, since the defect was
+that nothing called the scorer on a live verdict.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.models.state import AgentStatus, InvestigationState
+from app.workers.fused_alert_consumer import FusedAlertTriageWorker
+
+FALSE_POSITIVE = "false_positive"
+
+
[email protected](autouse=True)
+def _gate_on(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv("AISOC_AGENT_GROUNDEDNESS_GATE", raising=False)
+ monkeypatch.delenv("AISOC_AGENT_GROUNDEDNESS_FLOOR", raising=False)
+
+
+def _worker() -> FusedAlertTriageWorker:
+ return FusedAlertTriageWorker(bootstrap_servers="localhost:9092")
+
+
+def _state(findings: list[str], alert: dict | None = None) -> InvestigationState:
+ return InvestigationState(
+ run_id=uuid.uuid4(),
+ incident_id=uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ alert_summary="Outbound connection from WIN-DC01",
+ raw_alert=alert if alert is not None else {"hostname": "WIN-DC01", "src_ip": "10.0.0.5"},
+ findings=findings,
+ status=AgentStatus.COMPLETED,
+ )
+
+
+# ── the regression ────────────────────────────────────────────────────────
+
+
+def test_a_verdict_citing_an_ip_that_is_not_in_the_evidence_is_demoted():
+ """The case that was silently auto-closing.
+
+ The alert mentions 10.0.0.5. The reasoning confidently discusses
+ 203.0.113.77, which the agent was never given.
+ """
+ state = _state(["Traffic to 203.0.113.77 is a known benign CDN egress, closing."])
+ verdict, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.97)
+ assert verdict == "needs_review"
+ assert state.status is not AgentStatus.COMPLETED
+ assert state.groundedness is not None and state.groundedness < 0.75
+
+
+def test_a_grounded_verdict_is_left_alone():
+ state = _state(["Traffic from 10.0.0.5 matches the documented backup window."])
+ verdict, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.91)
+ assert verdict == FALSE_POSITIVE
+ assert confidence == 0.91
+ assert state.groundedness == 1.0
+
+
+def test_confidence_is_lowered_to_match_the_demoted_verdict():
+ """A 0.97 confidence must not survive onto a verdict we no longer trust."""
+ unseen_sha256 = "deadbeef" + "0" * 56 # 64 hex chars, absent from the alert
+ state = _state([f"Hash {unseen_sha256} is a known-good signed binary."])
+ _, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.97)
+ assert confidence < 0.97
+
+
+def test_the_demotion_is_explained_in_the_findings():
+ """An analyst reading the case must see why it was escalated."""
+ state = _state(["Traffic to 203.0.113.77 is benign."])
+ _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.95)
+ assert any("demoted" in f.lower() for f in state.findings)
+ assert any("203.0.113.77" in f for f in state.findings)
+
+
+# ── scope ─────────────────────────────────────────────────────────────────
+
+
+def test_an_escalating_verdict_is_not_gated():
+ """A verdict already routed to a human is not making an unsupervised call.
+
+ Demoting it would add review load without reducing risk.
+ """
+ state = _state(["Traffic to 203.0.113.77 indicates C2."])
+ verdict, confidence = _worker()._apply_groundedness_gate(state, "true_positive", 0.88)
+ assert verdict == "true_positive"
+ assert confidence == 0.88
+
+
+def test_reasoning_with_no_concrete_indicators_is_not_penalised():
+ """Nothing checkable was asserted, so nothing can be hallucinated."""
+ state = _state(["Matches the tenant's documented maintenance window."])
+ verdict, _ = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.9)
+ assert verdict == FALSE_POSITIVE
+
+
+def test_empty_reasoning_is_not_gated():
+ state = _state([])
+ verdict, _ = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.9)
+ assert verdict == FALSE_POSITIVE
+
+
+def test_indicators_in_the_raw_event_payload_count_as_evidence():
+ """Evidence is the whole alert the agent saw, not just its top fields."""
+ state = _state(
+ ["Connection to 198.51.100.9 matches the documented proxy."],
+ alert={"hostname": "WIN-DC01", "raw_event": {"dest": "198.51.100.9"}},
+ )
+ verdict, _ = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.9)
+ assert verdict == FALSE_POSITIVE
+
+
+# ── controls ──────────────────────────────────────────────────────────────
+
+
+def test_the_gate_can_be_disabled(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("AISOC_AGENT_GROUNDEDNESS_GATE", "0")
+ state = _state(["Traffic to 203.0.113.77 is benign."])
+ verdict, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.95)
+ assert verdict == FALSE_POSITIVE
+ assert confidence == 0.95
+
+
+def test_the_floor_is_configurable(monkeypatch: pytest.MonkeyPatch):
+ """Half the indicators grounded passes a 0.4 floor and fails a 0.9 one."""
+ findings = ["Traffic from 10.0.0.5 to 203.0.113.77 reviewed."]
+ monkeypatch.setenv("AISOC_AGENT_GROUNDEDNESS_FLOOR", "0.4")
+ assert _worker()._apply_groundedness_gate(_state(findings), FALSE_POSITIVE, 0.9)[0] == FALSE_POSITIVE
+ monkeypatch.setenv("AISOC_AGENT_GROUNDEDNESS_FLOOR", "0.9")
+ assert _worker()._apply_groundedness_gate(_state(findings), FALSE_POSITIVE, 0.9)[0] == "needs_review"
+
+
+def test_a_scoring_failure_never_changes_the_verdict(monkeypatch: pytest.MonkeyPatch):
+ """The verdict is the product. A broken scorer must not rewrite it."""
+ import app.workers.fused_alert_consumer as mod
+
+ def _boom(*a, **k): # noqa: ANN002, ANN003
+ raise RuntimeError("scorer exploded")
+
+ monkeypatch.setattr(mod, "score_groundedness", _boom)
+ state = _state(["Traffic to 203.0.113.77 is benign."])
+ verdict, confidence = _worker()._apply_groundedness_gate(state, FALSE_POSITIVE, 0.95)
+ assert verdict == FALSE_POSITIVE
+ assert confidence == 0.95