Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(kill-switch): the stop button now stops action dispatch, and stops claiming an MCP write surface (#1535)
Beenu Arorae85fa638b5ac
diff --git a/.github/workflows/action-durability-live.yml b/.github/workflows/action-durability-live.ymlindex 298f9c3c5..40bba1e5e 100644--- a/.github/workflows/action-durability-live.yml+++ b/.github/workflows/action-durability-live.yml@@ -235,3 +235,121 @@ jobs:exit 1fiecho "OK: with neither layer present another tenant's host is contained, and the suite goes red."++ # ── the kill switch actually stops this dispatcher ───────────────────+ #+ # Same Postgres, same runtime role, same reason to be live: the switch+ # is a row and the defect was that nothing read it. Parity 2.2+ # documented the switch as "checked first and separately by everything+ # that acts: closure in the triage worker, the actions dispatcher,+ # playbook dispatch and the MCP write tools" and `services/actions`+ # contained no reference to it at all, so an operator who pressed the+ # platform-wide stop kept dispatching isolations.+ #+ # Seeding uses the owner connection and only the owner connection,+ # because on this schema the global row (`tenant_id IS NULL`) satisfies+ # `WITH CHECK (tenant_id = current_tenant_id())` for no session at all.+ # That writability defect belongs to the PR making the global switch+ # engageable; what these cases grade is whether dispatch *reads* an+ # engaged switch, which was separately and completely false. The+ # dispatcher still reads as `aisoc_app`, under FORCE ROW LEVEL+ # SECURITY, which is the posture that ships.+ - name: An engaged kill switch stops the dispatcher, and a released one does not+ working-directory: services/actions+ env:+ AISOC_KILL_SWITCH_TEST_DSN: ${{ env.ACTIONS_DSN }}+ # aisoc-db-role: owner — seeds rows only; the global row satisfies WITH CHECK (tenant_id = current_tenant_id()) for no runtime session, and the dispatcher under test still reads as aisoc_app above+ AISOC_KILL_SWITCH_TEST_SEED_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PYTHONPATH: .+ run: python -m pytest tests/test_kill_switch_dispatch.py -v --tb=short -rs++ - name: Every case ran, none skipped+ working-directory: services/actions+ env:+ AISOC_KILL_SWITCH_TEST_DSN: ${{ env.ACTIONS_DSN }}+ # aisoc-db-role: owner — seeds rows only; the global row satisfies WITH CHECK (tenant_id = current_tenant_id()) for no runtime session, and the dispatcher under test still reads as aisoc_app above+ AISOC_KILL_SWITCH_TEST_SEED_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PYTHONPATH: .+ run: |+ set -euo pipefail+ python -m pytest tests/test_kill_switch_dispatch.py -q 2>&1 | tee /tmp/kill-switch-run.txt+ if grep -qE '[0-9]+ skipped' /tmp/kill-switch-run.txt; then+ echo "FAIL: a case skipped in the job whose whole purpose is to run it against a real switch."+ exit 1+ fi+ if ! grep -qE '[0-9]+ passed' /tmp/kill-switch-run.txt; then+ echo "FAIL: no case reported as passed."+ exit 1+ fi++ - name: The gate fails when dispatch stops consulting the switch+ working-directory: services/actions+ env:+ AISOC_KILL_SWITCH_TEST_DSN: ${{ env.ACTIONS_DSN }}+ # aisoc-db-role: owner — seeds rows only; the global row satisfies WITH CHECK (tenant_id = current_tenant_id()) for no runtime session, and the dispatcher under test still reads as aisoc_app above+ AISOC_KILL_SWITCH_TEST_SEED_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PYTHONPATH: .+ run: |+ set -euo pipefail+ cp app/live_actions/dispatcher.py /tmp/ks-dispatcher.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/live_actions/dispatcher.py")+ s = p.read_text()+ needle = " if switch.engaged:\n"+ if needle not in s:+ print("negative control could not find the kill-switch gate; it has been "+ "reshaped and this control no longer proves anything")+ sys.exit(1)+ p.write_text(s.replace(needle, " if False:\n", 1))+ PY+ set +e+ python -m pytest tests/test_kill_switch_dispatch.py -q >/dev/null 2>&1+ rc=$?+ set -e+ cp /tmp/ks-dispatcher.bak app/live_actions/dispatcher.py+ if [ "$rc" -eq 0 ]; then+ echo "FAIL: dispatch ignored an engaged switch and the suite stayed green."+ exit 1+ fi+ echo "OK: without the gate an engaged switch dispatches, and the suite goes red."++ - name: The gate fails when an unreadable switch is read as released+ working-directory: services/actions+ env:+ AISOC_KILL_SWITCH_TEST_DSN: ${{ env.ACTIONS_DSN }}+ # aisoc-db-role: owner — seeds rows only; the global row satisfies WITH CHECK (tenant_id = current_tenant_id()) for no runtime session, and the dispatcher under test still reads as aisoc_app above+ AISOC_KILL_SWITCH_TEST_SEED_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PYTHONPATH: .+ run: |+ set -euo pipefail+ cp app/services/kill_switch.py /tmp/ks-reader.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/kill_switch.py")+ s = p.read_text()+ needle = " unreadable=True,\n )\n"+ if needle not in s:+ print("negative control could not find the fail-closed return")+ sys.exit(1)+ p.write_text(s.replace(+ " return KillSwitchState(\n"+ " engaged=True,\n"+ ' scope="unknown",\n'+ ' reason="kill-switch state unreadable, refusing to dispatch",\n'+ " unreadable=True,\n"+ " )\n",+ " return _RELEASED\n", 1))+ PY+ set +e+ python -m pytest \+ "tests/test_kill_switch_dispatch.py::TestWhatHappensWhenTheSwitchCannotBeRead" \+ -q >/dev/null 2>&1+ rc=$?+ set -e+ cp /tmp/ks-reader.bak app/services/kill_switch.py+ if [ "$rc" -eq 0 ]; then+ echo "FAIL: a database that could not answer was read as 'nobody pressed it', and the suite stayed green."+ exit 1+ fi+ echo "OK: failing open on an unreadable switch goes red, as it must."diff --git a/docs/remediation/kill-switch-enforcement-reach.md b/docs/remediation/kill-switch-enforcement-reach.mdnew file mode 100644index 000000000..491651ad8--- /dev/null+++ b/docs/remediation/kill-switch-enforcement-reach.md@@ -0,0 +1,277 @@+# The kill switch stopped one of the four things it claimed to stop++`services/api/app/api/v1/endpoints/kill_switch.py` described the platform's+emergency stop as++> one boolean with a mandatory reason, checked first and separately by+> everything that acts: closure in the triage worker, the actions+> dispatcher, playbook dispatch and the MCP write tools.++One of those four was true.++This matters more than an inaccurate comment. An operator who engages a+control described as the platform-wide stop, watches automatic closure+halt, and concludes the platform is frozen, **stops looking for another way+to halt it** — while the actions dispatcher carries on isolating hosts and+disabling accounts at their vendors. A safety control that stops less than+it claims is worse than one that plainly does not exist. This repository's+own standard is that a mechanism nothing calls is treated as not existing;+the same standard applied to a *claim* means an unenforced enforcement point+is a false statement, not an aspiration.++## The verified inventory++Measured on `origin/main` at `3802d0dc`, before any change.++| Claimed enforcement point | Real? | Evidence |+|---|---|---|+| Closure in the triage worker | **yes** | `auto_triage_agent.py:558` calls `closure.decide()`, which calls `resolve_closure_policy`, which calls `kill_switch_engaged` before anything else |+| The actions dispatcher | **no** | `git grep -i 'kill.?switch' -- services/actions` returned zero matches, in any form |+| Playbook dispatch | **no** | zero matches in `services/agents/app/playbook/` and in `services/api/app/services/playbook_step_dispatch.py`. The single hit in `case_postmortem.py:223` is the string `"kill switch"` in a containment-phrase keyword list, unrelated |+| The MCP write tools | **no, and there is no such surface** | `services/mcp` exposes one tool touching the response surface, `aisoc_preview_action`. It is dry-run only; `DRY_RUN_PATH` is a module constant and `tests/actions.test.ts` asserts `/dispatch` appears nowhere in `src/` |++So: one of four enforced, two absent, and one that could not be enforced+because it does not exist.++### The per-tenant switch has the same reach, and a different second problem++The reader is one function, `kill_switch_engaged(pool, tenant_id)`, and it+resolves both scopes in a single query. Both scopes therefore had **exactly+the same reach** — closure only — and no scope-specific gap in enforcement.++They differ on the write side rather than the read side. On `main` the+tenant switch is engageable through `POST /api/v1/kill-switch/engage`. The+global switch has no engage route at all, and would not work if it had one:++```+INSERT ... (tenant_id = NULL) as aisoc_app, no tenant bound -> ERROR: new row violates row-level security policy+INSERT ... (tenant_id = NULL) as aisoc_app, tenant bound -> ERROR: new row violates row-level security policy+INSERT ... (tenant_id = <t>) as aisoc_app, tenant bound -> INSERT 0 1+```++`aisoc_kill_switch` carries `WITH CHECK (tenant_id = current_tenant_id())`.+For the global row `tenant_id` is `NULL`, and `NULL = NULL` is `NULL`, not+true, so the check refuses it for every session the runtime role can open.+This was reproduced here independently and is **not fixed in this change**:+[#1534](https://github.com/beenuar/AiSOC/pull/1534) owns it and carries the+migration. It is recorded because the two halves compound — before both land,+the platform-wide stop could neither be set nor, if set, obeyed by dispatch.++### Other documented-but-absent enforcement, in the same family++* **The claim-to-gate matrix cites a document that does not carry the+ claim.** `docs/audit/CLAIM_TO_GATE_MATRIX.md` points at+ `apps/docs/docs/operations/shadow-mode.md` for "Autonomous closure and+ dispatch can be stopped without a restart". That file contains zero+ occurrences of the string "kill".+* **There is no operator documentation for the switch anywhere.** No page+ under `apps/docs/`, no console surface under `apps/web/src/`. An operator+ cannot find out what it does except by reading the module that was wrong+ about it. Still open; the product surface is #1534's.++## What was implemented, and what was corrected++Two routes were available per point. The choice was made per point.++### Implemented — the actions dispatcher++`services/actions/app/live_actions/dispatcher.py::dispatch()` now reads the+switch **before** translating credentials and before looking up an executor.+This is the point that touches a customer's estate, so enforcement is the+only honest answer: correcting the claim here would have meant publishing+"the stop button does not stop response actions".++Checked first and separately from the autonomy policy, for the reason the+closure path already records: it is what somebody reaches for at 3am and it+must not depend on tier rows, capability contracts or a registered executor+being correct. It also closes a gap the autonomy gate has by construction —+that gate runs only `if not request.dry_run and (action_type is not None or+capability in CAPABILITY_CONTRACTS)`, so a capability with neither is+ungoverned. The switch has no such condition.++### Implemented — playbook dispatch, at the same line++Deliberately **not** a second check inside `playbook_step_dispatch.py`.+Playbook steps reach a vendor through exactly one chain:++```+action_bridge.py:159 POST /api/v1/playbook-steps/dispatch+ -> playbook_step_dispatch.dispatch_step()+ -> actions_client.dispatch_live_action()+ -> POST /api/v1/live-actions/dispatch+ -> live_actions_router.py:176 dispatch(request)+```++There is no second path. `playbook_step_dispatch.py` already states the+principle in its own docstring — "A policy mirrored in two services is a+policy that is off in whichever one is more generous" — and a second check+would be a second thing to forget. The same chokepoint also covers the+`/dry-run` sibling route, the agent loop, phishing purge and the phishing+report intake worker, because all of them terminate at `dispatch()`.++A test drives the HTTP route itself rather than only the function, because+"the function refuses" and "the route every caller actually uses refuses"+are different claims.++### Corrected — the MCP write tools++There are none, so there was nothing to enforce, and enforcement would have+meant inventing a surface in order to gate it.++The sentence was worse than an unenforced claim. It told a reader the MCP+server could perform actions. That was the more alarming half, and it was+never true: the server's action tool is preview-only and a test asserts the+dispatch path appears nowhere in its source. The docstring now says what the+switch stops, what it does not, and states plainly that this point was+removed because the surface does not exist.++### Decided — dry runs are stopped too++A preview is only credentials-free while the strip list in+`live_actions/builtins.py` matches what each client factory reads, and+`services/actions/app/executors/siem.py` records a release where it did not:++> "the factory still builds a client and a 'dry run' calls the customer's+> production SIEM. That is exactly what happened."++During a declared freeze that is not a risk worth carrying for the+convenience of a preview, and an operator who pressed the stop button did+not mean "stop, except for previews". The cost is real and is stated here+rather than hidden: while the switch is engaged, the console's "preview what+this would do" button and the MCP preview tool both return `blocked`.++## The fail-open / fail-closed trade-off++An unreadable switch **refuses**. A control that reads "I cannot tell" as+"nobody pressed it" is not a stop control.++The cost of that choice is that a database outage stops automated response+on deployments that have a database. That is a real cost and it is bounded+three ways, deliberately rather than by assumption:++1. **A deployment with no DSN configured is not affected at all.** No+ database means no switch table, which is a configuration and not a read+ failure — the same line `resolve_tenant_policy` already draws for the+ autonomy tier. Failing closed here would brick every single-tenant+ install in order to guard a row that cannot exist on it.+2. **A deployment that has a database is already degraded by the same+ outage.** `resolve_tenant_policy` falls to its notify-only floor (L1) on+ an unreadable read, so unattended execution has already stopped. Failing+ closed on the switch is consistent with the posture next door rather than+ a new outage mode.+3. **Humans are unaffected.** `BLOCKED` is a refusal to act automatically.+ Analysts keep triaging, the console keeps working, and an operator can+ still act directly at the vendor.++Two further bounds in the implementation: the connection carries a five+second timeout so a hung database becomes a refusal rather than a dispatch+that never returns, and **only successful reads are cached** — caching a+failure would turn one refused connection into seconds of refused dispatch+after the database came back.++The refusal names the read failure, not the switch:+`blocked_by: kill_switch_unreadable`, with a summary saying the state is+unreadable. Reporting it as "kill switch engaged" would send an operator to+look for a switch nobody pressed, which is the failure mode where a+diagnostic names the wrong subsystem — worse than a vague one.++## What an operator should now expect++With the switch engaged, in either scope:++* no response action reaches a vendor, from any caller — the REST route, the+ agent loop, a playbook step, phishing purge, or a preview;+* no alert is closed automatically;+* every refused action comes back **`blocked`**, not `failed`. `failed`+ invites a retry and the retry is refused identically; `blocked` carries+ `blocked_by: kill_switch`, the scope, and the operator's own reason, so a+ console can say which control stopped it rather than leaving a reader to+ guess between the switch and the tier ladder;+* `executed` — the platform's single word for "a vendor was touched" — is+ never reported, because the executor is not looked up, let alone called.++With the switch released, everything dispatches as before. That direction is+asserted too: a stop control stuck on is as broken as one stuck off, and+this repository has a recorded case where a fail-closed fix withheld every+grant on every deployment and passed its drifted-tenant test perfectly,+caught only by the healthy-tenant control.++## Still unenforced, and stated rather than implied++* **There is no console control for the kill switch in either scope.** Both+ are API-only. An operator at 3am needs `curl`.+* **The global switch cannot be written by the runtime role.** Reproduced+ above; owned by #1534.+* **No operator-facing documentation page exists** for the switch.+* **The agents service and the actions service read the switch with two+ separate functions.** They cannot share one — both name their top-level+ package `app`, so importing one into the other shadows it. The duplication+ is deliberate and is the same shape as `autonomy_evidence_rules`, which+ `services/api` carries byte-identical to `services/actions`. The DSN+ resolution *is* shared, through `tenant_policy.resolve_dsn`, with a test+ asserting both readers use the same function: two resolvers could disagree+ about whether a deployment has a database and the generous one would win.+* **The matrix row** that #1534 rewrites states "An engaged switch stops+ closure and not dispatch". This change falsifies the second half.+ Whichever of the two pull requests lands second has to correct it; it is+ not edited here, because editing a row another open branch is rewriting+ produces a conflict rather than a correction.++## Proof++Three commits in order, each run and recorded.++**1. The test fails on the unfixed tree**, driven through the real+`dispatch()` against real Postgres 16 with all 121 migrations applied, read+by the `aisoc_app` runtime role under `FORCE ROW LEVEL SECURITY`. Only the+vendor is replaced, by a recorder that counts calls:++```+8 failed, 4 passed+FAILED ... test_a_global_switch_stops_dispatch+FAILED ... test_a_tenant_switch_stops_that_tenants_dispatch+FAILED ... test_the_reason_names_the_switch_even_when_policy_would_also_refuse+FAILED ... test_a_dry_run_is_stopped_too+FAILED ... test_blocked_is_not_reported_as_failed+FAILED ... test_the_route_every_caller_reaches_is_governed_too+FAILED ... test_an_unreadable_switch_blocks_rather_than_permits+FAILED ... test_unreadable_does_not_claim_somebody_pressed_it+```++The four that pass are the positive controls — released switch, no row, no+database, and one tenant's switch not stopping another. They pass trivially+on a tree that never checks, which is exactly why they are there: they+cannot prove the defect, only catch a fix that stops everything forever.++**2. The fix**: `12 passed`.++**3. Negative controls**, each removing one line and requiring red:++| Control | Result |+|---|---|+| `if switch.engaged:` → `if False:` | `8 failed, 4 passed`; restored → `12 passed` |+| unreadable returns `_RELEASED` instead of refusing | `2 failed, 1 passed`; restored → `3 passed` |++Both are wired as steps in `action-durability-live.yml`, which already+provisions this exact stack, so they run on every pull request rather than+having been demonstrated once. Each control refuses to run if it cannot find+the line it removes, so a reshaped gate fails loudly instead of silently+proving nothing.++One caveat, stated rather than buried: the **seeding** connection is the+owner's, declared inline with `aisoc-db-role: owner` and a reason, because+`check_runtime_db_role.py` correctly refuses an undeclared superuser DSN on+a live surface — seeding as owner is exactly the workaround that hid the+global row's unwritability. It is used here for one reason and the reason is+narrow: until migration 123 lands, no runtime session can put the global row+in place at all, and these cases grade the *reader*. The dispatcher under+test still connects as `aisoc_app` under `FORCE ROW LEVEL SECURITY`. Once+#1534 lands, the seed DSN can be the runtime role and the marker deleted.++A note on the chosen `search_siem` capability: `isolate_host` is HIGH blast+and the autonomy gate refuses it at every tier, so a test watching it stop+would have passed on the unfixed tree for a reason unrelated to the switch.+`search_siem` is contracted `AUTOMATIC` and really does execute, so "it+stopped" can only mean the switch stopped it. `isolate_host` still appears,+asserting that the *reason* names the switch — two controls that both refuse+are one control an operator cannot release.diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.pyindex 2308f28d5..28ce323bd 100644--- a/services/actions/app/live_actions/dispatcher.py+++ b/services/actions/app/live_actions/dispatcher.py@@ -5,6 +5,11 @@ The dispatcher is the single entry point used by the REST router and byinternal callers (agent loop, playbook engine). It enforces these invariantsso individual executors never have to think about them:+ 0. **The kill switch is checked before anything else.** Global or per+ tenant, engaged or unreadable, every request returns BLOCKED without+ an executor being looked up. Parity 2.2 documented this and never+ built it: the switch stopped automatic closure and this dispatcher+ carried on isolating hosts.1. **Unknown (vendor, capability) returns FAILED, not 500.** Callersget a structured :class:`LiveActionResult` so the agent loop candecide whether to fall back to a different vendor.@@ -50,6 +55,7 @@ from app.services.autonomy_safety import (rollback_capability,)from app.services.credential_resolver import resolve_params+from app.services.kill_switch import KillSwitchState, kill_switch_statefrom app.services.maturity import _AUTO_ALLOWED_AT_TIER, MaturityTierfrom app.services.tenant_policy import TenantPolicy, resolve_tenant_policyfrom app.services.verification import PostActionVerifier, VerificationOutcome@@ -417,6 +423,38 @@ async def _verify_effect(return result.model_copy(update={"details": details})+def _stopped_by_kill_switch(request: LiveActionRequest, state: KillSwitchState) -> LiveActionResult:+ """A visible refusal that names the switch, and is not a failure.++ Three things this is deliberately not. Not SUCCEEDED, obviously. Not+ FAILED, because FAILED invites a retry and the next attempt is refused+ for the same reason — an agent loop would spend a freeze retrying. And+ not silent: ``blocked_by`` is a machine-readable field so a console or a+ playbook report can say *which* control stopped this, rather than+ leaving an operator to guess between the switch and the tier ladder.++ ``executed`` is the platform's single word for "a vendor was touched",+ and nothing here touched one: the executor is not looked up, let alone+ called, before this returns.+ """+ detail = (+ "kill-switch state unreadable, refusing to dispatch" if state.unreadable else f"kill switch engaged ({state.scope}): {state.reason}"+ )+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.BLOCKED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary=f"{request.capability} on {request.target or 'target'}: not dispatched — {detail}",+ details={+ "blocked_by": "kill_switch_unreadable" if state.unreadable else "kill_switch",+ "kill_switch_scope": state.scope,+ "kill_switch_reason": state.reason,+ "vendor_contacted": False,+ },+ )++def _not_executed(request: LiveActionRequest, status: LiveActionStatus, decision: AutonomyDecision) -> LiveActionResult:return LiveActionResult(request_id=request.request_id,@@ -449,6 +487,32 @@ async def dispatch(request: LiveActionRequest) -> LiveActionResult:dry_run=request.dry_run,)+ # ── The kill switch, before anything else ────────────────────────────+ #+ # First, and separately from the autonomy policy, because it is what+ # somebody reaches for at 3am and it must not depend on tier rows,+ # contracts or a registered executor being correct. Every other refusal+ # in this function is a judgement about one action; this one is an+ # operator saying stop.+ #+ # Dry runs are stopped too, which is a decision rather than an+ # oversight. A preview is only credentials-free if the strip list in+ # `builtins` matches what each client factory reads, and+ # `executors/siem.py` records what happened when it did not: "a 'dry+ # run' calls the customer's production SIEM. That is exactly what+ # happened." During a declared freeze that is not a risk worth carrying+ # for the convenience of a preview, and an operator who pressed the stop+ # button did not mean "stop, except for previews".+ switch = await kill_switch_state(str(request.tenant_id) if request.tenant_id else None)+ if switch.engaged:+ log.warning(+ "live_action.blocked_by_kill_switch",+ scope=switch.scope,+ unreadable=switch.unreadable,+ reason=switch.reason,+ )+ return _stopped_by_kill_switch(request, switch)+# Phase B2 — translate connector-style credentials into executor params.if request.auth_config:resolved = resolve_params(request.vendor_id, request.auth_config, extra=request.params)diff --git a/services/actions/app/services/kill_switch.py b/services/actions/app/services/kill_switch.pynew file mode 100644index 000000000..fce9a964d--- /dev/null+++ b/services/actions/app/services/kill_switch.py@@ -0,0 +1,200 @@+"""Is the stop button pressed, read from the service that touches vendors.++Parity plan 2.2 claimed the kill switch was "checked first and separately by+everything that acts: closure in the triage worker, the actions dispatcher,+playbook dispatch and the MCP write tools". Only the first was true. Until+this module existed, ``services/actions`` contained no reference to the+switch in any form, so an operator who engaged the platform-wide stop and+watched automatic closure halt was still dispatching isolations and account+disables at their vendors.++Why a second reader rather than importing the first+---------------------------------------------------+``services/agents/app/closure/policy.py`` reads the same two rows, and this+is not that module imported. It cannot be: both services name their+top-level package ``app``, so importing one into the other shadows it. The+duplication is the same shape as ``autonomy_evidence_rules``, which+``services/api`` carries byte-identical to this service, and it carries the+same risk — a safety control two services define differently is off in+whichever one is more generous. What stops the two drifting here is that+there is nothing to drift: both ask one question of one table, "is a row+engaged for the global scope or this tenant", and the SQL below is the whole+definition.++The DSN itself is genuinely shared, from :func:`tenant_policy.resolve_dsn`,+because "does this deployment have a database" is a question the autonomy+policy and the stop button must not answer differently.++What an unreadable switch means+-------------------------------+Dispatch fails **closed**, and the trade-off is deliberate rather than+assumed. A stop control that reads "I cannot tell" as "nobody pressed it"+is not a stop control: the operator engaged it, believes the platform is+frozen, and stops looking for another way to halt it. The cost is that a+database outage stops response actions on deployments that have a database.+That cost is bounded by three things:++* a deployment with **no** DSN configured is not affected at all. No+ database means no switch table, which is a configuration, not a failure —+ the same line ``resolve_tenant_policy`` already draws, and failing closed+ there would brick every single-tenant install to guard a row that cannot+ exist on it;+* a deployment that *has* a database is already degraded by the same+ outage. ``resolve_tenant_policy`` falls to its notify-only floor on an+ unreadable read, so unattended execution has stopped regardless;+* the refusal is :class:`LiveActionStatus.BLOCKED` with a reason naming the+ read failure, not the switch. Sending an operator to look for a switch+ nobody pressed is the failure mode where a diagnostic names the wrong+ subsystem, and that is worse than a vague one.++Analysts keep working through all of it: BLOCKED is a refusal to act+automatically, not an outage of the console.+"""++from __future__ import annotations++import os+import time+from dataclasses import dataclass+from typing import Any++import structlog++from app.services.tenant_policy import resolve_dsn++logger = structlog.get_logger(__name__)++#: Seconds a resolved switch state is reused. Short on purpose: parity 2.2+#: requires the switch to take effect "within one poll interval, without a+#: restart", and a long cache would make that untrue. Only a *successful*+#: read is cached — caching a failure would turn one refused connection into+#: several seconds of refused dispatch after the database came back.+_CACHE_TTL_ENV = "AISOC_KILL_SWITCH_TTL_SECONDS"+_DEFAULT_TTL_SECONDS = 5.0++#: Bounded, because this sits in front of every dispatch. A database that+#: hangs must become a refusal quickly rather than a dispatch that never+#: returns.+_CONNECT_TIMEOUT_SECONDS = 5.0++_cache: dict[str, tuple[float, KillSwitchState]] = {}+++@dataclass(frozen=True)+class KillSwitchState:+ """Whether to refuse, and the sentence an operator will read.++ ``unreadable`` is kept distinct from ``engaged`` rather than folded into+ one boolean. Both refuse; they are not the same event, and an operator+ told the wrong one debugs the wrong thing.+ """++ engaged: bool+ scope: str = ""+ reason: str = ""+ unreadable: bool = False++ def __bool__(self) -> bool:+ return self.engaged+++_RELEASED = KillSwitchState(engaged=False)+++def _ttl_seconds() -> float:+ raw = os.environ.get(_CACHE_TTL_ENV, "")+ if not raw.strip():+ return _DEFAULT_TTL_SECONDS+ try:+ return max(0.0, float(raw))+ except ValueError:+ logger.warning("kill_switch.bad_ttl_env", value=raw.strip()[:32])+ return _DEFAULT_TTL_SECONDS+++def reset_cache() -> None:+ """Drop the cache. For tests, and for a forced reload."""+ _cache.clear()+++def _cached(key: str) -> KillSwitchState | None:+ hit = _cache.get(key)+ if hit is None:+ return None+ expires, value = hit+ if time.monotonic() >= expires:+ _cache.pop(key, None)+ return None+ return value+++async def _fetch(dsn: str, tenant_id: str | None) -> list[Any]:+ import asyncpg # noqa: PLC0415 — optional at import time; only needed with a DSN++ conn = await asyncpg.connect(dsn, timeout=_CONNECT_TIMEOUT_SECONDS)+ try:+ return list(+ await conn.fetch(+ """+ SELECT tenant_id, reason+ FROM aisoc_kill_switch+ WHERE engaged = TRUE+ AND (tenant_id IS NULL OR tenant_id = $1::uuid)+ -- Global first: when both are engaged, the platform-wide+ -- one is the one the tenant cannot release, so naming the+ -- tenant's would send them to a switch that changes nothing.+ ORDER BY tenant_id NULLS FIRST+ """,+ str(tenant_id) if tenant_id is not None else None,+ )+ )+ finally:+ await conn.close()+++async def kill_switch_state(tenant_id: str | None) -> KillSwitchState:+ """Whether action dispatch is frozen for this tenant, and why.++ Either scope engaged is enough to refuse: the platform operator can stop+ everything and a tenant can stop their own, and neither needs the+ other's agreement.++ A ``tenant_id`` of ``None`` still consults the global row. An action with+ no tenant on it is not an action outside the platform-wide stop.+ """+ dsn = resolve_dsn()+ if dsn is None:+ # No database is a configuration, not a read failure. See the module+ # docstring: failing closed here stops deployments that cannot have+ # a switch at all.+ return _RELEASED++ key = f"kill:{tenant_id or '-'}"+ hit = _cached(key)+ if hit is not None:+ return hit++ try:+ rows = await _fetch(dsn, tenant_id)+ except Exception as exc: # noqa: BLE001 — a database that cannot answer is not a "no"+ logger.warning(+ "kill_switch.unreadable",+ tenant_id=str(tenant_id),+ error=str(exc)[:300],+ refusing=True,+ )+ return KillSwitchState(+ engaged=True,+ scope="unknown",+ reason="kill-switch state unreadable, refusing to dispatch",+ unreadable=True,+ )++ for row in rows:+ scope = "global" if row["tenant_id"] is None else "tenant"+ state = KillSwitchState(engaged=True, scope=scope, reason=str(row["reason"]))+ _cache[key] = (time.monotonic() + _ttl_seconds(), state)+ return state++ _cache[key] = (time.monotonic() + _ttl_seconds(), _RELEASED)+ return _RELEASEDdiff --git a/services/actions/app/services/tenant_policy.py b/services/actions/app/services/tenant_policy.pyindex 034d7865f..4ca7ed31f 100644--- a/services/actions/app/services/tenant_policy.py+++ b/services/actions/app/services/tenant_policy.py@@ -137,12 +137,18 @@ def _env_tier() -> MaturityTier:return MaturityTier.L1_NOTIFY-def _dsn() -> str | None:+def resolve_dsn() -> str | None:"""Resolve an asyncpg-compatible DSN, or None when no database is set.Accepts the SQLAlchemy form the API uses (`postgresql+asyncpg://`) as wellas the plain pgx form `services/ingest` uses, because both spellings arealready present in deployed environments.++ Public because `kill_switch` reads the same database on the same request+ and must agree with this module about whether one is configured. Two+ resolvers answering differently would mean the autonomy policy and the+ stop button disagree about whether this deployment has a database, and+ the generous one would win."""raw = os.environ.get("DATABASE_DSN") or os.environ.get("DATABASE_URL") or ""raw = raw.strip()@@ -355,7 +361,7 @@ async def _load_earned_verbs(conn: Any, tenant_id: str) -> dict[str, str]:async def resolve_tenant_policy(tenant_id: str | UUID | None) -> TenantPolicy:"""Resolve the autonomy policy that governs this tenant's actions."""- dsn = _dsn()+ dsn = resolve_dsn()if tenant_id is None or dsn is None:# Single-tenant or no database: the environment value is the operator's# explicit, documented choice.diff --git a/services/actions/tests/test_kill_switch_dispatch.py b/services/actions/tests/test_kill_switch_dispatch.pynew file mode 100644index 000000000..5f644881e--- /dev/null+++ b/services/actions/tests/test_kill_switch_dispatch.py@@ -0,0 +1,411 @@+"""An engaged kill switch stops the actions dispatcher.++The switch was documented as the platform-wide stop and reached one caller.+``services/api/app/api/v1/endpoints/kill_switch.py`` said it was "checked+first and separately by everything that acts: closure in the triage worker,+the actions dispatcher, playbook dispatch and the MCP write tools", and+``git grep -i kill.switch -- services/actions`` returned nothing at all. An+operator who pressed it believed vendor actions had stopped; isolations and+account disables carried on.++Why the vendor is the only thing replaced+-----------------------------------------+``dispatch()`` is the real dispatcher, the switch reader runs its real query+against a real Postgres, and the executor is a recorder that counts calls. A+fake dispatcher or a fake reader would answer whatever it was asked, and the+whole defect was that nothing asked.++Why ``search_siem`` and not ``isolate_host`` for the blocking cases+------------------------------------------------------------------+``isolate_host`` is HIGH blast and the autonomy gate refuses it at every+tier, so a test that watched it stop would have passed on the unfixed tree+for a reason that had nothing to do with the switch. ``search_siem`` is+contracted AUTOMATIC and really does execute, so "it stopped" can only mean+the switch stopped it. ``isolate_host`` still appears below, asserting the+*reason* names the switch: two controls that both refuse are one control an+operator cannot release, so the switch has to be legible as the cause.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio+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++#: Set by `action-durability-live.yml`, which already stands up Postgres as+#: the `aisoc_app` runtime role with every migration applied. Gated on an+#: explicit variable rather than on whether a connection happens to succeed:+#: a live case that silently degrades to a skip is a green run that measured+#: nothing.+_LIVE_DSN = os.environ.get("AISOC_KILL_SWITCH_TEST_DSN", "")++#: Privileged connection used only to seed rows. See :class:`_Switch`.+#: Falls back to the runtime DSN so that once the global row is writable by+#: the runtime role, one variable is enough.+_SEED_DSN = os.environ.get("AISOC_KILL_SWITCH_TEST_SEED_DSN", "") or _LIVE_DSN++live_only = pytest.mark.skipif(+ not _LIVE_DSN,+ reason="needs a real Postgres with migration 078 applied; set AISOC_KILL_SWITCH_TEST_DSN",+)+++class _RecordingExecutor:+ """Counts what reached the vendor. Nothing else about it is interesting.++ `calls` is the assertion that matters: a dispatcher that returns BLOCKED+ *after* contacting the vendor has not stopped anything, and a status+ string alone cannot tell the two apart.+ """++ def __init__(self, action_type: ActionType = ActionType.SEARCH_SIEM) -> None:+ self._legacy_action_type = action_type+ self.calls: list[LiveActionRequest] = []++ async def execute(self, request: LiveActionRequest) -> LiveActionResult:+ self.calls.append(request)+ return LiveActionResult(+ request_id=request.request_id,+ status=LiveActionStatus.SUCCEEDED,+ capability=request.capability,+ vendor_id=request.vendor_id,+ summary="vendor was contacted",+ )+++def recorder(monkeypatch: pytest.MonkeyPatch) -> _RecordingExecutor:+ executor = _RecordingExecutor()+ monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: executor)+ return executor+++class _Switch:+ """Seeds the real table so the real reader can be measured against it.++ Writes SQL rather than calling the API handlers because the two services+ cannot share an interpreter — both name their top-level package ``app``,+ so importing one shadows the other.++ Two DSNs, and the distinction is load-bearing. ``dsn`` is the runtime+ role the dispatcher reads with and is the thing under test. ``seed_dsn``+ is a privileged connection used only to put rows in place, because on+ ``main`` the global row cannot be written by the runtime role at all:+ ``aisoc_kill_switch`` carries ``WITH CHECK (tenant_id =+ current_tenant_id())`` and a NULL ``tenant_id`` satisfies it for no+ session, bound or unbound. That writability defect is reproduced here+ and owned by the PR that makes the global switch engageable; what these+ cases measure is whether dispatch *reads* an engaged switch, which is a+ separate question and was separately false.+ """++ def __init__(self, dsn: str, seed_dsn: str) -> None:+ self.dsn = dsn+ self.seed_dsn = seed_dsn++ async def _run(self, sql: str, *args: object) -> None:+ import asyncpg++ conn = await asyncpg.connect(self.seed_dsn, timeout=10.0)+ try:+ await conn.execute(sql, *args)+ finally:+ await conn.close()++ async def new_tenant(self) -> uuid.UUID:+ tenant = uuid.uuid4()+ await self._run(+ "INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3)",+ tenant,+ f"kill-switch-{tenant}",+ f"ks-{tenant}",+ )+ return tenant++ async def engage(self, tenant: uuid.UUID | None, reason: str) -> None:+ await self._run(+ """+ INSERT INTO aisoc_kill_switch (id, tenant_id, engaged, reason, engaged_by)+ VALUES ($1, $2, TRUE, $3, '[email protected]')+ """,+ uuid.uuid4(),+ tenant,+ reason,+ )++ async def release(self, tenant: uuid.UUID | None) -> None:+ await self._run(+ "UPDATE aisoc_kill_switch SET engaged = FALSE WHERE tenant_id IS NOT DISTINCT FROM $1",+ tenant,+ )+++@pytest_asyncio.fixture+async def switch(monkeypatch: pytest.MonkeyPatch) -> _Switch:+ """A clean switch table per test, and no caching.++ The reader caches a resolved state for a few seconds so the hot path does+ not pay a round trip per action. Left alone between tests that caches one+ test's verdict into the next, which would make a stop look like it worked+ when it was a leftover. Turning the TTL off is the honest way to get a+ cold read: a test that reaches into the module's cache would also be a+ test that passes when the cache is the only thing working.+ """+ import asyncpg++ monkeypatch.setenv("AISOC_KILL_SWITCH_TTL_SECONDS", "0")+ conn = await asyncpg.connect(_SEED_DSN, timeout=10.0)+ try:+ await conn.execute("DELETE FROM aisoc_kill_switch")+ finally:+ await conn.close()+ return _Switch(_LIVE_DSN, _SEED_DSN)++[email protected](autouse=True)+def _permissive_tenant_policy(monkeypatch: pytest.MonkeyPatch) -> None:+ """Remove every *other* reason to refuse.++ The tenant policy is stubbed and the switch reader is not. That is the+ point: if anything but the switch can explain a refusal, the test proves+ nothing about the switch.+ """++ async def _resolve(tenant_id): # noqa: ANN001, ANN202+ return TenantPolicy(tier=MaturityTier.L4_AUTOMATE, from_store=True)++ monkeypatch.setattr(dispatcher_mod, "resolve_tenant_policy", _resolve)+++def _request(**overrides) -> LiveActionRequest:+ payload = {+ "request_id": uuid.uuid4(),+ "capability": "search_siem",+ "vendor_id": "splunk",+ "target": "index=main",+ "dry_run": False,+ "requested_by": "[email protected]",+ }+ payload.update(overrides)+ return LiveActionRequest(**payload)+++# ── live: a real switch, a real reader, a real database ──────────────────+++@live_only+class TestAnEngagedSwitchStopsTheVendor:+ async def test_a_global_switch_stops_dispatch(self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch) -> None:+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(None, "platform-wide freeze: investigating runaway containment")++ result = await dispatch(_request(tenant_id=tenant))++ assert recorder.calls == [], "the vendor was contacted while the platform-wide stop was engaged"+ assert result.status is LiveActionStatus.BLOCKED+ assert result.details.get("blocked_by") == "kill_switch"+ assert result.details.get("kill_switch_scope") == "global"++ async def test_a_tenant_switch_stops_that_tenants_dispatch(+ self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(tenant, "tenant freeze while we work out what the agent did")++ result = await dispatch(_request(tenant_id=tenant))++ assert recorder.calls == []+ assert result.status is LiveActionStatus.BLOCKED+ assert result.details.get("kill_switch_scope") == "tenant"++ async def test_one_tenants_switch_does_not_stop_another(+ self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """A stop control that over-blocks is as broken as one that under-blocks."""+ frozen = await switch.new_tenant()+ working = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(frozen, "this tenant only, please")++ result = await dispatch(_request(tenant_id=working))++ assert len(recorder.calls) == 1, "an unrelated tenant's switch stopped this tenant's action"+ assert result.status is LiveActionStatus.SUCCEEDED++ async def test_the_reason_names_the_switch_even_when_policy_would_also_refuse(self, switch, monkeypatch: pytest.MonkeyPatch) -> None:+ """`isolate_host` is refused by the tier ladder too. Say which one.++ Two controls that both refuse are one control an operator cannot+ release: they lift the switch, the action still refuses, and they go+ looking for a second switch that does not exist.+ """+ tenant = await switch.new_tenant()+ isolator = _RecordingExecutor(ActionType.ISOLATE_HOST)+ monkeypatch.setattr(registry, "get_executor", lambda vendor, cap: isolator)+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(None, "platform-wide freeze while containment is reviewed")++ result = await dispatch(_request(capability="isolate_host", vendor_id="crowdstrike", target="WIN-DC01", tenant_id=tenant))++ assert isolator.calls == []+ assert result.details.get("blocked_by") == "kill_switch"+ assert "kill switch" in result.summary.lower()++ async def test_a_dry_run_is_stopped_too(self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch) -> None:+ """A preview is only credentials-free if the strip list is right.++ `services/actions/app/executors/siem.py` records what happens when it+ is not: "a 'dry run' calls the customer's production SIEM. That is+ exactly what happened". During a declared freeze that is the one risk+ not worth carrying for the convenience of a preview.+ """+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(None, "freeze everything, including previews")++ result = await dispatch(_request(tenant_id=tenant, dry_run=True))++ assert recorder.calls == []+ assert result.status is LiveActionStatus.BLOCKED++ async def test_blocked_is_not_reported_as_failed(self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch) -> None:+ """FAILED invites a retry. A deliberate stop is not a failure."""+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(None, "a deliberate freeze, not an outage")++ result = await dispatch(_request(tenant_id=tenant))++ assert result.status is not LiveActionStatus.FAILED+ assert result.status is not LiveActionStatus.SUCCEEDED+ assert result.error is None, "a blocked action has nothing to retry and no error to report"+++@live_only+class TestTheSwitchReleasedLetsWorkThrough:+ """The positive control. A stop control stuck on is a product that stopped."""++ async def test_a_released_switch_does_not_block(self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch) -> None:+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ await switch.engage(tenant, "freeze for a moment")+ await switch.release(tenant)++ result = await dispatch(_request(tenant_id=tenant))++ assert len(recorder.calls) == 1, "the switch was released and the action still did not run"+ assert result.status is LiveActionStatus.SUCCEEDED++ async def test_a_deployment_with_no_switch_row_dispatches_normally(+ self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """The overwhelmingly common case: nobody has ever pressed it."""+ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)++ result = await dispatch(_request(tenant_id=tenant))++ assert len(recorder.calls) == 1+ assert result.status is LiveActionStatus.SUCCEEDED++ async def test_the_route_every_caller_reaches_is_governed_too(+ self, switch, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Playbook dispatch terminates here, so this is where it is stopped.++ `action_bridge.py` posts to the API's `/playbook-steps/dispatch`,+ which resolves credentials and calls `actions_client`, which posts to+ `POST /api/v1/live-actions/dispatch` — this route. Gating the shared+ chokepoint rather than adding a second check in the playbook service+ is the same reasoning `playbook_step_dispatch.py` already records: a+ policy mirrored in two services is off in whichever is more generous.+ """+ from app.core.config import get_settings+ from app.main import app+ from fastapi.testclient import TestClient++ tenant = await switch.new_tenant()+ monkeypatch.setenv("DATABASE_DSN", switch.dsn)+ monkeypatch.setenv("AISOC_ACTIONS_SERVICE_TOKEN", "test-actions-service-token")+ get_settings.cache_clear()+ await switch.engage(None, "platform-wide freeze reaches the HTTP surface too")++ with TestClient(+ app,+ headers={"Authorization": "Bearer test-actions-service-token"},+ raise_server_exceptions=False,+ ) as client:+ response = client.post(+ "/api/v1/live-actions/dispatch",+ json={+ "capability": "search_siem",+ "vendor_id": "splunk",+ "target": "index=main",+ "tenant_id": str(tenant),+ "dry_run": False,+ },+ )++ assert recorder.calls == []+ assert response.status_code == 200, response.text+ assert response.json()["result"]["status"] == "blocked"+++# ── no database needed: the read path's own failure modes ────────────────+++class TestWhatHappensWhenTheSwitchCannotBeRead:+ async def test_an_unreadable_switch_blocks_rather_than_permits(+ self, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """A database that cannot answer "is the stop pressed" must not be read as "no".++ Points at a closed port, so this is the real reader failing for real.+ """+ monkeypatch.setenv("DATABASE_DSN", "postgresql://[email protected]:1/aisoc")++ result = await dispatch(_request(tenant_id=uuid.uuid4()))++ assert recorder.calls == []+ assert result.status is LiveActionStatus.BLOCKED+ assert result.details.get("blocked_by") == "kill_switch_unreadable"++ async def test_unreadable_does_not_claim_somebody_pressed_it(+ self, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Naming the wrong subsystem sends an operator to debug a switch nobody touched."""+ monkeypatch.setenv("DATABASE_DSN", "postgresql://[email protected]:1/aisoc")++ result = await dispatch(_request(tenant_id=uuid.uuid4()))++ assert result.details.get("blocked_by") != "kill_switch"+ assert "unreadable" in result.summary.lower()++ async def test_no_database_configured_does_not_block(self, recorder: _RecordingExecutor, monkeypatch: pytest.MonkeyPatch) -> None:+ """A deployment with no database has no switch, and must still work.++ The same line `resolve_tenant_policy` already draws: no DSN is an+ operator's documented single-tenant configuration, not a read+ failure. Failing closed here would brick every such install to guard+ a table that cannot exist on it.+ """+ monkeypatch.delenv("DATABASE_DSN", raising=False)+ monkeypatch.delenv("DATABASE_URL", raising=False)++ result = await dispatch(_request(tenant_id=uuid.uuid4()))++ assert len(recorder.calls) == 1+ assert result.status is LiveActionStatus.SUCCEEDEDdiff --git a/services/actions/tests/test_tenant_policy.py b/services/actions/tests/test_tenant_policy.pyindex e311e7164..eacf122e4 100644--- a/services/actions/tests/test_tenant_policy.py+++ b/services/actions/tests/test_tenant_policy.py@@ -125,7 +125,20 @@ async def test_a_bad_tier_env_value_is_conservative(monkeypatch: pytest.MonkeyPaasync def test_sqlalchemy_style_dsn_is_accepted(monkeypatch: pytest.MonkeyPatch):"""Both DSN spellings are already present in deployed environments."""monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://u:p@h/db")- assert tenant_policy._dsn() == "postgresql://u:p@h/db"+ assert tenant_policy.resolve_dsn() == "postgresql://u:p@h/db"+++async def test_the_kill_switch_reads_the_same_dsn_this_module_does(monkeypatch: pytest.MonkeyPatch):+ """One resolver, because two would disagree about whether a database exists.++ The autonomy policy and the stop button read the same database on the+ same request. If they resolved the DSN separately, a deployment could+ have a tier the policy could read and a switch the dispatcher could not,+ and the generous half would win.+ """+ from app.services import kill_switch++ assert kill_switch.resolve_dsn is tenant_policy.resolve_dsn# ── whitelist ─────────────────────────────────────────────────────────────diff --git a/services/api/app/api/v1/endpoints/kill_switch.py b/services/api/app/api/v1/endpoints/kill_switch.pyindex dba6b487b..8377c2c67 100644--- a/services/api/app/api/v1/endpoints/kill_switch.py+++ b/services/api/app/api/v1/endpoints/kill_switch.py@@ -11,8 +11,41 @@ and it must work without reasoning about per-class rows, without a deployand without a restart.So it is one boolean with a mandatory reason, checked first and separately-by everything that acts: closure in the triage worker, the actions-dispatcher, playbook dispatch and the MCP write tools.+by the two things that act without a human.++What it stops+-------------+1. **Automatic closure**, in the triage worker. ``closure.decide()`` checks+ the switch before the per-class policy, so an engaged switch withholds+ auto-close whatever the confidence.+2. **Action dispatch**, at ``services/actions`` ``live_actions.dispatch()``+ — before the executor is looked up, so no vendor is contacted. That is+ the single chokepoint every route to a customer's estate passes through:+ ``POST /live-actions/dispatch``, the ``/dry-run`` sibling, the agent+ loop, and **playbook steps**, which reach it through+ ``action_bridge`` → ``POST /playbook-steps/dispatch`` →+ ``actions_client``. A blocked request comes back ``blocked``, never+ ``failed``: failed invites a retry, and the retry is refused too.++Dry runs are stopped as well. A preview is only credentials-free while the+strip list matches what each client factory reads, and+``services/actions/app/executors/siem.py`` records a release where it did+not and a "dry run" reached the customer's production SIEM. An operator who+pressed the stop button did not mean "stop, except for previews".++What it does not stop+---------------------+Anything a human does. Analysts keep triaging, the console keeps working,+and an operator can still act directly at the vendor — the switch governs+what the platform does on its own, and is not an outage.++This paragraph used to name "the MCP write tools" as a third enforcement+point. There are no MCP write tools. ``services/mcp`` exposes one tool that+touches the response surface, ``aisoc_preview_action``, it is dry-run only,+and ``services/mcp/tests/actions.test.ts`` asserts that the path performing+an action appears nowhere in its source. Naming it here was worse than an+unenforced claim: it told a reader the MCP server could perform actions,+which was the more alarming half and was never true either.Two scopes----------