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
Evidence acquisition the agent recommended and nothing could run (#803)
Beenu Arora26e000d340cc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4aa44fa14..4f8ad335e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Nothing in `apps/web` consumes these three routes; it calls`/mssp/children`, which is unchanged.+- **Two `ActionType` members are removed: `add_ioc_to_blocklist` and+ `run_playbook`.** Neither had an executor. `POST /actions` accepted both and+ answered `No executor found for action type`, which reads as a broken+ deployment rather than a verb nobody built; it now rejects them at+ validation. A verb with no implementation path should leave the surface+ rather than sit on it dead.++ Why neither could be preserved by implementing it:++ - `add_ioc_to_blocklist` was a second name for `block_ioc`, which has a+ Defender arm, a capability contract, a registered adapter and a place in+ the vocabulary. Two names for one verb means half the callers reach the+ dead one. Use `block_ioc`.+ - `run_playbook` is the wrong shape for this registry rather than a missing+ feature. Playbook execution lives in `services/agents` and always has, and+ the contract in this service belongs to the *verb* — "run an arbitrary+ bundle of verbs" has no verb-level impact, reversal or verification probe+ to declare. Approving it once would execute whatever steps it contained+ without each step meeting its own contract, which is precisely what the+ per-capability contract exists to prevent. Playbooks already dispatch step+ by step through this service, so every step is graded on the way past.++ The actions service's `ActionType` is not part of `docs/openapi.yaml`, so+ the breaking-change gate does not see this; it is recorded here because a+ dropped enum value is a break whether or not a workflow notices.+### Added- **Tool attribution is now prevented at commit time and blocked in CI.** AiSOC@@ -195,6 +221,83 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The agent recommended evidence acquisition the platform could not+ perform.** `capture_forensics` was an `ActionType` with no executor+ anywhere, and `services/agents/app/agents/investigation_agent.py` proposes+ it by name whenever an investigation reaches the C2 or exfiltration stage,+ with `requires_approval=True`. So on the most serious class of incident the+ product raised an approval for forensic acquisition and failed with `No+ executor found for action type` when an analyst approved it — a control+ reachable from a recommendation and dead on approval.++ It now has a Microsoft Defender arm that collects an investigation package,+ declared LOW impact and **analyst-gated**. Analyst rather than automatic for+ the reason that separated `suppress_alert` from `update_alert_disposition`+ at an identical impact tier: the question is what bounds the verb. The+ writeback is bounded by a disposition mapping that refuses to close a+ confirmed true positive; this verb has no bound at all — it collects+ whatever the vendor package contains from whichever host it is pointed at,+ and the result is a copy of somebody's endpoint in a vendor cloud behind a+ download URI. Pointed at the wrong host that is a data-handling event nobody+ can take back.++ Only Defender, deliberately. MDE's investigation package is a whole-host+ artefact bundle whose completion state and download URI are both readable.+ CrowdStrike RTR's `get` retrieves one *named file*, which is a different+ verb with a different blast radius; wiring it here would make one capability+ mean two things depending on the tenant's vendor. Without MDE credentials+ the executor simulates and says which credentials would enable it, rather+ than reporting an acquisition that did not happen.++ The probe is real and reads the package back. Acquisition is asynchronous,+ so the vendor's response is emphatically not the confirmation — it says a+ machine action was queued. `Succeeded` **and** a retrievable download URI is+ VERIFIED; `Failed` / `TimeOut` / `Cancelled` is FAILED, which is the alarm+ worth having; `Pending` / `InProgress` is UNVERIFIED, because not finished+ is not the same fact as not happening. Reading the status alone would+ certify a collection that finished with nothing to download.++- **A delivered ChatOps prompt nobody had answered would have reported as a+ completed action.** `ChatOpsVerifyExecutor` worked, sat in+ `EXECUTOR_REGISTRY`, and no live-action adapter reached it, so the only+ route to it was the legacy `ActionType` endpoint — which has no capability+ contract, no approval matrix and no autonomy policy in front of it. Leaving+ it unreachable was the right call at the time: it returns+ `ActionStatus.RUNNING` to mean "the prompt went out, nobody has answered",+ and `_to_live_status` folded everything that was not `FAILED` or a+ simulation into `SUCCEEDED`.++ The fix is the missing state rather than the exemption.+ `LiveActionStatus.AWAITING_COMPLETION` means the vendor was touched and the+ outcome is not yet known — the opposite of `PENDING_APPROVAL`, which means+ nothing ran because policy wants a human first. Post-action verification+ does not run against it, since there is no effect to read back yet. The same+ state is what evidence acquisition needed, so one addition covers both+ executors that had no honest result to return.++ Registered against Slack and Teams, LOW impact and analyst-gated. Not+ automatic like `notify` at the same impact, because `notify` addresses a SOC+ channel and this addresses the account under investigation: sent+ automatically on a true positive it tells an attacker they have been+ detected, and the verb cannot know whether the person it is asking is the+ suspect. Its dry run simulates in the adapter rather than stripping+ credentials — the base adapter's strip-and-fall-through would turn a preview+ into a failure for an executor that has no simulation branch by design.++- **Nothing compared what the agent recommends against what the platform can+ execute.** `scripts/check_action_contract.py` compared four registries+ inside the actions service and could not see a fifth: the verbs+ `services/agents` puts in front of an analyst. It now parses every+ `ProposedAction(action_type=...)` call site — including the conditional form+ `attack_path_agent` uses — and fails when a proposed verb has no executor,+ naming the file and line. Run against the tree before this change it reports+ `capture_forensics` at `investigation_agent.py:157`.++ Both exemption lists in that gate are now empty, and+ `test_capability_reachability.py` asserts that emptiness directly, so a verb+ can only be exempted by editing a reviewable assertion rather than appending+ to a list.+- **The MSSP console showed six invented tenants and made no API call at all.**`MSSPDashboardView.tsx` declared `const TENANTS = [...]` — "Acme Financial","GlobalRetail Corp", "MedSecure Health" and three more, with invented alertdiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 402241637..fb653605d 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: 106 rows+The last row is the one worth reading first. It is the honest index: 107 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/concepts/automation-maturity.md b/apps/docs/docs/concepts/automation-maturity.mdindex 844465804..3a84e4e77 100644--- a/apps/docs/docs/concepts/automation-maturity.md+++ b/apps/docs/docs/concepts/automation-maturity.md@@ -96,11 +96,17 @@ Entry criteria:Auto-executed:-- `notify_slack`, `create_ticket`, `chatops_verify`, `search_siem`.+- `notify_slack`, `create_ticket`, `search_siem`.Gated:- Everything `LOW` and above.+- `chatops_verify`, despite its MINIMAL blast radius. Its capability contract+ is analyst-gated, and a contract can raise the requirement a tier would+ allow and never lower it. The verb messages the account under investigation+ rather than a SOC channel: sent automatically on a true positive it tells an+ attacker they have been detected, and it has no way to know whether the+ person it is asking is the suspect.Honest performance:@@ -128,12 +134,20 @@ Entry criteria:Auto-executed:-- Everything at L1 plus: `quarantine_file`, `capture_forensics`,- `add_ioc_to_blocklist`, `run_av_scan`, `create_notable_event`.+- Everything at L1 plus: `quarantine_file`, `run_av_scan`,+ `create_notable_event`.Gated:- Everything `MEDIUM` and above.+- `capture_forensics`, despite its LOW blast radius. The tier ladder is the+ blast-radius axis only, and a capability contract can raise the requirement+ the tier would allow — never lower it. Evidence acquisition is+ analyst-gated because nothing bounds what it collects or from whom: the+ result is a copy of somebody's endpoint in a vendor cloud, and pointed at+ the wrong host that is not undoable. See+ `services/actions/app/live_actions/capability_contracts.py`, which is the+ authority for any verb whose two axes disagree.Honest performance:@@ -155,10 +169,16 @@ counting recommendations as actions.### L3 — Remediate (medium-blast-radius autonomous, audited after-the-fact)The agent is allowed to take medium-blast-radius actions: block an IP at the-firewall, block a domain at DNS, kill a process, reset a password, run a-playbook. These affect a single resource but the affected resource is more-visible — a real human's password gets reset, a service's outbound traffic-is interrupted.+firewall, block a domain at DNS, kill a process, reset a password. These+affect a single resource but the affected resource is more visible — a real+human's password gets reset, a service's outbound traffic is interrupted.++A playbook is not one of them, and there is no `run_playbook` action. A+playbook is a sequence of these verbs, and it runs step by step through the+actions service so each step meets its own contract on the way past. An+action that ran a whole playbook would be approved once and then execute+whatever it contained, which is what the per-capability contract exists to+prevent.Entry criteria:@@ -172,7 +192,7 @@ Entry criteria:Auto-executed:- Everything at L2 plus: `block_ip`, `block_domain`, `kill_process`,- `reset_password`, `force_mfa`, `run_playbook`, `allow_ip`, `block_ioc`,+ `reset_password`, `force_mfa`, `allow_ip`, `block_ioc`,`sync_detection_rule`, `update_watcher`.Gated:diff --git a/apps/docs/docs/concepts/live-actions.md b/apps/docs/docs/concepts/live-actions.mdindex b2de83681..3e3345a4a 100644--- a/apps/docs/docs/concepts/live-actions.md+++ b/apps/docs/docs/concepts/live-actions.md@@ -224,8 +224,8 @@ included in the agent's planning catalogue. No core changes required.## Reachability-Four registries have to agree before a verb can be dispatched under-governance:+Five registries have to agree before a verb can be recommended and then+dispatched under governance:| Registry | What it supplies || --- | --- |@@ -233,6 +233,7 @@ governance:| `_BUILTIN_ADAPTERS` | The `(vendor_id, capability)` pair the dispatcher looks up || `CAPABILITY_CONTRACTS` | Impact, reversibility, verification, approval tier || `KNOWN_CAPABILITIES` | The vocabulary everything validates against |+| `ProposedAction(action_type=...)` | What the agent puts in front of an analyst |A verb can be complete in three of the four and unreachable, and nothing inthe failure message says which one is missing. `ack_alert` and@@ -259,12 +260,55 @@ The gate reports:contract, the approval matrix and the autonomy policy;- an adapter pointing at an `ActionType` with no executor, which would fail atexecution rather than at registration;-- an `ActionType` with no executor at all.--Two exemption lists carry the cases that are known and not yet closed, each-with the reason it is open. They are ratchets: an entry that gains an+- an `ActionType` with no executor at all;+- a verb the agent proposes by name that no executor implements.++That last one is the check that spans two services, and it is the one that+mattered most. `investigation_agent` proposes `capture_forensics` whenever an+investigation reaches the C2 or exfiltration stage, with+`requires_approval=True`. No executor implemented it, so on the most serious+class of incident the product recommended evidence acquisition, raised an+approval for it, and answered `No executor found for action type` when+somebody approved — a control reachable from a recommendation and dead on+approval. The other checks compare the actions service against itself; this+one compares it against the thing that puts a verb in front of a person.++**Both exemption lists are empty.** They are ratchets: an entry that gains animplementation and is not removed fails the build, because a baseline nobody-prunes is a gate that quietly stops checking.+prunes is a gate that quietly stops checking. Emptying them meant making a+decision per verb rather than recording one:++| Verb | Outcome |+| --- | --- |+| `capture_forensics` | Implemented — a Defender investigation-package arm with a probe that reads the package back |+| `chatops_verify` | Implemented — needed `LiveActionStatus.AWAITING_COMPLETION` before it could report honestly |+| `add_ioc_to_blocklist` | Removed — a second name for `block_ioc`, which is fully wired |+| `run_playbook` | Removed — playbook execution belongs to `services/agents`, and "run an arbitrary bundle of verbs" has no verb-level contract |++The rule the last two follow: a verb with no implementation path should leave+the `ActionType` surface rather than sit on it dead. The API accepts any+member of the enum, so a member with nothing behind it is a request that is+accepted and then fails with a message that reads like a broken deployment.++### Actions that are not finished when they return++Most executors are synchronous: the vendor call returns and the action is+over. Two are not, and both report `AWAITING_COMPLETION`:++- `chatops_verify` delivers a prompt and waits for a person to click.+- `capture_forensics` queues an MDE machine action that completes minutes+ later, or fails.++`AWAITING_COMPLETION` means the vendor was touched and the outcome is not yet+known. It is the opposite of `PENDING_APPROVAL`, which means nothing ran+because policy wants a human first. Post-action verification deliberately does+not run against it — there is no effect to read back yet.++Both executors were unreachable through governed dispatch until this state+existed, and leaving them that way was the right call at the time: the status+translation folded everything that was not `FAILED` or a simulation into+`SUCCEEDED`, so registering them would have reported an unanswered question+and an uncollected evidence package as completed actions.---diff --git a/apps/web/content/papers/l0-l4-automation-maturity.md b/apps/web/content/papers/l0-l4-automation-maturity.mdindex 01e75f5b8..b9b1dda04 100644--- a/apps/web/content/papers/l0-l4-automation-maturity.md+++ b/apps/web/content/papers/l0-l4-automation-maturity.md@@ -194,11 +194,17 @@ connector — Slack, Teams, PagerDuty, Opsgenie, or an ITSM connector forticket creation — and has opted into L1 explicitly via the`/api/v1/remediation/config` endpoint.-**What is auto-executed.** `notify_slack`, `create_ticket`,-`chatops_verify`, `search_siem`. These are the `MINIMAL`-blast-radius-actions defined in `ACTION_BLAST_RADIUS`.--**What is gated.** Every `LOW`, `MEDIUM`, and `HIGH` action is queued.+**What is auto-executed.** `notify_slack`, `create_ticket`, `search_siem`.+These are the `MINIMAL`-blast-radius actions defined in+`ACTION_BLAST_RADIUS`.++**What is gated.** Every `LOW`, `MEDIUM`, and `HIGH` action is queued, and so+is `chatops_verify` despite its MINIMAL blast radius. Its capability contract+is analyst-gated, and a contract can raise the requirement a tier would allow+and never lower it. The verb messages the account under investigation rather+than a SOC channel: sent automatically on a true positive it tells an attacker+they have been detected, and it has no way to know whether the person it is+asking is the suspect.**MTTR target.** Time-to-notify drops from minutes to seconds; time-to-contain is still bounded by human review. For the most common case —@@ -231,10 +237,15 @@ false-positive rate. The rollback semantics inaccepted.**What is auto-executed.** Everything at L1 plus: `quarantine_file`,-`capture_forensics`, `add_ioc_to_blocklist`, `run_av_scan`,-`create_notable_event`.+`run_av_scan`, `create_notable_event`.-**What is gated.** Everything `MEDIUM` and above is queued.+**What is gated.** Everything `MEDIUM` and above is queued, and so is+`capture_forensics` despite its LOW blast radius. The tier ladder is the+blast-radius axis; a capability contract can raise the requirement a tier+would allow and never lower it. Evidence acquisition is analyst-gated because+nothing bounds what it collects or from whom — the result is a copy of+somebody's endpoint in a vendor cloud, and pointed at the wrong host that is+not undoable.**MTTR target.** MTTR for the auto-execution path drops to single-digitminutes end-to-end. The bulk of AiSOC's published benchmark numbers come@@ -271,9 +282,10 @@ firewall rule changes are auditable on the firewall, password resets areauditable in the IdP audit log).**What is auto-executed.** Everything at L2 plus: `block_ip`,-`block_domain`, `kill_process`, `reset_password`, `force_mfa`,-`run_playbook`, `allow_ip`, `block_ioc`, `sync_detection_rule`,-`update_watcher`.+`block_domain`, `kill_process`, `reset_password`, `force_mfa`, `allow_ip`,+`block_ioc`, `sync_detection_rule`, `update_watcher`. A playbook is not an+action here: it is a sequence of these verbs, dispatched step by step so each+step meets its own contract rather than being approved wholesale.**What is gated.** Everything `HIGH` is queued.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex a1e4ad1d7..931bf8396 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -107,7 +107,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A tool that cannot answer reports why, rather than returning nothing | architecture (investigation tools) | `ci.yml` api job — the four tools whose data class nothing ingests return `available: false` naming the connector that would populate it, never an empty result set (which reads to a model as 'I checked and found nothing'), and the test asserts the reason is an ingestion gap rather than an argument error, since both set the same flag | GATED | - || Identity, organisational and business context can be imported and is re-runnable | architecture (context graph) | `ci.yml` api job (`test_context_import.py`) — an import never deletes, omitted fields do not blank stored values, `is_active` is derived from `end_date` rather than trusted (an export claiming a departed employee is active would erase the finding this data exists to enable), ids are namespaced per tenant, an unrecognised criticality is rejected rather than coerced because the autonomy policy reads it, and a CMDB host or account the platform has never ingested is reported as a coverage gap rather than created as a node that looks monitored; plus `graph` package tests for CloudAccount derivation from ARNs | GATED | Vulnerability and Secret nodes still need a scanner and CSPM feed; the threat chain needs the threatintel writer || Every response action declares its impact, reversal, permission and verification | README (governed response) | `ci.yml` actions job: `scripts/check_action_contract.py` asserts every registered executor declares a coherent contract. Defaults are unsafe on purpose (irreversible + prohibited), so an undeclared action fails closed and is named rather than quietly becoming dispatchable. A HIGH-impact action with no verification probe fails here rather than in an incident, and a declared reverse capability absent from the vocabulary fails too - the rollback path would otherwise resolve to nothing while believing it has a route back | GATED | - |-| An executor that exists is reachable, and a capability that is declared is implemented | concepts/live-actions.md (reachability) | `ci.yml` actions job: `scripts/check_action_contract.py` compares the four registries a verb needs — the legacy `ActionType` executor, the live-action adapter, the capability contract and the vocabulary — **in both directions**, plus `test_capability_reachability.py`, which injects drift in each direction and asserts the gate names it. `ack_alert` and `suppress_alert` had working Splunk, Elastic and Defender arms and appeared in none of the other three, so governed dispatch answered `executor_not_found` for code that ran; `create_ticket` and `notify` were registered and dispatchable while absent from the vocabulary they validate against. Both exemption lists are ratchets that fail when an entry gains an implementation and is not removed | GATED | three `ActionType` members still have no executor (`capture_forensics`, `add_ioc_to_blocklist`, `run_playbook`) and `chatops_verify` has no adapter — each is recorded in the gate with its reason rather than closed |+| An executor that exists is reachable, and a capability that is declared is implemented | concepts/live-actions.md (reachability) | `ci.yml` actions job: `scripts/check_action_contract.py` compares the five registries a verb needs before it can be recommended and then dispatched — the legacy `ActionType` executor, the live-action adapter, the capability contract, the vocabulary, and what `services/agents` proposes by name — **in both directions**, plus `test_capability_reachability.py`, which injects drift in each direction and asserts the gate names it. `ack_alert` and `suppress_alert` had working Splunk, Elastic and Defender arms and appeared in none of the other three, so governed dispatch answered `executor_not_found` for code that ran; `create_ticket` and `notify` were registered and dispatchable while absent from the vocabulary they validate against. Both exemption lists are ratchets that fail when an entry gains an implementation and is not removed | GATED | both exemption lists are empty: `capture_forensics` gained a Defender investigation-package arm with a probe that reads the package back, `chatops_verify` gained `AWAITING_COMPLETION` so a delivered-but-unanswered prompt stops reporting as a completed action, and `add_ioc_to_blocklist` / `run_playbook` left the `ActionType` surface because neither had an implementation path |+| A verb the agent recommends is one the platform can actually perform | concepts/live-actions.md (reachability) | `ci.yml` actions job: `scripts/check_action_contract.py` parses every `ProposedAction(action_type=...)` call site in `services/agents` (including the conditional form `attack_path_agent` uses) and fails when a proposed verb has no executor, plus `test_capability_reachability.py`, which injects that drift and asserts the gate names the file and line. `investigation_agent` proposed `capture_forensics` on the C2 / exfiltration path with `requires_approval=True` and nothing implemented it, so the product raised an approval for evidence acquisition on its most serious incidents and answered `No executor found for action type` when an analyst approved — the other reachability checks compare the actions service against itself and could not see it | GATED | - || Approval is a function of confidence and impact, and only ever stricter | README (graduated autonomy) | `ci.yml` actions job (`test_approval_matrix.py`, 45 cases) - severe and irreversible impact never auto-execute at any tier or confidence, a contract demanding a human survives L4 at 100%, an unknown tier collapses to the most restrictive, and a missing confidence score is the lowest band rather than a free pass (otherwise a scoring bug becomes an autonomous action) | GATED | - || The actions capability mirror matches the connectors enum | capabilities.py (mirror contract) | `ci.yml` actions job - folded into the contract gate. capabilities.py has documented this check at `tests/test_capability_mirror.py` for months; no such file exists, which is how four reverse verbs the contracts name went missing from both sides | GATED | - || The benchmark is runnable against a third-party agent | README (public benchmark) | `ci.yml` agents job - `packages/aisoc-benchmark` defines a one-method adapter protocol with no import from this repository, plus an HTTP adapter, and the suite includes a live run against an external stub. A benchmark a vendor cannot run against their own product is a self-report | GATED | the published scoreboard still carries only our own runs; third-party submissions need a review process, not more code |@@ -126,7 +127,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 106+- GATED: 107- PARTIAL: 9- 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/scripts/check_action_contract.py b/scripts/check_action_contract.pyindex f5debafb7..92715e30a 100644--- a/scripts/check_action_contract.py+++ b/scripts/check_action_contract.py@@ -1,5 +1,6 @@#!/usr/bin/env python3-"""Gate: every response action must declare what it does to a production estate.+"""Gate: every response action must declare what it does to a production estate,+and every verb the agent recommends must be one this service can perform.Pillar 3. An action registry is only useful if it can answer, before running,what an action does when the finding is wrong. Four things were previously@@ -319,37 +320,31 @@ def check_verification_probes() -> list[str]:#:#: A baseline, not a pass: the gate fails on anything new, and fails again when#: one of these gains an adapter and is not removed.-KNOWN_UNGOVERNED_EXECUTORS: dict[str, str] = {- "chatops_verify": (- "returns ActionStatus.RUNNING — the prompt was delivered and a human "- "has not answered yet. LiveActionStatus has no state for that, and "- "_to_live_status collapses everything that is not FAILED or a "- "simulation into SUCCEEDED, so registering it as-is would report an "- "unanswered question as a completed action. Needs a status for "- "'delivered, awaiting a reply' before it can be dispatched honestly."- ),-}+#:+#: **Empty, and that is the point.** It held one entry, ``chatops_verify``,+#: whose reason was that it returns ``ActionStatus.RUNNING`` — the prompt went+#: out and nobody has answered — while ``LiveActionStatus`` had no state for+#: that and ``_to_live_status`` folded everything not FAILED or simulated into+#: SUCCEEDED. Registering it then would have reported an unanswered question+#: as a completed action. The answer was to build the missing state+#: (``AWAITING_COMPLETION``) rather than to keep the exemption, and the same+#: state turned out to be what evidence acquisition needed too.+KNOWN_UNGOVERNED_EXECUTORS: dict[str, str] = {}#: ``ActionType`` members with no executor behind them at all. The legacy REST#: route answers "No executor found for action type", which reads as a#: misconfiguration rather than a verb nobody built.-KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR: dict[str, str] = {- "capture_forensics": (- "No executor anywhere. Worse than unused: "- "services/agents/app/agents/investigation_agent.py proposes it by name "- "on the C2/exfiltration path, so the product recommends evidence "- "acquisition it cannot perform, at the point where preserving evidence "- "matters most. Needs a real acquisition arm, not a stub."- ),- "add_ioc_to_blocklist": (- "Superseded by block_ioc, which has a Defender arm, a contract and a "- "registered adapter. Nothing dispatches this one."- ),- "run_playbook": (- "Playbook execution lives in services/agents. This member is a leftover "- "from before that split; the actions service has never run one."- ),-}+#:+#: **Also empty.** It held three. ``capture_forensics`` was the urgent one —+#: ``services/agents/app/agents/investigation_agent.py`` proposes it by name on+#: the C2 / exfiltration path, so on the most serious class of incident the+#: product recommended evidence acquisition it could not perform — and it now+#: has a Defender investigation-package arm and a probe that reads the package+#: back. The other two were removed rather than built: ``add_ioc_to_blocklist``+#: was a second name for ``block_ioc``, and ``run_playbook`` belongs to+#: ``services/agents`` and has no verb-level contract to declare. A verb with+#: no implementation path should leave the surface, not sit on it dead.+KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR: dict[str, str] = {}def check_capability_reachability() -> list[str]:@@ -482,6 +477,102 @@ def check_capability_reachability() -> list[str]:return errors+#: Where the agent decides what to recommend. Parsed rather than imported: the+#: gate runs with ``services/actions`` on the path and importing the agents+#: package would pull in its whole dependency tree for three string literals.+AGENTS_APP = REPO_ROOT / "services" / "agents" / "app"+++def _proposed_action_verbs() -> dict[str, list[str]]:+ """Every verb the agent can put in front of an analyst, and where from.++ Returns ``{verb: [source locations]}``. Handles the conditional form+ (``action_type=("isolate_host" if ... else "disable_user")``) because+ ``attack_path_agent`` uses it and a walker that only understood plain+ literals would silently grade half the vocabulary.+ """+ import ast++ found: dict[str, list[str]] = {}+ if not AGENTS_APP.exists():+ return found++ for path in sorted(AGENTS_APP.rglob("*.py")):+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except SyntaxError:+ continue+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ name = node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", "")+ if name != "ProposedAction":+ continue+ for keyword in node.keywords:+ if keyword.arg != "action_type":+ continue+ for value in _string_literals(keyword.value):+ found.setdefault(value, []).append(f"{path.relative_to(REPO_ROOT)}:{keyword.value.lineno}")+ return found+++def _string_literals(node: object) -> list[str]:+ """Constant strings a value expression can evaluate to."""+ import ast++ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return [node.value]+ if isinstance(node, ast.IfExp):+ return _string_literals(node.body) + _string_literals(node.orelse)+ return []+++def check_agent_proposed_actions() -> list[str]:+ """A verb the agent recommends must be one this service can perform.++ The fifth registry, and the one that made ``capture_forensics`` urgent+ rather than merely untidy. The other five directions compare the actions+ service against itself; this compares it against the thing that puts a+ verb in front of a human.++ ``investigation_agent`` proposes ``capture_forensics`` by name whenever an+ investigation reaches the C2 or exfiltration stage, with+ ``requires_approval=True``. So on the most serious class of incident the+ product recommended evidence acquisition, raised an approval for it, and+ answered "No executor found for action type" when somebody approved — a+ dead control on the path where preserving evidence matters most.++ Nothing compared the two, because they live in different services and the+ proposal is a free-text string rather than the enum. That is exactly the+ shape of drift this file exists to catch, so it is checked here rather+ than left to be rediscovered.+ """+ from app.models.action import ActionType+ from app.services.executor_registry import EXECUTOR_REGISTRY++ errors: list[str] = []+ executable = {action.value for action in EXECUTOR_REGISTRY}+ known = {action.value for action in ActionType}++ for verb, locations in sorted(_proposed_action_verbs().items()):+ where = ", ".join(sorted(set(locations)))+ if verb not in known:+ errors.append(+ f"{verb}: the agent proposes this at {where} and it is not an "+ f"ActionType at all, so the action API rejects it outright. "+ f"Implement the verb or stop proposing it."+ )+ elif verb not in executable:+ errors.append(+ f"{verb}: the agent proposes this at {where} and no executor "+ f"implements it. An analyst who approves the recommendation "+ f"gets 'No executor found for action type' — a control that is "+ f"reachable from a recommendation and dead on approval. "+ f"Implement the verb or stop proposing it."+ )+ return errors++def _ratchet(name: str, baseline: dict[str, str], resolved_set: set[str]) -> list[str]:"""A baseline may only ever shrink.@@ -557,6 +648,7 @@ def main(argv: list[str] | None = None) -> int:+ check_verification_probes()+ check_no_orphan_capabilities()+ check_capability_reachability()+ + check_agent_proposed_actions())except ImportError as exc:print(f"action-contract: cannot import the actions package: {exc}", file=sys.stderr)diff --git a/services/actions/app/clients/defender_client.py b/services/actions/app/clients/defender_client.pyindex a6f3cfaea..332904e5e 100644--- a/services/actions/app/clients/defender_client.py+++ b/services/actions/app/clients/defender_client.py@@ -177,6 +177,125 @@ class DefenderClient:"mde_action_id": action.get("id"),}+ async def collect_investigation_package(+ self,+ hostname: str,+ comment: str = "AiSOC forensic acquisition",+ ) -> dict[str, Any]:+ """Start an investigation-package collection on a machine.++ MDE's investigation package is the one broad forensic acquisition in+ this client's vendor set: the agent bundles running processes, network+ connections, registry hives, prefetch, scheduled tasks and event logs+ and uploads them for download.++ Collection is **asynchronous**. This returns as soon as Defender has+ queued the machine action, with ``status`` at ``Pending`` — the package+ does not exist yet. ``get_machine_action`` is how a caller finds out+ whether it ever did.+ """+ async with httpx.AsyncClient(timeout=30.0) as client:+ await self._ensure_token(client)+ machine = await self._resolve_machine(client, hostname)+ machine_id = machine["id"]++ resp = await client.post(+ f"{_MDE_BASE}/machines/{machine_id}/collectInvestigationPackage",+ headers=self._headers(),+ json={"Comment": comment},+ )+ resp.raise_for_status()+ action = resp.json()+ logger.info("mde.collect_investigation_package.queued", machine_id=machine_id, hostname=hostname)+ return {+ "success": True,+ "action": "collect_investigation_package",+ "machine_id": machine_id,+ "hostname": hostname,+ "mde_action_id": action.get("id"),+ "status": action.get("status"),+ }++ async def get_machine_action(self, action_id: str) -> dict[str, Any] | None:+ """Read a machine action's current state.++ The read-back half of every asynchronous MDE action. ``status`` is one+ of ``Pending`` / ``InProgress`` / ``Succeeded`` / ``Failed`` /+ ``TimeOut`` / ``Cancelled``; only the third means the work finished.++ Returns ``None`` when the action cannot be read, so a verifier can tell+ "I could not check" apart from "it failed" — which are different facts+ and are acted on differently.+ """+ async with httpx.AsyncClient(timeout=20.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_MDE_BASE}/machineactions/{action_id}",+ headers=self._headers(),+ )+ if resp.status_code != 200:+ logger.warning("mde.get_machine_action.failed", action_id=action_id, status=resp.status_code)+ return None+ return resp.json()++ async def list_machine_actions(+ self,+ machine_id: str,+ action_type: str,+ *,+ limit: int = 20,+ ) -> list[dict[str, Any]]:+ """Machine actions of one type against one machine, newest first.++ Sorted here rather than with ``$orderby`` because the ordering is the+ part a verifier depends on, and a server-side sort that silently is not+ applied would hand back the oldest action as if it were the newest.++ Returns an empty list both when there are none and when the read+ fails — the caller treats "nothing to read back" as indeterminate+ either way, and the failure is logged so it is not silent.+ """+ async with httpx.AsyncClient(timeout=20.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_MDE_BASE}/machineactions",+ headers=self._headers(),+ params={+ "$filter": f"machineId eq '{machine_id}' and type eq '{action_type}'",+ "$top": max(1, min(limit, 100)),+ },+ )+ if resp.status_code != 200:+ logger.warning(+ "mde.list_machine_actions.failed",+ machine_id=machine_id,+ type=action_type,+ status=resp.status_code,+ )+ return []+ actions = resp.json().get("value", [])+ return sorted(actions, key=lambda a: str(a.get("creationDateTimeUtc") or ""), reverse=True)++ async def get_investigation_package_uri(self, action_id: str) -> str | None:+ """The download URI for a completed investigation package.++ Defender only issues one once the collection succeeded, which is what+ makes it usable as evidence that a package exists rather than that a+ request was accepted. Returns ``None`` while the action is still+ running or if it never produced a package.+ """+ async with httpx.AsyncClient(timeout=20.0) as client:+ await self._ensure_token(client)+ resp = await client.get(+ f"{_MDE_BASE}/machineactions/{action_id}/getPackageUri",+ headers=self._headers(),+ )+ if resp.status_code != 200:+ logger.warning("mde.get_package_uri.unavailable", action_id=action_id, status=resp.status_code)+ return None+ uri = resp.json().get("value")+ return str(uri) if uri else None+async def _resolve_machine(self, client: httpx.AsyncClient, hostname: str) -> dict[str, Any]:"""Resolve hostname to MDE machine object (with auth already ensured)."""resp = await client.get(diff --git a/services/actions/app/executors/endpoint.py b/services/actions/app/executors/endpoint.pyindex dbaadb68a..caac1992b 100644--- a/services/actions/app/executors/endpoint.py+++ b/services/actions/app/executors/endpoint.py@@ -511,6 +511,109 @@ class RunScriptExecutor(BaseExecutor):)+#: The MDE machine-action type a forensic acquisition produces. Named once so+#: the executor and the verification probe cannot look for different things.+INVESTIGATION_PACKAGE_ACTION = "CollectInvestigationPackage"+++class CaptureForensicsExecutor(BaseExecutor):+ """Acquire a forensic evidence package from a host.++ ``capture_forensics`` was an ``ActionType`` with no executor behind it,+ and ``services/agents`` proposes it by name whenever an investigation maps+ to the C2 or exfiltration stage. So on the one class of incident where+ preserving evidence matters most, the product recommended an acquisition+ it could not perform and an analyst who approved it got "No executor found+ for action type" — which reads as a broken deployment rather than a verb+ nobody built.++ Defender only, deliberately+ ---------------------------+ Microsoft Defender's investigation package is the one broad acquisition in+ this service's vendor set: the agent bundles processes, network+ connections, registry, prefetch, scheduled tasks and event logs, and MDE+ exposes both the collection's completion state and a download URI, so the+ claim "evidence exists" is checkable rather than inferred from a 202.++ CrowdStrike RTR's ``get`` retrieves one *named file*, which is a different+ verb with a different blast radius. Wiring it here would make+ ``capture_forensics`` mean "collect the host's forensic package" on one+ vendor and "fetch this path" on another — the per-vendor drift the+ capability contract exists to prevent. A tenant without MDE credentials+ gets an honest simulation naming what to configure, not a fabricated+ acquisition.++ Reports ``RUNNING``, not ``COMPLETED``+ --------------------------------------+ Collection is asynchronous: MDE queues a machine action and the package+ appears minutes later. Reporting the queued request as completed is the+ same gap as reporting an accepted isolate call as a contained host — an+ analyst reads "done" and stops looking for the evidence. ``RUNNING`` says+ what is true: the acquisition started and the package is not there yet.+ """++ async def execute(self, request: ActionRequest) -> ActionResult:+ hostname = request.target+ logger.info("Executing capture_forensics", hostname=hostname)++ mde = _mde_client(request.parameters)+ if mde:+ try:+ result = await mde.collect_investigation_package(+ hostname,+ comment=request.rationale or "AiSOC forensic acquisition",+ )+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.RUNNING,+ blast_radius=BlastRadius.LOW,+ output={+ **result,+ # `executed` is the single field meaning a vendor was+ # actually touched. The acquisition being unfinished is+ # carried by `package_ready`, not by pretending nothing+ # ran.+ "executed": True,+ "package_ready": False,+ "vendor": "defender",+ },+ rollback_data={"hostname": hostname, "vendor": "defender"},+ )+ except Exception as exc:+ logger.error("capture_forensics.defender.failed", hostname=hostname, error=str(exc))+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.FAILED,+ blast_radius=BlastRadius.LOW,+ error=str(exc),+ completed_at=datetime.utcnow(),+ )++ logger.warning(+ "capture_forensics.simulation",+ hostname=hostname,+ reason="no Defender credentials provided",+ funnel="plugin-sdk",+ )+ return ActionResult(+ action_id=request.id,+ status=ActionStatus.COMPLETED,+ blast_radius=BlastRadius.LOW,+ output={+ "action": "capture_forensics",+ "hostname": hostname,+ "executed": False,+ "package_ready": False,+ "note": (+ "Simulation mode — provide mde_tenant_id/mde_client_id/mde_client_secret "+ "to collect a Defender investigation package." + _SIM_FUNNEL_CTA+ ),+ },+ rollback_data={},+ completed_at=datetime.utcnow(),+ )++class RunAVScanExecutor(BaseExecutor):"""Triggers an antivirus scan via Microsoft Defender for Endpoint.diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.pyindex b58d445c3..529b79a7e 100644--- a/services/actions/app/live_actions/builtins.py+++ b/services/actions/app/live_actions/builtins.py@@ -41,7 +41,9 @@ import structlogfrom app.executors import siemfrom app.executors.base import BaseExecutor+from app.executors.chatops import ChatOpsVerifyExecutorfrom app.executors.endpoint import (+ CaptureForensicsExecutor,IsolateHostExecutor,KillProcessExecutor,QuarantineFileExecutor,@@ -109,15 +111,24 @@ def _to_live_status(legacy_status: ActionStatus, output: dict[str, Any]) -> Live"""Translate a legacy ``ActionStatus`` into a :class:`LiveActionStatus`.Legacy status has more states (PENDING, AWAITING_APPROVAL, ...) but- only three are reachable from a synchronous executor call: COMPLETED,- FAILED, and (rarely) ROLLED_BACK. We collapse ROLLED_BACK into+ only four are reachable from an executor call: COMPLETED, FAILED,+ RUNNING, and (rarely) ROLLED_BACK. We collapse ROLLED_BACK intoSUCCEEDED because rollback is out-of-scope for the live-action layer— see :class:`LiveActionExecutor` docstring for the rationale.++ RUNNING is **not** collapsed. Two executors return it to mean "the work+ started and the outcome is not known yet": the ChatOps prompt nobody has+ answered, and the forensic package MDE has not finished collecting. This+ function used to fold both into SUCCEEDED, which is why registering either+ one would have reported an unanswered question and an absent evidence+ package as completed actions — and why they had no adapter at all."""if legacy_status == ActionStatus.FAILED:return LiveActionStatus.FAILEDif _detect_simulation(output):return LiveActionStatus.SIMULATED+ if legacy_status == ActionStatus.RUNNING:+ return LiveActionStatus.AWAITING_COMPLETIONreturn LiveActionStatus.SUCCEEDED@@ -202,6 +213,10 @@ class _LegacyExecutorAdapter(LiveActionExecutor):return f"Simulated {verb} {target}".strip()if status == LiveActionStatus.FAILED:return f"Failed to {verb} {target}".strip()+ if status == LiveActionStatus.AWAITING_COMPLETION:+ # Past tense here would say the work is done. It is not — that is+ # the whole reason this status exists.+ return f"Started {verb} {target}; not finished".strip()return f"{verb.capitalize()} {target}".strip()@@ -214,6 +229,13 @@ class _LegacyExecutorAdapter(LiveActionExecutor):# is present. Each adapter declares the credential keys it cares about so# the discovery API can surface "credentials missing" accurately and so# ``dry_run`` strips the right keys.+#+# The Defender arms borrow the SIEM module's tuple rather than repeating the+# three key names, because ``_mde_client`` and the SIEM module read the same+# set and ``tests/test_dry_run_credential_strip.py`` grades *every* adapter+# whose vendor is ``defender`` against it. A hand-copied list here is the+# shape that let a "dry run" reach production Splunk.+_MDE_KEYS = siem.DEFENDER_CLIENT_PARAM_KEYS@apply_contract@@ -235,7 +257,7 @@ class DefenderIsolateHost(_LegacyExecutorAdapter):requires_credentials = True_legacy_executor = IsolateHostExecutor()_legacy_action_type = ActionType.ISOLATE_HOST- _credential_keys = ("mde_tenant_id", "mde_client_id", "mde_client_secret")+ _credential_keys = _MDE_KEYS@apply_contract@@ -279,7 +301,38 @@ class DefenderRunAVScan(_LegacyExecutorAdapter):requires_credentials = True_legacy_executor = RunAVScanExecutor()_legacy_action_type = ActionType.RUN_AV_SCAN- _credential_keys = ("mde_tenant_id", "mde_client_id", "mde_client_secret")+ _credential_keys = _MDE_KEYS+++@apply_contract+class DefenderCaptureForensics(_LegacyExecutorAdapter):+ """Evidence acquisition, which had no executor at all until now.++ Only Defender: MDE's investigation package is a whole-host artefact+ bundle whose completion and download URI are both readable. CrowdStrike+ RTR's ``get`` fetches one named path, which is a different verb — see+ :class:`app.executors.endpoint.CaptureForensicsExecutor`.+ """++ vendor_id = "defender"+ capability = "capture_forensics"+ description = "Collect a Microsoft Defender investigation package from a host."+ requires_credentials = True+ _legacy_executor = CaptureForensicsExecutor()+ _legacy_action_type = ActionType.CAPTURE_FORENSICS+ _credential_keys = _MDE_KEYS++ def _summarise(self, output: dict[str, Any], status: LiveActionStatus) -> str:+ host = output.get("hostname") or ""+ action_id = output.get("mde_action_id") or ""+ if status == LiveActionStatus.FAILED:+ return f"Failed to start forensic acquisition on {host}".strip()+ if status == LiveActionStatus.SIMULATED:+ return f"Simulated forensic acquisition on {host}".strip()+ # The only other state this executor produces is AWAITING_COMPLETION.+ # Naming the machine action matters: it is what a later verification+ # pass reads, and without it the analyst has nothing to follow up.+ return f"Forensic acquisition queued on {host} (machine action {action_id}); package not yet available".strip()# ---------------------------------------------------------------------------@@ -406,7 +459,7 @@ _SPLUNK_KEYS = siem.SPLUNK_CLIENT_PARAM_KEYS_ELASTIC_KEYS = siem.ELASTIC_CLIENT_PARAM_KEYS_SENTINEL_KEYS = siem.SENTINEL_CLIENT_PARAM_KEYS_QRADAR_KEYS = siem.QRADAR_CLIENT_PARAM_KEYS-_DEFENDER_IOC_KEYS = siem.DEFENDER_CLIENT_PARAM_KEYS+_DEFENDER_IOC_KEYS = _MDE_KEYS@apply_contract@@ -787,6 +840,92 @@ class SlackNotify(_LegacyExecutorAdapter):_credential_keys = ("webhook_url",)+# ---------------------------------------------------------------------------+# Human-in-the-loop — ask the affected user, route the signed answer back+# ---------------------------------------------------------------------------+#+# ``ChatOpsVerifyExecutor`` worked and sat in ``EXECUTOR_REGISTRY`` with no+# adapter, because the only honest thing it can say — "the prompt went out and+# nobody has answered" — had no ``LiveActionStatus`` to land in, and+# ``_to_live_status`` folded it into SUCCEEDED. Registering it before+# AWAITING_COMPLETION existed would have reported an unanswered question as a+# completed action, which is worse than leaving it unreachable.+#+# ``transport`` is pinned per arm for the reason the SIEM arms pin+# ``alert_vendor``: otherwise the channel a prompt goes out on is decided by a+# default buried in the executor rather than by the caller's choice of vendor.+# Unlike those, there is no credential-ordering hazard to guard against — both+# transports authenticate with the same single ``webhook_url``, so the pin+# selects a message format, and a missing webhook still fails rather than+# silently choosing the other transport.+++class _ChatOpsVerify(_LegacyExecutorAdapter):+ """Shared body for the ChatOps transports.++ Declares neither ``capability`` nor ``vendor_id``: an intermediate class+ naming one without the other is graded by the action-contract gate as a+ half-declared executor.+ """++ requires_credentials = True+ _legacy_executor = ChatOpsVerifyExecutor()+ _legacy_action_type = ActionType.CHATOPS_VERIFY+ _credential_keys = ("webhook_url", "bot_token")+ _transport: str = ""++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ # The base class implements dry_run by stripping credentials so the+ # legacy executor falls into its simulation branch. This executor has+ # no such branch on purpose — its module docstring is explicit that an+ # unreachable transport is a hard failure, because an action whose+ # entire point is asking a person a question must not quietly not ask.+ # Stripping the webhook here would therefore report a preview as a+ # failure. Simulate in the adapter instead, before anything mints a+ # callback token or opens a socket.+ if request.dry_run:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SIMULATED,+ capability=self.capability,+ vendor_id=self.vendor_id,+ summary=f"Simulated {self._transport} verification prompt to {request.target or 'the affected user'}",+ details={+ "action": "chatops_verify",+ "transport": self._transport,+ "user_ref": request.params.get("user_ref") or request.target,+ "note": "Simulation mode — dry run, no prompt was delivered and no callback token was minted.",+ },+ )+ pinned = {**request.params, "transport": self._transport}+ return await super().execute(request.model_copy(update={"params": pinned}))++ def _summarise(self, output: dict[str, Any], status: LiveActionStatus) -> str:+ user = output.get("user_ref") or ""+ if status == LiveActionStatus.FAILED:+ return f"Failed to send a {self._transport} verification prompt to {user}".strip()+ if status == LiveActionStatus.SIMULATED:+ return f"Simulated {self._transport} verification prompt to {user}".strip()+ ttl = output.get("expires_in_seconds")+ return f"Asked {user} to confirm on {self._transport}; awaiting their reply (expires in {ttl}s)".strip()+++@apply_contract+class SlackChatOpsVerify(_ChatOpsVerify):+ capability = "chatops_verify"+ vendor_id = "slack"+ description = "Ask the affected user to confirm or deny activity via an interactive Slack prompt."+ _transport = "slack"+++@apply_contract+class TeamsChatOpsVerify(_ChatOpsVerify):+ capability = "chatops_verify"+ vendor_id = "teams"+ description = "Ask the affected user to confirm or deny activity via a Microsoft Teams card."+ _transport = "teams"++# ---------------------------------------------------------------------------# Registration entry point# ---------------------------------------------------------------------------@@ -813,6 +952,9 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (CrowdStrikeKillProcess,CrowdStrikeRunScript,DefenderRunAVScan,+ # Evidence acquisition: an ActionType the agent proposes on the C2 /+ # exfiltration path, which had no executor anywhere.+ DefenderCaptureForensics,# Identity (Okta)OktaDisableUser,OktaResetPassword,@@ -854,6 +996,10 @@ _BUILTIN_ADAPTERS: tuple[type[LiveActionExecutor], ...] = (ServiceNowCreateTicket,PagerDutyCreateTicket,SlackNotify,+ # Human-in-the-loop: a working executor whose honest "not answered yet"+ # had no status to land in until AWAITING_COMPLETION existed.+ SlackChatOpsVerify,+ TeamsChatOpsVerify,)diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.pyindex 0a62a7211..a354a531e 100644--- a/services/actions/app/live_actions/capabilities.py+++ b/services/actions/app/live_actions/capabilities.py@@ -96,6 +96,14 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset(# executor_not_found for code that worked."ack_alert","suppress_alert",+ # EVIDENCE. An ActionType with no executor anywhere, proposed by name+ # on the C2 / exfiltration path — so the most serious incidents got a+ # recommendation that answered "No executor found for action type".+ "capture_forensics",+ # HUMAN-IN-THE-LOOP. A working executor no adapter reached, because+ # its honest result ("prompt delivered, nobody has answered") had no+ # LiveActionStatus to land in.+ "chatops_verify",# TICKET"push_case","push_status",diff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.pyindex 18c53ad79..843bbda06 100644--- a/services/actions/app/live_actions/capability_contracts.py+++ b/services/actions/app/live_actions/capability_contracts.py@@ -177,6 +177,64 @@ CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {"precisely because its blast radius is not knowable in advance."),),+ "capture_forensics": CapabilityContract(+ impact=ActionImpact.LOW,+ approval=ApprovalRequirement.ANALYST,+ reversal=Reversal.MANUAL_ONLY,+ required_permission=_CONTAIN,+ has_verification_probe=True,+ note=(+ "Collects an evidence package from one host. The estate is "+ "unchanged, which is why the impact matches run_av_scan: some "+ "endpoint CPU and IO, and it finishes on its own. "+ "Analyst-gated rather than automatic on the same reasoning that "+ "separated suppress_alert from update_alert_disposition — the "+ "question is what bounds the verb, not how loud it is. The "+ "writeback is bounded by a disposition mapping that refuses to "+ "close a true positive; this one has no bound at all. It collects "+ "whatever the vendor package contains, from whichever host it is "+ "pointed at, and the result is a copy of somebody's endpoint — "+ "processes, registry, event logs, temp files — in a vendor cloud "+ "behind a download URI. Pointed at the wrong host that is a "+ "data-handling event nobody can take back, which is also why the "+ "reversal is manual: an operator deletes the package from the "+ "console, the copy having already been made. "+ "The probe is the reason this verb needed one at all: acquisition "+ "is asynchronous, so the API response is emphatically not the "+ "confirmation — it says a machine action was queued, and the "+ "package appears minutes later or never. The probe reads that "+ "machine action's terminal state and then asks for the download "+ "URI, so VERIFIED means a package exists and can be fetched. "+ "Still running answers indeterminate rather than either guess."+ ),+ ),+ # ── Human-in-the-loop ──────────────────────────────────────────────────+ "chatops_verify": CapabilityContract(+ impact=ActionImpact.LOW,+ approval=ApprovalRequirement.ANALYST,+ reversal=Reversal.MANUAL_ONLY,+ required_permission=_TICKET,+ has_verification_probe=False,+ verification_gap=(+ "There is no vendor state to read back. What this action produces "+ "is a delivered prompt, and the transport's own response is the "+ "confirmation of delivery — the case the probe rule waives below "+ "MODERATE. The thing a probe might want to check, whether the "+ "person answered, is not a state to poll: the answer arrives as a "+ "signed callback, and until it does the action reports "+ "awaiting_completion rather than success."+ ),+ note=(+ "Asks the affected user 'was this you?' and routes the signed "+ "answer onto the case. Shares notify's impact — a message cannot "+ "be unsent — but not its approval tier, because notify addresses "+ "a SOC channel and this addresses the account under "+ "investigation. Sent automatically on a true positive it tells an "+ "attacker they have been detected, and the verb has no way to "+ "know whether the person it is asking is the suspect. That "+ "missing bound is what makes it analyst-gated."+ ),+ ),# ── Identity ───────────────────────────────────────────────────────────"disable_user": CapabilityContract(impact=ActionImpact.HIGH,diff --git a/services/actions/app/live_actions/models.py b/services/actions/app/live_actions/models.pyindex f6e4bdc2e..018043ae0 100644--- a/services/actions/app/live_actions/models.py+++ b/services/actions/app/live_actions/models.py@@ -69,6 +69,22 @@ class LiveActionStatus(str, Enum):# invoked: the tier/blast policy blocked it outright, or it needs a human.BLOCKED = "blocked"PENDING_APPROVAL = "pending_approval"+ #: The vendor accepted the request, the work started, and the outcome is+ #: not known yet. Nothing failed and nothing is finished.+ #:+ #: Added because two executors had no honest state to land in and so were+ #: unreachable through governed dispatch. ``chatops_verify`` delivers a+ #: prompt and waits for a person to click; ``capture_forensics`` queues an+ #: acquisition that MDE completes minutes later. Both returned the legacy+ #: ``ActionStatus.RUNNING``, which ``_to_live_status`` collapsed into+ #: SUCCEEDED along with everything else that was not FAILED — reporting an+ #: unanswered question and an uncollected package as completed actions.+ #:+ #: Distinct from PENDING_APPROVAL, which means the opposite: nothing ran,+ #: because policy wants a human first. Here the vendor was touched and the+ #: caller has to come back — post-action verification deliberately does not+ #: run against this state, since there is not yet an effect to read back.+ AWAITING_COMPLETION = "awaiting_completion"class LiveActionRequest(BaseModel):diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.pyindex 1db065213..0fbf48b3c 100644--- a/services/actions/app/models/action.py+++ b/services/actions/app/models/action.py@@ -21,10 +21,28 @@ class ActionType(str, Enum):KILL_PROCESS = "kill_process"QUARANTINE_FILE = "quarantine_file"CAPTURE_FORENSICS = "capture_forensics"- ADD_IOC_TO_BLOCKLIST = "add_ioc_to_blocklist"NOTIFY_SLACK = "notify_slack"CREATE_TICKET = "create_ticket"- RUN_PLAYBOOK = "run_playbook"+ # `add_ioc_to_blocklist` and `run_playbook` were here and had no executor+ # behind either of them, so the API accepted both and answered "No+ # executor found for action type" — which reads as a broken deployment+ # rather than a verb nobody built. Neither was a missing implementation:+ #+ # add_ioc_to_blocklist a second name for `block_ioc`, which has a+ # Defender arm, a contract, an adapter and a place+ # in the vocabulary. Two names for one verb means+ # half the callers reach the dead one.+ # run_playbook playbook execution lives in services/agents and+ # always has. It is also the wrong shape for this+ # registry: the contract belongs to the verb, and+ # "run an arbitrary bundle of verbs" has no+ # verb-level impact, reversal or probe. Approving+ # it once would execute whatever steps it contains+ # without each one meeting its own contract, which+ # is precisely what the per-capability contract+ # exists to prevent. Playbooks dispatch step by+ # step through this service instead, so every step+ # is graded on the way past.# ChatOps user verification: outbound interactive Slack/Teams prompt# asking the affected user to confirm or deny an event ("Was this you?").# The response is HMAC-validated and routed back into the case timeline.@@ -85,10 +103,8 @@ ACTION_BLAST_RADIUS: dict[ActionType, BlastRadius] = {ActionType.KILL_PROCESS: BlastRadius.MEDIUM,ActionType.QUARANTINE_FILE: BlastRadius.LOW,ActionType.CAPTURE_FORENSICS: BlastRadius.LOW,- ActionType.ADD_IOC_TO_BLOCKLIST: BlastRadius.LOW,ActionType.NOTIFY_SLACK: BlastRadius.MINIMAL,ActionType.CREATE_TICKET: BlastRadius.MINIMAL,- ActionType.RUN_PLAYBOOK: BlastRadius.MEDIUM,ActionType.CHATOPS_VERIFY: BlastRadius.MINIMAL,# WS-E live vendor action blast radiiActionType.RUN_SCRIPT: BlastRadius.HIGH,diff --git a/services/actions/app/services/approval_gate.py b/services/actions/app/services/approval_gate.pyindex f079f3a7d..2277093d5 100644--- a/services/actions/app/services/approval_gate.py+++ b/services/actions/app/services/approval_gate.py@@ -18,12 +18,16 @@ auto-execute that did not before.Two honest limits, both logged rather than papered over:-Seven of the 25 ``ActionType`` members have no capability contract-(``ack_alert``, ``notify_slack``, ``run_playbook`` and four others). For-those the matrix has no impact to reason about and blast radius decides-alone. That is recorded at debug rather than guessed at, because inventing an-impact for an unmapped verb is how a gate starts certifying things it never-examined.+One of the 24 ``ActionType`` members has no capability contract, down from+five: ``capture_forensics`` and ``chatops_verify`` gained one, and+``add_ioc_to_blocklist`` and ``run_playbook`` left the enum because neither+had an implementation path. The one left is ``notify_slack``, and it is a+naming gap rather than an undeclared verb — the lookup below is by+``ActionType`` value and the matching capability is called ``notify``, which+does have a contract. For an unmapped verb the matrix has no impact to reason+about and blast radius decides alone. That is recorded at debug rather than+guessed at, because inventing an impact for an unmapped verb is how a gate+starts certifying things it never examined.A request with no ``confidence`` is treated as the lowest band. For anythingabove READ_ONLY impact that means analyst approval, which is a real tighteningdiff --git a/services/actions/app/services/executor_registry.py b/services/actions/app/services/executor_registry.pyindex 375858810..6d3fe4e74 100644--- a/services/actions/app/services/executor_registry.py+++ b/services/actions/app/services/executor_registry.py@@ -8,6 +8,7 @@ ActionRequest.parameters — no credentials = safe, observable simulation.from app.executors.chatops import ChatOpsVerifyExecutorfrom app.executors.endpoint import (+ CaptureForensicsExecutor,IsolateHostExecutor,KillProcessExecutor,QuarantineFileExecutor,@@ -45,6 +46,9 @@ EXECUTOR_REGISTRY = {ActionType.KILL_PROCESS: KillProcessExecutor(),ActionType.RUN_SCRIPT: RunScriptExecutor(),ActionType.RUN_AV_SCAN: RunAVScanExecutor(),+ # Evidence acquisition. The agent proposes this on the C2 / exfiltration+ # path, where it previously resolved to nothing.+ ActionType.CAPTURE_FORENSICS: CaptureForensicsExecutor(),# Identity (Okta)ActionType.DISABLE_USER: DisableUserExecutor(),ActionType.RESET_PASSWORD: ResetPasswordExecutor(),diff --git a/services/actions/app/services/verification.py b/services/actions/app/services/verification.pyindex e32871bf7..48194ce34 100644--- a/services/actions/app/services/verification.py+++ b/services/actions/app/services/verification.py@@ -30,8 +30,8 @@ from typing import Anyimport structlog-from app.clients.factories import _entra_client, _okta_client-from app.executors.endpoint import _cs_client+from app.clients.factories import _entra_client, _mde_client, _okta_client+from app.executors.endpoint import INVESTIGATION_PACKAGE_ACTION, _cs_clientfrom app.executors.siem import _ack_vendor, _qradar_client, _splunk_clientfrom app.models.action import ActionTypefrom app.services.disposition_writeback import WritebackAction, plan_writeback@@ -148,6 +148,80 @@ async def _probe_enable_user(target: str, params: dict[str, Any]) -> bool | Nonereturn None if blocked is None else not blocked+#: MDE machine-action states. Only one means the work finished; three mean it+#: definitively did not; the rest mean it is still going.+_MDE_ACTION_SUCCEEDED = "succeeded"+_MDE_ACTION_TERMINAL_FAILURES = {"failed", "timeout", "cancelled"}+++async def _probe_capture_forensics(target: str, params: dict[str, Any]) -> bool | None:+ """Confirm a forensic package actually exists and can be fetched.++ This is the verb where "the API returned 200" is furthest from the truth.+ Collection is asynchronous: MDE queues a machine action, replies+ immediately with ``Pending``, and the package appears minutes later or+ never. An executor reporting that as success tells an analyst the evidence+ is preserved at exactly the moment they stop looking for it.++ So VERIFIED requires two things, not one: the machine action reached+ ``Succeeded`` *and* Defender will hand over a download URI for it. A+ collection that claims to have finished and has nothing to download is a+ failure, not a success — reading only the status would certify it.++ Three outcomes, all of them real:++ * ``Succeeded`` with a package URI → True.+ * ``Failed`` / ``TimeOut`` / ``Cancelled`` → False. A genuine alarm: the+ responder believes they hold evidence and they do not.+ * ``Pending`` / ``InProgress`` → None. Not finished is not the same fact+ as not happening, and the immediate post-dispatch probe will almost+ always land here.++ Which action it reads+ ---------------------+ ``mde_action_id`` in params is used when present and is exact — the+ executor returns it, so a later re-verification can name the acquisition+ it means. Without one the probe falls back to the newest+ ``CollectInvestigationPackage`` action against that machine, which is this+ one unless a second collection was started on the same host in the same+ window. That ambiguity is narrow but real, so the action id is not+ swallowed: it is logged, and a caller who needs certainty passes it in.+ """+ mde = _mde_client(params)+ if mde is None:+ return None++ action_id = params.get("mde_action_id")+ if not action_id:+ machine = await mde.find_machine(target)+ if not machine or not machine.get("id"):+ # The host cannot be resolved, so nothing can be read back. Not a+ # failed acquisition — a host we cannot look at.+ return None+ actions = await mde.list_machine_actions(str(machine["id"]), INVESTIGATION_PACKAGE_ACTION, limit=5)+ if not actions:+ return None+ action_id = actions[0].get("id")+ if not action_id:+ return None++ action = await mde.get_machine_action(str(action_id))+ if not action:+ return None++ status = str(action.get("status") or "").lower()+ logger.info("verification.capture_forensics.read", target=target, mde_action_id=str(action_id), mde_status=status)++ if status in _MDE_ACTION_TERMINAL_FAILURES:+ return False+ if status != _MDE_ACTION_SUCCEEDED:+ return None++ # Succeeded. Now the part that makes this a check rather than a restatement+ # of the vendor's own optimism: ask for the artefact.+ return bool(await mde.get_investigation_package_uri(str(action_id)))++async def _probe_allow_ip(target: str, params: dict[str, Any]) -> bool | None:"""Confirm an IP block was actually removed.@@ -265,6 +339,7 @@ _DEFAULT_PROBES: dict[ActionType, Probe] = {ActionType.BLOCK_IP: _probe_block_ip,ActionType.DISABLE_USER: _probe_disable_user,ActionType.ALLOW_IP: _probe_allow_ip,+ ActionType.CAPTURE_FORENSICS: _probe_capture_forensics,ActionType.UPDATE_ALERT_DISPOSITION: _probe_alert_disposition,ActionType.ACK_ALERT: _probe_ack_alert,ActionType.SUPPRESS_ALERT: _probe_suppress_alert,diff --git a/services/actions/tests/test_capability_reachability.py b/services/actions/tests/test_capability_reachability.pyindex 4800a2cf6..58c293e99 100644--- a/services/actions/tests/test_capability_reachability.py+++ b/services/actions/tests/test_capability_reachability.py@@ -122,11 +122,64 @@ def test_exemption_lists_only_ever_shrink() -> None:assert len(reason.strip()) > 40-def test_every_action_type_has_an_executor_or_a_recorded_reason() -> None:- from check_action_contract import KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR+def test_both_exemption_baselines_are_empty() -> None:+ """The ratchet's floor, asserted rather than assumed.++ Both lists held entries and both are now empty: ``capture_forensics``+ gained a Defender arm, ``chatops_verify`` gained the status its honest+ result needed, and ``add_ioc_to_blocklist`` / ``run_playbook`` left the+ ``ActionType`` surface because neither had an implementation path. The+ previous form of this test compared the lists against reality and passed+ vacuously once they were empty, so it could not notice a new entry being+ added. This can: a verb may only be exempted by editing this assertion,+ which is a reviewable act rather than a quiet append.+ """+ from check_action_contract import (+ KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR,+ KNOWN_UNGOVERNED_EXECUTORS,+ )++ assert KNOWN_UNGOVERNED_EXECUTORS == {}+ assert KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR == {}+++def test_every_action_type_has_an_executor() -> None:+ """No exemptions left, so this is the whole claim.++ The API accepts any ``ActionType`` and then answers "No executor found for+ action type" for one with nothing behind it, which reads as a broken+ deployment rather than a verb nobody built.+ """+ missing = sorted(at.value for at in ActionType if at not in EXECUTOR_REGISTRY)+ assert missing == [], f"{missing} are accepted by the action API and dispatch to nothing"- missing = {at.value for at in ActionType if at not in EXECUTOR_REGISTRY}- assert missing <= set(KNOWN_ACTION_TYPES_WITHOUT_EXECUTOR)++def test_every_legacy_executor_is_reachable_through_governed_dispatch() -> None:+ """Likewise: nothing is reachable only through the ungoverned route."""+ reachable = {cls._legacy_action_type for cls in BRIDGING_ADAPTERS}+ unreachable = sorted(at.value for at in EXECUTOR_REGISTRY if at not in reachable)+ assert unreachable == [], f"{unreachable} work and governed dispatch answers executor_not_found for them"+++def test_the_agent_proposes_only_verbs_this_service_can_execute() -> None:+ """The fifth registry: what the agent recommends to a human.++ ``investigation_agent`` proposes ``capture_forensics`` on the C2 /+ exfiltration path with ``requires_approval=True``, and no executor+ implemented it — so the product raised an approval for evidence+ acquisition on its most serious incidents and failed on approval. The+ other five directions compare the actions service against itself; this is+ the one that compares it against the thing that puts a verb in front of a+ person.+ """+ from check_action_contract import _proposed_action_verbs++ proposed = _proposed_action_verbs()+ assert proposed, "found no ProposedAction call sites; the parser has drifted from the agents package"++ executable = {action.value for action in EXECUTOR_REGISTRY}+ dead = {verb: locations for verb, locations in proposed.items() if verb not in executable}+ assert dead == {}, f"the agent recommends verbs that dispatch to nothing: {dead}"def _run_gate() -> subprocess.CompletedProcess:@@ -154,6 +207,10 @@ def test_the_gate_passes_on_the_tree_as_committed() -> None:("adapter", "no live-action adapter reaches it"),# Remove the contract while the adapter stays.("contract", "no capability contract declares"),+ # Remove the executor for a verb the agent proposes by name: the+ # direction that spans two services, and the one capture_forensics+ # drifted in for as long as it existed.+ ("agent_proposal", "Implement the verb or stop proposing it"),],)def test_the_gate_fails_when_drift_is_introduced_in_each_direction(tmp_path: Path, drift: str, expected: str) -> None:@@ -173,6 +230,15 @@ def test_the_gate_fails_when_drift_is_introduced_in_each_direction(tmp_path: Pat"b._BUILTIN_ADAPTERS = tuple(c for c in b._BUILTIN_ADAPTERS if c.capability != 'ack_alert')\n"),"contract": "import app.live_actions.capability_contracts as cc\ncc.CAPABILITY_CONTRACTS.pop('ack_alert', None)\n",+ # The adapter goes too, otherwise direction 5 fires first and the+ # assertion would pass on the wrong message.+ "agent_proposal": (+ "import app.services.executor_registry as er\n"+ "import app.models.action as ma\n"+ "import app.live_actions.builtins as b\n"+ "er.EXECUTOR_REGISTRY.pop(ma.ActionType.CAPTURE_FORENSICS, None)\n"+ "b._BUILTIN_ADAPTERS = tuple(c for c in b._BUILTIN_ADAPTERS if c.capability != 'capture_forensics')\n"+ ),}[drift]driver = tmp_path / "drive.py"diff --git a/services/actions/tests/test_capture_forensics.py b/services/actions/tests/test_capture_forensics.pynew file mode 100644index 000000000..1b2b1d323--- /dev/null+++ b/services/actions/tests/test_capture_forensics.py@@ -0,0 +1,363 @@+"""Evidence acquisition: the verb the agent recommended and nothing could run.++``capture_forensics`` was an ``ActionType`` with no executor anywhere, and+``services/agents/app/agents/investigation_agent.py`` proposes it by name+whenever an investigation reaches the C2 or exfiltration stage, with+``requires_approval=True``. So the product raised an approval for evidence+acquisition on the most serious class of incident and answered "No executor+found for action type" when somebody approved it — a control that is reachable+from a recommendation and dead on approval.++Three claims are tested here, in the order they matter:++1. the verb resolves — through the legacy route *and* through governed+ dispatch, which are different failures with different error messages;+2. it does not lie about being finished. MDE queues a machine action and+ replies immediately; the package appears minutes later or never. The+ executor reports ``RUNNING`` / ``AWAITING_COMPLETION`` rather than success,+ because an analyst who reads "done" stops looking for the evidence;+3. the probe reads the package back rather than the vendor's own optimism —+ ``Succeeded`` with nothing to download is a failure, not a success.+"""++from __future__ import annotations++from unittest.mock import create_autospec+from uuid import uuid4++import httpx+import pytest+import respx+from app.clients.defender_client import DefenderClient+from app.executors import endpoint+from app.executors.endpoint import INVESTIGATION_PACKAGE_ACTION, CaptureForensicsExecutor+from app.live_actions import builtins, registry+from app.live_actions.capabilities import KNOWN_CAPABILITIES+from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS+from app.live_actions.contract import ActionImpact, ApprovalRequirement+from app.live_actions.models import LiveActionRequest, LiveActionStatus+from app.models.action import ActionRequest, ActionStatus, ActionType+from app.services import verification+from app.services.executor_registry import EXECUTOR_REGISTRY+from app.services.verification import PostActionVerifier, VerificationOutcome++MDE_CREDENTIALS = {+ "mde_tenant_id": "00000000-0000-0000-0000-000000000001",+ "mde_client_id": "00000000-0000-0000-0000-000000000002",+ "mde_client_secret": "unit-test-placeholder",+}++[email protected](autouse=True)+def _registered() -> None:+ registry.reset_for_tests()+ builtins.register_builtin_executors(overwrite=True)+++def _request(**parameters) -> ActionRequest:+ return ActionRequest(+ incident_id=uuid4(),+ tenant_id=uuid4(),+ action_type=ActionType.CAPTURE_FORENSICS,+ target=parameters.pop("target", "WS-4471"),+ parameters=parameters,+ rationale="Exfiltration/C2 stage detected — preserve evidence",+ )+++# ── 1. The verb resolves ───────────────────────────────────────────────────+++def test_capture_forensics_has_an_executor() -> None:+ """The legacy route. Without this it answers 'No executor found'."""+ assert ActionType.CAPTURE_FORENSICS in EXECUTOR_REGISTRY+++def test_capture_forensics_resolves_through_governed_dispatch() -> None:+ """The governed route, which has the contract and approval matrix on it.++ A legacy executor with no adapter is reachable only through the ActionType+ REST endpoint, which has none of those in front of it.+ """+ assert registry.get_executor("defender", "capture_forensics") is not None+++def test_capture_forensics_is_in_the_vocabulary_and_has_a_contract() -> None:+ assert "capture_forensics" in KNOWN_CAPABILITIES+ contract = CAPABILITY_CONTRACTS["capture_forensics"]+ # Analyst-gated, not automatic: the verb has no bound on what it collects+ # or from whom, which is the same reasoning that separated suppress_alert+ # from update_alert_disposition at an identical impact tier.+ assert contract.impact is ActionImpact.LOW+ assert contract.approval is ApprovalRequirement.ANALYST+ assert contract.has_verification_probe is True+ assert ActionType.CAPTURE_FORENSICS in verification._DEFAULT_PROBES+++# ── 2. It does not claim to have finished ──────────────────────────────────+++async def test_defender_arm_reports_running_not_completed(monkeypatch) -> None:+ """Collection is asynchronous, so 'completed' would be the 200-is-proof lie.++ Autospec'd, per the rule that simulation mode never constructs the client:+ a wrong keyword here is invisible until a live call raises ``TypeError``+ in a customer's tenant.+ """+ client = create_autospec(DefenderClient, spec_set=True, instance=True)+ client.collect_investigation_package.return_value = {+ "success": True,+ "action": "collect_investigation_package",+ "machine_id": "mde-1",+ "hostname": "WS-4471",+ "mde_action_id": "act-9",+ "status": "Pending",+ }+ monkeypatch.setattr(endpoint, "_mde_client", lambda params: client)++ result = await CaptureForensicsExecutor().execute(_request(**MDE_CREDENTIALS))++ assert result.status is ActionStatus.RUNNING, "a queued acquisition is not a completed one"+ assert result.output["executed"] is True+ assert result.output["package_ready"] is False+ assert result.output["mde_action_id"] == "act-9"+ client.collect_investigation_package.assert_called_once()+ assert client.collect_investigation_package.call_args.args[0] == "WS-4471"+++async def test_governed_dispatch_surfaces_awaiting_completion(monkeypatch) -> None:+ """The adapter-level claim, and the reason a new status had to exist.++ ``_to_live_status`` used to fold everything that was not FAILED or a+ simulation into SUCCEEDED, so an acquisition that had not happened yet+ would have been reported as a completed action.+ """+ client = create_autospec(DefenderClient, spec_set=True, instance=True)+ client.collect_investigation_package.return_value = {+ "hostname": "WS-4471",+ "mde_action_id": "act-9",+ "status": "Pending",+ }+ monkeypatch.setattr(endpoint, "_mde_client", lambda params: client)++ executor = registry.get_executor("defender", "capture_forensics")+ assert executor is not None+ result = await executor.execute(+ LiveActionRequest(+ capability="capture_forensics",+ vendor_id="defender",+ target="WS-4471",+ params=dict(MDE_CREDENTIALS),+ tenant_id=uuid4(),+ )+ )++ assert result.status is LiveActionStatus.AWAITING_COMPLETION+ assert "not yet available" in result.summary+ assert "act-9" in result.summary, "the machine action id is what a later verification pass reads"+++async def test_no_credentials_simulates_rather_than_claiming_an_acquisition() -> None:+ result = await CaptureForensicsExecutor().execute(_request())++ assert result.output["executed"] is False+ assert result.output["package_ready"] is False+ assert str(result.output["note"]).startswith("Simulation mode")+++async def test_dry_run_never_builds_a_defender_client(monkeypatch) -> None:+ """A preview must not reach the vendor, whatever credentials are supplied."""++ real = endpoint._mde_client++ def _tripwire(params):+ if real(params) is not None:+ raise AssertionError("a dry run built a live Defender client")+ return None++ monkeypatch.setattr(endpoint, "_mde_client", _tripwire)++ executor = registry.get_executor("defender", "capture_forensics")+ assert executor is not None+ result = await executor.execute(+ LiveActionRequest(+ capability="capture_forensics",+ vendor_id="defender",+ target="WS-4471",+ params=dict(MDE_CREDENTIALS),+ dry_run=True,+ tenant_id=uuid4(),+ )+ )++ assert result.status is LiveActionStatus.SIMULATED+++async def test_a_defender_failure_is_reported_as_failed(monkeypatch) -> None:+ client = create_autospec(DefenderClient, spec_set=True, instance=True)+ client.collect_investigation_package.side_effect = httpx.HTTPError("403 Forbidden")+ monkeypatch.setattr(endpoint, "_mde_client", lambda params: client)++ result = await CaptureForensicsExecutor().execute(_request(**MDE_CREDENTIALS))++ assert result.status is ActionStatus.FAILED+ assert "403" in (result.error or "")+++# ── 3. The probe reads the package back ────────────────────────────────────+++def _probe_client(status: str, *, package_uri: str | None) -> DefenderClient:+ client = create_autospec(DefenderClient, spec_set=True, instance=True)+ client.find_machine.return_value = {"id": "mde-1"}+ client.list_machine_actions.return_value = [{"id": "act-9", "creationDateTimeUtc": "2026-09-23T10:00:00Z"}]+ client.get_machine_action.return_value = {"id": "act-9", "status": status}+ client.get_investigation_package_uri.return_value = package_uri+ return client+++ ("status", "package_uri", "expected"),+ [+ # The only combination that means evidence exists and can be fetched.+ ("Succeeded", "https://mde.example.invalid/pkg.zip", VerificationOutcome.VERIFIED),+ # Claims to have finished with nothing to download. Reading the status+ # alone would certify this, which is why the probe asks for the artefact.+ ("Succeeded", None, VerificationOutcome.FAILED),+ # Genuine alarms: the responder believes they hold evidence and do not.+ ("Failed", None, VerificationOutcome.FAILED),+ ("TimeOut", None, VerificationOutcome.FAILED),+ ("Cancelled", None, VerificationOutcome.FAILED),+ # Not finished is not the same fact as not happening.+ ("Pending", None, VerificationOutcome.UNVERIFIED),+ ("InProgress", None, VerificationOutcome.UNVERIFIED),+ ],+)+async def test_the_probe_distinguishes_collected_from_failed_from_still_running(+ monkeypatch,+ status: str,+ package_uri: str | None,+ expected: VerificationOutcome,+) -> None:+ monkeypatch.setattr(verification, "_mde_client", lambda params: _probe_client(status, package_uri=package_uri))++ result = await PostActionVerifier().verify(ActionType.CAPTURE_FORENSICS, "WS-4471", dict(MDE_CREDENTIALS))++ assert result.outcome is expected+++async def test_the_probe_prefers_an_explicit_action_id(monkeypatch) -> None:+ """Given the id the executor returned, the probe reads exactly that action.++ Without one it falls back to the newest collection against the machine,+ which is this one unless somebody started a second on the same host in the+ same window. A caller who needs certainty passes the id.+ """+ client = _probe_client("Succeeded", package_uri="https://mde.example.invalid/pkg.zip")+ monkeypatch.setattr(verification, "_mde_client", lambda params: client)++ result = await PostActionVerifier().verify(+ ActionType.CAPTURE_FORENSICS,+ "WS-4471",+ {**MDE_CREDENTIALS, "mde_action_id": "act-explicit"},+ )++ assert result.outcome is VerificationOutcome.VERIFIED+ client.find_machine.assert_not_called()+ client.list_machine_actions.assert_not_called()+ client.get_machine_action.assert_called_once_with("act-explicit")+++async def test_the_probe_reports_unverified_without_credentials() -> None:+ """Honest over confident: "we cannot check" is not "it failed"."""+ result = await PostActionVerifier().verify(ActionType.CAPTURE_FORENSICS, "WS-4471", {})++ assert result.outcome is VerificationOutcome.UNVERIFIED+++# ── Wire shape ─────────────────────────────────────────────────────────────+++async def test_collect_investigation_package_hits_the_mde_endpoint() -> None:+ captured: dict[str, object] = {}++ respx.post("https://login.microsoftonline.com/tid/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))+ respx.get("https://api.securitycenter.microsoft.com/api/machines").mock(+ return_value=httpx.Response(200, json={"value": [{"id": "mde-1", "computerDnsName": "WS-4471"}]})+ )++ def respond(request: httpx.Request) -> httpx.Response:+ captured["body"] = request.read().decode()+ return httpx.Response(201, json={"id": "act-9", "type": INVESTIGATION_PACKAGE_ACTION, "status": "Pending"})++ respx.post("https://api.securitycenter.microsoft.com/api/machines/mde-1/collectInvestigationPackage").mock(side_effect=respond)++ client = DefenderClient(tenant_id="tid", client_id="cid", client_secret="unit-test-placeholder")+ result = await client.collect_investigation_package("WS-4471", comment="C2 stage")++ assert result["mde_action_id"] == "act-9"+ assert result["status"] == "Pending"+ assert "C2 stage" in str(captured["body"])+++async def test_package_uri_is_read_from_the_value_field() -> None:+ respx.post("https://login.microsoftonline.com/tid/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))+ respx.get("https://api.securitycenter.microsoft.com/api/machineactions/act-9/getPackageUri").mock(+ return_value=httpx.Response(200, json={"value": "https://mde.example.invalid/pkg.zip"})+ )++ client = DefenderClient(tenant_id="tid", client_id="cid", client_secret="unit-test-placeholder")+ assert await client.get_investigation_package_uri("act-9") == "https://mde.example.invalid/pkg.zip"+++async def test_package_uri_is_none_while_the_collection_is_still_running() -> None:+ """MDE only issues a URI once the package exists; 404 is not an error here."""+ respx.post("https://login.microsoftonline.com/tid/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))+ respx.get("https://api.securitycenter.microsoft.com/api/machineactions/act-9/getPackageUri").mock(+ return_value=httpx.Response(404, json={"error": {"code": "NotFound"}})+ )++ client = DefenderClient(tenant_id="tid", client_id="cid", client_secret="unit-test-placeholder")+ assert await client.get_investigation_package_uri("act-9") is None+++async def test_machine_actions_are_sorted_newest_first() -> None:+ """Sorted here, not with ``$orderby``.++ The ordering is the part the verifier depends on: a server-side sort that+ silently is not applied would hand back the oldest acquisition as if it+ were the one we just started.+ """+ respx.post("https://login.microsoftonline.com/tid/oauth2/v2.0/token").mock(return_value=httpx.Response(200, json={"access_token": "t"}))+ respx.get("https://api.securitycenter.microsoft.com/api/machineactions").mock(+ return_value=httpx.Response(+ 200,+ json={+ "value": [+ {"id": "old", "creationDateTimeUtc": "2026-09-01T00:00:00Z"},+ {"id": "new", "creationDateTimeUtc": "2026-09-23T00:00:00Z"},+ ]+ },+ )+ )++ client = DefenderClient(tenant_id="tid", client_id="cid", client_secret="unit-test-placeholder")+ actions = await client.list_machine_actions("mde-1", INVESTIGATION_PACKAGE_ACTION)++ assert [a["id"] for a in actions] == ["new", "old"]diff --git a/services/actions/tests/test_chatops_governed_dispatch.py b/services/actions/tests/test_chatops_governed_dispatch.pynew file mode 100644index 000000000..48a6a29a9--- /dev/null+++ b/services/actions/tests/test_chatops_governed_dispatch.py@@ -0,0 +1,256 @@+"""ChatOps verification: a working executor that had nowhere honest to land.++``ChatOpsVerifyExecutor`` has always worked and has always sat in+``EXECUTOR_REGISTRY``, and no live-action adapter reached it — so the only+route to it was the legacy ``ActionType`` endpoint, which has no capability+contract, no approval matrix and no autonomy policy in front of it.++It was left that way deliberately rather than registered, and the reason was+sound: the executor returns ``ActionStatus.RUNNING`` to mean "the prompt went+out and nobody has answered", ``LiveActionStatus`` had no state for that, and+``_to_live_status`` folded everything that was not FAILED or a simulation into+SUCCEEDED. Registering it as-is would have reported an unanswered question as+a completed action.++The fix is the missing state rather than the exemption — and ``AWAITING_COMPLETION``+turned out to be what evidence acquisition needed too, so one status covers+both executors that had no honest result to return.++Why this verb is analyst-gated at ``notify``'s impact: ``notify`` addresses a+SOC channel, this addresses the account under investigation. Sent+automatically on a true positive it tells an attacker they have been detected,+and the verb has no way to know whether the person it is asking is the+suspect.+"""++from __future__ import annotations++from uuid import uuid4++import pytest+from app.live_actions import builtins, registry+from app.live_actions.builtins import _to_live_status+from app.live_actions.capabilities import KNOWN_CAPABILITIES+from app.live_actions.capability_contracts import CAPABILITY_CONTRACTS+from app.live_actions.contract import ActionImpact, ApprovalRequirement+from app.live_actions.models import LiveActionRequest, LiveActionStatus+from app.models.action import ActionStatus, ActionType+from app.services.executor_registry import EXECUTOR_REGISTRY++PARAMS = {+ "webhook_url": "https://hooks.example.invalid/T000/B000/xxxx",+ "user_ref": "[email protected]",+ "question": "Did you sign in from Lagos at 03:14?",+}++[email protected](autouse=True)+def _registered() -> None:+ registry.reset_for_tests()+ builtins.register_builtin_executors(overwrite=True)+++def _chatops_enabled(monkeypatch) -> None:+ """The executor hard-fails when the feature flag is off, by design."""+ from app.core.config import get_settings++ settings = get_settings()+ monkeypatch.setattr(settings, "AISOC_FEATURE_CHATOPS_VERIFY", True, raising=False)+ monkeypatch.setattr(settings, "AISOC_CHATOPS_RESPONSE_SECRET", "unit-test-placeholder", raising=False)+++# ── The missing state ──────────────────────────────────────────────────────+++def test_running_no_longer_collapses_into_succeeded() -> None:+ """The unit-level form of the defect that kept this executor unreachable."""+ assert _to_live_status(ActionStatus.RUNNING, {}) is LiveActionStatus.AWAITING_COMPLETION+++def test_awaiting_completion_is_distinct_from_pending_approval() -> None:+ """They mean opposite things about whether the vendor was touched.++ PENDING_APPROVAL: nothing ran, policy wants a human first.+ AWAITING_COMPLETION: the vendor was touched and the outcome is not known.+ """+ assert LiveActionStatus.AWAITING_COMPLETION is not LiveActionStatus.PENDING_APPROVAL+ assert LiveActionStatus.AWAITING_COMPLETION.value == "awaiting_completion"+++def test_a_simulation_still_wins_over_running() -> None:+ """Order matters: a simulated result must never read as work in flight."""+ assert _to_live_status(ActionStatus.RUNNING, {"note": "Simulation mode — nothing sent"}) is LiveActionStatus.SIMULATED+++# ── Reachability ───────────────────────────────────────────────────────────++[email protected]("vendor", ["slack", "teams"])+def test_chatops_verify_resolves_through_governed_dispatch(vendor: str) -> None:+ assert registry.get_executor(vendor, "chatops_verify") is not None, (+ f"{vendor}/chatops_verify does not resolve, so the only route to a working " f"executor is the ungoverned ActionType endpoint."+ )+++def test_chatops_verify_is_in_the_vocabulary_and_has_a_contract() -> None:+ assert "chatops_verify" in KNOWN_CAPABILITIES+ assert ActionType.CHATOPS_VERIFY in EXECUTOR_REGISTRY++ contract = CAPABILITY_CONTRACTS["chatops_verify"]+ assert contract.impact is ActionImpact.LOW+ # Not automatic, unlike notify at the same impact: this one messages the+ # account under investigation rather than a SOC channel.+ assert contract.approval is ApprovalRequirement.ANALYST+ assert CAPABILITY_CONTRACTS["notify"].approval is ApprovalRequirement.AUTOMATIC+ # No probe, and the reason is recorded rather than silently absent.+ assert contract.has_verification_probe is False+ assert len(contract.verification_gap.strip()) > 40+++# ── Behaviour ──────────────────────────────────────────────────────────────+++async def test_a_delivered_prompt_is_not_reported_as_a_completed_action(monkeypatch, _chatops_enabled) -> None:+ """The regression this whole change exists to prevent.++ Before ``AWAITING_COMPLETION`` this path produced SUCCEEDED, which tells a+ responder a question has been answered when it has only been asked.+ """+ from app.executors import chatops++ async def _delivered(**kwargs):+ return {"ok": True, "transport": "slack"}++ async def _timeline(**kwargs):+ return None++ monkeypatch.setattr(chatops, "send_slack_prompt", _delivered)+ monkeypatch.setattr(chatops, "post_timeline_event", _timeline)++ executor = registry.get_executor("slack", "chatops_verify")+ assert executor is not None+ result = await executor.execute(+ LiveActionRequest(+ capability="chatops_verify",+ vendor_id="slack",+ target="[email protected]",+ params=dict(PARAMS),+ tenant_id=uuid4(),+ )+ )++ assert result.status is LiveActionStatus.AWAITING_COMPLETION+ assert result.status is not LiveActionStatus.SUCCEEDED+ assert "awaiting their reply" in result.summary+++async def test_each_arm_pins_its_own_transport(monkeypatch, _chatops_enabled) -> None:+ """A pin so the channel is the caller's choice of vendor, not a default.++ Unlike the SIEM arms there is no credential-ordering hazard to guard —+ both transports use the same single ``webhook_url`` — so the pin selects a+ message format rather than claiming an arm that could not have run.+ """+ from app.executors import chatops++ sent: list[str] = []++ async def _slack(**kwargs):+ sent.append("slack")+ return {"ok": True}++ async def _teams(**kwargs):+ sent.append("teams")+ return {"ok": True}++ async def _timeline(**kwargs):+ return None++ monkeypatch.setattr(chatops, "send_slack_prompt", _slack)+ monkeypatch.setattr(chatops, "send_teams_prompt", _teams)+ monkeypatch.setattr(chatops, "post_timeline_event", _timeline)++ for vendor in ("slack", "teams"):+ executor = registry.get_executor(vendor, "chatops_verify")+ assert executor is not None+ # `transport` is deliberately set to the *other* arm in the params, to+ # prove the pin wins over whatever the caller happened to pass.+ await executor.execute(+ LiveActionRequest(+ capability="chatops_verify",+ vendor_id=vendor,+ target="[email protected]",+ params={**PARAMS, "transport": "teams" if vendor == "slack" else "slack"},+ tenant_id=uuid4(),+ )+ )++ assert sent == ["slack", "teams"]+++async def test_a_dry_run_asks_nobody_anything(monkeypatch, _chatops_enabled) -> None:+ """The adapter simulates rather than stripping credentials.++ The base adapter implements dry_run by deleting credential keys so the+ legacy executor falls into its simulation branch. This executor has no+ such branch on purpose — its docstring is explicit that an unreachable+ transport is a hard failure, because an action whose point is asking a+ person a question must not quietly not ask. Stripping the webhook would+ therefore report a preview as a failure, so the adapter short-circuits+ before anything mints a callback token or opens a socket.+ """+ from app.executors import chatops++ async def _tripwire(**kwargs):+ raise AssertionError("a dry run delivered a real ChatOps prompt")++ monkeypatch.setattr(chatops, "send_slack_prompt", _tripwire)+ monkeypatch.setattr(chatops, "send_teams_prompt", _tripwire)+ monkeypatch.setattr(chatops, "mint_token", lambda **kwargs: (_ for _ in ()).throw(AssertionError("a dry run minted a callback token")))++ executor = registry.get_executor("slack", "chatops_verify")+ assert executor is not None+ result = await executor.execute(+ LiveActionRequest(+ capability="chatops_verify",+ vendor_id="slack",+ target="[email protected]",+ params=dict(PARAMS),+ dry_run=True,+ tenant_id=uuid4(),+ )+ )++ assert result.status is LiveActionStatus.SIMULATED+ assert "no prompt was delivered" in str(result.details.get("note", ""))+++async def test_an_undeliverable_prompt_still_fails(monkeypatch, _chatops_enabled) -> None:+ """AWAITING_COMPLETION must not become a place for failures to hide."""+ from app.executors import chatops+ from app.services.chatops_prompt import ChatOpsPromptError++ async def _boom(**kwargs):+ raise ChatOpsPromptError("channel_not_found")++ monkeypatch.setattr(chatops, "send_slack_prompt", _boom)++ executor = registry.get_executor("slack", "chatops_verify")+ assert executor is not None+ result = await executor.execute(+ LiveActionRequest(+ capability="chatops_verify",+ vendor_id="slack",+ target="[email protected]",+ params=dict(PARAMS),+ tenant_id=uuid4(),+ )+ )++ assert result.status is LiveActionStatus.FAILED+ assert "channel_not_found" in (result.error or "")diff --git a/services/actions/tests/test_live_action_builtins.py b/services/actions/tests/test_live_action_builtins.pyindex a2a106375..62c6aa9be 100644--- a/services/actions/tests/test_live_action_builtins.py+++ b/services/actions/tests/test_live_action_builtins.py@@ -58,8 +58,10 @@ def test_register_builtin_executors_returns_full_count() -> None:# registry — SentinelOne implemented seven operations with one# reachable, Entra six with one. The writeback arms are the return leg# of a two-way SIEM integration: AiSOC's verdict back onto the notable,- # signal, incident or offense that produced the alert.- assert count == 63+ # signal, incident or offense that produced the alert. Plus 3 for the+ # verbs that were reachable from a recommendation and not from dispatch:+ # Defender evidence acquisition, and the two ChatOps transports.+ assert count == 66def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:@@ -94,6 +96,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("crowdstrike", "unisolate_host"),("defender", "ack_alert"),("defender", "block_ioc"),+ ("defender", "capture_forensics"),("defender", "update_alert_disposition"),("defender", "get_host"),("defender", "isolate_host"),@@ -130,6 +133,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("sentinelone", "run_script"),("sentinelone", "unisolate_host"),("servicenow", "create_ticket"),+ ("slack", "chatops_verify"),("slack", "notify"),("splunk", "ack_alert"),("splunk", "create_notable_event"),@@ -137,6 +141,7 @@ def test_builtin_executors_cover_canonical_vendor_capability_pairs() -> None:("splunk", "search_siem"),("splunk", "sync_detection_rule"),("splunk", "update_alert_disposition"),+ ("teams", "chatops_verify"),}assert pairs == expected@@ -167,7 +172,7 @@ def test_register_builtin_executors_is_idempotent_with_overwrite() -> None:register_builtin_executors()# Second call without overwrite would raise — confirm overwrite works.count = register_builtin_executors(overwrite=True)- assert count == 63+ assert count == 66def test_register_builtin_twice_without_overwrite_raises() -> None:diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 8c9abb6a0..68c8590e0 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -146,6 +146,18 @@ class Capability(str, Enum):ACK_ALERT = "ack_alert"SUPPRESS_ALERT = "suppress_alert"+ # EVIDENCE — acquire artefacts from a host before they age out.+ # The investigation agent proposes this on the C2 / exfiltration path and+ # nothing implemented it, so the product recommended an acquisition it+ # could not perform at the point where evidence matters most.+ CAPTURE_FORENSICS = "capture_forensics"++ # HUMAN-IN-THE-LOOP — ask the affected person a question and route the+ # answer back onto the case. Distinct from NOTIFY: notify tells a SOC+ # channel something, this asks an end user to confirm or deny, and the+ # action is not finished until they answer.+ CHATOPS_VERIFY = "chatops_verify"+# TICKET — bidirectional ITSM (Jira / ServiceNow / etc.).PUSH_CASE = "push_case"PUSH_STATUS = "push_status"