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
Eval honesty wave: serving-model attribution, full-cohort closure accounting, conservative correlation fallback (#1581)
Beenu Aroraf840cbe2a665
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex ba434e1db..de7645de7 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -105,9 +105,14 @@ jobs:set -euo pipefailspine_paths='services/ingest/ services/fusion/ services/realtime/ docker-compose.yml scripts/integration/ .github/workflows/integration.yml'- migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/fusion/tests/test_asset_context_live.py services/fusion/app/services/asset_context.py .github/workflows/integration.yml'- migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/api/tests/test_alert_rail_business_context_live.py services/api/app/services/alert_rail.py services/agents/tests/test_business_context_tenant_rules_live.py services/agents/app/workers/business_context.py .github/workflows/integration.yml'- migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py services/api/tests/test_alert_queue_priority_live.py services/api/app/services/alert_queue.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py .github/workflows/integration.yml'+ # One assignment, deliberately. Three parallel lanes each appended+ # their live-test paths as a fresh `migration_paths=` line, and in+ # shell the last assignment wins silently — so two lanes' filter+ # entries (the asset-context live leg, then the business-context+ # rail legs) were inert: their live tests only ran when something+ # *else* in the surviving list changed. This is the union of all+ # three lists; the next lane extends it rather than re-assigning.+ migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/fusion/tests/test_asset_context_live.py services/fusion/app/services/asset_context.py services/api/tests/test_alert_rail_business_context_live.py services/api/app/services/alert_rail.py services/agents/tests/test_business_context_tenant_rules_live.py services/agents/app/workers/business_context.py services/api/tests/test_alert_queue_priority_live.py services/api/app/services/alert_queue.py .github/workflows/integration.yml'# backup_crypt.py was missing from the old filter, and it is where# every byte of the AES-256-GCM implementation lives — so a change# to the encryption itself did not run the gate that proves the@@ -1028,6 +1033,67 @@ jobs:# condition is on the steps instead, so the expensive half — a Postgres, an# S3 endpoint, a full dump-and-restore — is skipped when the diff touches# none of it, and the verdict still arrives.+ fusion-redis-live:+ # The fusion correlator and the windowed engine's claim protocol, against+ # a real Redis. Both have in-memory doubles in the unit suite, and both+ # rest on properties only the server has: `SET NX` deciding exactly one+ # winner between concurrent creators, TTL-driven window expiry, and the+ # owner-checked claim scripts. A single-threaded double passes those by+ # construction — the more-capable-than-reality shape — so the suites at+ # services/fusion/tests/integration/ existed and ran in no workflow,+ # which is the other recurring shape: a live suite that is decoration+ # until something sets its env var. This job is that something. The+ # Kafka/Postgres-legged tests in the same directory skip here, visibly,+ # and run under the spine job's full stack instead.+ name: Fusion correlator + windowed claims (live Redis)+ needs: changes+ if: needs.changes.outputs.spine == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ services:+ redis:+ image: redis:7-alpine+ ports:+ - 6379:6379+ options: >-+ --health-cmd "redis-cli ping"+ --health-interval 5s+ --health-timeout 3s+ --health-retries 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.11'+ cache: pip++ # The service's committed lock, not a hand-picked closure. This job+ # runs the whole tests/integration/ suite, and the install-parity gate+ # is right to hold a whole-suite run to the lock: a tiny closure+ # re-resolves inside the declared ranges, so the versions it grades+ # need not be the versions services/fusion/Dockerfile installs — and a+ # missing optional dependency (clickhouse-driver) silently grades the+ # `except ImportError` fallback where production grades the real path.+ - name: Install fusion's locked dependency set+ run: |+ set -euo pipefail+ python3 -m venv $RUNNER_TEMP/.venv-fusion+ python3 scripts/service_requirements.py fusion --locked > /tmp/fusion.lock.txt+ $RUNNER_TEMP/.venv-fusion/bin/pip install --quiet --disable-pip-version-check --no-deps -r /tmp/fusion.lock.txt++ - name: Correlator + windowed claims against the real server+ working-directory: services/fusion+ env:+ AISOC_TEST_REDIS: redis://127.0.0.1:6379/0+ run: |+ set -euo pipefail+ $RUNNER_TEMP/.venv-fusion/bin/python -m pytest tests/integration/ -q -p no:cacheprovider 2>&1 | tee /tmp/fusion-live.log+ # A run in which everything skipped is a configuration failure+ # wearing a green tick — the one outcome this job must refuse.+ grep -Eq "[1-9][0-9]* passed" /tmp/fusion-live.log \+ || { echo "::error::no live fusion test actually ran — the Redis leg is misconfigured"; exit 1; }+backup-restore:name: Backup → destroy → restore (Postgres via S3)runs-on: ubuntu-latestdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1da3a80dd..3f93888bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,84 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Serving-model attribution, end to end.** Every published verdict-eval+ row had `resolved_models: []` — 72 calls placed, answered, and+ unattributable, because the only serving-identity reader was the LiteLLM+ gateway header and the measured runs talked to an OpenAI-compatible+ endpoint directly. The extractor now reads the gateway header first+ (*verified*) and the response body's own `model` second+ (*self-reported*), credited only with evidence it came from the body —+ langchain falls back to the requested name when the body carries none,+ and a requested alias is never copied into serving metadata. Scorecards+ carry a `provenance_status` (`verified` / `self_reported` /+ `unattributed` / `serving_mismatch` / `no_calls`); a live run whose+ serving identity mismatches the requested model is refused as that+ model's performance and preserved as a diagnostic; the benchmark table+ gained an Attribution column with the five historical rows reading+ "unverified" rather than receiving invented attribution; and a measured+ auto-closure precision can no longer be bound to a call whose serving+ model no party vouched for — a clearing measurement over an unattributed+ call now **blocks** instead of authorising.++- **Full-cohort and closure accounting in the replay scorer.** Selective+ malicious recall silently dropped errored cases from its denominator; the+ scorer now also publishes full-cohort recall over every labelled+ malicious case with the four buckets that sum to it (caught, abstained,+ errored, answered-as-negative), the four proposed-closure cuts+ (malicious closure rate, closure contamination, benign closure coverage,+ unknown-label share — `closures_executed` pinned at zero because replay+ executes nothing), request reliability as five visible counts+ (requested / attempted / completed / failed / unattempted), per-severity+ segments, and per-source attribution counts.++- **The reflex path reports its stages and its decision contract.**+ Auto-triage summaries, logs and replay decisions now carry named stage+ timings (queue delay, business context, context fetch, decide,+ verification, persist, escalate, approvals, writeback) plus a structured+ decision contract — verdict, operational disposition, supporting and+ contradictory decisive claims, groundedness, missing prerequisites, and+ the escalation reason — assembled from signals that already ran, with+ `None` for a signal that never ran rather than an empty list pretending+ the check happened.++- **Retro-hunt rehearsal mode.** `RETRO_HUNT_DRY_RUN` runs every sweep+ exactly as live (the warehouse scan still consumes the tenant's sweep+ budget) and withholds every mutation at the write boundary inside+ `sweep_tenant`: matches come back as recorded proposals, no alert opens,+ no sighting row lands, and the dedup branch leaves its counters+ untouched — so a re-hunt can be rehearsed over history with no ability+ to touch production state.++- **A live-Redis proof for the correlator, and the suite that was wired to+ nothing.** `integration.yml` gains a `fusion-redis-live` job (keyed on+ the existing spine filter) running `services/fusion/tests/integration/`+ against a real server — window expiry, tenant boundaries, restart+ continuity, per-rule fallback grouping and concurrent-creator+ convergence — which also gives the windowed engine's claim-protocol+ suite its first workflow. An all-skipped run is refused rather than+ green.++- **The verdict model matrix.** `run_model_matrix.py --task verdict`+ grades the balanced corpus per model through `run_verdict_eval.py`+ (still a thin collator defining no scoring), records each row's+ configuration — pins, endpoint, prompt provenance, corpus digest,+ provenance status, serving models — and the runtime in+ comparable-but-unidentifying terms, and renders the constant-answer+ baselines beside the table. The committed verdict scorecard gained the+ deterministic-fallback baseline row: balanced accuracy exactly at the+ 0.250 constant floor, zero of 36 malicious cases caught — the rules+ floor every measured model is read against.++- **An annotated unsupported-claim measurement.** Sixteen hand-annotated+ (rationale, evidence, label) cases measure `score_claim_support` with an+ exactly-pinned confusion matrix (TP 7, FP 0, FN 1, TN 8), a recorded+ known miss that must stay missed until the pins move with it, and the+ annotation-independence limit stated where the number lives. The+ measurement found and drove a real detector fix: the claim pattern+ recognised "scheduled scan" while the support keys did not, so an alert+ whose evidence recorded `scheduled_scan` could state the claim and still+ be refused support.+- **Agentmetry ingest template: AI coding-agent activity as an input**(GitHub Discussion #1577). [Agentmetry](https://github.com/blitzcrieg1/agentmetry)records the tool calls Claude Code, Cursor, Codex and Copilot make through@@ -97,6 +175,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0SLO-exempt with its reason, and its status filter is pinned against thecase table's own CHECK constraint by test.+### Changed++- **A missing identifier narrows the correlation group instead of widening+ it.** Neither detection engine has ever emitted `mitre_tactics` (the+ ruleset carries technique ids only), so every detection alert's+ correlation key fell back to the literal `unknown` tactic and all of an+ entity's detection alerts collapsed into one incident per window;+ entity-less alerts merged tenant-wide. The fallback now scopes to the+ detection rule with an entity, never groups across rules without one,+ and groups only exact fingerprint repeats with no identifiers at all.+ Measured on a fixed detection-shaped cohort: 42.6 % reduction with 36+ cross-rule incident groups before, 24.5 % with zero after — the honest+ direction, because the difference was unrelated alerts counted as+ grouped. The tactic-carrying headline cohort is unchanged at 33.3 %. The+ correlator's creation race is closed with `SET NX` (concurrent first+ arrivals converge on one incident instead of orphaning an alert); the+ narrower merge/merge window is documented, not closed.++- **Verdict scorecards disclose the model-knowledge limit.** Evidence+ cutoffs constrain supplied context only; each scorecard now records the+ model's training cutoff when the operator states one and `unknown`+ otherwise, with the disclosure that pretrained weights may postdate the+ replayed events.+### Fixed- **The rail's business-context leg reads the event the writer actuallydiff --git a/FEEDBACK_EVAL_PROGRESS.md b/FEEDBACK_EVAL_PROGRESS.mdnew file mode 100644index 000000000..26f73ea4a--- /dev/null+++ b/FEEDBACK_EVAL_PROGRESS.md@@ -0,0 +1,77 @@+# Feedback-eval hardening — progress tracker++Session-scratch progress file for the community-feedback brief (reflex behaviour, retrospective+analysis, precision/recall, alert reduction, evidence references, model suitability).+This file is session scratch: it tracks lane state so interrupted work can resume.++- Branch: `feat/feedback-eval-hardening` (its own worktree of the shared git dir)+- Base: `origin/main` @ `828ff9c5` (PR #1575 merge; #1576 in history; #1578 expected to merge mid-task — re-fetch+merge before finalizing)+- Constraints: NO push / NO merge / NO PR — local commits only. Never enable model-driven auto-closure.+- Sibling lane: bizctx (PR #1578) owns services/fusion confidence.py+asset_context.py+fusion_engine.py,+ services/actions approval_rules/dispatcher/approval_gate + api vendored copy — expect conflicts there; combine, never take one side.+- Throwaway Postgres (mine): `feedback-pg` on 55435 (bizctx-pg on 55434 is NOT mine).++## Phase status++- [x] §1 Baseline audit + gap table (in final report)+- [x] §2 Model attribution provenance + decision safeguards (attribution module; eligibility binds measurements to attributed serving identity; scorecard provenance_status + refuse-to-advertise on serving_mismatch; benchmark table Attribution column)+- [x] §3 Stage timings + queue delay + decision contract on worker/replay/logs+- [x] §4 Retro-hunt dry-run mode at the write boundary; model-knowledge disclosure on scorecards (freeze machinery pre-existing, verified)+- [x] §5 Full-cohort recall + 4 closure cuts + reliability counts + per-severity in scorer; deterministic baseline row published+- [x] §6 Conservative fallback key (before 42.6%/36 cross-rule → after 24.5%/0); SET NX creation race fixed; live-Redis suite + CI job+- [x] §7 --task verdict matrix + runtime/config records; live rows NOT MEASURED (no project credential; harness tooling key deliberately not spent)+- [x] §8 Annotated claim-support measurement (TP7 FP0 FN1 TN8 pinned; found+fixed scheduled_scan support-key gap); bundles/ledger verified pre-existing+- [x] §9 benchmark.md (attribution column + mechanism + third reduction figure), CHANGELOG, gates green, main merged (#1578 combined)+- [x] §10 Final report delivered in session summary++## Notes / decisions++(append below)++### Done so far+- app/core/model_attribution.py: gateway_header > response_body (id-witness guard against langchain requested-name fallback); never copies requested alias. run_provenance_status: verified/self_reported/unattributed(:partial)/serving_mismatch/no_calls.+- cost_telemetry: CallRecord/CostTracker/CostSummary carry attribution_source + system_fingerprint; summary exports attribution_sources.+- replay runner: decisions carry attribution_sources + severity.+- aisoc_benchmark/replay.py: full-cohort malicious recall (+4 bucket counts), 4 closure metrics (proposed-only, executed pinned 0), requested/attempted/completed/failed/unattempted, per_severity segment, attribution aggregation + renderer sections.+- eligibility: ELIGIBLE requires model_attribution; BLOCKED('cannot be bound') otherwise; decision carries model_attribution. auto_triage passes serving identity; basis line serving_model=...; exchange records serving_model/attribution/system_fingerprint.+- run_verdict_eval: provenance_status + advertisable_as_model_performance + attribution_sources on scorecard; exit 2 on live serving_mismatch (scorecard still written as diagnostic); requested_total threaded.+- check_verdict_quality: Attribution column; serving_mismatch rows refused; historical rows render 'unverified (recorded before per-decision attribution existed)'; benchmark block regenerated.++### Key audit findings (for final gap table)+- fusion: build_alert (stateless detection_engine.py:326-355 + windowed_detection.py:893-918) never sets mitre_tactics; rules carry techniques only (no tactic key in any of 760+1770+76 rules); correlation_key falls to {tenant}:{entity}:unknown and entity-less to {tenant}:unknown:unknown (tenant-wide collapse). Correlator GET-then-SET race, index-TTL vs incident-TTL asymmetry. Incidents Redis-only.+- retro-hunt: full subsystem exists (workers/retro_hunt_consumer.py + services/retro_hunt/); idempotent via UNIQUE sighting + alert idempotency key; occurrence vs intel time separated; NO dry-run/eval mode; never links original decisions.+- eligibility recorded pre-resolution alias (fixed this session: serving identity now).+- run_model_matrix records no sampling/context/hardware (§7 todo).+- measure_triage_reliability.py REPAIRED since withdrawal (imports registry; test imports it).++### Final state+- Merged origin/main @ df369dfd (#1578) combining CHANGELOG sides; all suites green post-merge: fusion 1058, agents 2193, api 5022, benchmark 101, root gates OK.+- Containers: feedback-redis (63790) can be removed; feedback-pg never needed.++### Residual gaps recorded from the full audit-leg reports (post-delivery addendum)++Confirmed by the completed exploration legs after the main report; none alters a+shipped change, all belong on the unresolved-limitations record:++- `ModelRouter`/`build_router` and `cost_aware_cascade` (app/routing/) have zero+ production callers — dynamic stronger-model escalation is static gateway+ config today; the "exists unwired" shape, recorded not fixed.+- `sources_from_ledger` (copilot_grounding.py) is implemented and tested with no+ production caller, so copilot citations validate against console-supplied+ context only, never immutable tenant-scoped ledger rows.+- `evidence_completeness` (app/eval/agent_quality.py) is a real measure wired+ into run_evals with **no corpus declaring `expected_evidence`** — it honestly+ renders "no referent"; reference completeness therefore remains unmeasured+ (the new annotated corpus measures unsupported-claim rate, a different axis).+- Retro-hunt sightings record `feed_source` + `intel_first_seen_at` but no+ intelligence-version/catalog-version identifier.+- Replay's time axis is `closed_at` (analyst close) with context stores cut on+ recorded times — a reasonable occurrence-vs-availability proxy, not explicit+ ingestion-time modelling (retro-hunt models the distinction; replay proxies it).+- Policy rows carry no version column; closure decisions persist source ++ threshold + reason, not a policy revision id. Eligibility's full provenance+ dict reaches the ledger as a rendered basis string, not structured columns.+- Closed this addendum: scorecards now record the production-pinned sampling+ block (temperature/max_tokens/json_mode), imported from the reliability+ harness so three surfaces share one declaration; the verdict matrix carries+ it per row.diff --git a/ROADMAP.md b/ROADMAP.mdindex 3b7081b86..47e75c6fa 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **330 rows — 325 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **334 rows — 329 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/benchmark.md b/apps/docs/docs/benchmark.mdindex 7a58b7a5a..ed703cf3f 100644--- a/apps/docs/docs/benchmark.md+++ b/apps/docs/docs/benchmark.md@@ -119,14 +119,15 @@ refused.Corpus: **72 items** in **36 twin pairs** (`verdict_corpus_v1`, digest `sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86`). Twins share title, rule, severity, vendor and technique and differ only in the evidence, so severity alone separates nothing and a constant answer scores at most **0.250**. Hand-authored and synthetic: no recorded customer telemetry is involved.-| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed |-|---|---|---|---|---|---|---|---|-| `llama3.2:3b-instruct-q4_K_M` | live | 0.285 | 0.047 | 0.250 / 36 | 0.000 | 0.000 | 72 |-| `llama3.1:8b-instruct-q4_K_M` | live | 0.357 | 0.209 | 0.583 / 36 | 0.000 | 0.000 | 72 |-| `llama3:8b` | live | 0.279 | 0.113 | 0.639 / 36 | 0.000 | 0.000 | 72 |-| `qwen2.5:7b-instruct-q4_K_M` | live | 0.260 | 0.032 | 0.083 / 36 | 0.097 | 0.000 | 72 |-| `mistral:7b-instruct-v0.3-q4_K_M` | live | 0.210 | 0.202 | 0.639 / 36 | 0.306 | 0.000 | 72 |-| `any hosted provider (GPT-4o class)` | – | not measured — no funded key exists in this repository, and no hosted provider has ever been exercised | – | – | – | – | 0 |+| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed | Attribution |+|---|---|---|---|---|---|---|---|---|+| `llama3.2:3b-instruct-q4_K_M` | live | 0.285 | 0.047 | 0.250 / 36 | 0.000 | 0.000 | 72 | unverified (recorded before per-decision attribution existed) |+| `llama3.1:8b-instruct-q4_K_M` | live | 0.357 | 0.209 | 0.583 / 36 | 0.000 | 0.000 | 72 | unverified (recorded before per-decision attribution existed) |+| `llama3:8b` | live | 0.279 | 0.113 | 0.639 / 36 | 0.000 | 0.000 | 72 | unverified (recorded before per-decision attribution existed) |+| `qwen2.5:7b-instruct-q4_K_M` | live | 0.260 | 0.032 | 0.083 / 36 | 0.097 | 0.000 | 72 | unverified (recorded before per-decision attribution existed) |+| `mistral:7b-instruct-v0.3-q4_K_M` | live | 0.210 | 0.202 | 0.639 / 36 | 0.306 | 0.000 | 72 | unverified (recorded before per-decision attribution existed) |+| `deterministic fallback (no model)` | deterministic | 0.250 | 0.000 | 0.000 / 36 | 0.000 | – | 0 | no calls |+| `any hosted provider (GPT-4o class)` | – | not measured — no funded key exists in this repository, and no hosted provider has ever been exercised | – | – | – | – | 0 | – |Malicious recall prints the count behind it: a rate over 36 cases is a different claim from the same rate over four, and the figure alone cannot say which. Every measured row placed the model calls shown in the last column; a row that placed none is refused rather than published, because triage answers from a deterministic scorer when a provider fails and the resulting scorecard looks entirely normal.@@ -166,11 +167,25 @@ The 3B ran CPU-bound inside the stack container and the four 7–8B rows ranGPU-accelerated on the host, so the figures measure different machines.Dropping the column would have hidden that asymmetry instead of naming it.-**Per-decision model attribution is unverified.** Every run placed the model-calls shown and every call was answered — the reasoning in each decision is-specific to its alert — but `resolved_models` came back empty, so the-scorecard can show that 72 calls happened and cannot show which model served-each one. The count is measured; the attribution is not.+**Per-decision model attribution: unverified for the rows above, mechanised+for every run after them.** Those five runs placed the model calls shown and+every call was answered, but `resolved_models` came back empty — the serving+identity reader only knew the LiteLLM gateway header, and these runs talked+to an OpenAI-compatible endpoint directly. The serving model was in the+response body the whole time; nothing read it. The extractor now reads both,+most-authoritative first: the gateway's `x-litellm-model-name` header+(**verified** — the party that routed the call speaking), else the response+body's own `model` field (**self_reported** — the endpoint naming itself),+credited only when there is evidence it came from the body rather than from+langchain's fallback to the requested name, which is never copied into+serving metadata. Every new scorecard carries a `provenance_status` —+`verified` / `self_reported` / `unattributed` / `serving_mismatch` /+`no_calls` — and the Attribution column above renders it; a `serving_mismatch`+run is refused as any model's row outright, and the five historical rows keep+their honest "unverified" rather than receiving invented attribution. The+same identity now gates autonomy: a measured auto-closure precision cannot be+bound to a call whose serving model no party vouched for+(`services/agents/app/confidence/eligibility.py`).**No hosted provider has ever been exercised.** The hosted row reads *notmeasured* rather than `0`, because a zero in an accuracy column says the@@ -204,7 +219,8 @@ every PR targeting `main` or `develop`.| Suite | Metric | Per-case | Per-template macro | Target | What it checks ||--------------------------------|-------------------------|------------|------------------------|---------|----------------|-| Alert reduction (product logic) | reduction | 33.3 % | _n/a_ | 20–95 % | **The number that describes AiSOC.** Groups a noisy 1 000-alert stream with `RawAlert.correlation_key()` — the method `Correlator` actually calls |+| Alert reduction (product logic) | reduction | 33.3 % | _n/a_ | 20–95 % | **The number that describes AiSOC** on tactic-carrying alerts. Groups a noisy 1 000-alert stream with `RawAlert.correlation_key()` — the method `Correlator` actually calls |+| Alert reduction (detection-shaped) | reduction | 24.5 % | _n/a_ | pinned exactly | The same real key over alerts shaped like the detection engines' output (rule_id, **no tactics**), with zero cross-rule merges — see below for the before/after || Alert reduction (legacy suite) | reduction | 75.3 % | _n/a_ | ≥ 70 % | A four-tier scheme implemented inside the test. Retained for continuity; **does not describe this product** — see below || MITRE ATT&CK tactic accuracy | accuracy | 97.0 % | 96.4 % (n=55) | ≥ 80 % | Substrate self-consistency — keyword extractor vs. dataset written for it || Investigation completeness | mean keyword coverage | 94.2 % | 94.3 % (n=55) | ≥ 85 % | Substrate self-consistency — report template wraps the description; judge finds keywords from the description |@@ -239,6 +255,32 @@ Both numbers stay published. Deleting the old one would make the historyunreadable; presenting it without this note would be the thing this pageexists to prevent.+**There is now a third figure, and the story behind it is a fixed defect.**+The 33.3 % stream carries a MITRE tactic on every alert, and no detection+engine in this product has ever emitted one — the ruleset carries technique+ids only — so every *detection* alert's key fell back to the literal+`unknown` tactic and all of an entity's detection alerts collapsed into one+incident per window, whatever the rule or kill-chain stage. Alerts with no+entity merged **tenant-wide**. The fallback now narrows instead of widening+(same entity + no tactic groups per detection rule; no entity never groups+across rules), and the same `test_alert_reduction_real.py` measures a+detection-shaped cohort — 1,000 alerts, `rule_id` set, no tactics, ~4 %+entity-less — before and after on the identical stream:++| Cohort | Before | After |+|---|---|---|+| Incidents | 574 | 755 |+| Reduction | 42.6 % | **24.5 %** |+| Incident groups spanning more than one rule | 36 | **0** |++The reduction went **down**, and that is the honest direction: the+difference was unrelated alerts being counted as grouped, and review-work+reduction is only worth having over groups that are actually related. A+reader comparing reduction figures should also ask what else travels with+them — which malicious evidence a merged group buries is the companion+question, and the grouped-purity row (zero cross-rule groups) is this+page's answer for the detection cohort.+> The synthetic telemetry suite is a **schema/coverage gate**, not a scoring> suite, so it does not appear in the table. It checks that every incident has> ≥ 1 backing event, that all `{user}/{host}/{ip}/{campaign}` placeholdersdiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 878c98759..dca7d1fb4 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 325 rows+The last row is the one worth reading first. It is the honest index: 329 rows`GATED`, 5 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is whydiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 867d7631d..02e634863 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -220,7 +220,6 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The agents service requests the MCP registry at a path the API service serves | `services/agents/app/mcp/registry_client.py` | `ci.yml` agents job (`test_mcp_registry_client.py::test_the_registry_url_matches_where_the_route_is_mounted`: the app mount, the v1 router prefix and the endpoint router prefix are read out of the API service's own source with `ast` and composed the way the service composes them, then compared against the URL the client builds. Proven able to fail by emptying `API_PREFIX`, which names both the requested path and the served set) | core | GATED | The same defect D16 records: Phase 1.2 shipped a client missing `/api/v1`, so every request would have 404'd while three suites stayed green, because the test asserted the URL the code produced rather than the URL the service serves. This service cannot import that one, so reading the other tree's source is the only comparison in the direction that drifts || No MCP tool AiSOC ships can perform a response action; the action tool is dry-run only | `services/mcp/README.md` (Actions are previewed, never performed); `apps/docs/docs/integrations/mcp.md` | `ci.yml :: mcp` (`tests/actions.test.ts`: the **source** of `services/mcp/src/` is read and no string may name `/live-actions/dispatch`, so a second action tool added later is caught rather than only the one under test; the preview handler is driven against a recording client and asserted to make exactly one request, to the dry-run path, carrying `dry_run: true`; and its strict schema is asserted to reject a caller-supplied `dry_run: false`. Proven able to fail by pointing the module constant at the dispatch path, which reds both the source scan and the request assertion) | core | GATED | The enforcing control is upstream: `POST /api/v1/live-actions/dry-run` forces `dry_run: true` server-side whatever the body says and proxies only that path. This row is the second lock, on the side an agent can see, because an MCP key is credential material that lives in an editor's configuration file || Every tool AiSOC's MCP server publishes carries honest behaviour annotations | `services/mcp/README.md` (Tools exposed); `apps/docs/docs/integrations/mcp.md` (Annotations, and what is read-only) | `ci.yml :: mcp` (`tests/actions.test.ts`: every tool in `ALL_TOOLS` must declare `readOnlyHint` as a boolean rather than leaving it absent, no tool may be annotated destructive, and the set of tools annotated **not** read-only is pinned to exactly `aisoc_run_investigation`, so a future write tool cannot arrive annotated read-only and a read tool cannot drift into looking state-changing) | core | GATED | The annotations are what a client reads to decide whether it may call a tool at all. AiSOC's own MCP client refuses a tool whose server sets `destructiveHint: true` or `readOnlyHint: false`, and treats an absent annotation as no claim, so a server publishing nothing forces every operator to vouch for every tool by name |-| Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate. Phase 3 adds a second, harder corpus at incident level (`test_injection_incidents.py`) whose payloads are written to fit the field they arrive in, enforcing a floor, a ceiling and an exact ratchet naming every current blind spot by id | core | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate. The two corpora measure the same guard and are **not comparable**: one asks whether the guard recognises a string, the other whether it recognises it where an attacker can put it, and the second scores materially lower. Neither measures a model || An investigation can read the vendor a tenant actually runs, not just CrowdStrike and Okta | `plans/aisoc_gap_closure_plan.plan.md` (4.2); `services/actions/app/live_actions/investigation_reads.py` | `ci.yml` actions job (`test_investigation_reads_phase4.py`, 25 tests over seven new executors against vendor-shaped synthetic payloads on the real HTTP path. Each verb is tested for the pair that must never collapse: a host or principal the vendor does not hold is `SUCCEEDED` with `found: False`, a vendor that 5xxs is `FAILED`, and a failed read is asserted to carry **no** `count`, `detections` or `found` key, because a `count: 0` reaching a model is the strongest exonerating evidence there is and would be false. Entra's licensed risk leg may fail without taking the sign-ins down and reads as unknown rather than as no risk; Google Workspace's 403 names the missing `admin.reports.audit.readonly` scope rather than reporting an account with no logins) + `ci.yml` gates job (`check_action_contract.py`, 79 executors, and `check_capability_mirror` comparing the actions vocabulary against the connectors `Capability` enum in both directions) | core | GATED | Five of the seven are new vendor arms on the three existing read verbs, so they inherit the `READ_ONLY` contract and cannot drift low; only `lookup_cloud_audit` and `lookup_endpoint_telemetry` needed their own entry. **No call in this repository has been made against a live vendor** for any of them: there is no funded CrowdStrike, SentinelOne, Entra, Google Workspace, Defender or AWS account here, so the wire shapes are pinned against the vendors' published schemas and the live path is unverified, which the docs state rather than imply || A caller of a vendor read never supplies query text; the executor owns the query | `plans/aisoc_gap_closure_plan.plan.md` (4.1, 4.2); `services/actions/app/clients/defender_client.py` (`_HUNT_TEMPLATES`) | `ci.yml` actions job (`test_investigation_reads_phase4.py`: `lookup_endpoint_telemetry` is offered four rejected inputs including a bare KQL pipeline, a template name with a statement appended and a case variation, and each is refused **before the credential is read** with a route asserted uncalled, so a refused template cannot reach the vendor; the accepted path is asserted on the KQL that reaches the wire rather than on the argument, with a hostile indicator carrying a quote and a pipe appearing only in its escaped form; the window and row cap are asserted at 720h and 200 against a caller asking for 99,999h and 10,000 rows. Entra's OData literal is asserted the same way, with the doubled quote present and the single-quote form absent) | core | GATED | The escaping is grammar-specific and each grammar is handled at its own boundary: KQL escapes backslash and double quote, OData doubles a single quote, and the CloudTrail attribute key is checked against AWS's own closed vocabulary rather than escaped at all. A new vendor grammar needs its own escape and its own test; nothing structurally forces that beyond review || AWS CloudTrail is read without adding boto3 to a CORE service | `services/actions/app/clients/aws_cloudtrail_client.py`; [ADR-0007](../decisions/0007-connectors-and-actions-in-core.md) | `ci.yml` actions job (`test_investigation_reads_phase4.py`: the SigV4 canonical request is pinned line by line against the documented shape, including the blank line between canonical and signed headers and the body hash as the final line; `SignedHeaders` is parsed back out of the `Authorization` header the client produced and every name in it asserted present on the request, which is the failure mode of a hand-rolled signer; the signing-key derivation is asserted sensitive to secret, date **and** region in turn, so a dropped link in the chain cannot pass as a plausible hex string; a session token is asserted both signed and sent. `canonical_parts` is the function `_authorization` itself calls, so the test is not comparing a producer against a copy of itself) | core | GATED | **The live AWS path is unverified.** There is no funded AWS account in this repository, so what is gated is that the algorithm matches the specification and that the response parsing and projection work against a recorded payload. A signature that AWS itself accepts has not been observed. boto3 is deliberately not added: it is not in the `aisoc-actions` image (measured: `ModuleNotFoundError`, against 1.43.101 in `aisoc-connectors`) and ADR-0007 has just published that image at 539 MB |@@ -338,11 +337,16 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The platform-wide kill switch can actually be engaged, and an engaged one stops automatic closure and action dispatch | `docs/remediation/kill-switch-reachability.md`; `services/api/migrations/123_kill_switch_global_engageable.sql`; parity 2.2 | `kill-switch-live.yml :: The platform-wide stop can be engaged, and stops closure` (real Postgres, every migration applied, driven as the NOSUPERUSER NOBYPASSRLS `aisoc_app` role because the migration owner is a superuser and ignores policies even under FORCE ROW LEVEL SECURITY — the job fails if the DSN resolves to a role that can bypass, and the suite refuses to run against one, because seeding the global row as the owner is the workaround that hid this for 45 migrations. 25 cases across three suites: the global row is writable by an unbound session and by nothing else, a tenant cannot write the global row or another tenant's row or another tenant's audit row, an unbound session cannot write into any tenant, the real routes write the row end to end through the real ASGI app, a tenant_admin and an analyst are both refused 403 while the tenant switch still works for them, and `resolve_closure_policy` refuses a 0.99 verdict against a 0.50 bar with source=kill_switch for a tenant that engaged nothing itself) + `ci.yml :: Python — Tests` (api `test_kill_switch.py`, the global routes resolve their handler, require `platform_kill_switch:write` read off the resolved dependency tree rather than the handler source, and take the unbound session) + `action-durability-live.yml :: One approval, one vendor call, or an honest unknown` (real Postgres; the step *An engaged kill switch stops the dispatcher, and a released one does not* asserts both directions, and *The gate fails when dispatch stops consulting the switch* is the negative control, which refuses to run if it cannot find the line it removes) | core | GATED | Before this the global row had no writer at all: every write in the endpoint module bound the caller's tenant, so no endpoint, console control, CLI or script could set `tenant_id IS NULL`, while two readers consulted it on every alert. **There is still no console control for the kill switch in either scope** — both are API-only. **An engaged switch now stops action dispatch as well as closure**: the check sits in `live_actions.dispatch()` before the executor is resolved, which covers the actions dispatcher and playbook dispatch, since playbook steps reach a vendor through that one chain. Dry runs are stopped too, and an unreadable switch refuses rather than dispatching. The fourth point the module docstring claimed — the MCP write tools — was corrected rather than implemented, because no such write surface exists || Inside `services/agents`, an alert can be closed automatically from exactly one statement, and that statement asks permission first | `docs/remediation/phase-1-closure-authorization.md`; `services/agents/app/closure/authorization.py` | `ci.yml :: python-lint` (`check_closure_authorization.py`, plus its `--self-test`: only `investigator/ledger.py` may carry SQL that can set an alert to `'resolved'`, and the function holding it must call `authorize_auto_closure`. It reads the AST and considers only string constants that are not docstrings, because four files in this change quote that SQL in prose and a gate that fires on documentation gets switched off within a week; the self-test proves it stays silent on a docstring and a comment and fires on both the literal and `CASE ... THEN` forms) + `ci.yml` agents job (`test_closure_authorization.py` — default-deny for a tenant with no policy row, refusal when the pool is unavailable *and* when it is unconfigured, refusal for a non-closeable verdict, a shadow run and ungrounded reasoning, and an enumeration of every module that reaches the durable write) | core | GATED | The structural property and the offline behaviour are gated on every pull request. That the SQL then does what the gate assumes is the row below, and it is not gated per-PR. **The claim is scoped to `services/agents` because the gate is**: `services/connectors` closes a CVE-promotion alert of its own making through `RESOLVE_REMEDIATED_SQL` when every affected asset is patched — a deterministic, tenant-scoped lifecycle rule rather than an autonomous verdict, out of scope for this phase and named here so the row is not read as a product-wide claim || Every automatic closure of a production alert is checked against the current policy, grant and stop controls at the moment the row changes | `docs/remediation/phase-1-closure-authorization.md`; `services/agents/app/investigator/ledger.py` | `agent-auth-live.yml` (`tests/isolation/test_closure_authorization_live.py` — real Postgres with every migration applied, the real `persist_auto_triage`, the real `app.closure` modules and the real worker method for the outcome-memory path. Fifteen tests: no explicit policy does not close, an explicit one still does, a disabled policy and an unearned grant block, the memory and cached tiers are governed, a changed policy invalidates an earlier authorization, one tenant's policy cannot authorize another's, global and per-tenant stop controls, shadow leaves the analyst's columns alone, and an unauthorized verdict is still recorded as `triaged`. The code under test connects as the runtime role so RLS is in force; a superuser would ignore every policy and let the cross-tenant assertions pass for the wrong reason) | core | PARTIAL | The suite is wired into `agent-auth-live.yml` and **has been observed green on a CI runner** — 15 passed in the job `A service credential reaches the API and is scoped to one tenant` on this pull request — as well as locally against PostgreSQL 16, where 12 of the 15 fail on the pre-fix tree with the alert sitting at `resolved`. It is PARTIAL rather than GATED for one remaining reason: that run graded the pull request's merge ref, and the job has not yet run on `main`, so "the gate works" and "a future pull request cannot regress it" are still separate claims until the push-to-`main` run exists. Returns to GATED in the change that observes this job green on `main`. Two narrower gaps stay named in the remediation document: the global kill-switch row is uninsertable by the runtime role because of its own `WITH CHECK`, so the suite seeds it as the owner and the *write* path for that switch is not covered here; and the `"default"` tenant-placeholder resolution is governed by the same chokepoint but is never exercised with a live multi-tenant ambiguity |+| Every verdict scorecard names who vouched for the serving model, and a run that cannot be attributed to the model it requested is never published as that model's performance | `apps/docs/docs/benchmark.md` (Attribution column + "mechanised for every run after them") | `ci.yml :: Python — Tests` (agents `test_model_attribution.py` — gateway header outranks response body, an equal name with no `id` witness is refused so the requested alias is never copied into serving metadata, and `run_provenance_status` resolves verified / self_reported / unattributed / serving_mismatch / no_calls; `test_autonomy_eligibility.py::test_a_measurement_cannot_authorise_an_unattributed_serving_identity` and `test_auto_triage_autonomy_eligibility.py::test_a_measurement_cannot_bind_to_an_unattributed_call` — a clearing measured-performance row BLOCKS over a call no party attributed, proven at the production entry point with the positive control beside it) + `ci.yml :: Python — Lint & Type-check` (`check_verdict_quality.py --check` refuses a `serving_mismatch` row outright and renders historical rows as "unverified" rather than backfilling them) | core | GATED | — |+| The replay scorer accounts for every evaluated input: full-cohort malicious recall keeps errored and abstained cases in its denominator with buckets that sum to it, the four closure cuts are published over proposed closures with executed pinned at zero, and requested/attempted/completed/failed/unattempted are five visible counts | `apps/docs/docs/benchmark.md`; `packages/aisoc-benchmark/aisoc_benchmark/replay.py` | `ci.yml :: Python — Tests` (Benchmark harness step: `packages/aisoc-benchmark/tests/test_replay_cohort_metrics.py` — hand-verifiable TP/FP/FN/TN over a mixed cohort, full-cohort recall ≠ selective recall when a malicious case errored, malicious closure rate / closure contamination / benign closure coverage / unknown-label share with their denominators, no-proposed-closures renders not-measured rather than zero, and the renderer must say "proposed" and "executed: 0") | core | GATED | — |+| A missing correlation identifier narrows the group instead of widening it: detection alerts (which carry no tactic) group per rule on an entity, never across rules without one, and concurrent first-arrivals for one key converge on one incident | `apps/docs/docs/benchmark.md` ("There is now a third figure"); `services/fusion/app/models/alert.py` | `ci.yml :: Python — Service unit tests (fusion, honeytokens, purple-team)` (`test_alert_reduction_real.py::test_detection_shaped_stream_reduction_and_purity` — the detection-shaped cohort's 24.5 % pinned exactly, zero incident-groups spanning more than one rule, and group sizes summing to the stream so nothing vanishes; `test_alert_model.py` pins the fallback key shapes) + `integration.yml :: fusion-redis-live` (the real Correlator against a real Redis: window expiry, tenant boundary, restart continuity, per-rule fallback through the production path, and ten concurrent creators converging on one incident under `SET NX` — the job refuses an all-skipped run, and the same leg is the first workflow ever to run the windowed engine's claim-protocol live suite) | core | GATED | the merge/merge read-modify-write window is documented in the suite rather than closed; closing it takes an owner-checked script like the windowed engine's |+| A retro-hunt can be rehearsed over history with mutations withheld at the write boundary: dry-run sweeps run exactly as live (and still consume the sweep budget, because the scan happened) while matches come back as recorded proposals — no alert opens, no sighting row lands, no dedup counter moves | `services/api/app/services/retro_hunt/service.py`; `RETRO_HUNT_DRY_RUN` in `services/api/app/core/config.py` | `ci.yml :: Python — Tests` (api `test_retro_hunt.py` — `test_dry_run_records_the_proposal_and_writes_nothing` and `test_dry_run_does_not_mutate_an_existing_sighting` against a write-spying session, with `test_a_real_sweep_still_opens_the_alert` as the negative control proving the same sweep without the flag adds both rows) | core | GATED | — |+| The unsupported-claim detector gating auto-closure is measured, not merely asserted: a 16-case hand-annotated corpus pins its confusion matrix exactly in both directions, with the known miss recorded by id | `services/agents/app/confidence/claim_support.py`; `services/agents/tests/test_claim_support_measured.py` | `ci.yml :: Python — Tests` (agents `test_claim_support_measured.py` — TP 7 / FP 0 / FN 1 / TN 8 pinned exactly so a new miss and a new catch both fail until the pins move in the same commit; the recorded miss must stay missed or the test names the promotion; the zero-false-positive set covers negation, evidence-anchored approval and first-party context support — the analyst language production cannot afford to flag. The measurement found and drove a real fix: the MAINTENANCE claim pattern knew "scheduled scan" while the support keys did not) | core | GATED | regression-grade, stated in the corpus itself: the annotator authored the cases and had read the detector, so this is the tuned-corpus rate; an audit-grade rate needs cases authored by someone who has not read the patterns |## Summary-- Total: 330-- GATED: 325+- Total: 334+- GATED: 329- PARTIAL: 5- NO GATE: 0diff --git a/docs/evaluation/verdict_scorecard.json b/docs/evaluation/verdict_scorecard.jsonindex 524600c60..d337188a4 100644--- a/docs/evaluation/verdict_scorecard.json+++ b/docs/evaluation/verdict_scorecard.json@@ -1,165 +1,182 @@{- "baselines_note": "Four classes, so a constant answer scores 0.250 balanced accuracy and 0.500 plain accuracy. Both are stated beside the table because a score is only readable against the thing it has to beat.",- "commit": "f92e8bcd",- "comparability": [- "All five rows graded the same corpus digest through the same production triage path, 72 model calls each, zero provider errors.",- "Latency is NOT comparable across rows and is excluded from the decision: the 3B ran CPU-bound inside the stack container and the four 7-8B rows ran GPU-accelerated on the host. Kept per row so the asymmetry is stated rather than hidden.",- "resolved_models came back empty on every decision of every run, so per-decision model attribution is unverified even though the calls were placed and answered. The count of calls is measured; the attribution is not.",- "auto_close_precision rests on 7 to 37 candidates depending on the row. Those are small denominators and the column should be read as a warning sign, not as a ranking."- ],- "corpus": {- "classes": {- "benign": 18,- "benign_true_positive": 10,- "false_positive": 8,- "true_positive": 36- },- "constant_answer_ceiling": 0.25,- "digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "items": 72,- "majority_class_plain_accuracy": 0.5,- "name": "verdict_corpus_v1",- "pairs": 36+ "baselines_note": "Four classes, so a constant answer scores 0.250 balanced accuracy and 0.500 plain accuracy. Both are stated beside the table because a score is only readable against the thing it has to beat.",+ "commit": "f92e8bcd",+ "comparability": [+ "All five rows graded the same corpus digest through the same production triage path, 72 model calls each, zero provider errors.",+ "Latency is NOT comparable across rows and is excluded from the decision: the 3B ran CPU-bound inside the stack container and the four 7-8B rows ran GPU-accelerated on the host. Kept per row so the asymmetry is stated rather than hidden.",+ "resolved_models came back empty on every decision of every run, so per-decision model attribution is unverified even though the calls were placed and answered. The count of calls is measured; the attribution is not.",+ "auto_close_precision rests on 7 to 37 candidates depending on the row. Those are small denominators and the column should be read as a warning sign, not as a ranking."+ ],+ "corpus": {+ "classes": {+ "benign": 18,+ "benign_true_positive": 10,+ "false_positive": 8,+ "true_positive": 36},- "default_model": "llama3.2:3b-instruct-q4_K_M (CPU) / llama3.1:8b-instruct-q4_K_M (GPU, host-LLM)",- "default_rationale": "Chosen strictly by balanced accuracy, the metric this corpus was built to make meaningful. llama3.1:8b-instruct-q4_K_M leads at 0.357 against the 3B's 0.285 and a 0.250 constant-answer floor, and also leads on MCC (0.209), malicious precision (0.724) and calibration (ECE 0.349, the only row below 0.40). It therefore becomes the default on the GPU and host-LLM overlays. The 3B stays the default for CPU `make up`, where a ~5 GB model does not fit the 8 GB CORE budget -- a deployment constraint, not a score. Two findings outrank the ranking. First, every model measured is far closer to chance than to useful: the best balanced accuracy is 0.357 against a 0.250 floor, and three of five score below the 0.500 plain accuracy of always guessing the majority class. Second, auto-close precision is poor across the board -- 0.571 on seven candidates at best, 0.091 to 0.243 elsewhere -- so nothing measured here supports autonomous closure, and that is a finding about the auto-close gate rather than about which model to pick.",- "entries": [- {- "abstention_rate": 0.0,- "auto_close_considered": 7,- "auto_close_precision": 0.5714285714285714,- "balanced_accuracy": 0.28541666666666665,- "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "corpus_items": 72,- "decisions_errored": 0,- "expected_calibration_error": 0.441667,- "false_negatives": 27,- "hallucination_rate": 0.0,- "headline_accuracy": 0.3194444444444444,- "llm_calls_placed": 72,- "malicious_precision": 0.5,- "malicious_recall": 0.25,- "malicious_support": 36,- "matthews_corrcoef": 0.046864498582862235,- "measured_at": "2026-10-10",- "mode": "live",- "model": "llama3.2:3b-instruct-q4_K_M",- "note": "Retained for CPU `make up`: a ~5 GB 8B does not fit the 8 GB CORE budget alongside the rest of the stack.",- "role": "shipped default (CPU profile)",- "served_on": "CPU, in-stack container",- "time_to_verdict_p50_ms": 11188.0,- "total_tokens": 70983- },- {- "abstention_rate": 0.0,- "auto_close_considered": 9,- "auto_close_precision": 0.1111111111111111,- "balanced_accuracy": 0.35694444444444445,- "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "corpus_items": 72,- "decisions_errored": 0,- "expected_calibration_error": 0.348611,- "false_negatives": 15,- "hallucination_rate": 0.0,- "headline_accuracy": 0.4583333333333333,- "llm_calls_placed": 72,- "malicious_precision": 0.7241379310344828,- "malicious_recall": 0.5833333333333334,- "malicious_support": 36,- "matthews_corrcoef": 0.20863951686663296,- "measured_at": "2026-10-11",- "mode": "live",- "model": "llama3.1:8b-instruct-q4_K_M",- "note": "Best balanced accuracy, MCC, malicious precision and calibration of everything measured.",- "role": "winner (GPU / host-LLM profiles)",- "served_on": "GPU, host Ollama",- "time_to_verdict_p50_ms": 1698.0,- "total_tokens": 74495- },- {- "abstention_rate": 0.0,- "auto_close_considered": 11,- "auto_close_precision": 0.09090909090909091,- "balanced_accuracy": 0.2791666666666667,- "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "corpus_items": 72,- "decisions_errored": 0,- "expected_calibration_error": 0.420833,- "false_negatives": 13,- "hallucination_rate": 0.0,- "headline_accuracy": 0.4166666666666667,- "llm_calls_placed": 72,- "malicious_precision": 0.6571428571428571,- "malicious_recall": 0.6388888888888888,- "malicious_support": 36,- "matthews_corrcoef": 0.11329558957744541,- "measured_at": "2026-10-10",- "mode": "live",- "model": "llama3:8b",- "note": "Previous-generation llama3. Superseded by llama3.1:8b on every metric except malicious recall, where they tie.",- "role": "candidate",- "served_on": "GPU, host Ollama",- "time_to_verdict_p50_ms": 1546.0,- "total_tokens": 74808- },- {- "abstention_rate": 0.09722222222222222,- "auto_close_considered": 37,- "auto_close_precision": 0.24324324324324326,- "balanced_accuracy": 0.25972222222222224,- "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "corpus_items": 72,- "decisions_errored": 0,- "expected_calibration_error": 0.593846,- "false_negatives": 33,- "hallucination_rate": 0.0,- "headline_accuracy": 0.26153846153846155,- "llm_calls_placed": 72,- "malicious_precision": 0.75,- "malicious_recall": 0.08333333333333333,- "malicious_support": 36,- "matthews_corrcoef": 0.03241459519549664,- "measured_at": "2026-10-11",- "mode": "live",- "model": "qwen2.5:7b-instruct-q4_K_M",- "note": "Worst measured: catches 3 of 36 malicious cases and is the least calibrated of the five.",- "role": "candidate",- "served_on": "GPU, host Ollama",- "time_to_verdict_p50_ms": 1567.0,- "total_tokens": 77044- },- {- "abstention_rate": 0.3055555555555556,- "auto_close_considered": 14,- "auto_close_precision": 0.14285714285714285,- "balanced_accuracy": 0.2097222222222222,- "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",- "corpus_items": 72,- "decisions_errored": 0,- "expected_calibration_error": 0.366,- "false_negatives": 13,- "hallucination_rate": 0.0,- "headline_accuracy": 0.5,- "llm_calls_placed": 72,- "malicious_precision": 0.6571428571428571,- "malicious_recall": 0.6388888888888888,- "malicious_support": 36,- "matthews_corrcoef": 0.20247984364137678,- "measured_at": "2026-10-11",- "mode": "live",- "model": "mistral:7b-instruct-v0.3-q4_K_M",- "note": "Highest plain accuracy (0.500) and lowest balanced accuracy (0.210): it abstains on 31% of items, which flatters plain accuracy and is exactly what balanced accuracy exists to see through.",- "role": "candidate",- "served_on": "GPU, host Ollama",- "time_to_verdict_p50_ms": 2210.0,- "total_tokens": 93626- },- {- "measured": false,- "model": "any hosted provider (GPT-4o class)",- "not_measured_reason": "no funded key exists in this repository, and no hosted provider has ever been exercised"- }- ],- "generated_from": "scripts/run_verdict_eval.py",- "schema_version": "1.0"+ "constant_answer_ceiling": 0.25,+ "digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "items": 72,+ "majority_class_plain_accuracy": 0.5,+ "name": "verdict_corpus_v1",+ "pairs": 36+ },+ "default_model": "llama3.2:3b-instruct-q4_K_M (CPU) / llama3.1:8b-instruct-q4_K_M (GPU, host-LLM)",+ "default_rationale": "Chosen strictly by balanced accuracy, the metric this corpus was built to make meaningful. llama3.1:8b-instruct-q4_K_M leads at 0.357 against the 3B's 0.285 and a 0.250 constant-answer floor, and also leads on MCC (0.209), malicious precision (0.724) and calibration (ECE 0.349, the only row below 0.40). It therefore becomes the default on the GPU and host-LLM overlays. The 3B stays the default for CPU `make up`, where a ~5 GB model does not fit the 8 GB CORE budget -- a deployment constraint, not a score. Two findings outrank the ranking. First, every model measured is far closer to chance than to useful: the best balanced accuracy is 0.357 against a 0.250 floor, and three of five score below the 0.500 plain accuracy of always guessing the majority class. Second, auto-close precision is poor across the board -- 0.571 on seven candidates at best, 0.091 to 0.243 elsewhere -- so nothing measured here supports autonomous closure, and that is a finding about the auto-close gate rather than about which model to pick.",+ "entries": [+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 7,+ "auto_close_precision": 0.5714285714285714,+ "balanced_accuracy": 0.28541666666666665,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.441667,+ "false_negatives": 27,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.3194444444444444,+ "llm_calls_placed": 72,+ "malicious_precision": 0.5,+ "malicious_recall": 0.25,+ "malicious_support": 36,+ "matthews_corrcoef": 0.046864498582862235,+ "measured_at": "2026-10-10",+ "mode": "live",+ "model": "llama3.2:3b-instruct-q4_K_M",+ "note": "Retained for CPU `make up`: a ~5 GB 8B does not fit the 8 GB CORE budget alongside the rest of the stack.",+ "role": "shipped default (CPU profile)",+ "served_on": "CPU, in-stack container",+ "time_to_verdict_p50_ms": 11188.0,+ "total_tokens": 70983+ },+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 9,+ "auto_close_precision": 0.1111111111111111,+ "balanced_accuracy": 0.35694444444444445,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.348611,+ "false_negatives": 15,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.4583333333333333,+ "llm_calls_placed": 72,+ "malicious_precision": 0.7241379310344828,+ "malicious_recall": 0.5833333333333334,+ "malicious_support": 36,+ "matthews_corrcoef": 0.20863951686663296,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "llama3.1:8b-instruct-q4_K_M",+ "note": "Best balanced accuracy, MCC, malicious precision and calibration of everything measured.",+ "role": "winner (GPU / host-LLM profiles)",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1698.0,+ "total_tokens": 74495+ },+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 11,+ "auto_close_precision": 0.09090909090909091,+ "balanced_accuracy": 0.2791666666666667,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.420833,+ "false_negatives": 13,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.4166666666666667,+ "llm_calls_placed": 72,+ "malicious_precision": 0.6571428571428571,+ "malicious_recall": 0.6388888888888888,+ "malicious_support": 36,+ "matthews_corrcoef": 0.11329558957744541,+ "measured_at": "2026-10-10",+ "mode": "live",+ "model": "llama3:8b",+ "note": "Previous-generation llama3. Superseded by llama3.1:8b on every metric except malicious recall, where they tie.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1546.0,+ "total_tokens": 74808+ },+ {+ "abstention_rate": 0.09722222222222222,+ "auto_close_considered": 37,+ "auto_close_precision": 0.24324324324324326,+ "balanced_accuracy": 0.25972222222222224,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.593846,+ "false_negatives": 33,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.26153846153846155,+ "llm_calls_placed": 72,+ "malicious_precision": 0.75,+ "malicious_recall": 0.08333333333333333,+ "malicious_support": 36,+ "matthews_corrcoef": 0.03241459519549664,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "qwen2.5:7b-instruct-q4_K_M",+ "note": "Worst measured: catches 3 of 36 malicious cases and is the least calibrated of the five.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1567.0,+ "total_tokens": 77044+ },+ {+ "abstention_rate": 0.3055555555555556,+ "auto_close_considered": 14,+ "auto_close_precision": 0.14285714285714285,+ "balanced_accuracy": 0.2097222222222222,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.366,+ "false_negatives": 13,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.5,+ "llm_calls_placed": 72,+ "malicious_precision": 0.6571428571428571,+ "malicious_recall": 0.6388888888888888,+ "malicious_support": 36,+ "matthews_corrcoef": 0.20247984364137678,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "mistral:7b-instruct-v0.3-q4_K_M",+ "note": "Highest plain accuracy (0.500) and lowest balanced accuracy (0.210): it abstains on 31% of items, which flatters plain accuracy and is exactly what balanced accuracy exists to see through.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 2210.0,+ "total_tokens": 93626+ },+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 0,+ "auto_close_precision": null,+ "balanced_accuracy": 0.25,+ "hallucination_rate": null,+ "llm_calls_placed": 0,+ "majority_class_accuracy": 0.5,+ "malicious_recall": 0.0,+ "malicious_support": 36,+ "matthews_corrcoef": 0.0,+ "measured_at": "2026-10-31",+ "mode": "deterministic",+ "model": "deterministic fallback (no model)",+ "note": "The rules baseline the models must beat, measured through the same replay path (scripts/run_verdict_eval.py --deterministic). On this corpus the deterministic scorer answers benign to every item: balanced accuracy lands exactly on the 0.250 constant-answer floor, Matthews correlation is 0.0, and all 36 malicious cases are missed. Every alert it fails to close still routes to a human, which is the posture that makes this floor survivable.",+ "provenance_status": "no_calls"+ },+ {+ "measured": false,+ "model": "any hosted provider (GPT-4o class)",+ "not_measured_reason": "no funded key exists in this repository, and no hosted provider has ever been exercised"+ }+ ],+ "generated_from": "scripts/run_verdict_eval.py",+ "schema_version": "1.0"}diff --git a/packages/aisoc-benchmark/aisoc_benchmark/replay.py b/packages/aisoc-benchmark/aisoc_benchmark/replay.pyindex 3b3b12e11..ff3d1ad56 100644--- a/packages/aisoc-benchmark/aisoc_benchmark/replay.py+++ b/packages/aisoc-benchmark/aisoc_benchmark/replay.py@@ -198,11 +198,48 @@ class ReplayScore:graded: int = 0abstained: int = 0+ # ---- request reliability: five counts, nothing vanishes --------------+ #+ # `requested_total` is what the caller asked the run to grade — the corpus+ # size — and is `None` when the caller did not say, in which case+ # `unattempted` is unknown rather than zero. A run that stopped a third+ # of the way through must not publish a headline over the two-thirds it+ # never reached without the gap showing, and "failed" (triage refused or+ # crashed) is kept apart from "completed" because a failure that stops+ # the run cannot disappear from the headline.+ requested_total: int | None = None+ attempted: int = 0+ completed: int = 0+ failed: int = 0+ unattempted: int | None = None+# ---- the number an operator is deciding on ---------------------------malicious_support: int = 0malicious_recall: float | None = Nonemalicious_recall_ci: tuple[float, float] | None = Nonemalicious_precision: float | None = None++ # ---- the same recall over the full cohort -----------------------------+ #+ # `malicious_recall` above is *selective*: it is computed over labelled+ # decisions that did not error, so it answers "how good are the answers+ # it managed to give". A run that crashed on half the malicious cases+ # would quietly drop them from that denominator. The full-cohort figure+ # keeps every labelled malicious case — abstained, errored, all of it —+ # and the split of the misses is published as counts: an abstention or an+ # error retains the alert for a human (an operational safety outcome, not+ # a correct classification), while a malicious case answered with an+ # auto-closeable verdict reached nobody.+ malicious_support_full: int = 0+ malicious_recall_full_cohort: float | None = None+ malicious_abstained: int = 0+ malicious_errored: int = 0+ #: Malicious cases that stayed in front of a human: abstained + errored+ #: (both retain the alert) — distinct from caught, and from closed-away.+ malicious_reached_review: int = 0+ #: Malicious cases the agent answered with a non-malicious verdict. The+ #: dangerous direction: these reached nobody.+ malicious_closed_as_negative: int = 0#: Malicious cases the agent did not call malicious, as a count and a#: rate. Derivable from the confusion matrix and from `1 - recall`,#: and published as its own field anyway: a false negative is a@@ -260,6 +297,32 @@ class ReplayScore:auto_close_considered: int = 0auto_close_correct: int = 0auto_close_precision: float | None = None++ # ---- the four closure cuts, over *proposed* closures -------------------+ #+ # Replay executes nothing: every closure here is what the stated policy+ # *would have* closed, and `closures_executed` is pinned at zero so a+ # simulated closure can never read as a production outcome. Unlike+ # `auto_close_*` above (computed over labelled, answered decisions only),+ # the proposed-closure population spans every decision including the+ # unlabeled ones, because the unknown-label share among closures is one of+ # the four questions.+ #+ # * `malicious_closure_rate` — malicious items closed / all labelled+ # malicious (full cohort). The catastrophic direction, and a measured+ # 0.0 here is a counted zero, not an absence.+ # * `closure_contamination` — malicious closed / closures with known truth.+ # * `benign_closure_coverage` — benign-family items closed / all labelled+ # benign-family items ("benign-family" = the three non-malicious truth+ # classes). What the closure policy actually absorbs.+ # * `closure_unknown_share` — closures with no truth label / all closures.+ closures_proposed: int = 0+ closures_executed: int = 0+ malicious_closed_count: int = 0+ malicious_closure_rate: float | None = None+ closure_contamination: float | None = None+ benign_closure_coverage: float | None = None+ closure_unknown_share: float | None = None#: Share of labelled decisions the agent routed to a human instead of#: deciding. The same population as `abstention_rate`, named the way an#: operator sizing a queue thinks about it.@@ -286,6 +349,10 @@ class ReplayScore:hallucinated_examples: list[str] = field(default_factory=list)per_rule: list[SegmentScore] = field(default_factory=list)per_source: list[SegmentScore] = field(default_factory=list)+ #: Misses by severity. A miss on a critical alert and a miss on an info+ #: alert are different findings; one number for both hides the one that+ #: matters.+ per_severity: list[SegmentScore] = field(default_factory=list)# ---- cost and latency, reported not scored ---------------------------total_tokens: int = 0@@ -307,6 +374,13 @@ class ReplayScore:#: deterministic fallback when a provider is unreachable and a run that#: measured nothing otherwise looks entirely normal.llm_calls: int = 0+ #: Calls each attribution source vouched for, summed across decisions:+ #: ``{"gateway_header": n, "response_body": m}``. ``models`` says who+ #: served; this says on whose account, which is what separates *verified*+ #: attribution (the gateway spoke) from *self-reported* (the endpoint+ #: named itself) from none at all. The run-level provenance status is+ #: computed by the caller, which knows the requested model.+ attribution_sources: dict[str, int] = field(default_factory=dict)# ---- provenance ------------------------------------------------------bootstrap_resamples: int = BOOTSTRAP_RESAMPLES@@ -478,6 +552,7 @@ def score_replay(bootstrap_resamples: int = BOOTSTRAP_RESAMPLES,bootstrap_seed: int = BOOTSTRAP_SEED,auto_close_threshold: float = DEFAULT_AUTO_CLOSE_THRESHOLD,+ requested_total: int | None = None,) -> ReplayScore:"""Grade a replay run's decisions against the analysts' own labels.@@ -509,6 +584,19 @@ def score_replay(score.unlabeled = len(usable) - len(labelled)score.labelled = len(labelled)+ # ---- request reliability ----------------------------------------------+ #+ # `attempted` is what reached the grader; `requested_total` is what the+ # caller asked for, when it said. The difference is work the run never+ # reached — a partial run's gap, visible rather than silently absent. A+ # negative difference is a caller error and is clamped to the honest+ # reading (nothing unattempted) rather than published as negative work.+ score.requested_total = requested_total+ score.attempted = len(decisions)+ score.completed = len(usable)+ score.failed = len(errored)+ score.unattempted = max(0, requested_total - len(decisions)) if requested_total is not None else None+# Hallucination spans every decision that produced reasoning, answered or# not, and errored or not: an agent that invented an address before# failing has still invented it.@@ -543,6 +631,51 @@ def score_replay(score.time_to_verdict_p95_ms = score.p95_latency_msscore.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})score.llm_calls = sum(int(d.get("llm_calls") or 0) for d in decisions)+ attribution: dict[str, int] = {}+ for decision in decisions:+ for source, count in (decision.get("attribution_sources") or {}).items():+ attribution[str(source)] = attribution.get(str(source), 0) + int(count or 0)+ score.attribution_sources = dict(sorted(attribution.items()))++ # ---- the four closure cuts, over proposed closures ---------------------+ #+ # Spans every decision, including the unlabeled, because the unknown-label+ # share among closures is one of the four questions. Errored decisions+ # cannot be closures (a refusal retains the alert), and an abstention is+ # not in the closable verdict set, so neither needs excluding by hand.+ proposed = [+ d+ for d in decisions+ if not d.get("error") and d.get("verdict") in _AUTO_CLOSABLE_VERDICTS and float(d.get("confidence") or 0.0) >= auto_close_threshold+ ]+ score.closures_proposed = len(proposed)+ score.closures_executed = 0 # replay executes nothing, by construction+ known_truth = [d for d in proposed if d.get("labelled") and d.get("expected_disposition") in GRADED_DISPOSITIONS]+ malicious_closed = [d for d in known_truth if d.get("expected_disposition") == MALICIOUS]+ score.malicious_closed_count = len(malicious_closed)+ score.closure_contamination = _ratio(len(malicious_closed), len(known_truth))+ score.closure_unknown_share = _ratio(len(proposed) - len(known_truth), len(proposed))++ labelled_full = [d for d in decisions if d.get("labelled") and d.get("expected_disposition") in GRADED_DISPOSITIONS]+ malicious_full = [d for d in labelled_full if d.get("expected_disposition") == MALICIOUS]+ benign_family_full = [d for d in labelled_full if d.get("expected_disposition") != MALICIOUS]+ score.malicious_closure_rate = _ratio(len(malicious_closed), len(malicious_full))+ benign_closed = [d for d in known_truth if d.get("expected_disposition") != MALICIOUS]+ score.benign_closure_coverage = _ratio(len(benign_closed), len(benign_family_full))++ # ---- full-cohort malicious recall ---------------------------------------+ #+ # Over every labelled malicious case, errored included. Each case lands in+ # exactly one of four buckets — caught, abstained, errored, or answered+ # with a non-malicious verdict — and the buckets sum to the denominator,+ # so nothing vanishes.+ score.malicious_support_full = len(malicious_full)+ caught_full = sum(1 for d in malicious_full if not d.get("error") and d.get("verdict") == MALICIOUS)+ score.malicious_recall_full_cohort = _ratio(caught_full, len(malicious_full))+ score.malicious_errored = sum(1 for d in malicious_full if d.get("error"))+ score.malicious_abstained = sum(1 for d in malicious_full if not d.get("error") and _is_abstention(d))+ score.malicious_reached_review = score.malicious_abstained + score.malicious_errored+ score.malicious_closed_as_negative = len(malicious_full) - caught_full - score.malicious_reached_reviewif not labelled:score.headline_withheld_reason = (@@ -678,6 +811,7 @@ def score_replay(score.per_rule = _segment(labelled, "rule_id")score.per_source = _segment(labelled, "vendor")+ score.per_severity = _segment(labelled, "severity")return score@@ -710,6 +844,16 @@ def _ms(value: float | None) -> str:return "not measured" if value is None else f"{value:,.0f} ms"+def _attribution(score: ReplayScore) -> str:+ """Who vouched for the serving models, as per-source call counts."""+ if not score.attribution_sources:+ if score.llm_calls:+ return f"none of the {score.llm_calls} call(s) was attributed by any party"+ return "no call was placed, so there is nothing to attribute"+ parts = [f"{source}: {count}" for source, count in sorted(score.attribution_sources.items())]+ return f"{sum(score.attribution_sources.values())} of {score.llm_calls} call(s) attributed ({', '.join(parts)})"++def _models(score: ReplayScore) -> str:"""Which model answered, distinguishing the two ways of not knowing.@@ -736,9 +880,13 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None ="""lines: list[str] = ["# Replay evaluation", ""]+ unattempted = "unknown — the caller did not say how many were requested" if score.unattempted is None else str(score.unattempted)+ requested = "not stated" if score.requested_total is None else str(score.requested_total)lines += ["## What was graded","",+ f"- Requested: {requested}. Attempted: {score.attempted}. Completed: {score.completed}. "+ f"Failed: {score.failed}. Unattempted: {unattempted}",f"- Decisions replayed: {score.decisions}",f"- Carried an analyst label: {score.labelled}",f"- Unlabelled, excluded from accuracy: {score.unlabeled}",@@ -752,6 +900,24 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"- Recall, Wilson 95% interval: {_interval(score.malicious_recall_wilson)}",f"- Precision: {_pct(score.malicious_precision)}","",+ "## Full cohort",+ "",+ "Selective recall above is over answered-or-abstained labelled cases; a run",+ "that errored on a malicious case dropped it from that denominator. The",+ "full-cohort figure keeps every labelled malicious case. The buckets sum",+ "to the denominator, so nothing vanishes.",+ "",+ f"- Malicious cases, full cohort: {score.malicious_support_full}",+ f"- Recall, full cohort: {_pct(score.malicious_recall_full_cohort)}",+ f"- Abstained (retained for a human): {score.malicious_abstained}",+ f"- Errored (retained for a human): {score.malicious_errored}",+ f"- Reached review one way or the other: {score.malicious_reached_review}",+ f"- Answered with a non-malicious verdict (reached nobody): {score.malicious_closed_as_negative}",+ "",+ "An abstention or an error retains the alert — an operational safety",+ "outcome, not a correct classification, and it is counted as a miss in",+ "both recall figures.",+ "","## Headline accuracy","",]@@ -791,6 +957,16 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None ="rather than a zero, which would read as closing things and getting","them all wrong.","",+ "## Proposed closures",+ "",+ f"- Proposed: {score.closures_proposed}. Executed: {score.closures_executed} "+ "(replay executes nothing; every closure here is what the stated policy would have closed)",+ f"- Malicious closure rate: {_pct(score.malicious_closure_rate)} "+ f"({score.malicious_closed_count} of {score.malicious_support_full} labelled malicious)",+ f"- Closure contamination: {_pct(score.closure_contamination)} (malicious among closures with known truth)",+ f"- Benign closure coverage: {_pct(score.benign_closure_coverage)} (benign-family items the policy would absorb)",+ f"- Unknown-label share among closures: {_pct(score.closure_unknown_share)}",+ "","## Time to verdict","",f"- p50: {_ms(score.time_to_verdict_p50_ms)}",@@ -839,6 +1015,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =breakdowns: tuple[tuple[str, list[SegmentScore]], ...] = (("Per rule", score.per_rule),("Per source", score.per_source),+ ("Per severity", score.per_severity),)for title, segments in breakdowns:lines += ["", f"## {title}", "", "| Key | Answered | Accuracy | Malicious | Malicious recall |", "|---|---|---|---|---|"]@@ -861,6 +1038,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"p95 {'not measured' if score.p95_latency_ms is None else f'{score.p95_latency_ms:.0f} ms'}",f"- Model calls placed: {score.llm_calls}",f"- Models: {_models(score)}",+ f"- Attribution: {_attribution(score)}","","## Method","",diff --git a/packages/aisoc-benchmark/tests/test_replay_cohort_metrics.py b/packages/aisoc-benchmark/tests/test_replay_cohort_metrics.pynew file mode 100644index 000000000..d8126c9d3--- /dev/null+++ b/packages/aisoc-benchmark/tests/test_replay_cohort_metrics.py@@ -0,0 +1,228 @@+"""Full-cohort accounting: every evaluated input lands in exactly one bucket.++What these cover, and the defect each one blocks+------------------------------------------------+**Full-cohort malicious recall.** The selective ``malicious_recall`` is+computed over labelled decisions that did not error, so a run that *crashed*+on half the malicious cases silently dropped them from the denominator and+the published recall described the half it managed to answer. The full-cohort+figure keeps every labelled malicious case in its denominator — abstained,+errored, all of it — and the two are published side by side because they+answer different questions ("how good are its answers" vs "how much of the+threat landed somewhere safe").++**Closure accounting.** ``auto_close_precision`` answers "of what it would+have closed, how much was right" and nothing else. These four answer the+questions a buyer actually asks: how much of the malicious cohort would have+been closed (the catastrophic direction), how contaminated the closed pile is,+how much benign volume the closure actually absorbs, and how much of the+closed pile has no truth label at all. All are **proposed** closures — replay+executes nothing, and the score says so in its own fields.++**Request reliability.** ``requested / attempted / completed / failed /+unattempted`` as five visible counts, so a run that stopped a third of the way+through cannot publish a headline over the two-thirds it never reached without+the gap showing.+"""++from __future__ import annotations++from typing import Any++from aisoc_benchmark.replay import format_replay_report, score_replay++MALICIOUS = "true_positive"+FP = "false_positive"+BENIGN = "benign"+BTP = "benign_true_positive"+++def _decision(+ index: int,+ expected: str,+ verdict: str | None,+ *,+ confidence: float = 0.95,+ labelled: bool = True,+ error: str | None = None,+ severity: str = "high",+ attribution: dict[str, int] | None = None,+ llm_calls: int = 0,+) -> dict[str, Any]:+ return {+ "finding_id": f"F-{index:03d}",+ "vendor": "splunk",+ "rule_id": "rule-1",+ "closed_at": "2026-05-01T00:00:00+00:00",+ "expected_disposition": expected,+ "vendor_disposition": "disposition:1",+ "labelled": labelled,+ "verdict": verdict,+ "confidence": confidence,+ "tier": "llm",+ "findings": [],+ "confidence_basis": [],+ "evidence": {},+ "tokens": 0,+ "measured_usd": None,+ "estimated_usd": None,+ "unpriced_calls": 0,+ "latency_ms": 10,+ "resolved_models": [],+ "attribution_sources": attribution or {},+ "severity": severity,+ "llm_calls": llm_calls,+ "error": error,+ }+++# --------------------------------------------------------------------------+# Full-cohort malicious recall keeps errored and abstained cases+# --------------------------------------------------------------------------+++def test_full_cohort_recall_keeps_errored_malicious_in_the_denominator() -> None:+ """Ten malicious: 4 caught, 2 abstained, 2 called benign, 2 errored.++ Selective recall is over the 8 that did not error (4/8). Full-cohort+ recall is over all 10 (4/10), and the split of the other six is published+ as counts rather than vanishing.+ """+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(4)]+ rows += [_decision(10 + i, MALICIOUS, "needs_review") for i in range(2)]+ rows += [_decision(20 + i, MALICIOUS, BENIGN) for i in range(2)]+ rows += [_decision(30 + i, MALICIOUS, None, error="triage failed: boom") for i in range(2)]+ rows += [_decision(100 + i, FP, FP) for i in range(4)]++ score = score_replay(rows)++ assert score.malicious_support == 8 # selective: errored rows excluded+ assert score.malicious_recall == 4 / 8+ assert score.malicious_support_full == 10+ assert score.malicious_recall_full_cohort == 4 / 10+ assert score.malicious_abstained == 2+ assert score.malicious_errored == 2+ # Routed somewhere a human will look: abstentions and errors both retain+ # the alert. Misclassified-benign did NOT reach anyone — that is the+ # number the full-cohort view exists to surface.+ assert score.malicious_reached_review == 4+ assert score.malicious_closed_as_negative == 2+++def test_full_cohort_equals_selective_when_nothing_errored() -> None:+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(6)]+ rows += [_decision(100 + i, FP, FP) for i in range(4)]+ score = score_replay(rows)+ assert score.malicious_recall_full_cohort == score.malicious_recall == 1.0+ assert score.malicious_support_full == score.malicious_support == 6+++# --------------------------------------------------------------------------+# The four closure metrics, over proposed closures+# --------------------------------------------------------------------------+++def test_closure_metrics_report_all_four_cuts() -> None:+ """6 malicious (1 closed!), 8 benign-family (6 closed), 2 unlabeled closed.++ - malicious closure rate: 1/6 — the catastrophic direction.+ - contamination: among closures with known truth (7), 1 was malicious.+ - benign closure coverage: 6 of 8 benign-family items closed.+ - unknown share: 2 of 9 closures carry no truth label.+ """+ rows = [_decision(i, MALICIOUS, MALICIOUS, confidence=0.99) for i in range(5)]+ # The catastrophe: a malicious case the agent would have closed as benign.+ rows += [_decision(5, MALICIOUS, BENIGN, confidence=0.99)]+ rows += [_decision(10 + i, FP, FP, confidence=0.99) for i in range(3)]+ rows += [_decision(20 + i, BENIGN, BENIGN, confidence=0.99) for i in range(3)]+ # Benign-family items the agent escalated: not closed.+ rows += [_decision(30 + i, BTP, "needs_review") for i in range(2)]+ # Unlabeled items the agent would have closed.+ rows += [_decision(40 + i, "unlabeled", FP, confidence=0.99, labelled=False) for i in range(2)]++ score = score_replay(rows)++ assert score.closures_proposed == 9+ assert score.closures_executed == 0+ assert score.malicious_closure_rate == 1 / 6+ assert score.malicious_closed_count == 1+ assert score.closure_contamination == 1 / 7+ assert score.benign_closure_coverage == 6 / 8+ assert score.closure_unknown_share == 2 / 9+++def test_no_proposed_closures_reports_not_measured_not_zero() -> None:+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(3)]+ rows += [_decision(10 + i, FP, "needs_review") for i in range(3)]+ score = score_replay(rows)+ assert score.closures_proposed == 0+ assert score.closure_contamination is None+ assert score.closure_unknown_share is None+ # Malicious closure rate has a real denominator (3 malicious) and a true+ # zero numerator: nothing malicious was closed. That zero was counted.+ assert score.malicious_closure_rate == 0.0+++# --------------------------------------------------------------------------+# Request reliability: five counts, nothing vanishes+# --------------------------------------------------------------------------+++def test_reliability_counts_cover_every_requested_item() -> None:+ rows = [_decision(i, MALICIOUS, MALICIOUS) for i in range(4)]+ rows += [_decision(10, FP, FP), _decision(11, FP, None, error="triage failed: x")]+ score = score_replay(rows, requested_total=10)+ assert score.requested_total == 10+ assert score.attempted == 6+ assert score.completed == 5+ assert score.failed == 1+ assert score.unattempted == 4+++def test_unattempted_is_unknown_when_no_request_count_was_given() -> None:+ score = score_replay([_decision(0, MALICIOUS, MALICIOUS), _decision(1, FP, FP)])+ assert score.requested_total is None+ assert score.unattempted is None+++# --------------------------------------------------------------------------+# Attribution aggregation and per-severity segmentation+# --------------------------------------------------------------------------+++def test_attribution_sources_aggregate_across_decisions() -> None:+ rows = [+ _decision(0, MALICIOUS, MALICIOUS, attribution={"response_body": 1}, llm_calls=1),+ _decision(1, FP, FP, attribution={"response_body": 1}, llm_calls=1),+ _decision(2, FP, FP, llm_calls=1), # placed a call nobody attributed+ ]+ score = score_replay(rows)+ assert score.attribution_sources == {"response_body": 2}+ assert score.llm_calls == 3+++def test_per_severity_segments_are_reported() -> None:+ rows = [_decision(i, MALICIOUS, MALICIOUS, severity="critical") for i in range(2)]+ rows += [_decision(10 + i, MALICIOUS, BENIGN, severity="low") for i in range(2)]+ rows += [_decision(20 + i, FP, FP, severity="low") for i in range(2)]+ score = score_replay(rows)+ by_key = {segment.key: segment for segment in score.per_severity}+ assert by_key["critical"].malicious_recall == 1.0+ assert by_key["low"].malicious_recall == 0.0+++# --------------------------------------------------------------------------+# The renderer carries the new sections+# --------------------------------------------------------------------------+++def test_report_renders_full_cohort_and_closure_sections() -> None:+ rows = [_decision(i, MALICIOUS, MALICIOUS, confidence=0.99) for i in range(3)]+ rows += [_decision(10 + i, FP, FP, confidence=0.99) for i in range(3)]+ report = format_replay_report(score_replay(rows, requested_total=6))+ assert "Full cohort" in report+ assert "Proposed closures" in report+ assert "requested" in report.lower()+ # Proposed, never executed: the report says so in words.+ assert "proposed" in report.lower()+ assert "executed: 0" in report.lower()diff --git a/scripts/check_verdict_quality.py b/scripts/check_verdict_quality.pyindex 423e72217..16e3ee8db 100644--- a/scripts/check_verdict_quality.py+++ b/scripts/check_verdict_quality.py@@ -114,10 +114,38 @@ def validate_entry(entry: dict[str, Any]) -> None:"one thing this gate exists to refuse.")+ if entry.get("provenance_status") == "serving_mismatch":+ raise VerdictQualityError(+ f"{name}: the scorecard records provenance_status=serving_mismatch — what answered the "+ "calls is not the model this row names. The scorecard is a valid diagnostic; a table row "+ "under the requested model's name is a false attribution, and it is refused."+ )+if entry.get("balanced_accuracy") is None:raise VerdictQualityError(f"{name}: measured row carries no balanced_accuracy")+def _attribution_cell(entry: dict[str, Any]) -> str:+ """How the row's serving identity is known, or that it is not.++ A scorecard recorded before attribution existed carries no+ ``provenance_status`` and renders as **unverified** — the historical fact+ about those runs, never backfilled. A new scorecard carries the status its+ run earned (``verified`` from a gateway header, ``self_reported`` from the+ endpoint's own body, ``unattributed`` when calls were placed and nobody+ named the server). ``serving_mismatch`` never reaches this cell, because+ :func:`validate_entry` refuses the row outright.+ """+ status = entry.get("provenance_status")+ if not status:+ if entry.get("mode") == "deterministic":+ return "no calls"+ return "unverified (recorded before per-decision attribution existed)"+ if status == "no_calls":+ return "no calls"+ return str(status)++def render_table(scorecard: dict[str, Any]) -> str:"""Render the published block from the committed scorecard."""entries: list[dict[str, Any]] = list(scorecard.get("entries") or [])@@ -138,8 +166,8 @@ def render_table(scorecard: dict[str, Any]) -> str:f"**{_fmt(corpus.get('constant_answer_ceiling'))}**. Hand-authored and synthetic: ""no recorded customer telemetry is involved.","",- "| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed |",- "|---|---|---|---|---|---|---|---|",+ "| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed | Attribution |",+ "|---|---|---|---|---|---|---|---|---|",]for entry in entries:@@ -149,10 +177,10 @@ def render_table(scorecard: dict[str, Any]) -> str:# One spanning cell, not six copies of the same phrase: a reader# scanning the column must not see something that parses as a# score. The reason sits where the first number would.- lines.append(f"| {name} | – | {NOT_MEASURED} — {reason} | – | – | – | – | 0 |")+ lines.append(f"| {name} | – | {NOT_MEASURED} — {reason} | – | – | – | – | 0 | – |")continuelines.append(- "| {model} | {mode} | {ba} | {mcc} | {recall} | {abst} | {halluc} | {calls} |".format(+ "| {model} | {mode} | {ba} | {mcc} | {recall} | {abst} | {halluc} | {calls} | {attr} |".format(model=name,mode=entry["mode"],ba=_fmt(entry.get("balanced_accuracy")),@@ -165,6 +193,7 @@ def render_table(scorecard: dict[str, Any]) -> str:abst=_fmt(entry.get("abstention_rate")),halluc=_fmt(entry.get("hallucination_rate")),calls=entry.get("llm_calls_placed") or 0,+ attr=_attribution_cell(entry),))diff --git a/scripts/run_model_matrix.py b/scripts/run_model_matrix.pyindex 186302a2a..95c5a6766 100644--- a/scripts/run_model_matrix.py+++ b/scripts/run_model_matrix.py@@ -29,6 +29,7 @@ from __future__ import annotationsimport argparseimport jsonimport os+import platformimport subprocessimport sysimport tempfile@@ -38,6 +39,7 @@ from typing import AnyREPO_ROOT = Path(__file__).resolve().parent.parentRUN_EVALS = REPO_ROOT / "scripts" / "run_evals.py"+RUN_VERDICT_EVAL = REPO_ROOT / "scripts" / "run_verdict_eval.py"#: Roles the pin override has to cover. Setting only one leaves the other#: agents on their default model, which would make the matrix a comparison@@ -45,6 +47,24 @@ RUN_EVALS = REPO_ROOT / "scripts" / "run_evals.py"PIN_ROLES = ("triage", "investigation", "report", "recon")+def runtime_record() -> dict[str, Any]:+ """The host this matrix ran on, in terms two runs can be compared by.++ Generic by design: OS family, architecture, interpreter and core count+ say whether two matrices ran on comparable machines, and none of them+ identifies the machine. No hostname, no paths — a matrix artifact is a+ publishable file and must not carry anything that only describes one+ contributor's laptop. Latency differences between hosts are disclosed,+ never attributed to the models (same rule as the scorecards).+ """+ return {+ "os": platform.system(),+ "arch": platform.machine(),+ "python": platform.python_version(),+ "cpu_count": os.cpu_count(),+ }++@dataclassclass ModelResult:model: str@@ -52,12 +72,19 @@ class ModelResult:#: Populated only when measured. Absent rather than zeroed, because a#: zero accuracy and an unrun model must not render the same.metrics: dict[str, Any] = field(default_factory=dict)+ #: What was actually configured for this row: the pins applied, the+ #: endpoint, and — for verdict runs — the provenance status the scorecard+ #: earned. A row without its configuration cannot be reproduced, and two+ #: rows cannot be compared without knowing they were configured alike.+ configuration: dict[str, Any] = field(default_factory=dict)error: str | None = Nonedef to_dict(self) -> dict[str, Any]:out: dict[str, Any] = {"model": self.model, "measured": self.measured}if self.measured:out["metrics"] = self.metrics+ if self.configuration:+ out["configuration"] = self.configurationif self.error:out["error"] = self.errorreturn out@@ -145,6 +172,126 @@ def _project(block: dict[str, Any]) -> dict[str, Any]:}+def run_one_verdict(model: str, *, api_base: str, timeout: int) -> ModelResult:+ """Grade the verdict corpus on `model` through `run_verdict_eval.py`.++ The same thin-wrapper rule as the wet task: this collates a scorecard the+ verdict eval produced and computes nothing of its own. The scorecard's+ own refusals apply unchanged — a run that placed no model call, or whose+ serving identity mismatches the requested model, comes back as that+ row's error rather than as numbers.+ """+ with tempfile.TemporaryDirectory() as tmp:+ card_path = Path(tmp) / "scorecard.json"+ cmd = [+ sys.executable,+ str(RUN_VERDICT_EVAL),+ "--model",+ model,+ "--api-base",+ api_base,+ "--out",+ str(card_path),+ ]+ try:+ completed = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ timeout=timeout,+ cwd=REPO_ROOT,+ env={**os.environ, "PYTHONPATH": str(REPO_ROOT / "services" / "agents")},+ )+ except subprocess.TimeoutExpired:+ return ModelResult(model, measured=False, error=f"timed out after {timeout}s")++ if not card_path.exists():+ tail = (completed.stderr or completed.stdout or "").strip().splitlines()+ return ModelResult(model, measured=False, error=tail[-1][:300] if tail else f"exit {completed.returncode}")++ card = json.loads(card_path.read_text(encoding="utf-8"))++ configuration = {+ "requested_model": model,+ "api_base": api_base,+ "pins": [f"AISOC_MODEL_PIN_{role.upper()}" for role in ("triage", "investigation", "report", "recon", "summary", "copilot")],+ "prompt": card.get("prompt"),+ "sampling": card.get("sampling"),+ "corpus_digest": card.get("corpus_digest"),+ "provenance_status": card.get("provenance_status"),+ "resolved_models": card.get("resolved_models"),+ "model_knowledge": card.get("model_knowledge"),+ }++ if completed.returncode != 0:+ # The scorecard exists and the eval still refused the run — a+ # serving mismatch, most likely. The card is kept as the row's+ # configuration evidence; the row is not published as measured.+ return ModelResult(+ model,+ measured=False,+ configuration=configuration,+ error=f"refused by run_verdict_eval (provenance: {card.get('provenance_status')})",+ )++ return ModelResult(+ model,+ measured=True,+ configuration=configuration,+ metrics={+ "balanced_accuracy": card.get("balanced_accuracy"),+ "matthews_corrcoef": card.get("matthews_corrcoef"),+ "malicious_recall": card.get("malicious_recall"),+ "malicious_support": card.get("malicious_support"),+ "abstention_rate": card.get("abstention_rate"),+ "hallucination_rate": card.get("hallucination_rate"),+ "auto_close_precision": card.get("auto_close_precision"),+ "auto_close_considered": card.get("auto_close_considered"),+ "majority_class_accuracy": card.get("majority_class_accuracy"),+ "llm_calls_placed": card.get("llm_calls_placed"),+ "time_to_verdict_p95_ms": card.get("time_to_verdict_p95_ms"),+ "total_tokens": card.get("total_tokens"),+ },+ )+++def render_verdict_markdown(results: list[ModelResult]) -> str:+ lines = [+ "| Model | Balanced accuracy | MCC | Malicious recall | Abstention | Auto-close precision | Calls | Attribution |",+ "|-------|-------------------|-----|------------------|------------|----------------------|-------|-------------|",+ ]+ for result in results:+ if not result.measured:+ reason = result.error or "not measured"+ lines.append(f"| `{result.model}` | _not measured — {reason}_ |||||||")+ continue+ m = result.metrics++ def fmt(key: str, spec: str = "{:.3f}", metrics: dict = m) -> str:+ value = metrics.get(key)+ return spec.format(value) if isinstance(value, int | float) else "not measured"++ recall = (+ f"{fmt('malicious_recall')} / {m.get('malicious_support', '?')}" if m.get("malicious_recall") is not None else "not measured"+ )+ close = (+ f"{fmt('auto_close_precision')} over {m.get('auto_close_considered', 0)}"+ if m.get("auto_close_precision") is not None+ else "not measured"+ )+ lines.append(+ f"| `{result.model}` | {fmt('balanced_accuracy')} | {fmt('matthews_corrcoef')} | {recall} "+ f"| {fmt('abstention_rate', '{:.1%}')} | {close} | {m.get('llm_calls_placed', 0)} "+ f"| {result.configuration.get('provenance_status') or 'unattributed'} |"+ )+ lines.append("")+ lines.append(+ "_Baselines: a constant answer scores at most 0.250 balanced accuracy on this four-class corpus; "+ "compare plain accuracy against each row's majority_class_accuracy in the JSON._"+ )+ return "\n".join(lines)++def render_markdown(results: list[ModelResult]) -> str:lines = ["| Model | Incidents | MITRE accuracy | Abstention | Groundedness | p95 latency | Tokens/inv | $/incident |",@@ -185,6 +332,22 @@ def main(argv: list[str] | None = None) -> int:default=os.getenv("AISOC_MATRIX_MODELS", "gpt-4o-mini,gpt-4o"),help="Comma-separated model names to grade.",)+ parser.add_argument(+ "--task",+ choices=("wet", "verdict"),+ default="wet",+ help=(+ "which evaluation each model is graded on: 'wet' drives the 200-incident wet eval "+ "(scripts/run_evals.py --wet); 'verdict' drives the balanced verdict corpus "+ "(scripts/run_verdict_eval.py), one task per run because a model qualified on one task "+ "is not qualified on every task."+ ),+ )+ parser.add_argument(+ "--api-base",+ default=os.getenv("OPENAI_BASE_URL") or "",+ help="OpenAI-compatible base URL for --task verdict (a local server works; any non-empty key).",+ )parser.add_argument("--out", type=Path, help="Write the JSON result here.")parser.add_argument("--markdown-out", type=Path, help="Write the table here.")parser.add_argument(@@ -200,29 +363,56 @@ def main(argv: list[str] | None = None) -> int:print("model-matrix: no models requested", file=sys.stderr)return 2- live = has_live_key()+ if args.task == "verdict":+ # The verdict task needs an endpoint, not a hosted key: a locally+ # served model is a first-class subject here, and the per-run+ # scorecard carries the attribution that says who really answered.+ live = bool(args.api_base) or has_live_key()+ reason = "no --api-base and no live key configured"+ else:+ live = has_live_key()+ reason = "no live key configured"if not live:- print("model-matrix: no live LLM key configured — reporting 'not measured' for every model rather than emitting zeros.")-- results = [- run_one(model, limit=args.limit, timeout=args.timeout)- if live- else ModelResult(model, measured=False, error="no live key configured")- for model in models- ]+ print(f"model-matrix: {reason} — reporting 'not measured' for every model rather than emitting zeros.")++ if args.task == "verdict":+ results = [+ run_one_verdict(model, api_base=args.api_base, timeout=args.timeout)+ if live+ else ModelResult(model, measured=False, error=reason)+ for model in models+ ]+ else:+ results = [+ run_one(model, limit=args.limit, timeout=args.timeout) if live else ModelResult(model, measured=False, error=reason)+ for model in models+ ]payload = {- "corpus": "synthetic_incidents.json",+ "task": args.task,+ "corpus": "verdict_corpus_v1.json" if args.task == "verdict" else "synthetic_incidents.json","limit": args.limit,"partial": bool(args.limit),"live": live,+ # The host, in comparable-but-unidentifying terms, and the baselines a+ # verdict table is read against: with four classes a constant answer+ # scores 0.250 balanced accuracy, and each measured scorecard carries+ # its own majority_class_accuracy. Neither is a model result and+ # neither may be omitted from a published comparison.+ "runtime": runtime_record(),+ "baselines_note": (+ "Verdict task: a constant answer scores at most 0.250 balanced accuracy on the four-class "+ "corpus; majority_class_accuracy per row is what a reader compares plain accuracy against."+ if args.task == "verdict"+ else None+ ),"results": [r.to_dict() for r in results],}if args.out:args.out.parent.mkdir(parents=True, exist_ok=True)args.out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")- table = render_markdown(results)+ table = render_verdict_markdown(results) if args.task == "verdict" else render_markdown(results)if args.markdown_out:args.markdown_out.parent.mkdir(parents=True, exist_ok=True)args.markdown_out.write_text(table + "\n", encoding="utf-8")diff --git a/scripts/run_verdict_eval.py b/scripts/run_verdict_eval.pyindex a44de86bf..32d139712 100644--- a/scripts/run_verdict_eval.py+++ b/scripts/run_verdict_eval.py@@ -382,6 +382,17 @@ def main(argv: list[str] | None = None) -> int:help="key for that endpoint; local servers accept any non-empty string",)parser.add_argument("--corpus", type=Path, default=CORPUS)+ parser.add_argument(+ "--model-knowledge-cutoff",+ default=None,+ help=(+ "the model's published training-data cutoff (e.g. 2023-12), when the vendor states one. "+ "Recorded on the scorecard; left 'unknown' when not given. This bounds what the WEIGHTS "+ "may already know: the replay freeze constrains supplied context only, and a model whose "+ "training data postdates the corpus events may recognise them from pretraining rather "+ "than infer them from evidence — a limit every historical-predictive claim carries."+ ),+ )parser.add_argument("--out", type=Path, help="write the scorecard JSON here")parser.add_argument("--decisions-out", type=Path, help="write the per-item decisions here (stays local by default)")parser.add_argument("--tenant-id", default="00000000-0000-0000-0000-0000000000de")@@ -421,6 +432,27 @@ def main(argv: list[str] | None = None) -> int:answered_by_model = sum(1 for d in decisions if d.get("resolved_models"))errored = sum(1 for d in decisions if d.get("error"))+ # Run-level provenance: who vouched for the serving identity, and whether+ # what served answers for what was asked. Computed from per-decision+ # attribution, not asserted — see app.core.model_attribution.+ from app.core.model_attribution import (+ ADVERTISABLE_STATUSES,+ STATUS_MIXED_SERVING,+ run_provenance_status,+ )++ attribution_sources: dict[str, int] = {}+ for d in decisions:+ for source, count in (d.get("attribution_sources") or {}).items():+ attribution_sources[str(source)] = attribution_sources.get(str(source), 0) + int(count or 0)+ serving_models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})+ provenance_status = run_provenance_status(+ llm_calls=llm_calls,+ attributed_by_source=attribution_sources,+ serving_models=tuple(serving_models),+ requested=(args.model,) if args.model and not args.deterministic else (),+ )+live = llm_calls > 0if not live and not (args.deterministic or args.allow_no_llm):print(@@ -432,6 +464,7 @@ def main(argv: list[str] | None = None) -> int:)return 2+ from measure_triage_reliability import MAX_TOKENS, TEMPERATUREfrom score_replay_set import CorpusNotGradeable, grademodel_label = "deterministic" if args.deterministic else args.model@@ -442,6 +475,7 @@ def main(argv: list[str] | None = None) -> int:dataset=str(corpus.get("corpus_id") or "aisoc-verdict-v1"),commit=git_commit(),synthetic=True,+ requested_total=len(corpus["decisions"]),)except CorpusNotGradeable as exc:print(f"verdict-eval: REFUSED — {exc}", file=sys.stderr)@@ -465,12 +499,49 @@ def main(argv: list[str] | None = None) -> int:# eligibility matches on the prompt's version and content hash, so a# scorecard that does not name them can authorise nothing."prompt": prompt_provenance(),+ # The sampling the production triage call pins (`make_chat_model("triage",+ # temperature=0.0, max_tokens=2048, json_output=True)`). Imported from the+ # reliability harness rather than retyped, so the three surfaces that state+ # these values — the call site, that harness, and this scorecard — share+ # one declaration and drift together loudly instead of apart silently.+ # Two scorecards sampled differently are not comparable, and until now+ # nothing a reader could open said how a row was sampled.+ "sampling": {+ "temperature": TEMPERATURE,+ "max_tokens": MAX_TOKENS,+ "json_mode": True,+ "source": "production triage call site (app/agents/auto_triage_agent.py), held in step by the reliability harness",+ },+ # What the model's own weights may already contain. The replay freeze+ # and the leak check constrain the *supplied* context; they cannot+ # establish that pretrained weights hold no knowledge postdating the+ # corpus events, so a historical-predictive reading of this scorecard+ # is bounded by this field — and "unknown" is the honest default,+ # never an implied "before the events".+ "model_knowledge": {+ "release_or_training_cutoff": args.model_knowledge_cutoff or "unknown",+ "stated_by": "operator" if args.model_knowledge_cutoff else None,+ "disclosure": (+ "Evidence cutoffs constrain supplied context only; they do not establish that the "+ "model's pretrained weights contain no knowledge later than the events replayed."+ ),+ },"context_configuration": context_configuration(decisions),# The three numbers that decide whether the rest is worth reading."llm_calls_placed": llm_calls,"decisions_answered_by_model": answered_by_model,"decisions_errored": errored,"resolved_models": score.get("models") or [],+ # Who vouched for those serving models, and what the whole run may be+ # published as. `verified` means the gateway named every call's model;+ # `self_reported` means the serving endpoints named themselves;+ # `unattributed` means calls were placed and nobody said; and+ # `serving_mismatch` means what answered is not what was asked for.+ # Only the first two may be advertised as measured performance of the+ # named model — anything else is a diagnostic with a limitation.+ "attribution_sources": attribution_sources,+ "provenance_status": provenance_status,+ "advertisable_as_model_performance": (not args.deterministic) and provenance_status in ADVERTISABLE_STATUSES,# Writes production would have made, every one intercepted. Published# because "side-effect free" is a claim, and this is the measurement# behind it.@@ -519,7 +590,22 @@ def main(argv: list[str] | None = None) -> int:print(report["report_markdown"])print()- print(f"verdict-eval: model={model_label} mode={scorecard['mode']} llm_calls={llm_calls} errored={errored}")+ print(+ f"verdict-eval: model={model_label} mode={scorecard['mode']} llm_calls={llm_calls} errored={errored} provenance={provenance_status}"+ )++ if live and provenance_status == STATUS_MIXED_SERVING:+ # The scorecard above is preserved as a diagnostic — it says what was+ # measured and carries this limitation — but the run must not pass as+ # the requested model's performance, because something else answered.+ print(+ f"verdict-eval: REFUSED to attribute — the run was requested as {args.model!r} and the "+ f"serving identity that answered was {', '.join(serving_models) or 'unnamed'}. The scorecard "+ "is written with provenance_status=serving_mismatch and must not be published as the "+ f"requested model's performance. Fix the endpoint or the pin, then re-run.",+ file=sys.stderr,+ )+ return 2return 0diff --git a/scripts/score_replay_set.py b/scripts/score_replay_set.pyindex d9acc3283..cec52701d 100644--- a/scripts/score_replay_set.py+++ b/scripts/score_replay_set.py@@ -116,15 +116,21 @@ def grade(dataset: str,commit: str,synthetic: bool,+ requested_total: int | None = None,) -> dict[str, Any]:"""Score a labelled set and return a publishable report.`synthetic` is required rather than inferred. The spec says to labelsynthetic sets as synthetic, and a flag that defaults either waywould eventually be wrong silently.++ `requested_total` is how many items the caller asked the run to grade.+ When given, the score carries the requested/attempted/completed/failed/+ unattempted counts, so a partial run cannot publish a headline over the+ subset it reached without the gap showing."""assert_gradeable(decisions)- score = score_replay(decisions)+ score = score_replay(decisions, requested_total=requested_total)return {"model": model,diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.pyindex 4d059ac99..76a707b0a 100644--- a/services/agents/app/agents/auto_triage_agent.py+++ b/services/agents/app/agents/auto_triage_agent.py@@ -48,6 +48,7 @@ from app.context.identity import render_for_prompt as render_identityfrom app.context.knowledge_base import citation_basis, unresolvable_citationsfrom app.context.knowledge_base import render_for_prompt as render_runbooksfrom app.context.organisation_memory import render_for_prompt+from app.core.model_attribution import extract_serving_attributionfrom app.investigator.prompt_sanitizer import sanitize_text, wrap_untrustedfrom app.llm import safe_ainvokefrom app.llm.factory import make_chat_model@@ -583,6 +584,13 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:],)raw_text = response.content+ requested_model = getattr(llm, "model_name", None) or getattr(llm, "model", None)+ # Who actually served the call, by the strongest party that said:+ # the gateway's header, or the endpoint naming itself in the body.+ # Never a copy of the requested alias — an unattributed call records+ # exactly that, and the eligibility gate below treats it as a+ # serving identity no measurement can be bound to.+ attribution = extract_serving_attribution(response, requested=str(requested_model or ""))# Recorded before parsing, so a verdict that fails to parse still# leaves behind what the model was asked and what it said. The# ledger carries this onto the run (issue #1276): auto-triage is@@ -591,7 +599,10 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:state.record_llm_exchange(agent="auto_triage",purpose="triage.classify",- model=getattr(llm, "model_name", None) or getattr(llm, "model", None),+ model=requested_model,+ serving_model=attribution.serving_model,+ serving_attribution=attribution.source,+ system_fingerprint=attribution.system_fingerprint,prompt=[{"role": "system", "content": system_prompt},{"role": "user", "content": alert_context},@@ -725,6 +736,10 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:state.raw_alert,supporting_context=render_for_prompt(state.organisation_memory),)+ # As structure, not only as the basis strings below: the decision+ # contract reports supporting and contradictory evidence as lists a+ # machine can read, and the strings alone cannot be split back apart.+ state.claim_review = claim_support.as_dict()state.add_finding(f"Auto-triage: verdict={verdict}, confidence={confidence:.2f}, latency={elapsed_ms}ms")state.add_finding(f"Auto-triage rationale: {rationale}")@@ -763,14 +778,26 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:# by default and denied under AISOC_AUTONOMY_REQUIRE_MEASURED=1. The# verdict is recorded on the basis either way: "not measured" belongs in# front of whoever reviews the closure.+ # Evaluated against the serving identity when some party vouched for one,+ # because that is the thing a measurement names: a scorecard graded+ # llama3.1:8b must not authorise closures served by whatever the gateway+ # re-pointed the alias to since. Unattributed calls fall back to the+ # requested name so the UNMEASURED default is unchanged — and the+ # attribution travels into the decision, where a *matching* measurement+ # with no attribution blocks rather than binds.autonomy = eligibility.evaluate_eligibility(- model=getattr(llm, "model_name", None) or getattr(llm, "model", None),+ model=attribution.serving_model or requested_model,prompt_version=_triage_prompt().version,prompt_sha256=_triage_prompt().sha256,tenant_context=str(state.tenant_id) if getattr(state, "tenant_id", None) else "default",alert_class=_alert_class_of(state),+ model_attribution=attribution.source,)state.confidence_basis.append(f"auto_closure_safety={autonomy.render_precision()} ({autonomy.state.value}: {autonomy.reason})")+ state.confidence_basis.append(+ f"serving_model={attribution.serving_model or 'unattributed'}"+ f" (requested: {requested_model or 'unrecorded'}; attribution: {attribution.source or 'none'})"+ )if should_auto_close and not autonomy.allows_auto_close:_metrics["autonomy_not_earned"] += 1should_auto_close = Falsediff --git a/services/agents/app/confidence/claim_support.py b/services/agents/app/confidence/claim_support.pyindex 447dfe38d..2d53d1307 100644--- a/services/agents/app/confidence/claim_support.py+++ b/services/agents/app/confidence/claim_support.py@@ -237,6 +237,14 @@ _SUPPORT_KEYS: dict[ClaimKind, tuple[str, ...]] = {"scheduled","scheduled_job","scheduled_task",+ # The claim pattern recognises "scheduled (scan|job|task|reboot)", so+ # the support keys must cover the same four nouns — they covered two.+ # An alert whose evidence recorded `scheduled_scan` could state the+ # claim the pattern knows and still be refused support by the keys,+ # found by the annotated measurement in+ # tests/test_claim_support_measured.py (case CS-15).+ "scheduled_scan",+ "scheduled_reboot","planned_change",),ClaimKind.CHANGE_RECORD: ("change_ticket", "change_id", "change_number", "ticket_id", "rfc_id", "cr_id"),diff --git a/services/agents/app/confidence/eligibility.py b/services/agents/app/confidence/eligibility.pyindex ed893fb71..b0db435d3 100644--- a/services/agents/app/confidence/eligibility.py+++ b/services/agents/app/confidence/eligibility.py@@ -169,6 +169,11 @@ class EligibilityDecision:record: PerformanceRecord | None = None#: Whether the *caller's* posture lets an unmeasured configuration close.require_measured: bool = False+ #: Who vouched that the evaluated model served the call this decision is+ #: about: ``gateway_header``, ``response_body``, or ``None`` when no+ #: party did. Recorded so a reviewed closure names the strength of its+ #: own attribution.+ model_attribution: str | None = None@propertydef measured(self) -> bool:@@ -198,6 +203,7 @@ class EligibilityDecision:"state": self.state.value,"allows_auto_close": self.allows_auto_close,"reason": self.reason,+ "model_attribution": self.model_attribution,"auto_close_precision": self.precision,"samples": record.samples if record else None,"model": record.model if record else None,@@ -269,8 +275,20 @@ def evaluate_eligibility(records: tuple[PerformanceRecord, ...] | None = None,now_iso: str | None = None,require_measured: bool | None = None,+ model_attribution: str | None = None,) -> EligibilityDecision:- """Decide whether measured performance licenses closing this alert unattended."""+ """Decide whether measured performance licenses closing this alert unattended.++ ``model_attribution`` is who vouched that ``model`` actually served this+ call — ``gateway_header``, ``response_body``, or ``None`` when no party+ did (see :mod:`app.core.model_attribution`). It gates the *binding* of a+ measurement to the call, not the measurement's existence: a matching row+ cannot authorise a closure when nothing says the measured model is the+ one that answered, because a gateway re-pointing the alias is exactly+ the drift a measurement-gated closure exists to catch. With no matching+ row the state stays UNMEASURED whatever the attribution, or the strict+ posture would stop meaning anything.+ """strict = require_measured if require_measured is not None else _require_measured_from_env()rows = load_records() if records is None else recordsnow = datetime.fromisoformat(now_iso) if now_iso else datetime.now(UTC)@@ -282,6 +300,7 @@ def evaluate_eligibility(state=Eligibility.UNMEASURED,reason="no model identity was resolved for this run, so no measurement can be matched to it",require_measured=strict,+ model_attribution=model_attribution,)candidates = [@@ -318,6 +337,7 @@ def evaluate_eligibility(reason=f"the only matching measurement is stale: taken {age:.0f} days ago, ceiling {MAX_AGE_DAYS}",record=record,require_measured=strict,+ model_attribution=model_attribution,)if record.samples < MIN_SAMPLES:return EligibilityDecision(@@ -325,6 +345,7 @@ def evaluate_eligibility(reason=f"the matching measurement covers {record.samples} sample(s), below the minimum of {MIN_SAMPLES}",record=record,require_measured=strict,+ model_attribution=model_attribution,)if record.auto_close_precision < MIN_AUTO_CLOSE_PRECISION:return EligibilityDecision(@@ -335,14 +356,34 @@ def evaluate_eligibility(),record=record,require_measured=strict,+ model_attribution=model_attribution,+ )++ if model_attribution is None:+ # The measurement clears every bar and still cannot be used: nothing+ # vouched that the measured model served this call. BLOCKED rather+ # than UNMEASURED, because a measurement exists and the defect is+ # the binding — and the record travels on the decision so the+ # withheld authorisation names what it could not bind.+ return EligibilityDecision(+ state=Eligibility.BLOCKED,+ reason=(+ f"a clearing measurement exists for {model!r}, and this call's serving identity is "+ "unverified — no gateway header or response body named the model that answered, so "+ "the measurement cannot be bound to the call"+ ),+ record=record,+ require_measured=strict,+ model_attribution=None,)return EligibilityDecision(state=Eligibility.ELIGIBLE,reason=(f"measured auto-closure precision {record.auto_close_precision:.3f} over {record.samples} closures "- f"({record.measured_at}, {record.measured_by or 'unrecorded'})"+ f"({record.measured_at}, {record.measured_by or 'unrecorded'}; serving identity by {model_attribution})"),record=record,require_measured=strict,+ model_attribution=model_attribution,)diff --git a/services/agents/app/core/cost_telemetry.py b/services/agents/app/core/cost_telemetry.pyindex ed02f5a45..aab50da03 100644--- a/services/agents/app/core/cost_telemetry.py+++ b/services/agents/app/core/cost_telemetry.py@@ -65,7 +65,8 @@ from typing import Anyimport structlog-from app.core.gateway_cost import GatewayCost, extract_gateway_cost, extract_resolved_model+from app.core.gateway_cost import GatewayCost, extract_gateway_cost+from app.core.model_attribution import ATTRIBUTION_GATEWAY_HEADER, extract_serving_attributionfrom app.core.schema_bootstrap import ensure_columns, ensure_tablelogger = structlog.get_logger()@@ -184,9 +185,17 @@ class CallRecord:latency_ms: floatcost_usd: float | None = Nonecost_source: str = UNPRICED- #: What the gateway resolved ``model`` to, when it said. The alias asked- #: for is not the model billed, and only this answers "billed for what".+ #: The model that actually served the call, when some party named it. The+ #: alias asked for is not the model billed, and only this answers "billed+ #: for what". Never a copy of ``model``: an unattributed call keeps+ #: ``None`` here — see :mod:`app.core.model_attribution`.resolved_model: str | None = None+ #: Who named ``resolved_model``: ``gateway_header`` (the gateway said what+ #: it routed to — verified), ``response_body`` (the serving endpoint named+ #: itself — self-reported), or ``None`` when nobody did.+ attribution_source: str | None = None+ #: The backend's configuration fingerprint, when it published one.+ system_fingerprint: str | None = None#: Correlates with the gateway's own ``/spend/logs`` entry.call_id: str | None = Nonetool: str | None = None@@ -198,7 +207,9 @@ class CallRecord:if gateway is not None:self.cost_usd = gateway.cost_usdself.cost_source = GATEWAY- self.resolved_model = self.resolved_model or gateway.resolved_model+ if self.resolved_model is None and gateway.resolved_model:+ self.resolved_model = gateway.resolved_model+ self.attribution_source = self.attribution_source or ATTRIBUTION_GATEWAY_HEADERself.call_id = self.call_id or gateway.call_idreturn# No gateway figure. An estimate is allowed only against a concrete@@ -239,12 +250,21 @@ class CostSummary:estimated_calls: int = 0unpriced_calls: int = 0- #: What the gateway resolved the aliases to, when it said. Empty means no- #: model call was placed on this run, which is the honest answer for the- #: deterministic tier and is a different fact from "an unknown model".- #: Replay records it per decision so a report names the model it graded.+ #: The serving models some party named, when any did. Empty means either+ #: no model call was placed on this run — the honest answer for the+ #: deterministic tier — or calls were placed and nobody named the server,+ #: which ``attribution_sources`` distinguishes. Replay records it per+ #: decision so a report names the model it graded.resolved_models: tuple[str, ...] = ()+ #: How many calls each attribution source vouched for:+ #: ``{"gateway_header": n, "response_body": m}``. Empty when no call was+ #: attributed. The counts are what lets a run-level provenance status be+ #: computed honestly — "72 calls, 72 attributed by the body" is a+ #: different claim from "72 calls, none attributed", and ``resolved_models``+ #: alone cannot carry the difference.+ attribution_sources: dict[str, int] = field(default_factory=dict)+@classmethoddef from_tracker(cls, tracker: CostTracker) -> CostSummary:return cls(@@ -254,6 +274,7 @@ class CostSummary:estimated_calls=tracker.estimated_call_count,unpriced_calls=tracker.unpriced_call_count,resolved_models=tracker.resolved_models,+ attribution_sources=tracker.attribution_sources,)@@ -509,6 +530,8 @@ class CostTracker:step: str | None = None,gateway_cost: GatewayCost | None = None,resolved_model: str | None = None,+ attribution_source: str | None = None,+ system_fingerprint: str | None = None,) -> CallRecord:rec = CallRecord(model=model,@@ -519,6 +542,8 @@ class CostTracker:step=step,gateway_cost=gateway_cost,resolved_model=resolved_model,+ attribution_source=attribution_source,+ system_fingerprint=system_fingerprint,)self._records.append(rec)logger.info(@@ -587,9 +612,18 @@ class CostTracker:@propertydef resolved_models(self) -> tuple[str, ...]:- """Models the gateway said it billed, sorted. Empty when no call was placed."""+ """Serving models some party named, sorted. Empty when none was attributed."""return tuple(sorted({r.resolved_model for r in self._records if r.resolved_model}))+ @property+ def attribution_sources(self) -> dict[str, int]:+ """Calls vouched for by each attribution source. Empty when none was."""+ counts: dict[str, int] = {}+ for r in self._records:+ if r.resolved_model and r.attribution_source:+ counts[r.attribution_source] = counts.get(r.attribution_source, 0) + 1+ return counts+def summary(self) -> dict:"""The run's spend, with the provenance of every figure in it.@@ -619,6 +653,7 @@ class CostTracker:"call_count": len(self._records),"models": list({r.model for r in self._records}),"resolved_models": sorted({r.resolved_model for r in self._records if r.resolved_model}),+ "attribution_sources": self.attribution_sources,}async def flush(self) -> None:@@ -697,6 +732,12 @@ def record_llm_call(if tracker is None:return Noneprompt_tokens, completion_tokens = _extract_token_usage(response)+ # One extraction decides the serving identity for both the cost record and+ # the attribution fields, so the two cannot disagree about who answered.+ # The gateway header outranks the body inside the extractor; the body is+ # credited only with evidence it was parsed, never as a copy of the+ # requested name — see app/core/model_attribution.py.+ attribution = extract_serving_attribution(response, requested=model)return tracker.record(model=model,prompt_tokens=prompt_tokens,@@ -705,5 +746,7 @@ def record_llm_call(tool=tool,step=step,gateway_cost=extract_gateway_cost(response),- resolved_model=extract_resolved_model(response),+ resolved_model=attribution.serving_model,+ attribution_source=attribution.source,+ system_fingerprint=attribution.system_fingerprint,)diff --git a/services/agents/app/core/model_attribution.py b/services/agents/app/core/model_attribution.pynew file mode 100644index 000000000..d81d97abe--- /dev/null+++ b/services/agents/app/core/model_attribution.py@@ -0,0 +1,257 @@+"""Which model actually served a call, and how that is known.++The gap this closes+-------------------+Every row of the published verdict-quality table placed 72 model calls and+shipped ``resolved_models: []``. The runs were served by an OpenAI-compatible+endpoint directly — no LiteLLM gateway, so no ``x-litellm-model-name`` header —+and the header extractor in :mod:`app.core.gateway_cost` was the only serving+identity reader in the tree. The scorecard could prove the calls happened and+could not say which model took them, which the benchmark page had to disclose+as "per-decision model attribution is unverified".++The serving identity was in the response body the whole time: every+OpenAI-compatible server names the model it served in the chat completion's+``model`` field. This module reads it — carefully, because the obvious read is+wrong.++The trap in the obvious read+----------------------------+``langchain_openai`` builds ``response_metadata["model_name"]`` as::++ response_dict.get("model", self.model_name)++— the **requested** name is the fallback when the body carried none. Reading+the key naively would therefore fill missing serving-model metadata by copying+the requested alias, which is the one thing an attribution record must never+do: a scorecard would then claim a serving identity nobody reported.++So the body value is credited only when there is evidence it came from the+body:++* the reported name **differs** from the requested one (nothing but the body+ could have put it there), or+* the response carries its own ``id``, which langchain copies into+ ``response_metadata`` only when the body had one (``llm_output["id"]`` is+ set under ``if "id" in response_dict``). A body that carried ``id`` had the+ chance to state its model, and the OpenAI chat-completions schema carries+ both fields together.++The residual blind spot is stated rather than hidden: a nonstandard server+returning ``id`` without ``model`` would make langchain's fallback read as a+body echo. None of the servers this project routes to (OpenAI, LiteLLM,+Ollama, vLLM) omits ``model``, and the gateway header outranks the body+whenever both are present.++Three provenance levels, ordered+--------------------------------+``gateway_header``+ The LiteLLM gateway said what it resolved the alias to. The gateway is+ the party that routed the call, so this is the strongest claim available+ and the only one labelled *verified*.++``response_body``+ The serving endpoint named itself in the completion body. A server's own+ claim about itself — *self-reported*, trusted for attribution and+ labelled at its strength, never promoted to verified.++``None``+ Nobody said. Reported as unattributed, never filled from the request.++Stdlib only, and it never raises — same contract as+:mod:`app.core.gateway_cost`, for the same reason: an attribution module that+can throw would take down the LLM call it is describing.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from app.core.gateway_cost import RESOLVED_MODEL_HEADER, response_headers++__all__ = [+ "ADVERTISABLE_STATUSES",+ "ATTRIBUTION_GATEWAY_HEADER",+ "ATTRIBUTION_RESPONSE_BODY",+ "STATUS_MIXED_SERVING",+ "STATUS_NO_CALLS",+ "STATUS_SELF_REPORTED",+ "STATUS_UNATTRIBUTED",+ "STATUS_VERIFIED",+ "ServingAttribution",+ "extract_serving_attribution",+ "models_match",+ "run_provenance_status",+]++#: The gateway named the model it routed the alias to. Verified: the party+#: that placed the provider call is the one speaking.+ATTRIBUTION_GATEWAY_HEADER = "gateway_header"++#: The serving endpoint named itself in the completion body. Self-reported.+ATTRIBUTION_RESPONSE_BODY = "response_body"++#: Run-level provenance statuses. A scorecard carries exactly one of these,+#: and only the first two may be advertised as performance of a named model.+STATUS_VERIFIED = "verified"+STATUS_SELF_REPORTED = "self_reported"+#: Calls were placed and no party named the serving model (or named it for+#: only some calls — the ``:partial`` suffix says which).+STATUS_UNATTRIBUTED = "unattributed"+#: A serving identity was reported and it does not answer for the requested+#: model. A run in this state measured *something*, and the one thing it must+#: not be published as is the requested model's performance.+STATUS_MIXED_SERVING = "serving_mismatch"+#: No model call was placed at all. The deterministic tier's honest answer,+#: and the state the verdict harness refuses to publish as live.+STATUS_NO_CALLS = "no_calls"++#: Statuses under which a run may be described as measured performance of the+#: model it names. Everything else is a diagnostic with a limitation.+ADVERTISABLE_STATUSES = (STATUS_VERIFIED, STATUS_SELF_REPORTED)++#: Shape of a logical task alias. An alias is a label the gateway resolves,+#: so any concrete serving model is a correct answer for one. Mirrors+#: ``_GATEWAY_ALIAS_PREFIX`` in :mod:`app.core.cost_telemetry`.+_ALIAS_PREFIX = "aisoc-"+++@dataclass(frozen=True)+class ServingAttribution:+ """What served one call, by whose account."""++ #: The serving model, or ``None`` when no party named one. Never a copy+ #: of the requested name.+ serving_model: str | None = None+ #: :data:`ATTRIBUTION_GATEWAY_HEADER`, :data:`ATTRIBUTION_RESPONSE_BODY`,+ #: or ``None`` when unattributed.+ source: str | None = None+ #: The backend's own configuration fingerprint, when it published one+ #: (OpenAI's ``system_fingerprint``). The closest thing to an immutable+ #: deployment digest the chat-completions surface exposes.+ system_fingerprint: str | None = None+ #: The completion id, for joining a record to provider-side logs.+ response_id: str | None = None++ @property+ def attributed(self) -> bool:+ return self.serving_model is not None+++def _clean(value: Any) -> str | None:+ text = str(value).strip() if value is not None else ""+ return text or None+++def extract_serving_attribution(response: Any, *, requested: str) -> ServingAttribution:+ """The serving identity for ``response``, by the strongest party that spoke.++ ``requested`` is the model string the client asked for — the alias or the+ pin. It is used only to *refuse* an ambiguous body value, never as a+ fallback answer.+ """+ metadata = getattr(response, "response_metadata", None)+ metadata = metadata if isinstance(metadata, dict) else {}+ fingerprint = _clean(metadata.get("system_fingerprint"))+ response_id = _clean(metadata.get("id"))++ header_model = _clean(response_headers(response).get(RESOLVED_MODEL_HEADER))+ if header_model:+ return ServingAttribution(+ serving_model=header_model,+ source=ATTRIBUTION_GATEWAY_HEADER,+ system_fingerprint=fingerprint,+ response_id=response_id,+ )++ body_model = _clean(metadata.get("model_name"))+ if body_model:+ requested_clean = (requested or "").strip()+ # Credited only with evidence the body was parsed: a name the client+ # did not ask for, or the body's own ``id`` beside it. An equal name+ # with no witness is indistinguishable from langchain's fallback to+ # the requested model, and copying the request into serving metadata+ # is the defect this module exists to prevent.+ if body_model != requested_clean or response_id is not None:+ return ServingAttribution(+ serving_model=body_model,+ source=ATTRIBUTION_RESPONSE_BODY,+ system_fingerprint=fingerprint,+ response_id=response_id,+ )++ return ServingAttribution(system_fingerprint=fingerprint, response_id=response_id)+++def _bare(model: str) -> str:+ """The model name with any provider prefix dropped: ``ollama/x`` -> ``x``."""+ return model.rsplit("/", 1)[-1].strip().lower()+++def models_match(*, requested: str, serving: str) -> bool:+ """Whether ``serving`` answers for ``requested``.++ Three accepted shapes, each from a measured behaviour:++ * an ``aisoc-<role>`` alias is resolved by the gateway, so any concrete+ serving model is the correct answer for it (and is still named);+ * a provider prefix on the serving side (``ollama/qwen2:1.5b`` for+ ``qwen2:1.5b``) is routing, not substitution;+ * a version suffix on the serving side (``gpt-4o-2024-08-06`` for+ ``gpt-4o``) is the provider pinning the ask, not changing it. The+ suffix must extend the requested name at a ``-`` boundary, so+ ``gpt-4o-mini`` does not pass as ``gpt-4o``.+ """+ req = (requested or "").strip().lower()+ srv = (serving or "").strip().lower()+ if not req or not srv:+ return False+ if req.startswith(_ALIAS_PREFIX):+ return True+ req_bare, srv_bare = _bare(req), _bare(srv)+ if req_bare == srv_bare:+ return True+ # A dated/version suffix: the serving name extends the requested one at a+ # separator, and the extension is digit-led (a date or build number), so a+ # sibling model sharing the prefix (`gpt-4o-mini`) does not pass.+ if srv_bare.startswith(req_bare + "-"):+ suffix = srv_bare[len(req_bare) + 1 :]+ return bool(suffix) and suffix[0].isdigit()+ return False+++def run_provenance_status(+ *,+ llm_calls: int,+ attributed_by_source: dict[str, int],+ serving_models: tuple[str, ...] | list[str],+ requested: tuple[str, ...] | list[str],+) -> str:+ """One status for a whole run, computed from per-call attribution.++ The order of the checks is the order of the claims a reader cares about:++ 1. nothing was called — the strongest fact about the run;+ 2. something served that was not what was asked for — a substitution is+ disqualifying however well-attributed it is;+ 3. attribution incomplete — some or all calls have no named server;+ 4. every call attributed: verified when the gateway spoke for every call,+ self-reported when any call rests on the body's own claim.+ """+ if llm_calls <= 0:+ return STATUS_NO_CALLS++ for serving in serving_models:+ if not any(models_match(requested=req, serving=serving) for req in requested if req):+ return STATUS_MIXED_SERVING++ attributed = sum(attributed_by_source.values())+ if attributed <= 0:+ return STATUS_UNATTRIBUTED+ if attributed < llm_calls:+ return f"{STATUS_UNATTRIBUTED}:partial"++ if attributed_by_source.get(ATTRIBUTION_GATEWAY_HEADER, 0) == llm_calls:+ return STATUS_VERIFIED+ return STATUS_SELF_REPORTEDdiff --git a/services/agents/app/models/state.py b/services/agents/app/models/state.pyindex e89361209..177b05cf2 100644--- a/services/agents/app/models/state.py+++ b/services/agents/app/models/state.py@@ -124,6 +124,14 @@ class InvestigationState(BaseModel):# knowledge-base citations. `{"statement": str, "citations": [...]}`.business_impact: dict[str, Any] | None = None+ #: The claim-support review behind the verdict, as structure rather than+ #: only as basis strings: which decisive claims the evidence supported,+ #: which it did not, and which it contradicted+ #: (``ClaimSupportResult.as_dict()``). ``None`` on paths that never score+ #: claims — the deterministic tier, memory suppression — which is a+ #: different fact from "scored and found nothing".+ claim_review: dict[str, Any] | None = None+# Knowledge-base runbook chunks retrieved for this alert, as# `app.context.knowledge_base.RunbookRetrieval.as_state()` renders them:# the chunks, the markers a citation resolves through, and what the@@ -226,6 +234,9 @@ class InvestigationState(BaseModel):prompt: str | list[dict[str, Any]],response: str,duration_ms: int,+ serving_model: str | None = None,+ serving_attribution: str | None = None,+ system_fingerprint: str | None = None,) -> dict[str, Any]:"""Record one model call so the verdict it produced can be replayed.@@ -242,6 +253,15 @@ class InvestigationState(BaseModel):"agent": agent,"purpose": purpose,"model": model,+ # The serving identity, kept apart from the requested one above.+ # `model` is what was asked for; `serving_model` is what some+ # party said answered, `serving_attribution` is who said it+ # (gateway_header / response_body), and None means nobody did —+ # never a copy of the request. `system_fingerprint` is the+ # backend's own configuration digest when it published one.+ "serving_model": serving_model,+ "serving_attribution": serving_attribution,+ "system_fingerprint": system_fingerprint,"prompt": prompt_text[:_LLM_LITERAL_LIMIT],"prompt_truncated": len(prompt_text) > _LLM_LITERAL_LIMIT,"response": response[:_LLM_LITERAL_LIMIT],diff --git a/services/agents/app/replay/runner.py b/services/agents/app/replay/runner.pyindex 425da9892..be438bb58 100644--- a/services/agents/app/replay/runner.py+++ b/services/agents/app/replay/runner.py@@ -181,6 +181,30 @@ class ReplayDecision:tool_calls: int = 0resolved_models: list[str] = field(default_factory=list)+ #: Calls each attribution source vouched for on this decision:+ #: ``{"gateway_header": n, "response_body": m}``. Empty when calls were+ #: placed and nobody named the server — which is a different fact from+ #: "no call was placed", and the grader needs both to compute an honest+ #: run-level provenance status.+ attribution_sources: dict[str, int] = field(default_factory=dict)++ #: The alert's severity, carried for the per-severity miss breakdown. A+ #: miss on a critical alert and a miss on an info alert are different+ #: findings, and a grader that cannot segment by severity reports one+ #: number for both.+ severity: str | None = None++ #: Where the reflex path spent its time on this decision, by named stage+ #: (milliseconds). Latency is still reported and never graded; the stage+ #: split is what turns "slow" into "the context fetch, not the model".+ stage_timings_ms: dict[str, float] = field(default_factory=dict)++ #: The decision as the structured contract the worker now assembles:+ #: operational disposition, supporting and contradictory evidence,+ #: missing prerequisites, escalation reason. Carried verbatim so the+ #: grader and the report read the same shape a reviewer does.+ decision_contract: dict[str, Any] = field(default_factory=dict)+#: Model calls this decision actually placed, priced or not.#:#: The one number that separates "the model answered" from "the@@ -219,6 +243,10 @@ class ReplayDecision:"evidence": self.evidence,"tool_calls": self.tool_calls,"resolved_models": list(self.resolved_models),+ "attribution_sources": dict(self.attribution_sources),+ "severity": self.severity,+ "stage_timings_ms": dict(self.stage_timings_ms),+ "decision_contract": dict(self.decision_contract),"llm_calls": self.llm_calls,"tokens": self.tokens,"measured_usd": self.measured_usd,@@ -378,6 +406,7 @@ class ReplayRunner:expected_disposition=finding.disposition,vendor_disposition=finding.vendor_disposition,labelled=finding.is_labelled,+ severity=finding.severity,)try:@@ -425,6 +454,7 @@ 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 [])]+ decision.attribution_sources = {str(k): int(v) for k, v in (cost.get("attribution_sources") or {}).items()}# Every call the tracker saw, however it was priced. Summed from the# three priced/unpriced buckets rather than read off one of them: a# local model is unpriced, a hosted one is measured, and a harness@@ -441,4 +471,6 @@ class ReplayRunner:# 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 [])+ decision.stage_timings_ms = {str(k): float(v) for k, v in (summary.get("stage_timings_ms") or {}).items()}+ decision.decision_contract = dict(summary.get("decision_contract") or {})return decisiondiff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex 98ed01f0a..f2071472c 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -64,6 +64,7 @@ from app.routing.model_router import is_deterministic_modefrom app.security.llm_resolver import resolve_llm_configfrom app.workers.business_context import BusinessContextApplierfrom app.workers.entity_lane import EntityLanes, entity_of+from app.workers.reflex_observability import StageTimer, decision_contract, queue_delay_msfrom app.workers.shadow_mode import (LiveShadowModePolicy,ShadowDecision,@@ -215,6 +216,11 @@ def _cost_payload(cost: CostSummary, tokens: int) -> dict[str, Any]:"estimated_calls": cost.estimated_calls,"unpriced_calls": cost.unpriced_calls,"resolved_models": list(cost.resolved_models),+ # Who vouched for each resolved model, as per-source call counts.+ # Travels beside the names because the names alone cannot say whether+ # the gateway spoke (verified) or the endpoint named itself+ # (self-reported) — see app/core/model_attribution.py.+ "attribution_sources": dict(cost.attribution_sources),"tokens": tokens,}@@ -624,6 +630,13 @@ class FusedAlertTriageWorker:async def triage(self, message: dict[str, Any]) -> dict[str, Any] | None:"""Auto-triage one fused alert. Read-only (copilot): never dispatches aresponse. Returns a verdict summary dict, or None if unprocessable."""+ # Reflex observability: named stage spans plus the queue delay, so+ # "triage is slow" splits into the queue, the context fetch, the+ # model, the verification gates and the persistence that actually+ # spent the time. Reported on the summary and the completion log+ # line, joined to the outcome by the run id that already exists.+ timer = StageTimer()+ queued_ms = queue_delay_ms(message)# Phase B4 — apply business-context rules on the post-fusion alert BEFORE# any triage work. A suppress rule drops the alert (no triage spend); a# severity/route/tag rule mutates the alert the agent reasons over.@@ -633,10 +646,11 @@ class FusedAlertTriageWorker:# business-context rules per tenant and this worker only ever read# a YAML file whose path nothing sets, so authored rules applied to# no triage decision.- bc = await self._business_context.apply_for_tenant(- message.get("tenant_id") or message["alert"].get("tenant_id"),- message["alert"],- )+ with timer.measure("business_context"):+ bc = await self._business_context.apply_for_tenant(+ message.get("tenant_id") or message["alert"].get("tenant_id"),+ message["alert"],+ )bc_matched = bc.matched_rule_idsif bc.suppressed:_METRICS["bc_suppressed"] += 1@@ -647,6 +661,8 @@ class FusedAlertTriageWorker:"cost": _cost_payload(CostSummary(), 0),"business_context_rules": bc_matched,"response_dispatched": False,+ "queue_delay_ms": queued_ms,+ "stage_timings_ms": timer.as_millis(),}if bc.changed:_METRICS["bc_mutated"] += 1@@ -685,8 +701,19 @@ class FusedAlertTriageWorker:# (this is what makes alert volume actually shrink over time). Gated on# trust (human prior, or corroborated high-confidence AI prior).if _memory_suppression_enabled():- suppressed = await self._maybe_suppress_from_memory(state, fingerprint, bc_matched, writer=writer)+ with timer.measure("memory_suppression"):+ suppressed = await self._maybe_suppress_from_memory(state, fingerprint, bc_matched, writer=writer)if suppressed is not None:+ suppressed["queue_delay_ms"] = queued_ms+ suppressed["stage_timings_ms"] = timer.as_millis()+ suppressed["decision_contract"] = decision_contract(+ state,+ verdict=suppressed.get("verdict"),+ confidence=float(suppressed.get("confidence") or 0.0),+ tier="memory",+ auto_closed=False,+ suppressed_by_memory=True,+ )return suppresseddecision = governor.check(str(state.tenant_id), fingerprint)@@ -709,29 +736,33 @@ class FusedAlertTriageWorker:cfg = await self._resolve_tenant_llm(state.tenant_id)use_llm = decision.use_llm and not is_deterministic_mode() and cfg is not Noneif use_llm:- # What analysts have repeatedly taught this tenant's platform,- # read once here rather than inside the agent so the round trip- # is on the worker's timeline and is skipped entirely when no- # LLM call is going to happen. Never raises; an empty list just- # means the prompt is what it was before.- state.organisation_memory = await self._reader.fetch_statements(str(state.tenant_id))- # Phase 6.1: the tenant's own skill for this shape of alert.- # Read through the same port for the same reason: it is durable- # state a verdict depends on, so the replay freeze has to be- # able to reach it. Selection is per alert and cheap; the fetch- # behind it is cached.- await self._attach_tenant_skill(state)- # Phase 6.3: the tenant's own runbooks for this shape of alert.- # Same port again, and for a source the freeze holds still by- # a server-side cutoff rather than by capture, which is why- # the worker passes a query and never a point in time.- await self._attach_runbooks(state)- # Phase 6.3: what this tenant's analysts decided the last few- # times, and who is behind the account. Both are cutoff-frozen- # sources like runbooks, so neither takes a point in time from- # here.- await self._attach_recent_dispositions(state)- await self._attach_identity_context(state)+ # Evidence preparation, timed as one stage: five context+ # reads whose combined latency sits between the queue and+ # the model and was previously indistinguishable from both.+ with timer.measure("context_fetch"):+ # What analysts have repeatedly taught this tenant's platform,+ # read once here rather than inside the agent so the round trip+ # is on the worker's timeline and is skipped entirely when no+ # LLM call is going to happen. Never raises; an empty list just+ # means the prompt is what it was before.+ state.organisation_memory = await self._reader.fetch_statements(str(state.tenant_id))+ # Phase 6.1: the tenant's own skill for this shape of alert.+ # Read through the same port for the same reason: it is durable+ # state a verdict depends on, so the replay freeze has to be+ # able to reach it. Selection is per alert and cheap; the fetch+ # behind it is cached.+ await self._attach_tenant_skill(state)+ # Phase 6.3: the tenant's own runbooks for this shape of alert.+ # Same port again, and for a source the freeze holds still by+ # a server-side cutoff rather than by capture, which is why+ # the worker passes a query and never a point in time.+ await self._attach_runbooks(state)+ # Phase 6.3: what this tenant's analysts decided the last few+ # times, and who is behind the account. Both are cutoff-frozen+ # sources like runbooks, so neither takes a point in time from+ # here.+ await self._attach_recent_dispositions(state)+ await self._attach_identity_context(state)# Bind a CostTracker so every LLM call on this path records its# token/cost (safe_ainvoke -> record_llm_call) — previously the# highest-volume LLM spend was recorded as $0 and invisible.@@ -755,14 +786,18 @@ class FusedAlertTriageWorker:# the gateway as a bearer token, which 401s. Left unset,# make_chat_model resolves the key that pairs with the route# it actually chose.- with llm_override(- api_key=cfg.api_key if getattr(cfg, "api_key_from_tenant", False) else None,- base_url=cfg.base_url if getattr(cfg, "base_url_from_tenant", False) else None,- model=cfg.model if getattr(cfg, "model_from_tenant", False) else None,+ with (+ timer.measure("decide"),+ llm_override(+ api_key=cfg.api_key if getattr(cfg, "api_key_from_tenant", False) else None,+ base_url=cfg.base_url if getattr(cfg, "base_url_from_tenant", False) else None,+ model=cfg.model if getattr(cfg, "model_from_tenant", False) else None,+ ),):state, tier = await self._llm_triage(state)else:- state = await run_triage(state)+ with timer.measure("decide"):+ state = await run_triage(state)tier = "deterministic"_METRICS["deterministic"] += 1cost = CostSummary.from_tracker(tracker)@@ -790,11 +825,12 @@ class FusedAlertTriageWorker:# 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")- )+ with timer.measure("playbooks"):+ 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)}"@@ -843,10 +879,12 @@ class FusedAlertTriageWorker:# 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)+ with timer.measure("verification"):+ 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=cost, writer=writer)+ with timer.measure("persist"):+ await self._record(state, tier=tier, verdict=verdict, confidence=confidence, tokens=tokens, cost=cost, writer=writer)# Wave 1 — write the durable outcome back as a per-signature prior so# autonomous closures compound (a later identical alert can suppress).@@ -872,25 +910,48 @@ class FusedAlertTriageWorker:# High-confidence FP/BTP already terminated (status COMPLETED) and# skip enrichment. Best-effort: the verdict is already durable, so an# enrichment/investigation failure never fails the triage outcome.- if state.status is not AgentStatus.COMPLETED:- await self._maybe_escalate(state, writer=writer)+ escalated = state.status is not AgentStatus.COMPLETED+ if escalated:+ with timer.measure("escalate"):+ await self._maybe_escalate(state, writer=writer)# Queue every action that needs sign-off so a human can actually give# it. Until v9.0 proposed actions were persisted as JSON and stopped# there, so "requires_approval" described an approval nobody could# grant — the responder app's queue had no producer at all.- approvals = await self._raise_approvals(state, writer=writer)+ with timer.measure("approvals"):+ approvals = await self._raise_approvals(state, writer=writer)# Close the loop with the SIEM that raised this alert. Runs last and# fails soft: the verdict is already durable, and an unreachable# Splunk must not re-drive the retry path and dead-letter an alert# that was triaged correctly.- source_writeback = await self._write_back_to_source(state, verdict, confidence, rationale=_rationale_of(state), writer=writer)+ with timer.measure("writeback"):+ source_writeback = await self._write_back_to_source(state, verdict, confidence, rationale=_rationale_of(state), writer=writer)shadow = isinstance(writer, ShadowModeTriageWriter)if isinstance(writer, ShadowModeTriageWriter) and writer.recorded:_METRICS["shadow_decisions_recorded"] += 1+ stage_timings = timer.as_millis()+ contract = decision_contract(+ state,+ verdict=verdict,+ confidence=float(confidence or 0.0),+ tier=tier,+ auto_closed=state.status is AgentStatus.COMPLETED,+ escalated=escalated,+ )+ logger.info(+ "auto_triage_worker.reflex_timings",+ run_id=str(state.run_id),+ alert_id=(state.raw_alert or {}).get("id"),+ tier=tier,+ disposition=contract["operational_disposition"],+ queue_delay_ms=queued_ms,+ **{f"stage_{name}_ms": value for name, value in stage_timings.items()},+ )+return {# Phase 2.1. Stated on the summary rather than inferred from the# empty writeback and approval lists, because "shadow mode" and@@ -915,6 +976,14 @@ class FusedAlertTriageWorker:# run reports the same shape with `executed: False`."source_writeback": source_writeback,"proposed_actions": [{"action_type": a.action_type, "requires_approval": a.requires_approval} for a in state.proposed_actions],+ # Reflex observability: where the time went and what shape the+ # decision takes for a reviewer. `queue_delay_ms` is None when the+ # envelope carries no parseable `fused_at` — a replayed historical+ # finding legitimately has none, and inventing a delay would put a+ # plausible number on a measurement nobody took.+ "queue_delay_ms": queued_ms,+ "stage_timings_ms": stage_timings,+ "decision_contract": contract,}async def _sink_for(self, state: InvestigationState, fingerprint: str) -> TriageWriter:diff --git a/services/agents/app/workers/reflex_observability.py b/services/agents/app/workers/reflex_observability.pynew file mode 100644index 000000000..6d13c20f8--- /dev/null+++ b/services/agents/app/workers/reflex_observability.py@@ -0,0 +1,178 @@+"""What the reflex path did, stage by stage, and the contract its decision carries.++The reflex path — fused alert in, triage verdict out — was observable only as+a total: the agent logged one latency figure and the summary carried none,+so "triage is slow" could not be split into the queue, the context fetch,+the model, the verification gates or the persistence that actually spent the+time. The stage timer here is deliberately dumb: named monotonic spans,+accumulated per alert, reported in milliseconds on the summary and the log+line that already carries the run id — so a timing joins the outcome it+describes through the ids that exist rather than a new correlation scheme.++The decision contract is the other half. The verdict summary carried a+verdict, a confidence and prose findings; what it did not carry was the+*shape* a reviewer needs: what disposition was actually taken, which+evidence supported the decisive claims, which evidence contradicted them,+what was missing, and why the alert escalated if it did. All of that already+existed as scattered structure — the claim-support review, the groundedness+score, the injection scan, the closure-policy reason — and this assembles+it, inventing nothing: a field whose signal never ran is ``None``, never an+empty list pretending the check happened.+"""++from __future__ import annotations++import time+from datetime import UTC, datetime+from typing import Any++__all__ = ["StageTimer", "decision_contract", "queue_delay_ms"]+++class StageTimer:+ """Named monotonic spans, accumulated per alert.++ ``measure`` brackets a stage; repeated stages accumulate, so a retry+ inside one alert shows up as a bigger number rather than a lost one.+ Milliseconds, rounded to one decimal: the reflex path's interesting+ differences are tens of milliseconds, and microsecond noise in a report+ invites diffing two runs on digits that measure the host.+ """++ def __init__(self) -> None:+ self._started = time.monotonic()+ self._stages: dict[str, float] = {}++ def add(self, stage: str, seconds: float) -> None:+ self._stages[stage] = self._stages.get(stage, 0.0) + seconds++ def measure(self, stage: str) -> _Span:+ return _Span(self, stage)++ def as_millis(self) -> dict[str, float]:+ """Every measured stage plus the total since construction."""+ out = {name: round(seconds * 1000.0, 1) for name, seconds in sorted(self._stages.items())}+ out["total"] = round((time.monotonic() - self._started) * 1000.0, 1)+ return out+++class _Span:+ def __init__(self, timer: StageTimer, stage: str) -> None:+ self._timer = timer+ self._stage = stage+ self._t0 = 0.0++ def __enter__(self) -> _Span:+ self._t0 = time.monotonic()+ return self++ def __exit__(self, *_: Any) -> None:+ self._timer.add(self._stage, time.monotonic() - self._t0)+++def queue_delay_ms(message: dict[str, Any] | None) -> float | None:+ """How long the fused alert waited between fusion and triage, when knowable.++ Read off the envelope's ``fused_at`` against the wall clock. ``None`` when+ the envelope carries no parseable timestamp — a replayed historical+ finding legitimately has none, and inventing a delay for it would put a+ plausible-looking number on a measurement nobody took. A negative delay+ (clock skew between the fusion host and this one) is reported as+ measured, because hiding skew is how two hosts' clocks stay wrong.+ """+ if not isinstance(message, dict):+ return None+ raw = message.get("fused_at")+ if not raw:+ return None+ try:+ if isinstance(raw, datetime):+ fused_at = raw if raw.tzinfo else raw.replace(tzinfo=UTC)+ else:+ fused_at = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))+ if fused_at.tzinfo is None:+ fused_at = fused_at.replace(tzinfo=UTC)+ except ValueError:+ return None+ return round((datetime.now(UTC) - fused_at).total_seconds() * 1000.0, 1)+++def _operational_disposition(*, auto_closed: bool, suppressed_by_memory: bool, escalated: bool) -> str:+ """What actually happened to the alert, as one word a queue can filter on.++ Distinct from the verdict: a ``false_positive`` verdict below the+ confidence threshold is an *escalation*, and reading the verdict alone+ says the opposite.+ """+ if suppressed_by_memory:+ return "suppressed_repeat"+ if auto_closed:+ return "auto_closed"+ if escalated:+ return "escalated_to_investigation"+ return "queued_for_review"+++def decision_contract(+ state: Any,+ *,+ verdict: Any,+ confidence: float,+ tier: str,+ auto_closed: bool,+ suppressed_by_memory: bool = False,+ escalated: bool = False,+) -> dict[str, Any]:+ """The decision as a reviewable shape, assembled from signals that ran.++ Nothing here is computed fresh — every field reads structure the triage+ path already produced, so the contract cannot disagree with the ledger.+ A signal that never ran on this path reports ``None``, which a renderer+ shows as *not evaluated*; an empty list means the signal ran and found+ nothing, and the two must never be collapsed.+ """+ claim_review = getattr(state, "claim_review", None) or {}+ findings = [str(f) for f in (getattr(state, "findings", None) or [])]++ # The gates that demote or block record themselves in findings with+ # fixed lead phrases; the contract surfaces them as the machine-readable+ # reasons they are, pointing back at the prose for the detail.+ blocked = [f for f in findings if f.startswith(("Auto-close blocked", "Auto-close withheld"))]+ demoted = [f for f in findings if "demoted" in f.lower()]++ missing: list[str] = []+ if tier == "deterministic":+ missing.append("no model call was placed; the deterministic scorer answered")+ if getattr(state, "injection_suspected", False):+ missing.append("retrieved context was withheld for suspected prompt injection")++ escalation_reason: str | None = None+ if not auto_closed and not suppressed_by_memory:+ if blocked:+ escalation_reason = blocked[0]+ elif demoted:+ escalation_reason = demoted[0]+ elif str(verdict) == "true_positive":+ escalation_reason = "confirmed threat: a true positive always escalates"+ else:+ escalation_reason = f"verdict {verdict!r} at confidence {confidence:.2f} did not meet the closure policy"++ return {+ "verdict": str(verdict) if verdict else None,+ "operational_disposition": _operational_disposition(+ auto_closed=auto_closed,+ suppressed_by_memory=suppressed_by_memory,+ escalated=escalated,+ ),+ "rationale": next(iter(getattr(state, "confidence_basis", None) or []), None),+ # Supported / unsupported / contradicted decisive claims, when the+ # claim-support gate ran (the LLM path). None elsewhere — the+ # deterministic scorer makes no prose claims to review.+ "supporting_evidence": claim_review.get("supported") if claim_review else None,+ "contradictory_evidence": claim_review.get("contradicted") if claim_review else None,+ "contradicted_by": claim_review.get("contradicted_by") if claim_review else None,+ "groundedness": getattr(state, "groundedness", None),+ "missing_prerequisites": missing,+ "blocked_or_demoted_by": blocked + demoted,+ "escalation_reason": escalation_reason,+ }diff --git a/services/agents/tests/replay_recording.py b/services/agents/tests/replay_recording.pyindex 70a22732e..ebb22b3de 100644--- a/services/agents/tests/replay_recording.py+++ b/services/agents/tests/replay_recording.py@@ -128,9 +128,17 @@ class _Handler(BaseHTTPRequestHandler):_LATENCY_IN_FINDING = re.compile(r"latency=\d+ms")+#: Every field that measures the host rather than the input. `latency_ms` is+#: the original; `stage_timings_ms` is the reflex-path split of the same wall+#: clock, and `queue_delay_ms` reads the clock against the envelope. All+#: three vary between two identical runs on one machine, which is exactly why+#: they are reported and never graded.+_WALL_CLOCK_FIELDS = ("latency_ms", "stage_timings_ms", "queue_delay_ms")++def comparable(decision: dict[str, Any]) -> dict[str, Any]:"""A decision with the wall clock taken out, and nothing else."""- row = {key: value for key, value in decision.items() if key != "latency_ms"}+ row = {key: value for key, value in decision.items() if key not in _WALL_CLOCK_FIELDS}row["findings"] = [_LATENCY_IN_FINDING.sub("latency=<excluded>", str(f)) for f in row.get("findings") or []]return rowdiff --git a/services/agents/tests/test_auto_triage_autonomy_eligibility.py b/services/agents/tests/test_auto_triage_autonomy_eligibility.pyindex ba7353c20..2f6fb9447 100644--- a/services/agents/tests/test_auto_triage_autonomy_eligibility.py+++ b/services/agents/tests/test_auto_triage_autonomy_eligibility.py@@ -40,21 +40,35 @@ CLEAN_RATIONALE = (class _FixedReply:- def __init__(self, payload: dict[str, object]) -> None:+ """A stub endpoint that, like every real one, names the model it served.++ ``attributed=False`` strips the response metadata — the shape of a+ response whose serving identity no party vouched for, which is what a+ measurement must refuse to bind to.+ """++ def __init__(self, payload: dict[str, object], *, attributed: bool = True) -> None:self._payload = payload+ self._attributed = attributedself.model_name = "measured-model-v1"async def ainvoke(self, _messages, **_kwargs): # noqa: ANN001, ANN202+ attributed = self._attributed+class _Response:content = json.dumps(self._payload)+ # The body names the serving model beside its own id, which is+ # what langchain_openai copies into response_metadata when — and+ # only when — the body carried them.+ response_metadata = {"model_name": "measured-model-v1", "id": "chatcmpl-test-1"} if attributed else {}return _Response()@pytest.fixturedef pin_model(monkeypatch: pytest.MonkeyPatch):- def _pin(payload: dict[str, object]) -> None:- monkeypatch.setattr(auto_triage_agent, "make_chat_model", lambda *a, **k: _FixedReply(payload))+ def _pin(payload: dict[str, object], *, attributed: bool = True) -> None:+ monkeypatch.setattr(auto_triage_agent, "make_chat_model", lambda *a, **k: _FixedReply(payload, attributed=attributed))async def _passthrough(llm, messages, **kwargs): # noqa: ANN001, ANN202return await llm.ainvoke(messages, **kwargs)@@ -175,6 +189,47 @@ async def test_a_clearing_measurement_closes_and_says_what_it_rested_on(assert out.status is AgentStatus.COMPLETEDassert any("auto_closure_safety=0.980" in b for b in out.confidence_basis)+ # The closure names the serving identity it rested on and who vouched+ # for it — the record a disputed auto-close is explained from.+ assert any("serving_model=measured-model-v1" in b for b in out.confidence_basis)+++async def test_a_measurement_cannot_bind_to_an_unattributed_call(+ pin_model, authorized_closure_tenant, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Missing serving-model identity withholds a closure the measurement allowed.++ Same clearing measurement as the positive control above; the only change+ is a response whose metadata names no serving model — the shape of a+ call the gateway may have re-pointed since the measurement was taken.+ The measurement must not be bound to it.+ """+ prompt = auto_triage_agent._triage_prompt()+ state = _state()+ row = PerformanceRecord.from_dict(+ {+ "model": "measured-model-v1",+ "prompt_name": "triage.system",+ "prompt_version": prompt.version,+ "prompt_sha256": prompt.sha256,+ "tenant_context": str(state.tenant_id),+ "alert_class": None,+ "samples": 500,+ "auto_close_precision": 0.98,+ "corpus_digest": "sha256:" + "0" * 64,+ "code_revision": "0" * 40,+ "measured_at": "2026-10-20T00:00:00+00:00",+ "measured_by": "test",+ }+ )+ monkeypatch.setattr(eligibility, "load_records", lambda: (row,))+ pin_model(_closeable(), attributed=False)++ out = await auto_triage_agent.run_auto_triage(state)++ assert out.status is not AgentStatus.COMPLETED+ assert any("unverified" in f or "cannot be bound" in f for f in out.findings)+ assert any("serving_model=unattributed" in b for b in out.confidence_basis)async def test_eligibility_never_grants_a_closure_the_verdict_withheld(pin_model, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/services/agents/tests/test_autonomy_eligibility.py b/services/agents/tests/test_autonomy_eligibility.pyindex e53b12872..ba65a5132 100644--- a/services/agents/tests/test_autonomy_eligibility.py+++ b/services/agents/tests/test_autonomy_eligibility.py@@ -98,6 +98,7 @@ def test_a_clearing_measurement_is_eligible() -> None:alert_class="cloud",records=(_record(),),now_iso="2026-10-27T00:00:00+00:00",+ model_attribution="response_body",)assert decision.state is Eligibility.ELIGIBLE@@ -105,6 +106,57 @@ def test_a_clearing_measurement_is_eligible() -> None:assert decision.measured+def test_a_measurement_cannot_authorise_an_unattributed_serving_identity() -> None:+ """A matching measurement with no attribution for this call blocks.++ The measurement names a model. If no party — gateway header or the+ serving endpoint's own response body — vouched that this call was served+ by that model, the measurement cannot be bound to the call: the gateway+ may have re-pointed the alias since the measurement was taken, which is+ exactly the drift a measurement-gated closure exists to catch. BLOCKED+ rather than UNMEASURED, because a measurement exists and the problem is+ that it cannot be matched to the call in front of us.+ """+ decision = evaluate_eligibility(+ model="llama3.1:8b-instruct-q4_K_M",+ prompt_version="2",+ prompt_sha256="a" * 64,+ tenant_context="default",+ alert_class="cloud",+ records=(_record(),),+ now_iso="2026-10-27T00:00:00+00:00",+ model_attribution=None,+ )++ assert decision.state is Eligibility.BLOCKED+ assert not decision.allows_auto_close+ assert "unverified" in decision.reason or "attribut" in decision.reason+++def test_unmeasured_stays_unmeasured_whatever_the_attribution() -> None:+ """Attribution gates the *binding* of a measurement, not its absence.++ With no matching row there is nothing to bind, so the state stays+ UNMEASURED — additive by default, denied under the strict posture —+ identically for attributed and unattributed calls. Collapsing the two+ into BLOCKED would turn the strict flag into a no-op.+ """+ for attribution in ("gateway_header", None):+ decision = evaluate_eligibility(+ model="some-model-nobody-graded",+ prompt_version="2",+ prompt_sha256="a" * 64,+ tenant_context="default",+ alert_class="cloud",+ records=(_record(),),+ now_iso="2026-10-27T00:00:00+00:00",+ model_attribution=attribution,+ )+ assert decision.state is Eligibility.UNMEASURED++ assert decision.as_dict()["model_attribution"] is None++def test_a_measurement_below_the_precision_floor_blocks() -> None:decision = evaluate_eligibility(model="llama3.1:8b-instruct-q4_K_M",diff --git a/services/agents/tests/test_claim_support_measured.py b/services/agents/tests/test_claim_support_measured.pynew file mode 100644index 000000000..e4df1bdf9--- /dev/null+++ b/services/agents/tests/test_claim_support_measured.py@@ -0,0 +1,253 @@+"""The unsupported-claim detector, measured against hand-annotated cases.++What this is+------------+`score_claim_support` gates auto-closure in production, and until now its+quality was asserted case by case rather than *measured*: there was no+unsupported-claim rate anywhere in the tree, so "the detector works" rested+on the examples its own tests happened to contain. This file is the+measurement: a fixed annotated corpus of (rationale, evidence, human label)+triples, a confusion matrix over it, and the detector's precision and recall+pinned exactly — in both directions, so an improvement has to announce+itself in the same commit as a regression would.++What the annotation is, and is not+----------------------------------+Each case was labelled by reading the rationale against the evidence and+answering one question: *does this rationale rest on at least one decisive+claim — authorization, maintenance, a change record, sanctioned tooling,+prior review — that the evidence shown does not support?* The label is about+the text pair, not about the detector.++The annotation is **not independent in the strong sense**: the annotator had+read the detector's code, and authored the cases. That makes this a+regression-grade measurement of the detector on a fixed corpus — the same+standing as the injection guard's tuned-corpus rate — and NOT an audit-grade+unsupported-claim rate, which needs cases authored and labelled by someone+who has not read the patterns (the held-out discipline the behavioural+corpus already follows). That limit is stated here because the number below+will otherwise be quoted without it.++The published numbers+---------------------+Pinned exactly rather than floored: a floor hides drift in the direction+nobody checks, and these are small-denominator counts where every single+case moving is worth a look.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from app.confidence.claim_support import score_claim_support++#: Detector performance on the annotated corpus, pinned exactly. The+#: denominators travel with the rates (the repository rule: a mean without+#: its count is a different fact), and `tests/` is the publication venue —+#: quoting these anywhere else without the annotation caveat above is wrong.+EXPECTED_TRUE_POSITIVES = 7+EXPECTED_FALSE_POSITIVES = 0+EXPECTED_FALSE_NEGATIVES = 1+EXPECTED_TRUE_NEGATIVES = 8+++@dataclass(frozen=True)+class AnnotatedCase:+ case_id: str+ rationale: str+ evidence: dict[str, Any]+ #: The human label: the rationale rests on >= 1 unsupported decisive claim.+ unsupported_claim: bool+ #: Why the label is what it is — the annotation's working, kept beside it.+ annotation_note: str+ supporting_context: str | None = None+++CASES: tuple[AnnotatedCase, ...] = (+ # ── Unsupported decisive claims (the detector should flag) ────────────+ AnnotatedCase(+ case_id="CS-01",+ rationale="198.51.100.14 is our approved scanner under change CHG0049112, so the port sweep is expected.",+ evidence={"src_ip": "198.51.100.14", "ports_contacted": 1024},+ unsupported_claim=True,+ annotation_note="Approval and a change record asserted; evidence carries neither.",+ ),+ AnnotatedCase(+ case_id="CS-02",+ rationale="This window is scheduled maintenance for the cluster, and the reboots match the change window.",+ evidence={"hostname": "db-07", "event": "unexpected_reboot", "count": 4},+ unsupported_claim=True,+ annotation_note="Maintenance window asserted; nothing in the evidence records one.",+ ),+ AnnotatedCase(+ case_id="CS-03",+ rationale="The activity was previously reviewed and closed as a known false-positive by the SOC.",+ evidence={"rule_id": "edr-lolbin-exec", "process": "regsvr32.exe"},+ unsupported_claim=True,+ annotation_note="Prior review asserted; no disposition history is in the evidence or context.",+ ),+ AnnotatedCase(+ case_id="CS-04",+ rationale="This source is the internal vulnerability scanner, so the authentication failures are benign.",+ evidence={"src_ip": "203.0.113.9", "failed_logins": 212},+ unsupported_claim=True,+ annotation_note="Sanctioned tooling asserted; the evidence names no scanner.",+ ),+ AnnotatedCase(+ case_id="CS-05",+ rationale="Ticket INC-77421 covers this activity; the engineer was permitted to export the bucket.",+ evidence={"user": "j.doe", "action": "s3:GetObject", "object_count": 90210},+ unsupported_claim=True,+ annotation_note="A change/ticket record and a permission asserted; evidence has neither.",+ ),+ AnnotatedCase(+ case_id="CS-06",+ rationale="This is a red-team exercise; the beaconing is part of the engagement.",+ evidence={"domain": "cdn-metrics.example", "beacon_interval_s": 60},+ unsupported_claim=True,+ annotation_note="Engagement asserted with no engagement record anywhere.",+ ),+ AnnotatedCase(+ case_id="CS-07",+ rationale="The transfer was pre-approved; data movement of this size is sanctioned for this team each quarter.",+ evidence={"user": "a.smith", "bytes_out": 92_000_000_000},+ unsupported_claim=True,+ annotation_note="Approval asserted twice; evidence is a byte count and a username.",+ ),+ # ── Supported or claim-free rationales (the detector must not flag) ───+ AnnotatedCase(+ case_id="CS-08",+ rationale=(+ "The rule counts distinct destination ports and this source contacted 1024 of them, which is the condition it was written for."+ ),+ evidence={"src_ip": "198.51.100.14", "ports_contacted": 1024},+ unsupported_claim=False,+ annotation_note="Reasons from the telemetry; asserts no decisive claim.",+ ),+ AnnotatedCase(+ case_id="CS-09",+ rationale="The export was approved: the change record is in the evidence and names this user.",+ evidence={"user": "j.doe", "action": "s3:GetObject", "approval_id": "CHG0031177", "approved_by": "it-change-board"},+ unsupported_claim=False,+ annotation_note="Approval asserted and the evidence carries approval_id/approved_by.",+ ),+ AnnotatedCase(+ case_id="CS-10",+ rationale="Organisation memory records that this scanner subnet is sanctioned, which covers this source.",+ evidence={"src_ip": "192.0.2.33", "ports_contacted": 400},+ unsupported_claim=False,+ annotation_note="Sanctioned-tooling claim supported by first-party context, not the payload.",+ supporting_context=(+ "Analysts have repeatedly confirmed: 192.0.2.0/24 is the sanctioned internal scanner subnet (authorized scanner)."+ ),+ ),+ AnnotatedCase(+ case_id="CS-11",+ rationale="Nothing in the telemetry indicates this traffic was approved or part of any maintenance window, so it escalates.",+ evidence={"hostname": "ws-4", "event": "service_install"},+ unsupported_claim=False,+ annotation_note="Mentions the vocabulary under negation; asserts the opposite of the claim.",+ ),+ AnnotatedCase(+ case_id="CS-12",+ rationale="High-entropy domain, first seen today, resolved by one host only: consistent with command and control.",+ evidence={"domain": "qx7zt.example", "first_seen": "today", "resolver_count": 1},+ unsupported_claim=False,+ annotation_note="Escalating conclusion drawn from evidence; no decisive benign claim.",+ ),+ AnnotatedCase(+ case_id="CS-13",+ rationale="The sender claims to be from the IT helpdesk, which the evidence does not corroborate; treating as phishing.",+ evidence={"email_subject": "Password reset required", "sender": "[email protected]"},+ unsupported_claim=False,+ annotation_note="Reports a third party's claim without adopting it; 'claims to be' is not an assertion.",+ ),+ AnnotatedCase(+ case_id="CS-14",+ rationale="The binary is signed and the signature chain validates to the vendor, so execution from Program Files is expected.",+ evidence={"process": "updater.exe", "signature_valid": True, "signer": "Example Corp"},+ unsupported_claim=False,+ annotation_note="A code-signing fact read off the evidence; not a decisive-claim family.",+ ),+ AnnotatedCase(+ case_id="CS-15",+ rationale="The login burst matches the scheduled scan the evidence records for this window.",+ evidence={"src_ip": "192.0.2.7", "scheduled_scan": "weekly-authenticated-scan", "window": "02:00-03:00"},+ unsupported_claim=False,+ annotation_note="Maintenance-family claim supported by the scheduled_scan key in evidence.",+ ),+ # ── The known miss, kept as a miss ─────────────────────────────────────+ AnnotatedCase(+ case_id="CS-16",+ rationale="IT said this rollout is fine and the activity matches what the desktop team normally pushes.",+ evidence={"process": "deploy.ps1", "host_count": 240},+ unsupported_claim=True,+ annotation_note=(+ "A verbal-authority claim ('IT said this is fine') with no record. No pattern family covers "+ "informal authority that avoids the approval vocabulary — the known miss, recorded rather than "+ "patched, because tuning the detector against the corpus that measures it manufactures a rate."+ ),+ ),+)+++def _confusion() -> tuple[int, int, int, int]:+ tp = fp = fn = tn = 0+ for case in CASES:+ result = score_claim_support(case.rationale, case.evidence, supporting_context=case.supporting_context)+ flagged = result.blocks_auto_close+ if case.unsupported_claim and flagged:+ tp += 1+ elif case.unsupported_claim and not flagged:+ fn += 1+ elif not case.unsupported_claim and flagged:+ fp += 1+ else:+ tn += 1+ return tp, fp, fn, tn+++def test_corpus_is_balanced_enough_to_measure() -> None:+ """Half the corpus must be claim-free or supported, or the measurement+ rewards a detector that flags everything."""+ positives = sum(1 for case in CASES if case.unsupported_claim)+ assert 6 <= positives <= len(CASES) - 6+++def test_detector_confusion_matrix_is_pinned_exactly() -> None:+ """The measurement. Pinned in both directions: a new miss and a new catch+ both fail until the constants — and anything quoting them — move in the+ same commit."""+ tp, fp, fn, tn = _confusion()+ print(+ f"\n[eval] claim-support on {len(CASES)} annotated cases: "+ f"TP={tp} FP={fp} FN={fn} TN={tn} "+ f"precision={tp / (tp + fp) if tp + fp else float('nan'):.3f} "+ f"recall={tp / (tp + fn) if tp + fn else float('nan'):.3f}"+ )+ assert (tp, fp, fn, tn) == (+ EXPECTED_TRUE_POSITIVES,+ EXPECTED_FALSE_POSITIVES,+ EXPECTED_FALSE_NEGATIVES,+ EXPECTED_TRUE_NEGATIVES,+ ), f"detector moved on the annotated corpus: TP={tp} FP={fp} FN={fn} TN={tn}"+++def test_the_known_miss_is_the_one_annotated_as_missed() -> None:+ """CS-16 is the recorded blind spot. If the detector starts catching it,+ this fails too — the miss list must not decay into a description of a+ tree nobody re-measured (the injection ratchet's rule, applied here)."""+ case = next(c for c in CASES if c.case_id == "CS-16")+ result = score_claim_support(case.rationale, case.evidence)+ assert not result.blocks_auto_close, "the recorded miss is now caught: move it out of the miss list and update the pinned matrix"+++def test_zero_false_positives_holds_on_negated_and_supported_claims() -> None:+ """The cases production cannot afford to flag: negation, evidence-anchored+ approval, and first-party context support. A detector that flags these+ demotes ordinary analyst language and gets switched off within a week."""+ for case_id in ("CS-09", "CS-10", "CS-11", "CS-13", "CS-15"):+ case = next(c for c in CASES if c.case_id == case_id)+ result = score_claim_support(case.rationale, case.evidence, supporting_context=case.supporting_context)+ assert not result.blocks_auto_close, f"{case_id} flagged: {result.reason}"diff --git a/services/agents/tests/test_model_attribution.py b/services/agents/tests/test_model_attribution.pynew file mode 100644index 000000000..1cc1d9ef1--- /dev/null+++ b/services/agents/tests/test_model_attribution.py@@ -0,0 +1,246 @@+"""Serving-model attribution: who answered the call, and how we know.++The defect these cover+----------------------+Every published verdict-eval row measured a model served directly by an+OpenAI-compatible endpoint, and every one of them shipped with+``resolved_models: []`` — "calls were placed, but no gateway named the model+that took them". The serving identity was in the response body's ``model``+field the whole time; nothing read it, because the only extractor was the+LiteLLM-header one.++The trap that makes the body field dangerous to read naively:+``langchain_openai`` builds ``response_metadata["model_name"]`` as+``response_dict.get("model", self.model_name)`` — the **requested** name is+the fallback when the body carried none. Copying the requested alias into+serving-model metadata is exactly what the attribution rules forbid, so the+extractor only credits the body when there is evidence the body was parsed:+either the reported name differs from the requested one, or the response+carries its own ``id`` (set by langchain only when the body had one).++Fixtures mirror ``test_cost_provenance.py``: the LiteLLM headers are the+measured set from ``ghcr.io/berriai/litellm:v1.102.1``; the body shapes are+what an Ollama 0.5-class server and OpenAI's API return for a chat+completion.+"""++from __future__ import annotations++from types import SimpleNamespace++from app.core.cost_telemetry import CostSummary, CostTracker+from app.core.model_attribution import (+ ATTRIBUTION_GATEWAY_HEADER,+ ATTRIBUTION_RESPONSE_BODY,+ STATUS_MIXED_SERVING,+ STATUS_NO_CALLS,+ STATUS_SELF_REPORTED,+ STATUS_UNATTRIBUTED,+ STATUS_VERIFIED,+ extract_serving_attribution,+ models_match,+ run_provenance_status,+)++GATEWAY_HEADERS = {+ "x-litellm-call-id": "716640f2-e268-47dd-b53e-d956fe9d6361",+ "x-litellm-model-name": "ollama/qwen2:1.5b",+ "x-litellm-response-cost-original": "0.0",+}+++def _response(+ *,+ headers: dict[str, str] | None = None,+ model_name: str | None = None,+ response_id: str | None = None,+ system_fingerprint: str | None = None,+):+ metadata: dict[str, object] = {}+ if model_name is not None:+ metadata["model_name"] = model_name+ if response_id is not None:+ metadata["id"] = response_id+ if system_fingerprint is not None:+ metadata["system_fingerprint"] = system_fingerprint+ if headers is not None:+ metadata["headers"] = dict(headers)+ return SimpleNamespace(+ content="ok",+ usage_metadata={"input_tokens": 19, "output_tokens": 3},+ response_metadata=metadata,+ )+++# ---------------------------------------------------------------------------+# Extraction: which party named the serving model+# ---------------------------------------------------------------------------+++def test_gateway_header_is_the_strongest_source():+ """The party that routed the call says what it called."""+ response = _response(headers=GATEWAY_HEADERS, model_name="aisoc-triage", response_id="chatcmpl-1")+ attribution = extract_serving_attribution(response, requested="aisoc-triage")+ assert attribution.serving_model == "ollama/qwen2:1.5b"+ assert attribution.source == ATTRIBUTION_GATEWAY_HEADER+++def test_body_echo_with_id_witness_is_server_reported():+ """Ollama echoes the exact requested name — with an ``id``, that is the body speaking."""+ response = _response(model_name="llama3.1:8b-instruct-q4_K_M", response_id="chatcmpl-529")+ attribution = extract_serving_attribution(response, requested="llama3.1:8b-instruct-q4_K_M")+ assert attribution.serving_model == "llama3.1:8b-instruct-q4_K_M"+ assert attribution.source == ATTRIBUTION_RESPONSE_BODY+++def test_body_name_differing_from_request_is_server_reported_without_witness():+ """OpenAI answers ``gpt-4o`` with ``gpt-4o-2024-08-06``: only the body knows that."""+ response = _response(model_name="gpt-4o-2024-08-06")+ attribution = extract_serving_attribution(response, requested="gpt-4o")+ assert attribution.serving_model == "gpt-4o-2024-08-06"+ assert attribution.source == ATTRIBUTION_RESPONSE_BODY+++def test_equal_name_without_witness_is_not_attributed():+ """``model_name == requested`` with no ``id`` is indistinguishable from the+ langchain fallback that copies the requested name, so it must not be+ credited as a server claim. The requested alias is never copied into+ serving metadata."""+ response = _response(model_name="aisoc-triage")+ attribution = extract_serving_attribution(response, requested="aisoc-triage")+ assert attribution.serving_model is None+ assert attribution.source is None+++def test_no_metadata_is_not_attributed():+ attribution = extract_serving_attribution(SimpleNamespace(content="ok"), requested="gpt-4o")+ assert attribution.serving_model is None+ assert attribution.source is None+++def test_system_fingerprint_is_captured_when_present():+ response = _response(model_name="gpt-4o-2024-08-06", system_fingerprint="fp_abc123")+ attribution = extract_serving_attribution(response, requested="gpt-4o")+ assert attribution.system_fingerprint == "fp_abc123"+++def test_empty_fingerprint_is_absent_not_empty_string():+ """langchain defaults ``system_fingerprint`` to ``""`` — absent, not a value."""+ response = _response(model_name="gpt-4o-2024-08-06", system_fingerprint="")+ attribution = extract_serving_attribution(response, requested="gpt-4o")+ assert attribution.system_fingerprint is None+++# ---------------------------------------------------------------------------+# Matching: does the serving identity answer for the requested name+# ---------------------------------------------------------------------------+++def test_provider_prefix_does_not_defeat_a_match():+ assert models_match(requested="qwen2:1.5b", serving="ollama/qwen2:1.5b")+ assert models_match(requested="gpt-4o-mini", serving="openai/gpt-4o-mini")+++def test_a_version_suffix_still_matches_the_family():+ """OpenAI serves ``gpt-4o`` as ``gpt-4o-2024-08-06``; that is the same ask."""+ assert models_match(requested="gpt-4o", serving="gpt-4o-2024-08-06")+++def test_a_different_model_does_not_match():+ assert not models_match(requested="llama3.1:8b-instruct-q4_K_M", serving="ollama/qwen2:1.5b")+ assert not models_match(requested="gpt-4o", serving="gpt-4o-mini")+++def test_an_alias_matches_any_serving_model():+ """An ``aisoc-<role>`` alias is a label the gateway resolves — any concrete+ serving model is the correct answer for it, and must still be *named*."""+ assert models_match(requested="aisoc-triage", serving="ollama/qwen2:1.5b")+++# ---------------------------------------------------------------------------+# Run-level provenance status+# ---------------------------------------------------------------------------+++def test_zero_calls_is_its_own_status():+ assert run_provenance_status(llm_calls=0, attributed_by_source={}, serving_models=(), requested=()) == STATUS_NO_CALLS+++def test_all_gateway_attributed_is_verified():+ status = run_provenance_status(+ llm_calls=72,+ attributed_by_source={ATTRIBUTION_GATEWAY_HEADER: 72},+ serving_models=("ollama/qwen2:1.5b",),+ requested=("aisoc-triage",),+ )+ assert status == STATUS_VERIFIED+++def test_body_attribution_is_self_reported_not_verified():+ status = run_provenance_status(+ llm_calls=72,+ attributed_by_source={ATTRIBUTION_RESPONSE_BODY: 72},+ serving_models=("llama3.1:8b-instruct-q4_K_M",),+ requested=("llama3.1:8b-instruct-q4_K_M",),+ )+ assert status == STATUS_SELF_REPORTED+++def test_calls_with_no_attribution_are_unattributed():+ status = run_provenance_status(llm_calls=72, attributed_by_source={}, serving_models=(), requested=("gpt-4o",))+ assert status == STATUS_UNATTRIBUTED+++def test_partial_attribution_is_not_promoted():+ """60 attributed of 72 placed: the run cannot claim full attribution."""+ status = run_provenance_status(+ llm_calls=72,+ attributed_by_source={ATTRIBUTION_RESPONSE_BODY: 60},+ serving_models=("llama3.1:8b-instruct-q4_K_M",),+ requested=("llama3.1:8b-instruct-q4_K_M",),+ )+ assert status == STATUS_UNATTRIBUTED + ":partial"+++def test_a_substituted_backend_is_named_not_averaged():+ """A concrete requested model answered by a different one is a substitution,+ whatever the attribution source — the run must not be advertised as the+ requested model's performance."""+ status = run_provenance_status(+ llm_calls=72,+ attributed_by_source={ATTRIBUTION_GATEWAY_HEADER: 72},+ serving_models=("ollama/qwen2:1.5b",),+ requested=("llama3.1:8b-instruct-q4_K_M",),+ )+ assert status == STATUS_MIXED_SERVING+++# ---------------------------------------------------------------------------+# Tracker integration: attribution flows into the run summary+# ---------------------------------------------------------------------------+++async def test_tracker_attribution_reaches_the_summary():+ async with CostTracker(run_id="r1", tenant_id="t1", persist=False) as tracker:+ tracker.record(+ model="llama3.1:8b-instruct-q4_K_M",+ prompt_tokens=10,+ completion_tokens=5,+ latency_ms=12.0,+ resolved_model="llama3.1:8b-instruct-q4_K_M",+ attribution_source=ATTRIBUTION_RESPONSE_BODY,+ system_fingerprint="fp_x",+ )+ summary = CostSummary.from_tracker(tracker)+ assert summary.resolved_models == ("llama3.1:8b-instruct-q4_K_M",)+ assert summary.attribution_sources == {ATTRIBUTION_RESPONSE_BODY: 1}+ assert tracker.summary()["attribution_sources"] == {ATTRIBUTION_RESPONSE_BODY: 1}+++async def test_tracker_without_attribution_reports_none_not_requested_name():+ """A call whose serving identity is unknown must not inherit the alias."""+ async with CostTracker(run_id="r2", tenant_id="t1", persist=False) as tracker:+ tracker.record(model="aisoc-triage", prompt_tokens=10, completion_tokens=5, latency_ms=9.0)+ summary = CostSummary.from_tracker(tracker)+ assert summary.resolved_models == ()+ assert summary.attribution_sources == {}diff --git a/services/agents/tests/test_reflex_observability.py b/services/agents/tests/test_reflex_observability.pynew file mode 100644index 000000000..07beef0cc--- /dev/null+++ b/services/agents/tests/test_reflex_observability.py@@ -0,0 +1,148 @@+"""The reflex path reports where its time went and what shape its decision takes.++Driven through the production worker (`FusedAlertTriageWorker.triage`) over+the shadow sinks — the same construction the replay runner uses — so the+fields asserted here are the fields a replay decision and a live summary+actually carry, not the fields a helper would carry if something called it.++What each test blocks:++* a summary with no stage timings — "triage is slow" stays unsplittable into+ queue, context fetch, model, verification and persistence;+* a queue delay invented for an envelope that carries no `fused_at` — a+ replayed historical finding has none, and a plausible-looking number on a+ measurement nobody took is the repository's named failure shape;+* a decision contract whose "signal never ran" and "signal ran and found+ nothing" collapse into each other — the deterministic tier makes no prose+ claims, so its supporting-evidence field must be None, never [].+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta++from app.models.state import InvestigationState+from app.replay.shadow import ContextSnapshot, FrozenTriageContextReader, ShadowTriageWriter+from app.workers.fused_alert_consumer import FusedAlertTriageWorker+from app.workers.reflex_observability import StageTimer, decision_contract, queue_delay_ms++TENANT = "00000000-0000-0000-0000-0000000000de"+++def _worker() -> FusedAlertTriageWorker:+ return FusedAlertTriageWorker(+ bootstrap_servers="",+ writer=ShadowTriageWriter(),+ context_reader=FrozenTriageContextReader(ContextSnapshot(split_at=datetime(2026, 1, 1, tzinfo=UTC))),+ )+++def _message(*, fused_at: str | None = None) -> dict:+ alert = {+ "id": str(uuid.uuid4()),+ "title": "Impossible travel for alice",+ "rule_id": "idp-impossible-travel",+ "severity": "medium",+ "username": "alice",+ "raw_event": {"source_geo": "SE", "second_geo": "BR", "gap_minutes": 11},+ }+ message = {"tenant_id": TENANT, "id": str(uuid.uuid4()), "alert": alert}+ if fused_at is not None:+ message["fused_at"] = fused_at+ return message+++async def test_summary_carries_stage_timings_and_the_decision_contract() -> None:+ summary = await _worker().triage(_message())++ assert summary is not None+ timings = summary["stage_timings_ms"]+ assert timings["total"] >= 0.0+ assert "decide" in timings, "the verdict stage must be measured; it is where the model time goes"+ assert "persist" in timings+ assert "verification" in timings++ contract = summary["decision_contract"]+ assert contract["verdict"] == summary["verdict"]+ assert contract["operational_disposition"] in {+ "auto_closed",+ "escalated_to_investigation",+ "queued_for_review",+ "suppressed_repeat",+ }+ # The deterministic tier runs no claim-support review: None, never [],+ # because an empty list says the review ran and found nothing.+ assert contract["supporting_evidence"] is None+ assert contract["contradictory_evidence"] is None+ assert any("deterministic" in item for item in contract["missing_prerequisites"])+ if contract["operational_disposition"] != "auto_closed":+ assert contract["escalation_reason"], "an alert that did not close says why it escalated"+++async def test_queue_delay_is_measured_from_fused_at_and_never_invented() -> None:+ fused = (datetime.now(UTC) - timedelta(seconds=2)).isoformat()+ with_delay = await _worker().triage(_message(fused_at=fused))+ assert with_delay is not None+ assert with_delay["queue_delay_ms"] is not None+ assert with_delay["queue_delay_ms"] >= 1500.0++ without = await _worker().triage(_message())+ assert without is not None+ assert without["queue_delay_ms"] is None, "no fused_at on the envelope means no delay was measured, not a delay of zero"+++def test_queue_delay_parses_the_shapes_the_envelope_actually_carries() -> None:+ now = datetime.now(UTC)+ assert queue_delay_ms({"fused_at": now.isoformat()}) is not None+ assert queue_delay_ms({"fused_at": now.strftime("%Y-%m-%dT%H:%M:%SZ")}) is not None+ assert queue_delay_ms({"fused_at": "not a timestamp"}) is None+ assert queue_delay_ms({}) is None+ assert queue_delay_ms(None) is None+++def test_stage_timer_accumulates_repeated_stages() -> None:+ timer = StageTimer()+ with timer.measure("decide"):+ pass+ with timer.measure("decide"):+ pass+ millis = timer.as_millis()+ assert "decide" in millis+ assert millis["total"] >= millis["decide"]+++def test_contract_reports_claim_review_structure_when_it_ran() -> None:+ """The LLM path's claim review reaches the contract as lists, and the+ escalation reason names the block that caused it."""+ state = InvestigationState(+ incident_id=uuid.uuid4(),+ tenant_id=uuid.uuid4(),+ alert_summary="s",+ raw_alert={"id": "a-1"},+ )+ state.claim_review = {+ "scored": True,+ "score": 0.5,+ "supported": ["the rule counts distinct ports"],+ "unsupported": ["this is our approved scanner"],+ "contradicted": [],+ "contradicted_by": [],+ "reason": "1 decisive claim lacks support",+ }+ state.add_finding("Auto-close blocked: 1 decisive claim lacks support. Routed to manual review.")++ contract = decision_contract(+ state,+ verdict="false_positive",+ confidence=0.97,+ tier="llm",+ auto_closed=False,+ escalated=True,+ )++ assert contract["supporting_evidence"] == ["the rule counts distinct ports"]+ assert contract["contradictory_evidence"] == []+ assert contract["operational_disposition"] == "escalated_to_investigation"+ assert contract["escalation_reason"].startswith("Auto-close blocked")+ assert contract["blocked_or_demoted_by"]diff --git a/services/agents/tests/test_replay_route.py b/services/agents/tests/test_replay_route.pyindex 63502894f..e4e63228c 100644--- a/services/agents/tests/test_replay_route.py+++ b/services/agents/tests/test_replay_route.py@@ -302,7 +302,11 @@ def test_two_runs_over_one_history_produce_identical_decisions_through_the_routeassert response.status_code == 200rows = []for decision in response.json()["decisions"]:+ # Every wall-clock field: latency, its reflex-path stage split,+ # and the queue delay. All measure the host, not the input.decision.pop("latency_ms")+ decision.pop("stage_timings_ms", None)+ decision.pop("queue_delay_ms", None)rows.append(decision)return rowsdiff --git a/services/api/app/_vendor/aisoc_benchmark/replay.py b/services/api/app/_vendor/aisoc_benchmark/replay.pyindex 3b3b12e11..ff3d1ad56 100644--- a/services/api/app/_vendor/aisoc_benchmark/replay.py+++ b/services/api/app/_vendor/aisoc_benchmark/replay.py@@ -198,11 +198,48 @@ class ReplayScore:graded: int = 0abstained: int = 0+ # ---- request reliability: five counts, nothing vanishes --------------+ #+ # `requested_total` is what the caller asked the run to grade — the corpus+ # size — and is `None` when the caller did not say, in which case+ # `unattempted` is unknown rather than zero. A run that stopped a third+ # of the way through must not publish a headline over the two-thirds it+ # never reached without the gap showing, and "failed" (triage refused or+ # crashed) is kept apart from "completed" because a failure that stops+ # the run cannot disappear from the headline.+ requested_total: int | None = None+ attempted: int = 0+ completed: int = 0+ failed: int = 0+ unattempted: int | None = None+# ---- the number an operator is deciding on ---------------------------malicious_support: int = 0malicious_recall: float | None = Nonemalicious_recall_ci: tuple[float, float] | None = Nonemalicious_precision: float | None = None++ # ---- the same recall over the full cohort -----------------------------+ #+ # `malicious_recall` above is *selective*: it is computed over labelled+ # decisions that did not error, so it answers "how good are the answers+ # it managed to give". A run that crashed on half the malicious cases+ # would quietly drop them from that denominator. The full-cohort figure+ # keeps every labelled malicious case — abstained, errored, all of it —+ # and the split of the misses is published as counts: an abstention or an+ # error retains the alert for a human (an operational safety outcome, not+ # a correct classification), while a malicious case answered with an+ # auto-closeable verdict reached nobody.+ malicious_support_full: int = 0+ malicious_recall_full_cohort: float | None = None+ malicious_abstained: int = 0+ malicious_errored: int = 0+ #: Malicious cases that stayed in front of a human: abstained + errored+ #: (both retain the alert) — distinct from caught, and from closed-away.+ malicious_reached_review: int = 0+ #: Malicious cases the agent answered with a non-malicious verdict. The+ #: dangerous direction: these reached nobody.+ malicious_closed_as_negative: int = 0#: Malicious cases the agent did not call malicious, as a count and a#: rate. Derivable from the confusion matrix and from `1 - recall`,#: and published as its own field anyway: a false negative is a@@ -260,6 +297,32 @@ class ReplayScore:auto_close_considered: int = 0auto_close_correct: int = 0auto_close_precision: float | None = None++ # ---- the four closure cuts, over *proposed* closures -------------------+ #+ # Replay executes nothing: every closure here is what the stated policy+ # *would have* closed, and `closures_executed` is pinned at zero so a+ # simulated closure can never read as a production outcome. Unlike+ # `auto_close_*` above (computed over labelled, answered decisions only),+ # the proposed-closure population spans every decision including the+ # unlabeled ones, because the unknown-label share among closures is one of+ # the four questions.+ #+ # * `malicious_closure_rate` — malicious items closed / all labelled+ # malicious (full cohort). The catastrophic direction, and a measured+ # 0.0 here is a counted zero, not an absence.+ # * `closure_contamination` — malicious closed / closures with known truth.+ # * `benign_closure_coverage` — benign-family items closed / all labelled+ # benign-family items ("benign-family" = the three non-malicious truth+ # classes). What the closure policy actually absorbs.+ # * `closure_unknown_share` — closures with no truth label / all closures.+ closures_proposed: int = 0+ closures_executed: int = 0+ malicious_closed_count: int = 0+ malicious_closure_rate: float | None = None+ closure_contamination: float | None = None+ benign_closure_coverage: float | None = None+ closure_unknown_share: float | None = None#: Share of labelled decisions the agent routed to a human instead of#: deciding. The same population as `abstention_rate`, named the way an#: operator sizing a queue thinks about it.@@ -286,6 +349,10 @@ class ReplayScore:hallucinated_examples: list[str] = field(default_factory=list)per_rule: list[SegmentScore] = field(default_factory=list)per_source: list[SegmentScore] = field(default_factory=list)+ #: Misses by severity. A miss on a critical alert and a miss on an info+ #: alert are different findings; one number for both hides the one that+ #: matters.+ per_severity: list[SegmentScore] = field(default_factory=list)# ---- cost and latency, reported not scored ---------------------------total_tokens: int = 0@@ -307,6 +374,13 @@ class ReplayScore:#: deterministic fallback when a provider is unreachable and a run that#: measured nothing otherwise looks entirely normal.llm_calls: int = 0+ #: Calls each attribution source vouched for, summed across decisions:+ #: ``{"gateway_header": n, "response_body": m}``. ``models`` says who+ #: served; this says on whose account, which is what separates *verified*+ #: attribution (the gateway spoke) from *self-reported* (the endpoint+ #: named itself) from none at all. The run-level provenance status is+ #: computed by the caller, which knows the requested model.+ attribution_sources: dict[str, int] = field(default_factory=dict)# ---- provenance ------------------------------------------------------bootstrap_resamples: int = BOOTSTRAP_RESAMPLES@@ -478,6 +552,7 @@ def score_replay(bootstrap_resamples: int = BOOTSTRAP_RESAMPLES,bootstrap_seed: int = BOOTSTRAP_SEED,auto_close_threshold: float = DEFAULT_AUTO_CLOSE_THRESHOLD,+ requested_total: int | None = None,) -> ReplayScore:"""Grade a replay run's decisions against the analysts' own labels.@@ -509,6 +584,19 @@ def score_replay(score.unlabeled = len(usable) - len(labelled)score.labelled = len(labelled)+ # ---- request reliability ----------------------------------------------+ #+ # `attempted` is what reached the grader; `requested_total` is what the+ # caller asked for, when it said. The difference is work the run never+ # reached — a partial run's gap, visible rather than silently absent. A+ # negative difference is a caller error and is clamped to the honest+ # reading (nothing unattempted) rather than published as negative work.+ score.requested_total = requested_total+ score.attempted = len(decisions)+ score.completed = len(usable)+ score.failed = len(errored)+ score.unattempted = max(0, requested_total - len(decisions)) if requested_total is not None else None+# Hallucination spans every decision that produced reasoning, answered or# not, and errored or not: an agent that invented an address before# failing has still invented it.@@ -543,6 +631,51 @@ def score_replay(score.time_to_verdict_p95_ms = score.p95_latency_msscore.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})score.llm_calls = sum(int(d.get("llm_calls") or 0) for d in decisions)+ attribution: dict[str, int] = {}+ for decision in decisions:+ for source, count in (decision.get("attribution_sources") or {}).items():+ attribution[str(source)] = attribution.get(str(source), 0) + int(count or 0)+ score.attribution_sources = dict(sorted(attribution.items()))++ # ---- the four closure cuts, over proposed closures ---------------------+ #+ # Spans every decision, including the unlabeled, because the unknown-label+ # share among closures is one of the four questions. Errored decisions+ # cannot be closures (a refusal retains the alert), and an abstention is+ # not in the closable verdict set, so neither needs excluding by hand.+ proposed = [+ d+ for d in decisions+ if not d.get("error") and d.get("verdict") in _AUTO_CLOSABLE_VERDICTS and float(d.get("confidence") or 0.0) >= auto_close_threshold+ ]+ score.closures_proposed = len(proposed)+ score.closures_executed = 0 # replay executes nothing, by construction+ known_truth = [d for d in proposed if d.get("labelled") and d.get("expected_disposition") in GRADED_DISPOSITIONS]+ malicious_closed = [d for d in known_truth if d.get("expected_disposition") == MALICIOUS]+ score.malicious_closed_count = len(malicious_closed)+ score.closure_contamination = _ratio(len(malicious_closed), len(known_truth))+ score.closure_unknown_share = _ratio(len(proposed) - len(known_truth), len(proposed))++ labelled_full = [d for d in decisions if d.get("labelled") and d.get("expected_disposition") in GRADED_DISPOSITIONS]+ malicious_full = [d for d in labelled_full if d.get("expected_disposition") == MALICIOUS]+ benign_family_full = [d for d in labelled_full if d.get("expected_disposition") != MALICIOUS]+ score.malicious_closure_rate = _ratio(len(malicious_closed), len(malicious_full))+ benign_closed = [d for d in known_truth if d.get("expected_disposition") != MALICIOUS]+ score.benign_closure_coverage = _ratio(len(benign_closed), len(benign_family_full))++ # ---- full-cohort malicious recall ---------------------------------------+ #+ # Over every labelled malicious case, errored included. Each case lands in+ # exactly one of four buckets — caught, abstained, errored, or answered+ # with a non-malicious verdict — and the buckets sum to the denominator,+ # so nothing vanishes.+ score.malicious_support_full = len(malicious_full)+ caught_full = sum(1 for d in malicious_full if not d.get("error") and d.get("verdict") == MALICIOUS)+ score.malicious_recall_full_cohort = _ratio(caught_full, len(malicious_full))+ score.malicious_errored = sum(1 for d in malicious_full if d.get("error"))+ score.malicious_abstained = sum(1 for d in malicious_full if not d.get("error") and _is_abstention(d))+ score.malicious_reached_review = score.malicious_abstained + score.malicious_errored+ score.malicious_closed_as_negative = len(malicious_full) - caught_full - score.malicious_reached_reviewif not labelled:score.headline_withheld_reason = (@@ -678,6 +811,7 @@ def score_replay(score.per_rule = _segment(labelled, "rule_id")score.per_source = _segment(labelled, "vendor")+ score.per_severity = _segment(labelled, "severity")return score@@ -710,6 +844,16 @@ def _ms(value: float | None) -> str:return "not measured" if value is None else f"{value:,.0f} ms"+def _attribution(score: ReplayScore) -> str:+ """Who vouched for the serving models, as per-source call counts."""+ if not score.attribution_sources:+ if score.llm_calls:+ return f"none of the {score.llm_calls} call(s) was attributed by any party"+ return "no call was placed, so there is nothing to attribute"+ parts = [f"{source}: {count}" for source, count in sorted(score.attribution_sources.items())]+ return f"{sum(score.attribution_sources.values())} of {score.llm_calls} call(s) attributed ({', '.join(parts)})"++def _models(score: ReplayScore) -> str:"""Which model answered, distinguishing the two ways of not knowing.@@ -736,9 +880,13 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None ="""lines: list[str] = ["# Replay evaluation", ""]+ unattempted = "unknown — the caller did not say how many were requested" if score.unattempted is None else str(score.unattempted)+ requested = "not stated" if score.requested_total is None else str(score.requested_total)lines += ["## What was graded","",+ f"- Requested: {requested}. Attempted: {score.attempted}. Completed: {score.completed}. "+ f"Failed: {score.failed}. Unattempted: {unattempted}",f"- Decisions replayed: {score.decisions}",f"- Carried an analyst label: {score.labelled}",f"- Unlabelled, excluded from accuracy: {score.unlabeled}",@@ -752,6 +900,24 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"- Recall, Wilson 95% interval: {_interval(score.malicious_recall_wilson)}",f"- Precision: {_pct(score.malicious_precision)}","",+ "## Full cohort",+ "",+ "Selective recall above is over answered-or-abstained labelled cases; a run",+ "that errored on a malicious case dropped it from that denominator. The",+ "full-cohort figure keeps every labelled malicious case. The buckets sum",+ "to the denominator, so nothing vanishes.",+ "",+ f"- Malicious cases, full cohort: {score.malicious_support_full}",+ f"- Recall, full cohort: {_pct(score.malicious_recall_full_cohort)}",+ f"- Abstained (retained for a human): {score.malicious_abstained}",+ f"- Errored (retained for a human): {score.malicious_errored}",+ f"- Reached review one way or the other: {score.malicious_reached_review}",+ f"- Answered with a non-malicious verdict (reached nobody): {score.malicious_closed_as_negative}",+ "",+ "An abstention or an error retains the alert — an operational safety",+ "outcome, not a correct classification, and it is counted as a miss in",+ "both recall figures.",+ "","## Headline accuracy","",]@@ -791,6 +957,16 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None ="rather than a zero, which would read as closing things and getting","them all wrong.","",+ "## Proposed closures",+ "",+ f"- Proposed: {score.closures_proposed}. Executed: {score.closures_executed} "+ "(replay executes nothing; every closure here is what the stated policy would have closed)",+ f"- Malicious closure rate: {_pct(score.malicious_closure_rate)} "+ f"({score.malicious_closed_count} of {score.malicious_support_full} labelled malicious)",+ f"- Closure contamination: {_pct(score.closure_contamination)} (malicious among closures with known truth)",+ f"- Benign closure coverage: {_pct(score.benign_closure_coverage)} (benign-family items the policy would absorb)",+ f"- Unknown-label share among closures: {_pct(score.closure_unknown_share)}",+ "","## Time to verdict","",f"- p50: {_ms(score.time_to_verdict_p50_ms)}",@@ -839,6 +1015,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =breakdowns: tuple[tuple[str, list[SegmentScore]], ...] = (("Per rule", score.per_rule),("Per source", score.per_source),+ ("Per severity", score.per_severity),)for title, segments in breakdowns:lines += ["", f"## {title}", "", "| Key | Answered | Accuracy | Malicious | Malicious recall |", "|---|---|---|---|---|"]@@ -861,6 +1038,7 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"p95 {'not measured' if score.p95_latency_ms is None else f'{score.p95_latency_ms:.0f} ms'}",f"- Model calls placed: {score.llm_calls}",f"- Models: {_models(score)}",+ f"- Attribution: {_attribution(score)}","","## Method","",diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 4b89f5f50..1e9dfefc1 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -420,6 +420,16 @@ class Settings(BaseSettings):default=False,validation_alias=AliasChoices("RETRO_HUNT_ENABLED", "AISOC_RETRO_HUNT_ENABLED"),)+ # Evaluation mode for retro-hunts: sweeps run exactly as live ones do —+ # and still consume the tenant's sweep budget, because the warehouse scan+ # the budget bounds was performed — but matches come back as recorded+ # *proposals* and the mutation boundary inside `sweep_tenant` withholds+ # every write: no alert opens, no sighting row lands, no counter moves.+ # For rehearsing a re-hunt over history; off means live.+ RETRO_HUNT_DRY_RUN: bool = Field(+ default=False,+ validation_alias=AliasChoices("RETRO_HUNT_DRY_RUN", "AISOC_RETRO_HUNT_DRY_RUN"),+ )KAFKA_TOPIC_THREAT_INTEL: str = "aisoc.threat_intel"RETRO_HUNT_CONSUMER_GROUP: str = "aisoc-retro-hunt"diff --git a/services/api/app/services/retro_hunt/service.py b/services/api/app/services/retro_hunt/service.pyindex cf830b06f..fb8383594 100644--- a/services/api/app/services/retro_hunt/service.py+++ b/services/api/app/services/retro_hunt/service.py@@ -100,6 +100,14 @@ class TenantSweepReport:alert_id: uuid.UUID | None = Nonededuplicated: bool = Falsedetail: str = ""+ #: True when this sweep ran in evaluation (dry-run) mode: the match was+ #: recorded as a *proposal* and nothing was opened, refreshed or written.+ #: A proposed open must never read as an executed one, which is why this+ #: is a field on the report rather than a phrase in ``detail``.+ proposed: bool = False+ #: The alert a live sweep would have opened, by its identifying fields.+ #: ``None`` outside dry-run mode and on non-matches.+ proposed_alert: dict[str, Any] | None = Nonedef alert_idempotency_key(indicator_type: str, value: str) -> str:@@ -280,12 +288,22 @@ async def sweep_tenant(indicator: IntelIndicator,settings_row: RetroHuntSettings | None = None,now: datetime | None = None,+ dry_run: bool = False,) -> TenantSweepReport:"""Sweep one tenant for one indicator and open at most one alert.The caller is responsible for the transaction. Nothing here commits, so abatch of tenants can be swept and committed together, and a failure on onetenant does not half-write another.++ ``dry_run`` is the evaluation mode: the warehouse sweep runs exactly as a+ live one does — and therefore still consumes the tenant's sweep budget,+ because the scan the budget bounds was performed — but every mutation+ after it is withheld *here, at the boundary that owns the writes*: no+ alert is opened, no sighting row is inserted and the dedup branch leaves+ even its counters untouched. The match comes back as a **proposal** on+ the report, so a re-hunt can be rehearsed over history and graded without+ any ability to touch production state, whatever the caller does next."""now = now or datetime.now(UTC)@@ -351,6 +369,23 @@ async def sweep_tenant(surfaces = _matched_surfaces(outcome)+ if existing is not None and dry_run:+ # Known already, and this is a rehearsal: report what a live sweep+ # would have refreshed and leave even the counters alone. Advancing+ # `times_seen` from an evaluation would make the production record+ # claim sweeps that were drills.+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="swept",+ matched=True,+ alert_id=existing.alert_id,+ deduplicated=True,+ proposed=True,+ detail=(+ "DRY RUN — this indicator already has an alert for this tenant; a live sweep would have refreshed its sighting counters."+ ),+ )+if existing is not None:# Already known. Refresh what we learned and open nothing: this is the# branch that keeps a daily-republished indicator from becoming a@@ -373,6 +408,28 @@ async def sweep_tenant(),)+ if dry_run:+ # The mutation boundary. Everything an operator needs to judge the+ # would-be alert travels on the report; nothing reaches the session.+ return TenantSweepReport(+ tenant_id=tenant_id,+ outcome="swept",+ matched=True,+ proposed=True,+ proposed_alert={+ "title": f"Retro-hunt: {indicator.indicator_type} {indicator.value} seen in your history",+ "severity": DEFAULT_SEVERITY,+ "category": ALERT_CATEGORY,+ "idempotency_key": alert_idempotency_key(indicator.indicator_type, indicator.value),+ "total_sightings": outcome.total_sightings,+ "matched_surfaces": surfaces,+ "not_checked": outcome.gaps,+ "intel_first_seen_at": (indicator.first_seen_at.isoformat() if indicator.first_seen_at else None),+ "lookback_days": outcome.lookback_days,+ },+ detail=f"DRY RUN — a live sweep would have opened one alert for {outcome.total_sightings} sighting(s).",+ )+alert = await _open_alert(db, tenant_id=tenant_id, indicator=indicator, outcome=outcome)db.add(RetroHuntSighting(diff --git a/services/api/app/workers/retro_hunt_consumer.py b/services/api/app/workers/retro_hunt_consumer.pyindex ce7c24832..e2fcabeb7 100644--- a/services/api/app/workers/retro_hunt_consumer.py+++ b/services/api/app/workers/retro_hunt_consumer.py@@ -76,6 +76,17 @@ def _enabled() -> bool:return bool(getattr(settings, "RETRO_HUNT_ENABLED", False))+def _dry_run() -> bool:+ """Evaluation mode: sweeps run and report proposals, mutations are withheld.++ Read per sweep rather than once at startup, so an operator can flip a+ deployment into rehearsal before a noisy feed lands without a restart.+ The withholding itself lives inside ``sweep_tenant`` at the write+ boundary — this flag only selects the mode; it is not the guard.+ """+ return bool(getattr(settings, "RETRO_HUNT_DRY_RUN", False))++def parse_intel_event(raw: bytes | str) -> dict[str, Any] | None:"""Decode one message from the intel topic, or ``None`` if it is not one.@@ -280,7 +291,15 @@ async def handle_indicator(indicator: IntelIndicator) -> list[TenantSweepReport]tenant_id=settings_row.tenant_id,indicator=indicator,settings_row=settings_row,+ dry_run=_dry_run(),)+ if report.proposed:+ logger.info(+ "retro_hunt.dry_run_proposal tenant=%s matched=%s detail=%s",+ settings_row.tenant_id,+ report.matched,+ report.detail.replace("\r", "").replace("\n", " ")[:200],+ )await db.flush()except Exception:await savepoint.rollback()diff --git a/services/api/tests/test_retro_hunt.py b/services/api/tests/test_retro_hunt.pyindex eb1dbac02..e6e79e223 100644--- a/services/api/tests/test_retro_hunt.py+++ b/services/api/tests/test_retro_hunt.py@@ -209,6 +209,168 @@ async def _budget(row: _FakeSettings, *, now: datetime) -> bool:return await _consume_budget(cast(AsyncSession, None), cast(RetroHuntSettings, row), now=now)+# ------------------------------------------------------------- dry-run mode+++class _SpySession:+ """A session double that records every write it is asked to make.++ A spy rather than a richer fake, because the property under test *is* the+ write boundary: an evaluation sweep must record proposals and mutate+ nothing, and the honest way to assert "mutated nothing" is a counter that+ would have caught the mutation — the same shape as ShadowTriageWriter.+ """++ def __init__(self, *, existing_sighting: Any = None) -> None:+ self.added: list[Any] = []+ self.flushed = 0+ self._existing = existing_sighting++ async def get(self, *_: Any, **__: Any) -> None:+ return None++ async def execute(self, *_: Any, **__: Any) -> Any:+ existing = self._existing++ class _Result:+ def scalar_one_or_none(self) -> Any:+ return existing++ return _Result()++ def add(self, obj: Any) -> None:+ self.added.append(obj)++ async def flush(self) -> None:+ self.flushed += 1+++def _matched_outcome() -> SweepOutcome:+ return SweepOutcome(+ indicator_type="ip",+ value="203.0.113.7",+ lookback_days=90,+ lake=LakeSweepResult(+ indicator_type="ip",+ value="203.0.113.7",+ checked=True,+ sightings=4,+ first_sighting_at="2026-08-01T00:00:00+00:00",+ last_sighting_at="2026-08-03T00:00:00+00:00",+ columns_searched=("src_endpoint_ip",),+ connector_types=["aws_cloudtrail"],+ hosts=["ws-1"],+ users=[],+ ),+ federated=FederatedSweepResult(checked=False, unavailable_reason="not enabled for this tenant"),+ )+++def _enabled_settings() -> _FakeSettings:+ row = _FakeSettings(max_sweeps_per_hour=10, max_sweeps_per_day=10)+ row.enabled = True # type: ignore[attr-defined]+ row.lookback_days = 90 # type: ignore[attr-defined]+ row.include_federated = False # type: ignore[attr-defined]+ return row+++async def test_dry_run_records_the_proposal_and_writes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:+ """Evaluation mode: the sweep runs, the alert is proposed, nothing lands.++ The guard sits at the mutation boundary inside `sweep_tenant` — not in a+ prompt, not in the caller — so a dry run is *technically unable* to open+ an alert or a sighting row whatever the caller does next.+ """+ from app.services.retro_hunt import service as service_module++ async def _fake_sweep(*_: Any, **__: Any) -> SweepOutcome:+ return _matched_outcome()++ monkeypatch.setattr(service_module, "sweep_indicator", _fake_sweep)++ db = _SpySession()+ report = await service_module.sweep_tenant(+ cast(AsyncSession, db),+ tenant_id=TENANT,+ indicator=IntelIndicator(indicator_type="ip", value="203.0.113.7", feed_source="feodo"),+ settings_row=cast(RetroHuntSettings, _enabled_settings()),+ dry_run=True,+ )++ assert report.outcome == "swept"+ assert report.matched+ assert report.proposed, "a dry-run match is a proposal, never an executed open"+ assert report.alert_id is None+ assert report.proposed_alert is not None+ assert report.proposed_alert["idempotency_key"] == alert_idempotency_key("ip", "203.0.113.7")+ assert report.proposed_alert["total_sightings"] == 4+ assert db.added == [], "a dry run must write no alert and no sighting row"+ assert db.flushed == 0+++async def test_dry_run_does_not_mutate_an_existing_sighting(monkeypatch: pytest.MonkeyPatch) -> None:+ """The dedup branch updates times_seen/last_matched_at in a real sweep;+ an evaluation re-running history must leave even those counters alone."""+ from app.services.retro_hunt import service as service_module++ async def _fake_sweep(*_: Any, **__: Any) -> SweepOutcome:+ return _matched_outcome()++ monkeypatch.setattr(service_module, "sweep_indicator", _fake_sweep)++ @dataclass+ class _Sighting:+ alert_id: uuid.UUID+ times_seen: int = 3+ last_matched_at: datetime | None = None+ sightings: int = 1+ last_sighting_at: Any = None+ matched_surfaces: Any = None+ updated_at: Any = None++ existing = _Sighting(alert_id=uuid.uuid4())+ db = _SpySession(existing_sighting=existing)++ report = await service_module.sweep_tenant(+ cast(AsyncSession, db),+ tenant_id=TENANT,+ indicator=IntelIndicator(indicator_type="ip", value="203.0.113.7", feed_source="feodo"),+ settings_row=cast(RetroHuntSettings, _enabled_settings()),+ dry_run=True,+ )++ assert report.proposed and report.deduplicated+ assert report.alert_id == existing.alert_id, "the proposal names the record it would have refreshed"+ assert existing.times_seen == 3, "a dry run must not advance the sighting counters"+ assert existing.last_matched_at is None+ assert db.added == []+++async def test_a_real_sweep_still_opens_the_alert(monkeypatch: pytest.MonkeyPatch) -> None:+ """The negative control for the dry-run guard: the same sweep without+ dry_run adds the alert and the sighting row through the same session."""+ from app.services.retro_hunt import service as service_module++ async def _fake_sweep(*_: Any, **__: Any) -> SweepOutcome:+ return _matched_outcome()++ monkeypatch.setattr(service_module, "sweep_indicator", _fake_sweep)++ db = _SpySession()+ report = await service_module.sweep_tenant(+ cast(AsyncSession, db),+ tenant_id=TENANT,+ indicator=IntelIndicator(indicator_type="ip", value="203.0.113.7", feed_source="feodo"),+ settings_row=cast(RetroHuntSettings, _enabled_settings()),+ )++ assert report.matched and not report.proposed+ assert len(db.added) == 2, "a live sweep adds the alert and the sighting row"++@pytest.mark.asyncioasync def test_budget_refuses_once_the_hourly_allowance_is_spent() -> None:row = _FakeSettings()diff --git a/services/fusion/app/models/alert.py b/services/fusion/app/models/alert.pyindex 0b7ffcda6..7a5216edf 100644--- a/services/fusion/app/models/alert.py+++ b/services/fusion/app/models/alert.py@@ -123,11 +123,47 @@ class RawAlert(BaseModel):return hashlib.sha256(canonical.encode()).hexdigest()def correlation_key(self) -> str:- """Generate a key for alert correlation (grouping related alerts)."""- # Correlate by primary entity and tactic- entity = self.src_ip or self.hostname or self.username or self.domain or "unknown"- tactic = self.mitre_tactics[0] if self.mitre_tactics else "unknown"- return f"{self.tenant_id}:{entity}:{tactic}"+ """The key related alerts group under: entity and tactic, when both exist.++ When either is missing, the key **narrows instead of widening**. The+ previous fallback substituted the literal ``"unknown"`` for a missing+ field, and since neither detection engine has ever set+ ``mitre_tactics`` (the ruleset carries technique ids only), every+ detection alert's key read ``{tenant}:{entity}:unknown`` — all of an+ entity's detection alerts, whatever the rule or kill-chain stage,+ collapsed into one incident per window, titled after whichever alert+ arrived first. An exfiltration alert became row 37 inside an incident+ named for a port scan. Alerts with no entity either were worse:+ ``{tenant}:unknown:unknown`` merged unrelated alerts **tenant-wide**.++ The fallback ladder, most to least evidence of relatedness:++ * entity + tactic — unchanged, the designed key;+ * entity, no tactic — scoped to the detection rule. Same rule firing+ repeatedly on one entity is the storm correlation exists for;+ different rules on one entity are not known to be one incident, and+ merging them buries the one that mattered. The cost is stated: one+ event firing N tactic-less rules now makes N incidents rather than+ one, which fragments rather than buries — the recoverable+ direction, since a reviewer can join incidents and cannot unbury+ an alert nobody rendered;+ * no entity — never groups across rules, and a tactic (when present)+ narrows it further rather than standing alone tenant-wide;+ * no entity and no rule — groups by the dedup fingerprint, so exact+ repeats of one shape still collapse and nothing else does. Zero+ evidence of relatedness groups nothing.+ """+ entity = self.src_ip or self.hostname or self.username or self.domain+ tactic = self.mitre_tactics[0] if self.mitre_tactics else None+ if entity and tactic:+ return f"{self.tenant_id}:{entity}:{tactic}"+ rule = self.rule_id or self.rule_name+ if entity:+ scope = f"rule:{rule}" if rule else f"fp:{self.fingerprint()[:16]}"+ return f"{self.tenant_id}:{entity}:{scope}"+ if rule:+ return f"{self.tenant_id}:no-entity:rule:{rule}:{tactic or 'no-tactic'}"+ return f"{self.tenant_id}:no-entity:fp:{self.fingerprint()[:16]}"class ConfidenceLabel(str, Enum):diff --git a/services/fusion/app/services/correlator.py b/services/fusion/app/services/correlator.pyindex 390eca932..374db5265 100644--- a/services/fusion/app/services/correlator.py+++ b/services/fusion/app/services/correlator.py@@ -90,11 +90,47 @@ class Correlator:)return True, incident- # Create a new incident+ # Create a new incident. The payload is saved before the index points+ # at it, so a concurrent reader can never resolve the index to an+ # incident that does not exist yet.incident = self._create_incident(alert)await self._save_incident(incident)- # Map correlation key -> incident ID- await self._redis.set(index_key, str(incident.id), ex=self._window)+ # Map correlation key -> incident ID, atomically and only if no other+ # worker got there first. The previous plain SET made the two-replica+ # creation race invisible: both GETs missed, both SETs "succeeded",+ # the last writer owned the index, and the first writer's incident —+ # with its alert — became an unreachable orphan. NX makes exactly one+ # creator win; the loser merges its alert into the winner's incident,+ # and its own just-saved payload expires unreferenced, which costs a+ # few bytes of Redis for one window and loses nothing.+ created = await self._redis.set(index_key, str(incident.id), ex=self._window, nx=True)+ if not created:+ winner_bytes = await self._redis.get(index_key)+ winner_id = ""+ if winner_bytes is not None:+ try:+ winner_id = winner_bytes.decode() if isinstance(winner_bytes, bytes) else str(winner_bytes)+ except UnicodeDecodeError:+ winner_id = ""+ winner = await self._load_incident(winner_id) if winner_id else None+ if winner is not None and winner.alert_count < self._max_alerts:+ winner = await self._merge_alert(winner, alert)+ await self._save_incident(winner)+ logger.info(+ "Alert correlated to incident created concurrently",+ incident_id=winner_id,+ alert_id=str(alert.id),+ alert_count=winner.alert_count,+ )+ return True, winner+ # The winner expired or is unreadable in the gap. Take the index+ # over — our payload is already saved — rather than losing the+ # alert to a dead pointer. A merge that raced a *merge* (not a+ # creation) is still last-writer-wins on the incident payload;+ # that narrower window is documented in the live concurrency+ # test and closing it needs an owner-checked script like the+ # windowed engine's, not a bigger hammer here.+ await self._redis.set(index_key, str(incident.id), ex=self._window)logger.info("New incident created from alert",incident_id=str(incident.id),diff --git a/services/fusion/tests/integration/test_correlator_live.py b/services/fusion/tests/integration/test_correlator_live.pynew file mode 100644index 000000000..87958480f--- /dev/null+++ b/services/fusion/tests/integration/test_correlator_live.py@@ -0,0 +1,188 @@+"""The real Correlator against a real Redis: windows, tenants, restarts, races.++Every other correlation test drives the grouping *decision* —+`correlation_key()` plus a window — or a FakeRedis double. None of them can+answer the questions this file exists for, because each one is a property of+the server and the storage layer the doubles replace: does the window+actually expire, does a replacement worker keep correlating into the open+incident, can two concurrent creators split one logical incident in half.++The concurrency test is the reason this file exists. The pre-fix creation+path was GET (miss) → SET for every worker: the last SET owned the index and+every other worker's incident became an unreachable orphan carrying a real+alert — an alert that vanished from incident lineage while both callers were+told everything worked. A single-threaded double passes that sequence by+construction, which is exactly the more-capable-than-reality shape this+repository keeps finding.++Skips cleanly when no server is reachable, and says so rather than passing+quietly.++ docker run -d --name feedback-redis -p 63790:6379 redis:7-alpine+ AISOC_TEST_REDIS=redis://127.0.0.1:63790/0 pytest tests/integration/test_correlator_live.py+"""++from __future__ import annotations++import asyncio+import os+import uuid++import pytest+import pytest_asyncio+from app.models.alert import AlertSeverity, RawAlert+from app.services.correlator import _CORRELATION_PREFIX, Correlator++URL = os.getenv("AISOC_TEST_REDIS", "").strip()+pytestmark = pytest.mark.skipif(not URL, reason="set AISOC_TEST_REDIS=redis://host:port/db to run the live correlator proof")++TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-000000000001")+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-000000000002")+++@pytest_asyncio.fixture+async def redis(): # noqa: ANN201+ aioredis = pytest.importorskip("redis.asyncio")+ client = aioredis.from_url(URL)+ await client.flushdb()+ yield client+ await client.aclose()+++def _alert(+ *,+ tenant: uuid.UUID = TENANT_A,+ host: str | None = None,+ tactic: str | None = None,+ rule: str | None = None,+ title: str = "live test alert",+) -> RawAlert:+ return RawAlert(+ tenant_id=tenant,+ source="live-test",+ title=title,+ hostname=host,+ severity=AlertSeverity.MEDIUM,+ mitre_tactics=[tactic] if tactic else [],+ rule_id=rule,+ )+++def _correlator(redis, *, window: int = 3600) -> Correlator: # noqa: ANN001+ correlator = Correlator(redis)+ # The window is read from settings at construction; the live suite needs+ # a short one for the expiry proof and sets it on the instance it built+ # rather than mutating process settings under every other test.+ correlator._window = window+ return correlator+++async def test_same_key_within_window_joins_one_incident(redis) -> None: # noqa: ANN001+ correlator = _correlator(redis)+ host = f"ws-{uuid.uuid4().hex[:8]}"++ first_correlated, first = await correlator.correlate(_alert(host=host, tactic="execution"))+ second_correlated, second = await correlator.correlate(_alert(host=host, tactic="execution"))++ assert not first_correlated+ assert second_correlated+ assert second.id == first.id+ assert second.alert_count == 2+++async def test_tenant_boundary_separates_identical_entities(redis) -> None: # noqa: ANN001+ """Two tenants, same entity and tactic: never one incident."""+ correlator = _correlator(redis)+ host = f"ws-{uuid.uuid4().hex[:8]}"++ _, incident_a = await correlator.correlate(_alert(tenant=TENANT_A, host=host, tactic="execution"))+ correlated_b, incident_b = await correlator.correlate(_alert(tenant=TENANT_B, host=host, tactic="execution"))++ assert not correlated_b, "a second tenant's identical alert must open its own incident"+ assert incident_b.id != incident_a.id+ assert incident_b.tenant_id == TENANT_B+++async def test_window_expiry_opens_a_new_incident(redis) -> None: # noqa: ANN001+ """A late event lands in a new incident once the window has expired."""+ correlator = _correlator(redis, window=1)+ host = f"ws-{uuid.uuid4().hex[:8]}"++ _, first = await correlator.correlate(_alert(host=host, tactic="execution"))+ await asyncio.sleep(1.2)+ correlated, second = await correlator.correlate(_alert(host=host, tactic="execution"))++ assert not correlated, "the window expired; a new incident opens rather than a stale one growing forever"+ assert second.id != first.id+++async def test_restart_keeps_correlating_into_the_open_incident(redis) -> None: # noqa: ANN001+ """Correlation state lives in Redis, not the process: a replacement worker joins the same incident."""+ host = f"ws-{uuid.uuid4().hex[:8]}"++ _, first = await _correlator(redis).correlate(_alert(host=host, tactic="execution"))+ # A fresh Correlator stands in for the restarted replica.+ correlated, second = await _correlator(redis).correlate(_alert(host=host, tactic="execution"))++ assert correlated+ assert second.id == first.id+++async def test_detection_shaped_alerts_group_per_rule_in_the_real_store(redis) -> None: # noqa: ANN001+ """The conservative fallback holds through the production path, not only the key.++ Three tactic-less detection alerts on one entity: two of one rule join+ one incident, the third rule opens its own. Before the fallback all+ three shared `{tenant}:{entity}:unknown`.+ """+ correlator = _correlator(redis)+ host = f"ws-{uuid.uuid4().hex[:8]}"++ _, storm = await correlator.correlate(_alert(host=host, rule="r-1", title="storm 1"))+ joined, storm_2 = await correlator.correlate(_alert(host=host, rule="r-1", title="storm 2"))+ other_correlated, other = await correlator.correlate(_alert(host=host, rule="r-2", title="different rule"))++ assert joined and storm_2.id == storm.id+ assert not other_correlated, "a different rule on the same entity is not known to be one incident"+ assert other.id != storm.id+++async def test_concurrent_creators_converge_on_one_incident(redis) -> None: # noqa: ANN001+ """N concurrent first-arrivals for one key cannot split the incident.++ With `SET NX` exactly one creator wins the index and the losers merge+ into the winner, so every caller is told the same incident id and no+ alert lands in an unreachable orphan.++ What this deliberately does NOT assert: `alert_count == N`. Concurrent+ *merges* into one incident are still read-modify-write and can lose+ increments to each other; that narrower window is a known limit, named+ here and in the correlator, and closing it takes an owner-checked+ script like the windowed engine's. The property that must hold — the+ one the fix is for — is that no caller is handed a divergent incident.+ """+ correlator = _correlator(redis)+ host = f"ws-{uuid.uuid4().hex[:8]}"+ alerts = [_alert(host=host, tactic="execution", title=f"racer {i}") for i in range(10)]++ results = await asyncio.gather(*(correlator.correlate(a) for a in alerts))++ incident_ids = {str(incident.id) for _, incident in results}+ assert len(incident_ids) == 1, f"concurrent creators split one logical incident into {len(incident_ids)}"++ index_keys = [key async for key in redis.scan_iter(match=f"{_CORRELATION_PREFIX}*{host}*")]+ assert len(index_keys) == 1+ indexed = await redis.get(index_keys[0])+ assert (indexed.decode() if isinstance(indexed, bytes) else str(indexed)) in incident_ids++ # At least one merge landed beside the winner's own alert; the exact+ # count under racing merges is the documented limit above.+ winner_id = next(iter(incident_ids))+ reloaded = await correlator._load_incident(winner_id)+ assert reloaded is not None and reloaded.alert_count >= 2diff --git a/services/fusion/tests/test_alert_model.py b/services/fusion/tests/test_alert_model.pyindex e9e17d041..24ddb426e 100644--- a/services/fusion/tests/test_alert_model.py+++ b/services/fusion/tests/test_alert_model.py@@ -77,9 +77,18 @@ class TestRawAlertCorrelationKey:assert "server-42" in keyassert key.endswith(":execution")- def test_correlation_key_unknown_when_no_entity_or_tactic(self) -> None:+ def test_correlation_key_narrows_when_no_entity_or_tactic(self) -> None:+ """A missing identifier narrows the group instead of widening it.++ The old fallback substituted the literal "unknown" for both halves,+ which merged every entity-less, tactic-less alert tenant-wide. With+ no entity and no rule, the key now carries the dedup fingerprint, so+ only exact repeats of one shape group together.+ """a = _alert()- assert a.correlation_key().endswith(":unknown:unknown")+ key = a.correlation_key()+ assert ":no-entity:fp:" in key+ assert key == _alert().correlation_key(), "the same shape still groups with itself"def test_correlation_key_includes_tenant(self) -> None:tenant = UUID("22222222-2222-2222-2222-222222222222")diff --git a/services/fusion/tests/test_alert_reduction_real.py b/services/fusion/tests/test_alert_reduction_real.pyindex a078120d8..15cd86314 100644--- a/services/fusion/tests/test_alert_reduction_real.py+++ b/services/fusion/tests/test_alert_reduction_real.py@@ -182,20 +182,140 @@ def test_entity_precedence_is_src_ip_then_hostname() -> None:def test_alerts_without_a_tactic_do_not_all_collapse_together() -> None:- """`correlation_key()` falls back to the literal "unknown" for both- entity and tactic. Two unrelated alerts each missing one field still- differ on the other; two missing both would merge, which is worth- knowing rather than discovering in production."""+ """A missing identifier narrows the group instead of widening it.++ The previous fallback substituted the literal "unknown", and since+ neither detection engine sets `mitre_tactics`, every detection alert on+ one entity collapsed into one incident per window regardless of rule —+ and alerts with no entity merged tenant-wide. This file pinned that as+ "current behaviour, pinned so a change to it is deliberate"; this is the+ deliberate change.+ """a = RawAlert(tenant_id=TENANT, source="s", title="a", hostname="ws-1")b = RawAlert(tenant_id=TENANT, source="s", title="b", hostname="ws-2")assert a.correlation_key() != b.correlation_key()- bare_a = RawAlert(tenant_id=TENANT, source="s", title="a")- bare_b = RawAlert(tenant_id=TENANT, source="s", title="b")- assert bare_a.correlation_key() == bare_b.correlation_key(), (- "two alerts with no entity and no tactic share a key and will merge; "- "this is current behaviour, pinned so a change to it is deliberate"+ # Same entity, no tactic: grouping is per detection rule. The same rule+ # firing repeatedly is the storm correlation exists for; two different+ # rules are not known to be one incident and no longer merge.+ storm_1 = RawAlert(tenant_id=TENANT, source="s", title="a", hostname="ws-1", rule_id="r-1")+ storm_2 = RawAlert(tenant_id=TENANT, source="s", title="b", hostname="ws-1", rule_id="r-1")+ other_rule = RawAlert(tenant_id=TENANT, source="s", title="c", hostname="ws-1", rule_id="r-2")+ assert storm_1.correlation_key() == storm_2.correlation_key()+ assert storm_1.correlation_key() != other_rule.correlation_key()+ assert storm_1.correlation_key() == f"{TENANT}:ws-1:rule:r-1"++ # No entity: never groups across rules, and never tenant-wide.+ bare_a = RawAlert(tenant_id=TENANT, source="s", title="a", rule_id="r-1")+ bare_b = RawAlert(tenant_id=TENANT, source="s", title="b", rule_id="r-2")+ assert bare_a.correlation_key() != bare_b.correlation_key()+ assert bare_a.correlation_key() == f"{TENANT}:no-entity:rule:r-1:no-tactic"++ # No entity and no rule: zero evidence of relatedness groups nothing but+ # exact repeats of one shape (the dedup fingerprint).+ blank_a = RawAlert(tenant_id=TENANT, source="s", title="a")+ blank_b = RawAlert(tenant_id=TENANT, source="s", title="b")+ assert blank_a.correlation_key() != blank_b.correlation_key(), (+ "two alerts with no entity, no tactic and no rule carry no evidence of being related; merging them buries one under the other")+ repeat = RawAlert(tenant_id=TENANT, source="s", title="a")+ assert blank_a.correlation_key() == repeat.correlation_key(), "an exact repeat of the same shape still groups"+++#: The detection-shaped measurement. Both detection engines emit alerts with+#: a rule_id and NO mitre_tactics, so this stream — not the tactic-carrying+#: one above — is the shape the fallback governs. Measured on this fixed+#: cohort before and after the fallback landed (same stream, same window,+#: real `correlation_key()` both times):+#:+#: before 574 incidents, 42.6 % reduction, 36 incident-groups spanning+#: more than one rule, every no-entity alert merged tenant-wide+#: after 755 incidents, 24.5 % reduction, 0 cross-rule groups+#:+#: The reduction went DOWN and that is the honest direction: the difference+#: was unrelated alerts being counted as grouped. Review-work reduction is+#: only worth having over groups that are actually related.+DETECTION_STREAM_REDUCTION_PCT = 24.5++DETECTION_RULES = [f"det-rule-{i:02d}" for i in range(14)]+++def build_detection_stream(size: int = STREAM_SIZE) -> list[tuple[datetime, RawAlert]]:+ """Detection-engine-shaped alerts: rule_id set, no tactics, ~4% entity-less."""+ start = datetime(2026, 9, 22, 8, 0, tzinfo=UTC)+ stream: list[tuple[datetime, RawAlert]] = []+ for n in range(size):+ rule = DETECTION_RULES[_seeded(n, "rule", len(DETECTION_RULES))]+ host: str | None+ if n % 25 == 0:+ host = None+ offset = timedelta(minutes=_seeded(n, "ne-time", 240))+ elif n % 10 < 4:+ host = f"ws-{_seeded(n, 'burst-host', 12):03d}"+ offset = timedelta(minutes=_seeded(n, "burst-time", 45))+ else:+ host = f"ws-{_seeded(n, 'wide-host', 400):03d}"+ offset = timedelta(minutes=_seeded(n, "wide-time", 1440))+ stream.append(+ (+ start + offset,+ RawAlert(+ tenant_id=TENANT,+ source="synthetic",+ title=f"alert {n}",+ hostname=host,+ severity=AlertSeverity.MEDIUM,+ rule_id=rule,+ mitre_tactics=[],+ ),+ )+ )+ return stream+++def _group_members(stream: list[tuple[datetime, RawAlert]], window: timedelta = WINDOW) -> dict[tuple[str, datetime], list[RawAlert]]:+ """Alerts by the incident-group they land in under the real key + window."""+ open_at: dict[str, datetime] = {}+ members: dict[tuple[str, datetime], list[RawAlert]] = {}+ for when, alert in sorted(stream, key=lambda pair: pair[0]):+ key = alert.correlation_key()+ opened = open_at.get(key)+ if opened is None or when - opened > window:+ open_at[key] = when+ members.setdefault((key, open_at[key]), []).append(alert)+ return members+++def test_detection_shaped_stream_reduction_and_purity() -> None:+ """The measurement for the alerts the fallback actually governs.++ Three properties, each a claim the published figure rests on:++ * the reduction matches the published constant, so the number in prose+ cannot drift from the measurement;+ * no incident group spans more than one detection rule — cross-rule+ merges were exactly the unrelated-collapse this fallback removes;+ * every alert is accounted for: group sizes sum to the stream size, so+ nothing vanished into the grouping.+ """+ stream = build_detection_stream()+ members = _group_members(stream)+ incidents = len(members)+ reduction = 1 - (incidents / len(stream))++ print(f"\n[eval] detection-shaped reduction (real correlation_key): {len(stream)} alerts -> {incidents} incidents = {reduction:.1%}")++ assert round(reduction * 100, 1) == DETECTION_STREAM_REDUCTION_PCT, (+ f"detection-shaped reduction is now {reduction:.1%} but DETECTION_STREAM_REDUCTION_PCT says "+ f"{DETECTION_STREAM_REDUCTION_PCT} % — update the constant and the published surfaces together"+ )++ cross_rule = [group for group in members.values() if len({a.rule_id for a in group}) > 1]+ assert not cross_rule, (+ f"{len(cross_rule)} incident group(s) span more than one detection rule; the conservative fallback exists to make that impossible"+ )++ assert sum(len(group) for group in members.values()) == len(stream), "every alert resolves to exactly one group; nothing may vanish"def test_the_stream_is_reproducible() -> None: