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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(phase-B1): auto-triage every fused alert off the Kafka stream (copilot) (#451)
Beenu Arora3fcfb2662438
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 858f89af3..3841347a6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -317,7 +317,7 @@ jobs:# so both packages are required at import time, even though the# fusion-client test itself only calls into `app.tools.fusion`.run: |- pip install --quiet pytest pytest-asyncio respx langchain-core langchain-openai+ pip install --quiet pytest pytest-asyncio respx langchain-core langchain-openai langgraphcd services/agentspython3 -m pytest \tests/test_mitre_accuracy.py \@@ -332,6 +332,7 @@ jobs:tests/test_cost_governor.py \tests/test_model_router.py \tests/test_llm_ops.py \+ tests/test_fused_alert_worker.py \-v --tb=short# ──────────────────────────────────────────────diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 122816fac..b2046681d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Phase B1 — the agent now auto-triages every alert off the stream (copilot default).** The core autonomy gap: investigations were manual/API-only — nothing consumed `aisoc.alerts.fused`, so "an agent that triages every alert" wasn't true out of the box. New `services/agents/app/workers/fused_alert_consumer.py` (`FusedAlertTriageWorker`) subscribes to the fused-alert topic and auto-triages each alert. **Copilot / dry-run is the default**: triage is read-only — it classifies (verdict + calibrated confidence), records the reasoning to the Investigation Ledger (best-effort), and **never dispatches a response** (proposed actions carry `requires_approval=True`; `response_dispatched` is always `False`). Tier selection is cost- and determinism-aware: cost-governor `DEDUPLICATED` reuses the cached verdict (a flood of identical alerts costs one triage), `CIRCUIT_OPEN`/`AISOC_DETERMINISTIC`/no-LLM-key falls to deterministic heuristic triage (`run_triage` — the air-gapped/CI default), otherwise LLM auto-triage with a deterministic fallback on failure. Wired into the agents lifespan (off unless `KAFKA_BOOTSTRAP_SERVERS` is set) + compose (`depends_on: kafka`). 9 unit tests (`test_fused_alert_worker.py`, added to the CI agents gate; the job now also installs `langgraph`). Claim-to-gate matrix adds a GATED row "Agent auto-triages every alert" (20 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A4 — the behavioral (UEBA) model now feeds alert scoring in production (the three-model story is real).** `services/ueba` continuously scored every entity and emitted `ueba.anomalies`, but fusion never consumed them — so the Semantic-graph / Behavioral-UEBA / Knowledge-LLM story was only two models live. New `services/fusion/app/services/ueba_signal.py`: the fusion consumer subscribes to `ueba.anomalies` and caches the latest per-`(tenant, entity_type, entity_id)` anomaly in Redis with a TTL (behavioral signal is time-decaying); during `FusionEngine.process`, an alert looks up the highest anomaly across its own entities (username→user, hostname→device, src/dst IP→ip) and `apply_ueba_boost` raises the alert's confidence (risk-scaled, label recomputed) and anomaly score, recording an explainable `ueba_anomaly` factor. Fail-soft throughout (Redis miss/outage or malformed message ⇒ no boost, no raise). 10 fusion unit tests; full fusion suite 122 passed at 64% coverage. Claim-to-gate matrix adds a GATED row "Three-model AI: behavioral (UEBA) model feeds alert scoring" (19 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A3 — the default cold-boot stack is complete ("just works").** A plain `docker compose up` previously started the core services but left the connector runtime behind a `connectors` profile and graph-at-ingest OFF, so a fresh install wasn't the full spine. Now `docker-compose.yml` ships the connector runtime in the default profile (it idles harmlessly with no configured instances) and enables graph-at-ingest by default on `ingest-worker` (`AISOC_GRAPH_ENABLED=true` + Neo4j env + `depends_on`; the writer soft-fails if Neo4j is unreachable, so it never blocks ingest). `integration.yml` gains a Phase A3 gate asserting the default boot ships the connectors service **and** ingest enabled the graph writer **and** the Neo4j graph has nodes after the spine flowed — so combined with A1 (lake) and A2 (detection), a cold `up` is proven end-to-end: ingest → OCSF normalize → Kafka → ClickHouse lake + entity graph + detection engine → fused alert row. Claim-to-gate matrix: "`pnpm aisoc:demo` boots the real stack" PARTIAL → GATED (18 GATED / 10 PARTIAL / 1 NO GATE).- **Phase A2 — the executable detection corpus now fires on the live event stream.** The reality audit's second SIEM gap: ~939 executable rules existed but only ran in CI fixture-replay — nothing evaluated them against ingested events, so any telemetry that wasn't a vendor-asserted finding (the promoter's job) never became an alert. New `services/fusion/app/services/detection_engine.py` loads the native corpus exported to `app/data/detection_ruleset.json` (817 rules, by `scripts/export_detection_ruleset.py`) and evaluates each ingested event's connector-normalized fields — recovered from `ocsf_event["raw_data"]`, the shape the specs were authored against — via a **vendored, parity-gated** copy of the canonical `match_when` matcher (`app/services/detection_matcher.py`; `test_detection_matcher_parity.py` asserts byte-for-behaviour agreement with `scripts/generate_detections.py` over every committed fixture). Each firing rule becomes a `RawAlert` routed through the normal fusion dedup/correlate/persist pipeline. Product routing is fuzzy (correctness-first: unknown product ⇒ evaluate all). Gates: `integration.yml` posts an event matching `aws-root-account-login` and asserts the alert appears; `validate-detections.yml` drift-checks the exported ruleset; 16 fusion unit tests. Claim-to-gate matrix adds a GATED row "Detection rules fire on the live event stream" (17 GATED / 11 PARTIAL / 1 NO GATE).diff --git a/docker-compose.yml b/docker-compose.ymlindex 2ffc48761..2745b4ae6 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -361,12 +361,19 @@ services:condition: service_healthyredis:condition: service_healthy+ kafka:+ condition: service_healthyports:- "127.0.0.1:8001:8084"environment:DATABASE_URL: postgresql+asyncpg://aisoc:${POSTGRES_PASSWORD:-aisoc_dev_secret}@postgres:5432/aisocREDIS_URL: redis://:redis_dev_secret@redis:6379/4CORE_API_URL: http://api:8000+ # Phase B1 — auto-triage every fused alert off the Kafka stream (copilot:+ # read-only triage, no response dispatch). Degrades to deterministic+ # triage when no LLM key is set.+ KAFKA_BOOTSTRAP_SERVERS: kafka:29092+ KAFKA_TOPIC_ALERTS_FUSED: aisoc.alerts.fusedQDRANT_URL: http://qdrant:6333NEO4J_URI: bolt://neo4j:7687NEO4J_USER: neo4jdiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 311160167..21aa0b993 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -38,10 +38,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Ingested events land in the queryable ClickHouse lake | README (SIEM / lake) | `integration.yml :: spine` (Phase A1 — after the spine ingests, asserts `SELECT count() FROM aisoc.raw_events > 0` against the live ClickHouse container; `services/fusion` `LakeWriter` archives every normalized event) | GATED | - || Detection rules fire on the live event stream (not just CI fixtures) | README L170 (detection engine) | `integration.yml :: spine` (Phase A2 — posts an event matching the native `aws-root-account-login` rule, asserts the fusion `DetectionEngine` produces the alert) + `validate-detections.yml` (exported-ruleset drift `--check`) + fusion `test_detection_engine.py` / `test_detection_matcher_parity.py` | GATED | - || Three-model AI: behavioral (UEBA) model feeds alert scoring in production | README (multi-model) | `ci.yml` fusion job (`test_ueba_signal.py` — the `ueba.anomalies` stream warms a per-entity cache that boosts fuse-time confidence + anomaly score; wired in `fusion_engine.process`) | GATED | - |+| Agent auto-triages every alert (not manual/API-only) | README (autonomous triage) | `ci.yml` agents job (`test_fused_alert_worker.py` — `FusedAlertTriageWorker` consumes `aisoc.alerts.fused`, auto-triages each alert copilot/read-only with cost-governor dedup + circuit-breaker, degrades to deterministic triage without an LLM key, never dispatches a response) | GATED | - |## Summary-- GATED: 19+- GATED: 20- PARTIAL: 10- NO GATE: 1 (progressively closed through Phases 2–11 and A1–A4: insecure-defaults, secret/IaC scanning, signed releases, cross-store isolation, DAC candidate-rule + imported-count honesty, connector live-test, OpenAPI breaking-change, ClickHouse lake population (A1), live-stream detection (A2), default cold-boot stack (A3), and the behavioral-model fusion (A4). The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c/E1, which needs a budgeted live-agent run)diff --git a/services/agents/app/main.py b/services/agents/app/main.pyindex e54149cf7..27e619293 100644--- a/services/agents/app/main.py+++ b/services/agents/app/main.py@@ -1,3 +1,4 @@+import asyncioimport osfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager@@ -22,6 +23,7 @@ from app.hunt import store as hunt_storefrom app.investigator import ledger as investigation_ledgerfrom app.playbook import PlaybookStorefrom app.tools.mitre_full import embed_techniques_into_qdrant, load_attck_corpus+from app.workers.fused_alert_consumer import FusedAlertTriageWorker, worker_enabledlogger = structlog.get_logger()@@ -73,6 +75,23 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:except Exception as exc: # noqa: BLE001logger.warning("hunt.scheduler.start_failed", error=str(exc))+ # Phase B1 — auto-triage every fused alert off the Kafka stream (copilot:+ # read-only triage, no response dispatch). Off unless KAFKA_BOOTSTRAP_SERVERS+ # is set; degrades to deterministic triage without an LLM key.+ app.state.triage_worker = None+ app.state.triage_worker_task = None+ if worker_enabled():+ try:+ triage_worker = FusedAlertTriageWorker(+ bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"],+ topic=os.getenv("KAFKA_TOPIC_ALERTS_FUSED", "aisoc.alerts.fused"),+ )+ app.state.triage_worker = triage_worker+ app.state.triage_worker_task = asyncio.create_task(triage_worker.start())+ logger.info("auto_triage_worker.enabled")+ except Exception as exc: # noqa: BLE001 — never block API startup+ logger.warning("auto_triage_worker.start_failed", error=str(exc))+# Phase 2.6 — flip /readyz to 200 once startup work is done.app.state.mark_ready()@@ -81,6 +100,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:# Phase 2.6 — flip /readyz to 503 the moment we start draining.app.state.mark_not_ready()+ # Stop the auto-triage worker first so in-flight triage can finish.+ if getattr(app.state, "triage_worker", None) is not None:+ try:+ await app.state.triage_worker.stop()+ if app.state.triage_worker_task is not None:+ app.state.triage_worker_task.cancel()+ except Exception as exc: # noqa: BLE001+ logger.warning("auto_triage_worker.stop_failed", error=str(exc))+# Stop the hunt scheduler before draining DB pools so in-flight runs# can flush their writes.try:diff --git a/services/agents/app/workers/__init__.py b/services/agents/app/workers/__init__.pynew file mode 100644index 000000000..bc0cdee4e--- /dev/null+++ b/services/agents/app/workers/__init__.py@@ -0,0 +1 @@+"""Background workers for the agents service (Phase B1)."""diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pynew file mode 100644index 000000000..ab935db05--- /dev/null+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -0,0 +1,238 @@+"""Auto-triage every fused alert off the Kafka stream (Phase B1).++The reality audit's core autonomy gap: investigations were manual/API-only —+nothing consumed ``aisoc.alerts.fused`` to actually run the agent, so the+platform's headline claim (an agent that triages *every* alert, like a leading+AI-SOC) was not true out of the box. This worker closes that: it subscribes to+the fused-alert topic and runs auto-triage on each alert.++**Copilot / dry-run is the default.** Triage is *read-only*: the worker+classifies the alert (verdict + calibrated confidence), records the reasoning+to the Investigation Ledger, and stops. It NEVER executes a response action —+proposed actions carry ``requires_approval=True`` and are surfaced for a human+(or a tenant that has explicitly raised its L0-L4 autonomy tier — that wiring+is B2/C3). ``response_dispatched`` is therefore always ``False`` here.++Tier selection is cost- and determinism-aware, in this order (each degrades+safely to the deterministic tier, which needs no LLM key — the air-gapped /+no-key / CI default):++1. cost-governor ``DEDUPLICATED`` → reuse the cached verdict (a flood of+ identical alerts costs one triage, not N);+2. governor ``CIRCUIT_OPEN`` / ``AISOC_DETERMINISTIC`` / no LLM key →+ deterministic heuristic triage (``run_triage``);+3. otherwise → LLM auto-triage (``run_auto_triage``), falling back to+ deterministic triage if the LLM call fails.++Everything is fail-soft: a bad message is logged and skipped; a ledger/DB+outage degrades to "triage still runs, audit write is a no-op"; the Kafka loop+never dies on one poison alert.+"""++from __future__ import annotations++import json+import os+import uuid+from typing import Any++import structlog++from app.agents.auto_triage_agent import run_auto_triage+from app.agents.triage_agent import run_triage+from app.core.cost_governor import Decision, get_governor+from app.investigator import ledger as ledger_module+from app.models.state import AgentStatus, InvestigationState+from app.routing.model_router import is_deterministic_mode+from app.security.llm_resolver import resolve_llm_config++logger = structlog.get_logger()++_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_URL, "tryaisoc.com/agents/auto-triage")++_METRICS = {"triaged": 0, "deduplicated": 0, "deterministic": 0, "llm": 0, "errors": 0}+++def _coerce_uuid(value: Any, *, fallback: str) -> uuid.UUID:+ try:+ return uuid.UUID(str(value))+ except (ValueError, TypeError):+ return uuid.uuid5(_NAMESPACE, str(value or fallback))+++def build_state(message: dict[str, Any]) -> InvestigationState | None:+ """Map an ``aisoc.alerts.fused`` message to a seeded InvestigationState."""+ if not isinstance(message, dict):+ return None+ alert = message.get("alert")+ if not isinstance(alert, dict):+ return None+ tenant = _coerce_uuid(message.get("tenant_id") or alert.get("tenant_id"), fallback="default")+ incident = _coerce_uuid(message.get("incident_id") or message.get("id") or alert.get("id"), fallback=str(tenant))+ summary = str(alert.get("title") or "").strip()+ if message.get("narrative"):+ summary = f"{summary} — {message['narrative']}"[:1000] if summary else str(message["narrative"])[:1000]+ raw_alert = {+ "id": str(message.get("id") or alert.get("id") or ""),+ "severity": alert.get("severity"),+ "src_ip": alert.get("src_ip"),+ "dst_ip": alert.get("dst_ip"),+ "hostname": alert.get("hostname"),+ "username": alert.get("username"),+ "file_hash": alert.get("file_hash"),+ "domain": alert.get("domain"),+ "url": alert.get("url"),+ "mitre_techniques": alert.get("mitre_techniques", []),+ "risk_score": alert.get("risk_score", 0.0),+ "raw_event": alert.get("raw_event", {}),+ "confidence": message.get("confidence_score"),+ "fusion_decision": message.get("fusion_decision"),+ }+ return InvestigationState(+ incident_id=incident,+ tenant_id=tenant,+ alert_summary=summary,+ raw_alert=raw_alert,+ status=AgentStatus.PENDING,+ )+++class FusedAlertTriageWorker:+ """Consumes ``aisoc.alerts.fused`` and auto-triages each alert (copilot)."""++ def __init__(self, *, bootstrap_servers: str, topic: str = "aisoc.alerts.fused", group_id: str = "aisoc-agents-triage") -> None:+ self._bootstrap = bootstrap_servers+ self._topic = topic+ self._group_id = group_id+ self._consumer: Any | None = None+ self._running = False++ async def start(self) -> None:+ from aiokafka import AIOKafkaConsumer # noqa: PLC0415 — optional dep, only at runtime++ self._consumer = AIOKafkaConsumer(+ self._topic,+ bootstrap_servers=self._bootstrap,+ group_id=self._group_id,+ auto_offset_reset="latest",+ enable_auto_commit=True,+ value_deserializer=lambda m: json.loads(m.decode("utf-8")),+ )+ await self._consumer.start()+ self._running = True+ logger.info("auto_triage_worker.started", topic=self._topic, group=self._group_id)+ try:+ async for msg in self._consumer:+ if not self._running:+ break+ try:+ await self.triage(msg.value)+ except Exception as exc: # noqa: BLE001 — one poison alert must not kill the loop+ _METRICS["errors"] += 1+ logger.error("auto_triage_worker.error", error=str(exc), exc_info=True)+ finally:+ await self._consumer.stop()++ async def stop(self) -> None:+ self._running = False+ if self._consumer is not None:+ await self._consumer.stop()+ self._consumer = None+ logger.info("auto_triage_worker.stopped", metrics=dict(_METRICS))++ async def triage(self, message: dict[str, Any]) -> dict[str, Any] | None:+ """Auto-triage one fused alert. Read-only (copilot): never dispatches a+ response. Returns a verdict summary dict, or None if unprocessable."""+ state = build_state(message)+ if state is None:+ logger.warning("auto_triage_worker.unprocessable", keys=sorted(message.keys()) if isinstance(message, dict) else None)+ return None++ governor = get_governor()+ fingerprint = governor.evidence_fingerprint(str(state.tenant_id), state.raw_alert)+ decision = governor.check(str(state.tenant_id), fingerprint)++ tier: str+ if decision.decision is Decision.DEDUPLICATED and decision.cached_verdict:+ _METRICS["deduplicated"] += 1+ verdict = decision.cached_verdict.get("verdict")+ confidence = float(decision.cached_verdict.get("confidence", 0.0))+ tier = "cached"+ else:+ use_llm = decision.use_llm and not is_deterministic_mode() and await self._llm_available(state.tenant_id)+ if use_llm:+ state, tier = await self._llm_triage(state)+ else:+ state = await run_triage(state)+ tier = "deterministic"+ _METRICS["deterministic"] += 1+ verdict = state.verdict+ confidence = state.confidence++ _METRICS["triaged"] += 1+ await self._record(state, tier=tier, verdict=verdict, confidence=confidence)++ return {+ "run_id": str(state.run_id),+ "incident_id": str(state.incident_id),+ "tenant_id": str(state.tenant_id),+ "verdict": verdict,+ "confidence": confidence,+ "tier": tier,+ # Copilot default: triage is read-only, response requires approval.+ "response_dispatched": False,+ "proposed_actions": [{"action_type": a.action_type, "requires_approval": a.requires_approval} for a in state.proposed_actions],+ }++ async def _llm_available(self, tenant_id: uuid.UUID) -> bool:+ try:+ cfg = await resolve_llm_config(str(tenant_id))+ return bool(cfg.allowed and cfg.api_key)+ except Exception as exc: # noqa: BLE001 — resolver failure => deterministic+ logger.debug("auto_triage_worker.llm_resolve_failed", error=str(exc))+ return False++ async def _llm_triage(self, state: InvestigationState) -> tuple[InvestigationState, str]:+ try:+ state = await run_auto_triage(state)+ _METRICS["llm"] += 1+ return state, "llm"+ except Exception as exc: # noqa: BLE001 — fall back to deterministic triage+ logger.warning("auto_triage_worker.llm_failed_fallback", error=str(exc))+ state = await run_triage(state)+ _METRICS["deterministic"] += 1+ return state, "deterministic"++ async def _record(self, state: InvestigationState, *, tier: str, verdict: Any, confidence: float) -> None:+ """Best-effort ledger write. No DB => no-op (never raises)."""+ try:+ await ledger_module.start_run(+ run_id=state.run_id,+ case_id=str(state.incident_id),+ tenant_ref=str(state.tenant_id),+ alert_summary=state.alert_summary or "",+ raw_alert=state.raw_alert or {},+ model_used=f"kafka:auto_triage:{tier}",+ )+ await ledger_module.complete_run(+ run_id=state.run_id,+ tenant_id=state.tenant_id,+ status="completed",+ error=None,+ iterations=state.iteration_count,+ total_tokens=0,+ total_cost_usd=0.0,+ )+ except Exception as exc: # noqa: BLE001 — audit is best-effort+ logger.debug("auto_triage_worker.ledger_noop", error=str(exc), verdict=verdict, confidence=confidence)++ @staticmethod+ def get_metrics() -> dict[str, int]:+ return dict(_METRICS)+++def worker_enabled() -> bool:+ """Off unless a Kafka broker is configured and it's not explicitly disabled."""+ if os.getenv("AISOC_AGENT_KAFKA_DISABLE", "").strip().lower() in {"1", "true", "yes", "on"}:+ return False+ return bool(os.getenv("KAFKA_BOOTSTRAP_SERVERS", "").strip())diff --git a/services/agents/tests/test_fused_alert_worker.py b/services/agents/tests/test_fused_alert_worker.pynew file mode 100644index 000000000..769e25de0--- /dev/null+++ b/services/agents/tests/test_fused_alert_worker.py@@ -0,0 +1,174 @@+"""Phase B1 — auto-triage worker tests.++Proves every fused alert is auto-triaged (deterministically, no LLM key — the+copilot / air-gapped / CI default), that triage is READ-ONLY (no response is+ever dispatched; proposed actions require approval), that the cost governor's+dedup + circuit-breaker paths are honored, and that state-mapping + fail-soft+behavior hold.+"""++from __future__ import annotations++import uuid++import pytest+from app.core.cost_governor import Decision, GovernorDecision+from app.workers import fused_alert_consumer as worker_mod+from app.workers.fused_alert_consumer import FusedAlertTriageWorker, build_state++pytestmark = pytest.mark.asyncio++TENANT = "11111111-1111-1111-1111-111111111111"+++def _fused(**alert_overrides) -> dict:+ alert = {+ "id": "22222222-2222-2222-2222-222222222222",+ "tenant_id": TENANT,+ "title": "Credential dumping via LSASS access",+ "severity": "critical",+ "hostname": "WIN-DC01",+ "username": "svc-backup",+ "src_ip": "10.20.30.40",+ "mitre_techniques": ["T1003"],+ "risk_score": 0.9,+ "raw_event": {"a": 1},+ }+ alert.update(alert_overrides)+ return {+ "id": "22222222-2222-2222-2222-222222222222",+ "tenant_id": TENANT,+ "incident_id": "33333333-3333-3333-3333-333333333333",+ "fusion_decision": "new_incident",+ "confidence_score": 0.8,+ "narrative": "Fusion correlated 3 signals.",+ "alert": alert,+ }++[email protected](autouse=True)+def _no_ledger_db(monkeypatch):+ # Ledger writes are best-effort; make them explicit no-ops in tests.+ async def _noop(*args, **kwargs): # noqa: ANN002, ANN003+ return None++ monkeypatch.setattr(worker_mod.ledger_module, "start_run", _noop)+ monkeypatch.setattr(worker_mod.ledger_module, "complete_run", _noop)+ # Force the deterministic path unless a test overrides (no LLM key in CI).+ monkeypatch.setenv("AISOC_DETERMINISTIC", "0")+++def _worker() -> FusedAlertTriageWorker:+ return FusedAlertTriageWorker(bootstrap_servers="unused")+++# ── state mapping ─────────────────────────────────────────────────────────────+++async def test_build_state_maps_fused_alert():+ state = build_state(_fused())+ assert str(state.tenant_id) == TENANT+ assert "Credential dumping" in state.alert_summary+ assert state.raw_alert["hostname"] == "WIN-DC01"+ assert state.raw_alert["mitre_techniques"] == ["T1003"]+++async def test_build_state_rejects_non_alert():+ assert build_state({"tenant_id": TENANT}) is None+ assert build_state("nope") is None+++# ── auto-triage (deterministic default) ──────────────────────────────────────+++async def test_every_alert_is_triaged_deterministically_without_llm(monkeypatch):+ # No LLM key => deterministic tier.+ monkeypatch.setattr(worker_mod, "resolve_llm_config", _fake_llm_config(allowed=False))+ result = await _worker().triage(_fused())+ assert result is not None+ assert result["tier"] == "deterministic"+ assert result["verdict"] is not None+ assert result["confidence"] >= 0.0+++async def test_triage_is_read_only_no_response_dispatched(monkeypatch):+ monkeypatch.setattr(worker_mod, "resolve_llm_config", _fake_llm_config(allowed=False))+ result = await _worker().triage(_fused())+ # Copilot default: never dispatches a response; a critical alert proposes an+ # isolate_host action but it REQUIRES approval.+ assert result["response_dispatched"] is False+ assert any(a["action_type"] == "isolate_host" and a["requires_approval"] for a in result["proposed_actions"])+++async def test_deterministic_mode_forces_deterministic_even_with_key(monkeypatch):+ monkeypatch.setenv("AISOC_DETERMINISTIC", "1")+ monkeypatch.setattr(worker_mod, "resolve_llm_config", _fake_llm_config(allowed=True))+ result = await _worker().triage(_fused())+ assert result["tier"] == "deterministic"+++# ── cost governor integration ────────────────────────────────────────────────+++async def test_dedup_cache_short_circuits(monkeypatch):+ cached = GovernorDecision(+ decision=Decision.DEDUPLICATED,+ reason="dup",+ remaining_usd=10.0,+ cached_verdict={"verdict": "true_positive", "confidence": 0.91},+ )+ monkeypatch.setattr(worker_mod, "get_governor", lambda: _FakeGovernor(cached))+ result = await _worker().triage(_fused())+ assert result["tier"] == "cached"+ assert result["verdict"] == "true_positive"+ assert result["confidence"] == 0.91+++async def test_circuit_open_forces_deterministic(monkeypatch):+ open_decision = GovernorDecision(decision=Decision.CIRCUIT_OPEN, reason="budget", remaining_usd=0.0)+ monkeypatch.setattr(worker_mod, "get_governor", lambda: _FakeGovernor(open_decision))+ monkeypatch.setattr(worker_mod, "resolve_llm_config", _fake_llm_config(allowed=True))+ result = await _worker().triage(_fused())+ assert result["tier"] == "deterministic"+++# ── fail-soft ─────────────────────────────────────────────────────────────────+++async def test_unprocessable_message_returns_none():+ assert await _worker().triage({"garbage": True}) is None+++async def test_worker_enabled_flag(monkeypatch):+ monkeypatch.delenv("KAFKA_BOOTSTRAP_SERVERS", raising=False)+ assert worker_mod.worker_enabled() is False+ monkeypatch.setenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:9092")+ assert worker_mod.worker_enabled() is True+ monkeypatch.setenv("AISOC_AGENT_KAFKA_DISABLE", "1")+ assert worker_mod.worker_enabled() is False+++# ── helpers ───────────────────────────────────────────────────────────────────+++def _fake_llm_config(*, allowed: bool):+ class _Cfg:+ def __init__(self) -> None:+ self.allowed = allowed+ self.api_key = "sk-test" if allowed else None++ async def _resolve(_tenant): # noqa: ANN001+ return _Cfg()++ return _resolve+++class _FakeGovernor:+ def __init__(self, decision: GovernorDecision) -> None:+ self._decision = decision++ def evidence_fingerprint(self, tenant_id, alert): # noqa: ANN001, ARG002+ return "fp-" + str(uuid.uuid4())++ def check(self, tenant_id, fingerprint): # noqa: ANN001, ARG002+ return self._decision