# Build a policy

Write policy rules with all-or-any conditions, groups and request fields, send approvals through a chain, review the changes, backtest the draft over 30 days, try it next to the live version, then publish or roll back.

Use the policy builder's format to say when an agent's action is approved, reviewed by a person, needs stronger proof or is rejected. You save each change as a draft, read it back in plain sentences, check it against your last 30 days, and publish it at once or after a trial run.

**Before you begin:** read [policies](https://provenanceauth.com/docs/concepts/policies.md) for how rules run. The same format is used by a store's [checkout rules](https://provenanceauth.com/docs/authorize/guides/assess-checkouts.md) (`/v1/authorize/policies`), Attest's [risk policy](https://provenanceauth.com/docs/attest/concepts/risk-scoring.md) (`/v1/attest/risk_policies`) and [capture rules](https://provenanceauth.com/docs/attest/guides/capture-rules.md) (`/v1/attest/capture_policies`), and a person's own rules, so every step below works on those paths too.

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5
```

A rule has three parts:

| Part | In the builder | In the document |
| --- | --- | --- |
| IF | All or any of these match, with condition rows and one level of groups | `when` |
| THEN | Approve, Reject, Review (a store's checkout rules: Challenge), require stronger proof, ask your webhook, or approve and notify. On a store's checkout rules, Approve writes `frictionless: true` and also approves orders nothing covers; the rule says so on its sheet | `require` |
| Approval chain | Ordered steps, each with its people and how many must approve | `require.route.steps` |

## 1. Look up the fields

`GET /v1/account/policies/fields` lists what one audience's rules can read; `audience=builder` is your agent policy. The [field catalog](https://provenanceauth.com/docs/mandate/reference/policy-fields.md) explains the three layers and which fields Provenance verifies.

**curl**

```bash
curl -s "$PROVENANCE_API/v1/account/policies/fields?audience=builder" \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
const fields = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/account/policies/fields?audience=builder`, {
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
  })
).json();
```

**Python**

```python
import os, httpx

api, key = os.environ["PROVENANCE_API"], os.environ["PROVENANCE_KEY"]
fields = httpx.get(f"{api}/v1/account/policies/fields", params={"audience": "builder"},
                   headers={"Authorization": f"Bearer {key}"}).json()
```

```json
{
  "object": "policy_field_catalog",
  "audience": "builder",
  "standard": [
    { "fact": "order.amount", "label": "Order total", "type": "number", "trust": "verified", "layer": "standard" }
  ],
  "yours_window_days": 90,
  "yours_cap": 200,
  "any_field": { "fact": "field", "max_depth": 6, "list_marker": "[]", "trust": "reported" }
}
```

## 2. Save a draft

[`POST /v1/mandate/policies/versions`](https://provenanceauth.com/docs/api/policies.md#post-v1-mandate-policies-versions) validates a document and saves it as the next version without making it live. This draft tells Admins about any order over 10,000, and sends orders over 5,000 that are wires or charged to the research cost center through a two-step chain.

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/mandate/policies/versions \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "note": "big orders go to admins, then the owner",
    "document": { "rules": [
      { "id": "notify-finance", "label": "Orders over $10,000",
        "when": [{ "fact": "transaction_amount", "op": "gt", "value": 10000 }],
        "require": { "notify": { "to": ["role:admins"] } } },
      { "id": "big-orders", "label": "Orders over $5,000",
        "when": { "match": "all", "items": [
          { "fact": "transaction_amount", "op": "gt", "value": 5000 },
          { "match": "any", "conditions": [
            { "fact": "action_type", "op": "eq", "value": "wire" },
            { "fact": "field", "path": "metadata.cost_center", "op": "eq", "value": "research" }
          ] }
        ] },
        "require": { "approval": true, "route": { "steps": [
          { "to": ["role:admins"], "after": "2h" },
          { "to": ["role:owners"], "after": "1d" }
        ] } } }
    ] }
  }' | tee draft.json
```

**Node**

```ts
const document = {
  rules: [
    { id: "notify-finance", label: "Orders over $10,000", when: [{ fact: "transaction_amount", op: "gt", value: 10000 }], require: { notify: { to: ["role:admins"] } } },
    {
      id: "big-orders",
      label: "Orders over $5,000",
      when: {
        match: "all",
        items: [
          { fact: "transaction_amount", op: "gt", value: 5000 },
          { match: "any", conditions: [{ fact: "action_type", op: "eq", value: "wire" }, { fact: "field", path: "metadata.cost_center", op: "eq", value: "research" }] },
        ],
      },
      require: { approval: true, route: { steps: [{ to: ["role:admins"], after: "2h" }, { to: ["role:owners"], after: "1d" }] } },
    },
  ],
};
const draft = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies/versions`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ note: "big orders go to admins, then the owner", document }),
  })
).json();
```

**Python**

```python
document = {"rules": [
    {"id": "notify-finance", "label": "Orders over $10,000",
     "when": [{"fact": "transaction_amount", "op": "gt", "value": 10000}],
     "require": {"notify": {"to": ["role:admins"]}}},
    {"id": "big-orders", "label": "Orders over $5,000",
     "when": {"match": "all", "items": [
         {"fact": "transaction_amount", "op": "gt", "value": 5000},
         {"match": "any", "conditions": [
             {"fact": "action_type", "op": "eq", "value": "wire"},
             {"fact": "field", "path": "metadata.cost_center", "op": "eq", "value": "research"}]}]},
     "require": {"approval": True, "route": {"steps": [
         {"to": ["role:admins"], "after": "2h"}, {"to": ["role:owners"], "after": "1d"}]}}},
]}
draft = httpx.post(f"{api}/v1/mandate/policies/versions", headers={"Authorization": f"Bearer {key}"},
                   json={"note": "big orders go to admins, then the owner", "document": document}).json()
```

```json
{
  "object": "policy_version",
  "active": false,
  "note": "big orders go to admins, then the owner",
  "draft": true,
  "domain": "intent"
}
```

Keep the version number for the next steps:

```bash
export POLICY_VERSION=$(jq -r .version draft.json)
```

| In `when` | Meaning |
| --- | --- |
| A list of conditions | All of them must match (every saved policy reads this way) |
| `{ "match": "all" or "any", "items": [...] }` | All or any of the items match; an item is a condition or a group |
| A group `{ "match", "conditions" }` | One level only: a group never holds a group. At most 10 items and 20 conditions in a rule |
| `{ "fact": "field", "path": "…" }` | A request field, up to 6 dotted names; `[]` reads every element of a list, and `items: "all"` makes every element match |

A notify rule allows the request and tells the people it names, or your webhook endpoints with `"webhook": true` (the `mandate.policy.notified` event). It never decides, so the next rule still runs. Its `require` holds `notify` alone.

## 3. Review the changes

[`GET /v1/mandate/policies/versions/{version}/diff`](https://provenanceauth.com/docs/api/policies.md#get-v1-mandate-policies-versions-version-diff) compares the draft with the live version, rule by rule, in the same sentences the console shows. Pass `against=<n>` to compare with another version.

**curl**

```bash
curl -s "$PROVENANCE_API/v1/mandate/policies/versions/$POLICY_VERSION/diff" \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
const diff = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies/versions/${draft.version}/diff`, {
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
  })
).json();
```

**Python**

```python
diff = httpx.get(f"{api}/v1/mandate/policies/versions/{draft['version']}/diff",
                 headers={"Authorization": f"Bearer {key}"}).json()
```

```json
{
  "object": "policy_diff",
  "domain": "intent",
  "changes": [
    {
      "rule_id": "rul_01JD0H0TCKHFWW1N8CDJT4C90Q",
      "label": "Orders over $10,000",
      "change": "added",
      "after": "If amount is over 10,000, then approve and notify Admins"
    }
  ]
}
```

Each change says what happened to the rule, and a changed rule lists its changed `parts`, such as the conditions or the approval chain.

### Turn a rule off without deleting it

Set `"enabled": false` on a rule to keep it in the document but skip it: it never matches, decides or notifies, and the backtest leaves it out. Without the key, or with `true`, the rule is on.

The switch on each rule in the console and the app writes this key. Turning a rule off or on makes a draft like any other edit, and Review changes shows it as `turned_off` or `turned_on`.

```json
{ "id": "big-orders", "label": "Orders over $5,000", "enabled": false,
  "when": [{ "fact": "transaction_amount", "op": "gt", "value": 5000 }],
  "require": { "approval": true } }
```

## 4. Backtest the draft

[`POST /v1/mandate/policies/backtest`](https://provenanceauth.com/docs/api/policies.md#post-v1-mandate-policies-backtest) replays a document over your own requests from the last `days` (1 to 30, default 30) and says how often each rule would have matched and decided. It reads at most the newest 5,000 requests and changes nothing. Backtests are on Pro and above.

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/mandate/policies/backtest \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d "{ \"document\": $(jq .document draft.json), \"days\": 30 }"
```

**Node**

```ts
const backtest = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies/backtest`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ document, days: 30 }),
  })
).json();
```

**Python**

```python
backtest = httpx.post(f"{api}/v1/mandate/policies/backtest", headers={"Authorization": f"Bearer {key}"},
                      json={"document": document, "days": 30}).json()
```

```json
{
  "object": "policy_backtest",
  "available": true,
  "days": 30,
  "field_conditions_unscored": true
}
```

Each entry in `rules` has a `summary` such as "Last 30 days: would have reviewed 14 times, about 3 a week" (on a store's checkout rules, "challenged"). Request fields aren't kept with past decisions, so a field condition never matches in a backtest, and `field_conditions_unscored` says so. A trial run sees them.

Checkout rules and agent policies also answer `amounts`: the money each outcome would have touched, by currency. Checkout sums `order.amount` by `order.currency`; an agent policy sums `transaction_amount`, with `currency: null`. Each rule's entry has its own `amounts`. A request without the amount is counted in `totals` and in `unsummed`, not summed. The console's backtest line, its review page and a [rules embed](https://provenanceauth.com/docs/embeds/rules.md#preview-then-publish) preview show the same numbers, in one line built from `totals` and `amounts`.

```json
{
  "totals": { "allowed": 23, "challenged": 14, "rejected": 3 },
  "amounts": {
    "fact": "order.amount",
    "allowed": [{ "currency": "USD", "amount": 1870 }],
    "challenged": [{ "currency": "USD", "amount": 2915 }],
    "blocked": [{ "currency": "USD", "amount": 1240 }],
    "unsummed": 0
  }
}
```

## 5. Try it first, or publish

[`POST /v1/mandate/policies/versions/{version}/publish`](https://provenanceauth.com/docs/api/policies.md#post-v1-mandate-policies-versions-version-publish) makes the draft live now. With `trial_days` (1 to 30, Pro and above) the draft instead runs silently next to the live version: it decides nothing, and each request records what it would have done.

**curl**

```bash
curl -s -X POST "$PROVENANCE_API/v1/mandate/policies/versions/$POLICY_VERSION/publish" \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "trial_days": 7 }'
```

**Node**

```ts
const trial = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies/versions/${draft.version}/publish`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ trial_days: 7 }),
  })
).json();
```

**Python**

```python
trial = httpx.post(f"{api}/v1/mandate/policies/versions/{draft['version']}/publish",
                   headers={"Authorization": f"Bearer {key}"}, json={"trial_days": 7}).json()
```

```json
{
  "object": "policy_trial",
  "domain": "intent",
  "active": false
}
```

[`GET /v1/mandate/policies/trial`](https://provenanceauth.com/docs/api/policies.md#get-v1-mandate-policies-trial) shows the trial run: how many requests it saw, how many it would have decided differently, and up to 20 examples. When it looks right, publish the draft with one call:

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/mandate/policies/trial/promote \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
const live = await (
  await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies/trial/promote`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
  })
).json();
```

**Python**

```python
live = httpx.post(f"{api}/v1/mandate/policies/trial/promote", headers={"Authorization": f"Bearer {key}"}).json()
```

```json
{
  "object": "policy_version",
  "active": true,
  "domain": "intent",
  "promoted_from_trial": true
}
```

`DELETE /v1/mandate/policies/trial` stops a trial run and keeps the draft. Trial runs are for agent policies and checkout rules.

## 6. Roll back

Every version stays on record. To roll back, publish the earlier version: [`POST /v1/mandate/policies/versions/{version}/publish`](https://provenanceauth.com/docs/api/policies.md#post-v1-mandate-policies-versions-version-publish) makes it live again, and the history stays as it was. To return to the built-in default, delete the policy; the history stays.

**curl**

```bash
curl -s -X DELETE $PROVENANCE_API/v1/mandate/policies \
  -H "Authorization: Bearer $PROVENANCE_KEY"
```

**Node**

```ts
await fetch(`${process.env.PROVENANCE_API}/v1/mandate/policies`, {
  method: "DELETE",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}` },
});
```

**Python**

```python
httpx.delete(f"{api}/v1/mandate/policies", headers={"Authorization": f"Bearer {key}"})
```

```json
{
  "object": "policy",
  "domain": "intent",
  "version": null,
  "is_default": true
}
```

[`GET /v1/mandate/policies/versions/export`](https://provenanceauth.com/docs/api/policies.md#get-v1-mandate-policies-versions-export) returns every version with its document, on the Enterprise plan.

## Who can change a policy

From the console, changing a policy, an approver list or the approval expiry default needs the **Manage policies** permission and a passkey or authenticator check from the last 10 minutes. Owners have the permission and can grant it to admins; everyone else sees policies read-only, and a developer's change in live mode is held for approval. An API key is exempt from both and needs its product's scope instead ([scopes](https://provenanceauth.com/docs/get-started/authentication.md#scopes)). See [who can change policies](https://provenanceauth.com/docs/mandate/guides/route-approvals.md#who-can-change-policies).

## What each plan includes

Evaluating a policy is part of each decision and is never counted separately.

| Plan | Adds |
| --- | --- |
| Free, and people's own rules | The templates and the builder with the standard fields (the cart's own paths included), every fact, rules whose conditions each read one fact and all have to hold, as many rules as the policy holds (up to 50), every outcome except the webhook, and one approver per step (one `user:` or `role:owners`). A person's own rules keep any-of matching and lists |
| Pro | Backtests and trial runs, any-of matching and groups, spend and request limits (velocity), named lists, the developer editor, approval chains (more than one step, more than one approver, N of M, everyone), approver groups, outside approvers, Your fields (`metadata.*`) and the webhook outcome |
| Growth | Any field paths |
| Enterprise | More than 50 rules (up to 200) and version history export |

Backtests and trial runs moved from every plan and Growth to Pro and above on 2026-11-17. Free had a cap of 10 rules per policy until 2026-11-18; it has none now, and the developer editor moved to Pro and above the same day.

Per-order limits and [permission](https://provenanceauth.com/docs/mandate/concepts/grants.md) budgets are on every plan, Free included. An agent builder's spend and request limits (velocity) by hour, day or month, per account or per agent, are on Pro and above (they were on every plan until 2026-11-17).

A save that uses something above your plan answers `402 plan_required`, naming each rule and what it uses. The same check runs whether the console, the API or a [rules embed](https://provenanceauth.com/docs/embeds/rules.md) session saves.

## Where each version came from

Each version names where it was written. Versions saved before 2026-11-17 have no `source`.

| Field | What it holds |
| --- | --- |
| `source` | Where it was written: the console, the API, or a [rules embed](https://provenanceauth.com/docs/embeds/rules.md) session in your own admin tool (`embed`) |
| `created_by` | The console member or the API key; for an embed session, the key or member that minted the session |
| `embed_session` | On a version an embed session saved, the session's id |
| `draft_group` | Sandbox. On a draft an embed session saved in a draft group (the live demo's per-visitor drafts) |

A group's drafts wait apart from everyone else's: the version list leaves them out unless you pass `?draft_group=` with that group, and they never become the draft your console or other sessions build on. They're deleted 24 hours after they're saved unless they're published. See [per-visitor drafts](https://provenanceauth.com/docs/embeds/rules.md#per-visitor-drafts-in-sandbox).

The console's version list shows it on each row: "Embed session, minted by key …4f2a", "API key …4f2a" or "Console".

To let your team change some of these rules in your own admin, or on a phone, open **Embed in your admin** on Rules (Orders or Agent actions). It writes the mint code for the rules, blanks and bounds you pick, with a live preview and a hosted page link. See [rules in your admin](https://provenanceauth.com/docs/embeds/rules.md#build-the-scope-in-the-console).

## Every publish is recorded

Every change to which version runs, from any surface, writes a "Published a policy" row to the [audit log](https://provenanceauth.com/docs/account/console.md) and sends a webhook owned by the policy's product. The changes are a save that goes live, a draft published, a version activated, a restore, a trial run started or promoted, and a revert to the built-in rules. Saving a draft is not a publish.

| Policy | Webhook |
| --- | --- |
| Checkout rules | `authorize.policy.published` |
| The agent policy | `mandate.policy.published` |
| Capture rules, the claims risk policy | `attest.policy.published` |
| The traffic policy | `identify.policy.published` |

```json
{
  "type": "authorize.policy.published",
  "data": {
    "object": "policy_publish",
    "domain": "checkout",
    "version": 7,
    "previous_version": 6,
    "change": "published",
    "source": "api",
    "key_id": "key_4AWYBXZYMW81RB3MQNXH88967D",
    "published_at": "2026-11-17T10:21:44.000Z"
  }
}
```

Ids and numbers only, never the rules themselves: read the version with [`GET /v1/authorize/policies/versions/{version}`](https://provenanceauth.com/docs/api/checkout-policies.md#get-v1-authorize-policies-versions-version).

## How rules are evaluated

Rules run in order, and the first rule whose conditions hold and whose requirement isn't met decides. Each fact a condition reads has a cost, its tier: 0 for what the request and token carry, 1 for your own records (a spend limit, a named list), 2 for a network call (an external risk provider) and 3 for a model call.

`GET /v1/mandate/policies/versions/{version}/plan` (and the same path on every rule set) shows a version compiled into its plan: each rule's facts with their tiers, cheapest first, and warnings for a fact the rule set can't read, an operator that never matches its fact, or a rule that's never reached. The same document always has the same `plan_hash`.

Facts are read cheapest first, and a network call is made only when the outcome still depends on it: a rule whose cheaper conditions already fail never calls an external risk provider, and a decision that didn't need the answer doesn't record it. If a provider doesn't answer in time, its facts are unavailable and the settings below decide.

## When a fact is unavailable

A fact that can't be read is unavailable, never a made-up value: an external risk provider that didn't answer, a capture shot with no GPS, a Trace reading that wasn't found. What it does to a condition is decided by the first of these that is set:

1. the condition's `if_unavailable`;
2. the rule's `if_unavailable`;
3. the rule set's `settings.if_unavailable`;
4. the default for that kind of fact: an external risk fact and a capture fact don't match, and a Trace finding takes the cautious side.

| Setting | What happens |
| --- | --- |
| `skip` | The condition doesn't match |
| `match` | The condition matches |
| `ask` | The condition matches, and the rule asks a person instead of refusing |

On an external risk fact, `ignore` means `skip`. On Trace and agent rules, `fail_closed` takes the cautious side (a rule that restricts matches, a rule that approves doesn't) and `fail_open` the other.

## Moving existing rules

Agent policies, store checkout rules, seller rules and Attest claims risk rules are already in this format: a saved `when` list reads as "all of", so they open in the builder unchanged. `POST /v1/account/policies/migrations/run` records that per system after replaying recent requests through the old and the new rules; it writes a version only when every decision matches, and `GET /v1/account/policies/migrations` lists each run.

Called with an API key and no `system`, it runs only the systems the key's scopes cover and returns the others in `skipped` with `insufficient_scope`.

A person's existing rules (always ask above an amount, never at these stores, only between these hours) move into their own builder rules the first time they open **Your rules**, or with `POST /v1/personal/policies/migration`. Each keeps what it did:

| Rule | Becomes | On a company's request |
| --- | --- | --- |
| Never at these stores | Reject, reason `store_not_allowed`, checked first | `on_request: "hold"`: the request waits in the person's home |
| Always ask me above | Review, reason `ask_above`, checked before the permission's budget | Not affected |
| Only between these hours | Review, reason `outside_hours`, in the rule's time zone | `on_request: "defer"`: delivered like quiet hours |

Before anything is written, every combination of permission, store, currency, amount, category, spend and hour, plus the person's recent orders and companies' requests, runs through the old and the new rules; the move goes ahead only when each gives the same outcome and reason code.

The rules are then `tighten_only`: a stricter change saves at once, and a looser one needs the person's passkey and waits out a recent recovery.

The one case that stops the move is two time zones: hours in one zone while the person's other rules read the time in another. The run lists it and nothing changes.

## Errors you might see

| Code | Status | What it means |
| --- | --- | --- |
| `policy_invalid` | 400 | A rule fails validation; `error.details` names each rule and field |
| `route_invalid` | 400 | A chain or notify rule names a group, person or approver that isn't on your account |
| `plan_required` | 402 | The document uses something above your plan |
| `manage_policies_required` | 403 | Your console role can't change policies |
| `recent_two_factor_required` | 401 or 403 | Confirm with your passkey or authenticator, then retry |
| `policy_trial_not_active` | 409 | There is no trial run to promote |
| `resource_missing` | 404 | No version with that number |

## See also

- [Field catalog](https://provenanceauth.com/docs/mandate/reference/policy-fields.md)
- [Approval chains and expiry](https://provenanceauth.com/docs/mandate/guides/route-approvals.md#send-it-through-ordered-steps)
- [Policies](https://provenanceauth.com/docs/concepts/policies.md)
- [Set limits and policy](https://provenanceauth.com/docs/mandate/guides/set-limits-and-policy.md)
- [Webhooks](https://provenanceauth.com/docs/integrate/webhooks.md)
