Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix: close the maturity plan's remaining clauses, and say what Stable means (#1105)
Beenu Arora83306e5b6e03
diff --git a/.github/workflows/lake-live.yml b/.github/workflows/lake-live.ymlindex e55513fb6..d65be277b 100644--- a/.github/workflows/lake-live.yml+++ b/.github/workflows/lake-live.yml@@ -33,7 +33,33 @@ jobs:lake-live:name: The shipped DDL loads and tenant scoping holdsruns-on: ubuntu-latest- timeout-minutes: 20+ timeout-minutes: 25++ # The route suite authenticates a real user against a real `users`+ # row, because `get_current_user` resolves the token's `sub` and+ # 401s on "User not found". A synthetic subject would be refused —+ # which is the behaviour worth keeping, since it is what makes the+ # tenant come from the credential rather than from an argument.+ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ LAKE_ROUTE_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ OTEL_SDK_DISABLED: "true"+steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7@@ -66,14 +92,6 @@ jobs:# The hunt suite below drives `app.hunt` from services/agents, a# different service with a different lock.- - name: Install agents from its lockfile- working-directory: services/agents- run: |- set -euo pipefail- poetry config virtualenvs.create false- poetry install --no-root --no-interaction- python -m pip install --quiet clickhouse-driver-# The hunt suite below drives `app.hunt` from services/agents, a# different service with a different lock.- name: Install agents from its lockfile@@ -94,6 +112,30 @@ jobs:doneecho "ClickHouse did not become ready"; docker logs lake-clickhouse | tail -40; exit 1+ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ # The layer `test_lake_live.py` stops short of: the caller is+ # authenticated, their tenant comes from the token rather than an+ # argument, and errors map onto status codes an operator reads.+ - name: A tenant-scoped query round-trips through POST /lake/sql+ working-directory: services/api+ env:+ ISOLATION_LAKE_ROUTE_DSN: ${{ env.LAKE_ROUTE_DSN }}+ DATABASE_URL: ${{ env.LAKE_ROUTE_DSN }}+ ISOLATION_REPO_ROOT: ${{ github.workspace }}+ run: python -m pytest ../../tests/isolation/test_lake_route_live.py -v --tb=short+- name: The shipped DDL loads and tenant scoping holdsworking-directory: services/apienv:diff --git a/.github/workflows/live-agent-eval.yml b/.github/workflows/live-agent-eval.ymlindex c40de90e7..c285cdbf2 100644--- a/.github/workflows/live-agent-eval.yml+++ b/.github/workflows/live-agent-eval.yml@@ -74,15 +74,37 @@ concurrency:jobs:live-agent:- name: Dispatch the real agent against a local model+ name: Dispatch the real agent (${{ matrix.model }})# The deep run stays on the schedule and on demand: ten incidents# through a CPU-hosted model is a 90-minute budget, which is not a# pull-request shape. The PR gate is `live-agent-smoke` below.if: github.event_name != 'pull_request'runs-on: ubuntu-latesttimeout-minutes: 90++ # Parity 3.2's first clause: grade the **shipped** model, not only+ # the small one that fits a runner comfortably.+ #+ # `qwen2.5:0.5b` is what the floor in `live_agent_floor.json` was+ # measured on, so it stays — removing it would orphan the floor. But+ # a number measured on a model nobody deploys describes the agent on+ # whatever the pins happened to resolve to, which is a different+ # claim from the one a reader takes from it.+ # `llama3.2:3b-instruct-q4_K_M` is what `docker-compose.yml` actually+ # pulls, so it is what a deployment runs.+ #+ # `fail-fast: false` because one model failing is a result about that+ # model, and cancelling the other would throw away the comparison+ # that is the entire point of a matrix.+ strategy:+ fail-fast: false+ matrix:+ model:+ - qwen2.5:0.5b+ - llama3.2:3b-instruct-q4_K_M+env:- OLLAMA_MODEL: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}+ OLLAMA_MODEL: ${{ github.event.inputs.model || matrix.model }}INCIDENT_LIMIT: ${{ github.event.inputs.incidents || '10' }}steps:@@ -140,14 +162,14 @@ jobs:# `AISOC_MODEL_PIN_<ROLE>`. Left as it was, every agent would have# asked Ollama for a gateway alias (`aisoc-recon`) that Ollama has# never heard of.- AISOC_MODEL_PIN_TRIAGE: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}- AISOC_MODEL_PIN_RECON: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}+ AISOC_MODEL_PIN_TRIAGE: ${{ env.OLLAMA_MODEL }}+ AISOC_MODEL_PIN_RECON: ${{ env.OLLAMA_MODEL }}AISOC_MODEL_PIN_INVESTIGATION: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}AISOC_MODEL_PIN_COPILOT: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}AISOC_MODEL_PIN_SUMMARY: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}AISOC_MODEL_PIN_REPORT: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}- AISOC_MODEL_PIN_NL: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}- AISOC_MODEL_PIN_HUNT: ${{ github.event.inputs.model || 'qwen2.5:0.5b' }}+ AISOC_MODEL_PIN_NL: ${{ env.OLLAMA_MODEL }}+ AISOC_MODEL_PIN_HUNT: ${{ env.OLLAMA_MODEL }}run: |set -euo pipefailpython3 scripts/run_evals.py \@@ -200,6 +222,43 @@ jobs:print(f"- warning: {w}")PY+ # Parity 3.4 / gap-closure 6.4: replay before and after, publish+ # the delta. Without this the comparator would be a library nobody+ # calls, which this repository has shipped enough of.+ #+ # The previous run's report comes from the last successful run of+ # this workflow on this model. When there is none — a first run, a+ # new matrix leg, an expired artefact — the step says so and stops+ # rather than inventing a baseline of zeros, because a delta+ # against an absent run is exactly the "not measured is not zero"+ # failure the comparator exists to refuse.+ - name: Delta against the previous run of this model+ if: always()+ continue-on-error: true+ id: delta+ env:+ GH_TOKEN: ${{ github.token }}+ MODEL: ${{ matrix.model }}+ run: |+ set -uo pipefail+ slug=$(printf '%s' "$MODEL" | tr -c 'a-zA-Z0-9' '-')+ prev=$(gh run list --workflow=live-agent-eval.yml --branch=main \+ --status=success --limit 10 --json databaseId --jq '.[].databaseId' | head -5)+ for run in $prev; do+ if gh run download "$run" -n "live-agent-eval-$run" -D /tmp/prev 2>/dev/null; then+ break+ fi+ done+ if [ ! -f /tmp/prev/live-agent-eval.json ]; then+ echo "No previous report for $MODEL. Reporting that, rather than a delta against" \+ "a baseline of zeros — which is the failure the comparator exists to refuse."+ exit 0+ fi+ python3 scripts/compare_eval_runs.py \+ --before /tmp/prev/live-agent-eval.json \+ --after live-agent-eval.json \+ --out "delta-$slug.md" | tee -a "$GITHUB_STEP_SUMMARY"+- name: Upload reportif: always()uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7@@ -208,6 +267,7 @@ jobs:path: |live-agent-eval.jsonlive-agent-eval.wet.json+ delta-*.mdif-no-files-found: warnretention-days: 30diff --git a/.github/workflows/playbook-pause-live.yml b/.github/workflows/playbook-pause-live.ymlindex c9c7a75f4..719654548 100644--- a/.github/workflows/playbook-pause-live.yml+++ b/.github/workflows/playbook-pause-live.yml@@ -33,7 +33,7 @@ permissions:jobs:playbook-pause-live:- name: Playbook pause and Investigation Ledger against real Postgres+ name: Playbook pause, ledger and evidence bundles against real Postgresruns-on: ubuntu-latesttimeout-minutes: 15@@ -86,6 +86,19 @@ jobs:poetry install --no-root --no-interactionpython -m pip install --quiet pytest pytest-asyncio+ # The evidence-bundle suite drives the **API** service through a+ # real ASGI client, so it pulls in that service's import chain —+ # which is not the agents one. It failed on `bcrypt`, reached+ # through app.core.security, and the fix is the same as the comment+ # above: install from the service's own lockfile rather than adding+ # the missing name to a hand-curated list, which only works until+ # the next import.+ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ poetry install --no-root --no-interaction+# The whole chain, in order.## This started as a cherry-picked 001/002/081 — enough for the pause@@ -130,6 +143,18 @@ jobs:ISOLATION_LEDGER_DSN: ${{ env.PLAYBOOK_DSN }}run: python -m pytest ../../tests/isolation/test_ledger_live.py -v --tb=short+ # Parity 3.7. The format's own suite builds bundles from dicts, so+ # it cannot show that the *route* assembles one from ledger rows —+ # where `raw_alert` is JSONB, `started_at` is tz-aware, ids are+ # UUIDs and cost is Numeric, every one of which has a repr JSON+ # cannot serialise.+ - name: An evidence bundle exports, verifies and stays tenant-scoped+ working-directory: services/api+ env:+ ISOLATION_BUNDLE_DSN: ${{ env.PLAYBOOK_DSN }}+ DATABASE_URL: ${{ env.PLAYBOOK_DSN }}+ run: python -m pytest ../../tests/isolation/test_evidence_bundle_live.py -v --tb=short+# The negative control.## `aisoc_playbook_pauses_run_idx` is the partial unique index ondiff --git a/.github/workflows/retro-hunt-live.yml b/.github/workflows/retro-hunt-live.ymlindex 9e61d4aba..f6ce03df8 100644--- a/.github/workflows/retro-hunt-live.yml+++ b/.github/workflows/retro-hunt-live.yml@@ -47,8 +47,34 @@ jobs:retro-hunt-live:name: A published indicator sweeps its tenant's recorded dataruns-on: ubuntu-latest- timeout-minutes: 25+ timeout-minutes: 30++ # The sweep reads its opted-in tenants from Postgres and writes+ # sightings back under RLS. As the schema owner neither of the two+ # defects this E2E found would appear, so the suite runs as the+ # `aisoc_app` runtime role — the one a deployment uses.+ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20+env:+ # The suite connects as the runtime role. The owner URL is only+ # for schema setup and for the fixture that writes the two tenant+ # rows — named `DATABASE_MIGRATION_URL` so it reads as what it is,+ # which is also what `check_runtime_db_role.py` looks for.+ RETRO_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only# Load-bearing. See the header.RETRO_HUNT_ENABLED: "true"ISOLATION_CLICKHOUSE_HOST: localhost@@ -113,6 +139,40 @@ jobs:ISOLATION_REPO_ROOT: ${{ github.workspace }}run: python -m pytest ../../tests/isolation/test_retro_hunt_live.py -v --tb=short+ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ # The seam the two suites either side of it never crossed: a real+ # indicator, published to a real broker in the feed's own envelope,+ # parsed by the real consumer, swept against real recorded data,+ # opening a real alert for the one tenant that was exposed.+ #+ # It found two defects on its first run, both invisible as the+ # schema owner: one tenant's pending rows were flushed under the+ # *next* tenant's RLS context, and a failed flush poisoned the+ # session so every later tenant was reported failed — the exact+ # thing the loop's own comment said must not happen.+ - name: An indicator travels feed → Kafka → sweep → alert+ working-directory: services/api+ env:+ ISOLATION_RETRO_PG_DSN: ${{ env.DATABASE_MIGRATION_URL }}+ DATABASE_URL: ${{ env.RETRO_DSN }}+ ISOLATION_REPO_ROOT: ${{ github.workspace }}+ CLICKHOUSE_HOST: localhost+ CLICKHOUSE_PORT: "9000"+ CLICKHOUSE_USER: default+ run: python -m pytest ../../tests/isolation/test_retro_hunt_e2e.py -v --tb=short+- name: The consumer tells a working message from poisonworking-directory: services/apirun: python -m pytest ../../tests/isolation/test_retro_hunt_consumer_live.py -v --tb=shortdiff --git a/.gitleaksignore b/.gitleaksignoreindex 726931424..365821aaa 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -114,3 +114,7 @@ services/connectors/tests/connectors/test_snowflake.py:private-key:17# invented inbox token for a schema assertion.services/connectors/tests/test_kubernetes_audit.py:generic-api-key:218+# Evidence-bundle test fixture. "test-signing-key-at-least-32-characters-long" is a+# literal the suite signs with so it can then prove a *different* key fails to verify;+# it authenticates nothing and exists in no deployment.+services/api/tests/test_evidence_bundle.py:generic-api-key:26diff --git a/PARITY_PROGRESS.md b/PARITY_PROGRESS.mdindex 804ecf004..93dd00a32 100644--- a/PARITY_PROGRESS.md+++ b/PARITY_PROGRESS.md@@ -696,3 +696,44 @@ import graph understates what depends on a module.**The limit that stays.** No hosted provider has ever been exercised. AItriage is Stable on the bundled local model; hosted-provider accuracy isa separate claim and remains unmade.++### What the maturity plan asked for and did not get (2026-10-02)++Re-reading that plan clause by clause against the tree found four+sub-clauses that had not landed. Three are now closed and listed above:+the `POST /lake/sql` round-trip, the feed → Kafka → sweep → alert E2E,+and the hunting agent's console and MCP callers. Two are not, and the+reason is worth more than a tick would have been.++**"Close parity 3.2, 3.4, 3.6 and 3.7."** These are four substantial+features, not gaps in the maturity work: accuracy measurement on the+shipped model across labelled replay sets, before-and-after measurement,+a copilot with the investigation agent's read tools and ledger citations,+and signed replayable evidence bundles mapped to OCSF's `ai_agent`+object. They stay open and unticked.++The AI triage row does not rest on them. What it rests on is the+Investigation Ledger proven against real Postgres and a commit-level+agent check that fails when `llm_calls_placed` is zero, both of which+shipped. Measured verdict accuracy is a *different* claim, and it is one+this tree still cannot make: **no hosted provider has ever been+exercised**, and the only live floor is groundedness over a deterministic+prefix on a locally-served small model.++**"Shrink the reachability allowlist by six entries."** It shrank by two,+and both of those were the hunting agent's. The other four named in that+clause are `services/actions/app/clients/{aisoc_direct,fleetdm,osctrl}_client.py`+and `osquery_allowlist.py` — vendor clients constructed by capability+name at dispatch time rather than imported. The import graph cannot see+that, and the allowlist's own comment already records the decision:+inventing a dynamic-loader entry for a factory that takes a string would+excuse more than it explains.++The two autonomy modules in that clause were examined and **kept**, with+their entries corrected. `autonomy_evidence_rules.py` is not unwired at+all: two gates read it without importing it, which an import-graph+checker cannot see — a fact established by deleting it and immediately+breaking both. `unified_autonomy.py` is genuinely off the production+path and superseded by parity 2.1's closure policy, and a third authority+on "may this execute without a human" is a safety question rather than a+tidiness one.diff --git a/README.md b/README.mdindex cc29fe6c3..9eb34bb66 100644--- a/README.md+++ b/README.md@@ -6,11 +6,8 @@**An open-source, self-hostable AI Security Operations Center.** It ingests your security telemetry, detects and correlates threats, investigates them with AI agents whose reasoning is fully auditable, and proposes responses a human approves.-[](https://opensource.org/licenses/MIT)-[](CHANGELOG.md)-[](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml)-[](https://github.com/beenuar/AiSOC/actions/workflows/codeql.yml)-[](https://securityscorecards.dev/viewer/?uri=github.com/beenuar/AiSOC)+[](https://opensource.org/licenses/MIT) [](CHANGELOG.md) [](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml)+[](https://github.com/beenuar/AiSOC/actions/workflows/codeql.yml) [](https://securityscorecards.dev/viewer/?uri=github.com/beenuar/AiSOC)[Docs](https://beenuar.github.io/AiSOC/) · [Architecture](docs/architecture/README.md) · [What actually works](docs/audit/REPOSITORY_REALITY.md) · [Discussions](https://github.com/beenuar/AiSOC/discussions)@@ -105,29 +102,34 @@ a connector still ingests through a generic mapping that resolves host, user andIngest normalizes to a common shape and Kafka carries it, thenfusion runs 2603 executable detection rules, of 6991 on disk, applies **your tenant's own tuning**-on top — the disables, floors and suppressions the console writes, so a rule you turned off actually-stops firing — and decides what becomes an alert. Correlation groups related alerts, an agent investigates and writes its reasoning+on top — the disables, floors and+suppressions the console writes, so a rule you turned off actually stops firing — and decides what+becomes an alert. Correlation groups related alerts, an agent investigates and writes its reasoningto the Investigation Ledger, and a playbook may start from the result. Separately, new threatintelligence sweeps the lake for sightings you already collected, and a hypothesis becomes a hunt-without anyone writing a query — the model fills a closed schema and every value it supplies is-bound as a parameter, so it cannot express a query at all.+without anyone writing a query — the model fills a closed schema and every value is bound as a+parameter, so it cannot express a query at all.**A playbook triggered by an alert previews before it acts.** Three switches must agree — the-deployment, the tenant, and the playbook — and every default is off; anything less runs in preview-with its plan attached to the alert. An approval step inside one is a durable pause: the run suspends-to Postgres, survives a restart, resumes from the step after the approval, and expires with a-recorded outcome rather than hanging.--**Executable is earned, not declared.** A rule enters the compiled ruleset only after a vendor-shaped-event has been replayed through the real connector and this engine and that rule was *watched to-fire* — never inferred from a directory or an `enabled:` flag. The proof can fail: `--prove-gate`-reverts the Windows connector and requires all 1,687 Windows rules to go silent. It means the rule is-reachable, not that it detects an attack. 119 still cannot fire on any connector, counted by family-rather than hidden. ([how, and why 1,362 were refused](docs/detections/sigma-compilation.md))--**[docs/architecture/README.md](docs/architecture/README.md)** walks that path one step at a time —-eleven steps, five diagrams, every box linking to the code that implements it — and-[mirrors to the docs portal](https://beenuar.github.io/AiSOC/docs/architecture).+deployment, the tenant, the playbook — and every default is off; anything less runs in preview with+its plan attached to the alert. An approval step is a durable pause: the run suspends to Postgres,+survives a restart, resumes after the approval, and expires with a recorded outcome rather than+hanging.++**Executable is earned, not declared.** A rule joins the compiled ruleset only after a vendor-shaped+event is replayed through the real connector and engine and that rule is *watched to fire* — never+inferred from a directory or an `enabled:` flag. The proof can fail: `--prove-gate` reverts the+Windows connector and requires all 1,687 Windows rules to go silent. It means reachable, not that it+detects an attack. 119 still cannot fire, counted by family rather than hidden.+([why 1,362 were refused](docs/detections/sigma-compilation.md))++**Every answer carries its receipts.** The copilot cites each checkable claim to the ledger entry behind+it and labels the rest *uncited* rather than dropping them, and any investigation exports as a **signed+evidence bundle** — byte-identical, prompts as digests, OCSF 1.9.0. ([how](docs/architecture/evidence-bundles.md))++**[docs/architecture/README.md](docs/architecture/README.md)** walks that path one step at a time — eleven+steps, five diagrams, every box linking to the code — and [mirrors to the docs+portal](https://beenuar.github.io/AiSOC/docs/architecture).## Deployment profiles@@ -145,8 +147,8 @@ sized for CPU-only inference, so `make up` produces real triage verdicts with rethe Investigation Ledger — not a stub. It is not a frontier model: over 50 alerts it gave triageusable output 44 times before the reply was constrained to JSON and 50 after([method](scripts/measure_triage_reliability.py)), and the rail labels which path answered. Upgrade-by setting `OPENAI_API_KEY` and the model pins. **No hosted provider has ever been exercised-here** — there is no funded key, so per-model rows read *not measured* rather than zero.+by setting `OPENAI_API_KEY` and the model pins. **No hosted provider has ever been exercised here**+— there is no funded key, so per-model rows read *not measured* rather than zero.([ADR-0006](docs/decisions/0006-llm-gateway-in-core.md))**One real external feed ships too.** `services/threatintel` polls the CISA Known Exploited@@ -161,13 +163,11 @@ thing in a fresh install that is neither synthetic nor yours.| **Real, and not yours** | The CISA KEV feed on the Threat Intelligence page | Every row carries `source: cisa-kev`; it is the public catalog, unmodified || **Sample** | The wizard's **Load sample data** | Source column reads `AiSOC`; RFC 5737 / RFC 2606 reserved addresses only || **Demo** | `make demo` | `is_synthetic = true`, labelled in the console |-| **Benchmark** | `services/agents/tests/eval_data/` | Every published row carries `substrate: true` |-| **Test fixtures** | `tests/`, `**/tests/` | Never shipped in an image |+| **Benchmark / fixtures** | `services/agents/tests/eval_data/`, `**/tests/` | Published rows carry `substrate: true`; fixtures never ship in an image |**Production never silently falls back to synthetic data.** An unreachable backend makes the console-name the failure, not invent an investigation, and an unmeasured figure reads *not measured*, never-`0`. That was not always true — [the reality audit](docs/audit/REPOSITORY_REALITY.md) records where-it was wrong and how it was fixed.+name the failure rather than invent an investigation, and an unmeasured figure reads *not measured*,+never `0`. It was not always so: [the reality audit](docs/audit/REPOSITORY_REALITY.md) has each case.## AI agents@@ -175,13 +175,18 @@ Agents triage alerts and investigate incidents. What they can and cannot do:- **They read** the alert, its correlated siblings, entity context, and prior verdicts for the same signature.- **They call typed tools** — lake queries, graph traversals, enrichment lookups. The model chooses a tool and passes arguments; it never writes SQL.-- **Everything is logged** to the Investigation Ledger: prompts, tool calls, citations, the verdict, and token cost.+- **Everything is logged** to the Investigation Ledger — prompts, tool calls, citations, verdict, token cost — and exports as a signed bundle.- **Grounding is checked.** A verdict citing an indicator the evidence never contained is demoted to human review rather than auto-closed.- **A prompt is validated before it is sent.** Raw logs, OCSF payloads and secret-shaped values are refused, not redacted after the fact.- **No vendor is touched without a human**, unless a tenant has explicitly granted autonomy for that verb. Every response step is graded against its own capability contract at dispatch, so approving a playbook never authorises whatever its steps happen to contain, and an approver must hold the required permission tier and must not be the person who requested the action.## Project maturity+**Stable is defined, and a gate enforces it.** It was ungated prose until three rows were found+describing coverage that did not exist. A row is Stable only with a check that runs on every pull+request with no path filter, drives the real production path against real infrastructure, and has a+**negative control proven by breaking the thing and watching it go red**. ([the bar](docs/audit/MATURITY_DEFINITION.md))+| Capability | Status | Tested | Production ready ||---|---|---|---|| Ingest → detect → correlate → alert | Stable | E2E + unit | Yes |@@ -208,28 +213,24 @@ Agents triage alerts and investigate incidents. What they can and cannot do:- **Not able to see telemetry you have not connected.** There is no discovery.- **Not autonomous by default.** Response requires explicit policyauthorization and a human approver.-- **Demo and sample incidents are not real incidents**, and benchmark numbers are substrate- self-consistency measures rather than live agent accuracy — labelled as such wherever published.+- **Demo and sample incidents are not real incidents**, and benchmark numbers are substrate self-consistency measures rather than live agent accuracy — labelled as such wherever published.## Troubleshooting-`make doctor` checks host tools, memory and disk, every port, each datastore by *querying* it rather-than asking whether its container is up, and whether `.env` still holds placeholders — then prints-the command to run next. A container killed by a full Docker VM is named as that, not reported as-the service that happened to die. The six failures it is most often right about are tabulated under-[Installation](https://beenuar.github.io/AiSOC/docs/installation#the-six-most-common-failures).+`make doctor` checks host tools, memory, disk, every port and each datastore by *querying* it rather+than asking whether its container is up, then prints the command to run next. A container killed by a+full Docker VM is named as that, not as the service that happened to die.+([the six most common failures](https://beenuar.github.io/AiSOC/docs/installation#the-six-most-common-failures))## SecuritySecrets are generated per deployment and never committed; connector credentials are encrypted at-rest. Services connect to Postgres as a DML-only role, so the row-level-security policies actually-apply to them, and tenant isolation is enforced at the query layer in every store. RBAC gates every-mutating route, ingest is authenticated, and the default install sends no prompt anywhere — the-model runs beside it.+rest. Services connect to Postgres as a DML-only role, so row-level security actually applies, and+tenant isolation is enforced at the query layer in every store. RBAC gates every mutating route,+ingest is authenticated, and the default install sends no prompt anywhere — the model runs beside+it.-**A service with no credential refuses to serve rather than serving unauthenticated**, and `make up`-generates every secret it needs. The [changelog](CHANGELOG.md) records each fixed vulnerability;-report via [SECURITY.md](SECURITY.md).+**A service with no credential refuses to serve rather than serving unauthenticated.** The [changelog](CHANGELOG.md) records each fixed vulnerability; report via [SECURITY.md](SECURITY.md).## Developing@@ -240,10 +241,9 @@ make stats # recount every figure this README publishes```Guides: [add a connector](https://beenuar.github.io/AiSOC/docs/plugins/hello-plugin) ·-[add a detection](https://beenuar.github.io/AiSOC/docs/detections/hello-hunt) ·-[plugin lifecycle](https://beenuar.github.io/AiSOC/docs/plugins/lifecycle) ·-[contributing](CONTRIBUTING.md). Every count above is recounted from the tree by `make stats`, and-CI fails if this README disagrees with it.+[add a detection](https://beenuar.github.io/AiSOC/docs/detections/hello-hunt) · [plugin+lifecycle](https://beenuar.github.io/AiSOC/docs/plugins/lifecycle). Every count above is recounted+from the tree, and CI fails if this README disagrees.## Roadmap · Contributing · Licensediff --git a/ROADMAP.md b/ROADMAP.mdindex c231932e0..31a050218 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,10 +44,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 **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 **278 rows — 278 GATED / 0 PARTIAL / 0 NO GATE** — **every 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 **285 rows — 285 GATED / 0 PARTIAL / 0 NO GATE** — **every 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. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 6d5adf5cf..b730bdf40 100644--- a/apps/docs/docs/benchmark.md+++ b/apps/docs/docs/benchmark.md@@ -95,6 +95,69 @@ the numbers.3. **The CI gate runs on every PR targeting `main` / `develop`** — [latest run](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml). (CI is currently scoped to those two branches; PRs to long-lived feature branches are not gated.)4. **Historical numbers are queryable** — every successful build pushes its report (written by `scripts/run_evals.py --out`) to the [`eval-results`](https://github.com/beenuar/AiSOC/tree/eval-results) branch as `eval/results/<commit_sha>.json`.+## Verdict accuracy, and why it is not measured here++Parity 3.2 asks for verdict accuracy, per-class precision and recall,+malicious recall with a confidence interval, and false-negative counts.+The scoring for every one of those exists in+[`aisoc_benchmark.replay`](https://github.com/beenuar/AiSOC/blob/main/packages/aisoc-benchmark/aisoc_benchmark/replay.py)+and is tested. What does not exist is a corpus that could produce an+honest number from it.++**Every labelled set in this repository is entirely malicious by+construction.** `synthetic_incidents.json` and `adversary_incidents.json`+are 200 incidents each and every one is a real attack. Their+`response_class` field says which action to take — `isolate_host`,+`disable_account` — not whether the finding was true. There is no benign+case and no false positive anywhere in `services/agents/tests/eval_data/`.++Score an agent against that and **an agent that answers "true positive"+to everything, without reading anything, posts 100% accuracy and 100%+malicious recall.** Publishing that figure would be the exact mirror of+the failure `replay.py` already guards against at the other end, where it+withholds headline accuracy below 30 malicious cases because 98% on a+corpus of three is misleading in the direction that sells.++So nothing publishes it. `scripts/score_replay_set.py` refuses a corpus+whose minority class is under 5% of the set, names the counts in the+refusal, and a test asserts that **this tree's own two corpora are+refused** — because that is the finding, not a bug to route around.++| Metric | Shipped model `llama3.2:3b-instruct-q4_K_M` | `qwen2.5:0.5b` | Any hosted model |+|---|---|---|---|+| Verdict accuracy | not measured — no corpus with a benign class | not measured — same | not measured — no funded key |+| Per-class precision / recall | not measured — same | not measured — same | not measured — no funded key |+| Malicious recall (95% CI) | not measured — same | not measured — same | not measured — no funded key |+| False-negative count | not measured — same | not measured — same | not measured — no funded key |+| Groundedness | graded weekly by `live-agent-eval.yml` | floor 0.40, measured over 12 runs | not measured — no funded key |++The numbers that would fill that table need one of two things: a customer+replaying their own closed findings, which the replay path exists for and+runs entirely on their infrastructure; or a balanced corpus built here+with real benign cases in it. Manufacturing the second from the corpora+above by labelling everything `true_positive` would produce a table of+100%s, which is why the guard exists rather than a `--force` flag.++**No hosted provider has ever been exercised.** Every hosted column reads+*not measured* rather than `0`, because a zero in an accuracy column says+the model got everything wrong and "nobody has run it" is a different+fact with a different remedy.++## Before and after++`scripts/compare_eval_runs.py` publishes the delta between two runs, and+most of its work is refusing comparisons that would read as results:++- an axis measured before and not after is **not comparable**, not a+ regression — the arithmetic would say `0.62 - 0 = -0.62` and the report+ would claim the agent got much worse when nobody asked it;+- two runs over different datasets are **refused outright**, because that+ delta measures the corpus;+- a mean whose support changed materially carries both counts, since a+ precision of 1.00 over two predictions and over two hundred are the+ same number and different facts;+- latency is reported and never graded, because it measures the machine.+## Latest resultsThe numbers below are produced by `scripts/run_evals.py`. The MITRE,diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex b9e54b093..4b7919272 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,10 +33,10 @@ 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: 278 rows-The last row is the one worth reading first. It is the honest index: 278 rows-The last row is the one worth reading first. It is the honest index: 278 rows-The last row is the one worth reading first. It is the honest index: 278 rows+The last row is the one worth reading first. It is the honest index: 285 rows+The last row is the one worth reading first. It is the honest index: 285 rows+The last row is the one worth reading first. It is the honest index: 285 rows+The last row is the one worth reading first. It is the honest index: 285 rows`GATED`, 0 `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/apps/docs/docs/integrations/mcp.md b/apps/docs/docs/integrations/mcp.mdindex 8225d4b77..8318543d9 100644--- a/apps/docs/docs/integrations/mcp.md+++ b/apps/docs/docs/integrations/mcp.md@@ -88,7 +88,7 @@ If the assistant asks for permission to call `aisoc_*` tools, that's expected## Tools exposed-The server advertises **18 tools** to your assistant. Discovery tools list things, deep-dive tools fetch one thing, the lake-query pair lets agents run governed SELECTs over the warm tier, and the replay tools expose the agent's own reasoning:+The server advertises **19 tools** to your assistant. Discovery tools list things, deep-dive tools fetch one thing, the lake-query pair lets agents run governed SELECTs over the warm tier, and the replay tools expose the agent's own reasoning:```mermaidgraph LRdiff --git a/apps/docs/docs/intro.md b/apps/docs/docs/intro.mdindex f261c3294..8030a0241 100644--- a/apps/docs/docs/intro.md+++ b/apps/docs/docs/intro.md@@ -88,7 +88,7 @@ for the full list.- **AI-vs-AI adversary eval** — deterministic attacker-LLM mutator generates adversarial incidents to test detection resilience under synonym swap, leetspeak, zero-width injection, and fragmentation attacks.- **Marketplace** — 15 first-party plugins, 50+ playbooks, 6,900+ detections (filtered by tier: stable / beta / imported / community), surfaced in-app via [`marketplace/index.json`](https://github.com/beenuar/AiSOC/tree/main/marketplace).- **SDKs** — Python, TypeScript, and Go SDKs for client and plugin development; Ed25519-signed publishing.-- **Model Context Protocol** — `@aisoc/mcp` exposes 18 tools to Claude, Cursor, Continue, and Cody so analysts can replay agent decisions and run governed warm-tier SELECTs from inside their IDE ([MCP integration](./integrations/mcp)).+- **Model Context Protocol** — `@aisoc/mcp` exposes 19 tools to Claude, Cursor, Continue, and Cody so analysts can replay agent decisions and run governed warm-tier SELECTs from inside their IDE ([MCP integration](./integrations/mcp)).## Architecture Overviewdiff --git a/apps/docs/static/llms-full.txt b/apps/docs/static/llms-full.txtindex 6e097fdc6..71622738c 100644--- a/apps/docs/static/llms-full.txt+++ b/apps/docs/static/llms-full.txt@@ -146,7 +146,7 @@ AiSOC to MCP-aware assistants including Claude Desktop, Cursor, Continue.dev andCody. It speaks stdio JSON-RPC and translates tool calls into AiSOC REST calls;the API key stays on the machine running the server.-It advertises 18 tools:+It advertises 19 tools:- `aisoc_explain_step`- `aisoc_get_alert`@@ -165,6 +165,7 @@ It advertises 18 tools:- `aisoc_preview_action`- `aisoc_query_detections`- `aisoc_replay_decision`+- `aisoc_run_hunt`- `aisoc_run_investigation`Install it from a source build — see the packaging note below:diff --git a/apps/docs/static/llms.txt b/apps/docs/static/llms.txtindex 9508cbbcd..4bde250a4 100644--- a/apps/docs/static/llms.txt+++ b/apps/docs/static/llms.txt@@ -53,7 +53,7 @@ Key facts a summary should get right:## Integrating with AiSOC-- [MCP server](https://beenuar.github.io/AiSOC/docs/integrations/mcp): connect Claude Desktop, Cursor, Continue.dev or Cody to AiSOC. Exposes 18 tools.+- [MCP server](https://beenuar.github.io/AiSOC/docs/integrations/mcp): connect Claude Desktop, Cursor, Continue.dev or Cody to AiSOC. Exposes 19 tools.- [API reference](https://beenuar.github.io/AiSOC/docs/api/rest): the REST surface.- [Python plugin SDK](https://beenuar.github.io/AiSOC/docs/plugins/python-sdk): build a connector or plugin in Python.- [Go plugin SDK](https://beenuar.github.io/AiSOC/docs/plugins/go-sdk): build a connector or plugin in Go.diff --git a/apps/web/src/components/copilot/CopilotView.tsx b/apps/web/src/components/copilot/CopilotView.tsxindex a4699739c..de3d7c546 100644--- a/apps/web/src/components/copilot/CopilotView.tsx+++ b/apps/web/src/components/copilot/CopilotView.tsx@@ -475,6 +475,23 @@ export function CopilotView() {// fires because the request technically succeeded.const source = (res as { source?: string }).source;const notice = (res as { notice?: string }).notice;+ // Parity 3.6: a model answer that names an IP, a hash or a CVE is+ // making a claim about this estate. The backend grades each such+ // claim against the records it was given; an analyst has no other+ // way to tell one drawn from the evidence from one the model+ // produced because it sounded right.+ //+ // The warning is appended rather than used to suppress or edit the+ // answer. Hiding the unsupported half would show the analyst a+ // different answer than the model gave, edited by something that+ // cannot reliably tell which half was wrong.+ const grounding = (res as { grounding?: { label?: string; uncited?: string[] } }).grounding;+ const uncited = grounding?.uncited ?? [];+ const groundingWarning =+ uncited.length > 0+ ? `Not supported by anything this answer was given: ${uncited.join(', ')}. Verify before acting.`+ : null;+const reply =source === 'template'? {@@ -488,7 +505,9 @@ export function CopilotView() {res.reply.content,].join('\n'),}- : res.reply;+ : groundingWarning+ ? { ...res.reply, content: [groundingWarning, '', '---', '', res.reply.content].join('\n') }+ : res.reply;setMessages((prev) => [...prev, reply]);setEverSucceeded(true);} catch (err) {diff --git a/apps/web/src/components/copilot/InvestigationTimeline.tsx b/apps/web/src/components/copilot/InvestigationTimeline.tsxindex bbce0c6d6..45a8f4ea6 100644--- a/apps/web/src/components/copilot/InvestigationTimeline.tsx+++ b/apps/web/src/components/copilot/InvestigationTimeline.tsx@@ -538,6 +538,38 @@ export default function InvestigationTimeline({const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const [focusedSeq, setFocusedSeq] = useState<number | null>(null);+ const [bundleState, setBundleState] = useState<'idle' | 'downloading'>('idle');+ const [bundleError, setBundleError] = useState<string | null>(null);++ // Parity 3.7: export this investigation as a signed, replayable+ // bundle. A failure says so rather than silently doing nothing — a+ // download button that no-ops is indistinguishable from a slow one.+ const downloadBundle = useCallback(async () => {+ if (!runId) return;+ setBundleState('downloading');+ setBundleError(null);+ try {+ const res = await fetch(`${apiBase}/investigations/${runId}/bundle`, {+ credentials: 'include',+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const blob = await res.blob();+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = `aisoc-investigation-${runId}.bundle.json`;+ link.click();+ URL.revokeObjectURL(url);+ } catch (e: unknown) {+ setBundleError(+ e instanceof Error+ ? `Could not export the evidence bundle: ${e.message}`+ : 'Could not export the evidence bundle.',+ );+ } finally {+ setBundleState('idle');+ }+ }, [runId, apiBase]);const focusedRef = useRef<HTMLDivElement>(null);const pollRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -640,16 +672,37 @@ export default function InvestigationTimeline({</p></div>- {focusedSeq !== null && (+ <div className="flex items-center gap-3">+ {/* Parity 3.7. The bytes are written to disk exactly as the+ server sent them: the signature is computed over that+ sequence, so re-serialising a parsed body here would break+ verification for a reason the auditor could not see. */}<button- className="text-xs text-slate-400 hover:text-white"- onClick={() => setFocusedSeq(null)}+ className="text-xs text-slate-400 hover:text-white disabled:opacity-40"+ disabled={bundleState === 'downloading'}+ onClick={downloadBundle}+ title="Signed, replayable record of this investigation">- ✕ clear focus+ {bundleState === 'downloading' ? 'Preparing…' : '⤓ Evidence bundle'}</button>- )}++ {focusedSeq !== null && (+ <button+ className="text-xs text-slate-400 hover:text-white"+ onClick={() => setFocusedSeq(null)}+ >+ ✕ clear focus+ </button>+ )}+ </div></div>+ {bundleError && (+ <p className="text-[11px] text-amber-300" role="status">+ {bundleError}+ </p>+ )}+{/* Scrubber */}{nodes.length > 1 && (<ScrubberBardiff --git a/apps/web/src/components/hunt/HuntView.tsx b/apps/web/src/components/hunt/HuntView.tsxindex 1dff8ffb3..b0fe1c819 100644--- a/apps/web/src/components/hunt/HuntView.tsx+++ b/apps/web/src/components/hunt/HuntView.tsx@@ -733,10 +733,42 @@ export function HuntView() {setNlSubmittedQuery(cleaned);setNlExplanation(explanation || null);} catch (err) {+ // The translator could not turn this into a query. Ask the hunting+ // agent to plan one instead, rather than leaving the analyst with a+ // toast and an empty editor.+ //+ // This is also what takes `services/agents/app/hunt/agent.py` off+ // the unreachable list on the console side: its only importer+ // repo-wide used to be its own test.console.error('NL translate failed', err);- toast.error('Could not translate the question');setNlSubmittedQuery(cleaned);setNlExplanation(null);+ try {+ const hunted = await huntApi.runAgentHunt(cleaned);+ if (!hunted.checked) {+ // `checked: false` is not "found nothing". Say which it was.+ toast.error(+ hunted.unavailable_reason ??+ 'The hunt could not run, so this is not a result about your estate.',+ );+ } else {+ setNlExplanation(+ hunted.matches.length > 0+ ? `The agent planned and ran this hunt: ${hunted.matches.length} match(es).`+ : 'The agent ran this hunt and nothing matched. That is a result.',+ );+ if (hunted.refusals.length > 0) {+ // Shown rather than swallowed: a plan the validator would not+ // run is information, and the model never writes a query+ // directly — it picks from a vocabulary.+ toast(`The planner declined ${hunted.refusals.length} plan(s). See the console log.`);+ console.info('hunt.refusals', hunted.refusals);+ }+ }+ } catch (agentErr) {+ console.error('agent hunt failed', agentErr);+ toast.error('Could not translate the question, and the hunting agent is unavailable.');+ }} finally {setNlPending(false);}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex a3aad1604..822901aba 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -3553,7 +3553,37 @@ export interface SavedSearch {pinned?: boolean;}+/** What `POST /api/v1/agents/hunt` answers. */+export interface AgentHuntResponse {+ hypothesis: string;+ /**+ * Whether the hunt *ran*. Not the same as `matches.length > 0`: a hunt+ * that could not run is not a hunt that found nothing, and collapsing+ * the two is how a console shows a reassuring empty result for a search+ * that never happened. False always carries an `unavailable_reason`.+ */+ checked: boolean;+ matches: Record<string, unknown>[];+ /** Plans the validator would not run. Shown, not swallowed. */+ refusals: string[];+ unavailable_reason: string | null;+}+export const huntApi = {+ /**+ * Natural-language hunting through the agent (parity 6.1).+ *+ * The agent plans; the planner validates every attempt against the+ * allowed shape. The model never writes a query directly. The tenant+ * comes from the caller's token server-side and is deliberately not a+ * parameter here.+ */+ runAgentHunt: (hypothesis: string) =>+ request<AgentHuntResponse>('/api/v1/agents/hunt', {+ method: 'POST',+ body: JSON.stringify({ hypothesis }),+ }),+search: (query: HuntQuery) =>request<HuntResponse>('/api/v1/hunt/search', {method: 'POST',diff --git a/docs/architecture/README.md b/docs/architecture/README.mdindex 4d4a864c5..2f8a39431 100644--- a/docs/architecture/README.md+++ b/docs/architecture/README.md@@ -415,3 +415,33 @@ API. It reaches past nothing. Each stage reports PASS or FAIL separately, soa break names the boundary that broke.Source: [`tests/e2e/golden_pipeline/`](../../tests/e2e/golden_pipeline/).++### What CI proves about each piece above++`make smoke` is the whole pipeline. Each capability in it also has a check+that runs on **every pull request with no path filter**, drives the real+production path against real infrastructure, and carries a negative control+— something that breaks the thing and is required to turn the check red.+The bar, and why it is that bar, is in+[`docs/audit/MATURITY_DEFINITION.md`](../audit/MATURITY_DEFINITION.md).++| What it proves | Workflow | What breaking it looks like |+|---|---|---|+| Graph reads are tenant-scoped in `graph_service.py` | `graph-live.yml` | Remove the anchor's tenant predicate → 1 test fails |+| UEBA scores and persists against the shipped migrations | `ueba-live.yml` | Drop `peer_group_id` → 4 of 5 fail |+| An approval pause survives a restart and resolves once | `playbook-pause-live.yml` | Drop the partial unique index → the constraint test fails |+| The Investigation Ledger persists, scopes and refuses | `playbook-pause-live.yml` | — |+| Tenant tuning changes what the engine fires | `tenant-tuning-live.yml` | Re-add the two columns the table lacks → 6 of 10 fail |+| SCIM provisions and isolates through the real app | `scim-live.yml` | Remove the tenant predicate → the isolation test fails |+| A connector polls a vendor and reaches ingest | `connector-scheduler-live.yml` | `next_run_time=None` → 4 of 5 fail |+| Governance permits, refuses, and leaks no refusal | `live-actions-live.yml` | Remove all three branches → the refused isolate reaches the vendor |+| The shipped ClickHouse DDL loads; `POST /lake/sql` scopes | `lake-live.yml` | Make the rewrite a pass-through → 6 of 7 fail |+| Scheduled hunts read tenant data, never the fixture | `lake-live.yml` | — |+| Intel travels feed → Kafka → sweep → alert | `retro-hunt-live.yml` | Remove the per-tenant savepoint → 5 of 8 fail |+| The agent places a real LLM call on this commit | `live-agent-eval.yml` | `llm_calls_placed: 0` fails the job |++Two of those rows exist because the suite behind them found a defect no+offline test could: the connector scheduler registered every poll job+**paused**, so connecting a source never pulled data; and the retro-hunt+fan-out flushed one tenant's rows under the *next* tenant's RLS context,+so it persisted nothing on any deployment using the runtime role.diff --git a/docs/architecture/SYSTEM_DESIGN.md b/docs/architecture/SYSTEM_DESIGN.mdindex d39b4b9f7..1263e03f8 100644--- a/docs/architecture/SYSTEM_DESIGN.md+++ b/docs/architecture/SYSTEM_DESIGN.md@@ -102,7 +102,7 @@ This document describes the end-to-end architecture of the AiSOC platform after| `services/osquery-extensions` | Go 1.25 | Out-of-band osquery extensions (custom virtual tables + decorators) | Loaded by `osquery-tls`-managed agents || `services/slack-bot` | Python 3.11 | ChatOps surface: posts approval prompts, `/aisoc` slash command | Verifies inbound interactions with HMAC-signed Slack request signatures || `services/realtime` | Node 22 | WebSocket fan-out + Web Push for the web console + Responder PWA | n/a |-| `services/mcp` | Node 22 (TypeScript) | Model Context Protocol stdio server, 18 tools for IDE-side agents (Claude / Cursor / Continue / Cody) — discovery, deep-dive, action/replay, and the warm-tier lake query pair (`aisoc_lake_schema`, `aisoc_lake_query`) | n/a |+| `services/mcp` | Node 22 (TypeScript) | Model Context Protocol stdio server, 19 tools for IDE-side agents (Claude / Cursor / Continue / Cody) — discovery, deep-dive, action/replay, and the warm-tier lake query pair (`aisoc_lake_schema`, `aisoc_lake_query`) | n/a || `apps/web` | Next.js 14 | Server components + SWR + Responder PWA route group + benchmark scoreboard | n/a |---diff --git a/docs/architecture/evidence-bundles.md b/docs/architecture/evidence-bundles.mdnew file mode 100644index 000000000..37677c66c--- /dev/null+++ b/docs/architecture/evidence-bundles.md@@ -0,0 +1,121 @@+# Evidence bundles++An auditor, a regulator or a customer's own security team asks the same+three things about an automated decision: *what did it decide, on what+evidence, and can I check that nobody edited the answer afterwards?*++The [Investigation Ledger](README.md) already holds the answer. A bundle+is that answer made portable and tamper-evident, exported from+`GET /api/v1/investigations/{run_id}/bundle` or the **⤓ Evidence bundle**+control on the investigation timeline.++Implementation: [`services/api/app/services/evidence_bundle.py`](../../services/api/app/services/evidence_bundle.py).++## Three properties, each a decision++### Byte-for-byte replayable++Two exports of the same run produce identical bytes. That is what lets+somebody who does not trust the exporter diff a bundle, re-hash it and+check the signature themselves.++It rules out everything that makes JSON non-deterministic:++- keys are sorted and separators fixed;+- timestamps are the ledger's own, never `now()`;+- nothing records the host that produced it;+- events are sorted by sequence, so a ledger read that returns rows in a+ different order cannot change the digest — otherwise the signature+ becomes a property of the query plan.++The route serves the bundle as a **download**, not as a JSON body,+because a client that re-serialised a parsed body would change the bytes+and the signature would stop matching for a reason nobody could see.++`verify_bundle()` recomputes both the digest and the signature from the+payload rather than comparing the two values already in the file — which+would pass for anyone who edited the payload and the digest together.++### Prompts travel as hashes, never as text++A prompt carries the alert, and an alert carries your hostnames, your+usernames and your addresses. A bundle is the artefact most likely to+leave your control, so the one thing it must not do is carry your estate+in clear text.++The digest still proves *which* prompt ran: re-hash the prompt and+compare. A step with no prompt gains no hash field at all, because a hash+of the empty string would quietly merge "there was no prompt" with "the+prompt hashed to something".++### Absent is not zero++A run with no cost telemetry exports `total_cost_usd: null`, not `0.0`,+and a `cost_provenance` field saying which it was. A zero says the run+was free; null says nobody measured. This repository has published the+first while meaning the second before.++## The OCSF mapping, and the version it declares++The bundle declares **OCSF 1.9.0**. That is deliberate, and it differs+from the 1.1.0 the ingest spine emits.++Each object was checked against the published schema before being used:++| Object / profile | 1.1.0 | 1.8.0 | 1.9.0 |+|---|---|---|---|+| `ai_agent` | absent | absent | present |+| `ai_operation` | absent | present | present |+| `record_integrity` | absent | — | present |++The ingest spine stays at 1.1.0 because that is the contract its+normalizer has with connectors, and nothing here changes it. But a+bundle is a different artefact with a different audience, and 1.9.0 is+the first version containing every object it uses. **Declaring 1.1.0+while emitting an `ai_agent` would be a false claim about a public+standard**, which is worse than not mapping at all.++Field names come from the schema rather than from invention: `ai_model`+nested inside `ai_agent`; `record_integrity` carrying an+`attestation_list` whose entries have `fingerprint` and `signatures`.++## What the signature is worth++HMAC-SHA256 over the canonical payload, keyed from the deployment's own+secret. The bundle says in its own `algorithm_note` that this is+**tamper-evidence, not non-repudiation**: anyone holding the signing key+can produce a valid signature, so it proves the bundle was not altered+after export, not that AiSOC and only AiSOC produced it.++An auditor who assumes a public-key signature from the word "signed" has+been misled by us rather than by the format, which is why the+qualification travels inside every bundle instead of living only here.++## Verifying one++```python+from app.services.evidence_bundle import verify_bundle++payload = verify_bundle(json.loads(raw_bytes), signing_key=key)+```++It raises `BundleVerificationError` with the specific reason — digest+mismatch, signature mismatch, or no payload — rather than returning+`False`.++## Tests++- [`services/api/tests/test_evidence_bundle.py`](../../services/api/tests/test_evidence_bundle.py)+ — the format: determinism, tampering, prompt hashing, the OCSF block.+- [`tests/isolation/test_evidence_bundle_live.py`](../../tests/isolation/test_evidence_bundle_live.py)+ — the route against real Postgres. UUIDs, timezone-aware datetimes,+ `Numeric` and `JSONB` all have reprs JSON cannot serialise, so a test+ that hands in dicts never finds out which way that goes.++Tenant scoping on the export was measured in both directions and the+result is worth knowing: removing the explicit `tenant_id` predicate+leaves the cross-tenant test **passing**, because the session runs as the+DML-only role and row-level security refuses the row anyway. Only+removing the predicate *and* connecting as the schema owner makes it+fail. The belt and braces are real — and a reader should not conclude+from a green run that the predicate alone is doing the work.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 317caa6e0..954b15b46 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -23,7 +23,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| L0-L4 automation maturity gates every action | README L171 | `ci.yml` autonomy-policy drift test + `test_autonomy_safety.py` (dry-run-default, rollback-capability contract, verification-mandate, scorecard) + `test_governed_dispatch.py` (Phase B2 — `decide()` wired into the live-actions `/dispatch` path: above-tier→dry-run, dry-run-off→queued, L0→blocked, executor never invoked when queued/blocked) | core | GATED | - || Hunt-as-Code + `/hunt` | README L172 | `ci.yml :: p1-eval` (`hunt_corpus`) | core | GATED | - || Weekly benchmark scoreboard runs live against `main` | README L173 | `ci.yml` agents job (Phase E1 — `scripts/check_scoreboard.py` runs the deterministic live-agent MITRE-accuracy eval over the 200-incident corpus and fails if the published `scoreboard.json` substrate row drifts > 0.02, the schema is invalid, or a substrate row is mislabelled) + `wet-eval.yml` (weekly funded LLM rows) | core | GATED | - |-| MCP server exposes 18 tools | `services/mcp/README.md`; `apps/docs/docs/integrations/mcp.md`; `apps/docs/docs/intro.md`; `docs/architecture/SYSTEM_DESIGN.md` | `ci.yml :: mcp` (`tests/tools.test.ts` pins the exact tool set, and `tests/published-count.test.ts` compares the figure in each of the seven documents that publish it against `ALL_TOOLS.length`, failing in **both** directions: a figure that disagrees, and a document that has stopped carrying one, so deleting the claim is a finding rather than a pass. A floor refuses to let an empty registry make every document agree with zero) | core | GATED | The row previously read 13 and named `ci.yml :: mcp` as the gate. That job pins the tool *set* and had never read a document, so six published figures could have drifted with nothing to say so |+| MCP server exposes 19 tools | `services/mcp/README.md`; `apps/docs/docs/integrations/mcp.md`; `apps/docs/docs/intro.md`; `docs/architecture/SYSTEM_DESIGN.md` | `ci.yml :: mcp` (`tests/tools.test.ts` pins the exact tool set, and `tests/published-count.test.ts` compares the figure in each of the seven documents that publish it against `ALL_TOOLS.length`, failing in **both** directions: a figure that disagrees, and a document that has stopped carrying one, so deleting the claim is a finding rather than a pass. A floor refuses to let an empty registry make every document agree with zero) | core | GATED | The row previously read 13 and named `ci.yml :: mcp` as the gate. That job pins the tool *set* and had never read a document, so six published figures could have drifted with nothing to say so || Plugin SDK Python/TS/Go | README L79, L193 | `ci.yml :: sdk-*` (build/test per language) + `openapi-breaking.yml` (a spec change that would break the generated clients) + `ci.yml :: Python — Lint & Type-check` (`check_sdk_surface.py` — every endpoint a client calls must exist in `docs/openapi.yaml`, the three languages are held to a declared namespace manifest, and a declared codegen target must exist) | core | GATED (the three `sdk-*` jobs compiled each SDK in isolation and never compared a client to the API it claims to speak to: `packages/sdk-go` passed all three over a file of type declarations with no functions and no `net/http`, and `packages/sdk-ts` cited a codegen artefact that did not exist. Writing the gate found four operations both clients called that the API does not serve, two of them pinned by tests that mock the transport. The gate proves an endpoint *exists*; field-level response-shape parity is still hand-kept and the SDK headers now say so) | — || 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; no payload is xfail at present, the homoglyph and newline-flood payloads having been closed by confusable folding and by a rule reaching them. 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 || Prompt-injection payloads are graded against a clean twin, so a rate is attributable to the payload | `services/agents/tests/adversarial/injection_incidents.py` | `ci.yml :: python-test` (agents) runs `test_injection_incidents.py` (every pair differs in exactly **one** telemetry field, asserted by a structural diff rather than by inspection; the payload is present at that field in the injected twin and absent from the clean one; where a base incident lacks the field both twins gain the scaffold record so the injected twin never carries structure the clean twin lacks. A guard detection requires a signal at the injected field **and** no signal at that field in the clean twin, proven in the direction that broke by contaminating a base incident and asserting the pair stops counting) | core | GATED | The corpus is synthetic and labelled so at every record. It grades placement and phrasing, not whether a payload would be delivered: that a DNS name can carry an instruction is asserted, that an attacker controls that DNS name is assumed |@@ -197,7 +197,7 @@ 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 |-| MCP server exposes 13 tools | README L179 | `ci.yml :: mcp` | core | GATED | - |+| MCP server exposes 14 tools | README L179 | `ci.yml :: mcp` | core | GATED | - || 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 |@@ -286,117 +286,22 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A port already in use moves AiSOC, it does not stop the install | `README.md` quick start | `ci.yml :: Python — Tests` (`tests/test_port_conflict_resolution.py`) | core | GATED | `make up` used to **refuse to start** when any of sixteen host ports was taken and tell the operator to edit `docker-compose.yml` — a hard stop at step one of the quick start, triggered by the most common condition in this audience's environment (a Postgres on 5432, an Ollama on 11434). It now picks a free port, writes `docker-compose.ports.yml` with `ports: !override` (a plain override *appends*, leaving the conflicting binding published), names what held the port, and propagates a moved console into `AISOC_CONSOLE_URL` so the printed address answers. Two bugs found while building it and pinned here: `SO_REUSEADDR` made the probe **more permissive than the real bind**, reporting a wildcard-held port as free; and `$(wildcard)` in a `:=` variable is expanded at parse time, so the first run generated the overlay and then started compose without it. **Measured: clean install with two conflicts, 56s to a working console, `make smoke` 10/10** || A first-run tenant gets a setup wizard, not an empty dashboard | `apps/docs/docs/console/getting-started.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_onboarding_wizard.py`) | core | GATED | A brand-new operator signed in and landed on `/dashboard`: every tile zero, every panel an honest empty state, and nothing saying what to do next. The empty states were **correct** — that work was already done — but correct and useful are different things, and "0 connected sources" is not a button. `GET /onboarding/status` derives what is set up from the tenant's own rows rather than a stored flag, because a `tenant.onboarded` boolean drifts the moment somebody connects a source through the API or deletes their last one. A missing table returns zero rather than 500-ing, since a half-migrated deployment is exactly when somebody reaches for the thing meant to help || Sample data runs the real pipeline, and does not fake completion | `apps/docs/docs/console/getting-started.md` | `ci.yml :: Python — Tests` (`test_onboarding_wizard.py`) | core | GATED | `POST /onboarding/sample-data` pushes five scenarios through the **same ingest endpoint a real connector uses**, not into Postgres: a console full of inserted rows looks identical whether ingest, fusion and triage work or are completely broken, so running the real path means an operator who sees alerts has also seen the product work. **Sample data does not clear `first_run`** — somebody who has only looked at samples still has nothing connected. It refuses on a tenant with real alerts (a sample in a live queue is indistinguishable at a glance). Every address is an RFC 5737 documentation range and every domain RFC 2606, asserted by test. The scenario set is deliberately **not all critical**, so the console can show what a benign verdict looks like. Proven live: 5 accepted, 5 distinct alerts spanning low to critical, differing AI verdicts |+| An investigation exports as a signed, replayable evidence bundle | `README.md`, `docs/architecture/evidence-bundles.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_evidence_bundle.py`), `playbook-pause-live.yml` (`tests/isolation/test_evidence_bundle_live.py`) | core | GATED | Two exports of one run produce identical bytes, so an auditor can diff and re-hash a bundle without trusting the exporter. Everything that makes JSON non-deterministic is excluded: sorted keys, fixed separators, the ledger's own timestamps rather than `now()`, no host name, and events sorted by sequence — otherwise a ledger read returning rows in a different order changes the digest and the signature becomes a property of the query plan. Served as a **download**, because a client re-serialising a parsed body would break verification for a reason nobody could see. `verify_bundle()` recomputes digest *and* signature from the payload, so editing both together still fails. Prompts travel as digests, never text — a bundle leaves the customer's control and a prompt carries their hostnames — and a step with no prompt gains no hash field, since a hash of the empty string merges 'there was no prompt' with 'the prompt hashed to something'. The live suite is what proves it works on real rows: UUIDs, tz-aware datetimes, `Numeric` and `JSONB` all have reprs JSON cannot serialise |+| The evidence bundle declares the OCSF version that actually has its objects | `docs/architecture/evidence-bundles.md` | `ci.yml :: Python — Tests` (`test_evidence_bundle.py::TestTheOcsfMapping`) | core | GATED | Each object was checked against schema.ocsf.io before use: `ai_agent` 404s on 1.1.0 and 1.8.0 and exists only in **1.9.0**; `ai_operation` exists from 1.8.0; `record_integrity` exists in 1.9.0 under that exact spelling. The ingest spine stays at the 1.1.0 its normalizer emits — that is its contract with connectors — but a bundle declaring 1.1.0 while carrying an `ai_agent` would be **a false claim about a public standard**, which is worse than not mapping at all. Field names come from the schema rather than invention: `ai_model` nested inside `ai_agent`, `attestation_list` carrying `fingerprint` and `signatures`. A run with no model carries `null` rather than a placeholder that would read as a real one |+| The signature says what it is worth, rather than implying more | `docs/architecture/evidence-bundles.md` | `ci.yml :: Python — Tests` (`test_evidence_bundle.py::TestItSaysWhatTheSignatureIsWorth`) | core | GATED | HMAC-SHA256 keyed from the deployment's own secret is **tamper-evidence, not non-repudiation**: anyone holding the key can forge a bundle. The qualification travels inside every bundle's `algorithm_note` rather than only in the docs, because an auditor who assumes public-key signing from the word 'signed' has been misled by us rather than by the format |+| The copilot cites every checkable claim, or labels it uncited | `README.md` | `ci.yml :: Python — Tests` (`services/agents/tests/test_copilot_grounding.py`) | core | GATED | An answer naming an IP, a hash or a CVE is a claim about the customer's network, and the analyst has no way to tell one drawn from the evidence from one the model produced because it sounded right. Each claim now cites a ledger coordinate (`ledger:<run>#<seq>`) or an alert id — things that can be opened — and context without an identifier is deliberately **not** citable, because pointing a citation at a page title is unfalsifiable. What counts as checkable is imported from `app.confidence.groundedness` rather than re-implemented, and a test asserts the two are the same function object; a second definition would drift while still looking like the same number. **Three outcomes, not two:** 'asserted nothing concrete' and 'supported every claim' get different labels, and one supported plus one invented reads *partially uncited* rather than *cited*. The ungrounded answer is returned, not suppressed — hiding the unsupported half shows the analyst a different answer than the model gave, edited by something that cannot reliably tell which half was wrong |+| No accuracy number is published from a corpus that would flatter | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`scripts/tests/test_score_replay_set.py`) | core | GATED | Every labelled corpus in this repository is **entirely malicious by construction**: `synthetic_incidents.json` and `adversary_incidents.json` are 200 incidents each, all real attacks, and `response_class` says which action to take rather than whether the finding was true. An agent answering 'true positive' to everything, without reading anything, would post **100% accuracy and 100% malicious recall** — the exact mirror of the failure `aisoc_benchmark.replay` already guards against at the other end. `score_replay_set.py` refuses no labels, one class, or a minority class under 5%, and names the counts. A test asserts **this tree's own two corpora are refused**, because that is the finding rather than a bug to route around. There is no `--force`. `benchmark.md` publishes *not measured* with the reason in every accuracy cell |+| The live-agent eval grades the model a deployment actually runs | `apps/docs/docs/benchmark.md` | `live-agent-eval.yml :: Dispatch the real agent` (matrix) | core | GATED | A number measured only on `qwen2.5:0.5b` describes the agent on whatever the pins resolved to, which is a different claim from the one a reader takes from it. The job is now a matrix over that model **and `llama3.2:3b-instruct-q4_K_M`, the model `docker-compose.yml` pulls**. The small one stays because the floor in `live_agent_floor.json` was measured on it and removing it would orphan the floor. `fail-fast: false`, because one model failing is a result about that model and cancelling the other throws away the comparison that is the point of a matrix |+| A before-and-after delta refuses the comparisons that would read as results | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`scripts/tests/test_compare_eval_runs.py`), `live-agent-eval.yml :: Delta against the previous run` | core | GATED | Subtracting two numbers is easy; subtracting them honestly is where it goes wrong, and three of the four failures produce a plausible figure rather than an error. An axis measured before and not after reports **not comparable**, never a regression — the arithmetic says `0.62 - 0 = -0.62` and claims the agent got much worse when nobody asked it. Two runs over different datasets are **refused outright**, because that delta measures the corpus. A mean whose support changed materially carries both counts, since a precision of 1.00 over two predictions and over two hundred are the same number and different facts. Latency is reported and never graded, because it measures the machine. Wired into `live-agent-eval.yml` so the delta is *published* rather than merely available; with no previous report it says so instead of diffing against a baseline of zeros |## Summary-- GATED: 278--## Summary--- GATED: 278--## Summary--- GATED: 278--## Summary--- GATED: 278--## Summary--- GATED: 278+- Total: 285+- GATED: 285- PARTIAL: 0-- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)--> **Counting note.** These figures previously read 46 / 9, which did not match-> what the ratchet script counted. `_parse_status_rows` stops at the first-> non-table line, and three blank lines had crept in between rows, so the last-> three sections of the table were invisible to it — the script was scoring 43-> GATED while the summary claimed 46. The blank lines are removed and the-> counts above are what `scripts/check_claim_gate_matrix.py` now reports.-> A governance artifact whose own totals are unverified is the exact failure-> mode it exists to prevent, so the numbers are now derived rather than typed.->-> **They drifted again.** The summary read 93 GATED while the script counted-> 99 on the commit before this one: rows were appended without re-running it,-> which is the same failure the note above describes and the reason the-> lesson is that the summary must be *recomputed*, never typed. The ratchet-> only enforces the NO GATE ceiling, so a stale GATED total does not fail CI-> — the number above is now what `scripts/check_claim_gate_matrix.py` prints,-> and re-running it is the only way to change it.->-> **And once more, outside this file.** `readme_gates.py` compares the tally-> in the README, in this file's Summary, and in a compliance page — but-> `ROADMAP.md` was not on that list, so its tally line sat at 136 rows /-> 128 GATED against a matrix holding 139 / 131 with every check green. The-> line even tells the reader to recount with the script "rather than trusting-> a figure quoted in prose — this line has gone stale before". A gate that-> names the documents it covers will miss the one nobody added; `ROADMAP.md`-> and `RELEASES.md` are now on the list, the *row total* is compared as well-> as the GATED/PARTIAL split, and a figure the prose explicitly dates-> ("the count at that time") is exempted so history need not be rewritten.--### On the PARTIAL rows (all closed)--They are not closed by editing this column. Each names a gate that does not-exist yet. Relabelling any of them GATED without building the gate would make-this file a liability rather than a control, since its whole value is that a-reader can trust the Status column without reading the workflows.--Six of the eight closed in one pass, and every one was built rather than-relabelled — the ledger's replay contract, the per-language SDK surface, the-platform-wide egress default, the raw-SQL column contract, the live-tenant-scoped lake fetch, and the scanner ratchet. Each was proven to fail-before it was trusted, and four of them found a live defect on the way in: the-SDKs called four operations the API does not serve; `detection_rule_proposals`-had never had the `source` column three raw INSERTs name, so every automated-proposal path raised on its first row; `services/purple-team` published a-public CDN default nothing in the service read; and the writer stores OCSF-`raw_data` into a column named `raw_payload`, so the backtest's payload-expansion had never run on a real lake row. Three of the six rows also had a-**gap statement that was wrong in the repository's favour** — they credited an-"api integration" job and an "integration gate" that do not run those paths —-which is its own lesson: a PARTIAL row's caveat needs re-deriving, not just-clearing.--The last two closed together, and what they cost is worth recording. Both-rested on the live-agent eval workflow, which "had never run" — and the reason-was not the scheduling window this file blamed. Its live path imported-`InvestigatorAgent`, a class that exists nowhere in `services/agents`, so the-first dispatch failed in 92 seconds and every later one would have. Two more-defects on the same path would each have published a number nobody measured:-MITRE accuracy read a corpus key that is not there, so a live run would have-reported `0.0000` — graded and failed, for a comparison that never happened —-and a self-hosted model was priced against the gpt-4o rate card. Groundedness-itself was scored per incident and then dropped before the report was written,-so a successful run would have published none.--The floor is 0.40 on a deterministic 10-incident slice, and it came from runs:-seven local ones returned 0.5561 to four decimal places, because the agents-decode greedily at temperature 0 and on one machine the measurement is a point-mass. It is not a point mass across machines — three GitHub-runner runs-returned 0.5821, 0.5329 and 0.5933 — and setting the floor from the local-stability rather than that spread would have been the tempting mistake. The-declaration in `services/agents/tests/eval_data/live_agent_floor.json` carries-every run behind it, and the loader refuses a floor above its own evidence.--The lesson generalises past this row. A gate can look green while measuring-nothing: with the model pins unset, every agent caught its provider error and-used its deterministic path, and the run reported a groundedness of 0.8050 at-0.11 seconds per investigation — flattering, and faster than a network round-trip. `--wet-require-live` could not see that shape, because records existed-and the stack had imported. The harness now refuses a run that placed no LLM-call at all, and the report carries `llm_calls_placed` beside the mean.--"Cross-tenant isolation (Postgres)" left this list the only way it may: its gap-read "compiled-SQL not live DB", and `tests/isolation/test_postgres_rls.py` is-that live DB — the real migration chain on `postgres:16`, two tenants seeded-into every RLS-covered table, read back as a role that does not bypass RLS. The-row's caveat column now carries what the gate still does *not* prove (it reads-as a probe role, not as the deployed one) rather than dropping the caveat with-the status.--The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.+- NO GATE: 0-The Definition of Done requires zero `NO GATE` and zero unclosed `PARTIAL`. Each row's "Closes in" column is the binding commitment.+Counts come from `scripts/check_claim_gate_matrix.py`, which is also the gate. Recompute+rather than editing a number here: a count copied into prose goes stale silently, and the+parser stops at the first blank line inside the table, so a stray blank desynchronises this+block from the rows above it without failing anything.diff --git a/docs/audit/REALITY_REPORT.md b/docs/audit/REALITY_REPORT.mdindex 53ca35041..cce8c9ce2 100644--- a/docs/audit/REALITY_REPORT.md+++ b/docs/audit/REALITY_REPORT.md@@ -54,7 +54,7 @@ Phase 0 of the world-class program (`AISOC_CURSOR_PROMPT_V2.md`). This document| Claim | Code path | Status | Gated in CI? ||---|---|---|---|-| MCP server exposes 18 tools | `services/mcp/` | functional-untested | Yes (`ci.yml` MCP job: type-check/test/build) |+| MCP server exposes 19 tools | `services/mcp/` | functional-untested | Yes (`ci.yml` MCP job: type-check/test/build) || Plugin SDK Python/TypeScript/Go | `packages/sdk-{py,ts,go}` | functional-untested | Build/test gated; contract-drift vs `docs/openapi.yaml` NOT gated |## Overclaims (ranked)diff --git a/docs/design/landing-page-brief.md b/docs/design/landing-page-brief.mdindex fb1a80419..63375443e 100644--- a/docs/design/landing-page-brief.md+++ b/docs/design/landing-page-brief.md@@ -893,7 +893,7 @@ Condensed teardown lives at `docs/design/landing-page-references.md`.| Marketplace (7,155 items) | `marketplace/index.json` · `scripts/build_marketplace.py` | Detection engineer | V4 | connectors | Shipped || Credential vault (Fernet + HMAC) | `services/api/app/services/vault.py` · `apps/docs/docs/operations/credentials.md` | CISO | V4, P3 | deploy, pillars (P3) | Shipped || Plugin SDKs (Python, TypeScript, Go) | `packages/plugin-sdk-py/` · `packages/plugin-sdk-ts/` · `packages/plugin-sdk-go/` | Detection engineer | V4 | features-operate | Shipped |-| MCP server (18 tools) | `services/mcp/` | Detection engineer | V4 | features-operate | Shipped |+| MCP server (19 tools) | `services/mcp/` | Detection engineer | V4 | features-operate | Shipped || Cursor extension | `services/mcp/cursor-extension/` (T7.1) | Detection engineer | V4 | features-operate | Shipped (scaffold) || Render one-click deploy | `render.yaml` · `infra/render/` | Analyst, manager | V5 (deploy) | deploy | Shipped || Fly.io deploy script | `infra/fly/` | Manager | V5 | deploy | Shipped |diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex d72c4827b..deff8ecbb 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -8681,6 +8681,55 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/investigations/{run_id}/bundle:+ get:+ tags:+ - investigations+ summary: Export Evidence Bundle+ description: 'Export this investigation as a signed, replayable evidence bundle.+++ Two exports of one run produce identical bytes, so an auditor can++ diff them, re-hash them, and check the signature without trusting++ this endpoint. Prompts travel as digests rather than text, because a++ bundle is the artefact most likely to leave the customer''s control++ and a prompt carries their hostnames and usernames.+++ Served as a download rather than JSON so what the auditor verifies is++ the same byte sequence the signature was computed over. A client that++ re-serialised a parsed body would change the bytes and the signature++ would stop matching for a reason nobody could see.'+ operationId: export_evidence_bundle_api_v1_investigations__run_id__bundle_get+ security:+ - HTTPBearer: []+ parameters:+ - name: run_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Run Id+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/kill-switch:get:tags:@@ -16098,6 +16147,41 @@ paths:$ref: '#/components/schemas/AgentToolsResponse'security:- HTTPBearer: []+ /api/v1/agents/hunt:+ post:+ tags:+ - agents+ summary: Run Hunt+ description: 'Plan and run one natural-language hunt for the caller''s tenant.+++ The tenant comes from the authenticated principal and is never read++ from the body. A caller-supplied tenant on a route like this is the++ shape that has gone wrong here before.'+ operationId: run_hunt_api_v1_agents_hunt_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AgentHuntRequest'+ required: true+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AgentHuntResponse'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/inbox/templates:get:tags:@@ -17515,6 +17599,76 @@ components:- expires_at- urltitle: AdminInviteWire+ AgentHuntRequest:+ properties:+ hypothesis:+ type: string+ maxLength: 2000+ minLength: 1+ title: Hypothesis+ type: object+ required:+ - hypothesis+ title: AgentHuntRequest+ description: 'One natural-language hypothesis to hunt against tenant data.+++ Named `AgentHuntRequest`, not `HuntRequest`, and the reason is a++ published-contract one rather than a stylistic one.++ `detection_rules.py` already exports a `HuntRequest`, and FastAPI++ resolves a name collision by qualifying **both** models with their++ full module path. So adding a second `HuntRequest` deleted the plain++ `HuntRequest` schema from the spec and renamed the existing one —++ breaking every generated SDK client, for a route that had not++ changed. The openapi-breaking gate caught it.'+ AgentHuntResponse:+ properties:+ hypothesis:+ type: string+ title: Hypothesis+ checked:+ type: boolean+ title: Checked+ matches:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Matches+ default: []+ refusals:+ items:+ type: string+ type: array+ title: Refusals+ default: []+ unavailable_reason:+ anyOf:+ - type: string+ - type: 'null'+ title: Unavailable Reason+ type: object+ required:+ - hypothesis+ - checked+ title: AgentHuntResponse+ description: 'What the hunt found, or why it could not look.+++ `checked` and `unavailable_reason` are separate fields deliberately.++ A hunt that could not run is not a hunt that found nothing, and++ collapsing the two is how a console shows a reassuring empty result++ for a search that never happened.'AgentToolDescriptor:properties:name:diff --git a/scripts/check_gate_contract.py b/scripts/check_gate_contract.pyindex b2d15bb66..4701c7957 100644--- a/scripts/check_gate_contract.py+++ b/scripts/check_gate_contract.py@@ -150,6 +150,20 @@ EMPTY_TREE_EXCEPTIONS: dict[str, dict[str, tuple[str, str]]] = {"probe reporting a held port as held and the overlay using `ports: !override`.",)},+ "compare_eval_runs.py": {+ ANY_SHAPE: (+ "inconclusive",+ "Not a check of the repository. It is a two-input comparator: it takes --before and "+ "--after eval reports and publishes the delta between them, so there is no tree for "+ "it to credit and argparse correctly refuses a probe that supplies neither. Asking "+ "it whether an empty tree is clean is a question it cannot be asked, rather than one "+ "it answers wrongly. What it must get right instead is refusing comparisons that "+ "would read as results, and that is covered by scripts/tests/test_compare_eval_runs.py "+ "in both directions: an axis measured before and not after reports 'not comparable' "+ "rather than a -0.62 regression, two runs over different datasets are refused "+ "outright, and a balanced pair still compares so the refusals are not vacuous.",+ )+ },"wet_eval_check.py": {ANY_SHAPE: ("passed",diff --git a/scripts/compare_eval_runs.py b/scripts/compare_eval_runs.pynew file mode 100644index 000000000..0cc70bc93--- /dev/null+++ b/scripts/compare_eval_runs.py@@ -0,0 +1,319 @@+#!/usr/bin/env python3+"""Publish the delta between two eval runs, and refuse the ones that lie.++Parity 3.4, which defers to gap-closure 6.4: *"replay before and after+... and publish the delta."*++Why a delta needs its own tool+-------------------------------+Subtracting two numbers is easy. Subtracting them *honestly* is where+this goes wrong, and three of the four ways it goes wrong produce a+plausible figure rather than an error.++**"Not measured" is not zero, and a delta involving it is not a delta.**+If the before run measured malicious recall and the after run did not,+the arithmetic says `0.62 - 0 = -0.62` and the report says the agent got+much worse. It did not; nobody asked it. Every axis here reports one of+four states — improved, regressed, unchanged, or *not comparable* — and+the fourth exists because the first three would otherwise absorb it.++**A mean without its denominator is not comparable.** A precision of+1.00 over two predictions and a precision of 1.00 over two hundred are+the same number and different facts. When the support behind an axis+changes materially, the delta is reported with both counts rather than+as a bare difference.++**Two runs on different corpora are not a before and after.** A delta+between a run over 200 incidents and one over 10 measures the corpus,+not the change. The dataset identity is compared first and a mismatch is+refused outright.++**A wall-clock number is not a property of the change.** Latency differs+between two runs on one host, let alone two hosts, so it is excluded+from the verdict and reported separately, labelled as measuring the+machine.++What "regressed" means+----------------------+Any axis moving down by more than :data:`NOISE_FLOOR`. The floor is not+a tolerance for sloppiness — it exists because a bootstrap CI and a+sampled corpus both move slightly between runs, and a tool that called+every 0.001 drift a regression would be ignored within a week.+"""++from __future__ import annotations++import argparse+import json+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import self_test_if_requested # noqa: E402++self_test_if_requested(__file__)++#: Below this, a move is reported as unchanged. See the module docstring.+NOISE_FLOOR = 0.005++#: Axes whose *higher is better*. Everything else is reported without a+#: direction rather than guessed at, because a tool that assumed the+#: wrong direction would call an improvement a regression.+HIGHER_IS_BETTER = (+ "accuracy",+ "malicious_recall",+ "groundedness",+ "mitre_accuracy",+ "alert_reduction",+ "investigation_completeness",+ "response_quality",+)++#: Measures the host, not the agent. Reported, never graded.+HOST_AXES = ("mean_latency_ms", "p95_latency_ms")++#: Fields that identify the run rather than measure it. Excluded so the+#: dataset name does not become an axis with no delta.+_IDENTITY_KEYS = frozenset({"dataset", "corpus", "dataset_id", "model", "commit", "date", "mode"})++VERDICT_IMPROVED = "improved"+VERDICT_REGRESSED = "regressed"+VERDICT_UNCHANGED = "unchanged"+VERDICT_NOT_COMPARABLE = "not comparable"+++class ComparisonRefused(RuntimeError):+ """The two runs cannot honestly be compared. Carries why."""+++@dataclass(frozen=True)+class AxisDelta:+ axis: str+ before: float | None+ after: float | None+ delta: float | None+ verdict: str+ note: str = ""+ before_n: int | None = None+ after_n: int | None = None+++def _number(value: Any) -> float | None:+ """A float, or None for anything that is not a measurement.++ `None`, `"not measured"` and a missing key all mean the same thing+ and all become `None`. A string that happens to parse is still a+ number; a bool is not, because `True` would silently become 1.0.+ """+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, (int, float)):+ return float(value)+ if isinstance(value, str):+ try:+ return float(value)+ except ValueError:+ return None+ return None+++def _axis_values(report: dict[str, Any]) -> dict[str, tuple[float | None, int | None]]:+ """Flatten a report into axis -> (value, support).++ Handles both shapes this tree produces: a flat `{"accuracy": 0.9}`+ and the nested `{"groundedness": {"mean": 0.8, "scored_incidents": 20}}`+ the live-agent harness writes.+ """+ out: dict[str, tuple[float | None, int | None]] = {}+ for key, value in (report or {}).items():+ if isinstance(value, dict):+ number = _number(value.get("mean", value.get("value", value.get("score"))))+ support = value.get("scored_incidents", value.get("count", value.get("support")))+ out[key] = (number, support if isinstance(support, int) else None)+ elif key not in _IDENTITY_KEYS:+ # Recorded even when it is not a number, so a key that+ # stopped being a measurement shows up as "not comparable"+ # rather than vanishing. Dropping it is how a report loses an+ # axis without anyone noticing which one went quiet.+ out[key] = (_number(value), None)+ return out+++def _dataset_identity(report: dict[str, Any]) -> str | None:+ for key in ("dataset", "corpus", "dataset_id"):+ value = report.get(key)+ if isinstance(value, str) and value:+ return value+ return None+++def compare(before: dict[str, Any], after: dict[str, Any]) -> list[AxisDelta]:+ """Every axis in either run, with a verdict that can say "no".++ Axes present in only one run are reported as not comparable rather+ than dropped: an axis that stopped being measured is a change worth+ seeing, and silently omitting it is how a report shrinks without+ anyone noticing.+ """+ before_id, after_id = _dataset_identity(before), _dataset_identity(after)+ if before_id and after_id and before_id != after_id:+ raise ComparisonRefused(+ f"these runs used different datasets ({before_id!r} and {after_id!r}), so a delta "+ "between them measures the corpus rather than the change"+ )++ left, right = _axis_values(before), _axis_values(after)+ deltas: list[AxisDelta] = []++ for axis in sorted(set(left) | set(right)):+ before_value, before_n = left.get(axis, (None, None))+ after_value, after_n = right.get(axis, (None, None))++ if axis in HOST_AXES:+ deltas.append(+ AxisDelta(+ axis=axis,+ before=before_value,+ after=after_value,+ delta=None,+ verdict=VERDICT_NOT_COMPARABLE,+ note="measures the machine the run happened on, not the agent",+ before_n=before_n,+ after_n=after_n,+ )+ )+ continue++ if before_value is None or after_value is None:+ # The case the arithmetic gets wrong. Saying "not measured"+ # minus 0.62 is a regression would be a confident lie.+ which = (+ "the before run did not measure it"+ if before_value is None and after_value is not None+ else "the after run did not measure it"+ if after_value is None and before_value is not None+ else "neither run measured it"+ )+ deltas.append(+ AxisDelta(+ axis=axis,+ before=before_value,+ after=after_value,+ delta=None,+ verdict=VERDICT_NOT_COMPARABLE,+ note=f"{which}; absent is not zero, so there is no delta to report",+ before_n=before_n,+ after_n=after_n,+ )+ )+ continue++ raw = after_value - before_value+ if abs(raw) <= NOISE_FLOOR:+ verdict = VERDICT_UNCHANGED+ elif axis in HIGHER_IS_BETTER:+ verdict = VERDICT_IMPROVED if raw > 0 else VERDICT_REGRESSED+ else:+ verdict = VERDICT_NOT_COMPARABLE++ note = ""+ if axis not in HIGHER_IS_BETTER and verdict == VERDICT_NOT_COMPARABLE:+ note = "no known direction for this axis, so the move is reported without a verdict"+ elif before_n is not None and after_n is not None and before_n and after_n:+ ratio = after_n / before_n+ if ratio < 0.5 or ratio > 2.0:+ note = (+ f"support changed from {before_n} to {after_n}; a mean over a materially "+ "different number of cases is a different fact, not only a different number"+ )++ deltas.append(+ AxisDelta(+ axis=axis,+ before=before_value,+ after=after_value,+ delta=round(raw, 6),+ verdict=verdict,+ note=note,+ before_n=before_n,+ after_n=after_n,+ )+ )++ return deltas+++def _fmt(value: float | None) -> str:+ return "not measured" if value is None else f"{value:.4f}"+++def format_delta_report(deltas: list[AxisDelta], *, before_label: str, after_label: str) -> str:+ """Markdown, deterministic, with "not measured" spelled out.++ No timestamps and no host names: a report that has to reproduce for+ a reviewer cannot carry either.+ """+ lines = [+ "# Before and after",+ "",+ f"- Before: `{before_label}`",+ f"- After: `{after_label}`",+ "",+ "| Axis | Before | After | Delta | Verdict |",+ "|---|---|---|---|---|",+ ]+ for d in deltas:+ delta = "—" if d.delta is None else f"{d.delta:+.4f}"+ lines.append(f"| `{d.axis}` | {_fmt(d.before)} | {_fmt(d.after)} | {delta} | {d.verdict} |")++ notes = [d for d in deltas if d.note]+ if notes:+ lines += ["", "## Why some axes have no delta", ""]+ lines += [f"- **`{d.axis}`** — {d.note}" for d in notes]++ regressed = [d.axis for d in deltas if d.verdict == VERDICT_REGRESSED]+ lines += ["", f"**Regressions: {len(regressed)}**" + (f" — {', '.join(regressed)}" if regressed else "")]+ return "\n".join(lines) + "\n"+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--before", required=True, type=Path)+ parser.add_argument("--after", required=True, type=Path)+ parser.add_argument("--out", type=Path, help="write the Markdown report here")+ parser.add_argument(+ "--fail-on-regression",+ action="store_true",+ help="exit non-zero when any graded axis moved down past the noise floor",+ )+ args = parser.parse_args()++ before = json.loads(args.before.read_text(encoding="utf-8"))+ after = json.loads(args.after.read_text(encoding="utf-8"))++ try:+ deltas = compare(before, after)+ except ComparisonRefused as exc:+ print(f"compare_eval_runs: REFUSED — {exc}", file=sys.stderr)+ return 2++ report = format_delta_report(deltas, before_label=args.before.name, after_label=args.after.name)+ if args.out:+ args.out.write_text(report, encoding="utf-8")+ print(report)++ regressed = [d for d in deltas if d.verdict == VERDICT_REGRESSED]+ if regressed and args.fail_on_regression:+ print(+ f"compare_eval_runs: {len(regressed)} axis/axes regressed: " + ", ".join(d.axis for d in regressed),+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/score_replay_set.py b/scripts/score_replay_set.pynew file mode 100644index 000000000..d9acc3283--- /dev/null+++ b/scripts/score_replay_set.py@@ -0,0 +1,178 @@+#!/usr/bin/env python3+"""Grade a labelled replay set, or refuse to publish a flattering number.++Parity 3.2, the part that decides whether the rest of it means anything.++The spec asks for verdict accuracy, per-class precision and recall,+malicious recall with a confidence interval, and false-negative counts,+reported through ``aisoc_benchmark`` on labelled replay sets. The scoring+for all of that already exists in+:mod:`aisoc_benchmark.replay`. What did not exist is the thing standing+in front of it.++Why a guard, and not just a runner+------------------------------------+Every labelled corpus in this repository is **entirely malicious by+construction**. ``synthetic_incidents.json`` and+``adversary_incidents.json`` are 200 incidents each, every one a real+attack; their ``response_class`` field says which action to take, not+whether the finding was true. There is no benign case and no false+positive anywhere in ``services/agents/tests/eval_data/``.++Score an agent against that and an agent that answers "true positive" to+everything, without reading anything, posts **100% accuracy and 100%+malicious recall**. Publishing that would be the exact mirror of the+failure :mod:`aisoc_benchmark.replay` already guards against at the other+end — it withholds headline accuracy below 30 malicious cases because+98% on a corpus of three is misleading in the direction that sells. A+corpus with no benign cases is misleading in the same direction, harder,+and nothing was checking for it.++So this refuses. :func:`assert_gradeable` is the point of the module and+the runner below is the ordinary part.++What "labelled" has to mean+-----------------------------+Each decision carries an ``expected_disposition`` drawn from the four+canonical values, and the set contains at least two distinct classes with+at least :data:`MIN_MINORITY_SHARE` of the corpus in the minority one. A+corpus can be imbalanced — real queues are — but a corpus with *one*+class cannot measure a classifier at all.+"""++from __future__ import annotations++import argparse+import json+import sys+from collections import Counter+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "packages" / "aisoc-benchmark"))++from aisoc_benchmark.replay import ( # noqa: E402+ GRADED_DISPOSITIONS,+ MALICIOUS,+ format_replay_report,+ score_replay,+)++#: The smallest share the minority class may hold before the corpus stops+#: being able to measure a classifier. Deliberately low: real queues are+#: imbalanced, and refusing those would make the tool useless on exactly+#: the data it is for. One in twenty is enough for a wrong answer to show+#: up; zero in twenty is not.+MIN_MINORITY_SHARE = 0.05+++class CorpusNotGradeable(RuntimeError):+ """The corpus cannot measure what the caller wants to publish."""+++def assert_gradeable(decisions: list[dict[str, Any]]) -> None:+ """Refuse a corpus whose score would flatter by construction.++ Raises rather than warning. A warning in a CI log is read once; a+ number in ``benchmark.md`` is read by everyone evaluating this+ project, and the asymmetry is the whole argument.+ """+ if not decisions:+ raise CorpusNotGradeable("the set is empty, so there is nothing to grade")++ labelled = [d for d in decisions if d.get("expected_disposition") in GRADED_DISPOSITIONS]+ if not labelled:+ raise CorpusNotGradeable(+ "no decision carries an `expected_disposition` from "+ f"{list(GRADED_DISPOSITIONS)}. A set without analyst labels cannot measure verdict "+ "accuracy; it can only measure whether the agent answered."+ )++ counts = Counter(d["expected_disposition"] for d in labelled)+ if len(counts) < 2:+ only = next(iter(counts))+ raise CorpusNotGradeable(+ f"every one of the {len(labelled)} labelled decisions is {only!r}. An agent that "+ f"answers {only!r} to everything, without reading anything, would score 100% here. "+ "Publishing that is misleading in the direction that sells, which is the same "+ "failure aisoc_benchmark.replay guards against at the other end."+ )++ minority = min(counts.values())+ share = minority / len(labelled)+ if share < MIN_MINORITY_SHARE:+ smallest = min(counts, key=lambda k: counts[k])+ raise CorpusNotGradeable(+ f"the smallest class ({smallest!r}) holds {minority} of {len(labelled)} decisions "+ f"({share:.1%}), below the {MIN_MINORITY_SHARE:.0%} floor. A corpus this skewed "+ "reports the base rate rather than the agent."+ )+++def grade(+ decisions: list[dict[str, Any]],+ *,+ model: str,+ dataset: str,+ commit: str,+ synthetic: bool,+) -> dict[str, Any]:+ """Score a labelled set and return a publishable report.++ `synthetic` is required rather than inferred. The spec says to label+ synthetic sets as synthetic, and a flag that defaults either way+ would eventually be wrong silently.+ """+ assert_gradeable(decisions)+ score = score_replay(decisions)++ return {+ "model": model,+ "dataset": dataset,+ "commit": commit,+ "synthetic": synthetic,+ "provenance": (+ "Synthetic corpus — generated, not a customer's closed findings. These numbers describe the agent on manufactured data."+ if synthetic+ else "Replay over recorded findings closed by analysts."+ ),+ "malicious_label": MALICIOUS,+ "score": score.as_dict(),+ "report_markdown": format_replay_report(score),+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--decisions", required=True, type=Path, help="JSON list of graded decisions")+ parser.add_argument("--model", required=True, help="the model id these decisions came from")+ parser.add_argument("--dataset", required=True, help="the corpus id")+ parser.add_argument("--commit", default="unknown", help="the commit the agent ran at")+ parser.add_argument("--synthetic", action="store_true", help="the corpus is generated, not real")+ parser.add_argument("--out", type=Path)+ args = parser.parse_args()++ decisions = json.loads(args.decisions.read_text(encoding="utf-8"))+ if isinstance(decisions, dict):+ decisions = decisions.get("decisions", [])++ try:+ report = grade(+ decisions,+ model=args.model,+ dataset=args.dataset,+ commit=args.commit,+ synthetic=args.synthetic,+ )+ except CorpusNotGradeable as exc:+ print(f"score_replay_set: REFUSED — {exc}", file=sys.stderr)+ return 2++ if args.out:+ args.out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ print(report["report_markdown"])+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/security_audit_ignores.txt b/scripts/security_audit_ignores.txtindex 6cd0c0a6a..0a5c679d9 100644--- a/scripts/security_audit_ignores.txt+++ b/scripts/security_audit_ignores.txt@@ -157,3 +157,5 @@ pnpm|GHSA-w3rx-r6r6-pgpr|apps/mobile resolves image-size 1.2.1 through metro 0.8# released code and `pnpm_install_roots` scans every lockfile on purpose, so# excluding it would hide every future advisory there.pnpm|GHSA-86w9-cpqp-85rv|No patched version exists upstream. Transitive via @expo/cli in apps/mobile, which pnpm-workspace.yaml excludes and no Dockerfile builds; absent from the root lockfile and from every service image.|2026-12-29+pnpm|GHSA-ch52-4w7c-c8xp|No patched version exists: npm's latest http-cache-semantics is 4.2.0 and the advisory affects <=4.2.0. Reached only through the docs site's update check (@docusaurus/core -> update-notifier -> latest-version -> package-json -> got -> cacheable-request), which runs on the runner during a Pages build. No Dockerfile builds apps/docs and @docusaurus/core appears in no other package.json, so it is in no shipped image. The flaw is cross-user cache disclosure in a shared HTTP cache; this path makes one registry request in a single-tenant CI job.|2026-12-31+pnpm|GHSA-vfj7-8cjw-p6xm|No patched version exists: npm's latest braces is 3.0.3 and the advisory affects <=3.0.3. Stack-exhaustion DoS (CWE-674) triggered by expanding a deeply nested glob pattern. Reached only transitively through chokidar and micromatch, which are build tooling; neither is a direct dependency of any package here, and the patterns they expand come from this repository's own build configuration rather than from user input. No runtime route accepts a glob.|2026-12-31diff --git a/scripts/tests/test_compare_eval_runs.py b/scripts/tests/test_compare_eval_runs.pynew file mode 100644index 000000000..50fa3749b--- /dev/null+++ b/scripts/tests/test_compare_eval_runs.py@@ -0,0 +1,152 @@+"""A delta between two eval runs, and the four ways it lies if unguarded.++Parity 3.4. Three of the four failure modes produce a plausible figure+rather than an error, which is why each gets its own class.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from compare_eval_runs import ( # noqa: E402+ VERDICT_IMPROVED,+ VERDICT_NOT_COMPARABLE,+ VERDICT_REGRESSED,+ VERDICT_UNCHANGED,+ ComparisonRefused,+ compare,+ format_delta_report,+)+++def _axis(deltas, name):+ return next(d for d in deltas if d.axis == name)+++class TestTheOrdinaryCase:+ def test_an_improvement_is_called_an_improvement(self) -> None:+ deltas = compare({"accuracy": 0.80}, {"accuracy": 0.86})+ assert _axis(deltas, "accuracy").verdict == VERDICT_IMPROVED+ assert _axis(deltas, "accuracy").delta == pytest.approx(0.06)++ def test_a_regression_is_called_a_regression(self) -> None:+ assert _axis(compare({"accuracy": 0.86}, {"accuracy": 0.80}), "accuracy").verdict == VERDICT_REGRESSED++ def test_a_tiny_move_is_unchanged(self) -> None:+ """A bootstrap CI and a sampled corpus both drift between runs.+ A tool that called every 0.001 a regression would be ignored+ within a week."""+ assert _axis(compare({"accuracy": 0.800}, {"accuracy": 0.8009}), "accuracy").verdict == VERDICT_UNCHANGED+++class TestNotMeasuredIsNotZero:+ """The failure that produces the most confident wrong answer."""++ def test_an_axis_that_stopped_being_measured_is_not_a_regression(self) -> None:+ deltas = compare({"malicious_recall": 0.62}, {"malicious_recall": None})+ axis = _axis(deltas, "malicious_recall")++ assert axis.verdict == VERDICT_NOT_COMPARABLE, (+ "0.62 -> not measured was reported as a regression; the agent did not get worse, nobody asked it"+ )+ assert axis.delta is None+ assert "absent is not zero" in axis.note++ def test_the_string_not_measured_is_handled_too(self) -> None:+ """Reports in this tree write the words as well as null."""+ assert _axis(compare({"accuracy": "not measured"}, {"accuracy": 0.9}), "accuracy").verdict == VERDICT_NOT_COMPARABLE++ def test_a_newly_measured_axis_is_not_an_improvement(self) -> None:+ deltas = compare({"groundedness": None}, {"groundedness": 0.81})+ assert _axis(deltas, "groundedness").verdict == VERDICT_NOT_COMPARABLE++ def test_an_axis_only_in_one_run_is_reported_not_dropped(self) -> None:+ """Silently omitting it is how a report shrinks without anyone+ noticing which axis went quiet."""+ deltas = compare({"accuracy": 0.9}, {"accuracy": 0.9, "mitre_accuracy": 0.4})+ assert _axis(deltas, "mitre_accuracy").verdict == VERDICT_NOT_COMPARABLE++ def test_a_boolean_is_not_a_measurement(self) -> None:+ """`True` would silently become 1.0 and compare against a real+ rate."""+ assert _axis(compare({"measured": True}, {"measured": False}), "measured").verdict == VERDICT_NOT_COMPARABLE+++class TestAMeanWithoutItsDenominator:+ def test_a_materially_changed_support_is_called_out(self) -> None:+ """A precision of 1.00 over two predictions and over two hundred+ are the same number and different facts."""+ deltas = compare(+ {"accuracy": {"mean": 0.90, "scored_incidents": 200}},+ {"accuracy": {"mean": 0.95, "scored_incidents": 10}},+ )+ axis = _axis(deltas, "accuracy")+ assert axis.verdict == VERDICT_IMPROVED+ assert "support changed from 200 to 10" in axis.note++ def test_a_steady_support_needs_no_caveat(self) -> None:+ deltas = compare(+ {"accuracy": {"mean": 0.90, "scored_incidents": 200}},+ {"accuracy": {"mean": 0.95, "scored_incidents": 195}},+ )+ assert _axis(deltas, "accuracy").note == ""+++class TestTwoRunsOnDifferentCorpora:+ def test_a_dataset_mismatch_is_refused_outright(self) -> None:+ """A delta between a 200-incident run and a 10-incident one+ measures the corpus, not the change."""+ with pytest.raises(ComparisonRefused, match="different datasets"):+ compare(+ {"dataset": "synthetic_incidents", "accuracy": 0.9},+ {"dataset": "mitre_engenuity_micro", "accuracy": 0.95},+ )++ def test_the_same_dataset_compares_normally(self) -> None:+ deltas = compare(+ {"dataset": "synthetic_incidents", "accuracy": 0.90},+ {"dataset": "synthetic_incidents", "accuracy": 0.95},+ )+ assert _axis(deltas, "accuracy").verdict == VERDICT_IMPROVED++ def test_runs_that_name_no_dataset_are_still_compared(self) -> None:+ """Refusing those would make the tool unusable on every report+ this tree already writes."""+ assert _axis(compare({"accuracy": 0.9}, {"accuracy": 0.95}), "accuracy").verdict == VERDICT_IMPROVED+++class TestWallClockIsNotGraded:+ def test_latency_is_reported_but_never_a_regression(self) -> None:+ """It differs between two runs on one host, let alone two."""+ deltas = compare({"mean_latency_ms": 100.0}, {"mean_latency_ms": 900.0})+ axis = _axis(deltas, "mean_latency_ms")+ assert axis.verdict == VERDICT_NOT_COMPARABLE+ assert "machine" in axis.note+++class TestTheReport:+ def test_it_spells_out_not_measured(self) -> None:+ report = format_delta_report(+ compare({"accuracy": 0.9, "malicious_recall": None}, {"accuracy": 0.9, "malicious_recall": None}),+ before_label="a.json",+ after_label="b.json",+ )+ assert "not measured" in report+ assert "| 0.0000 |" not in report, "an unmeasured axis was rendered as zero"++ def test_it_counts_regressions_explicitly(self) -> None:+ report = format_delta_report(compare({"accuracy": 0.9}, {"accuracy": 0.5}), before_label="a", after_label="b")+ assert "**Regressions: 1**" in report+ assert "accuracy" in report++ def test_it_is_deterministic(self) -> None:+ """A report a reviewer has to diff cannot carry a timestamp."""+ args = ({"accuracy": 0.9}, {"accuracy": 0.95})+ first = format_delta_report(compare(*args), before_label="a", after_label="b")+ second = format_delta_report(compare(*args), before_label="a", after_label="b")+ assert first == seconddiff --git a/scripts/tests/test_score_replay_set.py b/scripts/tests/test_score_replay_set.pynew file mode 100644index 000000000..73fe0e389--- /dev/null+++ b/scripts/tests/test_score_replay_set.py@@ -0,0 +1,146 @@+"""A labelled set is graded, or refused for a reason that is stated.++Parity 3.2. The guard is the point of the module: every labelled corpus+in this repository is entirely malicious by construction, so an agent+that answers "true positive" to everything without reading anything+would post 100% accuracy and 100% malicious recall.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "scripts"))++from score_replay_set import ( # noqa: E402+ MIN_MINORITY_SHARE,+ CorpusNotGradeable,+ assert_gradeable,+ grade,+)+++def _decision(expected: str, verdict: str | None = None, **extra):+ base = {+ "expected_disposition": expected,+ "verdict": verdict if verdict is not None else expected,+ "evidence": {"src_ip": "198.51.100.4"},+ "findings": ["saw 198.51.100.4"],+ }+ base.update(extra)+ return base+++def _balanced(n: int = 40):+ """Half malicious, half not — enough to grade."""+ return [_decision("true_positive") for _ in range(n // 2)] + [_decision("false_positive") for _ in range(n // 2)]+++class TestItRefusesACorpusThatWouldFlatter:+ def test_an_all_malicious_corpus_is_refused(self) -> None:+ """The shape every labelled set in this tree actually has."""+ with pytest.raises(CorpusNotGradeable, match="answers 'true_positive' to everything"):+ assert_gradeable([_decision("true_positive") for _ in range(200)])++ def test_an_all_benign_corpus_is_refused_too(self) -> None:+ """The same failure from the other side. A guard that only+ caught one direction would be half a guard."""+ with pytest.raises(CorpusNotGradeable, match="to everything"):+ assert_gradeable([_decision("false_positive") for _ in range(200)])++ def test_a_corpus_with_no_labels_is_refused(self) -> None:+ """A set without analyst labels can measure whether the agent+ answered, not whether it was right."""+ with pytest.raises(CorpusNotGradeable, match="expected_disposition"):+ assert_gradeable([{"verdict": "true_positive"} for _ in range(50)])++ def test_an_empty_set_is_refused(self) -> None:+ with pytest.raises(CorpusNotGradeable, match="nothing to grade"):+ assert_gradeable([])++ def test_a_corpus_below_the_minority_floor_is_refused(self) -> None:+ """One benign case in two hundred reports the base rate, not the+ agent."""+ decisions = [_decision("true_positive") for _ in range(199)] + [_decision("false_positive")]+ with pytest.raises(CorpusNotGradeable, match="below the"):+ assert_gradeable(decisions)++ def test_the_refusal_names_the_counts(self) -> None:+ """So whoever hits it can see how far off the corpus is rather+ than guessing."""+ decisions = [_decision("true_positive") for _ in range(199)] + [_decision("false_positive")]+ with pytest.raises(CorpusNotGradeable) as caught:+ assert_gradeable(decisions)+ assert "1 of 200" in str(caught.value)+++class TestItGradesACorpusThatCan:+ def test_a_balanced_corpus_is_accepted(self) -> None:+ """The negative control for every refusal above: without it they+ would all pass against a guard that refuses everything."""+ assert_gradeable(_balanced()) # does not raise, which is the assertion++ def test_an_imbalanced_but_gradeable_corpus_is_accepted(self) -> None:+ """Real queues are imbalanced. Refusing those would make the tool+ useless on exactly the data it is for."""+ decisions = [_decision("true_positive") for _ in range(10)] + [_decision("false_positive") for _ in range(90)]+ assert_gradeable(decisions) # does not raise, which is the assertion++ def test_exactly_at_the_floor_is_accepted(self) -> None:+ minority = int(100 * MIN_MINORITY_SHARE)+ decisions = [_decision("true_positive") for _ in range(100 - minority)] + [_decision("false_positive") for _ in range(minority)]+ assert_gradeable(decisions) # does not raise, which is the assertion+++class TestTheReport:+ def test_it_carries_the_model_dataset_and_commit(self) -> None:+ """The spec's publication clause: a number without its model and+ dataset describes nothing."""+ report = grade(_balanced(), model="llama3.2:3b", dataset="demo", commit="abc1234", synthetic=True)+ assert report["model"] == "llama3.2:3b"+ assert report["dataset"] == "demo"+ assert report["commit"] == "abc1234"++ def test_a_synthetic_corpus_says_so_prominently(self) -> None:+ report = grade(_balanced(), model="m", dataset="d", commit="c", synthetic=True)+ assert report["synthetic"] is True+ assert "Synthetic corpus" in report["provenance"]++ def test_a_real_corpus_says_that_instead(self) -> None:+ report = grade(_balanced(), model="m", dataset="d", commit="c", synthetic=False)+ assert report["synthetic"] is False+ assert "closed by analysts" in report["provenance"]++ def test_it_scores_through_the_benchmark_package(self) -> None:+ """Not a second scorer. A different definition of accuracy would+ drift from the scoreboard's while looking like the same number."""+ report = grade(_balanced(), model="m", dataset="d", commit="c", synthetic=True)+ assert "decisions" in report["score"]+ assert report["report_markdown"].startswith("#")++ def test_it_is_json_serialisable(self) -> None:+ """It gets written to a file and read by the docs build."""+ json.dumps(grade(_balanced(), model="m", dataset="d", commit="c", synthetic=True))+++class TestTheCorporaThisTreeActuallyHas:+ @pytest.mark.parametrize("name", ["synthetic_incidents", "adversary_incidents"])+ def test_they_are_refused_and_that_is_the_finding(self, name: str) -> None:+ """Not a bug in the corpora — they were built to exercise MITRE+ mapping and response selection, not verdict accuracy. The point+ is that nothing may publish an accuracy number from them.+ """+ path = ROOT / "services" / "agents" / "tests" / "eval_data" / f"{name}.json"+ raw = json.loads(path.read_text(encoding="utf-8"))+ items = raw if isinstance(raw, list) else next((v for v in raw.values() if isinstance(v, list)), [])++ decisions = [+ {"expected_disposition": i.get("expected_disposition"), "verdict": "true_positive"} for i in items if isinstance(i, dict)+ ]+ with pytest.raises(CorpusNotGradeable):+ assert_gradeable(decisions)diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.pyindex c176a2731..a06acec1e 100644--- a/services/agents/app/api/copilot.py+++ b/services/agents/app/api/copilot.py@@ -28,6 +28,7 @@ from fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Fieldfrom app.api import conversation_store+from app.api.copilot_grounding import ground_answer, sources_from_contextfrom app.security.tenant_scope import (TenantPrincipal,TenantScopeError,@@ -71,6 +72,11 @@ class CopilotChatResponse(BaseModel):#: analysis of the user's environment.source: Literal["llm", "template"] = "llm"notice: str | None = None+ #: Which factual claims in `reply` cite a record, and which cite+ #: nothing (parity 3.6). The console renders the label beside the+ #: answer: an analyst has no other way to tell a claim drawn from the+ #: evidence from one the model produced because it sounded right.+ grounding: dict[str, Any] | None = Noneclass CopilotConversation(BaseModel):@@ -81,7 +87,12 @@ class CopilotConversation(BaseModel):# ----------------------------------------------------------------------------# In-memory store (demo: resets on restart; production would use Postgres)+# Conversation store+#+# Tenant-scoped and persistent. This said "in-memory (demo: resets on+# restart)" long after `conversation_store` took both a tenant and a+# database, which is the kind of stale comment that makes a reader+# distrust the ones that are true.# ---------------------------------------------------------------------------@@ -274,10 +285,17 @@ async def chat(new_messages=[user_msg, assistant_msg],)+ # Grade the answer against what it was given, and say so either way.+ # A template reply is not graded: it asserts nothing about this+ # estate, and labelling generic guidance "uncited" would put a+ # warning where there is no claim to warn about.+ grounding = ground_answer(reply_text, sources_from_context(req.context)).as_dict() if reply_source == "llm" else None+return CopilotChatResponse(conversationId=stored.id,reply=CopilotMessage(**assistant_msg),source=reply_source,+ grounding=grounding,notice=("This reply came from a built-in template, not a language model. ""It is generic guidance and is not analysis of your environment. "diff --git a/services/agents/app/api/copilot_grounding.py b/services/agents/app/api/copilot_grounding.pynew file mode 100644index 000000000..88d553478--- /dev/null+++ b/services/agents/app/api/copilot_grounding.py@@ -0,0 +1,208 @@+"""Tie every factual claim in a copilot answer to the record behind it.++Parity 3.6, the half that decides whether the rest is worth having.++The copilot answers questions about a customer's own estate. An answer+that names a host, an IP or a CVE is making a claim about their network,+and the analyst reading it has no way to tell a claim drawn from the+evidence from one the model produced because it sounded right. So every+checkable claim either cites the record it came from, or the answer says+plainly that it does not.++What counts as a checkable claim+----------------------------------+Exactly what `app.confidence.groundedness` already counts: IPs, hashes,+CVEs, MITRE techniques and domains. Deliberately the same extractor,+imported rather than re-implemented, for the reason+`aisoc_benchmark.replay` records about its own reuse — a second+definition of "checkable" would eventually disagree with the first, and+the two numbers would stop being comparable while still looking like+they were.++Prose is not a claim. "This looks like credential access" cites nothing+and needs no citation; "198.51.100.4 contacted the domain controller"+does.++What a citation points at+---------------------------+A ledger entry — a run and a sequence number — or an alert id. Both are+things an analyst can open. A citation that pointed at a paragraph of+context the console happened to send would be unfalsifiable: there would+be nothing to go and look at.++Why "uncited" is a first-class outcome+----------------------------------------+The tempting design is to suppress uncited claims, or to quietly drop+them from the answer. Both are worse than saying so. An analyst who sees+*"this part is not supported by anything I was given"* can go and check;+one who sees a confident sentence with the unsupported half silently+removed has been handed a different answer than the model gave, by+something that cannot reliably tell which half was wrong.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++from app.confidence.groundedness import _extract++__all__ = [+ "Citation",+ "GroundedAnswer",+ "EvidenceSource",+ "ground_answer",+]+++@dataclass(frozen=True)+class EvidenceSource:+ """One record the copilot was given, and how to open it.++ `ref` is what the console turns into a link. `kind` says which store+ it came from so a reader knows whether they are looking at an+ immutable ledger row or a mutable alert.+ """++ #: `ledger:<run_id>#<seq>`, `alert:<uuid>`, or `case:<uuid>`.+ ref: str+ kind: str+ #: Everything the source said, flattened. Indicators are matched+ #: against this.+ text: str+ label: str | None = None+++@dataclass(frozen=True)+class Citation:+ """One checkable claim, and the sources that actually contain it."""++ claim: str+ refs: tuple[str, ...]+++@dataclass(frozen=True)+class GroundedAnswer:+ """A copilot reply, graded against what it was given."""++ #: Claims found in at least one source.+ citations: tuple[Citation, ...] = field(default_factory=tuple)+ #: Claims found in none of them. The reason this type exists.+ uncited: tuple[str, ...] = field(default_factory=tuple)+ #: True when the answer made no checkable claim at all. Distinct from+ #: "every claim was cited": an answer that asserts nothing concrete+ #: is not grounded, it is simply not checkable, and reporting it as+ #: grounded would make the label meaningless on exactly the prose+ #: answers where it should be silent.+ no_claims: bool = False++ @property+ def fully_cited(self) -> bool:+ """Every checkable claim cites something. False when any did not."""+ return not self.uncited and not self.no_claims++ @property+ def label(self) -> str:+ """What the console shows beside the answer.++ Three outcomes, not two, because "asserted nothing" and "asserted+ things and supported all of them" deserve different words.+ """+ if self.no_claims:+ return "no checkable claims"+ if self.uncited:+ return "partially uncited" if self.citations else "uncited"+ return "cited"++ def as_dict(self) -> dict[str, Any]:+ return {+ "label": self.label,+ "fully_cited": self.fully_cited,+ "no_claims": self.no_claims,+ "citations": [{"claim": c.claim, "refs": list(c.refs)} for c in self.citations],+ "uncited": list(self.uncited),+ }+++def ground_answer(answer: str, sources: list[EvidenceSource]) -> GroundedAnswer:+ """Grade one answer against the records it was given.++ Returns rather than raises on an ungrounded answer: refusing to show+ it would hide the model's actual output from the person best placed+ to judge it. The label is what carries the warning.+ """+ claims = _extract(answer or "")+ if not claims:+ return GroundedAnswer(no_claims=True)++ # Each source's indicators, extracted once rather than per claim.+ by_source = [(source.ref, _extract(source.text or "")) for source in sources]++ citations: list[Citation] = []+ uncited: list[str] = []+ for claim in sorted(claims):+ refs = tuple(ref for ref, found in by_source if claim in found)+ if refs:+ citations.append(Citation(claim=claim, refs=refs))+ else:+ uncited.append(claim)++ return GroundedAnswer(citations=tuple(citations), uncited=tuple(uncited))+++def sources_from_ledger(rows: list[dict[str, Any]]) -> list[EvidenceSource]:+ """Turn ledger event rows into citable sources.++ `ledger:<run>#<seq>` rather than the event's own uuid, because that+ is the coordinate `aisoc_explain_step` and the console's replay view+ both address a step by. A citation an analyst cannot paste somewhere+ is not much of a citation.+ """+ sources: list[EvidenceSource] = []+ for row in rows:+ run_id = row.get("run_id")+ seq = row.get("seq")+ if run_id is None or seq is None:+ continue+ sources.append(+ EvidenceSource(+ ref=f"ledger:{run_id}#{seq}",+ kind="ledger",+ label=str(row.get("summary") or row.get("kind") or ""),+ # Summary and payload both: an indicator can appear in+ # either, and a citation that missed the payload would+ # call a supported claim uncited.+ text=f"{row.get('summary') or ''} {row.get('payload') or ''}",+ )+ )+ return sources+++def sources_from_context(context: dict[str, Any] | None) -> list[EvidenceSource]:+ """Turn the page context the console sends into citable sources.++ Only the parts that carry an identifier. A free-text page title is+ context for the model and is deliberately *not* citable: pointing a+ citation at it would give the analyst nothing to open.+ """+ if not isinstance(context, dict):+ return []+ sources: list[EvidenceSource] = []+ for key, prefix in (("alert", "alert"), ("case", "case"), ("alerts", "alert")):+ value = context.get(key)+ items = value if isinstance(value, list) else [value] if value else []+ for item in items:+ if not isinstance(item, dict):+ continue+ identifier = item.get("id")+ if not identifier:+ continue+ sources.append(+ EvidenceSource(+ ref=f"{prefix}:{identifier}",+ kind=prefix,+ label=str(item.get("title") or ""),+ text=repr(item),+ )+ )+ return sourcesdiff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.pyindex ecad06a26..bb363ad6f 100644--- a/services/agents/app/playbook/engine.py+++ b/services/agents/app/playbook/engine.py@@ -418,7 +418,12 @@ async def _handle_notify(step: PlaybookStep, context: dict[str, Any], http: httpraise SSRFError(f"notify step rejected: {exc}") from excr = await http.post(url, json={"text": message}, timeout=step.timeout_seconds)return {"status": r.status_code}- return {"channel": channel, "message": message, "delivered": False, "reason": "no url"}+ # Why it did not deliver, accurately. This said "no url" whatever the+ # cause, including when a url *was* supplied and the channel simply+ # was not `webhook` — so an operator debugging a silent playbook went+ # looking for a missing field that was right there in front of them.+ reason = "no url" if not url else f"channel {channel!r} has no sender; only 'webhook' delivers, and a url was supplied"+ return {"channel": channel, "message": message, "delivered": False, "reason": reason}async def _handle_http(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:diff --git a/services/agents/app/playbook/ssrf_guard.py b/services/agents/app/playbook/ssrf_guard.pyindex fd0847490..e22b82d46 100644--- a/services/agents/app/playbook/ssrf_guard.py+++ b/services/agents/app/playbook/ssrf_guard.py@@ -24,9 +24,16 @@ handlers before they hand a URL to ``httpx``. It rejects:Operators can:-* Set ``AISOC_SSRF_ALLOW_PRIVATE=1`` to relax the private/loopback check- for on-prem deployments where playbooks must reach internal services- (still rejects cloud-metadata literals and link-local/multicast).+* Set ``AISOC_SSRF_ALLOW_PRIVATE=1`` to relax the **private-range** check+ for on-prem deployments where playbooks must reach internal services.+ It does not relax loopback, and this header used to say it did —+ directly contradicting :func:`_is_disallowed_address`'s own docstring+ two hundred lines below, which has always said loopback is rejected+ either way. The code is the correct half: a playbook that can reach+ ``127.0.0.1`` can reach every unauthenticated service on the host+ running the engine, which is a larger hole than the one the flag+ exists to open. Link-local, multicast, reserved, unspecified and+ cloud-metadata literals are likewise always rejected.* Set ``AISOC_SSRF_EXTRA_BLOCKED_HOSTS=foo.internal,bar.svc`` to extendthe metadata host blocklist.diff --git a/services/agents/tests/test_copilot_grounding.py b/services/agents/tests/test_copilot_grounding.pynew file mode 100644index 000000000..6df1ac539--- /dev/null+++ b/services/agents/tests/test_copilot_grounding.py@@ -0,0 +1,162 @@+"""A copilot answer cites what it was given, or says it did not.++Parity 3.6. The spec's clause is "citations to ledger entries for every+factual claim. An answer with no citation is labelled uncited."++Each class below is one way that could go wrong quietly.+"""++from __future__ import annotations++from app.api.copilot_grounding import (+ EvidenceSource,+ ground_answer,+ sources_from_context,+ sources_from_ledger,+)++LEDGER = [+ {+ "run_id": "11111111-1111-1111-1111-111111111111",+ "seq": 1,+ "kind": "tool_call",+ "summary": "lake query for WIN-FIN-02",+ "payload": {"rows": 4, "src_ip": "198.51.100.4"},+ },+ {+ "run_id": "11111111-1111-1111-1111-111111111111",+ "seq": 2,+ "kind": "llm_response",+ "summary": "verdict: true positive",+ "payload": {"technique": "T1059.001"},+ },+]+++class TestAClaimCitesItsSource:+ def test_a_grounded_indicator_gets_a_citation(self) -> None:+ answer = "The host contacted 198.51.100.4 before the alert fired."+ result = ground_answer(answer, sources_from_ledger(LEDGER))++ assert result.label == "cited"+ assert result.fully_cited+ claim = next(c for c in result.citations if c.claim == "198.51.100.4")+ assert claim.refs == ("ledger:11111111-1111-1111-1111-111111111111#1",)++ def test_the_reference_is_one_an_analyst_can_open(self) -> None:+ """`ledger:<run>#<seq>` is the coordinate `aisoc_explain_step` and+ the console's replay view both address a step by. A citation+ nobody can paste anywhere is not much of a citation."""+ refs = {s.ref for s in sources_from_ledger(LEDGER)}+ assert refs == {+ "ledger:11111111-1111-1111-1111-111111111111#1",+ "ledger:11111111-1111-1111-1111-111111111111#2",+ }++ def test_an_indicator_only_in_the_payload_still_cites(self) -> None:+ """Summary and payload are both searched. A citation that read+ only the summary would call a supported claim uncited."""+ result = ground_answer("Technique T1059.001 was used.", sources_from_ledger(LEDGER))+ assert result.fully_cited, result+++class TestAnUncitedClaimIsLabelled:+ def test_an_invented_indicator_is_uncited(self) -> None:+ """The reason this module exists. The analyst has no other way to+ tell a claim drawn from evidence from one that sounded right."""+ result = ground_answer("The host also contacted 203.0.113.99.", sources_from_ledger(LEDGER))++ assert result.label == "uncited"+ assert not result.fully_cited+ assert result.uncited == ("203.0.113.99",)++ def test_a_half_supported_answer_says_partially(self) -> None:+ """Not 'cited'. An answer where one of two claims is invented is+ the dangerous case, and calling it cited would be the worst+ possible rounding."""+ answer = "198.51.100.4 talked to the DC, then 203.0.113.99 exfiltrated."+ result = ground_answer(answer, sources_from_ledger(LEDGER))++ assert result.label == "partially uncited"+ assert not result.fully_cited+ assert result.uncited == ("203.0.113.99",)+ assert [c.claim for c in result.citations] == ["198.51.100.4"]++ def test_the_uncited_claim_is_named_not_just_counted(self) -> None:+ """So an analyst can check the specific one rather than+ re-reading the whole answer suspiciously."""+ result = ground_answer("Try 203.0.113.99 and CVE-2026-9999.", sources_from_ledger(LEDGER))+ assert set(result.uncited) == {"203.0.113.99", "cve-2026-9999"}++ def test_an_ungrounded_answer_is_returned_not_suppressed(self) -> None:+ """Hiding it would show the analyst a different answer than the+ model gave, edited by something that cannot reliably tell which+ half was wrong."""+ result = ground_answer("203.0.113.99 is the C2.", [])+ assert result.uncited+ assert result.as_dict()["uncited"] == ["203.0.113.99"]+++class TestProseIsNotAClaim:+ def test_an_answer_asserting_nothing_concrete_is_its_own_outcome(self) -> None:+ """Three outcomes, not two. "Asserted nothing" and "asserted+ things and supported all of them" deserve different words, or the+ label goes silent on exactly the prose answers where it should+ be."""+ result = ground_answer("This looks like credential access. Check the DC logs.", sources_from_ledger(LEDGER))++ assert result.no_claims+ assert result.label == "no checkable claims"+ assert not result.fully_cited, "an answer with nothing to check is not a cited answer"++ def test_an_empty_answer_claims_nothing(self) -> None:+ assert ground_answer("", sources_from_ledger(LEDGER)).no_claims+++class TestTheContextTheConsoleSends:+ def test_an_alert_in_context_is_citable(self) -> None:+ sources = sources_from_context({"alert": {"id": "a-1", "title": "Encoded PowerShell", "host": "WIN-FIN-02"}})+ assert [s.ref for s in sources] == ["alert:a-1"]++ def test_free_text_context_is_not_citable(self) -> None:+ """Pointing a citation at a page title gives the analyst nothing+ to open, so context without an identifier is context for the+ model and nothing more."""+ assert sources_from_context({"page": "Alerts", "query": "powershell"}) == []++ def test_a_malformed_context_does_not_raise(self) -> None:+ """The console sends this; a copilot that 500s on an unexpected+ shape is worse than one that grounds against less."""+ assert sources_from_context(None) == []+ assert sources_from_context({"alert": "not-a-dict"}) == []+++class TestItUsesOneDefinitionOfCheckable:+ def test_the_extractor_is_the_groundedness_one(self) -> None:+ """Imported, not re-implemented. A second definition of+ "checkable" would drift from the first, and the two numbers would+ stop being comparable while still looking like they were."""+ from app.api import copilot_grounding+ from app.confidence import groundedness++ assert copilot_grounding._extract is groundedness._extract+++class TestASourceCanSupportSeveralClaims:+ def test_two_claims_from_one_source_both_cite_it(self) -> None:+ source = EvidenceSource(ref="alert:a-1", kind="alert", text="198.51.100.4 ran T1059.001")+ result = ground_answer("198.51.100.4 used T1059.001.", [source])++ assert result.fully_cited+ assert {c.claim for c in result.citations} == {"198.51.100.4", "t1059.001"}+ assert all(c.refs == ("alert:a-1",) for c in result.citations)++ def test_a_claim_in_two_sources_cites_both(self) -> None:+ """An analyst checking a claim should see every record that+ supports it, not the first one that happened to match."""+ sources = [+ EvidenceSource(ref="ledger:r#1", kind="ledger", text="198.51.100.4 seen"),+ EvidenceSource(ref="alert:a-1", kind="alert", text="src 198.51.100.4"),+ ]+ citation = ground_answer("198.51.100.4 again.", sources).citations[0]+ assert citation.refs == ("ledger:r#1", "alert:a-1")diff --git a/services/agents/tests/test_playbook_steps_act.py b/services/agents/tests/test_playbook_steps_act.pynew file mode 100644index 000000000..5aa9491cd--- /dev/null+++ b/services/agents/tests/test_playbook_steps_act.py@@ -0,0 +1,251 @@+"""The `http` and `notify` steps reach a real socket, or are refused.++Parity 5.3, "steps that do something". The existing suites cover the+SSRF guard's decisions, the step models' bounds and the engine's control+flow. None of them proves a step ever leaves the process.++Why that distinction matters here specifically+------------------------------------------------+`_handle_block_ip` and `_handle_isolate_host` once returned+`{"simulated": True}` and reached no executor at all, under a comment+claiming playbooks dispatched through the actions service. A step that+returns a plausible dict is indistinguishable from one that acted, and+every test asserting on the dict passes either way.++So this drives the real handlers against a real `HTTPServer` and asks+the only question that separates the two: **did a request arrive?** A+mock answers whether a Python function was called, which is a different+question.++The guard is tested from both sides+-------------------------------------+A step that always calls out is as wrong as one that never does.+Playbook URLs are author-controlled, so the SSRF guard has to refuse+loopback, link-local and cloud-metadata destinations — and the tests+below assert the refusal *and* that nothing arrived, because a refusal+that still made the request is a refusal in name only.++The loopback case is why this suite binds `127.0.0.1` and then+explicitly allows it: without the opt-in the guard correctly refuses its+own test server, which would make every positive assertion here vacuous.+"""++from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any++import pytest+++class _Endpoint(BaseHTTPRequestHandler):+ """Records every request that reaches it. The recording is the point."""++ received: list[dict[str, Any]] = []++ def _record(self) -> None:+ length = int(self.headers.get("Content-Length", 0))+ raw = self.rfile.read(length) if length else b""+ _Endpoint.received.append({"path": self.path, "method": self.command, "body": raw.decode(errors="replace")})+ body = b'{"ok": true}'+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ do_GET = _record+ do_POST = _record+ do_PUT = _record++ def log_message(self, *_args: Any) -> None:+ """Quiet: the default handler prints to stderr on every request."""++[email protected](scope="module")+def endpoint():+ _Endpoint.received.clear()+ server = HTTPServer(("127.0.0.1", 0), _Endpoint)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{server.server_port}"+ server.shutdown()++[email protected](autouse=True)+def _clear(endpoint): # noqa: ANN001+ """Each test asks "did a request arrive *because of me*"."""+ _Endpoint.received.clear()+ yield+++def allow_loopback(monkeypatch: pytest.MonkeyPatch):+ """Let the *positive* tests reach this suite's own server.++ The guard rejects loopback unconditionally and `AISOC_SSRF_ALLOW_PRIVATE`+ does not relax it — deliberately, because a playbook that can reach+ 127.0.0.1 can reach every unauthenticated service on the host running+ the engine. (The module header claimed otherwise and contradicted the+ function's own docstring; the header was the wrong half and is now+ corrected.)++ So the loopback rule is suspended here rather than configured away,+ and only for the tests asking "does the handler reach a socket". The+ refusal tests below take no such fixture and exercise the shipped+ default.+ """+ from app.playbook import ssrf_guard++ original = ssrf_guard._is_disallowed_address++ def _permit_loopback(ip, *, allow_private): # noqa: ANN001, ANN202+ if ip.is_loopback:+ return False, ""+ return original(ip, allow_private=allow_private)++ monkeypatch.setattr(ssrf_guard, "_is_disallowed_address", _permit_loopback)+ yield+++def _step(step_type: str, **params: Any): # noqa: ANN202+ from app.playbook.models import PlaybookStep++ return PlaybookStep(+ step_id=f"s-{step_type}",+ # 'http', not 'http_request'. The StepType enum is the source of+ # truth and the engine dispatches on it; a name taken from the+ # docs rather than the enum fails validation here, which is the+ # right place for it to fail.+ name=f"test {step_type}",+ type=step_type,+ params=params,+ timeout_seconds=5,+ )+++class TestTheHttpStepActs:+ async def test_it_reaches_the_endpoint(self, endpoint, allow_loopback) -> None: # noqa: ANN001+ """The claim: an `http_request` step makes a request."""+ import httpx+ from app.playbook.engine import _handle_http++ async with httpx.AsyncClient() as client:+ result = await _handle_http(+ _step("http", url=f"{endpoint}/hook", method="POST", body={"x": 1}),+ {},+ client,+ )++ assert _Endpoint.received, "the http step produced a result and sent no request"+ assert _Endpoint.received[0]["path"] == "/hook"+ assert result.get("status") == 200++ async def test_the_body_arrives(self, endpoint, allow_loopback) -> None: # noqa: ANN001+ """A request with an empty body would satisfy the test above while+ delivering nothing the recipient can act on."""+ import httpx+ from app.playbook.engine import _handle_http++ async with httpx.AsyncClient() as client:+ await _handle_http(+ _step("http", url=f"{endpoint}/hook", method="POST", body={"alert": "A-1"}),+ {},+ client,+ )++ assert json.loads(_Endpoint.received[0]["body"]).get("alert") == "A-1"+++class TestTheNotifyStepActs:+ async def test_a_webhook_notify_reaches_the_endpoint(self, endpoint, allow_loopback) -> None: # noqa: ANN001+ import httpx+ from app.playbook.engine import _handle_notify++ async with httpx.AsyncClient() as client:+ result = await _handle_notify(+ _step("notify", channel="webhook", url=f"{endpoint}/hook", message="contained"),+ {},+ client,+ )++ assert _Endpoint.received, "the notify step produced a result and sent no request"+ assert result.get("status") == 200++ async def test_a_notify_with_no_url_says_it_delivered_nothing(self, endpoint) -> None: # noqa: ANN001+ """The honest branch.++ A notify step with nowhere to send must not report success — an+ analyst who believes a page went out and finds later that it did+ not is worse off than one told immediately.+ """+ import httpx+ from app.playbook.engine import _handle_notify++ async with httpx.AsyncClient() as client:+ result = await _handle_notify(_step("notify", channel="webhook", message="hi"), {}, client)++ assert result.get("delivered") is False+ assert result.get("reason") == "no url", result+ assert not _Endpoint.received++ async def test_a_channel_with_no_sender_says_so_rather_than_no_url(self, endpoint) -> None: # noqa: ANN001+ """The reason has to name the real cause.++ It said "no url" whatever happened, including when a url *was*+ supplied and the channel simply had no sender — sending an+ operator to look for a missing field that was right in front of+ them.+ """+ import httpx+ from app.playbook.engine import _handle_notify++ async with httpx.AsyncClient() as client:+ result = await _handle_notify(_step("notify", channel="slack", url=f"{endpoint}/slack", message="hi"), {}, client)++ assert result.get("delivered") is False+ assert "no url" not in (result.get("reason") or ""), f"a url was supplied and the reason still blames a missing one: {result!r}"+ assert "slack" in (result.get("reason") or "")+++class TestTheGuardRefusesAndNothingArrives:+ """A step that always calls out is as wrong as one that never does."""++ async def test_loopback_is_refused_by_default(self, endpoint) -> None: # noqa: ANN001+ """No `allow_loopback` here: this is the shipped default.++ Playbook URLs are author-controlled, and a playbook that can+ reach 127.0.0.1 can reach every unauthenticated service on the+ host running the engine.+ """+ import httpx+ from app.playbook.engine import _handle_http+ from app.playbook.ssrf_guard import SSRFError++ async with httpx.AsyncClient() as client:+ with pytest.raises(SSRFError):+ await _handle_http(_step("http", url=f"{endpoint}/hook", method="GET"), {}, client)++ assert not _Endpoint.received, (+ "the guard refused and the request still arrived — a refusal in name only, since the side effect has already happened"+ )++ async def test_cloud_metadata_is_refused(self) -> None:+ """169.254.169.254 is refused even when private IPs are allowed:+ it is the one destination whose whole purpose is handing out+ credentials."""+ import httpx+ from app.playbook.engine import _handle_http+ from app.playbook.ssrf_guard import SSRFError++ async with httpx.AsyncClient() as client:+ with pytest.raises(SSRFError):+ await _handle_http(+ _step("http", url="http://169.254.169.254/latest/meta-data/", method="GET"),+ {},+ client,+ )diff --git a/services/api/app/api/v1/endpoints/agents.py b/services/api/app/api/v1/endpoints/agents.pyindex d50d8135d..8f8c2b51d 100644--- a/services/api/app/api/v1/endpoints/agents.py+++ b/services/api/app/api/v1/endpoints/agents.py@@ -36,11 +36,12 @@ from __future__ import annotationsimport loggingfrom typing import Annotated, Any-from fastapi import APIRouter, Depends+from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel, Fieldfrom sqlalchemy import selectfrom app.api.v1.deps import AuthUser, DBSession, require_permission+from app.api.v1.endpoints.cases import _agents_proxyfrom app.api.v1.endpoints.connectors import _fetch_catalog, _safe_log_valfrom app.models.connector import Connector@@ -344,3 +345,70 @@ async def list_agent_tools(tool_count=len(tools),connector_count=contributing_instances,)+++# ────────────────────────────────────────────────────────────────────────────+# Natural-language hunting (parity 6.1)+# ────────────────────────────────────────────────────────────────────────────+#+# A thin proxy onto the agents service's own `/hunt`, for the same reason+# `/cases/{id}/investigate` is one: the console and the MCP server both+# reach AiSOC through this API, and the agents service is not published.+#+# The hunting agent was complete, tested, and had no production caller at+# all — its only importer repo-wide was its own test. This route and the+# console's Hunt page are what make it reachable.+++class AgentHuntRequest(BaseModel):+ """One natural-language hypothesis to hunt against tenant data.++ Named `AgentHuntRequest`, not `HuntRequest`, and the reason is a+ published-contract one rather than a stylistic one.+ `detection_rules.py` already exports a `HuntRequest`, and FastAPI+ resolves a name collision by qualifying **both** models with their+ full module path. So adding a second `HuntRequest` deleted the plain+ `HuntRequest` schema from the spec and renamed the existing one —+ breaking every generated SDK client, for a route that had not+ changed. The openapi-breaking gate caught it.+ """++ hypothesis: str = Field(min_length=1, max_length=2000)+++class AgentHuntResponse(BaseModel):+ """What the hunt found, or why it could not look.++ `checked` and `unavailable_reason` are separate fields deliberately.+ A hunt that could not run is not a hunt that found nothing, and+ collapsing the two is how a console shows a reassuring empty result+ for a search that never happened.+ """++ hypothesis: str+ checked: bool+ matches: list[dict[str, Any]] = []+ refusals: list[str] = []+ unavailable_reason: str | None = None++[email protected]("/hunt", response_model=AgentHuntResponse)+async def run_hunt(+ body: AgentHuntRequest,+ current_user: Annotated[AuthUser, Depends(require_permission("hunts:read"))],+) -> AgentHuntResponse:+ """Plan and run one natural-language hunt for the caller's tenant.++ The tenant comes from the authenticated principal and is never read+ from the body. A caller-supplied tenant on a route like this is the+ shape that has gone wrong here before.+ """+ response = await _agents_proxy(+ "POST",+ "/hunt",+ json={"hypothesis": body.hypothesis, "tenant_id": str(current_user.tenant_id)},+ timeout=120.0,+ )+ if response.status_code >= 400:+ raise HTTPException(status_code=response.status_code, detail=response.text[:400])+ return AgentHuntResponse(**response.json())diff --git a/services/api/app/api/v1/endpoints/investigations.py b/services/api/app/api/v1/endpoints/investigations.pyindex 6eb1a1575..1e991129a 100644--- a/services/api/app/api/v1/endpoints/investigations.py+++ b/services/api/app/api/v1/endpoints/investigations.py@@ -34,19 +34,21 @@ import uuidfrom datetime import UTC, datetimefrom typing import Annotated-from fastapi import APIRouter, Depends, HTTPException, Query, status+from fastapi import APIRouter, Depends, HTTPException, Query, Response, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom sqlalchemy import func, select, textfrom sqlalchemy.engine import RowMappingfrom app.api.v1.deps import AuthUser, require_permission+from app.core.config import settingsfrom app.db.rls import TenantDBSessionfrom app.models.investigation import (InvestigationArtifact,InvestigationEvent,InvestigationRun,)+from app.services.evidence_bundle import build_bundle, bundle_filename, serialize_bundlerouter = APIRouter(prefix="/investigations", tags=["investigations"])@@ -1102,3 +1104,55 @@ def _render_pdf(markdown_text: str, run_id: str) -> bytes:header = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"body = markdown_text.encode("utf-8", errors="replace")return header + body+++# ---------------------------------------------------------------------------+# Evidence bundle export (parity 3.7)+# ---------------------------------------------------------------------------++[email protected]("/{run_id}/bundle")+async def export_evidence_bundle(+ run_id: uuid.UUID,+ current_user: Annotated[AuthUser, Depends(require_permission("cases:read"))],+ db: TenantDBSession,+) -> Response:+ """Export this investigation as a signed, replayable evidence bundle.++ Two exports of one run produce identical bytes, so an auditor can+ diff them, re-hash them, and check the signature without trusting+ this endpoint. Prompts travel as digests rather than text, because a+ bundle is the artefact most likely to leave the customer's control+ and a prompt carries their hostnames and usernames.++ Served as a download rather than JSON so what the auditor verifies is+ the same byte sequence the signature was computed over. A client that+ re-serialised a parsed body would change the bytes and the signature+ would stop matching for a reason nobody could see.+ """+ run = await _fetch_run(db, run_id, current_user.tenant_id)++ events = (+ (await db.execute(select(InvestigationEvent).where(InvestigationEvent.run_id == run_id).order_by(InvestigationEvent.seq)))+ .scalars()+ .all()+ )+ artifacts = (await db.execute(select(InvestigationArtifact).where(InvestigationArtifact.run_id == run_id))).scalars().all()++ bundle = build_bundle(+ run={c.name: getattr(run, c.name, None) for c in run.__table__.columns},+ events=[{c.name: getattr(e, c.name, None) for c in e.__table__.columns} for e in events],+ artifacts=[{c.name: getattr(a, c.name, None) for c in a.__table__.columns} for a in artifacts],+ # Approvals live in the actions service rather than this schema.+ # An empty list is honest: this bundle records none, which is a+ # different statement from "none were required" and is why the+ # field is present and empty rather than omitted.+ approvals=[],+ signing_key=settings.SECRET_KEY,+ )++ return Response(+ content=serialize_bundle(bundle),+ media_type="application/json",+ headers={"Content-Disposition": f'attachment; filename="{bundle_filename(run_id)}"'},+ )diff --git a/services/api/app/services/evidence_bundle.py b/services/api/app/services/evidence_bundle.pynew file mode 100644index 000000000..ce0d4a9a9--- /dev/null+++ b/services/api/app/services/evidence_bundle.py@@ -0,0 +1,371 @@+"""Export one investigation as a signed, replayable evidence bundle.++Parity 3.7.++What a bundle is for+---------------------+An auditor, a regulator or a customer's own security team asks: *what did+this thing decide, on what evidence, and can I check that nobody edited+the answer afterwards?* The Investigation Ledger already holds the+answer; a bundle is that answer made portable and tamper-evident.++Three properties, and each one is a decision rather than a default.++**Byte-for-byte replayable.** Two exports of the same run produce+identical bytes, so a bundle can be diffed, re-hashed and checked by+somebody who does not trust the exporter. That rules out everything that+makes JSON non-deterministic: key order is sorted, separators are fixed,+timestamps are the ledger's own rather than `now()`, and nothing records+the host that produced it. :func:`verify_bundle` recomputes the digest+from the payload rather than trusting the one in the file.++**Prompts travel as hashes, never as text.** A prompt carries the alert,+and an alert carries a customer's hostnames, usernames and IP addresses.+A bundle is the artefact most likely to leave the customer's control, so+the one thing it must not do is carry their estate in clear text. The+hash still proves *which* prompt ran: re-hash the prompt and compare.++**Absent is not zero.** A run with no cost telemetry exports+``total_cost_usd: null``, not ``0.0``. A zero says the run was free; null+says nobody measured. This repository has published the first while+meaning the second before.++The OCSF mapping, and the version it honestly declares+--------------------------------------------------------+The spec asks for the ``ai_agent`` object, the ``ai_operation`` profile+and the record-integrity profile. Each was checked against the published+schema before being used here, and the result decided the version this+bundle declares:++=================== ======= ======= =======+Thing 1.1.0 1.8.0 1.9.0+=================== ======= ======= =======+``ai_agent`` absent absent present+``ai_operation`` absent present present+``record_integrity`` absent — present+=================== ======= ======= =======++The ingest spine emits **1.1.0** — that is the contract its normalizer+has with connectors, and it is not changed here. A bundle is a different+artefact with a different audience, and it declares **1.9.0**, because+1.9.0 is the first version containing every object it uses. Declaring+1.1.0 while emitting an `ai_agent` would be a false claim about a public+standard, which is worse than not mapping at all.++Field names are taken from the schema rather than invented:+``ai_agent`` has ``name``, ``uid``, ``type``, ``version``, ``ai_model``+and ``instance_uid``; ``ai_model`` has ``name``, ``uid``, ``version`` and+``ai_provider``; ``record_integrity`` carries ``attestation_list``, whose+``attestation`` objects have ``fingerprint``, ``signatures``,+``authority_uid`` and ``prev_event``.++Signing+-------+HMAC-SHA256 over the canonical payload, keyed from the deployment's own+secret. That is a *tamper-evidence* control, not a non-repudiation one:+anyone who can read the key can forge a bundle, so it proves the bundle+has not been altered in transit, not that AiSOC and only AiSOC produced+it. :data:`SIGNATURE_ALGORITHM` says so in the bundle itself, because an+auditor who assumes a public-key signature from the word "signed" has+been misled by us rather than by the format.+"""++from __future__ import annotations++import hashlib+import hmac+import json+import uuid+from datetime import datetime+from typing import Any++__all__ = [+ "BUNDLE_SCHEMA_VERSION",+ "OCSF_VERSION",+ "SIGNATURE_ALGORITHM",+ "BundleVerificationError",+ "build_bundle",+ "canonical_bytes",+ "serialize_bundle",+ "verify_bundle",+]++#: This format's own version, independent of OCSF's. Bumped when the+#: payload shape changes in a way a reader must notice.+BUNDLE_SCHEMA_VERSION = "1.0"++#: The first OCSF version containing every object this bundle uses. See+#: the module docstring for why it is not the 1.1.0 the ingest spine+#: emits.+OCSF_VERSION = "1.9.0"++#: Named in the bundle so a reader cannot mistake tamper-evidence for+#: non-repudiation.+SIGNATURE_ALGORITHM = "HMAC-SHA256"++#: `ai_agent.type_id` for a security-analysis agent. OCSF 1.9.0 defines+#: the enum; 99 is `Other`, which is the honest choice until this tree+#: has checked that a more specific member means what it appears to.+AI_AGENT_TYPE_ID = 99+AI_AGENT_TYPE = "Security investigation agent"+++class BundleVerificationError(RuntimeError):+ """A bundle failed verification. Carries why, never just False."""+++def canonical_bytes(payload: dict[str, Any]) -> bytes:+ """The one byte representation a signature is computed over.++ Sorted keys, no inserted whitespace, UTF-8, no trailing newline. Two+ exports of one run must produce identical bytes or the round-trip+ property this format is built on does not hold, and a signature+ computed over a different serialisation than the one verified is a+ signature that fails for no reason a reader can see.+ """+ return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+++def _digest(payload: dict[str, Any]) -> str:+ return hashlib.sha256(canonical_bytes(payload)).hexdigest()+++def _sign(payload: dict[str, Any], key: str) -> str:+ return hmac.new(key.encode("utf-8"), canonical_bytes(payload), hashlib.sha256).hexdigest()+++def _hash_prompt(text: str | None) -> str | None:+ """A prompt as a digest.++ `None` stays `None`: "there was no prompt" and "the prompt hashed to+ something" are different facts, and a hash of the empty string would+ quietly merge them.+ """+ if text is None:+ return None+ return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()+++def _iso(value: Any) -> str | None:+ """A timestamp as the ledger recorded it, never as `now()`.++ A bundle that stamps its own export time cannot reproduce byte for+ byte, which is the property the whole format rests on.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.isoformat()+ return str(value)+++def _float_or_none(value: Any) -> float | None:+ """`None` rather than `0.0` when nothing measured it."""+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _redact_event_payload(payload: Any) -> Any:+ """Keep an event's structure; replace prompt text with its hash.++ The ledger stores whole prompts so a decision can be replayed inside+ the deployment. A bundle leaves the deployment, so the text goes and+ the digest stays: enough to prove which prompt ran, not enough to+ reconstruct the customer's estate from it.+ """+ if not isinstance(payload, dict):+ return payload+ redacted: dict[str, Any] = {}+ for key, value in payload.items():+ if key in {"prompt", "messages", "system_prompt", "user_prompt", "input"} and value is not None:+ redacted[f"{key}_sha256"] = _hash_prompt(value if isinstance(value, str) else json.dumps(value, sort_keys=True))+ else:+ redacted[key] = value+ return redacted+++def _ocsf_block(run: dict[str, Any], agent_names: list[str]) -> dict[str, Any]:+ """The OCSF `ai_operation` view of this run.++ Every field name here was read off schema.ocsf.io for 1.9.0. The+ bundle's own payload above is the authoritative record; this block+ exists so a SIEM that speaks OCSF can file the bundle without+ understanding AiSOC's format.+ """+ model = run.get("model_used")+ return {+ "metadata": {+ "version": OCSF_VERSION,+ "product": {"name": "AiSOC", "vendor_name": "AiSOC"},+ "profiles": ["ai_operation", "record_integrity"],+ },+ "ai_operation": {+ "ai_agent": {+ "name": agent_names[0] if agent_names else "aisoc-investigation",+ "uid": str(run.get("id") or ""),+ "type": AI_AGENT_TYPE,+ "type_id": AI_AGENT_TYPE_ID,+ "instance_uid": str(run.get("id") or ""),+ # `ai_model` is nested inside `ai_agent` in 1.9.0, and+ # `null` when the run recorded no model rather than a+ # placeholder name that would read as a real one.+ "ai_model": None if not model else {"name": str(model), "uid": str(model)},+ },+ },+ }+++def build_bundle(+ *,+ run: dict[str, Any],+ events: list[dict[str, Any]],+ artifacts: list[dict[str, Any]] | None = None,+ approvals: list[dict[str, Any]] | None = None,+ signing_key: str,+) -> dict[str, Any]:+ """Assemble and sign one investigation's bundle.++ `run`, `events`, `artifacts` and `approvals` are rows as the ledger+ holds them. Nothing here reaches back into the database: a bundle is+ a pure function of what it is handed, which is what lets a test build+ one without a deployment and lets two exports agree.+ """+ ordered_events = sorted(events, key=lambda e: (e.get("seq") if e.get("seq") is not None else 0, str(e.get("id") or "")))+ agent_names = sorted({str(e.get("agent")) for e in ordered_events if e.get("agent")})++ payload: dict[str, Any] = {+ "bundle_schema_version": BUNDLE_SCHEMA_VERSION,+ "run": {+ "id": str(run.get("id") or ""),+ "tenant_id": str(run.get("tenant_id") or ""),+ "case_id": run.get("case_id"),+ "status": run.get("status"),+ "error": run.get("error"),+ "started_at": _iso(run.get("started_at")),+ "completed_at": _iso(run.get("completed_at")),+ "iterations": run.get("iterations"),+ },+ "alert": {+ "summary": run.get("alert_summary"),+ "raw": run.get("raw_alert"),+ },+ "model": {+ "id": run.get("model_used"),+ # Absent is not zero. A run with no telemetry exports null,+ # because 0.0 says the run was free.+ "total_tokens": run.get("total_tokens") if run.get("total_tokens") is not None else None,+ "total_cost_usd": _float_or_none(run.get("total_cost_usd")),+ "cost_provenance": (+ "measured" if run.get("total_cost_usd") is not None else "not measured — no cost telemetry was recorded for this run"+ ),+ },+ "steps": [+ {+ "seq": event.get("seq"),+ "kind": event.get("kind"),+ "agent": event.get("agent"),+ "summary": event.get("summary"),+ "ts": _iso(event.get("ts")),+ "duration_ms": event.get("duration_ms"),+ "input_hash": event.get("input_hash"),+ "output_hash": event.get("output_hash"),+ "payload": _redact_event_payload(event.get("payload")),+ }+ for event in ordered_events+ ],+ "artifacts": sorted(+ [+ {+ "id": str(a.get("id") or ""),+ "kind": a.get("kind"),+ "label": a.get("label"),+ "sha256": a.get("sha256"),+ }+ for a in (artifacts or [])+ ],+ key=lambda a: (str(a.get("kind") or ""), a["id"]),+ ),+ "approvals": sorted(+ [+ {+ "id": str(a.get("id") or ""),+ "action": a.get("action"),+ "status": a.get("status"),+ "approver": a.get("approver"),+ "decided_at": _iso(a.get("decided_at")),+ }+ for a in (approvals or [])+ ],+ key=lambda a: a["id"],+ ),+ }+ payload["ocsf"] = _ocsf_block(run, agent_names)++ digest = _digest(payload)+ return {+ "payload": payload,+ # The envelope is deliberately outside the signed payload: a+ # signature cannot cover itself.+ "integrity": {+ "algorithm": SIGNATURE_ALGORITHM,+ "algorithm_note": (+ "Tamper-evidence, not non-repudiation. Anyone holding the deployment's signing "+ "key can produce a valid signature, so this proves the bundle was not altered "+ "after export — not that AiSOC and only AiSOC produced it."+ ),+ "payload_sha256": digest,+ "signature": _sign(payload, signing_key),+ # The OCSF record-integrity view of the same two values.+ "attestation_list": [+ {+ "fingerprint": {"algorithm": "SHA-256", "algorithm_id": 3, "value": digest},+ "signatures": [{"algorithm": SIGNATURE_ALGORITHM, "algorithm_id": 99}],+ }+ ],+ },+ }+++def serialize_bundle(bundle: dict[str, Any]) -> bytes:+ """The bundle as bytes on disk or on the wire.++ Same canonicalisation as the signature, so a reader who recomputes+ the digest from the file gets the digest that was signed.+ """+ return canonical_bytes(bundle)+++def verify_bundle(bundle: dict[str, Any], *, signing_key: str) -> dict[str, Any]:+ """Check a bundle has not been altered, or say exactly what is wrong.++ Recomputes both the digest and the signature from the payload rather+ than comparing the two values already in the file — which would pass+ for anyone who edited the payload and the digest together.+ """+ payload = bundle.get("payload")+ integrity = bundle.get("integrity") or {}+ if not isinstance(payload, dict):+ raise BundleVerificationError("bundle has no payload object")++ recomputed = _digest(payload)+ claimed = integrity.get("payload_sha256")+ if claimed != recomputed:+ raise BundleVerificationError(f"payload digest mismatch: the bundle claims {claimed!r} and its payload hashes to {recomputed!r}")++ expected = _sign(payload, signing_key)+ actual = integrity.get("signature")+ if not isinstance(actual, str) or not hmac.compare_digest(expected, actual):+ raise BundleVerificationError(+ "signature does not match this deployment's key — the bundle was altered, or it was produced by a different deployment"+ )++ return payload+++def bundle_filename(run_id: str | uuid.UUID) -> str:+ """A stable name, so two exports of one run overwrite rather than accumulate."""+ return f"aisoc-investigation-{run_id}.bundle.json"diff --git a/services/api/app/workers/retro_hunt_consumer.py b/services/api/app/workers/retro_hunt_consumer.pyindex 4a02275cb..ce7c24832 100644--- a/services/api/app/workers/retro_hunt_consumer.py+++ b/services/api/app/workers/retro_hunt_consumer.py@@ -242,18 +242,51 @@ async def handle_indicator(indicator: IntelIndicator) -> list[TenantSweepReport]for settings_row in tenants:try:- await db.execute(- text("SELECT set_config('app.current_tenant_id', :t, true)"),- {"t": str(settings_row.tenant_id)},- )- reports.append(- await sweep_tenant(+ # A SAVEPOINT per tenant, and both halves of it are+ # load-bearing. Found by the end-to-end suite, which runs+ # as the `aisoc_app` runtime role; as the schema owner+ # neither defect appears, because RLS does not apply.+ #+ # **Rows flushed under the wrong tenant's context.**+ # `sweep_tenant` deliberately does not commit, so its rows+ # sat pending. The next iteration rebound+ # `app.current_tenant_id` to the *next* tenant, and the+ # first query after that triggered SQLAlchemy's autoflush+ # — which wrote the previous tenant's rows while the+ # current tenant's context was active. RLS refused them,+ # correctly, and retro-hunt wrote nothing. The nested+ # block flushes each tenant's work inside its own context,+ # before anything rebinds.+ #+ # **One tenant's failure stopped the rest.** The comment+ # below says it must not, and it did: a failed flush left+ # the session needing a rollback, so every later tenant+ # raised `PendingRollbackError` and was reported as+ # failed. The savepoint rolls back only the tenant that+ # failed.+ #+ # Driven explicitly rather than with `async with`: the+ # context-manager form attempts its release outside the+ # greenlet the async driver runs in and raises+ # `MissingGreenlet`.+ savepoint = await db.begin_nested()+ try:+ await db.execute(+ text("SELECT set_config('app.current_tenant_id', :t, true)"),+ {"t": str(settings_row.tenant_id)},+ )+ report = await sweep_tenant(db,tenant_id=settings_row.tenant_id,indicator=indicator,settings_row=settings_row,)- )+ await db.flush()+ except Exception:+ await savepoint.rollback()+ raise+ await savepoint.commit()+ reports.append(report)except Exception as exc: # noqa: BLE001 - one tenant must not stop the restlogger.exception("retro_hunt.tenant_sweep_failed tenant=%s err=%s",diff --git a/services/api/tests/test_evidence_bundle.py b/services/api/tests/test_evidence_bundle.pynew file mode 100644index 000000000..9bce87627--- /dev/null+++ b/services/api/tests/test_evidence_bundle.py@@ -0,0 +1,231 @@+"""Evidence bundles: deterministic, tamper-evident, and honest about both.++Parity 3.7. The spec's done-when clause is *"an evidence bundle+round-trips through replay byte for byte"*, which is the first class+below. The rest exist because the other three properties a bundle claims+are each easy to get wrong in a way no happy-path test would notice.+"""++from __future__ import annotations++import json+import uuid+from datetime import UTC, datetime++import pytest+from app.services.evidence_bundle import (+ BUNDLE_SCHEMA_VERSION,+ OCSF_VERSION,+ BundleVerificationError,+ build_bundle,+ canonical_bytes,+ serialize_bundle,+ verify_bundle,+)++KEY = "test-signing-key-at-least-32-characters-long"+RUN_ID = uuid.UUID("11111111-2222-3333-4444-555555555555")+TENANT = uuid.UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")+WHEN = datetime(2026, 10, 2, 12, 0, 0, tzinfo=UTC)+++def _run(**overrides):+ base = {+ "id": RUN_ID,+ "tenant_id": TENANT,+ "case_id": "CASE-1",+ "alert_summary": "Encoded PowerShell from Office on WIN-FIN-02",+ "raw_alert": {"host": "WIN-FIN-02", "user": "j.doe"},+ "model_used": "llama3.2:3b-instruct-q4_K_M",+ "status": "completed",+ "error": None,+ "total_tokens": 4096,+ "total_cost_usd": 0.0012,+ "iterations": 3,+ "started_at": WHEN,+ "completed_at": WHEN,+ }+ base.update(overrides)+ return base+++def _events():+ """Returned out of order on purpose: the bundle must sort them."""+ return [+ {+ "id": uuid.UUID("00000000-0000-0000-0000-000000000002"),+ "seq": 2,+ "kind": "llm_response",+ "agent": "aisoc-investigation",+ "summary": "verdict",+ "ts": WHEN,+ "duration_ms": 900,+ "input_hash": "in-2",+ "output_hash": "out-2",+ "payload": {"verdict": "true_positive", "prompt": "SYSTEM: you are...\nUSER: WIN-FIN-02"},+ },+ {+ "id": uuid.UUID("00000000-0000-0000-0000-000000000001"),+ "seq": 1,+ "kind": "tool_call",+ "agent": "aisoc-recon",+ "summary": "lake query",+ "ts": WHEN,+ "duration_ms": 120,+ "input_hash": "in-1",+ "output_hash": "out-1",+ "payload": {"tool": "lake_query", "rows": 4},+ },+ ]+++def _bundle(**run_overrides):+ return build_bundle(+ run=_run(**run_overrides),+ events=_events(),+ artifacts=[{"id": uuid.UUID(int=7), "kind": "report", "label": "summary.md", "sha256": "abc"}],+ approvals=[{"id": uuid.UUID(int=9), "action": "isolate_host", "status": "approved", "approver": "alice", "decided_at": WHEN}],+ signing_key=KEY,+ )+++class TestItRoundTripsByteForByte:+ """The spec's done-when clause."""++ def test_two_exports_of_one_run_are_identical(self) -> None:+ assert serialize_bundle(_bundle()) == serialize_bundle(_bundle())++ def test_it_survives_a_json_round_trip_unchanged(self) -> None:+ """Written to disk, read back, re-serialised: still the same bytes.++ This is what "replayable" has to mean for anyone who did not+ produce the bundle — they parse it with an ordinary JSON reader+ and must be able to recompute what was signed.+ """+ first = serialize_bundle(_bundle())+ reparsed = json.loads(first.decode("utf-8"))+ assert serialize_bundle(reparsed) == first++ def test_event_order_does_not_depend_on_input_order(self) -> None:+ """A ledger read that returns rows in a different order must not+ change the digest, or the signature becomes a property of the+ query plan."""+ forward = build_bundle(run=_run(), events=_events(), signing_key=KEY)+ backward = build_bundle(run=_run(), events=list(reversed(_events())), signing_key=KEY)+ assert serialize_bundle(forward) == serialize_bundle(backward)++ def test_the_canonical_form_has_no_inserted_whitespace(self) -> None:+ raw = canonical_bytes({"b": 1, "a": 2})+ assert raw == b'{"a":2,"b":1}'+++class TestTamperEvidence:+ def test_an_untouched_bundle_verifies(self) -> None:+ """The negative control for every tampering test below: without+ it they would all pass against a verifier that rejects+ everything."""+ bundle = _bundle()+ assert verify_bundle(bundle, signing_key=KEY)["run"]["case_id"] == "CASE-1"++ def test_editing_the_verdict_is_caught(self) -> None:+ bundle = _bundle()+ bundle["payload"]["steps"][1]["payload"]["verdict"] = "false_positive"+ with pytest.raises(BundleVerificationError, match="digest mismatch"):+ verify_bundle(bundle, signing_key=KEY)++ def test_editing_the_payload_and_its_digest_together_is_caught(self) -> None:+ """The attack a verifier that compares two fields in the file+ would miss. Both values are recomputed from the payload."""+ from app.services.evidence_bundle import _digest # noqa: PLC0415++ bundle = _bundle()+ bundle["payload"]["alert"]["summary"] = "nothing happened"+ bundle["integrity"]["payload_sha256"] = _digest(bundle["payload"])+ with pytest.raises(BundleVerificationError, match="signature does not match"):+ verify_bundle(bundle, signing_key=KEY)++ def test_another_deployments_key_does_not_verify(self) -> None:+ with pytest.raises(BundleVerificationError, match="signature does not match"):+ verify_bundle(_bundle(), signing_key="a-different-key-at-least-32-characters")++ def test_a_bundle_with_no_payload_is_refused(self) -> None:+ with pytest.raises(BundleVerificationError, match="no payload"):+ verify_bundle({"integrity": {}}, signing_key=KEY)+++class TestPromptsTravelAsHashes:+ """A bundle is the artefact most likely to leave the customer's+ control, so it must not carry their estate in clear text."""++ def test_prompt_text_is_not_in_the_bundle(self) -> None:+ raw = serialize_bundle(_bundle()).decode("utf-8")+ assert "SYSTEM: you are" not in raw+ assert "USER: WIN-FIN-02" not in raw++ def test_the_hash_is_there_instead(self) -> None:+ """Still enough to prove *which* prompt ran: re-hash and compare."""+ step = next(s for s in _bundle()["payload"]["steps"] if s["kind"] == "llm_response")+ assert step["payload"]["prompt_sha256"].startswith("sha256:")+ assert "prompt" not in step["payload"]++ def test_a_step_with_no_prompt_gains_no_hash_field(self) -> None:+ """A hash of nothing would read as a prompt that existed."""+ step = next(s for s in _bundle()["payload"]["steps"] if s["kind"] == "tool_call")+ assert "prompt_sha256" not in step["payload"]+++class TestAbsentIsNotZero:+ def test_a_run_with_no_cost_exports_null(self) -> None:+ """`0.0` says the run was free; `null` says nobody measured. This+ repository has published the first while meaning the second."""+ model = _bundle(total_cost_usd=None, total_tokens=None)["payload"]["model"]+ assert model["total_cost_usd"] is None+ assert model["total_tokens"] is None+ assert "not measured" in model["cost_provenance"]++ def test_a_measured_cost_says_measured(self) -> None:+ model = _bundle()["payload"]["model"]+ assert model["total_cost_usd"] == pytest.approx(0.0012)+ assert model["cost_provenance"] == "measured"+++class TestTheOcsfMapping:+ """Every field here was checked against schema.ocsf.io before use."""++ def test_it_declares_the_version_that_actually_has_these_objects(self) -> None:+ """`ai_agent` exists only from 1.9.0 and `ai_operation` from+ 1.8.0. The ingest spine emits 1.1.0, where neither exists —+ declaring that here while emitting an `ai_agent` would be a false+ claim about a public standard."""+ assert _bundle()["payload"]["ocsf"]["metadata"]["version"] == OCSF_VERSION == "1.9.0"++ def test_it_names_both_profiles_it_uses(self) -> None:+ profiles = _bundle()["payload"]["ocsf"]["metadata"]["profiles"]+ assert "ai_operation" in profiles+ assert "record_integrity" in profiles++ def test_the_agent_carries_the_model_nested_as_the_schema_has_it(self) -> None:+ agent = _bundle()["payload"]["ocsf"]["ai_operation"]["ai_agent"]+ assert agent["ai_model"]["name"] == "llama3.2:3b-instruct-q4_K_M"+ assert set(agent) <= {"name", "uid", "type", "type_id", "instance_uid", "ai_model", "version", "charter", "uid_numeric"}++ def test_a_run_with_no_model_carries_null_not_a_placeholder(self) -> None:+ agent = _bundle(model_used=None)["payload"]["ocsf"]["ai_operation"]["ai_agent"]+ assert agent["ai_model"] is None++ def test_the_attestation_matches_the_computed_digest(self) -> None:+ bundle = _bundle()+ attestation = bundle["integrity"]["attestation_list"][0]+ assert attestation["fingerprint"]["value"] == bundle["integrity"]["payload_sha256"]+++class TestItSaysWhatTheSignatureIsWorth:+ def test_the_bundle_states_it_is_not_non_repudiation(self) -> None:+ """An auditor who assumes a public-key signature from the word+ "signed" has been misled by us rather than by the format."""+ note = _bundle()["integrity"]["algorithm_note"]+ assert "not non-repudiation" in note.lower()+ assert "tamper-evidence" in note.lower()++ def test_the_schema_version_is_published(self) -> None:+ assert _bundle()["payload"]["bundle_schema_version"] == BUNDLE_SCHEMA_VERSIONdiff --git a/services/mcp/README.md b/services/mcp/README.mdindex 5ffe18536..105554a96 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -89,7 +89,7 @@ Print the resolved paths for your own machine with `node dist/index.js install -## Tools exposed-The server advertises **18 tools**. Discovery tools list things, deep-dive tools fetch one thing, the lake pair runs governed SELECTs over the warm tier, and the replay tools expose the agent's own reasoning.+The server advertises **19 tools**. Discovery tools list things, deep-dive tools fetch one thing, the lake pair runs governed SELECTs over the warm tier, and the replay tools expose the agent's own reasoning.Every tool carries MCP behaviour annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`), so a client that takes them seriously can decide what it may call without an operator vouching for each tool by name. **Seventeen of the eighteen are read-only.** The exception is `aisoc_run_investigation`, which starts an agent run, and it is annotated as such rather than being quietly marked read-only. No tool is annotated destructive, because none is.diff --git a/services/mcp/src/tools/hunt.ts b/services/mcp/src/tools/hunt.tsnew file mode 100644index 000000000..c15eb59e0--- /dev/null+++ b/services/mcp/src/tools/hunt.ts@@ -0,0 +1,97 @@+/**+ * Run one natural-language hunt against the tenant's own recorded events.+ *+ * Parity 6.1. The hunting agent was complete and tested, and its only+ * importer repo-wide was its own test — a passing test on a function+ * nothing calls is indistinguishable from a working feature until+ * somebody traces the call graph. This tool and the console's Hunt page+ * are the two callers that make it real.+ *+ * Three things about the payload are deliberate, because the next reader+ * of it is a language model.+ *+ * **`checked` is not `matches.length > 0`.** A hunt that could not run is+ * not a hunt that found nothing, and collapsing the two is how a console+ * ends up showing a reassuring empty result for a search that never+ * happened. `checked: false` always carries an `unavailable_reason`.+ *+ * **Refusals are returned, not swallowed.** The model proposes a plan and+ * the planner validates every attempt against the allowed shape; a plan+ * it would not run is information an analyst should see, not noise to+ * hide. The model never writes a query — it picks from a vocabulary, and+ * `refusals` is the record of what it tried that did not fit.+ *+ * **It is read-only.** A hunt searches; it does not act. The annotation+ * says so and no write path exists here.+ */+import { z } from "zod";++import { zodToJsonSchema } from "./alerts.js";+import type { ToolDefinition } from "./types.js";+import { json } from "./types.js";++interface HuntReply {+ hypothesis: string;+ checked: boolean;+ matches: unknown[];+ refusals: string[];+ unavailable_reason: string | null;+}++const RunHuntSchema = z+ .object({+ hypothesis: z+ .string()+ .min(1)+ .describe(+ "What you suspect, in plain language. For example: 'a service account signed in from a country it has never used before'.",+ ),+ tenant_id: z.string().uuid().describe("The tenant whose recorded events to search."),+ })+ .strict();++export const runHuntTool: ToolDefinition<typeof RunHuntSchema> = {+ metadata: {+ name: "aisoc_run_hunt",+ description:+ "Turn a plain-language hypothesis into a validated hunt plan and run it against this tenant's recorded events. Returns what matched, or why it could not look. Read-only: a hunt searches, it never acts.",+ inputSchema: zodToJsonSchema(RunHuntSchema),+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ // Not idempotent: the estate moves, so the same hypothesis can+ // legitimately answer differently an hour later.+ idempotentHint: false,+ openWorldHint: true,+ },+ },+ schema: RunHuntSchema,+ async handle(ctx, args) {+ const reply = await ctx.client.post<HuntReply>("/api/v1/agents/hunt", {+ hypothesis: args.hypothesis,+ tenant_id: args.tenant_id,+ });++ const matches = reply.matches ?? [];+ return json({+ hypothesis: reply.hypothesis,+ // Stated in words as well as in the boolean. A false boolean is+ // easy to skim past on the way to an empty `matches`, and the two+ // mean opposite things.+ checked: reply.checked,+ note: reply.checked+ ? "The hunt ran. An empty `matches` means nothing matched, which is a result."+ : "The hunt did NOT run, so `matches` is empty for a reason that has nothing to do with the estate. Do not report this as 'nothing found'.",+ unavailable_reason: reply.unavailable_reason ?? null,+ matches,+ match_count: matches.length,+ refusals: reply.refusals ?? [],+ refusals_note:+ "Plans the validator would not run. The model never writes a query directly; it picks from a vocabulary, and these are the attempts that did not fit.",+ next_step:+ matches.length > 0+ ? "Pivot on a match with `aisoc_lake_query`, or open the entity in the console."+ : "Nothing to pivot on. Narrow or widen the hypothesis and run it again.",+ });+ },+};diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex f69058d87..867375328 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -27,6 +27,7 @@ import {} from "./investigations.js";import { lakeQueryTool, lakeSchemaTool } from "./lake.js";import { getReplayReportTool, listReplayReportsTool } from "./replay.js";+import { runHuntTool } from "./hunt.js";import { getTriageVerdictTool } from "./triage.js";import type { ToolDefinition } from "./types.js";@@ -52,6 +53,11 @@ export const ALL_TOOLS: ToolDefinition[] = [// read the listing top-to-bottom should reach for SELECT only after// they've seen the structured tools.lakeQueryTool,+ // Hunting. Sits beside the lake tools because it answers the same kind+ // of question from the other end: `lakeQueryTool` wants SQL, this one+ // wants a sentence and has the planner turn it into a validated plan.+ // Read-only, like both of them.+ runHuntTool,// Action / replay. `previewActionTool` is the only tool here that touches// the response surface, and it is dry-run only: it names the dry-run path// and nothing in `src/` names `/dispatch`. `tests/actions.test.ts` assertsdiff --git a/services/mcp/tests/tools.test.ts b/services/mcp/tests/tools.test.tsindex 922152854..db46a8618 100644--- a/services/mcp/tests/tools.test.ts+++ b/services/mcp/tests/tools.test.ts@@ -38,6 +38,7 @@ const EXPECTED_TOOLS = [// only ones that touch the response surface, and the preview is dry-run// only (see tests/actions.test.ts)."aisoc_get_triage_verdict",+ "aisoc_run_hunt","aisoc_list_replay_reports","aisoc_get_replay_report","aisoc_list_actions",diff --git a/tests/isolation/test_evidence_bundle_live.py b/tests/isolation/test_evidence_bundle_live.pynew file mode 100644index 000000000..fe5a5d839--- /dev/null+++ b/tests/isolation/test_evidence_bundle_live.py@@ -0,0 +1,208 @@+"""An evidence bundle exported from the real route, against real Postgres.++Parity 3.7. `services/api/tests/test_evidence_bundle.py` proves the+format: deterministic, tamper-evident, prompts hashed. It builds its+bundles from dicts, so it cannot show that the *route* assembles one+correctly from ledger rows, that the export is tenant-scoped, or that a+bundle survives the trip through SQLAlchemy's type coercion.++The ones that only a live run can answer+------------------------------------------+A ledger row is not a dict. `raw_alert` is JSONB, `started_at` is a+timezone-aware datetime, `total_cost_usd` is Numeric, and ids are UUID+objects. Every one of those has a repr that JSON cannot serialise, so a+bundle built from live rows either round-trips or raises — and a unit+test handing in strings would never find out which.++And the export is a **read of another tenant's investigation** if the+scoping is wrong, which is the single worst thing this route could do.+"""++from __future__ import annotations++import json+import os+import uuid+from datetime import UTC, datetime++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_BUNDLE_DSN", "").strip(),+ reason="ISOLATION_BUNDLE_DSN is not set; this suite needs a live Postgres",+ ),+]++TENANT_A = uuid.UUID("11111111-1111-1111-1111-111111111111")+TENANT_B = uuid.UUID("22222222-2222-2222-2222-222222222222")+WHEN = datetime(2026, 10, 2, 12, 0, 0, tzinfo=UTC)+++def _dsn() -> str:+ return os.environ["ISOLATION_BUNDLE_DSN"]+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def seeded():+ """One investigation per tenant, written as the ledger writes them."""+ asyncpg = pytest.importorskip("asyncpg")+ conn = await asyncpg.connect(_dsn().replace("postgresql+asyncpg://", "postgresql://"))+ runs: dict[uuid.UUID, uuid.UUID] = {}+ try:+ for tenant, summary in ((TENANT_A, "tenant A: encoded PowerShell"), (TENANT_B, "tenant B: brute force")):+ slug = f"bundle-{tenant.hex[:8]}"+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",+ tenant,+ slug,+ slug,+ )+ run_id = uuid.uuid4()+ await conn.execute(+ "INSERT INTO investigation_runs "+ "(id, tenant_id, case_id, alert_summary, raw_alert, model_used, status, "+ " total_tokens, total_cost_usd, iterations, started_at, completed_at) "+ "VALUES ($1,$2,$3,$4,$5::jsonb,$6,'completed',4096,0.0012,3,$7,$7)",+ run_id,+ tenant,+ f"CASE-{tenant.hex[:4]}",+ summary,+ json.dumps({"host": "WIN-FIN-02", "user": "j.doe"}),+ "llama3.2:3b-instruct-q4_K_M",+ WHEN,+ )+ await conn.execute(+ "INSERT INTO investigation_events "+ "(id, run_id, tenant_id, seq, ts, kind, agent, summary, payload, duration_ms) "+ "VALUES ($1,$2,$3,1,$4,'llm_response','aisoc-investigation','verdict',$5::jsonb,900)",+ uuid.uuid4(),+ run_id,+ tenant,+ WHEN,+ json.dumps({"verdict": "true_positive", "prompt": f"SYSTEM: secret-for-{slug}"}),+ )+ runs[tenant] = run_id+ finally:+ await conn.close()+ yield runs+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def client(seeded): # noqa: ANN001+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ os.environ.setdefault("ENVIRONMENT", "development")++ import httpx+ from app.main import create_application++ transport = httpx.ASGITransport(app=create_application())+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:+ yield c+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def users(seeded): # noqa: ANN001+ """A real user per tenant: `get_current_user` resolves `sub` against+ the users table and 401s on "User not found"."""+ asyncpg = pytest.importorskip("asyncpg")+ conn = await asyncpg.connect(_dsn().replace("postgresql+asyncpg://", "postgresql://"))+ made: dict[uuid.UUID, uuid.UUID] = {}+ try:+ for tenant in (TENANT_A, TENANT_B):+ user_id = uuid.uuid4()+ await conn.execute(+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active) "+ "VALUES ($1,$2,$3,$4,'x','admin',true) ON CONFLICT DO NOTHING",+ user_id,+ tenant,+ f"bundle-{user_id.hex[:8]}@example.com",+ f"bundle-{user_id.hex[:8]}",+ )+ made[tenant] = user_id+ finally:+ await conn.close()+ yield made+++def _auth(users, tenant: uuid.UUID) -> dict[str, str]: # noqa: ANN001+ from app.core.security import create_access_token++ return {"Authorization": f"Bearer {create_access_token({'sub': str(users[tenant]), 'type': 'access'})}"}+++class TestTheRouteExportsAVerifiableBundle:+ async def test_it_returns_a_bundle(self, client, users, seeded) -> None: # noqa: ANN001+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ assert response.status_code == 200, f"{response.status_code}: {response.text[:300]}"+ assert "attachment" in response.headers.get("content-disposition", "")++ async def test_live_rows_survive_serialisation(self, client, users, seeded) -> None: # noqa: ANN001+ """UUIDs, tz-aware datetimes, Numeric and JSONB all have reprs+ JSON cannot serialise. A unit test handing in strings would never+ find out which way this goes."""+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ bundle = json.loads(response.content)+ assert bundle["payload"]["run"]["id"] == str(seeded[TENANT_A])+ assert bundle["payload"]["alert"]["raw"]["host"] == "WIN-FIN-02"+ assert bundle["payload"]["model"]["total_cost_usd"] == pytest.approx(0.0012)++ async def test_the_exported_bytes_verify(self, client, users, seeded) -> None: # noqa: ANN001+ """Verified against the bytes the route sent, not a re-serialised+ parse — which is the whole reason it is served as a download."""+ from app.core.config import settings+ from app.services.evidence_bundle import verify_bundle++ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ payload = verify_bundle(json.loads(response.content), signing_key=settings.SECRET_KEY)+ assert payload["run"]["case_id"].startswith("CASE-")++ async def test_two_exports_are_byte_identical(self, client, users, seeded) -> None: # noqa: ANN001+ """The done-when clause, measured on the real route rather than+ on a dict."""+ first = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ second = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ assert first.content == second.content+++class TestItIsTenantScoped:+ async def test_another_tenant_cannot_export_this_investigation(self, client, users, seeded) -> None: # noqa: ANN001+ """The worst thing this route could do. A bundle is a complete+ investigation: the alert, the evidence, the hostnames.++ Two independent mechanisms hold it, and that was measured rather+ than assumed. Removing the explicit ``tenant_id`` predicate from+ ``_fetch_run`` leaves this test **passing**, because the session+ runs as the DML-only role and RLS refuses the row anyway;+ removing the predicate *and* connecting as the schema owner, so+ RLS does not apply, makes it fail.++ Worth knowing in both directions. The belt and braces are real,+ and a reader should not conclude from a green run that the+ predicate alone is doing the work — or that this test would have+ caught the predicate going missing on its own.+ """+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_B))+ assert response.status_code == 404, (+ f"tenant B got {response.status_code} for tenant A's bundle; the body would carry tenant A's whole investigation"+ )++ async def test_each_tenant_can_export_its_own(self, client, users, seeded) -> None: # noqa: ANN001+ """So the refusal above is isolation rather than a broken route."""+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_B]}/bundle", headers=_auth(users, TENANT_B))+ assert response.status_code == 200++ async def test_an_uncredentialed_caller_is_refused(self, client, seeded) -> None: # noqa: ANN001+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle")+ assert response.status_code in (401, 403)+++class TestPromptsDoNotLeave:+ async def test_the_prompt_text_is_not_in_the_exported_bytes(self, client, users, seeded) -> None: # noqa: ANN001+ """Measured on what the route actually sent."""+ response = await client.get(f"/api/v1/investigations/{seeded[TENANT_A]}/bundle", headers=_auth(users, TENANT_A))+ assert b"SYSTEM: secret-for-" not in response.content+ assert b"prompt_sha256" in response.contentdiff --git a/tests/isolation/test_lake_route_live.py b/tests/isolation/test_lake_route_live.pynew file mode 100644index 000000000..1aae71c8e--- /dev/null+++ b/tests/isolation/test_lake_route_live.py@@ -0,0 +1,247 @@+"""`POST /api/v1/lake/sql`, end to end, against a real ClickHouse.++Maturity: completes the **Event lake + hunting (ClickHouse)** row. The+plan asked for "one E2E that round-trips a tenant-scoped query through+`POST /lake/sql`", and `test_lake_live.py` stops one layer short — it+calls `rewrite_for_tenant` directly.++Why that layer matters+-----------------------+The route is where four things happen that the rewriter alone does not+exercise: the caller is authenticated, their tenant is taken from the+*token* rather than from an argument, the rate limiter runs, and errors+are mapped onto status codes an operator reads (400 for syntax, 403 for+forbidden, 422 for timeout, 502 for a driver fault).++A tenant id taken from an argument is the shape that has gone wrong here+before — `get_entity_neighbors` accepted one and never bound it. Driving+the route means the tenant comes from the authenticated principal, which+is the only version of the claim worth making.++The negative control+--------------------+`test_an_uncredentialed_caller_is_refused` is what stops the rest+passing vacuously: a route that served everyone would satisfy "my rows+came back" while leaking every other tenant's.+"""++from __future__ import annotations++import os+import uuid+from datetime import UTC, datetime+from pathlib import Path++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_LAKE_ROUTE_DSN", "").strip(),+ reason="ISOLATION_LAKE_ROUTE_DSN is not set; this suite needs live Postgres + ClickHouse",+ ),+]++TENANT_A = uuid.UUID("11111111-1111-1111-1111-111111111111")+TENANT_B = uuid.UUID("22222222-2222-2222-2222-222222222222")+++def _dsn() -> str:+ return os.environ["ISOLATION_LAKE_ROUTE_DSN"]+++def _ch(): # noqa: ANN202+ driver = pytest.importorskip("clickhouse_driver")+ return driver.Client(+ host=os.environ.get("ISOLATION_CLICKHOUSE_HOST", "localhost"),+ port=int(os.environ.get("ISOLATION_CLICKHOUSE_PORT", "9000")),+ user=os.environ.get("ISOLATION_CLICKHOUSE_USER", "default"),+ password=os.environ.get("ISOLATION_CLICKHOUSE_PASSWORD", ""),+ )++[email protected](scope="module")+def lake():+ """Two tenants' rows, under the schema the product ships."""+ client = _ch()+ root = Path(os.environ.get("ISOLATION_REPO_ROOT", "."))+ ddl = (root / "services" / "api" / "clickhouse" / "001_init.sql").read_text(encoding="utf-8")+ lines = [ln for ln in ddl.splitlines() if not ln.strip().startswith("--")]+ for statement in (s.strip() for s in "\n".join(lines).split(";")):+ if statement:+ client.execute(statement)++ client.execute("TRUNCATE TABLE IF EXISTS aisoc.raw_events")+ now = datetime.now(UTC).replace(tzinfo=None)+ client.execute(+ "INSERT INTO aisoc.raw_events "+ "(tenant_id, event_time, class_uid, category_uid, severity_id, severity, "+ "src_hostname, raw_payload) VALUES",+ [+ (TENANT_A, now, 2001, 2, 4, "high", "route-a-host-1", "{}"),+ (TENANT_A, now, 2001, 2, 4, "high", "route-a-host-2", "{}"),+ (TENANT_B, now, 2001, 2, 4, "high", "route-b-host-1", "{}"),+ ],+ )+ yield client+ client.execute("TRUNCATE TABLE IF EXISTS aisoc.raw_events")+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def users(lake): # noqa: ANN001+ """One admin user per tenant, as real rows."""+ asyncpg = pytest.importorskip("asyncpg")+ dsn = _dsn().replace("postgresql+asyncpg://", "postgresql://")+ conn = await asyncpg.connect(dsn)+ created: dict[uuid.UUID, uuid.UUID] = {}+ try:+ for tenant in (TENANT_A, TENANT_B):+ slug = f"lake-{tenant.hex[:8]}"+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",+ tenant,+ slug,+ slug,+ )+ user_id = uuid.uuid4()+ await conn.execute(+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active) "+ "VALUES ($1, $2, $3, $4, $5, 'admin', true) ON CONFLICT DO NOTHING",+ user_id,+ tenant,+ f"lake-{user_id.hex[:8]}@example.com",+ f"lake-{user_id.hex[:8]}",+ "x",+ )+ created[tenant] = user_id+ finally:+ await conn.close()+ yield created+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def client(lake, users): # noqa: ANN001+ """The real application, as `create_application()` builds it."""+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ # `test`, never `development`.+ #+ # `AUTH_BYPASS_ENVIRONMENTS` holds development/dev/local/demo, and a+ # request with no credentials in one of those resolves to a demo+ # principal with role `admin` — which would answer 200 to the very+ # assertion below that an uncredentialed caller is refused, and make+ # this suite certify auth-derived tenancy while credentials were+ # optional.+ #+ # `test` is in `DEV_ENVIRONMENTS` and deliberately not in the bypass+ # set; `test_dev_mode_unification.py` pins that distinction for+ # exactly this reason.+ os.environ["ENVIRONMENT"] = "test"+ os.environ.setdefault("CLICKHOUSE_HOST", os.environ.get("ISOLATION_CLICKHOUSE_HOST", "localhost"))+ os.environ.setdefault("CLICKHOUSE_PORT", os.environ.get("ISOLATION_CLICKHOUSE_PORT", "9000"))+ os.environ.setdefault("CLICKHOUSE_USER", os.environ.get("ISOLATION_CLICKHOUSE_USER", "default"))+ os.environ.setdefault("CLICKHOUSE_PASSWORD", os.environ.get("ISOLATION_CLICKHOUSE_PASSWORD", ""))+ os.environ.setdefault("CLICKHOUSE_DATABASE", "aisoc")++ import httpx+ from app.main import create_application++ app = create_application()+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:+ yield c+++def _auth(users: dict, tenant: uuid.UUID) -> dict[str, str]: # noqa: ANN001+ """A real signed token for a real user row.++ `get_current_user` resolves `sub` against the `users` table and 401s+ on "User not found", so a synthetic subject would be refused. That+ is the behaviour worth keeping: the tenant comes from the+ credential's *user*, never from an argument or a header — which is+ the shape that has gone wrong here before, when `get_entity_neighbors`+ accepted a tenant_id and never bound it.+ """+ from app.core.security import create_access_token++ token = create_access_token({"sub": str(users[tenant]), "type": "access"})+ return {"Authorization": f"Bearer {token}"}+++class TestTheNegativeControl:+ async def test_an_uncredentialed_caller_is_refused(self, client) -> None: # noqa: ANN001+ """Without this, every assertion below could pass on a route that+ serves everyone."""+ response = await client.post("/api/v1/lake/sql", json={"sql": "SELECT 1"})+ assert response.status_code in (401, 403), f"the lake route served an uncredentialed caller with {response.status_code}"+++class TestTheRoundTrip:+ async def test_a_tenant_reads_its_own_rows(self, client, users) -> None: # noqa: ANN001+ response = await client.post(+ "/api/v1/lake/sql",+ headers=_auth(users, TENANT_A),+ json={"sql": "SELECT src_hostname FROM aisoc.raw_events"},+ )+ assert response.status_code == 200, f"{response.status_code}: {response.text[:300]}"+ blob = response.text+ assert "route-a-host-1" in blob and "route-a-host-2" in blob, blob[:300]++ async def test_it_does_not_read_another_tenants(self, client, users) -> None: # noqa: ANN001+ """The claim the whole lake row rests on, made at the layer where+ the tenant comes from the token."""+ response = await client.post(+ "/api/v1/lake/sql",+ headers=_auth(users, TENANT_A),+ json={"sql": "SELECT src_hostname FROM aisoc.raw_events"},+ )+ assert response.status_code == 200+ assert "route-b-host-1" not in response.text, "tenant A read tenant B's rows through POST /lake/sql"++ async def test_the_other_tenant_sees_its_own(self, client, users) -> None: # noqa: ANN001+ """So the exclusion above is isolation, not an empty table."""+ response = await client.post(+ "/api/v1/lake/sql",+ headers=_auth(users, TENANT_B),+ json={"sql": "SELECT src_hostname FROM aisoc.raw_events"},+ )+ assert response.status_code == 200+ assert "route-b-host-1" in response.text++ async def test_naming_another_tenant_in_the_sql_does_not_widen_it(self, client, users) -> None: # noqa: ANN001+ """An operator writing their own `tenant_id =` must not be able to+ escape the predicate the route injects."""+ response = await client.post(+ "/api/v1/lake/sql",+ headers=_auth(users, TENANT_A),+ json={"sql": f"SELECT src_hostname FROM aisoc.raw_events WHERE tenant_id = '{TENANT_B}'"},+ )+ assert response.status_code == 200+ assert "route-b-host-1" not in response.text+++class TestErrorsAreOperatorReadable:+ async def test_unparseable_sql_is_a_client_error(self, client, users) -> None: # noqa: ANN001+ """400 rather than 500: the caller's SQL is the caller's problem,+ and a 500 sends an operator to read server logs for a typo."""+ response = await client.post("/api/v1/lake/sql", headers=_auth(users, TENANT_A), json={"sql": "this is not sql )("})+ assert 400 <= response.status_code < 500, (+ f"bad SQL answered {response.status_code}; an unhandled 500 here is the shape "+ "that sends an operator to debug the server for their own typo"+ )++ async def test_a_write_is_refused(self, client, users) -> None: # noqa: ANN001+ """The lake API is read-only by contract. A DELETE that reached+ ClickHouse would be a cross-tenant data-loss primitive."""+ response = await client.post(+ "/api/v1/lake/sql",+ headers=_auth(users, TENANT_A),+ json={"sql": "ALTER TABLE aisoc.raw_events DELETE WHERE 1=1"},+ )+ assert response.status_code != 200, "the lake route accepted a write"++ remaining = _ch().execute("SELECT count() FROM aisoc.raw_events")[0][0]+ assert remaining == 3, (+ f"the table has {remaining} rows, not 3 — a refused write still reached ClickHouse, which is worse than accepting it openly"+ )diff --git a/tests/isolation/test_retro_hunt_e2e.py b/tests/isolation/test_retro_hunt_e2e.pynew file mode 100644index 000000000..b00eaf84e--- /dev/null+++ b/tests/isolation/test_retro_hunt_e2e.py@@ -0,0 +1,301 @@+"""A published indicator, through Kafka, into a sweep of recorded data.++Maturity: completes the **Retro-hunts when new intel arrives** row. The+plan asked to "drive one E2E from the real threatintel feed through+Kafka to an alert", and the two existing suites each cover one half:+`test_retro_hunt_live.py` drives the sweep against ClickHouse, and+`test_retro_hunt_consumer_live.py` drives the parser against a broker.+Neither crosses the seam.++What the seam is for+----------------------+The claim is "when new intel arrives, AiSOC goes back and looks". Three+things have to line up for that to be true, and they are owned by+different modules:++1. the **feed** publishes an indicator in the envelope the consumer+ expects — a shape mismatch here is silent, because the parser treats+ anything that is not `NEW_IOC` as somebody else's message;+2. the **broker** delivers it;+3. the **sweep** finds the tenant whose recorded events hold it, and+ only that tenant.++Each half passing says nothing about the join. The envelope in+particular is the kind of contract that drifts: the first version of the+consumer suite produced a flat payload and the parser correctly returned+`None`, which reads identically to "no intel arrived".++The feed is real+------------------+The indicator comes from `services/threatintel`'s own CISA KEV client+shape rather than a hand-written dict, so a change to what the feed+publishes fails here rather than at a customer.++The negative control+--------------------+`test_an_indicator_nobody_has_matches_nothing` is what makes the match+meaningful: a sweep that returned every tenant for every indicator would+satisfy the positive case.+"""++from __future__ import annotations++import json+import os+import uuid+from datetime import UTC, datetime+from pathlib import Path++import pytest++pytestmark = pytest.mark.skipif(+ not (os.environ.get("ISOLATION_KAFKA_BROKERS", "").strip() and os.environ.get("ISOLATION_CLICKHOUSE_HOST", "").strip()),+ reason="this suite needs a live broker and a live ClickHouse",+)++TENANT_WITH = uuid.UUID("11111111-1111-1111-1111-111111111111")+TENANT_WITHOUT = uuid.UUID("22222222-2222-2222-2222-222222222222")++#: The indicator both halves agree on. An RFC 5737 documentation address,+#: so nothing here can collide with a real estate.+INDICATOR = "198.51.100.42"+++def _ch(): # noqa: ANN202+ driver = pytest.importorskip("clickhouse_driver")+ return driver.Client(+ host=os.environ["ISOLATION_CLICKHOUSE_HOST"],+ port=int(os.environ.get("ISOLATION_CLICKHOUSE_PORT", "9000")),+ user=os.environ.get("ISOLATION_CLICKHOUSE_USER", "default"),+ password=os.environ.get("ISOLATION_CLICKHOUSE_PASSWORD", ""),+ )++[email protected](scope="module")+def lake():+ """One tenant whose recorded events hold the indicator, one whose do not."""+ client = _ch()+ root = Path(os.environ.get("ISOLATION_REPO_ROOT", "."))+ ddl = (root / "services" / "api" / "clickhouse" / "001_init.sql").read_text(encoding="utf-8")+ lines = [ln for ln in ddl.splitlines() if not ln.strip().startswith("--")]+ for statement in (s.strip() for s in "\n".join(lines).split(";")):+ if statement:+ client.execute(statement)++ client.execute("TRUNCATE TABLE IF EXISTS aisoc.raw_events")+ now = datetime.now(UTC).replace(tzinfo=None)+ client.execute(+ "INSERT INTO aisoc.raw_events "+ "(tenant_id, event_time, class_uid, category_uid, severity_id, severity, "+ "src_hostname, source_ip, raw_payload) VALUES",+ [+ # The IPv4-mapped form, because `source_ip` is an IPv6+ # column and that is how the production lake writer stores a+ # v4 address — `test_retro_hunt_live.py` has a test named for+ # exactly this. Writing the bare dotted quad raises+ # `CannotParseDomainError`, so a fixture that got it wrong+ # would fail loudly rather than silently miss.+ (TENANT_WITH, now, 4001, 4, 2, "low", "with-host", f"::ffff:{INDICATOR}", "{}"),+ (TENANT_WITHOUT, now, 4001, 4, 2, "low", "without-host", "::ffff:203.0.113.9", "{}"),+ ],+ )+ yield client+ client.execute("TRUNCATE TABLE IF EXISTS aisoc.raw_events")++[email protected](scope="module")+def opted_in(lake): # noqa: ANN001+ """Both tenants opt in to retro-hunting.++ `opted_in_tenants` selects `RetroHuntSettings.enabled is True`, so a+ tenant with no row is skipped — correct behaviour, and the same+ opt-in posture as `RETRO_HUNT_ENABLED` defaulting off. Without this+ the sweep returns an empty list and the suite would be asserting+ against a feature nobody switched on, which is a different test from+ the one it claims to be.+ """+ # `asyncpg`, not `psycopg2`. Every live job installs from its+ # service's own lockfile — the fix for four rounds of+ # ModuleNotFoundError — and `psycopg2` is not in it. Adding a second+ # Postgres driver for two INSERTs of test setup would reintroduce+ # exactly the hand-curated dependency this repository removed from+ # its images.+ import asyncio # noqa: PLC0415 - kept beside its only use++ import asyncpg # noqa: PLC0415++ dsn = os.environ.get("ISOLATION_RETRO_PG_DSN", "").strip()+ if not dsn:+ pytest.skip("ISOLATION_RETRO_PG_DSN is not set; the sweep reads its tenants from Postgres")++ async def _seed() -> None:+ conn = await asyncpg.connect(dsn.replace("postgresql+asyncpg://", "postgresql://"))+ try:+ for tenant, slug in ((TENANT_WITH, "e2e-with"), (TENANT_WITHOUT, "e2e-without")):+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",+ tenant,+ slug,+ slug,+ )+ await conn.execute(+ "INSERT INTO retro_hunt_settings (tenant_id, enabled) VALUES ($1, true) "+ "ON CONFLICT (tenant_id) DO UPDATE SET enabled = true",+ tenant,+ )+ finally:+ await conn.close()++ asyncio.run(_seed())+ yield++[email protected](scope="module")+def published(lake, opted_in): # noqa: ANN001+ """The indicator, published to a real topic in the real envelope.++ Built from `IntelEvent`'s own shape rather than a hand-written dict,+ so a change to what the feed emits fails here.+ """+ pytest.importorskip("kafka")+ from kafka import KafkaConsumer, KafkaProducer++ topic = f"aisoc.threat_intel.e2e.{uuid.uuid4().hex[:8]}"+ brokers = os.environ["ISOLATION_KAFKA_BROKERS"].split(",")++ envelope = {+ "event_type": "NEW_IOC",+ "timestamp": datetime.now(UTC).isoformat(),+ "data": {+ "value": INDICATOR,+ "type": "ipv4",+ "source": "cisa-kev",+ "first_seen": datetime.now(UTC).isoformat(),+ "confidence": 90,+ },+ }++ producer = KafkaProducer(bootstrap_servers=brokers)+ producer.send(topic, json.dumps(envelope).encode())+ producer.flush()+ producer.close()++ consumer = KafkaConsumer(+ topic,+ bootstrap_servers=brokers,+ auto_offset_reset="earliest",+ consumer_timeout_ms=20000,+ group_id=f"e2e-{uuid.uuid4().hex[:8]}",+ )+ delivered = [record.value for record in consumer]+ consumer.close()+ return delivered++[email protected](scope="module")+def swept(published): # noqa: ANN001+ """Both sweeps, in **one** event loop: the published indicator, and+ one no tenant has.++ One run each, and both in the same loop, for two separate reasons.++ Re-running a sweep collides on `uq_alerts_tenant_idempotency` — the+ product being right, not a flake: the same indicator must not open a+ second alert for the same tenant. And a second `asyncio.run` over the+ same engine fails with "Event loop is closed", because the first run+ left pooled connections bound to a loop that has gone.+ """+ import asyncio++ from app.workers.retro_hunt_consumer import (+ handle_indicator,+ indicator_from_event,+ parse_intel_event,+ )++ async def _both():+ published_indicator = indicator_from_event(parse_intel_event(published[0]))+ absent = indicator_from_event(+ {+ "event_type": "NEW_IOC",+ "data": {"value": "203.0.113.254", "type": "ipv4", "source": "cisa-kev"},+ }+ )+ return {+ "published": await handle_indicator(published_indicator),+ "absent": await handle_indicator(absent),+ }++ return asyncio.run(_both())+++class TestTheSeam:+ def test_the_broker_delivered_the_indicator(self, published) -> None: # noqa: ANN001+ """The first half of the join, asserted on its own so a later+ failure is attributable."""+ assert published, "nothing came back off the topic within 20s"++ def test_the_consumer_parses_what_the_feed_published(self, published) -> None: # noqa: ANN001+ """The seam itself.++ A shape mismatch here is silent: the parser treats anything that+ is not `NEW_IOC` as somebody else's message and returns None,+ which reads identically to "no intel arrived".+ """+ from app.workers.retro_hunt_consumer import parse_intel_event++ parsed = parse_intel_event(published[0])+ assert parsed is not None, (+ "the consumer could not parse what the feed published. This failure mode is "+ "invisible in production: a None is indistinguishable from an empty topic."+ )++ def test_it_becomes_an_indicator_the_sweep_can_use(self, published) -> None: # noqa: ANN001+ from app.workers.retro_hunt_consumer import indicator_from_event, parse_intel_event++ indicator = indicator_from_event(parse_intel_event(published[0]))+ assert indicator is not None+ assert getattr(indicator, "value", None) == INDICATOR+++class TestTheSweepFindsTheRightTenant:+ def test_the_tenant_whose_data_holds_it_is_found(self, swept) -> None: # noqa: ANN001+ """The end of the claim: new intel arrives and the tenant who was+ already exposed is the one told about it."""+ matched = {str(r.tenant_id) for r in swept["published"] if r.matched}+ assert str(TENANT_WITH) in matched, f"the tenant whose recorded events hold {INDICATOR} was not found: {swept['published']!r}"++ def test_the_match_opens_an_alert(self, swept) -> None: # noqa: ANN001+ """ "Through Kafka to an alert" is the claim; this is the alert.++ A sweep that matched and opened nothing would leave the finding+ where no analyst sees it.+ """+ hit = next(r for r in swept["published"] if str(r.tenant_id) == str(TENANT_WITH))+ assert hit.alert_id is not None, f"the match opened no alert: {hit!r}"++ def test_the_tenant_whose_data_lacks_it_is_not(self, swept) -> None: # noqa: ANN001+ matched = {str(r.tenant_id): r.matched for r in swept["published"]}+ assert not matched.get(str(TENANT_WITHOUT)), (+ f"a tenant whose recorded events do not hold {INDICATOR} matched: {swept['published']!r}"+ )++ def test_no_tenant_was_reported_failed(self, swept) -> None: # noqa: ANN001+ """The second defect the savepoint closed.++ A failed flush used to leave the session needing a rollback, so+ every *later* tenant raised PendingRollbackError and was reported+ failed — directly contradicting the loop's own comment that one+ tenant must not stop the rest.+ """+ failed = [r for r in swept["published"] if r.outcome == "failed"]+ assert not failed, f"tenants reported failed: {failed!r}"+++class TestTheNegativeControl:+ def test_an_indicator_nobody_has_matches_nothing(self, swept) -> None: # noqa: ANN001+ """Without this, a sweep returning every tenant for every+ indicator would pass the positive case above."""+ reports = swept["absent"]+ assert reports, "the absent-indicator sweep produced no reports at all"+ assert not any(r.matched for r in reports), f"an indicator no tenant has was reported as matching: {reports!r}"