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
Playbooks that said they contained response steps, and did not (#814)
Beenu Arorac6e3f31b13f4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 71f81e070..33895f508 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1106,6 +1106,14 @@ jobs:run: python3 scripts/check_playbook_schema_parity.py --self-test- name: Parity gate testsrun: python3 -m pytest tests/test_playbook_schema_parity_gate.py -q+ - name: The documented upgrade command runs, and its output validates+ # MIGRATION.md has told operators to run `scripts/upgrade_playbooks.py`+ # since v4 and the script did not exist. The test asserts a v3 playbook+ # fails the real schema before and passes it after, so the doc cannot+ # go back to naming a command that is not there.+ run: python3 -m pytest tests/test_upgrade_playbooks.py -q+ - name: Shipped packs need no upgrade+ run: python3 scripts/upgrade_playbooks.py --dir playbooks# ──────────────────────────────────────────────# Docker Compose smoke testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 336a368ec..ee56a3104 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -213,6 +213,88 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0only to each other would have left the gate agreeing about a bound thatnothing installs.+- **A playbook step that names a response verb now reaches governed+ dispatch, and says honestly what happened to it.** Fifteen of the engine's+ twenty-two step types name an action against somebody's estate. Three of+ them — `block_ip`, `isolate_host`, `create_ticket` — returned+ `{"simulated": true}` from inside the engine, reached no executor, and were+ recorded `SUCCESS`; the other twelve had no handler at all. Meanwhile+ `services/actions` held working executors for fourteen of the fifteen,+ behind a contract declaring each verb's impact, reversibility, approval+ requirement and whether a probe exists to confirm the effect landed. The+ missing piece was never an executor. The comment in `action.py` asserting+ that "playbooks dispatch step by step through this service, so every step+ is graded on the way past" described something that did not happen.++ The bridge is `services/agents/app/playbook/action_bridge.py` ->+ `POST /api/v1/playbook-steps/dispatch` -> `live_actions.dispatch()`. It+ lands in the API rather than going direct because that service holds the+ credential vault and the tenant session, and `services/actions` is the only+ place that may change a customer's estate — the same shape, and the same+ reasoning, as `siem_writeback`. **One step, one request, one grading**: a+ playbook is not approved as a unit, so authorising it cannot authorise+ whatever its steps happen to contain.++ `executed` is the single field that means a vendor was touched. A preview,+ an approval queue, a blocked action, a tenant with no integration, a+ credential-less simulation and a vendor failure are each named and each+ `executed: false`, and a step that did not execute is recorded FAILED so+ the run halts under the default `on_failure: abort`. `AWAITING_COMPLETION`+ counts as executed and `PENDING_APPROVAL` does not: collapsing that pair+ either loses an action in flight or invents one that never ran. Execution+ is off by default (`AISOC_PLAYBOOK_ACTIONS_EXECUTE`), so out of the box a+ response step previews and reports a preview.++ **`approval` is the one step type deliberately not bridged.** It is a+ pause, and the engine is a single-threaded index walk with nothing to+ suspend and nothing to wake. It is also no longer the mechanism: every+ response step is now graded individually at dispatch and returns+ `pending_approval` on its own when a human is required, so a gate in front+ of one would gate a decision that is already gated. It fails closed with+ that reason recorded rather than shipping a handler that pretends.++ **`run_playbook` as a nested step stays unimplemented, and the calculus was+ re-examined rather than inherited.** Per-step grading was the missing piece+ the previous decision named, and it now exists — but the objection it was+ the answer to does not move: a nested playbook's steps are still not+ visible where the parent declares its policy. What changed is that the+ parent no longer *needs* to bound them, because each step is graded on+ arrival wherever it came from. What has not changed is that the engine+ cannot see a nested playbook's content before running it, so an author+ cannot review what a run will do, and a cycle across two playbooks that+ reference each other is unbounded by the per-step `visited` set. Recursion+ depth and an ancestor set would answer the second; the first is a product+ question about reviewability, not a governance gap, and it is the reason to+ keep waiting.++ The schema's `x-aisoc-execution` map gains a `governed` class rather than+ reusing `executed`, because "a handler ran and made an outbound call" and+ "a vendor was touched" are different claims and the second is answered per+ run. `simulated` stays in the vocabulary: it is the class for a handler+ that answers from inside the engine, which is what these three did, and+ deleting the word would make that state unspellable rather than absent.+ `check_playbook_schema_parity.py` compares `governed` against+ `engine.RESPONSE_STEP_TYPES` in both directions, so a verb wearing the+ label while being answered locally fails the build.++- **`scripts/upgrade_playbooks.py`, which `docs/upgrade/MIGRATION.md` has told+ operators to run since v4.** It did not exist, so the one command in the+ upgrade path that touches a customer's own content failed at exactly the+ moment it was needed. The field table beside it was worse: four of the five+ spellings in its "v4" column are rejected by the schema+ (`on_failure: {policy}`, `retry: {max_attempts, backoff}`,+ `condition: {expr, language}`, and `type: "action"`, which is not a step+ type at all), so following the doc by hand produced playbooks that would+ not validate either. Both are corrected.++ The script reports before it writes, validates its own output against the+ real `schemas/playbook.schema.json` before touching anything, and leaves+ alone any file whose upgrade would not validate. `loop`, `parallel`,+ `wait`, `run_playbook`, `action` and `trigger` are reported and refused+ rather than mapped onto a nearest neighbour — that rewrite is precisely the+ defect removed from the NL drafter, where a `disable_user` step shipped as+ `investigate`. An empty scan is a failure, not a clean bill of health.+- **`scripts/check_connector_profiles.py` — a connector-type drift gate thatreads in both directions.** Nothing compared the profile keys in`services/ingest/internal/normalizer/normalizer.go` against the identifiers@@ -741,6 +823,68 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`>=0.4.4,<0.5`. The devcontainer also told contributors to `uv sync` against`services/api/uv.lock`, which has never existed in this tree.+- **The capability contract was not consulted on the dispatch path an agent+ uses.** `POST /actions` has run the contract through+ `approval_gate.apply_matrix` since the approval gate was fixed.+ `live_actions.dispatch()` — the registry-driven path next to it, used by+ the agent loop, the console dry-run and now the playbook engine — ran+ `autonomy_safety.decide()` and nothing else. `decide()` reads+ `ACTION_BLAST_RADIUS`, a second risk ladder keyed on `ActionType`, and for+ **nine verbs it is the weaker of the two declarations** (`block_ip`,+ `block_domain` and `reset_password` are blast `medium` against impact+ `high`; `run_script` is blast `high` against impact `severe`;+ `quarantine_file` is blast `low` against impact `moderate`). So the same+ verb was graded differently depending on which door it came through, and+ the weaker grade belonged to the door an agent uses. `dispatch()` now+ applies the contract and `approval_matrix.evaluate` — each input may raise+ a requirement and none may lower it, so switching it on cannot make+ anything auto-execute that did not before.++ `LiveActionRequest` gains `confidence`, because the matrix needs both axes+ and the request carried only one. Absent is the lowest band, not a free+ pass: defaulting permissive turns a scoring bug into an autonomous+ containment.++ Three further holes closed in the same wiring:++ - **A contracted verb with no `ActionType` skipped governance entirely.**+ `_action_type_for` returned `None` for `revoke_session` and the whole+ gate was `if action_type is not None`, so a MODERATE-impact identity+ action reached its executor with no tier check, no blast check and no+ contract applied. Those verbs are now graded from the contract's own+ impact under the tenant's tier.+ - **A tenant `force_auto` override could lower a contract that declares+ `analyst`.** `ActionContract.approval` says the tenant's autonomy policy+ "can raise this but never lower it"; the override reached AUTO anyway,+ because the contract was not in the path. It still lifts the *tier+ ceiling*, which is what it is for, and no longer lifts the floor.+ - **An execution with no probe left the verification field blank.** Probes+ are keyed on `ActionType`, so a contracted verb without one had nothing+ to record. A blank field and a confirmed one are indistinguishable to a+ reader, so the honest answer — `unverified`, with the reason — is written+ explicitly.++- **A playbook run reported COMPLETED when its steps had failed.**+ `on_failure: continue` decides whether the run keeps going; it was also+ deciding what the run was called afterwards. 346 of the 380 steps in the+ shipped packs carry it, so a containment playbook whose every response step+ failed still finished green. A run that ends with any failed step is now+ FAILED, with an error naming how many and which, and the author's+ `continue` policy still governs whether the remaining steps are attempted.++- **`packages/types/src/playbook.ts` published a fourth playbook+ vocabulary.** A 28-member `ActionType` union (`notify_email`,+ `create_ticket_jira`, `collect_forensics`, `run_query_splunk`, …) matching+ neither the schema nor `StepType`; a `PlaybookStep.action: ActionConfig`+ shape the engine does not parse; `depends_on`, `run_parallel`,+ `blast_radius_check` fields nothing reads; and `waiting_approval` /+ `paused` run states the engine cannot enter. Nothing imports the package,+ which is why it drifted unnoticed — and is also why it mattered: it is what+ the next integrator would have built against, and the server would have+ rejected their code. Rewritten to mirror `StepType`, `PlaybookStep`,+ `RunStatus` and the dispatch report, and `check_playbook_schema_parity.py`+ now compares the published union against the engine's in both directions.+- **An event ingested under a connector type with no profile became an alertwith no host, no user and no source IP.** `_canonicalAliases` in`services/ingest/internal/normalizer/normalizer.go` already resolveddiff --git a/ROADMAP.md b/ROADMAP.mdindex df60431cf..71ba9c919 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -56,15 +56,23 @@ The claim-to-gate matrix stands at **108 rows — 99 GATED / 9 PARTIAL / 0 NO GA- [x] Eval harness: 20 synthetic incidents, ≥80% MITRE-tactic accuracy CI gate### Visual SOAR studio-- [x] React Flow playbook editor over the step types the engine implements- (enrich, investigate, notify, block_ip, isolate_host, create_ticket,- close_case, http, condition). Loop, Parallel, Wait and Human Approval- were listed here and exist in neither the palette nor the engine.+- [x] React Flow playbook editor over nine of the step types the engine+ implements (enrich, investigate, notify, block_ip, isolate_host,+ create_ticket, close_case, http, condition). The engine accepts 22 and+ runs 21; widening the palette to the rest is outstanding. Loop,+ Parallel, Wait and Human Approval were listed here and exist in neither+ the palette nor the engine.- [x] Sequential playbook engine with conditions, branching, retries andcycle detection. Not a DAG: there is no `depends_on` and no parallel- execution. No idempotency keys and no step-level blast-radius check —- `blast_radius` was declared by a schema the engine could not read, and- that schema has been removed rather than left as a promise.+ execution, and there are no idempotency keys.+- [x] Step-level risk grading, by dispatch rather than by a schema field.+ A step naming a response verb is dispatched to the action registry and+ graded against that verb's capability contract — impact, reversibility,+ approval requirement, verification probe — plus the tenant's autonomy+ tier and the finding's confidence. Per step, so authorising a playbook+ does not authorise what its steps contain. The old `blast_radius` step+ field promised this and was declared by a schema the engine could not+ read; it has been removed rather than left as a promise.- [x] `schemas/playbook.schema.json` (JSON Schema draft-07) for portabilityand CI linting, held to the engine in both directions by`scripts/check_playbook_schema_parity.py`diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex a44654b5b..90f22d65a 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: 115 rows+The last row is the one worth reading first. It is the honest index: 119 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/playbooks.md b/apps/docs/docs/concepts/playbooks.mdindex c3eb6ae93..c5f4ee06d 100644--- a/apps/docs/docs/concepts/playbooks.md+++ b/apps/docs/docs/concepts/playbooks.md@@ -103,31 +103,50 @@ being true.| `condition` | Pure branching node. Evaluates `condition` and routes to `next_true` / `next_false`. || `osquery_live_query` | Distributed osquery via osctrl / FleetDM / aisoc-direct, against an allow-listed template. |-**Simulated** — a handler runs and returns `{"simulated": true, ...}` without-touching a vendor. Wire them to real connectors by editing the handler, or-replace the step with an `http` step that calls your connector's enforcement-endpoint:--| `type` | What it does |-|--------|--------------|-| `block_ip` | Reports the IP it would block. |-| `isolate_host` | Reports the host it would isolate. |-| `create_ticket` | Reports the ticket it would open. |--**Vocabulary without an engine handler** — these parse, validate and are used-by the shipped packs, but no handler is registered, so the engine **fails the-step closed** rather than reporting a success it did not achieve. With the-default `on_failure: abort` that halts the run:--`approval`, `block_ioc`, `disable_user`, `reset_password`, `revoke_session`,-`force_mfa`, `kill_process`, `quarantine_file`, `run_av_scan`, `run_script`,-`search_siem`, `create_notable_event`.--Most of these verbs *do* have working executors in the actions service, which-grades each one against its own capability contract before it runs. What does-not exist yet is a bridge from a playbook step to that governed dispatch, so-today they are authoring vocabulary rather than execution. A run that reaches-one stops and says so.+**Governed** — the step is dispatched to the action registry in the actions+service, which grades it against the verb's own capability contract and the+tenant's autonomy policy before anything reaches a vendor:++`block_ip`, `block_ioc`, `isolate_host`, `kill_process`, `quarantine_file`,+`run_av_scan`, `run_script`, `disable_user`, `reset_password`,+`revoke_session`, `force_mfa`, `search_siem`, `create_notable_event`,+`create_ticket`.++Each step is dispatched **individually**. Approving or running a playbook does+not authorise whatever its steps happen to contain: the contract is applied+per verb, per step, at the moment that step runs. See+[Live actions](./live-actions.md) for what each verb declares about its impact,+reversibility, approval requirement and verification probe.++What comes back is a report whose `executed` field is the single thing that+means a vendor was actually touched:++| `status` | `executed` | Meaning |+|----------|-----------|---------|+| `executed` | `true` | The vendor ran it. `verification` says whether a probe confirmed the effect, or `unverified` if no probe exists. |+| `awaiting_completion` | `true` | The vendor accepted it and the outcome is not known yet. |+| `dry_run` | `false` | Previewed. This is the default posture — see below. |+| `pending_approval` | `false` | Held for an analyst by the contract or the tenant's tier. Nothing ran. |+| `blocked` | `false` | Refused by tenant policy. |+| `simulated` | `false` | The executor found no usable credentials and took its safe path. |+| `no_integration` | `false` | The verb is supported and this tenant has no enabled connector that performs it. |+| `unsupported` | `false` | No executor is registered for this verb in this deployment. |+| `failed` | `false` | The vendor or the dispatch itself failed. |++A step that did not execute is recorded `FAILED`, so the run halts under the+default `on_failure: abort`. This is deliberate: the steps after a containment+assume the containment happened.++**Execution is off by default.** `AISOC_PLAYBOOK_ACTIONS_EXECUTE` is unset, so+response steps preview and report `dry_run`. Set it to `1` to let a playbook+touch a vendor — and note that governance can still refuse an execution this+allows, and can never allow one it refuses. `AISOC_AGENTS_SERVICE_TOKEN` must+also be set, or the agents service cannot reach the API's service path and the+step fails closed saying so.++**No handler** — `approval` is the one step type the engine accepts and cannot+run. It fails closed with a reason; see+[Approvals and dry-runs](#approvals-and-dry-runs) below.Common step fields:@@ -169,7 +188,11 @@ handling.- `on_failure: "abort"` (default) — failed step stops the run, marks it`FAILED`, and emits `run.done` with the error.- `on_failure: "continue"` — log the failure but proceed to the next step.- Useful for best-effort enrichment that shouldn't block containment.+ Useful for best-effort enrichment that shouldn't block containment. It+ decides whether the run keeps going, not what the run is called: a run that+ finishes with any failed step is `FAILED`, with an error naming how many and+ which. A green tick over a containment that never happened is the same fake+ success one level up.- `on_failure: "retry"` — combined with `retry_max`, retries with exponentialbackoff before falling back to whatever you set as the next-failure mode.- Cycle detection — if the engine revisits the same `step.id`, it aborts with@@ -192,15 +215,28 @@ UI and in run history.**`dry_run` flag** — pass `dry_run: true` when calling`PlaybookEngine.run(...)`. Handlers short-circuit with-`{"dry_run": true, "step": <name>}` and emit the same realtime events, so you-can preview an entire run without touching production. A step whose type has-no handler is additionally reported as `unimplemented: true, would_fail: true`,-so a preview tells you which steps a real run would stop on.--**Human-in-the-loop is not implemented.** The engine is a single pass with no-pause or resume, and an `approval` step fails closed (see-[Steps](#steps) above), which halts the run under the default-`on_failure: abort`.+`{"dry_run": true, "executed": false, "step": <name>}` and emit the same+realtime events, so you can preview an entire run without touching+production. A governed step additionally reports `would_dispatch` and the+`target` it resolved, so a preview of a containment playbook reads as one. A+step whose type has no handler is reported as+`unimplemented: true, would_fail: true`, so a preview tells you which steps a+real run would stop on.++**An `approval` step is not implemented, and is no longer the mechanism.**+The engine is a single pass with no pause or resume, so there is nothing to+suspend and nothing to wake. It fails closed with a reason rather than+pretending, which halts the run under the default `on_failure: abort`.++You usually do not need one. Every response step is graded against its own+capability contract at dispatch and comes back `pending_approval` on its own+when a human is required — `isolate_host`, for instance, declares+`approval: analyst`, which no autonomy tier or confidence level lifts. An+`approval` step in front of it would gate a decision that is already gated.++Where you want an action to actually wait for a named approver, submit it to+the actions service (`POST /actions`), which holds it at `awaiting_approval`+and records the deciding principal. That path is real and audited.This section previously described a second supported pattern: model the gateas a `condition` step backed by a field an operator sets via@@ -211,11 +247,6 @@ run context and moves on. Worse, until recently an `approval` step reported`SUCCESS` without doing anything, so a playbook that modelled a gate ranstraight through it into whatever it was gating.-If you need an approval gate today, split the playbook: run the-investigative half, and submit the response verb to the actions service-(`POST /actions`), which grades it against its capability contract and holds-it at `awaiting_approval` for an analyst. That path is real and audited.-## Realtime eventsEvery run emits events to the realtime service so the UI can stream progress:diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 80e5cac7e..67c003fb9 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -127,15 +127,19 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No OSS default resolves to a specific deployment's hostname, so a self-hosted install never presents another deployment's host as its own | self-host contract; `apps/docs/docs/deployment/env-vars.md` (CORS default) | `hosted-hostname.yml` (`scripts/check_hosted_hostname.py` — an exact occurrence count per path, checked in **both** directions: a new or grown occurrence and a stale exemption whose occurrence is gone both fail, so an allow-list entry cannot outlive what justified it; the root is resolved from the working directory rather than `__file__` and verified against sentinels, a zero-match scan is reported as broken rather than clean, and `--self-test` runs first proving the detector separates known-bad from known-good and that the comparison rejects a vacuous pass; it also pins the six vendored `cors.py` copies byte-identical) + `tests/test_hosted_hostname_gate.py` (39 cases, including the ten runtime defaults that leaked and a check that the CORS-tuple extractor itself would notice the origin coming back) | GATED | - || A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only || Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list |-| The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | twelve step types are declared vocabulary with no engine handler; the schema says so per type and the engine fails them closed, so the gap is published rather than hidden. Closes when playbook steps dispatch through the actions service's per-capability contract |+| The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | the `governed` execution class is compared against `engine.RESPONSE_STEP_TYPES` in both directions, and the published `StepType` union in `packages/types` against the engine's, because that file had drifted into a fourth 28-member vocabulary nothing imported. `approval` is the one remaining unimplemented type and the schema says so || A step a playbook engine cannot run never reports that it ran | concepts/playbooks.md (error handling) | `ci.yml` agents job (`test_playbook_engine_correctness.py::TestUnimplementedStepTypesFailClosed` — an `approval` gate the engine cannot honour halts the run instead of passing it, every handler-less `StepType` is asserted to fail rather than succeed, a missing handler is not retried, an explicit `on_failure: continue` is still honoured, and a dry run reports `would_fail` rather than a bare `dry_run: true`) | GATED | - |+| A playbook step that names a response verb reaches governed dispatch | concepts/playbooks.md (governed step table) | `ci.yml` agents job (`test_playbook_action_bridge.py` — every member of `RESPONSE_STEP_TYPES` is asserted to produce one dispatch, each carrying its own step id, so the contract is applied per step rather than per playbook) + `ci.yml` api job (`test_playbook_step_dispatch.py`) + `ci.yml` P2 job (`check_playbook_schema_parity.py` compares the schema's `governed` class against `engine.RESPONSE_STEP_TYPES` in both directions, so a verb labelled governed that the engine answers locally fails the build) | GATED | `approval` is deliberately not bridged: the engine has no pause to suspend, and per-step grading has replaced the need for it |+| A playbook step that did not touch a vendor never reports that it did | concepts/playbooks.md (status table) | `ci.yml` agents job (`test_playbook_action_bridge.py::TestNoFakeSuccess` — each of six non-executing outcomes fails the step and the run; `awaiting_completion` is asserted to count as executed and `pending_approval` not to, because collapsing that pair loses an action in flight or invents one that never ran) + `ci.yml` api job (`test_playbook_step_dispatch.py::TestHowItReadsTheResult` — every `LiveActionStatus` maps to one honest outcome and an unrecognised status is treated as not executed) | GATED | execution is off by default (`AISOC_PLAYBOOK_ACTIONS_EXECUTE`), so out of the box a response step previews and says so |+| The capability contract is applied on the registry-driven dispatch path, not only on `POST /actions` | concepts/live-actions.md (contract belongs to the verb) | `ci.yml` actions job (`test_dispatch_capability_contract.py` — a verb the blast table calls medium is held at its declared high impact, a contracted verb with no `ActionType` is governed rather than skipped, missing confidence is the lowest band, a read-only verb is not gated, and the contract is asserted unable to lower a verdict blast radius already gated) + `test_dispatch_tenant_governance.py` (a tenant `force_auto` override lifts the tier ceiling and cannot lower a contract that demands an analyst) | GATED | probes are keyed on `ActionType`, so a contracted verb without one reports `unverified` with the reason rather than leaving the field blank |+| The documented playbook upgrade command exists and produces valid output | docs/upgrade/MIGRATION.md (Step 5) | `ci.yml` P2 job (`tests/test_upgrade_playbooks.py` — a v3 playbook is asserted not to validate before and to validate after, against the real `schemas/playbook.schema.json`; every declared rename must land on a type the schema declares; the four types with no v4 equivalent are reported and left unchanged rather than mapped onto a nearest neighbour; check mode writes nothing; an empty scan is a failure, not a clean bill of health) | GATED | the doc previously named a script that did not exist, beside a field table whose v4 column named four spellings the schema rejects || Every `ActionType` resolves a capability contract, so the confidence matrix is never skipped | concepts/live-actions.md (the one alias, and when it goes) | `ci.yml` actions job (`scripts/check_action_contract.py` directions 7 and 8 — every `ActionType` must resolve a contract by name or alias, and every alias must key a real `ActionType`, point at a real contract, not shadow a capability of the same name, and describe a bridge some adapter actually implements) + `test_approval_gate_wiring.py` (`notify_slack` at 10% confidence was approved for auto-execution and now requires an analyst; the alias is asserted unable to *lower* a requirement) | GATED | one alias entry (`notify_slack` -> `notify`), with its retirement condition recorded: it goes when `ActionType` does || Every check this matrix names is actually run by CI | this matrix (each row names a gate) | `ci.yml` (`scripts/check_gate_coverage.py` — resolves the whole graph rather than reading workflow names: workflows, `make` recipes they invoke, the pytest suites they collect and the scripts those reach, so a check wired only through a test still counts. Both directions — a check no workflow reaches, and a workflow step naming a `scripts/` path that does not exist. `--self-test` runs first and asserts the resolver discriminates rather than returning "reached" for everything, and the corpus counts are printed so it cannot report on a tree it never opened) | GATED | the ratchet for a deliberately-unwired check is empty; it may shrink, never grow || What counts as a check is decided by what a script does, not what it is named | `scripts/check_gate_coverage.py` (the inventory it reports on) | `ci.yml` (three structural signals, all read from the tree: a declared verdict flag, an exit status derived from findings the script accumulates, and a workflow job whose output another job branches on. The first two are intrinsic, so an uncalled gate is still inventoried and the `SCRIPT -> WORKFLOW` direction is not vacuous. The classifier is also checked in reverse — a script CI runs with `--check` that the classifier does not inventory fails as `classifier-blind-spot`) + `tests/test_gate_coverage_classifier.py` (10 cases, including a gate planted under a name no convention would reveal, and a generator that aborts on an empty read asserted *not* to be a check) | GATED | - |## Summary-- GATED: 115+- GATED: 119- 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/docs/openapi.yaml b/docs/openapi.yamlindex 912976825..fc4e8cdf9 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -4616,6 +4616,57 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/playbook-steps/dispatch:+ post:+ tags:+ - playbooks+ summary: Run one playbook step through governed action dispatch+ description: 'Dispatch one step and report what actually happened.+++ Never raises for an action-level outcome. A blocked action, an approval++ queue, a missing integration and a vendor failure are all 200 with++ ``executed: false`` and a status naming which one it was, so the engine++ has a single shape to read. ``HTTPException`` is reserved for callers++ this route will not serve at all.'+ operationId: dispatch_playbook_step_api_v1_playbook_steps_dispatch_post+ security:+ - HTTPBearer: []+ parameters:+ - name: x-aisoc-service-token+ in: header+ required: false+ schema:+ anyOf:+ - type: string+ - type: 'null'+ title: X-Aisoc-Service-Token+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/StepDispatchRequest'+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: object+ additionalProperties: true+ title: Response Dispatch Playbook Step Api V1 Playbook Steps Dispatch+ Post+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/plugins:get:tags:@@ -26702,6 +26753,60 @@ components:- dispositiontitle: SourceWritebackRequestdescription: What the caller believes about the alert.+ StepDispatchRequest:+ properties:+ capability:+ type: string+ title: Capability+ description: Response verb, e.g. 'isolate_host'. Must be a registered capability.+ target:+ type: string+ maxLength: 512+ title: Target+ description: Host, user, address or id the verb acts on.+ default: ''+ params:+ additionalProperties: true+ type: object+ title: Params+ vendor_id:+ type: string+ maxLength: 64+ title: Vendor Id+ description: Pin a vendor. Honoured only if the tenant has it configured.+ default: ''+ confidence:+ anyOf:+ - type: number+ maximum: 1.0+ minimum: 0.0+ - type: 'null'+ title: Confidence+ dry_run:+ type: boolean+ title: Dry Run+ default: true+ playbook_run_id:+ type: string+ maxLength: 64+ title: Playbook Run Id+ default: ''+ playbook_step_id:+ type: string+ maxLength: 64+ title: Playbook Step Id+ default: ''+ tenant_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Tenant Id+ type: object+ required:+ - capability+ title: StepDispatchRequest+ description: One playbook step, expressed as the verb it names.SubmissionResponse:properties:id:diff --git a/docs/upgrade/MIGRATION.md b/docs/upgrade/MIGRATION.mdindex 245501c8d..a91994e7c 100644--- a/docs/upgrade/MIGRATION.md+++ b/docs/upgrade/MIGRATION.md@@ -183,16 +183,32 @@ python3 scripts/lint_playbooks.py| v3 field | v4 field | Notes ||----------|----------|-------|-| `type: "action"` | `type: "action"` | Unchanged |-| `on_error: "stop"` | `on_failure: { policy: "abort" }` | Renamed |-| `retry: 3` | `retry: { max_attempts: 3, backoff: "exponential" }` | Expanded |-| `condition: "..."` | `condition: { expr: "...", language: "jmespath" }` | Structured |-| `timeout: 60` | `timeout_seconds: 60` | Renamed |+| `type: "action"` | the specific verb | `action` was a meta-type. Use `block_ip`, `isolate_host`, `disable_user` … — the contract belongs to the verb |+| `type: "isolate"` / `"block"` / `"create_case"` / `"script"` / `"human_approval"` | `isolate_host` / `block_ip` / `create_ticket` / `run_script` / `approval` | Renamed |+| `on_error: "stop"` | `on_failure: "abort"` | Renamed, and a plain string — not an object |+| `retry: { max_attempts: 3 }` | `retry_max: 3` | Flattened. Backoff is not configurable; the engine uses `min(2**attempt, 30)` seconds |+| `condition: { expr: "…", language: "jmespath" }` | `condition: "…"` | The engine's parser is deliberately restricted: one comparison, no JMESPath, no `and`/`or` chains. The structured `{field, operator, value}` form also works |+| `timeout: 60` | `timeout_seconds: 60` | Renamed. Ceiling is 3600s |+| `blast_radius`, `depends_on`, `output_key` | *(removed)* | Declared by the v3 schema and never read by any engine. `blast_radius` in particular promised that "the engine enforces analyst approval for destructive steps" and the engine could not see the field. Approval is now decided per capability at dispatch — see [Playbooks](../../apps/docs/docs/concepts/playbooks.md) |++`loop`, `parallel`, `wait` and `run_playbook` have **no v4 equivalent.** They+named control flow this engine does not have — it is a single-threaded index+walk — so there is no correct rewrite and the upgrader reports them rather+than mapping them onto a nearest neighbour.**Auto-upgrade playbooks:**+The upgrader reports before it writes, and validates its own output against+`schemas/playbook.schema.json` before touching anything. A file whose upgrade+would not validate is left alone and named.+```bash-python3 scripts/upgrade_playbooks.py --dir playbooks/+# Report only — nothing on disk changes. Exit 1 means "something would change",+# exit 2 means a file needs a person.+python3 scripts/upgrade_playbooks.py --dir playbooks++# Apply, once the report looks right+python3 scripts/upgrade_playbooks.py --dir playbooks --write```---@@ -314,8 +330,11 @@ A: Yes. Use a different Docker Compose project name:`docker compose -p aisoc-v4 up -d`Q: Will my v3 playbooks still run?-A: After `python3 scripts/upgrade_playbooks.py`, yes. The v4 engine is-backward-compatible for the core `action` step type.+A: Run `python3 scripts/upgrade_playbooks.py --dir playbooks` first — it+reports what would change without writing. Most playbooks need only the field+renames above. A playbook using `loop`, `parallel`, `wait`, `run_playbook` or+the generic `action` type needs a decision from you: those name behaviour the+v4 engine does not have, and the upgrader will say so rather than guess.Q: How do I roll back to v3 if something goes wrong?A: Restore the PostgreSQL backup from Step 1, then `docker compose pull` withdiff --git a/packages/types/src/playbook.ts b/packages/types/src/playbook.tsindex c40f3daf9..d97e67a2a 100644--- a/packages/types/src/playbook.ts+++ b/packages/types/src/playbook.ts@@ -1,141 +1,179 @@/**- * Playbook / SOAR automation types+ * Playbook / SOAR automation types.+ *+ * These mirror `schemas/playbook.schema.json` and the runtime model in+ * `services/agents/app/playbook/models.py`, and+ * `scripts/check_playbook_schema_parity.py` fails the build when they drift.+ *+ * They used to describe a different product. The previous version declared a+ * 28-member `ActionType` union (`notify_email`, `create_ticket_jira`,+ * `collect_forensics`, `run_query_splunk`, …) that matched neither the schema+ * nor the engine, a `PlaybookStep.action: ActionConfig` shape the engine does+ * not parse, `depends_on` / `run_parallel` / `blast_radius_check` fields+ * nothing reads, and `waiting_approval` / `paused` run states the engine+ * cannot enter — it is a single-threaded index walk with no pause or resume.+ * Nothing imported it, so the drift was invisible; a shared-types package+ * that is wrong is worse than one that is absent, because the next person to+ * import it inherits a contract the server will reject.*/-export type PlaybookTriggerType =- | "alert_created"- | "alert_severity_changed"- | "alert_status_changed"- | "case_created"- | "manual"- | "scheduled"- | "webhook"- | "threat_intel_hit";+/** What can start a playbook. Mirrors `trigger.on` in the schema. */+export type PlaybookTrigger = "alert" | "case" | "manual" | "schedule";-export type ActionType =- | "notify_slack"- | "notify_email"- | "create_ticket_jira"- | "create_ticket_servicenow"- | "page_oncall_pagerduty"- | "enrich_ip"- | "enrich_domain"- | "enrich_hash"- | "enrich_user"- | "isolate_host"- | "contain_user"+/**+ * Every step type the engine accepts. Mirrors `StepType`.+ *+ * What the engine *does* with each one is published in the schema's+ * `x-aisoc-execution` map and reflected in {@link StepExecution} below —+ * accepting a step type and performing it are different claims, and the+ * distinction is the point.+ */+export type StepType =+ | "enrich"+ | "investigate"+ | "notify"| "block_ip"- | "block_domain"- | "block_hash"+ | "block_ioc"+ | "isolate_host"+ | "create_ticket"+ | "close_case"+ | "http"+ | "condition"+ | "osquery_live_query"+ | "approval"+ | "disable_user"+ | "reset_password"| "revoke_session"- | "snapshot_host"- | "collect_forensics"- | "run_query_splunk"- | "run_query_crowdstrike"- | "custom_http"- | "wait"- | "human_approval"- | "set_alert_status"- | "set_case_priority"- | "add_case_comment"- | "assign_case"- | "conditional";+ | "force_mfa"+ | "kill_process"+ | "quarantine_file"+ | "run_av_scan"+ | "run_script"+ | "search_siem"+ | "create_notable_event";-export interface ActionConfig {- action_type: ActionType;- parameters: Record<string, unknown>;- timeout_seconds?: number;- retry_count?: number;- retry_delay_seconds?: number;- on_failure?: "stop" | "continue" | "rollback";- // For conditional action- condition_field?: string;- condition_operator?: "eq" | "ne" | "gt" | "lt" | "contains" | "regex";- condition_value?: unknown;- true_branch?: string[]; // step IDs- false_branch?: string[];+/**+ * What happens when a step of a given type runs.+ *+ * - `executed` — a handler runs and has a real effect.+ * - `governed` — the step is dispatched to the action registry in+ * `services/actions`, where the capability contract and the tenant's+ * autonomy policy decide whether a vendor is touched. Whether one *was* is+ * answered per run by {@link StepDispatchReport.executed}, never assumed.+ * - `unimplemented` — no handler; the engine fails the step closed rather+ * than reporting a success it did not achieve.+ */+export type StepExecution = "executed" | "governed" | "unimplemented";++/**+ * Guard on a step. Either the structured form or an expression string.+ *+ * The expression parser is deliberately restricted to one comparison: no+ * `and`/`or` chains, no function calls, no `eval`.+ */+export interface StepCondition {+ field?: string;+ operator?: "eq" | "ne" | "gt" | "lt" | "contains" | "exists";+ value?: unknown;+ expression?: string;}export interface PlaybookStep {id: string;name: string;- description?: string;- action: ActionConfig;- depends_on?: string[]; // IDs of steps that must complete first- run_parallel?: boolean;- is_approval_gate?: boolean;- approval_roles?: string[];- dry_run_safe?: boolean; // Can be safely run in dry_run mode- blast_radius_check?: boolean; // Require blast-radius assessment before execution+ type: StepType;+ /** Free-form per-verb arguments. Each executor declares its own shape. */+ params?: Record<string, unknown>;+ condition?: StepCondition | string;+ on_failure?: "abort" | "continue" | "retry";+ /** Ceiling is 25 (`bounds.ABSOLUTE_MAX_RETRIES`). */+ retry_max?: number;+ /** 1..3600 seconds (`bounds.ABSOLUTE_MAX_TIMEOUT_SECONDS`). */+ timeout_seconds?: number;+ /** Step id to jump to. The engine branches; it does not build a DAG. */+ next_true?: string;+ next_false?: string;}export interface Playbook {- id: string;- tenant_id: string;+ id?: string;name: string;- description: string;- version: number;- is_active: boolean;- is_draft: boolean;-- trigger: {- type: PlaybookTriggerType;- conditions?: Record<string, unknown>; // e.g., severity = "critical"- schedule?: string; // cron expression- webhook_id?: string;+ description?: string;+ version?: string;+ tags?: string[];+ trigger?: {+ on?: PlaybookTrigger;+ [key: string]: unknown;};-steps: PlaybookStep[];- tags: string[];+ author?: string;+ enabled?: boolean;+ created_at?: string;+ updated_at?: string;+ /**+ * Authored documentation the engine does not read. Declared because real+ * playbooks carry them and a schema that rejected them would be wrong;+ * named here so nobody mistakes them for behaviour.+ */+ inputs?: Record<string, unknown>;+ dry_run_support?: boolean;+}- created_by: string;- created_at: string;- updated_at: string;- approved_by?: string;- approved_at?: string;+/** Mirrors `RunStatus`. There is no `paused` and no `waiting_approval`. */+export type PlaybookRunStatus = "pending" | "running" | "completed" | "failed" | "cancelled";- // Stats- run_count?: number;- success_rate?: number;- avg_duration_seconds?: number;- last_run_at?: string;- last_run_status?: "success" | "partial" | "failed";-}+/** Mirrors `StepStatus`. */+export type PlaybookStepStatus = "pending" | "skipped" | "running" | "success" | "failed";-export type PlaybookRunStatus = "running" | "waiting_approval" | "paused" | "completed" | "failed" | "cancelled";+/**+ * What a governed response step reports back.+ *+ * `executed` is the single field that means a vendor was actually touched. A+ * preview, an approval queue, a blocked action and a tenant with no+ * integration are all `false`, and `status` says which.+ */+export interface StepDispatchReport {+ capability: string;+ status:+ | "executed"+ | "awaiting_completion"+ | "dry_run"+ | "simulated"+ | "pending_approval"+ | "blocked"+ | "no_integration"+ | "unsupported"+ | "failed";+ executed: boolean;+ summary: string;+ vendor_id?: string;+ detail?: string;+ /** Absent when the action did not run: there is nothing to read back. */+ verification?: "verified" | "failed" | "unverified";+ verification_reason?: string;+ autonomy_mode?: string;+ blast_radius?: string;+}export interface PlaybookStepResult {step_id: string;- step_name: string;- status: "pending" | "running" | "success" | "failed" | "skipped" | "waiting_approval";- started_at?: string;- completed_at?: string;- output?: Record<string, unknown>;- error?: string;- dry_run?: boolean;+ name: string;+ status: PlaybookStepStatus;+ /** The handler's return value. For a governed step, a {@link StepDispatchReport}. */+ result?: Record<string, unknown>;+ /** Set on a `condition` step: the step id the engine jumped to. */+ branch?: string;}export interface PlaybookRun {- id: string;+ run_id: string;playbook_id: string;- tenant_id: string;- trigger_type: PlaybookTriggerType;- trigger_context: {- alert_id?: string;- case_id?: string;- manual_by?: string;- };+ playbook_name: string;status: PlaybookRunStatus;- is_dry_run: boolean;+ /** Trigger context plus every step's flattened output. */+ context: Record<string, unknown>;step_results: PlaybookStepResult[];started_at: string;- completed_at?: string;- error?: string;- blast_radius_assessment?: {- estimated_scope: string;- affected_assets: string[];- requires_approval: boolean;- approved_by?: string;- approved_at?: string;- };+ finished_at: string;+ error?: string | null;}diff --git a/schemas/playbook.schema.json b/schemas/playbook.schema.jsonindex 18e19c3fe..f519f141c 100644--- a/schemas/playbook.schema.json+++ b/schemas/playbook.schema.json@@ -8,7 +8,7 @@"additionalProperties": false,"x-aisoc-execution": {- "description": "What `services/agents/app/playbook/engine.py` does with each step type. `executed` = a handler runs and has a real effect (an outbound call to a service, or engine-internal control flow). `simulated` = a handler runs and returns `simulated: true` without touching a vendor. `unimplemented` = no handler is registered; the engine fails the step closed rather than reporting a success it did not achieve. This map is machine-checked against the engine's handler table, so it cannot drift into an aspirational claim.",+ "description": "What `services/agents/app/playbook/engine.py` does with each step type. `executed` = a handler runs and has a real effect (an outbound call to a service, or engine-internal control flow). `governed` = the step is dispatched through the action registry in `services/actions`, where the capability contract and the tenant autonomy policy decide whether a vendor is touched; the step reports which happened and `executed` is the single field that means one was, so a preview, an approval queue and a missing integration are each named rather than reported as a success. `unimplemented` = no handler is registered; the engine fails the step closed rather than reporting a success it did not achieve. This map is machine-checked against the engine's handler table, so it cannot drift into an aspirational claim.","enrich": "executed","investigate": "executed","notify": "executed",@@ -16,21 +16,21 @@"close_case": "executed","condition": "executed","osquery_live_query": "executed",- "block_ip": "simulated",- "isolate_host": "simulated",- "create_ticket": "simulated",+ "block_ip": "governed",+ "isolate_host": "governed",+ "create_ticket": "governed","approval": "unimplemented",- "block_ioc": "unimplemented",- "disable_user": "unimplemented",- "reset_password": "unimplemented",- "revoke_session": "unimplemented",- "force_mfa": "unimplemented",- "kill_process": "unimplemented",- "quarantine_file": "unimplemented",- "run_av_scan": "unimplemented",- "run_script": "unimplemented",- "search_siem": "unimplemented",- "create_notable_event": "unimplemented"+ "block_ioc": "governed",+ "disable_user": "governed",+ "reset_password": "governed",+ "revoke_session": "governed",+ "force_mfa": "governed",+ "kill_process": "governed",+ "quarantine_file": "governed",+ "run_av_scan": "governed",+ "run_script": "governed",+ "search_siem": "governed",+ "create_notable_event": "governed"},"properties": {diff --git a/scripts/check_playbook_schema_parity.py b/scripts/check_playbook_schema_parity.pyindex b08dbdd42..2944c9b85 100644--- a/scripts/check_playbook_schema_parity.py+++ b/scripts/check_playbook_schema_parity.py@@ -35,6 +35,7 @@ from __future__ import annotationsimport argparseimport inspectimport json+import reimport sysfrom dataclasses import dataclass, field, replacefrom pathlib import Path@@ -48,9 +49,27 @@ from pathlib import PathINERT_AUTHORED_KEYS: frozenset[str] = frozenset({"inputs", "dry_run_support"})#: Execution classes usable in the schema's ``x-aisoc-execution`` map.-_RUNS = frozenset({"executed", "simulated"})+#:+#: ``governed`` means the step is handed to the action registry in+#: ``services/actions``, which grades it against the capability contract and+#: the tenant's autonomy policy before anything reaches a vendor. It is in+#: ``_RUNS`` because a handler exists and makes a real outbound call — what+#: it does *not* claim is that a vendor was necessarily touched, which the+#: step's own ``executed`` field answers per run.+#:+#: ``simulated`` is retained in the vocabulary deliberately. It is the class+#: for a handler that answers from inside the engine without reaching an+#: executor, which is what ``block_ip`` and ``isolate_host`` used to do, and+#: dropping the word would make that state unspellable rather than absent.+_RUNS = frozenset({"executed", "governed", "simulated"})_EXECUTION_CLASSES = _RUNS | {"unimplemented"}+#: Verbs the engine dispatches through the action registry. Compared against+#: ``engine.RESPONSE_STEP_TYPES`` in both directions, because a step marked+#: ``governed`` that the engine answers locally would be the old defect with+#: a new label on it.+_GOVERNED = "governed"+class GateError(RuntimeError):"""The gate could not inspect what it is supposed to inspect.@@ -68,6 +87,11 @@ class Registries:model_step_types: frozenset[str]handler_step_types: frozenset[str]inline_step_types: frozenset[str]+ #: Verbs the engine routes to the action registry rather than answering+ #: locally (``engine.RESPONSE_STEP_TYPES``).+ response_step_types: frozenset[str]+ #: The ``StepType`` union published in ``packages/types``.+ typescript_step_types: frozenset[str]execution: dict[str, str]schema_timeout_max: intschema_timeout_min: int@@ -192,6 +216,37 @@ def _model_playbook_keys(models_mod) -> frozenset[str]:return frozenset(models_mod.Playbook.model_fields.keys())+#: ``| "value"`` members of a TypeScript string-literal union.+_TS_UNION_MEMBER = re.compile(r'^\s*\|\s*"([a-z_]+)"', re.MULTILINE)+++def _typescript_step_types(root: Path) -> frozenset[str]:+ """The ``StepType`` union published in ``packages/types``.++ A fourth vocabulary lived here undetected because nothing imports the+ package: 28 members (``notify_email``, ``create_ticket_jira``,+ ``collect_forensics`` …) matching neither the schema nor the engine. An+ unimported wrong contract is still a wrong contract — it is what the next+ person to import it will build against.++ Parsed rather than transpiled so the gate needs no Node toolchain, which+ is why the union is written one ``| "member"`` per line.+ """+ path = root / "packages" / "types" / "src" / "playbook.ts"+ if not path.is_file():+ raise GateError(f"{path} is missing; the published TypeScript vocabulary cannot be compared")+ text = path.read_text()+ marker = "export type StepType ="+ start = text.find(marker)+ if start == -1:+ raise GateError(f"{path} declares no `export type StepType` union to compare against the engine")+ end = text.find(";", start)+ members = frozenset(_TS_UNION_MEMBER.findall(text[start:end]))+ if not members:+ raise GateError(f"{path} declares a StepType union the gate could not parse; refusing to compare against nothing")+ return members++def _validator_triggers(root: Path) -> frozenset[str]:"""``scripts/validate_playbooks.py`` keeps its own trigger allow-list."""scripts = str(root / "scripts")@@ -229,6 +284,8 @@ def collect(root: Path) -> Registries:model_step_types=frozenset(st.value for st in models_mod.StepType),handler_step_types=frozenset(st.value for st in engine_mod._HANDLERS),inline_step_types=_inline_step_types(engine_mod, models_mod),+ response_step_types=frozenset(st.value for st in engine_mod.RESPONSE_STEP_TYPES),+ typescript_step_types=_typescript_step_types(root),execution=_schema_execution(schema),schema_timeout_max=s_tmax,schema_timeout_min=s_tmin,@@ -295,6 +352,39 @@ def compare(reg: Registries) -> list[str]:f"{reg.execution.get(k, '(absent)')!r} — the schema is understating what the product does.")+ # 2b. the published TypeScript vocabulary <-> StepType, both ways.+ # `packages/types` is what an integrator builds against, and it had+ # drifted into an entirely separate 28-member vocabulary that nothing+ # imported and nothing checked.+ for missing in sorted(reg.model_step_types - reg.typescript_step_types):+ errors.append(+ f"`StepType` implements {missing!r} and `packages/types/src/playbook.ts` does not publish it — "+ f"an integrator typing against the package cannot express a step the engine runs."+ )+ for extra in sorted(reg.typescript_step_types - reg.model_step_types):+ errors.append(+ f"`packages/types/src/playbook.ts` publishes step type {extra!r}, which `StepType` does not implement — "+ f"code that type-checks against the package would be rejected by the server."+ )++ # 3b. `governed` claims <-> the engine's response-verb set, both ways.+ # A step labelled `governed` that the engine answers from inside its+ # own process is the exact defect this label replaced: `block_ip` used+ # to return `{"simulated": true}` and reach no executor. And a verb the+ # engine routes to the registry while the schema calls it something+ # else understates the governance an author is relying on.+ claims_governed = frozenset(k for k, v in reg.execution.items() if v == _GOVERNED)+ for k in sorted(claims_governed - reg.response_step_types):+ errors.append(+ f"`x-aisoc-execution` marks {k!r} governed, but the engine does not route it "+ f"through the action registry — a local answer wearing the label of a dispatched one."+ )+ for k in sorted(reg.response_step_types - claims_governed):+ errors.append(+ f"the engine dispatches {k!r} through the action registry but `x-aisoc-execution` "+ f"marks it {reg.execution.get(k, '(absent)')!r}."+ )+# 4. bounds, both ways (a schema ceiling below the engine's rejects valid# playbooks; above it promises headroom Pydantic will refuse).if reg.schema_timeout_max != reg.engine_timeout_max:@@ -403,6 +493,17 @@ def self_test(reg: Registries) -> list[str]:replace(reg, model_step_types=reg.model_step_types | {absent}),"the schema does not declare it",)+ expect(+ "the published TypeScript union lost a verb the engine runs",+ replace(reg, typescript_step_types=reg.typescript_step_types - {victim}),+ "does not publish it",+ )+ expect(+ # The shape the file was actually in: a vocabulary of its own.+ "the published TypeScript union invented a verb",+ replace(reg, typescript_step_types=reg.typescript_step_types | {"create_ticket_jira"}),+ "which `StepType` does not implement",+ )expect("declared type with no execution annotation",replace(reg, execution={k: v for k, v in reg.execution.items() if k != victim}),@@ -428,6 +529,25 @@ def self_test(reg: Registries) -> list[str]:replace(reg, execution={**reg.execution, running: "unimplemented"}),"understating what the product does",)++ governed_now = sorted(k for k, v in reg.execution.items() if v == _GOVERNED)+ if not governed_now:+ failures.append("self-test: no step type is annotated governed; cannot test the registry directions")+ else:+ dispatched = governed_now[0]+ expect(+ # The precise shape of the bug this label replaced: a verb that+ # says it goes through the action registry and is answered inside+ # the engine instead.+ "annotation claims governed dispatch the engine does not do",+ replace(reg, response_step_types=reg.response_step_types - {dispatched}),+ "a local answer wearing the label of a dispatched one",+ )+ expect(+ "engine dispatches a verb the annotation calls merely executed",+ replace(reg, execution={**reg.execution, dispatched: "executed"}),+ "through the action registry but `x-aisoc-execution`",+ )expect("timeout ceiling drift", replace(reg, schema_timeout_max=reg.engine_timeout_max + 1), "timeout ceiling disagrees")expect("retry ceiling drift", replace(reg, schema_retry_max=reg.engine_retry_max + 1), "retry ceiling disagrees")expect(@@ -473,7 +593,10 @@ def main() -> int:print(f"repo root {root}")print(f"schema {', '.join(reg.schema_files) or '(none)'}")print("engine services/agents/app/playbook/engine.py")- print(f"step types schema {len(reg.schema_step_types)} | StepType {len(reg.model_step_types)} | runnable {len(reg.runnable)}")+ print(+ f"step types schema {len(reg.schema_step_types)} | StepType {len(reg.model_step_types)} "+ f"| runnable {len(reg.runnable)} | packages/types {len(reg.typescript_step_types)}"+ )counts = {c: sum(1 for v in reg.execution.values() if v == c) for c in sorted(_EXECUTION_CLASSES)}print("execution " + " | ".join(f"{k} {v}" for k, v in counts.items()))print(f"bounds timeout {reg.schema_timeout_min}..{reg.schema_timeout_max}s | retries <={reg.schema_retry_max}")diff --git a/scripts/upgrade_playbooks.py b/scripts/upgrade_playbooks.pynew file mode 100644index 000000000..7e7fdc570--- /dev/null+++ b/scripts/upgrade_playbooks.py@@ -0,0 +1,278 @@+#!/usr/bin/env python3+"""Upgrade pre-v4 playbook JSON to the schema the engine actually accepts.++``docs/upgrade/MIGRATION.md`` has told operators to run this script since v4.+It did not exist, so the one command in the upgrade path that touches their+own content failed at exactly the moment they needed it — and the table of+field renames beside it named four spellings the schema rejects, so following+the doc by hand produced playbooks that would not validate either.++Design, in the order the decisions matter+------------------------------------------+**It reports before it writes.** The default is ``--check``: nothing on disk+changes and the exit code says whether anything would. A migration tool whose+first act is to rewrite a customer's content is one people run once and then+never trust.++**It validates its own output.** Every upgraded playbook is checked against+``schemas/playbook.schema.json`` before it is written, and a file whose+upgrade does not validate is left alone and reported. An upgrader that+produces invalid output is worse than no upgrader, because the failure+arrives later and somewhere else.++**It refuses rather than invents.** Four v3 step types — ``loop``,+``parallel``, ``wait`` and ``run_playbook`` — name control flow this engine+does not have. There is no correct rewrite, so those files are reported and+skipped. Mapping them onto a "nearest neighbour" is precisely the defect that+was removed from the NL drafter, where a ``disable_user`` step shipped as+``investigate``.+"""++from __future__ import annotations++import argparse+import copy+import json+import sys+from pathlib import Path+from typing import Any++try:+ import jsonschema+except ModuleNotFoundError: # pragma: no cover - the CI job installs it+ jsonschema = None # type: ignore[assignment]+++#: v3 step types that are a different spelling of a verb the engine runs.+#: Each is a synonym, not an approximation — ``isolate`` and ``isolate_host``+#: are the same action, so the rewrite loses nothing.+STEP_TYPE_RENAMES: dict[str, str] = {+ "isolate": "isolate_host",+ "block": "block_ip",+ "create_case": "create_ticket",+ "script": "run_script",+ "human_approval": "approval",+}++#: v3 step types with no v4 equivalent, and why. Reported, never rewritten.+UNMAPPABLE: dict[str, str] = {+ "loop": "the engine is a single-threaded index walk with no iteration construct",+ "parallel": "the engine runs one step at a time; there is no fan-out",+ "wait": "the engine has no timer and no pause",+ "run_playbook": (+ "nested playbooks are deliberately not implemented: a nested playbook's steps are "+ "not visible where the parent declares its policy, so the parent cannot bound them"+ ),+ "action": (+ "'action' was a meta-type. Replace it with the specific verb the step performs "+ "(block_ip, isolate_host, disable_user, ...), because the contract belongs to the verb"+ ),+ "trigger": "a trigger is playbook-level (the top-level `trigger` object), never a step",+}++#: Step types the engine accepts but cannot run. Upgrading *to* one is valid+#: and the file will validate, so this is a warning rather than a refusal.+STILL_FAILS_CLOSED: dict[str, str] = {+ "approval": (+ "the engine has no pause, so an `approval` step fails closed. Response steps are now "+ "graded individually at dispatch and return `pending_approval` on their own, so the "+ "gate is usually redundant — see apps/docs/docs/concepts/playbooks.md"+ ),+}++_ON_FAILURE = {"stop": "abort", "abort": "abort", "continue": "continue", "retry": "retry"}+++class Finding:+ """One thing that happened to one file."""++ def __init__(self, path: Path, kind: str, message: str) -> None:+ self.path = path+ self.kind = kind # "changed" | "blocked" | "warning" | "invalid"+ self.message = message++ def __str__(self) -> str:+ return f"{self.kind.upper():8} {self.path}: {self.message}"+++def _upgrade_condition(value: Any) -> Any:+ """v3 wrapped the expression in ``{expr, language}``; v4 takes the string.++ The engine's own parser is deliberately restricted — no JMESPath, no+ compound boolean chains — so a v3 condition naming a language is carried+ across as its expression text and flagged if it looks like JMESPath.+ """+ if isinstance(value, dict) and "expr" in value:+ return str(value["expr"])+ return value+++def _upgrade_retry(step: dict[str, Any]) -> None:+ """``retry: {max_attempts, backoff}`` became the scalar ``retry_max``.++ Backoff is not configurable: the engine uses ``min(2**attempt, 30)``. A+ declared backoff strategy is dropped rather than translated into a field+ nothing reads, which is what the removed root schema did.+ """+ retry = step.pop("retry", None)+ if isinstance(retry, dict):+ attempts = retry.get("max_attempts", retry.get("max"))+ if isinstance(attempts, int):+ step["retry_max"] = attempts+ elif isinstance(retry, int):+ step["retry_max"] = retry+++def upgrade_playbook(doc: dict[str, Any]) -> tuple[dict[str, Any], list[str], list[str]]:+ """Return ``(upgraded, changes, blockers)``. Never mutates ``doc``."""+ out = copy.deepcopy(doc)+ changes: list[str] = []+ blockers: list[str] = []++ for key in ("blast_radius", "depends_on", "output_key"):+ if key in out:+ out.pop(key)+ changes.append(f"dropped playbook key '{key}' (never read by the engine)")++ for index, step in enumerate(out.get("steps") or []):+ if not isinstance(step, dict):+ continue+ where = f"step {index}"++ raw_type = step.get("type")+ if raw_type in UNMAPPABLE:+ blockers.append(f"{where}: type '{raw_type}' has no v4 equivalent — {UNMAPPABLE[raw_type]}")+ elif raw_type in STEP_TYPE_RENAMES:+ step["type"] = STEP_TYPE_RENAMES[raw_type]+ changes.append(f"{where}: type '{raw_type}' -> '{step['type']}'")++ if "on_error" in step:+ policy = step.pop("on_error")+ step["on_failure"] = _ON_FAILURE.get(str(policy), "abort")+ changes.append(f"{where}: on_error '{policy}' -> on_failure '{step['on_failure']}'")+ elif isinstance(step.get("on_failure"), dict):+ # v3.x briefly wrapped it: ``on_failure: {policy: "abort"}``.+ policy = step["on_failure"].get("policy", "abort")+ step["on_failure"] = _ON_FAILURE.get(str(policy), "abort")+ changes.append(f"{where}: on_failure object -> '{step['on_failure']}'")++ if "timeout" in step:+ step["timeout_seconds"] = step.pop("timeout")+ changes.append(f"{where}: timeout -> timeout_seconds")++ if "retry" in step:+ _upgrade_retry(step)+ changes.append(f"{where}: retry object -> retry_max")++ if "condition" in step:+ upgraded = _upgrade_condition(step["condition"])+ if upgraded is not step["condition"]:+ step["condition"] = upgraded+ changes.append(f"{where}: condition object -> expression string")++ for dead in ("blast_radius", "depends_on", "output_key"):+ if dead in step:+ step.pop(dead)+ changes.append(f"{where}: dropped '{dead}' (never read by the engine)")++ return out, changes, blockers+++def _load_schema(root: Path) -> Any:+ path = root / "schemas" / "playbook.schema.json"+ if not path.is_file():+ raise SystemExit(f"upgrade_playbooks: cannot find {path}; run this from inside the repository")+ return json.loads(path.read_text())+++def _validate(schema: Any, doc: dict[str, Any]) -> list[str]:+ if jsonschema is None:+ return ["jsonschema is not installed, so the upgraded playbook could not be checked — install it before writing"]+ validator = jsonschema.Draft7Validator(schema)+ errors = sorted(validator.iter_errors(doc), key=lambda e: list(e.path))+ return [f"{'.'.join(str(p) for p in e.path) or '(root)'}: {e.message}" for e in errors]+++def _targets(root: Path, directory: str | None) -> list[Path]:+ base = (root / directory).resolve() if directory else root+ if not base.is_dir():+ raise SystemExit(f"upgrade_playbooks: {base} is not a directory")+ return sorted(p for p in base.rglob("*.playbook.json") if "node_modules" not in p.parts and ".git" not in p.parts)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Upgrade pre-v4 playbook JSON to the current schema.")+ parser.add_argument("--dir", default="playbooks", help="directory to scan, relative to the repo root (default: playbooks)")+ parser.add_argument("--write", action="store_true", help="write the upgraded files. Without this nothing on disk changes.")+ parser.add_argument("--repo-root", default=None)+ args = parser.parse_args(argv)++ root = Path(args.repo_root).resolve() if args.repo_root else Path(__file__).resolve().parent.parent+ schema = _load_schema(root)+ files = _targets(root, args.dir)++ print(f"upgrade_playbooks: repo root {root}")+ print(f"upgrade_playbooks: scanning {root / args.dir} — {len(files)} playbook file(s)")+ if not files:+ # An empty scan is a broken scan, not a clean bill of health: the same+ # defect that let the lint job report "2/2 passed" over 62 unchecked+ # packs.+ print("upgrade_playbooks: found no *.playbook.json files. Check --dir; this is not a pass.")+ return 1++ findings: list[Finding] = []+ for path in files:+ try:+ doc = json.loads(path.read_text())+ except json.JSONDecodeError as exc:+ findings.append(Finding(path, "invalid", f"JSON parse error: {exc}"))+ continue++ upgraded, changes, blockers = upgrade_playbook(doc)+ for blocker in blockers:+ findings.append(Finding(path, "blocked", blocker))+ if blockers:+ continue+ if not changes:+ continue++ errors = _validate(schema, upgraded)+ if errors:+ findings.append(Finding(path, "invalid", f"upgrade would not validate ({errors[0]}); left unchanged"))+ continue++ for step in upgraded.get("steps") or []:+ note = STILL_FAILS_CLOSED.get(step.get("type") if isinstance(step, dict) else None)+ if note:+ findings.append(Finding(path, "warning", f"step type '{step['type']}' is accepted and still fails closed — {note}"))++ findings.append(Finding(path, "changed", "; ".join(changes)))+ if args.write:+ path.write_text(json.dumps(upgraded, indent=2) + "\n")++ for finding in findings:+ print(f" {finding}")++ changed = sum(1 for f in findings if f.kind == "changed")+ blocked = sum(1 for f in findings if f.kind == "blocked")+ invalid = sum(1 for f in findings if f.kind == "invalid")++ print()+ if args.write:+ print(f"upgrade_playbooks: rewrote {changed} file(s); {blocked} blocked, {invalid} could not be upgraded.")+ else:+ print(f"upgrade_playbooks: {changed} file(s) would change; {blocked} blocked, {invalid} could not be upgraded.")+ print("upgrade_playbooks: nothing was written. Re-run with --write once the report looks right.")++ # Blocked and invalid are real problems that need a person. "Would change"+ # is not a failure in check mode, but it is a non-zero answer so a script+ # can branch on it.+ if blocked or invalid:+ return 2+ if changed and not args.write:+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.pyindex eba932bd4..b7e6e3d06 100644--- a/services/actions/app/live_actions/dispatcher.py+++ b/services/actions/app/live_actions/dispatcher.py@@ -31,26 +31,32 @@ so individual executors never have to think about them:from __future__ import annotationsimport os+from dataclasses import replacefrom typing import Anyfrom uuid import uuid4import structlogfrom app.models.action import ActionRequest, ActionType+from app.services.approval_matrix import evaluate as evaluate_matrixfrom app.services.autonomy_safety import (+ _BLAST_ORDER,ACTION_BLAST_RADIUS,AutonomyDecision,AutonomyMode,BlastRadius,+ RollbackCapability,decide,rollback_capability,)from app.services.credential_resolver import resolve_params-from app.services.maturity import MaturityTier+from app.services.maturity import _AUTO_ALLOWED_AT_TIER, MaturityTierfrom app.services.tenant_policy import TenantPolicy, resolve_tenant_policyfrom app.services.verification import PostActionVerifier, VerificationOutcomefrom . import registry+from .capability_contracts import CAPABILITY_CONTRACTS+from .contract import ActionImpact, ApprovalRequirement, Reversalfrom .models import LiveActionRequest, LiveActionResult, LiveActionStatuslogger = structlog.get_logger(__name__)@@ -120,19 +126,176 @@ async def _govern(request: LiveActionRequest, action_type: ActionType) -> Autonof"action type '{action_type.value}' is blocked by tenant policy",)if override.get("force_auto"):- return _override_decision(- action_type,- policy,- AutonomyMode.AUTO,- f"action type '{action_type.value}' is force-auto by tenant policy",+ # The override lifts the *tier ceiling* — that is what it is for — so+ # the contract is graded as though the tenant were at L4. It does not+ # lift the contract's own floors: a verb declared `analyst` or+ # `mandatory_human`, or one whose impact is never autonomous, stays+ # gated. `ActionContract.approval` says the tenant's autonomy policy+ # "can raise this but never lower it", and before the contract was+ # consulted on this path an override could lower it silently.+ return _apply_capability_contract(+ request,+ _override_decision(+ action_type,+ policy,+ AutonomyMode.AUTO,+ f"action type '{action_type.value}' is force-auto by tenant policy",+ ),+ tier_label="L4",)- return decide(- action_request,+ return _apply_capability_contract(+ request,+ decide(+ action_request,+ tier=policy.tier,+ whitelisted=policy.is_whitelisted(action_type.value, request.target),+ ),+ tier_label=_tier_label(policy.tier),+ )+++def _tier_label(tier: object) -> str:+ """Map a ``MaturityTier`` onto the ``L0``..``L4`` labels the matrix uses."""+ name = getattr(tier, "name", None)+ if isinstance(name, str) and name.startswith("L"):+ return name.split("_")[0]+ return "L1"+++#: Blast radius implied by a capability's declared impact, for the verbs that+#: have a contract and no ``ActionType``. ``ACTION_BLAST_RADIUS`` is keyed on+#: ``ActionType``, so those verbs resolved to nothing and skipped governance+#: altogether — ``revoke_session`` is MODERATE-impact identity disruption and+#: was executing with no tier check, no blast check and no contract applied.+#: The mapping is the conservative reading of the same two ladders.+_IMPACT_BLAST: dict[ActionImpact, BlastRadius] = {+ ActionImpact.READ_ONLY: BlastRadius.MINIMAL,+ ActionImpact.LOW: BlastRadius.LOW,+ ActionImpact.MODERATE: BlastRadius.MEDIUM,+ ActionImpact.HIGH: BlastRadius.HIGH,+ ActionImpact.SEVERE: BlastRadius.CRITICAL,+ ActionImpact.IRREVERSIBLE: BlastRadius.CRITICAL,+}+++async def _govern_by_contract_alone(request: LiveActionRequest) -> AutonomyDecision:+ """Baseline verdict for a capability with a contract and no ``ActionType``.++ Built from the tenant's tier and the contract's own impact so that+ :func:`_apply_capability_contract` has something to raise. Without this a+ contracted verb outside the legacy enum reached its executor with no+ governance at all, which is the worst of both vocabularies: declared+ dangerous and dispatched unchecked.+ """+ contract = CAPABILITY_CONTRACTS[request.capability]+ blast = _IMPACT_BLAST[contract.impact]+ policy = await resolve_tenant_policy(request.tenant_id)+ allowed = _AUTO_ALLOWED_AT_TIER.get(policy.tier, set())+ mode = AutonomyMode.AUTO if blast in allowed else AutonomyMode.QUEUED_APPROVAL+ baseline = AutonomyDecision(+ mode=mode,+ blast_radius=blast,tier=policy.tier,- whitelisted=policy.is_whitelisted(action_type.value, request.target),+ rollback=(RollbackCapability.REVERSIBLE if contract.reversal is Reversal.PLATFORM else RollbackCapability.UNSUPPORTED),+ requires_verification=(mode is AutonomyMode.AUTO and _BLAST_ORDER[blast] >= _BLAST_ORDER[BlastRadius.MEDIUM]),+ reason=(+ f"capability '{request.capability}' has no legacy ActionType; graded from its "+ f"contract ({contract.impact.value} impact) under tier {policy.tier.name}"+ ),+ )+ return _apply_capability_contract(request, baseline, tier_label=_tier_label(policy.tier))+++def _apply_capability_contract(+ request: LiveActionRequest,+ decision: AutonomyDecision,+ *,+ tier_label: str,+) -> AutonomyDecision:+ """Raise the autonomy verdict to whatever the capability contract demands.++ ``decide()`` answers one question — is this verb's *blast radius* inside+ the tenant's tier. The capability contract answers the other two, and this+ dispatcher never asked them: what the verb does to an estate when the+ finding is wrong (``impact``), and whether the reason is good enough+ (``confidence``). ``approval_matrix.evaluate`` combines them and has been+ wired into ``POST /actions`` since the approval gate was fixed; the+ registry-driven path next to it still decided on blast radius alone, so+ the same verb was graded differently depending on which door it came+ through.++ Composition rule is the matrix's own: each input may raise a requirement+ and none may lower it. This function therefore never turns a QUEUED or+ BLOCKED verdict into an AUTO one — it can only move in the safe direction,+ which is why switching it on cannot make anything execute that did not+ before.++ A capability with no contract is left to blast radius and recorded at+ debug, not guessed at. ``scripts/check_action_contract.py`` fails the+ build when a registered executor has none, so this is a real absence+ rather than a silent default.+ """+ contract = CAPABILITY_CONTRACTS.get(request.capability)+ if contract is None:+ logger.debug(+ "live_action.no_capability_contract",+ capability=request.capability,+ note="blast radius decides alone; impact is unknown for this verb",+ )+ return decision++ if contract.impact is ActionImpact.READ_ONLY and contract.approval is ApprovalRequirement.AUTOMATIC:+ # A read has nothing to raise. `capability_contracts` calls the read+ # verbs "automatic by construction ... gating a read behind an analyst+ # is how an agent learns to conclude without looking", and+ # `approval_matrix`'s own docstring names an enrichment stuck in an+ # approval queue as a failure mode it exists to prevent — yet its tier+ # ceiling returns ANALYST for every impact at L0 and L1, which is the+ # default tier. Rather than overturn `TIER_MAX_AUTOMATIC`, which is a+ # deliberate posture for state-changing impact and is tested as one,+ # the read case keeps whatever blast radius decided. That still blocks+ # at L0, where nothing executes at all.+ return decision++ verdict = evaluate_matrix(+ impact=contract.impact,+ declared_approval=contract.approval,+ confidence=request.confidence,+ tier=tier_label,)+ if verdict.is_blocked:+ return replace(+ decision,+ mode=AutonomyMode.BLOCKED,+ reason=verdict.reason,+ requires_verification=False,+ )++ if verdict.requirement == ApprovalRequirement.AUTOMATIC:+ # The matrix is content. Whatever blast radius decided stands.+ return decision++ if decision.mode is AutonomyMode.AUTO:+ # The only direction this function moves: an action the tier would+ # have auto-executed, held because impact and confidence say so.+ # Verification goes with it — nothing ran, so there is no effect to+ # read back.+ return replace(+ decision,+ mode=AutonomyMode.QUEUED_APPROVAL,+ reason=verdict.reason,+ requires_verification=False,+ )++ if decision.mode is AutonomyMode.QUEUED_APPROVAL:+ # Already gated. Keep the matrix's reason, which names impact and+ # confidence — more use to an approver than "blast radius exceeded".+ return replace(decision, reason=verdict.reason)++ return decision+def _override_decision(action_type: ActionType,@@ -268,8 +431,8 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:# possible — so governance applies to would-be real executions only.decision: AutonomyDecision | None = Noneaction_type = _action_type_for(request, executor)- if action_type is not None and not request.dry_run:- decision = await _govern(request, action_type)+ if not request.dry_run and (action_type is not None or request.capability in CAPABILITY_CONTRACTS):+ decision = await (_govern(request, action_type) if action_type is not None else _govern_by_contract_alone(request))log = log.bind(autonomy_mode=decision.mode.value, blast=decision.blast_radius.value)if decision.mode is AutonomyMode.BLOCKED:log.warning("live_action.blocked_by_policy", reason=decision.reason)@@ -330,14 +493,19 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:# Verification runs only for a real execution that actually succeeded. A# dry run and a SIMULATED result have nothing to verify, and a failed# execution is already an honest negative.- if (- decision is not None- and decision.requires_verification- and not request.dry_run- and result.status is LiveActionStatus.SUCCEEDED- and action_type is not None- ):- result = await _verify_effect(request, result, action_type, log)+ if decision is not None and decision.requires_verification and not request.dry_run and result.status is LiveActionStatus.SUCCEEDED:+ if action_type is not None:+ result = await _verify_effect(request, result, action_type, log)+ else:+ # Probes are keyed on ActionType, so a contracted verb outside the+ # legacy enum has none. Say so rather than leaving the field blank:+ # an absent `verification` key and a verified one are indis-+ # tinguishable to a reader, and the honest answer here is that+ # nothing checked.+ details = dict(result.details)+ details["verification"] = "unverified"+ details["verification_reason"] = f"no probe is registered for '{request.capability}'; it has no ActionType to key one on"+ result = result.model_copy(update={"details": details})log.info("live_action.completed",diff --git a/services/actions/app/live_actions/models.py b/services/actions/app/live_actions/models.pyindex 018043ae0..c5dc7734e 100644--- a/services/actions/app/live_actions/models.py+++ b/services/actions/app/live_actions/models.py@@ -121,6 +121,15 @@ class LiveActionRequest(BaseModel):auth_config: dict[str, Any] | None = Nonedry_run: bool = False+ #: How sure the caller is that the finding justifying this action is real,+ #: 0..1. The capability contract says what the verb does to an estate; this+ #: says how good the reason is. ``approval_matrix`` needs both.+ #:+ #: ``None`` is not "no opinion", it is the lowest band — the matrix treats+ #: it that way on purpose, because defaulting permissive turns a scoring+ #: bug into an autonomous containment.+ confidence: float | None = Field(default=None, ge=0.0, le=1.0)+# Provenance — these are filled in by the API layer / agent runner so# the executor's structured logs can be correlated back to the case or# playbook that triggered it. They are optional because plugin authors@@ -128,6 +137,10 @@ class LiveActionRequest(BaseModel):# synthetic UUIDs.case_id: UUID | None = Noneplaybook_run_id: UUID | None = None+ #: The step that asked for this, when the caller is a playbook. Carried so+ #: the audit trail names the step rather than only the run: a playbook can+ #: contain several actions and "run X did something" is not an audit trail.+ playbook_step_id: str = ""tenant_id: UUID | None = Nonerequested_by: str = "system"diff --git a/services/actions/app/models/action.py b/services/actions/app/models/action.pyindex 0fbf48b3c..17dcf9647 100644--- a/services/actions/app/models/action.py+++ b/services/actions/app/models/action.py@@ -42,7 +42,19 @@ class ActionType(str, Enum):# 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.+ # is graded on the way past — via+ # `services/agents/app/playbook/action_bridge.py`+ # and `POST /api/v1/playbook-steps/dispatch`.+ #+ # That last sentence was not true when it was+ # written. `_handle_block_ip` and+ # `_handle_isolate_host` returned+ # `{"simulated": True}` from inside the engine and+ # reached no executor, and twelve further step+ # types had no handler at all. The bridge named+ # above is what made it true; the named modules+ # are here so the claim can be checked rather than+ # taken on trust.# 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.diff --git a/services/actions/tests/test_dispatch_capability_contract.py b/services/actions/tests/test_dispatch_capability_contract.pynew file mode 100644index 000000000..5c690b61b--- /dev/null+++ b/services/actions/tests/test_dispatch_capability_contract.py@@ -0,0 +1,206 @@+"""The capability contract must be consulted on the registry-driven path too.++`POST /actions` has run the contract through `approval_gate.apply_matrix`+since the approval gate was fixed. `live_actions.dispatch()` — the path the+agent loop, the console dry-run and now the playbook engine use — ran+`autonomy_safety.decide()` and nothing else. `decide()` reads+`ACTION_BLAST_RADIUS`, a second risk ladder keyed on `ActionType`, and for+nine verbs it is the *weaker* of the two declarations:++ block_ip blast medium vs impact high+ block_domain blast medium vs impact high+ reset_password blast medium vs impact high+ run_script blast high vs impact severe+ quarantine_file blast low vs impact moderate+ ...++So the same verb was graded differently depending on which door it came+through, and the weaker grade belonged to the door an agent uses.++Two further holes these tests pin:++* a capability with a contract and no `ActionType` (`revoke_session`) reached+ its executor with *no* governance at all — `_action_type_for` returned None+ and the whole gate was skipped;+* a tenant `force_auto` override lowered a contract that declares `analyst`,+ which `ActionContract.approval` explicitly forbids ("can raise this but+ never lower it").++Every test here fails against the tree before this change.+"""++from __future__ import annotations++import uuid++import pytest+from app.live_actions import dispatcher as dispatcher_mod+from app.live_actions import registry+from app.live_actions.dispatcher import dispatch+from app.live_actions.models import LiveActionRequest, LiveActionResult, LiveActionStatus+from app.models.action import ActionType+from app.services.maturity import MaturityTier+from app.services.tenant_policy import TenantPolicy++pytestmark = pytest.mark.asyncio+++class _OkExecutor:+ """Reports success without touching a vendor.++ `_legacy_action_type` is set to None for the capabilities that genuinely+ have none, so the test exercises the same lookup production does.+ """++ def __init__(self, action_type: ActionType | None = None) -> None:+ if action_type is not None:+ self._legacy_action_type = action_type++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary="executed",+ )+++def _request(capability: str, **overrides) -> LiveActionRequest:+ payload: dict = {+ "capability": capability,+ "vendor_id": "crowdstrike",+ "target": "WIN-DC01",+ "dry_run": False,+ "tenant_id": uuid.uuid4(),+ "requested_by": "[email protected]",+ }+ payload.update(overrides)+ return LiveActionRequest(**payload)+++def _policy(monkeypatch: pytest.MonkeyPatch, policy: TenantPolicy) -> None:+ async def _resolve(tenant_id): # noqa: ANN001, ANN202+ return policy++ monkeypatch.setattr(dispatcher_mod, "resolve_tenant_policy", _resolve)+++def _executor(monkeypatch: pytest.MonkeyPatch, action_type: ActionType | None) -> None:+ monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: _OkExecutor(action_type))++[email protected](autouse=True)+def _no_probe(monkeypatch: pytest.MonkeyPatch):+ """A stub verifier so these assertions are about the verdict only."""++ class _V:+ async def verify(self, action_type, target, params): # noqa: ANN001+ from app.services.verification import VerificationOutcome, VerificationResult++ return VerificationResult(VerificationOutcome.UNVERIFIED, action_type, target, reason="stub")++ monkeypatch.setattr(dispatcher_mod, "PostActionVerifier", _V)+++async def test_a_verb_the_blast_table_calls_medium_is_held_at_its_declared_high_impact(+ monkeypatch: pytest.MonkeyPatch,+):+ """`block_ip`: blast medium, impact high. L3 allows medium and not high.++ Pre-change this executed, because only the weaker ladder was read.+ """+ _executor(monkeypatch, ActionType.BLOCK_IP)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L3_REMEDIATE, from_store=True))+ result = await dispatch(_request("block_ip", confidence=1.0))+ assert result.status is LiveActionStatus.PENDING_APPROVAL+ assert "high" in result.summary+++async def test_missing_confidence_is_the_lowest_band_not_a_free_pass(+ monkeypatch: pytest.MonkeyPatch,+):+ """A LOW-impact automatic verb still needs a reason above the floor."""+ _executor(monkeypatch, ActionType.CREATE_NOTABLE_EVENT)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L4_AUTOMATE, from_store=True))++ held = await dispatch(_request("create_notable_event"))+ assert held.status is LiveActionStatus.PENDING_APPROVAL+ assert "below the 90% floor" in held.summary++ ran = await dispatch(_request("create_notable_event", confidence=0.95))+ assert ran.status is LiveActionStatus.SUCCEEDED+++async def test_a_read_only_verb_is_not_gated_by_the_contract(+ monkeypatch: pytest.MonkeyPatch,+):+ """Gating a read behind an analyst is how an agent learns to conclude+ without looking. `search_siem` is read_only/automatic and must run."""+ _executor(monkeypatch, ActionType.SEARCH_SIEM)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L1_NOTIFY, from_store=True))+ result = await dispatch(_request("search_siem"))+ assert result.status is LiveActionStatus.SUCCEEDED+++async def test_a_severe_verb_is_never_autonomous_at_any_tier_or_confidence(+ monkeypatch: pytest.MonkeyPatch,+):+ """`run_script` declares severe impact and mandatory_human approval."""+ _executor(monkeypatch, ActionType.RUN_SCRIPT)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L4_AUTOMATE, from_store=True))+ result = await dispatch(_request("run_script", confidence=1.0))+ assert result.status is LiveActionStatus.PENDING_APPROVAL+++async def test_a_contracted_verb_with_no_action_type_is_still_governed(+ monkeypatch: pytest.MonkeyPatch,+):+ """`revoke_session` has a contract and no `ActionType`.++ `_action_type_for` returned None, so the entire governance block was+ skipped and a MODERATE-impact identity action reached its executor with+ no tier check, no blast check and no contract applied.+ """+ _executor(monkeypatch, None)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L1_NOTIFY, from_store=True))+ result = await dispatch(_request("revoke_session"))+ assert result.status is LiveActionStatus.PENDING_APPROVAL+ assert result.details["autonomy_mode"] == "queued_approval"+++async def test_an_uncontracted_capability_is_left_to_blast_radius(+ monkeypatch: pytest.MonkeyPatch,+):+ """A verb nobody declared is recorded, not guessed at.++ Inventing an impact for it is how a gate starts certifying things it+ never examined. `check_action_contract.py` fails the build when a+ *registered* executor has no contract, so this stays a real absence.+ """+ _executor(monkeypatch, None)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L1_NOTIFY, from_store=True))+ result = await dispatch(_request("a_verb_nobody_declared"))+ assert result.status is LiveActionStatus.SUCCEEDED+ assert "autonomy_mode" not in result.details+++async def test_the_contract_never_lowers_a_verdict_blast_radius_already_gated(+ monkeypatch: pytest.MonkeyPatch,+):+ """`search_siem` is automatic, but L0 observes. The contract must not lift it."""+ _executor(monkeypatch, ActionType.SEARCH_SIEM)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L0_OBSERVE, from_store=True))+ result = await dispatch(_request("search_siem"))+ assert result.status is LiveActionStatus.BLOCKED+++async def test_a_dry_run_is_not_graded(monkeypatch: pytest.MonkeyPatch):+ """Nothing reaches a vendor, so there is nothing to hold for an analyst.++ A dry run that queued for approval would make preview useless.+ """+ _executor(monkeypatch, ActionType.ISOLATE_HOST)+ _policy(monkeypatch, TenantPolicy(tier=MaturityTier.L1_NOTIFY, from_store=True))+ result = await dispatch(_request("isolate_host", dry_run=True))+ assert result.status is LiveActionStatus.SUCCEEDEDdiff --git a/services/actions/tests/test_dispatch_tenant_governance.py b/services/actions/tests/test_dispatch_tenant_governance.pyindex 810f52014..887164080 100644--- a/services/actions/tests/test_dispatch_tenant_governance.py+++ b/services/actions/tests/test_dispatch_tenant_governance.py@@ -23,7 +23,8 @@ pytestmark = pytest.mark.asyncioclass _OkExecutor:- _legacy_action_type = ActionType.ISOLATE_HOST+ def __init__(self, action_type: ActionType = ActionType.ISOLATE_HOST) -> None:+ self._legacy_action_type = action_typeasync def execute(self, request: LiveActionRequest) -> LiveActionResult:return LiveActionResult(@@ -102,23 +103,53 @@ async def test_force_auto_override_still_requires_verification():"""Skipping the approval queue is not the same as skipping the proof.- A tenant who force-autos host isolation has chosen to act without a human- in the loop, which makes read-back confirmation more important, not less.+ A tenant who force-autos a verb has chosen to act without a human in the+ loop, which makes read-back confirmation more important, not less.++ Uses `create_notable_event` because the override has to land on a verb the+ capability contract actually permits to run automatically — see+ `test_force_auto_cannot_lower_a_contract_that_demands_an_analyst`."""+ monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: _OkExecutor(ActionType.CREATE_NOTABLE_EVENT))_policy(monkeypatch,TenantPolicy(tier=MaturityTier.L2_CONTAIN,- action_overrides={"isolate_host": {"force_auto": True}},+ action_overrides={"create_notable_event": {"force_auto": True}},from_store=True,source="tenant_policy",),)- result = await dispatch(_request())+ result = await dispatch(_request(capability="create_notable_event", confidence=0.95))assert result.status is LiveActionStatus.SUCCEEDEDassert result.details["verification"] == "unverified"+async def test_force_auto_cannot_lower_a_contract_that_demands_an_analyst(+ monkeypatch: pytest.MonkeyPatch,+):+ """A tenant override outranks the tier ladder. It does not outrank the contract.++ `ActionContract.approval` says the tenant's autonomy policy "can raise+ this but never lower it", and `isolate_host` declares `analyst`. On this+ path the override was reaching AUTO anyway, because the capability+ contract was never consulted here at all — only the blast-radius table+ was, and it is the weaker of the two declarations for nine verbs.+ """+ _policy(+ monkeypatch,+ TenantPolicy(+ tier=MaturityTier.L4_AUTOMATE,+ action_overrides={"isolate_host": {"force_auto": True}},+ from_store=True,+ source="tenant_policy",+ ),+ )+ result = await dispatch(_request(confidence=1.0))+ assert result.status is LiveActionStatus.PENDING_APPROVAL+ assert "analyst approval" in result.summary++async def test_whitelist_is_passed_through_to_the_autonomy_decision(monkeypatch: pytest.MonkeyPatch,):@@ -156,14 +187,15 @@ async def test_the_policy_source_is_recorded_for_the_audit_trail(monkeypatch: pytest.MonkeyPatch,):"""An operator must be able to tell a tenant choice from a default."""+ monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: _OkExecutor(ActionType.CREATE_NOTABLE_EVENT))_policy(monkeypatch,TenantPolicy(tier=MaturityTier.L4_AUTOMATE,- action_overrides={"isolate_host": {"force_auto": True}},+ action_overrides={"create_notable_event": {"force_auto": True}},from_store=True,source="tenant_policy",),)- result = await dispatch(_request())+ result = await dispatch(_request(capability="create_notable_event", confidence=0.95))assert "tenant_policy" in result.details["autonomy_reason"]diff --git a/services/actions/tests/test_dispatch_verification.py b/services/actions/tests/test_dispatch_verification.pyindex 61a5d6fa6..178ce58f5 100644--- a/services/actions/tests/test_dispatch_verification.py+++ b/services/actions/tests/test_dispatch_verification.py@@ -88,7 +88,16 @@ def _request(**overrides) -> LiveActionRequest:@pytest.fixture(autouse=True)def _wire(monkeypatch: pytest.MonkeyPatch):- """Executor always succeeds; autonomy always demands verification."""+ """Executor always succeeds; autonomy always demands verification.++ Stubbing `_govern` replaces the whole verdict, capability contract+ included — deliberately, because `isolate_host` declares+ `approval: analyst`, which the matrix never lifts at any tier or+ confidence. With the real verdict in the path nothing here would reach an+ executor and these tests would quietly stop testing verification. What the+ contract layer does has its own tests in+ `test_dispatch_capability_contract.py`.+ """monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: _OkExecutor())monkeypatch.setattr(dispatcher_mod,diff --git a/services/agents/app/playbook/action_bridge.py b/services/agents/app/playbook/action_bridge.pynew file mode 100644index 000000000..1f45134a9--- /dev/null+++ b/services/agents/app/playbook/action_bridge.py@@ -0,0 +1,156 @@+"""Ask the API to run one playbook step as a governed action.++The engine does not dispatch. This module is one authenticated POST, a+structured log line, and no policy — deliberately, because the API holds the+credential vault and the tenant session, and ``services/actions`` owns the+per-capability contract that decides whether a verb may run at all. A second+opinion here would be a second place that can isolate a customer's host.++Fail closed, not fail soft+--------------------------+``siem_writeback`` next door fails *soft*: the verdict is already durable by+the time it runs and a Splunk outage must not undo it. This is the opposite+case. A step that says it blocked an address and did not must never be+recorded as a success, so every failure path here returns a report with+``executed: false`` and the engine fails the step. The default+``on_failure: abort`` then halts the run, which is the behaviour an operator+reading "block the C2 address" expects when it did not happen.++Preview by default+------------------+``AISOC_PLAYBOOK_ACTIONS_EXECUTE`` is **off** unless an operator turns it on,+so a playbook previews its response steps and reports them as previews. The+switch is read here *and* honoured downstream by the same+``dry_run``-defaults-true rule in ``actions_client``, so neither end can turn+it on alone.+"""++from __future__ import annotations++import logging+import os+from typing import Any++import httpx++#: Stdlib logging rather than structlog, matching `engine.py`. The playbook+#: package states "zero external dependencies beyond httpx + stdlib" in its+#: own docstring and it is load-bearing: `scripts/validate_playbooks.py` and+#: the schema-parity gate import the package with only jsonschema, pydantic+#: and httpx installed, so a structlog import here fails the pack validator+#: rather than the module that added it.+logger = logging.getLogger("aisoc.playbook.action_bridge")++_API_URL = os.getenv("API_SERVICE_URL", os.getenv("API_URL", "http://api:8000"))+_TIMEOUT_S = float(os.getenv("AISOC_PLAYBOOK_ACTION_TIMEOUT_S", "45"))+++def actions_enabled() -> bool:+ """Whether playbook steps may reach the action registry at all.++ On by default: reaching governed dispatch is not the same as executing.+ A disabled bridge means the step fails closed rather than previewing,+ because "we did not even ask" is a different fact from "we asked and it+ was held".+ """+ return os.getenv("AISOC_PLAYBOOK_ACTIONS_ENABLED", "1").strip().lower() not in {"0", "false", "no", "off"}+++def actions_execute() -> bool:+ """Whether a playbook step may touch a vendor, as opposed to previewing.++ Off by default, matching the platform's copilot posture. Governance can+ still refuse an execution this allows; it can never allow one this+ refuses.+ """+ return os.getenv("AISOC_PLAYBOOK_ACTIONS_EXECUTE", "0").strip().lower() in {"1", "true", "yes", "on"}+++def _service_token() -> str:+ """Shared secret for the API's service path. Empty means "do not call"."""+ return os.getenv("AISOC_AGENTS_SERVICE_TOKEN", "").strip()+++class BridgeUnavailable(RuntimeError):+ """The step could not be dispatched. Carries the operator-facing reason.++ Raised rather than returned so a caller cannot forget to check: the+ engine's handler turns it into a failed step, and a failed step halts the+ run under the default policy.+ """+++async def dispatch_step(+ *,+ capability: str,+ tenant_id: str,+ target: str = "",+ params: dict[str, Any] | None = None,+ vendor_id: str = "",+ confidence: float | None = None,+ playbook_run_id: str = "",+ playbook_step_id: str = "",+) -> dict[str, Any]:+ """POST one step to the API and return its report verbatim.++ The report's ``executed`` field is the single thing that means a vendor+ was touched. It is returned unmodified — narrowing it to a boolean here+ would throw away the distinction between "held for an analyst", "no+ integration configured" and "previewed", which are the three answers an+ author most needs.+ """+ if not actions_enabled():+ raise BridgeUnavailable(+ f"playbook action dispatch is disabled (AISOC_PLAYBOOK_ACTIONS_ENABLED=0), so '{capability}' was not attempted"+ )+ if not tenant_id:+ # The API refuses a service call with no tenant, and guessing one+ # here would be a cross-tenant action.+ raise BridgeUnavailable(f"'{capability}' has no tenant in the run context, and a response action cannot be run without one")++ token = _service_token()+ if not token:+ raise BridgeUnavailable(+ f"'{capability}' was not dispatched: AISOC_AGENTS_SERVICE_TOKEN is unset, so the API's service path is closed"+ )++ payload: dict[str, Any] = {+ "capability": capability,+ "target": target,+ "params": params or {},+ "vendor_id": vendor_id,+ "dry_run": not actions_execute(),+ "tenant_id": tenant_id,+ "playbook_run_id": playbook_run_id,+ "playbook_step_id": playbook_step_id,+ }+ if confidence is not None:+ payload["confidence"] = max(0.0, min(1.0, float(confidence)))++ url = f"{_API_URL.rstrip('/')}/api/v1/playbook-steps/dispatch"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_S) as client:+ response = await client.post(url, json=payload, headers={"X-AiSOC-Service-Token": token})+ except httpx.HTTPError as exc:+ raise BridgeUnavailable(f"the action service could not be reached for '{capability}': {exc}") from exc++ if response.status_code >= 400:+ raise BridgeUnavailable(f"the API refused '{capability}' with HTTP {response.status_code}")++ try:+ report = response.json()+ except ValueError as exc:+ raise BridgeUnavailable(f"the API returned a non-JSON body for '{capability}'") from exc+ if not isinstance(report, dict) or "executed" not in report:+ raise BridgeUnavailable(f"the API returned a report with no 'executed' field for '{capability}'")++ logger.info(+ # `executed` is echoed verbatim: if it is False no vendor was+ # touched, whatever the HTTP status said.+ "playbook_action.dispatched capability=%s status=%s executed=%s step=%s",+ capability,+ report.get("status"),+ bool(report.get("executed")),+ playbook_step_id,+ )+ return reportdiff --git a/services/agents/app/playbook/engine.py b/services/agents/app/playbook/engine.pyindex 134613440..638ac83b8 100644--- a/services/agents/app/playbook/engine.py+++ b/services/agents/app/playbook/engine.py@@ -23,6 +23,7 @@ from typing import Anyimport httpx+from . import action_bridgefrom .bounds import clamp_timeoutfrom .models import Playbook, PlaybookStep, StepCondition, StepTypefrom .ssrf_guard import SSRFError, validate_outbound_url@@ -81,6 +82,11 @@ class PlaybookRun:self.trigger_context: dict[str, Any] = trigger_context# Accumulated output from previous steps — available to later steps as {{prev.*}}self.context: dict[str, Any] = dict(trigger_context)+ # Under an engine-reserved key so it cannot be overwritten by a step+ # result flattened into the context. A response action's audit record+ # names the run it came from, and losing that mid-run would leave an+ # isolated host with no trace of what asked for it.+ self.context["_run_id"] = self.run_idself.step_results: list[dict[str, Any]] = []self.started_at: str = ""self.finished_at: str = ""@@ -389,18 +395,120 @@ async def _handle_http(step: PlaybookStep, context: dict[str, Any], http: httpx.return {"status": r.status_code, "body": r.text[:500]}-async def _handle_block_ip(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:- ip = step.params.get("ip") or context.get("src_ip", "")- return {"action": "block_ip", "ip": ip, "simulated": True}+# ---------------------------------------------------------------------------+# Response steps — the bridge to governed dispatch+# ---------------------------------------------------------------------------+#+# Fifteen step types name a verb that changes somebody's estate. Three of them+# used to be answered here with ``{"simulated": True}`` and reached no executor+# at all; the other twelve had no handler. `services/actions` has held working+# executors for fourteen of the fifteen the whole time, behind a contract that+# declares each verb's impact, reversibility, approval requirement and whether+# a probe exists to confirm the effect landed.+#+# Each of these steps is now one governed dispatch, graded on its own+# capability. A playbook is not approved as a unit: authorising the playbook+# cannot authorise whatever its steps happen to contain, because the contract+# is applied per step at the far end.+#+# `approval` is the one verb that is not bridged, and the reason is recorded+# at its entry in ``_UNBRIDGEABLE`` rather than papered over with a handler.+++#: Where each verb's target lives, in the order it should be looked for:+#: first the step's own params, then the trigger context. A verb with no+#: natural scalar target (the details ride in ``params``) maps to ``()``.+_TARGET_KEYS: dict[StepType, tuple[str, ...]] = {+ StepType.BLOCK_IP: ("ip", "address", "src_ip", "source_ip"),+ StepType.BLOCK_IOC: ("ioc", "indicator", "hash", "domain", "ip"),+ StepType.ISOLATE_HOST: ("host", "hostname", "device_id", "host_id"),+ StepType.KILL_PROCESS: ("host", "hostname", "device_id", "host_id"),+ StepType.QUARANTINE_FILE: ("host", "hostname", "device_id", "host_id"),+ StepType.RUN_AV_SCAN: ("host", "hostname", "device_id", "host_id"),+ StepType.RUN_SCRIPT: ("host", "hostname", "device_id", "host_id"),+ StepType.DISABLE_USER: ("user", "username", "user_id", "upn", "email"),+ StepType.RESET_PASSWORD: ("user", "username", "user_id", "upn", "email"),+ StepType.REVOKE_SESSION: ("user", "username", "user_id", "upn", "email"),+ StepType.FORCE_MFA: ("user", "username", "user_id", "upn", "email"),+ StepType.SEARCH_SIEM: ("query", "search"),+ StepType.CREATE_NOTABLE_EVENT: ("title", "name"),+ StepType.CREATE_TICKET: (),+}++#: Step types that name a verb but deliberately have no bridge, with the+#: reason. The engine reports the reason instead of a bare "no handler", and+#: the schema's ``x-aisoc-execution`` map records the same state, so an author+#: can tell before writing the playbook rather than after running it.+_UNBRIDGEABLE: dict[StepType, str] = {+ StepType.APPROVAL: (+ "an approval step is a pause, and this engine is a single-threaded "+ "index walk with no pause or resume — there is nothing to suspend and "+ "nothing to wake. It is also no longer the mechanism: every response "+ "step is now graded against its own capability contract at dispatch "+ "and returns 'pending_approval' on its own when a human is required, "+ "so an approval step in front of one would gate a decision that is "+ "already gated. Remove it, or hold the action in the actions service, "+ "which does queue for an analyst."+ ),+}-async def _handle_isolate_host(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:- host = step.params.get("host") or context.get("host", "")- return {"action": "isolate_host", "host": host, "simulated": True}+def _resolve_target(step: PlaybookStep, context: dict[str, Any]) -> str:+ """First non-empty target for this verb, from params then context."""+ for key in _TARGET_KEYS.get(step.type, ()):+ for source in (step.params, context):+ value = source.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""-async def _handle_create_ticket(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:- return {"action": "create_ticket", "params": step.params, "simulated": True}+def _resolve_confidence(step: PlaybookStep, context: dict[str, Any]) -> float | None:+ """How good the reason for acting is, as a 0..1 fraction.++ Alerts carry confidence as an integer 0-100 and the agent carries it as a+ fraction, so both spellings arrive here. ``None`` is returned when there+ is no score at all rather than a default, because the approval matrix+ treats a missing score as the lowest band and inventing a middling one+ would quietly raise what an unscored action is allowed to do.+ """+ for source in (step.params, context):+ raw = source.get("confidence")+ if isinstance(raw, bool) or raw is None:+ continue+ if isinstance(raw, int | float):+ value = float(raw)+ return min(1.0, value / 100.0) if value > 1.0 else max(0.0, value)+ return None+++def _make_response_handler(step_type: StepType):+ """Build the handler for one response verb.++ One factory rather than fifteen near-identical functions: the verb is the+ only thing that differs, and fifteen copies is fifteen chances for one of+ them to drift into doing something the contract did not grade.+ """++ async def _handler(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:+ report = await action_bridge.dispatch_step(+ capability=step_type.value,+ tenant_id=str(context.get("tenant_id") or ""),+ target=_resolve_target(step, context),+ params=dict(step.params),+ vendor_id=str(step.params.get("vendor") or step.params.get("vendor_id") or ""),+ confidence=_resolve_confidence(step, context),+ playbook_run_id=str(context.get("_run_id") or ""),+ playbook_step_id=step.id,+ )+ # Returned verbatim. `executed` is the single field that means a+ # vendor was touched, and the run loop reads it rather than assuming+ # that a handler which returned at all did its job.+ return report++ _handler.__name__ = f"_handle_{step_type.value}"+ _handler.__qualname__ = _handler.__name__+ return _handlerasync def _handle_close_case(step: PlaybookStep, context: dict[str, Any], http: httpx.AsyncClient) -> dict:@@ -522,16 +630,19 @@ async def _handle_osquery_live_query(step: PlaybookStep, context: dict[str, Any]return {"error": str(exc), "partial": True, "stub": True}+#: Verbs dispatched through the action registry. Derived from `_TARGET_KEYS`+#: so the two cannot drift: a verb added to one without the other would+#: either dispatch with no target or declare a target nothing reads.+RESPONSE_STEP_TYPES: frozenset[StepType] = frozenset(_TARGET_KEYS)+_HANDLERS = {StepType.ENRICH: _handle_enrich,StepType.INVESTIGATE: _handle_investigate,StepType.NOTIFY: _handle_notify,StepType.HTTP: _handle_http,- StepType.BLOCK_IP: _handle_block_ip,- StepType.ISOLATE_HOST: _handle_isolate_host,- StepType.CREATE_TICKET: _handle_create_ticket,StepType.CLOSE_CASE: _handle_close_case,StepType.OSQUERY_LIVE_QUERY: _handle_osquery_live_query,+ **{step_type: _make_response_handler(step_type) for step_type in sorted(RESPONSE_STEP_TYPES, key=lambda s: s.value)},}@@ -627,6 +738,8 @@ class PlaybookEngine:attempt = 0handler = _HANDLERS.get(step.type)+ unbridgeable = _UNBRIDGEABLE.get(step.type)+if handler is None and not dry_run:# Fail closed, and skip the retry loop — a missing handler# will still be missing on the next attempt.@@ -641,8 +754,13 @@ class PlaybookEngine:# means the default ``on_failure: abort`` halts the run.step_status = StepStatus.FAILEDresult = {- "error": f"step type {step.type.value!r} has no handler in this engine",+ "error": (+ f"step type {step.type.value!r} is not runnable: {unbridgeable}"+ if unbridgeable+ else f"step type {step.type.value!r} has no handler in this engine"+ ),"unimplemented": True,+ "executed": False,"_elapsed_ms": 0,}logger.error(@@ -656,18 +774,41 @@ class PlaybookEngine:t0 = time.perf_counter()try:if dry_run:- result = {"dry_run": True, "step": step.name}+ result = {"dry_run": True, "executed": False, "step": step.name}if handler is None:# A dry run exists to tell the author what# would happen. "dry_run: true" alone would# imply this step is fine.result["unimplemented"] = Trueresult["would_fail"] = True+ if unbridgeable:+ result["reason"] = unbridgeable+ elif step.type in RESPONSE_STEP_TYPES:+ # Name the verb a live run would dispatch,+ # so a preview of a containment playbook+ # reads as a containment playbook.+ result["would_dispatch"] = step.type.value+ result["target"] = _resolve_target(step, pr.context)else:result = await handler(step, pr.context, http)elapsed = time.perf_counter() - t0result["_elapsed_ms"] = round(elapsed * 1000)- break # success+ # A handler that returned is not a step that ran.+ # Every response verb reports `executed`, and a+ # False there means the action was previewed, held+ # for an analyst, blocked, unconfigured or refused+ # — none of which is a step that did what it says.+ # Reporting those as SUCCESS is the defect this+ # whole path exists to remove, so they fail closed+ # and the default `on_failure: abort` halts the run.+ if step.type in RESPONSE_STEP_TYPES and not result.get("executed"):+ step_status = StepStatus.FAILED+ result.setdefault(+ "error",+ f"{step.type.value} did not execute ({result.get('status', 'unknown')}): "+ f"{result.get('summary') or result.get('detail') or 'no vendor was touched'}",+ )+ break # the handler answered; status is set aboveexcept Exception as exc: # noqa: BLE001elapsed = time.perf_counter() - t0logger.error("Step %s attempt %d failed: %s", step.name, attempt, exc)@@ -716,7 +857,23 @@ class PlaybookEngine:current_idx += 1if pr.status == RunStatus.RUNNING:- pr.status = RunStatus.COMPLETED+ # `on_failure: continue` decides whether the run keeps going.+ # It does not decide what the run is called afterwards, and+ # 346 of the 380 steps in the shipped packs carry it — so+ # reading it as "report this as completed" would put a green+ # tick over a containment that never happened, which is the+ # failure this whole path exists to remove. The run finished;+ # it did not do everything it said.+ failed = [r["name"] for r in pr.step_results if r["status"] == StepStatus.FAILED]+ if failed:+ pr.status = RunStatus.FAILED+ shown = ", ".join(f"'{name}'" for name in failed[:3])+ more = f" and {len(failed) - 3} more" if len(failed) > 3 else ""+ pr.error = (+ f"{len(failed)} of {len(pr.step_results)} steps failed " f"({shown}{more}); the run continued past them by policy"+ )+ else:+ pr.status = RunStatus.COMPLETEDpr.finished_at = datetime.now(UTC).isoformat()await _emit(pr.run_id, "run.done", pr.to_dict(), http)diff --git a/services/agents/tests/test_playbook_action_bridge.py b/services/agents/tests/test_playbook_action_bridge.pynew file mode 100644index 000000000..f851dbc25--- /dev/null+++ b/services/agents/tests/test_playbook_action_bridge.py@@ -0,0 +1,252 @@+"""A playbook step that names a response verb must reach governed dispatch.++The defect these cover passed every test in the repository while doing+nothing. `_handle_block_ip` and `_handle_isolate_host` returned+``{"action": ..., "simulated": True}`` from inside the engine, reached no+executor, and the run loop recorded SUCCESS — so a playbook an operator+believed contained real response steps contained none, and reported+COMPLETED. Twelve further step types had no handler at all.++The assertions below are therefore about *where the call went* and *what the+step claimed*, not about a return value being non-empty. A handler that+returns a dict is not a step that ran.+"""++from __future__ import annotations++from typing import Any++import pytest+from app.playbook import action_bridge+from app.playbook.engine import RESPONSE_STEP_TYPES, PlaybookEngine, RunStatus, StepStatus+from app.playbook.models import Playbook, PlaybookStep, StepType++pytestmark = pytest.mark.asyncio+++def _playbook(*steps: PlaybookStep) -> Playbook:+ return Playbook(id="pb-1", name="Containment", steps=list(steps))+++class _Recorder:+ """Stands in for the API hop and records exactly what it was asked."""++ def __init__(self, report: dict[str, Any] | None = None, raises: Exception | None = None) -> None:+ self.calls: list[dict[str, Any]] = []+ self._report = report or {"capability": "?", "status": "executed", "executed": True, "summary": "done"}+ self._raises = raises++ async def __call__(self, **kwargs: Any) -> dict[str, Any]:+ self.calls.append(kwargs)+ if self._raises is not None:+ raise self._raises+ return {**self._report, "capability": kwargs["capability"]}+++def bridge(monkeypatch: pytest.MonkeyPatch):+ """Install a recorder in place of the HTTP hop and return it."""++ def _install(report: dict[str, Any] | None = None, raises: Exception | None = None) -> _Recorder:+ recorder = _Recorder(report, raises)+ monkeypatch.setattr(action_bridge, "dispatch_step", recorder)+ return recorder++ return _install+++class TestEveryResponseVerbReachesDispatch:+ async def test_all_fifteen_response_verbs_dispatch(self, bridge) -> None:+ """Pre-change: three returned `simulated: True` locally and twelve+ had no handler at all."""+ recorder = bridge()+ for step_type in sorted(RESPONSE_STEP_TYPES, key=lambda s: s.value):+ pb = _playbook(PlaybookStep(id="s1", name=step_type.value, type=step_type))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})+ assert run.step_results[0]["status"] == StepStatus.SUCCESS, step_type.value++ dispatched = [c["capability"] for c in recorder.calls]+ assert sorted(dispatched) == sorted(s.value for s in RESPONSE_STEP_TYPES)++ async def test_the_three_that_used_to_simulate_now_reach_an_executor(self, bridge) -> None:+ """`block_ip`, `isolate_host` and `create_ticket` specifically.++ Named individually because these are the ones the `action.py` comment+ claimed already dispatched "step by step through this service".+ """+ recorder = bridge()+ pb = _playbook(+ PlaybookStep(id="s1", name="block", type=StepType.BLOCK_IP, params={"ip": "203.0.113.10"}),+ PlaybookStep(id="s2", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "ws-042"}),+ PlaybookStep(id="s3", name="ticket", type=StepType.CREATE_TICKET),+ )+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert run.status == RunStatus.COMPLETED+ assert [c["capability"] for c in recorder.calls] == ["block_ip", "isolate_host", "create_ticket"]+ assert recorder.calls[0]["target"] == "203.0.113.10"+ assert recorder.calls[1]["target"] == "ws-042"+ for result in run.step_results:+ assert "simulated" not in result["result"]++ async def test_each_step_is_dispatched_separately_and_carries_its_own_id(self, bridge) -> None:+ """Per-step grading is the whole design: one request per step, so the+ contract is applied to each verb rather than to the playbook."""+ recorder = bridge()+ pb = _playbook(+ PlaybookStep(id="alpha", name="block", type=StepType.BLOCK_IP, params={"ip": "198.51.100.4"}),+ PlaybookStep(id="beta", name="disable", type=StepType.DISABLE_USER, params={"user": "jdoe"}),+ )+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert len(recorder.calls) == 2+ assert [c["playbook_step_id"] for c in recorder.calls] == ["alpha", "beta"]+ assert [c["capability"] for c in recorder.calls] == ["block_ip", "disable_user"]+ # Every dispatch names the run, so an isolated host is traceable to+ # the playbook that asked for it.+ assert all(c["playbook_run_id"] == run.run_id for c in recorder.calls)+++class TestNoFakeSuccess:+ @pytest.mark.parametrize(+ ("status", "summary"),+ [+ ("pending_approval", "needs an analyst"),+ ("blocked", "blocked by policy"),+ ("simulated", "no vendor was touched"),+ ("dry_run", "previewed"),+ ("no_integration", "no enabled connector"),+ ("unsupported", "no executor is registered"),+ ],+ )+ async def test_a_step_that_did_not_execute_fails(self, bridge, status: str, summary: str) -> None:+ """`executed` is the single field that means a vendor was touched.++ Each of these is a real, distinct outcome and none of them is the+ step doing what it says, so none may be recorded as a success.+ """+ bridge({"status": status, "executed": False, "summary": summary})+ pb = _playbook(PlaybookStep(id="s1", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "ws-1"}))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert run.step_results[0]["status"] == StepStatus.FAILED+ assert run.status == RunStatus.FAILED+ assert status in run.step_results[0]["result"]["error"]++ async def test_awaiting_completion_counts_as_executed(self, bridge) -> None:+ """The vendor was touched and the outcome is not known yet.++ Distinct from `pending_approval`, where nothing ran. Failing this one+ would lose an action that is genuinely in flight.+ """+ bridge({"status": "awaiting_completion", "executed": True, "summary": "MDE accepted the acquisition"})+ pb = _playbook(PlaybookStep(id="s1", name="collect", type=StepType.RUN_SCRIPT, params={"host": "ws-1"}))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert run.step_results[0]["status"] == StepStatus.SUCCESS+ assert run.step_results[0]["result"]["executed"] is True++ async def test_a_run_whose_response_steps_all_failed_is_not_completed(self, bridge) -> None:+ """The run-level version of the same claim."""+ bridge({"status": "pending_approval", "executed": False, "summary": "held"})+ pb = _playbook(+ PlaybookStep(id="s1", name="block", type=StepType.BLOCK_IP, on_failure="continue", params={"ip": "1.2.3.4"}),+ PlaybookStep(id="s2", name="isolate", type=StepType.ISOLATE_HOST, on_failure="continue", params={"host": "h"}),+ )+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert run.status == RunStatus.FAILED+ assert "2 of 2 steps failed" in (run.error or "")++ async def test_an_unreachable_bridge_fails_the_step_rather_than_simulating(self, bridge) -> None:+ """Falling back to a preview is how the original defect would return."""+ bridge(raises=action_bridge.BridgeUnavailable("the action service could not be reached"))+ pb = _playbook(PlaybookStep(id="s1", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "ws-1"}))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert run.step_results[0]["status"] == StepStatus.FAILED+ assert run.status == RunStatus.FAILED+ assert "could not be reached" in run.step_results[0]["result"]["error"]+++class TestWhatTheBridgeSends:+ async def test_a_missing_tenant_is_refused_rather_than_guessed(self) -> None:+ """A response action with no tenant would be a cross-tenant action."""+ with pytest.raises(action_bridge.BridgeUnavailable, match="no tenant"):+ await action_bridge.dispatch_step(capability="isolate_host", tenant_id="")++ async def test_no_service_token_is_a_loud_refusal_not_a_silent_skip(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.delenv("AISOC_AGENTS_SERVICE_TOKEN", raising=False)+ with pytest.raises(action_bridge.BridgeUnavailable, match="AISOC_AGENTS_SERVICE_TOKEN"):+ await action_bridge.dispatch_step(capability="isolate_host", tenant_id="t-1")++ async def test_execution_is_off_by_default_so_a_step_previews(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Copilot is the platform's posture; a playbook does not opt out of it."""+ monkeypatch.delenv("AISOC_PLAYBOOK_ACTIONS_EXECUTE", raising=False)+ assert action_bridge.actions_execute() is False+ monkeypatch.setenv("AISOC_PLAYBOOK_ACTIONS_EXECUTE", "1")+ assert action_bridge.actions_execute() is True++ @pytest.mark.parametrize(+ ("context_value", "expected"),+ [+ (92, 0.92), # alerts carry confidence as an int 0-100+ (0.92, 0.92), # the agent carries it as a fraction+ (None, None), # absent is the lowest band, not a middling default+ ],+ )+ async def test_confidence_reaches_the_matrix_in_the_shape_it_expects(+ self,+ bridge,+ context_value: float | None,+ expected: float | None,+ ) -> None:+ recorder = bridge()+ context: dict[str, Any] = {"tenant_id": "t-1"}+ if context_value is not None:+ context["confidence"] = context_value+ pb = _playbook(PlaybookStep(id="s1", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "h"}))+ await PlaybookEngine().run(pb, context)++ assert recorder.calls[0]["confidence"] == expected++ async def test_a_pinned_vendor_is_forwarded_not_resolved_here(self, bridge) -> None:+ """Which vendor a tenant has is a fact only the API can read."""+ recorder = bridge()+ pb = _playbook(PlaybookStep(id="s1", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "h", "vendor": "sentinelone"}))+ await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ assert recorder.calls[0]["vendor_id"] == "sentinelone"+++class TestApprovalStaysUnbridged:+ async def test_approval_has_no_handler_and_says_why(self) -> None:+ """The one verb with no bridge. It is a pause, and the engine is an+ index walk with nothing to suspend — recorded rather than faked."""+ pb = _playbook(PlaybookStep(id="gate", name="sign-off", type=StepType.APPROVAL))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"})++ result = run.step_results[0]["result"]+ assert run.step_results[0]["status"] == StepStatus.FAILED+ assert result["unimplemented"] is True+ assert result["executed"] is False+ assert "no pause or resume" in result["error"]+ assert "pending_approval" in result["error"], "the reason must name the mechanism that replaced it"+++class TestDryRunPreview:+ async def test_a_preview_names_the_verb_and_target_it_would_dispatch(self) -> None:+ """A preview of a containment playbook must read as one."""+ pb = _playbook(PlaybookStep(id="s1", name="isolate", type=StepType.ISOLATE_HOST, params={"host": "ws-042"}))+ run = await PlaybookEngine().run(pb, {"tenant_id": "t-1"}, dry_run=True)++ result = run.step_results[0]["result"]+ assert result["would_dispatch"] == "isolate_host"+ assert result["target"] == "ws-042"+ assert result["executed"] is Falsediff --git a/services/agents/tests/test_playbook_engine_correctness.py b/services/agents/tests/test_playbook_engine_correctness.pyindex 6c91e3794..00b71e06b 100644--- a/services/agents/tests/test_playbook_engine_correctness.py+++ b/services/agents/tests/test_playbook_engine_correctness.py@@ -468,9 +468,14 @@ class TestUnimplementedStepTypesFailClosed:assert run.step_results[0]["result"]["_elapsed_ms"] == 0@pytest.mark.asyncio- async def test_on_failure_continue_is_still_honoured(self) -> None:- """Failing closed must not mean ignoring the author's policy: a step- explicitly marked ``continue`` still lets the run proceed."""+ async def test_on_failure_continue_lets_the_run_proceed_without_calling_it_completed(self) -> None:+ """``continue`` decides whether the run keeps going, not what it is called.++ 346 of the 380 steps in the shipped packs carry ``on_failure:+ continue``, so treating it as "report this run as completed" would put+ a green tick over a containment that never happened — which is the+ same fake success, moved up one level from the step to the run.+ """pb = _make_playbook([PlaybookStep(id="s1", name="best-effort scan", type=StepType.RUN_AV_SCAN, on_failure="continue"),@@ -480,9 +485,10 @@ class TestUnimplementedStepTypesFailClosed:run = await PlaybookEngine().run(pb, trigger_context={})- assert len(run.step_results) == 2+ assert len(run.step_results) == 2, "the author said continue; both steps must be attempted"assert all(r["status"] == StepStatus.FAILED for r in run.step_results)- assert run.status == RunStatus.COMPLETED+ assert run.status == RunStatus.FAILED+ assert run.error and "2 of 2 steps failed" in run.error@pytest.mark.asyncioasync def test_a_dry_run_says_which_steps_would_fail(self) -> None:diff --git a/services/api/app/api/v1/endpoints/playbook_steps.py b/services/api/app/api/v1/endpoints/playbook_steps.pynew file mode 100644index 000000000..5a05378ad--- /dev/null+++ b/services/api/app/api/v1/endpoints/playbook_steps.py@@ -0,0 +1,117 @@+"""The route a playbook step reaches governed dispatch through.++The playbook engine runs in ``services/agents``, which holds no credential+vault and no tenant database session. It therefore cannot dispatch a response+action, and until now it did not try: ``block_ip`` and ``isolate_host``+returned ``{"simulated": true}`` from inside the engine and twelve further+step types had no handler at all.++This route is the hop between them. It authenticates the same two ways+``alerts/{id}/source-writeback`` does — a session for a person, a shared+service token for the agents worker — and delegates every question about+whether the action may run to ``services/actions``, which owns the contract.++One step, one request, one grading. A playbook is not approved as a unit:+each step arrives here on its own and is graded on its own capability, so+authorising a playbook cannot authorise whatever its steps happen to contain.+"""++from __future__ import annotations++import uuid+from typing import Annotated, Any++import structlog+from fastapi import APIRouter, Depends, Header, HTTPException, status+from pydantic import BaseModel, Field+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.v1.deps import CurrentUser+from app.api.v1.endpoints.alert_writeback import optional_user, service_token_valid+from app.db.database import get_db+from app.services.playbook_step_dispatch import dispatch_step++logger = structlog.get_logger(__name__)++router = APIRouter(prefix="/playbook-steps", tags=["playbooks"])+++class StepDispatchRequest(BaseModel):+ """One playbook step, expressed as the verb it names."""++ capability: str = Field(description="Response verb, e.g. 'isolate_host'. Must be a registered capability.")+ target: str = Field(default="", max_length=512, description="Host, user, address or id the verb acts on.")+ params: dict[str, Any] = Field(default_factory=dict)+ vendor_id: str = Field(default="", max_length=64, description="Pin a vendor. Honoured only if the tenant has it configured.")+ confidence: float | None = Field(default=None, ge=0.0, le=1.0)+ #: Defaults to a preview. Every caller that wants a vendor touched has to+ #: say so — a forgotten field should cost a preview, not a containment.+ dry_run: bool = True+ playbook_run_id: str = Field(default="", max_length=64)+ playbook_step_id: str = Field(default="", max_length=64)+ #: Required from a service caller, which has no session to read it from.+ #: Ignored for a session caller, whose tenant comes from the session.+ tenant_id: uuid.UUID | None = None+++def _resolve_caller(+ body_tenant_id: uuid.UUID | None,+ user: CurrentUser | None,+ service_token: str | None,+) -> tuple[uuid.UUID, str]:+ """``(tenant_id, requested_by)`` for an authorised caller, or 401/403.++ A session's tenant comes from the session. Taking the client's copy would+ let any authenticated user drive a containment against another tenant's+ estate through a playbook step.+ """+ if user is not None:+ user.require_permission("actions:execute")+ return user.tenant_id, f"user:{user.email}"++ if service_token_valid(service_token):+ if body_tenant_id is None:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="a service caller must name the tenant it is acting for",+ )+ return body_tenant_id, "aisoc-playbook"++ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="authentication required",+ headers={"WWW-Authenticate": "Bearer"},+ )++[email protected]("/dispatch", summary="Run one playbook step through governed action dispatch")+async def dispatch_playbook_step(+ body: StepDispatchRequest,+ user: Annotated[CurrentUser | None, Depends(optional_user)],+ db: Annotated[AsyncSession, Depends(get_db)],+ x_aisoc_service_token: Annotated[str | None, Header()] = None,+) -> dict[str, Any]:+ """Dispatch one step and report what actually happened.++ Never raises for an action-level outcome. A blocked action, an approval+ queue, a missing integration and a vendor failure are all 200 with+ ``executed: false`` and a status naming which one it was, so the engine+ has a single shape to read. ``HTTPException`` is reserved for callers+ this route will not serve at all.+ """+ tenant_id, requested_by = _resolve_caller(body.tenant_id, user, x_aisoc_service_token)++ report = await dispatch_step(+ db,+ tenant_id=tenant_id,+ capability=body.capability,+ target=body.target,+ params=body.params,+ vendor_id=body.vendor_id,+ confidence=body.confidence,+ dry_run=body.dry_run,+ requested_by=requested_by,+ playbook_run_id=body.playbook_run_id,+ playbook_step_id=body.playbook_step_id,+ )+ return report.as_dict()diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex e55c69585..c161febff 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -58,6 +58,7 @@ from app.api.v1.endpoints import (oncall,passkeys,phishing,+ playbook_steps,playbooks,plugins,posture,@@ -120,6 +121,10 @@ api_router.include_router(rule_tuning.router)api_router.include_router(federated.router)api_router.include_router(graph.router)api_router.include_router(playbooks.router)+# One playbook step, graded on its own capability, through the same governed+# dispatch a manually-approved action takes. The engine has no vault and no+# tenant session, so this is where a step turns into a real vendor call.+api_router.include_router(playbook_steps.router)api_router.include_router(plugins.router)api_router.include_router(community.router)api_router.include_router(marketplace.router)diff --git a/services/api/app/services/actions_client.py b/services/api/app/services/actions_client.pyindex b487716c0..439889b22 100644--- a/services/api/app/services/actions_client.py+++ b/services/api/app/services/actions_client.py@@ -16,6 +16,7 @@ One client, one contract, one place to fix the next thing.from __future__ import annotations+import refrom typing import Anyimport httpx@@ -96,6 +97,45 @@ async def _post(path: str, payload: dict[str, Any] | None) -> dict[str, Any]:return body+async def _get(path: str) -> Any:+ url = f"{base_url()}{path}"+ try:+ async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client:+ response = await client.get(url, headers=service_headers())+ except httpx.HTTPError as exc:+ raise ActionsServiceError(f"actions service unreachable: {exc}") from exc+ if response.status_code >= 400:+ detail = _detail(response)+ raise ActionsServiceError(detail, status_code=response.status_code, upstream_detail=detail)+ try:+ return response.json()+ except ValueError as exc:+ raise ActionsServiceError("actions service returned a non-JSON body") from exc+++#: Capability verbs are short identifiers from a closed vocabulary. This one+#: is interpolated into an upstream path that carries the service token, so+#: it is checked here rather than trusted — the same guard the browser-facing+#: proxy applies, for the same reason.+_IDENTIFIER = re.compile(r"^[a-z0-9][a-z0-9_]{0,63}$")+++async def vendors_for_capability(capability: str) -> list[str]:+ """Vendor ids with a registered executor for ``capability``.++ Asked of the actions service rather than mirrored here. A second copy of+ the registry in this process would be a list that goes stale the first+ time somebody ships a vendor, and the failure would look like "this+ tenant has no integration" rather than "the list is old".+ """+ if not _IDENTIFIER.match(capability):+ raise ActionsServiceError(f"{capability!r} is not a capability identifier")+ body = await _get(f"/api/v1/live-actions/by-capability/{capability}")+ if not isinstance(body, list):+ raise ActionsServiceError("actions service returned an unexpected body shape")+ return [str(v) for v in body]++def _detail(response: httpx.Response) -> str:try:payload = response.json()@@ -168,6 +208,9 @@ async def dispatch_live_action(dry_run: bool = True,requested_by: str = "aisoc-api",case_id: str | None = None,+ confidence: float | None = None,+ playbook_run_id: str | None = None,+ playbook_step_id: str | None = None,) -> dict[str, Any]:"""Dispatch a ``(vendor_id, capability)`` pair to the live-action registry.@@ -181,6 +224,10 @@ async def dispatch_live_action(schema* field names; the actions service translates them into theexecutor's vendor-prefixed parameters at the dispatch boundary. They arepassed per call and never persisted here.++ ``confidence`` is how good the reason for acting is, and it is a real+ input: the approval matrix grades impact against it, and omitting it is+ the lowest band rather than no opinion."""payload: dict[str, Any] = {"capability": capability,@@ -195,6 +242,12 @@ async def dispatch_live_action(payload["auth_config"] = auth_configif case_id:payload["case_id"] = case_id+ if confidence is not None:+ payload["confidence"] = confidence+ if playbook_run_id:+ payload["playbook_run_id"] = playbook_run_id+ if playbook_step_id:+ payload["playbook_step_id"] = playbook_step_id# `/dry-run` forces dry_run server-side regardless of the body, so a# preview cannot become a live call through a serialisation mistake.path = "/api/v1/live-actions/dispatch" if not dry_run else "/api/v1/live-actions/dry-run"diff --git a/services/api/app/services/playbook_step_dispatch.py b/services/api/app/services/playbook_step_dispatch.pynew file mode 100644index 000000000..0b17dfd43--- /dev/null+++ b/services/api/app/services/playbook_step_dispatch.py@@ -0,0 +1,393 @@+"""Turn a playbook step that names a response verb into a governed action.++Twelve of the engine's twenty-two step types had no handler, and three more+(``block_ip``, ``isolate_host``, ``create_ticket``) returned+``{"simulated": true}`` from inside the agents service and reached no executor+at all. Meanwhile ``services/actions`` held working executors for fourteen of+those fifteen verbs behind a per-capability contract. The missing piece was+never an executor. It was this: a way from a step to governed dispatch.++Why the hop lands here+----------------------+The agents worker cannot dispatch on its own. This service holds the+credential vault, the tenant-scoped database session and the actions-service+token, and ``services/actions`` is the single place that may change a+customer's estate. A second dispatcher in the agents service would mean two+places that can isolate a host, two audit trails and two copies of the+credential handling, of which one would go stale. Same reasoning, and the+same shape, as ``siem_writeback``.++What this module decides, and what it does not+----------------------------------------------+It decides **which vendor** and **which credentials**, because those are+tenant facts and this is the only service that can read them. It decides+nothing about whether the action may run: risk, reversibility, approval and+verification are declared per capability in ``services/actions`` and applied+by ``live_actions.dispatch()``. A policy mirrored in two services is a policy+that disagrees with itself eventually.++Honesty rules, which are the point of the whole exercise+--------------------------------------------------------+``executed`` is the single field that means a vendor was touched. A dry run,+a simulation, an approval queue, a missing integration and a refusal are all+``executed=False`` and each says which one it was. Nothing here reports+``succeeded`` for work that did not happen — replacing one silent simulation+with another would leave the product exactly where it started.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass, field+from typing import Any++import structlog+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.connector import Connector+from app.security.credential_vault import CredentialVaultError, get_vault+from app.services import actions_client++logger = structlog.get_logger(__name__)++#: Step outcomes that are *not* an execution, each naming its own reason.+#: Kept as a closed vocabulary so a caller can branch on it, and so a new+#: outcome has to be added deliberately rather than arriving as free text.+NOT_EXECUTED_STATES: frozenset[str] = frozenset(+ {+ "dry_run",+ "simulated",+ "pending_approval",+ "blocked",+ "no_integration",+ "failed",+ "unsupported",+ }+)+++@dataclass+class StepDispatchReport:+ """What actually happened to one step.++ ``executed`` is deliberately not derived from ``status`` by the caller.+ Every construction site sets it explicitly, so adding a status cannot+ accidentally inherit "a vendor was touched".+ """++ capability: str+ status: str+ executed: bool+ summary: str+ vendor_id: str = ""+ detail: str = ""+ #: ``verified`` | ``failed`` | ``unverified``. Absent when the action did+ #: not run, because there is nothing to read back.+ verification: str = ""+ verification_reason: str = ""+ autonomy_mode: str = ""+ blast_radius: str = ""+ details: dict[str, Any] = field(default_factory=dict)++ def as_dict(self) -> dict[str, Any]:+ out: dict[str, Any] = {+ "capability": self.capability,+ "status": self.status,+ "executed": self.executed,+ "summary": self.summary,+ }+ for key in ("vendor_id", "detail", "verification", "verification_reason", "autonomy_mode", "blast_radius"):+ value = getattr(self, key)+ if value:+ out[key] = value+ if self.details:+ out["details"] = self.details+ return out+++#: Connector-instance settings a response action needs that are configuration+#: rather than secrets, so they must not be encrypted at rest as though they+#: were. Mirrors ``siem_writeback._operational_config``.+_OPERATIONAL_KEYS = ("base_url", "region", "closing_reason_id", "owner", "owner_upn", "project_key", "instance_url")+++async def dispatch_step(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ capability: str,+ target: str,+ params: dict[str, Any] | None = None,+ vendor_id: str = "",+ confidence: float | None = None,+ dry_run: bool = True,+ requested_by: str = "aisoc-playbook",+ playbook_run_id: str = "",+ playbook_step_id: str = "",+) -> StepDispatchReport:+ """Resolve a vendor, resolve its credentials, and dispatch under governance."""+ log = logger.bind(+ capability=capability,+ tenant_id=str(tenant_id),+ playbook_run_id=playbook_run_id,+ playbook_step_id=playbook_step_id,+ dry_run=dry_run,+ )++ try:+ implementers = await actions_client.vendors_for_capability(capability)+ except actions_client.ActionsServiceError as exc:+ log.warning("playbook_step.registry_unreachable", error=str(exc)[:300])+ return StepDispatchReport(+ capability=capability,+ status="failed",+ executed=False,+ summary=f"Could not reach the action registry to run '{capability}'.",+ detail=exc.upstream_detail,+ )++ if not implementers:+ # Distinct from "this tenant has no integration": nothing in the+ # product can perform this verb, so no amount of configuration helps.+ return StepDispatchReport(+ capability=capability,+ status="unsupported",+ executed=False,+ summary=f"No executor is registered for '{capability}' in this deployment.",+ detail="A verb must be in both the Capability enum and KNOWN_CAPABILITIES to reach an executor.",+ )++ connector = await _pick_connector(db, tenant_id=tenant_id, capability=capability, implementers=implementers, pinned=vendor_id)+ if connector is None:+ configured = ", ".join(sorted(implementers))+ return StepDispatchReport(+ capability=capability,+ status="no_integration",+ executed=False,+ vendor_id=vendor_id,+ summary=(+ f"'{capability}' is supported, and this tenant has no enabled connector that performs it."+ if not vendor_id+ else f"'{capability}' was pinned to '{vendor_id}', which this tenant has not configured."+ ),+ detail=f"vendors that implement it: {configured}",+ )++ resolved_vendor = connector.connector_type+ log = log.bind(vendor_id=resolved_vendor)++ try:+ auth_config = get_vault().decrypt_dict(connector.auth_config or {})+ except CredentialVaultError as exc:+ # Reported, never downgraded to a simulation. A step that silently+ # became a preview because a key would not decrypt is the failure+ # this whole change exists to remove.+ log.warning("playbook_step.credentials_undecryptable")+ return StepDispatchReport(+ capability=capability,+ status="failed",+ executed=False,+ vendor_id=resolved_vendor,+ summary=f"Credentials for {resolved_vendor} could not be decrypted, so '{capability}' did not run.",+ detail=str(exc)[:500],+ )+ auth_config.update(_operational_config(connector))++ try:+ body = await actions_client.dispatch_live_action(+ capability=capability,+ vendor_id=resolved_vendor,+ target=target,+ tenant_id=str(tenant_id),+ params=dict(params or {}),+ auth_config=auth_config or None,+ dry_run=dry_run,+ requested_by=requested_by,+ confidence=confidence,+ playbook_run_id=playbook_run_id or None,+ playbook_step_id=playbook_step_id or None,+ )+ except actions_client.ActionsServiceError as exc:+ log.warning("playbook_step.dispatch_refused", status_code=exc.status_code)+ return StepDispatchReport(+ capability=capability,+ status="failed",+ executed=False,+ vendor_id=resolved_vendor,+ summary=f"The action service refused '{capability}'.",+ detail=exc.upstream_detail,+ )++ report = _interpret(capability, resolved_vendor, body, dry_run=dry_run)+ log.info("playbook_step.dispatched", status=report.status, executed=report.executed)+ return report+++async def _pick_connector(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ capability: str,+ implementers: list[str],+ pinned: str,+) -> Connector | None:+ """The tenant's enabled connector for this verb, or ``None``.++ A pinned vendor is honoured only if the tenant actually has it. Honouring+ a pin without checking is how a "dry run" ends up calling somebody's+ firewall, and how an action reports against a vendor that was never+ involved.++ Where the step names no vendor and the tenant has several, the choice is+ deterministic (first by name) rather than whichever row the database+ happened to return. A non-deterministic containment target is not a+ feature.+ """+ wanted = [pinned] if pinned else implementers+ rows = (+ (+ await db.execute(+ select(Connector)+ .where(Connector.tenant_id == tenant_id)+ .where(Connector.connector_type.in_(wanted))+ .where(Connector.is_enabled.is_(True))+ .order_by(Connector.connector_type, Connector.name)+ )+ )+ .scalars()+ .all()+ )+ for connector in rows:+ if pinned and connector.connector_type != pinned:+ continue+ if connector.connector_type not in implementers:+ # The pin named a connector the tenant has and no executor can+ # drive. Not a match, and not something to substitute around.+ continue+ allowed = connector.allowed_capabilities+ if allowed is not None and capability not in allowed:+ # Per-instance downscoping is a tenant saying "not this verb on+ # this integration". A playbook does not outrank it.+ logger.info(+ "playbook_step.capability_downscoped",+ vendor_id=connector.connector_type,+ capability=capability,+ )+ continue+ return connector+ return None+++def _operational_config(connector: Connector) -> dict[str, Any]:+ config = connector.connector_config or {}+ return {key: config[key] for key in _OPERATIONAL_KEYS if config.get(key) is not None}+++def _interpret(capability: str, vendor_id: str, body: dict[str, Any], *, dry_run: bool) -> StepDispatchReport:+ """Translate a live-action response into an honest step outcome.++ The live-action layer already distinguishes the states that matter, and+ this function's only job is to not collapse them. In particular+ ``AWAITING_COMPLETION`` — the vendor was touched and the outcome is not+ known yet — counts as ``executed``, while ``PENDING_APPROVAL`` — nothing+ ran, a human is needed — does not. Reporting the first as pending would+ lose an action that is genuinely in flight; reporting the second as+ executed would be the fake success this replaces.+ """+ result = body.get("result") if isinstance(body.get("result"), dict) else {}+ details = result.get("details") if isinstance(result.get("details"), dict) else {}+ status = str(result.get("status") or "")+ summary = str(result.get("summary") or "")++ common = {+ "capability": capability,+ "vendor_id": vendor_id,+ "autonomy_mode": str(details.get("autonomy_mode") or ""),+ "blast_radius": str(details.get("blast_radius") or ""),+ }++ if status == "failed":+ return StepDispatchReport(+ **common,+ status="failed",+ executed=False,+ summary=summary or f"'{capability}' failed on {vendor_id}.",+ detail=str(result.get("error") or "")[:2000],+ verification=str(details.get("verification") or ""),+ verification_reason=str(details.get("verification_reason") or ""),+ )++ if status == "blocked":+ return StepDispatchReport(+ **common,+ status="blocked",+ executed=False,+ summary=summary or f"'{capability}' was blocked by policy.",+ detail=str(details.get("reason") or ""),+ )++ if status == "pending_approval":+ return StepDispatchReport(+ **common,+ status="pending_approval",+ executed=False,+ summary=summary or f"'{capability}' needs an analyst before it runs.",+ detail=str(details.get("reason") or ""),+ )++ if dry_run:+ # Checked before `simulated` because a dry run *is* how the builtin+ # adapters preview: they strip the credentials and the executor takes+ # its simulation branch, so every dry run comes back SIMULATED. Saying+ # "simulated" here would suggest the credentials were missing, which+ # is a different and much more alarming fact. Never an execution,+ # whatever status came back.+ return StepDispatchReport(+ **common,+ status="dry_run",+ executed=False,+ summary=f"DRY RUN — '{capability}' was previewed against {vendor_id} and nothing was changed.",+ detail=summary,+ )++ if status == "simulated":+ return StepDispatchReport(+ **common,+ status="simulated",+ executed=False,+ summary=summary or f"'{capability}' ran in simulation — no vendor was touched.",+ detail="The executor found no usable credentials and took its safe path.",+ )++ if status == "awaiting_completion":+ return StepDispatchReport(+ **common,+ status="awaiting_completion",+ executed=True,+ summary=summary or f"'{capability}' was accepted by {vendor_id}; the outcome is not known yet.",+ verification=str(details.get("verification") or ""),+ verification_reason=str(details.get("verification_reason") or ""),+ )++ if status == "succeeded":+ return StepDispatchReport(+ **common,+ status="executed",+ executed=True,+ summary=summary or f"'{capability}' executed on {vendor_id}.",+ verification=str(details.get("verification") or "unverified"),+ verification_reason=str(details.get("verification_reason") or "no probe ran for this action"),+ )++ # An unrecognised status is not a success. The live-action layer owns this+ # vocabulary, so a new member arriving here means this function is behind+ # — and guessing "it probably worked" is how the collapse being fixed got+ # in originally.+ logger.warning("playbook_step.unrecognised_status", status=status, capability=capability)+ return StepDispatchReport(+ **common,+ status="failed",+ executed=False,+ summary=f"'{capability}' returned an unrecognised status {status!r}; treated as not executed.",+ )diff --git a/services/api/tests/test_playbook_step_dispatch.py b/services/api/tests/test_playbook_step_dispatch.pynew file mode 100644index 000000000..8c4b47c79--- /dev/null+++ b/services/api/tests/test_playbook_step_dispatch.py@@ -0,0 +1,290 @@+"""The API hop a playbook step takes to reach governed dispatch.++This module decides two things and no more: which vendor, and which+credentials. Everything about whether the verb may run belongs to+``services/actions``, so the tests here are mostly about the answers this+layer gives when it *cannot* dispatch — because those are the answers that+used to be a silent simulation.++The load-bearing assertion in almost every case is ``executed``. It is the+single field that means a vendor was touched, and every path that did not+touch one has to say so and say which path it was.+"""++from __future__ import annotations++import uuid+from typing import Any++import pytest+from app.services import actions_client, playbook_step_dispatch+from app.services.playbook_step_dispatch import StepDispatchReport, dispatch_step++pytestmark = pytest.mark.asyncio++TENANT = uuid.uuid4()+++class _Connector:+ """The fields this module reads off a connector row."""++ def __init__(self, connector_type: str, *, allowed: list[str] | None = None, config: dict | None = None) -> None:+ self.connector_type = connector_type+ self.name = connector_type+ self.auth_config = {"api_token": "vault:v1:ciphertext"}+ self.connector_config = config or {}+ self.allowed_capabilities = allowed+++def _wire(+ monkeypatch: pytest.MonkeyPatch,+ *,+ implementers: list[str] | Exception,+ connectors: list[_Connector] | None = None,+ response: dict[str, Any] | Exception | None = None,+) -> list[dict[str, Any]]:+ """Stand in for the action registry, the tenant database and the vault."""+ sent: list[dict[str, Any]] = []++ async def _vendors(capability: str) -> list[str]:+ if isinstance(implementers, Exception):+ raise implementers+ return implementers++ async def _dispatch(**kwargs: Any) -> dict[str, Any]:+ sent.append(kwargs)+ if isinstance(response, Exception):+ raise response+ return response or {"result": {"status": "succeeded", "summary": "done", "details": {}}}++ monkeypatch.setattr(actions_client, "vendors_for_capability", _vendors)+ monkeypatch.setattr(actions_client, "dispatch_live_action", _dispatch)+ monkeypatch.setattr(playbook_step_dispatch, "get_vault", _Vault)++ rows = connectors if connectors is not None else [_Connector("crowdstrike")]++ async def _pick_connector(db, *, tenant_id, capability, implementers, pinned): # noqa: ANN001+ for connector in rows:+ if pinned and connector.connector_type != pinned:+ continue+ if connector.connector_type not in implementers:+ continue+ if connector.allowed_capabilities is not None and capability not in connector.allowed_capabilities:+ continue+ return connector+ return None++ monkeypatch.setattr(playbook_step_dispatch, "_pick_connector", _pick_connector)+ return sent+++class _Vault:+ def decrypt_dict(self, blob: dict) -> dict:+ return {"api_token": "plaintext"}+++async def _run(**overrides: Any) -> StepDispatchReport:+ payload: dict[str, Any] = {+ "tenant_id": TENANT,+ "capability": "isolate_host",+ "target": "ws-042",+ "dry_run": False,+ }+ payload.update(overrides)+ return await dispatch_step(None, **payload) # type: ignore[arg-type]+++class TestWhenItCannotDispatch:+ async def test_a_verb_no_executor_implements_is_unsupported_not_simulated(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Distinct from "this tenant has no integration": no configuration helps."""+ _wire(monkeypatch, implementers=[])+ report = await _run()+ assert report.status == "unsupported"+ assert report.executed is False+ assert "KNOWN_CAPABILITIES" in report.detail++ async def test_a_tenant_with_no_connector_says_so(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _wire(monkeypatch, implementers=["crowdstrike", "defender"], connectors=[])+ report = await _run()+ assert report.status == "no_integration"+ assert report.executed is False+ assert "crowdstrike, defender" in report.detail++ async def test_a_pinned_vendor_the_tenant_does_not_have_is_refused_not_substituted(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Quietly using a different vendor is how an action gets reported+ against one that was never involved."""+ sent = _wire(monkeypatch, implementers=["crowdstrike", "defender"], connectors=[_Connector("crowdstrike")])+ report = await _run(vendor_id="defender")+ assert report.status == "no_integration"+ assert report.executed is False+ assert sent == []++ async def test_per_instance_downscoping_outranks_the_playbook(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A tenant who excluded a verb on an integration meant it."""+ sent = _wire(+ monkeypatch,+ implementers=["crowdstrike"],+ connectors=[_Connector("crowdstrike", allowed=["pull_alerts", "get_host"])],+ )+ report = await _run()+ assert report.status == "no_integration"+ assert sent == []++ async def test_undecryptable_credentials_fail_rather_than_preview(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A step that silently became a preview because a key would not+ decrypt is the failure this whole change removes."""+ from app.security.credential_vault import CredentialVaultError++ sent = _wire(monkeypatch, implementers=["crowdstrike"])++ class _Broken:+ def decrypt_dict(self, blob: dict) -> dict:+ raise CredentialVaultError("key rotated out")++ monkeypatch.setattr(playbook_step_dispatch, "get_vault", _Broken)+ report = await _run()+ assert report.status == "failed"+ assert report.executed is False+ assert sent == []++ async def test_an_unreachable_registry_is_a_failure_not_an_empty_list(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """An outage must not read as "the product cannot do this"."""+ _wire(monkeypatch, implementers=actions_client.ActionsServiceError("connection refused"))+ report = await _run()+ assert report.status == "failed"+ assert report.executed is False+++class TestHowItReadsTheResult:+ @pytest.mark.parametrize(+ ("upstream", "status", "executed"),+ [+ ("succeeded", "executed", True),+ ("awaiting_completion", "awaiting_completion", True),+ ("pending_approval", "pending_approval", False),+ ("blocked", "blocked", False),+ ("simulated", "simulated", False),+ ("failed", "failed", False),+ ],+ )+ async def test_every_live_action_status_maps_to_one_honest_outcome(+ self,+ monkeypatch: pytest.MonkeyPatch,+ upstream: str,+ status: str,+ executed: bool,+ ) -> None:+ """`AWAITING_COMPLETION` and `PENDING_APPROVAL` are the pair that+ must not collapse: the vendor was touched in one and not the other."""+ _wire(monkeypatch, implementers=["crowdstrike"], response={"result": {"status": upstream, "summary": "s", "details": {}}})+ report = await _run()+ assert report.status == status+ assert report.executed is executed++ async def test_an_unrecognised_status_is_not_a_success(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Guessing "it probably worked" is how the collapse got in originally."""+ _wire(monkeypatch, implementers=["crowdstrike"], response={"result": {"status": "invented", "details": {}}})+ report = await _run()+ assert report.status == "failed"+ assert report.executed is False++ async def test_a_dry_run_is_never_an_execution_whatever_came_back(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _wire(monkeypatch, implementers=["crowdstrike"], response={"result": {"status": "succeeded", "details": {}}})+ report = await _run(dry_run=True)+ assert report.status == "dry_run"+ assert report.executed is False++ async def test_the_verification_verdict_is_carried_through_verbatim(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """ "Unverifiable means not autonomous" needs the verdict to survive+ the hop, or the step reports success with nothing behind it."""+ _wire(+ monkeypatch,+ implementers=["crowdstrike"],+ response={+ "result": {+ "status": "succeeded",+ "summary": "isolated",+ "details": {"verification": "verified", "verification_reason": "device reports contained"},+ }+ },+ )+ report = await _run()+ assert report.verification == "verified"+ assert report.verification_reason == "device reports contained"++ async def test_an_execution_with_no_probe_reports_unverified_rather_than_blank(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A blank field and a confirmed one look identical to a reader."""+ _wire(monkeypatch, implementers=["crowdstrike"], response={"result": {"status": "succeeded", "details": {}}})+ report = await _run()+ assert report.executed is True+ assert report.verification == "unverified"+++class TestWhatItSendsOn:+ async def test_confidence_and_provenance_reach_the_action_service(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ sent = _wire(monkeypatch, implementers=["crowdstrike"])+ await _run(confidence=0.93, playbook_run_id="run-7", playbook_step_id="step-2")+ assert sent[0]["confidence"] == 0.93+ assert sent[0]["playbook_run_id"] == "run-7"+ assert sent[0]["playbook_step_id"] == "step-2"++ async def test_non_secret_instance_settings_travel_with_the_credentials(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """A vendor that needs a base URL is unusable without one, and a URL+ is configuration rather than a secret."""+ sent = _wire(+ monkeypatch,+ implementers=["crowdstrike"],+ connectors=[_Connector("crowdstrike", config={"base_url": "https://edr.internal", "unrelated": "x"})],+ )+ await _run()+ assert sent[0]["auth_config"]["base_url"] == "https://edr.internal"+ assert "unrelated" not in sent[0]["auth_config"]++ async def test_the_report_only_carries_fields_that_have_a_value(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """An empty string in a JSON report reads as an answer."""+ _wire(monkeypatch, implementers=["crowdstrike"], response={"result": {"status": "pending_approval", "details": {}}})+ body = (await _run()).as_dict()+ assert "verification" not in body+ assert body["executed"] is False+++class TestCapabilityGuard:+ @pytest.mark.parametrize("value", ["../../admin", "isolate_host/../x", "with space", "", "UPPER"])+ async def test_a_capability_that_could_steer_the_upstream_request_is_refused(self, value: str) -> None:+ """This path carries the service token, so the segment is checked+ rather than trusted — the same guard the browser-facing proxy uses."""+ with pytest.raises(actions_client.ActionsServiceError):+ await actions_client.vendors_for_capability(value)diff --git a/tests/test_upgrade_playbooks.py b/tests/test_upgrade_playbooks.pynew file mode 100644index 000000000..190f30949--- /dev/null+++ b/tests/test_upgrade_playbooks.py@@ -0,0 +1,146 @@+"""The upgrader the migration doc has told operators to run since v4.++The script did not exist. A migration doc that fails does so at exactly the+moment it is needed, which is why the test that matters here is not "the+function returns a dict" but "the output validates against the schema the+engine actually enforces" — checked against the real+`schemas/playbook.schema.json`, not a fixture copy of it.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import jsonschema+import pytest++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "scripts"))++import upgrade_playbooks as up # noqa: E402++SCHEMA = json.loads((ROOT / "schemas" / "playbook.schema.json").read_text())+++def _validate(doc: dict) -> list[str]:+ return [e.message for e in jsonschema.Draft7Validator(SCHEMA).iter_errors(doc)]+++def _v3(**step_overrides) -> dict:+ step = {"id": "s1", "name": "contain", "type": "isolate"}+ step.update(step_overrides)+ return {"name": "Legacy playbook", "trigger": {"on": "alert"}, "steps": [step]}+++class TestTheOutputIsActuallyValid:+ def test_a_v3_playbook_upgrades_into_something_the_schema_accepts(self) -> None:+ """The whole promise in one assertion."""+ legacy = _v3(+ on_error="stop",+ timeout=120,+ retry={"max_attempts": 3, "backoff": "exponential"},+ condition={"expr": "severity == 'high'", "language": "jmespath"},+ )+ assert _validate(legacy), "fixture assumption broken: the v3 shape should NOT validate"++ upgraded, changes, blockers = up.upgrade_playbook(legacy)++ assert blockers == []+ assert _validate(upgraded) == [], f"upgrade produced something the engine rejects: {_validate(upgraded)}"+ step = upgraded["steps"][0]+ assert step["type"] == "isolate_host"+ assert step["on_failure"] == "abort"+ assert step["timeout_seconds"] == 120+ assert step["retry_max"] == 3+ assert step["condition"] == "severity == 'high'"+ assert changes++ @pytest.mark.parametrize(+ ("old", "new"),+ sorted(up.STEP_TYPE_RENAMES.items()),+ )+ def test_every_declared_rename_lands_on_a_type_the_schema_declares(self, old: str, new: str) -> None:+ """A rename onto a type the schema does not declare would produce a+ file that fails the very lint the doc tells you to run next."""+ upgraded, _, blockers = up.upgrade_playbook(_v3(type=old))+ assert blockers == []+ assert upgraded["steps"][0]["type"] == new+ assert _validate(upgraded) == []++ def test_an_already_current_playbook_is_left_alone(self) -> None:+ """Re-running the upgrader must be a no-op, or nobody can run it twice."""+ current = json.loads((ROOT / "services" / "agents" / "data" / "playbooks" / "phishing-triage.playbook.json").read_text())+ upgraded, changes, blockers = up.upgrade_playbook(current)+ assert changes == []+ assert blockers == []+ assert upgraded == current+++class TestItRefusesRatherThanInvents:+ @pytest.mark.parametrize("step_type", sorted(up.UNMAPPABLE))+ def test_a_type_with_no_equivalent_is_reported_not_rewritten(self, step_type: str) -> None:+ """Mapping these onto a "nearest neighbour" is the defect that was+ removed from the NL drafter, where a `disable_user` step shipped as+ `investigate`."""+ upgraded, _, blockers = up.upgrade_playbook(_v3(type=step_type))+ assert blockers, f"{step_type} must be reported"+ assert step_type in blockers[0]+ assert upgraded["steps"][0]["type"] == step_type, "a blocked type must not be silently changed"++ def test_the_two_vocabularies_do_not_overlap(self) -> None:+ """A type in both tables would be renamed and reported at once."""+ assert not (set(up.STEP_TYPE_RENAMES) & set(up.UNMAPPABLE))++ def test_every_renamed_and_blocked_type_is_absent_from_the_current_schema(self) -> None:+ """These are v3 spellings. One still in the schema means the table+ is describing a rename that is not a rename."""+ declared = set(SCHEMA["definitions"]["PlaybookStep"]["properties"]["type"]["enum"])+ assert not (set(up.STEP_TYPE_RENAMES) & declared)+ assert not (set(up.UNMAPPABLE) & declared)+++class TestTheCommandLine:+ def test_check_mode_writes_nothing(self, tmp_path: Path) -> None:+ pack = tmp_path / "playbooks"+ pack.mkdir()+ target = pack / "legacy.playbook.json"+ original = json.dumps(_v3(on_error="stop"))+ target.write_text(original)++ code = up.main(["--dir", "playbooks", "--repo-root", str(ROOT), "--dir", str(pack)])++ assert code == 1, "'would change' is a non-zero answer so a script can branch on it"+ assert target.read_text() == original++ def test_write_mode_produces_a_file_that_passes_the_real_linter(self, tmp_path: Path) -> None:+ pack = tmp_path / "playbooks"+ pack.mkdir()+ target = pack / "legacy.playbook.json"+ target.write_text(json.dumps(_v3(on_error="stop", timeout=90)))++ assert up.main(["--repo-root", str(ROOT), "--dir", str(pack), "--write"]) == 0+ assert _validate(json.loads(target.read_text())) == []++ def test_a_blocked_file_exits_two_and_is_not_rewritten(self, tmp_path: Path) -> None:+ pack = tmp_path / "playbooks"+ pack.mkdir()+ target = pack / "loopy.playbook.json"+ original = json.dumps(_v3(type="loop"))+ target.write_text(original)++ assert up.main(["--repo-root", str(ROOT), "--dir", str(pack), "--write"]) == 2+ assert target.read_text() == original++ def test_finding_no_files_is_a_broken_scan_not_a_clean_bill_of_health(self, tmp_path: Path) -> None:+ """The same defect that let the lint job report "2/2 passed" over 62+ unchecked packs."""+ empty = tmp_path / "nothing"+ empty.mkdir()+ assert up.main(["--repo-root", str(ROOT), "--dir", str(empty)]) == 1++ def test_the_shipped_packs_need_no_upgrade(self) -> None:+ """They are v4 already; a non-zero answer here would mean the+ upgrader disagrees with the schema the packs pass."""+ assert up.main(["--repo-root", str(ROOT), "--dir", "playbooks"]) == 0