Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(autonomy): promote autonomy on a measured track record, and demote on drift (#908)

Beenu Aroraf23a781e4663
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index b6809e9fc..9ab40b6e0 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -528,6 +528,29 @@ jobs:
POSTGRES_RLS_ISOLATION_REQUIRED: '1'
run: python -m pytest tests/isolation/test_postgres_rls.py -v --tb=short
+ # Gap-closure Phase 2.3's "Done when", run rather than reasoned about: a
+ # test tenant with 20 shadow decisions cannot enable auto-close, can
+ # once the thresholds are met, and is demoted when injected
+ # disagreements cross the drift threshold.
+ #
+ # It belongs here and nowhere else. The unit suites prove the arithmetic
+ # and prove the statements are built correctly, and between them they
+ # would still miss the failure that matters most: an aggregate that
+ # counts something slightly different from what the evaluator expects.
+ # The SQL and the evaluator agree by convention, and a convention is
+ # what drifts. Only a real Postgres executing the real statement over
+ # real rows closes that. It is also the only place the hash chain over
+ # the transitions can be verified, since it is computed on insert from
+ # the previous row for the same tenant.
+ #
+ # AUTONOMY_PROMOTION_LIVE_REQUIRED turns an unreachable database into a
+ # failure rather than a skip, for the same reason as the two jobs above.
+ - name: Evidence-gated autonomy, end to end (live Postgres)
+ working-directory: services/api
+ env:
+ AUTONOMY_PROMOTION_LIVE_REQUIRED: '1'
+ run: python -m pytest ../../tests/isolation/test_autonomy_promotion_live.py -v --tb=short
+
# The static half of this gate runs on every PR in security.yml. This is
# the half that can only be answered by a database: the role the
# deployment actually connects as, inspected in pg_roles and pg_class.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7d198ae6b..38e5872db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Autonomy promoted by a measured track record, not by a settings toggle**
+ (gap-closure Phase 2.3). Phase 2.2 made agreement measurable. This is what
+ the measurement is for.
+
+ **The gap.** A tenant's autonomy posture was a number somebody typed. The
+ L0 to L4 tier, the per-action thresholds and the force-auto override were
+ all settings, and nothing anywhere connected what the agent had actually
+ got right to what it was allowed to do unattended.
+
+ **How it works.** A tenant asks for a capability, either auto-closing an
+ alert class or raising a response verb's autonomy tier, and the evidence
+ decides. Granting requires a configurable minimum sample (100 decisions by
+ default, at least 30 of them closed as malicious), 95% agreement over
+ answered decisions, 90% recall on malicious, an abstention rate at or below
+ 30%, and a trailing slice of recent decisions that is not already in
+ decline. Every check runs and every failure comes back together: an
+ operator told one thing at a time fixes it, re-asks, is told the next
+ thing, and overrides out of frustration rather than on the merits.
+
+ **The four refusals it exists to make.** Too few decisions. Enough
+ decisions but too few malicious ones, which a real queue produces by itself
+ because it is mostly false positives, and where agreement says only that
+ the agent recognises noise. Agreement that is high only because the agent
+ abstains, closed by three independent guards: agreement's denominator
+ excludes abstentions so declining cannot inflate it, the abstention rate is
+ capped, and malicious recall counts an abstention as a miss. And drift that
+ arrives gradually, which a 30-day average absorbs: 99% for three weeks and
+ 70% this week still posts about 95%, so the trailing 50 decisions are
+ scored separately and either one falling below the floors demotes.
+
+ **Demotion is automatic and is not the mirror of promotion.** Standing
+ grants are re-checked whenever they are read. The demotion floors sit below
+ the promotion thresholds on purpose, because equal values would flip a
+ grant on every decision that crossed the line and fill the audit log with
+ churn nobody reads. Promotion refuses an unmeasured rate, since "not
+ measured" must never be read as "met the threshold"; demotion ignores one,
+ since a week with no malicious alert is not evidence the agent got worse
+ and revoking over an empty denominator would make quiet weeks dangerous.
+
+ **An override stays visibly an override.** A gate with no override is a
+ gate that gets worked around by people who then stop telling you, so an
+ operator can grant over a refusal with a stated reason. It lands as a
+ different audit action (`autonomy:overridden`), a constrained `source`
+ column on the grant row, the waived refusals inside the evidence snapshot,
+ and an amber label on the scorecard. The source is derived from the gate's
+ own verdict and `evaluate_promotion` takes no override argument, so no
+ caller can have an override recorded as earned. An override is re-checked
+ and demoted on the same floors: it means "I accept this today", not "stop
+ measuring".
+
+ **The snapshot is the point.** Every transition is written to the
+ hash-chained audit log with the numbers frozen: the counts and the rates,
+ the thresholds by value so a later retune does not rewrite past
+ justifications, the window as absolute timestamps, the first and last
+ decision id so the rows can still be found, the models that produced the
+ verdicts, and a digest of the rules that judged it. A recomputed
+ justification would describe a different world while looking authoritative
+ doing it.
+
+ **What a track record cannot unlock.** A grant raises the tier ceiling to
+ L3, which permits MINIMAL, LOW and MEDIUM blast radius, and stops there.
+ Agreement on triage verdicts is evidence about the agent's judgement and is
+ not evidence that a high-blast containment was the right call. The
+ capability contract still applies on top, so a verb declared `analyst` or
+ `mandatory_human` stays gated however good the numbers are.
+
+ **The gates.** Five new claim-to-gate rows, taking the matrix to 164 rows
+ and 156 GATED. The phase's "Done when" runs against a real Postgres in
+ `integration.yml` rather than being reasoned about: 13 tests seed recorded
+ decisions, refuse a tenant at 20, grant it at 150, inject disagreements and
+ watch the demotion land, then replay the promotion and the demotion through
+ `audit_hash.verify_chain`. The live half exists because the aggregate SQL
+ and the evaluator agree by convention, and a convention is what drifts.
+ Migration `067_autonomy_grants.sql`. Documented at
+ `apps/docs/docs/operations/shadow-mode.md`.
+
- **Shadow mode on the live queue, and agreement measured against your own
analysts** (gap-closure Phase 2.1 and 2.2). Phase 1 made a customer's closed
history gradeable. This makes the live queue gradeable too, which is the
diff --git a/GAP_CLOSURE_PROGRESS.md b/GAP_CLOSURE_PROGRESS.md
index 6cb9dac4e..9b3e31516 100644
--- a/GAP_CLOSURE_PROGRESS.md
+++ b/GAP_CLOSURE_PROGRESS.md
@@ -261,7 +261,18 @@ the decomposition and what each link rests on are in D8 above.
- [x] **2.1 Shadow mode**, per tenant and per alert class. Shipped in [#906](https://github.com/beenuar/AiSOC/pull/906). The seam is Phase 1.2's: `FusedAlertTriageWorker` already routes every write through the `TriageWriter` port, so shadow mode is a wrapper around the tenant's live sink rather than a second code path. Chosen per alert, not per worker, because the class is not known until the alert is in hand; the constructor sinks are untouched, which is what keeps the Phase 1.2 AST test true. Migration **066** adds `aisoc_shadow_mode` and `aisoc_shadow_decisions`. Analyst closures arrive from two places: a bounded sweep over closed alerts in this console, and the five Phase 1.1 SIEM readers polled back out of the customer's own product and matched on the vendor finding id. See D9 for the one property everything else rests on.
- [x] **2.2 Rolling agreement** per alert class, rule, source and model, on the operations dashboard and the autonomy scorecard. Shipped in [#906](https://github.com/beenuar/AiSOC/pull/906). The metrics are Phase 1.3's and "uses the Phase 1 metrics" is now a gate rather than a sentence: `check_replay_contract_parity.py` went from three trees to four and compares `GRADED_DISPOSITIONS`, `ABSTENTION_VERDICTS`, `MALICIOUS` and `UNLABELED` in both directions, proven capable of failing by drifting each collection in turn. Agreement is computed over *answered* decisions only so abstaining cannot inflate it, malicious recall counts an abstention as a miss, a rate with no denominator reads "not measured", and every rate travels with its count. Matrix 156 rows to 159, GATED 148 to 151.
-- [ ] **2.3 Promotion gate**, with automatic demotion on drift and every transition written to the hash-chained audit log.
+- [x] **2.3 Promotion gate**, with automatic demotion on drift and every transition written to the hash-chained audit log. Shipped in [#908](https://github.com/beenuar/AiSOC/pull/908). Migration **067** adds `aisoc_autonomy_grants`. The gate is pure and lives in the vendored rules module so `services/actions` enforces the same arithmetic at dispatch that `services/api` decides on at promotion time. Wired into all three modules the plan names: `unified_autonomy.unified_decision` gained an `earned_grant` argument that can only widen the reversible MEDIUM-blast branch, `tenant_policy.TenantPolicy` carries the earned verbs and never issues one, and `autonomy_policy.py` gained `GET`/`POST`/`DELETE /grants`. The dispatcher was also wired, because `unified_decision` turned out to have no production caller at all (see D12). The "Done when" runs against a real Postgres in `integration.yml`. See D13 for why the ceiling stops at L3.
+
+**Done when:** on recorded data, a test tenant cannot enable auto-close for a
+class with 20 shadow decisions, can once the thresholds are met, and is demoted
+when injected disagreements cross the drift threshold.
+
+**Met.** `tests/isolation/test_autonomy_promotion_live.py`, 13 tests against
+`postgres:16` with the full API migration chain applied: refused at 20 with
+`insufficient_sample` and `insufficient_malicious` and nothing written, granted
+at 150 with the full snapshot, demoted after 30 injected disagreements with
+`recent_drift` among the reasons, and the promotion and demotion replayed
+through `audit_hash.verify_chain`.
## Phase 3: Prompt-injection evaluation suite
@@ -387,6 +398,16 @@ Nothing yet beyond this kickoff. Each entry below will name its PR.
[#904](https://github.com/beenuar/AiSOC/pull/904). Suites: `services/agents`
1252 to 1280, `packages/aisoc-benchmark` 35 to 57, `services/connectors` 880
to 886. Every other suite unchanged and passing.
+- [x] **Phase 2.1 shadow mode and 2.2 rolling agreement.**
+ [#906](https://github.com/beenuar/AiSOC/pull/906). Migration 066. Suites:
+ `services/agents` 1293 to 1311, `services/actions` 767 to 801, `services/api`
+ 2852 to 2872, `apps/web` settings vitest 9 to 15. Claim matrix 156 rows to
+ 159, GATED 148 to 151.
+- [x] **Phase 2.3 evidence-gated autonomy.**
+ [#908](https://github.com/beenuar/AiSOC/pull/908). Migration 067. Suites:
+ `services/actions` 801 to 835, `apps/web` settings vitest 32 to 36, and
+ `tests/isolation/test_autonomy_promotion_live.py` 13 passing against live
+ `postgres:16`. Claim matrix 159 rows to 164, GATED 151 to 156.
### D9. A shadow verdict must not reach `alerts.disposition`, and the guard belongs in the SQL
@@ -453,6 +474,74 @@ the five mirrors already in the tree, with
`sync_vendored_autonomy_evidence.py --check` wired into `ci.yml`. Two copies
allowed to differ means the control is off in whichever one is more generous.
+### D12. `unified_decision` had no production caller, and the plan names it anyway
+
+The plan says to wire the promotion gate into
+`services/actions/app/services/unified_autonomy.py`. Doing only that would
+have wired it into nothing.
+
+`unified_decision` is referenced in exactly one place in the tree:
+`services/actions/tests/test_unified_autonomy.py`. The live path is
+`live_actions/dispatcher.py::_govern`, which composes a different
+`AutonomyDecision` (the one in `autonomy_safety`) from `decide()`, the tenant
+policy and `_apply_capability_contract`. This is the repository's most-repeated
+shape: a mechanism that exists, is unit-tested, and is not on the path that
+needs it.
+
+**Resolution:** both. `unified_decision` takes the grant and is kept
+consistent, because the plan names it and because a second grader that
+disagreed with the first would be worse than the unwired one. And the grant is
+wired into `_govern`, where it raises the tier ceiling exactly as the existing
+`force_auto` override does and then passes through `_apply_capability_contract`
+unchanged, so the contract's floors still apply. Adding a third grader beside
+the two that already compose would have re-created the "same verb graded
+differently depending on which door it came through" defect this tree already
+fixed once.
+
+### D13. A grant stops at L3 where `force_auto` goes to L4
+
+`force_auto` lifts the ceiling to L4, which permits HIGH blast radius. An
+earned grant lifts it to L3, which stops at MEDIUM.
+
+The two are not the same kind of thing. `force_auto` is a human writing down a
+decision about one verb. A grant is an inference from agreement on *triage
+verdicts*, which is evidence about the agent's judgement and is not evidence
+that isolating a host was the right call. Letting one number unlock both is how
+a measurement of one thing becomes permission for another, and it would be
+invisible afterwards because the resulting action looks identical either way.
+
+`test_earned_autonomy_wiring.py` pins the ceiling, pins that a grant never
+lowers a bar (a 40-case sweep over blast radius, confidence and reversibility
+asserting the only permitted movement is queued to auto on the reversible
+MEDIUM branch), and pins that confidence is still required, since a grant is
+evidence about the agent in general and confidence is what it says about this
+decision.
+
+### D14. The live database is not optional for this phase
+
+The unit suites prove the arithmetic and prove the statements are built
+correctly. Between them they would still miss the failure that matters most: an
+aggregate that counts something slightly different from what the evaluator
+expects. The SQL and the evaluator agree by convention, and a convention is
+what drifts.
+
+One instance of exactly that was found by running it. `to_named_params` turns
+`$2::text[]` into `:graded::text[]`, and SQLAlchemy's `text()` parser reads the
+second colon pair as the start of another bind parameter, so a stray colon
+reached Postgres and every agreement query on the API side failed to parse.
+Both unit suites were green. The cast is gone from the shared SQL (both drivers
+infer the array type from the column) and the SQLAlchemy caller declares it
+with `bindparam(..., type_=ARRAY(Text))` instead.
+
+The live suite is also the only place the hash chain over the transitions can
+be checked, since `entry_hash` is computed on insert from the previous row for
+the same tenant. It cleans up the evidence and the grants and deliberately
+leaves the tenant, the operator and the audit rows: `audit_log` refuses a
+DELETE by trigger, `audit_log.tenant_id` cascades from `tenants` and
+`audit_log.actor_id` is `ON DELETE SET NULL` from `users`, so removing either
+reaches the trigger and is refused. Working around that in a test would mean
+demonstrating the hole the trigger closes, so the refusal is asserted instead.
+
### Notes for the next session
Two traps this program hit that are worth not re-learning.
diff --git a/ROADMAP.md b/ROADMAP.md
index c4dd74a72..0ef0b5b5b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,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 **159 rows — 151 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 **164 rows — 156 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. 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 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index a58af3631..12b4f5b2e 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 151 rows
+The last row is the one worth reading first. It is the honest index: 156 rows
`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refuses
to let a row sit at `NO GATE`.
diff --git a/apps/docs/docs/operations/shadow-mode.md b/apps/docs/docs/operations/shadow-mode.md
index 9c8c65d33..eebdeaaab 100644
--- a/apps/docs/docs/operations/shadow-mode.md
+++ b/apps/docs/docs/operations/shadow-mode.md
@@ -180,3 +180,134 @@ change makes every figure before it a description of something else.
They say nothing about **response actions**. Shadow mode measures triage
verdicts. Whether a containment action would have been correct is a different
question this does not answer.
+
+## Earning autonomy
+
+Measurement exists so that autonomy can be earned rather than switched on. Once
+a class has a track record, a tenant can ask for a capability and the evidence
+decides.
+
+Two capabilities can be earned:
+
+* `auto_close` on an alert class: the agent closes alerts of that class without
+ a human.
+* `auto_execute` on a response verb: that verb's autonomy tier ceiling rises.
+
+```bash
+curl -X POST "$AISOC/api/v1/autonomy-policy/grants" \
+ -H "Authorization: Bearer $TOKEN" \
+ -H 'Content-Type: application/json' \
+ -d '{"scope_kind": "alert_class", "scope_key": "identity", "capability": "auto_close"}'
+```
+
+A refusal comes back as a `200` with `granted: false` and the reasons. Being
+told no by a safety control is the control working, and returning it as an
+error would invite a client to retry it.
+
+### What has to be true
+
+| Threshold | Default | Why |
+|---|---|---|
+| Decisions in the window | 100 | A handful of agreements is not a track record. |
+| Of those, closed as malicious | 30 | A real queue reaches 100 decisions with two true positives in it. Agreement over that says the agent recognises noise, which is not the question. Same floor replay uses before printing a headline accuracy. |
+| Agreement, over answered decisions | 95% | |
+| Recall on malicious | 90% | An abstention counts as a miss here. |
+| Abstention rate | at most 30% | Caps the share of the queue the agent may decline. |
+| The trailing slice | not in decline | Checked against the demotion floors, so a grant is never issued into a decline it would immediately be revoked for. |
+
+Every check runs and every failure comes back. An operator told one thing at a
+time fixes it, re-asks, is told the next thing, and overrides out of
+frustration rather than on the merits.
+
+### Demotion is automatic
+
+Standing grants are re-checked whenever they are read and whenever the
+dispatch path refreshes. A grant is demoted when agreement falls below 90%,
+malicious recall below 80%, the abstention rate rises above the cap, or the
+trailing slice of recent decisions has slipped below those floors even though
+the window average has not.
+
+The demotion floors sit below the promotion thresholds on purpose. Equal values
+would flip a grant on every decision that moved the rate across the line, and
+the audit log would fill with churn nobody reads, which is how a real demotion
+gets missed.
+
+One asymmetry worth knowing, because it looks like an inconsistency:
+**promotion refuses an unmeasured rate and demotion ignores one.** For a
+promotion, nothing has been shown, so the answer is no. For a demotion, a week
+in which no malicious alert arrived is not evidence the agent got worse, and
+revoking a grant over an empty denominator would make quiet weeks dangerous.
+
+### What a grant can and cannot unlock
+
+A grant on a response verb raises the tier ceiling to **L3**, which permits
+MINIMAL, LOW and MEDIUM blast radius. It stops there. No track record on triage
+agreement makes `isolate_host` unattended, because agreement on triage verdicts
+is evidence about the agent's judgement and is not evidence that a high-blast
+containment was the right call.
+
+The capability contract still applies on top. A verb declared `analyst` or
+`mandatory_human`, or one whose impact is never autonomous, stays gated however
+good the numbers are: a contract's floors may be raised and never lowered.
+
+### Overrides
+
+An operator can grant a capability the evidence refuses:
+
+```bash
+curl -X POST "$AISOC/api/v1/autonomy-policy/grants" \
+ -H "Authorization: Bearer $TOKEN" \
+ -H 'Content-Type: application/json' \
+ -d '{"scope_kind": "alert_class", "scope_key": "identity", "capability": "auto_close",
+ "override": true, "override_reason": "Accepted for a two-week pilot"}'
+```
+
+A gate with no override is a gate that gets worked around by people who then
+stop telling you. What must not happen is an override becoming
+indistinguishable from earned autonomy once it is a week old, so it is a
+different word in four places:
+
+* a different audit action, `autonomy:overridden` rather than `autonomy:granted`
+* a `source` of `operator_override` on the grant row
+* the refusals that were waived, recorded in the evidence snapshot
+* an amber "operator override" label on the autonomy scorecard, beside the
+ reason the operator gave
+
+A reason is required. An override nobody can review now is not reviewable later
+either.
+
+An override is re-checked and demoted on the same floors as an earned grant. It
+means "I accept this today", not "stop measuring"; exempting it would make the
+override permanent, which is the one thing that would turn it back into the
+settings toggle this replaces.
+
+### The evidence snapshot
+
+Every promotion and demotion is written to the hash-chained audit log with the
+numbers frozen at the moment it was made. Not a reference to them, and not a
+flag that lets them be recomputed later.
+
+Six months after a disputed auto-closure, "why was this tenant allowed to do
+that" has to be answerable against the numbers as they stood on the day. By
+then the window has moved, decisions have aged out, the thresholds may have
+been retuned and the model has probably changed, so a recomputed justification
+would describe a different world while looking authoritative doing it.
+
+The snapshot holds:
+
+* the counts and the rates derived from them, for the window and the trailing
+ slice
+* the thresholds **by value**, so a threshold retuned next quarter does not
+ rewrite the justification for every promotion granted under the old one
+* the window as absolute timestamps, because "the last 30 days" stops meaning
+ anything the moment it is read on a different day
+* the first and last decision id, so the rows behind the summary can still be
+ found after the window has moved on
+* the models that produced the verdicts, and whether the closures came from
+ this console, a vendor, or both
+* a digest of the rules that judged it, so a later reader can tell "the gate
+ was more lenient then" from "the numbers were better"
+
+The audit log refuses deletion by trigger and each entry chains onto the
+previous one for the same tenant, so the record of a grant cannot be quietly
+removed.
diff --git a/apps/web/src/components/settings/AutonomyPolicy.tsx b/apps/web/src/components/settings/AutonomyPolicy.tsx
index 8d1285d8b..0a8dfefc8 100644
--- a/apps/web/src/components/settings/AutonomyPolicy.tsx
+++ b/apps/web/src/components/settings/AutonomyPolicy.tsx
@@ -33,6 +33,7 @@ import {
type AutonomyActionPolicy,
type AutonomyBlastRadius,
type AutonomyPolicyResponse,
+ type GrantListResponse,
type AutonomyThresholdTriple,
} from '@/lib/api';
import { Skeleton } from '@/components/ui/Skeleton';
@@ -109,6 +110,16 @@ export function AutonomyPolicyPanel() {
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
+ // Phase 2.3. Reading this also re-checks every standing grant against its
+ // current evidence, so a capability whose track record has slipped is
+ // demoted here rather than being listed as current while failing at
+ // dispatch, which would leave this page disagreeing with the product.
+ const { data: grantList } = useSWR<GrantListResponse>(
+ 'settings:autonomy-grants',
+ () => autonomyPolicyApi.grants(),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
return (
<div>
<PanelHeader
@@ -121,7 +132,7 @@ export function AutonomyPolicyPanel() {
copilot). Rendered once the policy loads so the CISO sees the
whole-SOC autonomy posture before drilling into per-action rows. */}
{!isLoading && !error && actions.length > 0 ? (
- <AutonomyScorecard actions={actions} agreement={agreement} />
+ <AutonomyScorecard actions={actions} agreement={agreement} grants={grantList?.grants} />
) : null}
{/* Legend */}
diff --git a/apps/web/src/components/settings/AutonomyScorecard.test.tsx b/apps/web/src/components/settings/AutonomyScorecard.test.tsx
index f8ddda69b..9d23486a8 100644
--- a/apps/web/src/components/settings/AutonomyScorecard.test.tsx
+++ b/apps/web/src/components/settings/AutonomyScorecard.test.tsx
@@ -15,6 +15,7 @@ import type {
AgreementWindow,
AutonomyActionPolicy,
AutonomyBlastRadius,
+ AutonomyGrant,
} from '@/lib/api';
import {
AutonomyScorecard,
@@ -211,3 +212,67 @@ describe('<AutonomyScorecard /> track record', () => {
expect(screen.getByText('not measured')).toBeInTheDocument();
});
});
+
+// ─── Earned autonomy (gap-closure Phase 2.3) ─────────────────────────────────
+//
+// One property, and it is the reason the grant carries a `source` at all: an
+// override must stay legible as an override. Autonomy somebody earned and
+// autonomy somebody overruled a refusal to grant behave identically and are
+// very different things to be reading during an incident review.
+
+function grant(overrides: Partial<AutonomyGrant> = {}): AutonomyGrant {
+ return {
+ id: 'g1',
+ scope_kind: 'alert_class',
+ scope_key: 'identity',
+ capability: 'auto_close',
+ state: 'granted',
+ source: 'earned',
+ is_override: false,
+ ...overrides,
+ };
+}
+
+describe('<AutonomyScorecard /> earned autonomy', () => {
+ it('says nothing when the tenant holds no capabilities', () => {
+ render(<AutonomyScorecard actions={[action('block_ip', 'medium', 0.9)]} grants={[]} />);
+ expect(screen.queryByText(/Autonomy granted/i)).not.toBeInTheDocument();
+ });
+
+ it('labels an earned grant as earned', () => {
+ render(<AutonomyScorecard actions={[action('block_ip', 'medium', 0.9)]} grants={[grant()]} />);
+ expect(screen.getByText('earned')).toBeInTheDocument();
+ expect(screen.queryByText('operator override')).not.toBeInTheDocument();
+ });
+
+ it('labels an override as an override and shows the stated reason', () => {
+ render(
+ <AutonomyScorecard
+ actions={[action('block_ip', 'medium', 0.9)]}
+ grants={[
+ grant({
+ source: 'operator_override',
+ is_override: true,
+ override_reason: 'Accepted for a two-week pilot',
+ }),
+ ]}
+ />,
+ );
+ expect(screen.getByText('operator override')).toBeInTheDocument();
+ expect(screen.getByText('Accepted for a two-week pilot')).toBeInTheDocument();
+ });
+
+ it('keeps a demoted grant visible with why it was taken away', () => {
+ // A capability that was revoked is more interesting than one never held,
+ // and hiding it would make "what happened to our auto-close" unanswerable
+ // from this page.
+ render(
+ <AutonomyScorecard
+ actions={[action('block_ip', 'medium', 0.9)]}
+ grants={[grant({ state: 'demoted', demoted_reason: 'recent_drift' })]}
+ />,
+ );
+ expect(screen.getByText('demoted')).toBeInTheDocument();
+ expect(screen.getByText('recent_drift')).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/settings/AutonomyScorecard.tsx b/apps/web/src/components/settings/AutonomyScorecard.tsx
index b01a2799d..15031cf12 100644
--- a/apps/web/src/components/settings/AutonomyScorecard.tsx
+++ b/apps/web/src/components/settings/AutonomyScorecard.tsx
@@ -36,6 +36,7 @@ import type {
AgreementResponse,
AutonomyActionPolicy,
AutonomyBlastRadius,
+ AutonomyGrant,
} from '@/lib/api';
export type AutonomyPosture = 'copilot' | 'autopilot';
@@ -151,9 +152,11 @@ export function summariseTrackRecord(agreement: AgreementResponse | null | undef
export function AutonomyScorecard({
actions,
agreement,
+ grants,
}: {
actions: AutonomyActionPolicy[];
agreement?: AgreementResponse | null;
+ grants?: AutonomyGrant[];
}) {
const card = computeScorecard(actions);
const isCopilot = card.posture === 'copilot';
@@ -207,6 +210,59 @@ export function AutonomyScorecard({
</div>
<TrackRecord record={record} />
+ <EarnedAutonomy grants={grants ?? []} />
+ </div>
+ );
+}
+
+/**
+ * Capabilities this tenant holds, and how each one came to be held.
+ *
+ * Gap-closure Phase 2.3. The distinction this renders is the whole reason the
+ * grant carries a `source` rather than a boolean: autonomy somebody earned and
+ * autonomy somebody overruled a refusal to grant look identical in behaviour
+ * and are very different things to be looking at during an incident review. A
+ * demoted row stays visible for the same reason: a capability that was taken
+ * away is more interesting than one that was never held.
+ */
+function EarnedAutonomy({ grants }: { grants: AutonomyGrant[] }) {
+ if (grants.length === 0) return null;
+
+ return (
+ <div className="mt-4 border-t border-gray-800 pt-3">
+ <p className="text-[11px] uppercase tracking-wide text-gray-500">Autonomy granted</p>
+ <ul className="mt-2 space-y-1.5">
+ {grants.map((grant) => (
+ <li key={grant.id} className="flex flex-wrap items-baseline gap-2 text-sm">
+ <span className="font-mono text-xs text-gray-300">
+ {grant.capability} · {grant.scope_key}
+ </span>
+ <span
+ className={clsx(
+ 'rounded px-1.5 py-0.5 text-[11px] ring-1 ring-inset',
+ grant.state === 'demoted'
+ ? 'bg-gray-500/10 text-gray-400 ring-gray-600/40'
+ : grant.is_override
+ ? 'bg-amber-500/10 text-amber-300 ring-amber-500/30'
+ : 'bg-emerald-500/10 text-emerald-300 ring-emerald-500/30',
+ )}
+ >
+ {grant.state === 'demoted'
+ ? 'demoted'
+ : grant.is_override
+ ? 'operator override'
+ : 'earned'}
+ </span>
+ <span className="text-[11px] text-gray-500">
+ {grant.state === 'demoted'
+ ? grant.demoted_reason || 'the evidence no longer supports it'
+ : grant.is_override
+ ? grant.override_reason || 'no reason recorded'
+ : 'met every threshold on its own'}
+ </span>
+ </li>
+ ))}
+ </ul>
</div>
);
}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 9419107ce..214a10e77 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -5037,6 +5037,27 @@ export const autonomyPolicyApi = {
{ method: 'PUT', body: JSON.stringify({ enabled }) },
),
+ /** Capabilities this tenant has earned, or that an operator overruled into place. */
+ grants: () => request<GrantListResponse>('/api/v1/autonomy-policy/grants'),
+
+ /**
+ * Ask for a capability. A refusal is a 200 with `granted: false` and the
+ * reasons: being told no by a safety control is the control working, and
+ * surfacing it as an error invites a client to retry it.
+ */
+ requestGrant: (payload: PromotionRequestBody) =>
+ request<PromotionResponse>('/api/v1/autonomy-policy/grants', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
+
+ /** Hand a capability back. Audited as a revocation, not as a demotion. */
+ revokeGrant: (params: { scope_kind: string; scope_key: string; capability: string }) =>
+ request<void>(
+ `/api/v1/autonomy-policy/grants?${new URLSearchParams(params).toString()}`,
+ { method: 'DELETE' },
+ ),
+
/** Rolling agreement between the agent and this tenant's own analysts. */
agreement: (params?: { scope_kind?: string; scope_key?: string }) => {
const query = new URLSearchParams();
@@ -5103,6 +5124,57 @@ export interface AgreementThresholds {
drift_min_answered: number;
}
+// ─── Evidence-gated autonomy (gap-closure Phase 2.3) ────────────────────────
+//
+// `source` and `is_override` are both carried because the distinction has to
+// survive without anyone inferring it. An override is autonomy a human
+// overruled a refusal to grant, and six months later "was this earned" must
+// be answerable from the row rather than reconstructed from the numbers.
+
+export type GrantState = 'shadow' | 'granted' | 'demoted';
+export type GrantSource = 'earned' | 'operator_override';
+
+export interface AutonomyGrant {
+ id: string;
+ scope_kind: string;
+ scope_key: string;
+ capability: string;
+ state: GrantState;
+ source: GrantSource;
+ is_override: boolean;
+ evidence?: Record<string, unknown> | null;
+ granted_at?: string | null;
+ demoted_at?: string | null;
+ demoted_reason?: string | null;
+ override_reason?: string | null;
+}
+
+export interface GrantListResponse {
+ tenant_id: string;
+ grants: AutonomyGrant[];
+ /** Grants this request's reconciliation pass demoted. */
+ demoted_now: Array<Record<string, unknown>>;
+}
+
+export interface PromotionRequestBody {
+ scope_kind: string;
+ scope_key: string;
+ capability: string;
+ override?: boolean;
+ override_reason?: string | null;
+}
+
+export interface PromotionResponse {
+ granted: boolean;
+ state: GrantState;
+ source: GrantSource;
+ is_override: boolean;
+ /** What to fix on a refusal; what was waived on an override. */
+ refusals: string[];
+ evidence: Record<string, unknown>;
+ changed: boolean;
+}
+
export interface AgreementResponse {
tenant_id: string;
scope_kind: string;
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 562709fb6..f30ce3efb 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -166,11 +166,16 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A shadow verdict never fills in the analyst column it will be graded against | `apps/docs/docs/operations/shadow-mode.md`; `services/agents/app/workers/shadow_mode.py` | `ci.yml` agents job (`test_shadow_mode.py`) - the shadow sink is asserted to decline every acting method against a delegate that *records* rather than performs, so a forwarded call shows up as a recorded one rather than as an absence; `persist_auto_triage` is asserted to force `auto_closed` off and the `shadow` flag on; and the ledger statement is read to confirm `disposition`, `status` and `resolved_at` are each guarded by that flag with `NOT $10` rather than by the caller remembering to pass `auto_closed=False`. Plus `ci.yml` api job (`test_shadow_agreement.py`) - reconciliation only reads closed alerts and only writes decisions with `resolved_at IS NULL`, so a later change of mind cannot rewrite evidence a promotion already rested on | GATED | The SQL guard is read, not executed: there is no Postgres in the unit suites, so what is proven is that the statement carries the guard and binds the flag, not that Postgres evaluates the CASE as written. A live replay of the statement belongs with the isolation suite |
| Agreement cannot be improved by declining to answer | `apps/docs/docs/operations/shadow-mode.md`; `services/actions/app/services/autonomy_evidence_rules.py` | `ci.yml` actions job (`test_autonomy_evidence_rules.py`) - the same ten right answers are scored with nothing declined and with ninety declined, and the agreement rate is asserted identical, because abstaining removes a decision from the numerator and the denominator together. The counterweight is asserted from the other side: a window where the agent answered ten of forty labelled cases posts a perfect agreement rate and a malicious recall of 8/30, since recall's denominator is every malicious case whether answered or not. The abstention rate is asserted to move where agreement does not, and `AgreementWindow` refuses to construct at all when its counts do not add up, so a miscounted aggregate raises instead of publishing a plausible rate | GATED | The metric is gated; what it is used *for* is Phase 2.3. This row proves the rate cannot be gamed, not that anything yet refuses a promotion on it |
| Live agreement is scored by the Phase 1 metrics rather than a second set | `plans/aisoc_gap_closure_plan.plan.md` (2.2, "using the Phase 1 metrics"); `apps/docs/docs/operations/shadow-mode.md` | `ci.yml :: python-lint` (`check_replay_contract_parity.py`, extended from three trees to four: `GRADED_DISPOSITIONS`, `ABSTENTION_VERDICTS` and the `MALICIOUS` spelling must be identical strings in `autonomy_evidence_rules.py` and in `aisoc_benchmark/replay.py`, compared in both directions, and `UNLABELED` must be spelled the same in all three. Proven capable of failing by drifting each of the two collections in turn and watching it fire, rather than only having never fired) + `ci.yml` (`sync_vendored_autonomy_evidence.py --check`, which byte-compares the API's copy, because a safety control defined twice is off in whichever copy is more generous) | GATED | Parity of the definitions is gated. That the two implementations compute the same number from the same rows is not: the grader scores a list of decision dicts and the live path aggregates in SQL, so they share a vocabulary rather than a code path |
+| Autonomy is granted on a measured track record, and refused without one | `apps/docs/docs/operations/shadow-mode.md` (earning autonomy); `services/actions/app/services/autonomy_evidence_rules.py` | `ci.yml` actions job (`test_autonomy_promotion_gate.py`, which starts from one qualifying control and breaks one property per test, so a failure names the property rather than the file) + `integration.yml` (`tests/isolation/test_autonomy_promotion_live.py`, the phase's "Done when" run against a real Postgres: a tenant with 20 recorded shadow decisions is refused, the same tenant with 150 is granted, and injected disagreements demote it. The live half exists because the aggregate and the evaluator agree by convention and a convention is what drifts: only a real database executing the real statement over real rows proves the SQL counts what the gate expects. `AUTONOMY_PROMOTION_LIVE_REQUIRED=1` turns an unreachable database into a failure rather than a skip) | GATED | The four refusals are gated. What is not gated is whether the thresholds are the *right* numbers: 100 decisions and 30 malicious are the plan's, and 95% agreement and 90% recall are choices nobody has yet validated against an outcome. They are configurable per call and travel by value in every snapshot |
+| A promotion cannot be earned by an agent that declines its hard cases | `apps/docs/docs/operations/shadow-mode.md` (what has to be true) | `ci.yml` actions job (`test_autonomy_promotion_gate.py::TestRefusalThreeAgreementBoughtByAbstaining` - an agent that answered a fifth of its queue perfectly is refused, and the test that matters removes the abstention cap entirely and asserts it is *still* refused, on malicious recall, so the second guard is shown to be load-bearing rather than redundant) + `integration.yml` (`test_an_abstention_is_excluded_from_agreement_by_the_real_sql`, which asserts the same property of the aggregate rather than of the type: 10 answered and 90 declined reads as 100% agreement and a 90% abstention rate against live Postgres) | GATED | Three guards, all gated: agreement's denominator, the abstention cap, and recall counting an abstention as a miss. None of them detects an agent that answers confidently and wrongly in a way its analysts also got wrong, which is the limit of grading against human labels at all |
+| An override is distinguishable from earned autonomy, six months later | `apps/docs/docs/operations/shadow-mode.md` (overrides); `067_autonomy_grants.sql` | `integration.yml` (`test_it_is_a_different_word_everywhere_it_lands` - the audit action is `autonomy:overridden` not `autonomy:granted`, the grant row's `source` column is `operator_override`, and the refusals that were waived are in both the row's evidence snapshot and the audit entry's changes. The earned case is asserted from the other side: `waived_refusals` is an empty list, which is the record that nothing had to be overruled. `test_an_override_is_demoted_on_the_same_floors` asserts an override is not permanent, since exempting it would turn it back into the settings toggle this phase replaces) + `ci.yml` web (`AutonomyScorecard.test.tsx` renders the three states distinctly) | GATED | The source is derived from the gate's own verdict and `evaluate_promotion` takes no override argument, so a caller cannot have an override recorded as earned; a test pins that signature. What is not gated is whether the operator's stated reason is truthful |
+| Every autonomy transition is in the hash-chained audit log with its evidence | `plans/aisoc_gap_closure_plan.plan.md` (2.3); `apps/docs/docs/operations/shadow-mode.md` | `integration.yml` (`TestTheTransitionsAreInTheHashChainedLog` - a promotion and the demotion that follows it are replayed through `audit_hash.verify_chain`, the same pure function an external auditor would run over a CSV export, and the second entry is asserted to chain onto the first rather than starting a new one. A `DELETE` against the trail is asserted to raise, because a grant whose record can be quietly removed has no audit trail) | GATED | The chain and the snapshot's presence are gated. The snapshot's *sufficiency* is a judgement: it carries the counts, the thresholds by value, absolute window bounds, the first and last decision id, the models and a digest of the rules, which is what a later reader needs, but no test can prove a question nobody has asked yet is answerable |
+| A track record cannot unlock a high-blast containment | `apps/docs/docs/operations/shadow-mode.md` (what a grant can and cannot unlock); `services/actions/app/live_actions/dispatcher.py` | `ci.yml` actions job (`test_earned_autonomy_wiring.py` - an earned grant raises the tier ceiling to L3 and no further, so MINIMAL, LOW and MEDIUM blast are reachable and HIGH and CRITICAL are not, whatever the evidence says; the capability contract still applies on top, so a verb declared `analyst` or `mandatory_human` stays gated; and a grant is asserted never to lower a bar, only to widen the branch that was already heading for the approval queue) | GATED | The ceiling is gated. The reasoning behind it is a judgement and is stated where the code is: agreement on triage verdicts is evidence about the agent's judgement, not evidence that a high-blast containment was the right call, and one number must not be allowed to unlock both |
| A replay report prints "not measured" where there was no denominator, and no headline accuracy on a corpus too thin to support one | `apps/docs/docs/evaluation/replay.md`; `packages/aisoc-benchmark/aisoc_benchmark/replay.py` | `ci.yml` benchmark job (`test_replay_metrics.py` — a class the agent never predicted reports `None` precision and renders as "not measured", because `0.0` in a recall column says the agent missed every case and "never asked" is a different fact; below 30 malicious cases the headline is withheld with the count and the reason, and the rendered report is asserted to contain no percentage in that section. Three populations are asserted apart: unlabelled findings excluded from accuracy and counted, triage refusals scored as neither answer nor abstention, and abstentions counted against malicious recall. A verdict outside the taxonomy gets its own confusion-matrix column rather than being folded into one the agent did not say. Bootstrap intervals are seeded and the seed and resample count travel in the report, so two runs over one corpus render byte-identically) | GATED | Hallucination extraction reuses the existing `_INDICATOR_PATTERNS`, which over-counts rather than under-counts: a phrase shaped like a domain is checked and, if absent from the evidence, counted. The published rate is a ceiling and the per-decision list travels with it so a disputed count can be re-derived |
## Summary
-- GATED: 151
+- GATED: 156
- PARTIAL: 8
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 0a6676e25..e47df3956 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -10919,6 +10919,117 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/autonomy-policy/grants:
+ get:
+ tags:
+ - autonomy-policy
+ summary: List Autonomy Grants
+ description: 'Every capability this tenant holds or has held, re-checked on
+ the way out.
+
+
+ Reconciliation runs first. A grant whose evidence has slipped below the
+
+ demotion floors is demoted here rather than being listed as current and
+
+ quietly failing at dispatch, which would leave an operator reading a page
+
+ that disagrees with the product.'
+ operationId: list_autonomy_grants_api_v1_autonomy_policy_grants_get
+ security:
+ - HTTPBearer: []
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GrantListResponse'
+ post:
+ tags:
+ - autonomy-policy
+ summary: Request Autonomy Grant
+ description: 'Ask for a capability. The evidence decides; an operator may overrule.
+
+
+ A refusal is a 200 carrying `granted: false` and the reasons, not an
+
+ error. Being told no by a safety control is the control working, and
+
+ rendering it as a failure invites a client to retry it.
+
+
+ The tenant comes from the credential. `scope_key` narrows within that
+
+ tenant and cannot reach past it.'
+ operationId: request_autonomy_grant_api_v1_autonomy_policy_grants_post
+ security:
+ - HTTPBearer: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PromotionRequest'
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PromotionResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ delete:
+ tags:
+ - autonomy-policy
+ summary: Revoke Autonomy Grant
+ description: 'Hand a capability back.
+
+
+ Audited as a revocation rather than as a demotion. A human deciding to
+
+ stop and the evidence deciding for them are different events, and one word
+
+ for both would make "was this taken away because the numbers slipped"
+
+ unanswerable from the log.'
+ operationId: revoke_autonomy_grant_api_v1_autonomy_policy_grants_delete
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: scope_kind
+ in: query
+ required: true
+ schema:
+ type: string
+ title: Scope Kind
+ - name: scope_key
+ in: query
+ required: true
+ schema:
+ type: string
+ maxLength: 200
+ title: Scope Key
+ - name: capability
+ in: query
+ required: true
+ schema:
+ type: string
+ title: Capability
+ responses:
+ '204':
+ description: Successful Response
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/business-context/rules:
get:
tags:
@@ -21313,6 +21424,87 @@ components:
- period_start
- period_end
title: GenerateRequest
+ GrantListResponse:
+ properties:
+ tenant_id:
+ type: string
+ title: Tenant Id
+ grants:
+ items:
+ $ref: '#/components/schemas/GrantModel'
+ type: array
+ title: Grants
+ demoted_now:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Demoted Now
+ type: object
+ required:
+ - tenant_id
+ - grants
+ - demoted_now
+ title: GrantListResponse
+ GrantModel:
+ properties:
+ id:
+ type: string
+ title: Id
+ scope_kind:
+ type: string
+ title: Scope Kind
+ scope_key:
+ type: string
+ title: Scope Key
+ capability:
+ type: string
+ title: Capability
+ state:
+ type: string
+ title: State
+ source:
+ type: string
+ title: Source
+ is_override:
+ type: boolean
+ title: Is Override
+ evidence:
+ anyOf:
+ - additionalProperties: true
+ type: object
+ - type: 'null'
+ title: Evidence
+ granted_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Granted At
+ demoted_at:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Demoted At
+ demoted_reason:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Demoted Reason
+ override_reason:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Override Reason
+ type: object
+ required:
+ - id
+ - scope_kind
+ - scope_key
+ - capability
+ - state
+ - source
+ - is_override
+ title: GrantModel
GraphEdge:
properties:
source:
@@ -25237,6 +25429,73 @@ components:
- suppressed
- changed
title: PreviewRow
+ PromotionRequest:
+ properties:
+ scope_kind:
+ type: string
+ title: Scope Kind
+ description: alert_class or action_verb
+ scope_key:
+ type: string
+ maxLength: 200
+ minLength: 1
+ title: Scope Key
+ capability:
+ type: string
+ title: Capability
+ description: auto_close or auto_execute
+ override:
+ type: boolean
+ title: Override
+ default: false
+ override_reason:
+ anyOf:
+ - type: string
+ maxLength: 500
+ - type: 'null'
+ title: Override Reason
+ type: object
+ required:
+ - scope_kind
+ - scope_key
+ - capability
+ title: PromotionRequest
+ PromotionResponse:
+ properties:
+ granted:
+ type: boolean
+ title: Granted
+ state:
+ type: string
+ title: State
+ source:
+ type: string
+ title: Source
+ is_override:
+ type: boolean
+ title: Is Override
+ refusals:
+ items:
+ type: string
+ type: array
+ title: Refusals
+ evidence:
+ additionalProperties: true
+ type: object
+ title: Evidence
+ changed:
+ type: boolean
+ title: Changed
+ type: object
+ required:
+ - granted
+ - state
+ - source
+ - is_override
+ - refusals
+ - evidence
+ - changed
+ title: PromotionResponse
ProposalResponse:
properties:
id:
diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.py
index 6c1f3a1df..ee8fafe46 100644
--- a/services/actions/app/live_actions/dispatcher.py
+++ b/services/actions/app/live_actions/dispatcher.py
@@ -59,6 +59,13 @@ from .capability_contracts import CAPABILITY_CONTRACTS
from .contract import ActionImpact, ApprovalRequirement, Reversal
from .models import LiveActionRequest, LiveActionResult, LiveActionStatus
+#: The highest tier an earned grant may lift a tenant to. L3 permits MINIMAL,
+#: LOW and MEDIUM blast radius and stops there, so no track record on triage
+#: agreement can make a HIGH-blast containment unattended. `force_auto`, which
+#: is a human writing down a decision about one verb rather than an inference
+#: from agreement, still goes to L4.
+EARNED_TIER_CEILING = MaturityTier.L3_REMEDIATE
+
logger = structlog.get_logger(__name__)
_TIER_ENV = "AISOC_MATURITY_TIER"
@@ -144,14 +151,50 @@ async def _govern(request: LiveActionRequest, action_type: ActionType) -> Autono
tier_label="L4",
)
+ # Gap-closure Phase 2.3. A tenant that has run this verb's alert classes in
+ # shadow and agreed with its own analysts often enough, over a large enough
+ # sample with enough of it malicious, holds an earned grant. The grant
+ # raises the *tier ceiling* exactly as `force_auto` does, and for the same
+ # reason: it is the ceiling that is being argued about, not the contract.
+ #
+ # It stops at L3, where `force_auto` goes to L4. `force_auto` is a human
+ # writing down a decision about one verb; a grant is an inference from
+ # agreement on triage verdicts. That is evidence about the agent's
+ # judgement, and it is not evidence that a HIGH-blast containment was the
+ # right call. L3 permits MINIMAL, LOW and MEDIUM blast and stops there, so
+ # no track record can make `isolate_host` unattended.
+ #
+ # `_apply_capability_contract` still runs on top, so a verb declared
+ # `analyst` or `mandatory_human` stays gated however good the numbers are:
+ # the contract's floors may be raised and never lowered.
+ earned = policy.earned_autonomy_for(action_type.value)
+ effective_tier = policy.tier
+ if earned and policy.tier < EARNED_TIER_CEILING:
+ effective_tier = EARNED_TIER_CEILING
+
+ decision = decide(
+ action_request,
+ tier=effective_tier,
+ whitelisted=policy.is_whitelisted(action_type.value, request.target),
+ )
+ if effective_tier is not policy.tier:
+ # Say which grant did it, and whether it was earned or overruled into
+ # existence. An incident review quotes this sentence, and "autonomous
+ # on a measured track record" and "autonomous because somebody
+ # overruled the gate" are the same action and different findings.
+ earned_phrase = "an operator override of the promotion gate" if earned == "operator_override" else "a measured track record"
+ decision = replace(
+ decision,
+ reason=(
+ f"{decision.reason}; tier ceiling raised from {policy.tier.name} to "
+ f"{effective_tier.name} for '{action_type.value}' under {earned_phrase}"
+ ),
+ )
+
return _apply_capability_contract(
request,
- decide(
- action_request,
- tier=policy.tier,
- whitelisted=policy.is_whitelisted(action_type.value, request.target),
- ),
- tier_label=_tier_label(policy.tier),
+ decision,
+ tier_label=_tier_label(effective_tier),
)
diff --git a/services/actions/app/services/autonomy_evidence_rules.py b/services/actions/app/services/autonomy_evidence_rules.py
index 2256f4ff7..c2b7a87c0 100644
--- a/services/actions/app/services/autonomy_evidence_rules.py
+++ b/services/actions/app/services/autonomy_evidence_rules.py
@@ -1,7 +1,6 @@
-"""How agreement between the agent and a tenant's analysts is measured, decided once.
+"""How autonomy is earned, and what it takes to keep it, decided once.
-Gap-closure Phase 2.2. The promotion gate that reads these numbers arrives in
-Phase 2.3 and sits on top of this file rather than beside it.
+Gap-closure Phase 2.2 and 2.3.
Two services have to agree about this and neither can import the other.
``services/actions`` enforces autonomy at dispatch, where an over-generous
@@ -62,36 +61,153 @@ shows one shows both. The trailing slice is a count rather than a date range
so it means the same thing for a tenant with ten alerts a day and for one with
ten thousand.
-The thresholds live here even though nothing in this file enforces them
-======================================================================
-
-:class:`PromotionThresholds` carries the window length, which this file needs,
-and the floors, which it does not. They travel together because the scorecard
-shows progress toward them ("47 of the 100 decisions, 12 of the 30 malicious
-ones") and because a floor stated in one service and enforced in another is
-the pair that drifts.
+Four refusals the gate exists to make
+=====================================
+
+A promotion gate is only worth the cases where it says no. Each of these is a
+separate :class:`Refusal` rather than one "not eligible", because an operator
+who is told no needs to know what would change the answer, and a gate that
+takes three round trips to explain itself gets overridden out of frustration
+rather than on the merits. Every check runs; none is short-circuited.
+
+**Too few decisions.** :attr:`PromotionThresholds.min_decisions`, 100 by
+default. Nothing subtle: a handful of agreements is not a track record.
+
+**Enough decisions, too few malicious ones.** A real queue is mostly false
+positives, so a tenant reaches 100 decisions with two true positives in them.
+Agreement over that sample says the agent can recognise noise, which is not
+the question being asked. :attr:`PromotionThresholds.min_malicious`, 30 by
+default, is the same floor Phase 1 uses before it will print a headline
+accuracy, and for the same reason.
+
+**Agreement that is high only because the agent abstains.** Three independent
+guards, described above: agreement's denominator excludes abstentions so they
+cannot inflate it, :attr:`PromotionThresholds.max_abstention_rate` caps the
+share of decisions that may be abstentions at all, and malicious recall counts
+an abstention as a miss.
+
+**Drift that arrives gradually.** The window passes while the last fortnight
+falls apart. :func:`evaluate_promotion` scores the same trailing slice that
+would demote an existing grant, so a grant is never issued into a decline it
+would immediately be revoked for.
+
+Demotion floors sit below promotion thresholds on purpose
+=========================================================
+
+If the two were equal a grant would flip on every decision that moved the rate
+across the line, and the audit log would fill with churn nobody could read,
+which is how a real demotion gets missed.
+:attr:`PromotionThresholds.demotion_agreement` and
+:attr:`~PromotionThresholds.demotion_malicious_recall` are the floors, and the
+gap is deliberate hysteresis.
+
+The snapshot is the point
+=========================
+
+:meth:`EvidenceSnapshot.as_dict` is what lands in the audit log beside the
+transition. "Auto-close was enabled for the identity class on 3 March" is not
+auditable; the same sentence carrying the sample size, the agreement rate, the
+recall on malicious, the thresholds in force that day and the window they were
+measured over is.
+
+It records the thresholds **by value** rather than by name, because a
+threshold retuned next quarter would otherwise rewrite the justification for
+every promotion granted under the old one. It records the window as absolute
+timestamps rather than "the last 30 days", which stops meaning anything the
+moment it is read on a different day. It records the counts each rate was
+computed over. And it records :data:`RULES_DIGEST`, a hash of the
+decision-relevant constants in this file, so a reader six months later can
+tell "the gate was more lenient then" from "the numbers were better".
+
+An override is a different word, not a different number
+=======================================================
+
+:class:`GrantSource` has two members and nothing derives which one applies
+from a request field. ``EARNED`` is reserved for a grant the evidence
+justified on its own; ``OPERATOR_OVERRIDE`` is a human overruling a refusal,
+and the refusals that were overruled travel in the snapshot. A caller cannot
+ask for its override to be recorded as earned, because the source is decided
+from the gate's own verdict.
"""
from __future__ import annotations
-from dataclasses import asdict, dataclass
+import hashlib
+import json
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from enum import Enum
from typing import Any
__all__ = [
"ABSTENTION_VERDICTS",
"AGREEMENT_COUNTS_SQL",
+ "CAPABILITIES",
"DEFAULT_THRESHOLDS",
"GRADED_DISPOSITIONS",
"MALICIOUS",
"RECENT_COUNTS_SQL",
+ "RULES_DIGEST",
+ "SCOPE_KINDS",
"UNLABELED",
"AgreementWindow",
+ "EvidenceSnapshot",
+ "GrantSource",
+ "GrantState",
"PromotionThresholds",
+ "Refusal",
+ "TransitionDecision",
+ "evaluate_demotion",
+ "evaluate_promotion",
"scoped_sql",
"to_named_params",
"window_from_counts",
]
+
+class Refusal(str, Enum):
+ """Why a promotion was refused. One member per thing an operator could fix."""
+
+ INSUFFICIENT_SAMPLE = "insufficient_sample"
+ INSUFFICIENT_MALICIOUS = "insufficient_malicious"
+ EXCESSIVE_ABSTENTION = "excessive_abstention"
+ AGREEMENT_BELOW_THRESHOLD = "agreement_below_threshold"
+ MALICIOUS_RECALL_BELOW_THRESHOLD = "malicious_recall_below_threshold"
+ RECENT_DRIFT = "recent_drift"
+ SHADOW_MODE_NOT_ENABLED = "shadow_mode_not_enabled"
+
+
+class GrantState(str, Enum):
+ """Where a scope sits on the ladder from measured to trusted."""
+
+ SHADOW = "shadow"
+ GRANTED = "granted"
+ DEMOTED = "demoted"
+
+
+class GrantSource(str, Enum):
+ """How a grant came to exist. Never inferred from a request field.
+
+ Two words in the database, two words in the audit log, two words on the
+ console, so nothing downstream has to reconstruct which one happened from
+ the numbers.
+ """
+
+ EARNED = "earned"
+ OPERATOR_OVERRIDE = "operator_override"
+
+
+#: What a grant may be about. ``alert_class`` grants auto-closure for a class
+#: of alerts; ``action_verb`` raises one response verb's autonomy tier. Fixed
+#: here rather than left open because both halves of the system have to agree
+#: what a scope key means before they can agree a grant applies.
+SCOPE_KINDS: tuple[str, ...] = ("alert_class", "action_verb")
+
+#: What a grant permits. Listed rather than free text so a capability nobody
+#: enforces cannot be granted: a row saying a tenant may do something no code
+#: path consults is indistinguishable from autonomy that works.
+CAPABILITIES: tuple[str, ...] = ("auto_close", "auto_execute")
+
#: The disposition that means "this was a real threat". One spelling, shared
#: with the writeback taxonomy and the replay grader.
MALICIOUS = "true_positive"
@@ -276,6 +392,178 @@ def window_from_counts(counts: dict[str, Any]) -> AgreementWindow:
)
+@dataclass(frozen=True)
+class EvidenceSnapshot:
+ """The numbers a transition rested on, frozen at the moment it was made."""
+
+ scope_kind: str
+ scope_key: str
+ capability: str
+ window: AgreementWindow
+ recent: AgreementWindow
+ thresholds: PromotionThresholds
+ window_start: datetime
+ window_end: datetime
+ #: Refusals the evidence raised. Empty on an earned grant, populated on a
+ #: demotion, and populated on an override, which is what makes an override
+ #: legible as one rather than as a promotion with unusual numbers.
+ refusals: tuple[Refusal, ...] = ()
+ #: Oldest and newest decision in the window, so the rows behind the
+ #: summary can still be found after the window has moved on.
+ first_decision_id: str | None = None
+ last_decision_id: str | None = None
+ #: Which models produced the verdicts. A model change makes every figure
+ #: before it a description of something else.
+ models: tuple[str, ...] = ()
+ #: Where the analyst closures came from: this console, a vendor, or both.
+ #: "Our analysts agree with it" and "their SIEM agrees with it" are
+ #: different claims and a promotion may rest on either.
+ resolution_sources: tuple[str, ...] = ()
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "scope_kind": self.scope_kind,
+ "scope_key": self.scope_key,
+ "capability": self.capability,
+ "window": self.window.as_dict(),
+ "recent": self.recent.as_dict(),
+ # By value, not by name. A threshold retuned next quarter must not
+ # silently rewrite what this promotion was measured against.
+ "thresholds": self.thresholds.as_dict(),
+ "window_start": self.window_start.isoformat(),
+ "window_end": self.window_end.isoformat(),
+ "refusals": [refusal.value for refusal in self.refusals],
+ "first_decision_id": self.first_decision_id,
+ "last_decision_id": self.last_decision_id,
+ "models": list(self.models),
+ "resolution_sources": list(self.resolution_sources),
+ # Which version of this file judged it. Lets a later reader tell
+ # "the gate was more lenient then" from "the numbers were better".
+ "rules_digest": RULES_DIGEST,
+ }
+
+
+@dataclass(frozen=True)
+class TransitionDecision:
+ """The gate's answer: whether the capability may be held, and why not."""
+
+ allowed: bool
+ refusals: tuple[Refusal, ...] = field(default_factory=tuple)
+
+ @property
+ def refusal_values(self) -> list[str]:
+ return [refusal.value for refusal in self.refusals]
+
+
+def evaluate_promotion(
+ *,
+ window: AgreementWindow,
+ recent: AgreementWindow,
+ thresholds: PromotionThresholds = DEFAULT_THRESHOLDS,
+ shadow_enabled: bool = True,
+) -> TransitionDecision:
+ """Decide whether this track record earns the capability.
+
+ Every check runs; the refusals are not short-circuited. An operator told
+ only the first thing wrong fixes it, re-asks, and is told the second.
+ """
+ refusals: list[Refusal] = []
+
+ if not shadow_enabled:
+ # Nothing was being measured, so there is no track record. Without
+ # this the refusal would be "too few decisions", which reads as "try
+ # again later" rather than "you have not started".
+ refusals.append(Refusal.SHADOW_MODE_NOT_ENABLED)
+
+ if window.labelled < thresholds.min_decisions:
+ refusals.append(Refusal.INSUFFICIENT_SAMPLE)
+
+ if window.malicious_support < thresholds.min_malicious:
+ refusals.append(Refusal.INSUFFICIENT_MALICIOUS)
+
+ abstention = window.abstention_rate
+ if abstention is not None and abstention > thresholds.max_abstention_rate:
+ refusals.append(Refusal.EXCESSIVE_ABSTENTION)
+
+ agreement = window.agreement_rate
+ # `None` is a refusal, not a pass. An agent that answered nothing has an
+ # unmeasured agreement rate, and "not measured" must never be read here as
+ # "met the threshold".
+ if agreement is None or agreement < thresholds.min_agreement:
+ refusals.append(Refusal.AGREEMENT_BELOW_THRESHOLD)
+
+ recall = window.malicious_recall
+ if recall is None or recall < thresholds.min_malicious_recall:
+ refusals.append(Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD)
+
+ # The window can pass while the last fortnight is falling apart. Promotion
+ # is refused on the same trailing slice that would demote an existing
+ # grant, so a grant is never issued into a decline it would immediately be
+ # revoked for.
+ if _recent_has_drifted(recent, thresholds):
+ refusals.append(Refusal.RECENT_DRIFT)
+
+ return TransitionDecision(allowed=not refusals, refusals=tuple(refusals))
+
+
+def evaluate_demotion(
+ *,
+ window: AgreementWindow,
+ recent: AgreementWindow,
+ thresholds: PromotionThresholds = DEFAULT_THRESHOLDS,
+) -> TransitionDecision:
+ """Decide whether an existing grant may stand.
+
+ ``allowed`` means "the grant survives". The floors are below the promotion
+ thresholds so a rate hovering near the line does not flip the grant on
+ every decision, and the trailing slice is checked independently so a
+ decline the window's average is still absorbing is still caught.
+
+ Unlike promotion, an unmeasured rate does **not** demote. A week in which
+ no malicious alert arrived is not evidence the agent got worse, and
+ revoking a grant over an empty denominator would make quiet weeks
+ dangerous.
+ """
+ refusals: list[Refusal] = []
+
+ agreement = window.agreement_rate
+ if agreement is not None and agreement < thresholds.demotion_agreement:
+ refusals.append(Refusal.AGREEMENT_BELOW_THRESHOLD)
+
+ recall = window.malicious_recall
+ if recall is not None and recall < thresholds.demotion_malicious_recall:
+ refusals.append(Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD)
+
+ abstention = window.abstention_rate
+ if abstention is not None and abstention > thresholds.max_abstention_rate:
+ refusals.append(Refusal.EXCESSIVE_ABSTENTION)
+
+ if _recent_has_drifted(recent, thresholds):
+ refusals.append(Refusal.RECENT_DRIFT)
+
+ return TransitionDecision(allowed=not refusals, refusals=tuple(refusals))
+
+
+def _recent_has_drifted(recent: AgreementWindow, thresholds: PromotionThresholds) -> bool:
+ """Whether the trailing slice has fallen below the demotion floors.
+
+ Returns ``False`` on a slice too small to judge. A quiet tenant should not
+ lose a grant because the three decisions since Friday included one
+ disagreement, and ``drift_min_answered`` is where that line is drawn.
+ ``False`` here means "the recent slice cannot say", not "the recent slice
+ is fine"; the window checks apply either way.
+ """
+ if recent.answered < thresholds.drift_min_answered:
+ return False
+ agreement = recent.agreement_rate
+ if agreement is not None and agreement < thresholds.demotion_agreement:
+ return True
+ recall = recent.malicious_recall
+ # Only judge recall on a slice that contained malicious cases at all.
+ # `None` means none arrived, which is not evidence of a decline.
+ return recall is not None and recall < thresholds.demotion_malicious_recall
+
+
# ---------------------------------------------------------------------------
# The aggregate, written once
# ---------------------------------------------------------------------------
@@ -289,6 +577,15 @@ def window_from_counts(counts: dict[str, Any]) -> AgreementWindow:
# The placeholders are numbered (`$1`) for asyncpg. SQLAlchemy callers pass the
# statement through `text()` after `to_named_params()` renames them, because
# the two drivers disagree about placeholder syntax and only about that.
+#
+# The two array parameters carry no `::text[]` cast. They used to, and it was
+# wrong in a way that only shows up on the SQLAlchemy half: `to_named_params`
+# turns `$2::text[]` into `:graded::text[]`, and SQLAlchemy's `text()` parser
+# reads the second colon pair as the start of another bind parameter, so a
+# stray colon reaches Postgres and the statement fails to parse. Both drivers
+# infer the array type from the column being compared, so the cast bought
+# nothing on either side. The SQLAlchemy caller declares the type with
+# `bindparam(..., type_=ARRAY(Text))` instead.
#: Scope filters are applied by the caller as an additional predicate, appended
#: where this marker sits. Written as a marker rather than as string
@@ -298,18 +595,18 @@ _SCOPE_MARKER = "/*scope*/"
AGREEMENT_COUNTS_SQL = f"""
SELECT
COUNT(*)::int AS resolved,
- COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2::text[]))::int AS labelled,
+ COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2))::int AS labelled,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND COALESCE(d.verdict, '') = ANY($3::text[])
+ WHERE d.analyst_disposition = ANY($2)
+ AND COALESCE(d.verdict, '') = ANY($3)
)::int AS abstained,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
)::int AS answered,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
AND d.verdict = d.analyst_disposition
)::int AS agreed,
COUNT(*) FILTER (WHERE d.analyst_disposition = $4)::int AS malicious_support,
@@ -341,18 +638,18 @@ WITH recent AS (
)
SELECT
COUNT(*)::int AS resolved,
- COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2::text[]))::int AS labelled,
+ COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2))::int AS labelled,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND COALESCE(d.verdict, '') = ANY($3::text[])
+ WHERE d.analyst_disposition = ANY($2)
+ AND COALESCE(d.verdict, '') = ANY($3)
)::int AS abstained,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
)::int AS answered,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
AND d.verdict = d.analyst_disposition
)::int AS agreed,
COUNT(*) FILTER (WHERE d.analyst_disposition = $4)::int AS malicious_support,
@@ -384,3 +681,31 @@ def to_named_params(statement: str, names: list[str]) -> str:
for index in range(len(names), 0, -1):
statement = statement.replace(f"${index}", f":{names[index - 1]}")
return statement
+
+
+def _digest_source() -> dict[str, Any]:
+ """The constants a reader would need to reproduce a past decision.
+
+ Deliberately not a hash of the whole file: a docstring edit must not make
+ every historical snapshot look like it was judged by different rules,
+ because then the digest stops being read.
+ """
+ return {
+ "malicious": MALICIOUS,
+ "graded_dispositions": list(GRADED_DISPOSITIONS),
+ "unlabeled": UNLABELED,
+ "abstention_verdicts": sorted(ABSTENTION_VERDICTS),
+ "refusals": [refusal.value for refusal in Refusal],
+ "grant_states": [state.value for state in GrantState],
+ "grant_sources": [source.value for source in GrantSource],
+ "scope_kinds": list(SCOPE_KINDS),
+ "capabilities": list(CAPABILITIES),
+ "default_thresholds": DEFAULT_THRESHOLDS.as_dict(),
+ "agreement_sql": AGREEMENT_COUNTS_SQL,
+ "recent_sql": RECENT_COUNTS_SQL,
+ }
+
+
+#: Hash of everything above that can change what the gate decides. Travels in
+#: every evidence snapshot.
+RULES_DIGEST = hashlib.sha256(json.dumps(_digest_source(), sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
diff --git a/services/actions/app/services/tenant_policy.py b/services/actions/app/services/tenant_policy.py
index 5b6e3fde8..a0b2b7970 100644
--- a/services/actions/app/services/tenant_policy.py
+++ b/services/actions/app/services/tenant_policy.py
@@ -65,6 +65,22 @@ class TenantPolicy:
#: audit trail so an operator can tell a real tenant choice from a default.
from_store: bool = False
source: str = "environment"
+ #: Gap-closure Phase 2.3. Response verbs this tenant has *earned* the right
+ #: to run unattended, keyed by verb, with the source the grant carries.
+ #: Read-only here: this service enforces grants and never issues them, and
+ #: keeping the write path in one place is what stops a dispatch-time
+ #: convenience from turning into a second way to become autonomous.
+ earned_verbs: dict[str, str] = field(default_factory=dict)
+
+ def earned_autonomy_for(self, action_type: str) -> str | None:
+ """The grant source for this verb, or ``None`` when none is held.
+
+ Returns the *source* rather than a boolean so a caller can put the
+ distinction in a rationale. "Auto-executed on a measured track record"
+ and "auto-executed because somebody overruled the gate" are the same
+ action and very different sentences in an incident review.
+ """
+ return self.earned_verbs.get(action_type)
def is_whitelisted(self, action_type: str, target: str | None) -> bool:
"""True when an unexpired whitelist entry covers this action/target.
@@ -148,6 +164,12 @@ async def _load_from_store(tenant_id: str, dsn: str) -> TenantPolicy | None:
""",
UUID(tenant_id),
)
+ # Read on the same connection, before it closes. A second connection
+ # for three columns would double the round trips on a latency-
+ # sensitive path, and the two reads have to describe the same instant
+ # anyway: a tier read before a demotion and a grant list read after it
+ # would compose into a posture neither half ever held.
+ earned_verbs = await _load_earned_verbs(conn, tenant_id)
finally:
await conn.close()
@@ -179,9 +201,42 @@ async def _load_from_store(tenant_id: str, dsn: str) -> TenantPolicy | None:
whitelist=whitelist,
from_store=True,
source="tenant_policy",
+ earned_verbs=earned_verbs,
)
+async def _load_earned_verbs(conn: Any, tenant_id: str) -> dict[str, str]:
+ """Which response verbs this tenant has earned the right to run unattended.
+
+ Gap-closure Phase 2.3. Only rows in the ``granted`` state count; a demoted
+ grant keeps its row so the history survives, and reading it as current is
+ exactly the mistake that would let a revoked capability keep executing.
+
+ A read failure returns nothing rather than raising. That is the safe
+ direction here and it is the opposite of the choice made for the tier: an
+ unreadable *tier* falls back to a conservative floor because the tier
+ permits, while an unreadable *grant list* simply grants nothing, so the
+ caller falls back to whatever the tier alone allows. Failing loudly would
+ take the dispatch path down to avoid being too cautious.
+ """
+ try:
+ rows = await conn.fetch(
+ """
+ SELECT scope_key, source
+ FROM aisoc_autonomy_grants
+ WHERE tenant_id = $1
+ AND state = 'granted'
+ AND scope_kind = 'action_verb'
+ AND capability = 'auto_execute'
+ """,
+ UUID(tenant_id),
+ )
+ except Exception as exc: # noqa: BLE001 - no grant is the safe answer
+ logger.warning("tenant_policy.grants_unreadable", tenant_id=tenant_id, error=str(exc)[:300])
+ return {}
+ return {str(row["scope_key"]): str(row["source"]) for row in rows}
+
+
async def resolve_tenant_policy(tenant_id: str | UUID | None) -> TenantPolicy:
"""Resolve the autonomy policy that governs this tenant's actions."""
dsn = _dsn()
diff --git a/services/actions/app/services/unified_autonomy.py b/services/actions/app/services/unified_autonomy.py
index 983ff7ff5..5a98cfcb8 100644
--- a/services/actions/app/services/unified_autonomy.py
+++ b/services/actions/app/services/unified_autonomy.py
@@ -10,6 +10,36 @@ high model confidence may auto-execute by default (it can be rolled back and
its scope is limited), while anything non-reversible, high/critical blast, or
low-confidence still requires a human. This is the "auto-response by default for
reversible low-blast actions, gated by confidence + rollback" behaviour.
+
+Earned autonomy (gap-closure Phase 2.3)
+=======================================
+
+Confidence is what the model says about itself. It is not evidence, and an
+agent that is confidently wrong is exactly the case this module has to survive.
+Phase 2.3 adds the second input: a *grant*, which a tenant earns by running an
+alert class in shadow mode and agreeing with their own analysts often enough,
+across a large enough sample, with enough of it malicious.
+
+A grant is deliberately a **narrow widening** rather than a new ladder.
+
+* It only ever moves a MEDIUM-blast reversible action from the approval queue
+ to AUTO, and only when confidence already clears the LOW-blast floor. A
+ track record on triage verdicts is evidence about *judgement*; it is not
+ evidence that a HIGH-blast containment was the right call, and the two get
+ conflated the moment one number is allowed to unlock everything.
+* It never touches CRITICAL blast and never touches a non-reversible action.
+ Those refusals come first in :func:`unified_decision` and are unreachable
+ from here, which is why they are checked before the grant is consulted
+ rather than after.
+* It cannot lower a bar. A grant is consulted only on the path that was
+ already heading for the approval queue, so the worst a wrong grant can do is
+ auto-execute something reversible that a human would have approved.
+
+The grant's *source* travels into the rationale rather than being reduced to a
+boolean. "Auto-executed on a measured track record" and "auto-executed because
+an operator overruled the gate" describe the same action and read very
+differently in an incident review, and the rationale is what ends up quoted
+there.
"""
from __future__ import annotations
@@ -31,6 +61,10 @@ class AutonomyDecision:
rationale: str
confidence: float
reversible: bool
+ #: ``earned`` or ``operator_override`` when a Phase 2.3 grant is what
+ #: allowed this to run unattended, ``None`` otherwise. Recorded separately
+ #: from the rationale so a caller can filter on it without parsing prose.
+ earned_from: str | None = None
def is_reversible(action_type: str) -> bool:
@@ -45,13 +79,21 @@ def unified_decision(
reversible: bool | None = None,
low_blast_floor: float = AUTO_LOW_BLAST_CONFIDENCE,
medium_blast_floor: float = AUTO_MEDIUM_BLAST_CONFIDENCE,
+ earned_grant: str | None = None,
) -> AutonomyDecision:
- """Decide how an action may run, unifying model confidence with blast radius."""
+ """Decide how an action may run, unifying model confidence with blast radius.
+
+ ``earned_grant`` is the source of a Phase 2.3 autonomy grant for this verb
+ (``earned`` or ``operator_override``), or ``None``. It can only widen the
+ MEDIUM-blast branch below, and only above the LOW-blast confidence floor;
+ every refusal above that branch is reached first and is unreachable from
+ here. See the module docstring for why the widening is that narrow.
+ """
rev = is_reversible(action_type) if reversible is None else reversible
conf = max(0.0, min(1.0, confidence))
- def d(mode: AutonomyMode, why: str) -> AutonomyDecision:
- return AutonomyDecision(mode=mode, rationale=why, confidence=conf, reversible=rev)
+ def d(mode: AutonomyMode, why: str, *, earned: str | None = None) -> AutonomyDecision:
+ return AutonomyDecision(mode=mode, rationale=why, confidence=conf, reversible=rev, earned_from=earned)
# Critical blast is never auto, regardless of confidence.
if blast_radius == BlastRadius.CRITICAL:
@@ -71,4 +113,19 @@ def unified_decision(
if blast_radius == BlastRadius.MEDIUM and conf >= medium_blast_floor:
return d(AutonomyMode.AUTO, f"reversible MEDIUM-blast action, confidence {conf:.2f} >= {medium_blast_floor:.2f} — auto-execute")
+ # The one place a grant changes the answer. Everything above is reached
+ # first: CRITICAL blast, a non-reversible action and HIGH blast have all
+ # already returned, so no track record can unlock them. The LOW floor is
+ # required as well as the grant, because a grant is evidence about the
+ # agent's judgement in general and confidence is what it says about this
+ # decision, and neither substitutes for the other.
+ if earned_grant and blast_radius == BlastRadius.MEDIUM and conf >= low_blast_floor:
+ earned_phrase = "an operator override" if earned_grant == "operator_override" else "a measured track record"
+ return d(
+ AutonomyMode.AUTO,
+ f"reversible MEDIUM-blast action, confidence {conf:.2f} >= {low_blast_floor:.2f} and this verb "
+ f"is autonomous under {earned_phrase} — auto-execute",
+ earned=earned_grant,
+ )
+
return d(AutonomyMode.QUEUED_APPROVAL, f"confidence {conf:.2f} below auto floor for {blast_radius.value} blast — queued for approval")
diff --git a/services/actions/tests/test_autonomy_promotion_gate.py b/services/actions/tests/test_autonomy_promotion_gate.py
new file mode 100644
index 000000000..35c6899a9
--- /dev/null
+++ b/services/actions/tests/test_autonomy_promotion_gate.py
@@ -0,0 +1,294 @@
+"""The promotion gate, tested on the cases where it has to say no.
+
+Gap-closure Phase 2.3.
+
+A gate is worth only its refusals. Four of them are interesting enough that
+getting any one wrong would let a tenant act unattended on a track record that
+does not support it, and each fails in a way that looks reasonable from the
+outside:
+
+* too few decisions, which is the easy one
+* enough decisions but too few malicious ones, which a queue produces by
+ itself because a real queue is mostly false positives
+* agreement that is high only because the agent abstains, which looks like
+ caution from every angle
+* drift that arrives gradually, which a window average absorbs
+
+The fifth case, and the one the audit log exists for, is an operator
+overruling a refusal. That has to stay possible and has to stay visibly
+distinct from autonomy anybody earned.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.autonomy_evidence_rules import (
+ DEFAULT_THRESHOLDS,
+ AgreementWindow,
+ GrantSource,
+ PromotionThresholds,
+ Refusal,
+ evaluate_demotion,
+ evaluate_promotion,
+)
+
+
+def window(
+ *,
+ labelled: int,
+ agreed: int,
+ malicious_support: int,
+ malicious_caught: int,
+ abstained: int = 0,
+ unlabeled: int = 0,
+) -> AgreementWindow:
+ """A window with the counts named, and answered derived so they add up."""
+ return AgreementWindow(
+ resolved=labelled + unlabeled,
+ labelled=labelled,
+ abstained=abstained,
+ answered=labelled - abstained,
+ agreed=agreed,
+ malicious_support=malicious_support,
+ malicious_caught=malicious_caught,
+ )
+
+
+def qualifying() -> AgreementWindow:
+ """A track record that earns the capability, used as the control.
+
+ Every refusal test below starts from this and breaks one thing, so a test
+ that fails tells you which property it was rather than that something is
+ wrong somewhere.
+ """
+ return window(labelled=120, agreed=112, malicious_support=35, malicious_caught=34, abstained=6)
+
+
+def healthy_recent() -> AgreementWindow:
+ return window(labelled=50, agreed=49, malicious_support=14, malicious_caught=14, abstained=1)
+
+
+class TestTheControlIsActuallyQualifying:
+ def test_a_good_track_record_earns_it(self):
+ verdict = evaluate_promotion(window=qualifying(), recent=healthy_recent())
+ assert verdict.allowed is True
+ assert verdict.refusals == ()
+
+
+class TestRefusalOneTooFewDecisions:
+ def test_twenty_decisions_is_not_a_track_record(self):
+ verdict = evaluate_promotion(
+ window=window(labelled=20, agreed=20, malicious_support=8, malicious_caught=8),
+ recent=window(labelled=20, agreed=20, malicious_support=8, malicious_caught=8),
+ )
+ assert verdict.allowed is False
+ assert Refusal.INSUFFICIENT_SAMPLE in verdict.refusals
+
+ def test_perfect_agreement_does_not_substitute_for_a_sample(self):
+ """20 for 20 is 100%, and it is still 20."""
+ verdict = evaluate_promotion(
+ window=window(labelled=20, agreed=20, malicious_support=20, malicious_caught=20),
+ recent=AgreementWindow(),
+ )
+ assert verdict.allowed is False
+
+ def test_the_floor_is_configurable(self):
+ small = window(labelled=20, agreed=20, malicious_support=8, malicious_caught=8)
+ relaxed = PromotionThresholds(min_decisions=10, min_malicious=5, drift_min_answered=100)
+ assert evaluate_promotion(window=small, recent=small, thresholds=relaxed).allowed is True
+
+
+class TestRefusalTwoTooFewMaliciousCases:
+ def test_a_large_sample_of_a_quiet_queue_is_refused(self):
+ """A real queue reaches 100 decisions with two true positives in it.
+
+ Agreement over that sample says the agent can recognise noise. That is
+ not the question, and it is the shape almost every evaluation corpus
+ naturally takes.
+ """
+ verdict = evaluate_promotion(
+ window=window(labelled=400, agreed=398, malicious_support=2, malicious_caught=2),
+ recent=window(labelled=50, agreed=50, malicious_support=0, malicious_caught=0),
+ )
+ assert verdict.allowed is False
+ assert Refusal.INSUFFICIENT_MALICIOUS in verdict.refusals
+ # And not for want of a sample: the sample is four times the floor.
+ assert Refusal.INSUFFICIENT_SAMPLE not in verdict.refusals
+
+ def test_the_floor_matches_the_one_replay_uses(self):
+ """Phase 1 withholds a headline accuracy below 30 malicious cases.
+
+ Two different floors for the same statistical problem would mean a
+ replay report that refuses to print a number and a promotion gate that
+ acts on it.
+ """
+ assert DEFAULT_THRESHOLDS.min_malicious == 30
+
+ def test_zero_malicious_cases_refuses_on_recall_too(self):
+ """An unmeasured recall is a refusal, not a pass.
+
+ "Not measured" must never be read here as "met the threshold", which
+ is the direction a `None` silently takes if it is compared with `<`.
+ """
+ verdict = evaluate_promotion(
+ window=window(labelled=400, agreed=400, malicious_support=0, malicious_caught=0),
+ recent=AgreementWindow(),
+ )
+ assert Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD in verdict.refusals
+
+
+class TestRefusalThreeAgreementBoughtByAbstaining:
+ def test_an_agent_that_declines_most_of_its_queue_is_refused(self):
+ """Perfect on everything it answered, and it answered a fifth of them.
+
+ This is the refusal a naive gate misses, because every number it looks
+ at is excellent.
+ """
+ verdict = evaluate_promotion(
+ window=window(labelled=200, abstained=160, agreed=40, malicious_support=40, malicious_caught=12),
+ recent=window(labelled=50, abstained=40, agreed=10, malicious_support=10, malicious_caught=3),
+ )
+ assert verdict.allowed is False
+ assert Refusal.EXCESSIVE_ABSTENTION in verdict.refusals
+
+ def test_abstaining_did_not_lift_the_agreement_rate_that_was_checked(self):
+ """The guard that does not depend on a threshold at all.
+
+ Even with the abstention cap removed, the agent is refused, because
+ every malicious case it declined counted against recall. Two
+ independent guards, and this test removes the first to prove the
+ second is load-bearing rather than redundant.
+ """
+ evasive = window(labelled=200, abstained=160, agreed=40, malicious_support=40, malicious_caught=12)
+ assert evasive.agreement_rate == 1.0
+
+ no_abstention_cap = PromotionThresholds(max_abstention_rate=1.0)
+ verdict = evaluate_promotion(window=evasive, recent=AgreementWindow(), thresholds=no_abstention_cap)
+
+ assert verdict.allowed is False
+ assert Refusal.EXCESSIVE_ABSTENTION not in verdict.refusals
+ assert Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD in verdict.refusals
+
+ def test_answering_nothing_at_all_is_refused_rather_than_unmeasured(self):
+ verdict = evaluate_promotion(
+ window=window(labelled=200, abstained=200, agreed=0, malicious_support=40, malicious_caught=0),
+ recent=AgreementWindow(),
+ )
+ assert verdict.allowed is False
+ assert Refusal.AGREEMENT_BELOW_THRESHOLD in verdict.refusals
+
+
+class TestRefusalFourGradualDrift:
+ def test_a_window_that_still_passes_is_refused_when_the_recent_slice_has_slipped(self):
+ """The case a window average is built to hide.
+
+ Three weeks at 99% and one week at 70% still averages about 95%. The
+ window is genuinely qualifying here; the trailing slice is not, and
+ that is the whole finding.
+ """
+ recent_decline = window(labelled=50, agreed=35, malicious_support=12, malicious_caught=11, abstained=2)
+ assert (recent_decline.agreement_rate or 0) < DEFAULT_THRESHOLDS.demotion_agreement
+
+ verdict = evaluate_promotion(window=qualifying(), recent=recent_decline)
+
+ assert verdict.allowed is False
+ assert verdict.refusals == (Refusal.RECENT_DRIFT,)
+
+ def test_an_existing_grant_is_demoted_on_the_same_slice(self):
+ """Promotion and demotion read the same trailing slice.
+
+ A grant issued into a decline it would be revoked for the next moment
+ would produce a promote/demote pair in the audit log seconds apart,
+ which reads as a malfunction rather than as a gate working.
+ """
+ recent_decline = window(labelled=50, agreed=35, malicious_support=12, malicious_caught=11, abstained=2)
+ assert evaluate_demotion(window=qualifying(), recent=recent_decline).allowed is False
+
+ def test_a_slice_too_small_to_judge_does_not_demote(self):
+ """A quiet tenant must not lose a grant over three decisions.
+
+ `False` from the drift check means "the recent slice cannot say", not
+ "the recent slice is fine"; the window checks still apply, and this
+ test pins the distinction so a later tightening does not make quiet
+ weeks dangerous.
+ """
+ tiny_and_bad = window(labelled=4, agreed=1, malicious_support=2, malicious_caught=0)
+ assert evaluate_demotion(window=qualifying(), recent=tiny_and_bad).allowed is True
+
+ def test_a_recent_slice_with_no_malicious_cases_does_not_demote_on_recall(self):
+ """No true positives arrived. That is not evidence the agent got worse."""
+ quiet = window(labelled=50, agreed=49, malicious_support=0, malicious_caught=0, abstained=1)
+ assert evaluate_demotion(window=qualifying(), recent=quiet).allowed is True
+
+
+class TestDemotionIsNotTheMirrorOfPromotion:
+ def test_the_floors_sit_below_the_promotion_thresholds(self):
+ """Deliberate hysteresis: a rate at the line must not flip the grant."""
+ borderline = window(labelled=120, agreed=112, malicious_support=35, malicious_caught=30, abstained=0)
+ rate = borderline.agreement_rate or 0.0
+ assert rate < DEFAULT_THRESHOLDS.min_agreement
+ assert rate >= DEFAULT_THRESHOLDS.demotion_agreement
+
+ # Not good enough to earn, good enough to keep. That gap is the point.
+ assert evaluate_promotion(window=borderline, recent=healthy_recent()).allowed is False
+ assert evaluate_demotion(window=borderline, recent=healthy_recent()).allowed is True
+
+ def test_an_unmeasured_rate_refuses_a_promotion_and_does_not_demote_a_grant(self):
+ """The asymmetry stated as a test, because it looks like an inconsistency.
+
+ Promotion: nothing has been shown, so no. Demotion: nothing has been
+ shown, so there is no evidence the agent got worse, and revoking over
+ an empty denominator would punish a quiet week.
+ """
+ nothing_yet = AgreementWindow()
+ assert evaluate_promotion(window=nothing_yet, recent=nothing_yet).allowed is False
+ assert evaluate_demotion(window=nothing_yet, recent=nothing_yet).allowed is True
+
+
+class TestItSaysEverythingThatIsWrongAtOnce:
+ def test_refusals_are_not_short_circuited(self):
+ """An operator told one thing at a time overrides out of frustration.
+
+ Three separate problems here, and all three come back together.
+ """
+ verdict = evaluate_promotion(
+ window=window(labelled=30, abstained=20, agreed=6, malicious_support=4, malicious_caught=1),
+ recent=AgreementWindow(),
+ )
+ assert Refusal.INSUFFICIENT_SAMPLE in verdict.refusals
+ assert Refusal.INSUFFICIENT_MALICIOUS in verdict.refusals
+ assert Refusal.EXCESSIVE_ABSTENTION in verdict.refusals
+ assert len(verdict.refusals) >= 3
+
+ def test_never_measured_is_its_own_refusal(self):
+ """A tenant who never started must not be told to try again later."""
+ verdict = evaluate_promotion(window=qualifying(), recent=healthy_recent(), shadow_enabled=False)
+ assert verdict.allowed is False
+ assert verdict.refusals == (Refusal.SHADOW_MODE_NOT_ENABLED,)
+
+
+class TestAnOverrideIsADifferentWord:
+ def test_the_two_sources_are_distinct_values(self):
+ assert GrantSource.EARNED.value != GrantSource.OPERATOR_OVERRIDE.value
+
+ def test_the_gate_verdict_is_identical_whether_or_not_an_override_follows(self):
+ """`evaluate_promotion` takes no override argument, and that is the design.
+
+ The source is decided from this verdict by the caller, so there is no
+ argument a caller could pass that would make a refused promotion
+ evaluate as allowed and be recorded as earned.
+ """
+ import inspect
+
+ parameters = set(inspect.signature(evaluate_promotion).parameters)
+ assert "override" not in parameters
+ assert parameters == {"window", "recent", "thresholds", "shadow_enabled"}
+
+
+class TestThresholdsTravelByValue:
+ def test_a_snapshot_records_numbers_not_a_reference(self):
+ """Retuning a threshold next quarter must not rewrite past justifications."""
+ strict = PromotionThresholds(min_agreement=0.99)
+ payload = strict.as_dict()
+ assert payload["min_agreement"] == pytest.approx(0.99)
+ assert payload["min_decisions"] == DEFAULT_THRESHOLDS.min_decisions
diff --git a/services/actions/tests/test_earned_autonomy_wiring.py b/services/actions/tests/test_earned_autonomy_wiring.py
new file mode 100644
index 000000000..7f60a4220
--- /dev/null
+++ b/services/actions/tests/test_earned_autonomy_wiring.py
@@ -0,0 +1,192 @@
+"""What an earned grant is allowed to change at dispatch, and what it is not.
+
+Gap-closure Phase 2.3.
+
+A grant is a narrow widening, and the tests worth having are about the edges of
+that narrowness rather than about the happy path. An autonomy control that only
+ever gets tested on the case where it says yes is a control nobody has checked
+the shape of.
+
+The reasoning the tests pin, stated once: agreement on triage verdicts is
+evidence about the agent's *judgement*. It is not evidence that isolating a
+host was the right call. Allowing one number to unlock both is how a
+measurement of one thing becomes permission for another.
+"""
+
+from __future__ import annotations
+
+from app.live_actions.dispatcher import EARNED_TIER_CEILING
+from app.models.action import BlastRadius
+from app.services.autonomy_evidence_rules import GrantSource
+from app.services.autonomy_safety import AutonomyMode
+from app.services.maturity import _AUTO_ALLOWED_AT_TIER, MaturityTier
+from app.services.tenant_policy import TenantPolicy
+from app.services.unified_autonomy import unified_decision
+
+
+class TestTheCeilingStopsAtMediumBlast:
+ def test_a_grant_cannot_reach_l4(self):
+ """`force_auto` goes to L4; a grant stops at L3.
+
+ The difference is what each one is. `force_auto` is a human writing
+ down a decision about one verb. A grant is an inference from agreement
+ on triage verdicts, and an inference must not buy as much as a
+ decision.
+ """
+ assert EARNED_TIER_CEILING is MaturityTier.L3_REMEDIATE
+ assert EARNED_TIER_CEILING < MaturityTier.L4_AUTOMATE
+
+ def test_the_ceiling_permits_medium_and_nothing_above_it(self):
+ permitted = _AUTO_ALLOWED_AT_TIER[EARNED_TIER_CEILING]
+ assert BlastRadius.MEDIUM in permitted
+ assert BlastRadius.HIGH not in permitted
+ assert BlastRadius.CRITICAL not in permitted
+
+
+class TestThePolicyCarriesTheGrantButNeverIssuesOne:
+ def test_a_tenant_with_no_grants_has_no_earned_autonomy(self):
+ assert TenantPolicy(tier=MaturityTier.L2_CONTAIN).earned_autonomy_for("block_ip") is None
+
+ def test_the_source_comes_back_rather_than_a_boolean(self):
+ """A caller has to be able to say *which* kind of autonomy this was.
+
+ "Auto-executed on a measured track record" and "auto-executed because
+ somebody overruled the gate" are the same action and very different
+ sentences in an incident review, and the rationale is what gets quoted
+ there.
+ """
+ policy = TenantPolicy(
+ tier=MaturityTier.L2_CONTAIN,
+ earned_verbs={"block_ip": GrantSource.OPERATOR_OVERRIDE.value},
+ )
+ assert policy.earned_autonomy_for("block_ip") == "operator_override"
+
+ def test_a_grant_for_one_verb_does_not_cover_another(self):
+ policy = TenantPolicy(tier=MaturityTier.L2_CONTAIN, earned_verbs={"block_ip": "earned"})
+ assert policy.earned_autonomy_for("isolate_host") is None
+
+
+class TestAGrantOnlyWidensOneBranch:
+ def test_it_does_not_reach_a_critical_blast_action(self):
+ """Checked before the grant is consulted, so no evidence can reach it."""
+ decision = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.CRITICAL,
+ confidence=0.99,
+ reversible=True,
+ earned_grant="earned",
+ )
+ assert decision.mode is AutonomyMode.QUEUED_APPROVAL
+ assert decision.earned_from is None
+
+ def test_it_does_not_reach_a_non_reversible_action(self):
+ """Without a rollback path a wrong call cannot be undone, whatever the record."""
+ decision = unified_decision(
+ action_type="isolate_host",
+ blast_radius=BlastRadius.LOW,
+ confidence=0.99,
+ reversible=False,
+ earned_grant="earned",
+ )
+ assert decision.mode is AutonomyMode.QUEUED_APPROVAL
+
+ def test_it_does_not_reach_a_high_blast_action(self):
+ decision = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.HIGH,
+ confidence=0.99,
+ reversible=True,
+ earned_grant="earned",
+ )
+ assert decision.mode is AutonomyMode.QUEUED_APPROVAL
+
+ def test_it_widens_a_medium_blast_action_above_the_low_floor(self):
+ """The one place a grant changes the answer.
+
+ Without the grant a reversible MEDIUM-blast action at 0.90 confidence
+ queues, because the MEDIUM floor is 0.95.
+ """
+ without = unified_decision(action_type="block_ip", blast_radius=BlastRadius.MEDIUM, confidence=0.90, reversible=True)
+ assert without.mode is AutonomyMode.QUEUED_APPROVAL
+
+ with_grant = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.MEDIUM,
+ confidence=0.90,
+ reversible=True,
+ earned_grant="earned",
+ )
+ assert with_grant.mode is AutonomyMode.AUTO
+ assert with_grant.earned_from == "earned"
+
+ def test_confidence_is_still_required(self):
+ """A grant is evidence about the agent in general.
+
+ Confidence is what it says about this decision. Neither substitutes
+ for the other, so a low-confidence call still queues even with a
+ perfect track record behind the verb.
+ """
+ decision = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.MEDIUM,
+ confidence=0.40,
+ reversible=True,
+ earned_grant="earned",
+ )
+ assert decision.mode is AutonomyMode.QUEUED_APPROVAL
+
+ def test_a_grant_never_lowers_a_bar(self):
+ """It is consulted only on the path already heading for the queue.
+
+ So the worst a wrong grant can do is auto-execute something reversible
+ that a human would have approved. Everything that was AUTO without it
+ stays AUTO, and everything that was BLOCKED or queued for a structural
+ reason stays there.
+ """
+ for blast in (BlastRadius.LOW, BlastRadius.MEDIUM, BlastRadius.HIGH, BlastRadius.CRITICAL):
+ for confidence in (0.10, 0.50, 0.86, 0.96, 1.0):
+ for reversible in (True, False):
+ plain = unified_decision(
+ action_type="block_ip",
+ blast_radius=blast,
+ confidence=confidence,
+ reversible=reversible,
+ )
+ granted = unified_decision(
+ action_type="block_ip",
+ blast_radius=blast,
+ confidence=confidence,
+ reversible=reversible,
+ earned_grant="earned",
+ )
+ if plain.mode is AutonomyMode.AUTO:
+ assert granted.mode is AutonomyMode.AUTO, (blast, confidence, reversible)
+ else:
+ # The only permitted movement is queued -> auto, and
+ # only on the reversible MEDIUM branch.
+ assert granted.mode in {plain.mode, AutonomyMode.AUTO}
+ if granted.mode is not plain.mode:
+ assert blast is BlastRadius.MEDIUM and reversible
+
+
+class TestTheRationaleSaysWhichKind:
+ def test_an_earned_grant_reads_as_a_track_record(self):
+ decision = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.MEDIUM,
+ confidence=0.90,
+ reversible=True,
+ earned_grant="earned",
+ )
+ assert "measured track record" in decision.rationale
+
+ def test_an_override_reads_as_an_override(self):
+ decision = unified_decision(
+ action_type="block_ip",
+ blast_radius=BlastRadius.MEDIUM,
+ confidence=0.90,
+ reversible=True,
+ earned_grant="operator_override",
+ )
+ assert "operator override" in decision.rationale
+ assert decision.earned_from == "operator_override"
diff --git a/services/api/app/_vendor/autonomy_evidence_rules.py b/services/api/app/_vendor/autonomy_evidence_rules.py
index 2256f4ff7..c2b7a87c0 100644
--- a/services/api/app/_vendor/autonomy_evidence_rules.py
+++ b/services/api/app/_vendor/autonomy_evidence_rules.py
@@ -1,7 +1,6 @@
-"""How agreement between the agent and a tenant's analysts is measured, decided once.
+"""How autonomy is earned, and what it takes to keep it, decided once.
-Gap-closure Phase 2.2. The promotion gate that reads these numbers arrives in
-Phase 2.3 and sits on top of this file rather than beside it.
+Gap-closure Phase 2.2 and 2.3.
Two services have to agree about this and neither can import the other.
``services/actions`` enforces autonomy at dispatch, where an over-generous
@@ -62,36 +61,153 @@ shows one shows both. The trailing slice is a count rather than a date range
so it means the same thing for a tenant with ten alerts a day and for one with
ten thousand.
-The thresholds live here even though nothing in this file enforces them
-======================================================================
-
-:class:`PromotionThresholds` carries the window length, which this file needs,
-and the floors, which it does not. They travel together because the scorecard
-shows progress toward them ("47 of the 100 decisions, 12 of the 30 malicious
-ones") and because a floor stated in one service and enforced in another is
-the pair that drifts.
+Four refusals the gate exists to make
+=====================================
+
+A promotion gate is only worth the cases where it says no. Each of these is a
+separate :class:`Refusal` rather than one "not eligible", because an operator
+who is told no needs to know what would change the answer, and a gate that
+takes three round trips to explain itself gets overridden out of frustration
+rather than on the merits. Every check runs; none is short-circuited.
+
+**Too few decisions.** :attr:`PromotionThresholds.min_decisions`, 100 by
+default. Nothing subtle: a handful of agreements is not a track record.
+
+**Enough decisions, too few malicious ones.** A real queue is mostly false
+positives, so a tenant reaches 100 decisions with two true positives in them.
+Agreement over that sample says the agent can recognise noise, which is not
+the question being asked. :attr:`PromotionThresholds.min_malicious`, 30 by
+default, is the same floor Phase 1 uses before it will print a headline
+accuracy, and for the same reason.
+
+**Agreement that is high only because the agent abstains.** Three independent
+guards, described above: agreement's denominator excludes abstentions so they
+cannot inflate it, :attr:`PromotionThresholds.max_abstention_rate` caps the
+share of decisions that may be abstentions at all, and malicious recall counts
+an abstention as a miss.
+
+**Drift that arrives gradually.** The window passes while the last fortnight
+falls apart. :func:`evaluate_promotion` scores the same trailing slice that
+would demote an existing grant, so a grant is never issued into a decline it
+would immediately be revoked for.
+
+Demotion floors sit below promotion thresholds on purpose
+=========================================================
+
+If the two were equal a grant would flip on every decision that moved the rate
+across the line, and the audit log would fill with churn nobody could read,
+which is how a real demotion gets missed.
+:attr:`PromotionThresholds.demotion_agreement` and
+:attr:`~PromotionThresholds.demotion_malicious_recall` are the floors, and the
+gap is deliberate hysteresis.
+
+The snapshot is the point
+=========================
+
+:meth:`EvidenceSnapshot.as_dict` is what lands in the audit log beside the
+transition. "Auto-close was enabled for the identity class on 3 March" is not
+auditable; the same sentence carrying the sample size, the agreement rate, the
+recall on malicious, the thresholds in force that day and the window they were
+measured over is.
+
+It records the thresholds **by value** rather than by name, because a
+threshold retuned next quarter would otherwise rewrite the justification for
+every promotion granted under the old one. It records the window as absolute
+timestamps rather than "the last 30 days", which stops meaning anything the
+moment it is read on a different day. It records the counts each rate was
+computed over. And it records :data:`RULES_DIGEST`, a hash of the
+decision-relevant constants in this file, so a reader six months later can
+tell "the gate was more lenient then" from "the numbers were better".
+
+An override is a different word, not a different number
+=======================================================
+
+:class:`GrantSource` has two members and nothing derives which one applies
+from a request field. ``EARNED`` is reserved for a grant the evidence
+justified on its own; ``OPERATOR_OVERRIDE`` is a human overruling a refusal,
+and the refusals that were overruled travel in the snapshot. A caller cannot
+ask for its override to be recorded as earned, because the source is decided
+from the gate's own verdict.
"""
from __future__ import annotations
-from dataclasses import asdict, dataclass
+import hashlib
+import json
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from enum import Enum
from typing import Any
__all__ = [
"ABSTENTION_VERDICTS",
"AGREEMENT_COUNTS_SQL",
+ "CAPABILITIES",
"DEFAULT_THRESHOLDS",
"GRADED_DISPOSITIONS",
"MALICIOUS",
"RECENT_COUNTS_SQL",
+ "RULES_DIGEST",
+ "SCOPE_KINDS",
"UNLABELED",
"AgreementWindow",
+ "EvidenceSnapshot",
+ "GrantSource",
+ "GrantState",
"PromotionThresholds",
+ "Refusal",
+ "TransitionDecision",
+ "evaluate_demotion",
+ "evaluate_promotion",
"scoped_sql",
"to_named_params",
"window_from_counts",
]
+
+class Refusal(str, Enum):
+ """Why a promotion was refused. One member per thing an operator could fix."""
+
+ INSUFFICIENT_SAMPLE = "insufficient_sample"
+ INSUFFICIENT_MALICIOUS = "insufficient_malicious"
+ EXCESSIVE_ABSTENTION = "excessive_abstention"
+ AGREEMENT_BELOW_THRESHOLD = "agreement_below_threshold"
+ MALICIOUS_RECALL_BELOW_THRESHOLD = "malicious_recall_below_threshold"
+ RECENT_DRIFT = "recent_drift"
+ SHADOW_MODE_NOT_ENABLED = "shadow_mode_not_enabled"
+
+
+class GrantState(str, Enum):
+ """Where a scope sits on the ladder from measured to trusted."""
+
+ SHADOW = "shadow"
+ GRANTED = "granted"
+ DEMOTED = "demoted"
+
+
+class GrantSource(str, Enum):
+ """How a grant came to exist. Never inferred from a request field.
+
+ Two words in the database, two words in the audit log, two words on the
+ console, so nothing downstream has to reconstruct which one happened from
+ the numbers.
+ """
+
+ EARNED = "earned"
+ OPERATOR_OVERRIDE = "operator_override"
+
+
+#: What a grant may be about. ``alert_class`` grants auto-closure for a class
+#: of alerts; ``action_verb`` raises one response verb's autonomy tier. Fixed
+#: here rather than left open because both halves of the system have to agree
+#: what a scope key means before they can agree a grant applies.
+SCOPE_KINDS: tuple[str, ...] = ("alert_class", "action_verb")
+
+#: What a grant permits. Listed rather than free text so a capability nobody
+#: enforces cannot be granted: a row saying a tenant may do something no code
+#: path consults is indistinguishable from autonomy that works.
+CAPABILITIES: tuple[str, ...] = ("auto_close", "auto_execute")
+
#: The disposition that means "this was a real threat". One spelling, shared
#: with the writeback taxonomy and the replay grader.
MALICIOUS = "true_positive"
@@ -276,6 +392,178 @@ def window_from_counts(counts: dict[str, Any]) -> AgreementWindow:
)
+@dataclass(frozen=True)
+class EvidenceSnapshot:
+ """The numbers a transition rested on, frozen at the moment it was made."""
+
+ scope_kind: str
+ scope_key: str
+ capability: str
+ window: AgreementWindow
+ recent: AgreementWindow
+ thresholds: PromotionThresholds
+ window_start: datetime
+ window_end: datetime
+ #: Refusals the evidence raised. Empty on an earned grant, populated on a
+ #: demotion, and populated on an override, which is what makes an override
+ #: legible as one rather than as a promotion with unusual numbers.
+ refusals: tuple[Refusal, ...] = ()
+ #: Oldest and newest decision in the window, so the rows behind the
+ #: summary can still be found after the window has moved on.
+ first_decision_id: str | None = None
+ last_decision_id: str | None = None
+ #: Which models produced the verdicts. A model change makes every figure
+ #: before it a description of something else.
+ models: tuple[str, ...] = ()
+ #: Where the analyst closures came from: this console, a vendor, or both.
+ #: "Our analysts agree with it" and "their SIEM agrees with it" are
+ #: different claims and a promotion may rest on either.
+ resolution_sources: tuple[str, ...] = ()
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "scope_kind": self.scope_kind,
+ "scope_key": self.scope_key,
+ "capability": self.capability,
+ "window": self.window.as_dict(),
+ "recent": self.recent.as_dict(),
+ # By value, not by name. A threshold retuned next quarter must not
+ # silently rewrite what this promotion was measured against.
+ "thresholds": self.thresholds.as_dict(),
+ "window_start": self.window_start.isoformat(),
+ "window_end": self.window_end.isoformat(),
+ "refusals": [refusal.value for refusal in self.refusals],
+ "first_decision_id": self.first_decision_id,
+ "last_decision_id": self.last_decision_id,
+ "models": list(self.models),
+ "resolution_sources": list(self.resolution_sources),
+ # Which version of this file judged it. Lets a later reader tell
+ # "the gate was more lenient then" from "the numbers were better".
+ "rules_digest": RULES_DIGEST,
+ }
+
+
+@dataclass(frozen=True)
+class TransitionDecision:
+ """The gate's answer: whether the capability may be held, and why not."""
+
+ allowed: bool
+ refusals: tuple[Refusal, ...] = field(default_factory=tuple)
+
+ @property
+ def refusal_values(self) -> list[str]:
+ return [refusal.value for refusal in self.refusals]
+
+
+def evaluate_promotion(
+ *,
+ window: AgreementWindow,
+ recent: AgreementWindow,
+ thresholds: PromotionThresholds = DEFAULT_THRESHOLDS,
+ shadow_enabled: bool = True,
+) -> TransitionDecision:
+ """Decide whether this track record earns the capability.
+
+ Every check runs; the refusals are not short-circuited. An operator told
+ only the first thing wrong fixes it, re-asks, and is told the second.
+ """
+ refusals: list[Refusal] = []
+
+ if not shadow_enabled:
+ # Nothing was being measured, so there is no track record. Without
+ # this the refusal would be "too few decisions", which reads as "try
+ # again later" rather than "you have not started".
+ refusals.append(Refusal.SHADOW_MODE_NOT_ENABLED)
+
+ if window.labelled < thresholds.min_decisions:
+ refusals.append(Refusal.INSUFFICIENT_SAMPLE)
+
+ if window.malicious_support < thresholds.min_malicious:
+ refusals.append(Refusal.INSUFFICIENT_MALICIOUS)
+
+ abstention = window.abstention_rate
+ if abstention is not None and abstention > thresholds.max_abstention_rate:
+ refusals.append(Refusal.EXCESSIVE_ABSTENTION)
+
+ agreement = window.agreement_rate
+ # `None` is a refusal, not a pass. An agent that answered nothing has an
+ # unmeasured agreement rate, and "not measured" must never be read here as
+ # "met the threshold".
+ if agreement is None or agreement < thresholds.min_agreement:
+ refusals.append(Refusal.AGREEMENT_BELOW_THRESHOLD)
+
+ recall = window.malicious_recall
+ if recall is None or recall < thresholds.min_malicious_recall:
+ refusals.append(Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD)
+
+ # The window can pass while the last fortnight is falling apart. Promotion
+ # is refused on the same trailing slice that would demote an existing
+ # grant, so a grant is never issued into a decline it would immediately be
+ # revoked for.
+ if _recent_has_drifted(recent, thresholds):
+ refusals.append(Refusal.RECENT_DRIFT)
+
+ return TransitionDecision(allowed=not refusals, refusals=tuple(refusals))
+
+
+def evaluate_demotion(
+ *,
+ window: AgreementWindow,
+ recent: AgreementWindow,
+ thresholds: PromotionThresholds = DEFAULT_THRESHOLDS,
+) -> TransitionDecision:
+ """Decide whether an existing grant may stand.
+
+ ``allowed`` means "the grant survives". The floors are below the promotion
+ thresholds so a rate hovering near the line does not flip the grant on
+ every decision, and the trailing slice is checked independently so a
+ decline the window's average is still absorbing is still caught.
+
+ Unlike promotion, an unmeasured rate does **not** demote. A week in which
+ no malicious alert arrived is not evidence the agent got worse, and
+ revoking a grant over an empty denominator would make quiet weeks
+ dangerous.
+ """
+ refusals: list[Refusal] = []
+
+ agreement = window.agreement_rate
+ if agreement is not None and agreement < thresholds.demotion_agreement:
+ refusals.append(Refusal.AGREEMENT_BELOW_THRESHOLD)
+
+ recall = window.malicious_recall
+ if recall is not None and recall < thresholds.demotion_malicious_recall:
+ refusals.append(Refusal.MALICIOUS_RECALL_BELOW_THRESHOLD)
+
+ abstention = window.abstention_rate
+ if abstention is not None and abstention > thresholds.max_abstention_rate:
+ refusals.append(Refusal.EXCESSIVE_ABSTENTION)
+
+ if _recent_has_drifted(recent, thresholds):
+ refusals.append(Refusal.RECENT_DRIFT)
+
+ return TransitionDecision(allowed=not refusals, refusals=tuple(refusals))
+
+
+def _recent_has_drifted(recent: AgreementWindow, thresholds: PromotionThresholds) -> bool:
+ """Whether the trailing slice has fallen below the demotion floors.
+
+ Returns ``False`` on a slice too small to judge. A quiet tenant should not
+ lose a grant because the three decisions since Friday included one
+ disagreement, and ``drift_min_answered`` is where that line is drawn.
+ ``False`` here means "the recent slice cannot say", not "the recent slice
+ is fine"; the window checks apply either way.
+ """
+ if recent.answered < thresholds.drift_min_answered:
+ return False
+ agreement = recent.agreement_rate
+ if agreement is not None and agreement < thresholds.demotion_agreement:
+ return True
+ recall = recent.malicious_recall
+ # Only judge recall on a slice that contained malicious cases at all.
+ # `None` means none arrived, which is not evidence of a decline.
+ return recall is not None and recall < thresholds.demotion_malicious_recall
+
+
# ---------------------------------------------------------------------------
# The aggregate, written once
# ---------------------------------------------------------------------------
@@ -289,6 +577,15 @@ def window_from_counts(counts: dict[str, Any]) -> AgreementWindow:
# The placeholders are numbered (`$1`) for asyncpg. SQLAlchemy callers pass the
# statement through `text()` after `to_named_params()` renames them, because
# the two drivers disagree about placeholder syntax and only about that.
+#
+# The two array parameters carry no `::text[]` cast. They used to, and it was
+# wrong in a way that only shows up on the SQLAlchemy half: `to_named_params`
+# turns `$2::text[]` into `:graded::text[]`, and SQLAlchemy's `text()` parser
+# reads the second colon pair as the start of another bind parameter, so a
+# stray colon reaches Postgres and the statement fails to parse. Both drivers
+# infer the array type from the column being compared, so the cast bought
+# nothing on either side. The SQLAlchemy caller declares the type with
+# `bindparam(..., type_=ARRAY(Text))` instead.
#: Scope filters are applied by the caller as an additional predicate, appended
#: where this marker sits. Written as a marker rather than as string
@@ -298,18 +595,18 @@ _SCOPE_MARKER = "/*scope*/"
AGREEMENT_COUNTS_SQL = f"""
SELECT
COUNT(*)::int AS resolved,
- COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2::text[]))::int AS labelled,
+ COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2))::int AS labelled,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND COALESCE(d.verdict, '') = ANY($3::text[])
+ WHERE d.analyst_disposition = ANY($2)
+ AND COALESCE(d.verdict, '') = ANY($3)
)::int AS abstained,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
)::int AS answered,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
AND d.verdict = d.analyst_disposition
)::int AS agreed,
COUNT(*) FILTER (WHERE d.analyst_disposition = $4)::int AS malicious_support,
@@ -341,18 +638,18 @@ WITH recent AS (
)
SELECT
COUNT(*)::int AS resolved,
- COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2::text[]))::int AS labelled,
+ COUNT(*) FILTER (WHERE d.analyst_disposition = ANY($2))::int AS labelled,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND COALESCE(d.verdict, '') = ANY($3::text[])
+ WHERE d.analyst_disposition = ANY($2)
+ AND COALESCE(d.verdict, '') = ANY($3)
)::int AS abstained,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
)::int AS answered,
COUNT(*) FILTER (
- WHERE d.analyst_disposition = ANY($2::text[])
- AND NOT (COALESCE(d.verdict, '') = ANY($3::text[]))
+ WHERE d.analyst_disposition = ANY($2)
+ AND NOT (COALESCE(d.verdict, '') = ANY($3))
AND d.verdict = d.analyst_disposition
)::int AS agreed,
COUNT(*) FILTER (WHERE d.analyst_disposition = $4)::int AS malicious_support,
@@ -384,3 +681,31 @@ def to_named_params(statement: str, names: list[str]) -> str:
for index in range(len(names), 0, -1):
statement = statement.replace(f"${index}", f":{names[index - 1]}")
return statement
+
+
+def _digest_source() -> dict[str, Any]:
+ """The constants a reader would need to reproduce a past decision.
+
+ Deliberately not a hash of the whole file: a docstring edit must not make
+ every historical snapshot look like it was judged by different rules,
+ because then the digest stops being read.
+ """
+ return {
+ "malicious": MALICIOUS,
+ "graded_dispositions": list(GRADED_DISPOSITIONS),
+ "unlabeled": UNLABELED,
+ "abstention_verdicts": sorted(ABSTENTION_VERDICTS),
+ "refusals": [refusal.value for refusal in Refusal],
+ "grant_states": [state.value for state in GrantState],
+ "grant_sources": [source.value for source in GrantSource],
+ "scope_kinds": list(SCOPE_KINDS),
+ "capabilities": list(CAPABILITIES),
+ "default_thresholds": DEFAULT_THRESHOLDS.as_dict(),
+ "agreement_sql": AGREEMENT_COUNTS_SQL,
+ "recent_sql": RECENT_COUNTS_SQL,
+ }
+
+
+#: Hash of everything above that can change what the gate decides. Travels in
+#: every evidence snapshot.
+RULES_DIGEST = hashlib.sha256(json.dumps(_digest_source(), sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
diff --git a/services/api/app/api/v1/endpoints/autonomy_policy.py b/services/api/app/api/v1/endpoints/autonomy_policy.py
index 382992695..a9a41bd01 100644
--- a/services/api/app/api/v1/endpoints/autonomy_policy.py
+++ b/services/api/app/api/v1/endpoints/autonomy_policy.py
@@ -22,13 +22,20 @@ from __future__ import annotations
from datetime import UTC, datetime
import structlog
-from fastapi import APIRouter, HTTPException, Query, status
+from fastapi import APIRouter, HTTPException, Query, Request, status
from pydantic import BaseModel, Field, model_validator
from sqlalchemy import text
from app._vendor.autonomy_evidence_rules import PromotionThresholds
from app.api.v1.deps import AuthUser, DBSession
from app.db.rls import TenantDBSession
+from app.services.autonomy_grants import (
+ GrantScopeError,
+ list_grants,
+ reconcile_grants,
+ request_promotion,
+ revoke_grant,
+)
from app.services.shadow_agreement import (
SCOPE_COLUMNS,
agreement_for,
@@ -744,3 +751,170 @@ async def get_agreement(
by_source=breakdowns["source"],
by_model=breakdowns["model"],
)
+
+
+# ---------------------------------------------------------------------------
+# Evidence-gated autonomy (gap-closure Phase 2.3)
+#
+# The thresholds at the top of this module are a setting. These routes are
+# not: a tenant asks for a capability and the answer comes from their measured
+# track record. The gate refuses more often than it grants, which is the
+# point, so every refusal names what would change the answer.
+# ---------------------------------------------------------------------------
+
+
+class GrantModel(BaseModel):
+ id: str
+ scope_kind: str
+ scope_key: str
+ capability: str
+ state: str
+ source: str
+ #: Surfaced as its own field so no client has to compare a string to know
+ #: it is looking at autonomy somebody overruled into existence.
+ is_override: bool
+ evidence: dict | None = None
+ granted_at: str | None = None
+ demoted_at: str | None = None
+ demoted_reason: str | None = None
+ override_reason: str | None = None
+
+
+class GrantListResponse(BaseModel):
+ tenant_id: str
+ grants: list[GrantModel]
+ #: Grants demoted by this request's reconciliation pass. Returned rather
+ #: than left to be noticed, because an operator who just lost a capability
+ #: should find out on the page that took it, not from a dashboard later.
+ demoted_now: list[dict]
+
+
+class PromotionRequest(BaseModel):
+ scope_kind: str = Field(..., description="alert_class or action_verb")
+ scope_key: str = Field(..., min_length=1, max_length=200)
+ capability: str = Field(..., description="auto_close or auto_execute")
+ #: Ask for the capability even though the evidence refuses. The gate still
+ #: runs and still records what it refused; what changes is that the grant
+ #: is written and labelled an override.
+ override: bool = False
+ override_reason: str | None = Field(None, max_length=500)
+
+
+class PromotionResponse(BaseModel):
+ granted: bool
+ state: str
+ source: str
+ is_override: bool
+ #: Empty on an earned grant. On a refusal these are what to fix; on an
+ #: override they are what was waived, and they travel into the audit log
+ #: alongside the grant.
+ refusals: list[str]
+ evidence: dict
+ changed: bool
+
+
[email protected]("/grants", response_model=GrantListResponse)
+async def list_autonomy_grants(
+ user: AuthUser,
+ db: TenantDBSession,
+ request: Request,
+) -> GrantListResponse:
+ """Every capability this tenant holds or has held, re-checked on the way out.
+
+ Reconciliation runs first. A grant whose evidence has slipped below the
+ demotion floors is demoted here rather than being listed as current and
+ quietly failing at dispatch, which would leave an operator reading a page
+ that disagrees with the product.
+ """
+ await user.require_permission_db("settings:read", db)
+
+ await reconcile_local_closures(db, user.tenant_id)
+ demoted = await reconcile_grants(db, user.tenant_id, request=request)
+ grants = await list_grants(db, user.tenant_id)
+
+ return GrantListResponse(
+ tenant_id=str(user.tenant_id),
+ grants=[GrantModel(**row.as_dict()) for row in grants],
+ demoted_now=[transition.as_dict() for transition in demoted],
+ )
+
+
[email protected]("/grants", response_model=PromotionResponse)
+async def request_autonomy_grant(
+ payload: PromotionRequest,
+ user: AuthUser,
+ db: TenantDBSession,
+ request: Request,
+) -> PromotionResponse:
+ """Ask for a capability. The evidence decides; an operator may overrule.
+
+ A refusal is a 200 carrying `granted: false` and the reasons, not an
+ error. Being told no by a safety control is the control working, and
+ rendering it as a failure invites a client to retry it.
+
+ The tenant comes from the credential. `scope_key` narrows within that
+ tenant and cannot reach past it.
+ """
+ await user.require_permission_db("settings:write", db)
+
+ if payload.override and not (payload.override_reason or "").strip():
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="an override requires a reason: an override nobody can review is not reviewable later either",
+ )
+
+ # Closures first. An operator who has just finished working a queue should
+ # be judged on those decisions, not on the state before them.
+ await reconcile_local_closures(db, user.tenant_id)
+
+ try:
+ transition = await request_promotion(
+ db,
+ tenant_id=user.tenant_id,
+ actor_id=user.user_id,
+ actor_email=user.email,
+ scope_kind=payload.scope_kind,
+ scope_key=payload.scope_key,
+ capability=payload.capability,
+ override=payload.override,
+ override_reason=payload.override_reason,
+ request=request,
+ )
+ except GrantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+
+ return PromotionResponse(**transition.as_dict())
+
+
[email protected]("/grants", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
+async def revoke_autonomy_grant(
+ user: AuthUser,
+ db: TenantDBSession,
+ request: Request,
+ scope_kind: str = Query(...),
+ scope_key: str = Query(..., max_length=200),
+ capability: str = Query(...),
+) -> None:
+ """Hand a capability back.
+
+ Audited as a revocation rather than as a demotion. A human deciding to
+ stop and the evidence deciding for them are different events, and one word
+ for both would make "was this taken away because the numbers slipped"
+ unanswerable from the log.
+ """
+ await user.require_permission_db("settings:write", db)
+ try:
+ revoked = await revoke_grant(
+ db,
+ tenant_id=user.tenant_id,
+ actor_id=user.user_id,
+ actor_email=user.email,
+ scope_kind=scope_kind,
+ scope_key=scope_key,
+ capability=capability,
+ request=request,
+ )
+ except GrantScopeError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+ if not revoked:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no standing grant for that scope")
diff --git a/services/api/app/services/autonomy_grants.py b/services/api/app/services/autonomy_grants.py
new file mode 100644
index 000000000..2577de048
--- /dev/null
+++ b/services/api/app/services/autonomy_grants.py
@@ -0,0 +1,666 @@
+"""Autonomy granted on a measured track record, and taken back when it slips.
+
+Gap-closure Phase 2.3.
+
+The thesis of this phase, in one sentence: autonomy is promoted by evidence,
+not by a settings toggle. This module is where that becomes true. Nothing here
+decides *what* the thresholds are or *how* agreement is computed, both of which
+live in ``app/_vendor/autonomy_evidence_rules.py``, a byte-identical copy of
+the module ``services/actions`` enforces from. What lives here is the part that
+needs a database and an audit log: reading the evidence, recording the
+transition, and writing it where it cannot later be rewritten.
+
+Three properties are worth stating where somebody changing this file will see
+them.
+
+**A transition always carries its evidence.** Not a reference to it, not a
+flag that lets it be recomputed later: the numbers themselves, frozen. Six
+months after a disputed auto-closure, "why was this tenant allowed to do that"
+has to be answerable against the numbers as they stood on the day. By then the
+window has moved, decisions have aged out, the thresholds may have been
+retuned and the model has probably changed, so a recomputed justification
+would describe a different world while looking authoritative doing it.
+
+**An override is a different word, never a different number.** An operator can
+overrule a refusal, and that has to stay possible, because a gate with no
+override is a gate that gets worked around by people who then stop telling you.
+What must not happen is an override becoming indistinguishable from earned
+autonomy once it is a week old. So the source is derived from the gate's own
+verdict rather than from anything the caller sends, it is a constrained column
+rather than a flag inside the JSON, it is a different audit action string, and
+the refusals that were overruled travel in the snapshot beside it.
+
+**Demotion is not the mirror image of promotion.** Promotion refuses an
+unmeasured rate, because "not measured" must never be read as "met the
+threshold". Demotion ignores one, because a week in which no malicious alert
+arrived is not evidence the agent got worse, and revoking a grant over an
+empty denominator would make quiet weeks dangerous.
+
+Where the audit write goes
+==========================
+
+``emit_audit`` queues the row on the caller's session and computes the hash
+chain; the caller owns the transaction. Every transition here commits the
+grant and its audit row together, so a grant cannot exist without the entry
+that explains it.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+import structlog
+from fastapi import Request
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app._vendor.autonomy_evidence_rules import (
+ CAPABILITIES,
+ SCOPE_KINDS,
+ EvidenceSnapshot,
+ GrantSource,
+ GrantState,
+ PromotionThresholds,
+ Refusal,
+ TransitionDecision,
+ evaluate_demotion,
+ evaluate_promotion,
+)
+from app.services.audit import emit_audit
+from app.services.shadow_agreement import agreement_for
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "AUDIT_DEMOTED",
+ "AUDIT_GRANTED",
+ "AUDIT_OVERRIDDEN",
+ "AUDIT_REVOKED",
+ "GrantRow",
+ "GrantTransition",
+ "list_grants",
+ "reconcile_grants",
+ "request_promotion",
+ "revoke_grant",
+]
+
+#: Four audit actions, not one with a field. A reader filtering the audit log
+#: for "who gave this tenant autonomy they had not earned" must not have to
+#: parse JSON to find out, and a single `autonomy:changed` action would make
+#: an override and an earned grant the same line until somebody did.
+AUDIT_GRANTED = "autonomy:granted"
+AUDIT_OVERRIDDEN = "autonomy:overridden"
+AUDIT_DEMOTED = "autonomy:demoted"
+AUDIT_REVOKED = "autonomy:revoked"
+
+
+class GrantScopeError(ValueError):
+ """A scope or capability outside the fixed vocabulary."""
+
+
+@dataclass(frozen=True)
+class GrantRow:
+ """One tenant's standing on one capability, as the console renders it."""
+
+ id: str
+ scope_kind: str
+ scope_key: str
+ capability: str
+ state: str
+ source: str
+ evidence: dict[str, Any] | None
+ granted_at: str | None
+ demoted_at: str | None
+ demoted_reason: str | None
+ override_reason: str | None
+
+ @property
+ def is_override(self) -> bool:
+ """Whether this autonomy was overruled into existence rather than earned."""
+ return self.source == GrantSource.OPERATOR_OVERRIDE.value
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "scope_kind": self.scope_kind,
+ "scope_key": self.scope_key,
+ "capability": self.capability,
+ "state": self.state,
+ "source": self.source,
+ # Surfaced as its own field so no client has to compare a string
+ # to know it is looking at an override.
+ "is_override": self.is_override,
+ "evidence": self.evidence,
+ "granted_at": self.granted_at,
+ "demoted_at": self.demoted_at,
+ "demoted_reason": self.demoted_reason,
+ "override_reason": self.override_reason,
+ }
+
+
+@dataclass(frozen=True)
+class GrantTransition:
+ """What happened when a promotion was asked for, or a grant re-checked."""
+
+ granted: bool
+ state: str
+ source: str
+ refusals: tuple[Refusal, ...]
+ evidence: dict[str, Any]
+ changed: bool
+
+ @property
+ def refusal_values(self) -> list[str]:
+ return [refusal.value for refusal in self.refusals]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "granted": self.granted,
+ "state": self.state,
+ "source": self.source,
+ "is_override": self.source == GrantSource.OPERATOR_OVERRIDE.value,
+ "refusals": self.refusal_values,
+ "evidence": self.evidence,
+ "changed": self.changed,
+ }
+
+
+def _validate_scope(scope_kind: str, scope_key: str, capability: str) -> None:
+ """Refuse anything outside the vocabulary both services share.
+
+ A grant naming a capability no code path consults is indistinguishable
+ from autonomy that works, right up until somebody relies on it.
+ """
+ if scope_kind not in SCOPE_KINDS:
+ raise GrantScopeError(f"scope_kind must be one of {list(SCOPE_KINDS)}")
+ if capability not in CAPABILITIES:
+ raise GrantScopeError(f"capability must be one of {list(CAPABILITIES)}")
+ if not scope_key or len(scope_key) > 200:
+ raise GrantScopeError("scope_key must be between 1 and 200 characters")
+
+
+async def _shadow_enabled(db: AsyncSession, tenant_id: uuid.UUID | str, scope_kind: str, scope_key: str) -> bool:
+ """Whether this scope was ever being measured.
+
+ Only meaningful for an alert class. A response verb's track record is the
+ triage verdicts behind the alerts it would act on, which is the tenant's
+ shadow mode as a whole, so an action-verb scope asks whether anything at
+ all is being measured.
+ """
+ if scope_kind == "alert_class":
+ classes = [scope_key, "*"]
+ else:
+ classes = None
+
+ if classes is None:
+ row = (
+ (
+ await db.execute(
+ text("SELECT bool_or(enabled) AS enabled FROM aisoc_shadow_mode WHERE tenant_id = :tenant_id"),
+ {"tenant_id": str(tenant_id)},
+ )
+ )
+ .mappings()
+ .first()
+ )
+ else:
+ row = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT bool_or(enabled) AS enabled
+ FROM aisoc_shadow_mode
+ WHERE tenant_id = :tenant_id AND alert_class = ANY(:classes)
+ """
+ ),
+ {"tenant_id": str(tenant_id), "classes": classes},
+ )
+ )
+ .mappings()
+ .first()
+ )
+ return bool(row and row["enabled"])
+
+
+async def _snapshot(
+ db: AsyncSession,
+ tenant_id: uuid.UUID | str,
+ *,
+ scope_kind: str,
+ scope_key: str,
+ capability: str,
+ thresholds: PromotionThresholds,
+ refusals: tuple[Refusal, ...],
+ now: datetime | None = None,
+) -> tuple[EvidenceSnapshot, TransitionDecision, bool]:
+ """Read the evidence for one scope and judge it.
+
+ Returns the snapshot, the promotion verdict and whether shadow mode was
+ on, because the caller needs all three and reading the evidence twice
+ would risk judging one window and recording another.
+ """
+ # An action-verb grant is judged on the tenant's whole track record: the
+ # verdicts behind the alerts that verb would act on are not filed under
+ # the verb's name, and inventing a per-verb slice of triage agreement
+ # would be a number with nothing behind it.
+ evidence_scope = "alert_class" if scope_kind == "alert_class" else "tenant"
+ evidence = await agreement_for(
+ db,
+ tenant_id,
+ scope_kind=evidence_scope,
+ scope_key=scope_key if evidence_scope == "alert_class" else "*",
+ thresholds=thresholds,
+ now=now,
+ with_provenance=True,
+ )
+ shadow_on = await _shadow_enabled(db, tenant_id, scope_kind, scope_key)
+ verdict = evaluate_promotion(
+ window=evidence.window,
+ recent=evidence.recent,
+ thresholds=thresholds,
+ shadow_enabled=shadow_on,
+ )
+ snapshot = EvidenceSnapshot(
+ scope_kind=scope_kind,
+ scope_key=scope_key,
+ capability=capability,
+ window=evidence.window,
+ recent=evidence.recent,
+ thresholds=thresholds,
+ window_start=evidence.window_start,
+ window_end=evidence.window_end,
+ refusals=refusals or verdict.refusals,
+ first_decision_id=evidence.provenance.first_decision_id,
+ last_decision_id=evidence.provenance.last_decision_id,
+ models=evidence.provenance.models,
+ resolution_sources=evidence.provenance.resolution_sources,
+ )
+ return snapshot, verdict, shadow_on
+
+
+async def request_promotion(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID | str,
+ actor_id: uuid.UUID | None,
+ actor_email: str | None,
+ scope_kind: str,
+ scope_key: str,
+ capability: str,
+ override: bool = False,
+ override_reason: str | None = None,
+ thresholds: PromotionThresholds | None = None,
+ request: Request | None = None,
+ now: datetime | None = None,
+) -> GrantTransition:
+ """Grant the capability if the evidence earns it, or if a human overrules.
+
+ ``override`` never changes what the gate decides. It changes what happens
+ to the refusals: without it they are returned and nothing is written, with
+ it they are written into the snapshot beside a grant whose ``source`` says
+ it was overruled. The verdict is computed first and identically either
+ way, which is why the source cannot be faked by the caller.
+ """
+ _validate_scope(scope_kind, scope_key, capability)
+ limits = thresholds or PromotionThresholds()
+
+ snapshot, verdict, _ = await _snapshot(
+ db,
+ tenant_id,
+ scope_kind=scope_kind,
+ scope_key=scope_key,
+ capability=capability,
+ thresholds=limits,
+ refusals=(),
+ now=now,
+ )
+
+ if not verdict.allowed and not override:
+ # Refused. Nothing is written: a refusal is not a state change, and a
+ # row recording every time somebody asked would bury the transitions
+ # that matter.
+ logger.info(
+ "autonomy_grants.refused",
+ tenant_id=str(tenant_id),
+ scope_kind=scope_kind,
+ scope_key=scope_key,
+ capability=capability,
+ refusals=verdict.refusal_values,
+ )
+ return GrantTransition(
+ granted=False,
+ state=GrantState.SHADOW.value,
+ source=GrantSource.EARNED.value,
+ refusals=verdict.refusals,
+ evidence=snapshot.as_dict(),
+ changed=False,
+ )
+
+ source = GrantSource.EARNED if verdict.allowed else GrantSource.OPERATOR_OVERRIDE
+ payload = snapshot.as_dict()
+
+ await db.execute(
+ text(
+ """
+ INSERT INTO aisoc_autonomy_grants
+ (tenant_id, scope_kind, scope_key, capability, state, source,
+ evidence, granted_at, granted_by, override_reason, updated_at)
+ VALUES
+ (:tenant_id, :scope_kind, :scope_key, :capability, 'granted', :source,
+ CAST(:evidence AS JSONB), now(), :granted_by, :override_reason, now())
+ ON CONFLICT (tenant_id, scope_kind, scope_key, capability) DO UPDATE SET
+ state = 'granted',
+ source = EXCLUDED.source,
+ evidence = EXCLUDED.evidence,
+ granted_at = now(),
+ granted_by = EXCLUDED.granted_by,
+ override_reason = EXCLUDED.override_reason,
+ -- Cleared, because they describe the previous demotion and a
+ -- row showing both a current grant and a demotion reason
+ -- invites the reader to think the grant is still revoked.
+ demoted_at = NULL,
+ demoted_reason = NULL,
+ updated_at = now()
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "scope_kind": scope_kind,
+ "scope_key": scope_key,
+ "capability": capability,
+ "source": source.value,
+ "evidence": _json(payload),
+ "granted_by": str(actor_id) if actor_id else None,
+ "override_reason": override_reason if source is GrantSource.OPERATOR_OVERRIDE else None,
+ },
+ )
+
+ await emit_audit(
+ db=db,
+ tenant_id=_as_uuid(tenant_id),
+ actor_id=actor_id,
+ actor_email=actor_email,
+ action=AUDIT_GRANTED if source is GrantSource.EARNED else AUDIT_OVERRIDDEN,
+ resource="autonomy_grant",
+ resource_id=f"{scope_kind}:{scope_key}:{capability}",
+ changes={
+ "state": GrantState.GRANTED.value,
+ "source": source.value,
+ "override_reason": override_reason,
+ # On an override these are the refusals that were overruled. On an
+ # earned grant the list is empty, which is itself the record that
+ # nothing had to be waived.
+ "waived_refusals": verdict.refusal_values if source is GrantSource.OPERATOR_OVERRIDE else [],
+ "evidence": payload,
+ },
+ request=request,
+ )
+ await db.commit()
+
+ logger.info(
+ "autonomy_grants.granted",
+ tenant_id=str(tenant_id),
+ scope_kind=scope_kind,
+ scope_key=scope_key,
+ capability=capability,
+ source=source.value,
+ waived=verdict.refusal_values if source is GrantSource.OPERATOR_OVERRIDE else [],
+ )
+ return GrantTransition(
+ granted=True,
+ state=GrantState.GRANTED.value,
+ source=source.value,
+ refusals=verdict.refusals,
+ evidence=payload,
+ changed=True,
+ )
+
+
+async def reconcile_grants(
+ db: AsyncSession,
+ tenant_id: uuid.UUID | str,
+ *,
+ thresholds: PromotionThresholds | None = None,
+ request: Request | None = None,
+ now: datetime | None = None,
+) -> list[GrantTransition]:
+ """Re-check every standing grant and demote the ones that no longer hold.
+
+ Demotion is automatic in the sense that nobody has to ask for it: this
+ runs whenever the grants are read and whenever the dispatch path refreshes
+ its view, so a grant cannot outlive its evidence by more than the interval
+ between those.
+
+ An override is re-checked too, and demoted on the same floors. An operator
+ overruling a refusal is saying "I accept this today", not "stop measuring";
+ exempting overrides would make the override permanent, which is the one
+ thing that would turn it into a settings toggle after all.
+ """
+ limits = thresholds or PromotionThresholds()
+ rows = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT scope_kind, scope_key, capability, source
+ FROM aisoc_autonomy_grants
+ WHERE tenant_id = :tenant_id AND state = 'granted'
+ ORDER BY scope_kind, scope_key, capability
+ """
+ ),
+ {"tenant_id": str(tenant_id)},
+ )
+ )
+ .mappings()
+ .all()
+ )
+
+ transitions: list[GrantTransition] = []
+ for row in rows:
+ evidence_scope = "alert_class" if row["scope_kind"] == "alert_class" else "tenant"
+ evidence = await agreement_for(
+ db,
+ tenant_id,
+ scope_kind=evidence_scope,
+ scope_key=row["scope_key"] if evidence_scope == "alert_class" else "*",
+ thresholds=limits,
+ now=now,
+ with_provenance=True,
+ )
+ verdict = evaluate_demotion(window=evidence.window, recent=evidence.recent, thresholds=limits)
+ if verdict.allowed:
+ continue
+
+ snapshot = EvidenceSnapshot(
+ scope_kind=row["scope_kind"],
+ scope_key=row["scope_key"],
+ capability=row["capability"],
+ window=evidence.window,
+ recent=evidence.recent,
+ thresholds=limits,
+ window_start=evidence.window_start,
+ window_end=evidence.window_end,
+ refusals=verdict.refusals,
+ first_decision_id=evidence.provenance.first_decision_id,
+ last_decision_id=evidence.provenance.last_decision_id,
+ models=evidence.provenance.models,
+ resolution_sources=evidence.provenance.resolution_sources,
+ )
+ payload = snapshot.as_dict()
+ reason = ", ".join(verdict.refusal_values)
+
+ await db.execute(
+ text(
+ """
+ UPDATE aisoc_autonomy_grants
+ SET state = 'demoted',
+ evidence = CAST(:evidence AS JSONB),
+ demoted_at = now(),
+ demoted_reason = :reason,
+ updated_at = now()
+ WHERE tenant_id = :tenant_id
+ AND scope_kind = :scope_kind
+ AND scope_key = :scope_key
+ AND capability = :capability
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "scope_kind": row["scope_kind"],
+ "scope_key": row["scope_key"],
+ "capability": row["capability"],
+ "evidence": _json(payload),
+ "reason": reason,
+ },
+ )
+ await emit_audit(
+ db=db,
+ tenant_id=_as_uuid(tenant_id),
+ # No actor: nobody asked for this. An actor id here would name
+ # whoever happened to load the page as the person who revoked it.
+ actor_id=None,
+ actor_email=None,
+ action=AUDIT_DEMOTED,
+ resource="autonomy_grant",
+ resource_id=f"{row['scope_kind']}:{row['scope_key']}:{row['capability']}",
+ changes={
+ "state": GrantState.DEMOTED.value,
+ "previous_source": row["source"],
+ "refusals": verdict.refusal_values,
+ "evidence": payload,
+ },
+ request=request,
+ )
+ transitions.append(
+ GrantTransition(
+ granted=False,
+ state=GrantState.DEMOTED.value,
+ source=row["source"],
+ refusals=verdict.refusals,
+ evidence=payload,
+ changed=True,
+ )
+ )
+ logger.warning(
+ "autonomy_grants.demoted",
+ tenant_id=str(tenant_id),
+ scope_kind=row["scope_kind"],
+ scope_key=row["scope_key"],
+ capability=row["capability"],
+ refusals=verdict.refusal_values,
+ )
+
+ if transitions:
+ await db.commit()
+ return transitions
+
+
+async def revoke_grant(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID | str,
+ actor_id: uuid.UUID | None,
+ actor_email: str | None,
+ scope_kind: str,
+ scope_key: str,
+ capability: str,
+ request: Request | None = None,
+) -> bool:
+ """Hand a capability back. Returns whether a standing grant was revoked.
+
+ Deliberately not the same audit action as a demotion. A human deciding to
+ stop and the evidence deciding for them are different events, and folding
+ them together would make "was this taken away because the numbers slipped"
+ unanswerable from the log.
+ """
+ _validate_scope(scope_kind, scope_key, capability)
+ result = await db.execute(
+ text(
+ """
+ UPDATE aisoc_autonomy_grants
+ SET state = 'shadow',
+ demoted_at = now(),
+ demoted_reason = 'revoked by operator',
+ updated_at = now()
+ WHERE tenant_id = :tenant_id
+ AND scope_kind = :scope_kind
+ AND scope_key = :scope_key
+ AND capability = :capability
+ AND state = 'granted'
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "scope_kind": scope_kind,
+ "scope_key": scope_key,
+ "capability": capability,
+ },
+ )
+ if not result.rowcount:
+ return False
+
+ await emit_audit(
+ db=db,
+ tenant_id=_as_uuid(tenant_id),
+ actor_id=actor_id,
+ actor_email=actor_email,
+ action=AUDIT_REVOKED,
+ resource="autonomy_grant",
+ resource_id=f"{scope_kind}:{scope_key}:{capability}",
+ changes={"state": GrantState.SHADOW.value},
+ request=request,
+ )
+ await db.commit()
+ return True
+
+
+async def list_grants(db: AsyncSession, tenant_id: uuid.UUID | str) -> list[GrantRow]:
+ """Every grant this tenant holds or has held, current state first."""
+ rows = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT id::text AS id, scope_kind, scope_key, capability, state, source,
+ evidence, granted_at, demoted_at, demoted_reason, override_reason
+ FROM aisoc_autonomy_grants
+ WHERE tenant_id = :tenant_id
+ ORDER BY state, scope_kind, scope_key, capability
+ """
+ ),
+ {"tenant_id": str(tenant_id)},
+ )
+ )
+ .mappings()
+ .all()
+ )
+ return [
+ GrantRow(
+ id=row["id"],
+ scope_kind=row["scope_kind"],
+ scope_key=row["scope_key"],
+ capability=row["capability"],
+ state=row["state"],
+ source=row["source"],
+ evidence=row["evidence"],
+ granted_at=row["granted_at"].isoformat() if row["granted_at"] else None,
+ demoted_at=row["demoted_at"].isoformat() if row["demoted_at"] else None,
+ demoted_reason=row["demoted_reason"],
+ override_reason=row["override_reason"],
+ )
+ for row in rows
+ ]
+
+
+def _json(payload: dict[str, Any]) -> str:
+ import json # noqa: PLC0415 - only needed on the write path
+
+ return json.dumps(payload, sort_keys=True, default=str)
+
+
+def _as_uuid(value: uuid.UUID | str) -> uuid.UUID:
+ return value if isinstance(value, uuid.UUID) else uuid.UUID(str(value))
diff --git a/services/api/app/services/shadow_agreement.py b/services/api/app/services/shadow_agreement.py
index 01af007b6..6c0970922 100644
--- a/services/api/app/services/shadow_agreement.py
+++ b/services/api/app/services/shadow_agreement.py
@@ -48,13 +48,15 @@ same way, because "closed, reason not recorded" is exactly that shrug.
from __future__ import annotations
import uuid
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
-from sqlalchemy import text
+from sqlalchemy import bindparam, text
+from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.types import Text
from app._vendor.autonomy_evidence_rules import (
ABSTENTION_VERDICTS,
@@ -75,11 +77,33 @@ logger = structlog.get_logger(__name__)
__all__ = [
"AgreementEvidence",
"ScopeBreakdown",
+ "WindowProvenance",
"agreement_for",
"breakdown_for",
"reconcile_local_closures",
]
+
+#: Parameters that carry a list and therefore need a declared type. Without it
+#: SQLAlchemy binds a Python list as a scalar of unknown type and Postgres
+#: refuses the comparison. Declaring it here rather than casting inside the
+#: shared SQL keeps that statement identical for the asyncpg caller, which
+#: infers the type from the column and needs no help.
+_ARRAY_PARAMS = ("graded", "abstentions")
+
+
+def _statement(sql: str):
+ """``text()`` with whichever array parameters this statement actually binds.
+
+ Only the ones present, because ``bindparams`` raises on a name the
+ statement does not contain: the reconcile sweep binds ``graded`` and not
+ ``abstentions``, and declaring both unconditionally took it down.
+ """
+ declared = [bindparam(name, type_=ARRAY(Text)) for name in _ARRAY_PARAMS if f":{name}" in sql]
+ statement = text(sql)
+ return statement.bindparams(*declared) if declared else statement
+
+
#: The placeholder names the two aggregates bind, in ``$1 … $7`` order.
_PARAM_NAMES = [
"tenant_id",
@@ -102,6 +126,22 @@ SCOPE_COLUMNS: dict[str, str] = {
}
+@dataclass(frozen=True)
+class WindowProvenance:
+ """Where the window's rows came from, for the audit snapshot.
+
+ Counts summarise; these let somebody find the rows again. A promotion
+ disputed six months later resolves into a list of alerts an operator can
+ open, and without the decision ids at both ends of the window there is no
+ way back to them once the window has moved on.
+ """
+
+ first_decision_id: str | None = None
+ last_decision_id: str | None = None
+ models: tuple[str, ...] = ()
+ resolution_sources: tuple[str, ...] = ()
+
+
@dataclass(frozen=True)
class AgreementEvidence:
"""One scope's track record: the window, and the trailing slice of it."""
@@ -112,6 +152,7 @@ class AgreementEvidence:
recent: AgreementWindow
window_start: datetime
window_end: datetime
+ provenance: WindowProvenance = field(default_factory=WindowProvenance)
def as_dict(self) -> dict[str, Any]:
return {
@@ -167,7 +208,7 @@ async def reconcile_local_closures(
was known at the time is the thing an audit needs; a later correction is a
new fact, and it arrives as new decisions rather than by editing old ones.
"""
- statement = text(
+ statement = _statement(
"""
UPDATE aisoc_shadow_decisions d
SET analyst_disposition = CASE
@@ -221,6 +262,40 @@ def _scope_predicate(scope_kind: str, scope_key: str) -> tuple[str, dict[str, An
return f"AND d.{column} = :scope_key", {"scope_key": scope_key}
+async def _provenance(
+ db: AsyncSession,
+ predicate: str,
+ params: dict[str, Any],
+) -> WindowProvenance:
+ """The ends of the window, and what produced the verdicts inside it."""
+ row = (
+ await db.execute(
+ text(
+ f"""
+ SELECT
+ (ARRAY_AGG(d.id ORDER BY d.resolved_at ASC))[1]::text AS first_decision_id,
+ (ARRAY_AGG(d.id ORDER BY d.resolved_at DESC))[1]::text AS last_decision_id,
+ ARRAY_REMOVE(ARRAY_AGG(DISTINCT d.model), NULL) AS models,
+ ARRAY_REMOVE(ARRAY_AGG(DISTINCT d.resolution_source), NULL) AS resolution_sources
+ FROM aisoc_shadow_decisions d
+ WHERE d.tenant_id = :tenant_id
+ AND d.resolved_at IS NOT NULL
+ AND d.resolved_at >= :window_start
+ AND d.resolved_at <= :window_end
+ {predicate}
+ """
+ ),
+ params,
+ )
+ ).mappings().first() or {}
+ return WindowProvenance(
+ first_decision_id=row.get("first_decision_id"),
+ last_decision_id=row.get("last_decision_id"),
+ models=tuple(sorted(row.get("models") or ())),
+ resolution_sources=tuple(sorted(row.get("resolution_sources") or ())),
+ )
+
+
async def agreement_for(
db: AsyncSession,
tenant_id: uuid.UUID | str,
@@ -229,6 +304,7 @@ async def agreement_for(
scope_key: str = "*",
thresholds: PromotionThresholds | None = None,
now: datetime | None = None,
+ with_provenance: bool = False,
) -> AgreementEvidence:
"""The tenant's rolling agreement for one scope, plus its trailing slice.
@@ -236,6 +312,10 @@ async def agreement_for(
nothing and gets the wall clock. The window bounds are returned as
absolute timestamps rather than as "the last 30 days", because the second
form stops meaning anything the moment somebody reads it on a later day.
+
+ ``with_provenance`` adds the decision ids at each end of the window, the
+ models that produced the verdicts and where the closures came from. It is
+ off by default because only the audit snapshot needs them.
"""
limits = thresholds or PromotionThresholds()
window_end = now or datetime.now(UTC)
@@ -245,10 +325,12 @@ async def agreement_for(
params = {**_bind(tenant_id, window_start, window_end, limits.drift_sample), **extra}
window_row = (
- (await db.execute(text(to_named_params(scoped_sql(AGREEMENT_COUNTS_SQL, predicate), _PARAM_NAMES)), params)).mappings().first()
+ (await db.execute(_statement(to_named_params(scoped_sql(AGREEMENT_COUNTS_SQL, predicate), _PARAM_NAMES)), params))
+ .mappings()
+ .first()
)
recent_row = (
- (await db.execute(text(to_named_params(scoped_sql(RECENT_COUNTS_SQL, predicate), _PARAM_NAMES)), params)).mappings().first()
+ (await db.execute(_statement(to_named_params(scoped_sql(RECENT_COUNTS_SQL, predicate), _PARAM_NAMES)), params)).mappings().first()
)
return AgreementEvidence(
@@ -258,6 +340,11 @@ async def agreement_for(
recent=window_from_counts(dict(recent_row or {})),
window_start=window_start,
window_end=window_end,
+ # Only fetched when a snapshot is about to be written. The console
+ # reads this endpoint on every visit and does not need the decision
+ # ids, and an extra aggregate on a hot read for a field nobody renders
+ # is the kind of cost that never gets attributed back to its cause.
+ provenance=(await _provenance(db, predicate, params) if with_provenance else WindowProvenance()),
)
@@ -289,7 +376,7 @@ async def breakdown_for(
# scoped. Kept beside the caller instead of in the rules module because
# only the console needs it: the dispatch gate asks about one scope at a
# time and must never pull a whole table across to answer that.
- statement = text(
+ statement = _statement(
f"""
SELECT
COALESCE(NULLIF(d.{column}, ''), 'unattributed') AS key,
diff --git a/services/api/migrations/067_autonomy_grants.sql b/services/api/migrations/067_autonomy_grants.sql
new file mode 100644
index 000000000..a0c81380a
--- /dev/null
+++ b/services/api/migrations/067_autonomy_grants.sql
@@ -0,0 +1,130 @@
+-- 067: what a tenant earned, what it was measured on, and who overruled it.
+--
+-- Gap-closure Phase 2.3.
+--
+-- 066 records what the agent said and what the analysts said. This is the
+-- thing decided from that: whether a tenant may let the agent auto-close an
+-- alert class, or raise one response verb's autonomy tier, without a human in
+-- the loop each time.
+--
+-- Why the evidence is stored on the row and not looked up
+-- -------------------------------------------------------
+-- The obvious design keeps a `granted` flag and recomputes the justification
+-- on demand. It cannot answer the only question anybody asks of this table.
+-- Six months after a disputed auto-closure, "why was this tenant allowed to
+-- do that" has to be answered against the numbers as they stood on the day,
+-- and by then the window has moved, decisions have aged out, the thresholds
+-- may have been retuned and the model has probably changed. A recomputed
+-- justification would describe a different world and would look authoritative
+-- doing it.
+--
+-- So `evidence` is a snapshot: the counts, the rates derived from them, the
+-- thresholds by value, the window as absolute timestamps, the models that
+-- produced the verdicts, the first and last decision id so the underlying
+-- rows can still be found, and a digest of the rule set that judged it. The
+-- shape is `EvidenceSnapshot.as_dict()` in `autonomy_evidence_rules.py`.
+--
+-- Why `source` is a column and not a flag in the JSON
+-- ---------------------------------------------------
+-- An operator can overrule a refusal. That has to stay possible: a gate with
+-- no override is a gate that gets worked around. What must not happen is an
+-- override becoming indistinguishable from earned autonomy once it is a week
+-- old, so it is a first-class column with a CHECK constraint, it is a
+-- different audit action, and the refusals that were overruled travel in the
+-- snapshot beside it. `source` is derived from the gate's own verdict and
+-- never from a request field, so a caller cannot ask for an override to be
+-- recorded as earned.
+--
+-- Why demotions update rather than delete
+-- ---------------------------------------
+-- A grant that was revoked is the most interesting row in this table. One
+-- row per (tenant, scope, capability), carrying its current state and the
+-- evidence for the last transition; the full history is the audit log, which
+-- is hash-chained and cannot be rewritten.
+
+CREATE TABLE IF NOT EXISTS aisoc_autonomy_grants (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ -- `alert_class` grants auto-closure for a class of alerts; `action_verb`
+ -- raises one response verb's autonomy tier. Constrained because both
+ -- halves of the system have to agree what a scope key means before they
+ -- can agree a grant applies to something.
+ scope_kind TEXT NOT NULL CHECK (scope_kind IN ('alert_class', 'action_verb')),
+ scope_key TEXT NOT NULL,
+ capability TEXT NOT NULL CHECK (capability IN ('auto_close', 'auto_execute')),
+
+ -- shadow: measuring, not acting. granted: earned or overridden.
+ -- demoted: held and lost. A revoked grant keeps its row, because it is
+ -- the most interesting one in the table.
+ state TEXT NOT NULL DEFAULT 'shadow'
+ CHECK (state IN ('shadow', 'granted', 'demoted')),
+ -- Never inferred from a request field. `earned` means the evidence met
+ -- every threshold on its own; `operator_override` means a human overruled
+ -- a refusal, and the refusals are in `evidence`.
+ source TEXT NOT NULL DEFAULT 'earned'
+ CHECK (source IN ('earned', 'operator_override')),
+
+ -- `EvidenceSnapshot.as_dict()`. Not null on a granted or demoted row:
+ -- a transition with no evidence is exactly the thing this table exists
+ -- to make impossible.
+ evidence JSONB,
+
+ granted_at TIMESTAMPTZ,
+ granted_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ demoted_at TIMESTAMPTZ,
+ -- The refusal words that caused the demotion, joined. Kept beside the
+ -- snapshot so a reader scanning the table sees why without parsing JSON.
+ demoted_reason TEXT,
+ -- Free text an operator supplies when overruling. Required by the route
+ -- rather than by the column, because an override with no stated reason is
+ -- an override nobody can review, and the route is where a 422 is useful.
+ override_reason TEXT,
+
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ UNIQUE (tenant_id, scope_kind, scope_key, capability)
+);
+
+COMMENT ON TABLE aisoc_autonomy_grants IS
+ 'Autonomy a tenant has earned, or that an operator granted over a refusal. '
+ 'One row per (tenant, scope, capability); the transition history is the '
+ 'hash-chained audit log, which cannot be rewritten.';
+COMMENT ON COLUMN aisoc_autonomy_grants.evidence IS
+ 'EvidenceSnapshot.as_dict(): counts, rates, thresholds by value, the window '
+ 'as absolute timestamps, models, the first and last decision id, and a digest '
+ 'of the rules that judged it. Stored rather than recomputed because a window '
+ 'that has moved on describes a different world.';
+COMMENT ON COLUMN aisoc_autonomy_grants.source IS
+ 'earned | operator_override. Derived from the gate verdict, never from a '
+ 'request field, so an override cannot be recorded as earned.';
+
+CREATE INDEX IF NOT EXISTS idx_autonomy_grants_tenant
+ ON aisoc_autonomy_grants (tenant_id, state);
+-- The dispatch path asks one question: does this tenant hold this capability
+-- for this scope. Partial, because a demoted row never answers it yes.
+CREATE INDEX IF NOT EXISTS idx_autonomy_grants_lookup
+ ON aisoc_autonomy_grants (tenant_id, capability, scope_kind, scope_key)
+ WHERE state = 'granted';
+
+-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets
+-- the cross-tenant workers (retention purge, tenant deletion) and the actions
+-- service's unbound connection read this; dropping it makes those silently
+-- see nothing, which here would mean every tenant losing their autonomy at
+-- dispatch with no error anywhere. FORCE so the owner does not walk past.
+ALTER TABLE aisoc_autonomy_grants ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_autonomy_grants FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_autonomy_grants_tenant ON aisoc_autonomy_grants;
+CREATE POLICY aisoc_autonomy_grants_tenant ON aisoc_autonomy_grants
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+-- 061 set ALTER DEFAULT PRIVILEGES so new tables pick these up, but only for
+-- tables created by the role that ran it. Granting explicitly means a chain
+-- replayed by a different owner still leaves the runtime role able to work.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ GRANT SELECT, INSERT, UPDATE, DELETE ON aisoc_autonomy_grants TO aisoc_app;
+ END IF;
+END
+$$;
diff --git a/tests/isolation/test_autonomy_promotion_live.py b/tests/isolation/test_autonomy_promotion_live.py
new file mode 100644
index 000000000..0b929dba9
--- /dev/null
+++ b/tests/isolation/test_autonomy_promotion_live.py
@@ -0,0 +1,648 @@
+"""The promotion gate, end to end, against a real database.
+
+Gap-closure Phase 2.3. This is the phase's "Done when", run rather than
+reasoned about:
+
+ on recorded data, a test tenant cannot enable auto-close for a class with
+ 20 shadow decisions, can once the thresholds are met, and is demoted when
+ injected disagreements cross the drift threshold.
+
+Why it lives here and not in a service suite
+--------------------------------------------
+
+The unit tests in ``services/actions`` prove the arithmetic and the unit tests
+in ``services/api`` prove the statements are built correctly, and between them
+they still would not catch the failure that matters most: an aggregate that
+counts something slightly different from what the evaluator expects. The SQL
+and the evaluator agree by convention, and a convention is what drifts. Only a
+real Postgres executing the real statement over real rows closes that, so this
+suite seeds decisions, runs the production aggregate over them and asks the
+production gate what it thinks.
+
+It is also the only place the audit trail can be checked properly. The hash
+chain is computed on insert from the previous row for the same tenant, so a
+mocked session cannot tell you whether a promotion, an override and a
+demotion actually chain.
+
+Skipping
+--------
+
+Skips when no Postgres answers, and refuses to skip when
+``AUTONOMY_PROMOTION_LIVE_REQUIRED`` is set, following
+``test_postgres_rls.py``. A suite that can silently skip where it is supposed
+to run is a suite that reports green for a gate nobody executed.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import uuid
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+DSN = os.environ.get("DATABASE_URL", "")
+REQUIRED = os.environ.get("AUTONOMY_PROMOTION_LIVE_REQUIRED", "").strip().lower() in {"1", "true", "yes", "on"}
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.skipif(
+ "postgres" not in DSN and not REQUIRED,
+ reason="no Postgres DATABASE_URL; set AUTONOMY_PROMOTION_LIVE_REQUIRED=1 to make this a failure",
+ ),
+]
+
+#: Fixed so a failure is reproducible. Every decision below is written out
+#: rather than generated from a distribution: "recorded data" means a reader
+#: can count the rows that produced a verdict, and a random corpus that
+#: happened to cross a threshold would be evidence about the seed.
+CLASS = "identity"
+RULE = "det-identity-004"
+SOURCE = "okta"
+MODEL = "ollama_chat/llama3.2:3b"
+
+MALICIOUS = "true_positive"
+FALSE_POSITIVE = "false_positive"
+NEEDS_REVIEW = "needs_review"
+
+
+def _sqlalchemy_url(url: str) -> str:
+ """Whatever spelling the environment holds, as an asyncpg SQLAlchemy URL."""
+ if url.startswith("postgresql+asyncpg://"):
+ return url
+ return re.sub(r"^postgres(ql)?://", "postgresql+asyncpg://", url)
+
+
+#: A module-scoped *async* fixture binds itself to one event loop and
+#: pytest-asyncio gives each test a fresh one, so the setup is an async context
+#: manager entered inside each test instead. Same reason, and the same shape,
+#: as ``test_postgres_rls.py``.
+@asynccontextmanager
+async def probe():
+ """A tenant, an operator, shadow mode on for one class, and a bound session.
+
+ Everything it creates it deletes, in foreign-key order, so a failing test
+ does not poison the next one with rows the aggregate would count.
+ """
+ sqlalchemy_asyncio = pytest.importorskip("sqlalchemy.ext.asyncio")
+ from sqlalchemy import text
+
+ engine = sqlalchemy_asyncio.create_async_engine(_sqlalchemy_url(DSN), pool_pre_ping=True)
+ maker = sqlalchemy_asyncio.async_sessionmaker(engine, expire_on_commit=False)
+ session = maker()
+ try:
+ try:
+ await session.execute(text("SELECT 1 FROM aisoc_autonomy_grants LIMIT 0"))
+ except Exception as exc: # noqa: BLE001
+ await session.rollback()
+ if REQUIRED:
+ pytest.fail(f"migration 067 has not been applied: {exc}")
+ pytest.skip(f"aisoc_autonomy_grants is absent: {exc}")
+
+ tenant_id = uuid.uuid4()
+ slug = f"promo-{tenant_id.hex[:10]}"
+ await session.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :name, :slug)"),
+ {"id": tenant_id, "name": "Promotion gate probe", "slug": slug},
+ )
+ user_id = uuid.uuid4()
+ await session.execute(
+ text(
+ """
+ INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active)
+ VALUES (:id, :tenant_id, :email, :username, 'x', 'tenant_admin', TRUE)
+ """
+ ),
+ {"id": user_id, "tenant_id": tenant_id, "email": f"{slug}@example.com", "username": slug},
+ )
+ await session.execute(
+ text(
+ """
+ INSERT INTO aisoc_shadow_mode (tenant_id, alert_class, enabled, enabled_at)
+ VALUES (:tenant_id, :alert_class, TRUE, now())
+ """
+ ),
+ {"tenant_id": tenant_id, "alert_class": CLASS},
+ )
+ await session.commit()
+ try:
+ yield session, tenant_id, user_id
+ finally:
+ # The evidence and the grants, and nothing that the audit trail
+ # hangs off. `audit_log` refuses a DELETE by trigger;
+ # `audit_log.tenant_id` cascades from `tenants` and
+ # `audit_log.actor_id` is `ON DELETE SET NULL` from `users`, so
+ # removing either one reaches the trigger as a delete or an update
+ # and is refused. Working around that here would mean
+ # demonstrating the hole the trigger closes, so the probe leaves
+ # the tenant and the operator behind. Each run uses a fresh tenant
+ # UUID and every aggregate is tenant-scoped, so the residue cannot
+ # reach another test. `test_the_audit_trail_cannot_be_deleted`
+ # asserts the refusal rather than treating it as an inconvenience.
+ for table in ("aisoc_autonomy_grants", "aisoc_shadow_decisions", "aisoc_shadow_mode"):
+ await session.execute(text(f"DELETE FROM {table} WHERE tenant_id = :t"), {"t": tenant_id})
+ await session.commit()
+ finally:
+ await session.close()
+ await engine.dispose()
+
+
+async def _record(
+ session,
+ tenant_id: uuid.UUID,
+ *,
+ count: int,
+ verdict: str,
+ disposition: str,
+ resolved_at: datetime,
+ spacing_seconds: int = 60,
+) -> None:
+ """Write ``count`` decisions that all said ``verdict`` and were closed ``disposition``.
+
+ ``resolved_at`` advances, because the trailing drift slice is ordered by
+ it. Rows written with one timestamp would make "the most recent 50" an
+ arbitrary 50.
+ """
+ from sqlalchemy import text
+
+ for index in range(count):
+ await session.execute(
+ text(
+ """
+ INSERT INTO aisoc_shadow_decisions
+ (tenant_id, alert_id, alert_class, rule_id, source, model, verdict,
+ confidence, decided_at, analyst_disposition, resolution_source, resolved_at)
+ VALUES
+ (:tenant_id, :alert_id, :alert_class, :rule_id, :source, :model, :verdict,
+ 0.91, :resolved_at, :disposition, 'aisoc', :resolved_at)
+ """
+ ),
+ {
+ "tenant_id": tenant_id,
+ "alert_id": uuid.uuid4(),
+ "alert_class": CLASS,
+ "rule_id": RULE,
+ "source": SOURCE,
+ "model": MODEL,
+ "verdict": verdict,
+ "disposition": disposition,
+ "resolved_at": resolved_at + timedelta(seconds=index * spacing_seconds),
+ },
+ )
+ await session.commit()
+
+
+async def _promote(session, tenant_id, user_id, **kwargs):
+ from app.services.autonomy_grants import request_promotion
+
+ return await request_promotion(
+ session,
+ tenant_id=tenant_id,
+ actor_id=user_id,
+ actor_email="[email protected]",
+ scope_kind="alert_class",
+ scope_key=CLASS,
+ capability="auto_close",
+ **kwargs,
+ )
+
+
+async def _audit_actions(session, tenant_id) -> list[str]:
+ from sqlalchemy import text
+
+ rows = (
+ (
+ await session.execute(
+ text("SELECT action FROM audit_log WHERE tenant_id = :t ORDER BY created_at, id"),
+ {"t": tenant_id},
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return [str(row) for row in rows]
+
+
+class TestTheDoneWhen:
+ async def test_twenty_decisions_cannot_enable_auto_close(self):
+ """The first clause. Twenty perfect decisions are not a track record."""
+ async with probe() as (session, tenant_id, user_id):
+ base = datetime.now(UTC) - timedelta(days=5)
+ await _record(session, tenant_id, count=12, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=8, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(hours=1))
+
+ transition = await _promote(session, tenant_id, user_id)
+
+ assert transition.granted is False
+ assert "insufficient_sample" in transition.refusal_values
+ assert "insufficient_malicious" in transition.refusal_values
+ # Every count that produced the refusal travels with it, so the
+ # operator is told the distance rather than only the verdict.
+ window = transition.evidence["window"]
+ assert window["labelled"] == 20
+ assert window["malicious_support"] == 8
+ assert transition.evidence["thresholds"]["min_decisions"] == 100
+ # A refusal is not a state change, so nothing was written.
+ assert await _audit_actions(session, tenant_id) == []
+
+ async def test_once_the_thresholds_are_met_it_is_granted(self):
+ """The second clause, and the evidence snapshot that justifies it."""
+ async with probe() as (session, tenant_id, user_id):
+ base = datetime.now(UTC) - timedelta(days=10)
+ # 150 decisions: 110 false positives agreed, 36 malicious of which 34
+ # were caught, and 4 abstentions. Agreement 144/146 = 98.6%, recall
+ # 34/36 = 94.4%, abstention 4/150 = 2.7%. Every floor cleared.
+ await _record(session, tenant_id, count=110, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(
+ session,
+ tenant_id,
+ count=34,
+ verdict=MALICIOUS,
+ disposition=MALICIOUS,
+ resolved_at=base + timedelta(days=1),
+ )
+ await _record(
+ session,
+ tenant_id,
+ count=2,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=base + timedelta(days=2),
+ )
+ await _record(
+ session,
+ tenant_id,
+ count=4,
+ verdict=NEEDS_REVIEW,
+ disposition=FALSE_POSITIVE,
+ resolved_at=base + timedelta(days=3),
+ )
+
+ transition = await _promote(session, tenant_id, user_id)
+
+ assert transition.granted is True, transition.refusal_values
+ assert transition.source == "earned"
+ assert transition.refusals == ()
+
+ window = transition.evidence["window"]
+ assert window["labelled"] == 150
+ assert window["answered"] == 146
+ assert window["agreed"] == 144
+ assert window["malicious_support"] == 36
+ assert window["malicious_caught"] == 34
+ assert window["agreement_rate"] == pytest.approx(144 / 146)
+ assert window["malicious_recall"] == pytest.approx(34 / 36)
+
+ # The snapshot has to still explain this in six months.
+ evidence = transition.evidence
+ assert evidence["thresholds"]["min_agreement"] == 0.95
+ assert datetime.fromisoformat(evidence["window_start"]) < datetime.fromisoformat(evidence["window_end"])
+ assert evidence["first_decision_id"] and evidence["last_decision_id"]
+ assert evidence["models"] == [MODEL]
+ assert evidence["resolution_sources"] == ["aisoc"]
+ assert len(evidence["rules_digest"]) == 64
+
+ assert await _audit_actions(session, tenant_id) == ["autonomy:granted"]
+
+ async def test_injected_disagreements_demote_it(self):
+ """The third clause: drift that the window average is still absorbing.
+
+ The tenant is granted on a strong 30-day record, then 30 recent
+ disagreements are injected. The *window* still passes comfortably:
+ that is the whole point, and a gate reading only the window would
+ leave this grant standing.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.autonomy_grants import reconcile_grants
+ from app.services.shadow_agreement import agreement_for
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(
+ session,
+ tenant_id,
+ count=40,
+ verdict=MALICIOUS,
+ disposition=MALICIOUS,
+ resolved_at=base + timedelta(days=1),
+ )
+ granted = await _promote(session, tenant_id, user_id)
+ assert granted.granted is True, granted.refusal_values
+
+ # Nothing has changed yet, so a re-check leaves it alone.
+ assert await reconcile_grants(session, tenant_id) == []
+
+ # 30 recent disagreements. Against 240 earlier decisions the window
+ # agreement is 240/270 = 88.9%, and the trailing 50 is 20/50 = 40%.
+ await _record(
+ session,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+
+ evidence = await agreement_for(session, tenant_id, scope_kind="alert_class", scope_key=CLASS)
+ assert (evidence.recent.agreement_rate or 1.0) < 0.9, "the injected slice should be visibly bad"
+
+ demotions = await reconcile_grants(session, tenant_id)
+
+ assert len(demotions) == 1
+ assert demotions[0].state == "demoted"
+ assert "recent_drift" in demotions[0].refusal_values
+ assert await _audit_actions(session, tenant_id) == ["autonomy:granted", "autonomy:demoted"]
+
+ async def test_the_demoted_grant_no_longer_confers_anything(self):
+ """A revoked capability must stop being readable as current.
+
+ The dispatch path reads `state = 'granted'`, so a demoted row that
+ still answered that query would be a capability nobody could see had
+ been taken away.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.autonomy_grants import reconcile_grants
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+ await _promote(session, tenant_id, user_id)
+ await _record(
+ session,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+ await reconcile_grants(session, tenant_id)
+
+ live = (
+ await session.execute(
+ text(
+ """
+ SELECT count(*) FROM aisoc_autonomy_grants
+ WHERE tenant_id = :t AND state = 'granted' AND capability = 'auto_close'
+ """
+ ),
+ {"t": tenant_id},
+ )
+ ).scalar_one()
+ assert live == 0
+
+
+class TestAnOverrideIsVisiblyAnOverride:
+ async def test_an_operator_can_grant_over_a_refusal(self):
+ """The gate must be overridable, or it gets worked around silently."""
+ async with probe() as (session, tenant_id, user_id):
+ base = datetime.now(UTC) - timedelta(days=2)
+ await _record(session, tenant_id, count=20, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+
+ transition = await _promote(session, tenant_id, user_id, override=True, override_reason="Accepted for a two-week pilot")
+
+ assert transition.granted is True
+ assert transition.source == "operator_override"
+
+ async def test_it_is_a_different_word_everywhere_it_lands(self):
+ """Three places, because one of them alone would be reconstructable.
+
+ The audit action, the grant row's source column, and the refusals
+ carried in the snapshot. Six months later "was this earned" has to be
+ answerable without inferring it from the numbers, which is exactly
+ what somebody would have to do if the override were only a flag
+ inside the evidence JSON.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=2)
+ await _record(session, tenant_id, count=20, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _promote(session, tenant_id, user_id, override=True, override_reason="Pilot")
+
+ assert await _audit_actions(session, tenant_id) == ["autonomy:overridden"]
+
+ row = (
+ (
+ await session.execute(
+ text(
+ """
+ SELECT source, override_reason, evidence
+ FROM aisoc_autonomy_grants WHERE tenant_id = :t
+ """
+ ),
+ {"t": tenant_id},
+ )
+ )
+ .mappings()
+ .one()
+ )
+ assert row["source"] == "operator_override"
+ assert row["override_reason"] == "Pilot"
+ # The refusals that were overruled are in the snapshot, so the
+ # override records what it waived rather than only that it happened.
+ assert "insufficient_sample" in row["evidence"]["refusals"]
+
+ changes = (
+ await session.execute(
+ text("SELECT changes FROM audit_log WHERE tenant_id = :t ORDER BY created_at DESC LIMIT 1"),
+ {"t": tenant_id},
+ )
+ ).scalar_one()
+ assert changes["source"] == "operator_override"
+ assert "insufficient_sample" in changes["waived_refusals"]
+
+ async def test_an_earned_grant_waives_nothing_and_says_so(self):
+ """The empty list is the record that nothing had to be overruled."""
+ async with probe() as (session, tenant_id, user_id):
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=10)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+ await _promote(session, tenant_id, user_id)
+
+ changes = (
+ await session.execute(
+ text("SELECT changes FROM audit_log WHERE tenant_id = :t ORDER BY created_at DESC LIMIT 1"),
+ {"t": tenant_id},
+ )
+ ).scalar_one()
+ assert changes["source"] == "earned"
+ assert changes["waived_refusals"] == []
+
+ async def test_an_override_is_demoted_on_the_same_floors(self):
+ """An override is "I accept this today", not "stop measuring".
+
+ Exempting overrides from demotion would make them permanent, which is
+ the one thing that would turn the override back into the settings
+ toggle this phase exists to replace.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.autonomy_grants import reconcile_grants
+
+ base = datetime.now(UTC) - timedelta(days=2)
+ await _record(session, tenant_id, count=30, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _promote(session, tenant_id, user_id, override=True, override_reason="Pilot")
+
+ await _record(
+ session,
+ tenant_id,
+ count=40,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=10),
+ )
+ demotions = await reconcile_grants(session, tenant_id)
+
+ assert len(demotions) == 1
+ assert demotions[0].state == "demoted"
+
+
+class TestTheAggregateAndTheEvaluatorAgree:
+ async def test_an_abstention_is_excluded_from_agreement_by_the_real_sql(self):
+ """The property the unit tests assert about the type, asserted about the query.
+
+ This is the one that cannot be checked without a database: the type
+ and the SQL agree by convention, and if the aggregate counted an
+ abstention as a disagreement, every unit test would still pass while
+ the live rate was wrong in the direction that refuses promotions.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.shadow_agreement import agreement_for
+
+ base = datetime.now(UTC) - timedelta(days=3)
+ await _record(session, tenant_id, count=10, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(
+ session,
+ tenant_id,
+ count=90,
+ verdict=NEEDS_REVIEW,
+ disposition=FALSE_POSITIVE,
+ resolved_at=base + timedelta(hours=1),
+ )
+
+ evidence = await agreement_for(session, tenant_id, scope_kind="alert_class", scope_key=CLASS)
+
+ assert evidence.window.labelled == 100
+ assert evidence.window.answered == 10
+ assert evidence.window.abstained == 90
+ # Perfect over what it answered, and the abstention rate is what moved.
+ assert evidence.window.agreement_rate == 1.0
+ assert evidence.window.abstention_rate == pytest.approx(0.9)
+
+ async def test_an_unlabeled_closure_is_resolved_but_not_graded(self):
+ """An analyst who declined to classify must not become agreement."""
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.shadow_agreement import agreement_for
+
+ base = datetime.now(UTC) - timedelta(days=3)
+ await _record(session, tenant_id, count=10, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(
+ session,
+ tenant_id,
+ count=40,
+ verdict=FALSE_POSITIVE,
+ disposition="unlabeled",
+ resolved_at=base + timedelta(hours=1),
+ )
+
+ evidence = await agreement_for(session, tenant_id, scope_kind="alert_class", scope_key=CLASS)
+
+ assert evidence.window.resolved == 50
+ assert evidence.window.labelled == 10
+ assert evidence.window.unlabeled == 40
+ assert evidence.window.agreement_rate == 1.0
+
+ async def test_an_unresolved_decision_is_not_evidence_yet(self):
+ """A verdict nobody has closed is neither agreement nor disagreement."""
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.shadow_agreement import agreement_for
+ from sqlalchemy import text
+
+ for _ in range(25):
+ await session.execute(
+ text(
+ """
+ INSERT INTO aisoc_shadow_decisions
+ (tenant_id, alert_id, alert_class, verdict, confidence, decided_at)
+ VALUES (:t, :a, :c, 'false_positive', 0.9, now())
+ """
+ ),
+ {"t": tenant_id, "a": uuid.uuid4(), "c": CLASS},
+ )
+ await session.commit()
+
+ evidence = await agreement_for(session, tenant_id, scope_kind="alert_class", scope_key=CLASS)
+ assert evidence.window.resolved == 0
+ assert evidence.window.agreement_rate is None
+
+
+class TestTheTransitionsAreInTheHashChainedLog:
+ async def test_the_audit_trail_of_a_promotion_cannot_be_deleted(self):
+ """The plan asks for the hash-chained log, so being append-only is the claim.
+
+ A grant an operator can quietly remove the record of is a grant with
+ no audit trail. The trigger refuses the DELETE, and this asserts the
+ refusal rather than assuming it.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=2)
+ await _record(session, tenant_id, count=20, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _promote(session, tenant_id, user_id, override=True, override_reason="Pilot")
+
+ with pytest.raises(Exception, match="immutable"):
+ await session.execute(text("DELETE FROM audit_log WHERE tenant_id = :t"), {"t": tenant_id})
+ await session.rollback()
+
+ async def test_promotion_and_demotion_chain_together(self):
+ """Every transition joins one chain, in order, verifiable offline.
+
+ `verify_chain` is the same pure function an external auditor would run
+ over a CSV export, so what is checked here is what they would check.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.services.audit_hash import verify_chain
+ from app.services.autonomy_grants import reconcile_grants
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+ await _promote(session, tenant_id, user_id)
+ await _record(
+ session,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+ await reconcile_grants(session, tenant_id)
+
+ rows = (
+ (
+ await session.execute(
+ text(
+ """
+ SELECT id, tenant_id, actor_id, actor_email, actor_ip, action, resource,
+ resource_id, changes, metadata, created_at, prev_hash, entry_hash
+ FROM audit_log WHERE tenant_id = :t ORDER BY created_at, id
+ """
+ ),
+ {"t": tenant_id},
+ )
+ )
+ .mappings()
+ .all()
+ )
+
+ assert [row["action"] for row in rows] == ["autonomy:granted", "autonomy:demoted"]
+ valid, index, reason = verify_chain([dict(row) for row in rows])
+ assert valid, f"chain broken at row {index}: {reason}"
+ # The second row chains onto the first rather than starting a new one.
+ assert rows[1]["prev_hash"] == rows[0]["entry_hash"]