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
fix(wave 3, partial): replay and shadow mode measure the real run (#1118)
Beenu Arorad25d6552d557
diff --git a/.github/workflows/agent-auth-live.yml b/.github/workflows/agent-auth-live.ymlindex d3f30b63a..e0c320acf 100644--- a/.github/workflows/agent-auth-live.yml+++ b/.github/workflows/agent-auth-live.yml@@ -112,6 +112,19 @@ jobs:ISOLATION_CROSS_SERVICE: "1"run: python -m pytest ../../tests/isolation/test_api_to_connectors_auth.py -v --tb=short -rs+ # Runs in no workflow at all before this. The claim row "Analyst+ # dispositions are point-in-time during a replay" cited a workflow that+ # skips it, and the suite skips itself unless the DSN says postgres --+ # so it had never executed anywhere. `DISPOSITIONS_CUTOFF_LIVE_REQUIRED`+ # turns its own skip into a failure, which is what makes this job+ # evidence rather than a green tick.+ - name: Analyst dispositions are point-in-time during a replay+ working-directory: services/api+ env:+ DATABASE_URL: ${{ env.LIVE_DSN }}+ DISPOSITIONS_CUTOFF_LIVE_REQUIRED: "1"+ run: python -m pytest ../../tests/isolation/test_recent_dispositions_cutoff_live.py -v --tb=short -rs+- name: Install agents from its lockfileworking-directory: services/agentsrun: |diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex c8d15218b..a8d00367e 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -116,7 +116,7 @@ jobs:# the only thing that proves the whole chain is the end-to-end run.# Every tree it crosses is listed, because a change to any one of# them can break a link none of the unit suites can see.- replay_paths='services/api/app/services/replay_evaluation/ services/api/app/api/v1/endpoints/evaluations.py services/api/app/_vendor/aisoc_benchmark/ services/agents/app/replay/ services/agents/app/api/replay_router.py services/actions/app/api/replay_history_router.py services/actions/app/services/alert_history.py services/connectors/app/api/router.py packages/aisoc-benchmark/ packages/aisoc-cli/ tests/e2e/test_replay_cli_end_to_end.py .github/workflows/integration.yml'+ replay_paths='services/api/app/services/replay_evaluation/ services/api/app/api/v1/endpoints/evaluations.py services/api/app/_vendor/aisoc_benchmark/ services/agents/app/replay/ services/agents/app/api/replay_router.py services/actions/app/api/replay_history_router.py services/actions/app/services/alert_history.py services/connectors/app/api/router.py packages/aisoc-benchmark/ packages/aisoc-cli/ tests/e2e/test_replay_cli_end_to_end.py .github/workflows/integration.yml services/agents/app/workers/fused_alert_consumer.py services/agents/app/replay/shadow.py services/actions/app/clients/ services/ingest/internal/normalizer/ services/agents/app/closure/'base_ref=""if [ -n "${{ github.base_ref }}" ]; thendiff --git a/.github/workflows/wet-eval.yml b/.github/workflows/wet-eval.ymlindex 3b7fbb669..447e85145 100644--- a/.github/workflows/wet-eval.yml+++ b/.github/workflows/wet-eval.yml@@ -171,19 +171,32 @@ jobs:# uses in `ci.yml` so the wet eval runs against a known-good# frozen agent surface.# ──────────────────────────────────────────────- - name: Install agent dependencies+ - name: Install agents from its own locked dependency setrun: |set -euo pipefail- pip install --quiet \- "fastapi>=0.117,<0.142" "pydantic[email]" "pydantic-settings" \- "sqlalchemy[asyncio]" "asyncpg" "structlog" \- "PyJWT>=2.8,<3" "cryptography>=46,<51" "passlib[bcrypt]" \- "tenacity" "pyyaml" "prometheus-client" \- "neo4j" "redis" "celery" "httpx" "aiofiles" \- "email-validator" "PyJWT>=2.8,<3" "aiosqlite" \- "langchain>=0.3" "langchain-openai>=0.2" \- "langgraph>=0.2" "openai>=1.40" \- "pytest" "pytest-asyncio"+ # The lockfile, not a hand-written list. The list this replaced named+ # 18 packages and omitted `mcp` and `opentelemetry`, both of which+ # the agents app imports at module scope (`app/mcp/client.py`,+ # `app/core/telemetry.py`, `app/investigator/orchestrator.py`). A set+ # that differs from the lock means this job grades software nobody+ # ships.+ python -m pip install --quiet --upgrade pip+ python -m pip install --quiet $(python3 scripts/service_requirements.py agents --locked)+ python -m pip install --quiet pytest pytest-asyncio++ # Setup has to fail loudly, and differently from "no funded key". A+ # skipped job and a broken job both print nothing, and the scoreboard+ # cannot tell them apart.+ - name: The agent imports, or this job says so instead of measuring nothing+ working-directory: services/agents+ run: |+ set -euo pipefail+ if ! python -c "import app.mcp.client, app.core.telemetry, app.investigator.orchestrator" 2>/tmp/import-err; then+ echo "::error title=wet-eval::the agents package does not import, so nothing below could have been measured."+ cat /tmp/import-err+ exit 1+ fi+ echo "agents imports cleanly, so a figure below is a measurement rather than a default."# ──────────────────────────────────────────────# Step 3 — run the wet eval.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d154a6d5..9d27fb26e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -176,7 +176,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **The live agent evaluation could never have measured anything.** It imported`InvestigatorAgent`, a class that exists only in the historical prototype, and the hosted-keycheck returned first so the broken import was never reached. Repointed at the real agent, it- measures a **9.3% verdict-flip rate** against a local model.+ measures a **9.3% verdict-flip rate** — one manual run of the 200-incident synthetic corpus against a locally-served `llama3.2:3b`, which is not the model a hosted deployment resolves. A single run on one model, not a distribution: the weekly job that would produce one has no funded key, so it skips.- **Three stores had a backup and no restore.** `backup.sh` covered five, `restore.sh` covered two.Neo4j, Qdrant and Redis now restore, and `check_backup_restore_parity.py` fails CI on the nextstore that gains a backup without one.diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.mdindex c3a803ec0..d557dca40 100644--- a/FIX_PASS_PROGRESS.md+++ b/FIX_PASS_PROGRESS.md@@ -87,17 +87,17 @@ conditional `numpy` pins collide into an unresolvable install. Parse with## Wave 3: Replay, shadow mode and evaluation measure the real thing- [ ] **3.1** Frozen context, not empty context-- [ ] **3.2** No side effects from a replay+- [x] **3.2** No side effects from a replay- [ ] **3.3** Input shapes: per-source adapters for Elastic and Defender-- [ ] **3.4** Model attribution: `model_used` is set from the call that answered+- [x] **3.4** Model attribution: `model_used` is set from the call that answered- [ ] **3.5** Non-degenerate acceptance for the reproducibility test-- [ ] **3.6** Tool calls recorded from the ledger, not hard-coded to 0+- [x] **3.6** Tool calls recorded from the ledger, not hard-coded to 0- [ ] **3.7** Demotion without a page load- [ ] **3.8** Skills: activation evidence, LLM-path-only disclosure, console retraction-- [ ] **3.9** The weekly live evaluation can actually run-- [ ] **3.10** The 9.3% flip rate is qualified or removed-- [ ] **3.11** CI runs the live tests-- [ ] **3.12** Pivot counting excludes failed calls+- [~] **3.9** The weekly live evaluation installs from the lockfile and fails loudly; it still cannot *run* without a funded key (M2)+- [x] **3.10** The 9.3% flip rate is qualified or removed+- [x] **3.11** CI runs the live tests+- [x] **3.12** Pivot counting excludes failed calls## Wave 4: Enterprise identity, white-label and metering@@ -522,3 +522,56 @@ left implied.* Removing the row took the matrix 291 -> 290, which `readme_gates` caught inthree more documents quoting the old figure. That is the copied-count failureworking as designed.++## Wave 3 (partial): what is done and what is not++**Done, each with a reproduction and a negative control:** 3.2, 3.4, 3.6,+3.10, 3.11, 3.12, and the actionable half of 3.9.++**Not started:** 3.1 (frozen context), 3.3 (per-source input adapters),+3.5 (non-degenerate acceptance), 3.7 (demotion without a page load),+3.8 (skills activation evidence and the console retraction).++### 3.2 A replay has no side effects++Two of the four the plan names were **already closed** and are recorded as+such rather than re-fixed: `ShadowTriageWriter.persists_cost` is `False`, and+every write method returns the nothing-happened value its live counterpart+returns on a no-op.++The other two did not reach the worker through the writer, so nothing declined+them. `alert_trigger.run_for_alert` was unconditional, so **a replay of last+month's alerts would have fired this month's playbooks**. And the cost+governor's `DEDUPLICATED` branch answered from a live cache, so a replayed+verdict could be one production already produced, which measures the cache.++Adding the two members to the writer protocol immediately named the three+classes that implement it, because `ShadowModeTriageWriter` stopped satisfying+`isinstance`. Shadow mode answers differently from replay on purpose: it+withholds playbooks and keeps deduplication, and both reasons are written down.++### 3.4, 3.6, 3.12++See the commit; each is a figure that was structurally unable to be right.+`InvestigationState` had no `model_used`, so the shadow writer's `getattr`+default was the only branch that ever ran. `tool_calls` was a literal under a+comment promising it would move. `_classify_pivots` counted a raised call as a+pivot, so four timeouts looked like four pivots.++### 3.9 is half done, and the half that is left is M2++Installing from the lockfile and failing loudly on an import error are done.+The job still cannot produce a number, because it is gated on a funded key+that does not exist. **The claim row "The weekly job cannot go green having+measured nothing" is therefore still not true**, and is left for wave 7 to+downgrade rather than quietly marked done here.++### A correction to the plan's reading of 3.6++The plan calls the literal `0` a hardcoded placeholder. It is not: zero is the+correct answer today, because shadow mode declines escalation and escalation is+the only stage that calls tools. The defect is narrower and worse -- the+comment above it says the figure is "recorded so a future change that gives+triage a tool shows up here as a number moving off zero", and a literal can+never move. The fix derives the same zero from the ledger so it can change+when the run does.diff --git a/RELEASES.md b/RELEASES.mdindex 8205a864e..f5756cb84 100644--- a/RELEASES.md+++ b/RELEASES.md@@ -4,7 +4,7 @@ This file mirrors what used to live in the "What's new" section of [`README.md`]> **TL;DR for first-time visitors:** AiSOC is on `v16.0.1`, released 2026-10-04. **A security release, no breaking changes.** It closes **GHSA-4gx4-x7gm-4xq8**, a high-severity privilege escalation reported by [HaiND](https://github.com/Haind03): the check that decides whether a caller may *confer* authority read the caller's static role, while the check that admits a caller to the route read its database-resolved permissions. Those are two different answers whenever a tenant uses database-backed RBAC — which is the configuration where it matters, since narrowing an account is what those tables are for. A `tenant_admin` deliberately restricted to `users:write` still carried 28 permissions statically and could grant itself the other 27. **If you use the `roles` and `user_roles` tables to restrict accounts, upgrade.** Deployments with no RBAC rows were never exposed, because the static map was already the correct answer for them. The report named one route; the resolver is shared, so five more had it — authoring a role, re-permissioning one, creating a user, delegating to a child tenant, and minting an API key, that last needing no target user and yielding a durable credential. `scripts/check_role_grant_scope.py` gains a direction that fails CI when a grant is measured against the wrong authority; its previous directions passed on the vulnerable tree because they asked only whether a route *reached* the chokepoint, and all six did. Also raises `serialize-javascript` to `>=7.1.2` and `http-cache-semantics` to `>=4.3.0`. The chart publishes as **`7.3.1`**. Everything below describes v16.0.0 and earlier, which this release does not change.>-> **Previously:** AiSOC was on `v16.0.0`, released 2026-10-03. **One breaking change:** the `cases` table is gone and its rows live in `aisoc_cases`. Any SQL of your own against `cases` — a Grafana panel, a scheduled export — now fails with "relation does not exist" rather than returning stale rows, which is the intended behaviour. The theme is a single shape repeated seventeen times: **a mechanism that is complete, tested, and has no caller**, so it passes CI forever while doing nothing. SSO could not sign anyone in — `aisoc_sso_connections` was written by nothing, so every SAML and OIDC callback returned 403 on every deployment, while both handlers were fully tested. MTTA published a confident `0.0` because `alerts.first_seen_at` had no writer. The evidence chain an auditor exports was always `[]`. SLA reporting ran 350 lines of correct arithmetic over an empty table. The console's rule-Approve button could not succeed. The live agent evaluation imported a class that exists only in the historical prototype. And the two case tables never synchronised, so **every case an analyst created was invisible to every case metric** — which is the break above. Measured, not asserted: an agent answering "true positive" to everything scored **1.000** on the detection corpus and now scores **0.727**, because the benign class was derived from `response_class == "monitor"` and those incidents are BloodHound enumeration tagged T1087.002. The first live behavioural run published "unsafe action proposal rate 0.0%", which meant the agent proposed no actions at all; it now reports **not measured** and the verdict flip rate is a real **9.3%**. New: detection lifecycle with rollback and separation of duties, content packs, alert prioritisation, case queues and escalation, legal hold and residency, workload identity and time-boxed elevation, restore paths for Neo4j/Qdrant/Redis, and inbound translation from Splunk SPL, Sentinel KQL and Elastic EQL — on the 2,005 rules bundled here, 1,734 translate and **1,711 of those only partially**. A 22-page technical guide ships as a PDF with real console screenshots. The chart publishes as **`7.3.0`**. Everything below describes v15.1.0 and earlier, which this release does not change.+> **Previously:** AiSOC was on `v16.0.0`, released 2026-10-03. **One breaking change:** the `cases` table is gone and its rows live in `aisoc_cases`. Any SQL of your own against `cases` — a Grafana panel, a scheduled export — now fails with "relation does not exist" rather than returning stale rows, which is the intended behaviour. The theme is a single shape repeated seventeen times: **a mechanism that is complete, tested, and has no caller**, so it passes CI forever while doing nothing. SSO could not sign anyone in — `aisoc_sso_connections` was written by nothing, so every SAML and OIDC callback returned 403 on every deployment, while both handlers were fully tested. MTTA published a confident `0.0` because `alerts.first_seen_at` had no writer. The evidence chain an auditor exports was always `[]`. SLA reporting ran 350 lines of correct arithmetic over an empty table. The console's rule-Approve button could not succeed. The live agent evaluation imported a class that exists only in the historical prototype. And the two case tables never synchronised, so **every case an analyst created was invisible to every case metric** — which is the break above. Measured, not asserted: an agent answering "true positive" to everything scored **1.000** on the detection corpus and now scores **0.727**, because the benign class was derived from `response_class == "monitor"` and those incidents are BloodHound enumeration tagged T1087.002. The first live behavioural run published "unsafe action proposal rate 0.0%", which meant the agent proposed no actions at all; it now reports **not measured** and the verdict flip rate is **9.3%** from one manual run of the 200-incident synthetic corpus against a locally-served `llama3.2:3b`, which is not the model a hosted deployment resolves. New: detection lifecycle with rollback and separation of duties, content packs, alert prioritisation, case queues and escalation, legal hold and residency, workload identity and time-boxed elevation, restore paths for Neo4j/Qdrant/Redis, and inbound translation from Splunk SPL, Sentinel KQL and Elastic EQL — on the 2,005 rules bundled here, 1,734 translate and **1,711 of those only partially**. A 22-page technical guide ships as a PDF with real console screenshots. The chart publishes as **`7.3.0`**. Everything below describes v15.1.0 and earlier, which this release does not change.>> **Before that:** AiSOC was on `v15.1.0`, released 2026-10-03. **No breaking changes** — two routes are added and none removed, so every generated SDK client keeps working. The theme is the gap between a capability existing and a user reaching it: `v15.0.0` closed thirteen security defects sharing the shape *a control that exists, passes its tests and never runs*, and this release applies the same reading to the product. Playbooks could not act at all — `find_matching()` had no production caller, so no playbook had ever run from an alert, and the `approval` step was documented as a durable pause with nowhere to suspend to. A tenant's detection tuning never reached the streaming engine, so a rule turned off in the console kept firing. Every CloudTrail event collapsed onto a single alert, which a one-event pipeline test cannot reveal. Three things are worth reading before upgrading: **first run changed substantially** (`make up` resolves a port conflict instead of refusing to start, measured at 64 seconds from clone to signed-in console on a host with 5432 and 11434 both taken, and a new tenant lands on a setup wizard), **CloudTrail users will see more alerts**, and **the project-maturity table now means something** — `Stable` has a written definition in `docs/audit/MATURITY_DEFINITION.md` and a gate, and the two rows that claimed CI coverage which existed nowhere were fixed rather than relabelled. New: signed, replayable evidence bundles at `GET /api/v1/investigations/{run_id}/bundle`, byte-identical across exports with prompts as digests and an OCSF 1.9.0 mapping checked against the published schema before use; and a copilot that cites every checkable claim to a ledger entry or labels it **uncited**. On the benchmark page, **verdict accuracy is published as *not measured*, with the reason** — every labelled corpus here is entirely malicious by construction, so an agent answering "true positive" to everything would post 100%, and `scripts/score_replay_set.py` refuses such a corpus with a test asserting this tree's own two are refused. The chart publishes as **`7.2.0`**. Everything below describes v15.0.0 and earlier, which this release does not change.diff --git a/services/agents/app/investigator/deep_investigation.py b/services/agents/app/investigator/deep_investigation.pyindex 77afd45ce..7e9fdaaca 100644--- a/services/agents/app/investigator/deep_investigation.py+++ b/services/agents/app/investigator/deep_investigation.py@@ -301,13 +301,26 @@ def _classify_pivots(trace: list[dict[str, Any]]) -> tuple[list[str], list[str]]A tool that reported ``available: false`` is not a pivot — counting itwould let an investigation reach its depth floor by calling four toolsthat all answered "not ingested".++ Neither is a tool that **raised**. ``app/tools/registry.py`` returns+ ``{"error": f"{type(exc).__name__}: {exc}"}`` when a tool throws, and that+ shape carries no ``available`` key at all, so it used to fall into the+ ``else`` and count. Four tools that all timed out therefore looked like+ four pivots, and an investigation could report the depth it was required to+ reach while having learned nothing."""pivots: list[str] = []unavailable: list[str] = []for entry in trace:name = entry.get("tool", "")preview = str(entry.get("result_preview", ""))- if "'available': False" in preview or '"available": false' in preview:+ unavailable_flag = "'available': False" in preview or '"available": false' in preview+ # Matched on the key rather than on the word, so a *result* mentioning+ # an error — a SIEM row whose message contains "error" — is still a+ # pivot. Only the registry's own failure envelope has the key at the+ # top of the mapping.+ errored = "'error':" in preview or '"error":' in preview+ if unavailable_flag or errored:unavailable.append(name)else:pivots.append(name)diff --git a/services/agents/app/models/state.py b/services/agents/app/models/state.pyindex 41c42277e..0e85fa9ec 100644--- a/services/agents/app/models/state.py+++ b/services/agents/app/models/state.py@@ -60,6 +60,21 @@ class InvestigationState(BaseModel):budget_exhausted: bool = Falsebudget_exhausted_reason: str | None = None+ #: The model that actually answered this triage, set from the call rather+ #: than from the pin.+ #:+ #: `fused_alert_consumer` stamps a shadow decision with+ #: `getattr(state, "model_used", None)`. The field did not exist, so that+ #: default was the only branch that ever ran and **every shadow decision+ #: recorded a null model** -- which makes per-model agreement, the reason+ #: the column exists, empty on every deployment.+ #:+ #: `None` means "no model answered", which is the honest value on the+ #: deterministic path. It is deliberately not defaulted to a pin name: a+ #: non-null column that nobody wrote is worse than an empty one, because+ #: it reads as a measurement.+ model_used: str | None = None+# Identifiersrun_id: UUID = Field(default_factory=uuid4)incident_id: UUIDdiff --git a/services/agents/app/replay/runner.py b/services/agents/app/replay/runner.pyindex e1b1cf691..e66b24965 100644--- a/services/agents/app/replay/runner.py+++ b/services/agents/app/replay/runner.py@@ -69,6 +69,22 @@ __all__ = [DEFAULT_TRAIN_FRACTION = 0.7+#: Ledger row kinds that mean a tool was called. The ledger also carries+#: `llm_response`, `hunt_plan` and others, so counting every row would report+#: the model's own turns as tool calls.+_TOOL_CALL_KINDS = frozenset({"tool_call"})+++def _tool_calls_recorded(rows: list[dict[str, object]]) -> int:+ """How many tool calls this run actually made.++ Zero for a run whose ledger carries none, which is the honest answer and+ also today's answer on the shadow path. The difference from a literal is+ that this one changes when the run does.+ """+ return sum(1 for row in rows if str(row.get("kind") or "") in _TOOL_CALL_KINDS)++@dataclass(frozen=True)class TimeSplit:"""Where history was cut, and what fell either side."""@@ -356,9 +372,12 @@ class ReplayRunner:decision.estimated_usd = cost.get("estimated_usd")decision.unpriced_calls = int(cost.get("unpriced_calls") or 0)decision.resolved_models = [str(m) for m in (cost.get("resolved_models") or [])]- # Structurally zero rather than unmeasured: shadow mode declines- # escalation, and escalation is the only stage of this path that calls- # tools. Recorded so a future change that gives triage a tool shows up- # here as a number moving off zero.- decision.tool_calls = 0+ # Derived, not asserted. The literal `0` that stood here was the+ # correct answer -- shadow mode declines escalation, and escalation is+ # the only stage of this path that calls tools -- under a comment+ # saying it was "recorded so a future change that gives triage a tool+ # shows up here as a number moving off zero". A literal can never+ # move, so the comment and the code contradicted each other, and the+ # day triage gained a tool the report would have kept saying zero.+ decision.tool_calls = _tool_calls_recorded(summary.get("ledger") or [])return decisiondiff --git a/services/agents/app/replay/shadow.py b/services/agents/app/replay/shadow.pyindex 4e69d0cc8..61fdeea5a 100644--- a/services/agents/app/replay/shadow.py+++ b/services/agents/app/replay/shadow.py@@ -152,6 +152,28 @@ class ShadowTriageWriter:def persists_cost(self) -> bool:return False+ @property+ def fires_playbooks(self) -> bool:+ """Whether a matched playbook may actually run from this triage.++ `alert_trigger.run_for_alert` was called unconditionally, so a replay+ of last month's alerts would have **fired this month's playbooks** --+ real notifications, real tickets, real containment previews -- against+ rows a grader was only meant to score.+ """+ return False++ @property+ def uses_dedup_cache(self) -> bool:+ """Whether a cached production verdict may answer for this alert.++ The cost governor returns `Decision.DEDUPLICATED` with a verdict from+ a live cache. Accepting one during a replay grades the cache rather+ than the agent, and the figure that comes out is a measurement of+ something that already happened.+ """+ return False+@propertydef total_writes(self) -> int:"""How many writes production would have made. Zero is the claim under test."""diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex 8f309eee2..21b66d999 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -551,7 +551,11 @@ class FusedAlertTriageWorker:# and "no call was made" is a different fact from "the call was free".cost: CostSummary = CostSummary()tokens = 0- if decision.decision is Decision.DEDUPLICATED and decision.cached_verdict:+ # `writer.uses_dedup_cache` because a replay must not be graded on a+ # verdict production already produced: that measures the cache rather+ # than the agent, and the figure describes something that already+ # happened.+ if decision.decision is Decision.DEDUPLICATED and decision.cached_verdict and writer.uses_dedup_cache:_METRICS["deduplicated"] += 1verdict = decision.cached_verdict.get("verdict")confidence = float(decision.cached_verdict.get("confidence", 0.0))@@ -618,6 +622,14 @@ class FusedAlertTriageWorker:_METRICS["deterministic"] += 1cost = CostSummary.from_tracker(tracker)tokens = tracker.total_tokens+ # From the call that answered, not from the pin. The shadow+ # writer stamps a decision with `state.model_used`, and the+ # field did not exist, so every shadow decision recorded a+ # null model and per-model agreement was empty on every+ # deployment. `resolved_models` is what the tracker observed,+ # so the deterministic path correctly leaves this `None`.+ if cost.resolved_models:+ state.model_used = ", ".join(sorted({str(m) for m in cost.resolved_models}))# Parity 5.1. `find_matching()` had no production caller, so no# playbook ever ran from an alert. Three switches must agree@@ -629,7 +641,15 @@ class FusedAlertTriageWorker:# verdict and the confidence, and before them it would be# matching on an alert nobody has assessed.try:- playbook_outcome = await alert_trigger.run_for_alert(state)+ # `writer.fires_playbooks` because this was unconditional, so a+ # replay of last month's alerts would have fired this month's+ # playbooks -- real notifications, real tickets -- against rows a+ # grader was only meant to score.+ playbook_outcome = (+ await alert_trigger.run_for_alert(state)+ if writer.fires_playbooks+ else alert_trigger.TriggerOutcome(skipped_reason="replay: playbooks are not fired")+ )if playbook_outcome.matched:state.add_finding(f"Playbooks matched: {', '.join(playbook_outcome.matched)}"diff --git a/services/agents/app/workers/shadow_mode.py b/services/agents/app/workers/shadow_mode.pyindex f22bdbdcd..b7e48a718 100644--- a/services/agents/app/workers/shadow_mode.py+++ b/services/agents/app/workers/shadow_mode.py@@ -330,6 +330,21 @@ class ShadowModeTriageWriter:# see the spend.return True+ @property+ def fires_playbooks(self) -> bool:+ # Shadow mode is measuring whether the agent *would* be right, before a+ # tenant grants it autonomy. A playbook that ran would be the agent+ # acting on a verdict nobody has accepted yet, which is the one thing+ # the mode exists to withhold.+ return False++ @property+ def uses_dedup_cache(self) -> bool:+ # Production behaviour. A tenant measuring a real stream should see the+ # same deduplication a live run would do, or the shadow scorecard+ # describes a different workload from the one it is predicting.+ return True+async def persist_auto_triage(self, **fields: Any) -> None:"""Record the verdict without letting it stand in for the analyst's."""fields["auto_closed"] = Falsediff --git a/services/agents/app/workers/triage_persistence.py b/services/agents/app/workers/triage_persistence.pyindex 8d069d0d9..641c65d7b 100644--- a/services/agents/app/workers/triage_persistence.py+++ b/services/agents/app/workers/triage_persistence.py@@ -144,6 +144,26 @@ class TriageWriter(Protocol):is declined."""+ @property+ def fires_playbooks(self) -> bool:+ """Whether a matched playbook may actually run from this triage.++ `alert_trigger.run_for_alert` was called unconditionally, so a replay+ of last month's alerts would have **fired this month's playbooks** --+ real notifications, real tickets, real containment previews -- against+ rows a grader was only meant to score.+ """++ @property+ def uses_dedup_cache(self) -> bool:+ """Whether a cached production verdict may answer for this alert.++ The cost governor returns `Decision.DEDUPLICATED` with a verdict from+ a live cache. Accepting one during a replay grades the cache rather+ than the agent, and the figure that comes out is a measurement of+ something that already happened.+ """+async def persist_auto_triage(self, **fields: Any) -> None:"""Write the verdict to the ledger and the ``alerts`` row.@@ -282,6 +302,28 @@ class LiveTriageWriter:def persists_cost(self) -> bool:return True+ @property+ def fires_playbooks(self) -> bool:+ """Whether a matched playbook may actually run from this triage.++ `alert_trigger.run_for_alert` was called unconditionally, so a replay+ of last month's alerts would have **fired this month's playbooks** --+ real notifications, real tickets, real containment previews -- against+ rows a grader was only meant to score.+ """+ return True++ @property+ def uses_dedup_cache(self) -> bool:+ """Whether a cached production verdict may answer for this alert.++ The cost governor returns `Decision.DEDUPLICATED` with a verdict from+ a live cache. Accepting one during a replay grades the cache rather+ than the agent, and the figure that comes out is a measurement of+ something that already happened.+ """+ return True+async def persist_auto_triage(self, **fields: Any) -> None:await ledger_module.persist_auto_triage(**fields)diff --git a/services/agents/tests/test_replay_measures_the_real_run.py b/services/agents/tests/test_replay_measures_the_real_run.pynew file mode 100644index 000000000..ee47dfd0d--- /dev/null+++ b/services/agents/tests/test_replay_measures_the_real_run.py@@ -0,0 +1,232 @@+"""Replay and shadow mode record what happened, not a placeholder.++Fix pass items 3.4, 3.6 and 3.12. See `plans/aisoc_fix_pass_plan.plan.md`.++Three figures that were structurally unable to be right+-------------------------------------------------------+**3.4 Model attribution.** `fused_alert_consumer` stamps a shadow decision+with `model=_opt_text(getattr(state, "model_used", None))`. `InvestigationState`+has 33 fields and none of them is `model_used`, so that `getattr` default is+the only branch that ever runs: **every shadow decision records a null model**,+and per-model agreement -- the whole point of recording it -- is empty on every+deployment.++**3.6 Tool calls.** The replay runner sets `decision.tool_calls = 0` under a+comment saying it is "recorded so a future change that gives triage a tool+shows up here as a number moving off zero". A literal zero can never move off+zero. The intent in the comment and the code contradict each other.++**3.12 Pivot counting.** `_classify_pivots` treats a result as a pivot unless+its preview contains `available: false`. A tool that raised returns+`{"error": "..."}` from the registry wrapper, which has no `available` key, so+**a failed call counts as a pivot** and an investigation can reach its depth+floor on four tools that all threw.++What this file asserts+----------------------+The real functions, with the real shapes they are handed in production. No+mock stands between the assertion and the thing being measured, because in all+three cases the thing being measured is a single arithmetic or attribute step+and a mock of it would be the test asserting its own input.+"""++from __future__ import annotations++import pytest+++class TestPivotsCountOnlySuccessfulCalls:+ """3.12 -- a failed call is not a pivot."""++ def test_a_tool_that_raised_is_not_counted_as_a_pivot(self) -> None:+ """The registry wrapper's shape, verbatim.++ `app/tools/registry.py` returns `{"error": f"{type(exc).__name__}: {exc}"}`+ when a tool raises. It has no `available` key, so the pre-fix+ classifier put it in `pivots`.+ """+ from app.investigator.deep_investigation import _classify_pivots++ trace = [+ {"tool": "lake_process_activity", "result_preview": "{'error': 'TimeoutError: '}"},+ {"tool": "lake_network", "result_preview": '{"error": "ConnectError: refused"}'},+ ]++ pivots, unavailable = _classify_pivots(trace)++ assert pivots == [], f"a failed call was counted as a pivot: {pivots}"+ assert sorted(unavailable) == ["lake_network", "lake_process_activity"]++ def test_an_unavailable_tool_is_still_not_a_pivot(self) -> None:+ """The case that already worked, so the fix cannot regress it."""+ from app.investigator.deep_investigation import _classify_pivots++ pivots, unavailable = _classify_pivots([{"tool": "siem_search", "result_preview": "{'available': False, 'reason': 'no backend'}"}])++ assert pivots == []+ assert unavailable == ["siem_search"]++ def test_a_successful_call_is_a_pivot(self) -> None:+ """The negative control. A classifier that called everything a failure+ would satisfy both assertions above."""+ from app.investigator.deep_investigation import _classify_pivots++ pivots, unavailable = _classify_pivots(+ [{"tool": "lake_process_activity", "result_preview": "{'available': True, 'rows': [{'host': 'WS-42'}]}"}]+ )++ assert pivots == ["lake_process_activity"]+ assert unavailable == []++ def test_depth_cannot_be_reached_on_failures_alone(self) -> None:+ """Why this matters, stated as the property rather than the mechanism.++ Four tools that all threw must not look like four pivots, or an+ investigation reports the depth it was required to reach while having+ learned nothing.+ """+ from app.investigator.deep_investigation import _classify_pivots++ trace = [{"tool": f"tool_{n}", "result_preview": "{'error': 'RuntimeError: boom'}"} for n in range(4)]++ pivots, _ = _classify_pivots(trace)++ assert len(set(pivots)) == 0, f"four failed calls produced {len(set(pivots))} distinct pivots"+++def _state(**extra):+ """A minimally valid state. Only `incident_id` is required."""+ import uuid++ from app.models.state import InvestigationState++ return InvestigationState(incident_id=uuid.uuid4(), tenant_id=uuid.uuid4(), **extra)+++class TestTheStateCarriesTheModelThatAnswered:+ """3.4 -- a shadow decision must name the model it came from."""++ def test_investigation_state_has_a_field_for_the_model_used(self) -> None:+ """`getattr(state, "model_used", None)` is read by the shadow writer.++ Pre-fix the field does not exist, so the default is the only branch+ that runs and every shadow decision records a null model.+ """+ from app.models.state import InvestigationState++ assert "model_used" in InvestigationState.model_fields, (+ "InvestigationState has no `model_used`, so the shadow writer's `getattr(state, 'model_used', None)` can only ever be None"+ )++ def test_a_state_round_trips_the_model_it_was_given(self) -> None:++ state = _state(model_used="aisoc-triage")++ assert state.model_used == "aisoc-triage"++ def test_a_state_with_no_model_records_none_rather_than_a_guess(self) -> None:+ """The negative control. A default of `"unknown"` would make the+ column non-null and useless; absence has to stay legible."""++ assert _state().model_used is None+++class TestToolCallsAreCountedRatherThanAsserted:+ """3.6 -- the number has to be able to move."""++ def test_the_runner_does_not_assign_a_literal_zero(self) -> None:+ """Read as source deliberately, and this is the one place that is right.++ The defect is not a wrong value -- zero is the correct answer today,+ because shadow mode declines escalation and escalation is the only+ stage that calls tools. The defect is that the comment above it says+ the figure is "recorded so a future change that gives triage a tool+ shows up here as a number moving off zero", and a literal can never+ move. There is no runtime behaviour to assert against, because the+ current correct answer and the hardcoded answer are the same number;+ what can be asserted is that the figure is derived.+ """+ import inspect++ from app.replay import runner++ source = inspect.getsource(runner)++ assert "decision.tool_calls = 0" not in source, (+ "tool_calls is assigned a literal, so the comment's promise that it "+ "will move off zero when triage gains a tool cannot come true"+ )++ def test_the_count_comes_from_the_ledger(self) -> None:+ from app.replay import runner++ assert hasattr(runner, "_tool_calls_recorded"), "no helper derives the tool-call count, so nothing reads what actually happened"++ @pytest.mark.parametrize(+ ("rows", "expected"),+ [([], 0), ([{"kind": "tool_call"}], 1), ([{"kind": "tool_call"}, {"kind": "llm_response"}], 1)],+ )+ def test_only_tool_call_rows_are_counted(self, rows: list[dict], expected: int) -> None:+ """Counting every ledger row would report the LLM calls as tool calls."""+ from app.replay.runner import _tool_calls_recorded++ assert _tool_calls_recorded(rows) == expected+++class TestAReplayHasNoSideEffects:+ """3.2 -- two of the four leaks the plan names.++ The other two were already closed: `ShadowTriageWriter.persists_cost` is+ `False` so the cost ledger is not written, and every write method returns+ the "nothing happened" value its live counterpart returns on a no-op.++ These two were not, because neither reaches the worker through the writer:+ `alert_trigger.run_for_alert` was called unconditionally, and the cost+ governor's `DEDUPLICATED` branch answered from a live cache. Both now ask+ the writer, which is the same mechanism the other two already used.+ """++ def test_the_replay_writer_declines_both(self) -> None:+ from app.replay.shadow import ShadowTriageWriter++ writer = ShadowTriageWriter()++ assert writer.fires_playbooks is False, "a replay of last month's alerts would fire this month's playbooks"+ assert writer.uses_dedup_cache is False, "a replay graded on a cached production verdict measures the cache, not the agent"++ def test_the_live_writer_still_does_both(self) -> None:+ """The negative control. A fix that declined these everywhere would+ turn playbooks and deduplication off in production."""+ from app.workers.triage_persistence import LiveTriageWriter++ writer = LiveTriageWriter()++ assert writer.fires_playbooks is True+ assert writer.uses_dedup_cache is True++ def test_shadow_mode_withholds_playbooks_but_keeps_deduplication(self) -> None:+ """Shadow mode is measuring, not replaying, so the two differ.++ A playbook that ran would be the agent acting on a verdict nobody has+ accepted, which is what the mode exists to withhold. Deduplication is+ production behaviour, and turning it off would make the scorecard+ describe a different workload from the one it predicts.+ """+ from app.workers.shadow_mode import ShadowModeTriageWriter++ writer = ShadowModeTriageWriter.__new__(ShadowModeTriageWriter)++ assert writer.fires_playbooks is False+ assert writer.uses_dedup_cache is True++ def test_the_protocol_declares_both(self) -> None:+ """The protocol, not three separate classes.++ A writer added later that forgets one fails against the+ protocol, which is how the three existing writers were found when+ these two members were added.+ """+ from app.workers.triage_persistence import TriageWriter++ for name in ("fires_playbooks", "uses_dedup_cache"):+ assert hasattr(TriageWriter, name), f"the writer protocol does not declare {name}"