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(eval): run the real agent against a local model, and score groundedness (#657)

Beenu Arora9c8b1d3acf1c
diff --git a/.github/workflows/live-agent-eval.yml b/.github/workflows/live-agent-eval.yml
new file mode 100644
index 000000000..01e9fc06b
--- /dev/null
+++ b/.github/workflows/live-agent-eval.yml
@@ -0,0 +1,154 @@
+name: Live agent eval (local model)
+
+# The project's own REALITY_REPORT names this as "the hard ceiling on the
+# project's credibility": no gated suite runs the live agent. `mitre_accuracy`
+# is an offline keyword extractor, and the one job that does dispatch the real
+# LangGraph — wet-eval.yml — no-ops without a funded provider key, so forks and
+# most PRs have never measured agent accuracy at all.
+#
+# A local model removes the funding dependency. Ollama serves an
+# OpenAI-compatible endpoint, `services/agents/app/llm/factory.py` already
+# honours OPENAI_BASE_URL, so the real agent can be dispatched on a runner with
+# no secret of any kind.
+#
+# Two deliberate constraints:
+#
+# * `--wet-limit` — a CPU-hosted model cannot chew through all 200 incidents
+# in a CI budget. The slice is a deterministic prefix so runs stay
+# comparable, and the report records how many were dispatched.
+# * `--wet-require-live` — without it the harness degrades to substrate
+# numbers on any failure, which would publish deterministic estimates as
+# live-agent performance. A gate that can pass without calling the model is
+# worse than no gate.
+#
+# Not a PR gate yet, on purpose. It follows the observe-then-ratchet convention
+# already used by security.yml: prove the job is stable and establish a floor
+# from real runs first, then promote it to `pull_request` and make the
+# threshold blocking. Promoting it before the floor is grounded in measurements
+# would just be inventing a number.
+
+on:
+ workflow_dispatch:
+ inputs:
+ model:
+ description: 'Ollama model tag'
+ type: string
+ default: 'qwen2.5:0.5b'
+ incidents:
+ description: 'How many incidents to dispatch'
+ type: string
+ default: '20'
+ schedule:
+ - cron: '0 3 * * 2'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: live-agent-eval-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ live-agent:
+ name: Dispatch the real agent against a local model
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ env:
+ OLLAMA_MODEL: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}
+ INCIDENT_LIMIT: ${{ github.event.inputs.incidents || '20' }}
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.11'
+
+ # The full agent dependency set, not the trimmed list ci.yml uses for
+ # unit tests: this job needs `app.investigator` to actually import, and
+ # the harness treats an ImportError as a degraded run.
+ - name: Install agent dependencies
+ working-directory: services/agents
+ run: |
+ set -euo pipefail
+ python -m pip install --quiet --upgrade pip poetry
+ poetry config virtualenvs.create false
+ poetry install --no-root --no-interaction
+
+ - name: Install Ollama
+ run: |
+ set -euo pipefail
+ curl -fsSL https://ollama.com/install.sh | sh
+ ollama --version
+
+ - name: Serve the model
+ run: |
+ set -euo pipefail
+ nohup ollama serve > "$RUNNER_TEMP/ollama.log" 2>&1 &
+ for i in $(seq 1 30); do
+ if curl -sf http://127.0.0.1:11434/api/tags >/dev/null; then
+ echo "ollama up after ${i}s"; break
+ fi
+ sleep 1
+ done
+ curl -sf http://127.0.0.1:11434/api/tags >/dev/null || {
+ echo "::error title=live-agent-eval::Ollama never became ready."
+ tail -50 "$RUNNER_TEMP/ollama.log"
+ exit 1
+ }
+ ollama pull "$OLLAMA_MODEL"
+
+ - name: Dispatch the agent
+ env:
+ # The harness reads its key from this dedicated slot; the value is
+ # irrelevant to Ollama but the SDK requires one to be present.
+ WET_EVAL_OPENAI_KEY: ollama
+ OPENAI_API_KEY: ollama
+ OPENAI_BASE_URL: http://127.0.0.1:11434/v1
+ AISOC_LLM_MODEL: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}
+ run: |
+ set -euo pipefail
+ python3 scripts/run_evals.py \
+ --wet \
+ --wet-require-live \
+ --wet-limit "$INCIDENT_LIMIT" \
+ --out live-agent-eval.json \
+ --wet-out live-agent-eval.wet.json
+
+ - name: Summarise
+ if: always()
+ run: |
+ set -uo pipefail
+ if [ ! -f live-agent-eval.wet.json ]; then
+ echo "No report produced — see the dispatch step." >> "$GITHUB_STEP_SUMMARY"
+ exit 0
+ fi
+ python3 - <<'PY' >> "$GITHUB_STEP_SUMMARY"
+ import json
+ block = json.load(open("live-agent-eval.wet.json"))
+ print("## Live agent eval (local model)\n")
+ print(f"- mode: `{block.get('mode')}`")
+ print(f"- model: `{block.get('model')}`")
+ agg = block.get("aggregate", {})
+ lat = agg.get("latency_ms", {})
+ print(f"- incidents dispatched: {block.get('incident_count', 'unknown')}")
+ if lat:
+ print(f"- latency p50/p95 ms: {lat.get('p50')} / {lat.get('p95')}")
+ for w in block.get("warnings", []):
+ print(f"- warning: {w}")
+ PY
+
+ - name: Upload report
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ name: live-agent-eval-${{ github.run_id }}
+ path: |
+ live-agent-eval.json
+ live-agent-eval.wet.json
+ if-no-files-found: warn
+ retention-days: 30
+
+ - name: Ollama log on failure
+ if: failure()
+ run: tail -100 "$RUNNER_TEMP/ollama.log" || true
diff --git a/scripts/run_evals.py b/scripts/run_evals.py
old mode 100755
new mode 100644
index d53021c2d..e3808ae83
--- a/scripts/run_evals.py
+++ b/scripts/run_evals.py
@@ -854,6 +854,28 @@ def main() -> None:
"the substrate suites."
),
)
+ parser.add_argument(
+ "--wet-limit",
+ type=int,
+ default=None,
+ help=(
+ "Only meaningful with --wet. Dispatch at most N incidents instead "
+ "of the full 200. A CPU-hosted local model cannot finish the whole "
+ "corpus inside a CI budget; the slice is a deterministic prefix so "
+ "runs stay comparable, and the report records how many were used."
+ ),
+ )
+ parser.add_argument(
+ "--wet-require-live",
+ action="store_true",
+ help=(
+ "Only meaningful with --wet. Fail instead of degrading to dry-run "
+ "numbers when the live agent cannot be reached. Degrading is right "
+ "for a reporting job, but fatal for a gate: a degraded run would "
+ "publish substrate numbers as live-agent performance. Any job that "
+ "asserts on these numbers must pass this."
+ ),
+ )
args = parser.parse_args()
# Wet-eval mode short-circuits the substrate gates entirely (T5.5).
@@ -873,10 +895,21 @@ def main() -> None:
file=sys.stderr,
)
sys.exit(2)
- wet_report = compute_wet_eval(
- mode=wet_mode,
- harness_version=f"scripts/run_evals.py @ {os.environ.get('GITHUB_SHA', 'local')}",
- )
+ try:
+ wet_report = compute_wet_eval(
+ mode=wet_mode,
+ harness_version=(
+ f"scripts/run_evals.py @ {os.environ.get('GITHUB_SHA', 'local')}"
+ ),
+ limit=args.wet_limit,
+ require_live=args.wet_require_live,
+ )
+ except RuntimeError as exc:
+ # Only reachable under --wet-require-live. A caller that asked for
+ # live numbers and got a degraded run needs a non-zero exit, not a
+ # well-formed report full of substrate estimates.
+ print(f"[run_evals] live wet-eval required but unavailable: {exc}", file=sys.stderr)
+ sys.exit(3)
wet_block = wet_report.to_dict(include_records=False)
summary = {
"generated_at": datetime.now(UTC).isoformat(),
diff --git a/scripts/wet_eval.py b/scripts/wet_eval.py
index e55153948..d16d6fa1c 100644
--- a/scripts/wet_eval.py
+++ b/scripts/wet_eval.py
@@ -191,6 +191,12 @@ class WetEvalRecord:
latency_seconds: float
usd: float
mitre_correct: bool
+ # Fraction of the concrete indicators the agent asserted that actually
+ # appear in the evidence it was handed. Only meaningful on the live path —
+ # the dry-run path synthesises no agent text, so it stays None rather than
+ # reporting a flattering 1.0 for output that was never produced.
+ groundedness: float | None = None
+ hallucinated: list[str] = field(default_factory=list)
@property
def total_tokens(self) -> int:
@@ -258,10 +264,14 @@ def _live_records(
incidents_path: Path | str,
*,
model: str,
-) -> tuple[list[WetEvalRecord], list[str]]:
+ limit: int | None = None,
+) -> tuple[list[WetEvalRecord], list[str], bool]:
"""Dispatch the 200-incident set against the live agent.
- Returns ``(records, warnings)``. If the agent stack can't be imported
+ Returns ``(records, warnings, degraded)``, where ``degraded`` is True when
+ the records are substrate fallbacks rather than real agent output. A
+ warning alone is not degradation: a missing optional axis costs one metric,
+ not the run. If the agent stack can't be imported
(e.g. running on a bare-Python host) we fall back to the dry-run
records and append a clear warning so the workflow can mark the run
as degraded rather than silently emitting fake numbers.
@@ -274,6 +284,9 @@ def _live_records(
provider didn't surface usage.
"""
warnings: list[str] = []
+ # Resolved below alongside the agent. Kept as a name here so a missing
+ # groundedness module degrades that one axis to None rather than raising.
+ _score_groundedness = None
try:
# Imported lazily to keep the dry-run path stdlib-only.
from app.investigator import ( # type: ignore # noqa: F401
@@ -285,9 +298,26 @@ def _live_records(
f"{exc!r}. Falling back to dry-run shape; tag the report "
"consumer to render the warning."
)
- return _dry_run_records(incidents_path, model=model), warnings
+ return _dry_run_records(incidents_path, model=model), warnings, True
+
+ # Scored only on the live path, where there is real agent text to check
+ # against the evidence. Its absence costs one axis, not the run.
+ try:
+ from app.confidence.groundedness import ( # type: ignore
+ score_groundedness as _imported_score,
+ )
+
+ _score_groundedness = _imported_score
+ except Exception as exc: # pragma: no cover - degraded envs only.
+ warnings.append(f"Groundedness axis unavailable: {exc!r}")
incidents = json.loads(Path(incidents_path).read_text())
+ # A CPU-hosted local model cannot chew through all 200 incidents inside a
+ # CI budget. Taking a deterministic prefix keeps the slice comparable
+ # between runs; the slice size is reported so nobody mistakes a 20-incident
+ # sample for the full corpus.
+ if limit is not None and limit > 0:
+ incidents = incidents[:limit]
records: list[WetEvalRecord] = []
# Read the API key from the dedicated wet-eval slot rather than
@@ -301,7 +331,7 @@ def _live_records(
"skipped this run; falling back to dry-run shape so the "
"workflow doesn't emit fabricated numbers."
)
- return _dry_run_records(incidents_path, model=model), warnings
+ return _dry_run_records(incidents_path, model=model), warnings, True
# Best-effort: stash the key in OPENAI_API_KEY for the agent's
# default LLM resolver, but don't override it if something else
@@ -338,12 +368,33 @@ def _live_records(
expected = set(inc.get("expected_mitre_tactics") or [])
mitre_correct = bool(expected and (predicted & expected))
+ # Groundedness: did the agent assert any concrete indicator that the
+ # evidence never contained? This is the one axis that measures the live
+ # model rather than the substrate, and it is deterministic — no judge
+ # model, just regex indicator extraction on both sides.
+ grounded_score: float | None = None
+ hallucinated: list[str] = []
+ if _score_groundedness is not None:
+ evidence_text = " ".join(
+ [
+ str(inc.get("description") or ""),
+ str(inc.get("title") or ""),
+ " ".join(str(k) for k in (inc.get("evidence_keywords") or [])),
+ json.dumps(inc.get("telemetry") or []),
+ ]
+ )
+ scored = _score_groundedness(str(result), evidence_text)
+ grounded_score = scored.score
+ hallucinated = list(scored.hallucinated)
+
records.append(
WetEvalRecord(
incident_id=str(inc.get("id") or ""),
template_id=str(inc.get("template_id") or ""),
family=family_for_template(str(inc.get("template_id") or "")),
severity=str(inc.get("severity") or "medium").lower(),
+ groundedness=grounded_score,
+ hallucinated=hallucinated,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
latency_seconds=round(latency_s, 4),
@@ -353,7 +404,7 @@ def _live_records(
mitre_correct=mitre_correct,
)
)
- return records, warnings
+ return records, warnings, False
# ---------------------------------------------------------------------------
@@ -556,24 +607,49 @@ def compute_wet_eval(
model: str = DEFAULT_MODEL,
rate_card: dict[str, dict[str, float]] | None = None,
harness_version: str = "",
+ limit: int | None = None,
+ require_live: bool = False,
) -> WetEvalReport:
"""Top-level entry point. Returns a populated ``WetEvalReport``.
``mode`` must be either ``"dry_run"`` (no live calls, deterministic
shape from substrate) or ``"live"`` (real LangGraph agent + LLM).
+
+ ``limit`` caps how many incidents the live path dispatches, so a
+ CPU-hosted local model can finish inside a CI budget.
+
+ ``require_live`` turns the degrade-to-dry-run behaviour into a hard
+ error. Degrading is right for a reporting job — better a labelled
+ estimate than a crash — but fatal for a *gate*: a run that silently
+ substitutes substrate numbers would report a healthy live agent while
+ never having called one. Anything asserting on these numbers must pass
+ ``require_live=True``.
"""
if mode not in {"dry_run", "live"}:
raise ValueError(f"mode must be 'dry_run' or 'live', got {mode!r}")
if mode == "dry_run":
+ if require_live:
+ raise RuntimeError("require_live=True is incompatible with mode='dry_run'")
records = _dry_run_records(incidents_path, model=model)
warnings: list[str] = []
else:
- records, warnings = _live_records(incidents_path, model=model)
+ records, warnings, degraded = _live_records(
+ incidents_path, model=model, limit=limit
+ )
+ if require_live and degraded:
+ raise RuntimeError(
+ "require_live=True but the live path fell back to substrate "
+ "numbers:\n - " + "\n - ".join(warnings)
+ )
# Degrade-cleanly: if the live path could not produce records
# we re-tag the report as ``dry_run`` so consumers don't think
# they're looking at real numbers.
if not records:
+ if require_live:
+ raise RuntimeError(
+ "require_live=True but the live agent produced zero records."
+ )
warnings.append(
"Live agent path produced zero records. Re-tagging as "
"dry_run with synthesised shape to keep the report well-"