# Agent governance

Humans, AI agents and service accounts share **one `Principal` spine**. There is no
parallel "bot user" table, no second permission system, and no place where an agent's
authority is decided by different code from a human's.

That is the design commitment: an agent acting with no visible human behind it is how
the Drift breach stayed invisible for weeks.

## Identity

An agent has:

- a `Principal` row, created in the **same transaction** as its identity — a
  half-created agent would be a principal with no governance attached;
- a **mandatory sponsor**, who must be an active member of the org. Agents never
  outlive their sponsor's authority: offboarding a sponsor suspends their agents
  pending transfer, so orphaned agents stop acting immediately;
- an `OrgMembership`, capped at `MEMBER`. An agent is never OWNER, ADMIN or BILLING,
  and an agent with no membership can do literally nothing;
- a `maxTier` (below), validated on grant rather than by convention;
- a lifecycle: `ACTIVE` / `SUSPENDED` / `RETIRED`.

## Capability tiers

```
telemetry:read  <  context:hydrate  <  sandbox:execute  <  pr:propose  <  pr:merge
```

**`pr:merge` is human-only and ungrantable to an agent at any level.** It is rejected
by `assertGrantableTier()` at grant time, and again by the approval engine at use time,
and the approval engine's check runs *before* any organization policy is loaded. No
configuration change makes it possible.

## Delegation

A human's access token is exchanged **down** to a narrow, audience-bound, short-lived
agent token carrying nested RFC 8693 `act` claims. The point is that every downstream
action renders as:

> Claude Code, acting for alice@acme, incident #123

**Effective permissions = requested ∩ delegating user's ∩ agent's allowed.** All three
legs are enforced independently. The delegating user's leg is itself the intersection
of their memberships and the scopes on the token they presented, so a user driving the
API with a narrowed token cannot delegate authority that token does not carry.

### Blast radius

An incident-scoped credential is bound to one incident. A global request hook resolves
what each request is reaching for — an issue, or a whole project — and refuses anything
outside that incident. It is a hook rather than a per-route guard because a blast
radius that has to be remembered leaks the first time someone adds an endpoint.

## Approvals: deny–ask–allow

Every governed action resolves to `ALLOW`, `ASK` or `DENY`. Four gates run **before**
organization policy is consulted, and no policy row reaches past them:

1. Human-only actions (`pr.merge`, `fix.approve`, anything `*.merge`) are DENIED for
   every non-human principal.
2. `Organization.aiEnabled === false` denies every non-human action. A kill switch that
   policy can override is not a kill switch.
3. `Organization.agentPrCreationEnabled === false` denies `pr.propose`.
4. A SUSPENDED or RETIRED agent is denied.
5. A switched-off agent surface, then a change freeze in force (see
   [Kill switches](#kill-switches) and [Change freezes](#change-freezes)), deny a bound
   principal; the verdict names which one in `gate`.

Risk classes map to defaults: `SAFE`/`ELEVATED` → ALLOW, `SENSITIVE` → ASK,
`CRITICAL` → DENY. An **unknown action is SENSITIVE**, so a new action is gated by
default rather than by remembering to classify it. The risk table has a null prototype,
so an agent-supplied action named `toString` cannot inherit its way to a lookup hit.

### The sole-approver rule

*The human who initiated an agent run may not be the sole approver of its output.*
Enforced in three places:

- the delegation chain is **persisted** on the request, and re-derived from
  `Delegation` rows for agent requesters that carried no `act` claim, so it cannot be
  dodged by minting a plain agent token;
- votes live in their own table with `@@unique(requestId, voterPrincipalId)`, so
  "distinct approvers" is a database constraint rather than an application count;
- a request is APPROVED only when it has `minApprovers` votes **and** at least one vote
  from outside the delegation chain. The initiator may vote; they may not be alone.

`minApprovers` is frozen from the policy at creation time, so a mid-flight policy edit
cannot lower the bar for a request already in the queue.

### Conditions and shadow rows

A policy row can be narrowed with **conditions** and tried out in **shadow** mode. Both are edited
in **Settings, Approval policies**.

**Conditions** are a closed grammar over facts Bucker computes from the plan, never over the
requester's text: `{ "all": [ ... ] }` or `{ "any": [ ... ] }` of condition objects, where every key
of one object must hold. The keys cover the shape of the change (`anyChange`, `field` compared
before and after, `changeAmount` in absolute or percent terms), its reach (`audienceShareAfter`,
`audienceShareDelta`, `trafficShare`, `eventsDroppedPerDay`, `dependentsAffected`,
`dollarsPerMonthDelta`), where it lands and where it came from (`environment`, `direction`,
`provenance`, `taint`) and, for an action whose family declares them, its own `fact`s. The editor
offers exactly the keys the grammar has and starts each from a valid example; the server checks the
meaning when the row is saved and refuses a row that could never hold, such as a `fact` on a
risk-class row.

How a conditioned row is chosen:

- Among the rows that match an action, **more conditions beat fewer**; a row with none is the
  fallback.
- **An unmeasured input never loosens anything.** A row that allows on a condition does not match
  an input nobody measured, because a failed measurement must not be the reason something is
  approved. A row that asks or denies does match it.
- A row only governs under the risk class the action is resolved under. A governed family's acts
  are classed from the plan's difference on every request, so a row for such an action under a
  higher class applies exactly when the change is classed there.

**Shadow mode** records what a row *would* have decided, beside the real decision, and changes
nothing. The policies tab shows, for each shadow row, how many decisions it would have changed in
the last 14 days (counted from the `approval_policy.shadow_verdict` audit rows), so an owner can see
the effect of a stricter row before it enforces. A shadow row decides nothing, and a row that has not
been evaluated yet shows no count rather than zero.

Loosening is guarded. When the deployment installs the loosening gate, an edit that takes
authority from the people who approve things needs a second owner instead of a direct save:
lowering the number of approvers, relaxing a deny to an ask or an ask to an allow, adding an allow
row, switching a strict row to shadow, deleting a strict row, or making an allow row broader or a
strict row narrower.

## Review mode

An organization chooses how agent and integration changes are reviewed, in **Settings, Review
mode**. There are two modes. **Automatic** (the default) leaves the decision to your approval
policy and, only when an owner sets a risk ceiling, lets the decision model approve more within the
goals the owner sets. **Human review required** makes every change an agent or integration proposes
wait for a person. In either mode merges, denied actions and person-only acts stay with a person,
and a critical deploy is automatic only in an environment an owner switched on, with a passing
verification. Production's switch needs the owner's password or security key. See
[Review mode](/docs/review-mode) for the goals, the opt-ins and the audit trail.

## Budgets and the spend meter

Budgets key on the **(agent, on-behalf-of user, incident)** tuple — the LiteLLM
virtual-key pattern. A single spend is charged to **every** budget that covers it: an
org-wide cap for the agent, a cap for what it may spend on one person's behalf, and a
cap for one incident all apply at once, and the tightest wins.

Charging only the most specific budget would let a loop that keeps inventing new
incident ids escape the agent-wide ceiling entirely.

## Grants

A new agent holds its tier's reads and the `core` toolset, and nothing else. A **grant** is how a
person hands it more: a scope, a toolset or a tool, for an agent that runs with nobody present to
delegate (a watcher, a scout). Five rules hold for all of them (`domain/src/modules/agents/grants.ts`).

- **A grant never exceeds the person who issued it.** Issuing one needs `manage_agents`, a reason,
  and the scope itself: the grantor must hold it in the organization and so must the credential they
  present. For an agent's own credential, `check()` then satisfies a granted scope on an object only
  when the grantor's role permits it on that object (resolved the way `act.pid` is) and the object lies
  inside the grant's `objectScope` (named projects, or projects carrying a policy tag).
  `allowedAgentScopes` is (tier ∩ role) ∪ granted, minus human-only, and token minting and exchange
  intersect with it; `assertWithinResourceCeiling` still refuses what the MCP ceiling does not hold.
- **Lapse is decided on read, never by a sweep.** Expiry, revocation, an `activatesAt` still in the
  future, a suspended agent, and a grantor who lost the scope, left the org or was deactivated all take
  the grant out of the next request. A token minted on the strength of a grant loses the scope when
  the grant ends.
- **Widening is a human act, narrowing is not.** `agent_grant.widen` is human-only: a person's own
  session, no delegation, no OAuth client. `agent_grant.narrow` (a revoke, an earlier expiry, fewer
  projects) takes effect at once and an agent may narrow its own grants.
- **A dangerous scope waits.** `infra:act`, `db:write`, `queue:write`, `playbook:run` and `cost:cap`
  activate 24 hours after they are issued; the widen row (an owner-alert action) records when. A second
  `manage_agents` holder confirming it sooner lands with the step-up work.
- **A grant always ends**: 90 days by default, 365 at most.

What can be granted is `AGENT_GRANTABLE_SCOPES`, derived from the scope registry: Table R's reads and
narrow writes (not `agents:control`) plus `event:read`, `issue:triage`, `issue:resolve`, `fix:propose`,
`alerts:write`, `status:write` and `release:write`. Never a human-only scope, `hotfix:deploy`,
`agent:manage`, `member:invite`, `org:write`, `project:write` or `project:admin`. A write the agent then
asks for still passes the approvals engine, and the review mode never loosens it.

REST: `GET|POST /orgs/:o/agents/:id/grants`, `DELETE …/grants/:grantId`, `POST …/grants/:grantId/narrow`.
The dashboard shows the list on the agent page for people who manage agents.

**`agent_context_get`** (MCP, core, no input) answers "who am I and what can I do" from the token alone:
the identity, every effective scope with the layer that decided it (`tier`, `grant` with its id and
grantor, `membership` or `ceiling`) and why any is locked, the toolsets, trust rung per category, remaining
budgets, taint state and decay, the review mode in force, and the org's kill switches. A granted scope
outside the live MCP ceiling reads "held until the SG-059 review". `decision_preview` reports the same
taint state and names `taint` as the layer when the floor changed its answer. There is no `agents_list`
tool: its scope, `governance:read`, is outside the ceiling SG-059 holds.

## Kill switches

`Organization.agentSurfacesDisabled` names the agent surfaces an owner or admin switched off:
`mcp.all`, `mcp.write`, `infra.act`, `flags.write`, `pipeline.write`, `analytics.write`,
`playbook.run`, `playbook.propose`, `cost.cap`, `agents.control` and `oauth_clients`. A switch holds
from the very next decision: it is read with the organization row the engine already loads, never
cached, and the MCP transport reads it on every call from a bound caller.

- **Who is bound.** An agent, a SERVICE principal, an OAuth client and any triggered act (an alert, a
  worker, a playbook step). A person in the dashboard is not bound: the stop exists to hold a runaway
  or hijacked non-human actor, and it must never lock out the owner who has to release it.
- **What each surface covers.** `mcp.all` stops every MCP tool call; `mcp.write` stops every MCP write;
  the family surfaces bind the act wherever it arrives (`surfaceForAction` maps each registered action
  to one, by family: the flag family to `flags.write`, log pipeline rules and saved queries to
  `pipeline.write`, and so on). The switches' own control plane is never stopped by a switch.
- **Engaging** (`agent_surface.disable`) is the safety direction: any owner or admin holding org
  `write`, at once, no approval, no step-up, an audit row and an alert to the organization's owners. The
  threat module's SERVICE principal may also engage `mcp.write` or `oauth_clients` on a HIGH anomaly
  (opt-in per pass, off by default). **No agent engages or releases any surface**: the stop binds every
  other agent and client, so in an injected agent it would be a denial of service.
- **Releasing** (`agent_surface.enable`) is human-only (`org:admin`, an owner), in a person's own
  session, with a reason of at least ten characters and a step-up bound to that surface and that reason
  (a challenge for another surface or another reason does not verify), an audit row and an owner alert.
- **Refusals** are our own sentence naming the surface (`The "mcp.write" agent surface is switched off
  for this organization ...`); over REST a 403 with `refusalCode: SURFACE_DISABLED`; over MCP a protocol
  error (`-32003`, `details.reason: surface_disabled`) before the arguments are parsed.

REST: `GET /orgs/:org/agent-surfaces`, `POST .../:surface/disable`, `POST .../:surface/enable/challenge`,
`POST .../:surface/enable`. `decision_preview` reports `killSwitch: {surface, engagedAt}` when a switch is
why an act would be refused.

## Change freezes

A freeze window refuses changes for a period. It is explicit about what it covers: `{ "all": true }`, or
any of `projectIds`, `policyTags`, `environments`, `families`, `actions` (several dimensions AND; a
dimension the target does not state counts as covered; an empty selector is refused when written). It is
a one-off (`startsAt`, `endsAt`, at most 14 days) or a recurrence (`rrule`, `durationMinutes`, `tz`:
DAILY, WEEKLY with BYDAY, MONTHLY with BYMONTHDAY, INTERVAL, COUNT, UNTIL, in the window's own zone,
with at most 12 occurrences inside 90 days; a longer rule is cut at the twelfth and `endsAt` says where).

| Mode | Refuses |
| --- | --- |
| `deny_changes` | every write except the safety direction the registry marks (`direction: tighten`: narrowing, disabling a flag, pausing a rollout, reverting a loosening, creating a freeze) |
| `deny_loosening` | only what loosens or silences (`loosen`, `silence`, and `classified` until classified) |

Deny wins on overlap: every covering window must permit the act. A freeze binds **every door**, with the
same function (`assertNotFrozen`, `approvals/engine.ts`): the approvals engine for an agent, a SERVICE
principal, an OAuth client or a triggered act; every REST write route of a governed family, through a
preHandler derived from the route's own `config.bucker.action` (`api/src/lib/governed-route.ts`, lint
`test/app/governed-routes.test.ts`), for a person too; and `bucker.yml` apply, resource by resource and
before its first write. `freeze_window.*` and `agent_surface.*` are never frozen.

- **Creating** (`freeze_window.create`): a person holding org `write`, direct. An agent proposes one
  (`freeze_window_propose`, 72 hours at most) for a person to accept. Edits are in the safety direction
  only (stricter mode, later end, wider scope); to loosen a freeze, end it.
- **Ending and deleting** (`freeze_window.end`, `.delete`): human-only, `org:admin`, audited. Ending keeps
  the row as history.
- **Break-glass** (`freeze_window.break_glass`): a named owner or admin in their own session, a reason of
  at least 20 characters, at most four hours, a step-up bound to the freeze id, the reason and the
  minutes, one live at a time per person per freeze. It crosses that one window for that one person; it
  is never offered to an API key, a SERVICE principal, an agent or a delegated client, and it does not
  cross a second covering window. It raises a banner in the organization (`GET /orgs/:org/break-glass`),
  alerts every owner and notifies the freeze's creator.
- **Notices.** Owners are told when a freeze starts and when it ends, and receive one digest every 15
  minutes of what a freeze refused (`freeze.refused` audit rows, deduplicated per caller, act and window).
  Titles never contain the window's name.
- **What agents see.** `freeze_windows_list` (read) and `decision_preview`'s `freeze: {windowId, mode,
  endsAt}`; the window's name and reason are member-authored, fenced and declared untrusted.

REST: `GET|POST /orgs/:org/freeze-windows`, `PATCH|DELETE .../:id`, `POST .../:id/end`,
`POST .../:id/break-glass/challenge`, `POST .../:id/break-glass`.

## Governed operations

A write an agent proposes to alerting, sampling, logs, checks or flags is a **governed operation** of
a registered family (`domain/src/modules/operations/`), and every door runs it in the same twelve steps:

1. **The act is derived, not named.** The family reads the object, applies the proposed change, and
   classifies the difference (`alert_rule.mute`, `flag.narrow`, `sampling_rule.create` ...). An act
   that is not in the action registry cannot be performed, and an argument can never lower the class
   the diff gives it.
2. **A preview comes first and is its own call** (`*_preview` tool, `POST .../preview` route): the
   numbers are replayed from stored data, the audience is measured by Bucker and never asserted, and a
   retried preview can never become the action. A family that requires a preview refuses to apply
   without a stored one whose digest matches.
3. **The plan has a digest.** What the approver sees is the plan text, the target and its revision, the
   blast radius, the verification signal, the inverse and the time-box, all hashed. The apply runs the
   plan stored on the operation row whose digest was approved, never a re-derived one.
4. **The decision is the engine's.** Policy, the ask floors, kill switches, change freezes, window caps
   and the review mode apply in that order; review mode never loosens a DENY, an invariant or a
   dual-control ASK, and merging stays with a person in both modes. A CRITICAL vote or a dual-control
   vote needs a passkey step-up bound to the transaction.
5. **The apply is a compare-and-swap** on the revision the plan was derived against, inside the spend
   transaction. If any door (REST, dashboard, Slack, config-as-code, another agent) moved the object, the
   operation ends `TARGET_CHANGED` and nothing is written.
6. **The change is verified and can be undone.** A stored signal is judged after the window
   (`verifyAt`); the operation carries a receipt and a registered inverse (`operationRevert` runs the
   same engine). A time-boxed change ends by itself through the operations pass, which cannot be
   paused.

**Shadow.** A rule an agent creates starts in shadow (`lifecycle: SHADOW`): it is evaluated and records
what it would have fired, delivers nothing, and lapses after 14 days. Promotion asks a person, with the
evidence on the card, and re-checks the blocking quality keys at the apply. Config-as-code applied by an
agent principal is born shadow too. A person's own direct edit and a CI service key keep writing LIVE.

**Held tools.** A tool whose relation prices a scope outside the SG-059 ceiling is declared in
`HELD_TOOL_RELATIONS` and is not listed for any token a production path can mint; its toolset reads
`locked` with the reason `held`. Nothing about a held tool is a separate switch: widening the ceiling
and removing the relation from the list are the same commit (H-55).

Reading what happened: `operations_list` and `operation_get` (MCP), `GET /orgs/:org/operations`
(REST), and the operations page in the dashboard.

## Audit

Every decision — approve, reject, expire, and **refused attempts** — writes an
`AuditLog` row. Action granularity is the point: "this agent had approval rights" is
not an audit trail; "this human approved that PR at that time" is.

Governance-relevant non-events are audited too. If an approval request was opened and
no channel was configured to notify anyone, that is recorded, and "no channel exists"
and "Slack returned 500" are recorded as different facts rather than blurred into one
word.

## Where authorization lives

One module, in two halves: the engine is `domain/src/modules/authz` and the Fastify
preHandlers that call it at a route boundary are `api/src/modules/authz/guards.ts` and
`request-scope.ts` (roadmap P5.4 — nothing but the request plumbing stayed behind).
Relations resolve through it for every principal kind. There are 55: the original eleven (`read`,
`write`, `admin`, `triage`, `resolve`, `invite`, `manage_agents`, `propose_fix`, `approve_fix`,
`deploy_hotfix`, `manage_billing`) and a narrow family each for configuring or reading one area
(`configure_alerts`, `configure_metrics`, `configure_pipeline`, `configure_flags`, `read_security`,
`read_governance`, `control_agents` and the rest; the list is `RELATIONS` in
`domain/src/modules/authz/check.ts`, and every governed action's relation is in
[actions.md](actions.md)). A relation maps to a scope; the scope vocabulary has 56 entries, and
the ones an agent can be granted are listed in [Grants](#grants). No route reimplements a
permission check; the approval engine consults authz's own agent gate rather than
mirroring it, so a gate added there takes effect everywhere without a second edit.

## Phase 4 families (the Datadog side)

Registered through the same engine, each with its chain proved end to end: `db_session_cancel`, `gate`,
`ci_quarantine`, `collector_profile`, `metric_tag_rule`, `sampling_budget`, `log_quota`, `log_conversion`,
`slo`, `routing_policy`, `finding_suppression`, `block_rule`, `cost_budget`, `provider_cap`, `check_budget`,
`log_parse_rule` and more. Every write tool of these is on a held relation (SG-059), so no production-mintable
token lists it. A parse rule an agent writes lands in shadow, is replayed on lines the agent was never shown, and
enabling it is a person's decision with that replay on the card. An index is proposed as a draft pull request and
Bucker never merges or runs the statement. The list is in `docs/unified-platform/phase4-gate.md`.

## Phase 5 (earned autonomy, playbooks, experiments, narrowed approvals)

Four additions change what an approval can say or skip, and none of them adds a way around the engine.

- **Earned rungs (ACP-20, F-14).** A rung lowers one act's class for one actor in one category, and only after
  evidence: at least three verified results, a shadow trial of at least 14 days and a revert rate below the category's
  ceiling. The offer is made by the system and **accepted by a person**: a first-party session, never an OAuth client,
  an acting-as delegation or a credential with no sign-in factor. A revert or a failed verification demotes the grant at
  once and automatically, and a missed incident does the same where a category declares it. LADDER_FORBIDDEN acts
  (human-only, widening, launch, ship, resume, publish, delete) can never be in a category; safety and lever categories
  ship in shadow behind a per-family constant until OD-DP-11 is answered. Nothing is granted by default: the registry
  ships empty of grants.
- **Playbooks (F-22, MON-21).** A published playbook version is approved once by digest; a run is a governed operation
  and **every step re-enters `governedOperation`** for the run's principal, so a freeze, a kill switch or a held relation
  stops a run mid-way exactly as it stops a direct call. A step an agent could not take directly is not a step.
- **Approver narrowing (ACP-25).** A person approving may approve a strictly smaller plan than the agent asked for. The
  narrowed plan has its own digest, the apply is bound to it, and a narrowing that widens blast is refused. Human-only.
- **Experiments (FLAG-14, FLAG-19).** Agents draft and propose launch; a human ships. A result an agent reads states
  its validity checks and never a bare "significant", and the decision is a pre-registered rule plus a signed human
  decision.

Everything a Phase 5 tool writes is held on the SG-059 review (H-26), and merging stays human at every level. The
release checklist is `docs/unified-platform/phase5-gate.md`.

## Not built

- No autonomous merge, at any trust level.
- Cross-tenant agent reputation or shared trust scores do not exist.
