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
Depth 1.4-1.6: measure verdict quality across five local models, publish it, ship the design-partner replay kit (#1301)
Beenu Aroraa76073c20119
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 31cae7ca8..8de41fb49 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2105,6 +2105,18 @@ jobs:cat injection_eval.md} >> "${GITHUB_STEP_SUMMARY}"+ # Depth 1.6. The published verdict-quality table is generated from the+ # committed scorecard, so a number edited into the page by hand, or a+ # scorecard refreshed without regenerating the page, reds this step.+ #+ # It also refuses a scorecard that could put a score-shaped cell where+ # no measurement exists -- most importantly a row claiming a live+ # measurement that placed zero model calls, which is exactly what a run+ # against a dead endpoint produces once triage falls through to its+ # deterministic scorer.+ - name: Verdict quality (published table matches the committed scorecard)+ run: python3 scripts/check_verdict_quality.py --check+- name: Post job summaryif: always()run: |diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.mdindex f89214461..19cd4bb58 100644--- a/DEPTH_PROGRESS.md+++ b/DEPTH_PROGRESS.md@@ -43,7 +43,7 @@ requires in its own pull request body.| 8.2 | #1206 | `endpoints/access_conditions.py` || 8.3 | #1210 | `docs/security/` |-Not started: phases 3, 4, 6, 7, 9 and the whole of 10, plus 1.4--1.6 and+Not started: phases 3, 4, 6, 7, 9 and the whole of 10, and2.4--2.7. Those remain `[ ]` and are not claimed here.## Migration and ADR numbers claimed@@ -208,9 +208,10 @@ will re-take it on a sized host.`scripts/run_model_matrix.py` reports **0 of 2 models measured** with "no liveLLM key configured". This is the gate behaving correctly: it refuses to-publish `0.000` where it means "not measured". Phase 1.4 adds local 7--8B-candidates, which need no key and *can* be measured here; the hosted rows stay-`[!]` until the maintainer funds a key.+publish `0.000` where it means "not measured". Phase 1.4 has since measured+two local candidates, which need no key: see the verdict-quality table on the+benchmark page and the 1.4 note below. The hosted rows stay `[!]` until the+maintainer funds a key, and still read "not measured" rather than zero.### D4 -- Not all 74 "windowed" rules need a window@@ -347,9 +348,110 @@ invented fields on the first run of the gate.Wilson interval, false negatives, auto-close precision, escalation rate,time to verdict- [x] **1.3** Close `fake_tool_output` structurally (≤ 0.10 tuned and held-out)-- [ ] **1.4** A 7--8B local model in the matrix, chosen by score-- [ ] **1.5** `make replay-eval` design-partner kit-- [ ] **1.6** Published "Verdict quality" table with a `--check` drift gate+- [x] **1.4** A 7--8B local model in the matrix, chosen by score+- [x] **1.5** `make replay-eval` design-partner kit+- [x] **1.6** Published "Verdict quality" table with a `--check` drift gate++### 1.4 -- five local models measured; the winner is generation, not size++All five graded the same corpus digest through the production triage path,+72 model calls each, zero provider errors.++| Model | Balanced acc. | MCC | Malicious recall | Malicious prec. | ECE | Auto-close prec. |+|---|---|---|---|---|---|---|+| `llama3.1:8b-instruct-q4_K_M` | **0.357** | **0.209** | 0.583 / 36 | **0.724** | **0.349** | 0.111 (9) |+| `llama3.2:3b-instruct-q4_K_M` (CPU default) | 0.285 | 0.047 | 0.250 / 36 | 0.500 | 0.442 | 0.571 (7) |+| `llama3:8b` | 0.279 | 0.113 | **0.639** / 36 | 0.657 | 0.421 | 0.091 (11) |+| `qwen2.5:7b-instruct-q4_K_M` | 0.260 | 0.032 | 0.083 / 36 | 0.750 | 0.594 | 0.243 (37) |+| `mistral:7b-instruct-v0.3-q4_K_M` | 0.210 | 0.202 | **0.639** / 36 | 0.657 | 0.366 | 0.143 (14) |++Four classes: a constant answer scores **0.250** balanced accuracy, and+always guessing the majority class scores **0.500** plain accuracy.++**Decision, strictly by balanced accuracy:** `llama3.1:8b-instruct-q4_K_M`+becomes the default on `docker-compose.gpu.yml` and+`docker-compose.host-llm.yml`. It also leads on MCC, malicious precision and+calibration, and is the only row with ECE below 0.40. The 3B stays the+default for CPU `make up`, where a ~5 GB model does not fit the 8 GB CORE+budget -- a deployment constraint, not a score.++**Size is the wrong unit.** The previous-generation `llama3:8b` scores+*below* the 3B it would replace, so "upgrade to an 8B" is not advice that+survives measurement. An earlier revision of this file recorded exactly that+conclusion from `llama3:8b` alone and was wrong; the LiteLLM config's hint+now carries all five numbers instead.++**Two findings outrank the ranking.** Every model measured is far closer to+chance than to useful -- the best is 0.357 against a 0.250 floor, and three+of five fall below the 0.500 plain accuracy of guessing the majority class.+And auto-close precision is poor across the board (0.091-0.571 on 7-37+candidates), so **nothing measured here supports autonomous closure**. That+is a finding about the auto-close gate, not about which model to pick.++Caveats published rather than smoothed over:++- **Latency is excluded from the comparison.** The 3B ran CPU-bound inside+ the stack container and the four 7--8B rows GPU-accelerated on the host,+ so the figures measure different machines. All are still printed.+- **Per-decision model attribution is unverified.** Every call was placed+ and answered -- each decision carries reasoning specific to its alert --+ but `resolved_models` came back empty on every run, so the scorecard shows+ that 72 calls happened and not which model served each.+- **Auto-close precision rests on 7 to 37 candidates.** Small denominators;+ read the column as a warning sign, not a ranking.++**Writing the winner into the GPU overlay broke the GPU overlay, and CI+caught it.** Adding the model default left the+`deploy.resources.reservations.devices` block nested under `litellm`+instead of `ollama`. The file still parsed, `docker compose config` still+resolved, and `make up-gpu` would still have come up -- with the card+reserved by a proxy that runs no inference while generation fell back to+the CPU. There is no error anywhere in that sequence, which is why the+existing `test_it_touches_only_ollama` was the only thing between it and a+release.++Its companion assertion failed for a legitimate reason at the same time:+the overlay now *must* touch three services, since the measured default+needs a pull instruction on `ollama-pull` and routing on `litellm`. The+assertion was re-expressed rather than relaxed, and two properties added --+a device reserved on any service but `ollama` fails, and the model pulled+must be the model routed to. That second one guards the quiet failure: the+gateway 404s on a model nothing pulled, triage swallows it into the+deterministic fallback, and the stack looks healthy while measuring no+model at all. Each was proven by injecting the defect it names.++### 1.5 -- run end to end against a live stack, not a mock++`make replay-eval` / `make replay-eval-verify` drove a real run through the+API against a mocked Splunk ES holding 200 recorded closed notables: 200+read, 60 replayed in the test window, 240 production writes intercepted, a+signed bundle written and verified, and a wrong key refused with exit 1.++The live run is what found the three defects the unit tests could not: the+decisions route answers a bare array and the kit assumed an envelope; a+machine named only in the agent's reasoning survived redaction; and the+prose and identifier passes named their counter namespace in different+cases, so one host could take two tokens. All three are fixed with+regression tests, each proven to fail against the pre-fix tree.++Known gap: the run abstained on all 60 decisions because the stack's triage+reached no model, so the kit has been exercised on a deterministic run end+to end but **not yet on a run with real model verdicts in it**.++### 1.6 -- the section it replaced was wrong, not merely stale++`apps/docs/docs/benchmark.md` said verdict accuracy was not measured here+and could not be. Item 1.1's corpus made that false. The reasoning is kept+(it is why `score_replay_set.py` still refuses this tree's two all-malicious+corpora) and the conclusion is replaced by the measurement.++`scripts/check_verdict_quality.py --check` is wired into `ci.yml` and fails+on drift between the committed scorecard and the published block, proven by+reverting a number and watching it red. It also refuses five scorecard+shapes that would each publish a score-shaped cell with no measurement+behind it -- the load-bearing one being a row claiming a live measurement+that placed zero model calls, which is precisely what a run against a dead+endpoint produces once triage falls through to its deterministic scorer.## Phase 2: A semantic layer and live posturediff --git a/Makefile b/Makefileindex c34a5007e..ce161b3a8 100644--- a/Makefile+++ b/Makefile@@ -79,7 +79,7 @@ console_url = $(if $(strip $(CONSOLE_URL)),$(strip $(CONSOLE_URL)),http://localh.PHONY: help install env up up-dev up-full up-gpu up-host-llm _gpu_preflight pull down restart status doctor smoke _anonymous_write_is_refused demo logs clean \bootstrap ingest-token api-token test test-unit test-integration test-e2e stats papers \- papers-install demo-script+ papers-install demo-script replay-eval replay-eval-verifyhelp:@echo ""@@ -486,6 +486,35 @@ test-e2e: smokestats:@$(PYTHON) scripts/project_stats.py+# ── Replay evaluation: grade AiSOC on your own closed alerts ───────────────+#+# Reads a window of closed findings out of your SIEM, replays them through+# the same triage path a live alert takes, scores the verdicts against what+# your analysts decided, and writes one signed file.+#+# It writes nothing to your deployment: the replay runs in shadow mode and+# the count of writes it intercepted travels in the bundle, so a replay that+# quietly stopped replaying can be told from one whose writes were suppressed.+#+# Air-gapped by default. If a hosted model answered, the run is refused+# unless you passed --hosted, and the refusal names the model. The check+# reads the models that actually answered rather than a config file, because+# a config file states an intention.+#+# make replay-eval ARGS="--connector-id <uuid>"+# make replay-eval ARGS="--connector-id <uuid> --since 2026-07-01T00:00:00Z --until 2026-10-01T00:00:00Z"+# make replay-eval ARGS="--connector-id <uuid> --export-items" # per-decision rows, redacted+# make replay-eval-verify ARGS="aisoc-replay-<id>.bundle.json"+#+# Credentials: AISOC_API_KEY carries the tenant, so there is no tenant flag.+# AISOC_REPLAY_SIGNING_KEY (or SECRET_KEY) signs the bundle, so it verifies+# on this deployment and nowhere else.+replay-eval:+ @$(PYTHON) scripts/run_replay_eval.py run $(ARGS)++replay-eval-verify:+ @$(PYTHON) scripts/run_replay_eval.py verify $(ARGS)+# ── Papers + demo script (pre-existing) ────────────────────────────────────papers:diff --git a/apps/docs/docs/benchmark.md b/apps/docs/docs/benchmark.mdindex a1578d761..7a58b7a5a 100644--- a/apps/docs/docs/benchmark.md+++ b/apps/docs/docs/benchmark.md@@ -95,53 +95,87 @@ 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.+## Verdict quality++**This section used to say verdict accuracy was not measured here and could+not be. That was true when it was written, and it is no longer true.** The+reason it was true is worth keeping: every labelled set in this repository+was malicious by construction, so an agent answering "true positive" to+everything, without reading anything, posted 100% accuracy and 100%+malicious recall. `scripts/score_replay_set.py` still refuses those corpora,+and a test still asserts that **this tree's own two corpora are refused**,+because that was the finding rather than a bug to route around.++What changed is a corpus that can produce an honest number:+[`verdict_corpus_v1.json`](https://github.com/beenuar/AiSOC/blob/main/services/agents/tests/eval_data/verdict/verdict_corpus_v1.json)+— 72 hand-authored items in 36 twin pairs, where each pair shares its title,+rule, severity, vendor and ATT&CK technique and differs **only** in the+evidence. Severity alone therefore separates nothing. Every item carries+`is_synthetic: true`; no recorded customer telemetry is involved, and the+corpus README names every public dataset considered and why each was+refused.++<!-- BEGIN:verdict-quality -->++Corpus: **72 items** in **36 twin pairs** (`verdict_corpus_v1`, digest `sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86`). Twins share title, rule, severity, vendor and technique and differ only in the evidence, so severity alone separates nothing and a constant answer scores at most **0.250**. Hand-authored and synthetic: no recorded customer telemetry is involved.++| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed |+|---|---|---|---|---|---|---|---|+| `llama3.2:3b-instruct-q4_K_M` | live | 0.285 | 0.047 | 0.250 / 36 | 0.000 | 0.000 | 72 |+| `llama3.1:8b-instruct-q4_K_M` | live | 0.357 | 0.209 | 0.583 / 36 | 0.000 | 0.000 | 72 |+| `llama3:8b` | live | 0.279 | 0.113 | 0.639 / 36 | 0.000 | 0.000 | 72 |+| `qwen2.5:7b-instruct-q4_K_M` | live | 0.260 | 0.032 | 0.083 / 36 | 0.097 | 0.000 | 72 |+| `mistral:7b-instruct-v0.3-q4_K_M` | live | 0.210 | 0.202 | 0.639 / 36 | 0.306 | 0.000 | 72 |+| `any hosted provider (GPT-4o class)` | – | not measured — no funded key exists in this repository, and no hosted provider has ever been exercised | – | – | – | – | 0 |++Malicious recall prints the count behind it: a rate over 36 cases is a different claim from the same rate over four, and the figure alone cannot say which. Every measured row placed the model calls shown in the last column; a row that placed none is refused rather than published, because triage answers from a deterministic scorer when a provider fails and the resulting scorecard looks entirely normal.++**Shipped default: `llama3.2:3b-instruct-q4_K_M (CPU) / llama3.1:8b-instruct-q4_K_M (GPU, host-LLM)`.** Chosen strictly by balanced accuracy, the metric this corpus was built to make meaningful. llama3.1:8b-instruct-q4_K_M leads at 0.357 against the 3B's 0.285 and a 0.250 constant-answer floor, and also leads on MCC (0.209), malicious precision (0.724) and calibration (ECE 0.349, the only row below 0.40). It therefore becomes the default on the GPU and host-LLM overlays. The 3B stays the default for CPU `make up`, where a ~5 GB model does not fit the 8 GB CORE budget -- a deployment constraint, not a score. Two findings outrank the ranking. First, every model measured is far closer to chance than to useful: the best balanced accuracy is 0.357 against a 0.250 floor, and three of five score below the 0.500 plain accuracy of always guessing the majority class. Second, auto-close precision is poor across the board -- 0.571 on seven candidates at best, 0.091 to 0.243 elsewhere -- so nothing measured here supports autonomous closure, and that is a finding about the auto-close gate rather than about which model to pick.++<!-- END:verdict-quality -->++### How to read this table++The two baselines are the point. With four classes, **a constant answer+scores 0.250 balanced accuracy**, and **always guessing the majority class+scores 0.500 plain accuracy**. The best model measured reaches 0.357, and+three of the five fall below 0.500 on plain accuracy. So the honest+headline is not which model wins — it is that **every one of them is far+closer to chance than to useful**, and that the next thing to change is the+verdict path and the prompt rather than the size of the model.++**Size is the wrong unit.** `llama3.1:8b` leads the table, and the+previous-generation `llama3:8b` scores *below* the 3B it would replace.+"Upgrade to an 8B" is not advice that survives measurement; the generation+mattered more than the parameter count here.++**`mistral:7b` is why balanced accuracy is the headline metric.** It posts+the highest plain accuracy of any row (0.500) and the lowest balanced+accuracy (0.210), because it abstains on 31% of items. Plain accuracy+rewards that and balanced accuracy sees through it, which is the entire+reason the corpus was built in twin pairs.++**Nothing here supports autonomous closure.** Auto-close precision ranges+from 0.091 to 0.571 across the five, on denominators of 7 to 37 candidates.+Even the best of those means closing seven alerts to get four right. That+is a finding about the auto-close gate rather than about model choice, and+it is the reason the shipped posture stays human-approval.++**Latency is excluded from the comparison and is published per row anyway.**+The 3B ran CPU-bound inside the stack container and the four 7–8B rows ran+GPU-accelerated on the host, so the figures measure different machines.+Dropping the column would have hidden that asymmetry instead of naming it.++**Per-decision model attribution is unverified.** Every run placed the model+calls shown and every call was answered — the reasoning in each decision is+specific to its alert — but `resolved_models` came back empty, so the+scorecard can show that 72 calls happened and cannot show which model served+each one. The count is measured; the attribution is not.++**No hosted provider has ever been exercised.** The hosted row 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 afterdiff --git a/apps/docs/docs/evaluation/replay.md b/apps/docs/docs/evaluation/replay.mdindex 4ce9a5580..41f0ef3d0 100644--- a/apps/docs/docs/evaluation/replay.md+++ b/apps/docs/docs/evaluation/replay.md@@ -311,6 +311,73 @@ renderer is a different artefact from the one you read. The per-decision rowsare kept separately, and carry the evidence triage was given, so a number youdisagree with can be re-derived rather than re-argued.+### The design-partner kit++The three paths above give you a report. The kit wraps the same run in the+two things you need before a report can leave your building: a signature that+says it came from your deployment unaltered, and a redaction pass that means+you can hand it to us without handing over your estate.++```bash+make replay-eval ARGS="--connector-id <uuid>"+```++It needs two values in the environment — `AISOC_API_KEY`, and+`AISOC_REPLAY_SIGNING_KEY`, which is any secret you choose and keep. The+signing key never leaves your deployment and is not recoverable from a+bundle, so a bundle you send us proves it was produced by a holder of that+key and has not been edited since, and nothing more.++The output is a JSON evidence bundle:++```+{+ "payload": { "schema_version", "generated_at", "method", "scores", "privacy", "items"? },+ "integrity": { "payload_sha256", "algorithm": "HMAC-SHA256", "signature" }+}+```++Verify one — yours, or one we send back to you — with:++```bash+make replay-eval-verify ARGS="path/to/bundle.json"+```++It exits non-zero and says so when the signature does not match the key in+your environment, which is the same answer for an edited bundle and for one+produced by a different deployment, because from the outside those are the+same event.++**Aggregates by default; items only if you ask.** A bundle carries the+scores, the method and the privacy block. Per-finding rows are withheld+unless you pass `--export-items`, and the hallucinated-indicator examples are+withheld with them, because an example is a verbatim quotation of your+analyst's or the model's prose about one of your machines.++**What redaction does and does not do.** Identifiers — finding id, rule,+source, tenant, connector — are replaced whole with stable tokens (`RULE_1`,+`HOST_2`), so two rows about one rule can still be seen to concern one rule+while the rule is not named. The agent's free text goes through the same+tokens plus the platform's pattern redactor plus a pass for host-shaped words+the identifier pass never saw, which is what catches a machine the model+quoted in its reasoning and nothing else mentioned. Public taxonomy is held+back deliberately: `SHA-256`, `CVE-2026-1234`, `RFC-1918` and `x86-64` all+match the host shape and all stay readable, because reasoning rewritten into+`HOST_4 hashing` protects nothing and cannot be reviewed. The raw evidence+triage was given is dropped outright rather than redacted.++The bundle states its own limits in a `privacy` block rather than leaving you+to infer them: what the free-text pass does not catch, that the token map is+never exported, and that evidence was withheld. Read it before you send one.++**Egress is classified, not assumed.** Every bundle records whether anything+left your estate, derived from the models the run actually resolved rather+than from the flags you passed: `none` when every call went to a local model+or no call was placed at all, `hosted` when a third-party provider was used —+which the kit refuses to do unless you pass `--hosted` — and `unverified`+when calls were placed that the gateway did not attribute, which is reported+as unknown rather than quietly as `none`.+## Reproducibility, stated precisely**A report reproduces byte for byte between two runs over the same pinned@@ -382,6 +449,16 @@ through the same triage path production uses.on a local checkout. When they are, the PDF route answers 503 naming them,rather than serving an empty file; JSON and Markdown carry the same reportand need nothing extra.+- **Redaction is a pattern pass, and patterns have edges.** A single-word+ machine name with no digit and no separator is indistinguishable from an+ ordinary word, and a host whose first segment collides with public+ taxonomy — one literally named `sha-1` — is kept for the same reason+ `SHA-256` is. The bundle names both limits in its own privacy block. Read+ a bundle before sending it; the kit makes a leak unlikely, not impossible.+- **A signature proves integrity and origin, not honesty.** It says a holder+ of your key produced those bytes and nobody changed them afterwards. It+ says nothing about whether the window was chosen fairly, which is why the+ method block travels inside the signed payload.- **Hallucination counting errs high.** Indicators are extracted from theagent's own reasoning with the same pattern set the synthetic-corpus graderchecks against, so a phrase shaped like a domain is checked and, if absentdiff --git a/docs/evaluation/verdict_scorecard.json b/docs/evaluation/verdict_scorecard.jsonnew file mode 100644index 000000000..524600c60--- /dev/null+++ b/docs/evaluation/verdict_scorecard.json@@ -0,0 +1,165 @@+{+ "baselines_note": "Four classes, so a constant answer scores 0.250 balanced accuracy and 0.500 plain accuracy. Both are stated beside the table because a score is only readable against the thing it has to beat.",+ "commit": "f92e8bcd",+ "comparability": [+ "All five rows graded the same corpus digest through the same production triage path, 72 model calls each, zero provider errors.",+ "Latency is NOT comparable across rows and is excluded from the decision: the 3B ran CPU-bound inside the stack container and the four 7-8B rows ran GPU-accelerated on the host. Kept per row so the asymmetry is stated rather than hidden.",+ "resolved_models came back empty on every decision of every run, so per-decision model attribution is unverified even though the calls were placed and answered. The count of calls is measured; the attribution is not.",+ "auto_close_precision rests on 7 to 37 candidates depending on the row. Those are small denominators and the column should be read as a warning sign, not as a ranking."+ ],+ "corpus": {+ "classes": {+ "benign": 18,+ "benign_true_positive": 10,+ "false_positive": 8,+ "true_positive": 36+ },+ "constant_answer_ceiling": 0.25,+ "digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "items": 72,+ "majority_class_plain_accuracy": 0.5,+ "name": "verdict_corpus_v1",+ "pairs": 36+ },+ "default_model": "llama3.2:3b-instruct-q4_K_M (CPU) / llama3.1:8b-instruct-q4_K_M (GPU, host-LLM)",+ "default_rationale": "Chosen strictly by balanced accuracy, the metric this corpus was built to make meaningful. llama3.1:8b-instruct-q4_K_M leads at 0.357 against the 3B's 0.285 and a 0.250 constant-answer floor, and also leads on MCC (0.209), malicious precision (0.724) and calibration (ECE 0.349, the only row below 0.40). It therefore becomes the default on the GPU and host-LLM overlays. The 3B stays the default for CPU `make up`, where a ~5 GB model does not fit the 8 GB CORE budget -- a deployment constraint, not a score. Two findings outrank the ranking. First, every model measured is far closer to chance than to useful: the best balanced accuracy is 0.357 against a 0.250 floor, and three of five score below the 0.500 plain accuracy of always guessing the majority class. Second, auto-close precision is poor across the board -- 0.571 on seven candidates at best, 0.091 to 0.243 elsewhere -- so nothing measured here supports autonomous closure, and that is a finding about the auto-close gate rather than about which model to pick.",+ "entries": [+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 7,+ "auto_close_precision": 0.5714285714285714,+ "balanced_accuracy": 0.28541666666666665,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.441667,+ "false_negatives": 27,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.3194444444444444,+ "llm_calls_placed": 72,+ "malicious_precision": 0.5,+ "malicious_recall": 0.25,+ "malicious_support": 36,+ "matthews_corrcoef": 0.046864498582862235,+ "measured_at": "2026-10-10",+ "mode": "live",+ "model": "llama3.2:3b-instruct-q4_K_M",+ "note": "Retained for CPU `make up`: a ~5 GB 8B does not fit the 8 GB CORE budget alongside the rest of the stack.",+ "role": "shipped default (CPU profile)",+ "served_on": "CPU, in-stack container",+ "time_to_verdict_p50_ms": 11188.0,+ "total_tokens": 70983+ },+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 9,+ "auto_close_precision": 0.1111111111111111,+ "balanced_accuracy": 0.35694444444444445,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.348611,+ "false_negatives": 15,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.4583333333333333,+ "llm_calls_placed": 72,+ "malicious_precision": 0.7241379310344828,+ "malicious_recall": 0.5833333333333334,+ "malicious_support": 36,+ "matthews_corrcoef": 0.20863951686663296,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "llama3.1:8b-instruct-q4_K_M",+ "note": "Best balanced accuracy, MCC, malicious precision and calibration of everything measured.",+ "role": "winner (GPU / host-LLM profiles)",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1698.0,+ "total_tokens": 74495+ },+ {+ "abstention_rate": 0.0,+ "auto_close_considered": 11,+ "auto_close_precision": 0.09090909090909091,+ "balanced_accuracy": 0.2791666666666667,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.420833,+ "false_negatives": 13,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.4166666666666667,+ "llm_calls_placed": 72,+ "malicious_precision": 0.6571428571428571,+ "malicious_recall": 0.6388888888888888,+ "malicious_support": 36,+ "matthews_corrcoef": 0.11329558957744541,+ "measured_at": "2026-10-10",+ "mode": "live",+ "model": "llama3:8b",+ "note": "Previous-generation llama3. Superseded by llama3.1:8b on every metric except malicious recall, where they tie.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1546.0,+ "total_tokens": 74808+ },+ {+ "abstention_rate": 0.09722222222222222,+ "auto_close_considered": 37,+ "auto_close_precision": 0.24324324324324326,+ "balanced_accuracy": 0.25972222222222224,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.593846,+ "false_negatives": 33,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.26153846153846155,+ "llm_calls_placed": 72,+ "malicious_precision": 0.75,+ "malicious_recall": 0.08333333333333333,+ "malicious_support": 36,+ "matthews_corrcoef": 0.03241459519549664,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "qwen2.5:7b-instruct-q4_K_M",+ "note": "Worst measured: catches 3 of 36 malicious cases and is the least calibrated of the five.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 1567.0,+ "total_tokens": 77044+ },+ {+ "abstention_rate": 0.3055555555555556,+ "auto_close_considered": 14,+ "auto_close_precision": 0.14285714285714285,+ "balanced_accuracy": 0.2097222222222222,+ "corpus_digest": "sha256:ec60d7bddabcc5b28d8942cea52d770bd8a2d13b93396826a6deab1dcba6aa86",+ "corpus_items": 72,+ "decisions_errored": 0,+ "expected_calibration_error": 0.366,+ "false_negatives": 13,+ "hallucination_rate": 0.0,+ "headline_accuracy": 0.5,+ "llm_calls_placed": 72,+ "malicious_precision": 0.6571428571428571,+ "malicious_recall": 0.6388888888888888,+ "malicious_support": 36,+ "matthews_corrcoef": 0.20247984364137678,+ "measured_at": "2026-10-11",+ "mode": "live",+ "model": "mistral:7b-instruct-v0.3-q4_K_M",+ "note": "Highest plain accuracy (0.500) and lowest balanced accuracy (0.210): it abstains on 31% of items, which flatters plain accuracy and is exactly what balanced accuracy exists to see through.",+ "role": "candidate",+ "served_on": "GPU, host Ollama",+ "time_to_verdict_p50_ms": 2210.0,+ "total_tokens": 93626+ },+ {+ "measured": false,+ "model": "any hosted provider (GPT-4o class)",+ "not_measured_reason": "no funded key exists in this repository, and no hosted provider has ever been exercised"+ }+ ],+ "generated_from": "scripts/run_verdict_eval.py",+ "schema_version": "1.0"+}diff --git a/infra/compose/docker-compose.gpu.yml b/infra/compose/docker-compose.gpu.ymlindex 6721a86ec..655725585 100644--- a/infra/compose/docker-compose.gpu.yml+++ b/infra/compose/docker-compose.gpu.yml@@ -41,6 +41,21 @@# visible device; set `AISOC_GPU_COUNT=all` to expose every device, or pin# specific ones with `device_ids` instead of `count` if you share the host.+# Model+# -----+# This overlay moves the default off the 3B the CPU profile ships. That is a+# measurement, not a preference: graded on the 72-item balanced verdict+# corpus, `llama3.1:8b-instruct-q4_K_M` scores 0.357 balanced accuracy+# against the 3B's 0.285 and a 0.250 constant-answer floor, and is the only+# model measured whose calibration error falls below 0.40. The table and the+# four rows it beat are published on the benchmark page under "Verdict+# quality"; `scripts/run_verdict_eval.py` reproduces it.+#+# It needs roughly 6 GB of VRAM rather than the 3B's 3 GB. Override with+# AISOC_LLM_LOCAL_MODEL plus the two routing variables if your card is+# smaller -- all three have to move together, or the gateway routes to a+# model nothing pulled.+services:ollama:environment:@@ -48,6 +63,11 @@ services:# unset rather than forced, because a hardcoded layer count is wrong# on every card except the one it was measured on.OLLAMA_NUM_PARALLEL: "${OLLAMA_NUM_PARALLEL:-1}"+ # The reservation belongs to the service that runs the model. Ollama is+ # the only one here that does any inference: litellm proxies and+ # ollama-pull downloads, so a device reserved on either of those is a+ # GPU held by something that cannot use it while generation runs on the+ # CPU -- the overlay reporting success having done nothing.deploy:resources:reservations:@@ -55,3 +75,11 @@ services:- driver: nvidiacount: ${AISOC_GPU_COUNT:-1}capabilities: [gpu]++ ollama-pull:+ entrypoint: ["ollama", "pull", "${AISOC_LLM_LOCAL_MODEL:-llama3.1:8b-instruct-q4_K_M}"]++ litellm:+ environment:+ AISOC_LLM_MODEL_FAST: ${AISOC_LLM_MODEL_FAST:-ollama_chat/llama3.1:8b-instruct-q4_K_M}+ AISOC_LLM_MODEL_DEEP: ${AISOC_LLM_MODEL_DEEP:-ollama_chat/llama3.1:8b-instruct-q4_K_M}diff --git a/infra/compose/docker-compose.host-llm.yml b/infra/compose/docker-compose.host-llm.ymlindex b4ac3397c..b442dd9d5 100644--- a/infra/compose/docker-compose.host-llm.yml+++ b/infra/compose/docker-compose.host-llm.yml@@ -51,7 +51,18 @@## and confirm the model this stack asks for is pulled:#-# ollama pull llama3.2:3b-instruct-q4_K_M+# ollama pull llama3.1:8b-instruct-q4_K_M+#+# Why the 8B here and the 3B on CPU `make up`+# -------------------------------------------+# A host Ollama is the path that reaches a real GPU -- on a Mac it uses Metal,+# which a Linux container never can -- so this overlay defaults to the model+# that won on score rather than the one that fits an 8 GB CPU budget. Graded+# on the 72-item balanced verdict corpus, `llama3.1:8b-instruct-q4_K_M`+# scores 0.357 balanced accuracy against the 3B's 0.285 and a 0.250+# constant-answer floor, with the best malicious precision (0.724) and the+# only calibration error below 0.40 of the five models measured. The table is+# published on the benchmark page under "Verdict quality".## Point at something else entirely by setting AISOC_LLM_API_BASE in `.env` —# another machine on the LAN, or an existing vLLM. This overlay only supplies@@ -70,6 +81,12 @@ services:- "host.docker.internal:host-gateway"environment:AISOC_LLM_API_BASE: "${AISOC_LLM_API_BASE:-http://host.docker.internal:11434}"+ # Both routing variables move together with the pull instruction above.+ # Setting one alone points the gateway at a model nobody pulled, which+ # surfaces as a provider 404 that triage swallows into its deterministic+ # fallback -- a stack that looks healthy and measures nothing.+ AISOC_LLM_MODEL_FAST: ${AISOC_LLM_MODEL_FAST:-ollama_chat/llama3.1:8b-instruct-q4_K_M}+ AISOC_LLM_MODEL_DEEP: ${AISOC_LLM_MODEL_DEEP:-ollama_chat/llama3.1:8b-instruct-q4_K_M}# The API reads Ollama directly for the runtime probe behind# `GET /api/v1/llm/runtime` — "is the model on a GPU or a CPU" is answered bydiff --git a/infra/litellm/config.yaml b/infra/litellm/config.yamlindex eb442096c..17c623c05 100644--- a/infra/litellm/config.yaml+++ b/infra/litellm/config.yaml@@ -128,6 +128,26 @@ model_list:# a bigger local AISOC_LLM_MODEL_DEEP=ollama_chat/llama3.1:8b# (pull it first: docker compose exec ollama ollama pull llama3.1:8b)#+ # On "a bigger local": pick by measurement, and mind the generation. Graded+ # on the 72-item balanced verdict corpus, five local models came out:+ #+ # llama3.1:8b-instruct-q4_K_M 0.357 balanced ECE 0.349 <- best+ # llama3.2:3b-instruct-q4_K_M 0.285 balanced ECE 0.442 <- CPU default+ # llama3:8b 0.279 balanced ECE 0.421+ # qwen2.5:7b-instruct-q4_K_M 0.260 balanced ECE 0.594+ # mistral:7b-instruct-v0.3 0.210 balanced ECE 0.366+ #+ # So "8B" is not the useful unit: llama3.1:8b leads and the previous-+ # generation llama3:8b scores below the 3B it would replace. The GPU and+ # host-LLM overlays already default to the winner; this line is for anyone+ # routing a single role by hand.+ #+ # Two caveats that outrank the ranking. A constant answer scores 0.250, so+ # every row here is far closer to chance than to useful. And auto-close+ # precision is poor across all five (0.091-0.571 on 7-37 candidates), so+ # nothing measured supports autonomous closure on any of them. Re-grade+ # with `scripts/run_verdict_eval.py` before moving a deployment.+ ## Per-alias divergence — a different model for one workload only — is the case# that does need an edit: replace that alias's `os.environ/...` with a literal.diff --git a/packages/aisoc-benchmark/aisoc_benchmark/replay.py b/packages/aisoc-benchmark/aisoc_benchmark/replay.pyindex e7021d0d2..3b3b12e11 100644--- a/packages/aisoc-benchmark/aisoc_benchmark/replay.py+++ b/packages/aisoc-benchmark/aisoc_benchmark/replay.py@@ -295,6 +295,18 @@ class ReplayScore:mean_latency_ms: float | None = Nonep95_latency_ms: float | None = Nonemodels: list[str] = field(default_factory=list)+ #: Model calls the run placed, however they were priced.+ #:+ #: Separate from ``models`` because the two answer different questions and+ #: only one of them is always answerable. ``models`` is what the *gateway*+ #: said it billed, read off a LiteLLM response header, so it is empty on a+ #: run that talked straight to a provider -- an air-gapped Ollama, say --+ #: even though every call was placed and paid for in tokens. Reporting+ #: that state as "no model call was placed" is a false statement about the+ #: most important fact in the report, since triage answers from its+ #: deterministic fallback when a provider is unreachable and a run that+ #: measured nothing otherwise looks entirely normal.+ llm_calls: int = 0# ---- provenance ------------------------------------------------------bootstrap_resamples: int = BOOTSTRAP_RESAMPLES@@ -530,6 +542,7 @@ def score_replay(score.time_to_verdict_p50_ms = _percentile(latencies, 0.50)score.time_to_verdict_p95_ms = score.p95_latency_msscore.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})+ score.llm_calls = sum(int(d.get("llm_calls") or 0) for d in decisions)if not labelled:score.headline_withheld_reason = (@@ -697,6 +710,22 @@ def _ms(value: float | None) -> str:return "not measured" if value is None else f"{value:,.0f} ms"+def _models(score: ReplayScore) -> str:+ """Which model answered, distinguishing the two ways of not knowing.++ "No call was placed" and "calls were placed and the gateway did not say+ which model took them" are different facts with different remedies, and+ collapsing them prints the first when the second is true. That reads as+ a run that measured the deterministic fallback, which is the single most+ misleading thing this report could say about itself.+ """+ if score.models:+ return ", ".join(score.models)+ if score.llm_calls:+ return f"not attributed — {score.llm_calls} call(s) placed, but no gateway named the model that took them"+ return "none, no model call was placed"++def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None = None) -> str:"""Render the report as Markdown, malicious recall first.@@ -830,7 +859,8 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"calls with no price at all: {score.unpriced_calls})",f"{LATENCY_LINE_PREFIX} {'not measured' if score.mean_latency_ms is None else f'{score.mean_latency_ms:.0f} ms'}, "f"p95 {'not measured' if score.p95_latency_ms is None else f'{score.p95_latency_ms:.0f} ms'}",- f"- Models: {', '.join(score.models) if score.models else 'none, no model call was placed'}",+ f"- Model calls placed: {score.llm_calls}",+ f"- Models: {_models(score)}","","## Method","",diff --git a/packages/aisoc-benchmark/tests/test_replay_metrics.py b/packages/aisoc-benchmark/tests/test_replay_metrics.pyindex a511862ef..81098983f 100644--- a/packages/aisoc-benchmark/tests/test_replay_metrics.py+++ b/packages/aisoc-benchmark/tests/test_replay_metrics.py@@ -392,3 +392,58 @@ def test_the_latency_fields_named_for_the_json_export_exist_on_the_score() -> Nofor field in LATENCY_FIELDS:assert field in score+++# --------------------------------------------------------------------------+# Which model answered, and the two different ways of not knowing+#+# Depth plan 1.4. `models` is read off a LiteLLM response header, so a run+# that talked straight to a provider leaves it empty while placing every+# call. The renderer used to print "none, no model call was placed" for that+# state, which is a false statement about the one fact that decides whether+# the rest of the report means anything: triage answers from its+# deterministic fallback when a provider is unreachable, so a run that+# measured nothing otherwise looks entirely normal.+# --------------------------------------------------------------------------+++def _with_calls(row: dict[str, Any], calls: int, models: list[str] | None = None) -> dict[str, Any]:+ row["llm_calls"] = calls+ row["resolved_models"] = models or []+ return row+++def test_calls_with_no_gateway_attribution_do_not_read_as_no_calls() -> None:+ rows = [_with_calls(d, 1) for d in _corpus(MIN_MALICIOUS_FOR_HEADLINE, 10)]+ score = score_replay(rows)++ assert score.llm_calls == len(rows)+ assert score.models == []++ report = format_replay_report(score)+ assert "none, no model call was placed" not in report+ assert f"{len(rows)} call(s) placed" in report+++def test_a_run_that_placed_no_call_still_says_so() -> None:+ rows = [_with_calls(d, 0) for d in _corpus(MIN_MALICIOUS_FOR_HEADLINE, 10)]+ score = score_replay(rows)++ assert score.llm_calls == 0+ assert "none, no model call was placed" in format_replay_report(score)+++def test_a_named_model_is_reported_as_itself() -> None:+ rows = [_with_calls(d, 1, ["ollama/llama3.1:8b"]) for d in _corpus(MIN_MALICIOUS_FOR_HEADLINE, 10)]+ report = format_replay_report(score_replay(rows))++ assert "ollama/llama3.1:8b" in report+ assert "not attributed" not in report+++def test_the_call_count_is_published_beside_the_models() -> None:+ """A reader must not have to infer "this measured nothing" from an absence."""+ rows = [_with_calls(d, 2) for d in _corpus(MIN_MALICIOUS_FOR_HEADLINE, 10)]+ report = format_replay_report(score_replay(rows))++ assert f"- Model calls placed: {2 * len(rows)}" in reportdiff --git a/scripts/check_module_reachability.py b/scripts/check_module_reachability.pyindex 5a5a11a2d..9d2c82a55 100644--- a/scripts/check_module_reachability.py+++ b/scripts/check_module_reachability.py@@ -73,6 +73,29 @@ ENTRY_POINT_DIRS = ("alembic/versions",)+#: Repo-root CLIs that are themselves a way the product is run, mapped to+#: the service whose ``app`` package they put on ``sys.path``. Their+#: ``from app.…`` imports are entry points into that service.+#:+#: Deliberately a named map and not "anything under ``scripts/`` counts".+#: Nine repo-root scripts import a service's ``app``, and most are CI+#: analysis tools that import a module precisely to inspect it — counting+#: those would let a checker vouch for dead code, which is weaker evidence+#: than the test imports this gate already refuses. The bar for an entry+#: here is that a user runs it: a documented ``make`` target or a command+#: the docs tell someone to type.+#:+#: A path that no longer exists, or that no longer imports the service,+#: fails the gate rather than lingering — the same discipline as the+#: allowlist below, for the same reason.+CLI_ENTRY_POINTS: dict[str, str] = {+ # `make replay-eval` / `make replay-eval-verify`. Builds and verifies+ # the design-partner evidence bundle on the operator's machine, so the+ # builder, the redactor and the verifier are imported from the API tree+ # rather than reached through a route.+ "scripts/run_replay_eval.py": "services/api",+}+#: Loaders that import by computed name. Each maps to the directory whose#: modules it reaches.DYNAMIC_LOADERS: dict[str, tuple[str, ...]] = {@@ -179,6 +202,7 @@ class Report:reachable: int = 0unreachable: list[str] = field(default_factory=list)stale_allowlist: list[str] = field(default_factory=list)+ broken_cli_entries: list[str] = field(default_factory=list)def _service_dirs(root: pathlib.Path) -> list[pathlib.Path]:@@ -257,6 +281,30 @@ def inspect(root: pathlib.Path) -> Report:rel = path.relative_to(service).as_posix()if rel in ENTRY_POINT_NAMES or any(rel.startswith(d + "/") for d in ENTRY_POINT_DIRS):entries.add(name)++ # A repo-root CLI reaches into exactly one service's `app`, so the+ # modules it names are roots for that service.+ service_rel = service.relative_to(root).as_posix()+ for cli_rel, cli_service in CLI_ENTRY_POINTS.items():+ if cli_service != service_rel:+ continue+ cli = root / cli_rel+ if not cli.is_file():+ report.broken_cli_entries.append(f"{cli_rel} (no such file)")+ continue+ named = {i for i in _imports(cli, "") if i == "app" or i.startswith("app.")}+ resolved = set()+ for imported in named:+ candidate = imported+ while candidate and candidate not in by_name:+ candidate = candidate.rsplit(".", 1)[0] if "." in candidate else ""+ if candidate:+ resolved.add(candidate)+ if not resolved:+ report.broken_cli_entries.append(f"{cli_rel} (imports no module of {cli_service})")+ continue+ entries |= resolved+report.entry_points += len(entries)# Dynamic loaders reach whole directories.@@ -330,6 +378,23 @@ def _verdict(report: Report) -> int:)return 2+ # Ahead of the findings below: a CLI entry that no longer resolves+ # silently stops rooting the walk, which *adds* unreachable modules. The+ # gate would then report those as dead code and send someone to delete+ # working code, when the real fault is one stale path here.+ if report.broken_cli_entries:+ print(+ "check_module_reachability: CLI entry points that no longer reach their service:",+ file=sys.stderr,+ )+ for rel in report.broken_cli_entries:+ print(f" {rel}", file=sys.stderr)+ print(+ "Fix the path or drop the entry. Left stale it roots nothing, and the modules it reached are then reported as dead code.",+ file=sys.stderr,+ )+ return 1+if report.stale_allowlist:print("check_module_reachability: allowlist entries that no longer describe an unreachable module:",@@ -392,6 +457,47 @@ def self_test() -> int:unreachable = {pathlib.Path(r).name for r in report.unreachable}extra.append(("reach is transitive", "deep.py" not in unreachable))+ # A repo-root CLI roots the walk — and only when it is mapped, so+ # the map cannot be bypassed by dropping a file into `scripts/`.+ cli_dir = pathlib.Path(tmp) / "scripts"+ cli_dir.mkdir(parents=True)+ (cli_dir / "run_probe.py").write_text("from app import orphan\n", encoding="utf-8")+ report = inspect(pathlib.Path(tmp))+ extra.append(+ (+ "an unmapped script under scripts/ does not rescue a module",+ "orphan.py" in {pathlib.Path(r).name for r in report.unreachable},+ )+ )++ CLI_ENTRY_POINTS["scripts/run_probe.py"] = "services/probe"+ try:+ report = inspect(pathlib.Path(tmp))+ extra.append(+ (+ "a mapped CLI makes what it imports reachable",+ "orphan.py" not in {pathlib.Path(r).name for r in report.unreachable},+ )+ )++ # The stale-entry arm, which is what keeps the map honest.+ (cli_dir / "run_probe.py").unlink()+ report = inspect(pathlib.Path(tmp))+ extra.append(("a mapped CLI that has gone is reported", bool(report.broken_cli_entries)))+ extra.append(("and that is a failure, not a pass", _verdict(report) == 1))++ # Present but no longer importing the service: the quieter half.+ (cli_dir / "run_probe.py").write_text("X = 1\n", encoding="utf-8")+ report = inspect(pathlib.Path(tmp))+ extra.append(+ (+ "a mapped CLI that stopped importing the service is reported",+ any("imports no module" in e for e in report.broken_cli_entries),+ )+ )+ finally:+ CLI_ENTRY_POINTS.pop("scripts/run_probe.py", None)+report = inspect(repo_root())extra.append((diff --git a/scripts/check_verdict_quality.py b/scripts/check_verdict_quality.pynew file mode 100644index 000000000..423e72217--- /dev/null+++ b/scripts/check_verdict_quality.py@@ -0,0 +1,252 @@+#!/usr/bin/env python3+"""Depth plan 1.6: publish verdict quality, and refuse to publish a number nobody measured.++The page this writes replaces a section that said verdict accuracy was *not*+measured here. That section was true when it was written and the corpus (item+1.1) is what made it false, so the honest move is to publish the measurement+rather than to delete the caveat.++Everything this script publishes comes out of a committed scorecard file,+which is itself the output of ``scripts/run_verdict_eval.py``. There is no+scoring in this file and there must never be: a second definition of "verdict+accuracy" would drift from the one the eval produces, which is the defect the+alert-reduction suite already shipped once.++What this gate is actually for+------------------------------+A table on a public page is a claim, and the failure mode is not that a+number is wrong — it is that a number is *absent* and renders as ``0.000``,+which a reader cannot distinguish from a model that was graded and scored+zero. That is the single rule this enforces, in both directions:++* a row with no measurement must carry a reason and render as+ ``not measured — <reason>``; a row that tries to publish a bare number+ without a measurement behind it is refused;+* a row claiming a live measurement must show that a model call was actually+ placed, because triage catches a provider error and falls through to a+ deterministic scorer, so a run against a dead endpoint produces a full set+ of confident verdicts and a scorecard that looks entirely normal.++Run:+ python3 scripts/check_verdict_quality.py --check+ python3 scripts/check_verdict_quality.py --write-benchmark+ python3 scripts/check_verdict_quality.py --self-test+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++BEGIN = "<!-- BEGIN:verdict-quality -->"+END = "<!-- END:verdict-quality -->"++#: Default location of the committed scorecard set.+SCORECARD_PATH = Path("docs/evaluation/verdict_scorecard.json")+BENCHMARK_PATH = Path("apps/docs/docs/benchmark.md")++#: Rendered in place of a number whenever a row carries no measurement. The+#: reason is mandatory and appended after it, because "not measured" alone+#: invites the reader to assume the measurement is merely pending.+NOT_MEASURED = "not measured"+++class VerdictQualityError(RuntimeError):+ """A scorecard that cannot be published honestly."""+++def _fmt(value: object, digits: int = 3) -> str:+ """Render a metric, or an em dash when the run did not produce one.++ A metric legitimately absent from a measured run (no auto-close candidate+ was considered, so there is no auto-close precision) is distinct from a+ row that was never measured at all, and the two must not look alike.+ """+ if value is None:+ return "–"+ if isinstance(value, bool): # guard: bool is an int subclass+ return str(value)+ if isinstance(value, (int, float)):+ return f"{float(value):.{digits}f}"+ return str(value)+++def validate_entry(entry: dict[str, Any]) -> None:+ """Refuse an entry that cannot be rendered without misleading a reader."""+ name = entry.get("model") or "<unnamed>"++ if not entry.get("model"):+ raise VerdictQualityError("a scorecard entry has no model name")++ if entry.get("measured") is False:+ reason = (entry.get("not_measured_reason") or "").strip()+ if not reason:+ raise VerdictQualityError(+ f"{name}: an unmeasured row must say why. Without a reason the row reads as "+ "pending, and a reader cannot tell an unfunded model from a failed one."+ )+ for field in ("balanced_accuracy", "malicious_recall", "headline_accuracy"):+ if entry.get(field) is not None:+ raise VerdictQualityError(+ f"{name}: carries {field}={entry[field]!r} while declaring measured=false. "+ "One of the two is wrong, and publishing the number would be the worse guess."+ )+ return++ mode = entry.get("mode")+ if mode not in {"live", "deterministic"}:+ raise VerdictQualityError(f"{name}: mode must be 'live' or 'deterministic', not {mode!r}")++ if mode == "live" and not entry.get("llm_calls_placed"):+ raise VerdictQualityError(+ f"{name}: claims a live measurement with llm_calls_placed={entry.get('llm_calls_placed')!r}. "+ "Triage falls through to a deterministic scorer on a provider error, so a run against a "+ "dead endpoint yields a full set of verdicts and a normal-looking scorecard. That is the "+ "one thing this gate exists to refuse."+ )++ if entry.get("balanced_accuracy") is None:+ raise VerdictQualityError(f"{name}: measured row carries no balanced_accuracy")+++def render_table(scorecard: dict[str, Any]) -> str:+ """Render the published block from the committed scorecard."""+ entries: list[dict[str, Any]] = list(scorecard.get("entries") or [])+ if not entries:+ raise VerdictQualityError("the scorecard holds no entries; refusing to publish an empty table")+ for entry in entries:+ validate_entry(entry)++ corpus = scorecard.get("corpus") or {}+ lines: list[str] = [+ BEGIN,+ "",+ f"Corpus: **{corpus.get('items', '?')} items** in "+ f"**{corpus.get('pairs', '?')} twin pairs** "+ f"(`{corpus.get('name', 'verdict_corpus_v1')}`, digest `{corpus.get('digest', '?')}`). "+ "Twins share title, rule, severity, vendor and technique and differ only in the evidence, "+ "so severity alone separates nothing and a constant answer scores at most "+ f"**{_fmt(corpus.get('constant_answer_ceiling'))}**. Hand-authored and synthetic: "+ "no recorded customer telemetry is involved.",+ "",+ "| Model | Mode | Balanced accuracy | MCC | Malicious recall | Abstention | Hallucination rate | Calls placed |",+ "|---|---|---|---|---|---|---|---|",+ ]++ for entry in entries:+ name = f"`{entry['model']}`"+ if entry.get("measured") is False:+ reason = entry["not_measured_reason"].strip().rstrip(".")+ # One spanning cell, not six copies of the same phrase: a reader+ # scanning the column must not see something that parses as a+ # score. The reason sits where the first number would.+ lines.append(f"| {name} | – | {NOT_MEASURED} — {reason} | – | – | – | – | 0 |")+ continue+ lines.append(+ "| {model} | {mode} | {ba} | {mcc} | {recall} | {abst} | {halluc} | {calls} |".format(+ model=name,+ mode=entry["mode"],+ ba=_fmt(entry.get("balanced_accuracy")),+ mcc=_fmt(entry.get("matthews_corrcoef")),+ recall=(+ f"{_fmt(entry.get('malicious_recall'))} / {entry.get('malicious_support', '?')}"+ if entry.get("malicious_recall") is not None+ else "–"+ ),+ abst=_fmt(entry.get("abstention_rate")),+ halluc=_fmt(entry.get("hallucination_rate")),+ calls=entry.get("llm_calls_placed") or 0,+ )+ )++ measured = [e for e in entries if e.get("measured") is not False]+ lines += [+ "",+ f"Malicious recall prints the count behind it: a rate over {measured[0].get('malicious_support', '?')} "+ "cases is a different claim from the same rate over four, and the figure alone cannot say which. "+ "Every measured row placed the model calls shown in the last column; a row that placed none is "+ "refused rather than published, because triage answers from a deterministic scorer when a "+ "provider fails and the resulting scorecard looks entirely normal."+ if measured+ else "",+ "",+ ]+ if winner := scorecard.get("default_model"):+ lines += [+ f"**Shipped default: `{winner}`.** " + (scorecard.get("default_rationale") or "").strip(),+ "",+ ]+ lines.append(END)+ return "\n".join(line for line in lines if line is not None)+++def splice(markdown: str, block: str) -> str:+ """Replace the delimited block, leaving the rest of the page untouched."""+ if BEGIN not in markdown or END not in markdown:+ raise VerdictQualityError(f"{BENCHMARK_PATH} carries no {BEGIN} / {END} block to fill")+ head, _, rest = markdown.partition(BEGIN)+ _, _, tail = rest.partition(END)+ return head + block + tail+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--check", action="store_true", help="Fail when the published block is stale or dishonest.")+ parser.add_argument("--write-benchmark", action="store_true", help="Rewrite the block from the scorecard.")+ parser.add_argument("--scorecard", type=Path, default=None)+ parser.add_argument("--benchmark-md", type=Path, default=None)+ args = parser.parse_args(argv)++ root = repo_root()+ scorecard_path = args.scorecard or (root / SCORECARD_PATH)+ benchmark_path = args.benchmark_md or (root / BENCHMARK_PATH)++ if not scorecard_path.exists():+ print(f"verdict-quality: no scorecard at {scorecard_path}", file=sys.stderr)+ return 1++ try:+ scorecard = json.loads(scorecard_path.read_text(encoding="utf-8"))+ block = render_table(scorecard)+ except VerdictQualityError as exc:+ print(f"verdict-quality: REFUSED — {exc}", file=sys.stderr)+ return 1++ markdown = benchmark_path.read_text(encoding="utf-8")+ try:+ updated = splice(markdown, block)+ except VerdictQualityError as exc:+ print(f"verdict-quality: {exc}", file=sys.stderr)+ return 1++ if args.write_benchmark:+ benchmark_path.write_text(updated, encoding="utf-8")+ print(f"verdict-quality: wrote the block into {benchmark_path}")+ return 0++ if args.check:+ if updated != markdown:+ print(+ "verdict-quality: the published block does not match the committed scorecard.\n"+ " Regenerate it with: python3 scripts/check_verdict_quality.py --write-benchmark",+ file=sys.stderr,+ )+ return 1+ print("verdict-quality: OK — the published table matches the committed scorecard")+ return 0++ print(block)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/run_replay_eval.py b/scripts/run_replay_eval.pynew file mode 100644index 000000000..dd2482521--- /dev/null+++ b/scripts/run_replay_eval.py@@ -0,0 +1,429 @@+#!/usr/bin/env python3+"""`make replay-eval` — grade AiSOC on your own closed alerts, on your host.++Phase 1.5, the design-partner kit. One command: it reads a window of+closed findings out of your SIEM through the readers in+`services/actions/app/services/alert_history.py`, replays them through+the same triage path a live alert takes, scores the result against what+your analysts actually decided, and writes one signed file.++What this program is *not* is a second implementation of any of that. It+drives `POST /api/v1/evaluations/replay`, which is the same job the+console's **Evaluate on your history** page and the `aisoc replay` CLI+start. A kit with its own reader, its own runner or its own scorer would+measure itself rather than the product, and would stop measuring the+product the first time one of them changed. Everything original here is+about the artefact: what it contains, that it cannot have been altered,+and that running it did not send your estate to anybody.++Egress is decided by what answered, not by what was configured+-------------------------------------------------------------+A preflight that reads a config file and concludes "this deployment uses+a local model" is a claim about an intention. This program instead reads+the models the run actually resolved, out of the score, and refuses to+write a bundle if a hosted model answered and `--hosted` was not passed.++There is a third state and it is the honest one to get right. Calling a+local Ollama directly, rather than through the bundled gateway, places+real model calls that carry no attribution header, so the run knows calls+happened and cannot name the model. That is recorded as `unverified` and+never as `none`: "nothing left your estate" and "I could not tell what+answered" are different facts, and only one of them is a privacy claim.++Nothing is written to your deployment. The replay runs in shadow mode,+and the count of writes it intercepted travels in the bundle so that a+replay that quietly stopped replaying can be told from one whose writes+were suppressed.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+from pathlib import Path+from typing import Any++REPO_ROOT = Path(__file__).resolve().parents[1]+# The bundle builder and the verifier live in the API tree, which is also+# where the vault and the redactor live. Importing one service's `app` is+# fine; importing two is not, because all three name their package `app`.+sys.path.insert(0, str(REPO_ROOT / "services" / "api"))++from app.services.evidence_bundle import ( # noqa: E402+ BundleVerificationError,+ canonical_bytes,+ verify_bundle,+)+from app.services.replay_evaluation.bundle import ( # noqa: E402+ build_replay_bundle,+ replay_bundle_filename,+)++#: Provider prefixes that run on hardware the partner controls. A model id+#: with none of these, and that is not the deterministic tier, is treated+#: as hosted — the safe direction, because a provider this list has not+#: heard of is more likely to be a new hosted one than a new local one.+LOCAL_PROVIDER_PREFIXES = (+ "ollama/",+ "ollama_chat/",+ "vllm/",+ "lm_studio/",+ "llamafile/",+ "text-completion-openai/",+ "huggingface/",+ "local/",+)++#: Not a model. Triage's offline floor, which places no call at all.+DETERMINISTIC = "deterministic"++DEFAULT_POLL_SECONDS = 5.0+DEFAULT_TIMEOUT_SECONDS = 3600.0+++class ReplayEvalError(RuntimeError):+ """Something the operator can act on. Printed without a traceback."""+++# --------------------------------------------------------------------------+# Talking to the deployment+# --------------------------------------------------------------------------+++def _request(method: str, url: str, *, token: str, payload: dict | None = None, timeout: float = 120.0) -> Any:+ # urllib honours `file://`, `ftp://` and friends, so a base URL that+ # arrives from a flag or the environment can turn an HTTP client into a+ # file reader. Refuse anything that is not HTTP(S) before opening it,+ # rather than trusting the caller to have passed a URL at all.+ scheme = urllib.parse.urlsplit(url).scheme.lower()+ if scheme not in ("http", "https"):+ raise ReplayEvalError(+ f"refusing to request {url!r}: --api-url must be http:// or https://, got {scheme or 'no'} scheme. "+ "urllib would otherwise read local files through a file:// URL."+ )++ body = json.dumps(payload).encode("utf-8") if payload is not None else None+ request = urllib.request.Request(url, data=body, method=method)+ request.add_header("Authorization", f"Bearer {token}")+ if body is not None:+ request.add_header("Content-Type", "application/json")++ try:+ # The scheme is checked against an allow-list at the top of this+ # function, which is the condition the rule exists to ask for. It+ # matches on the call shape and cannot see a guard, so the+ # suppression is scoped to this one line: any *other* urlopen added+ # to this file still fails the scan.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 - scheme checked above+ raw = response.read().decode("utf-8")+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", "replace")[:400]+ raise ReplayEvalError(f"{method} {url} answered HTTP {exc.code}: {detail}") from exc+ except urllib.error.URLError as exc:+ raise ReplayEvalError(+ f"could not reach AiSOC at {url}: {exc.reason}. Is the stack up? `make status` shows what is running."+ ) from exc++ return json.loads(raw) if raw else None+++def _start_run(base: str, token: str, args: argparse.Namespace) -> str:+ payload: dict[str, Any] = {"connector_id": args.connector_id, "vendor": args.vendor}+ if args.since:+ payload["window_start"] = args.since+ if args.until:+ payload["window_end"] = args.until+ if args.train_fraction is not None:+ payload["train_fraction"] = args.train_fraction++ started = _request("POST", f"{base}/api/v1/evaluations/replay", token=token, payload=payload)+ run_id = (started or {}).get("id")+ if not run_id:+ raise ReplayEvalError(f"the replay job did not return an id; it answered {started!r}")+ return str(run_id)+++def _await_run(base: str, token: str, run_id: str, *, timeout: float, poll: float) -> dict[str, Any]:+ deadline = time.monotonic() + timeout+ last = ""+ while time.monotonic() < deadline:+ state = _request("GET", f"{base}/api/v1/evaluations/replay/{run_id}", token=token) or {}+ status = str(state.get("status") or "")+ if status != last:+ print(f" {status}", file=sys.stderr)+ last = status+ if status == "completed":+ return state+ if status == "failed":+ raise ReplayEvalError(f"the replay failed: {state.get('error') or 'no reason was recorded'}")+ time.sleep(poll)++ raise ReplayEvalError(+ f"the replay did not finish within {timeout:.0f}s. It is still running: collect it later with "+ f"`--collect {run_id}`, or raise --timeout."+ )+++# --------------------------------------------------------------------------+# Egress+# --------------------------------------------------------------------------+++def _is_local(model: str) -> bool:+ lowered = model.strip().lower()+ if not lowered or lowered == DETERMINISTIC:+ return True+ return lowered.startswith(LOCAL_PROVIDER_PREFIXES)+++def classify_egress(score: dict[str, Any]) -> dict[str, Any]:+ """What left the estate, read from the models that actually answered.++ Three states, because collapsing the third into the first is the+ mistake that would turn a measurement into a false privacy claim.+ """+ models = [str(m) for m in (score.get("models") or [])]+ calls = int(score.get("llm_calls") or 0)+ hosted = sorted({m for m in models if not _is_local(m)})++ if hosted:+ return {+ "egress": "hosted",+ "hosted_models": hosted,+ "models": sorted(set(models)),+ "llm_calls": calls,+ "note": (+ "A hosted model answered, so the alert content triage reasoned over was sent to that provider, "+ "exactly as it is during live triage."+ ),+ }++ if calls > 0 and not models:+ return {+ "egress": "unverified",+ "hosted_models": [],+ "models": [],+ "llm_calls": calls,+ "note": (+ f"{calls} model call(s) were placed and none carried an attribution header, which is what a direct "+ f"call to a local runtime looks like when it does not go through the bundled gateway. This run "+ f"cannot prove which model answered, so it does not claim nothing left your estate. Route through "+ f"the gateway to have the model recorded."+ ),+ }++ if calls == 0:+ return {+ "egress": "none",+ "hosted_models": [],+ "models": sorted(set(models)),+ "llm_calls": 0,+ "note": (+ "No model call was placed at all: every verdict came from the deterministic floor. Nothing left "+ "your estate, and nothing measured a model either."+ ),+ }++ return {+ "egress": "none",+ "hosted_models": [],+ "models": sorted(set(models)),+ "llm_calls": calls,+ "note": "Every model that answered runs on hardware you control.",+ }+++# --------------------------------------------------------------------------+# Commands+# --------------------------------------------------------------------------+++def _signing_key() -> str:+ key = os.environ.get("AISOC_REPLAY_SIGNING_KEY") or os.environ.get("SECRET_KEY") or ""+ if not key:+ raise ReplayEvalError(+ "no signing key. Set AISOC_REPLAY_SIGNING_KEY (or SECRET_KEY) to this deployment's secret so the "+ "bundle can be verified here later. Signing with a default would produce a file that verifies for "+ "anyone, which is worse than an unsigned one because it reads as tamper-evident."+ )+ return key+++def command_run(args: argparse.Namespace) -> int:+ base = args.api_url.rstrip("/")+ token = args.api_key or os.environ.get("AISOC_API_KEY") or ""+ if not token:+ raise ReplayEvalError("no credential. Pass --api-key or set AISOC_API_KEY. The tenant comes from the key.")+ key = _signing_key()++ if args.collect:+ run_id = args.collect+ print(f"Collecting replay {run_id}", file=sys.stderr)+ else:+ if not args.connector_id:+ raise ReplayEvalError("--connector-id is required. `aisoc connectors list` shows the ones you have saved.")+ print(f"Starting a replay against connector {args.connector_id}", file=sys.stderr)+ run_id = _start_run(base, token, args)++ # Everything past this point can fail on something that has nothing to do+ # with the replay — a credential that expires while a long window is+ # being graded is the ordinary case, not an exotic one. The run is server+ # side and survives, so the id and the command that resumes it are worth+ # more to the operator than the error alone.+ try:+ state = _await_run(base, token, run_id, timeout=args.timeout, poll=args.poll)++ report = _request("GET", f"{base}/api/v1/evaluations/replay/{run_id}/export?format=json", token=token) or {}+ score = dict(report.get("score") or {})+ method = dict(report.get("method") or {})+ if not score:+ raise ReplayEvalError("the completed run carried no score; there is nothing to publish")+ except ReplayEvalError as exc:+ raise ReplayEvalError(+ f'{exc}\n\nThe run itself is server side and was not lost. Collect it with:\n make replay-eval ARGS="--collect {run_id}"'+ ) from exc++ egress = classify_egress(score)+ if egress["egress"] == "hosted" and not args.hosted:+ raise ReplayEvalError(+ "refusing to write a bundle: a hosted model answered ("+ + ", ".join(egress["hosted_models"])+ + ") and --hosted was not passed. The kit runs air-gapped on a local model by default. If you meant "+ "to use your own hosted key, re-run with --hosted; the bundle will record that the content was sent."+ )++ items = None+ if args.export_items:+ decisions = _request("GET", f"{base}/api/v1/evaluations/replay/{run_id}/decisions", token=token)+ # The route answers a bare array. Accept the enveloped shapes too+ # rather than pinning the one this was written against: a kit that+ # breaks on a route growing an envelope is a kit nobody can upgrade.+ if isinstance(decisions, list):+ items = decisions+ elif isinstance(decisions, dict):+ items = decisions.get("items") or decisions.get("decisions") or []+ else:+ raise ReplayEvalError(f"the decisions route answered {type(decisions).__name__}, which this kit cannot read")+ print(f" exporting {len(items)} decision row(s), redacted", file=sys.stderr)++ bundle = build_replay_bundle(+ score=score,+ method=method,+ model=egress,+ items=items,+ signing_key=key,+ evaluation_id=run_id,+ tenant_id=str(state.get("tenant_id") or ""),+ )++ out = Path(args.output) if args.output else Path(replay_bundle_filename(run_id))+ out.write_bytes(canonical_bytes(bundle))++ # Every rate prints the count it was computed over. `0.0` beside a bare+ # `graded 0` reads as a broken run; `0.0 over 40 malicious cases, 40+ # abstained` is the same number saying what actually happened, which is+ # that the agent routed every one of them to a human rather than missing+ # them silently. The full report states this at length; a one-screen+ # summary that dropped the denominator would be the surface that+ # disagrees with it.+ graded = score.get("graded")+ recall = score.get("malicious_recall")+ support = score.get("malicious_support") or 0+ abstained = score.get("abstained") or 0+ recall_line = (+ f"{recall:.3f} over {support} malicious case(s)"+ if recall is not None+ else f"not measured — {support} malicious case(s) in the window"+ )+ print(f"\nWrote {out}", file=sys.stderr)+ print(f" decisions {score.get('decisions')} ({score.get('labelled')} labelled, {abstained} abstained)", file=sys.stderr)+ print(f" graded {graded}", file=sys.stderr)+ print(f" malicious recall {recall_line}", file=sys.stderr)+ print(f" egress {egress['egress']} — {egress['note']}", file=sys.stderr)+ print(f" items {'included, redacted' if items is not None else 'withheld (pass --export-items)'}", file=sys.stderr)+ print(f"\nVerify it with:\n python3 scripts/run_replay_eval.py verify {out}", file=sys.stderr)+ return 0+++def command_verify(args: argparse.Namespace) -> int:+ path = Path(args.path)+ if not path.is_file():+ raise ReplayEvalError(f"no such bundle: {path}")+ key = _signing_key()++ try:+ bundle = json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise ReplayEvalError(f"{path} is not valid JSON: {exc}") from exc++ try:+ payload = verify_bundle(bundle, signing_key=key)+ except BundleVerificationError as exc:+ print(f"FAIL: {exc}", file=sys.stderr)+ return 1++ scores = payload.get("scores") or {}+ model = payload.get("model") or {}+ print(f"OK: {path} verifies against this deployment's key")+ print(f" schema {payload.get('bundle_schema_version')}")+ print(f" generated {payload.get('generated_at')}")+ print(f" graded {scores.get('graded')}")+ print(f" malicious recall {scores.get('malicious_recall') if scores.get('malicious_recall') is not None else 'not measured'}")+ print(f" egress {model.get('egress')}")+ print(f" items {'included' if 'items' in payload else 'withheld'}")+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="run_replay_eval.py", description=__doc__.split("\n")[0])+ sub = parser.add_subparsers(dest="command")++ run = sub.add_parser("run", help="read history, replay it, write a signed bundle")+ run.add_argument("--api-url", default=os.environ.get("AISOC_API_URL", "http://localhost:8000"))+ run.add_argument("--api-key", default=None, help="defaults to $AISOC_API_KEY. The tenant comes from the key.")+ run.add_argument("--connector-id", default=os.environ.get("AISOC_REPLAY_CONNECTOR_ID"))+ run.add_argument("--vendor", default=None, help="override the vendor inferred from the connector")+ run.add_argument("--since", default=None, help="ISO-8601. Pin the window, or a second run covers a different one.")+ run.add_argument("--until", default=None, help="ISO-8601")+ run.add_argument("--train-fraction", type=float, default=None)+ run.add_argument("--output", default=None)+ run.add_argument(+ "--export-items",+ action="store_true",+ help="include per-decision rows, redacted. Without it only aggregates travel.",+ )+ run.add_argument(+ "--hosted",+ action="store_true",+ help="permit a hosted model. Without it the run is refused if one answered.",+ )+ run.add_argument("--collect", default=None, help="collect a run started earlier, by id")+ run.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT_SECONDS)+ run.add_argument("--poll", type=float, default=DEFAULT_POLL_SECONDS)+ run.set_defaults(handler=command_run)++ verify = sub.add_parser("verify", help="check a bundle has not been altered")+ verify.add_argument("path")+ verify.set_defaults(handler=command_verify)++ args = parser.parse_args(argv)+ if not getattr(args, "handler", None):+ parser.print_help()+ return 2++ try:+ return int(args.handler(args))+ except ReplayEvalError as exc:+ print(f"\nFAIL: {exc}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/run_verdict_eval.py b/scripts/run_verdict_eval.pynew file mode 100644index 000000000..8ab2194a0--- /dev/null+++ b/scripts/run_verdict_eval.py@@ -0,0 +1,479 @@+#!/usr/bin/env python3+"""Grade production triage against the balanced verdict corpus.++Depth plan 1.4. The corpus is `services/agents/tests/eval_data/verdict/`+(item 1.1): 72 hand-authored items in 36 twin pairs, where each pair shares+its title, rule, severity, vendor and ATT&CK technique and differs *only* in+the evidence. Severity alone therefore separates nothing, and a constant+answer scores at most 0.500.++What this is, and what it deliberately is not+----------------------------------------------+It is a **corpus loader and an honesty gate** in front of two things that+already exist:++* the decision is produced by :meth:`ReplayRunner.replay_window`, which+ drives the production :meth:`FusedAlertTriageWorker.triage` behind the+ shadow sinks, so nothing is written and no second triage exists;+* the score is produced by :func:`scripts.score_replay_set.grade`, which+ delegates to :func:`aisoc_benchmark.replay.score_replay` and carries the+ `assert_gradeable` refusal.++There is no scoring in this file. A second definition of "verdict accuracy"+would drift from the one on the scoreboard, which is the defect the+alert-reduction suite already shipped once, where an in-test+reimplementation published a figure the product did not produce.++The leak this file exists to prevent+-------------------------------------+Corpus ids end in ``-B`` or ``-M``. The envelope builder puts the finding id+into ``raw_alert["id"]``, which is in the triage prompt, so replaying the+corpus under its own ids would hand the model a one-character answer key and+publish the result as accuracy. Every item is therefore replayed under an+**opaque id** derived by hash, and the true id is restored on the decision+afterwards, where only the grader sees it.++That is not left to care. :func:`assert_no_leak` re-reads the built envelope+and fails the run if any held-out value — the corpus names them in its own+``held_out_from_the_model`` header — is reachable anywhere inside it.++Refusing a run that measured nothing+-------------------------------------+Triage catches a provider error and falls through to its deterministic+scorer. A run against an unreachable gateway therefore produces a full set+of confident-looking verdicts and a report that looks entirely normal. This+refuses to publish one: ``--require-live`` (the default) fails when no+decision placed a model call. ``--deterministic`` runs that path on purpose+and labels the scorecard with it, so the floor can be published as a floor.++Run:++ python3 scripts/run_verdict_eval.py \\+ --model llama3.1:8b-instruct-q4_K_M \\+ --api-base http://127.0.0.1:11435/v1 \\+ --out /tmp/scorecard.json+"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import json+import logging+import os+import subprocess+import sys+import uuid+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++REPO_ROOT = Path(__file__).resolve().parents[1]+CORPUS = REPO_ROOT / "services" / "agents" / "tests" / "eval_data" / "verdict" / "verdict_corpus_v1.json"++sys.path.insert(0, str(REPO_ROOT / "packages" / "aisoc-benchmark"))+sys.path.insert(0, str(REPO_ROOT / "scripts"))+sys.path.insert(0, str(REPO_ROOT / "services" / "agents"))++#: The roles a triage run can reach. Pinned together, because pinning one+#: leaves the rest on their default and the scorecard would name a model+#: that answered some of the calls.+PIN_ROLES = ("triage", "investigation", "report", "recon", "summary", "copilot")++#: Namespace for the opaque alert ids. Fixed, so a given corpus item replays+#: under the same opaque id on every run and two scorecards are comparable+#: row by row.+_OPAQUE_NS = uuid.UUID("6f1d0a1e-9c3b-4f6a-8d2e-7b5c4a3f1e20")+++class VerdictEvalError(RuntimeError):+ """The run cannot produce a publishable number."""+++def quieten_logs(level: int = logging.WARNING) -> None:+ """Keep per-alert triage logging out of the report on stdout.++ The report is Markdown a caller redirects into a file, and 72 alerts of+ structlog output through the same stream corrupts it. Raised to WARNING+ rather than silenced: a provider error has to stay visible, because it+ is the thing that turns a live run into a deterministic one.+ """+ import structlog++ logging.basicConfig(level=level, stream=sys.stderr, force=True)+ structlog.configure(+ wrapper_class=structlog.make_filtering_bound_logger(level),+ logger_factory=structlog.PrintLoggerFactory(sys.stderr),+ )+++def opaque_alert_id(corpus_id: str) -> str:+ """A stable alert id that encodes nothing about the label.++ ``uuid5`` over a fixed namespace: deterministic, so the same item keeps+ the same id across runs and models, and one-way, so neither the ``-B``+ suffix nor the pair it belongs to survives into the prompt.+ """+ return str(uuid.uuid5(_OPAQUE_NS, corpus_id))+++def load_corpus(path: Path) -> dict[str, Any]:+ corpus = json.loads(path.read_text(encoding="utf-8"))+ items = corpus.get("decisions") or []+ if not items:+ raise VerdictEvalError(f"{path} carries no `decisions`")+ return corpus+++def corpus_digest(path: Path) -> str:+ """SHA-256 of the corpus bytes, so a published row names the data it used.++ Over the file as committed rather than over a normalised projection of+ it: the claim a reader checks is "this scorecard was produced from this+ file", and any re-serialisation would make that claim uncheckable.+ """+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def build_finding(item: dict[str, Any], *, closed_at: datetime) -> Any:+ """One corpus item as the finding shape replay already grades.++ Carries exactly the five fields the corpus README permits — ``evidence``,+ ``title``, ``severity``, ``vendor`` and ``rule_id`` — under an opaque id.+ The disposition rides along on the finding because the *grader* reads it+ off the decision; it never enters the envelope.+ """+ from app.replay.findings import HistoricalFinding++ return HistoricalFinding(+ vendor=str(item.get("vendor") or ""),+ finding_id=opaque_alert_id(str(item["id"])),+ title=str(item.get("title") or ""),+ disposition=str(item.get("expected_disposition") or "unlabeled"),+ vendor_disposition="",+ closed_at=closed_at,+ rule_id=item.get("rule_id"),+ severity=item.get("severity"),+ raw=dict(item.get("evidence") or {}),+ )+++class CorpusEnvelopeNormalizer:+ """Pass-through, because a corpus item is already the agent's input.++ :mod:`app.replay.normalize` refuses to ship a fallback normalizer, and+ it is right to: replaying a *customer's* vendor rows through a mapping+ production does not use would publish a number about a pipeline nobody+ runs. This is the other case. There is no vendor row here and no mapping+ to perform — the corpus authors ``evidence`` as the facts the agent is+ given, and the README says to pass exactly that.++ So this performs no field mapping at all. It hands the evidence back as+ ``raw_event`` and lets :func:`to_fused_envelope` assemble the message,+ which keeps the envelope construction identical to the replay path. The+ limit that creates is stated in the scorecard rather than hidden here:+ this measures triage's judgement on given evidence, and says nothing+ about any connector's mapping.+ """++ connector_id = "verdict-corpus"++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ return {"raw_event": dict(raw)}+++def _walk(node: Any) -> Any:+ """Every scalar reachable in a nested structure, keys included."""+ if isinstance(node, dict):+ for key, value in node.items():+ yield key+ yield from _walk(value)+ elif isinstance(node, (list, tuple)):+ for value in node:+ yield from _walk(value)+ else:+ yield node+++def assert_no_leak(envelope: dict[str, Any], item: dict[str, Any], held_out: list[str]) -> None:+ """Fail the run if a held-out value is reachable inside the envelope.++ Checked against the envelope that was actually built, not against the+ code that built it. A reviewer reading the builder can confirm it omits+ the answer today; only re-reading the output catches the field a later+ edit adds back.++ The corpus id is checked too. It is not in the corpus's own hold-out+ list because the list names *fields*, and the id is a leak for a+ different reason: its ``-B``/``-M`` suffix is the label.+ """+ reachable = {str(value) for value in _walk(envelope) if value not in (None, "")}++ if str(item["id"]) in reachable:+ raise VerdictEvalError(+ f"corpus id {item['id']!r} is reachable inside the envelope. Its suffix is the label, "+ "so the model would be able to read the answer off the alert id."+ )++ for field_name in held_out:+ if field_name in ("pair_id", "twin_of"):+ # Values, not names: a pair id is an id and would leak the twin.+ value = item.get(field_name)+ if value and str(value) in reachable:+ raise VerdictEvalError(f"held-out {field_name}={value!r} is reachable inside the envelope")+ continue+ value = item.get(field_name)+ if value in (None, "", [], {}):+ continue+ if isinstance(value, str):+ # Prose. Compare on a distinctive slice rather than exact+ # equality, so a value that was embedded into a longer string+ # is still caught.+ needle = value.strip()[:60].lower()+ haystack = json.dumps(envelope, sort_keys=True, default=str).lower()+ if needle and needle in haystack:+ raise VerdictEvalError(+ f"held-out field {field_name!r} is reachable inside the envelope. "+ "It states the analyst's reason, so a run that fed it to the model would measure nothing."+ )+ elif str(value) in reachable:+ raise VerdictEvalError(f"held-out field {field_name!r} is reachable inside the envelope")+++async def replay_corpus(+ corpus: dict[str, Any],+ *,+ tenant_id: str,+) -> tuple[list[dict[str, Any]], dict[str, int], int]:+ """Replay every item through production triage and return graded decisions.++ Also returns what the shadow writer intercepted. Those counts are+ evidence rather than a fault: :class:`ShadowTriageWriter` records what+ production *would* have written and performs none of it, so a non-zero+ count is the interception working. Zero would be the surprising reading —+ it would mean triage reached no persistence path at all.+ """+ from app.replay.normalize import to_fused_envelope+ from app.replay.runner import ReplayRunner+ from app.replay.shadow import ContextSnapshot++ items = corpus["decisions"]+ held_out = list(corpus.get("held_out_from_the_model") or [])+ authored = str(corpus.get("authored_at") or "2026-01-01")+ closed_at = datetime.fromisoformat(authored).replace(tzinfo=UTC)++ normalizer = CorpusEnvelopeNormalizer()+ findings = [build_finding(item, closed_at=closed_at) for item in items]++ # The leak check runs on the envelope the runner will build, assembled+ # here through the same function, before a single model call is placed.+ # Failing after a 72-item run would be a worse time to find out.+ for item, finding in zip(items, findings, strict=True):+ envelope = to_fused_envelope(+ finding,+ normalizer.normalize(dict(finding.raw)),+ tenant_id=tenant_id,+ connector_id=normalizer.connector_id,+ )+ assert_no_leak(envelope, item, held_out)++ runner = ReplayRunner(+ normalizer=normalizer,+ tenant_id=tenant_id,+ connector_id=normalizer.connector_id,+ )+ window = await runner.replay_window(+ findings,+ # Empty: a hand-authored corpus has no history, so there are no+ # priors, statements or skills to freeze. An empty frozen context is+ # the honest one — seeding priors here would score the ground truth.+ snapshot=ContextSnapshot(split_at=closed_at),+ )++ decisions: list[dict[str, Any]] = []+ for item, decision in zip(items, window.decisions, strict=True):+ row = decision.as_dict()+ # The true id is restored only now, on the record the grader reads.+ # It was never in the prompt.+ row["finding_id"] = str(item["id"])+ row["corpus_id"] = str(item["id"])+ row["opaque_alert_id"] = opaque_alert_id(str(item["id"]))+ row["pair_id"] = item.get("pair_id")+ row["family"] = item.get("family")+ row["is_synthetic"] = bool(item.get("is_synthetic"))+ decisions.append(row)+ return decisions, dict(window.writes_attempted), window.total_writes+++def git_commit() -> str:+ try:+ out = subprocess.run(+ ["git", "rev-parse", "HEAD"],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return "unknown"+ return out.stdout.strip() or "unknown"+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument(+ "--model",+ required=True,+ help=(+ "the model id to pin every role to, exactly as the endpoint at --api-base names it, "+ "e.g. llama3.1:8b-instruct-q4_K_M. A LiteLLM routing prefix such as ollama_chat/ "+ "belongs only in front of a LiteLLM gateway: an OpenAI-compatible server answers 404 "+ "for it, triage swallows that into its deterministic fallback, and the run is refused "+ "for measuring nothing."+ ),+ )+ parser.add_argument("--api-base", default=os.getenv("OPENAI_BASE_URL") or "", help="OpenAI-compatible base URL the model is served at")+ parser.add_argument(+ "--api-key",+ default=os.getenv("OPENAI_API_KEY") or "",+ help="key for that endpoint; local servers accept any non-empty string",+ )+ parser.add_argument("--corpus", type=Path, default=CORPUS)+ parser.add_argument("--out", type=Path, help="write the scorecard JSON here")+ parser.add_argument("--decisions-out", type=Path, help="write the per-item decisions here (stays local by default)")+ parser.add_argument("--tenant-id", default="00000000-0000-0000-0000-0000000000de")+ parser.add_argument(+ "--deterministic",+ action="store_true",+ help="run the offline deterministic path on purpose and label the scorecard as such",+ )+ parser.add_argument(+ "--allow-no-llm",+ action="store_true",+ help="do not refuse a run that placed no model call. Only honest with --deterministic.",+ )+ parser.add_argument("--verbose", action="store_true", help="keep per-alert triage logging on stderr")+ args = parser.parse_args(argv)++ quieten_logs(logging.DEBUG if args.verbose else logging.WARNING)++ if args.model and not args.deterministic:+ for role in PIN_ROLES:+ os.environ[f"AISOC_MODEL_PIN_{role.upper()}"] = args.model+ if args.api_base:+ os.environ["OPENAI_BASE_URL"] = args.api_base+ os.environ["AISOC_LLM_API_BASE"] = args.api_base+ if args.api_key:+ os.environ["OPENAI_API_KEY"] = args.api_key++ corpus = load_corpus(args.corpus)++ try:+ decisions, writes_intercepted, total_intercepted = asyncio.run(replay_corpus(corpus, tenant_id=args.tenant_id))+ except VerdictEvalError as exc:+ print(f"verdict-eval: REFUSED — {exc}", file=sys.stderr)+ return 2++ llm_calls = sum(int(d.get("llm_calls") or 0) for d in decisions)+ answered_by_model = sum(1 for d in decisions if d.get("resolved_models"))+ errored = sum(1 for d in decisions if d.get("error"))++ live = llm_calls > 0+ if not live and not (args.deterministic or args.allow_no_llm):+ print(+ "verdict-eval: REFUSED — not one decision placed a model call, so this run measured the "+ "deterministic fallback and not the model. Triage catches a provider error and falls through "+ "to its offline scorer, which is why the report would otherwise look entirely normal. "+ "Fix the endpoint, or pass --deterministic to publish the floor as a floor.",+ file=sys.stderr,+ )+ return 2++ from score_replay_set import CorpusNotGradeable, grade++ model_label = "deterministic" if args.deterministic else args.model+ try:+ report = grade(+ decisions,+ model=model_label,+ dataset=str(corpus.get("corpus_id") or "aisoc-verdict-v1"),+ commit=git_commit(),+ synthetic=True,+ )+ except CorpusNotGradeable as exc:+ print(f"verdict-eval: REFUSED — {exc}", file=sys.stderr)+ return 2++ score = report["score"]+ scorecard = {+ "model": model_label,+ "api_base": args.api_base if live else None,+ "mode": "deterministic" if args.deterministic else "live",+ "dataset": report["dataset"],+ "corpus_digest": f"sha256:{corpus_digest(args.corpus)}",+ "corpus_items": len(decisions),+ "commit": report["commit"],+ "measured_at": datetime.now(UTC).strftime("%Y-%m-%d"),+ "synthetic": True,+ "provenance": report["provenance"],+ # The three numbers that decide whether the rest is worth reading.+ "llm_calls_placed": llm_calls,+ "decisions_answered_by_model": answered_by_model,+ "decisions_errored": errored,+ "resolved_models": score.get("models") or [],+ # Writes production would have made, every one intercepted. Published+ # because "side-effect free" is a claim, and this is the measurement+ # behind it.+ "writes_intercepted": total_intercepted,+ "writes_intercepted_by_sink": writes_intercepted,+ "limits": [+ # Parenthesised so the three fragments are visibly one element.+ # Bare adjacent literals inside a list are how a missing comma+ # silently merges two entries, which is exactly what the reader+ # of a limits list cannot afford to have happen.+ (+ "Measures triage's judgement on given evidence. The corpus authors each item as the "+ "facts the agent is handed, so no connector mapping is exercised and this says nothing "+ "about any vendor's field mapping."+ ),+ "Every item is hand-authored and synthetic. No recorded customer telemetry is involved.",+ "Latency is reported and never graded: it measures the host this ran on.",+ ],+ "balanced_accuracy": score.get("balanced_accuracy"),+ "matthews_corrcoef": score.get("matthews_corrcoef"),+ "majority_class_accuracy": score.get("majority_class_accuracy"),+ "headline_accuracy": score.get("headline_accuracy"),+ "malicious_support": score.get("malicious_support"),+ "malicious_recall": score.get("malicious_recall"),+ "malicious_recall_wilson": score.get("malicious_recall_wilson"),+ "malicious_precision": score.get("malicious_precision"),+ "false_negatives": score.get("false_negatives"),+ "false_negative_verdicts": score.get("false_negative_verdicts"),+ "abstention_rate": score.get("abstention_rate"),+ "auto_close_precision": score.get("auto_close_precision"),+ "auto_close_considered": score.get("auto_close_considered"),+ "hallucination_rate": score.get("hallucination_rate"),+ "indicators_checked": score.get("indicators_checked"),+ "expected_calibration_error": score.get("expected_calibration_error"),+ "time_to_verdict_p50_ms": score.get("time_to_verdict_p50_ms"),+ "time_to_verdict_p95_ms": score.get("time_to_verdict_p95_ms"),+ "total_tokens": score.get("total_tokens"),+ }++ if args.out:+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(json.dumps(scorecard, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ if args.decisions_out:+ args.decisions_out.parent.mkdir(parents=True, exist_ok=True)+ args.decisions_out.write_text(json.dumps(decisions, indent=2, sort_keys=True) + "\n", encoding="utf-8")++ print(report["report_markdown"])+ print()+ print(f"verdict-eval: model={model_label} mode={scorecard['mode']} llm_calls={llm_calls} errored={errored}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/app/replay/runner.py b/services/agents/app/replay/runner.pyindex e66b24965..425da9892 100644--- a/services/agents/app/replay/runner.py+++ b/services/agents/app/replay/runner.py@@ -61,6 +61,7 @@ __all__ = ["ReplayRun","ReplayRunner","TimeSplit",+ "WindowReplay","split_by_time",]@@ -179,6 +180,17 @@ class ReplayDecision:tool_calls: int = 0resolved_models: list[str] = field(default_factory=list)++ #: Model calls this decision actually placed, priced or not.+ #:+ #: The one number that separates "the model answered" from "the+ #: deterministic fallback answered". Triage catches a provider error and+ #: falls through to its offline scorer, so a run against an unreachable+ #: gateway produces a full set of confident-looking verdicts and a+ #: perfectly ordinary-looking report. `resolved_models` goes empty in that+ #: case and is the signal a reader would have to notice; this is the same+ #: fact as a count, so a harness can refuse the run instead.+ llm_calls: int = 0tokens: int = 0measured_usd: float | None = Noneestimated_usd: float | None = None@@ -207,6 +219,7 @@ class ReplayDecision:"evidence": self.evidence,"tool_calls": self.tool_calls,"resolved_models": list(self.resolved_models),+ "llm_calls": self.llm_calls,"tokens": self.tokens,"measured_usd": self.measured_usd,"estimated_usd": self.estimated_usd,@@ -216,6 +229,24 @@ class ReplayDecision:}+@dataclass(frozen=True)+class WindowReplay:+ """What replaying one set of findings produced, before anything scores it.++ Separate from :class:`ReplayRun` because a window has no split. The+ time split is a property of *history* — it exists so an operator asking+ "would this have worked last quarter" gets an answer about a contiguous+ period. A hand-authored corpus has no close times to cut on, and+ manufacturing some so the shape fits would put an invented timestamp+ into the method note of every report that used it.+ """++ decisions: list[ReplayDecision]+ writes_attempted: dict[str, int]+ total_writes: int+ cutoff_context: dict[str, Any]++@dataclassclass ReplayRun:"""A completed replay: the decisions, the split, and how it was produced."""@@ -280,8 +311,33 @@ class ReplayRunner:f"{split.split_at.isoformat()}; a snapshot taken at a different instant is not a freeze")+ window = await self.replay_window(split.test, snapshot=frozen)+ return ReplayRun(+ decisions=window.decisions,+ split=split,+ snapshot=frozen,+ writes_attempted=window.writes_attempted,+ tenant_id=self._tenant_id,+ connector_id=self._connector_id,+ cutoff_context=window.cutoff_context,+ )++ async def replay_window(+ self,+ findings: Sequence[HistoricalFinding],+ *,+ snapshot: ContextSnapshot,+ ) -> WindowReplay:+ """Replay a set of findings through production triage, writing nothing.++ The working half of :meth:`run`, reachable without a time split so a+ corpus that has no history can be graded through the same path. There+ is deliberately no second decision-building loop anywhere: a harness+ that built its own would measure itself rather than the product, and+ would stop measuring the product the first time a prompt changed.+ """writer = ShadowTriageWriter()- reader = FrozenTriageContextReader(frozen)+ reader = FrozenTriageContextReader(snapshot)# The production worker, constructed exactly as the Kafka consumer# constructs it apart from the two sinks. `bootstrap_servers` is# required by the signature and unused: `triage()` never touches the@@ -294,7 +350,7 @@ class ReplayRunner:)decisions: list[ReplayDecision] = []- for finding in split.test:+ for finding in findings:decisions.append(await self._replay_one(worker, finding))logger.info(@@ -304,13 +360,10 @@ class ReplayRunner:decisions=len(decisions),writes_attempted=writer.total_writes,)- return ReplayRun(+ return WindowReplay(decisions=decisions,- split=split,- snapshot=frozen,writes_attempted=dict(writer.calls),- tenant_id=self._tenant_id,- connector_id=self._connector_id,+ total_writes=writer.total_writes,# Read after the window, not before: these totals are what the# cutoff sources did over the run.cutoff_context=reader.as_method_note(),@@ -372,6 +425,14 @@ class ReplayRunner:decision.estimated_usd = cost.get("estimated_usd")decision.unpriced_calls = int(cost.get("unpriced_calls") or 0)decision.resolved_models = [str(m) for m in (cost.get("resolved_models") or [])]+ # Every call the tracker saw, however it was priced. Summed from the+ # three priced/unpriced buckets rather than read off one of them: a+ # local model is unpriced, a hosted one is measured, and a harness+ # that counted only the priced calls would conclude an air-gapped run+ # placed none.+ decision.llm_calls = (+ int(cost.get("measured_calls") or 0) + int(cost.get("estimated_calls") or 0) + int(cost.get("unpriced_calls") or 0)+ )# Derived, not asserted. The literal `0` that stood here was the# correct answer -- shadow mode declines escalation, and escalation is# the only stage of this path that calls tools -- under a commentdiff --git a/services/api/app/_vendor/aisoc_benchmark/replay.py b/services/api/app/_vendor/aisoc_benchmark/replay.pyindex e7021d0d2..3b3b12e11 100644--- a/services/api/app/_vendor/aisoc_benchmark/replay.py+++ b/services/api/app/_vendor/aisoc_benchmark/replay.py@@ -295,6 +295,18 @@ class ReplayScore:mean_latency_ms: float | None = Nonep95_latency_ms: float | None = Nonemodels: list[str] = field(default_factory=list)+ #: Model calls the run placed, however they were priced.+ #:+ #: Separate from ``models`` because the two answer different questions and+ #: only one of them is always answerable. ``models`` is what the *gateway*+ #: said it billed, read off a LiteLLM response header, so it is empty on a+ #: run that talked straight to a provider -- an air-gapped Ollama, say --+ #: even though every call was placed and paid for in tokens. Reporting+ #: that state as "no model call was placed" is a false statement about the+ #: most important fact in the report, since triage answers from its+ #: deterministic fallback when a provider is unreachable and a run that+ #: measured nothing otherwise looks entirely normal.+ llm_calls: int = 0# ---- provenance ------------------------------------------------------bootstrap_resamples: int = BOOTSTRAP_RESAMPLES@@ -530,6 +542,7 @@ def score_replay(score.time_to_verdict_p50_ms = _percentile(latencies, 0.50)score.time_to_verdict_p95_ms = score.p95_latency_msscore.models = sorted({str(m) for d in decisions for m in (d.get("resolved_models") or [])})+ score.llm_calls = sum(int(d.get("llm_calls") or 0) for d in decisions)if not labelled:score.headline_withheld_reason = (@@ -697,6 +710,22 @@ def _ms(value: float | None) -> str:return "not measured" if value is None else f"{value:,.0f} ms"+def _models(score: ReplayScore) -> str:+ """Which model answered, distinguishing the two ways of not knowing.++ "No call was placed" and "calls were placed and the gateway did not say+ which model took them" are different facts with different remedies, and+ collapsing them prints the first when the second is true. That reads as+ a run that measured the deterministic fallback, which is the single most+ misleading thing this report could say about itself.+ """+ if score.models:+ return ", ".join(score.models)+ if score.llm_calls:+ return f"not attributed — {score.llm_calls} call(s) placed, but no gateway named the model that took them"+ return "none, no model call was placed"++def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None = None) -> str:"""Render the report as Markdown, malicious recall first.@@ -830,7 +859,8 @@ def format_replay_report(score: ReplayScore, *, method: dict[str, Any] | None =f"calls with no price at all: {score.unpriced_calls})",f"{LATENCY_LINE_PREFIX} {'not measured' if score.mean_latency_ms is None else f'{score.mean_latency_ms:.0f} ms'}, "f"p95 {'not measured' if score.p95_latency_ms is None else f'{score.p95_latency_ms:.0f} ms'}",- f"- Models: {', '.join(score.models) if score.models else 'none, no model call was placed'}",+ f"- Model calls placed: {score.llm_calls}",+ f"- Models: {_models(score)}","","## Method","",diff --git a/services/api/app/services/evidence_bundle.py b/services/api/app/services/evidence_bundle.pyindex ce0d4a9a9..4fe86ffcf 100644--- a/services/api/app/services/evidence_bundle.py+++ b/services/api/app/services/evidence_bundle.py@@ -87,6 +87,7 @@ __all__ = ["build_bundle","canonical_bytes","serialize_bundle",+ "sign_envelope","verify_bundle",]@@ -134,6 +135,43 @@ def _sign(payload: dict[str, Any], key: str) -> str:return hmac.new(key.encode("utf-8"), canonical_bytes(payload), hashlib.sha256).hexdigest()+def sign_envelope(payload: dict[str, Any], *, signing_key: str) -> dict[str, Any]:+ """The integrity block for any signed payload this tree exports.++ Public, and the only producer of one, so a second bundle format cannot+ arrive with a signature computed over a different serialisation than+ :func:`verify_bundle` recomputes. The replay evidence bundle carries a+ different payload shape and the same envelope for exactly that reason.++ Refuses an empty key rather than signing with one. An HMAC over the+ empty string is a valid signature that anybody can forge, and a bundle+ carrying one looks signed to every reader who does not check.+ """+ if not signing_key:+ raise ValueError(+ "refusing to sign with an empty key: the result would verify for anyone, which is worse "+ "than an unsigned bundle because it reads as tamper-evident"+ )+ digest = _digest(payload)+ return {+ "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 _hash_prompt(text: str | None) -> str | None:"""A prompt as a digest.@@ -305,28 +343,11 @@ def build_bundle(}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}],- }- ],- },+ "integrity": sign_envelope(payload, signing_key=signing_key),}diff --git a/services/api/app/services/replay_evaluation/bundle.py b/services/api/app/services/replay_evaluation/bundle.pynew file mode 100644index 000000000..72643f269--- /dev/null+++ b/services/api/app/services/replay_evaluation/bundle.py@@ -0,0 +1,452 @@+"""The signed, redacted artefact a design partner sends back.++Phase 1.5. `make replay-eval` runs a replay on the partner's own host and+writes one of these. It is the only thing that leaves their estate, so the+whole module is organised around one question: what is in a replay result+that a partner would not want to publish?++The answer is not "the item rows", which is the assumption that makes this+dangerous. Three fields in the **aggregate** carry free text lifted+verbatim from the partner's environment:++* ``per_rule[].key`` — their detection rule names, which describe their+ coverage and often their internal naming scheme;+* ``per_source[].key`` — the products they run;+* ``hallucinated_examples`` — indicator strings pulled out of the agent's+ own reasoning, so hostnames, internal domains and addresses, selected+ precisely because they looked like indicators.++So "aggregate only" is not a privacy control by itself, and a redaction+pass that ran only over exported items would have shipped all three. The+pass runs over everything, always, with no flag to disable it: the partner+already holds the unredacted report in their own API, and a bundle is by+definition the copy that travels.++Two passes, because the fields need different treatment and running one+over both would be wrong in both directions.++**Identifiers are replaced whole.** A rule name, a source name and a+finding id are each *entirely* an identifier, so they become ``RULE_1``,+``SOURCE_1``, ``FINDING_1``. Nothing is pattern-matched inside them. This+matters: :class:`Pseudonymizer` redacts hostnames only as FQDNs under an+internal suffix, so a rule named ``Suspicious PowerShell on FIN-DB-01``+passes through it unchanged, and rule names are full of bare short+hostnames, team names and internal project codenames. Tokenising the+whole value cannot miss a pattern because it matches no patterns.++**Free text is pattern-redacted**, because the agent's reasoning is the+thing a maintainer needs in order to tell a wrong verdict from a right+verdict reached for a wrong reason, and replacing it whole would leave+nothing to read. That pass is :class:`Pseudonymizer` — the same module+triage uses before it sends evidence to a hosted model, not a second+redactor written for this format — preceded by a literal substitution of+every identifier already tokenised, so a host named in a rule carries the+same token where it appears in the reasoning.++The limits of the second pass are stated in the bundle itself rather than+implied. It catches email addresses, internal FQDNs, private addresses,+filesystem paths and down-level logon names. It does not catch a bare+short hostname that appears nowhere but in prose, and it deliberately+keeps public domains and addresses, which are indicators rather than the+partner's property. A privacy note that overstated this would be worse+than none, because it is read by someone deciding what to send.++Both passes are reversible *locally*: the maps stay in the process that+built the bundle and are never written into it, so ``HOST_2`` is stable+within one bundle and meaningless outside it, and a reader can see that+two rows concern one host without learning which.++Signing is :func:`app.services.evidence_bundle.sign_envelope`, the same+integrity block an investigation bundle carries, so one verifier reads+both and a signature cannot be computed over a different serialisation+than the one checked.+"""++from __future__ import annotations++import re+import uuid+from collections.abc import Mapping, Sequence+from datetime import UTC, datetime+from typing import Any++from app._vendor.redactor import Pseudonymizer+from app.services.evidence_bundle import sign_envelope++__all__ = [+ "REPLAY_BUNDLE_SCHEMA_VERSION",+ "BundleRedactor",+ "ReplayBundleError",+ "build_replay_bundle",+ "redact_aggregate",+ "redact_items",+ "replay_bundle_filename",+]++#: This format's own version. Bumped when the payload shape changes in a+#: way a reader must notice.+REPLAY_BUNDLE_SCHEMA_VERSION = "1.0"++#: Dropped from an exported item rather than pseudonymized. `evidence` is+#: the whole alert body triage reasoned over — raw vendor fields, command+#: lines, file paths, request bodies. Pseudonymizing free-form vendor JSON+#: means trusting a regex set to have seen every shape a vendor emits, and+#: the honest answer is that it has not. The grading-relevant facts are+#: already in the verdict, the label and the confidence beside it.+_DROPPED_ITEM_FIELDS = frozenset({"evidence"})++#: Item fields carrying free text the agent wrote. Pseudonymized, not+#: dropped: the reasoning is the thing a maintainer needs in order to tell+#: a wrong verdict from a right verdict reached for a wrong reason.+_FREE_TEXT_ITEM_FIELDS = ("findings", "confidence_basis")++#: Item fields that identify a row in the partner's SIEM, and the token+#: kind each takes. Replaced whole, so two rows under one rule still group,+#: which is what makes an exported item set re-derivable into the same+#: confusion matrix.+_IDENTIFIER_ITEM_FIELDS = {"finding_id": "FINDING", "rule_id": "RULE"}++#: Aggregate segments keyed on partner-derived names, and the token kind+#: each takes. `per_rule` shares the `RULE` kind with the item field, so a+#: rule is the same token in the breakdown and in the rows behind it.+_AGGREGATE_SEGMENTS = {"per_rule": "RULE", "per_source": "SOURCE"}+++#: A word shaped like an internal host: alphanumeric segments joined by+#: hyphens, with at least one digit somewhere. `FIN-DB-01`, `web-03` and+#: `ip-10-2-3-4` match; `PowerShell`, `Suspicious` and `multi-factor` do+#: not, because a pattern that rewrote ordinary words in the agent's+#: reasoning would damage the thing the reasoning is exported for.+#:+#: Deliberately narrow, and deliberately not presented as complete: a host+#: named `atlas` is indistinguishable from a noun and is not matched. The+#: bundle's privacy block says so.+_HOST_SHAPED_RE = re.compile(r"\b(?=[A-Za-z0-9-]*\d)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)+\b")++#: Leading segments that make a host-shaped match public taxonomy rather+#: than a machine. `SHA-256`, `CVE-2026-1234`, `RFC-1918` and `AES-256` all+#: match the host shape and all must survive: they are the vocabulary the+#: agent reasons in, and a bundle whose reasoning says `HOST_4 hashing`+#: instead of `SHA-256 hashing` has been made unreadable to protect+#: nothing. Compared case-insensitively against the match's first segment.+_PUBLIC_TAXONOMY_PREFIXES = frozenset(+ {+ "aes",+ "arm",+ "base",+ "cve",+ "cwe",+ "capec",+ "des",+ "ec",+ "gmt",+ "hmac",+ "http",+ "https",+ "ieee",+ "iso",+ "md",+ "nist",+ "rfc",+ "rsa",+ "sha",+ "ssl",+ "tls",+ "utc",+ "utf",+ "x86",+ }+)++#: Minimum length for an identifier to be substituted back into free text.+#: Below this the literal is as likely to be a word as a name — a rule id of+#: ``s3`` would rewrite every mention of the service — and the substitution+#: would damage the reasoning it exists to preserve.+_MIN_SUBSTITUTABLE_LENGTH = 4+++class ReplayBundleError(RuntimeError):+ """A bundle could not be built. Carries why, never just None."""+++def _utc_iso(value: datetime | None = None) -> str:+ moment = value or datetime.now(UTC)+ if moment.tzinfo is None:+ moment = moment.replace(tzinfo=UTC)+ return moment.astimezone(UTC).isoformat()+++class BundleRedactor:+ """The two passes, sharing one map so tokens agree across sections.++ One instance per bundle. A per-section instance would emit three+ tokens for one host and destroy exactly the structure an export exists+ to preserve: that two rows concern the same thing.+ """++ def __init__(self, *, tenant_id: str = "") -> None:+ self._pseudonymizer = Pseudonymizer(tenant_id=tenant_id)+ self._identifiers: dict[tuple[str, str], str] = {}+ self._counters: dict[str, int] = {}++ def identifier(self, kind: str, value: object) -> str:+ """Replace a whole identifier with a stable token.++ Matches nothing inside the value, so it cannot miss a pattern.++ Host-shaped words *inside* the value are additionally registered+ for the free-text pass. A rule named ``Suspicious PowerShell on+ FIN-DB-01`` otherwise leaves ``FIN-DB-01`` readable everywhere the+ agent mentions it, because substituting the whole rule name cannot+ match the bare host inside a sentence, and the pattern redactor+ sees hostnames only as FQDNs under an internal suffix.+ """+ text = str(value)+ if not text:+ return text+ key = (kind, text)+ token = self._identifiers.get(key)+ if token is None:+ self._counters[kind] = self._counters.get(kind, 0) + 1+ token = f"{kind}_{self._counters[kind]}"+ self._identifiers[key] = token+ for host in _HOST_SHAPED_RE.findall(text):+ if host != text:+ self.identifier("HOST", host)+ return token++ def free_text(self, value: object) -> str:+ """Pattern-redact prose, after substituting identifiers already seen.++ Longest literal first, so a rule named ``FIN-DB-01 lateral`` is+ replaced before the host ``FIN-DB-01`` it contains and the result+ is not a token glued to a fragment of the longer name.+ """+ text = str(value)+ if not text:+ return text+ known = sorted(+ ((literal, token) for (_, literal), token in self._identifiers.items() if len(literal) >= _MIN_SUBSTITUTABLE_LENGTH),+ key=lambda pair: len(pair[0]),+ reverse=True,+ )+ for literal, token in known:+ text = text.replace(literal, token)+ text = self._redact_bare_hosts(text)+ return self._pseudonymizer.redact(text)++ def _redact_bare_hosts(self, text: str) -> str:+ """Replace host-shaped tokens the identifier pass never saw.++ The agent's own reasoning quotes machine names it pulled out of the+ event — ``Extracted 2 IOCs: ['198.51.100.7', 'WS-040']`` — and those+ names appear in no identifier field, so nothing registered them. The+ pseudonymizer below only rewrites qualified domain names, which a+ bare NetBIOS-style name is not. This is the leak a real partner+ bundle hits first, so the shape is matched directly here.++ Matches resolving to public taxonomy are left alone: see+ ``_PUBLIC_TAXONOMY_PREFIXES``.+ """++ def substitute(match: re.Match[str]) -> str:+ literal = match.group(0)+ head = re.split(r"[-_.]", literal, maxsplit=1)[0].lower()+ if head in _PUBLIC_TAXONOMY_PREFIXES:+ return literal+ # "HOST" exactly: the kind string is the counter's namespace, so+ # a lowercase spelling here would give the same machine two+ # different tokens depending on whether an identifier field or a+ # sentence mentioned it first, and the bundle would stop being+ # joinable across its own rows.+ return self.identifier("HOST", literal)++ return _HOST_SHAPED_RE.sub(substitute, text)+++def redact_aggregate(score: Mapping[str, Any], redactor: BundleRedactor, *, include_examples: bool = False) -> dict[str, Any]:+ """Redact the three aggregate fields carrying partner-derived text.++ Everything else in a score is a number, a count or a term from this+ repository's own fixed vocabulary, and is copied through unchanged. A+ pass that redacted every string would rewrite the class labels and the+ confusion-matrix axes, and a report whose classes read ``TOKEN_4``+ grades nothing.+ """+ redacted = dict(score)++ for segment, kind in _AGGREGATE_SEGMENTS.items():+ rows = redacted.get(segment)+ if not isinstance(rows, list):+ continue+ redacted[segment] = [+ {**row, "key": redactor.identifier(kind, row.get("key", ""))} if isinstance(row, Mapping) else row for row in rows+ ]++ # `hallucinated_examples` is item-level detail that leaked into the+ # aggregate: a list of indicator strings pulled out of the agent's+ # reasoning, selected *because* they looked like hostnames, domains and+ # addresses. The rate, the numerator and the denominator beside it carry+ # the whole analytic value for a reader of a shared artefact, so the+ # strings are withheld unless the partner is exporting item detail+ # anyway. They remain in the partner's own unredacted report.+ if "hallucinated_examples" in redacted:+ if include_examples:+ redacted["hallucinated_examples"] = [redactor.free_text(item) for item in redacted["hallucinated_examples"]]+ else:+ count = len(redacted["hallucinated_examples"]) if isinstance(redacted["hallucinated_examples"], list) else 0+ redacted["hallucinated_examples"] = []+ redacted["hallucinated_examples_withheld"] = count+ redacted["hallucinated_examples_note"] = (+ f"{count} example indicator(s) withheld. They are substrings of the agent's reasoning about your "+ f"estate, and no pattern set de-identifies free text reliably. The rate and its two counts are "+ f"above; the examples are in your own report. Export item detail to include them."+ )++ return redacted+++def redact_items(decisions: Sequence[Mapping[str, Any]], redactor: BundleRedactor) -> list[dict[str, Any]]:+ """One redacted row per decision, re-derivable into the same matrix.++ Keeps every field the scorer reads — the label, the verdict, the+ confidence, whether it errored — so a maintainer handed only this can+ recompute the aggregate and get the number in the same bundle. That+ property is what makes an export worth asking for; a row stripped to+ the point where the score cannot be checked is just a smaller leak.+ """+ rows: list[dict[str, Any]] = []+ for decision in decisions:+ row = {key: value for key, value in decision.items() if key not in _DROPPED_ITEM_FIELDS}++ for field, kind in _IDENTIFIER_ITEM_FIELDS.items():+ if row.get(field) is not None:+ row[field] = redactor.identifier(kind, row[field])++ for field in _FREE_TEXT_ITEM_FIELDS:+ value = row.get(field)+ if isinstance(value, list):+ row[field] = [redactor.free_text(item) for item in value]+ elif isinstance(value, str):+ row[field] = redactor.free_text(value)++ # An error string is a stack-adjacent message that can quote a host+ # or a URL. Kept, because "this row errored" is load-bearing for+ # reading the counts, and redacted for the same reason the+ # reasoning is.+ if isinstance(row.get("error"), str):+ row["error"] = redactor.free_text(row["error"])++ row["evidence_withheld"] = True+ rows.append(row)+ return rows+++def _redact_method(method: Mapping[str, Any], redactor: BundleRedactor) -> dict[str, Any]:+ """The method note, with the free text it carries redacted.++ `history.connector_type` is a connector id from this repository's own+ registry and stays readable — a bundle that hid which product was read+ could not be interpreted at all. `tenant_id` and `connector_id` are+ this deployment's own UUIDs and become tokens, because a bundle that+ travels should not name the instance it came from.+ """+ redacted = dict(method)++ for field, kind in (("tenant_id", "TENANT"), ("connector_id", "CONNECTOR")):+ if redacted.get(field):+ redacted[field] = redactor.identifier(kind, redacted[field])++ unread = redacted.get("frozen_context_unread")+ if isinstance(unread, list):+ redacted["frozen_context_unread"] = [redactor.free_text(item) for item in unread]++ return redacted+++def build_replay_bundle(+ *,+ score: Mapping[str, Any],+ method: Mapping[str, Any],+ model: Mapping[str, Any],+ signing_key: str,+ items: Sequence[Mapping[str, Any]] | None = None,+ evaluation_id: str | uuid.UUID | None = None,+ generated_at: datetime | None = None,+ tenant_id: str = "",+) -> dict[str, Any]:+ """Assemble, redact and sign one replay result.++ `items` is absent by default. Passing it is the partner's explicit+ choice to export per-decision detail; it is redacted either way, so+ the flag controls volume rather than whether the pass ran.++ A pure function of what it is handed: nothing here reads a database or+ an environment, which is what lets a test build one without a+ deployment and lets two exports of one run agree byte for byte.+ """+ if not score:+ raise ReplayBundleError("refusing to build a bundle with no score: an empty aggregate would publish as a run that graded nothing")++ # One redactor for the whole bundle, so a host appearing in a rule name,+ # in the reasoning and in an item row is the same token in all three.+ redactor = BundleRedactor(tenant_id=tenant_id)++ # Identifiers first. `redact_aggregate` registers every rule and source+ # name, so the free-text passes that follow can substitute them before+ # falling back to pattern matching.+ scores = redact_aggregate(score, redactor, include_examples=items is not None)+ redacted_items = redact_items(items, redactor) if items is not None else None++ payload: dict[str, Any] = {+ "bundle_schema_version": REPLAY_BUNDLE_SCHEMA_VERSION,+ "kind": "replay_evaluation",+ "evaluation_id": str(evaluation_id) if evaluation_id else None,+ "generated_at": _utc_iso(generated_at),+ "model": dict(model),+ "scores": scores,+ "method": _redact_method(method, redactor),+ "privacy": {+ "identifiers": "replaced whole with stable tokens (RULE_n, SOURCE_n, FINDING_n, TENANT_n, CONNECTOR_n)",+ "free_text": "pattern-redacted by app._vendor.redactor.Pseudonymizer, after substituting known identifiers",+ "free_text_catches": [+ "email addresses",+ "FQDNs under an internal suffix",+ "private IPv4 addresses",+ "Windows, UNC and multi-segment unix paths",+ "down-level logon names (DOMAIN\\user)",+ ],+ "free_text_does_not_catch": [+ "a single-word machine name carrying no digit and no separator, which is indistinguishable from an ordinary word",+ "a name whose leading segment collides with public taxonomy, such as a host literally named sha-1",+ "public domains and addresses, kept deliberately because they are indicators rather than your property",+ ],+ "reversible_locally": True,+ "mapping_exported": False,+ "mapping_note": (+ "Tokens are stable within this bundle and meaningless outside it. The map lives only in "+ "the process that produced the bundle and is never written to it, so two rows can be seen "+ "to concern one host without that host being named."+ ),+ "evidence_included": False,+ "evidence_note": (+ "Per-decision `evidence` is dropped rather than redacted. It is free-form vendor JSON, "+ "and redacting it would mean trusting a pattern set to have seen every shape a vendor emits."+ ),+ "items_included": items is not None,+ },+ }++ if redacted_items is not None:+ payload["items"] = redacted_items++ return {+ "payload": payload,+ # Outside the payload: a signature cannot cover itself.+ "integrity": sign_envelope(payload, signing_key=signing_key),+ }+++def replay_bundle_filename(evaluation_id: str | uuid.UUID) -> str:+ """A stable name, so two exports of one run overwrite rather than accumulate."""+ return f"aisoc-replay-{evaluation_id}.bundle.json"diff --git a/services/api/tests/test_replay_eval_bundle.py b/services/api/tests/test_replay_eval_bundle.pynew file mode 100644index 000000000..a8aee83c5--- /dev/null+++ b/services/api/tests/test_replay_eval_bundle.py@@ -0,0 +1,390 @@+"""The replay evidence bundle: what leaves the partner's estate.++Phase 1.5. Every test here is about one of three properties, because a+bundle that fails any of them is worse than no bundle: it does not carry+the partner's data, it cannot be altered without detection, and the+numbers in it can be re-derived by whoever receives it.++The leak tests assert on the **serialised bundle**, not on the field that+was redacted. Asserting that `per_rule[0]["key"] == "RULE_1"` passes while+the same rule name sits untouched three keys away, which is how a+redaction pass ships with a hole in it. `"FIN-DB-01" not in json.dumps(...)`+cannot pass that way.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime++import pytest+from app.services.evidence_bundle import BundleVerificationError, verify_bundle+from app.services.replay_evaluation.bundle import (+ REPLAY_BUNDLE_SCHEMA_VERSION,+ BundleRedactor,+ ReplayBundleError,+ build_replay_bundle,+ replay_bundle_filename,+)++#: A hostname in the shape real estates use, carried in three places a+#: replay result puts partner text: a rule name, an indicator example and+#: the agent's own reasoning.+HOST = "FIN-DB-01"+RULE = f"Suspicious PowerShell on {HOST}"+SIGNING_KEY = "a-deployment-signing-key"+++def _score() -> dict[str, object]:+ return {+ "decisions": 40,+ "graded": 36,+ "malicious_support": 31,+ "malicious_recall": 0.8125,+ "balanced_accuracy": 0.742,+ "hallucination_rate": 0.05,+ "hallucinated_total": 2,+ "indicators_checked": 40,+ "hallucinated_examples": [HOST, "evil.example.com"],+ "per_rule": [{"key": RULE, "graded": 12, "correct": 9, "accuracy": 0.75}],+ "per_source": [{"key": "splunk", "graded": 36, "correct": 27, "accuracy": 0.75}],+ "confusion": {"true_positive": {"true_positive": 26, "benign": 5}},+ }+++def _method() -> dict[str, object]:+ return {+ "tenant_id": "6f2b1f1e-0000-4000-8000-000000000001",+ "connector_id": "9c1d7a52-0000-4000-8000-000000000002",+ "history": {"vendor": "splunk", "findings_read": 40, "findings_labelled": 36},+ "split": {"train_fraction": 0.7},+ }+++def _items() -> list[dict[str, object]]:+ return [+ {+ "finding_id": "NB-00177",+ "rule_id": RULE,+ "vendor": "splunk",+ "expected_disposition": "true_positive",+ "verdict": "true_positive",+ "confidence": 0.91,+ "labelled": True,+ "findings": [f"{HOST} ran an encoded command and multi-factor was not used"],+ "confidence_basis": [f"the account signed in from 10.2.3.4 to {HOST}"],+ "evidence": {"host": HOST, "command_line": "powershell -enc SQBFAFgA", "user": "ACME\\priya"},+ "error": None,+ },+ {+ "finding_id": "NB-00178",+ "rule_id": RULE,+ "vendor": "splunk",+ "expected_disposition": "false_positive",+ "verdict": "benign",+ "confidence": 0.44,+ "labelled": True,+ "findings": ["the scheduled task is signed by the vendor"],+ "confidence_basis": [],+ "evidence": {"host": "WEB-07", "command_line": "updater.exe"},+ "error": None,+ },+ ]+++def _aggregate_bundle() -> dict:+ return build_replay_bundle(score=_score(), method=_method(), model={"id": "ollama_chat/llama3.2:3b"}, signing_key=SIGNING_KEY)+++def _item_bundle() -> dict:+ return build_replay_bundle(+ score=_score(),+ method=_method(),+ model={"id": "ollama_chat/llama3.2:3b"},+ items=_items(),+ signing_key=SIGNING_KEY,+ )+++# --------------------------------------------------------------------------+# What does not leave+# --------------------------------------------------------------------------++[email protected]("bundle_factory", [_aggregate_bundle, _item_bundle], ids=["aggregate", "with-items"])+def test_no_partner_identifier_survives_anywhere_in_the_bundle(bundle_factory) -> None:+ """Asserted over the whole serialised artefact, not per field."""+ serialised = json.dumps(bundle_factory())++ for secret in (HOST, RULE, "powershell -enc", "ACME\\priya", "10.2.3.4", "WEB-07"):+ assert secret not in serialised, f"{secret!r} survived redaction and would leave the partner's estate"+++def test_the_tenant_and_connector_this_came_from_are_not_named() -> None:+ serialised = json.dumps(_item_bundle())++ assert "6f2b1f1e" not in serialised+ assert "9c1d7a52" not in serialised+++def test_evidence_is_dropped_rather_than_redacted() -> None:+ """Free-form vendor JSON is not something a pattern set can be trusted over."""+ payload = _item_bundle()["payload"]++ for row in payload["items"]:+ assert "evidence" not in row+ assert row["evidence_withheld"] is True+ assert payload["privacy"]["evidence_included"] is False+++def test_indicator_examples_are_withheld_from_an_aggregate_bundle() -> None:+ """They are item-level detail that leaked into the aggregate.++ The rate and its two counts carry the analytic value; the strings are+ substrings of the agent's reasoning about the partner's estate.+ """+ scores = _aggregate_bundle()["payload"]["scores"]++ assert scores["hallucinated_examples"] == []+ assert scores["hallucinated_examples_withheld"] == 2+ # The measurement itself survives — withholding the examples must not+ # turn a measured rate into a missing one.+ assert scores["hallucination_rate"] == 0.05+ assert scores["indicators_checked"] == 40+++def test_exporting_items_is_what_includes_the_examples() -> None:+ scores = _item_bundle()["payload"]["scores"]++ assert scores["hallucinated_examples"], "exporting item detail should carry the examples through, redacted"+ assert HOST not in json.dumps(scores["hallucinated_examples"])+++def test_a_public_indicator_is_kept_because_it_is_not_the_partners_property() -> None:+ """The deliberate half of the trade-off, asserted so a change is visible."""+ scores = _item_bundle()["payload"]["scores"]++ # Equality against each element, never `in`: both a substring test over+ # the serialised blob and a containment test spelled with `in` would+ # also pass on `evil.example.com.attacker.test`, which is a different+ # host and the opposite of what this asserts.+ assert any(example == "evil.example.com" for example in scores["hallucinated_examples"])+++# --------------------------------------------------------------------------+# What survives, because a bundle nobody can read is not a deliverable+# --------------------------------------------------------------------------+++def test_the_scoring_vocabulary_is_not_redacted() -> None:+ """A report whose class labels read TOKEN_4 grades nothing."""+ scores = _item_bundle()["payload"]["scores"]++ assert "true_positive" in scores["confusion"]+ assert scores["confusion"]["true_positive"]["benign"] == 5+ assert scores["balanced_accuracy"] == 0.742+ assert scores["malicious_recall"] == 0.8125+++def test_ordinary_words_in_the_reasoning_survive() -> None:+ """The host pattern must not rewrite hyphenated English.++ `multi-factor` has a hyphen and no digit. A pattern that took it would+ damage the reasoning the export exists to carry.+ """+ findings = _item_bundle()["payload"]["items"][0]["findings"][0]++ assert "multi-factor was not used" in findings+ assert "ran an encoded command" in findings+++def test_one_rule_is_one_token_across_the_breakdown_and_the_rows() -> None:+ """Grouping is the property that makes an export re-derivable."""+ payload = _item_bundle()["payload"]++ rule_token = payload["scores"]["per_rule"][0]["key"]+ assert rule_token.startswith("RULE_")+ assert {row["rule_id"] for row in payload["items"]} == {rule_token}+++def test_two_findings_under_one_rule_keep_distinct_identities() -> None:+ payload = _item_bundle()["payload"]++ ids = [row["finding_id"] for row in payload["items"]]+ assert len(set(ids)) == 2, "distinct findings collapsed onto one token and the rows can no longer be told apart"+++def test_the_confusion_matrix_can_be_recomputed_from_the_exported_rows() -> None:+ """The point of exporting items: the receiver can check the aggregate."""+ rows = _item_bundle()["payload"]["items"]++ pairs = [(row["expected_disposition"], row["verdict"]) for row in rows]+ assert pairs == [("true_positive", "true_positive"), ("false_positive", "benign")]+++# --------------------------------------------------------------------------+# Integrity+# --------------------------------------------------------------------------+++def test_a_bundle_verifies_against_the_key_that_signed_it() -> None:+ bundle = _item_bundle()++ assert verify_bundle(bundle, signing_key=SIGNING_KEY) == bundle["payload"]+++def test_an_altered_score_is_detected() -> None:+ """The negative control for the whole format."""+ bundle = json.loads(json.dumps(_item_bundle()))+ bundle["payload"]["scores"]["malicious_recall"] = 1.0++ with pytest.raises(BundleVerificationError, match="digest mismatch"):+ verify_bundle(bundle, signing_key=SIGNING_KEY)+++def test_altering_the_payload_and_its_digest_together_is_still_detected() -> None:+ """A verifier that compared the two values in the file would pass here."""+ import hashlib++ from app.services.evidence_bundle import canonical_bytes++ bundle = json.loads(json.dumps(_item_bundle()))+ bundle["payload"]["scores"]["malicious_recall"] = 1.0+ bundle["integrity"]["payload_sha256"] = hashlib.sha256(canonical_bytes(bundle["payload"])).hexdigest()++ with pytest.raises(BundleVerificationError, match="signature does not match"):+ verify_bundle(bundle, signing_key=SIGNING_KEY)+++def test_another_deployments_key_does_not_verify() -> None:+ with pytest.raises(BundleVerificationError, match="signature does not match"):+ verify_bundle(_item_bundle(), signing_key="a-different-deployments-key")+++def test_signing_with_an_empty_key_is_refused() -> None:+ """An HMAC over the empty string verifies for anyone who tries it."""+ with pytest.raises(ValueError, match="empty key"):+ build_replay_bundle(score=_score(), method=_method(), model={}, signing_key="")+++def test_a_bundle_with_no_score_is_refused() -> None:+ with pytest.raises(ReplayBundleError, match="graded nothing"):+ build_replay_bundle(score={}, method=_method(), model={}, signing_key=SIGNING_KEY)+++# --------------------------------------------------------------------------+# Reproducibility+# --------------------------------------------------------------------------+++def test_two_bundles_of_one_result_are_byte_identical() -> None:+ """Apart from the generation time, which is pinned here to test the rest."""+ at = datetime(2026, 10, 11, 12, 0, tzinfo=UTC)++ # Spelled out at each call rather than splatted from one dict: a dict of+ # mixed-typed values widens to a single join type, which costs the+ # per-argument checking this file otherwise gets for free.+ def build() -> dict:+ return build_replay_bundle(+ score=_score(),+ method=_method(),+ model={"id": "m"},+ items=_items(),+ signing_key=SIGNING_KEY,+ generated_at=at,+ )++ first = build()+ second = build()++ assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True)+++def test_the_schema_version_and_kind_are_stated() -> None:+ payload = _aggregate_bundle()["payload"]++ assert payload["bundle_schema_version"] == REPLAY_BUNDLE_SCHEMA_VERSION+ assert payload["kind"] == "replay_evaluation"+++def test_the_filename_is_stable_for_one_run() -> None:+ assert replay_bundle_filename("abc") == "aisoc-replay-abc.bundle.json"+++# --------------------------------------------------------------------------+# The redactor's own edges+# --------------------------------------------------------------------------+++def test_a_short_identifier_is_not_substituted_into_prose() -> None:+ """A rule id of `s3` would otherwise rewrite every mention of the service."""+ redactor = BundleRedactor()+ redactor.identifier("RULE", "s3")++ assert "s3 bucket" in redactor.free_text("the s3 bucket was public")+++def test_the_longest_identifier_wins_when_two_overlap() -> None:+ redactor = BundleRedactor()+ outer = redactor.identifier("RULE", "FIN-DB-01 lateral movement")+ inner = redactor.identifier("HOST", "FIN-DB-01")++ assert redactor.free_text("FIN-DB-01 lateral movement fired") == f"{outer} fired"+ assert redactor.free_text("traffic from FIN-DB-01 only") == f"traffic from {inner} only"+++def test_the_privacy_block_states_what_the_pass_does_not_catch() -> None:+ """A note read by someone deciding what to send must not overstate."""+ privacy = _item_bundle()["payload"]["privacy"]++ assert privacy["mapping_exported"] is False+ assert privacy["free_text_does_not_catch"], "the limits of a pattern-based pass must be stated, not implied"+ assert any("single-word machine name" in limit for limit in privacy["free_text_does_not_catch"])+++def test_bare_host_in_agent_prose_is_redacted() -> None:+ """A machine named only in the agent's reasoning must not survive.++ This is the leak the first live run against a real reader produced: the+ recon step writes ``Extracted 2 IOCs: ['198.51.100.7', 'WS-040']`` and+ ``WS-040`` appears in no identifier field, so nothing registered it.+ """+ redactor = BundleRedactor()++ out = redactor.free_text("Extracted 2 IOCs for enrichment: ['198.51.100.7', 'WS-040']")++ assert "WS-040" not in out+ assert "198.51.100.7" not in out+++def test_public_taxonomy_survives_host_redaction() -> None:+ """The agent reasons in CVE and ATT&CK terms; those are not machines.++ Every term below matches the host shape. Rewriting them would make the+ reasoning unreadable while protecting nothing, which is the failure mode+ that makes a redactor get switched off.+ """+ redactor = BundleRedactor()+ text = "SHA-256 matched, CVE-2026-1234 applies, technique T1059.001, RFC-1918 space, AES-256 key, x86-64 binary"++ out = redactor.free_text(text)++ assert out == text+++def test_one_host_gets_one_token_whichever_pass_sees_it_first() -> None:+ """The identifier pass and the prose pass must share a namespace.++ They are separate code paths naming the same machine. If they disagree,+ two rows about one host read as two hosts and the bundle stops being+ joinable against itself -- which is most of what it is for.+ """+ from_identifier = BundleRedactor()+ from_identifier.identifier("rule", "Lateral movement on FIN-DB-01")+ identifier_first = from_identifier.free_text("the host FIN-DB-01 was contacted")++ from_prose = BundleRedactor()+ prose_first = from_prose.free_text("the host FIN-DB-01 was contacted")++ assert "FIN-DB-01" not in identifier_first+ assert identifier_first == prose_first, "the same host named by two passes must produce one token"diff --git a/tests/test_model_runtime_overlays.py b/tests/test_model_runtime_overlays.pyindex 57c2d826d..f38b7b85e 100644--- a/tests/test_model_runtime_overlays.py+++ b/tests/test_model_runtime_overlays.py@@ -103,12 +103,47 @@ class TestTheGpuOverlayDoesTheOppositeThing:assert any(d.get("driver") == "nvidia" for d in devices)assert any("gpu" in (d.get("capabilities") or []) for d in devices)- def test_it_touches_only_ollama(self) -> None:+ def test_only_the_service_that_runs_the_model_reserves_a_device(self) -> None:+ """The reservation moved onto `litellm` once, while this file was being+ edited for the model default, and nothing else would have noticed: the+ overlay still parsed, `make up-gpu` still came up, and the GPU sat+ held by a proxy that does no inference while generation ran on the+ CPU. A reservation anywhere but `ollama` is that bug."""+ services = _load(GPU_OVERLAY).get("services") or {}++ reserving = sorted(name for name, body in services.items() if _device_reservations(body or {}))++ assert reserving == ["ollama"], f"a device is reserved on {reserving}, and only ollama runs the model"++ def test_it_touches_only_the_three_services_the_runtime_needs(self) -> None:"""An overlay that quietly changed other services would be a second- deployment shape nobody reviewed."""+ deployment shape nobody reviewed.++ Three rather than one since the overlay also carries the measured GPU+ model default: the device goes to `ollama`, the pull instruction to+ `ollama-pull` and the routing to `litellm`. Still a closed set, so a+ fourth service appearing here fails."""services = _load(GPU_OVERLAY).get("services") or {}+ expected = {"ollama", "ollama-pull", "litellm"}++ assert set(services) == expected, f"the GPU overlay also changes {sorted(set(services) - expected)}"++ def test_the_model_it_pulls_is_the_model_it_routes_to(self) -> None:+ """The failure this prevents is silent in the worst way: the gateway+ routes to a model nothing pulled, the provider answers 404, and triage+ swallows that into its deterministic fallback. The stack is healthy,+ every container is up, and the measurement is of no model at all."""+ services = _load(GPU_OVERLAY).get("services") or {}++ pulled = (services.get("ollama-pull") or {}).get("entrypoint") or []+ env = ((services.get("litellm") or {}).get("environment")) or {}++ assert pulled, "the overlay pulls nothing"+ model = pulled[-1].split(":-")[-1].rstrip("}")- assert set(services) == {"ollama"}, f"the GPU overlay also changes {sorted(set(services) - {'ollama'})}"+ for key in ("AISOC_LLM_MODEL_FAST", "AISOC_LLM_MODEL_DEEP"):+ routed = str(env.get(key, "")).split(":-")[-1].rstrip("}")+ assert routed.endswith(model), f"{key} routes to {routed!r} and the overlay pulls {model!r}"class TestTheHostLlmOverlayStopsTheBundledOne:diff --git a/tests/test_verdict_quality_gate.py b/tests/test_verdict_quality_gate.pynew file mode 100644index 000000000..4b3286207--- /dev/null+++ b/tests/test_verdict_quality_gate.py@@ -0,0 +1,115 @@+"""Depth plan 1.6: the published verdict-quality table must not be able to lie.++The table's failure mode is not a wrong number. It is an *absent* number+rendered as ``0.000``, which a reader cannot tell apart from a model that was+graded and scored zero. Every test here is a shape that would produce exactly+that, and each must be refused rather than rendered.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))++from check_verdict_quality import ( # noqa: E402+ NOT_MEASURED,+ VerdictQualityError,+ render_table,+ splice,+ validate_entry,+)++MEASURED = {+ "model": "llama3.2:3b-instruct-q4_K_M",+ "mode": "live",+ "llm_calls_placed": 72,+ "balanced_accuracy": 0.63,+ "matthews_corrcoef": 0.27,+ "malicious_recall": 0.70,+ "malicious_support": 30,+ "abstention_rate": 0.1,+ "hallucination_rate": 0.0,+}++UNMEASURED = {+ "model": "gpt-4o",+ "measured": False,+ "not_measured_reason": "no funded key for a hosted provider in this repository",+}+++def test_unmeasured_row_must_carry_a_reason() -> None:+ with pytest.raises(VerdictQualityError, match="must say why"):+ validate_entry({"model": "gpt-4o", "measured": False})+++def test_unmeasured_row_may_not_also_carry_a_score() -> None:+ """The contradiction must be refused, not resolved in favour of the number."""+ with pytest.raises(VerdictQualityError, match="measured=false"):+ validate_entry({**UNMEASURED, "balanced_accuracy": 0.0})+++def test_live_row_that_placed_no_model_call_is_refused() -> None:+ """The defect this gate exists for.++ Triage catches a provider error and answers from its deterministic+ scorer, so a run against a dead endpoint produces a full set of+ confident verdicts and a scorecard that reads entirely normally.+ """+ with pytest.raises(VerdictQualityError, match="llm_calls_placed"):+ validate_entry({**MEASURED, "llm_calls_placed": 0})+++def test_measured_row_without_an_accuracy_is_refused() -> None:+ entry = {k: v for k, v in MEASURED.items() if k != "balanced_accuracy"}+ with pytest.raises(VerdictQualityError, match="no balanced_accuracy"):+ validate_entry(entry)+++def test_mode_outside_the_two_known_paths_is_refused() -> None:+ with pytest.raises(VerdictQualityError, match="must be 'live' or 'deterministic'"):+ validate_entry({**MEASURED, "mode": "offline"})+++def test_deterministic_row_is_allowed_to_place_no_calls() -> None:+ """The floor is a legitimate published row: it is labelled as the floor."""+ validate_entry({**MEASURED, "mode": "deterministic", "llm_calls_placed": 0})+++def test_unmeasured_renders_as_words_and_never_as_a_number() -> None:+ table = render_table({"entries": [MEASURED, UNMEASURED], "corpus": {"items": 72, "pairs": 36}})++ row = next(line for line in table.splitlines() if "gpt-4o" in line)+ assert NOT_MEASURED in row+ assert "no funded key" in row+ assert "0.000" not in row, "an unmeasured model must never render a score-shaped cell"+++def test_recall_always_travels_with_its_support() -> None:+ """A rate over 30 cases and the same rate over four are different claims."""+ table = render_table({"entries": [MEASURED], "corpus": {"items": 72, "pairs": 36}})++ row = next(line for line in table.splitlines() if "llama3.2" in line)+ assert "0.700 / 30" in row+++def test_empty_scorecard_is_refused_rather_than_rendered_blank() -> None:+ with pytest.raises(VerdictQualityError, match="no entries"):+ render_table({"entries": [], "corpus": {}})+++def test_splice_refuses_a_page_with_no_block() -> None:+ with pytest.raises(VerdictQualityError, match="no .* block"):+ splice("# a page with no markers\n", "block")+++def test_splice_leaves_the_rest_of_the_page_alone() -> None:+ page = "# head\n\n<!-- BEGIN:verdict-quality -->\nold\n<!-- END:verdict-quality -->\n\n# tail\n"+ out = splice(page, "<!-- BEGIN:verdict-quality -->\nnew\n<!-- END:verdict-quality -->")++ assert "# head" in out and "# tail" in out+ assert "old" not in out and "new" in out