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(closure): one authorization chokepoint for every automatic alert closure (#1525)
Beenu Arora56504986c938
diff --git a/.github/workflows/agent-auth-live.yml b/.github/workflows/agent-auth-live.ymlindex 6274e94c8..43e8712a9 100644--- a/.github/workflows/agent-auth-live.yml+++ b/.github/workflows/agent-auth-live.yml@@ -18,6 +18,10 @@ on:- "services/agents/app/hunt/**"- "tests/isolation/test_agent_service_auth_live.py"- "tests/isolation/test_closure_grant_live.py"+ - "tests/isolation/test_closure_authorization_live.py"+ - "services/agents/app/investigator/ledger.py"+ - "services/agents/app/memory/institutional.py"+ - "services/agents/app/workers/**"- "tests/isolation/test_api_to_connectors_auth.py"- "services/api/app/api/v1/endpoints/federated.py"- "services/api/app/services/case_fanout.py"@@ -128,6 +132,25 @@ jobs:ISOLATION_CLOSURE_DSN: ${{ env.LIVE_DSN }}run: python -m pytest ../../tests/isolation/test_closure_grant_live.py -v --tb=short -rs+ # Closure remediation Phase 1. Two modules disagreed about who asks+ # permission before an alert closes, and the disagreement is resolved by+ # SQL, so a fake connection cannot see it: the offline double answers+ # both sides happily and cannot run the `CASE` expression that is the+ # actual closure.+ #+ # Two DSNs on purpose. The code under test connects as the runtime role,+ # where RLS is forced — a superuser ignores every policy and would let+ # the cross-tenant assertions pass for the wrong reason. Fixtures write+ # rows for several tenants at once and read them back, which under those+ # same policies needs the owner.+ - name: Every automatic closure passes the authorization chokepoint+ working-directory: services/agents+ env:+ ISOLATION_CLOSURE_AUTHZ_DSN: ${{ env.LIVE_DSN }}+ # aisoc-db-role: owner — fixtures only. The suite seeds scratch tenants, policy rows for several tenants at once and the *global* kill-switch row, whose own WITH CHECK (tenant_id = current_tenant_id()) makes it uninsertable by any non-owner. The code under test reads ISOLATION_CLOSURE_AUTHZ_DSN above, which is the runtime role, so every assertion is still judged under forced RLS+ ISOLATION_CLOSURE_AUTHZ_ADMIN_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc+ run: python -m pytest ../../tests/isolation/test_closure_authorization_live.py -v --tb=short -rs+- name: A tenant can opt itself into retro-huntsworking-directory: services/apienv:diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 80cf594ab..c64c8c76e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -363,6 +363,17 @@ jobs:run: python scripts/check_one_permission_model.py --self-test- name: Verify the database is authoritative for permissionsrun: python scripts/check_one_permission_model.py+ # `alerts.status` reaches 'resolved' from one statement, and for a while+ # two callers reached it while only one asked permission: the+ # outcome-memory suppression branch closed alerts having consulted no+ # policy, no grant and no kill switch. The wiring test that was supposed+ # to cover this asserted one substring against one function, so it could+ # not see the path nobody remembered. This holds the property the+ # chokepoint rests on — one closure statement, in one module, gated.+ - name: Closure authorization chokepoint — self-test+ run: python scripts/check_closure_authorization.py --self-test+ - name: Verify every automatic closure passes the authorization chokepoint+ run: python scripts/check_closure_authorization.py# Thirteen Kafka clients across Python, Go and TypeScript, and not one# passed a security protocol — so every one took the library default,# which is PLAINTEXT in all three. The spine carries raw event bodies,diff --git a/ROADMAP.md b/ROADMAP.mdindex 9c5aadc41..2ff329bcc 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **322 rows — 318 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **324 rows — 319 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 6cc551782..9a0979cbb 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,8 +33,8 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `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: 318 rows-`GATED`, 4 `PARTIAL`, and a ratchet that refuses to let a row sit at+The last row is the one worth reading first. It is the honest index: 319 rows+`GATED`, 5 `PARTIAL`, and a ratchet that refuses to let a row sit at`NO GATE`. Re-read the figure from the table rather than from here — a countcopied into prose goes stale in silence, which is why`scripts/readme_gates.py` cross-checks this sentence against the matrix.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex c33c4a0a1..f12f190b4 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -330,12 +330,14 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No two database migrations claim the same number, so a chain applies in one order on a fresh install and on an upgrade alike | `services/api/app/scripts/run_migrations.py` (orders by filename, records applied by filename); `scripts/check_migration_numbering.py` | `migration-numbering.yml :: migration-numbering` (no `paths:` filter on either trigger, so it grades every pull request and every push to a protected branch — the collision is a property of a *pair* of files and the second half can arrive from somebody else's merge, so a filter scoped to the migrations directory would miss exactly the case that bites. Discovers all 6 numbered chains structurally rather than from a list, which is what finds `services/osquery-tls/app/db/versions` under its non-conventional `script_location`. Proven against the real defect: a worktree holding both `121_fusion_alert_outbox.sql` and PR 1525's `121_closure_authorization_default_deny.sql` exits 1 naming both, and the same tree with the new-duplicate arm disabled reports a confident OK. The 13 historical collisions already on main are frozen by file set, checked in both directions so a stale exemption and a third file joining an old pair each fail | core | GATED | — || A query credited as tenant-scoped is one whose `tenant_id` constrains the rows read or written, not one that merely mentions the column | `scripts/check_tenant_query_predicates.py` (`_tenant_predicate_in_sql`) | `isolation.yml :: Tenant query predicates` (the credit is decided by the clause the token sits in, so a `RETURNING` list, a `SELECT` projection, an `ORDER BY`, a `GROUP BY`, an UPDATE `SET` and a SQL comment all stop counting, while `WHERE`, join `ON`, `USING`, `HAVING`, an INSERT column list and an `ON CONFLICT` target still do. Both code paths were fixed, not one: `_names` collects string constants, so the statement's own SQL came back round and a second bare-token test re-granted the credit on 14 of the 17 statements the first fix had demoted. 36 self-test cases written per SQL *clause* rather than per instance found, including the padding-free fragment branch and a control that an appended fragment naming the column without comparing it still fails. Proven both ways on the live tree: with its ratchet entry removed the real `UPDATE … RETURNING id, tenant_id` outbox claim is flagged, and reverting the detector to the bare-token match stops it being flagged | core | GATED | — || The platform-wide kill switch can actually be engaged, and an engaged one stops automatic closure and action dispatch | `docs/remediation/kill-switch-reachability.md`; `services/api/migrations/123_kill_switch_global_engageable.sql`; parity 2.2 | `kill-switch-live.yml :: The platform-wide stop can be engaged, and stops closure` (real Postgres, every migration applied, driven as the NOSUPERUSER NOBYPASSRLS `aisoc_app` role because the migration owner is a superuser and ignores policies even under FORCE ROW LEVEL SECURITY — the job fails if the DSN resolves to a role that can bypass, and the suite refuses to run against one, because seeding the global row as the owner is the workaround that hid this for 45 migrations. 25 cases across three suites: the global row is writable by an unbound session and by nothing else, a tenant cannot write the global row or another tenant's row or another tenant's audit row, an unbound session cannot write into any tenant, the real routes write the row end to end through the real ASGI app, a tenant_admin and an analyst are both refused 403 while the tenant switch still works for them, and `resolve_closure_policy` refuses a 0.99 verdict against a 0.50 bar with source=kill_switch for a tenant that engaged nothing itself) + `ci.yml :: Python — Tests` (api `test_kill_switch.py`, the global routes resolve their handler, require `platform_kill_switch:write` read off the resolved dependency tree rather than the handler source, and take the unbound session) + `action-durability-live.yml :: One approval, one vendor call, or an honest unknown` (real Postgres; the step *An engaged kill switch stops the dispatcher, and a released one does not* asserts both directions, and *The gate fails when dispatch stops consulting the switch* is the negative control, which refuses to run if it cannot find the line it removes) | core | GATED | Before this the global row had no writer at all: every write in the endpoint module bound the caller's tenant, so no endpoint, console control, CLI or script could set `tenant_id IS NULL`, while two readers consulted it on every alert. **There is still no console control for the kill switch in either scope** — both are API-only. **An engaged switch now stops action dispatch as well as closure**: the check sits in `live_actions.dispatch()` before the executor is resolved, which covers the actions dispatcher and playbook dispatch, since playbook steps reach a vendor through that one chain. Dry runs are stopped too, and an unreadable switch refuses rather than dispatching. The fourth point the module docstring claimed — the MCP write tools — was corrected rather than implemented, because no such write surface exists |+| Inside `services/agents`, an alert can be closed automatically from exactly one statement, and that statement asks permission first | `docs/remediation/phase-1-closure-authorization.md`; `services/agents/app/closure/authorization.py` | `ci.yml :: python-lint` (`check_closure_authorization.py`, plus its `--self-test`: only `investigator/ledger.py` may carry SQL that can set an alert to `'resolved'`, and the function holding it must call `authorize_auto_closure`. It reads the AST and considers only string constants that are not docstrings, because four files in this change quote that SQL in prose and a gate that fires on documentation gets switched off within a week; the self-test proves it stays silent on a docstring and a comment and fires on both the literal and `CASE ... THEN` forms) + `ci.yml` agents job (`test_closure_authorization.py` — default-deny for a tenant with no policy row, refusal when the pool is unavailable *and* when it is unconfigured, refusal for a non-closeable verdict, a shadow run and ungrounded reasoning, and an enumeration of every module that reaches the durable write) | core | GATED | The structural property and the offline behaviour are gated on every pull request. That the SQL then does what the gate assumes is the row below, and it is not gated per-PR. **The claim is scoped to `services/agents` because the gate is**: `services/connectors` closes a CVE-promotion alert of its own making through `RESOLVE_REMEDIATED_SQL` when every affected asset is patched — a deterministic, tenant-scoped lifecycle rule rather than an autonomous verdict, out of scope for this phase and named here so the row is not read as a product-wide claim |+| Every automatic closure of a production alert is checked against the current policy, grant and stop controls at the moment the row changes | `docs/remediation/phase-1-closure-authorization.md`; `services/agents/app/investigator/ledger.py` | `agent-auth-live.yml` (`tests/isolation/test_closure_authorization_live.py` — real Postgres with every migration applied, the real `persist_auto_triage`, the real `app.closure` modules and the real worker method for the outcome-memory path. Fifteen tests: no explicit policy does not close, an explicit one still does, a disabled policy and an unearned grant block, the memory and cached tiers are governed, a changed policy invalidates an earlier authorization, one tenant's policy cannot authorize another's, global and per-tenant stop controls, shadow leaves the analyst's columns alone, and an unauthorized verdict is still recorded as `triaged`. The code under test connects as the runtime role so RLS is in force; a superuser would ignore every policy and let the cross-tenant assertions pass for the wrong reason) | core | PARTIAL | The suite is wired into `agent-auth-live.yml` and **has been observed green on a CI runner** — 15 passed in the job `A service credential reaches the API and is scoped to one tenant` on this pull request — as well as locally against PostgreSQL 16, where 12 of the 15 fail on the pre-fix tree with the alert sitting at `resolved`. It is PARTIAL rather than GATED for one remaining reason: that run graded the pull request's merge ref, and the job has not yet run on `main`, so "the gate works" and "a future pull request cannot regress it" are still separate claims until the push-to-`main` run exists. Returns to GATED in the change that observes this job green on `main`. Two narrower gaps stay named in the remediation document: the global kill-switch row is uninsertable by the runtime role because of its own `WITH CHECK`, so the suite seeds it as the owner and the *write* path for that switch is not covered here; and the `"default"` tenant-placeholder resolution is governed by the same chokepoint but is never exercised with a live multi-tenant ambiguity |## Summary-- Total: 322-- GATED: 318-- PARTIAL: 4+- Total: 324+- GATED: 319+- PARTIAL: 5- NO GATE: 0Counts come from `scripts/check_claim_gate_matrix.py`, which is also the gate. Recomputediff --git a/docs/remediation/phase-1-closure-authorization.md b/docs/remediation/phase-1-closure-authorization.mdnew file mode 100644index 000000000..747e3f158--- /dev/null+++ b/docs/remediation/phase-1-closure-authorization.md@@ -0,0 +1,421 @@+# Phase 1 — centralizing automatic alert-closure authorization++Automatic closure of a production alert now passes exactly one authorization+check, immediately before the row changes, whatever route the verdict took to+get there.++Before this, `alerts.status` could reach `'resolved'` down two paths and only+one of them asked permission. A verdict remembered from a previous alert was+being treated as permission remembered from a previous alert, which is not the+same thing and was never decided by anybody.++## The shape of the fix++Within `services/agents`, `alerts.status` becomes `'resolved'` in exactly one+statement: the `UPDATE alerts` at the end of+`app.investigator.ledger.persist_auto_triage`, gated on a caller-supplied+`auto_closed` flag. That makes a chokepoint possible, so the authorization now+lives inside that function, between resolving the alert's tenant and opening+the transaction:++```+caller (LLM triage / outcome memory / cached verdict / retry / resumed run)+ │ auto_closed=True+ ▼+ledger.persist_auto_triage+ │ tenant resolved to its canonical UUID+ ▼+closure.authorization.authorize_auto_closure ← the only gate+ │ delegates per-tenant policy to closure.policy.decide+ ▼+UPDATE alerts ... CASE WHEN $7 AND NOT $10 THEN 'resolved'+```++Three properties follow from putting it there rather than in each caller:++- **A new caller is governed by default.** The previous arrangement required+ every caller to remember; one did not, for as long as it existed.+- **Recovery re-evaluates.** A retry, a resumed run or a deduplicated verdict+ persists a decision reached earlier, sometimes much earlier. Because the+ check runs at the write, the answer always comes from the policy in force+ when the row changes. An authorization carried alongside a verdict would let+ a tenant disable closure and still have in-flight work close alerts behind+ them.+- **The tenant is the row's tenant.** `persist_auto_triage` has already+ resolved `tenant_ref` to the canonical UUID, so the policy that is read+ belongs to the alert being closed and not to whatever string the caller+ passed.++It is **not** a second policy implementation. Thresholds, the enabled flag,+`require_grant` and the kill switch stay in `app/closure/policy.py` and are+reached through `closure_policy.decide`. What the chokepoint adds is the set+of preconditions that are not per-tenant policy — the verdict has to be+auto-closeable, the run has to be real rather than shadow or replay, and the+reasoning has to be grounded — plus one call site everything passes through.++`run_auto_triage` still pre-checks the policy. That call is advisory and is+what puts `Auto-close withheld: ...` in front of an operator at triage time;+the chokepoint is what decides. Both derive the alert class through+`authorization.alert_class_of`, so they cannot disagree about which policy row+applies.++## Findings++### Finding 1 — a second, ungoverned path to `resolved` (critical)++**Status: reproduced.**++**Affected production path.**+`FusedAlertTriageWorker._maybe_suppress_from_memory` →+`_record` → `TriageWriter.persist_auto_triage` →+`ledger.persist_auto_triage` → `UPDATE alerts`.++`_maybe_suppress_from_memory` set `state.status = AgentStatus.COMPLETED`+directly from a stored outcome prior, and `_record` forwarded+`auto_closed=state.status is AgentStatus.COMPLETED`. The strings+`closure_policy` and `kill_switch` appear in `fused_alert_consumer.py` only+inside comments. Consequences, all confirmed against a live database on the+pre-fix tree:++- a tenant with `enabled = false` in `aisoc_closure_policies` still got+ automatic closures;+- the kill switch — global or per tenant — did not stop this path;+- `require_grant` was not consulted, so a tenant waiting for shadow mode to+ earn an `auto_close` grant closed alerts anyway;+- the confidence recorded against the decision was read off the stored prior+ (`float(prior.get("confidence", 0.9))`) rather than measured for this alert.++It was gated only by `_memory_suppression_enabled()`, which is on by default.++**Regression tests.**+`tests/isolation/test_closure_authorization_live.py`:++- `TestEveryClosurePathIsGoverned::test_the_memory_suppression_path_is_governed`+- `TestEveryClosurePathIsGoverned::test_the_real_suppression_path_does_not_close_an_unauthorized_alert`+ — drives the real worker method with the real `LiveTriageWriter`, the real+ ledger and the real policy; only the outcome prior is supplied, because that+ is the worker's input rather than the authorization+- `TestStopControls::test_the_memory_path_obeys_the_kill_switch`+- `TestEveryClosurePathIsGoverned::test_the_cached_verdict_path_is_governed`++**Fix.** The authorization moved to `ledger.persist_auto_triage`, so the+suppression branch is governed without it having to ask. Suppression still+short-circuits re-triage — the prior is good evidence about the alert and+re-triaging it would be waste — but the closure it used to imply is now+decided separately.++**Compatibility.** A deployment with an enabled policy sees no change. A+deployment relying on suppression to close alerts while its policy said+otherwise stops doing so, which is the defect.++### Finding 10 — the policy was permissive when its pool was `None` (critical)++**Status: reproduced.**++**Affected production path.** `closure.policy._pool()` →+`memory.institutional._get_pool()`.++With `pool is None` the module reported the kill switch **not engaged** and+fell back to `allowed = confidence >= default_threshold`. `None` was far more+reachable than "no database configured": `_get_pool` returned it on any+exception from `asyncpg.create_pool` **and** when the bootstrap probe on+`aisoc_institutional_memory` failed. So a missing migration, or an ACL problem+on a table the closure policy never reads, silently disabled the closure+policy and the kill switch together — logged at `debug`.++**Regression tests.** `services/agents/tests/test_closure_authorization.py`:++- `TestAnUnavailableDatabaseRefuses::test_a_pool_that_failed_to_open_refuses`+- `TestAnUnavailableDatabaseRefuses::test_an_unconfigured_database_refuses_too`+- `TestAnUnavailableDatabaseRefuses::test_the_kill_switch_refuses_when_the_pool_is_unavailable`+- `TestTheMemoryTableDoesNotGateTheClosurePolicy::test_a_failed_memory_bootstrap_still_yields_a_pool`++**Fix.** Two parts.++1. The pool accessor returns a *reason* alongside the pool.+ `institutional.connection_pool()` answers `POOL_READY`,+ `POOL_UNCONFIGURED` (no `DATABASE_URL` anywhere) or `POOL_UNAVAILABLE`+ (configured and unusable). `POOL_UNAVAILABLE` refuses, in the kill switch+ and in the policy. `POOL_UNCONFIGURED` also refuses, because a deployment+ with no policy store has recorded no authorization — and no durable closure+ can happen there anyway, since `persist_auto_triage` returns early without+ a ledger pool.+2. The institutional-memory bootstrap no longer decides whether *other*+ readers get a connection. `_connect()` opens the pool; `_get_pool()` adds+ the table probe for the memory store's own use and no longer closes the+ shared pool when it fails. The memory store still degrades to its+ in-process dict; the closure policy keeps its database.++The `create_pool` failure also moved from `debug` to `warning`: a deployment+that configured a database and did not get one is a fault an operator has to+see, and a safety control is about to refuse because of it.++In-query failures were already correct and are unchanged.++### Finding 14 — no policy row meant permission (by design, now changed)++**Status: source-confirmed, changed deliberately.**++**Affected production path.** `closure.policy.resolve_closure_policy`, the+`row is None` branch.++A tenant with no row in `aisoc_closure_policies` auto-closed at+`confidence >= AUTO_CLOSE_THRESHOLD` (0.85). The original rationale was+additivity — "a deployment that configures nothing behaves exactly as it did"+— which was true of the code and wrong as a posture: it turned the absence of+a decision into a decision, and every tenant auto-closed from its first+confident benign verdict, including one that had never opened the screen.++**Regression tests.**++- `test_closure_authorization.py::TestTheDefaultIsRefusal::test_a_tenant_with_no_policy_row_is_not_authorized`+- `test_closure_authorization.py::TestTheDefaultIsRefusal::test_a_missing_tenant_is_not_authorized`+- `tests/isolation/...::TestClosureNeedsExplicitAuthorization::test_an_eligible_verdict_does_not_close_without_an_explicit_policy`+- the positive control beside it,+ `test_an_explicitly_authorized_tenant_still_closes`, which is what stops a+ gate that refuses everything from looking like a fix++`services/agents/tests/test_closure_policy.py::test_no_policy_row_is_not_authorization`+previously asserted the opposite and is updated in place, with the old+reasoning kept in its docstring.++**Fix.** The `row is None` branch refuses, with+`source="default_deny"` and a reason naming the alert class. Nothing is+inferred from history: a tenant that was auto-closing yesterday *because+nobody had decided anything* has still not decided anything.++**Compatibility — this is the breaking change in this phase.** A deployment+that never configured a closure policy and relied on the implicit default+stops auto-closing until somebody authorizes it. See the migration below for+how to find out whether that is you, and how to restore it deliberately.++### Already fixed before this phase — left alone, pinned++**Status: already-fixed.** Shadow and replay cannot mutate production status:+`shadow_mode.py` forces `auto_closed=False, shadow=True`, and the ledger SQL+guards with `NOT $10`. In-query policy failures already refused.++Both are now pinned by tests here —+`TestShadowAndReplay::test_a_shadow_run_leaves_production_status_untouched`+and `TestTheChokepointItself::test_a_shadow_run_is_refused` — so the+chokepoint cannot regress them. The chokepoint refuses a shadow run itself as+well, which is a third mechanism saying the same thing; that is deliberate, so+its answer is complete on its own terms rather than depending on a reader+holding all three in their head.++## The migration++`services/api/migrations/122_closure_authorization_default_deny.sql`.++**What it does.** Creates `aisoc_closure_authorization_migration` and writes+one row per existing tenant recording which side of the default change that+tenant fell on: `preserved` (an explicit policy row decides, exactly as+before) or `requires_authorization` (closure was implicit and is now+withheld). It is an audit record. Nothing reads it to make a decision.++**What it deliberately does not do.** It creates no policy rows. An `INSERT`+granting a row to every tenant that had auto-closed in the past would be the+same mistake in a different place — inferring authorization from behaviour the+old default produced. Only a human may grant this.++**Upgrade.** Forward-only and idempotent; re-running records nothing twice.+Apply it in the usual order and then ask who is affected:++```sql+SELECT t.slug, m.outcome+ FROM aisoc_closure_authorization_migration m+ JOIN tenants t ON t.id = m.tenant_id+ WHERE m.outcome = 'requires_authorization'+ ORDER BY t.slug;+```++**Restoring closure for a tenant** is a deliberate grant, per tenant, with a+reason — the same row the console writes:++```sql+INSERT INTO aisoc_closure_policies+ (tenant_id, alert_class, enabled, threshold, require_grant, updated_by, reason)+VALUES ('<tenant-uuid>'::uuid, NULL, TRUE, 0.85, FALSE,+ '<operator>', 'restoring pre-122 automatic closure, reviewed <date>');+```++`require_grant = FALSE` reproduces the old default exactly. Leaving it `TRUE`+is the safer choice: closure then additionally waits for an `auto_close` grant+that shadow mode has to earn.++**Rollback.** There is no schema change to undo beyond+`DROP TABLE IF EXISTS aisoc_closure_authorization_migration;`. Reverting the+*behaviour* means reverting the code change, not the migration — the migration+only records what happened.++## The gate++`scripts/check_closure_authorization.py` asserts the two properties the+chokepoint rests on: that only the ledger carries SQL which can set an alert+to `'resolved'`, and that the function holding it calls+`authorize_auto_closure`. It reads the AST and considers only string constants+that are not docstrings, because this document, the gate itself and+`authorization.py` all quote that SQL in prose — a gate that fires on+documentation gets switched off within a week.++`--self-test` proves the detector in both directions over five cases:+it must stay silent on a docstring and a comment, fire on both the literal+`status = 'resolved'` and the `CASE ... THEN 'resolved'` form the ledger+actually uses, and report a chokepoint call only where one exists.++## Verification performed++All commands were run from a worktree at `origin/main`, with a service+virtualenv built from `services/agents`'s own locked set+(`python3 scripts/service_requirements.py agents --locked`), and against+PostgreSQL 16 with all 137 migrations applied as the schema owner. The code+under test connects as the **runtime** role `aisoc_app`, not the owner, so RLS+is in force; a superuser would ignore every policy and let the cross-tenant+assertions pass for the wrong reason.++| Check | Result |+| --- | --- |+| Live suite, pre-fix | 12 failed, 3 passed — every failure the alert sitting at `resolved` |+| Live suite, post-fix (local) | **15 passed** |+| Live suite on a CI runner ([run](https://github.com/beenuar/AiSOC/actions/runs/40515014261)) | **15 passed** |+| Offline closure suites, post-fix | **28 passed** |+| Agents suite, baseline on `origin/main` | 2050 passed, 5 skipped |+| Agents suite, post-fix | **2066 passed, 5 skipped** |+| `ruff format --check .` | 2599 files already formatted |+| `ruff check services/ scripts/ tests/ tools/` | All checks passed |+| `scripts/check_mypy_baseline.py` | OK — no tree got worse (964 findings, 20 trees) |+| `scripts/check_closure_authorization.py` | OK, and `--self-test` OK (5 cases, both directions) |+| Migrations on a **fresh** database, 001→122 in order | **137 applied cleanly** |+| Migration 122 re-applied | idempotent, records nothing twice |+| `scripts/check_claim_gate_matrix.py` | 321 rows — 316 GATED, 5 PARTIAL, 0 NO GATE |+| `scripts/check_gate_coverage.py` | OK — all 178 checks reachable from a workflow |+| `scripts/check_attribution.py --all` | OK — 13,666 tracked files, no tool attribution |+| `scripts/check_competitor_names.py` | OK |+| `scripts/check_machine_paths.py` | OK — 13,209 tracked text files, no machine-specific path |+| `scripts/check_comment_paths.py` | OK — 2,284 repository paths named in comments all exist |+| `scripts/check_module_reachability.py` | OK — 1,036 of 1,064 modules reachable |+| `scripts/check_raw_sql_columns.py` | OK — 560 statements parsed, 367 compared |+| `scripts/check_text_bind_casts.py` | OK — no `:name::type` |++The three passing live tests on the pre-fix tree are the positive control, the+shadow guard and manual closure — all three are properties the fix had to+preserve rather than establish, so their passing before and after is the+intended reading.++### Negative controls++Each mechanism was reverted on top of the fix and the suites re-run, then the+file restored from `HEAD` and the suites confirmed green again. Reverting one+mechanism at a time is what makes the result attributable: a single+pre-fix-versus-post-fix comparison shows the three changes together and cannot+say which test is held up by which.++**1. Remove the chokepoint call from `ledger.persist_auto_triage`** (18 lines).++```+12 failed, 3 passed tests/isolation/test_closure_authorization_live.py+check_closure_authorization: investigator/ledger.py:persist_auto_triage can set+an alert to 'resolved' without calling authorize_auto_closure. An automatic+closure would bypass the tenant's policy, the earned grant and the kill switch.+exit=1+```++The three still passing are the positive control, the shadow guard and manual+closure — the properties the chokepoint is not responsible for.++**2. Restore the permissive `row is None` branch** (Finding 14).++```+2 failed, 26 passed test_closure_authorization.py::...::test_a_tenant_with_no_policy_row_is_not_authorized+ test_closure_policy.py::TestPerTenantPolicy::test_no_policy_row_is_not_authorization+3 failed, 12 passed live: test_an_eligible_verdict_does_not_close_without_an_explicit_policy+ test_one_tenants_policy_cannot_authorize_anothers_closure+ test_an_unauthorized_verdict_is_still_recorded+```++**3. Restore `pool is None → (False, "")` in `kill_switch_engaged`** (Finding 10).++```+2 failed, 14 passed test_a_pool_that_failed_to_open_refuses+ test_the_kill_switch_refuses_when_the_pool_is_unavailable+```++After restoring all three: 28 offline passed, 15 live passed.++## A second automatic closure path, outside this phase++Found while rebasing, by asking the question this phase is about against the+whole tree rather than against the service it changes. It was there before+this work started and the original audit missed it.++`services/connectors/app/vuln_promotion_sql.py` carries+`RESOLVE_REMEDIATED_SQL`, run on a schedule from the connectors sweep+(`scheduler.py`), which does:++```sql+UPDATE alerts al+ SET status = 'resolved', resolved_at = NOW(), disposition = 'remediated: …'+ WHERE al.tenant_id = CAST(:tenant_id AS uuid)+ AND al.status NOT IN ('resolved', 'closed')+ AND al.idempotency_key LIKE 'vuln-promo:%'+ AND NOT EXISTS (… any unremediated asset for this CVE …)+```++So it is a second statement that automatically resolves a production alert,+and the chokepoint does not govern it.++**It is deliberately not fixed here**, for reasons worth recording rather than+leaving as a silence:++- It is a different category. The chokepoint governs an *autonomous verdict* —+ a machine deciding an alert is benign and acting on that judgement. This+ closes the connector's own synthetic alert when the condition the alert+ represents has provably gone away: every asset carrying the CVE is patched.+ That is a lifecycle rule, and the closure is a statement of fact rather than+ an assessment.+- Its blast radius is bounded by construction: `idempotency_key LIKE+ 'vuln-promo:%'` restricts it to rows the sweep itself minted, and the+ tenant is bound per statement.+- `services/connectors` is another phase's tree. Editing it from here is+ exactly the cross-lane write this programme asks workers not to make.++What a later phase should decide is whether "the alert's underlying condition+is gone" belongs under the same authorization as "a model thinks this is+benign", or whether it is correctly a separate lifecycle concern. This+document records the question rather than answering it.++The practical consequence now is one of wording: the gate walks+`services/agents/app` only, so neither it nor its claim row says "the only+path to `resolved`" without naming the tree it means.++## Remaining limitations++Stated plainly, because an implied pass is worth less than a named gap.++- **The live suite has run green on a CI runner, but not yet on `main`.** It+ is wired into `.github/workflows/agent-auth-live.yml`, the job that already+ stands up Postgres with every migration applied and runs the sibling+ closure-grant suite, and all 15 tests passed there on this pull request.+ That run graded the pull request's merge ref; the job has not run on `main`,+ so "the gate works" and "a future pull request cannot regress it" remain+ separate claims. The claim-to-gate matrix row is `PARTIAL` for that reason+ and returns to `GATED` in the change that observes it green on `main`.+- **No hosted model was exercised.** Nothing here places an LLM call; the+ tests drive the persistence and policy path with verdicts supplied directly.+ That is the correct scope for an authorization fix, but it means this work+ says nothing about model behaviour.+- **The console has no screen for this yet.** A tenant that lands on+ `requires_authorization` is restored with the SQL above. Surfacing it in the+ settings UI is follow-on work and is not in this phase.+- **`aisoc_kill_switch`'s `WITH CHECK (tenant_id = current_tenant_id())`+ makes the global row (`tenant_id IS NULL`) uninsertable by the runtime+ role.** Noticed while writing the live suite, which works around it by+ seeding as the owner. The *read* path — the one that matters for stopping+ closures — is unaffected and is covered by the tests here. Whether the+ global switch can be engaged through the product at all is outside this+ phase's scope and is not fixed here.+- **One tenant-attribution path is unverified.** `persist_auto_triage`+ resolves the `"default"` placeholder to the canonical seed tenant in a+ single-tenant install. The tests here always pass an explicit UUID, so the+ placeholder path is governed by the same chokepoint but has not been+ exercised with a live multi-tenant ambiguity.diff --git a/scripts/check_closure_authorization.py b/scripts/check_closure_authorization.pynew file mode 100644index 000000000..5cb1e5b67--- /dev/null+++ b/scripts/check_closure_authorization.py@@ -0,0 +1,267 @@+#!/usr/bin/env python3+"""Every automatic closure of an alert passes the closure authorization chokepoint.++Phase 1 of the closure remediation. See+`docs/remediation/phase-1-closure-authorization.md`.++What this gate is for+---------------------+`alerts.status` becomes `'resolved'` in exactly one statement in+`services/agents`: the `UPDATE alerts` at the end of+`app.investigator.ledger.persist_auto_triage`. That is what makes a chokepoint+possible at all — and it is also a property that nothing was holding.++**Scope, stated because the obvious reading is wider than the truth.** This+gate walks `services/agents/app` and nothing else, so what it proves is that+*the agent* has one governed closure path. It is not a claim about the+product: `services/connectors`'s vulnerability sweep carries its own+`RESOLVE_REMEDIATED_SQL`, which closes a CVE-promotion alert of its own making+once every affected asset is patched. That is a deterministic lifecycle rule+rather than an autonomous verdict, it is tenant-scoped, and it is outside this+phase — but a verdict string here saying "the only path to 'resolved'" would+be false, so neither this gate nor its claim row says it. A second+path to that statement had already appeared once: the outcome-memory+suppression branch reached it with `auto_closed=True` having consulted no+policy, no grant and no kill switch, and the test covering closure wiring+asserted one substring against one function, so it could not see it.++So this gate asserts two things:++1. only the ledger module contains SQL that can set an alert to `'resolved'`;+2. the function containing that SQL calls `authorize_auto_closure`.++Why it reads the AST and not the text+-------------------------------------+Grepping for `'resolved'` matches prose. This module's own docstring quotes+the SQL two paragraphs above, `authorization.py` quotes it as well, and a+line-based scanner flags both — a gate that fires on documentation gets+switched off within a week. Only string constants that are *not* docstrings+are considered, which is the difference between SQL the process executes and+English a reader reads.++Run it:++ python3 scripts/check_closure_authorization.py+ python3 scripts/check_closure_authorization.py --self-test+"""++from __future__ import annotations++import argparse+import ast+import re+import sys+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root # noqa: E402++#: The module permitted to carry closure SQL, relative to the agents app.+LEDGER = "investigator/ledger.py"++#: The function inside it that must consult the chokepoint.+GATED_FUNCTION = "persist_auto_triage"++#: The chokepoint's name, as it is called.+CHOKEPOINT = "authorize_auto_closure"++#: A SQL fragment that can move a row's status to resolved. Matches both the+#: literal assignment and the `CASE ... THEN 'resolved'` form the ledger uses.+_CLOSURE_SQL = re.compile(+ r"""(?isx)+ (+ status \s* = \s* ['"]resolved['"] # status = 'resolved'+ | THEN \s+ ['"]resolved['"] # CASE ... THEN 'resolved'+ )+ """+)+++def _docstring_nodes(tree: ast.AST) -> set[int]:+ """Identity of every string constant that is a docstring.++ A docstring is the first statement of a module, class or function and is+ a bare string expression. Everything else that is a string constant is+ data the program uses.+ """+ found: set[int] = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ body = getattr(node, "body", None) or []+ if not body:+ continue+ first = body[0]+ if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):+ found.add(id(first.value))+ return found+++def executable_strings(source: str) -> list[str]:+ """Every string constant in `source` that is not a docstring."""+ tree = ast.parse(source)+ docstrings = _docstring_nodes(tree)+ return [+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings+ ]+++def modules_with_closure_sql(app_root: Path) -> set[str]:+ """Modules under `app_root` carrying SQL that can resolve an alert."""+ found: set[str] = set()+ for path in sorted(app_root.rglob("*.py")):+ try:+ strings = executable_strings(path.read_text(encoding="utf-8"))+ except SyntaxError as exc: # pragma: no cover - a broken tree fails elsewhere+ print(f"check_closure_authorization: cannot parse {path}: {exc}", file=sys.stderr)+ return {"<unparseable>"}+ if any(_CLOSURE_SQL.search(text) for text in strings):+ found.add(path.relative_to(app_root).as_posix())+ return found+++def function_calls(source: str, function: str) -> set[str]:+ """The names called inside `function`, however it is spelled."""+ tree = ast.parse(source)+ calls: set[str] = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) or node.name != function:+ continue+ for inner in ast.walk(node):+ if not isinstance(inner, ast.Call):+ continue+ target = inner.func+ if isinstance(target, ast.Name):+ calls.add(target.id)+ elif isinstance(target, ast.Attribute):+ calls.add(target.attr)+ return calls+++def check(repo_root: Path) -> list[str]:+ """Returns a list of failures. Empty means the chokepoint holds."""+ app_root = repo_root / "services" / "agents" / "app"+ if not app_root.is_dir():+ return [f"no agents app at {app_root}"]++ failures: list[str] = []++ writers = modules_with_closure_sql(app_root)+ if writers != {LEDGER}:+ extra = sorted(writers - {LEDGER})+ if extra:+ failures.append(+ "SQL that can set an alert to 'resolved' appears outside the ledger, inside services/agents: "+ + ", ".join(extra)+ + f". Every automatic closure must go through {CHOKEPOINT}; "+ "a second statement is a second path nothing governs."+ )+ if LEDGER not in writers:+ failures.append(+ f"{LEDGER} no longer contains the closure SQL this gate exists to guard. "+ "If it moved, move the chokepoint with it and update this gate."+ )++ ledger_path = app_root / LEDGER+ if ledger_path.is_file():+ calls = function_calls(ledger_path.read_text(encoding="utf-8"), GATED_FUNCTION)+ if CHOKEPOINT not in calls:+ failures.append(+ f"{LEDGER}:{GATED_FUNCTION} can set an alert to 'resolved' without calling {CHOKEPOINT}. "+ "An automatic closure would bypass the tenant's policy, the earned grant and the kill switch."+ )+ else:+ failures.append(f"{LEDGER} is missing")++ return failures+++_SELF_TEST_GOOD = '''+"""A module whose docstring quotes the SQL: status = 'resolved'."""+# A comment mentioning THEN 'resolved' as well.+async def unrelated(conn):+ await conn.execute("UPDATE alerts SET status = 'triaged' WHERE id = $1")+'''++_SELF_TEST_BAD = """+async def sneaky(conn):+ await conn.execute("UPDATE alerts SET status = 'resolved' WHERE id = $1")+"""++_SELF_TEST_CASE_FORM = """+async def sneaky(conn):+ await conn.execute("UPDATE alerts SET status = CASE WHEN $1 THEN 'resolved' ELSE status END")+"""+++def self_test() -> int:+ """Prove the detector fires on SQL and stays silent on prose.++ Both directions, because a gate that cannot fire and a gate that fires on+ everything fail the same way in practice: somebody stops believing it.+ """+ failures = []++ if any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_GOOD)):+ failures.append("the detector flagged a module that only mentions the SQL in a docstring or a comment")++ if not any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_BAD)):+ failures.append("the detector missed a literal `status = 'resolved'` UPDATE")++ if not any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_CASE_FORM)):+ failures.append("the detector missed the `CASE ... THEN 'resolved'` form the ledger actually uses")++ ungated = """+async def persist_auto_triage(conn):+ await conn.execute("UPDATE alerts SET status = 'resolved'")+"""+ if CHOKEPOINT in function_calls(ungated, GATED_FUNCTION):+ failures.append("the call detector reported a chokepoint call in a function that makes none")++ gated = f"""+async def {GATED_FUNCTION}(conn):+ decision = await {CHOKEPOINT}(tenant_ref="t")+ await conn.execute("UPDATE alerts SET status = 'resolved'")+"""+ if CHOKEPOINT not in function_calls(gated, GATED_FUNCTION):+ failures.append("the call detector missed a direct chokepoint call")++ for failure in failures:+ print(f"check_closure_authorization: SELF-TEST FAILED — {failure}", file=sys.stderr)+ if failures:+ return 1+ print("check_closure_authorization: self-test OK (5 cases, both directions)")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--self-test", action="store_true", help="prove the detector works in both directions")+ # `repo_root()` asks git rather than counting directories above this file.+ # Two levels up is whatever happens to be there, which is the wrong answer+ # the moment the script is copied, vendored or run from a build context.+ parser.add_argument("--root", type=Path, default=None)+ args = parser.parse_args()++ if args.self_test:+ return self_test()++ failures = check(args.root or repo_root())+ for failure in failures:+ print(f"check_closure_authorization: {failure}", file=sys.stderr)+ if failures:+ return 1+ print(+ f"check_closure_authorization: OK — within services/agents, {LEDGER}:{GATED_FUNCTION} "+ "is the only path to 'resolved' and it is gated"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/app/agents/auto_triage_agent.py b/services/agents/app/agents/auto_triage_agent.pyindex fd87424ca..450a1862e 100644--- a/services/agents/app/agents/auto_triage_agent.py+++ b/services/agents/app/agents/auto_triage_agent.py@@ -37,6 +37,7 @@ from app.agents.dispositions import (TRUE_POSITIVE,normalize_disposition,)+from app.closure import authorization as closure_authorizationfrom app.closure.qa_sampling import ClosureQaSamplerfrom app.confidence import eligibilityfrom app.confidence.claim_support import score_claim_support@@ -138,18 +139,19 @@ def _alert_class_of(state: InvestigationState) -> str | None:Prefers the explicit category the fused alert carries; falls back to thedetection rule's category, which is what the shadow-mode grants arescoped by, so a grant and a policy row agree on what "this class" means.++ The ``raw_alert`` half delegates to :func:`app.closure.authorization.alert_class_of`+ rather than restating the key list. This function pre-checks the policy+ and the chokepoint at the durable write re-checks it; if the two derived+ the class differently, one policy row could pass here and fail there, and+ the disagreement would look like a flapping gate rather than two readers+ of the same field."""for attribute in ("alert_class", "category", "alert_category"):value = getattr(state, attribute, None)if isinstance(value, str) and value.strip():return value.strip()- raw = getattr(state, "raw_alert", None) or {}- if isinstance(raw, dict):- for key in ("alert_class", "category", "rule_category"):- value = raw.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- return None+ return closure_authorization.alert_class_of(getattr(state, "raw_alert", None) or {})def _scannable_fields(state: InvestigationState) -> list[tuple[str, Any]]:diff --git a/services/agents/app/closure/__init__.py b/services/agents/app/closure/__init__.pyindex 509c040da..f76bd4a6b 100644--- a/services/agents/app/closure/__init__.py+++ b/services/agents/app/closure/__init__.py@@ -7,6 +7,33 @@ with no caller look reachable to ``scripts/check_module_reachability.py``.Placing this here keeps that gate's verdict on ``guardrails`` honest."""-from .policy import ClosureDecision, decide, kill_switch_engaged, reset_cache, shared_pool+from .policy import (+ POOL_READY,+ POOL_UNAVAILABLE,+ POOL_UNCONFIGURED,+ ClosureDecision,+ decide,+ kill_switch_engaged,+ reset_cache,+ resolve_pool,+ shared_pool,+)-__all__ = ["ClosureDecision", "decide", "kill_switch_engaged", "reset_cache", "shared_pool"]+# `authorization` is deliberately NOT re-exported here. It imports+# `app.agents.dispositions`, and `app.agents` reaches back into this package,+# so eagerly importing it from the package root would be a cycle. Callers+# import `app.closure.authorization` directly, which is also the honest+# spelling for a chokepoint: it should be obvious in a diff when a module+# starts depending on it.++__all__ = [+ "POOL_READY",+ "POOL_UNAVAILABLE",+ "POOL_UNCONFIGURED",+ "ClosureDecision",+ "decide",+ "kill_switch_engaged",+ "reset_cache",+ "resolve_pool",+ "shared_pool",+]diff --git a/services/agents/app/closure/authorization.py b/services/agents/app/closure/authorization.pynew file mode 100644index 000000000..e4577bc01--- /dev/null+++ b/services/agents/app/closure/authorization.py@@ -0,0 +1,203 @@+"""The one place a production alert may be authorized to close itself.++Phase 1 of the closure remediation. See+`docs/remediation/phase-1-closure-authorization.md`.++Why this exists+---------------+Within this service, `alerts.status` becomes `'resolved'` in exactly one+statement: the `UPDATE alerts` at the end of+:func:`app.investigator.ledger.persist_auto_triage`,+whose `CASE WHEN $7 AND NOT $10 THEN 'resolved'` turns on a caller-supplied+`auto_closed` flag. Two production callers set that flag and only one of them+asked permission.++* :func:`app.agents.auto_triage_agent.run_auto_triage` consulted+ :func:`app.closure.policy.decide` — the kill switch, the tenant's policy+ row, the earned `auto_close` grant.+* :meth:`FusedAlertTriageWorker._maybe_suppress_from_memory` set+ `AgentStatus.COMPLETED` straight from a stored outcome prior, and+ `_record` forwarded `auto_closed=state.status is AgentStatus.COMPLETED`.+ The strings `closure_policy` and `kill_switch` appear in that module only+ inside comments.++A remembered verdict had become remembered permission. A trusted prior says+something about the *alert*; it says nothing about whether this tenant, today,+under the current policy, with the stop controls as they stand, permits a+machine to close it.++What this is not+----------------+It is **not** a second policy implementation. Thresholds, the enabled flag,+`require_grant` and the kill switch all stay in :mod:`app.closure.policy` and+are reached through :func:`policy.decide`. What this module adds is the set of+preconditions that are not per-tenant policy at all — the verdict has to be+auto-closeable, the run has to be real rather than a shadow or a replay, and+the reasoning has to be grounded in the evidence — and, crucially, a single+call site that every caller of the durable write passes through.++The agent still pre-checks the policy before it writes a verdict, because an+operator reading an alert wants "auto-close withheld: ..." in the findings+rather than silence. That pre-check is advisory. This one decides, it runs+against the state of the world at the moment of the write, and because it+lives inside `persist_auto_triage` a future caller cannot route around it+without removing it.++Why at the write and not at the decision+----------------------------------------+Retries, resumed work and deduplicated verdicts all persist a verdict that+was reached earlier, sometimes much earlier. An authorization computed with+the verdict and carried alongside it would let a tenant disable closure and+still have in-flight work close alerts afterwards. Evaluating here means the+answer is always derived from the policy that is in force when the row+changes, never from the one that was in force when the model answered.+"""++from __future__ import annotations++from collections.abc import Mapping+from dataclasses import dataclass+from typing import Any++import structlog++from app.closure import policy as closure_policy+from app.memory.institutional import POOL_READY, POOL_UNAVAILABLE, POOL_UNCONFIGURED++logger = structlog.get_logger()++__all__ = [+ "POOL_READY",+ "POOL_UNAVAILABLE",+ "POOL_UNCONFIGURED",+ "ClosureAuthorization",+ "alert_class_of",+ "authorize_auto_closure",+]++#: The keys a fused alert may carry its class under, in precedence order.+#: Shared with :func:`app.agents.auto_triage_agent._alert_class_of` rather+#: than restated, because the agent pre-checks the policy for one class and+#: this module re-checks it at the write: two derivations that disagreed+#: would let a policy row pass one and fail the other, and the result would+#: read as a flapping gate rather than as two readers of one field.+_CLASS_KEYS = ("alert_class", "category", "rule_category")+++@dataclass(frozen=True)+class ClosureAuthorization:+ """Whether this write may close the alert, and why not if it may not."""++ allowed: bool+ reason: str+ #: Which control decided. One of ``shadow``, ``verdict``,+ #: ``groundedness``, ``kill_switch``, ``policy``, ``default_deny``,+ #: ``error``. Written into the alert's findings so an operator asking+ #: "why is this still open" is told which control to look at, rather+ #: than being sent to debug a subsystem that is working.+ source: str+ threshold: float | None = None++ def __bool__(self) -> bool:+ return self.allowed+++def alert_class_of(raw_alert: Mapping[str, Any] | None) -> str | None:+ """The class a closure policy row and an `auto_close` grant key on."""+ if not isinstance(raw_alert, Mapping):+ return None+ for key in _CLASS_KEYS:+ value = raw_alert.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return None+++async def authorize_auto_closure(+ *,+ tenant_ref: str | None,+ raw_alert: Mapping[str, Any] | None,+ verdict: str,+ confidence: float,+ shadow: bool,+ ungrounded: bool | None,+ tier: str,+ default_threshold: float | None = None,+) -> ClosureAuthorization:+ """Decide whether this durable write may move an alert to ``resolved``.++ Called from :func:`app.investigator.ledger.persist_auto_triage` with the+ tenant already resolved to its canonical UUID, so the policy that is read+ is unambiguously the one belonging to the alert being closed.++ Every failure is a refusal. An unreadable policy, an unreachable+ database, a tenant that cannot be identified: none of them is a yes.+ """+ # Imported here, not at module scope, and this is the documented+ # circular-dependency exception rather than a style slip. The ledger+ # imports this module, `app.agents.__init__` eagerly imports+ # `auto_triage_agent`, and that reaches the ledger — so a top-level+ # `from app.agents.dispositions import ...` makes `app.closure.authorization`+ # unimportable with a partially-initialised-module error. The same applies+ # to `AUTO_CLOSE_THRESHOLD` below, which additionally is mutable at+ # runtime through `set_threshold`, so reading it per call is what keeps+ # the chokepoint and the agent's pre-check in step.+ from app.agents.dispositions import AUTO_CLOSEABLE_DISPOSITIONS, normalize_disposition++ if shadow:+ # Belt and braces. `persist_auto_triage`'s SQL already guards with+ # `NOT $10`, and `ShadowTriageWriter` already forces `auto_closed`+ # off. Repeating it here means the chokepoint's answer is complete on+ # its own terms, so a reader does not have to hold three mechanisms+ # in their head to know a shadow run cannot close anything.+ return ClosureAuthorization(False, "shadow run: production status is never changed by an observation", "shadow")++ normalized = normalize_disposition(str(verdict or ""), default="")+ if normalized not in AUTO_CLOSEABLE_DISPOSITIONS:+ return ClosureAuthorization(+ False,+ f"verdict {normalized or str(verdict)!r} is not auto-closeable; it escalates to a human",+ "verdict",+ )++ if ungrounded:+ # The groundedness gate demotes the verdict in the worker, but only+ # when it is switched on and only on the LLM path. Repeating the+ # refusal here means an ungrounded verdict cannot close an alert by+ # arriving through some other tier.+ return ClosureAuthorization(+ False,+ "the reasoning cites indicators the evidence does not contain, so the verdict is not fit to close on",+ "groundedness",+ )++ if not (tenant_ref or "").strip():+ return ClosureAuthorization(+ False,+ "no tenant on this verdict, so no policy can authorize closing it",+ "default_deny",+ )++ threshold = default_threshold+ if threshold is None:+ from app.agents.auto_triage_agent import AUTO_CLOSE_THRESHOLD++ threshold = AUTO_CLOSE_THRESHOLD++ decision = await closure_policy.decide(+ tenant_id=tenant_ref,+ alert_class=alert_class_of(raw_alert),+ confidence=float(confidence or 0.0),+ default_threshold=float(threshold),+ )++ if not decision.allowed:+ logger.info(+ "closure.authorization.withheld",+ tenant_id=tenant_ref,+ tier=tier,+ verdict=normalized,+ source=decision.source,+ reason=decision.reason,+ )+ return ClosureAuthorization(decision.allowed, decision.reason, decision.source, decision.threshold)diff --git a/services/agents/app/closure/policy.py b/services/agents/app/closure/policy.pyindex 44acb5b34..47605b531 100644--- a/services/agents/app/closure/policy.py+++ b/services/agents/app/closure/policy.py@@ -47,8 +47,23 @@ from typing import Anyimport structlog+from app.memory.institutional import POOL_READY, POOL_UNAVAILABLE, POOL_UNCONFIGURED+logger = structlog.get_logger()+__all__ = [+ "POOL_READY",+ "POOL_UNAVAILABLE",+ "POOL_UNCONFIGURED",+ "ClosureDecision",+ "decide",+ "kill_switch_engaged",+ "reset_cache",+ "resolve_closure_policy",+ "resolve_pool",+ "shared_pool",+]+#: Seconds a resolved policy or switch state is reused. Short, because the#: plan requires the switch to take effect "within one poll interval,#: without a restart", and a long cache would make that untrue.@@ -62,27 +77,36 @@ _cache: dict[str, tuple[float, Any]] = {}_pool_factory = None-async def _pool() -> Any | None:+async def resolve_pool() -> tuple[Any | None, str]:+ """The pool, and why there is not one.++ The state matters more than the pool. ``None`` used to be the only+ answer, and this module read it as "nothing is configured, fall back to+ the process-wide threshold" — permissive. But ``None`` also meant "a+ database is configured and we could not reach it", which must refuse.+ Those two are now different values and the callers below branch on them.+ """global _pool_factory # noqa: PLW0603if _pool_factory is None:- from app.memory.institutional import _get_pool+ from app.memory.institutional import connection_pool- _pool_factory = _get_pool+ _pool_factory = connection_pooltry:return await _pool_factory()except Exception as exc: # noqa: BLE001logger.warning("closure.pool.unavailable", error=str(exc))- return None+ return None, POOL_UNAVAILABLEasync def shared_pool() -> Any | None:"""The pool this package reads, for callers that need their own query.- Exported rather than left as `_pool`, so a caller does not reach- through the package into a private name the type checker refuses and- a refactor can silently move.+ Exported rather than left private, so a caller does not reach through+ the package into a name the type checker refuses and a refactor can+ silently move."""- return await _pool()+ pool, _ = await resolve_pool()+ return poolasync def decide(@@ -93,12 +117,14 @@ async def decide(default_threshold: float,) -> ClosureDecision:"""The call the triage path makes. Resolves its own pool."""+ pool, state = await resolve_pool()return await resolve_closure_policy(- await _pool(),+ pool,tenant_id=tenant_id,alert_class=alert_class,confidence=confidence,default_threshold=default_threshold,+ pool_state=state,)@@ -137,12 +163,23 @@ def _store(key: str, value: Any) -> None:_cache[key] = (time.monotonic() + _CACHE_TTL_SECONDS, value)-async def kill_switch_engaged(pool: Any, tenant_id: str | None) -> tuple[bool, str]:+async def kill_switch_engaged(+ pool: Any,+ tenant_id: str | None,+ *,+ pool_state: str = POOL_READY,+) -> tuple[bool, str]:"""Whether closure and dispatch are frozen, and the reason.Checks the global row and the tenant's row. Either engaged is enough:the platform operator can stop everything, and a tenant can stop theirown, and neither needs the other's agreement.++ ``pool_state`` exists because ``pool is None`` returned ``(False, "")``+ here — the switch reporting itself *not engaged* on a database it could+ not read. A stop control that answers "no" when it cannot answer at all+ is worse than one that is missing, because an operator who pressed it+ believes it took effect."""key = f"kill:{tenant_id or '-'}"hit = _cached(key)@@ -150,7 +187,12 @@ async def kill_switch_engaged(pool: Any, tenant_id: str | None) -> tuple[bool, sreturn hitif pool is None:- return (False, "")+ if pool_state == POOL_UNCONFIGURED:+ # No database anywhere, so there is no switch and nothing durable+ # to close either. Not cached: a deployment that gains a database+ # must not keep answering from before it had one.+ return (False, "")+ return (True, "__unreadable__:kill-switch state unreadable, refusing to auto-close")try:async with pool.acquire() as conn:@@ -191,23 +233,35 @@ async def resolve_closure_policy(alert_class: str | None,confidence: float,default_threshold: float,+ pool_state: str = POOL_READY,) -> ClosureDecision:"""Decide whether this verdict may close the alert without a human."""- engaged, why = await kill_switch_engaged(pool, tenant_id)+ engaged, why = await kill_switch_engaged(pool, tenant_id, pool_state=pool_state)if engaged:if why.startswith("__unreadable__:"):return ClosureDecision(False, default_threshold, why.split(":", 1)[1], source="error")return ClosureDecision(False, default_threshold, why, source="kill_switch")- if pool is None or not tenant_id:- # No database and no tenant: the process-wide threshold, exactly as- # before this module existed.- allowed = confidence >= default_threshold+ if pool is None:+ # Reached only for POOL_UNCONFIGURED; the unavailable case already+ # refused above, through the switch. Either way there is no recorded+ # authorization to read, and automatic closure requires one.return ClosureDecision(- allowed,+ False,default_threshold,- f"process-wide threshold {default_threshold:.2f}",- source="env",+ "no closure policy store is configured, so no tenant has authorized automatic closure",+ source="default_deny",+ )++ if not tenant_id:+ # A closure that cannot be attributed to a tenant cannot be+ # authorized by one. This used to fall through to the process-wide+ # threshold, which authorized it on behalf of nobody.+ return ClosureDecision(+ False,+ default_threshold,+ "no tenant on this verdict, so no policy can authorize closing it",+ source="default_deny",)key = f"policy:{tenant_id}:{alert_class or '-'}"@@ -241,13 +295,25 @@ async def resolve_closure_policy(row = Noneif row is None:- # No policy configured. Additive: behave as before.- allowed = confidence >= default_threshold+ # No policy configured, and that is not consent.+ #+ # This used to apply the process-wide threshold, so every tenant+ # auto-closed from the first confident benign verdict — including one+ # that had never opened the screen. The absence of a row is the+ # absence of a decision, and inferring authorization from it is+ # exactly what this phase exists to stop. Nothing is inferred from a+ # tenant's history either: a tenant that was auto-closing yesterday+ # because of this default is not thereby authorized today.+ #+ # Migration 122 records, per tenant, which side of this change each+ # deployment fell on, so an operator can see who is affected and+ # re-authorize deliberately rather than discovering it from a queue+ # that stopped draining.return ClosureDecision(- allowed,+ False,default_threshold,- f"no tenant policy, process-wide threshold {default_threshold:.2f}",- source="env",+ f"{alert_class or 'this tenant'} has no closure policy, and automatic closure requires an explicit one",+ source="default_deny",)if not row["enabled"]:diff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.pyindex b4dd4a77f..0c403636d 100644--- a/services/agents/app/investigator/ledger.py+++ b/services/agents/app/investigator/ledger.py@@ -33,6 +33,7 @@ from typing import Anyimport asyncpgimport structlog+from app.closure.authorization import authorize_auto_closurefrom app.investigator.chatops_notify import notify_chatopslogger = structlog.get_logger()@@ -572,6 +573,40 @@ async def persist_auto_triage(logger.debug("ledger.auto_triage_skip", reason="unknown_tenant", tenant_ref=tenant_ref)return Falseawait _set_rls_context(conn, tenant_id)++ # The authorization chokepoint. This is the only statement in the+ # service that can set `alerts.status = 'resolved'`, so it is the+ # only place the question has to be asked — and asking it here+ # rather than in each caller is what stops a future path closing+ # alerts without one. `_maybe_suppress_from_memory` was exactly+ # that path: it reached this function with `auto_closed=True`+ # having consulted no policy, no grant and no kill switch.+ #+ # Evaluated against the tenant this row actually belongs to, not+ # the caller's `tenant_ref`, and immediately before the write+ # rather than when the verdict was reached — so a retry, a resumed+ # run or a deduplicated verdict is judged by the policy in force+ # now. An authorization that travelled with a verdict would let a+ # tenant disable closure and still have in-flight work close+ # alerts behind them.+ if auto_closed:+ authorization = await authorize_auto_closure(+ tenant_ref=str(tenant_id),+ raw_alert=raw_alert,+ verdict=verdict,+ confidence=confidence,+ shadow=shadow,+ ungrounded=bool(ungrounded),+ tier=tier,+ )+ if not authorization.allowed:+ auto_closed = False+ # Said out loud on the alert itself. An alert that+ # silently stays open is a support ticket, and the+ # agent's own pre-check cannot have written this reason+ # because the policy may have changed since.+ findings = [*(findings or []), f"Auto-close withheld ({authorization.source}): {authorization.reason}"]+async with conn.transaction():await conn.execute("""diff --git a/services/agents/app/memory/institutional.py b/services/agents/app/memory/institutional.pyindex 062dbd45d..579503d71 100644--- a/services/agents/app/memory/institutional.py+++ b/services/agents/app/memory/institutional.py@@ -29,10 +29,35 @@ from app.core.schema_bootstrap import ensure_tablelogger = structlog.get_logger()+#: Why there is, or is not, a connection pool. The distinction is the whole+#: point: ``None`` used to mean all three of these at once, and+#: ``app.closure.policy`` read that single ``None`` as "no database is+#: configured, use the permissive process-wide default". It is far more+#: reachable than that — any exception from ``create_pool`` and any failure of+#: the bootstrap probe below produce the same ``None`` — so a missing+#: migration or an ACL problem on a table the closure policy never reads+#: silently disabled the closure policy and the kill switch together, logged+#: at ``debug``.+#:+#: ``POOL_UNCONFIGURED`` is a deployment that has no ``DATABASE_URL``.+#: ``POOL_UNAVAILABLE`` is a deployment that has one and could not use it.+#: A caller making a safety decision must be able to tell those apart.+POOL_READY = "ready"+POOL_UNCONFIGURED = "unconfigured"+POOL_UNAVAILABLE = "unavailable"+_FALLBACK: dict[str, Any] = {}_POOL: Any = None # asyncpg.Pool | None+#: The connected pool, independent of whether this module's own table exists.+#: Shared with ``app.closure``; see :func:`connection_pool`.+_RAW_POOL: Any = None++#: Tri-state: ``None`` not yet probed, ``True``/``False`` the probe's answer.+#: Cached so a deployment without the table does not re-probe on every read.+_MEMORY_TABLE_READY: bool | None = None+#: Only used when the table is genuinely absent — normally it arrives with#: ``services/api/migrations/022_institutional_memory.sql``, which also gives#: it the RLS policy this copy cannot.@@ -57,31 +82,96 @@ def _normalise_dsn(url: str) -> str:return url.replace("postgresql+asyncpg://", "postgresql://").replace("postgres+asyncpg://", "postgresql://")-async def _get_pool() -> Any | None:- global _POOL- if _POOL is not None:- return _POOL+async def _connect() -> tuple[Any | None, str]:+ """Open, or reuse, the pool. Requires no particular table to exist.++ Split from :func:`_get_pool` so that this module's own bootstrap cannot+ decide whether *other* readers of the same database get a connection.+ It used to: a failed probe on ``aisoc_institutional_memory`` closed the+ pool and returned ``None``, and the closure policy — which reads two+ entirely different tables — resolved its pool through here and read that+ ``None`` as permission to fall back to a permissive default.+ """+ global _RAW_POOL+ if _RAW_POOL is not None:+ return _RAW_POOL, POOL_READY+dsn = os.environ.get("DATABASE_URL", "").strip()if not dsn:- return None+ return None, POOL_UNCONFIGURED+try:import asyncpg # type: ignore[import]- pool = await asyncpg.create_pool(_normalise_dsn(dsn), min_size=1, max_size=3)+ _RAW_POOL = await asyncpg.create_pool(_normalise_dsn(dsn), min_size=1, max_size=3)+ except Exception as exc:+ # `warning`, not `debug`. A deployment that configured a database and+ # did not get one is a fault an operator has to see, and a safety+ # control is about to refuse because of it.+ logger.warning("memory.institutional.db_unavailable", error=str(exc))+ return None, POOL_UNAVAILABLE++ return _RAW_POOL, POOL_READY+++async def connection_pool() -> tuple[Any | None, str]:+ """A pool to the operational database, and why there is not one.++ The accessor other packages use. Returns the same pool+ :func:`_get_pool` would, without requiring this module's table: a reader+ of ``aisoc_closure_policies`` has no stake in whether+ ``aisoc_institutional_memory`` exists, and making it one is how a missing+ migration turned into a disabled kill switch.+ """+ return await _connect()+++async def close_pool() -> None:+ """Release the shared pool. For tests and for a clean shutdown."""+ global _POOL, _RAW_POOL, _MEMORY_TABLE_READY+ pool, _RAW_POOL = _RAW_POOL, None+ _POOL = None+ _MEMORY_TABLE_READY = None+ if pool is not None:+ await pool.close()+++async def _get_pool() -> Any | None:+ """The pool *this* store may use: the table has to be there.++ Still returns ``None`` when the probe fails, because the memory store+ genuinely cannot work without its table and falls back to the in-process+ dict. What changed is that the failure no longer closes the connection+ everything else shares.+ """+ global _POOL, _MEMORY_TABLE_READY+ if _POOL is not None:+ return _POOL++ pool, state = await _connect()+ if pool is None or state != POOL_READY:+ return None++ if _MEMORY_TABLE_READY is False:+ return None++ try:# Probe before creating: the runtime role holds DML only, and# `CREATE TABLE IF NOT EXISTS` checks the schema ACL before the# existence test, so it raises even when the table is there. See# app/core/schema_bootstrap.py.async with pool.acquire() as conn:- if not await ensure_table(conn, "aisoc_institutional_memory", _MEMORY_DDL):- await pool.close()- return None- _POOL = pool- return _POOL+ _MEMORY_TABLE_READY = bool(await ensure_table(conn, "aisoc_institutional_memory", _MEMORY_DDL))except Exception as exc:- logger.debug("memory.institutional.db_unavailable", error=str(exc))+ logger.debug("memory.institutional.table_unavailable", error=str(exc))+ _MEMORY_TABLE_READY = False++ if not _MEMORY_TABLE_READY:return None+ _POOL = pool+ return _POOL+async def institutional_get(tenant_id: str, key: str) -> Any | None:pool = await _get_pool()diff --git a/services/agents/tests/conftest.py b/services/agents/tests/conftest.pyindex c3a715b09..599c3bcd4 100644--- a/services/agents/tests/conftest.py+++ b/services/agents/tests/conftest.py@@ -56,6 +56,51 @@ def _reset_agent_singletons():_RESPONSE_CACHE.clear()+def authorized_closure_tenant(monkeypatch: pytest.MonkeyPatch):+ """A tenant that has explicitly authorized automatic closure.++ Automatic closure is default-deny since the Phase 1 closure remediation:+ a tenant with no row in `aisoc_closure_policies` does not auto-close, and+ neither does a deployment with no policy store at all — which is every+ test in this suite, because `_no_ambient_database` removes the DSN.++ That makes "did this alert auto-close?" ambiguous for a test about some+ *other* control. `test_clean_evidence_still_autocloses` is really+ asserting that the prompt-injection guard did not demote a clean verdict;+ it has no opinion about closure policy, and without this fixture it would+ be asserting the closure default instead and would pass or fail for a+ reason it never mentions.++ Deliberately opt-in rather than autouse. Requesting it by name is the+ test saying out loud which side of the default it assumes, and an+ autouse version would make the whole suite permissive and hide the new+ default from every test at once.++ Nothing that covers authorization itself uses this. Those tests drive the+ real policy (`test_closure_authorization.py`) and the real policy against+ real Postgres (`tests/isolation/test_closure_authorization_live.py`).+ """+ from app import closure as closure_package+ from app.closure import policy as closure_policy++ async def _authorized(*, tenant_id, alert_class, confidence, default_threshold): # noqa: ANN001, ANN202, ARG001+ return closure_policy.ClosureDecision(+ confidence >= default_threshold,+ default_threshold,+ "test fixture: this tenant has authorized automatic closure",+ source="policy",+ )++ # Both spellings. `auto_triage_agent` calls `app.closure.decide` (the+ # package re-export) and the ledger chokepoint calls+ # `app.closure.policy.decide`; patching one would leave the other live and+ # the test would turn on which path it happened to take.+ monkeypatch.setattr(closure_package, "decide", _authorized)+ monkeypatch.setattr(closure_policy, "decide", _authorized)+ return _authorized++@pytest.fixture(autouse=True)def _no_ambient_database(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch):"""Run the unit suite with no database, and fail loudly if one is reached.diff --git a/services/agents/tests/test_auto_triage_autonomy_eligibility.py b/services/agents/tests/test_auto_triage_autonomy_eligibility.pyindex f63dbf2e7..ba7353c20 100644--- a/services/agents/tests/test_auto_triage_autonomy_eligibility.py+++ b/services/agents/tests/test_auto_triage_autonomy_eligibility.py@@ -92,7 +92,7 @@ async def test_the_eligibility_verdict_is_recorded_on_every_closure(pin_model) -assert "not measured" in basis[0]-async def test_unmeasured_does_not_block_by_default(pin_model) -> None:+async def test_unmeasured_does_not_block_by_default(pin_model, authorized_closure_tenant) -> None:"""Additive: a deployment that has measured nothing behaves as it did."""pin_model(_closeable())@@ -101,7 +101,9 @@ async def test_unmeasured_does_not_block_by_default(pin_model) -> None:assert state.status is AgentStatus.COMPLETED-async def test_the_strict_posture_withholds_a_closure_the_threshold_allowed(pin_model, monkeypatch: pytest.MonkeyPatch) -> None:+async def test_the_strict_posture_withholds_a_closure_the_threshold_allowed(+ pin_model, authorized_closure_tenant, monkeypatch: pytest.MonkeyPatch+) -> None:monkeypatch.setenv("AISOC_AUTONOMY_REQUIRE_MEASURED", "1")pin_model(_closeable())@@ -112,7 +114,9 @@ async def test_the_strict_posture_withholds_a_closure_the_threshold_allowed(pin_assert any("Auto-close withheld" in f and "not measured" in f for f in state.findings)-async def test_a_measurement_below_the_floor_withholds_the_closure(pin_model, monkeypatch: pytest.MonkeyPatch) -> None:+async def test_a_measurement_below_the_floor_withholds_the_closure(+ pin_model, authorized_closure_tenant, monkeypatch: pytest.MonkeyPatch+) -> None:"""A graded configuration that fell short blocks regardless of posture."""prompt = auto_triage_agent._triage_prompt()state = _state()@@ -141,7 +145,9 @@ async def test_a_measurement_below_the_floor_withholds_the_closure(pin_model, moassert any("0.62" in f for f in out.findings)-async def test_a_clearing_measurement_closes_and_says_what_it_rested_on(pin_model, monkeypatch: pytest.MonkeyPatch) -> None:+async def test_a_clearing_measurement_closes_and_says_what_it_rested_on(+ pin_model, authorized_closure_tenant, monkeypatch: pytest.MonkeyPatch+) -> None:"""The positive control. A gate stuck closed reads exactly like working caution."""prompt = auto_triage_agent._triage_prompt()state = _state()diff --git a/services/agents/tests/test_auto_triage_claim_support.py b/services/agents/tests/test_auto_triage_claim_support.pyindex 7f58d9bcf..654172486 100644--- a/services/agents/tests/test_auto_triage_claim_support.py+++ b/services/agents/tests/test_auto_triage_claim_support.py@@ -95,7 +95,7 @@ async def test_unsupported_authorization_claim_blocks_the_closure(pin_model) ->assert any(b.startswith("claim_support=") for b in state.confidence_basis)-async def test_an_evidenced_authorization_claim_still_closes(pin_model) -> None:+async def test_an_evidenced_authorization_claim_still_closes(pin_model, authorized_closure_tenant) -> None:"""The legitimate case. A check that refuses this is one somebody disables."""alert = {**SCAN_ALERT, "change_ticket": "CHG0049112", "approved_by": "security-engineering"}pin_model(@@ -112,7 +112,7 @@ async def test_an_evidenced_authorization_claim_still_closes(pin_model) -> None:assert not any("Auto-close blocked" in f for f in state.findings)-async def test_a_rationale_making_no_decisive_claim_still_closes(pin_model) -> None:+async def test_a_rationale_making_no_decisive_claim_still_closes(pin_model, authorized_closure_tenant) -> None:"""Not scored must not behave like a score of zero."""pin_model({diff --git a/services/agents/tests/test_auto_triage_dispositions.py b/services/agents/tests/test_auto_triage_dispositions.pyindex 77eaec562..c655a58ff 100644--- a/services/agents/tests/test_auto_triage_dispositions.py+++ b/services/agents/tests/test_auto_triage_dispositions.py@@ -94,7 +94,7 @@ def test_btp_is_a_valid_detection_not_a_false_positive():@pytest.mark.asyncio-async def test_approved_penetration_test_is_benign_true_positive(monkeypatch):+async def test_approved_penetration_test_is_benign_true_positive(monkeypatch, authorized_closure_tenant):_patch_llm(monkeypatch, BENIGN_TRUE_POSITIVE, 0.95, "approved red-team engagement, matches change ticket CHG0049112")# The evidence now carries the approval the rationale cites. It did not,# and this test asserted the closure anyway — so it was pinning "an@@ -140,7 +140,7 @@ async def test_scheduled_scanner_is_benign_true_positive(monkeypatch):@pytest.mark.asyncio-async def test_genuine_false_positive(monkeypatch):+async def test_genuine_false_positive(monkeypatch, authorized_closure_tenant):_patch_llm(monkeypatch, FALSE_POSITIVE, 0.92, "rule misfired on a mis-parsed command-line field")out = await ata.run_auto_triage(_state("Suspicious PowerShell", {"severity": "low", "risk_score": 0.1}))assert out.verdict == FALSE_POSITIVEdiff --git a/services/agents/tests/test_auto_triage_injection.py b/services/agents/tests/test_auto_triage_injection.pyindex f9b673e9c..bdf118a6a 100644--- a/services/agents/tests/test_auto_triage_injection.py+++ b/services/agents/tests/test_auto_triage_injection.py@@ -55,7 +55,7 @@ async def test_prompt_injection_in_evidence_blocks_autoclose(monkeypatch):@pytest.mark.asyncio-async def test_clean_evidence_still_autocloses(monkeypatch):+async def test_clean_evidence_still_autocloses(monkeypatch, authorized_closure_tenant):_patch_llm(monkeypatch, FALSE_POSITIVE, 0.98)ata._metrics["injection_demoted"] = 0st = _state("Scheduled scan", {"severity": "low", "note": "Nessus scheduled vulnerability scan from 10.0.0.5"})diff --git a/services/agents/tests/test_closure_authorization.py b/services/agents/tests/test_closure_authorization.pynew file mode 100644index 000000000..1559b3c1b--- /dev/null+++ b/services/agents/tests/test_closure_authorization.py@@ -0,0 +1,352 @@+"""The closure chokepoint: default-deny, fail-closed, and nothing routes around it.++Phase 1 of the closure remediation. See+`docs/remediation/phase-1-closure-authorization.md`.++The live half of this is `tests/isolation/test_closure_authorization_live.py`,+which drives real Postgres. What is here is the part a database cannot answer:+what the module does when there is no database, and whether every production+path that can close an alert actually goes through the gate.++The second half deserves a note. `test_closure_policy.py` already carried a+wiring test, and it asserted `"closure_policy.decide(" in source` against one+function. That is the weak shape this repository keeps rediscovering: it+confirms the path somebody remembered to check, and says nothing about the+path they forgot — which is precisely how the outcome-memory closure went+unnoticed for as long as it did. The replacement below enumerates every site+in the service that can set `alerts.status = 'resolved'` and requires each one+to be governed, so a new path fails the test by existing.+"""++from __future__ import annotations++import subprocess+from contextlib import asynccontextmanager+from pathlib import Path++import pytest+from app.closure import policy as closure+++def _repo_root() -> Path:+ """The repository per git, not per this file's position in it.++ Counting directories above `__file__` is the thing+ `scripts/gate_toolkit.repo_root` exists to stop: four levels up is+ whatever happens to be there, and the repo's own meta-gate rejects it.+ """+ out = subprocess.run( # noqa: S603+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ check=False,+ cwd=Path(__file__).resolve().parent,+ )+ if out.returncode == 0 and out.stdout.strip():+ return Path(out.stdout.strip()).resolve()+ return Path(__file__).resolve().parents[3]+++class _Conn:+ def __init__(self, *, policy_row=None, grant=None, switches=()): # noqa: ANN001+ self.policy_row = policy_row+ self.grant = grant+ self.switches = list(switches)++ async def fetchrow(self, sql: str, *args): # noqa: ANN001, ARG002+ if "autonomy_grants" in sql:+ return self.grant+ return self.policy_row++ async def fetch(self, sql: str, *args): # noqa: ANN001, ARG002+ return self.switches+++class _Pool:+ def __init__(self, conn: _Conn) -> None:+ self._conn = conn++ @asynccontextmanager+ async def acquire(self):+ yield self._conn++[email protected](autouse=True)+def _clear_cache():+ closure.reset_cache()+ yield+ closure.reset_cache()+++class TestTheDefaultIsRefusal:+ """Finding 14. The absence of a policy row was read as permission."""++ async def test_a_tenant_with_no_policy_row_is_not_authorized(self) -> None:+ decision = await closure.resolve_closure_policy(+ _Pool(_Conn(policy_row=None)),+ tenant_id="t1",+ alert_class="identity",+ confidence=0.99,+ default_threshold=0.85,+ )+ assert decision.allowed is False, (+ "a tenant that has configured nothing auto-closed, so automatic closure did not require explicit authorization"+ )+ assert decision.source == "default_deny"++ async def test_an_explicit_policy_still_decides(self) -> None:+ """The positive control. Default-deny must not mean deny-everything."""+ decision = await closure.resolve_closure_policy(+ _Pool(_Conn(policy_row={"enabled": True, "threshold": 0.80, "require_grant": False, "alert_class": "identity"})),+ tenant_id="t1",+ alert_class="identity",+ confidence=0.99,+ default_threshold=0.85,+ )+ assert decision.allowed is True+ assert decision.source == "policy"++ async def test_a_missing_tenant_is_not_authorized(self) -> None:+ """A closure that cannot be attributed to a tenant cannot be authorized."""+ decision = await closure.resolve_closure_policy(+ _Pool(_Conn(policy_row=None)),+ tenant_id=None,+ alert_class=None,+ confidence=1.0,+ default_threshold=0.85,+ )+ assert decision.allowed is False+++class TestAnUnavailableDatabaseRefuses:+ """Finding 10. `pool is None` was permissive, and it is far more reachable+ than "no database configured": `institutional._get_pool` returns None on+ any exception from `create_pool` *and* when the bootstrap probe on an+ unrelated table fails. A missing migration therefore disabled the closure+ policy and the kill switch together, logged at `debug`."""++ async def test_a_pool_that_failed_to_open_refuses(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def _unavailable():+ return None, closure.POOL_UNAVAILABLE++ monkeypatch.setattr(closure, "resolve_pool", _unavailable)++ decision = await closure.decide(+ tenant_id="t1",+ alert_class="identity",+ confidence=1.0,+ default_threshold=0.85,+ )+ assert decision.allowed is False, "a database that is configured but unreachable was read as permission to close"+ assert decision.source == "error"++ async def test_an_unconfigured_database_refuses_too(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """No database means no recorded authorization, which is not a yes."""++ async def _unconfigured():+ return None, closure.POOL_UNCONFIGURED++ monkeypatch.setattr(closure, "resolve_pool", _unconfigured)++ decision = await closure.decide(+ tenant_id="t1",+ alert_class="identity",+ confidence=1.0,+ default_threshold=0.85,+ )+ assert decision.allowed is False++ async def test_the_kill_switch_refuses_when_the_pool_is_unavailable(self) -> None:+ engaged, reason = await closure.kill_switch_engaged(None, "t1", pool_state=closure.POOL_UNAVAILABLE)+ assert engaged is True, "an unreadable stop control was reported as not engaged"+ assert "unreadable" in reason+++class TestTheMemoryTableDoesNotGateTheClosurePolicy:+ """The institutional-memory bootstrap must not be able to switch closure off.++ `_get_pool` probed `aisoc_institutional_memory` and, when the probe+ failed, closed the pool and returned None — so an ACL problem or a missing+ migration on a table the closure policy never reads took the policy and+ the kill switch down with it.+ """++ async def test_a_failed_memory_bootstrap_still_yields_a_pool(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from app.memory import institutional++ sentinel = object()++ async def _connect():+ return sentinel, institutional.POOL_READY++ async def _probe_fails(*args, **kwargs): # noqa: ANN002, ANN003, ARG001+ return False++ monkeypatch.setattr(institutional, "_connect", _connect)+ monkeypatch.setattr(institutional, "ensure_table", _probe_fails)+ monkeypatch.setattr(institutional, "_POOL", None, raising=False)+ monkeypatch.setattr(institutional, "_MEMORY_TABLE_READY", None, raising=False)++ pool, state = await institutional.connection_pool()++ assert pool is sentinel, "a failed memory-table probe removed the pool the closure policy reads"+ assert state == institutional.POOL_READY+ assert await institutional._get_pool() is None, "the memory store itself must still decline its unusable table"+++class TestTheChokepointItself:+ async def test_a_verdict_that_is_not_auto_closeable_is_refused(self) -> None:+ from app.closure import authorization++ decision = await authorization.authorize_auto_closure(+ tenant_ref="t1",+ raw_alert={"category": "identity"},+ verdict="true_positive",+ confidence=1.0,+ shadow=False,+ ungrounded=False,+ tier="llm",+ )+ assert decision.allowed is False+ assert decision.source == "verdict"++ async def test_a_shadow_run_is_refused(self) -> None:+ from app.closure import authorization++ decision = await authorization.authorize_auto_closure(+ tenant_ref="t1",+ raw_alert={},+ verdict="benign",+ confidence=1.0,+ shadow=True,+ ungrounded=False,+ tier="llm",+ )+ assert decision.allowed is False+ assert decision.source == "shadow"++ async def test_an_ungrounded_verdict_is_refused(self) -> None:+ """Evidence quality is a precondition of closure, not a label on it."""+ from app.closure import authorization++ decision = await authorization.authorize_auto_closure(+ tenant_ref="t1",+ raw_alert={},+ verdict="benign",+ confidence=1.0,+ shadow=False,+ ungrounded=True,+ tier="llm",+ )+ assert decision.allowed is False+ assert decision.source == "groundedness"++ async def test_the_reason_is_always_populated(self) -> None:+ """An alert that silently stays open is a support ticket."""+ from app.closure import authorization++ decision = await authorization.authorize_auto_closure(+ tenant_ref="t1",+ raw_alert={},+ verdict="benign",+ confidence=1.0,+ shadow=True,+ ungrounded=False,+ tier="memory",+ )+ assert decision.reason.strip()++ async def test_the_alert_class_matches_what_the_agent_resolves(self) -> None:+ """Both sides must mean the same thing by "this class".++ The agent pre-checks the policy for one class and the chokepoint+ re-checks it at the write. If they derived the class differently, a+ policy row could pass one and fail the other, and the disagreement+ would read as a flapping gate rather than as two readers.+ """+ import uuid as _uuid++ from app.agents import auto_triage_agent+ from app.closure import authorization+ from app.models.state import InvestigationState++ raw = {"id": "a", "category": "identity"}+ state = InvestigationState(incident_id=_uuid.uuid4(), tenant_id=_uuid.uuid4(), raw_alert=raw)++ assert auto_triage_agent._alert_class_of(state) == authorization.alert_class_of(raw)+++class TestNothingRoutesAroundTheChokepoint:+ """Enumerates the closure paths instead of spot-checking one of them."""++ def test_the_chokepoint_gate_passes(self) -> None:+ """Runs `scripts/check_closure_authorization.py` rather than restating it.++ The gate asserts that only the ledger carries SQL which can set an+ alert to `'resolved'`, and that the function holding it calls the+ chokepoint. Shelling out keeps one implementation: a copy of the+ detector here is the copy that drifts, and this repository has shipped+ that exact shape more than once.+ """+ import subprocess+ import sys++ root = _repo_root()+ gate = root / "scripts" / "check_closure_authorization.py"+ assert gate.is_file(), f"the closure chokepoint gate is missing at {gate}"++ result = subprocess.run( # noqa: S603+ [sys.executable, str(gate), "--root", str(root)],+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, f"closure chokepoint gate failed:\n{result.stdout}\n{result.stderr}"++ def test_the_gate_itself_detects_both_ways(self) -> None:+ """A gate nobody proved is a gate nobody should believe."""+ import subprocess+ import sys++ result = subprocess.run( # noqa: S603+ [sys.executable, str(_repo_root() / "scripts" / "check_closure_authorization.py"), "--self-test"],+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, f"closure chokepoint gate self-test failed:\n{result.stdout}\n{result.stderr}"++ def test_the_ledger_consults_the_chokepoint_before_closing(self) -> None:+ import inspect++ from app.investigator import ledger as ledger_module++ source = inspect.getsource(ledger_module.persist_auto_triage)+ assert "authorize_auto_closure(" in source, (+ "persist_auto_triage can set alerts.status='resolved' without consulting the closure authorization"+ )++ def test_every_caller_of_persist_auto_triage_is_covered(self) -> None:+ """The reason this is an enumeration and not a spot check.++ Each of these reaches the one durable write with a caller-supplied+ `auto_closed`. Listing them makes a new one a test failure rather+ than a silent fourth path.+ """+ import pathlib++ root = pathlib.Path(__file__).resolve().parents[1] / "app"+ callers = {+ path.relative_to(root).as_posix() for path in root.rglob("*.py") if "persist_auto_triage(" in path.read_text(encoding="utf-8")+ }+ assert callers == {+ "investigator/ledger.py",+ "workers/fused_alert_consumer.py",+ "workers/shadow_mode.py",+ "workers/triage_persistence.py",+ "replay/shadow.py",+ }, f"the set of modules reaching the durable closure write changed: {sorted(callers)}"diff --git a/services/agents/tests/test_closure_policy.py b/services/agents/tests/test_closure_policy.pyindex 078220ceb..6d00cef6b 100644--- a/services/agents/tests/test_closure_policy.py+++ b/services/agents/tests/test_closure_policy.py@@ -61,14 +61,22 @@ def _clear_cache():@pytest.mark.asyncioclass TestPerTenantPolicy:- async def test_no_policy_row_behaves_exactly_as_before(self) -> None:- """Additive. A deployment that configures nothing is unchanged."""+ async def test_no_policy_row_is_not_authorization(self) -> None:+ """This used to assert the opposite, and that was the defect.++ The original reading was "additive: a deployment that configures+ nothing is unchanged", which was true of the code and wrong as a+ posture — it made the absence of a decision into a decision, so every+ tenant auto-closed from its first confident benign verdict. Closure+ remediation Finding 14; the behaviour is covered end to end in+ `test_closure_authorization.py` and the live suite.+ """pool = _Pool(_Conn(policy_row=None))decision = await closure.resolve_closure_policy(pool, tenant_id="t1", alert_class="identity", confidence=0.9, default_threshold=0.85)- assert decision.allowed is True- assert decision.source == "env"+ assert decision.allowed is False+ assert decision.source == "default_deny"assert decision.threshold == 0.85async def test_a_tenant_can_disable_closure_for_one_class(self) -> None:@@ -188,16 +196,27 @@ class TestFailureIsRefusal:class TestTheWiring:"""The policy is consulted by the real closure decision, not justimportable. A passing test on an uncalled function is indistinguishable- from a working feature until someone traces the call graph."""+ from a working feature until someone traces the call graph.++ These two assert the *agent's* pre-check, which is advisory: it is what+ puts "auto-close withheld" in front of an operator. Authorization itself+ is decided at the durable write, and the test that no path can reach that+ write ungoverned is+ `test_closure_authorization.TestNothingRoutesAroundTheChokepoint`, which+ enumerates every closure path rather than checking the one somebody+ remembered. The enumeration exists because this class, in its original+ form, was the whole of the wiring coverage — and the second closure path+ went unnoticed underneath it for exactly that reason.+ """- def test_the_triage_agent_calls_the_policy(self) -> None:+ def test_the_triage_agent_pre_checks_the_policy(self) -> None:import inspectfrom app.agents import auto_triage_agentsource = inspect.getsource(auto_triage_agent.run_auto_triage)assert "closure_policy.decide(" in source, (- "run_auto_triage does not consult the closure policy, so the policy table is another mechanism with no reader"+ "run_auto_triage does not consult the closure policy, so an operator loses the explanation on the alert")assert "should_auto_close = verdict in AUTO_CLOSEABLE_DISPOSITIONS and closure.allowed" in sourcediff --git a/services/agents/tests/test_tool_result_channel.py b/services/agents/tests/test_tool_result_channel.pyindex bc7cdf383..fdb4f9034 100644--- a/services/agents/tests/test_tool_result_channel.py+++ b/services/agents/tests/test_tool_result_channel.py@@ -284,7 +284,11 @@ class TestAVerdictRestingOnACallThatNeverHappened:assert any("enrich_ioc" in f and "never called" in f for f in out.findings)@pytest.mark.asyncio- async def test_an_ordinary_rationale_still_auto_closes(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_an_ordinary_rationale_still_auto_closes(+ self,+ monkeypatch: pytest.MonkeyPatch,+ authorized_closure_tenant, # noqa: ANN001+ ) -> None:"""The negative control for the demotion. A check that blocks everyclosure is indistinguishable from a broken one."""# Reasons from the telemetry and claims no authorization. It used todiff --git a/services/api/migrations/122_closure_authorization_default_deny.sql b/services/api/migrations/122_closure_authorization_default_deny.sqlnew file mode 100644index 000000000..9e12df6dc--- /dev/null+++ b/services/api/migrations/122_closure_authorization_default_deny.sql@@ -0,0 +1,124 @@+-- 122_closure_authorization_default_deny.sql+--+-- Record what the closure default-deny change means for each tenant on this+-- deployment, so an operator can see who is affected and re-authorize+-- deliberately.+--+-- What changed in the code+-- ────────────────────────+-- ``app/closure/policy.py`` used to treat a tenant with no row in+-- ``aisoc_closure_policies`` as permission to auto-close at the process-wide+-- threshold (``AISOC_AUTO_CLOSE_THRESHOLD``, 0.85). Every tenant therefore+-- auto-closed from the first confident benign verdict, including one that had+-- never opened the screen. The absence of a decision was being read as a+-- decision.+--+-- From now on, automatic closure requires an explicit, enabled policy row.+--+-- What this migration does NOT do, and why+-- ────────────────────────────────────────+-- It creates no policy rows. It would be easy to write an INSERT that gave a+-- row to every tenant that had auto-closed in the past — and that would be+-- the same mistake in a different place: inferring authorization from+-- behaviour that the old default produced. A tenant that was auto-closing+-- yesterday *because nobody had decided anything* has still not decided+-- anything. Only a human may grant this, through the console or by the SQL in+-- the rollback section below.+--+-- Deliberately configured tenants are untouched. A row that says+-- ``enabled = true`` keeps auto-closing at its own threshold, and a row that+-- says ``enabled = false`` keeps refusing: both are explicit, and this change+-- is about the tenants who had neither.+--+-- What it does instead+-- ────────────────────+-- Writes one row per existing tenant saying which side of the change that+-- tenant fell on, at the moment the migration ran. That is the "recorded+-- outcome": a deployment upgrading into default-deny can answer "which of my+-- tenants just lost automatic closure" with a query rather than with a+-- support ticket from the tenant.+--+-- Forward-only. Re-running it is safe and records nothing a second time.++CREATE TABLE IF NOT EXISTS aisoc_closure_authorization_migration (+ tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,++ -- TRUE when the tenant already had at least one row in+ -- `aisoc_closure_policies` at migration time, i.e. somebody had made a+ -- deliberate choice that this change preserves verbatim.+ had_explicit_policy BOOLEAN NOT NULL,++ -- TRUE when at least one of those rows was enabled. NULL when there were+ -- no rows at all — "not applicable", which is a different fact from+ -- "there was a row and it was off".+ was_enabled BOOLEAN,++ -- The tenant's posture after this change, in one word, so the common+ -- question needs no joins: 'preserved' (an explicit row decides, as+ -- before) or 'requires_authorization' (closure was implicit and is now+ -- withheld until somebody authorizes it).+ outcome TEXT NOT NULL+ CHECK (outcome IN ('preserved', 'requires_authorization')),++ recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++COMMENT ON TABLE aisoc_closure_authorization_migration IS+ 'Per-tenant outcome of the closure default-deny change (migration 122). '+ 'An audit record, not a control: nothing reads it to make a decision.';++INSERT INTO aisoc_closure_authorization_migration (tenant_id, had_explicit_policy, was_enabled, outcome)+SELECT+ t.id,+ p.row_count > 0,+ CASE WHEN p.row_count > 0 THEN p.enabled_count > 0 ELSE NULL END,+ CASE WHEN p.row_count > 0 THEN 'preserved' ELSE 'requires_authorization' END+FROM tenants t+LEFT JOIN LATERAL (+ SELECT+ COUNT(*) AS row_count,+ COUNT(*) FILTER (WHERE c.enabled) AS enabled_count+ FROM aisoc_closure_policies c+ WHERE c.tenant_id = t.id+) p ON TRUE+ON CONFLICT (tenant_id) DO NOTHING;++-- Same posture as every other tenant-scoped table here. The read is an audit+-- read, so the usual `current_tenant_id() IS NULL` arm is kept: a platform+-- operator running the upgrade report has no single tenant bound.+ALTER TABLE aisoc_closure_authorization_migration ENABLE ROW LEVEL SECURITY;+ALTER TABLE aisoc_closure_authorization_migration FORCE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS tenant_isolation ON aisoc_closure_authorization_migration;+CREATE POLICY tenant_isolation ON aisoc_closure_authorization_migration+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (tenant_id = current_tenant_id());++GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_closure_authorization_migration TO aisoc_app;++-- Upgrade report — which tenants just lost implicit automatic closure:+--+-- SELECT t.slug, m.outcome+-- FROM aisoc_closure_authorization_migration m+-- JOIN tenants t ON t.id = m.tenant_id+-- WHERE m.outcome = 'requires_authorization'+-- ORDER BY t.slug;+--+-- Rollback+-- ────────+-- There is no schema change to undo beyond dropping the audit table:+--+-- DROP TABLE IF EXISTS aisoc_closure_authorization_migration;+--+-- Restoring the previous *behaviour* for a tenant is a deliberate grant, and+-- is the same statement the console writes. Per tenant, with a reason, never+-- in bulk across the table:+--+-- INSERT INTO aisoc_closure_policies+-- (tenant_id, alert_class, enabled, threshold, require_grant, updated_by, reason)+-- VALUES ('<tenant-uuid>'::uuid, NULL, TRUE, 0.85, FALSE,+-- '<operator>', 'restoring pre-122 automatic closure, reviewed <date>');+--+-- `require_grant = FALSE` reproduces the old default exactly. Leaving it TRUE+-- is the safer choice: closure then additionally waits for an `auto_close`+-- grant that shadow mode has to earn.diff --git a/tests/isolation/test_closure_authorization_live.py b/tests/isolation/test_closure_authorization_live.pynew file mode 100644index 000000000..fa97b767f--- /dev/null+++ b/tests/isolation/test_closure_authorization_live.py@@ -0,0 +1,560 @@+"""Every automatic closure of a production alert passes one authorization check.++Phase 1 of the closure remediation. See+`docs/remediation/phase-1-closure-authorization.md`.++What was wrong+--------------+`alerts.status` reaches `'resolved'` from exactly one statement — the `UPDATE+alerts` at the end of `app.investigator.ledger.persist_auto_triage`, whose+`CASE WHEN $7 AND NOT $10 THEN 'resolved'` turns on the caller-supplied+`auto_closed` flag. Two callers set that flag and only one of them asked+permission:++* `run_auto_triage` consulted `closure_policy.decide(...)` — the kill switch,+ the tenant's policy row, the earned `auto_close` grant;+* `FusedAlertTriageWorker._maybe_suppress_from_memory` set+ `state.status = COMPLETED` straight from a stored outcome prior, and+ `_record` forwarded `auto_closed=state.status is AgentStatus.COMPLETED`.+ The strings `closure_policy` and `kill_switch` appear in that module only+ inside comments.++So a tenant with `enabled = false` still got automatic closures, the kill+switch did not stop them, `require_grant` was not consulted, and the+confidence written against the decision was read off the prior rather than+measured. A remembered verdict was being treated as remembered permission.++Why this file is a live suite+-----------------------------+The defect is a disagreement between two modules about who asked permission,+resolved by SQL. A fake connection answers both sides happily: the offline+suite had a `_Pool` whose `fetchrow` returns whatever it was constructed with,+which cannot tell a policy that refused from a policy that was never read, and+cannot run the `CASE` expression that is the actual closure. Everything here+drives the real `persist_auto_triage`, the real `app.closure` modules and real+Postgres with every migration applied, and asserts on the row afterwards.++Against the pre-fix tree the first, third, fourth, fifth, sixth, seventh,+eighth and eleventh tests fail with the alert sitting at `status='resolved'`.+"""++from __future__ import annotations++import os+import uuid+from datetime import UTC, datetime+from typing import Any++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_CLOSURE_AUTHZ_DSN", "").strip(),+ reason="ISOLATION_CLOSURE_AUTHZ_DSN is not set; this suite needs a live Postgres",+ ),+]++#: The verdict every test here uses. Auto-closeable, so nothing in these+#: results turns on verdict eligibility — the question under test is+#: authorization, and a non-closeable verdict would pass for the wrong reason.+BENIGN = "benign"+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_CLOSURE_AUTHZ_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_CLOSURE_AUTHZ_DSN is not set")+ return value+++def _admin_dsn() -> str:+ """The schema owner, used only for fixtures and assertions.++ The code under test runs as the *runtime* role, where RLS is forced and+ a superuser's exemption cannot make a cross-tenant assertion pass for the+ wrong reason. Test setup is a different job: it writes rows for several+ tenants at once and reads them back, which under those same policies+ needs the owner. Keeping the two roles apart is what lets the production+ path be judged under the policies it really runs under.+ """+ return os.environ.get("ISOLATION_CLOSURE_AUTHZ_ADMIN_DSN", "").strip() or _dsn()+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def pool():+ """A real asyncpg pool, plus the `DATABASE_URL` production reads.++ Both the ledger and the closure policy resolve their own pool from the+ environment. Setting it here rather than handing each a pool is the+ point: a test that injected pools would not notice a module that+ resolves the wrong one.+ """+ asyncpg = pytest.importorskip("asyncpg")+ os.environ["DATABASE_URL"] = _dsn()++ from app.closure import policy as closure_policy+ from app.investigator import ledger as ledger_module++ created = await asyncpg.create_pool(+ _admin_dsn().replace("postgresql+asyncpg://", "postgresql://"),+ min_size=1,+ max_size=6,+ )+ yield created+ await created.close()++ await ledger_module.close_pool()+ # The closure package resolves the institutional pool. Closed through the+ # accessor it exports rather than by reaching into a private global, so+ # this teardown does not depend on the shape of a module it is testing.+ shared = await closure_policy.shared_pool()+ if shared is not None:+ await shared.close()+ closure_policy.reset_cache()++[email protected](autouse=True)+def _clear_policy_cache():+ """The policy caches its answer for ten seconds.++ Every test here changes a policy row and then asks again, which is+ exactly the window the cache covers, so leaving it would make tests pass+ or fail on their ordering.+ """+ from app.closure import policy as closure_policy++ closure_policy.reset_cache()+ yield+ closure_policy.reset_cache()+++async def _tenant(pool) -> str:+ tenant_id = str(uuid.uuid4())+ async with pool.acquire() as conn:+ await conn.execute(+ "INSERT INTO tenants (id, name, slug) VALUES ($1::uuid, $2, $3)",+ tenant_id,+ "closure-authz",+ f"closure-authz-{tenant_id[:8]}",+ )+ return tenant_id+++async def _alert(pool, tenant_id: str, *, category: str = "identity") -> str:+ alert_id = str(uuid.uuid4())+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO alerts (id, tenant_id, title, severity, status, category)+ VALUES ($1::uuid, $2::uuid, 'closure authorization probe', 'medium', 'new', $3)+ """,+ alert_id,+ tenant_id,+ category,+ )+ return alert_id+++async def _policy(+ pool,+ tenant_id: str,+ *,+ enabled: bool,+ threshold: float | None = None,+ require_grant: bool = False,+ alert_class: str | None = None,+) -> None:+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO aisoc_closure_policies+ (tenant_id, alert_class, enabled, threshold, require_grant)+ VALUES ($1::uuid, $2, $3, $4, $5)+ """,+ tenant_id,+ alert_class,+ enabled,+ threshold,+ require_grant,+ )+++async def _grant(pool, tenant_id: str, *, alert_class: str, state: str = "granted") -> None:+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO aisoc_autonomy_grants+ (tenant_id, scope_kind, scope_key, capability, state, source, evidence)+ VALUES ($1::uuid, 'alert_class', $2, 'auto_close', $3, 'earned', '{}'::jsonb)+ """,+ tenant_id,+ alert_class,+ state,+ )+++async def _engage_kill_switch(pool, tenant_id: str | None, *, reason: str) -> None:+ async with pool.acquire() as conn:+ await conn.execute(+ """+ INSERT INTO aisoc_kill_switch (tenant_id, engaged, reason, engaged_by)+ VALUES ($1::uuid, TRUE, $2, 'isolation-suite')+ """,+ tenant_id,+ reason,+ )+++async def _release_kill_switches(pool) -> None:+ async with pool.acquire() as conn:+ await conn.execute("DELETE FROM aisoc_kill_switch")+++async def _row(pool, alert_id: str) -> dict[str, Any]:+ async with pool.acquire() as conn:+ found = await conn.fetchrow(+ "SELECT status, disposition, resolved_at, ai_score FROM alerts WHERE id = $1::uuid",+ alert_id,+ )+ return dict(found)+++async def _persist(+ *,+ tenant_id: str,+ alert_id: str,+ auto_closed: bool = True,+ confidence: float = 0.99,+ tier: str = "llm",+ verdict: str = BENIGN,+ shadow: bool = False,+ category: str = "identity",+) -> bool:+ """The real durable write, called exactly as the worker calls it."""+ from app.investigator import ledger as ledger_module++ return await ledger_module.persist_auto_triage(+ run_id=uuid.uuid4(),+ alert_id=alert_id,+ tenant_ref=tenant_id,+ alert_summary="closure authorization probe",+ raw_alert={"id": alert_id, "category": category},+ tier=tier,+ verdict=verdict,+ confidence=confidence,+ rationale="probe",+ findings=[],+ proposed_actions=[],+ auto_closed=auto_closed,+ shadow=shadow,+ )+++class TestClosureNeedsExplicitAuthorization:+ """A tenant that has authorized nothing gets no automatic closures."""++ async def test_an_eligible_verdict_does_not_close_without_an_explicit_policy(self, pool) -> None:+ """Finding 14. The absence of a policy row was read as permission.++ `resolve_closure_policy` returned `confidence >= default_threshold`+ for a tenant with no row, so every tenant auto-closed from the moment+ the agent produced a confident benign verdict — including one that had+ never opened the screen.+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)++ await _persist(tenant_id=tenant_id, alert_id=alert_id)++ row = await _row(pool, alert_id)+ assert row["status"] != "resolved", "an alert auto-resolved for a tenant that has authorized no automatic closure at all"+ assert row["resolved_at"] is None++ async def test_an_explicitly_authorized_tenant_still_closes(self, pool) -> None:+ """The positive control, and the reason it is not optional.++ A gate that refuses everything satisfies every other assertion in+ this file. Without this test, wiring the chokepoint to `return False`+ would look like a complete fix.+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=True, threshold=0.80, require_grant=False)++ await _persist(tenant_id=tenant_id, alert_id=alert_id)++ row = await _row(pool, alert_id)+ assert row["status"] == "resolved", "an explicitly authorized tenant stopped auto-closing"+ assert row["resolved_at"] is not None+ assert row["disposition"] == BENIGN++ async def test_a_disabled_policy_blocks_closure(self, pool) -> None:+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=False)++ await _persist(tenant_id=tenant_id, alert_id=alert_id)++ assert (await _row(pool, alert_id))["status"] != "resolved"++ async def test_an_unearned_grant_blocks_closure(self, pool) -> None:+ """`require_grant` is the tenant saying "only once shadow mode earns it"."""+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=True)++ await _persist(tenant_id=tenant_id, alert_id=alert_id)++ assert (await _row(pool, alert_id))["status"] != "resolved"++ from app.closure import policy as closure_policy++ earned = await _alert(pool, tenant_id)+ await _grant(pool, tenant_id, alert_class="identity")+ closure_policy.reset_cache()++ await _persist(tenant_id=tenant_id, alert_id=earned)++ assert (await _row(pool, earned))["status"] == "resolved", "an earned grant did not unblock closure"+++class TestEveryClosurePathIsGoverned:+ """The LLM path asked permission. The other two did not."""++ async def test_the_memory_suppression_path_is_governed(self, pool) -> None:+ """Finding 1, at the durable boundary.++ `_maybe_suppress_from_memory` reaches `persist_auto_triage` with+ `auto_closed=True` and `tier='memory'` having consulted no policy at+ all. A trusted prior is evidence about the alert; it is not a grant.+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=False)++ await _persist(tenant_id=tenant_id, alert_id=alert_id, tier="memory", confidence=0.9)++ assert (await _row(pool, alert_id))["status"] != "resolved", (+ "outcome-memory suppression closed an alert for a tenant whose policy disables closure"+ )++ async def test_the_cached_verdict_path_is_governed(self, pool) -> None:+ """A cached verdict is a remembered answer, not remembered permission.++ The cost governor returns `Decision.DEDUPLICATED` with a verdict+ produced for an earlier alert, possibly under a policy that has since+ changed.+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=False)++ await _persist(tenant_id=tenant_id, alert_id=alert_id, tier="cached")++ assert (await _row(pool, alert_id))["status"] != "resolved"++ async def test_the_real_suppression_path_does_not_close_an_unauthorized_alert(self, pool) -> None:+ """The whole of Finding 1, driven through the worker rather than the ledger.++ Everything here is production: the real `FusedAlertTriageWorker`+ method, the real `LiveTriageWriter`, the real ledger and the real+ policy. Only the outcome prior is supplied, because that is the+ worker's *input* — a reader is the seam replay already uses, and+ faking it fakes the alert's history, not the authorization.+ """+ from app.agents.dispositions import BENIGN as BENIGN_DISPOSITION+ from app.memory.outcomes import HUMAN+ from app.models.state import InvestigationState+ from app.workers.fused_alert_consumer import FusedAlertTriageWorker+ from app.workers.triage_persistence import LiveTriageWriter++ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=False)++ class _PriorReader:+ """Returns one trusted prior. Every other read is empty."""++ async def lookup_prior(self, tenant: str, signature: str) -> dict[str, Any]: # noqa: ARG002+ return {+ "disposition": BENIGN_DISPOSITION,+ "confidence": 0.97,+ "count": 5,+ "author": HUMAN,+ "last_seen": datetime.now(UTC).isoformat(),+ }++ worker = FusedAlertTriageWorker.__new__(FusedAlertTriageWorker)+ worker._reader = _PriorReader() # type: ignore[assignment]+ worker._writer = LiveTriageWriter()++ state = InvestigationState(+ incident_id=uuid.uuid4(),+ tenant_id=uuid.UUID(tenant_id),+ alert_summary="repeat alert",+ raw_alert={"id": alert_id, "category": "identity"},+ )++ suppressed = await worker._maybe_suppress_from_memory(+ state,+ "sig-authz-probe",+ [],+ writer=LiveTriageWriter(),+ )++ assert suppressed is not None, "the prior should still suppress re-triage; only the closure is withheld"+ assert (await _row(pool, alert_id))["status"] != "resolved", (+ "the production memory-suppression path closed an alert the tenant's policy forbids"+ )+++class TestAuthorizationIsEvaluatedAtTheWrite:+ async def test_a_changed_policy_invalidates_an_earlier_authorization(self, pool) -> None:+ """Recovery must re-evaluate, never replay a stale permissive answer.++ A retried or resumed alert is persisted long after the decision that+ produced its verdict. If the authorization travelled with the verdict,+ a tenant disabling closure would not stop work already in flight.+ """+ from app.closure import policy as closure_policy++ tenant_id = await _tenant(pool)+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=False)++ first = await _alert(pool, tenant_id)+ await _persist(tenant_id=tenant_id, alert_id=first)+ assert (await _row(pool, first))["status"] == "resolved"++ async with pool.acquire() as conn:+ await conn.execute("UPDATE aisoc_closure_policies SET enabled = FALSE WHERE tenant_id = $1::uuid", tenant_id)+ closure_policy.reset_cache()++ second = await _alert(pool, tenant_id)+ await _persist(tenant_id=tenant_id, alert_id=second)++ assert (await _row(pool, second))["status"] != "resolved", (+ "closure continued after the tenant disabled it, so the authorization was retained rather than re-evaluated"+ )++ async def test_one_tenants_policy_cannot_authorize_anothers_closure(self, pool) -> None:+ authorized = await _tenant(pool)+ await _policy(pool, authorized, enabled=True, threshold=0.5, require_grant=False)++ other = await _tenant(pool)+ alert_id = await _alert(pool, other)++ await _persist(tenant_id=other, alert_id=alert_id)++ assert (await _row(pool, alert_id))["status"] != "resolved"+++class TestStopControls:+ async def test_a_global_kill_switch_stops_closure(self, pool) -> None:+ from app.closure import policy as closure_policy++ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=False)+ await _engage_kill_switch(pool, None, reason="incident 4471")+ closure_policy.reset_cache()++ try:+ await _persist(tenant_id=tenant_id, alert_id=alert_id)+ assert (await _row(pool, alert_id))["status"] != "resolved"+ finally:+ await _release_kill_switches(pool)+ closure_policy.reset_cache()++ async def test_a_tenant_kill_switch_stops_only_that_tenant(self, pool) -> None:+ from app.closure import policy as closure_policy++ stopped = await _tenant(pool)+ running = await _tenant(pool)+ for tenant_id in (stopped, running):+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=False)+ await _engage_kill_switch(pool, stopped, reason="tuning")+ closure_policy.reset_cache()++ try:+ stopped_alert = await _alert(pool, stopped)+ await _persist(tenant_id=stopped, alert_id=stopped_alert)+ assert (await _row(pool, stopped_alert))["status"] != "resolved"++ closure_policy.reset_cache()+ running_alert = await _alert(pool, running)+ await _persist(tenant_id=running, alert_id=running_alert)+ assert (await _row(pool, running_alert))["status"] == "resolved", "one tenant's stop control froze another tenant's closures"+ finally:+ await _release_kill_switches(pool)+ closure_policy.reset_cache()++ async def test_the_memory_path_obeys_the_kill_switch(self, pool) -> None:+ """The switch somebody reaches for at 3am did not reach this path at all."""+ from app.closure import policy as closure_policy++ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=False)+ await _engage_kill_switch(pool, None, reason="incident 4471")+ closure_policy.reset_cache()++ try:+ await _persist(tenant_id=tenant_id, alert_id=alert_id, tier="memory", confidence=0.9)+ assert (await _row(pool, alert_id))["status"] != "resolved", "the kill switch did not stop an outcome-memory closure"+ finally:+ await _release_kill_switches(pool)+ closure_policy.reset_cache()+++class TestShadowAndReplay:+ async def test_a_shadow_run_leaves_production_status_untouched(self, pool) -> None:+ """Already fixed before this phase; pinned here so the chokepoint cannot regress it."""+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)+ await _policy(pool, tenant_id, enabled=True, threshold=0.5, require_grant=False)++ await _persist(tenant_id=tenant_id, alert_id=alert_id, shadow=True)++ row = await _row(pool, alert_id)+ assert row["status"] != "resolved"+ assert row["disposition"] is None, "a shadow verdict landed in the column the analyst fills in"+++class TestManualClosureIsUnaffected:+ async def test_an_analyst_can_still_close_an_alert(self, pool) -> None:+ """The gate governs *automatic* closure only.++ A human resolving an alert through the API writes this row directly+ and must keep working for a tenant that has authorized no automation.+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)++ async with pool.acquire() as conn:+ await conn.execute(+ "UPDATE alerts SET status = 'closed', disposition = $2, resolved_at = now() WHERE id = $1::uuid",+ alert_id,+ "false_positive",+ )++ row = await _row(pool, alert_id)+ assert row["status"] == "closed"+ assert row["disposition"] == "false_positive"++ async def test_an_unauthorized_verdict_is_still_recorded(self, pool) -> None:+ """Withholding the closure must not withhold the triage.++ The alert stays open with the agent's verdict visible on it, which is+ the difference between "held for a human" and "lost".+ """+ tenant_id = await _tenant(pool)+ alert_id = await _alert(pool, tenant_id)++ written = await _persist(tenant_id=tenant_id, alert_id=alert_id)++ assert written is True+ row = await _row(pool, alert_id)+ assert row["status"] == "triaged", "an alert held back from closure should still show as triaged"+ assert row["ai_score"] == pytest.approx(0.99)diff --git a/tests/isolation/test_kill_switch_closure_live.py b/tests/isolation/test_kill_switch_closure_live.pyindex 36b589086..97be78db1 100644--- a/tests/isolation/test_kill_switch_closure_live.py+++ b/tests/isolation/test_kill_switch_closure_live.py@@ -86,6 +86,34 @@ async def _tenant(pool) -> str:return tenant_id+async def _authorize_closure(pool, tenant_id: str, *, threshold: float = 0.50) -> None:+ """Give the tenant an explicit closure policy.++ Automatic closure is default-deny: a tenant with no row in+ `aisoc_closure_policies` does not auto-close, whatever the kill switch+ says. A test about the *switch* therefore has to authorize closure+ first, or releasing the switch leaves the alert refused for an unrelated+ reason and the test proves nothing about the switch at all.+ """+ async with pool.acquire() as conn, conn.transaction():+ # `aisoc_closure_policies` is FORCE ROW LEVEL SECURITY with+ # `WITH CHECK (tenant_id = current_tenant_id())`, so a write needs a+ # bound tenant. This suite otherwise runs unbound -- which is correct+ # for the global kill-switch row and is why the three tests above+ # need no binding. Bound transaction-locally so nothing leaks into+ # the next test on a pooled connection.+ await conn.execute("SELECT set_config('app.current_tenant_id', $1, true)", tenant_id)+ await conn.execute(+ """+ INSERT INTO aisoc_closure_policies+ (tenant_id, alert_class, enabled, threshold, require_grant)+ VALUES ($1::uuid, NULL, TRUE, $2, FALSE)+ """,+ tenant_id,+ threshold,+ )++async def _engage_globally(pool, reason: str) -> None:async with pool.acquire() as conn:await conn.execute(@@ -149,6 +177,10 @@ class TestTheClosurePathObservesTheGlobalSwitch:from app.closure.policy import kill_switch_engaged, reset_cache, resolve_closure_policytenant_id = await _tenant(pool)+ # Closure is default-deny, so without an explicit policy the release+ # below would be masked by the missing policy and this control could+ # not tell "switch released" from "tenant never authorized closure".+ await _authorize_closure(pool, tenant_id)await _engage_globally(pool, "platform-wide stop")reset_cache()assert (await kill_switch_engaged(pool, tenant_id))[0] is True