Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(evaluation): read back the findings a customer's analysts already closed (#903)

Beenu Arora2b3c1490cb84
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea774b5cf..2ad283e89 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Closed-finding history readers: the analyst labels a replay evaluation
+ grades against** (gap-closure Phase 1.1). AiSOC could already push a verdict
+ into somebody else's SIEM. It could not read back the findings a customer's
+ own analysts had already closed, so there was no way for an operator to
+ measure triage against their own decisions on their own data before being
+ asked to trust it. The published benchmark is substrate self-consistency on
+ a synthetic corpus, which answers a different question.
+
+ Five readers now list closed findings in a time window, each row carrying
+ the analyst's disposition, their reason, who closed it and when:
+ `SplunkClient.list_closed_notables`, `SentinelClient.list_closed_incidents`,
+ `ElasticClient.list_closed_signals`, `QRadarClient.list_closed_offenses` and
+ `DefenderClient.list_resolved_alerts`. They extend the clients in
+ `services/actions`, which already own the credential path and already hold
+ the writeback going the other way.
+
+ **The rule that carries the value is the refusal to guess.** Vendor labels
+ map to the canonical taxonomy in one place,
+ `app/services/alert_history.py`, rather than five places that could disagree
+ about what "benign positive" means. Anything outside that taxonomy becomes
+ `unlabeled` and is excluded from accuracy. That is not an edge case: Splunk
+ ES ships dispositions literally named "Other" and "Undetermined", and
+ Sentinel and Defender both ship an explicit `Undetermined` or `Unknown`
+ classification. An analyst who picked one of those said they did not know,
+ and folding it into `true_positive` because the finding happened to be
+ closed would manufacture agreement out of an admission of uncertainty.
+
+ Two vendor-specific decisions are worth stating rather than burying.
+ Elastic Security ships no disposition field at all: closing a signal records
+ no reason, so the honest reader returns `unlabeled` unless the deployment
+ has adopted a workflow tag, and the convention it reads is documented rather
+ than assumed. QRadar's "Non-Issue" maps to `benign` and not
+ `benign_true_positive`, because it makes no claim about whether the rule was
+ right, which is the distinction `benign` exists to carry.
+
+ **Measured:** 30 new tests drive each reader's real HTTP path against
+ vendor-shaped payloads with a mock transport, so a wrong endpoint, a wrong
+ filter or a parser that fails on the documented response shape is caught
+ here rather than on a customer's history. The `services/actions` suite goes
+ from 737 to 767 passing.
+
+ **Gate:** `ci.yml` actions job (`test_alert_history.py`), with a new
+ claim-to-gate row. The assertions that hold the claim are the negative ones:
+ every vendor's explicit "I do not know" is asserted to land on `unlabeled`,
+ two conflicting Elastic tags yield `unlabeled` rather than a coin flip, and
+ `unlabeled` is asserted not to be a member of `CANONICAL_DISPOSITIONS` so
+ nothing downstream can score it as a verdict. `ClosedFinding.__post_init__`
+ refuses a disposition that is neither canonical nor `unlabeled`, so a mapper
+ cannot introduce a third vocabulary. An unparseable close time raises rather
+ than defaulting to now, because a silently wrong close time would put a row
+ on the wrong side of the train/test split and leak the answer into its own
+ evaluation.
+
## [11.2.0] — 2026-09-26
### Added
diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.md
index 95a7dbac8..262953c51 100644
--- a/GAP_CLOSURE_PROGRESS.md
+++ b/GAP_CLOSURE_PROGRESS.md
@@ -147,7 +147,7 @@ Phase 1.1 is genuinely new work, and the writeback direction it mirrors
## Phase 1: Replay evaluation on a customer's own history
-- [~] **1.1 History readers.** Closed-finding readers for Splunk ES, Microsoft Sentinel, Elastic Security, IBM QRadar and Microsoft Defender XDR, each row carrying the analyst's disposition, reason, closer and close time; vendor labels mapped to the canonical taxonomy, with anything outside it becoming `unlabeled` and excluded from accuracy rather than guessed.
+- [x] **1.1 History readers.** Shipped in [#903](https://github.com/beenuar/AiSOC/pull/903). Five readers on the clients in `services/actions`, which already own the credential path and already hold the writeback going the other way: `SplunkClient.list_closed_notables`, `SentinelClient.list_closed_incidents`, `ElasticClient.list_closed_signals`, `QRadarClient.list_closed_offenses`, `DefenderClient.list_resolved_alerts`. One taxonomy module (`app/services/alert_history.py`) rather than five that could disagree. 30 tests drive each reader's real HTTP path against vendor-shaped payloads; the `services/actions` suite goes 737 to 767. Claim-to-gate row added, matrix 147 rows to 148, GATED 139 to 140. Two vendor decisions recorded in `apps/docs/docs/evaluation/replay.md`: Elastic ships no disposition field so an untagged deployment yields no labels, and QRadar "Non-Issue" is `benign` not `benign_true_positive` because it makes no claim about whether the rule was right.
- [ ] **1.2 Replay runner.** New module in `services/agents`. Production `normalize()`, time ordering, 70/30 time split, the production triage path in shadow mode with persistence injected, memory and context frozen at the split point, and verdict, confidence, evidence, tool calls, model id, tokens, measured cost and latency recorded.
- [ ] **1.3 Scoring.** Extend `packages/aisoc-benchmark`: per-class precision and recall with malicious recall first, confusion matrix, abstention rate, calibration with expected calibration error, hallucination rate, per-rule and per-source breakdowns, bootstrap confidence intervals, and no headline accuracy below 30 malicious cases.
- [ ] **1.4 Surfaces.** CLI `aisoc replay`, async API job with tenant-scoped tables, the "Evaluate on your history" console page, and JSON, Markdown and PDF export.
@@ -277,6 +277,25 @@ as a number that was not measured.
Nothing yet beyond this kickoff. Each entry below will name its PR.
-- [x] **Kickoff.** Locked plan saved verbatim to
- `plans/aisoc_gap_closure_plan.plan.md`, this tracker created, hooks installed
- via `scripts/setup_hooks.sh`, and the baseline above captured and recorded.
+- [x] **Kickoff.** [#901](https://github.com/beenuar/AiSOC/pull/901), merged.
+ Locked plan saved verbatim to `plans/aisoc_gap_closure_plan.plan.md`, this
+ tracker created, hooks installed via `scripts/setup_hooks.sh`, and the
+ baseline above captured and recorded.
+- [x] **Phase 1.1, history readers.**
+ [#903](https://github.com/beenuar/AiSOC/pull/903).
+
+### Notes for the next session
+
+Two traps this program hit that are worth not re-learning.
+
+**A gate run before `git add` reads a different tree than CI does.**
+`check_comment_paths.py` failed naming two comments that pointed at
+`apps/docs/docs/evaluation/replay.md`. The file existed. It was untracked, and
+the gate's corpus is `git ls-files`. Staging first made it pass. The same shape
+made a `ruff format --check` comparison against `main` look like `main` had two
+unformatted files: `git stash` leaves untracked files in place, so the "base"
+run was still seeing the new ones.
+
+**Backgrounding a long run kills it here.** The first baseline attempt was
+started with `nohup ... &` and was dead within a minute, having written 41
+progress dots. Long suites run in the foreground.
diff --git a/RELEASES.md b/RELEASES.md
index 1bcd1486a..801537e33 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -2,7 +2,7 @@
This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md).
-> **TL;DR for first-time visitors:** AiSOC is on `v11.2.0`, released 2026-09-26 — the release where the detection engine went from 833 rules to **2,603**, and every one of the 1,770 added rules was watched to fire before it shipped. The library had held roughly 7,000 ATT&CK-mapped rules for months while 833 ran, and the reason turned out to be one thing: Windows events nest their payload under `System`/`EventData`, one level below anything the engine flattened, so `CommandLine` and `Image` read `None` and no Windows rule could fire however correctly it was written. Fixed in the connector; the engine and matcher are byte-identical. 1,362 imported rules were **refused** with recorded reasons, which matters as much as the 1,770 accepted. **It is a minor: nothing here forces an operator to act** — but the detection surface is 3.1x wider, so a deployment with Windows telemetry should expect more alerts from the same stream. Every product claim is backed by a failing CI test (claim-to-gate matrix: 147 rows — 139 GATED / 8 PARTIAL / 0 NO GATE, counted from the table by `scripts/check_claim_gate_matrix.py`). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
+> **TL;DR for first-time visitors:** AiSOC is on `v11.2.0`, released 2026-09-26 — the release where the detection engine went from 833 rules to **2,603**, and every one of the 1,770 added rules was watched to fire before it shipped. The library had held roughly 7,000 ATT&CK-mapped rules for months while 833 ran, and the reason turned out to be one thing: Windows events nest their payload under `System`/`EventData`, one level below anything the engine flattened, so `CommandLine` and `Image` read `None` and no Windows rule could fire however correctly it was written. Fixed in the connector; the engine and matcher are byte-identical. 1,362 imported rules were **refused** with recorded reasons, which matters as much as the 1,770 accepted. **It is a minor: nothing here forces an operator to act** — but the detection surface is 3.1x wider, so a deployment with Windows telemetry should expect more alerts from the same stream. Every product claim is backed by a failing CI test (claim-to-gate matrix: 148 rows — 140 GATED / 8 PARTIAL / 0 NO GATE, counted from the table by `scripts/check_claim_gate_matrix.py`). The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
---
diff --git a/ROADMAP.md b/ROADMAP.md
index cd202eb78..5c418be5d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **147 rows — 139 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **148 rows — 140 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 0d115067a..c8a276af8 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 139 rows
+The last row is the one worth reading first. It is the honest index: 140 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/evaluation/replay.md b/apps/docs/docs/evaluation/replay.md
new file mode 100644
index 000000000..39687eef4
--- /dev/null
+++ b/apps/docs/docs/evaluation/replay.md
@@ -0,0 +1,183 @@
+---
+title: Evaluate AiSOC on your own history
+sidebar_label: Replay evaluation
+---
+
+# Evaluate AiSOC on your own history
+
+The published [benchmark](../benchmark.md) measures AiSOC against a synthetic
+corpus, and three of its four axes are substrate self-consistency rather than
+agent accuracy. That is a useful regression gate and a poor basis for deciding
+whether to trust the product on your estate.
+
+Replay evaluation answers the question that actually matters: **how does AiSOC
+triage compare with what your analysts already decided, on your data?**
+
+:::note What exists today
+This page currently documents the **history readers**, which are the first half
+of the feature: the part that reads your closed findings and turns your
+analysts' labels into something gradeable. The replay runner, the scoring
+report and the `aisoc replay` command land next and this page grows with them.
+Nothing here describes a capability that is not in the tree.
+:::
+
+## The one rule worth reading first
+
+**A label AiSOC cannot name is excluded from accuracy. It is never guessed.**
+
+This is the difference between an evaluation and a sales sheet, and it costs
+sample size on purpose.
+
+Every vendor in this list ships a way for an analyst to say "I do not know".
+Splunk Enterprise Security has dispositions named *Other* and *Undetermined*.
+Microsoft Sentinel has an `Undetermined` classification. Defender XDR has
+`Unknown`. An analyst who chose one of those made no claim, and folding it into
+`true_positive` because the finding happened to be closed would manufacture
+agreement out of an admission of uncertainty.
+
+Those rows are read, counted and reported as `unlabeled`. They never enter the
+confusion matrix. If your history is mostly unlabeled, the report tells you
+that instead of printing a confident number derived from a handful of rows.
+
+## The canonical taxonomy
+
+Vendor labels map onto the same taxonomy AiSOC already uses when it writes a
+disposition back into your SIEM, so a verdict means the same thing in both
+directions.
+
+| Canonical | Means |
+|---|---|
+| `true_positive` | Valid detection of malicious or unauthorised activity. |
+| `benign_true_positive` | Valid detection of authorised or expected activity. The rule was **correct**, so this is not a false positive and never counts toward a rule's false-positive rate. |
+| `false_positive` | Invalid detection. The intended condition was not present. |
+| `benign` | Real but non-threatening activity, making no claim about whether the rule was right. |
+| `needs_review` | Insufficient evidence to decide safely. |
+| `escalate` | Analyst-forced escalation. |
+| `unlabeled` | **Not a verdict.** The analyst recorded nothing this platform can name. Excluded from accuracy. |
+
+## What each vendor needs
+
+### Splunk Enterprise Security
+
+Reads notables at status 5 (Resolved) and 6 (Closed) through the `notable`
+macro, which is what resolves the correct index on a customised install.
+
+The six stock dispositions map as follows. Dispositions 5 and 6 are absent on
+purpose, and a site that has added custom dispositions from 7 upward will see
+them as `unlabeled`.
+
+| Splunk ES | Canonical |
+|---|---|
+| `disposition:1` True Positive, Suspicious Activity | `true_positive` |
+| `disposition:2` Benign Positive, Suspicious But Expected | `benign_true_positive` |
+| `disposition:3` False Positive, Incorrect Analytic Logic | `false_positive` |
+| `disposition:4` False Positive, Inaccurate Data | `false_positive` |
+| `disposition:5` Other | `unlabeled` |
+| `disposition:6` Undetermined | `unlabeled` |
+
+Enterprise Security is routinely customised, so the reader accepts a
+`search_override`. Supply your own SPL if your site renames statuses or keeps
+review state in its own lookup. It must return these fields: `event_id`,
+`rule_id`, `rule_name`, `urgency`, `disposition`, `review_time`, `reviewer`,
+`comment`.
+
+### Microsoft Sentinel
+
+Reads incidents with `properties/status eq 'Closed'`, following `nextLink` so a
+window larger than one page is read whole rather than truncated to whatever
+sorted first.
+
+`TruePositive` maps to `true_positive`, `BenignPositive` to
+`benign_true_positive`, `FalsePositive` to `false_positive`, and
+`Undetermined` to `unlabeled`. `classificationReason` and
+`classificationComment` are carried as the analyst's reason.
+
+### Elastic Security
+
+**Elastic ships no disposition field.** Closing a signal sets
+`kibana.alert.workflow_status` to `closed` and records no reason at all.
+
+So an untagged Elastic deployment yields **no labels**, and the reader says so
+rather than inferring that a closed signal was a true positive. If you want
+your Elastic history graded, adopt one of these values in
+`kibana.alert.workflow_tags`:
+
+| Workflow tag | Canonical |
+|---|---|
+| `true_positive` | `true_positive` |
+| `benign_positive` or `benign_true_positive` | `benign_true_positive` |
+| `false_positive` | `false_positive` |
+| `benign` | `benign` |
+
+A signal carrying two conflicting tags is `unlabeled`, because picking one
+would be a guess.
+
+### IBM QRadar
+
+Reads offenses with `status = CLOSED`. An offense carries only a numeric
+`closing_reason_id`, so the id-to-text table is read from your appliance at
+`/api/siem/offense_closing_reasons` rather than hardcoded, because closing
+reasons are site-configurable.
+
+The three stock reasons map as follows. A custom reason, or one the appliance
+declines to resolve, is `unlabeled`.
+
+| QRadar closing reason | Canonical |
+|---|---|
+| False-Positive, Tuned | `false_positive` |
+| Non-Issue | `benign` |
+| Policy Violation | `true_positive` |
+
+"Non-Issue" is deliberately `benign` and not `benign_true_positive`. It makes
+no claim about whether the rule was right, and crediting the detection with
+being correct on the strength of an analyst saying only that nothing happened
+would inflate the rule's apparent quality.
+
+If the closing-reason lookup is refused, the offenses are still read and every
+row lands `unlabeled`. A partial answer beats no answer.
+
+### Microsoft Defender XDR
+
+Reads alerts with `status eq 'Resolved'`, following `@odata.nextLink`.
+
+Defender separates two fields that must not be conflated. `classification` is
+the verdict and is what maps to a disposition. `determination` is the reason
+(Malware, SecurityTesting, Phishing and so on) and is carried as the analyst's
+reason, never scored. Putting a reason code into a confusion matrix would be a
+category error.
+
+| Defender classification | Canonical |
+|---|---|
+| `TruePositive` | `true_positive` |
+| `InformationalExpectedActivity` | `benign_true_positive` |
+| `FalsePositive` | `false_positive` |
+| `Unknown` | `unlabeled` |
+
+## Privacy: where your data goes
+
+Reading your history happens inside your deployment, against credentials you
+already configured for that SIEM. The findings are processed by the services
+you are already running.
+
+**Data leaves your deployment only when the model you configured is hosted by
+a third party.** If AiSOC is pointed at a hosted provider, the alert content
+that triage reasons over is sent to that provider in the ordinary way, exactly
+as it is during live triage. If you run a local model, through the bundled
+gateway or your own, nothing leaves.
+
+This is a property of your model configuration and not of replay evaluation.
+Replay adds no new egress: it reads findings you already own and runs them
+through the same triage path production uses.
+
+## Limits
+
+- **Reachability, not completeness.** The readers parse each vendor's
+ documented response shape. They cannot know whether your retention window
+ holds the period you asked for, or whether your analysts labelled
+ consistently.
+- **An unparseable close time is an error, not a default.** A silently wrong
+ close time would put a finding on the wrong side of a train/test split and
+ leak the answer into its own evaluation, so it raises.
+- **Elastic yields nothing without tags**, as above.
+- **The vendor's own label is kept verbatim** alongside the mapped one, so you
+ can audit a mapping you disagree with rather than having to trust it.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 019d01430..57fc1df36 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -13,6 +13,7 @@ const sidebars: SidebarsConfig = {
"benchmark",
"benchmark-methodology",
"benchmark-scoreboard",
+ "evaluation/replay",
],
},
{
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 3ccd14bf6..8fb357df9 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -155,10 +155,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| The retracted 75.3% alert-reduction figure is never presented as a measurement | `apps/docs/docs/benchmark.md`, `benchmarks/alert-reduction.md`, `BenchmarkResults.tsx`, `ComparisonTable.tsx`, `benchmark/page.tsx` | `ci.yml :: python-lint` (`check_alert_reduction_claims.py --check` — scans every published surface: no file may assert the legacy harness runs the production grouping ("faithful re-implementation", "same logic"), any file quoting 75.3% must carry the retraction, the `alert_reduction` suite card may not be declared `kind: 'measurement'`, and every surface publishing the real figure must quote `PUBLISHED_REDUCTION_PCT` from `services/fusion/tests/test_alert_reduction_real.py`, which that test asserts against its own measurement — so the chain from measurement to prose has no hand-copied link. `benchmark.md` had withdrawn the claim while two other surfaces went on asserting it, and `benchmark.md` itself re-asserted it in its own intro blockquote) | GATED | - |
| The same verb is graded identically whichever dispatch door it arrives through | README (graduated autonomy); `concepts/live-actions.md` | `ci.yml` actions job (`test_approval_doors_agree.py` — both live doors driven over 23 capabilities x 5 tiers x 3 confidence bands, 345 combinations, asserting the same answer to "did a vendor get touched without a human". A dry-run preview does not count as a touch, since the registry door downgrades an over-tier request to one. Against the previous tree it reports 5 disagreements: `search_siem` is read_only and automatic and sat in the analyst queue at the default tier while executing through the other door, because `TIER_MAX_AUTOMATIC["L1"]` said a tier the ladder defines as "MINIMAL blast-radius actions are automatic" auto-executes nothing; and `update_alert_disposition` was the one ActionType with no `ACTION_BLAST_RADIUS` entry, which is not a missing entry but two different ones, since the four readers of that table supply two different fallbacks. Structural checks alongside it fail a door that imports the raw matrix or compares against a specific `ActionImpact` inside its grading path — the shape a re-introduced bypass has — and require every `ActionType` to carry an explicit blast radius so neither fallback decides anything) | GATED | the grading itself is one function, `approval_matrix.evaluate_contract`, rather than two kept in agreement by discipline; the sweep exists for the axis it cannot unify, which is each door's separate blast-radius layer |
| An image the deployment files tell an operator to pull exists, at the tag they will request | README quickstart (`docker compose up`), `docs/deployment/*`, `infra/helm/aisoc` | `image-availability.yml` (daily) + the `verify` job of `publish-images.yml` and `release.yml` (`scripts/check_published_images.py` — resolves every reference in `docker-compose.yml` and the chart the way the tooling that reads them does, `${AISOC_VERSION:-latest}` to its default and an empty chart `tag:` to `Chart.AppVersion`, then asks GHCR. `--require-fresh` also compares the version the tag names, or the `VERSION` at the commit the image records in `org.opencontainers.image.revision`, against the tree. Against `main` before this gate existed it reported 14 findings: `aisoc-web:latest` two releases behind, `aisoc-web:v11.0.0` never pushed, three images named by compose that had never been published once, and a chart whose every tag defaulted to a `Chart.AppVersion` no image carried. Offline it prints SKIPPED rather than OK, and `--require-network` makes that a failure) | GATED | Third-party images (`postgres`, `redis`, `ghcr.io/berriai/litellm`) are named and counted but not resolved: the claim is about the images this project publishes, and anonymous third-party registry reads are rate-limited per runner IP. Existence is not asked on a pull request, because a PR that adds a service names an image that cannot exist until it has merged and published |
+| An analyst label AiSOC cannot name is excluded from evaluation rather than guessed | `apps/docs/docs/evaluation/replay.md`; `services/actions/app/services/alert_history.py` (the taxonomy and its refusal rule) | `ci.yml` actions job (`test_alert_history.py`: each of the five SIEM readers is driven over its real HTTP path against vendor-shaped payloads with a mock transport, so a wrong endpoint, a wrong filter or a parser that KeyErrors on the documented shape fails here rather than on a customer's history. The assertions that carry the claim are the negative ones: every vendor's explicit "I do not know" (Splunk ES dispositions 5 `Other` and 6 `Undetermined`, Sentinel `Undetermined`, Defender `Unknown`, a site-custom QRadar closing reason, an untagged Elastic signal) is asserted to land on `unlabeled`, two conflicting Elastic tags yield `unlabeled` rather than a coin flip, and `unlabeled` is asserted **not** to be a member of `CANONICAL_DISPOSITIONS` so nothing downstream can score it as a verdict. `ClosedFinding.__post_init__` refuses a disposition that is neither canonical nor `unlabeled`, so a mapper cannot invent a third vocabulary. An unparseable close time raises rather than defaulting to now, because a silently-wrong close time puts a row on the wrong side of the train/test split and leaks the answer into its own evaluation) | GATED | Reachability and taxonomy only: the gate proves each reader parses its vendor's documented shape and refuses to guess, never that a given deployment's history is complete. Elastic ships no disposition field at all, so an untagged Elastic deployment yields no labels and the replay report says so rather than grading on zero |
## Summary
-- GATED: 139
+- GATED: 140
- PARTIAL: 8
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/services/actions/app/clients/defender_client.py b/services/actions/app/clients/defender_client.py
index 332904e5e..4eed0d62c 100644
--- a/services/actions/app/clients/defender_client.py
+++ b/services/actions/app/clients/defender_client.py
@@ -11,6 +11,7 @@ Credentials expected in ActionRequest.parameters:
from __future__ import annotations
+from datetime import datetime
from typing import Any
import httpx
@@ -53,6 +54,52 @@ class DefenderClient:
if not self._token:
await self._authenticate(client)
+ async def list_resolved_alerts(
+ self,
+ since: datetime,
+ until: datetime,
+ *,
+ limit: int = 1000,
+ ) -> list[dict[str, Any]]:
+ """List alerts an analyst resolved in the window, with their classification.
+
+ Gap-closure Phase 1.1.
+
+ Defender XDR separates two fields an evaluation must not conflate:
+ ``classification`` is the verdict (TruePositive,
+ InformationalExpectedActivity, FalsePositive, Unknown) and
+ ``determination`` is the reason (Malware, SecurityTesting, Phishing and
+ so on). Only the first maps to a disposition; the second is carried as
+ the analyst's reason. ``Unknown`` is a real choice in the product and
+ stays unlabeled.
+
+ ``@odata.nextLink`` is followed so a window larger than one page is
+ read whole rather than truncated to whatever sorted first.
+ """
+ results: list[dict[str, Any]] = []
+ url: str | None = f"{_MDE_BASE}/alerts"
+ params: dict[str, Any] | None = {
+ "$filter": (
+ f"status eq 'Resolved' and "
+ f"lastUpdateTime ge {since.strftime('%Y-%m-%dT%H:%M:%SZ')} and "
+ f"lastUpdateTime le {until.strftime('%Y-%m-%dT%H:%M:%SZ')}"
+ ),
+ "$orderby": "lastUpdateTime asc",
+ "$top": min(limit, 100),
+ }
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ await self._ensure_token(client)
+ while url and len(results) < limit:
+ resp = await client.get(url, headers=self._headers(), params=params)
+ resp.raise_for_status()
+ body = resp.json() if resp.content else {}
+ results.extend(body.get("value") or [])
+ # nextLink already carries the filter and the skip token.
+ url = body.get("@odata.nextLink")
+ params = None
+ logger.info("defender.resolved_alerts", count=len(results))
+ return results[:limit]
+
async def find_machine(self, hostname: str) -> dict[str, Any] | None:
"""Look up a machine by hostname in Defender for Endpoint."""
async with httpx.AsyncClient(timeout=20.0) as client:
diff --git a/services/actions/app/clients/elastic_client.py b/services/actions/app/clients/elastic_client.py
index 3d288149a..8ded65ebd 100644
--- a/services/actions/app/clients/elastic_client.py
+++ b/services/actions/app/clients/elastic_client.py
@@ -13,6 +13,7 @@ Credentials expected in ActionRequest.parameters:
from __future__ import annotations
+from datetime import datetime
from typing import Any
import httpx
@@ -93,6 +94,62 @@ class ElasticClient:
logger.info("elastic.dsl.complete", index=index, results=len(hits))
return [h["_source"] for h in hits]
+ async def list_closed_signals(
+ self,
+ since: datetime,
+ until: datetime,
+ *,
+ limit: int = 1000,
+ index: str = ".alerts-security.alerts-*",
+ ) -> list[dict[str, Any]]:
+ """List detection signals an analyst closed in the window.
+
+ Gap-closure Phase 1.1.
+
+ Elastic ships no disposition field: closing a signal sets
+ ``kibana.alert.workflow_status`` to ``closed`` and records no reason.
+ So this reader returns the signals and
+ :func:`app.services.alert_history.map_elastic_disposition` reads the
+ deployment's workflow tags, yielding ``unlabeled`` when there are none.
+ That is the honest outcome for an untagged deployment, and the
+ alternative, inferring a disposition from the fact of closure, would
+ label every closed signal a true positive.
+
+ Unlike :meth:`run_dsl_search` this keeps the whole hit rather than
+ ``_source`` alone, because ``_id`` is the signal's identity and the
+ parser needs it.
+ """
+ body = {
+ "query": {
+ "bool": {
+ "filter": [
+ {"term": {"kibana.alert.workflow_status": "closed"}},
+ {
+ "range": {
+ "@timestamp": {
+ "gte": since.isoformat(),
+ "lte": until.isoformat(),
+ }
+ }
+ },
+ ]
+ }
+ },
+ "size": limit,
+ "sort": [{"@timestamp": {"order": "asc"}}],
+ }
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ resp = await client.post(
+ f"{self._es_url}/{index}/_search",
+ headers=self._es_headers(),
+ auth=self._auth(), # type: ignore[arg-type]
+ json=body,
+ )
+ resp.raise_for_status()
+ hits = resp.json().get("hits", {}).get("hits", [])
+ logger.info("elastic.closed_signals", count=len(hits))
+ return list(hits)
+
async def create_or_update_detection_rule(
self,
rule_config: dict[str, Any],
diff --git a/services/actions/app/clients/qradar_client.py b/services/actions/app/clients/qradar_client.py
index d3195f8c1..fc1c7dbb6 100644
--- a/services/actions/app/clients/qradar_client.py
+++ b/services/actions/app/clients/qradar_client.py
@@ -16,6 +16,7 @@ a weaker posture, never the default.
from __future__ import annotations
+from datetime import datetime
from typing import Any
import httpx
@@ -69,6 +70,70 @@ class QRadarClient:
response.raise_for_status()
return response.json() if response.content else {}
+ async def list_closed_offenses(
+ self,
+ since: datetime,
+ until: datetime,
+ *,
+ limit: int = 1000,
+ ) -> list[dict[str, Any]]:
+ """List offenses an analyst closed in the window, with the reason resolved.
+
+ Gap-closure Phase 1.1.
+
+ An offense carries only a numeric ``closing_reason_id``, and a number
+ is not a label anyone can map to a disposition. QRadar's closing
+ reasons are also site-configurable, so the id-to-name table is read
+ from the appliance rather than hardcoded, and each offense is given a
+ ``closing_reason_name`` for the parser. An id the appliance does not
+ resolve is left without a name, which the parser reads as ``unlabeled``
+ rather than inventing a reason for it.
+ """
+ reasons = await self._closing_reasons()
+ async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:
+ response = await client.get(
+ f"{self._base}/api/siem/offenses",
+ headers={**self._headers(), "Range": f"items=0-{max(limit - 1, 0)}"},
+ params={
+ "filter": (
+ f"status = CLOSED and close_time >= {int(since.timestamp() * 1000)} "
+ f"and close_time <= {int(until.timestamp() * 1000)}"
+ ),
+ "fields": ("id,description,status,severity,offense_type,close_time,last_updated_time,closing_reason_id,closing_user"),
+ },
+ )
+ response.raise_for_status()
+ offenses = response.json() if response.content else []
+
+ for offense in offenses:
+ name = reasons.get(offense.get("closing_reason_id"))
+ if name is not None:
+ offense["closing_reason_name"] = name
+ logger.info("qradar.closed_offenses", count=len(offenses))
+ return list(offenses)
+
+ async def _closing_reasons(self) -> dict[Any, str]:
+ """Read the appliance's closing-reason id to text table.
+
+ Never raises: an appliance that refuses this endpoint should yield
+ offenses whose reason is unknown, which the parser scores as
+ ``unlabeled``. Failing the whole history read over the lookup would
+ turn a partial answer into no answer.
+ """
+ try:
+ async with httpx.AsyncClient(timeout=self._timeout, verify=self._verify_ssl) as client:
+ response = await client.get(
+ f"{self._base}/api/siem/offense_closing_reasons",
+ headers=self._headers(),
+ params={"fields": "id,text"},
+ )
+ response.raise_for_status()
+ rows = response.json() if response.content else []
+ except Exception as exc: # noqa: BLE001, a missing lookup degrades to unlabeled
+ logger.warning("qradar.closing_reasons_unavailable", error=str(exc))
+ return {}
+ return {row["id"]: row["text"] for row in rows if "id" in row and "text" in row}
+
async def add_note(self, offense_id: str, note_text: str) -> dict[str, Any]:
"""Attach a note to an offense.
diff --git a/services/actions/app/clients/sentinel_client.py b/services/actions/app/clients/sentinel_client.py
index 964cd0be0..2ea3b3f6c 100644
--- a/services/actions/app/clients/sentinel_client.py
+++ b/services/actions/app/clients/sentinel_client.py
@@ -14,6 +14,7 @@ Credentials expected in ``ActionRequest.parameters``:
from __future__ import annotations
+from datetime import datetime
from typing import Any
import httpx
@@ -84,6 +85,57 @@ class SentinelClient:
self._token = response.json()["access_token"]
return self._token
+ def _incidents_url(self) -> str:
+ return (
+ f"{ARM_BASE}/subscriptions/{self._subscription_id}"
+ f"/resourceGroups/{self._resource_group}"
+ f"/providers/Microsoft.OperationalInsights/workspaces/{self._workspace_name}"
+ f"/providers/Microsoft.SecurityInsights/incidents"
+ )
+
+ async def list_closed_incidents(
+ self,
+ since: datetime,
+ until: datetime,
+ *,
+ limit: int = 1000,
+ ) -> list[dict[str, Any]]:
+ """List incidents an analyst closed in the window, with their classification.
+
+ Gap-closure Phase 1.1. ARM pages with ``nextLink``; the loop follows it
+ rather than reading only the first page, because a first-page-only read
+ would silently grade a customer on whichever incidents happened to sort
+ first and report the sample size as if it were the whole window.
+
+ The OData filter bounds the window server-side. ``Status eq 'Closed'``
+ is the only status that carries a classification, so an open incident
+ cannot enter the corpus.
+ """
+ results: list[dict[str, Any]] = []
+ url: str | None = self._incidents_url()
+ params: dict[str, Any] | None = {
+ "api-version": API_VERSION,
+ "$filter": (
+ f"properties/status eq 'Closed' and "
+ f"properties/lastModifiedTimeUtc ge {since.isoformat()} and "
+ f"properties/lastModifiedTimeUtc le {until.isoformat()}"
+ ),
+ "$orderby": "properties/lastModifiedTimeUtc asc",
+ "$top": min(limit, 200),
+ }
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
+ token = await self._access_token(client)
+ while url and len(results) < limit:
+ response = await client.get(url, headers={"Authorization": f"Bearer {token}"}, params=params)
+ response.raise_for_status()
+ body = response.json() if response.content else {}
+ results.extend(body.get("value") or [])
+ # nextLink carries its own query string; re-sending params
+ # would duplicate $filter and ARM rejects the request.
+ url = body.get("nextLink")
+ params = None
+ return results[:limit]
+
async def get_incident(self, incident_id: str) -> dict[str, Any]:
"""Read one incident. Used as the writeback verification probe."""
async with httpx.AsyncClient(timeout=self._timeout) as client:
diff --git a/services/actions/app/clients/splunk_client.py b/services/actions/app/clients/splunk_client.py
index 9f6d8d020..d13309eaf 100644
--- a/services/actions/app/clients/splunk_client.py
+++ b/services/actions/app/clients/splunk_client.py
@@ -13,6 +13,7 @@ Credentials expected in ActionRequest.parameters:
from __future__ import annotations
import json
+from datetime import datetime
from typing import Any
import httpx
@@ -101,6 +102,48 @@ class SplunkClient:
logger.info("splunk.search.complete", sid=sid, result_count=len(results))
return results
+ async def list_closed_notables(
+ self,
+ since: datetime,
+ until: datetime,
+ *,
+ limit: int = 1000,
+ search_override: str | None = None,
+ ) -> list[dict[str, Any]]:
+ """List notables an analyst closed in the window, with their disposition.
+
+ Gap-closure Phase 1.1: the read half of the writeback in
+ :mod:`app.services.disposition_writeback`, so replay evaluation can be
+ graded against the customer's own analysts.
+
+ ``status`` 5 and 6 are Splunk ES's Resolved and Closed. The ``notable``
+ macro is used rather than a literal ``index=notable`` because it is
+ what resolves the correct index on a customised install, and every ES
+ deployment ships it.
+
+ ``search_override`` exists because Enterprise Security is routinely
+ customised: a site with extra dispositions, a renamed status or its own
+ review lookup supplies its own SPL rather than being told its history
+ cannot be read. The fields the parser needs are documented in
+ `apps/docs/docs/evaluation/replay.md`.
+ """
+ spl = search_override or (
+ "`notable` | search status IN (5, 6) | fields event_id rule_id rule_name urgency disposition review_time reviewer comment _time"
+ )
+ rows = await self.run_search(
+ spl,
+ earliest_time=str(int(since.timestamp())),
+ latest_time=str(int(until.timestamp())),
+ max_count=limit,
+ )
+ logger.info(
+ "splunk.closed_notables",
+ count=len(rows),
+ since=since.isoformat(),
+ until=until.isoformat(),
+ )
+ return rows
+
async def create_notable_event(
self,
rule_name: str,
diff --git a/services/actions/app/services/alert_history.py b/services/actions/app/services/alert_history.py
new file mode 100644
index 000000000..62f8c91d8
--- /dev/null
+++ b/services/actions/app/services/alert_history.py
@@ -0,0 +1,450 @@
+"""Closed-finding history readers: the analyst labels replay evaluation grades against.
+
+Gap-closure Phase 1.1.
+
+AiSOC can already push a verdict *into* somebody else's SIEM
+(:mod:`app.services.disposition_writeback`). This module is the other
+direction: read back the findings a customer's own analysts already closed, so
+triage can be measured against their decisions on their data before anyone is
+asked to trust it.
+
+Why the taxonomy work lives here and not in each client
+=======================================================
+
+The five clients own the credential path and the HTTP, and nothing else. Every
+vendor label lands in one table in this module for two reasons. A per-client
+mapping is five places to disagree about what "benign positive" means, and the
+writeback in the opposite direction already reads one canonical vocabulary, so
+a second one would let a verdict mean one thing going out and another coming
+back.
+
+The rule that matters most
+==========================
+
+**A label outside the canonical set becomes** :data:`UNLABELED` **and is
+excluded from accuracy. It is never guessed at.**
+
+This is the difference between an evaluation and a sales sheet. Splunk ES
+disposition 5 is literally named "Other" and disposition 6 "Undetermined";
+Sentinel and Defender both ship an explicit ``Undetermined`` / ``Unknown``
+classification. An analyst who selected one of those said "I do not know", and
+folding that into ``true_positive`` because the finding happened to be closed
+would manufacture agreement out of an analyst's admission of uncertainty. The
+scoring layer counts these separately and reports them, so a customer whose
+history is mostly unlabeled sees that fact rather than a confident number
+derived from a handful of rows.
+
+:data:`UNLABELED` is deliberately **not** a member of
+``CANONICAL_DISPOSITIONS``. Anything that treats it as a verdict fails a
+membership check rather than silently scoring it.
+
+A note on Elastic
+=================
+
+Four of the five vendors ship a first-class disposition field. Elastic Security
+does not: a signal carries ``kibana.alert.workflow_status`` of ``open``,
+``acknowledged`` or ``closed``, and closing one records no reason. So the
+honest Elastic reader returns :data:`UNLABELED` for every closed signal unless
+the deployment has adopted a workflow tag, and
+:func:`map_elastic_disposition` reads that tag against a documented
+convention. Inventing an Elastic taxonomy so the column looked as full as the
+other four would have made every Elastic row a fabricated label.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from app.services.disposition_writeback import (
+ BENIGN,
+ BENIGN_TRUE_POSITIVE,
+ CANONICAL_DISPOSITIONS,
+ FALSE_POSITIVE,
+ TRUE_POSITIVE,
+)
+
+#: An analyst closed the finding without recording a disposition this platform
+#: can name. Excluded from accuracy rather than guessed. Deliberately not a
+#: member of ``CANONICAL_DISPOSITIONS``.
+UNLABELED = "unlabeled"
+
+__all__ = [
+ "UNLABELED",
+ "ClosedFinding",
+ "map_defender_disposition",
+ "map_elastic_disposition",
+ "map_qradar_disposition",
+ "map_sentinel_disposition",
+ "map_splunk_disposition",
+ "parse_defender_alert",
+ "parse_elastic_signal",
+ "parse_qradar_offense",
+ "parse_sentinel_incident",
+ "parse_splunk_notable",
+]
+
+
+@dataclass(frozen=True)
+class ClosedFinding:
+ """One finding a human already closed, with the label they chose.
+
+ ``raw`` carries the vendor payload untouched so the replay runner can hand
+ it to the same connector ``normalize()`` production uses, rather than
+ normalizing a second way here and grading the agent on an input shape it
+ never sees in production.
+ """
+
+ vendor: str
+ finding_id: str
+ title: str
+ #: Canonical disposition, or :data:`UNLABELED`.
+ disposition: str
+ #: The vendor's own label, kept verbatim. A reader who disagrees with a
+ #: mapping needs to see what was actually recorded, and an unmapped label
+ #: is worth reporting back rather than discarding.
+ vendor_disposition: str
+ closed_at: datetime
+ closed_by: str | None = None
+ reason: str | None = None
+ rule_id: str | None = None
+ severity: str | None = None
+ raw: Mapping[str, Any] = field(default_factory=dict)
+
+ def __post_init__(self) -> None:
+ if self.disposition != UNLABELED and self.disposition not in CANONICAL_DISPOSITIONS:
+ raise ValueError(
+ f"{self.disposition!r} is neither canonical nor {UNLABELED!r}. A mapper returned "
+ f"a value the taxonomy does not define, which would be scored as if an analyst "
+ f"had chosen it."
+ )
+
+ @property
+ def is_labelled(self) -> bool:
+ """Whether this row may contribute to accuracy."""
+ return self.disposition != UNLABELED
+
+
+def _coerce_time(value: Any) -> datetime:
+ """Best-effort vendor timestamp to an aware UTC datetime.
+
+ Vendors disagree: Splunk sends epoch seconds as a string, QRadar epoch
+ milliseconds as an int, and the Microsoft APIs ISO-8601 with a ``Z``. An
+ unparseable value raises rather than defaulting to "now", because a
+ silently-wrong close time would put a finding on the wrong side of the
+ train/test split and leak the answer into its own evaluation.
+ """
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, (int, float)):
+ # QRadar milliseconds vs Splunk seconds. 10^11 seconds is year 5138,
+ # so anything above it is unambiguously milliseconds.
+ seconds = float(value) / 1000.0 if float(value) > 1e11 else float(value)
+ return datetime.fromtimestamp(seconds, tz=UTC)
+ if isinstance(value, str) and value.strip():
+ text = value.strip()
+ try:
+ return _coerce_time(float(text))
+ except ValueError:
+ pass
+ try:
+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise ValueError(f"unparseable close time {value!r}") from exc
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ raise ValueError(f"unparseable close time {value!r}")
+
+
+def _norm(label: object) -> str:
+ return str(label or "").strip().lower().replace("-", "_").replace(" ", "_")
+
+
+def _submap(row: Mapping[str, Any], key: str) -> Mapping[str, Any]:
+ """Read a nested mapping, or an empty one when it is missing or not a mapping.
+
+ Both Microsoft APIs nest the fields that matter (``properties`` on a
+ Sentinel incident, ``_source`` on an Elastic hit), and a vendor that
+ returns ``null`` there should yield an empty row rather than an
+ ``AttributeError`` three lines later.
+ """
+ value = row.get(key)
+ return value if isinstance(value, Mapping) else {}
+
+
+def _first_rule_id(value: object) -> str | None:
+ """Read the first analytic-rule id off a Sentinel incident.
+
+ Sentinel returns a list because one incident can be raised by several
+ rules. The first is recorded so a per-rule breakdown has a key; the full
+ list stays in ``raw`` for anyone who needs it.
+ """
+ if isinstance(value, (list, tuple)) and value:
+ return str(value[0])
+ return None
+
+
+def _opt_str(row: Mapping[str, Any], key: str) -> str | None:
+ """Read an optional string field, collapsing empty and absent to ``None``.
+
+ ``None`` and ``""`` mean the same thing here: the vendor did not record
+ it. Keeping them distinct would put empty strings in the closed-by column
+ of a report.
+ """
+ value = row.get(key)
+ return str(value) if value else None
+
+
+# --------------------------------------------------------------------------
+# Splunk Enterprise Security
+# --------------------------------------------------------------------------
+
+#: Splunk ES ships six dispositions out of the box, keyed ``disposition:N``.
+#: 5 ("Other") and 6 ("Undetermined") are absent on purpose: both are an
+#: analyst declining to classify, so both fall through to UNLABELED. Sites may
+#: add custom dispositions from 7 upward; those are unmapped by construction.
+_SPLUNK_DISPOSITIONS: dict[str, str] = {
+ "disposition:1": TRUE_POSITIVE, # True Positive - Suspicious Activity
+ "disposition:2": BENIGN_TRUE_POSITIVE, # Benign Positive - Suspicious But Expected
+ "disposition:3": FALSE_POSITIVE, # False Positive - Incorrect Analytic Logic
+ "disposition:4": FALSE_POSITIVE, # False Positive - Inaccurate Data
+ # Splunk also renders the labels rather than the keys in some exports.
+ "true_positive_suspicious_activity": TRUE_POSITIVE,
+ "benign_positive_suspicious_but_expected": BENIGN_TRUE_POSITIVE,
+ "false_positive_incorrect_analytic_logic": FALSE_POSITIVE,
+ "false_positive_inaccurate_data": FALSE_POSITIVE,
+}
+
+
+def map_splunk_disposition(label: object) -> str:
+ """Map a Splunk ES notable disposition to the canonical taxonomy."""
+ return _SPLUNK_DISPOSITIONS.get(_norm(label), UNLABELED)
+
+
+def parse_splunk_notable(row: Mapping[str, Any]) -> ClosedFinding:
+ """Parse one closed Splunk ES notable from a ``/services/search/jobs`` result row."""
+ raw_label = row.get("disposition") or ""
+ return ClosedFinding(
+ vendor="splunk",
+ finding_id=str(row.get("event_id") or row.get("rule_id") or ""),
+ title=str(row.get("rule_name") or row.get("search_name") or ""),
+ disposition=map_splunk_disposition(raw_label),
+ vendor_disposition=str(raw_label),
+ closed_at=_coerce_time(row.get("review_time") or row.get("_time")),
+ closed_by=_opt_str(row, "reviewer"),
+ reason=_opt_str(row, "comment"),
+ rule_id=_opt_str(row, "rule_id"),
+ severity=(_opt_str(row, "urgency") or "").lower() or None,
+ raw=dict(row),
+ )
+
+
+# --------------------------------------------------------------------------
+# Microsoft Sentinel
+# --------------------------------------------------------------------------
+
+#: Sentinel's ``classification`` on a closed incident. ``Undetermined`` is a
+#: first-class choice in the product and is left unmapped on purpose.
+_SENTINEL_CLASSIFICATIONS: dict[str, str] = {
+ "truepositive": TRUE_POSITIVE,
+ "benignpositive": BENIGN_TRUE_POSITIVE,
+ "falsepositive": FALSE_POSITIVE,
+}
+
+
+def map_sentinel_disposition(label: object) -> str:
+ """Map a Microsoft Sentinel incident classification to the canonical taxonomy."""
+ return _SENTINEL_CLASSIFICATIONS.get(_norm(label).replace("_", ""), UNLABELED)
+
+
+def parse_sentinel_incident(row: Mapping[str, Any]) -> ClosedFinding:
+ """Parse one closed Sentinel incident from the ARM incidents API."""
+ props = _submap(row, "properties")
+ raw_label = props.get("classification") or ""
+ closed_by_field = props.get("closedBy")
+ closer: Any = closed_by_field
+ if isinstance(closed_by_field, Mapping):
+ closer = closed_by_field.get("userPrincipalName") or closed_by_field.get("name")
+ # `classificationReason` is the structured half; `classificationComment`
+ # is the analyst's prose. Both are useful and neither is always present.
+ reason_parts = [str(props[k]) for k in ("classificationReason", "classificationComment") if props.get(k)]
+ return ClosedFinding(
+ vendor="sentinel",
+ finding_id=str(row.get("name") or props.get("incidentNumber") or ""),
+ title=str(props.get("title") or ""),
+ disposition=map_sentinel_disposition(raw_label),
+ vendor_disposition=str(raw_label),
+ closed_at=_coerce_time(props.get("lastModifiedTimeUtc") or props.get("closedTime")),
+ closed_by=(str(closer) if closer else None),
+ reason=(": ".join(reason_parts) or None),
+ rule_id=_first_rule_id(props.get("relatedAnalyticRuleIds")),
+ severity=(_opt_str(props, "severity") or "").lower() or None,
+ raw=dict(row),
+ )
+
+
+# --------------------------------------------------------------------------
+# Elastic Security
+# --------------------------------------------------------------------------
+
+#: Elastic ships no disposition field. A deployment that wants its history
+#: graded adopts one of these workflow tags; everything else is UNLABELED.
+#: Documented in `apps/docs/docs/evaluation/replay.md` so the convention is
+#: something an operator can adopt rather than something this code assumes.
+_ELASTIC_WORKFLOW_TAGS: dict[str, str] = {
+ "true_positive": TRUE_POSITIVE,
+ "benign_positive": BENIGN_TRUE_POSITIVE,
+ "benign_true_positive": BENIGN_TRUE_POSITIVE,
+ "false_positive": FALSE_POSITIVE,
+ "benign": BENIGN,
+}
+
+
+def map_elastic_disposition(tags: object) -> str:
+ """Map Elastic ``kibana.alert.workflow_tags`` to the canonical taxonomy.
+
+ Returns :data:`UNLABELED` when no recognised tag is present, which is the
+ common case: closing an Elastic signal records no reason, so an untagged
+ deployment yields no labels at all. Two conflicting tags also yield
+ :data:`UNLABELED`, because picking one would be a guess.
+ """
+ if isinstance(tags, str):
+ tags = [tags]
+ if not isinstance(tags, (list, tuple)):
+ return UNLABELED
+ found = {_ELASTIC_WORKFLOW_TAGS[_norm(t)] for t in tags if _norm(t) in _ELASTIC_WORKFLOW_TAGS}
+ return found.pop() if len(found) == 1 else UNLABELED
+
+
+def parse_elastic_signal(row: Mapping[str, Any]) -> ClosedFinding:
+ """Parse one closed Elastic Security signal from a ``_search`` hit."""
+ nested = _submap(row, "_source")
+ src: Mapping[str, Any] = nested or row
+ tags = src.get("kibana.alert.workflow_tags") or src.get("tags") or []
+ return ClosedFinding(
+ vendor="elastic",
+ finding_id=str(row.get("_id") or src.get("kibana.alert.uuid") or ""),
+ title=str(src.get("kibana.alert.rule.name") or src.get("message") or ""),
+ disposition=map_elastic_disposition(tags),
+ vendor_disposition=",".join(str(t) for t in tags) if tags else "",
+ closed_at=_coerce_time(src.get("kibana.alert.workflow_status_updated_at") or src.get("@timestamp")),
+ closed_by=(str(src["kibana.alert.workflow_user"]) if src.get("kibana.alert.workflow_user") else None),
+ reason=(str(src["kibana.alert.workflow_reason"]) if src.get("kibana.alert.workflow_reason") else None),
+ rule_id=(str(src["kibana.alert.rule.uuid"]) if src.get("kibana.alert.rule.uuid") else None),
+ severity=(str(src["kibana.alert.severity"]).lower() if src.get("kibana.alert.severity") else None),
+ raw=dict(row),
+ )
+
+
+# --------------------------------------------------------------------------
+# IBM QRadar
+# --------------------------------------------------------------------------
+
+#: QRadar closing reasons are site-configurable; these three ship by default.
+#: "Non-Issue" maps to ``benign`` rather than ``benign_true_positive`` because
+#: it makes no claim about whether the rule was right, which is exactly the
+#: distinction ``benign`` exists to carry. A custom reason is UNLABELED.
+_QRADAR_CLOSING_REASONS: dict[str, str] = {
+ "false_positive,_tuned": FALSE_POSITIVE,
+ "false_positive_tuned": FALSE_POSITIVE,
+ "non_issue": BENIGN,
+ "policy_violation": TRUE_POSITIVE,
+}
+
+
+def map_qradar_disposition(label: object) -> str:
+ """Map a QRadar offense closing reason to the canonical taxonomy."""
+ return _QRADAR_CLOSING_REASONS.get(_norm(label), UNLABELED)
+
+
+def parse_qradar_offense(row: Mapping[str, Any]) -> ClosedFinding:
+ """Parse one closed QRadar offense from ``/api/siem/offenses``.
+
+ ``closing_reason_name`` is resolved by the client from
+ ``/api/siem/offense_closing_reasons``; the offense itself only carries the
+ numeric ``closing_reason_id``, and a number is not a label anyone can map.
+ """
+ raw_label = row.get("closing_reason_name") or ""
+ return ClosedFinding(
+ vendor="qradar",
+ finding_id=str(row.get("id") or ""),
+ title=str(row.get("description") or "").strip(),
+ disposition=map_qradar_disposition(raw_label),
+ vendor_disposition=str(raw_label),
+ closed_at=_coerce_time(row.get("close_time") or row.get("last_updated_time")),
+ closed_by=_opt_str(row, "closing_user"),
+ reason=(str(raw_label) or None),
+ rule_id=(None if row.get("offense_type") is None else str(row.get("offense_type"))),
+ severity=_qradar_severity(row.get("severity")),
+ raw=dict(row),
+ )
+
+
+def _qradar_severity(value: Any) -> str | None:
+ """QRadar grades 1-10. Fold onto the platform's five-tier ladder."""
+ if value is None:
+ return None
+ try:
+ n = int(value)
+ except (TypeError, ValueError):
+ return None
+ if n >= 9:
+ return "critical"
+ if n >= 7:
+ return "high"
+ if n >= 4:
+ return "medium"
+ if n >= 2:
+ return "low"
+ return "info"
+
+
+# --------------------------------------------------------------------------
+# Microsoft Defender XDR
+# --------------------------------------------------------------------------
+
+#: Defender XDR's ``classification``. ``Unknown`` is a real choice in the
+#: product and is left unmapped.
+_DEFENDER_CLASSIFICATIONS: dict[str, str] = {
+ "truepositive": TRUE_POSITIVE,
+ "informationalexpectedactivity": BENIGN_TRUE_POSITIVE,
+ "benignpositive": BENIGN_TRUE_POSITIVE,
+ "falsepositive": FALSE_POSITIVE,
+}
+
+
+def map_defender_disposition(label: object) -> str:
+ """Map a Microsoft Defender XDR classification to the canonical taxonomy."""
+ return _DEFENDER_CLASSIFICATIONS.get(_norm(label).replace("_", ""), UNLABELED)
+
+
+def parse_defender_alert(row: Mapping[str, Any]) -> ClosedFinding:
+ """Parse one resolved Defender XDR alert from the Defender for Endpoint API.
+
+ Field names follow the Defender for Endpoint alert resource, which is what
+ :meth:`app.clients.defender_client.DefenderClient.list_resolved_alerts`
+ reads. The Graph security API spells three of them differently
+ (``displayName``, ``lastUpdateDateTime``, ``resolvedDateTime``), so those
+ are accepted as fallbacks rather than making a Graph-sourced row parse to
+ an empty title and an unparseable close time.
+ """
+ raw_label = row.get("classification") or ""
+ return ClosedFinding(
+ vendor="defender",
+ finding_id=str(row.get("id") or row.get("incidentId") or ""),
+ title=str(row.get("title") or row.get("displayName") or ""),
+ disposition=map_defender_disposition(raw_label),
+ vendor_disposition=str(raw_label),
+ closed_at=_coerce_time(
+ row.get("resolvedTime") or row.get("lastUpdateTime") or row.get("resolvedDateTime") or row.get("lastUpdateDateTime")
+ ),
+ closed_by=_opt_str(row, "assignedTo"),
+ # `determination` is the structured "why" (Malware, SecurityTesting,
+ # Phishing, ...) and is a different field from the classification.
+ # Conflating the two would score "Phishing" as if it were a verdict.
+ reason=_opt_str(row, "determination"),
+ rule_id=_opt_str(row, "detectionSource"),
+ severity=(_opt_str(row, "severity") or "").lower() or None,
+ raw=dict(row),
+ )
diff --git a/services/actions/tests/test_alert_history.py b/services/actions/tests/test_alert_history.py
new file mode 100644
index 000000000..b50c0217e
--- /dev/null
+++ b/services/actions/tests/test_alert_history.py
@@ -0,0 +1,556 @@
+"""Closed-finding history readers, against recorded vendor-shaped payloads.
+
+Gap-closure Phase 1.1 gate.
+
+Every payload here is **synthetic**, hand-built to the shape each vendor's API
+documents. None came from a customer. They are recorded fixtures in the sense
+the plan means: the reader's real HTTP path is driven against them with a mock
+transport, so a wrong endpoint, a wrong filter or a parser that KeyErrors on
+the documented response shape fails here rather than on a customer's history.
+
+The assertions that matter are the ones about *not* labelling. An evaluation
+that guesses a disposition manufactures agreement, so each vendor's explicit
+"I do not know" value is asserted to land on ``unlabeled``, and ``unlabeled``
+is asserted not to be a canonical disposition so nothing downstream can score
+it as a verdict.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import httpx
+import pytest
+import respx
+from app.clients.defender_client import DefenderClient
+from app.clients.elastic_client import ElasticClient
+from app.clients.qradar_client import QRadarClient
+from app.clients.sentinel_client import SentinelClient
+from app.clients.splunk_client import SplunkClient
+from app.services.alert_history import (
+ UNLABELED,
+ ClosedFinding,
+ map_defender_disposition,
+ map_elastic_disposition,
+ map_qradar_disposition,
+ map_sentinel_disposition,
+ map_splunk_disposition,
+ parse_defender_alert,
+ parse_elastic_signal,
+ parse_qradar_offense,
+ parse_sentinel_incident,
+ parse_splunk_notable,
+)
+from app.services.disposition_writeback import (
+ BENIGN,
+ BENIGN_TRUE_POSITIVE,
+ CANONICAL_DISPOSITIONS,
+ FALSE_POSITIVE,
+ TRUE_POSITIVE,
+)
+
+SINCE = datetime(2026, 9, 1, tzinfo=UTC)
+UNTIL = datetime(2026, 9, 26, tzinfo=UTC)
+
+
+# ---------------------------------------------------------------------------
+# The rule the whole phase rests on
+# ---------------------------------------------------------------------------
+
+
+def test_unlabeled_is_not_a_canonical_disposition():
+ """If it were, a "do not know" would be scorable as a verdict.
+
+ Everything downstream decides whether a row counts by asking whether its
+ disposition is canonical. Putting ``unlabeled`` in that set would silently
+ re-admit every row this phase exists to exclude.
+ """
+ assert UNLABELED not in CANONICAL_DISPOSITIONS
+
+
+def test_a_mapper_returning_an_undefined_value_is_refused_at_construction():
+ with pytest.raises(ValueError, match="neither canonical nor"):
+ ClosedFinding(
+ vendor="splunk",
+ finding_id="1",
+ title="t",
+ disposition="probably_bad",
+ vendor_disposition="?",
+ closed_at=SINCE,
+ )
+
+
+ ("mapper", "undetermined_label"),
+ [
+ (map_splunk_disposition, "disposition:6"), # ES "Undetermined"
+ (map_splunk_disposition, "disposition:5"), # ES "Other"
+ (map_sentinel_disposition, "Undetermined"),
+ (map_defender_disposition, "Unknown"),
+ (map_qradar_disposition, "Acceptable Business Risk"), # site-custom
+ (map_elastic_disposition, []),
+ ],
+)
+def test_every_vendors_i_do_not_know_lands_on_unlabeled(mapper, undetermined_label):
+ assert mapper(undetermined_label) == UNLABELED
+
+
+ "mapper",
+ [
+ map_splunk_disposition,
+ map_sentinel_disposition,
+ map_defender_disposition,
+ map_qradar_disposition,
+ map_elastic_disposition,
+ ],
+)
+def test_an_unknown_label_is_never_guessed(mapper):
+ for junk in ("", None, "totally-made-up", " "):
+ assert mapper(junk) == UNLABELED
+
+
+def test_two_conflicting_elastic_tags_yield_unlabeled_rather_than_a_coin_flip():
+ assert map_elastic_disposition(["true_positive", "false_positive"]) == UNLABELED
+ assert map_elastic_disposition(["true_positive"]) == TRUE_POSITIVE
+
+
+# ---------------------------------------------------------------------------
+# Splunk Enterprise Security
+# ---------------------------------------------------------------------------
+
+_SPLUNK_NOTABLES = {
+ "results": [
+ {
+ "event_id": "ABC123@@notable@@aaa",
+ "rule_id": "ESCU-Suspicious-Powershell",
+ "rule_name": "Suspicious PowerShell Encoded Command",
+ "urgency": "high",
+ "disposition": "disposition:1",
+ "review_time": "1790294400",
+ "reviewer": "a.analyst",
+ "comment": "Confirmed beacon, host isolated.",
+ "_time": "1790290800",
+ },
+ {
+ "event_id": "ABC123@@notable@@bbb",
+ "rule_id": "ESCU-Vuln-Scan",
+ "rule_name": "Internal Vulnerability Scan Detected",
+ "urgency": "medium",
+ "disposition": "disposition:2",
+ "review_time": "1790298000",
+ "reviewer": "b.analyst",
+ "comment": "Scheduled Qualys scan window.",
+ "_time": "1790294400",
+ },
+ {
+ "event_id": "ABC123@@notable@@ccc",
+ "rule_id": "ESCU-Broken-Logic",
+ "rule_name": "Anomalous Login Volume",
+ "urgency": "low",
+ "disposition": "disposition:6", # Undetermined
+ "review_time": "1790301600",
+ "reviewer": "c.analyst",
+ "comment": "Could not tell either way.",
+ "_time": "1790298000",
+ },
+ ]
+}
+
+
+async def test_splunk_reader_drives_its_real_search_path():
+ respx.post(url__regex=r"https://splunk:8089/services/search/jobs$").mock(return_value=httpx.Response(201, json={"sid": "sid-1"}))
+ results = respx.get(url__regex=r".*/services/search/jobs/sid-1/results.*").mock(return_value=httpx.Response(200, json=_SPLUNK_NOTABLES))
+
+ client = SplunkClient(host="https://splunk:8089", token="t")
+ rows = await client.list_closed_notables(SINCE, UNTIL)
+
+ assert results.called
+ assert len(rows) == 3
+ findings = [parse_splunk_notable(r) for r in rows]
+ assert [f.disposition for f in findings] == [
+ TRUE_POSITIVE,
+ BENIGN_TRUE_POSITIVE,
+ UNLABELED,
+ ]
+ assert findings[0].closed_by == "a.analyst"
+ assert findings[0].reason == "Confirmed beacon, host isolated."
+ assert findings[0].closed_at == datetime(2026, 9, 25, 0, 0, tzinfo=UTC)
+ # The undetermined row is present but excluded from accuracy.
+ assert [f.is_labelled for f in findings] == [True, True, False]
+
+
+async def test_splunk_search_is_bounded_to_the_requested_window_and_to_closed_notables():
+ created = respx.post(url__regex=r"https://splunk:8089/services/search/jobs$").mock(
+ return_value=httpx.Response(201, json={"sid": "sid-1"})
+ )
+ respx.get(url__regex=r".*/results.*").mock(return_value=httpx.Response(200, json={"results": []}))
+ client = SplunkClient(host="https://splunk:8089", token="t")
+ await client.list_closed_notables(SINCE, UNTIL)
+
+ body = created.calls[0].request.content.decode()
+ assert "status+IN+%285%2C+6%29" in body or "status IN (5, 6)" in body.replace("+", " ")
+ assert str(int(SINCE.timestamp())) in body
+ assert str(int(UNTIL.timestamp())) in body
+
+
+async def test_splunk_search_override_is_honoured_for_a_customised_es():
+ created = respx.post(url__regex=r".*/services/search/jobs$").mock(return_value=httpx.Response(201, json={"sid": "s"}))
+ respx.get(url__regex=r".*/results.*").mock(return_value=httpx.Response(200, json={"results": []}))
+ client = SplunkClient(host="https://splunk:8089", token="t")
+ await client.list_closed_notables(SINCE, UNTIL, search_override="`my_review_lookup`")
+
+ assert "my_review_lookup" in created.calls[0].request.content.decode()
+
+
+# ---------------------------------------------------------------------------
+# Microsoft Sentinel
+# ---------------------------------------------------------------------------
+
+_SENTINEL_PAGE_1 = {
+ "value": [
+ {
+ "name": "1111-2222",
+ "properties": {
+ "title": "Mass download by a single user",
+ "status": "Closed",
+ "severity": "Medium",
+ "classification": "BenignPositive",
+ "classificationReason": "SuspiciousButExpected",
+ "classificationComment": "Quarterly data export by the finance team.",
+ "lastModifiedTimeUtc": "2026-09-20T10:00:00Z",
+ "closedBy": {"userPrincipalName": "[email protected]"},
+ "relatedAnalyticRuleIds": ["/rules/mass-download"],
+ },
+ }
+ ],
+ "nextLink": "https://management.azure.com/next-page",
+}
+
+_SENTINEL_PAGE_2 = {
+ "value": [
+ {
+ "name": "3333-4444",
+ "properties": {
+ "title": "Impossible travel",
+ "status": "Closed",
+ "severity": "High",
+ "classification": "Undetermined",
+ "lastModifiedTimeUtc": "2026-09-21T11:00:00Z",
+ },
+ }
+ ]
+}
+
+
+async def test_sentinel_reader_follows_nextlink_rather_than_truncating_the_window():
+ respx.post(url__regex=r".*/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "tok"}))
+ respx.get(url__regex=r".*/providers/Microsoft\.SecurityInsights/incidents\?.*").mock(
+ return_value=httpx.Response(200, json=_SENTINEL_PAGE_1)
+ )
+ page2 = respx.get(url__regex=r"https://management.azure.com/next-page").mock(return_value=httpx.Response(200, json=_SENTINEL_PAGE_2))
+
+ client = SentinelClient("t", "c", "s", "sub", "rg", "ws")
+ rows = await client.list_closed_incidents(SINCE, UNTIL)
+
+ assert page2.called, "a first-page-only read reports a truncated sample as the whole window"
+ assert len(rows) == 2
+ findings = [parse_sentinel_incident(r) for r in rows]
+ assert findings[0].disposition == BENIGN_TRUE_POSITIVE
+ assert findings[0].closed_by == "[email protected]"
+ assert "SuspiciousButExpected" in (findings[0].reason or "")
+ assert findings[1].disposition == UNLABELED
+
+
+async def test_sentinel_filter_names_closed_and_bounds_the_window():
+ respx.post(url__regex=r".*/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "tok"}))
+ route = respx.get(url__regex=r".*/incidents\?.*").mock(return_value=httpx.Response(200, json={"value": []}))
+ client = SentinelClient("t", "c", "s", "sub", "rg", "ws")
+ await client.list_closed_incidents(SINCE, UNTIL)
+
+ query = str(route.calls[0].request.url)
+ assert "status+eq+%27Closed%27" in query or "status eq 'Closed'" in query
+ assert "2026-09-01" in query and "2026-09-26" in query
+
+
+# ---------------------------------------------------------------------------
+# Elastic Security
+# ---------------------------------------------------------------------------
+
+_ELASTIC_HITS = {
+ "hits": {
+ "hits": [
+ {
+ "_id": "sig-1",
+ "_source": {
+ "kibana.alert.rule.name": "Potential Credential Dumping",
+ "kibana.alert.rule.uuid": "rule-abc",
+ "kibana.alert.severity": "high",
+ "kibana.alert.workflow_status": "closed",
+ "kibana.alert.workflow_tags": ["false_positive"],
+ "kibana.alert.workflow_user": "d.analyst",
+ "@timestamp": "2026-09-15T08:00:00Z",
+ },
+ },
+ {
+ "_id": "sig-2",
+ "_source": {
+ "kibana.alert.rule.name": "Unusual Parent-Child Process",
+ "kibana.alert.workflow_status": "closed",
+ "@timestamp": "2026-09-16T08:00:00Z",
+ },
+ },
+ ]
+ }
+}
+
+
+async def test_elastic_reader_keeps_the_hit_id_and_labels_only_what_was_tagged():
+ route = respx.post(url__regex=r"https://es:9200/.*/_search").mock(return_value=httpx.Response(200, json=_ELASTIC_HITS))
+ client = ElasticClient(es_url="https://es:9200", api_key="k")
+ hits = await client.list_closed_signals(SINCE, UNTIL)
+
+ assert route.called
+ findings = [parse_elastic_signal(h) for h in hits]
+ # `_id` is the signal's identity; run_dsl_search drops it, which is why
+ # this reader does not reuse it.
+ assert [f.finding_id for f in findings] == ["sig-1", "sig-2"]
+ assert findings[0].disposition == FALSE_POSITIVE
+ # Untagged: Elastic records no reason when a signal is closed, so the
+ # honest answer is unlabeled rather than "closed, therefore benign".
+ assert findings[1].disposition == UNLABELED
+
+
+async def test_elastic_query_asks_only_for_closed_signals_in_the_window():
+ route = respx.post(url__regex=r".*/_search").mock(return_value=httpx.Response(200, json={"hits": {"hits": []}}))
+ client = ElasticClient(es_url="https://es:9200", api_key="k")
+ await client.list_closed_signals(SINCE, UNTIL)
+
+ body = route.calls[0].request.content.decode()
+ assert '"kibana.alert.workflow_status":"closed"' in body
+ assert "2026-09-01" in body and "2026-09-26" in body
+
+
+# ---------------------------------------------------------------------------
+# IBM QRadar
+# ---------------------------------------------------------------------------
+
+_QRADAR_REASONS = [
+ {"id": 1, "text": "False-Positive, Tuned"},
+ {"id": 2, "text": "Non-Issue"},
+ {"id": 3, "text": "Policy Violation"},
+]
+
+_QRADAR_OFFENSES = [
+ {
+ "id": 501,
+ "description": "Multiple Login Failures\n",
+ "status": "CLOSED",
+ "severity": 8,
+ "offense_type": 3,
+ "close_time": 1790294400000,
+ "closing_reason_id": 1,
+ "closing_user": "e.analyst",
+ },
+ {
+ "id": 502,
+ "description": "Outbound Data Transfer\n",
+ "status": "CLOSED",
+ "severity": 9,
+ "offense_type": 7,
+ "close_time": 1790298000000,
+ "closing_reason_id": 3,
+ "closing_user": "f.analyst",
+ },
+ {
+ "id": 503,
+ "description": "Site-specific rule\n",
+ "status": "CLOSED",
+ "severity": 2,
+ "close_time": 1790301600000,
+ "closing_reason_id": 99, # a reason the appliance does not resolve
+ },
+]
+
+
+async def test_qradar_resolves_closing_reason_ids_to_names_before_mapping():
+ respx.get(url__regex=r".*/api/siem/offense_closing_reasons.*").mock(return_value=httpx.Response(200, json=_QRADAR_REASONS))
+ respx.get(url__regex=r".*/api/siem/offenses\?.*").mock(return_value=httpx.Response(200, json=_QRADAR_OFFENSES))
+
+ client = QRadarClient(base_url="https://qradar", api_token="t")
+ offenses = await client.list_closed_offenses(SINCE, UNTIL)
+ findings = [parse_qradar_offense(o) for o in offenses]
+
+ assert [f.disposition for f in findings] == [FALSE_POSITIVE, TRUE_POSITIVE, UNLABELED]
+ # A numeric id is not a label anyone can map; the unresolved one stays
+ # unlabeled rather than being invented.
+ assert findings[2].vendor_disposition == ""
+ assert findings[0].severity == "high"
+ assert findings[1].severity == "critical"
+ assert findings[0].closed_at == datetime(2026, 9, 25, 0, 0, tzinfo=UTC)
+
+
+async def test_qradar_history_still_reads_when_the_reason_lookup_is_refused():
+ """A partial answer beats no answer, and the rows land unlabeled."""
+ respx.get(url__regex=r".*/offense_closing_reasons.*").mock(return_value=httpx.Response(403, json={"message": "forbidden"}))
+ respx.get(url__regex=r".*/api/siem/offenses\?.*").mock(return_value=httpx.Response(200, json=_QRADAR_OFFENSES))
+ client = QRadarClient(base_url="https://qradar", api_token="t")
+ offenses = await client.list_closed_offenses(SINCE, UNTIL)
+
+ assert len(offenses) == 3
+ assert all(parse_qradar_offense(o).disposition == UNLABELED for o in offenses)
+
+
+async def test_qradar_filter_names_closed_and_bounds_the_window_in_milliseconds():
+ respx.get(url__regex=r".*/offense_closing_reasons.*").mock(return_value=httpx.Response(200, json=_QRADAR_REASONS))
+ route = respx.get(url__regex=r".*/api/siem/offenses\?.*").mock(return_value=httpx.Response(200, json=[]))
+ client = QRadarClient(base_url="https://qradar", api_token="t")
+ await client.list_closed_offenses(SINCE, UNTIL)
+
+ query = str(route.calls[0].request.url)
+ assert "status+%3D+CLOSED" in query or "status = CLOSED" in query
+ assert str(int(SINCE.timestamp() * 1000)) in query
+
+
+# ---------------------------------------------------------------------------
+# Microsoft Defender XDR
+# ---------------------------------------------------------------------------
+
+_DEFENDER_PAGE_1 = {
+ "value": [
+ {
+ "id": "da-1",
+ "title": "Suspicious process injection",
+ "severity": "High",
+ "status": "Resolved",
+ "classification": "TruePositive",
+ "determination": "Malware",
+ "detectionSource": "WindowsDefenderAtp",
+ "assignedTo": "g.analyst",
+ "resolvedTime": "2026-09-18T12:00:00Z",
+ }
+ ],
+ "@odata.nextLink": "https://api.securitycenter.microsoft.com/api/alerts?$skiptoken=2",
+}
+
+_DEFENDER_PAGE_2 = {
+ "value": [
+ {
+ "id": "da-2",
+ "title": "Security testing tool detected",
+ "severity": "Medium",
+ "status": "Resolved",
+ "classification": "InformationalExpectedActivity",
+ "determination": "SecurityTesting",
+ "resolvedTime": "2026-09-19T12:00:00Z",
+ },
+ {
+ "id": "da-3",
+ "title": "Anomalous sign-in",
+ "severity": "Low",
+ "status": "Resolved",
+ "classification": "Unknown",
+ "resolvedTime": "2026-09-19T13:00:00Z",
+ },
+ ]
+}
+
+
+async def test_defender_reader_follows_odata_nextlink_and_separates_verdict_from_reason():
+ respx.post(url__regex=r".*/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "tok"}))
+ respx.get(url__regex=r"https://api\.securitycenter\.microsoft\.com/api/alerts\?%24filter.*").mock(
+ return_value=httpx.Response(200, json=_DEFENDER_PAGE_1)
+ )
+ page2 = respx.get(url__regex=r".*skiptoken.*").mock(return_value=httpx.Response(200, json=_DEFENDER_PAGE_2))
+
+ client = DefenderClient("t", "c", "s")
+ rows = await client.list_resolved_alerts(SINCE, UNTIL)
+
+ assert page2.called
+ findings = [parse_defender_alert(r) for r in rows]
+ assert [f.disposition for f in findings] == [
+ TRUE_POSITIVE,
+ BENIGN_TRUE_POSITIVE,
+ UNLABELED,
+ ]
+ # `determination` is the reason, never the verdict. Scoring "Malware" as a
+ # disposition would put a reason code into the confusion matrix.
+ assert findings[0].reason == "Malware"
+ assert findings[0].vendor_disposition == "TruePositive"
+ assert findings[1].reason == "SecurityTesting"
+
+
+async def test_defender_filter_names_resolved_and_bounds_the_window():
+ respx.post(url__regex=r".*/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "tok"}))
+ route = respx.get(url__regex=r".*/api/alerts\?%24filter.*").mock(return_value=httpx.Response(200, json={"value": []}))
+ client = DefenderClient("t", "c", "s")
+ await client.list_resolved_alerts(SINCE, UNTIL)
+
+ query = str(route.calls[0].request.url)
+ assert "status+eq+%27Resolved%27" in query or "status eq 'Resolved'" in query
+ assert "2026-09-01T00%3A00%3A00Z" in query
+
+
+# ---------------------------------------------------------------------------
+# Timestamps decide which side of the train/test split a row lands on
+# ---------------------------------------------------------------------------
+
+
+def test_vendor_epoch_dialects_all_land_on_the_same_instant():
+ """Splunk sends epoch seconds as a string, QRadar milliseconds as an int."""
+ splunk = parse_splunk_notable({"event_id": "a", "disposition": "disposition:1", "review_time": "1790294400"})
+ qradar = parse_qradar_offense({"id": 1, "closing_reason_name": "Policy Violation", "close_time": 1790294400000})
+ assert splunk.closed_at == qradar.closed_at == datetime(2026, 9, 25, 0, 0, tzinfo=UTC)
+
+
+def test_an_unparseable_close_time_raises_rather_than_defaulting_to_now():
+ """A silently-wrong close time puts a row on the wrong side of the split.
+
+ That is the leak this phase exists to prevent, so it fails loudly.
+ """
+ with pytest.raises(ValueError, match="unparseable close time"):
+ parse_splunk_notable({"event_id": "a", "disposition": "disposition:1", "review_time": ""})
+
+
+def test_the_vendor_label_is_kept_verbatim_even_when_it_maps():
+ """A reader who disagrees with a mapping needs to see what was recorded."""
+ finding = parse_sentinel_incident(
+ {"name": "x", "properties": {"classification": "BenignPositive", "lastModifiedTimeUtc": "2026-09-20T10:00:00Z"}}
+ )
+ assert finding.disposition == BENIGN_TRUE_POSITIVE
+ assert finding.vendor_disposition == "BenignPositive"
+
+
+def test_qradar_non_issue_is_benign_not_benign_true_positive():
+ """ "Non-Issue" makes no claim about whether the rule was right.
+
+ ``benign`` exists to carry exactly that distinction, and folding it into
+ ``benign_true_positive`` would credit the detection with being correct on
+ the strength of an analyst saying only that nothing happened.
+ """
+ assert map_qradar_disposition("Non-Issue") == BENIGN
+ assert map_qradar_disposition("Non-Issue") != BENIGN_TRUE_POSITIVE