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.

fix(console): derive the autonomy posture from the control that gates execution (#1282)

Beenu Arora197d4672c9e7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2dd4654ea..78d1b17e0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -537,6 +537,17 @@ jobs:
# something executes that the other half would have refused.
- name: Verify vendored autonomy evidence rules are in sync
run: python scripts/sync_vendored_autonomy_evidence.py --check
+ # Issue #1243. The seventh mirror, and the one with a worked example of
+ # the failure attached. The console's autonomy page has to say whether a
+ # response verb runs unattended; it used to answer from a confidence
+ # threshold no dispatch path reads, and announced "Autopilot — 7
+ # high-blast actions auto-execute" on a stock install whose dispatcher
+ # queues every one of them. It now calls the same `evaluate_contract`
+ # the dispatcher calls. These three modules are what that function
+ # needs, and a settings page is the worse half to be wrong in: nothing
+ # executes there, so nothing contradicts it.
+ - name: Verify vendored action contracts are in sync
+ run: python scripts/sync_vendored_action_contracts.py --check
# Phase 1.1 — the registry at
# `services/connectors/app/connectors/__init__.py` is the single source
# of truth for the "N connectors" claim. The check verifies that:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3489248a0..4eef9a5ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **The autonomy settings page announced an autopilot posture no deployment
+ has** ([#1243](https://github.com/beenuar/AiSOC/issues/1243)). On a fresh
+ install, Settings → Autonomy guardrails rendered **"Autopilot · 7 high-blast
+ actions auto-execute"** with ACTIONS 19 / AUTO-EXEC 19. None of it was true,
+ and the two halves of why are worth separating.
+
+ *It was a display defect, not a posture defect.* The console decided an
+ action auto-executed from the confidence threshold beside it —
+ `thresholds.auto < 1` in `AutonomyScorecard.tsx` — and the highest threshold
+ in the shipped table is `0.95`, so all nineteen qualified and the seven
+ high- and critical-blast rows flipped the badge. What actually gates a
+ response verb is the tenant's L0–L4 maturity tier and the verb's capability
+ contract, both in `services/actions`. The deployment default is **L1**,
+ which auto-executes nothing above a read, and every containment verb
+ declares `analyst` approval — so the dispatcher queued all seven, exactly as
+ `README.md` says it does. A security product telling an operator their
+ estate is unattended when it is not is the defect, whichever direction the
+ error runs.
+
+ *The table the page edits has no production reader.* `aisoc_autonomy_thresholds`
+ is read by `services/agents/app/policy/guardrails.py`, which nothing on a
+ production path imports. The page now says so, rather than leaving a column
+ of editable sliders to imply otherwise.
+
+ `GET /api/v1/autonomy-policy` now returns an `effective` block (the resolved
+ tier, where it came from, what it may execute without a human, and which
+ verbs actually do) plus a per-action verdict. Those verdicts come from
+ `evaluate_contract` — the same function both dispatch doors call — reached
+ through a byte-identical mirror at
+ `services/api/app/_vendor/action_contracts/`, with
+ `scripts/sync_vendored_action_contracts.py --check` wired into CI. A second
+ implementation would drift, and the drift is the bug.
+
+ Three smaller things fall out of it. `delete_object` is rendered as **no
+ executor** rather than as a critical-blast verb running unattended: it is not
+ an `ActionType`, has no capability contract and has no executor anywhere in
+ the tree — it was a string in two threshold tables. The card now names the
+ tier the badge was derived from, so the claim has a stated basis. And an
+ absent verdict counts as *not* auto-executing, because inferring one from
+ whatever else is on the row is how this happened the first time.
+
## [18.0.0] - 2026-10-09
### BREAKING
diff --git a/ROADMAP.md b/ROADMAP.md
index bfe05540a..05a619fee 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **300 rows — 297 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 **301 rows — 298 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. 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 db760eccd..22689cb1b 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 | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 297 rows
+The last row is the one worth reading first. It is the honest index: 298 rows
`GATED`, 3 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
diff --git a/apps/docs/docs/concepts/capabilities.md b/apps/docs/docs/concepts/capabilities.md
index d457f518d..87a351740 100644
--- a/apps/docs/docs/concepts/capabilities.md
+++ b/apps/docs/docs/concepts/capabilities.md
@@ -39,7 +39,7 @@ verdict the AI produces is measurable, configurable, and learnable from.
|---|---|---|
| **Three-tier memory** | `services/agents/app/memory/` | Session (in-process LRU) + working (Redis, 24h TTL) + institutional (Postgres, permanent) tiers; pgvector-ready schema |
| **Calibrated confidence** | every agent output | Each verdict carries `confidence` (0–1) + `confidence_basis` (list of factors); Brier-score gate in CI eval harness |
-| **Autonomy guardrails** | `/api/v1/autonomy-policy` | Per-action `auto / review / escalate / reject` thresholds in YAML; tenant-specific overrides via DB; admin UI in **Settings → Autonomy Policy** |
+| **Autonomy guardrails** | `/api/v1/autonomy-policy` | Per-action `auto / review / escalate / reject` thresholds in YAML; tenant-specific overrides via DB; admin UI in **Settings → Autonomy Policy**. The response also carries the posture actually in force — the resolved L0–L4 tier and, per action, whether it would reach a vendor without a human — because the thresholds are advisory and no dispatch path reads them |
| **SOC metrics dashboard** | `/api/v1/metrics/soc` | MTTD / MTTR / MTTC / FPR / escalation rate / ATT&CK heatmap / confidence calibration over time; auto-refresh every 60s |
| **Analyst-override feedback loop** | `/api/v1/feedback` | When an analyst corrects a verdict: persists `disposition`, writes the lesson to `aisoc_institutional_memory`, and surfaces *retroactive candidates* — past alerts in the same tenant matching the same coarse signature that would now flip disposition; bulk-apply with one click |
| **Investigation cost telemetry** | `services/agents/app/core/cost_telemetry.py` | Tokens / model / $ / latency per run; aggregate in metrics dashboard |
diff --git a/apps/docs/docs/operations/shadow-mode.md b/apps/docs/docs/operations/shadow-mode.md
index 721ae89fd..b72941ebe 100644
--- a/apps/docs/docs/operations/shadow-mode.md
+++ b/apps/docs/docs/operations/shadow-mode.md
@@ -244,10 +244,14 @@ thing for a tenant seeing ten alerts a day and one seeing ten thousand.
* **SOC operations dashboard**: the "Agreement with analysts" panel, with the
breakdowns by alert class and by source.
-* **Settings, Autonomy guardrails**: the scorecard shows the configured posture
+* **Settings, Autonomy guardrails**: the scorecard shows the posture in force
and the measured track record on one card, because the question they answer
together is the only one worth asking, which is whether the posture is
- justified.
+ justified. The posture comes from the autonomy tier and each action's
+ capability contract — the two things that decide whether a verb reaches a
+ vendor. The per-action confidence thresholds on the same page are advisory
+ and the page says so: nothing in the response path reads
+ `aisoc_autonomy_thresholds` today.
* **`GET /api/v1/autonomy-policy/agreement`**: the same figures, with
breakdowns by alert class, rule, source and model.
diff --git a/apps/web/src/components/settings/AutonomyPolicy.tsx b/apps/web/src/components/settings/AutonomyPolicy.tsx
index 0a8dfefc8..b96334ae1 100644
--- a/apps/web/src/components/settings/AutonomyPolicy.tsx
+++ b/apps/web/src/components/settings/AutonomyPolicy.tsx
@@ -124,15 +124,21 @@ export function AutonomyPolicyPanel() {
<div>
<PanelHeader
title="Autonomy guardrails"
- description="Per-action confidence thresholds. The agent uses these to decide whether to act silently, queue for analyst review, page on-call, or refuse."
+ description="Per-action confidence thresholds, and the autonomy tier that decides what actually runs without a human."
/>
<div className="space-y-5 px-6 py-5">
{/* Phase C3 — autopilot/copilot posture + scorecard (defaults to
copilot). Rendered once the policy loads so the CISO sees the
- whole-SOC autonomy posture before drilling into per-action rows. */}
+ whole-SOC autonomy posture before drilling into per-action rows.
+ `effective` is what the badge is computed from; see the card. */}
{!isLoading && !error && actions.length > 0 ? (
- <AutonomyScorecard actions={actions} agreement={agreement} grants={grantList?.grants} />
+ <AutonomyScorecard
+ actions={actions}
+ agreement={agreement}
+ grants={grantList?.grants}
+ effective={data?.effective}
+ />
) : null}
{/* Legend */}
@@ -154,7 +160,18 @@ export function AutonomyPolicyPanel() {
<Pill tone="red">&lt; escalation</Pill> agent refuses
</li>
</ul>
- <p className="mt-3 text-[11px] text-gray-500">
+ {/* Said here as well as on the card, because this is the block that
+ explains the sliders and a reader who stops at it would otherwise
+ leave believing the thresholds govern a vendor call. */}
+ <p className="mt-3 text-[11px] text-amber-300/80">
+ These thresholds are advisory. Nothing in the response path reads{' '}
+ <code className="font-mono text-amber-200/80">
+ aisoc_autonomy_thresholds
+ </code>{' '}
+ today — whether a verb reaches a vendor unattended is decided by the
+ autonomy tier above and by the action&apos;s own capability contract.
+ </p>
+ <p className="mt-2 text-[11px] text-gray-500">
Defaults are loaded from{' '}
<code className="font-mono text-gray-400">
services/agents/config/autonomy_policy.yaml
@@ -162,8 +179,8 @@ export function AutonomyPolicyPanel() {
. Tenant overrides written here are stored in{' '}
<code className="font-mono text-gray-400">
aisoc_autonomy_thresholds
- </code>{' '}
- and read on the next investigation.
+ </code>
+ .
</p>
</div>
@@ -282,6 +299,24 @@ function ActionRow({
</span>
);
+ // A verb with no executor is not a verb with a cautious threshold. Rendering
+ // a critical-blast name like `delete_object` beside a slider implies the
+ // platform can do it and is choosing not to; nothing in the tree can.
+ const runtimeTag =
+ action.executable === false ? (
+ <span className="rounded-full bg-gray-500/10 px-2 py-0.5 text-[11px] font-medium text-gray-400 ring-1 ring-gray-500/30">
+ no executor
+ </span>
+ ) : action.effective_auto_execute ? (
+ <span className="rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-300 ring-1 ring-amber-500/30">
+ runs unattended
+ </span>
+ ) : action.executable ? (
+ <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[11px] font-medium text-emerald-300 ring-1 ring-emerald-500/30">
+ human approves
+ </span>
+ ) : null;
+
return (
<li className="rounded-lg border border-gray-800 bg-gray-950/40 p-4 transition-colors hover:border-gray-700">
<div className="flex flex-col gap-1 border-b border-gray-800 pb-3 sm:flex-row sm:items-start sm:justify-between">
@@ -299,7 +334,11 @@ function ActionRow({
blast: {action.blast_radius}
</span>
{overrideTag}
+ {runtimeTag}
</div>
+ {action.effective_reason ? (
+ <p className="mt-1 text-[11px] text-gray-500">{action.effective_reason}</p>
+ ) : null}
{action.last_updated_at ? (
<p className="mt-1 text-[11px] text-gray-500">
Last updated{' '}
diff --git a/apps/web/src/components/settings/AutonomyScorecard.test.tsx b/apps/web/src/components/settings/AutonomyScorecard.test.tsx
index 9d23486a8..667398f98 100644
--- a/apps/web/src/components/settings/AutonomyScorecard.test.tsx
+++ b/apps/web/src/components/settings/AutonomyScorecard.test.tsx
@@ -2,10 +2,21 @@
* Tests for the autonomy posture scorecard (Phase C3).
*
* Pins the copilot-default contract: the posture only flips to Autopilot when a
- * high/critical-blast action is configured to auto-execute; otherwise it stays
- * Copilot (a human signs off on high-blast actions). Also checks the pure
- * compute (distribution by blast radius, auto-exec + override counts) and the
- * rendered summary.
+ * high/critical-blast action really does reach a vendor unattended; otherwise it
+ * stays Copilot. Also checks the pure compute (distribution by blast radius,
+ * auto-exec + unimplemented counts) and the rendered summary.
+ *
+ * Issue #1243 rewrote what "auto-executes" means here. It used to be
+ * `thresholds.auto < 1` — a reading of the confidence threshold beside each
+ * row, which no dispatch path consults — and on shipped defaults that made
+ * nineteen of nineteen actions autonomous and put an Autopilot badge on a
+ * deployment that queues all of them. It is now `effective_auto_execute`, which
+ * the API resolves from the autonomy tier and the action's capability contract.
+ *
+ * The tests that mattered most are the two that encode the difference:
+ * `a reachable confidence threshold is not an auto-execution` fails on the
+ * pre-fix compute, and `an action with no verdict is not assumed autonomous`
+ * pins the fail-closed direction.
*/
import { describe, expect, it } from 'vitest';
@@ -15,6 +26,7 @@ import type {
AgreementWindow,
AutonomyActionPolicy,
AutonomyBlastRadius,
+ AutonomyEffective,
AutonomyGrant,
} from '@/lib/api';
import {
@@ -29,6 +41,7 @@ function action(
blast: AutonomyBlastRadius,
auto: number,
overridden = false,
+ runtime: Partial<AutonomyActionPolicy> = {},
): AutonomyActionPolicy {
return {
action: name,
@@ -36,30 +49,94 @@ function action(
thresholds: { auto, review: Math.max(0, auto - 0.2), escalation: Math.max(0, auto - 0.4) },
default_thresholds: { auto: 1, review: 0.8, escalation: 0.6 },
overridden,
+ // Default to the posture a stock install actually has: a registered verb
+ // that a human signs off on.
+ capability: name,
+ executable: true,
+ effective_auto_execute: false,
+ auto_executes_at_any_tier: false,
+ effective_tier: 'L1',
+ effective_reason: 'The action\u2019s contract requires analyst approval even at 100% confidence.',
+ ...runtime,
+ };
+}
+
+const AUTO = { effective_auto_execute: true, auto_executes_at_any_tier: true } as const;
+
+function effective(overrides: Partial<AutonomyEffective> = {}): AutonomyEffective {
+ return {
+ tier: 'L1',
+ tier_label: 'L1-Notify',
+ tier_source: 'environment',
+ max_automatic_impact: 'read_only',
+ auto_executing_actions: [],
+ high_blast_auto_executing: [],
+ unimplemented_actions: [],
+ thresholds_are_advisory: true,
+ advisory_note:
+ 'These thresholds are advisory: nothing in the response path reads them yet.',
+ ...overrides,
};
}
describe('computeScorecard', () => {
+ it('a reachable confidence threshold is not an auto-execution', () => {
+ // The defect, as a test. Every one of these has `auto < 1`, which the
+ // pre-fix compute read as autonomous — including the high-blast one, which
+ // is what flipped the badge to Autopilot on a stock install.
+ const card = computeScorecard([
+ action('lookup_ip', 'read', 0.0),
+ action('isolate_host', 'high', 0.92),
+ action('block_ip', 'high', 0.9),
+ ]);
+ expect(card.posture).toBe('copilot');
+ expect(card.autoExecuting).toBe(0);
+ expect(card.highBlastAuto).toBe(0);
+ });
+
it('defaults to copilot when no high-blast action auto-executes', () => {
const card = computeScorecard([
- action('notify_slack', 'read', 0.5), // low blast auto-exec is fine
- action('isolate_host', 'high', 1.0), // auto == 1.0 => never auto
- action('block_ip', 'medium', 0.9),
+ action('search_siem', 'read', 0.5, false, AUTO), // a read running itself is fine
+ action('isolate_host', 'high', 1.0),
+ action('block_ip', 'medium', 0.9, false, AUTO),
]);
expect(card.posture).toBe('copilot');
expect(card.total).toBe(3);
- expect(card.autoExecuting).toBe(2); // notify + block_ip
+ expect(card.autoExecuting).toBe(2); // search_siem + block_ip
expect(card.highBlastAuto).toBe(0);
});
it('flips to autopilot when a high-blast action auto-executes', () => {
- const card = computeScorecard([
- action('isolate_host', 'high', 0.85), // high blast, auto-executes
- ]);
+ const card = computeScorecard([action('isolate_host', 'high', 0.85, false, AUTO)]);
expect(card.posture).toBe('autopilot');
expect(card.highBlastAuto).toBe(1);
});
+ it('an action with no verdict is not assumed autonomous', () => {
+ // An older API, or a field that failed to serialise. Announcing autonomy
+ // that is not there is the failure this card exists to stop, so an absent
+ // answer counts as "a human approves".
+ const card = computeScorecard([
+ {
+ ...action('isolate_host', 'high', 0.85),
+ effective_auto_execute: undefined,
+ auto_executes_at_any_tier: undefined,
+ },
+ ]);
+ expect(card.posture).toBe('copilot');
+ expect(card.autoExecuting).toBe(0);
+ });
+
+ it('counts a verb with no executor apart from one a human approves', () => {
+ const card = computeScorecard([
+ action('delete_object', 'critical', 0.95, false, { capability: null, executable: false }),
+ action('isolate_host', 'high', 0.92),
+ ]);
+ expect(card.unimplemented).toBe(1);
+ expect(card.autoExecuting).toBe(0);
+ expect(card.highBlastTotal).toBe(2);
+ });
+
it('counts overrides and distribution by blast radius', () => {
const card = computeScorecard([
action('a', 'read', 0.5, true),
@@ -80,16 +157,60 @@ describe('computeScorecard', () => {
describe('AutonomyScorecard', () => {
it('renders the Copilot badge by default', () => {
- render(<AutonomyScorecard actions={[action('isolate_host', 'high', 1.0)]} />);
+ render(<AutonomyScorecard actions={[action('isolate_host', 'high', 0.92)]} />);
expect(screen.getByText('Copilot')).toBeInTheDocument();
expect(screen.getByText(/always require a human/i)).toBeInTheDocument();
});
+ it('claims only what the current tier supports when a contract could ever allow it', () => {
+ // `auto_executes_at_any_tier` is true, so "no tier executes these
+ // unattended" would be false. The weaker sentence is the true one.
+ render(
+ <AutonomyScorecard
+ actions={[action('isolate_host', 'high', 0.92, false, { auto_executes_at_any_tier: true })]}
+ />,
+ );
+ expect(screen.getByText('Copilot')).toBeInTheDocument();
+ expect(screen.getByText(/at the current autonomy tier/i)).toBeInTheDocument();
+ expect(screen.queryByText(/no autonomy tier/i)).not.toBeInTheDocument();
+ });
+
it('renders the Autopilot badge with a warning when high-blast auto-executes', () => {
- render(<AutonomyScorecard actions={[action('isolate_host', 'high', 0.8)]} />);
+ render(<AutonomyScorecard actions={[action('isolate_host', 'high', 0.8, false, AUTO)]} />);
expect(screen.getByText('Autopilot')).toBeInTheDocument();
expect(screen.getByText(/auto-execute/i)).toBeInTheDocument();
});
+
+ it('names the tier the posture was derived from, and where it came from', () => {
+ // A badge with no stated basis is how a posture read off the wrong table
+ // went unchallenged for as long as it did.
+ render(
+ <AutonomyScorecard actions={[action('isolate_host', 'high', 0.92)]} effective={effective()} />,
+ );
+ expect(screen.getByText('L1-Notify')).toBeInTheDocument();
+ expect(screen.getByText(/deployment default/i)).toBeInTheDocument();
+ expect(screen.getByText(/up to read only impact/i)).toBeInTheDocument();
+ });
+
+ it('says the thresholds are advisory rather than leaving the sliders to imply otherwise', () => {
+ render(
+ <AutonomyScorecard actions={[action('isolate_host', 'high', 0.92)]} effective={effective()} />,
+ );
+ expect(screen.getByText(/nothing in the response path reads them/i)).toBeInTheDocument();
+ });
+
+ it('names the verbs with no executor instead of showing them as gated actions', () => {
+ render(
+ <AutonomyScorecard
+ actions={[
+ action('delete_object', 'critical', 0.95, false, { capability: null, executable: false }),
+ ]}
+ effective={effective({ unimplemented_actions: ['delete_object'] })}
+ />,
+ );
+ expect(screen.getByText(/No executor is registered for/i)).toBeInTheDocument();
+ expect(screen.getByText('delete_object')).toBeInTheDocument();
+ });
});
// ─── Measured track record (gap-closure Phase 2.2) ───────────────────────────
diff --git a/apps/web/src/components/settings/AutonomyScorecard.tsx b/apps/web/src/components/settings/AutonomyScorecard.tsx
index 15031cf12..03913a246 100644
--- a/apps/web/src/components/settings/AutonomyScorecard.tsx
+++ b/apps/web/src/components/settings/AutonomyScorecard.tsx
@@ -5,15 +5,35 @@
*
* Sits atop the per-action guardrail editor (`AutonomyPolicy.tsx`) and answers
* the question a CISO actually asks: "how autonomous is my SOC right now, and
- * where does a human still sign off?" It computes an honest posture from the
- * *configured* per-action policy (not fabricated runtime stats):
+ * where does a human still sign off?"
*
* - **Posture** — Copilot (the safe default: high/critical-blast actions
- * always require a human) vs Autopilot (at least one high-blast action is
- * configured to auto-execute). Data-class scoping is expressed through the
- * per-action blast radius, so the scorecard groups by blast radius.
- * - **Distribution** — how many actions auto-execute, queue for review, or
- * always gate on a human, bucketed by blast radius.
+ * always require a human) vs Autopilot (at least one high-blast action
+ * really does reach a vendor unattended). Data-class scoping is expressed
+ * through the per-action blast radius, so the scorecard groups by it.
+ * - **Distribution** — how many actions auto-execute, how many have no
+ * executor behind them at all, bucketed by blast radius.
+ *
+ * Where "auto-executes" comes from, and where it used to come from
+ * ----------------------------------------------------------------
+ * It is `effective_auto_execute`, which the API resolves from the autonomy
+ * tier in force and the action's capability contract — the two things that
+ * actually decide whether `services/actions` dispatches or queues.
+ *
+ * This card used to decide for itself, from the confidence threshold beside
+ * each row: `thresholds.auto < 1` meant "some confidence level lets the agent
+ * act", therefore auto-executing. Every one of the nineteen shipped defaults
+ * is below 1.0 and seven are high- or critical-blast, so a freshly installed
+ * deployment opened this page on **"Autopilot · 7 high-blast actions
+ * auto-execute"** — while its dispatcher, at the default L1 tier, queued all
+ * seven for human approval. The thresholds are read by no production path at
+ * all, so the number was not merely stale; it described a mechanism that was
+ * not running. A security product telling an operator their estate is
+ * unattended when it is not is the kind of wrong that gets acted on.
+ *
+ * An absent `effective_auto_execute` counts as **not** auto-executing. The
+ * failure to avoid is announcing autonomy that is not there, and inferring it
+ * from whatever else is on the row is how that happened the first time.
*
* The compute is a pure function so it's unit-tested directly; the component is
* a thin presentational shell.
@@ -36,6 +56,7 @@ import type {
AgreementResponse,
AutonomyActionPolicy,
AutonomyBlastRadius,
+ AutonomyEffective,
AutonomyGrant,
} from '@/lib/api';
@@ -45,20 +66,31 @@ export interface AutonomyScorecardData {
posture: AutonomyPosture;
total: number;
overridden: number;
- /** Actions whose `auto` threshold is reachable (auto-execute is configured). */
+ /** Actions that really do reach a vendor without a human. */
autoExecuting: number;
- /** High/critical blast actions configured to auto-execute (the autopilot signal). */
+ /** High/critical blast actions that do (the autopilot signal). */
highBlastAuto: number;
+ /** Actions with no executor registered behind the verb at all. */
+ unimplemented: number;
+ /**
+ * High/critical-blast actions that no autonomy tier could ever run
+ * unattended. When this accounts for all of them, the copilot claim is a
+ * property of the contracts rather than of today's tier setting, and the
+ * card is allowed to say so.
+ */
+ highBlastNeverAuto: number;
+ highBlastTotal: number;
byBlast: Record<AutonomyBlastRadius, number>;
}
const HIGH_BLAST: ReadonlySet<AutonomyBlastRadius> = new Set(['high', 'critical']);
-// An action "auto-executes" when its `auto` threshold is below 1.0 — i.e. some
-// confidence level lets the agent act without a human. auto == 1.0 means
-// "never auto" (always at least review), the safe copilot setting.
+// The API resolves this from the autonomy tier and the capability contract.
+// Absent means "we were not told", which is rendered as not auto-executing:
+// the alternative is guessing, and guessing from the threshold beside it is
+// what made this card announce an autopilot posture no deployment held.
function autoExecutes(a: AutonomyActionPolicy): boolean {
- return a.thresholds.auto < 1;
+ return a.effective_auto_execute === true;
}
export function computeScorecard(actions: AutonomyActionPolicy[]): AutonomyScorecardData {
@@ -74,24 +106,34 @@ export function computeScorecard(actions: AutonomyActionPolicy[]): AutonomyScore
let overridden = 0;
let autoExecuting = 0;
let highBlastAuto = 0;
+ let unimplemented = 0;
+ let highBlastNeverAuto = 0;
+ let highBlastTotal = 0;
for (const a of actions) {
byBlast[a.blast_radius] = (byBlast[a.blast_radius] ?? 0) + 1;
if (a.overridden) overridden += 1;
+ if (a.executable === false) unimplemented += 1;
+ const high = HIGH_BLAST.has(a.blast_radius);
+ if (high) highBlastTotal += 1;
if (autoExecutes(a)) {
autoExecuting += 1;
- if (HIGH_BLAST.has(a.blast_radius)) highBlastAuto += 1;
+ if (high) highBlastAuto += 1;
}
+ if (high && a.auto_executes_at_any_tier === false) highBlastNeverAuto += 1;
}
return {
- // Copilot is the default; only a high/critical-blast action configured to
- // auto-execute flips the posture to autopilot.
+ // Copilot is the default; only a high/critical-blast action that actually
+ // executes without a human flips the posture to autopilot.
posture: highBlastAuto > 0 ? 'autopilot' : 'copilot',
total: actions.length,
overridden,
autoExecuting,
highBlastAuto,
+ unimplemented,
+ highBlastNeverAuto,
+ highBlastTotal,
byBlast,
};
}
@@ -149,14 +191,31 @@ export function summariseTrackRecord(agreement: AgreementResponse | null | undef
};
}
+/** The sentence beside the posture badge. */
+export function postureSummary(card: AutonomyScorecardData): string {
+ if (card.posture === 'autopilot') {
+ return `${card.highBlastAuto} high-blast action${card.highBlastAuto === 1 ? '' : 's'} auto-execute — review carefully.`;
+ }
+ // Two different claims, and conflating them is how this card went wrong
+ // before. "No tier ever runs these unattended" is a property of the
+ // contracts and survives a tier change; "nothing does today" is a reading of
+ // the current setting and does not.
+ if (card.highBlastTotal > 0 && card.highBlastNeverAuto === card.highBlastTotal) {
+ return 'High- and critical-blast actions always require a human — no autonomy tier executes them unattended.';
+ }
+ return 'Nothing here reaches a vendor without a human at the current autonomy tier.';
+}
+
export function AutonomyScorecard({
actions,
agreement,
grants,
+ effective,
}: {
actions: AutonomyActionPolicy[];
agreement?: AgreementResponse | null;
grants?: AutonomyGrant[];
+ effective?: AutonomyEffective | null;
}) {
const card = computeScorecard(actions);
const isCopilot = card.posture === 'copilot';
@@ -182,20 +241,21 @@ export function AutonomyScorecard({
>
{isCopilot ? 'Copilot' : 'Autopilot'}
</span>
- <span className="text-xs text-gray-400">
- {isCopilot
- ? 'High- and critical-blast actions always require a human.'
- : `${card.highBlastAuto} high-blast action${card.highBlastAuto === 1 ? '' : 's'} auto-execute — review carefully.`}
- </span>
+ <span className="text-xs text-gray-400">{postureSummary(card)}</span>
</div>
</div>
<dl className="flex gap-4 text-right">
<Stat label="Actions" value={card.total} />
<Stat label="Auto-exec" value={card.autoExecuting} />
+ {card.unimplemented > 0 ? (
+ <Stat label="No executor" value={card.unimplemented} hint="advisory only" />
+ ) : null}
<Stat label="Overridden" value={card.overridden} />
</dl>
</div>
+ <EffectiveControl effective={effective} />
+
<div className="mt-4 flex flex-wrap gap-2" aria-label="Actions by blast radius">
{(Object.entries(card.byBlast) as [AutonomyBlastRadius, number][])
.filter(([, n]) => n > 0)
@@ -215,6 +275,48 @@ export function AutonomyScorecard({
);
}
+/** Where the posture above comes from: the tier, and what it may execute.
+ *
+ * Named on the card rather than left to the per-action rows because the badge
+ * is the thing an operator reads and leaves with, and "Copilot" without the
+ * tier beside it is a claim with no stated basis — which is exactly how a
+ * posture derived from the wrong table went unchallenged.
+ */
+const TIER_SOURCE_LABEL: Record<string, string> = {
+ tenant_policy: 'set for this tenant',
+ environment: 'deployment default',
+ unreadable_policy_floor: 'policy unreadable — held at the conservative floor',
+};
+
+function EffectiveControl({ effective }: { effective?: AutonomyEffective | null }) {
+ if (!effective) return null;
+ const source = TIER_SOURCE_LABEL[effective.tier_source] ?? effective.tier_source;
+
+ return (
+ <div className="mt-3 rounded-lg border border-gray-800 bg-gray-950/60 p-3">
+ <p className="text-[11px] uppercase tracking-wide text-gray-500">What gates execution</p>
+ <p className="mt-1 text-xs text-gray-300">
+ Autonomy tier{' '}
+ <span className="font-mono text-gray-100">{effective.tier_label}</span>{' '}
+ <span className="text-gray-500">({source})</span>.{' '}
+ {effective.max_automatic_impact === null
+ ? 'This tier executes nothing without a human, not even a read.'
+ : `Without a human it executes up to ${effective.max_automatic_impact.replace('_', ' ')} impact, and only where the action's own contract allows it.`}
+ </p>
+ {effective.thresholds_are_advisory ? (
+ <p className="mt-2 text-[11px] text-amber-300/80">{effective.advisory_note}</p>
+ ) : null}
+ {effective.unimplemented_actions.length > 0 ? (
+ <p className="mt-2 text-[11px] text-gray-500">
+ No executor is registered for{' '}
+ <span className="font-mono">{effective.unimplemented_actions.join(', ')}</span>. Thresholds
+ for these change nothing.
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
/**
* Capabilities this tenant holds, and how each one came to be held.
*
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 5ba9502e7..b64707c2b 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -5743,11 +5743,40 @@ export interface AutonomyActionPolicy {
last_updated_at?: string | null;
last_updated_by?: string | null;
last_reason?: string | null;
+ /**
+ * Whether this verb reaches a vendor without a human, resolved by the API
+ * from the autonomy tier and the capability contract — the control that
+ * actually gates execution. Optional so an older API blanks the posture
+ * rather than letting the console infer one from the thresholds, which is
+ * the defect this field exists to retire.
+ */
+ effective_auto_execute?: boolean;
+ /** The same question at the top of the tier ladder. */
+ auto_executes_at_any_tier?: boolean;
+ /** Capability it resolves to in the action registry, null when none does. */
+ capability?: string | null;
+ executable?: boolean;
+ effective_tier?: string;
+ effective_reason?: string;
+}
+
+/** The control that gates execution, as reported by the API. */
+export interface AutonomyEffective {
+ tier: string;
+ tier_label: string;
+ tier_source: string;
+ max_automatic_impact: string | null;
+ auto_executing_actions: string[];
+ high_blast_auto_executing: string[];
+ unimplemented_actions: string[];
+ thresholds_are_advisory: boolean;
+ advisory_note: string;
}
export interface AutonomyPolicyResponse {
tenant_id: string;
actions: AutonomyActionPolicy[];
+ effective?: AutonomyEffective;
}
export interface AutonomyThresholdUpdate {
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 8ea85a7d6..313031ae0 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -57,7 +57,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Related alerts auto-collapse into one ordered attack chain at fuse time | README (attack chains) | `ci.yml` fusion job (`test_attack_chain_grouper.py` — shared-entity alerts join one chain within the window, members ordered by MITRE kill-chain stage, cross-entity link via shared IP; wired into `fusion_engine.process` → `enrichments.attack_chain`) | full | GATED | - |
| Effective Permissions resolves against a live posture snapshot (not empty stub) | README (effective permissions) | `ci.yml` api job (`test_posture_loader.py` — assembles the Okta resolver snapshot from connector `get_resource_config` calls and resolves it; cloud providers consume a connector-provided reconciled snapshot; failures degrade to empty, never fabricated) + connectors `/connectors/{id}/resource_config` endpoint | core | GATED | - |
| Unified Data Explorer (NL + SQL across the lake) replaces the SIEM context-switch | README (data explorer) | `ci.yml` web-test job (`ExploreView.test.tsx` — NL question → `nl-query/translate` → `lake/sql` → BI table; raw-SQL run; source pivots to identity/graph/intel; error surfaced) + web-lint type-check | core | GATED | - |
-| Autonomy posture is copilot-by-default with a visible per-action/blast scorecard | README (autopilot/copilot) | `ci.yml` web-test job (`AutonomyScorecard.test.tsx` — posture stays Copilot unless a high/critical-blast action auto-executes; distribution + override counts; rendered badge) | core | GATED | - |
+| Autonomy posture is copilot-by-default with a visible per-action/blast scorecard | README (autopilot/copilot) | `ci.yml` web-test job (`AutonomyScorecard.test.tsx` — the posture stays Copilot unless a high/critical-blast action *actually* reaches a vendor unattended, which the API resolves from the tier in force and the capability contract. The test that used to back this row read `thresholds.auto < 1`, a confidence cutoff no dispatch path consults, so on shipped defaults it counted 19 of 19 actions autonomous and rendered Autopilot on a stock install whose dispatcher queues all of them. `a reachable confidence threshold is not an auto-execution` fails against that compute. An absent verdict counts as not auto-executing, so an older API blanks the claim rather than inventing one) | core | GATED | - |
+| The posture the console shows is derived from the control that gates execution | `services/api/app/services/autonomy_effective.py`; README (autopilot/copilot) | `ci.yml` api job (`test_autonomy_effective_posture.py` — a default install reports tier L1, nothing high-blast auto-executing, and `delete_object` as having no executor rather than as a critical-blast verb running unattended; one case asserts an action exists whose confidence threshold is reachable *and* whose runtime verdict is gated, so wiring the verdict back to the threshold fails rather than passing on field names. Nine cases, all nine failing against the pre-fix response) + `ci.yml :: python-lint` (`sync_vendored_action_contracts.py --check` byte-compares the API's copy of `contract.py`, `capability_contracts.py` and `approval_rules.py`, because the console calling the dispatcher's own `evaluate_contract` is the entire mechanism and a second copy is wrong in whichever one is more generous) + `ci.yml` actions job (`test_tier_ladder_parity.py` — the L0-L4 ladder is spelled once as an enum and once as strings, compared in both directions, and the three readers of `AISOC_MATURITY_TIER` are swept over the same 23 inputs) | core | GATED | The tier is resolved from `remediation_maturity` and from this process's environment. An operator who exports `AISOC_MATURITY_TIER` on the actions container alone would see the deployment default here; nothing in compose, Helm or Terraform sets it, and a tenant that has chosen a tier has a row, which is read first |
| Broad SIEM/NDR/edge coverage (QRadar, Exabeam, Securonix, Devo, Netskope, Windows/Sysmon, Zeek/Suricata, syslog/CEF) | README (connector count) | `ci.yml` connectors job (`test_schemas.py` + `test_conformance.py` gate every connector; `test_siem_expansion.py` + `test_ndr_edge_expansion.py` pin each new connector's severity-ladder mapping) + `generate_connector_count.py --check` (registry-derived count, README phrase) | core | GATED | - |
| The console's `connector_type` vocabulary names only connectors the platform can ingest | `packages/types/src/generated/connector-types.ts` (the exported `ConnectorType` union) | `ci.yml` python-lint job (`scripts/generate_connector_types.py --self-test` then `--check` — the union is generated from `_CONNECTOR_CLASSES`, the `connectorProfiles` keys and the `connectorTypeCanonical` folds, so it cannot be hand-edited into naming something nothing resolves; the self-test hand-edits the output, deletes it, puts a union back in `connector.ts` and flattens a fold, and requires each to be caught) + `check_connector_profiles.py` (every member resolved against the normalizer and the registry, in both directions) + `tests/test_connector_types_generated.py` (13 cases: regeneration is idempotent, reversing the registry changes no byte, identity is read off the class so `jira_connector.py` -> `jira` and `tenable.py` -> `tenable_io` are not misnamed, and a new connector shows up as drift) | core | GATED | - |
| AI/LLM-usage governance: audit connector + detections + tiered lake storage | README (AI usage / storage) | `ci.yml` connectors job (`test_llm_usage.py` — OpenAI/Anthropic audit connector emits the dotted `event_type` the `llm-*` rules match) + `validate-detections.yml` (8 `llm-*` native rules replay) + api job (`test_storage_tiering.py` — hot/cold TTL-move policy + DDL gate; verified on live ClickHouse) | full | GATED | - |
@@ -311,8 +312,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 300
-- GATED: 297
+- Total: 301
+- GATED: 298
- PARTIAL: 3
- NO GATE: 0
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 25afae03c..b44a475c8 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -14163,7 +14163,22 @@ paths:
overrides), the hard-coded defaults, and an ``overridden`` flag the UI
- uses to render a "modified from default" badge.'
+ uses to render a "modified from default" badge.
+
+
+ Every action also carries whether it would *actually* execute without a
+
+ human, resolved from the tenant''s maturity tier and the verb''s capability
+
+ contract by ``app/services/autonomy_effective.py``. The thresholds and
+
+ that answer are different facts, and the console previously derived the
+
+ second from the first: a threshold below 1.0 was read as "auto-executes",
+
+ which on stock defaults made nineteen of nineteen actions autonomous and
+
+ put an Autopilot badge on a deployment that queues all of them.'
operationId: get_autonomy_policy_api_v1_autonomy_policy_get
responses:
'200':
@@ -19560,6 +19575,29 @@ components:
- type: string
- type: 'null'
title: Last Reason
+ capability:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Capability
+ executable:
+ type: boolean
+ title: Executable
+ default: false
+ effective_auto_execute:
+ type: boolean
+ title: Effective Auto Execute
+ default: false
+ auto_executes_at_any_tier:
+ type: boolean
+ title: Auto Executes At Any Tier
+ default: false
+ effective_tier:
+ type: string
+ title: Effective Tier
+ effective_reason:
+ type: string
+ title: Effective Reason
type: object
required:
- action
@@ -19567,6 +19605,8 @@ components:
- thresholds
- default_thresholds
- overridden
+ - effective_tier
+ - effective_reason
title: ActionPolicy
AddAlertsRequest:
properties:
@@ -21770,10 +21810,13 @@ components:
$ref: '#/components/schemas/ActionPolicy'
type: array
title: Actions
+ effective:
+ $ref: '#/components/schemas/EffectiveAutonomy'
type: object
required:
- tenant_id
- actions
+ - effective
title: AutonomyPolicyResponse
AvailableTools:
properties:
@@ -25102,6 +25145,57 @@ components:
- valid_from
- created_at
title: EdgeOut
+ EffectiveAutonomy:
+ properties:
+ tier:
+ type: string
+ title: Tier
+ tier_label:
+ type: string
+ title: Tier Label
+ tier_source:
+ type: string
+ title: Tier Source
+ max_automatic_impact:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Max Automatic Impact
+ auto_executing_actions:
+ items:
+ type: string
+ type: array
+ title: Auto Executing Actions
+ high_blast_auto_executing:
+ items:
+ type: string
+ type: array
+ title: High Blast Auto Executing
+ unimplemented_actions:
+ items:
+ type: string
+ type: array
+ title: Unimplemented Actions
+ thresholds_are_advisory:
+ type: boolean
+ title: Thresholds Are Advisory
+ advisory_note:
+ type: string
+ title: Advisory Note
+ type: object
+ required:
+ - tier
+ - tier_label
+ - tier_source
+ - max_automatic_impact
+ - auto_executing_actions
+ - high_blast_auto_executing
+ - unimplemented_actions
+ - thresholds_are_advisory
+ - advisory_note
+ title: EffectiveAutonomy
+ description: The control that actually gates execution, as the console must
+ show it.
EffectiveRuleCountOut:
properties:
total:
diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.json
index 03b4d9070..bc50281c7 100644
--- a/scripts/mypy_baseline.json
+++ b/scripts/mypy_baseline.json
@@ -318,6 +318,9 @@
}
},
"services/api": {
+ "app/_vendor/action_contracts/capability_contracts.py": {
+ "attr-defined": 7
+ },
"app/_vendor/ssrf_guard.py": {
"attr-defined": 6,
"union-attr": 1
diff --git a/scripts/sync_vendored_action_contracts.py b/scripts/sync_vendored_action_contracts.py
new file mode 100644
index 000000000..22f634f95
--- /dev/null
+++ b/scripts/sync_vendored_action_contracts.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Keep the API's copy of the action contracts byte-identical to the source.
+
+``services/actions`` decides whether a response verb may run without a human:
+``contract.py`` defines the vocabulary, ``capability_contracts.py`` declares
+what each verb does to an estate, and ``approval_rules.py`` grades the two
+against the tenant's autonomy tier.
+
+``services/api`` serves the console's autonomy page, which has to tell an
+operator whether a verb would actually auto-execute. It cannot import the
+actions service: both package their code as top-level ``app`` and each image
+is built with only its own service directory as context. So the three modules
+exist twice.
+
+They are byte-compared rather than spot-checked because this exact file is a
+worked example of why. The console used to answer the question with a rule of
+its own — a per-action confidence threshold read from a table no dispatch path
+consults — and concluded that seven high-blast verbs ran unattended on a
+deployment whose dispatcher queues every one of them for a human. A safety
+claim that two services compute differently is wrong in whichever one is more
+generous, and a settings page is the more dangerous place to be wrong: nothing
+executes, so nothing contradicts it.
+
+Run modes
+---------
+* ``python scripts/sync_vendored_action_contracts.py`` copy source to vendored.
+* ``python scripts/sync_vendored_action_contracts.py --check`` fail when they differ.
+
+Same shape and same reasoning as ``sync_vendored_autonomy_evidence.py`` and
+``sync_vendored_nl_query.py``; dependency free so it runs on a bare
+interpreter before any install step.
+
+AiSOC, open-source AI Security Operations Center (MIT License).
+"""
+
+from __future__ import annotations
+
+import argparse
+import filecmp
+import shutil
+import sys
+from pathlib import Path
+
+# `scripts/` is on sys.path when this file is run as a program, but not when a
+# test loads it by path with importlib. gate_toolkit sits beside it either way.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import repo_root, self_test_if_requested # noqa: E402
+
+self_test_if_requested(__file__)
+
+REPO_ROOT = repo_root()
+SOURCE_DIR = REPO_ROOT / "services" / "actions" / "app" / "live_actions"
+VENDORED_DIR = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "action_contracts"
+
+#: The three modules the grading needs, and nothing else from that package.
+#: ``live_actions/`` also holds the dispatcher, the registry and every vendor
+#: adapter; those reach httpx, the credential vault and the tenant database,
+#: none of which belong in the API's copy. The three below import only each
+#: other and the standard library, which is what makes the mirror possible.
+SYNCED_FILES: tuple[str, ...] = ("contract.py", "capability_contracts.py", "approval_rules.py")
+
+#: Present only on the vendored side. ``__init__.py`` is the package marker —
+#: the source copies live in a package whose own ``__init__`` imports the
+#: dispatcher, so it cannot be mirrored.
+VENDORED_ONLY: tuple[str, ...] = ("__init__.py", "VENDORED.md")
+
+
+def _drift() -> list[str]:
+ problems: list[str] = []
+
+ if not SOURCE_DIR.is_dir():
+ return [f" - source directory missing: {SOURCE_DIR}"]
+ if not VENDORED_DIR.is_dir():
+ return [f" - vendored directory missing: {VENDORED_DIR}"]
+
+ for name in SYNCED_FILES:
+ src = SOURCE_DIR / name
+ dst = VENDORED_DIR / name
+ if not src.is_file():
+ problems.append(f" - missing in source tree: {name}")
+ continue
+ if not dst.is_file():
+ problems.append(f" - missing in vendored tree: {name}")
+ continue
+ if not filecmp.cmp(src, dst, shallow=False):
+ problems.append(f" - out of date: {name}")
+
+ for name in VENDORED_ONLY:
+ if not (VENDORED_DIR / name).is_file():
+ problems.append(f" - missing vendored-only file: {name}")
+
+ # A stray module in the vendored tree is the drift that runs the other
+ # way: something copied in once and then diverged with nothing comparing
+ # it. Named rather than ignored.
+ declared = set(SYNCED_FILES) | set(VENDORED_ONLY)
+ for path in sorted(VENDORED_DIR.iterdir()):
+ if path.is_file() and path.suffix == ".py" and path.name not in declared:
+ problems.append(f" - unexpected file in vendored tree: {path.name}")
+
+ return problems
+
+
+def _check() -> int:
+ problems = _drift()
+ if problems:
+ print(
+ "FAIL: the vendored action contracts are out of sync with the source.\n"
+ + "\n".join(problems)
+ + "\n\nThe console would then answer 'would this verb auto-execute' with a\n"
+ "different rule than the dispatcher applies, which is the defect this\n"
+ "mirror exists to prevent.\n"
+ "Re-run: python scripts/sync_vendored_action_contracts.py",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"OK: vendored action contracts match source ({len(SYNCED_FILES)} modules).")
+ return 0
+
+
+def _sync() -> int:
+ if not SOURCE_DIR.is_dir():
+ print(f"FAIL: source directory missing: {SOURCE_DIR}", file=sys.stderr)
+ return 1
+
+ VENDORED_DIR.mkdir(parents=True, exist_ok=True)
+ for name in SYNCED_FILES:
+ src = SOURCE_DIR / name
+ if not src.is_file():
+ print(f"FAIL: source file missing: {src}", file=sys.stderr)
+ return 1
+ dst = VENDORED_DIR / name
+ shutil.copy2(src, dst)
+ print(f"copied {src.relative_to(REPO_ROOT)} -> {dst.relative_to(REPO_ROOT)}")
+
+ print(f"\nDone. Commit the changes under {VENDORED_DIR.relative_to(REPO_ROOT)}/.")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Sync the vendored action contracts.")
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Verify the vendored copies match the source; do not write.",
+ )
+ args = parser.parse_args()
+ return _check() if args.check else _sync()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/actions/app/live_actions/approval_rules.py b/services/actions/app/live_actions/approval_rules.py
new file mode 100644
index 000000000..a37c71ea1
--- /dev/null
+++ b/services/actions/app/live_actions/approval_rules.py
@@ -0,0 +1,383 @@
+"""Approval as a function of confidence *and* impact, not autonomy tier alone.
+
+The L0–L4 ladder answers "how much is this tenant willing to automate". It
+does not answer "is this particular action safe at this particular
+confidence", and treating one as the other produces both failure modes:
+enriching an IOC blocked behind an approval queue because the tier is low,
+and isolating a production database server auto-executed because the tier is
+high and the model said 94%.
+
+The matrix is the second axis. Every decision needs both:
+
+ enrich an IOC any confidence automatic
+ search endpoints any confidence automatic
+ block a known-bad hash >= 99% automatic
+ kill a process >= 98% policy (tier decides)
+ disable an account >= 99% analyst approval
+ isolate a production host any confidence mandatory human
+ delete a cloud resource any confidence prohibited
+
+Two properties are non-negotiable and are asserted in tests:
+
+**The matrix can only raise a requirement, never lower it.** If either the
+action's declared contract or the confidence threshold says a human is
+needed, a human is needed. An autonomy tier of L4 does not override an
+action declared MANDATORY_HUMAN, and high confidence does not override an
+IRREVERSIBLE impact.
+
+**Missing confidence is not high confidence.** An action arriving with no
+confidence score is treated as the lowest band. The alternative — defaulting
+to permissive — means a scoring bug becomes an autonomous action.
+
+Why the rules sit here rather than in ``app.services.approval_matrix``
+=====================================================================
+
+They were in that module, which every door still imports them from — it is
+now a re-export and the import path has not moved. What moved is the file,
+next to ``contract.py`` and ``capability_contracts.py``, so that the three
+of them form a self-contained unit importing nothing but each other and the
+standard library.
+
+That matters because a second service needs the same answer. The console's
+autonomy page has to say whether a verb would actually auto-execute, and it
+is served by ``services/api``, which cannot import this one: both package
+their code as top-level ``app`` and each image is built with only its own
+service directory as context. So ``services/api`` carries a byte-identical
+copy at ``app/_vendor/action_contracts/`` and
+``scripts/sync_vendored_action_contracts.py --check`` fails the build when
+the two drift — the arrangement already used for the LLM input contract, the
+deterministic narrative and the autonomy evidence rules.
+
+The console reading its own definition of "auto-executes" is exactly the
+defect this move repairs. It read a per-action confidence threshold from a
+table no dispatch path consults, concluded that seven high-blast verbs ran
+unattended, and announced an autopilot posture on a deployment where the
+dispatcher queues every one of them for a human.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Protocol
+
+from .contract import (
+ NEVER_AUTONOMOUS,
+ ActionImpact,
+ ApprovalRequirement,
+)
+
+logger = logging.getLogger("aisoc.approval_matrix")
+
+
+class _Contract(Protocol):
+ """The two fields a capability contract contributes to a grading.
+
+ Structural rather than an import of ``CapabilityContract``: an executor
+ class carries the same two attributes without being one, and every door
+ grades both kinds. Naming the dataclass would exclude the executors.
+ """
+
+ @property
+ def impact(self) -> ActionImpact:
+ """What this does to the estate if the finding is wrong."""
+
+ @property
+ def approval(self) -> ApprovalRequirement:
+ """Baseline requirement, which the matrix may raise and never lower."""
+
+
+#: Confidence floor per impact tier for a *fully automatic* execution.
+#: Below the floor, the action drops to analyst approval.
+#:
+#: The numbers are deliberately steep. The cost of an unnecessary approval is
+#: a few minutes of analyst time; the cost of a wrong autonomous containment
+#: is an outage plus the trust needed to ever enable autonomy again.
+AUTOMATIC_CONFIDENCE_FLOOR: dict[ActionImpact, float] = {
+ ActionImpact.READ_ONLY: 0.0,
+ ActionImpact.LOW: 0.90,
+ ActionImpact.MODERATE: 0.98,
+ ActionImpact.HIGH: 0.99,
+ # SEVERE and IRREVERSIBLE are absent on purpose: no floor exists because
+ # no confidence makes them automatic. Encoded in NEVER_AUTONOMOUS rather
+ # than as an unreachable threshold like 1.01, which invites someone to
+ # "just lower it a bit".
+}
+
+#: Autonomy tiers, lowest to highest. Mirrors the L0–L4 ladder.
+TIER_ORDER = ("L0", "L1", "L2", "L3", "L4")
+
+#: The same ladder as ``MaturityTier`` spells it, and as its ``label``
+#: property renders it. Repeated here because this module may not import
+#: ``app.services.maturity`` — that module is reached through the dispatcher,
+#: and importing it back would close the loop — and because the vendored copy
+#: has no ``MaturityTier`` to reach at all.
+#:
+#: ``services/actions/tests/test_tier_ladder_parity.py`` compares both tuples
+#: and the labels against the enum in both directions, so the repetition
+#: cannot become a disagreement.
+TIER_FULL_NAMES = ("L0_OBSERVE", "L1_NOTIFY", "L2_CONTAIN", "L3_REMEDIATE", "L4_AUTOMATE")
+
+TIER_LABELS: dict[str, str] = {
+ "L0": "L0-Observe",
+ "L1": "L1-Notify",
+ "L2": "L2-Contain",
+ "L3": "L3-Remediate",
+ "L4": "L4-Automate",
+}
+
+#: Deployment-wide tier when ``AISOC_MATURITY_TIER`` is unset. Notify-only:
+#: the platform surfaces everything and acts on nothing above a read.
+DEFAULT_TIER = "L1"
+
+#: The highest tier an *earned* autonomy grant may lift a verb to. A grant is
+#: an inference from agreement on triage verdicts, which is evidence about the
+#: agent's judgement and not evidence that a HIGH-blast containment was the
+#: right call — so no track record reaches L4. ``dispatcher`` applies it;
+#: the console has to apply the same ceiling or it would describe a posture
+#: the deployment does not hold.
+EARNED_TIER_CEILING_LABEL = "L3"
+
+
+def tier_from_env_value(raw: str | None) -> tuple[str, bool]:
+ """Canonical tier for a raw ``AISOC_MATURITY_TIER`` value.
+
+ Returns ``(tier, recognised)``. ``recognised`` is False only when a
+ non-empty value matched nothing, which the caller logs — an unset
+ variable is the ordinary case and not a misconfiguration.
+
+ Accepts ``L2``, ``L2_CONTAIN`` and ``2``, which is what the dispatcher
+ has always accepted. An unparseable value falls back to
+ :data:`DEFAULT_TIER` rather than to the highest tier, because the one
+ thing a typo must not do is grant autonomy nobody asked for.
+ """
+ cleaned = (raw or "").strip().upper()
+ if not cleaned:
+ return DEFAULT_TIER, True
+ for index, tier in enumerate(TIER_ORDER):
+ if cleaned in {tier, TIER_FULL_NAMES[index], str(index)}:
+ return tier, True
+ return DEFAULT_TIER, False
+
+
+#: The highest impact each tier may execute without an analyst, *given* the
+#: confidence floor above is also met.
+#:
+#: ``None`` means exactly one thing: this tier executes nothing at all. That
+#: is true of L0 and of L0 only. ``maturity.py`` defines the ladder as "L0 —
+#: Observe: all actions routed to approval queue. L1 — Notify: MINIMAL
+#: blast-radius actions are automatic", and ``_AUTO_ALLOWED_AT_TIER`` encodes
+#: it as ``set()`` for L0 and ``{MINIMAL}`` for L1. READ_ONLY impact is the
+#: same thing as MINIMAL blast radius — ``dispatcher._IMPACT_BLAST`` maps one
+#: onto the other — so L1's entry here is READ_ONLY.
+#:
+#: It read ``None``, which put a pure read into the analyst queue at the
+#: default tier. That is the failure mode this module's own docstring opens
+#: by naming, and the contract gate calls a read requiring approval
+#: "mis-classified or not actually a read". The registry door had grown a
+#: local bypass to route around it; this table entry is where the answer
+#: belongs, so there is one of it.
+#:
+#: Only READ_ONLY moves. Every impact above it ranks higher than the L1
+#: ceiling and still returns ANALYST, exactly as the ``None`` branch did.
+TIER_MAX_AUTOMATIC: dict[str, ActionImpact | None] = {
+ "L0": None, # observe only — not even a read
+ "L1": ActionImpact.READ_ONLY, # notify: reads run, nothing acts
+ "L2": ActionImpact.READ_ONLY,
+ "L3": ActionImpact.MODERATE, # reversible actions
+ "L4": ActionImpact.HIGH, # bounded response; never SEVERE or IRREVERSIBLE
+}
+
+_IMPACT_ORDER = (
+ ActionImpact.READ_ONLY,
+ ActionImpact.LOW,
+ ActionImpact.MODERATE,
+ ActionImpact.HIGH,
+ ActionImpact.SEVERE,
+ ActionImpact.IRREVERSIBLE,
+)
+
+
+def _impact_rank(impact: ActionImpact) -> int:
+ return _IMPACT_ORDER.index(impact)
+
+
+@dataclass(frozen=True)
+class ApprovalDecision:
+ """What must happen before this action runs, and why.
+
+ ``reason`` is not decoration. It is shown to the analyst in the approval
+ queue and written to the audit trail, and "requires approval" without a
+ reason is the kind of prompt people learn to click through.
+ """
+
+ requirement: ApprovalRequirement
+ reason: str
+ impact: ActionImpact
+ confidence: float
+ tier: str
+
+ @property
+ def can_auto_execute(self) -> bool:
+ return self.requirement == ApprovalRequirement.AUTOMATIC
+
+ @property
+ def is_blocked(self) -> bool:
+ return self.requirement == ApprovalRequirement.PROHIBITED
+
+
+def evaluate(
+ *,
+ impact: ActionImpact,
+ declared_approval: ApprovalRequirement,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Combine the action's contract, the finding's confidence and the tenant's tier.
+
+ The result is the *most restrictive* of the three. Each input can raise
+ the requirement; none can lower it.
+ """
+ # Missing confidence is the lowest band, not a free pass. Defaulting
+ # permissive would turn a scoring bug into an autonomous action.
+ score = 0.0 if confidence is None else max(0.0, min(1.0, float(confidence)))
+ tier = tier if tier in TIER_ORDER else "L0"
+
+ if declared_approval == ApprovalRequirement.PROHIBITED:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.PROHIBITED,
+ reason=(
+ "This action is declared prohibited by its own contract. No "
+ "autonomy tier or confidence level executes it from the platform."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if impact in NEVER_AUTONOMOUS:
+ requirement = ApprovalRequirement.PROHIBITED if impact == ActionImpact.IRREVERSIBLE else ApprovalRequirement.MANDATORY_HUMAN
+ return ApprovalDecision(
+ requirement=requirement,
+ reason=(
+ f"Impact is {impact.value}: "
+ + (
+ "the action cannot be undone, so the platform does not execute it."
+ if impact == ActionImpact.IRREVERSIBLE
+ else f"a human must approve regardless of confidence ({score:.0%}) or autonomy tier ({tier})."
+ )
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.MANDATORY_HUMAN:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.MANDATORY_HUMAN,
+ reason=(f"The action's contract requires a human regardless of confidence ({score:.0%}) or autonomy tier ({tier})."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ ceiling = TIER_MAX_AUTOMATIC.get(tier)
+ if ceiling is None:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} does not auto-execute any action; this is a recommendation for an analyst to approve."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if _impact_rank(impact) > _impact_rank(ceiling):
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} auto-executes up to {ceiling.value} impact; this action is {impact.value}."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ floor = AUTOMATIC_CONFIDENCE_FLOOR.get(impact)
+ if floor is None:
+ # Defensive: an impact tier with no floor and not in NEVER_AUTONOMOUS
+ # means the two tables disagree. Fail closed rather than guess.
+ logger.warning("approval_matrix.no_floor impact=%s", impact.value)
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=f"No confidence floor is defined for {impact.value} impact.",
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if score < floor:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Confidence {score:.0%} is below the {floor:.0%} floor for {impact.value}-impact actions."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.ANALYST:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"The action's contract requires analyst approval even at {score:.0%} confidence."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.AUTOMATIC,
+ reason=(
+ f"{impact.value} impact at {score:.0%} confidence clears the {floor:.0%} "
+ f"floor, and tier {tier} permits automatic execution up to "
+ f"{ceiling.value}."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+
+def evaluate_contract(
+ *,
+ contract: _Contract,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Grade a capability contract. **The one place a door may decide.**
+
+ Every entry point that grades a verb calls this and nothing else:
+ ``approval_gate.apply_matrix`` behind ``POST /actions``,
+ ``dispatcher._apply_capability_contract`` behind
+ ``POST /live-actions/dispatch`` and the playbook bridge, and — through the
+ vendored copy — the console's autonomy page, which previously answered the
+ question for itself and got it wrong.
+
+ It exists because the two doors were separately responsible for
+ unpacking a contract into :func:`evaluate`'s four arguments, and one of
+ them grew a local short-circuit the other did not have. ``search_siem``
+ is read_only/automatic and returned ``awaiting_approval`` through the
+ legacy door while executing through the registry door — the same verb
+ graded differently depending on which door it came through, which is the
+ precise thing the dispatcher's docstring says its contract block exists
+ to stop.
+
+ Keeping the unpacking here is what makes that structural rather than a
+ matter of discipline. A third door gets the answer by calling this; it
+ cannot get a different one without reimplementing the function, and
+ ``services/actions/tests/test_approval_doors_agree.py`` sweeps both live
+ doors over every capability, tier and confidence band to catch it if one
+ does.
+ """
+ return evaluate(
+ impact=contract.impact,
+ declared_approval=contract.approval,
+ confidence=confidence,
+ tier=tier,
+ )
diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.py
index ee8fafe46..2308f28d5 100644
--- a/services/actions/app/live_actions/dispatcher.py
+++ b/services/actions/app/live_actions/dispatcher.py
@@ -55,6 +55,7 @@ from app.services.tenant_policy import TenantPolicy, resolve_tenant_policy
from app.services.verification import PostActionVerifier, VerificationOutcome
from . import registry
+from .approval_rules import EARNED_TIER_CEILING_LABEL, TIER_ORDER, tier_from_env_value
from .capability_contracts import CAPABILITY_CONTRACTS
from .contract import ActionImpact, ApprovalRequirement, Reversal
from .models import LiveActionRequest, LiveActionResult, LiveActionStatus
@@ -64,7 +65,11 @@ from .models import LiveActionRequest, LiveActionResult, LiveActionStatus
#: 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
+#:
+#: Read from `approval_rules` rather than written here, because the console
+#: has to apply the same ceiling when it tells an operator which verbs run
+#: unattended, and it reaches that module through the vendored copy.
+EARNED_TIER_CEILING = MaturityTier(TIER_ORDER.index(EARNED_TIER_CEILING_LABEL))
logger = structlog.get_logger(__name__)
@@ -77,15 +82,17 @@ def configured_tier() -> MaturityTier:
Accepts ``L2`` / ``L2_CONTAIN`` / ``2``. Per-tenant tier scoping arrives
with the autonomy-scoping UI (Phase C3); until then one conservative
deployment default keeps copilot the out-of-the-box posture.
+
+ The parsing itself lives in ``approval_rules`` because the console has to
+ name the tier in force on its autonomy page, and a second reader of the
+ same variable answering differently is how that page came to announce a
+ posture the dispatcher does not implement.
"""
- raw = os.environ.get(_TIER_ENV, "").strip().upper()
- if not raw:
- return MaturityTier.L1_NOTIFY
- for tier in MaturityTier:
- if raw in {tier.name, tier.name.split("_")[0], str(tier.value)}:
- return tier
- logger.warning("live_action.bad_tier_env", value=raw)
- return MaturityTier.L1_NOTIFY
+ raw = os.environ.get(_TIER_ENV, "")
+ tier, recognised = tier_from_env_value(raw)
+ if not recognised:
+ logger.warning("live_action.bad_tier_env", value=raw.strip().upper())
+ return MaturityTier(TIER_ORDER.index(tier))
def _action_type_for(request: LiveActionRequest, executor: object) -> ActionType | None:
diff --git a/services/actions/app/services/approval_gate.py b/services/actions/app/services/approval_gate.py
index 22f6eec36..e98260586 100644
--- a/services/actions/app/services/approval_gate.py
+++ b/services/actions/app/services/approval_gate.py
@@ -45,13 +45,15 @@ import structlog
from app.live_actions.capability_contracts import contract_for_action_type
from app.live_actions.contract import ApprovalRequirement
from app.models.action import ActionRequest, ActionStatus, BlastRadius
-from app.services.approval_matrix import evaluate_contract
+from app.services.approval_matrix import DEFAULT_TIER, evaluate_contract
logger = structlog.get_logger()
-#: Conservative default when no tenant policy can be read. Mirrors
-#: ``dispatcher.configured_tier``: L1 notifies, it does not act.
-_DEFAULT_TIER = "L1"
+#: Conservative default when no tenant policy can be read. Not a local
+#: literal: ``dispatcher.configured_tier``, this gate and the console's
+#: autonomy page all have to name the same tier, and three copies of "L1" is
+#: three chances for one of them to move.
+_DEFAULT_TIER = DEFAULT_TIER
def _tier_label(tier: object) -> str:
diff --git a/services/actions/app/services/approval_matrix.py b/services/actions/app/services/approval_matrix.py
index 60124cc84..08a6a4207 100644
--- a/services/actions/app/services/approval_matrix.py
+++ b/services/actions/app/services/approval_matrix.py
@@ -1,303 +1,46 @@
-"""Approval as a function of confidence *and* impact, not autonomy tier alone.
-
-The L0–L4 ladder answers "how much is this tenant willing to automate". It
-does not answer "is this particular action safe at this particular
-confidence", and treating one as the other produces both failure modes:
-enriching an IOC blocked behind an approval queue because the tier is low,
-and isolating a production database server auto-executed because the tier is
-high and the model said 94%.
-
-The matrix is the second axis. Every decision needs both:
-
- enrich an IOC any confidence automatic
- search endpoints any confidence automatic
- block a known-bad hash >= 99% automatic
- kill a process >= 98% policy (tier decides)
- disable an account >= 99% analyst approval
- isolate a production host any confidence mandatory human
- delete a cloud resource any confidence prohibited
-
-Two properties are non-negotiable and are asserted in tests:
-
-**The matrix can only raise a requirement, never lower it.** If either the
-action's declared contract or the confidence threshold says a human is
-needed, a human is needed. An autonomy tier of L4 does not override an
-action declared MANDATORY_HUMAN, and high confidence does not override an
-IRREVERSIBLE impact.
-
-**Missing confidence is not high confidence.** An action arriving with no
-confidence score is treated as the lowest band. The alternative — defaulting
-to permissive — means a scoring bug becomes an autonomous action.
+"""The approval matrix, re-exported from where both services can read it.
+
+Every door still imports ``evaluate_contract`` from here and the grading has
+not changed. The rules themselves moved one directory across to
+``app/live_actions/approval_rules.py``, beside ``contract.py`` and
+``capability_contracts.py``, so that the three form a unit importing nothing
+but each other and the standard library — which is what lets ``services/api``
+carry a byte-identical copy at ``app/_vendor/action_contracts/`` and answer
+"would this verb auto-execute" with the same function the dispatcher uses
+rather than with a second opinion of its own.
+
+``scripts/sync_vendored_action_contracts.py --check`` keeps the two copies
+identical. ``tests/test_approval_doors_agree.py`` reads imports from this
+module path by name, so the path staying put is load-bearing rather than
+merely convenient.
"""
from __future__ import annotations
-import logging
-from dataclasses import dataclass
-from typing import Protocol
-
-from app.live_actions.contract import (
- NEVER_AUTONOMOUS,
- ActionImpact,
- ApprovalRequirement,
-)
-
-logger = logging.getLogger("aisoc.approval_matrix")
-
-
-class _Contract(Protocol):
- """The two fields a capability contract contributes to a grading.
-
- Structural rather than an import of ``CapabilityContract``: this module
- lives in ``app.services`` and that one in ``app.live_actions``, whose
- package ``__init__`` already imports the dispatcher, which imports this
- module. Naming the class would close that loop.
- """
-
- @property
- def impact(self) -> ActionImpact:
- """What this does to the estate if the finding is wrong."""
-
- @property
- def approval(self) -> ApprovalRequirement:
- """Baseline requirement, which the matrix may raise and never lower."""
-
-
-#: Confidence floor per impact tier for a *fully automatic* execution.
-#: Below the floor, the action drops to analyst approval.
-#:
-#: The numbers are deliberately steep. The cost of an unnecessary approval is
-#: a few minutes of analyst time; the cost of a wrong autonomous containment
-#: is an outage plus the trust needed to ever enable autonomy again.
-AUTOMATIC_CONFIDENCE_FLOOR: dict[ActionImpact, float] = {
- ActionImpact.READ_ONLY: 0.0,
- ActionImpact.LOW: 0.90,
- ActionImpact.MODERATE: 0.98,
- ActionImpact.HIGH: 0.99,
- # SEVERE and IRREVERSIBLE are absent on purpose: no floor exists because
- # no confidence makes them automatic. Encoded in NEVER_AUTONOMOUS rather
- # than as an unreachable threshold like 1.01, which invites someone to
- # "just lower it a bit".
-}
-
-#: Autonomy tiers, lowest to highest. Mirrors the L0–L4 ladder.
-TIER_ORDER = ("L0", "L1", "L2", "L3", "L4")
-
-#: The highest impact each tier may execute without an analyst, *given* the
-#: confidence floor above is also met.
-#:
-#: ``None`` means exactly one thing: this tier executes nothing at all. That
-#: is true of L0 and of L0 only. ``maturity.py`` defines the ladder as "L0 —
-#: Observe: all actions routed to approval queue. L1 — Notify: MINIMAL
-#: blast-radius actions are automatic", and ``_AUTO_ALLOWED_AT_TIER`` encodes
-#: it as ``set()`` for L0 and ``{MINIMAL}`` for L1. READ_ONLY impact is the
-#: same thing as MINIMAL blast radius — ``dispatcher._IMPACT_BLAST`` maps one
-#: onto the other — so L1's entry here is READ_ONLY.
-#:
-#: It read ``None``, which put a pure read into the analyst queue at the
-#: default tier. That is the failure mode this module's own docstring opens
-#: by naming, and the contract gate calls a read requiring approval
-#: "mis-classified or not actually a read". The registry door had grown a
-#: local bypass to route around it; this table entry is where the answer
-#: belongs, so there is one of it.
-#:
-#: Only READ_ONLY moves. Every impact above it ranks higher than the L1
-#: ceiling and still returns ANALYST, exactly as the ``None`` branch did.
-TIER_MAX_AUTOMATIC: dict[str, ActionImpact | None] = {
- "L0": None, # observe only — not even a read
- "L1": ActionImpact.READ_ONLY, # notify: reads run, nothing acts
- "L2": ActionImpact.READ_ONLY,
- "L3": ActionImpact.MODERATE, # reversible actions
- "L4": ActionImpact.HIGH, # bounded response; never SEVERE or IRREVERSIBLE
-}
-
-_IMPACT_ORDER = (
- ActionImpact.READ_ONLY,
- ActionImpact.LOW,
- ActionImpact.MODERATE,
- ActionImpact.HIGH,
- ActionImpact.SEVERE,
- ActionImpact.IRREVERSIBLE,
+from app.live_actions.approval_rules import (
+ AUTOMATIC_CONFIDENCE_FLOOR,
+ DEFAULT_TIER,
+ TIER_FULL_NAMES,
+ TIER_LABELS,
+ TIER_MAX_AUTOMATIC,
+ TIER_ORDER,
+ ApprovalDecision,
+ evaluate,
+ evaluate_contract,
+ logger,
+ tier_from_env_value,
)
-
-def _impact_rank(impact: ActionImpact) -> int:
- return _IMPACT_ORDER.index(impact)
-
-
-@dataclass(frozen=True)
-class ApprovalDecision:
- """What must happen before this action runs, and why.
-
- ``reason`` is not decoration. It is shown to the analyst in the approval
- queue and written to the audit trail, and "requires approval" without a
- reason is the kind of prompt people learn to click through.
- """
-
- requirement: ApprovalRequirement
- reason: str
- impact: ActionImpact
- confidence: float
- tier: str
-
- @property
- def can_auto_execute(self) -> bool:
- return self.requirement == ApprovalRequirement.AUTOMATIC
-
- @property
- def is_blocked(self) -> bool:
- return self.requirement == ApprovalRequirement.PROHIBITED
-
-
-def evaluate(
- *,
- impact: ActionImpact,
- declared_approval: ApprovalRequirement,
- confidence: float | None,
- tier: str,
-) -> ApprovalDecision:
- """Combine the action's contract, the finding's confidence and the tenant's tier.
-
- The result is the *most restrictive* of the three. Each input can raise
- the requirement; none can lower it.
- """
- # Missing confidence is the lowest band, not a free pass. Defaulting
- # permissive would turn a scoring bug into an autonomous action.
- score = 0.0 if confidence is None else max(0.0, min(1.0, float(confidence)))
- tier = tier if tier in TIER_ORDER else "L0"
-
- if declared_approval == ApprovalRequirement.PROHIBITED:
- return ApprovalDecision(
- requirement=ApprovalRequirement.PROHIBITED,
- reason=(
- "This action is declared prohibited by its own contract. No "
- "autonomy tier or confidence level executes it from the platform."
- ),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- if impact in NEVER_AUTONOMOUS:
- requirement = ApprovalRequirement.PROHIBITED if impact == ActionImpact.IRREVERSIBLE else ApprovalRequirement.MANDATORY_HUMAN
- return ApprovalDecision(
- requirement=requirement,
- reason=(
- f"Impact is {impact.value}: "
- + (
- "the action cannot be undone, so the platform does not execute it."
- if impact == ActionImpact.IRREVERSIBLE
- else f"a human must approve regardless of confidence ({score:.0%}) or autonomy tier ({tier})."
- )
- ),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- if declared_approval == ApprovalRequirement.MANDATORY_HUMAN:
- return ApprovalDecision(
- requirement=ApprovalRequirement.MANDATORY_HUMAN,
- reason=(f"The action's contract requires a human regardless of confidence ({score:.0%}) or autonomy tier ({tier})."),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- ceiling = TIER_MAX_AUTOMATIC.get(tier)
- if ceiling is None:
- return ApprovalDecision(
- requirement=ApprovalRequirement.ANALYST,
- reason=(f"Autonomy tier {tier} does not auto-execute any action; this is a recommendation for an analyst to approve."),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- if _impact_rank(impact) > _impact_rank(ceiling):
- return ApprovalDecision(
- requirement=ApprovalRequirement.ANALYST,
- reason=(f"Autonomy tier {tier} auto-executes up to {ceiling.value} impact; this action is {impact.value}."),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- floor = AUTOMATIC_CONFIDENCE_FLOOR.get(impact)
- if floor is None:
- # Defensive: an impact tier with no floor and not in NEVER_AUTONOMOUS
- # means the two tables disagree. Fail closed rather than guess.
- logger.warning("approval_matrix.no_floor impact=%s", impact.value)
- return ApprovalDecision(
- requirement=ApprovalRequirement.ANALYST,
- reason=f"No confidence floor is defined for {impact.value} impact.",
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- if score < floor:
- return ApprovalDecision(
- requirement=ApprovalRequirement.ANALYST,
- reason=(f"Confidence {score:.0%} is below the {floor:.0%} floor for {impact.value}-impact actions."),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- if declared_approval == ApprovalRequirement.ANALYST:
- return ApprovalDecision(
- requirement=ApprovalRequirement.ANALYST,
- reason=(f"The action's contract requires analyst approval even at {score:.0%} confidence."),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
- return ApprovalDecision(
- requirement=ApprovalRequirement.AUTOMATIC,
- reason=(
- f"{impact.value} impact at {score:.0%} confidence clears the {floor:.0%} "
- f"floor, and tier {tier} permits automatic execution up to "
- f"{ceiling.value}."
- ),
- impact=impact,
- confidence=score,
- tier=tier,
- )
-
-
-def evaluate_contract(
- *,
- contract: _Contract,
- confidence: float | None,
- tier: str,
-) -> ApprovalDecision:
- """Grade a capability contract. **The one place a door may decide.**
-
- Every entry point that grades a verb calls this and nothing else:
- ``approval_gate.apply_matrix`` behind ``POST /actions``,
- ``dispatcher._apply_capability_contract`` behind
- ``POST /live-actions/dispatch`` and the playbook bridge.
-
- It exists because the two doors were separately responsible for
- unpacking a contract into :func:`evaluate`'s four arguments, and one of
- them grew a local short-circuit the other did not have. ``search_siem``
- is read_only/automatic and returned ``awaiting_approval`` through the
- legacy door while executing through the registry door — the same verb
- graded differently depending on which door it came through, which is the
- precise thing the dispatcher's docstring says its contract block exists
- to stop.
-
- Keeping the unpacking here is what makes that structural rather than a
- matter of discipline. A third door gets the answer by calling this; it
- cannot get a different one without reimplementing the function, and
- ``tests/test_approval_doors_agree.py`` sweeps both live doors over every
- capability, tier and confidence band to catch it if one does.
- """
- return evaluate(
- impact=contract.impact,
- declared_approval=contract.approval,
- confidence=confidence,
- tier=tier,
- )
+__all__ = [
+ "AUTOMATIC_CONFIDENCE_FLOOR",
+ "DEFAULT_TIER",
+ "TIER_FULL_NAMES",
+ "TIER_LABELS",
+ "TIER_MAX_AUTOMATIC",
+ "TIER_ORDER",
+ "ApprovalDecision",
+ "evaluate",
+ "evaluate_contract",
+ "logger",
+ "tier_from_env_value",
+]
diff --git a/services/actions/tests/test_tier_ladder_parity.py b/services/actions/tests/test_tier_ladder_parity.py
new file mode 100644
index 000000000..01b620b13
--- /dev/null
+++ b/services/actions/tests/test_tier_ladder_parity.py
@@ -0,0 +1,111 @@
+"""The L0-L4 ladder is spelled in two places. They may not disagree.
+
+``MaturityTier`` is the enum the dispatcher and the gate pass around.
+``approval_rules`` repeats the same ladder as plain strings, because it may
+not import ``app.services.maturity`` — that module is reached through the
+dispatcher and importing it back would close the loop — and because the copy
+``services/api`` vendors has no enum to reach at all.
+
+A repetition nobody compares is a disagreement waiting to happen, and this one
+decides whether a containment verb runs unattended. So compare it, in both
+directions: a member added to the enum and a tier added to the tuple each have
+to fail here.
+
+The env parsing is checked the same way. Three readers answer "which tier did
+the operator ask for": the dispatcher, the tenant-policy fallback, and now the
+console through the vendored copy. ``tenant_policy`` keeps its own
+implementation — it is imported *by* the dispatcher, so reaching into
+``live_actions`` from it would be a cycle — which is exactly the arrangement
+that needs a test rather than a convention.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.live_actions.approval_rules import (
+ DEFAULT_TIER,
+ EARNED_TIER_CEILING_LABEL,
+ TIER_FULL_NAMES,
+ TIER_LABELS,
+ TIER_ORDER,
+ tier_from_env_value,
+)
+from app.live_actions.dispatcher import EARNED_TIER_CEILING, configured_tier
+from app.services.maturity import MaturityTier
+from app.services.tenant_policy import UNREADABLE_POLICY_FLOOR, _env_tier
+
+#: Every spelling the dispatcher has always accepted, plus the ways an
+#: operator gets it wrong. A typo must never grant autonomy nobody asked for,
+#: so the unrecognised cases are here deliberately.
+ENV_VALUES = (
+ "",
+ " ",
+ "L0",
+ "L1",
+ "L2",
+ "L3",
+ "L4",
+ "l2",
+ " l3 ",
+ "L0_OBSERVE",
+ "L1_NOTIFY",
+ "L2_CONTAIN",
+ "L3_REMEDIATE",
+ "L4_AUTOMATE",
+ "0",
+ "1",
+ "2",
+ "3",
+ "4",
+ "L5",
+ "5",
+ "TOTALLY_AUTONOMOUS",
+ "AUTOMATE",
+)
+
+
+def test_the_two_ladders_have_the_same_tiers() -> None:
+ assert len(TIER_ORDER) == len(TIER_FULL_NAMES) == len(MaturityTier)
+ assert tuple(member.name for member in MaturityTier) == TIER_FULL_NAMES
+ assert tuple(member.name.split("_")[0] for member in MaturityTier) == TIER_ORDER
+
+
+def test_a_tier_index_is_its_enum_value() -> None:
+ """``MaturityTier(TIER_ORDER.index(t))`` is how the dispatcher converts."""
+ for index, short in enumerate(TIER_ORDER):
+ assert MaturityTier(index).name.split("_")[0] == short
+ assert MaturityTier[TIER_FULL_NAMES[index]].value == index
+
+
+def test_the_labels_are_the_enum_labels() -> None:
+ assert set(TIER_LABELS) == set(TIER_ORDER)
+ for member in MaturityTier:
+ assert TIER_LABELS[member.name.split("_")[0]] == member.label
+
+
[email protected]("raw", ENV_VALUES)
+def test_every_reader_of_the_tier_variable_agrees(raw: str, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("AISOC_MATURITY_TIER", raw)
+ shared, _recognised = tier_from_env_value(raw)
+
+ assert configured_tier().name.split("_")[0] == shared
+ assert _env_tier().name.split("_")[0] == shared
+
+
+def test_an_unparseable_value_falls_back_rather_than_up() -> None:
+ for raw in ("L5", "5", "TOTALLY_AUTONOMOUS", "AUTOMATE"):
+ tier, recognised = tier_from_env_value(raw)
+ assert recognised is False
+ assert tier == DEFAULT_TIER
+
+
+def test_the_default_and_the_unreadable_floor_are_the_same_tier() -> None:
+ """Both mean "notify, do not act". Two literals would let one move."""
+ assert DEFAULT_TIER == "L1"
+ assert UNREADABLE_POLICY_FLOOR.name.split("_")[0] == DEFAULT_TIER
+
+
+def test_the_earned_ceiling_label_is_the_dispatcher_ceiling() -> None:
+ """A grant may lift a verb to L3 and no further, wherever it is read."""
+ assert EARNED_TIER_CEILING.name.split("_")[0] == EARNED_TIER_CEILING_LABEL
+ assert EARNED_TIER_CEILING is MaturityTier.L3_REMEDIATE
diff --git a/services/api/app/_vendor/action_contracts/VENDORED.md b/services/api/app/_vendor/action_contracts/VENDORED.md
new file mode 100644
index 000000000..9f137261c
--- /dev/null
+++ b/services/api/app/_vendor/action_contracts/VENDORED.md
@@ -0,0 +1,44 @@
+# Vendored: action contracts
+
+This directory is an **automatically maintained mirror** of three modules from
+`services/actions/app/live_actions/`. Do not hand-edit the `.py` files here.
+
+## Why it exists
+
+`services/actions` decides whether a response verb may run without a human.
+`services/api` serves the console's autonomy page, which has to tell an
+operator whether a verb would actually auto-execute on their deployment.
+
+Neither service can import the other: both package their code as top-level
+`app`, and each Docker image is built with only its own service directory as
+the build context. So the grading has to exist twice.
+
+It is byte-compared rather than spot-checked because this page is the worked
+example of what happens otherwise. The console answered "does this
+auto-execute" from a per-action confidence threshold in a table no dispatch
+path reads, concluded that seven high-blast verbs ran unattended, and showed
+an **Autopilot** badge on a stock install whose dispatcher queues every one of
+them for human approval. A safety claim two services compute differently is
+wrong in whichever one is more generous, and a settings page is the worse
+place to be wrong — nothing executes there, so nothing contradicts it.
+
+## How it stays in sync
+
+Run `python scripts/sync_vendored_action_contracts.py` whenever you change any
+of the source modules. CI runs the same script in `--check` mode in
+`.github/workflows/ci.yml` and fails the build if the trees drift.
+
+## Files
+
+| Vendored file | Source of truth |
+| ------------------------- | ------------------------------------------------------------------ |
+| `contract.py` | `services/actions/app/live_actions/contract.py` |
+| `capability_contracts.py` | `services/actions/app/live_actions/capability_contracts.py` |
+| `approval_rules.py` | `services/actions/app/live_actions/approval_rules.py` |
+| `__init__.py` | vendored only — the source package's `__init__` imports the dispatcher |
+| `VENDORED.md` | vendored only |
+
+## Consumer
+
+`services/api/app/services/autonomy_effective.py`, behind
+`GET /api/v1/autonomy-policy`.
diff --git a/services/api/app/_vendor/action_contracts/__init__.py b/services/api/app/_vendor/action_contracts/__init__.py
new file mode 100644
index 000000000..4a5a67620
--- /dev/null
+++ b/services/api/app/_vendor/action_contracts/__init__.py
@@ -0,0 +1,51 @@
+"""Vendored mirror of the action contracts from ``services/actions``.
+
+Do not hand-edit the modules beside this one. They are byte-identical copies
+of ``services/actions/app/live_actions/{contract,capability_contracts,approval_rules}.py``
+maintained by ``scripts/sync_vendored_action_contracts.py``, which CI runs in
+``--check`` mode.
+
+This file is the package marker and exists only here: the source modules live
+in a package whose own ``__init__`` imports the dispatcher, the registry and
+every vendor adapter, none of which belong in the API image.
+
+What the API uses it for: the console's autonomy page has to say whether a
+response verb would actually auto-execute under the deployment's autonomy
+tier. Answering that with a second rule is what the page used to do, and it
+announced an autopilot posture on a deployment that queues every containment
+verb for a human. See ``app/services/autonomy_effective.py``.
+"""
+
+from .approval_rules import (
+ AUTOMATIC_CONFIDENCE_FLOOR,
+ DEFAULT_TIER,
+ TIER_FULL_NAMES,
+ TIER_LABELS,
+ TIER_MAX_AUTOMATIC,
+ TIER_ORDER,
+ ApprovalDecision,
+ evaluate,
+ evaluate_contract,
+ tier_from_env_value,
+)
+from .capability_contracts import CAPABILITY_CONTRACTS, CapabilityContract
+from .contract import NEVER_AUTONOMOUS, ActionImpact, ApprovalRequirement, Reversal
+
+__all__ = [
+ "AUTOMATIC_CONFIDENCE_FLOOR",
+ "CAPABILITY_CONTRACTS",
+ "DEFAULT_TIER",
+ "NEVER_AUTONOMOUS",
+ "TIER_FULL_NAMES",
+ "TIER_LABELS",
+ "TIER_MAX_AUTOMATIC",
+ "TIER_ORDER",
+ "ActionImpact",
+ "ApprovalDecision",
+ "ApprovalRequirement",
+ "CapabilityContract",
+ "Reversal",
+ "evaluate",
+ "evaluate_contract",
+ "tier_from_env_value",
+]
diff --git a/services/api/app/_vendor/action_contracts/approval_rules.py b/services/api/app/_vendor/action_contracts/approval_rules.py
new file mode 100644
index 000000000..a37c71ea1
--- /dev/null
+++ b/services/api/app/_vendor/action_contracts/approval_rules.py
@@ -0,0 +1,383 @@
+"""Approval as a function of confidence *and* impact, not autonomy tier alone.
+
+The L0–L4 ladder answers "how much is this tenant willing to automate". It
+does not answer "is this particular action safe at this particular
+confidence", and treating one as the other produces both failure modes:
+enriching an IOC blocked behind an approval queue because the tier is low,
+and isolating a production database server auto-executed because the tier is
+high and the model said 94%.
+
+The matrix is the second axis. Every decision needs both:
+
+ enrich an IOC any confidence automatic
+ search endpoints any confidence automatic
+ block a known-bad hash >= 99% automatic
+ kill a process >= 98% policy (tier decides)
+ disable an account >= 99% analyst approval
+ isolate a production host any confidence mandatory human
+ delete a cloud resource any confidence prohibited
+
+Two properties are non-negotiable and are asserted in tests:
+
+**The matrix can only raise a requirement, never lower it.** If either the
+action's declared contract or the confidence threshold says a human is
+needed, a human is needed. An autonomy tier of L4 does not override an
+action declared MANDATORY_HUMAN, and high confidence does not override an
+IRREVERSIBLE impact.
+
+**Missing confidence is not high confidence.** An action arriving with no
+confidence score is treated as the lowest band. The alternative — defaulting
+to permissive — means a scoring bug becomes an autonomous action.
+
+Why the rules sit here rather than in ``app.services.approval_matrix``
+=====================================================================
+
+They were in that module, which every door still imports them from — it is
+now a re-export and the import path has not moved. What moved is the file,
+next to ``contract.py`` and ``capability_contracts.py``, so that the three
+of them form a self-contained unit importing nothing but each other and the
+standard library.
+
+That matters because a second service needs the same answer. The console's
+autonomy page has to say whether a verb would actually auto-execute, and it
+is served by ``services/api``, which cannot import this one: both package
+their code as top-level ``app`` and each image is built with only its own
+service directory as context. So ``services/api`` carries a byte-identical
+copy at ``app/_vendor/action_contracts/`` and
+``scripts/sync_vendored_action_contracts.py --check`` fails the build when
+the two drift — the arrangement already used for the LLM input contract, the
+deterministic narrative and the autonomy evidence rules.
+
+The console reading its own definition of "auto-executes" is exactly the
+defect this move repairs. It read a per-action confidence threshold from a
+table no dispatch path consults, concluded that seven high-blast verbs ran
+unattended, and announced an autopilot posture on a deployment where the
+dispatcher queues every one of them for a human.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Protocol
+
+from .contract import (
+ NEVER_AUTONOMOUS,
+ ActionImpact,
+ ApprovalRequirement,
+)
+
+logger = logging.getLogger("aisoc.approval_matrix")
+
+
+class _Contract(Protocol):
+ """The two fields a capability contract contributes to a grading.
+
+ Structural rather than an import of ``CapabilityContract``: an executor
+ class carries the same two attributes without being one, and every door
+ grades both kinds. Naming the dataclass would exclude the executors.
+ """
+
+ @property
+ def impact(self) -> ActionImpact:
+ """What this does to the estate if the finding is wrong."""
+
+ @property
+ def approval(self) -> ApprovalRequirement:
+ """Baseline requirement, which the matrix may raise and never lower."""
+
+
+#: Confidence floor per impact tier for a *fully automatic* execution.
+#: Below the floor, the action drops to analyst approval.
+#:
+#: The numbers are deliberately steep. The cost of an unnecessary approval is
+#: a few minutes of analyst time; the cost of a wrong autonomous containment
+#: is an outage plus the trust needed to ever enable autonomy again.
+AUTOMATIC_CONFIDENCE_FLOOR: dict[ActionImpact, float] = {
+ ActionImpact.READ_ONLY: 0.0,
+ ActionImpact.LOW: 0.90,
+ ActionImpact.MODERATE: 0.98,
+ ActionImpact.HIGH: 0.99,
+ # SEVERE and IRREVERSIBLE are absent on purpose: no floor exists because
+ # no confidence makes them automatic. Encoded in NEVER_AUTONOMOUS rather
+ # than as an unreachable threshold like 1.01, which invites someone to
+ # "just lower it a bit".
+}
+
+#: Autonomy tiers, lowest to highest. Mirrors the L0–L4 ladder.
+TIER_ORDER = ("L0", "L1", "L2", "L3", "L4")
+
+#: The same ladder as ``MaturityTier`` spells it, and as its ``label``
+#: property renders it. Repeated here because this module may not import
+#: ``app.services.maturity`` — that module is reached through the dispatcher,
+#: and importing it back would close the loop — and because the vendored copy
+#: has no ``MaturityTier`` to reach at all.
+#:
+#: ``services/actions/tests/test_tier_ladder_parity.py`` compares both tuples
+#: and the labels against the enum in both directions, so the repetition
+#: cannot become a disagreement.
+TIER_FULL_NAMES = ("L0_OBSERVE", "L1_NOTIFY", "L2_CONTAIN", "L3_REMEDIATE", "L4_AUTOMATE")
+
+TIER_LABELS: dict[str, str] = {
+ "L0": "L0-Observe",
+ "L1": "L1-Notify",
+ "L2": "L2-Contain",
+ "L3": "L3-Remediate",
+ "L4": "L4-Automate",
+}
+
+#: Deployment-wide tier when ``AISOC_MATURITY_TIER`` is unset. Notify-only:
+#: the platform surfaces everything and acts on nothing above a read.
+DEFAULT_TIER = "L1"
+
+#: The highest tier an *earned* autonomy grant may lift a verb to. A grant is
+#: an inference from agreement on triage verdicts, which is evidence about the
+#: agent's judgement and not evidence that a HIGH-blast containment was the
+#: right call — so no track record reaches L4. ``dispatcher`` applies it;
+#: the console has to apply the same ceiling or it would describe a posture
+#: the deployment does not hold.
+EARNED_TIER_CEILING_LABEL = "L3"
+
+
+def tier_from_env_value(raw: str | None) -> tuple[str, bool]:
+ """Canonical tier for a raw ``AISOC_MATURITY_TIER`` value.
+
+ Returns ``(tier, recognised)``. ``recognised`` is False only when a
+ non-empty value matched nothing, which the caller logs — an unset
+ variable is the ordinary case and not a misconfiguration.
+
+ Accepts ``L2``, ``L2_CONTAIN`` and ``2``, which is what the dispatcher
+ has always accepted. An unparseable value falls back to
+ :data:`DEFAULT_TIER` rather than to the highest tier, because the one
+ thing a typo must not do is grant autonomy nobody asked for.
+ """
+ cleaned = (raw or "").strip().upper()
+ if not cleaned:
+ return DEFAULT_TIER, True
+ for index, tier in enumerate(TIER_ORDER):
+ if cleaned in {tier, TIER_FULL_NAMES[index], str(index)}:
+ return tier, True
+ return DEFAULT_TIER, False
+
+
+#: The highest impact each tier may execute without an analyst, *given* the
+#: confidence floor above is also met.
+#:
+#: ``None`` means exactly one thing: this tier executes nothing at all. That
+#: is true of L0 and of L0 only. ``maturity.py`` defines the ladder as "L0 —
+#: Observe: all actions routed to approval queue. L1 — Notify: MINIMAL
+#: blast-radius actions are automatic", and ``_AUTO_ALLOWED_AT_TIER`` encodes
+#: it as ``set()`` for L0 and ``{MINIMAL}`` for L1. READ_ONLY impact is the
+#: same thing as MINIMAL blast radius — ``dispatcher._IMPACT_BLAST`` maps one
+#: onto the other — so L1's entry here is READ_ONLY.
+#:
+#: It read ``None``, which put a pure read into the analyst queue at the
+#: default tier. That is the failure mode this module's own docstring opens
+#: by naming, and the contract gate calls a read requiring approval
+#: "mis-classified or not actually a read". The registry door had grown a
+#: local bypass to route around it; this table entry is where the answer
+#: belongs, so there is one of it.
+#:
+#: Only READ_ONLY moves. Every impact above it ranks higher than the L1
+#: ceiling and still returns ANALYST, exactly as the ``None`` branch did.
+TIER_MAX_AUTOMATIC: dict[str, ActionImpact | None] = {
+ "L0": None, # observe only — not even a read
+ "L1": ActionImpact.READ_ONLY, # notify: reads run, nothing acts
+ "L2": ActionImpact.READ_ONLY,
+ "L3": ActionImpact.MODERATE, # reversible actions
+ "L4": ActionImpact.HIGH, # bounded response; never SEVERE or IRREVERSIBLE
+}
+
+_IMPACT_ORDER = (
+ ActionImpact.READ_ONLY,
+ ActionImpact.LOW,
+ ActionImpact.MODERATE,
+ ActionImpact.HIGH,
+ ActionImpact.SEVERE,
+ ActionImpact.IRREVERSIBLE,
+)
+
+
+def _impact_rank(impact: ActionImpact) -> int:
+ return _IMPACT_ORDER.index(impact)
+
+
+@dataclass(frozen=True)
+class ApprovalDecision:
+ """What must happen before this action runs, and why.
+
+ ``reason`` is not decoration. It is shown to the analyst in the approval
+ queue and written to the audit trail, and "requires approval" without a
+ reason is the kind of prompt people learn to click through.
+ """
+
+ requirement: ApprovalRequirement
+ reason: str
+ impact: ActionImpact
+ confidence: float
+ tier: str
+
+ @property
+ def can_auto_execute(self) -> bool:
+ return self.requirement == ApprovalRequirement.AUTOMATIC
+
+ @property
+ def is_blocked(self) -> bool:
+ return self.requirement == ApprovalRequirement.PROHIBITED
+
+
+def evaluate(
+ *,
+ impact: ActionImpact,
+ declared_approval: ApprovalRequirement,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Combine the action's contract, the finding's confidence and the tenant's tier.
+
+ The result is the *most restrictive* of the three. Each input can raise
+ the requirement; none can lower it.
+ """
+ # Missing confidence is the lowest band, not a free pass. Defaulting
+ # permissive would turn a scoring bug into an autonomous action.
+ score = 0.0 if confidence is None else max(0.0, min(1.0, float(confidence)))
+ tier = tier if tier in TIER_ORDER else "L0"
+
+ if declared_approval == ApprovalRequirement.PROHIBITED:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.PROHIBITED,
+ reason=(
+ "This action is declared prohibited by its own contract. No "
+ "autonomy tier or confidence level executes it from the platform."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if impact in NEVER_AUTONOMOUS:
+ requirement = ApprovalRequirement.PROHIBITED if impact == ActionImpact.IRREVERSIBLE else ApprovalRequirement.MANDATORY_HUMAN
+ return ApprovalDecision(
+ requirement=requirement,
+ reason=(
+ f"Impact is {impact.value}: "
+ + (
+ "the action cannot be undone, so the platform does not execute it."
+ if impact == ActionImpact.IRREVERSIBLE
+ else f"a human must approve regardless of confidence ({score:.0%}) or autonomy tier ({tier})."
+ )
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.MANDATORY_HUMAN:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.MANDATORY_HUMAN,
+ reason=(f"The action's contract requires a human regardless of confidence ({score:.0%}) or autonomy tier ({tier})."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ ceiling = TIER_MAX_AUTOMATIC.get(tier)
+ if ceiling is None:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} does not auto-execute any action; this is a recommendation for an analyst to approve."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if _impact_rank(impact) > _impact_rank(ceiling):
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} auto-executes up to {ceiling.value} impact; this action is {impact.value}."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ floor = AUTOMATIC_CONFIDENCE_FLOOR.get(impact)
+ if floor is None:
+ # Defensive: an impact tier with no floor and not in NEVER_AUTONOMOUS
+ # means the two tables disagree. Fail closed rather than guess.
+ logger.warning("approval_matrix.no_floor impact=%s", impact.value)
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=f"No confidence floor is defined for {impact.value} impact.",
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if score < floor:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Confidence {score:.0%} is below the {floor:.0%} floor for {impact.value}-impact actions."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.ANALYST:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"The action's contract requires analyst approval even at {score:.0%} confidence."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.AUTOMATIC,
+ reason=(
+ f"{impact.value} impact at {score:.0%} confidence clears the {floor:.0%} "
+ f"floor, and tier {tier} permits automatic execution up to "
+ f"{ceiling.value}."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+
+def evaluate_contract(
+ *,
+ contract: _Contract,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Grade a capability contract. **The one place a door may decide.**
+
+ Every entry point that grades a verb calls this and nothing else:
+ ``approval_gate.apply_matrix`` behind ``POST /actions``,
+ ``dispatcher._apply_capability_contract`` behind
+ ``POST /live-actions/dispatch`` and the playbook bridge, and — through the
+ vendored copy — the console's autonomy page, which previously answered the
+ question for itself and got it wrong.
+
+ It exists because the two doors were separately responsible for
+ unpacking a contract into :func:`evaluate`'s four arguments, and one of
+ them grew a local short-circuit the other did not have. ``search_siem``
+ is read_only/automatic and returned ``awaiting_approval`` through the
+ legacy door while executing through the registry door — the same verb
+ graded differently depending on which door it came through, which is the
+ precise thing the dispatcher's docstring says its contract block exists
+ to stop.
+
+ Keeping the unpacking here is what makes that structural rather than a
+ matter of discipline. A third door gets the answer by calling this; it
+ cannot get a different one without reimplementing the function, and
+ ``services/actions/tests/test_approval_doors_agree.py`` sweeps both live
+ doors over every capability, tier and confidence band to catch it if one
+ does.
+ """
+ return evaluate(
+ impact=contract.impact,
+ declared_approval=contract.approval,
+ confidence=confidence,
+ tier=tier,
+ )
diff --git a/services/api/app/_vendor/action_contracts/capability_contracts.py b/services/api/app/_vendor/action_contracts/capability_contracts.py
new file mode 100644
index 000000000..97ced04a6
--- /dev/null
+++ b/services/api/app/_vendor/action_contracts/capability_contracts.py
@@ -0,0 +1,780 @@
+"""Contract per capability, not per vendor.
+
+What an action does to an estate is a property of the verb. Isolating a host
+is equally disruptive on CrowdStrike, Defender and SentinelOne, so declaring
+it three times invites the three to drift — and the one that drifts low is
+the one that auto-executes.
+
+Adding a vendor for an existing verb therefore inherits the classification
+automatically. Adding a *new verb* requires an entry here, which the
+conformance gate enforces, so a capability cannot reach dispatch without
+somebody having decided what it does when the finding is wrong.
+
+The classifications below are deliberately conservative. The cost of an
+unnecessary approval is a few minutes of analyst time. The cost of a wrong
+autonomous containment is an outage plus the organisational trust needed to
+ever enable autonomy again, and that second one does not come back.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from .contract import ActionImpact, ApprovalRequirement, Reversal
+
+
+@dataclass(frozen=True)
+class CapabilityContract:
+ impact: ActionImpact
+ approval: ApprovalRequirement
+ reversal: Reversal
+ required_permission: str
+ reverse_capability: str = ""
+ has_verification_probe: bool = False
+ verification_gap: str = ""
+ note: str = ""
+
+
+_READ = "actions:read"
+_CONTAIN = "actions:contain"
+#: Reading a vendor is not containment and should not require the
+#: permission that isolates a host — bundling them means anyone who
+#: can look can also act.
+_INVESTIGATE = "actions:investigate"
+_IDENTITY = "actions:identity"
+_NETWORK = "actions:network"
+_TICKET = "actions:ticket"
+
+CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
+ # ── Read-only ──────────────────────────────────────────────────────────
+ # ── Read-only investigation verbs ───────────────────────────────────
+ #
+ # Twenty-nine executors could change the estate and exactly one could
+ # ask it a question. That shapes an agent: with no way to read a
+ # vendor, an investigation can only reach the lake, and anything the
+ # lake did not ingest is invisible to it.
+ #
+ # These are automatic by construction. They change nothing, so there is
+ # nothing to verify and nothing to approve — and gating a read behind
+ # an analyst is how an agent learns to conclude without looking.
+ "get_host": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_INVESTIGATE,
+ note="Device record from the EDR: OS, agent version, last seen, containment state.",
+ ),
+ "get_detections": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_INVESTIGATE,
+ note=(
+ "Recent vendor detections for a host. What the EDR already "
+ "concluded, which is context an investigation should start from "
+ "rather than rediscover."
+ ),
+ ),
+ # search_hash is deliberately absent. Fleet-wide hash prevalence is
+ # the most useful read of the four — first-seen timestamps clustered
+ # in one morning mean something different from a binary present for
+ # a year — but CrowdStrike exposes it through an endpoint whose shape
+ # I could not verify, and a declared capability with no working
+ # executor is the exact defect this contract exists to prevent.
+ "get_user_activity": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_INVESTIGATE,
+ note="Recent authentication events for a principal, from the IdP.",
+ ),
+ "lookup_cloud_audit": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_INVESTIGATE,
+ has_verification_probe=False,
+ verification_gap=(
+ "A read leaves nothing behind to read back, so there is no write "
+ "for a probe to confirm. Recorded rather than left blank so this "
+ "reads as the answer it is and not as an omission."
+ ),
+ note=(
+ "Cloud control-plane audit events for one principal, resource or "
+ "API call. The window and the attribute are typed arguments; the "
+ "caller never supplies query text."
+ ),
+ ),
+ "lookup_endpoint_telemetry": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_INVESTIGATE,
+ has_verification_probe=False,
+ verification_gap=("A read leaves nothing behind to read back. Same reasoning as lookup_cloud_audit and search_siem."),
+ note=(
+ "Sightings of one indicator in endpoint telemetry, through the "
+ "EDR's own hunting index. The query is one of a closed set of "
+ "templates the executor owns; a caller supplies a template name, "
+ "an indicator and a window, never a query string. That is a "
+ "security boundary rather than a convenience: this verb is "
+ "reachable from an investigation agent, and the indicator it "
+ "passes was lifted out of attacker-influenced alert text."
+ ),
+ ),
+ "osquery_live_query": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_READ,
+ has_verification_probe=False,
+ verification_gap=(
+ "A read leaves nothing behind to read back, the same gap "
+ "search_siem and lookup_endpoint_telemetry record. The rows the "
+ "fleet returned are the response; asking again would be a second "
+ "query, not a confirmation of the first."
+ ),
+ note=(
+ "Runs one of a closed set of allowlisted osquery templates across "
+ "a fleet. READ_ONLY is a statement about the SQL, which the "
+ "caller cannot write: app.clients.osquery_allowlist owns every "
+ "template and renders the parameters. A verb that accepted query "
+ "text would not be read-only at this tier, because osquery can "
+ "read any file the agent can."
+ ),
+ ),
+ "search_siem": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_READ,
+ has_verification_probe=False,
+ verification_gap=(
+ "A read leaves nothing behind to read back. Verification answers "
+ "'did the write land', and there is no write — the results are "
+ "the response, and a second query would not confirm the first, it "
+ "would be another one. Recorded rather than left blank so this "
+ "reads as the answer it is and not as an omission."
+ ),
+ note="A query. Safe at any confidence, which is the point of separating impact from confidence.",
+ ),
+ # ── Endpoint containment ───────────────────────────────────────────────
+ "isolate_host": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="unisolate_host",
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "Cuts one machine off the network. Reversible, but somebody notices "
+ "immediately. The verification probe matters more here than anywhere: "
+ "believing a host is contained when it is not is the failure this "
+ "whole contract exists to prevent."
+ ),
+ ),
+ "unisolate_host": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="isolate_host",
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "No ActionType exists for unisolate_host, so the verifier cannot be "
+ "reached for it. The isolate_host probe reads the same containment "
+ "state and would answer this too; wiring needs an ActionType."
+ ),
+ note="Restoring connectivity is itself a decision; it needs the same approval.",
+ ),
+ "quarantine_file": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="restore_file",
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "Quarantining a legitimate binary breaks whatever depended on it. "
+ "The CrowdStrike arm is an RTR 'rm', so the probe reads the path "
+ "back with 'ls': the effect is the file's absence, and RTR "
+ "accepting a delete is not the same fact. SentinelOne's arm "
+ "fetches the file into the forensics vault instead of removing "
+ "it, so the probe reports indeterminate there rather than "
+ "checking for an absence that arm never causes."
+ ),
+ ),
+ "restore_file": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="quarantine_file",
+ required_permission=_CONTAIN,
+ ),
+ "kill_process": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "A killed process cannot be un-killed, but the effect does not "
+ "persist: a service restarts, a user runs the program again. "
+ "Self-healing is the honest answer here, not 'irreversible'. "
+ "The probe re-reads the host's process table over RTR, because "
+ "an accepted 'kill' and a dead process differ whenever the agent "
+ "is offline or the process is protected. SentinelOne targets "
+ "binaries by hash and lists no processes, so that arm reports "
+ "indeterminate."
+ ),
+ ),
+ "run_av_scan": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "Consumes CPU on one host and finishes. Nothing to undo. It is "
+ "automatic, and Defender replies 'Pending' the instant it queues "
+ "the sweep — so the response is the one thing that certainly is "
+ "not the confirmation. The probe reads the machine action's "
+ "terminal state instead, and answers indeterminate while the "
+ "scan is still running, which an immediate post-dispatch check "
+ "almost always is."
+ ),
+ ),
+ "run_script": CapabilityContract(
+ impact=ActionImpact.SEVERE,
+ approval=ApprovalRequirement.MANDATORY_HUMAN,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "There is nothing to probe. The platform cannot know what an "
+ "arbitrary script was supposed to do, so no read-back can confirm it "
+ "did it. The exit code says the script ran, which is a different "
+ "claim. This is why the action is mandatory-human: the approver is "
+ "the verification."
+ ),
+ note=(
+ "Arbitrary code on a production host. The platform cannot reason "
+ "about what a script does, so no confidence score is meaningful and "
+ "no autonomy tier executes it. Classified SEVERE rather than HIGH "
+ "precisely because its blast radius is not knowable in advance."
+ ),
+ ),
+ "capture_forensics": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "Collects an evidence package from one host. The estate is "
+ "unchanged, which is why the impact matches run_av_scan: some "
+ "endpoint CPU and IO, and it finishes on its own. "
+ "Analyst-gated rather than automatic on the same reasoning that "
+ "separated suppress_alert from update_alert_disposition — the "
+ "question is what bounds the verb, not how loud it is. The "
+ "writeback is bounded by a disposition mapping that refuses to "
+ "close a true positive; this one has no bound at all. It collects "
+ "whatever the vendor package contains, from whichever host it is "
+ "pointed at, and the result is a copy of somebody's endpoint — "
+ "processes, registry, event logs, temp files — in a vendor cloud "
+ "behind a download URI. Pointed at the wrong host that is a "
+ "data-handling event nobody can take back, which is also why the "
+ "reversal is manual: an operator deletes the package from the "
+ "console, the copy having already been made. "
+ "The probe is the reason this verb needed one at all: acquisition "
+ "is asynchronous, so the API response is emphatically not the "
+ "confirmation — it says a machine action was queued, and the "
+ "package appears minutes later or never. The probe reads that "
+ "machine action's terminal state and then asks for the download "
+ "URI, so VERIFIED means a package exists and can be fetched. "
+ "Still running answers indeterminate rather than either guess."
+ ),
+ ),
+ # ── Human-in-the-loop ──────────────────────────────────────────────────
+ "chatops_verify": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "There is no vendor state to read back. What this action produces "
+ "is a delivered prompt, and the transport's own response is the "
+ "confirmation of delivery — the case the probe rule waives below "
+ "MODERATE. The thing a probe might want to check, whether the "
+ "person answered, is not a state to poll: the answer arrives as a "
+ "signed callback, and until it does the action reports "
+ "awaiting_completion rather than success."
+ ),
+ note=(
+ "Asks the affected user 'was this you?' and routes the signed "
+ "answer onto the case. Shares notify's impact — a message cannot "
+ "be unsent — but not its approval tier, because notify addresses "
+ "a SOC channel and this addresses the account under "
+ "investigation. Sent automatically on a true positive it tells an "
+ "attacker they have been detected, and the verb has no way to "
+ "know whether the person it is asking is the suspect. That "
+ "missing bound is what makes it analyst-gated."
+ ),
+ ),
+ # ── Identity ───────────────────────────────────────────────────────────
+ "disable_user": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="enable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=True,
+ note="Stops one person working. Reversible, and instantly noticed.",
+ ),
+ "enable_user": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.MANDATORY_HUMAN,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="disable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "No ActionType exists for enable_user. _probe_enable_user is "
+ "implemented and reads the same directory state as the disable probe; "
+ "it is unreachable until the verb has an ActionType."
+ ),
+ note=(
+ "Re-enabling an account is a higher bar than disabling it: the "
+ "failure mode is restoring access to a compromised identity, and "
+ "no model output should be sufficient for that."
+ ),
+ ),
+ "suspend_session": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "Okta removed session listing from the Management API, so there is no "
+ "supported read-back for 'are this user's sessions actually cleared'. "
+ "Entra's revokeSignInSessions has the same shape."
+ ),
+ note=(
+ "Forces re-authentication, and the user restores their own access by "
+ "logging in — cheap enough that automating it is tempting. It is "
+ "analyst-gated anyway, because an unverifiable containment reported as "
+ "successful is the isolate_host failure in miniature: the responder "
+ "believes the session is gone and moves on."
+ ),
+ ),
+ "revoke_session": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "Same absent read-back as suspend_session, stated here rather than "
+ "by reference because a gap that points at another entry stops "
+ "being checkable when that entry changes. Okta withdrew session "
+ "listing from the Management API and Entra's revokeSignInSessions "
+ "returns only an acknowledgement, so neither provider will say "
+ "whether the sessions are gone. The nearest readable field, "
+ "Entra's signInSessionsValidFromDateTime, moves when the call is "
+ "accepted rather than when the tokens stop working, so a probe "
+ "reading it would report VERIFIED on the strength of the same "
+ "acknowledgement the executor already has."
+ ),
+ ),
+ "reset_password": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "Neither Okta nor Entra exposes a readable 'password was reset' state. "
+ "The user's lifecycle status is unchanged by a reset, so a probe "
+ "reading it would confirm nothing and report VERIFIED for a reset that "
+ "never happened — worse than reporting unverified. The obvious "
+ "candidate, Okta's passwordChanged timestamp, is the wrong read and "
+ "not merely a missing one: the executor calls "
+ "lifecycle/reset_password with sendEmail, which issues a recovery "
+ "link. The password changes later, if the user follows it, so a "
+ "probe watching that field would report FAILED for every correctly "
+ "executed reset and VERIFIED only once the user had already "
+ "recovered. Entra's lastPasswordChangeDateTime behaves the same way."
+ ),
+ note="The user recovers through the normal reset flow, but is locked out until they do.",
+ ),
+ "force_mfa": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "'Re-enrolment required' is not a readable flag on either provider — "
+ "the factor list looks the same before and after. A probe reading it "
+ "would report VERIFIED for a reset that never applied."
+ ),
+ note="Re-enrolment friction, not a lockout, but unverifiable and so not automatic.",
+ ),
+ "block_user_signin": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="enable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=False,
+ verification_gap=(
+ "No ActionType exists for block_user_signin, so the verifier cannot be "
+ "reached. The disable_user probe covers the same directory state."
+ ),
+ ),
+ # ── Network ────────────────────────────────────────────────────────────
+ "block_ip": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_ip",
+ required_permission=_NETWORK,
+ has_verification_probe=True,
+ note=(
+ "Blocking a shared egress address, a CDN edge or a SaaS endpoint "
+ "takes out far more than the intended target, and the alert rarely "
+ "says which kind of address it is."
+ ),
+ ),
+ "allow_ip": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_ip",
+ required_permission=_NETWORK,
+ has_verification_probe=True,
+ note="Removing a block is a security decision, so it is not automatic.",
+ ),
+ "block_domain": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_domain",
+ required_permission=_NETWORK,
+ has_verification_probe=False,
+ verification_gap=(
+ "The only registered executor is a generic placeholder with no "
+ "enforcement point to read back from. A real arm (Route 53 Resolver "
+ "DNS Firewall, Umbrella, a DNS RPZ) would expose one; until one is "
+ "wired, claiming verification would certify a block that never "
+ "happened."
+ ),
+ ),
+ "allow_domain": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_domain",
+ required_permission=_NETWORK,
+ ),
+ "block_hash": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_hash",
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "Same absent read as block_ioc, of which this is the narrowest "
+ "case: the indicator API creates and deletes and offers no list "
+ "to compare against. Unlike block_ioc this one is automatic, so "
+ "the gap is load-bearing and worth restating — it has no "
+ "ActionType either, which means a probe could not be keyed to it "
+ "even if Defender grew the read tomorrow."
+ ),
+ note=(
+ "A hash identifies one exact binary, so a wrong block affects only "
+ "that file. The narrowest containment the platform has, and the "
+ "one genuinely safe to automate at high confidence."
+ ),
+ ),
+ "allow_hash": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_hash",
+ required_permission=_CONTAIN,
+ ),
+ "block_ioc": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_ioc",
+ required_permission=_NETWORK,
+ has_verification_probe=False,
+ verification_gap=(
+ "Defender's indicator API is write-only in this client: block_ioc "
+ "creates one and remove_ioc deletes one by id, and there is no read "
+ "of the current indicator set to compare against. Confirming the "
+ "indicator exists would also be the weaker of the two available "
+ "claims — what a responder needs to know is whether it is being "
+ "enforced on the estate, and Defender reports indicator "
+ "distribution nowhere this client can reach."
+ ),
+ note="Breadth depends on the indicator type, so it is classified at the worst case.",
+ ),
+ "allow_ioc": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_ioc",
+ required_permission=_NETWORK,
+ ),
+ # ── SIEM / detection content ───────────────────────────────────────────
+ "create_notable_event": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "The creation is synchronous — Splunk's /services/notable_events "
+ "either writes the notable or returns an error, with no queued "
+ "state in between — so unlike run_av_scan the response really is "
+ "the confirmation. It is also the only one available: the reply "
+ "carries no event_id, and get_notable_event_state needs one. "
+ "Searching the notable index by rule name instead would match any "
+ "notable that rule has ever produced, which is a probe that "
+ "passes without the action."
+ ),
+ note="Writes a record into someone else's queue. Noise, not damage.",
+ ),
+ "sync_detection_rule": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="sync_detection_rule",
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "The client writes correlation searches and watchers through "
+ "create-or-update calls and exposes no read of the saved "
+ "definition, so there is nothing to compare the intended content "
+ "against. Confirming the object merely exists would be the wrong "
+ "check anyway: this verb's failure mode is a rule that saved with "
+ "different content, not one that did not save."
+ ),
+ note=(
+ "Changing detection content in the customer's SIEM can silence a "
+ "rule as easily as add one. Its own reverse: sync the prior version."
+ ),
+ ),
+ "update_watcher": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="update_watcher",
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ verification_gap=(
+ "Same absence as sync_detection_rule, which this is the Elastic "
+ "spelling of: the write goes through a create-or-update and no "
+ "read of the stored watcher comes back to compare against."
+ ),
+ ),
+ "update_alert_disposition": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=True,
+ note=(
+ "Writes a verdict onto a finding in the customer's SIEM. Classified "
+ "the same as create_notable_event and push_status, which it is the "
+ "mirror image of: it changes a queue item, not an estate, and a "
+ "wrong one is re-opened from the vendor console in a click. "
+ "What bounds it is not the approval tier but the disposition "
+ "mapping — a confirmed true positive escalates and is never "
+ "closed, and a verdict outside the taxonomy is refused rather than "
+ "guessed (app/services/disposition_writeback.py). On top of that "
+ "the feature ships dry-run by default: AISOC_SIEM_WRITEBACK_EXECUTE "
+ "is off, so an operator opts in to the vendor call, not out of it. "
+ "The probe re-reads the finding and compares its state against the "
+ "plan the executor derived from the same disposition: Splunk's "
+ "notable status and QRadar's offense status both change observably "
+ "on a close. A QRadar escalation leaves the offense OPEN, which is "
+ "also its prior state, so that combination answers indeterminate "
+ "rather than confirming a write that may not have happened."
+ ),
+ ),
+ # ── Alert lifecycle ────────────────────────────────────────────────────
+ #
+ # Impact is the same as update_alert_disposition, and for the same reason:
+ # these move a queue item, not an estate. The approval tiers differ,
+ # because what bounds the writeback is its disposition mapping and these
+ # two verbs have none — they do what the caller says.
+ "ack_alert": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=True,
+ note=(
+ "Marks a vendor finding in-progress and owned by AiSOC. It removes "
+ "nothing from anyone's view — it says who is already looking, which "
+ "is the point of automating it: two analysts working the same "
+ "notable is the cost of not doing so. The probe reads the notable's "
+ "status back, so the claim is checked rather than inferred from a "
+ "202."
+ ),
+ ),
+ "suppress_alert": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=True,
+ note=(
+ "Closes a vendor finding outright. The impact is a queue item, the "
+ "same as update_alert_disposition — but analyst-gated where that "
+ "one is automatic, because the thing that makes the writeback safe "
+ "to automate is the disposition mapping that refuses to close a "
+ "confirmed true positive, and this verb has no such bound. It "
+ "closes whatever it is pointed at, on the caller's say-so. Prefer "
+ "update_alert_disposition for anything driven by a verdict; this "
+ "exists for an analyst acting deliberately."
+ ),
+ ),
+ # ── Ticketing and notification ─────────────────────────────────────────
+ "create_ticket": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "This is the case the probe rule waives, and it is worth writing "
+ "down rather than leaving as an absence. Jira, ServiceNow and "
+ "PagerDuty all return the identifier they allocated, and none of "
+ "them can allocate one without having created the record — so the "
+ "response is the confirmation, in the strict sense that a "
+ "read-back could not tell us anything the create did not. The "
+ "identifier is also what every later step uses, so a fabricated "
+ "one fails loudly at the next transition rather than passing "
+ "silently."
+ ),
+ ),
+ "push_case": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Creates a record in the ticketing system and gets its identifier "
+ "back, the same as create_ticket: the identifier cannot exist "
+ "without the record."
+ ),
+ ),
+ "push_status": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Updates a record the caller already holds the identifier for, "
+ "and the vendors answer with the transition they applied. No "
+ "ActionType keys this one, so a probe could not be reached for it "
+ "in any case."
+ ),
+ ),
+ "notify": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ has_verification_probe=False,
+ verification_gap=(
+ "Chat platforms return the posted message's timestamp, which is "
+ "the confirmation — they cannot allocate one for a message they "
+ "did not post. Reading the channel back afterwards would answer a "
+ "different question, whether anyone has since deleted it."
+ ),
+ note=("A message cannot be unsent, but paging the wrong channel is embarrassment rather than impact."),
+ ),
+}
+
+
+#: Legacy ``ActionType`` value -> capability name, for the cases where the
+#: two vocabularies chose different words for the same verb.
+#:
+#: Only one entry, and it is a naming gap rather than a missing capability:
+#: the public API verb is ``notify_slack`` (it predates the capability
+#: registry and names the transport), the capability is ``notify`` (it names
+#: the verb, which is the whole point of a per-capability contract), and
+#: ``SlackNotify`` in ``builtins.py`` already bridges them. What was missing
+#: was anything that told a *lookup by ActionType value* about the bridge, so
+#: ``approval_gate`` found no contract, skipped the confidence matrix
+#: entirely and let blast radius decide alone.
+#:
+#: Why an alias and not a rename. ``action_type`` is persisted as free text:
+#: ``remediation_whitelist`` (migration 015) stores operator pre-approvals
+#: keyed ``UNIQUE (tenant_id, action_type)``, so renaming the enum member
+#: silently orphans every row an operator created for ``notify_slack`` —
+#: their pre-approval stops matching and nobody is told. It is also a
+#: documented request field (``{"action_type": "notify_slack"}`` in
+#: ``apps/docs/docs/operations/notifications.md``) and a member of the
+#: ``ActionType`` union in ``packages/types``.
+#:
+#: When to delete this. It retires with ``ActionType`` itself: the enum is
+#: already the legacy half of the registry (every adapter carries a
+#: ``_legacy_action_type`` pointing back at it) and the live-actions path
+#: dispatches on capability strings. When the ``POST /actions`` body takes a
+#: capability and the ``remediation_whitelist`` rows have been migrated,
+#: this map and the enum go together. Until then a new entry here needs the
+#: same justification: a *naming* difference for a verb that already has a
+#: contract, never a stand-in for a capability nobody wrote.
+ACTION_TYPE_CAPABILITY_ALIASES: dict[str, str] = {
+ "notify_slack": "notify",
+}
+
+
+def contract_for_action_type(action_type_value: str) -> CapabilityContract | None:
+ """Resolve a legacy ``ActionType`` value to its capability contract.
+
+ Tries the value as a capability name first, then the alias map. Returns
+ ``None`` when the verb genuinely has no contract, so callers can say so
+ rather than invent an impact for it.
+ """
+ contract = CAPABILITY_CONTRACTS.get(action_type_value)
+ if contract is not None:
+ return contract
+ aliased = ACTION_TYPE_CAPABILITY_ALIASES.get(action_type_value)
+ if aliased is None:
+ return None
+ return CAPABILITY_CONTRACTS.get(aliased)
+
+
+def apply_contract(cls: type) -> type:
+ """Class decorator: stamp the capability's contract onto an executor.
+
+ Used instead of per-class declarations so twenty vendors implementing
+ ``isolate_host`` cannot disagree about how dangerous it is — and the one
+ that disagrees low is the one that auto-executes.
+ """
+ contract = CAPABILITY_CONTRACTS.get(getattr(cls, "capability", ""))
+ if contract is None:
+ # Left with the unsafe defaults, so the conformance gate names it
+ # rather than the action quietly becoming dispatchable.
+ return cls
+ cls.impact = contract.impact
+ cls.approval = contract.approval
+ cls.reversal = contract.reversal
+ cls.reverse_capability = contract.reverse_capability
+ cls.required_permission = contract.required_permission
+ cls.has_verification_probe = contract.has_verification_probe
+ cls.verification_gap = contract.verification_gap
+ return cls
diff --git a/services/api/app/_vendor/action_contracts/contract.py b/services/api/app/_vendor/action_contracts/contract.py
new file mode 100644
index 000000000..863b08dbc
--- /dev/null
+++ b/services/api/app/_vendor/action_contracts/contract.py
@@ -0,0 +1,304 @@
+"""The action contract: what every response action must declare about itself.
+
+Pillar 3. An action registry is only as good as what it can tell you *before*
+it runs. Today an executor declares four things — vendor, capability, whether
+it needs credentials, and a description — and everything that actually
+governs execution is inferred elsewhere or not at all:
+
+* risk is inferred from the capability name in one place and from a policy
+ table in another, and the two can disagree
+* reversibility is not declared, so the rollback path has a hardcoded list of
+ four actions and nothing tells you whether a fifth is reversible
+* verification is not declared, so an action reports success on an HTTP 200
+ and nobody knows whether a probe exists to check the effect landed
+* nothing distinguishes "needs approval" from "no tier may ever auto-execute
+ this"
+
+This module makes all of it declarative, and
+``scripts/check_action_contract.py`` makes it enforced. The point is not
+tidiness: the gap between "the API returned 200" and "the host is actually
+contained" is how a SOC comes to believe it responded when it did not.
+
+Adding a field here is a breaking change for every executor, which is
+deliberate. An action that cannot say what it does to a production estate
+should not be dispatchable.
+"""
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class ActionImpact(str, Enum):
+ """What this action does to the estate if it is wrong.
+
+ Impact is a property of the action, not of the confidence in the
+ finding. The two are combined by the approval matrix; conflating them is
+ how "we were 99% sure" becomes justification for an irreversible action.
+ """
+
+ #: Reads only. No state changes anywhere.
+ READ_ONLY = "read_only"
+
+ #: Changes state, trivially undone, no user-visible disruption.
+ #: Blocking a known-bad hash; adding a watchlist entry.
+ LOW = "low"
+
+ #: Disrupts one user or one process. Reversible in seconds.
+ #: Killing a process; revoking a session.
+ MODERATE = "moderate"
+
+ #: Disrupts one person's ability to work, or one host's connectivity.
+ #: Reversible, but someone notices immediately.
+ #: Disabling an account; isolating a workstation.
+ HIGH = "high"
+
+ #: Disrupts a service other people depend on. Reversible in principle,
+ #: but the outage is real while it lasts.
+ #: Isolating a production server; blocking a shared egress address.
+ SEVERE = "severe"
+
+ #: Cannot be undone. Deleting a resource; rotating a key whose old value
+ #: is gone. No autonomy tier may execute these, ever.
+ IRREVERSIBLE = "irreversible"
+
+
+class ApprovalRequirement(str, Enum):
+ """Who, if anyone, must sign off before this executes."""
+
+ #: Safe to run without asking, subject to the tenant's autonomy tier.
+ AUTOMATIC = "automatic"
+
+ #: Requires an analyst approval, recorded with the approving principal.
+ ANALYST = "analyst"
+
+ #: Requires a human regardless of confidence or tier. Not "a high bar" —
+ #: an actual floor that autonomy cannot lift.
+ MANDATORY_HUMAN = "mandatory_human"
+
+ #: No path executes this from the platform. Present in the vocabulary so
+ #: an action can be *declared* prohibited rather than merely unimplemented,
+ #: which is the difference between a control and an absence.
+ PROHIBITED = "prohibited"
+
+
+#: Impact tiers that no autonomy level may auto-execute, whatever the
+#: confidence. Kept as data rather than an `if` so the gate can assert it.
+NEVER_AUTONOMOUS: frozenset[ActionImpact] = frozenset({ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE})
+
+
+class Reversal(str, Enum):
+ """How the effect of an action is undone, if it can be.
+
+ "Reversible" is not one thing, and collapsing it into a boolean forces
+ wrong answers. Killing a process cannot be un-killed, but the effect does
+ not persist — the service restarts, or the user runs the program again.
+ Isolating a host persists until something un-isolates it. Those need
+ different handling and a different conversation with an approver.
+ """
+
+ #: Nothing to undo; the action changed no state.
+ NOT_APPLICABLE = "not_applicable"
+
+ #: The platform can undo it by dispatching ``reverse_capability``.
+ PLATFORM = "platform"
+
+ #: The effect does not persist: a killed process can be restarted, a
+ #: cleared session can be re-established by logging in. Disruptive at the
+ #: moment it happens, gone shortly after, with no operator action needed.
+ SELF_HEALING = "self_healing"
+
+ #: Persists and the platform cannot undo it. An operator has to undo it
+ #: by hand, during an incident, from a runbook they have not read.
+ MANUAL_ONLY = "manual_only"
+
+ #: Cannot be undone by anyone.
+ NONE = "none"
+
+
+#: Impact tiers that must declare *some* route back. Not necessarily a
+#: platform reverse: self-healing is an honest answer for a killed process.
+#: MANUAL_ONLY at these tiers is what the gate rejects, because an action
+#: that disrupts a person or a service and leaves no route back is one
+#: somebody has to fix by hand at 3am.
+MUST_HAVE_A_ROUTE_BACK: frozenset[ActionImpact] = frozenset({ActionImpact.MODERATE, ActionImpact.HIGH, ActionImpact.SEVERE})
+
+#: Backwards-compatible alias; the gate imports this name.
+MUST_BE_REVERSIBLE = MUST_HAVE_A_ROUTE_BACK
+
+
+_IMPACT_ORDER: tuple[ActionImpact, ...] = (
+ ActionImpact.READ_ONLY,
+ ActionImpact.LOW,
+ ActionImpact.MODERATE,
+ ActionImpact.HIGH,
+ ActionImpact.SEVERE,
+ ActionImpact.IRREVERSIBLE,
+)
+
+
+def _impact_rank(impact: ActionImpact) -> int:
+ return _IMPACT_ORDER.index(impact)
+
+
+class ActionContract:
+ """Declarative contract mixed into every ``LiveActionExecutor``.
+
+ Every field has a deliberately unsafe default. An executor that forgets
+ to declare its impact is treated as irreversible and prohibited, so the
+ omission fails closed and the conformance gate names it — rather than the
+ action quietly defaulting to "safe to auto-execute".
+ """
+
+ #: What this does to the estate if the finding is wrong.
+ impact: ActionImpact = ActionImpact.IRREVERSIBLE
+
+ #: Baseline approval requirement. The tenant's autonomy policy and the
+ #: confidence matrix can raise this but never lower it.
+ approval: ApprovalRequirement = ApprovalRequirement.PROHIBITED
+
+ #: JSON schema for ``LiveActionRequest.params``. Used to validate before
+ #: dispatch and to render the approval UI, so an approver sees what they
+ #: are approving rather than an opaque dict.
+ parameters_schema: dict = {} # noqa: RUF012 - overridden per executor
+
+ #: RBAC permission the invoking principal must hold. Enforced by the
+ #: dispatcher; declared here so the gate can assert every state-changing
+ #: action has one.
+ required_permission: str = ""
+
+ #: How the effect is undone. Defaults to NONE so an undeclared action
+ #: fails closed.
+ reversal: Reversal = Reversal.NONE
+
+ #: Capability that undoes this one, e.g. ``unisolate_host`` for
+ #: ``isolate_host``. Required when and only when ``reversal`` is PLATFORM.
+ reverse_capability: str = ""
+
+ #: Whether a post-action probe exists that reads the vendor's state to
+ #: confirm the effect landed. Without one, "succeeded" means "the API
+ #: accepted the request", which is not the same claim.
+ has_verification_probe: bool = False
+
+ #: Why no probe exists, for an action disruptive enough to need one.
+ #: Required when a HIGH or SEVERE action declares no probe, so the
+ #: absence is a recorded decision rather than an omission nobody
+ #: noticed. Some vendors genuinely expose no read-back; that is an
+ #: acceptable answer and an unacceptable silence.
+ verification_gap: str = ""
+
+ #: Whether ``execute()`` honours ``dry_run`` by making no state change.
+ #: Declared rather than assumed because a dry run that still calls the
+ #: vendor has happened here before.
+ supports_dry_run: bool = True
+
+ @classmethod
+ def contract_violations(cls) -> list[str]:
+ """Self-check. Returns the ways this declaration is inconsistent.
+
+ Called by the conformance gate for every registered executor, and
+ usable directly in a plugin author's own tests.
+ """
+ problems: list[str] = []
+ impact = cls.impact
+ approval = cls.approval
+
+ if impact == ActionImpact.READ_ONLY:
+ # A read that requires approval is either mis-classified or is
+ # not actually a read.
+ if approval in (ApprovalRequirement.MANDATORY_HUMAN, ApprovalRequirement.PROHIBITED):
+ problems.append(f"impact is read_only but approval is {approval.value}; a read that nobody may perform is mis-classified")
+ return problems
+
+ if not cls.required_permission:
+ problems.append("state-changing action declares no required_permission, so the dispatcher has nothing to authorise against")
+
+ # The route-back requirement exists to bound *autonomous* damage. An
+ # action a human must personally approve is one where the approver is
+ # accepting the irreversibility knowingly, which is a legitimate
+ # declared posture — running an RTR script is the example. Actions
+ # that can execute without a human still need a way back.
+ human_gated = approval in (
+ ApprovalRequirement.MANDATORY_HUMAN,
+ ApprovalRequirement.PROHIBITED,
+ )
+
+ if (
+ impact in MUST_HAVE_A_ROUTE_BACK
+ and not human_gated
+ and cls.reversal in (Reversal.NONE, Reversal.MANUAL_ONLY, Reversal.NOT_APPLICABLE)
+ ):
+ problems.append(
+ f"impact is {impact.value} but reversal is {cls.reversal.value}; "
+ f"an action that disrupts a person or a service must either be "
+ f"undoable by the platform or self-healing, otherwise somebody "
+ f"undoes it by hand during an incident"
+ )
+
+ if cls.reversal == Reversal.PLATFORM and not cls.reverse_capability:
+ problems.append("reversal is 'platform' but no reverse_capability is named, so the rollback path has nothing to dispatch")
+
+ if cls.reversal != Reversal.PLATFORM and cls.reverse_capability:
+ problems.append(
+ f"reverse_capability {cls.reverse_capability!r} is declared but "
+ f"reversal is {cls.reversal.value}; the rollback path would not use it"
+ )
+
+ if impact in NEVER_AUTONOMOUS and approval == ApprovalRequirement.AUTOMATIC:
+ problems.append(
+ f"impact is {impact.value} but approval is automatic; no autonomy tier may auto-execute this regardless of confidence"
+ )
+
+ # A probe is required wherever the effect is mechanically checkable.
+ # It is waived only for a human-gated action whose effect is not — you
+ # cannot probe whether an arbitrary script did the right thing, and the
+ # human who approved it is watching. HIGH impact is never waived: that
+ # is the containment tier, where believing a host is contained when it
+ # is not is the specific failure this contract exists to prevent.
+ # An action that can execute without a human *and* disrupts something
+ # must be verifiable: nothing else is checking, so "the API returned
+ # 200" becomes the whole of the evidence.
+ #
+ # Scoped to MODERATE and above on purpose. Creating a ticket or
+ # posting a message returns the created object's id, so the response
+ # genuinely is the confirmation — demanding a second read there would
+ # be ceremony, and a rule that fires on cases nobody can act on is a
+ # rule people learn to suppress.
+ if (
+ approval == ApprovalRequirement.AUTOMATIC
+ and _impact_rank(impact) >= _impact_rank(ActionImpact.MODERATE)
+ and not cls.has_verification_probe
+ ):
+ # Unverifiable means not autonomous. A verification_gap explains
+ # why no probe exists; it does not buy back the right to execute
+ # without anyone checking. Downgrade the action to analyst
+ # approval and the contract is coherent again.
+ problems.append(
+ "approval is automatic at "
+ f"{impact.value} impact with no verification probe. Nothing would "
+ "check the effect, so the action certifies itself. Either add a "
+ "probe or require analyst approval — an unverifiable action is not "
+ "an autonomous one, whatever the confidence."
+ )
+
+ # For the containment tiers, an absent probe is allowed but must be
+ # explained. Some vendors genuinely expose no read-back — that is an
+ # acceptable answer. Silence is not, because an omission and a
+ # deliberate decision look identical afterwards, and this is the
+ # claim the whole contract exists to make trustworthy.
+ if impact in (ActionImpact.HIGH, ActionImpact.SEVERE) and not cls.has_verification_probe and not cls.verification_gap.strip():
+ problems.append(
+ f"impact is {impact.value} and no verification probe is declared, "
+ f"with no verification_gap explaining why. The action would report "
+ f"success on an accepted request with nothing checking the effect — "
+ f"which is how a SOC comes to believe a host is contained when it is "
+ f"not. State the reason if the vendor offers no read-back."
+ )
+
+ if not cls.supports_dry_run and approval != ApprovalRequirement.PROHIBITED:
+ problems.append("action does not support dry_run, so it cannot be previewed or exercised in copilot mode")
+
+ if cls.parameters_schema and not isinstance(cls.parameters_schema, dict):
+ problems.append("parameters_schema must be a JSON-schema object")
+
+ return problems
diff --git a/services/api/app/api/v1/endpoints/autonomy_policy.py b/services/api/app/api/v1/endpoints/autonomy_policy.py
index 9ce77dcde..f4cec0543 100644
--- a/services/api/app/api/v1/endpoints/autonomy_policy.py
+++ b/services/api/app/api/v1/endpoints/autonomy_policy.py
@@ -12,6 +12,25 @@ This module manages the **DB tenant overrides** layer. Reads return the
*effective* policy after merging defaults + DB so the admin UI can show a
single coherent view; writes only persist to the DB layer.
+Those thresholds are not the control that gates execution, and the response
+says so
+=============================================================================
+
+``aisoc_autonomy_thresholds`` is read by
+``services/agents/app/policy/guardrails.py`` and by nothing on a production
+path — ``services/agents/app/closure/policy.py`` records that in its own
+words. A response verb reaches a vendor through ``services/actions``, which
+grades it on the tenant's L0–L4 maturity tier and the verb's capability
+contract.
+
+The console had no way to tell the difference and inferred one: an ``auto``
+threshold below 1.0 meant the action auto-executed. All nineteen shipped
+defaults are below 1.0, so a stock install announced
+"Autopilot — 7 high-blast actions auto-execute" while its dispatcher, at the
+default L1, queued every one of them for a human. Every read therefore now
+carries an ``effective`` block and per-action verdicts resolved from the real
+control by ``app/services/autonomy_effective.py``.
+
All endpoints are tenant-scoped and require ``settings:read`` /
``settings:write`` permissions (typically held only by the ``tenant_admin``
role — see ``services/api/app/core/security.py``).
@@ -31,6 +50,12 @@ from starlette.convertors import Convertor, register_url_convertor
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_effective import (
+ ActionAutonomy,
+ EffectiveTier,
+ grade_action,
+ resolve_effective_tier,
+)
from app.services.autonomy_grants import (
GrantScopeError,
list_grants,
@@ -201,10 +226,53 @@ class ActionPolicy(BaseModel):
last_updated_by: str | None = None
last_reason: str | None = None
+ # ── What actually happens to this verb, as opposed to what the
+ # thresholds above describe. See `app/services/autonomy_effective.py`.
+ #: The capability it resolves to in the action registry, or null when no
+ #: executor is registered under this name. `delete_object` is the one
+ #: that matters: it is critical-blast in the table above, it is not an
+ #: `ActionType`, it has no contract and no executor, and the page used to
+ #: count it among the verbs running unattended.
+ capability: str | None = None
+ executable: bool = False
+ #: Whether this verb reaches a vendor without a human on this deployment.
+ effective_auto_execute: bool = False
+ #: The same question at L4. False here means no tier, no `force_auto`
+ #: override and no earned grant can make it unattended, because a
+ #: contract floor may be raised and never lowered.
+ auto_executes_at_any_tier: bool = False
+ #: The ceiling applied to this verb, which an override or an earned grant
+ #: can raise above the tenant's own tier.
+ effective_tier: str
+ effective_reason: str
+
+
+class EffectiveAutonomy(BaseModel):
+ """The control that actually gates execution, as the console must show it."""
+
+ tier: str
+ tier_label: str
+ #: `tenant_policy`, `environment`, or `unreadable_policy_floor`.
+ tier_source: str
+ #: Highest impact this tier executes without an analyst; null at L0.
+ max_automatic_impact: str | None
+ auto_executing_actions: list[str]
+ high_blast_auto_executing: list[str]
+ #: Verbs in the table below with no registered executor.
+ unimplemented_actions: list[str]
+ #: Always true today, and stated rather than implied: nothing in the
+ #: dispatch path reads `aisoc_autonomy_thresholds`. The only reader is
+ #: `services/agents/app/policy/guardrails.py`, which no production path
+ #: imports. Leaving the page silent about that is what let a column of
+ #: editable sliders read as a live control.
+ thresholds_are_advisory: bool
+ advisory_note: str
+
class AutonomyPolicyResponse(BaseModel):
tenant_id: str
actions: list[ActionPolicy]
+ effective: EffectiveAutonomy
class ThresholdUpdateRequest(BaseModel):
@@ -310,6 +378,28 @@ def _row_to_triple(row: dict) -> ThresholdTriple:
# ---------------------------------------------------------------------------
+#: Blast radii a CISO is asking about when they ask whether the SOC acts on
+#: its own. Mirrors the set the console used to flip its posture badge on.
+_HIGH_BLAST = frozenset({"high", "critical"})
+
+_ADVISORY_NOTE = (
+ "These thresholds are advisory: nothing in the response path reads them yet. "
+ "What gates execution is the autonomy tier below plus each action's capability contract."
+)
+
+
+def _autonomy_fields(verdict: ActionAutonomy) -> dict[str, object]:
+ """The effective-posture half of an ``ActionPolicy``, built once."""
+ return {
+ "capability": verdict.capability,
+ "executable": verdict.executable,
+ "effective_auto_execute": verdict.auto_executes,
+ "auto_executes_at_any_tier": verdict.auto_executes_at_any_tier,
+ "effective_tier": verdict.tier,
+ "effective_reason": verdict.reason,
+ }
+
+
@router.get("", response_model=AutonomyPolicyResponse)
async def get_autonomy_policy(
user: AuthUser,
@@ -320,16 +410,26 @@ async def get_autonomy_policy(
For each known action we surface the merged thresholds (defaults + DB
overrides), the hard-coded defaults, and an ``overridden`` flag the UI
uses to render a "modified from default" badge.
+
+ Every action also carries whether it would *actually* execute without a
+ human, resolved from the tenant's maturity tier and the verb's capability
+ contract by ``app/services/autonomy_effective.py``. The thresholds and
+ that answer are different facts, and the console previously derived the
+ second from the first: a threshold below 1.0 was read as "auto-executes",
+ which on stock defaults made nineteen of nineteen actions autonomous and
+ put an Autopilot badge on a deployment that queues all of them.
"""
await user.require_permission_db("settings:read", db)
overrides = await _fetch_overrides(db, str(user.tenant_id))
+ effective: EffectiveTier = await resolve_effective_tier(db, str(user.tenant_id))
actions: list[ActionPolicy] = []
seen: set[str] = set()
for action in _DEFAULTS:
seen.add(action)
defaults = _default_triple(action)
+ autonomy = _autonomy_fields(grade_action(action, effective))
row = overrides.get(action)
if row is not None:
thresholds = _row_to_triple(row)
@@ -344,6 +444,7 @@ async def get_autonomy_policy(
last_updated_at=row["updated_at"].isoformat() if row.get("updated_at") else None,
last_updated_by=row.get("updated_by"),
last_reason=row.get("reason"),
+ **autonomy,
)
)
else:
@@ -354,6 +455,7 @@ async def get_autonomy_policy(
thresholds=defaults,
default_thresholds=defaults,
overridden=False,
+ **autonomy,
)
)
@@ -374,11 +476,26 @@ async def get_autonomy_policy(
last_updated_at=row["updated_at"].isoformat() if row.get("updated_at") else None,
last_updated_by=row.get("updated_by"),
last_reason=row.get("reason"),
+ **_autonomy_fields(grade_action(action, effective)),
)
)
actions.sort(key=lambda a: (a.blast_radius, a.action))
- return AutonomyPolicyResponse(tenant_id=str(user.tenant_id), actions=actions)
+ return AutonomyPolicyResponse(
+ tenant_id=str(user.tenant_id),
+ actions=actions,
+ effective=EffectiveAutonomy(
+ tier=effective.tier,
+ tier_label=effective.label,
+ tier_source=effective.source,
+ max_automatic_impact=effective.max_automatic_impact,
+ auto_executing_actions=[a.action for a in actions if a.effective_auto_execute],
+ high_blast_auto_executing=[a.action for a in actions if a.effective_auto_execute and a.blast_radius in _HIGH_BLAST],
+ unimplemented_actions=[a.action for a in actions if not a.executable],
+ thresholds_are_advisory=True,
+ advisory_note=_ADVISORY_NOTE,
+ ),
+ )
@router.put("/{action:autonomy_action}", response_model=ThresholdUpdateResponse)
diff --git a/services/api/app/services/autonomy_effective.py b/services/api/app/services/autonomy_effective.py
new file mode 100644
index 000000000..37ccc61f0
--- /dev/null
+++ b/services/api/app/services/autonomy_effective.py
@@ -0,0 +1,296 @@
+"""What the console may truthfully say about autonomy.
+
+The autonomy settings page used to answer "does this action auto-execute"
+from the per-action confidence thresholds it edits: an ``auto`` threshold
+below 1.0 meant some confidence level let the agent act, so the action
+auto-executed. Nineteen of nineteen shipped defaults are below 1.0 and seven
+of them are high- or critical-blast, so a stock install opened on
+**"Autopilot — 7 high-blast actions auto-execute"**.
+
+Nothing about that was true, and the reason is worth stating precisely
+because the shape recurs.
+
+*The table the page edits has no production reader.* ``aisoc_autonomy_thresholds``
+is read by ``services/agents/app/policy/guardrails.py``, which no production
+path imports — ``services/agents/app/closure/policy.py`` says so in its own
+words. A threshold written here changes nothing today.
+
+*The control that does gate execution is somewhere else entirely.* A response
+verb reaches a vendor through ``services/actions``, which grades it on the
+tenant's L0–L4 maturity tier and the verb's own capability contract. The
+deployment default is L1, which auto-executes nothing above a read, and every
+containment verb's contract declares ``analyst`` — so the dispatcher queues
+every one of those seven for a human.
+
+So this module answers the question from the control that actually decides.
+``evaluate_contract`` here is the same function the dispatcher calls; it
+reaches it through ``app/_vendor/action_contracts/``, a byte-identical mirror
+kept in step by ``scripts/sync_vendored_action_contracts.py --check``. A
+second implementation would drift, and the drift is the defect.
+
+Two deliberate choices about how the question is asked:
+
+**Confidence is pinned at 1.0.** The console is not grading a finding; it is
+describing a posture. Asking at the most permissive confidence any decision
+could carry makes a "no" the strongest available statement: not "this did not
+clear the bar today" but "nothing clears the bar".
+
+**Two answers, not one.** ``auto_executes`` is the answer at the ceiling this
+tenant currently has. ``auto_executes_at_any_tier`` asks the same question at
+L4, the top of the ladder. The second is what makes the copilot claim
+defensible, because it is immune to a tier change, a ``force_auto`` override
+and an earned grant alike: a contract floor may be raised and never lowered.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any
+
+import structlog
+from sqlalchemy import text
+
+from app._vendor.action_contracts import (
+ CAPABILITY_CONTRACTS,
+ TIER_LABELS,
+ TIER_MAX_AUTOMATIC,
+ TIER_ORDER,
+ evaluate_contract,
+)
+from app._vendor.action_contracts.approval_rules import (
+ DEFAULT_TIER,
+ EARNED_TIER_CEILING_LABEL,
+ tier_from_env_value,
+)
+
+logger = structlog.get_logger(__name__)
+
+#: Same variable ``services/actions`` reads. See :func:`resolve_effective_tier`
+#: for what it can and cannot tell us.
+TIER_ENV = "AISOC_MATURITY_TIER"
+
+#: Tier used when a policy row exists and cannot be read. Mirrors
+#: ``tenant_policy.UNREADABLE_POLICY_FLOOR``: if a per-tenant policy may exist
+#: and we cannot read it, inheriting a possibly-more-permissive default is how
+#: a page comes to claim autonomy nobody authorised.
+UNREADABLE_POLICY_FLOOR = DEFAULT_TIER
+
+#: Where the tier came from, in the vocabulary ``TenantPolicy.source`` uses.
+SOURCE_TENANT_POLICY = "tenant_policy"
+SOURCE_ENVIRONMENT = "environment"
+SOURCE_UNREADABLE = "unreadable_policy_floor"
+
+
+@dataclass(frozen=True)
+class EffectiveTier:
+ """The autonomy ceiling in force, and where it came from."""
+
+ tier: str
+ label: str
+ source: str
+ #: Highest impact this tier executes without an analyst. ``None`` at L0,
+ #: which executes nothing at all — not even a read.
+ max_automatic_impact: str | None
+ action_overrides: dict[str, Any] = field(default_factory=dict)
+ #: Verbs holding a standing ``auto_execute`` grant. These lift the ceiling
+ #: to L3 for that verb alone.
+ earned_verbs: frozenset[str] = frozenset()
+
+
+@dataclass(frozen=True)
+class ActionAutonomy:
+ """Whether one named action can reach a vendor without a human."""
+
+ #: The capability it resolves to in the action registry, or ``None`` when
+ #: no executor is registered under this name.
+ capability: str | None
+ executable: bool
+ auto_executes: bool
+ auto_executes_at_any_tier: bool
+ #: The ceiling applied to this action specifically, which an override or
+ #: an earned grant can raise above the tenant's own tier.
+ tier: str
+ reason: str
+
+
+def _tier_rank(tier: str) -> int:
+ return TIER_ORDER.index(tier) if tier in TIER_ORDER else 0
+
+
+def _as_dict(value: Any) -> dict[str, Any]:
+ """JSONB arrives as a dict on asyncpg and as a string on some drivers."""
+ if isinstance(value, str):
+ try:
+ value = json.loads(value)
+ except ValueError:
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _effective(tier: str, source: str, **rest: Any) -> EffectiveTier:
+ ceiling = TIER_MAX_AUTOMATIC.get(tier)
+ return EffectiveTier(
+ tier=tier,
+ label=TIER_LABELS.get(tier, tier),
+ source=source,
+ max_automatic_impact=ceiling.value if ceiling is not None else None,
+ **rest,
+ )
+
+
+def tier_from_environment() -> EffectiveTier:
+ """The deployment-wide tier, parsed the way the dispatcher parses it.
+
+ One caveat is worth being plain about on the page as well as here: this
+ reads *this process's* environment. ``AISOC_MATURITY_TIER`` is set per
+ container, so an operator who exports it for the actions service alone
+ would see the default here. No compose file, Helm value or Terraform
+ default in this repository sets it, so the two agree out of the box — and
+ a tenant that has chosen a tier in the console has a row, which is read
+ first and is not subject to this at all.
+ """
+ raw = os.environ.get(TIER_ENV, "")
+ tier, recognised = tier_from_env_value(raw)
+ if not recognised:
+ logger.warning("autonomy_effective.bad_tier_env", value=raw.strip().upper())
+ return _effective(tier, SOURCE_ENVIRONMENT)
+
+
+async def _earned_verbs(db: Any, tenant_id: str) -> frozenset[str]:
+ """Verbs this tenant has earned the right to run unattended.
+
+ Read without re-checking the evidence behind each grant, which
+ ``tenant_policy._load_earned_verbs`` does before the dispatcher honours
+ one. That makes this *more* generous than the dispatcher, which is the
+ correct direction for a display: a page that omits a grant would tell an
+ operator a human signs off on something that in fact runs by itself.
+ """
+ try:
+ rows = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT scope_key
+ FROM aisoc_autonomy_grants
+ WHERE tenant_id = :tenant_id
+ AND state = 'granted'
+ AND scope_kind = 'action_verb'
+ AND capability = 'auto_execute'
+ """
+ ),
+ {"tenant_id": str(tenant_id)},
+ )
+ )
+ .mappings()
+ .all()
+ )
+ except Exception as exc: # noqa: BLE001 — an unreadable grant list is not a tier failure
+ logger.warning("autonomy_effective.grants_unreadable", tenant_id=str(tenant_id), error=str(exc)[:300])
+ return frozenset()
+ return frozenset(str(row["scope_key"]) for row in rows)
+
+
+async def resolve_effective_tier(db: Any, tenant_id: str) -> EffectiveTier:
+ """Resolve the autonomy ceiling in the same order ``services/actions`` does.
+
+ Tenant policy row, then the deployment environment, then a conservative
+ floor when a row may exist and cannot be read. Written against the same
+ table ``tenant_policy._load_from_store`` reads — ``remediation_maturity``,
+ which this service owns the write path for behind
+ ``PUT /api/v1/remediation/config`` — so the console is reading the row the
+ dispatcher will act on rather than a copy of it.
+ """
+ try:
+ row = (
+ (
+ await db.execute(
+ text("SELECT maturity_tier, action_overrides FROM remediation_maturity WHERE tenant_id = :tenant_id"),
+ {"tenant_id": str(tenant_id)},
+ )
+ )
+ .mappings()
+ .first()
+ )
+ except Exception as exc: # noqa: BLE001 — never inherit a permissive default on error
+ logger.warning("autonomy_effective.policy_unreadable", tenant_id=str(tenant_id), error=str(exc)[:300])
+ return _effective(UNREADABLE_POLICY_FLOOR, SOURCE_UNREADABLE)
+
+ earned = await _earned_verbs(db, tenant_id)
+
+ if row is None:
+ base = tier_from_environment()
+ return _effective(base.tier, base.source, earned_verbs=earned)
+
+ level = row["maturity_tier"]
+ if not isinstance(level, int) or not 0 <= level < len(TIER_ORDER):
+ # A tier outside the ladder is a corrupt row, not a posture. The
+ # dispatcher raises here and lands on its own floor; so do we.
+ logger.warning("autonomy_effective.tier_out_of_range", tenant_id=str(tenant_id), value=str(level)[:40])
+ return _effective(UNREADABLE_POLICY_FLOOR, SOURCE_UNREADABLE, earned_verbs=earned)
+
+ return _effective(
+ TIER_ORDER[level],
+ SOURCE_TENANT_POLICY,
+ action_overrides=_as_dict(row["action_overrides"]),
+ earned_verbs=earned,
+ )
+
+
+#: Said once rather than per action, because fifteen of the nineteen shipped
+#: threshold rows land on it and a reader should recognise the same sentence.
+NO_EXECUTOR_REASON = "No response capability is registered under this name, so no dispatch path runs it. These thresholds are advisory."
+
+
+def grade_action(action: str, effective: EffectiveTier) -> ActionAutonomy:
+ """Would *action* reach a vendor without a human, on this deployment?
+
+ The answer comes from ``evaluate_contract`` — the function both dispatch
+ doors call — so the page cannot disagree with the product without the
+ byte-comparison gate failing first.
+ """
+ contract = CAPABILITY_CONTRACTS.get(action)
+ if contract is None:
+ return ActionAutonomy(
+ capability=None,
+ executable=False,
+ auto_executes=False,
+ auto_executes_at_any_tier=False,
+ tier=effective.tier,
+ reason=NO_EXECUTOR_REASON,
+ )
+
+ override = _as_dict(effective.action_overrides.get(action))
+ if override.get("block"):
+ return ActionAutonomy(
+ capability=action,
+ executable=True,
+ auto_executes=False,
+ auto_executes_at_any_tier=False,
+ tier=effective.tier,
+ reason="Blocked by a tenant policy override. No tier or confidence executes it.",
+ )
+
+ # An override is a human writing down a decision about one verb, so it
+ # lifts the ceiling to the top of the ladder; an earned grant is an
+ # inference from triage agreement and stops at L3. Both raise the ceiling
+ # only — the contract's own floor still applies underneath.
+ tier = effective.tier
+ if override.get("force_auto"):
+ tier = TIER_ORDER[-1]
+ elif action in effective.earned_verbs and _tier_rank(tier) < _tier_rank(EARNED_TIER_CEILING_LABEL):
+ tier = EARNED_TIER_CEILING_LABEL
+
+ now = evaluate_contract(contract=contract, confidence=1.0, tier=tier)
+ ever = evaluate_contract(contract=contract, confidence=1.0, tier=TIER_ORDER[-1])
+
+ return ActionAutonomy(
+ capability=action,
+ executable=True,
+ auto_executes=now.can_auto_execute,
+ auto_executes_at_any_tier=ever.can_auto_execute,
+ tier=tier,
+ reason=now.reason,
+ )
diff --git a/services/api/tests/test_autonomy_effective_posture.py b/services/api/tests/test_autonomy_effective_posture.py
new file mode 100644
index 000000000..915120b01
--- /dev/null
+++ b/services/api/tests/test_autonomy_effective_posture.py
@@ -0,0 +1,225 @@
+"""Issue #1243: the autonomy page described a posture the product does not have.
+
+``GET /api/v1/autonomy-policy`` returned nineteen per-action confidence
+thresholds and nothing else. The console inferred "this action auto-executes"
+from ``thresholds.auto < 1``, every shipped default is below 1.0, and seven of
+the nineteen are high- or critical-blast — so a fresh install rendered
+**"Autopilot · 7 high-blast actions auto-execute"**.
+
+Nothing in the response path reads those thresholds. A response verb is graded
+by ``services/actions`` on the tenant's L0-L4 maturity tier and the verb's own
+capability contract; the deployment default is L1, which auto-executes nothing
+above a read, and every containment verb declares ``analyst``. The dispatcher
+queues all seven.
+
+These tests assert the endpoint reports the control that actually decides.
+
+Two things they are careful about:
+
+*They fail on the pre-fix tree for the defect, not for an import.* Only
+``autonomy_policy``, ``CurrentUser`` and ``get_db`` are imported, all of which
+exist on both sides. A run against the previous module fails because the
+response carries no ``effective`` block and no per-action verdict.
+
+*They assert the two answers differ.* ``test_a_reachable_threshold_is_not_an_
+auto_execution`` fails if somebody wires the effective verdict back to the
+threshold, which is the specific regression that would restore the bug while
+leaving every field name in place.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import uuid
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints import autonomy_policy
+
+TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")
+
+#: The seven rows the console counted as unattended containment. Named rather
+#: than derived from ``_BLAST_RADIUS`` so a future edit that quietly drops one
+#: from the table does not also drop it from the assertion.
+HIGH_BLAST_ACTIONS = (
+ "block_ip",
+ "delete_object",
+ "disable_user_account",
+ "firewall_rule_add",
+ "firewall_rule_remove",
+ "isolate_host",
+ "quarantine_file",
+)
+
+#: Threshold rows whose verb has no executor anywhere in the tree. The one
+#: issue #1243 names explicitly is ``delete_object``: critical blast radius, no
+#: ``ActionType``, no capability contract, no executor — and it was being
+#: counted among the verbs running unattended.
+VERBS_WITH_NO_EXECUTOR = ("delete_object", "firewall_rule_add", "firewall_rule_remove")
+
+
+def _result(*, mappings_all: list[Any] | None = None, mappings_first: Any = None) -> MagicMock:
+ result = MagicMock()
+ mappings = MagicMock()
+ mappings.all = MagicMock(return_value=list(mappings_all or []))
+ mappings.first = MagicMock(return_value=mappings_first)
+ result.mappings = MagicMock(return_value=mappings)
+ # The RBAC lookup in `require_permission_db` reads rows directly; an empty
+ # list sends it to the static role map, where `tenant_admin` holds
+ # `settings:read`.
+ result.all = MagicMock(return_value=[])
+ return result
+
+
+def _db(*, maturity_row: dict[str, Any] | None = None, granted_verbs: tuple[str, ...] = ()) -> AsyncMock:
+ """A session that answers the three statements this handler issues."""
+
+ async def execute(statement: Any, params: Any = None) -> MagicMock:
+ sql = str(statement)
+ if "remediation_maturity" in sql:
+ return _result(mappings_first=maturity_row)
+ if "aisoc_autonomy_grants" in sql:
+ return _result(mappings_all=[{"scope_key": verb} for verb in granted_verbs])
+ if "aisoc_autonomy_thresholds" in sql:
+ return _result(mappings_all=[])
+ return _result()
+
+ db = AsyncMock()
+ db.execute = AsyncMock(side_effect=execute)
+ db.commit = AsyncMock()
+ db.rollback = AsyncMock()
+ return db
+
+
+def _policy(**kwargs: Any) -> dict[str, Any]:
+ user = CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role="tenant_admin", email="[email protected]")
+ response = asyncio.run(autonomy_policy.get_autonomy_policy(user=user, db=_db(**kwargs)))
+ return response.model_dump()
+
+
+def default_install(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ """A tenant that has configured nothing, on a deployment that set nothing."""
+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)
+ return _policy()
+
+
+def _by_action(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ return {row["action"]: row for row in payload["actions"]}
+
+
+def test_the_response_names_the_control_that_gates_execution(default_install: dict[str, Any]) -> None:
+ assert "effective" in default_install, (
+ "the response carries only confidence thresholds, so the console has nothing to derive a "
+ "posture from except a table no dispatch path reads — which is issue #1243"
+ )
+ effective = default_install["effective"]
+ assert effective["tier"] == "L1"
+ assert effective["tier_label"] == "L1-Notify"
+ assert effective["tier_source"] == "environment"
+ assert effective["max_automatic_impact"] == "read_only"
+
+
+def test_a_fresh_install_reports_copilot_not_autopilot(default_install: dict[str, Any]) -> None:
+ """The headline claim. Nothing high-blast runs unattended at L1."""
+ effective = default_install["effective"]
+ assert effective["high_blast_auto_executing"] == [], (
+ f"the API reports {effective['high_blast_auto_executing']} high-blast actions as "
+ f"auto-executing on a default install; the dispatcher queues every one of them"
+ )
+ assert effective["auto_executing_actions"] == []
+
+ rows = _by_action(default_install)
+ for action in HIGH_BLAST_ACTIONS:
+ assert rows[action]["effective_auto_execute"] is False, f"{action} is reported as auto-executing"
+
+
+def test_a_reachable_threshold_is_not_an_auto_execution(default_install: dict[str, Any]) -> None:
+ """The two answers must be able to disagree, or the fix is cosmetic.
+
+ ``thresholds.auto < 1`` was the console's definition of auto-executing.
+ If the effective verdict were ever wired back to it, every assertion above
+ would still pass on names alone. This one fails.
+ """
+ reachable_but_gated = [
+ row["action"] for row in default_install["actions"] if row["thresholds"]["auto"] < 1 and not row["effective_auto_execute"]
+ ]
+ assert reachable_but_gated, (
+ "no action has a reachable confidence threshold and a gated runtime verdict, so the "
+ "effective answer is still being derived from the threshold"
+ )
+
+
+def test_a_verb_with_no_executor_is_not_presented_as_executable(default_install: dict[str, Any]) -> None:
+ """`delete_object` is critical-blast, has no executor, and was counted."""
+ rows = _by_action(default_install)
+ for action in VERBS_WITH_NO_EXECUTOR:
+ assert rows[action]["executable"] is False, f"{action} is presented as executable; nothing in the tree can run it"
+ assert rows[action]["capability"] is None
+ assert rows[action]["effective_auto_execute"] is False
+ assert "advisory" in rows[action]["effective_reason"]
+
+ assert set(VERBS_WITH_NO_EXECUTOR) <= set(default_install["effective"]["unimplemented_actions"])
+
+
+def test_the_thresholds_are_declared_advisory(default_install: dict[str, Any]) -> None:
+ """Stated, not implied. An editable slider reads as a live control."""
+ effective = default_install["effective"]
+ assert effective["thresholds_are_advisory"] is True
+ assert "advisory" in effective["advisory_note"].lower()
+
+
+def test_an_operator_tier_is_read_from_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Parsed by the same function the dispatcher uses, including its aliases."""
+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L4_AUTOMATE")
+ effective = _policy()["effective"]
+ assert effective["tier"] == "L4"
+ assert effective["max_automatic_impact"] == "high"
+
+
+def test_the_top_of_the_ladder_still_does_not_auto_execute_containment(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A tier raises a ceiling; it cannot lower a contract's own floor.
+
+ Every containment verb on this page declares ``analyst`` approval, so the
+ copilot claim is a property of the contracts rather than of the default
+ tier — which is what lets the card say "no autonomy tier executes these
+ unattended" rather than "none does today".
+ """
+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L4")
+ payload = _policy(maturity_row={"maturity_tier": 4, "action_overrides": {}})
+ rows = _by_action(payload)
+ for action in HIGH_BLAST_ACTIONS:
+ assert rows[action]["auto_executes_at_any_tier"] is False, f"{action} would auto-execute at some tier"
+ assert payload["effective"]["tier_source"] == "tenant_policy"
+ assert payload["effective"]["high_blast_auto_executing"] == []
+
+
+def test_an_unreadable_policy_row_falls_back_to_the_conservative_floor(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Never inherit a permissive default when a tenant policy may exist.
+
+ Mirrors ``tenant_policy.UNREADABLE_POLICY_FLOOR``. A corrupt tier is the
+ readable form of the same problem: a row exists and does not mean anything.
+ """
+ monkeypatch.setenv("AISOC_MATURITY_TIER", "L4")
+ payload = _policy(maturity_row={"maturity_tier": 9, "action_overrides": {}})
+ assert payload["effective"]["tier"] == "L1"
+ assert payload["effective"]["tier_source"] == "unreadable_policy_floor"
+
+
+def test_an_earned_grant_raises_the_ceiling_it_is_allowed_to_raise(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A grant lifts the tier ceiling for one verb and stops at L3.
+
+ Read without re-checking the evidence behind it, which makes this page
+ slightly more generous than the dispatcher. That is the right direction:
+ omitting a grant would tell an operator a human signs off on something
+ that in fact runs by itself.
+ """
+ monkeypatch.delenv("AISOC_MATURITY_TIER", raising=False)
+ payload = _policy(granted_verbs=("quarantine_file",))
+ row = _by_action(payload)["quarantine_file"]
+ assert row["effective_tier"] == "L3"
+ # Still gated: the contract declares analyst approval, and no ceiling
+ # lowers that.
+ assert row["effective_auto_execute"] is False