Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(skills): activation reads its backtest, and over the alerts the skill matches (#1190)
Beenu Arora7ede0c296572
diff --git a/apps/docs/docs/console/tenant-skills.md b/apps/docs/docs/console/tenant-skills.mdindex 32ef47811..fe18157f4 100644--- a/apps/docs/docs/console/tenant-skills.md+++ b/apps/docs/docs/console/tenant-skills.md@@ -1,7 +1,7 @@---title: Tenant skillssidebar_label: Tenant skills-description: Teach the investigation agent what is normal in your estate, backtest it against your own closed findings, and activate it.+description: Teach the investigation agent what is normal in your estate, backtest it against your own closed findings, and activate it over the API.---# Tenant skills@@ -14,6 +14,22 @@ When a skill matches an alert it supplies the investigation plan instead ofthe built-in strategy, and its guidance reaches the triage prompt. When noskill matches, nothing changes.+:::info There is no skill editor in the console yet++Skills are authored, backtested and activated over the API routes listed at+the bottom of this page. Nothing under `/settings` or anywhere else in the+console reads or writes them today, so what follows is a `curl` or SDK+workflow rather than a point-and-click one. An editor is on the roadmap+alongside the ones for agent definitions and MCP server registrations, which+are API-only for the same reason.++The API is shaped for that editor: `POST /validate` answers without saving so+a form can check a document as it is typed, and `GET /api/v1/tenant-skills`+returns the tool vocabulary alongside the skills so a picker can offer it.+Those are affordances waiting for a caller, not a description of a screen that+exists.+:::+## What a skill looks like```yaml@@ -92,8 +108,7 @@ Every name must be a tool your agent can actually call:you have registered, **enabled**, and named on that server's allowlist.`GET /api/v1/tenant-skills` returns the current list under `available_tools`,-so the editor can offer them rather than making you discover the vocabulary by-being refused.+so you can read the vocabulary rather than discovering it by being refused.:::note When the check cannot be made@@ -125,12 +140,24 @@ halves of it. The route refuses with a 409 naming which of these is wrong:- no backtest attached;- the backtest graded a different version;- the skill has already expired;-- the skill is already active.+- the skill is already active;+- one of the two attached runs is missing, still going, or failed;+- the window those runs graded holds no alert this skill matches.The same rule is written into a database CHECK constraint, so it holds evenagainst a direct fix-up, and `scripts/check_tenant_skill_contract.py` failsthe build if it disappears from either place or from this page.+The last two refusals exist because the first four can all be satisfied by a+backtest that measured nothing. Two attached ids say a report exists, not that+it says anything: both runs can have crashed, or can have graded four hundred+alerts of which none is one this skill applies to. Activation therefore opens+both runs and compares them over the alerts the skill's `match` block selects.+What it requires is that the comparison exists, never that it is favourable: a+threshold on the number would be a target to tune a skill against, and an+organisational fact that happens not to move last quarter's verdicts is still+true about your estate.+## Backtesting`POST /api/v1/tenant-skills/{skill_id}/backtest` starts **two**@@ -143,6 +170,34 @@ resample count:Read them side by side at `GET /api/v1/evaluations/replay/{id}`. The onlydifference between the two reports is the skill.+### Compare them over the alerts the skill matches, not over the headlines++A skill applies to a shape of alert, usually a handful out of hundreds. Both+runs cover the same window, so the difference between their two headline+figures is an average over every alert in it, most of which the skill never+touched.++Four matched alerts in twenty: a skill that corrects every one of them moves+the headline by 0.20, and a skill that breaks every one of them moves it by+-0.20. Across a few hundred findings neither is visible at all. So a headline+that barely moved is not evidence that the skill changed little; it is mostly+evidence that the window was bigger than the skill. The figure that describes+the skill is the one over the alerts it selects, and that is the comparison+activation makes.++### A skill only reaches triage on the LLM path++Guidance is read, matched and put into the prompt only when the alert takes+the LLM path. A tenant with no model configured, a deployment started with+`AISOC_DETERMINISTIC=1`, and an alert the cost governor answered from its+deduplication cache all skip it.++So a backtest run under any of those produces two identical reports, and that+result means **the skill was never applied** rather than the skill was applied+and changed nothing. Those are different facts and only one of them is about+your skill. Check that the candidate run's decisions carry a model-backed tier+before reading a flat result as a verdict on the text.+:::caution What a backtest number does and does not sayThe skill is applied to a window that closed before it was written. That is@@ -176,7 +231,7 @@ skill already steered. Use `POST /{skill_id}/retire`, which keeps it.| `GET /api/v1/tenant-skills` | `settings:read` | With `available_tools`. || `GET /api/v1/tenant-skills/{skill_id}` | `settings:read` | || `GET /api/v1/tenant-skills/{skill_id}/versions` | `settings:read` | Resolves a recorded `skill@vN`. |-| `POST /api/v1/tenant-skills/validate` | `settings:read` | Returns `valid: false` with the message rather than a 422, so the editor can call it as you type. |+| `POST /api/v1/tenant-skills/validate` | `settings:read` | Returns `valid: false` with the message rather than a 422, so a caller can check a half-typed document without a failed request. || `PUT /api/v1/tenant-skills` | `settings:write` | The id is inside the document. || `POST /api/v1/tenant-skills/{skill_id}/backtest` | `connectors:write` | Reaches your SIEM with stored credentials, so the same bar as testing a connector. || `POST /api/v1/tenant-skills/{skill_id}/activate` | `settings:write` | |diff --git a/apps/docs/docs/console/triage-context.md b/apps/docs/docs/console/triage-context.mdindex 802710bd1..65dba4cdb 100644--- a/apps/docs/docs/console/triage-context.md+++ b/apps/docs/docs/console/triage-context.md@@ -28,7 +28,7 @@ that is done differs by source and is described under|---|---|---|| Organisation memory | Compiled from tagged analyst disagreement (`/feedback`) | Durable statements about what is normal in your estate || Outcome priors | Every durable verdict, per evidence signature | A repeat alert matching a trusted prior benign disposition is closed without re-triage |-| Tenant skills | Authored in the console, backtested, activated | Your own investigation approach for alerts of a given shape |+| Tenant skills | Authored over the [tenant-skills API](./tenant-skills.md), backtested, activated — there is no console editor yet | Your own investigation approach for alerts of a given shape || Knowledge-base runbooks | Documents you ingested at `/kb` | Excerpts from your runbooks that mention something this alert mentions, with citations |## Knowledge-base runbooks@@ -73,8 +73,8 @@ a seventh runbook.### How runbook text is containedRunbook text is treated as untrusted, and more carefully than a tenant skill-is. A skill is typed into the console by one person holding `settings:write`,-into fields that are individually parsed and capped. A knowledge-base article+is. A skill is written by one person holding `settings:write`, into fields+that are individually parsed and capped. A knowledge-base articleis longer, is often imported in bulk from a wiki or a vendor advisory, isedited by more people over more time, and reaches the prompt as prose. Anadvisory pasted into a runbook routinely quotes attacker output verbatim,diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex eda3876ac..2a00cd705 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -211,9 +211,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A fusion replica can be destroyed mid-stream with no event lost and none duplicated | `apps/docs/docs/operations/ha-deployment.md`; `apps/docs/docs/operations/performance.md` (failure injection) | `scripts/chaos/fusion_restart.py` (asserts against the `alerts` table in PostgreSQL, never against anything the replacement pod reports about itself: every sequence number ingest accepted must appear exactly once, and a missing one and a repeated one fail separately and are named). Self-tested in both directions, including the case where a loss and a duplicate cancel out in the row count. Run against the Kubernetes deployment on 2026-09-27; the result is committed at `docs/perf/results/2026-09-27-kind-chaos.json` and `perf.yml :: published-results` requires it to carry a verdict | core | GATED | The self-test is gated on every PR touching the harness, and the **execution** now runs live on the weekly `chaos.yml` schedule: `fusion-restart` boots the compose spine, pushes 3,000 events, destroys the fusion container at the halfway mark and asserts against the `alerts` table that every accepted sequence number appears exactly once -- loss and duplicates both. The previous caveat was that this needed a three-node cluster; it does not, because the property under test is the consumer's commit discipline and the sink's idempotency, and a single replica killed mid-stream exercises both. A multi-replica run additionally exercises rebalance, and `docs/audit/REPOSITORY_REALITY.md` still records the date and shape of the one hand-run cluster test rather than implying it recurs || A Helm install connects the event spine, rather than installing every object and consuming nothing | `infra/helm/aisoc/values-ha.yaml`; `apps/docs/docs/operations/ha-deployment.md` | `helm.yml :: render` (`KAFKA_BOOTSTRAP_SERVERS` is asserted present in the rendered ConfigMap and to resolve to the release's own brokers when the chart deploys them; a three-replica render is asserted to carry all three KRaft quorum voters; `ueba.enabled=false` is asserted to render no UEBA object, which it previously did) | full | GATED | Rendering is gated. That the brokers then form a quorum and fusion attaches was exercised on kind on 2026-09-27 and is recorded as such, not as a continuous check || A cross-service route this program adds is asserted against the URL the serving side actually serves | `GAP_CLOSURE_PROGRESS.md` (D16) | `ci.yml` api job (`test_agent_tools.py` parses `services/api/app/main.py`, `api/v1/router.py` and the endpoint module with `ast`, composes all three prefix levels, and asserts each literal the agents service builds is in the served set. Proven able to fail from **both** sides: dropping `/api/v1` from the client's path, and renaming the router's own prefix. The helper raises rather than returning an empty set, so a parser that stopped matching cannot certify nothing. Also asserts the `impact` field the API filters on exists on `LiveActionDescriptor` **and** is populated from the contract rather than left at its default) | core | GATED | Covers the two routes this phase adds and the actions discovery route it consumes. It is not a repository-wide scan: the general version would need every client's URL construction to be statically resolvable, and several build theirs from settings |-| A tenant can author an investigation skill in the console and it changes the plan on matching alerts | `apps/docs/docs/console/tenant-skills.md`; `plans/aisoc_gap_closure_plan.plan.md` (6.1, 6.2) | `ci.yml` agents job (`test_tenant_skill_investigation.py::test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert`: one alert run twice through the real `run_deep_investigation`, everything held constant except whether the tenant has an active skill, asserting on the **system prompt the tool loop was handed** rather than on the verdict, because a verdict can be unchanged by a plan that did change. The built-in the alert would otherwise select is asserted by name, so "the skill won" and "nothing selected anything" are told apart) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py`) | core | GATED | A skill supplies the plan **and** the triage guidance. A skill that only changed the pivot plan could not be backtested at all: the replay grades triage verdicts, so the delta would read zero on every run |+| A tenant can author an investigation skill over the API and it changes the plan on matching alerts | `apps/docs/docs/console/tenant-skills.md`; `plans/aisoc_gap_closure_plan.plan.md` (6.1, 6.2) | `ci.yml` agents job (`test_tenant_skill_investigation.py::test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert`: one alert run twice through the real `run_deep_investigation`, everything held constant except whether the tenant has an active skill, asserting on the **system prompt the tool loop was handed** rather than on the verdict, because a verdict can be unchanged by a plan that did change. The built-in the alert would otherwise select is asserted by name, so "the skill won" and "nothing selected anything" are told apart) + `ci.yml` api job (`test_tenant_skills.py::TestRoutes` drives the authoring half through the real router) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py`) | core | GATED | A skill supplies the plan **and** the triage guidance. A skill that only changed the pivot plan could not be backtested at all: the replay grades triage verdicts, so the delta would read zero on every run. **Claim corrected by fix-pass 3.8:** it read "in the console", and there is no skill editor in `apps/web` — no route, no component, and no occurrence of the word anywhere under `apps/web/src`. The gate never checked for one, so the row read GATED over a surface that does not exist. The API is shaped for an editor and parity 6.3 builds it; until then this is an API workflow and the docs page says so in its first section || A skill may only name a tool that tenant's agent can actually call | `apps/docs/docs/console/tenant-skills.md` (expected_pivots is validated against your tools) | `ci.yml` api job (`test_tenant_skills.py::TestToolValidation`: the inventory is built from the tenant's **enabled** MCP servers only, so a registered-but-disabled server, an empty allowlist and another tenant's server each contribute nothing; a misspelt built-in and an un-allowlisted MCP tool get different messages because the author's next action differs) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` compares `BUILTIN_PIVOTS` against the agents service's `KNOWN_PIVOTS` in **both** directions; proven able to fail by deleting a pivot from each side in turn) | core | GATED | Phase 4.3's per-tenant vendor-read advertisement does not exist yet, so the inventory is the built-in lake pivots plus Phase 5.2's MCP allowlists. A pivot naming a vendor read verb is refused with a sentence saying the surface is not built, rather than silently accepted |-| A skill cannot be activated without a backtest of the exact version being activated | `apps/docs/docs/console/tenant-skills.md` (Lifecycle) | `ci.yml` api job (`test_tenant_skills.py::TestLifecycle`: activation is refused with no backtest, with a backtest of a different version, when expired, and when one evaluation is used as its own baseline; a content edit is asserted to bump the version, drop the row to draft and detach both reports, while a reformat that leaves the parsed body identical keeps them) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the rule in the migration's CHECK, in the store and on the docs page; proven able to fail by weakening the SQL clause) | core | GATED | Stated in three places on purpose. The CHECK holds against a direct fix-up; the store's refusal is what produces a sentence an operator can act on rather than a constraint name |+| A skill cannot be activated without a completed backtest of the exact version, graded over alerts that skill matches | `apps/docs/docs/console/tenant-skills.md` (Lifecycle) | `ci.yml` api job (`test_tenant_skills.py::TestLifecycle`: activation is refused with no backtest, with a backtest of a different version, when expired, and when one evaluation is used as its own baseline; a content edit is asserted to bump the version, drop the row to draft and detach both reports, while a reformat that leaves the parsed body identical keeps them. `TestActivationReadsTheBacktest` seeds the two replay runs and refuses activation when either is missing, still going or failed, and when the graded window holds no alert the skill's match block selects; `test_the_delta_is_computed_over_the_matched_alerts_and_not_the_window` pins the matched subset at 4 of a 20-alert window and fails when the comparison widens to the window. `TestMatchBlockSelection` covers each of the four match conditions) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the rule in the migration's CHECK, in the store and on the docs page; proven able to fail by weakening the SQL clause) | core | GATED | Stated in three places on purpose. The CHECK holds against a direct fix-up; the store's refusal is what produces a sentence an operator can act on rather than a constraint name. **Widened by fix-pass 3.8:** the version check alone was satisfied by two ids naming two crashed runs, or a window holding nothing the skill applies to, so activation now opens both runs. The subset is the skill's declared match scope read from each decision's recorded evidence, which is **not** a record of which alerts triage actually applied the skill to: a replay decision does not carry the skill that steered it, so the scope can be wider than the set production steered and never narrower || Every investigation a skill guided records which version guided it, and that version resolves back to its text | `apps/docs/docs/console/tenant-skills.md` (What gets recorded) | `ci.yml` agents job (`test_tenant_skill_investigation.py`: the provenance carries id, version and owner; the investigation pins the version triage already used rather than re-resolving, since the fetch is cached and an activation between the two reads would split them) + `ci.yml` api job (`test_tenant_skills.py`: a content edit leaves both versions in `aisoc_tenant_skill_versions`, and retire keeps the history while delete removes it) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py` requires the field on both `DeepInvestigationResult` and `InvestigationState`; proven able to fail by renaming it on either) | core | GATED | A recorded version with no history row is provenance-shaped and not provenance, so a skill row whose version is absent or zero is refused by the resolver rather than served || Tenant skills are frozen at the split point during a replay, and the backtest bypass is published rather than silent | `apps/docs/docs/console/tenant-skills.md` (What a backtest number does and does not say); `services/agents/app/replay/shadow.py` | `ci.yml` agents job (`test_replay_leakage.py`: a skill activated after the split never reaches the prompt, with a **sensitivity half** that runs the live reader and asserts the same poison does; the backtest candidate is asserted to reach the prompt *and* to be named in the method note with its caveat, with a sensitivity half asserting an ordinary replay of the same instant freezes it out; a skill with no activation stamp is counted the way an undated statement is) + `ci.yml` gates job (`scripts/check_triage_context_freeze.py`: every source `TriageContextReader` declares must be implemented by both readers, and every snapshot store must be filtered by `capture_context` and publish `_frozen` and `_dropped_after_split` in the method note. Proven able to fail by removing the frozen reader's method, by silencing the bypass, and by deleting one kept-count key while a neighbouring key remained, which an earlier substring version of the check missed) | core | GATED | A skill backtest deliberately applies a candidate authored after the window, which is what a backtest is. The figure is a statement about that window and not a forecast, and the method note says so in those words rather than leaving a reader to infer it || A SCIM request's tenant comes from its credential, never from the request | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `docs/decisions/0008-scim-trust-boundary.md`; `apps/docs/docs/operations/scim.md` | `isolation.yml` (`check_route_auth.py` and `check_route_tenant_scope.py` see `ScimPrincipal` as an authenticating dependency, so every one of the 17 SCIM routes is counted as authenticated rather than exempted; `aisoc_scim_tokens.tenant_id` is NOT NULL and RFC 7643 defines no tenant attribute) + `ci.yml` api job (`test_scim_provisioning.py::TestTokens` - a second tenant's credential gets 404 for a principal the first created, and discovery refuses an anonymous caller) | core | GATED | The credential is the only source of tenancy because the protocol has no field for one. There is nothing to intersect: a SCIM handler that read a tenant from anywhere would be the finding |diff --git a/services/api/app/api/v1/endpoints/tenant_skills.py b/services/api/app/api/v1/endpoints/tenant_skills.pyindex 0429ba069..24d6b637f 100644--- a/services/api/app/api/v1/endpoints/tenant_skills.py+++ b/services/api/app/api/v1/endpoints/tenant_skills.py@@ -462,7 +462,16 @@ async def backtest_tenant_skill("tenant's other active skills; the candidate carries those plus this one. Read them ""side by side at GET /evaluations/replay/{id}. This skill was authored after the window ""closed and is applied to it on purpose, so the result measures the skill against this "- "window and is not a forecast of its accuracy on new alerts."+ "window and is not a forecast of its accuracy on new alerts. "+ "Compare the two reports over the alerts this skill matches, not over their headline "+ "figures: a skill selecting a handful of a few hundred findings cannot move a headline "+ "in either direction, so a headline that barely moved says nothing about the skill. "+ "Activation applies the same rule and refuses a backtest whose window holds no alert "+ "this skill matches. "+ "A skill reaches triage only when the alert takes the LLM path, so a run with no model "+ "configured for this tenant, or one started with AISOC_DETERMINISTIC=1, produces two "+ "identical reports because the skill was never applied -- which is a different fact "+ "from a skill that was applied and changed nothing."),)diff --git a/services/api/app/services/tenant_skills/backtest.py b/services/api/app/services/tenant_skills/backtest.pynew file mode 100644index 000000000..c772bdf94--- /dev/null+++ b/services/api/app/services/tenant_skills/backtest.py@@ -0,0 +1,386 @@+"""Read a skill's two backtest runs and compare them over the alerts it matches.++Fix-pass 3.8.++Activation used to read two UUIDs and a version number. Nothing opened the+runs those ids name, so a skill activated identically whether the backtest had+completed, crashed, or was still queued, and whether the window it graded+contained a single alert the skill applies to.++Why the subset is the whole point+---------------------------------+Both runs cover the same window, so a headline difference between them is an+average over every alert in it. A skill matches a shape of alert, usually a+handful out of hundreds. Suppose four matched alerts out of twenty: a skill+that corrects every one of them moves the headline by 0.20, and a skill that+breaks every one of them moves it by -0.20, and both figures sit inside the+noise of any real queue. Averaged over a few hundred findings neither is+visible at all. The comparison that describes the *skill* is over the alerts+the skill selects, and it is the one activation is allowed to rest on.++So the gate is: both runs completed, and the matched subset is not empty. The+gate is deliberately **not** on the value of the delta. A threshold would be a+target to tune a skill against, and an organisational fact that happens not to+move last quarter's verdicts is still true about the estate.++How "the alerts the skill matches" is decided, and what that is not+--------------------------------------------------------------------+From the skill's own ``match`` block, evaluated against the evidence each+replay decision recorded: the rule id, the ATT&CK techniques, the connector+the alert came from, and the title the agent was handed as its summary. Those+are the four conditions :func:`app.context.tenant_skills.select_skill` scores+on in the agents service, read from the same places.++It is **not** a record of which alerts triage actually applied the skill to. A+replay decision does not carry the skill that steered it, so that record does+not exist to read. The difference is that agents-side selection also arbitrates+between competing skills, and a tenant whose more specific skill wins on the+same alert would have had that one applied. This subset is therefore the+skill's declared scope, which can be wider than the set production steered,+never narrower. Widening dilutes the delta toward the whole-window figure; it+cannot manufacture a match for a skill that selects nothing.+"""++from __future__ import annotations++import json+import uuid+from collections.abc import Mapping+from dataclasses import dataclass+from typing import Any++from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++from app._vendor.aisoc_benchmark.replay import ABSTENTION_VERDICTS+from app.services.tenant_skills.models import SkillMatch++__all__ = [+ "COMPLETED",+ "MatchedDelta",+ "match_from_body",+ "matched_delta",+ "selects",+]++#: The terminal status a run reaches when it produced a report.+#: ``app.services.replay_evaluation.store`` writes it; this module only reads.+COMPLETED = "completed"++#: Nothing useful comes of comparing more than this, and a window larger than+#: it was truncated when the decisions were stored: ``list_decisions`` caps at+#: the same figure. Stated here so the two cannot drift into disagreeing about+#: how much of a long window the comparison saw.+MAX_DECISIONS = 2000+++@dataclass(frozen=True)+class MatchedDelta:+ """What the two runs say about the alerts one skill selects.++ Every mean carries the count it was computed over, and an accuracy with no+ labelled alert behind it is ``None`` rather than ``0.0``: a zero in an+ accuracy column says the agent got every one of these wrong, which is a+ different fact from no analyst having said.+ """++ #: Decisions the two runs have in common, matched or not. The denominator+ #: the old whole-window reading used. Not "graded": it counts unlabelled+ #: findings too, and an accuracy denominator that quietly includes them+ #: is how a rate comes to describe more rows than anybody scored.+ window_compared: int+ #: Of those, the ones this skill's match block selects.+ matched: int+ #: Of those, the ones an analyst labelled and *both* runs answered.+ matched_graded: int+ #: Matched findings the two runs disagree about. Computable with no+ #: labels at all, and the only figure that is zero exactly when the skill+ #: changed nothing on the alerts it applies to.+ verdicts_changed: int++ baseline_accuracy: float | None+ candidate_accuracy: float | None+ accuracy_delta: float | None++ #: The same comparison over the whole window, kept beside the matched one+ #: rather than dropped. The gap between the two is what this module exists+ #: to make visible.+ window_accuracy_delta: float | None++ #: Set when activation must refuse, and phrased for the operator. ``None``+ #: means the comparison stands.+ blocked_reason: str | None = None++ def as_log_fields(self) -> dict[str, Any]:+ return {+ "window_compared": self.window_compared,+ "matched": self.matched,+ "matched_graded": self.matched_graded,+ "verdicts_changed": self.verdicts_changed,+ "baseline_accuracy": self.baseline_accuracy,+ "candidate_accuracy": self.candidate_accuracy,+ "accuracy_delta": self.accuracy_delta,+ "window_accuracy_delta": self.window_accuracy_delta,+ }+++def _blocked(reason: str) -> MatchedDelta:+ return MatchedDelta(+ window_compared=0,+ matched=0,+ matched_graded=0,+ verdicts_changed=0,+ baseline_accuracy=None,+ candidate_accuracy=None,+ accuracy_delta=None,+ window_accuracy_delta=None,+ blocked_reason=reason,+ )+++def match_from_body(body: Mapping[str, Any]) -> SkillMatch:+ """Just the match block out of a stored skill, with its parse-time casing.++ Narrower than :func:`app.services.tenant_skills.models.skill_from_body` on+ purpose. That one rebuilds the whole document and raises on a body with no+ expiry; this runs on the activation path, where a parse error would reach+ the route as a 500 rather than as the 409 every other refusal produces,+ and nothing here reads a field outside ``match``.+ """+ raw = body.get("match")+ raw = raw if isinstance(raw, Mapping) else {}++ def _strings(key: str, *, upper: bool = False, lower: bool = False) -> tuple[str, ...]:+ values = raw.get(key)+ if not isinstance(values, list):+ return ()+ out = []+ for item in values:+ if not isinstance(item, str) or not item.strip():+ continue+ text_value = item.strip()+ out.append(text_value.upper() if upper else text_value.lower() if lower else text_value)+ return tuple(out)++ return SkillMatch(+ techniques=_strings("techniques", upper=True),+ rule_ids=_strings("rule_ids"),+ sources=_strings("sources", lower=True),+ keywords=_strings("keywords", lower=True),+ )+++def selects(match: SkillMatch, decision: Mapping[str, Any]) -> bool:+ """Whether this skill's match block applies to one replayed decision.++ The four conditions are read the way the agents-side selector reads them,+ including the casing each is normalised to at parse time and the rule that+ a skill written against a parent technique matches a sub-technique alert.+ Scoring is absent on purpose: the selector ranks several skills against one+ alert, and the question here is whether this one skill applies at all.+ """+ evidence = decision.get("evidence")+ evidence = evidence if isinstance(evidence, Mapping) else {}++ rule_id = str(decision.get("rule_id") or evidence.get("rule_id") or "").strip()+ if rule_id and rule_id in match.rule_ids:+ return True++ mapped = {str(t).upper() for t in (evidence.get("mitre_techniques") or []) if str(t).strip()}+ for technique in match.techniques:+ if any(m == technique or m.startswith(technique + ".") for m in mapped):+ return True++ source = str(evidence.get("connector_type") or evidence.get("source") or decision.get("vendor") or "").strip().lower()+ if source and source in match.sources:+ return True++ # The title is what ``build_state`` puts in ``alert_summary``, which is the+ # string the selector searches, so a keyword that would hit in production+ # hits here.+ title = str(evidence.get("title") or "").lower()+ return bool(title) and any(keyword in title for keyword in match.keywords)+++def _answered(decision: Mapping[str, Any]) -> bool:+ """A graded answer: labelled, not an abstention, and not a refusal.++ ``ABSTENTION_VERDICTS`` comes from the replay scorer rather than from a+ second list here, so an alert excluded from the published accuracy is+ excluded from this one.+ """+ if not decision.get("labelled") or decision.get("error"):+ return False+ return str(decision.get("verdict") or "") not in ABSTENTION_VERDICTS+++def _accuracy(decisions: list[Mapping[str, Any]]) -> tuple[int, float | None]:+ answered = [d for d in decisions if _answered(d)]+ if not answered:+ return 0, None+ correct = sum(1 for d in answered if d.get("verdict") == d.get("expected_disposition"))+ return len(answered), correct / len(answered)+++def compare(+ match: SkillMatch,+ baseline: list[Mapping[str, Any]],+ candidate: list[Mapping[str, Any]],+) -> MatchedDelta:+ """Pair two runs' decisions by finding and compare the matched ones.++ Pairing by ``finding_id`` rather than by position: the two runs grade the+ same window, but a normalisation failure on one side drops a decision, and+ comparing two lists of different lengths by index would silently compare+ different alerts.+ """+ by_finding = {str(d.get("finding_id") or ""): d for d in baseline}+ pairs: list[tuple[Mapping[str, Any], Mapping[str, Any]]] = []+ for row in candidate:+ other = by_finding.get(str(row.get("finding_id") or ""))+ if other is not None:+ pairs.append((other, row))++ matched = [(b, c) for b, c in pairs if selects(match, c)]++ # Each side scored over its own answered rows, because this figure exists+ # to reproduce the gap between the two published headlines, and those are+ # computed independently, one per report.+ _, window_baseline_accuracy = _accuracy([b for b, _ in pairs])+ _, window_candidate_accuracy = _accuracy([c for _, c in pairs])+ window_delta = (+ window_candidate_accuracy - window_baseline_accuracy+ if window_baseline_accuracy is not None and window_candidate_accuracy is not None+ else None+ )++ # One denominator for both sides of the matched comparison, unlike the+ # window figure above: over a handful of alerts a finding only one run+ # answered would move the delta without either agent having changed its+ # mind about anything.+ gradable = [(b, c) for b, c in matched if _answered(b) and _answered(c)]+ _, baseline_accuracy = _accuracy([b for b, _ in gradable])+ _, candidate_accuracy = _accuracy([c for _, c in gradable])+ accuracy_delta = candidate_accuracy - baseline_accuracy if baseline_accuracy is not None and candidate_accuracy is not None else None++ return MatchedDelta(+ window_compared=len(pairs),+ matched=len(matched),+ matched_graded=len(gradable),+ verdicts_changed=sum(1 for b, c in matched if b.get("verdict") != c.get("verdict")),+ baseline_accuracy=baseline_accuracy,+ candidate_accuracy=candidate_accuracy,+ accuracy_delta=accuracy_delta,+ window_accuracy_delta=window_delta,+ blocked_reason=None,+ )+++async def matched_delta(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ match: SkillMatch,+ baseline_evaluation_id: uuid.UUID | None,+ candidate_evaluation_id: uuid.UUID | None,+) -> MatchedDelta:+ """The comparison, or the reason there is none to make."""+ if baseline_evaluation_id is None or candidate_evaluation_id is None: # pragma: no cover - the caller checks first+ return _blocked("this skill has no backtest attached")++ for label, evaluation_id in (("baseline", baseline_evaluation_id), ("candidate", candidate_evaluation_id)):+ status, error = await _evaluation_state(db, tenant_id=tenant_id, evaluation_id=evaluation_id)+ if status is None:+ return _blocked(+ f"the attached {label} backtest names replay run {evaluation_id} and this tenant has no such "+ f"replay run. Re-run the backtest: activation reads both reports, and an id pointing at "+ f"nothing cannot be read."+ )+ if status != COMPLETED:+ if status == "failed":+ return _blocked(+ f"the {label} backtest run failed and graded nothing: {error or 'no reason was recorded'}. "+ f"Fix that and re-run the backtest. Activating on a failed run would put this skill in "+ f"front of every matching alert on the strength of a measurement that never happened."+ )+ return _blocked(+ f"the {label} backtest run has not finished; it is {status}. Wait for both runs to complete, "+ f"then activate. Nothing is wrong with the skill."+ )++ baseline = await _decisions(db, tenant_id=tenant_id, evaluation_id=baseline_evaluation_id)+ candidate = await _decisions(db, tenant_id=tenant_id, evaluation_id=candidate_evaluation_id)+ delta = compare(match, baseline, candidate)++ if delta.matched == 0:+ if delta.window_compared == 0:+ return _blocked(+ "both backtest runs completed and recorded no decisions in common, so there is nothing to "+ "compare. Re-run the backtest over a window that holds closed findings."+ )+ return _blocked(+ f"the backtest compared {delta.window_compared} alerts across the two runs and this skill's "+ f"match block selects none of them, so the difference between the two reports is entirely over "+ f"alerts this skill never touches. Re-run the backtest over a window containing alerts this "+ f"skill matches, or widen the match block to the alerts you meant."+ )+ return delta+++async def _evaluation_state(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ evaluation_id: uuid.UUID,+) -> tuple[str | None, str | None]:+ """One run's status and failure reason, or ``(None, None)`` when it is gone.++ Tenant-scoped in the predicate rather than by RLS alone, the same way every+ other read of this table is: another tenant's run must read as absent.+ """+ row = (+ await db.execute(+ text("SELECT status, error FROM aisoc_replay_evaluations WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=evaluation_id, tenant_id=tenant_id+ )+ )+ ).fetchone()+ if row is None:+ return None, None+ return str(row.status), (str(row.error)[:400] if row.error else None)+++async def _decisions(db: AsyncSession, *, tenant_id: uuid.UUID, evaluation_id: uuid.UUID) -> list[Mapping[str, Any]]:+ """Every decision one run recorded, as the dicts the runner wrote.++ Ordered by ``finding_id`` so a truncated read takes the same prefix from+ both runs: comparing the first two thousand of one against a differently+ ordered first two thousand of the other would pair alerts that are not the+ same alert.+ """+ rows = (+ await db.execute(+ text(+ "SELECT decision FROM aisoc_replay_decisions "+ "WHERE evaluation_id = :evaluation_id AND tenant_id = :tenant_id "+ "ORDER BY finding_id LIMIT :limit"+ ).bindparams(evaluation_id=evaluation_id, tenant_id=tenant_id, limit=MAX_DECISIONS)+ )+ ).fetchall()+ return [parsed for row in rows if (parsed := _as_mapping(row.decision)) is not None]+++def _as_mapping(value: Any) -> Mapping[str, Any] | None:+ """Read a JSONB column back, whatever the driver handed over.++ Same reader as ``replay_evaluation.store``: these statements go through+ ``text()``, so the value arrives parsed on one driver and as a string on+ another, and a row that is neither is skipped rather than guessed at.+ """+ if isinstance(value, str):+ try:+ parsed = json.loads(value)+ except ValueError:+ return None+ return parsed if isinstance(parsed, dict) else None+ return value if isinstance(value, Mapping) else Nonediff --git a/services/api/app/services/tenant_skills/store.py b/services/api/app/services/tenant_skills/store.pyindex a709b9bb2..17427eaa1 100644--- a/services/api/app/services/tenant_skills/store.py+++ b/services/api/app/services/tenant_skills/store.py@@ -19,6 +19,17 @@ baseline is a number rather than a comparison. The database constraint saysthe same thing, so neither this module nor a later one can be the only placethe rule lives.+**Activation reads those two runs rather than only their ids.** Fix-pass 3.8.+An id and a version number say that a report was attached, not that it says+anything: two crashed runs, two queued ones, or two runs over a window holding+no alert this skill selects all satisfy the check above. So activation opens+both runs, requires that both completed, and compares them over the alerts the+skill's match block selects rather than over the whole window.+``app.services.tenant_skills.backtest`` explains why the subset is the point;+the short version is that a skill matching four alerts in two hundred cannot+move a headline either way, so the headline cannot be what activation rests+on. The gate is that the comparison exists, never that it is favourable.+What a backtest is here-----------------------Two Phase 1 replay evaluations over the same history window: one with the@@ -48,6 +59,7 @@ from app.models.tenant_skill import (from app.models.tenant_skill import (TenantSkill as TenantSkillRow,)+from app.services.tenant_skills import backtest as backtest_readerfrom app.services.tenant_skills.models import SkillParseError, TenantSkill, parse_skill_yaml, skill_from_bodyfrom app.services.tenant_skills.tools import tool_inventory_for_tenant, validate_expected_pivots@@ -325,7 +337,12 @@ async def activate_skill(actor_id: uuid.UUID | None,now: datetime | None = None,) -> TenantSkillRow:- """Put a backtested skill into service. Four refusals, each with its own reason."""+ """Put a backtested skill into service, refusing anything that would put untested guidance in front of alerts.++ Every refusal says which thing is wrong and what to do about it. They are+ deliberately not counted here: the count drifted the moment this function+ grew the two refusals fix-pass 3.8 added.+ """moment = now or datetime.now(UTC)row = await _row(db, tenant_id, skill_id)@@ -349,6 +366,16 @@ async def activate_skill(if row.status == ACTIVE:raise SkillLifecycleError("this skill is already active")+ delta = await backtest_reader.matched_delta(+ db,+ tenant_id=tenant_id,+ match=backtest_reader.match_from_body(row.body or {}),+ baseline_evaluation_id=row.backtest_baseline_id,+ candidate_evaluation_id=row.backtest_evaluation_id,+ )+ if delta.blocked_reason is not None:+ raise SkillLifecycleError(delta.blocked_reason)+row.status = ACTIVErow.activated_at = momentrow.activated_by = actor_id@@ -360,6 +387,7 @@ async def activate_skill(skill_id=skill_id,version=row.version,backtest_evaluation_id=str(row.backtest_evaluation_id),+ **delta.as_log_fields(),)return rowdiff --git a/services/api/tests/test_tenant_skills.py b/services/api/tests/test_tenant_skills.pyindex 07a6cbff5..43674e830 100644--- a/services/api/tests/test_tenant_skills.py+++ b/services/api/tests/test_tenant_skills.py@@ -12,7 +12,9 @@ Five properties, each asserted by name below:* an edit bumps the version and drops the skill back to draft, detaching thebacktest, so a report can never describe text nobody is running* activation refuses every way of reaching it without a current backtest, and- the message names which one+ the message names which one, including the two refusals that need the+ replay rows themselves: a run that did not complete, and a window holding+ no alert this skill's match block selects* the internal route is service-token only, and a valid console session is notenough@@ -28,6 +30,8 @@ loses it, which is what keeps one from becoming the only guard.from __future__ import annotations+import json+import sqlite3import uuidfrom datetime import UTC, datetime, timedelta@@ -42,16 +46,24 @@ from app.models.connector import Connectorfrom app.models.mcp_server import McpServerfrom app.models.tenant_skill import ACTIVE, BACKTESTED, DRAFT, RETIRED, TenantSkill, TenantSkillVersionfrom app.services.agent_tools import vendor_reads+from app.services.tenant_skills import backtest as skill_backtestfrom app.services.tenant_skills import storefrom app.services.tenant_skills.models import SkillParseError, parse_skill_yamlfrom app.services.tenant_skills.tools import BUILTIN_PIVOTS, ToolInventory, tool_inventory_for_tenant, validate_expected_pivotsfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from sqlalchemy import text as sa_textfrom sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.dialects.postgresql import UUID as PgUUIDfrom sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom sqlalchemy.ext.compiler import compiles+# The replay tables have no ORM model -- they are read and written through+# ``text()`` -- so their UUID parameters arrive at the driver as ``uuid.UUID``.+# asyncpg encodes those natively; sqlite3 refuses an unknown type outright, and+# the symptom is an InterfaceError rather than a wrong answer.+sqlite3.register_adapter(uuid.UUID, str)+TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")OTHER_TENANT = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")USER = uuid.UUID("11111111-1111-1111-1111-111111111111")@@ -123,20 +135,145 @@ def _quiet_action_registry(monkeypatch):yield+#: The two replay tables activation now reads, reduced to the columns it+#: reads. Written out rather than created from metadata because migration 065+#: declares them in SQL and no ORM model exists to render; the column names and+#: types here are the ones the production statements bind against.+_REPLAY_DDL = (+ """+ CREATE TABLE aisoc_replay_evaluations (+ id CHAR(36) PRIMARY KEY,+ tenant_id CHAR(36) NOT NULL,+ status TEXT NOT NULL,+ error TEXT+ )+ """,+ """+ CREATE TABLE aisoc_replay_decisions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ evaluation_id CHAR(36) NOT NULL,+ tenant_id CHAR(36) NOT NULL,+ finding_id TEXT NOT NULL,+ vendor TEXT NOT NULL DEFAULT '',+ rule_id TEXT,+ expected_disposition TEXT NOT NULL DEFAULT '',+ labelled BOOLEAN NOT NULL DEFAULT 0,+ verdict TEXT,+ tier TEXT NOT NULL DEFAULT '',+ decision TEXT NOT NULL DEFAULT '{}'+ )+ """,+)++@pytest_asyncio.fixtureasync def session_factory():engine = create_async_engine("sqlite+aiosqlite:///:memory:")async with engine.begin() as conn:- # Only these three. A whole-metadata create_all drags in models using+ # Only these four. A whole-metadata create_all drags in models using# Postgres ARRAY, which SQLite cannot render.await conn.run_sync(Base.metadata.create_all,tables=[TenantSkill.__table__, TenantSkillVersion.__table__, McpServer.__table__, Connector.__table__],)+ for statement in _REPLAY_DDL:+ await conn.execute(sa_text(statement))yield async_sessionmaker(engine, expire_on_commit=False)await engine.dispose()+def _decision(+ *,+ finding_id: str,+ verdict: str,+ expected: str = "malicious",+ rule_id: str = "rule-unrelated",+ techniques: tuple[str, ...] = (),+ title: str = "Something happened",+ labelled: bool = True,+) -> dict:+ """One replayed decision, in the shape ``ReplayDecision.as_dict`` writes.++ ``evidence`` is the fused alert the agent was handed, which is where the+ source, the techniques and the title the match block reads come from.+ """+ return {+ "finding_id": finding_id,+ "vendor": "splunk",+ "rule_id": rule_id,+ "expected_disposition": expected,+ "labelled": labelled,+ "verdict": verdict,+ "tier": "llm",+ "evidence": {+ "title": title,+ "rule_id": rule_id,+ "connector_type": "splunk",+ "mitre_techniques": list(techniques),+ },+ }+++async def _seed_evaluation(db, *, status: str, decisions: tuple[dict, ...] = (), error: str | None = None) -> uuid.UUID:+ """Insert one replay run and the decisions behind it. Returns its id."""+ evaluation_id = uuid.uuid4()+ await db.execute(+ sa_text("INSERT INTO aisoc_replay_evaluations (id, tenant_id, status, error) VALUES (:id, :tenant, :status, :error)").bindparams(+ id=evaluation_id, tenant=TENANT, status=status, error=error+ )+ )+ for decision in decisions:+ await db.execute(+ sa_text(+ "INSERT INTO aisoc_replay_decisions "+ "(evaluation_id, tenant_id, finding_id, vendor, rule_id, expected_disposition, labelled, verdict, tier, decision) "+ "VALUES (:evaluation_id, :tenant, :finding_id, :vendor, :rule_id, :expected, :labelled, :verdict, :tier, :decision)"+ ).bindparams(+ evaluation_id=evaluation_id,+ tenant=TENANT,+ finding_id=decision["finding_id"],+ vendor=decision["vendor"],+ rule_id=decision["rule_id"],+ expected=decision["expected_disposition"],+ labelled=decision["labelled"],+ verdict=decision["verdict"],+ tier=decision["tier"],+ decision=json.dumps(decision, sort_keys=True),+ )+ )+ return evaluation_id+++#: One matched alert (the skill names this rule id) and one the skill does not+#: select, so a default backtest is enough to activate and the matched subset+#: is still a strict subset of the window.+def _default_window(*, matched_verdict: str) -> tuple[dict, ...]:+ return (+ _decision(finding_id="f-matched", verdict=matched_verdict, rule_id="rule-encoded-powershell"),+ _decision(finding_id="f-other", verdict="malicious", rule_id="rule-unrelated"),+ )+++async def _attach_completed_backtest(+ db,+ *,+ skill_id: str = "finance-batch-powershell",+ baseline: tuple[dict, ...] | None = None,+ candidate: tuple[dict, ...] | None = None,+) -> tuple[uuid.UUID, uuid.UUID]:+ """Two completed runs over a window this skill matches, attached to it."""+ baseline_id = await _seed_evaluation(db, status="completed", decisions=baseline or _default_window(matched_verdict="benign"))+ candidate_id = await _seed_evaluation(db, status="completed", decisions=candidate or _default_window(matched_verdict="malicious"))+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id=skill_id,+ baseline_evaluation_id=baseline_id,+ candidate_evaluation_id=candidate_id,+ )+ return baseline_id, candidate_id++# ---------------------------------------------------------------------------# The document# ---------------------------------------------------------------------------@@ -493,16 +630,9 @@ class TestLifecycle:@pytest.mark.asyncioasync def test_activation_stamps_the_version_row_with_the_backtest(self, session_factory) -> None:""" "Its backtest report is attached to its activation" is this assertion."""- baseline, candidate = uuid.uuid4(), uuid.uuid4()async with session_factory() as db:await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())- await store.attach_backtest(- db,- tenant_id=TENANT,- skill_id="finance-batch-powershell",- baseline_evaluation_id=baseline,- candidate_evaluation_id=candidate,- )+ baseline, candidate = await _attach_completed_backtest(db)row = await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)await db.commit()@@ -520,13 +650,7 @@ class TestLifecycle:"""Expiry is applied in the query, so a skill stops steering the moment it lapses."""async with session_factory() as db:await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())- await store.attach_backtest(- db,- tenant_id=TENANT,- skill_id="finance-batch-powershell",- baseline_evaluation_id=uuid.uuid4(),- candidate_evaluation_id=uuid.uuid4(),- )+ await _attach_completed_backtest(db)await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)await db.commit()@@ -539,13 +663,7 @@ class TestLifecycle:async def test_a_retired_skill_keeps_its_history_and_stops_being_served(self, session_factory) -> None:async with session_factory() as db:await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())- await store.attach_backtest(- db,- tenant_id=TENANT,- skill_id="finance-batch-powershell",- baseline_evaluation_id=uuid.uuid4(),- candidate_evaluation_id=uuid.uuid4(),- )+ await _attach_completed_backtest(db)await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)row = await store.retire_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell")await db.commit()@@ -560,6 +678,299 @@ class TestLifecycle:assert history[0].body["guidance"]+class TestActivationReadsTheBacktest:+ """Activation reads the two runs it names, rather than only their ids.++ Fix-pass 3.8. The version check above answers "does this report describe+ this text". These answer the two questions after it: did the runs that+ produced the report finish, and did the report grade anything this skill+ applies to. A pair of ids that point at two crashed runs, or at a window+ holding no alert the skill selects, satisfies every earlier refusal.+ """++ @pytest.mark.asyncio+ async def test_activation_is_refused_when_an_attached_run_does_not_exist(self, session_factory) -> None:+ """Two ids pointing at nothing are not a backtest.++ Nothing in the schema makes the attached ids foreign keys, so a+ fix-up, a purge or a bug leaves a skill naming runs that are gone.+ """+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=uuid.uuid4(),+ candidate_evaluation_id=uuid.uuid4(),+ )+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ assert "no such replay run" in str(exc.value)++ @pytest.mark.asyncio+ async def test_activation_is_refused_when_both_runs_failed(self, session_factory) -> None:+ """A failed backtest measured nothing, and measured nothing loudly.++ This is the defect fix-pass 3.8 names: the two ids are attached, the+ version matches, and both runs died without grading a single finding.+ """+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ baseline = await _seed_evaluation(db, status="failed", error="the actions service is unreachable")+ candidate = await _seed_evaluation(db, status="failed", error="the actions service is unreachable")+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=baseline,+ candidate_evaluation_id=candidate,+ )+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ message = str(exc.value)+ assert "failed" in message+ # The reason the run gave, so the operator fixes the run rather than+ # the skill. A refusal naming only the status sends them to re-read+ # their YAML for a fault that is not in it.+ assert "actions service is unreachable" in message++ @pytest.mark.asyncio+ async def test_activation_is_refused_while_a_run_is_still_going(self, session_factory) -> None:+ """Queued and running are not failures, and the message must not read as one."""+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ baseline = await _seed_evaluation(db, status="completed", decisions=_default_window(matched_verdict="benign"))+ candidate = await _seed_evaluation(db, status="running")+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=baseline,+ candidate_evaluation_id=candidate,+ )+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ message = str(exc.value)+ assert "running" in message+ assert "has not finished" in message++ @pytest.mark.asyncio+ async def test_activation_is_refused_when_the_window_holds_no_alert_this_skill_matches(self, session_factory) -> None:+ """Two completed runs over a window the skill does not apply to.++ Both runs graded the same two hundred alerts and the skill selects+ none of them, so every difference between the two reports comes from+ alerts this skill never touches. The headline delta is a statement+ about the window, not about the skill.+ """+ unrelated = tuple(+ _decision(finding_id=f"f-{index}", verdict="malicious", rule_id="rule-unrelated", title="Impossible travel")+ for index in range(8)+ )+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ baseline = await _seed_evaluation(db, status="completed", decisions=unrelated)+ candidate = await _seed_evaluation(db, status="completed", decisions=unrelated)+ await store.attach_backtest(+ db,+ tenant_id=TENANT,+ skill_id="finance-batch-powershell",+ baseline_evaluation_id=baseline,+ candidate_evaluation_id=candidate,+ )+ await db.commit()+ with pytest.raises(store.SkillLifecycleError) as exc:+ await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ message = str(exc.value)+ assert "match block selects none of them" in message+ # The window size, so the operator can tell "nothing was graded" from+ # "plenty was graded and none of it was yours".+ assert "8" in message++ @pytest.mark.asyncio+ async def test_the_delta_is_computed_over_the_matched_alerts_and_not_the_window(self, session_factory) -> None:+ """The number activation records is the one about this skill.++ The window is twenty alerts; the skill matches four. The candidate run+ fixes all four and changes nothing else, so the matched delta is 1.00+ and the whole-window delta is 0.20. A gate reading the second would+ call a skill that fixed every alert it touches a 20% improvement, and+ would call a skill that broke every one of them a rounding error.+ """+ matched = tuple(_decision(finding_id=f"m-{index}", verdict="benign", rule_id="rule-encoded-powershell") for index in range(4))+ others = tuple(_decision(finding_id=f"o-{index}", verdict="malicious", rule_id="rule-unrelated") for index in range(16))+ fixed = tuple(_decision(finding_id=f"m-{index}", verdict="malicious", rule_id="rule-encoded-powershell") for index in range(4))++ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await _attach_completed_backtest(db, baseline=matched + others, candidate=fixed + others)+ row = await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ await db.commit()+ assert row.status == ACTIVE++ delta = await skill_backtest.matched_delta(+ db,+ tenant_id=TENANT,+ match=skill_backtest.match_from_body(row.body),+ baseline_evaluation_id=row.backtest_baseline_id,+ candidate_evaluation_id=row.backtest_evaluation_id,+ )++ assert delta.blocked_reason is None+ assert (delta.window_compared, delta.matched, delta.matched_graded) == (20, 4, 4)+ assert (delta.baseline_accuracy, delta.candidate_accuracy) == (0.0, 1.0)+ assert delta.accuracy_delta == 1.0+ # The figure the old activation would have rested on, kept beside it+ # rather than dropped, because the gap between the two is the point.+ assert delta.window_accuracy_delta == pytest.approx(0.2)+ assert delta.verdicts_changed == 4++ @pytest.mark.asyncio+ async def test_a_skill_that_changed_nothing_still_activates(self, session_factory) -> None:+ """The gate is that a delta exists, never that it is favourable.++ A threshold on the value would be a target to tune a skill against,+ and an organisational fact that happens not to move last quarter's+ verdicts is still true about the estate.+ """+ window = _default_window(matched_verdict="malicious")+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await _attach_completed_backtest(db, baseline=window, candidate=window)+ row = await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ await db.commit()++ delta = await skill_backtest.matched_delta(+ db,+ tenant_id=TENANT,+ match=skill_backtest.match_from_body(row.body),+ baseline_evaluation_id=row.backtest_baseline_id,+ candidate_evaluation_id=row.backtest_evaluation_id,+ )++ assert row.status == ACTIVE+ assert (delta.verdicts_changed, delta.accuracy_delta) == (0, 0.0)++ @pytest.mark.asyncio+ async def test_a_matched_alert_nobody_labelled_leaves_the_accuracy_unmeasured(self, session_factory) -> None:+ """An unlabelled window can still show what changed, and must not show an accuracy.++ Zero in an accuracy column reads as "the agent got every one of these+ wrong", which is a different fact from "no analyst said".+ """+ unlabelled = (+ _decision(finding_id="m-0", verdict="benign", rule_id="rule-encoded-powershell", labelled=False, expected="unlabeled"),+ )+ changed = (+ _decision(finding_id="m-0", verdict="malicious", rule_id="rule-encoded-powershell", labelled=False, expected="unlabeled"),+ )+ async with session_factory() as db:+ await store.save_skill(db, tenant_id=TENANT, author_id=USER, source_yaml=_yaml())+ await _attach_completed_backtest(db, baseline=unlabelled, candidate=changed)+ row = await store.activate_skill(db, tenant_id=TENANT, skill_id="finance-batch-powershell", actor_id=USER)+ await db.commit()++ delta = await skill_backtest.matched_delta(+ db,+ tenant_id=TENANT,+ match=skill_backtest.match_from_body(row.body),+ baseline_evaluation_id=row.backtest_baseline_id,+ candidate_evaluation_id=row.backtest_evaluation_id,+ )++ assert delta.matched == 1+ assert delta.matched_graded == 0+ assert delta.accuracy_delta is None+ assert delta.verdicts_changed == 1+++class TestMatchBlockSelection:+ """Which alerts a skill's own ``match`` block selects.++ The four conditions are the ones ``select_skill`` scores on in the agents+ service, and each is asserted here against the evidence a replay records.+ """++ @pytest.mark.parametrize(+ ("decision_kwargs", "selected"),+ [+ ({"rule_id": "rule-encoded-powershell"}, True),+ ({"rule_id": "rule-something-else"}, False),+ # A sub-technique alert matches a skill written against the+ # parent, the reading both selectors use.+ ({"techniques": ("T1059.001",)}, True),+ ({"techniques": ("T1059",)}, False),+ ({"techniques": ("T1078.004",)}, False),+ ],+ )+ def test_each_condition(self, decision_kwargs, selected) -> None:+ skill = parse_skill_yaml(_yaml())+ decision = _decision(finding_id="f", verdict="benign", **{"rule_id": "rule-unrelated", **decision_kwargs})+ assert skill_backtest.selects(skill.match, decision) is selected++ def test_a_parent_technique_in_the_skill_selects_a_sub_technique_alert(self) -> None:+ source = _drop_block(_yaml(), "match") + "\nmatch:\n techniques: [T1059]"+ skill = parse_skill_yaml(source)+ assert skill_backtest.selects(skill.match, _decision(finding_id="f", verdict="benign", techniques=("T1059.001",)))++ def test_a_keyword_is_read_from_the_title_the_agent_was_given(self) -> None:+ source = _drop_block(_yaml(), "match") + "\nmatch:\n keywords: [svc_batch]"+ skill = parse_skill_yaml(source)+ assert skill_backtest.selects(skill.match, _decision(finding_id="f", verdict="benign", title="Encoded PowerShell by SVC_BATCH"))+ assert not skill_backtest.selects(skill.match, _decision(finding_id="f", verdict="benign", title="Impossible travel"))++ def test_the_source_condition_reads_the_connector_the_alert_came_from(self) -> None:+ source = _drop_block(_yaml(), "match") + "\nmatch:\n sources: [splunk]"+ skill = parse_skill_yaml(source)+ assert skill_backtest.selects(skill.match, _decision(finding_id="f", verdict="benign"))++ def test_a_body_whose_casing_was_never_normalised_still_selects(self) -> None:+ """Activation reads the stored JSONB, not the document, so the read normalises too.++ A body the parser wrote is already canonical, so comparing+ ``match_from_body(skill.as_dict())`` against ``skill.match`` compares+ the parser with a copy of itself: it passes with the normalisation+ deleted. This body is the shape a direct fix-up or an older parser+ leaves behind, and it is the one that tells the two apart.+ """+ stored = {+ "match": {+ "techniques": ["t1059.001"],+ "rule_ids": ["rule-encoded-powershell"],+ "sources": ["CrowdStrike"],+ "keywords": ["SVC_Batch"],+ }+ }+ match = skill_backtest.match_from_body(stored)+ assert match.techniques == ("T1059.001",)+ assert match.sources == ("crowdstrike",)+ assert match.keywords == ("svc_batch",)+ assert skill_backtest.selects(match, _decision(finding_id="f", verdict="benign", techniques=("T1059.001",)))+ assert skill_backtest.selects(match, _decision(finding_id="f", verdict="benign", title="Encoded PowerShell by svc_batch"))++ def test_the_parser_and_the_stored_read_agree_on_a_document(self) -> None:+ """The round trip, which the casing test above cannot cover on its own."""+ skill = parse_skill_yaml(_yaml())+ assert skill_backtest.match_from_body(skill.as_dict()) == skill.match++ def test_a_body_with_no_match_block_selects_nothing(self) -> None:+ """A body whose block was emptied must refuse every alert, never accept every one.++ The parser already refuses an empty match block at authoring time, so+ this is the read path's own floor: the wrong direction here would let a+ skill with no conditions claim the whole window as its matched set,+ which is the comparison this module exists to stop activation resting+ on.+ """+ match = skill_backtest.match_from_body({})+ assert match.is_empty()+ assert not skill_backtest.selects(match, _decision(finding_id="f", verdict="benign", rule_id="rule-encoded-powershell"))++# ---------------------------------------------------------------------------# Routes# ---------------------------------------------------------------------------@@ -700,13 +1111,7 @@ def _activate(session_factory, skill_id: str) -> None:async def _run() -> None:async with session_factory() as db:- await store.attach_backtest(- db,- tenant_id=TENANT,- skill_id=skill_id,- baseline_evaluation_id=uuid.uuid4(),- candidate_evaluation_id=uuid.uuid4(),- )+ await _attach_completed_backtest(db, skill_id=skill_id)await store.activate_skill(db, tenant_id=TENANT, skill_id=skill_id, actor_id=USER)await db.commit()