# Show rules in your admin

Show your Provenance checkout, agent and capture rules to your staff inside your own admin tool with <provenance-rules>, or on a hosted page for phones, scoped by your server on every session.

`<provenance-rules>` shows your Provenance rules to your staff inside your own admin tool, and lets them change the values you choose: your Authorize checkout rules, your Mandate rules for agents' actions, or your Attest capture rules for photos. Each rule is one line, in plain words, with its outcome on the right: Approve, Challenge, Reject or Review.

Your server decides which rules a session shows, which values are blanks and within which bounds, and which rules are locked, every time it mints a session. Nothing is saved on our side between sessions.

A session minted with `mode: "edit"` saves your staff's changes as a draft version of the policy, which a console member or your server publishes. A session minted with `mode: "publish"` and `rules.saves: "publish"` can publish from the element too, after a preview of what the change would have done.

**Before you begin:** a publishable key (see [embeds](https://provenanceauth.com/docs/embeds.md#1-create-a-publishable-key)) and a secret key with the scope of the rules' product: `authorize` for checkout rules, `mandate` for agents' rules, `attest` for capture rules. In live the embed needs Pro or the Free trial; in sandbox it works on every plan.

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

## 1. Mint a session on your server

Your server mints a short session with [`POST /v1/embed/tokens`](https://provenanceauth.com/docs/api/embeds.md#post-v1-embed-tokens), `widget: "rules"`, the kind of rules as `object_id` and the full scope in `rules`. Put it behind a route your admin page calls, after your own sign-in check:

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/embed/tokens \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "widget": "rules", "object_id": "checkout", "rules": { "show": [ { "rule_id": "rul_default_no_mandate_or_approval", "locked": true } ] } }'
```

**Node**

```ts
// GET /admin/provenance/rules-session (your route, behind your staff sign-in)
const session = await prov.embed.createToken({
  widget: "rules",
  objectId: "checkout",
  rules: {
    show: [
      { ruleId: "orders-over-limit", fields: [{ path: "when.0.value", min: 50, max: 5000 }] },
      { ruleId: "known-bad-bots", locked: true },
    ],
  },
});
res.json({ token: session.embedToken });
```

**Python**

```python
token = prov.embed.create_token(
    widget="rules",
    object_id="checkout",
    rules={"show": [{"rule_id": "orders-over-limit", "fields": [{"path": "when.0.value", "min": 50, "max": 5000}]}, {"rule_id": "known-bad-bots", "locked": True}]},
)["embed_token"]
```

**Go**

```go
lo, hi := 50.0, 5000.0
session, err := embed.CreateToken(ctx, pv.EmbedTokenParams{
	Widget:   pv.WidgetRules,
	ObjectID: "checkout",
	Rules: &pv.RulesEmbedScope{Show: []pv.RulesEmbedShow{
		{RuleID: "orders-over-limit", Fields: []pv.RulesEmbedField{{Path: "when.0.value", Min: &lo, Max: &hi}}},
		{RuleID: "known-bad-bots", Locked: true},
	}},
})
```

| Field | What it does |
| --- | --- |
| `object_id` | The kind of rules: `checkout` (Authorize, needs an `authorize` key), `intent` (Mandate, needs a `mandate` key) or `capture` (Attest, needs an `attest` key). |
| `mode` | `view` (the default), `edit` or `publish`. |
| `rules.show` | 1 to 50 rules of that kind's live policy, by ID. Rules you don't list stay hidden. |
| `rules.show[].fields` | The values that are blanks: a path into the rule (`when.0.value`) with `min` and `max` for a number, or `values` for a word. |
| `rules.show[].locked` | Shown read-only. |
| `rules.show[].can_turn_off` | Whether staff may turn the rule off (not by default). |
| `rules.add_from_templates` | Template IDs staff may add (none by default). |
| `rules.saves` | `draft` (the default) or `publish`, with mode `publish`. |
| `rules.draft_group` | Sandbox only: a label of up to 64 characters that keeps this session's drafts apart (see [per-visitor drafts](#per-visitor-drafts-in-sandbox)). `400` in live. |
| `ttl` | Seconds, up to 900 (15 minutes). |

For your agents' rules, mint `object_id: "intent"` with a `mandate` key, listing rules of your Mandate policy:

```ts
const session = await prov.embed.createToken({
  widget: "rules",
  objectId: "intent",
  mode: "edit",
  rules: {
    show: [
      { ruleId: "big-spend", fields: [{ path: "when.0.value", min: 50, max: 2000 }] },
      { ruleId: "no-wire-transfers", locked: true },
    ],
  },
});
```

For your capture rules, mint `object_id: "capture"` with an `attest` key, listing rules of your capture policy ([`GET /v1/attest/capture_policies`](https://provenanceauth.com/docs/api/capture-policies.md#get-v1-attest-capture-policies)). A capture rule approves, reviews or rejects a photo; there is no Challenge:

```ts
const session = await prov.embed.createToken({
  widget: "rules",
  objectId: "capture",
  mode: "edit",
  rules: {
    show: [
      { ruleId: "rul_01JD9Z3K7P2QW8M4N6R5T1V0XA", fields: [{ path: "when.0.value", min: 1, max: 50 }] }, // More than 5 km from the loss address
      { ruleId: "rul_01JD9Z3K7P2QW8M4N6R5T1V0XB", locked: true }, // Mock location
    ],
    addFromTemplates: ["capture_no_gps"],
  },
});
```

The scope is strict: an unknown key is `400` [`parameter_invalid`](https://provenanceauth.com/docs/platform/errors.md#parameter_invalid), so a typo never widens a session. A rule ID that isn't in the policy is `400` [`rules_embed_rule_missing`](https://provenanceauth.com/docs/platform/errors.md#rules_embed_rule_missing), naming the entry. The response echoes the scope as stored, every default written out. List rule IDs with [`GET /v1/authorize/policies`](https://provenanceauth.com/docs/api/checkout-policies.md#get-v1-authorize-policies) or [`GET /v1/mandate/policies`](https://provenanceauth.com/docs/api/policies.md#get-v1-mandate-policies).

## 2. Drop the element in your page

```bash
npm install @provenance/embed
```

```html
<script type="module" src="https://unpkg.com/@provenance/embed"></script>

<provenance-rules base-url="https://sandbox-api.provenanceauth.com" publishable-key="prv_pub_1D10TzJo8F73Z7ZHhWGKPpn0K7suJ0se" theme="inherit"></provenance-rules>

<script>
  const el = document.querySelector("provenance-rules");
  el.getToken = async () => (await (await fetch("/admin/provenance/rules-session")).json()).token;
</script>
```

The element calls `getToken()` on load and one minute before each session ends. In React:

```tsx
import { ProvenanceRules } from "@provenance/embed/react";

<ProvenanceRules
  baseUrl={process.env.NEXT_PUBLIC_PROVENANCE_API!}
  publishableKey="prv_pub_1D10TzJo8F73Z7ZHhWGKPpn0K7suJ0se"
  getToken={async () => (await (await fetch("/admin/provenance/rules-session")).json()).token}
/>;
```

## What it shows

| Row | Example | Right side |
| --- | --- | --- |
| A rule with a blank | Order total is over **150** (between 50 and 5,000) | Reject |
| A rule without blanks | Known bad bots | Reject · locked |
| A rule turned off | Signed agent with a covering grant | Approve · off |
| After the customer answers | Location doesn't match billing | Review |
| What happens otherwise | Otherwise | Challenge |
| What happens otherwise, after the customer answers | Otherwise | Allow |
| Version | Version 5, saved 1:20 pm (Draft saved 1:24 pm, after a save; the status line stays empty and carries `data-saved-version`) |  |

Rules show in your policy's own order, the order they run in. A rule you listed and then removed shows as one line saying so; the next mint refuses it.

Checkout's default rows are rules like any other, with the same ID in every account. List them in `rules.show` to show them; the view marks each with `default: true`:

| Rule ID | Row | Right side |
| --- | --- | --- |
| `rul_default_covered_by_mandate` | Within a mandate | Allow |
| `rul_default_looks_like_a_person` | Looks like a person | Allow |
| `rul_default_unclassified_approve` | Unclassified | Allow |
| `rul_default_no_mandate_or_approval` | No mandate or approval | Challenge |
| `rul_default_declined` | Declined by the customer (after the customer answers) | Reject |
| `rul_default_location_matches_billing` | Location matches billing (after the customer answers) | Allow |
| `rul_default_location_differs` | Location doesn't match billing (after the customer answers) | Review |

The view's `policy` names your policy's ID and the version shown, as an assessment's `policy` block does, so the rule an assessment names (`policy.rule.id`) is the row with that `rule_id`.

Capture rules end with what your checks decide for a photo no rule matches: "Flagged by the checks" (Review), drawn as the last rule, then the one "Otherwise" (Allow). A capture rule on a fact that may be missing says what it does then ("If a fact is missing: don't match").

The outcome words, the locked and off labels, the last rows and the version line are fixed: your styles can't relabel a Reject as an Approve. Your rule names are your own text. To see what the element gets, call `GET /v1/embed/rules` with the session: never a rule you didn't list, a list's name, an approver, a key or a decision.

## Changing rules

In an `edit` session each blank is an input: a number within its bounds, a word from its list, or yes and no. A rule you let the session turn off (`can_turn_off`) has a switch. **Add a rule** lists the templates you allowed (`add_from_templates`). **Save** (**Save draft** in a `publish` session) sends only what changed to `POST /v1/embed/rules/versions`, from your staff member's browser with the session:

```json
{
  "base_version": 5,
  "changes": [{ "rule_id": "orders-over-limit", "values": { "when.0.value": 200 } }],
  "add": [{ "template": "store_unsigned_agents" }]
}
```

| What happens | Detail |
| --- | --- |
| A new draft version | The rules rebuilt from `base_version` with only these changes; rules you didn't list and locked rules stay exactly as they were |
| The same checks as the console | The policy's schema, every plan gate and every reference, so a change Free can't save is refused here too |
| Who saved it | The version's `source` is `embed`, `embed_session` is the session's `id`, and `created_by` is the key or console member that minted it. No staff name is recorded |
| What the session reads next | The draft it saved (`draft: true`), and the rules it added |

A value outside its bounds says so on the row ("Between 50 and 5,000") and **Save** waits; the server checks again and answers `400 rules_embed_out_of_scope`, naming the change. If someone saved a newer version or draft first, the save answers `409 policy_version_conflict`; the element reloads the rules and says "Changed elsewhere at 2:04 pm".

The draft goes live like any other: **Review** and **Publish** in the console, or [`POST /v1/authorize/policies/versions/{version}/publish`](https://provenanceauth.com/docs/api/checkout-policies.md#post-v1-authorize-policies-versions-version-publish) ([`POST /v1/mandate/policies/versions/{version}/publish`](https://provenanceauth.com/docs/api/policies.md#post-v1-mandate-policies-versions-version-publish) for agents' rules). Every publish writes an audit row and sends `authorize.policy.published` or `mandate.policy.published` (see [every publish is recorded](https://provenanceauth.com/docs/mandate/guides/policy-builder.md#every-publish-is-recorded)).

## Preview, then publish

In a `publish` session whose scope saves `publish`, the element has **Preview** and **Publish** beside **Save draft**. **Preview** replays the rules as edited over the last 30 days of your own orders with `POST /v1/embed/rules/backtest` and shows one line under the rules, with the same counts and dollar values as the console's backtest:

```text
Last 30 days: would have rejected 3 orders ($1,240) and challenged 14 ($2,915).
```

**Publish** works only after a preview of exactly what's on screen; any edit after the preview clears it. Publishing saves the change as a draft (when there is one) and publishes that draft with the preview's `backtest_id` through `POST /v1/embed/rules/versions/{version}/publish`. **Try 7 days first** (shown when your plan has trial runs) runs the draft as a trial beside the live rules instead.

```json
{ "backtest_id": "rbt_tonq1o_SK1B_IlgZnoSfO_z-9ulf4ibSthiEfZpemOofLZcNGM", "trial_days": 7 }
```

| What the preview answers | Detail |
| --- | --- |
| `totals` | Orders the rules would have approved, challenged and rejected, every rule counted |
| `amounts` | `order.amount` summed per outcome by currency (`unsummed` counts orders without one); an agent's `transaction_amount` for agents' rules. Capture rules preview counts only: a photo has no amount |
| `rules` | For each rule the session shows, how many orders it would have decided and their sum. Never a rule you didn't list, an order or a customer |
| `sentence` | The line above, as the console shows it |
| `backtest_id` | Good for 10 minutes, in this session, for exactly these rules |

A publish without a `backtest_id`, or with one for other rules, another session or older than 10 minutes, is `400 rules_embed_backtest_required`. Only a draft waiting to be published can be published here; rolling back to an older version stays in the console and the API. Each publish writes the audit row and sends the product's `policy.published` webhook (Authorize, Mandate or Attest) with `source: "embed"`, the session's `embed_session` and the key that minted it. Backtests and trial runs are on Pro and above.

## The Advanced view

Mint a session with `rules.advanced: true` (an `edit` or `publish` session) and the element shows **Advanced** beside its title. The Advanced view is the console's rule editor inside your admin: your staff edit a rule whole, or add a new rule from the kind's catalog.

| In the Advanced view | Detail |
| --- | --- |
| **Edit** on a rule | The rule's name, whether all or any of its conditions must hold, each condition (a field, an operator, a value), one level of groups and the outcome (Approve, Challenge, Reject or Review, as the kind offers) |
| **New rule** | A rule from any field in the kind's catalog; checkout rules pick when it runs, at checkout or after the customer answers |
| "Edit in the Provenance console" | A rule with parts the element never edits: routing, notify targets, a webhook, a list, a missing-fact choice, or a field outside the catalog. Locked rules stay read-only |
| **Preview** | Every editing session previews in the Advanced view; each rule shows its own line from the backtest under it |

The element reads the catalog from `GET /v1/embed/rules/catalog`: the kind's fields by key (`order.amount`, a request field as `field:order.ship_to.country`, a spend limit on agents' rules as `velocity:amount_sum:month:agent`), their operators and values in words, and the outcomes per phase. It never lists your own metadata keys or a list operator.

Each field carries its `group`, what the field describes (the order, the agent, the customer's approval, the cart sent with the request), and the element's field picker lists the fields under those groups. No two fields of a kind share a label.

### Narrow the field picker

Add `rules.advanced_fields` to offer only the fields your staff need, by catalog key:

```json
{
  "advanced": true,
  "advanced_fields": ["order.amount", "agent.bot_likelihood_score", "agent.verified", "approval.decision", "approval.passkey_age_days"]
}
```

The catalog then names them in `offered_fields`, and the picker lists only those. A new condition reads one of them; a rule the session edits keeps the fields it already reads, so editing never drops a condition. A key outside the kind's catalog, or the option without `advanced: true`, is `400` at mint; a save that adds a condition on another field is `400 rules_embed_out_of_scope`.

A save sends whole rules in `rules`, beside any `changes`:

```json
{
  "base_version": 5,
  "rules": [
    {
      "rule_id": "rul_01M7Q4ZM8TA1ZE6PD3RJZV7WMX",
      "label": "Big or unsigned",
      "match": "any",
      "items": [
        { "field": "order.amount", "op": "gt", "value": 300 },
        { "field": "agent.verified", "op": "eq", "value": false }
      ],
      "outcome": "challenge"
    },
    {
      "label": "Uncovered gift orders",
      "match": "all",
      "items": [
        { "field": "checkout.covered", "op": "eq", "value": "none" },
        { "match": "any", "conditions": [{ "field": "order.amount", "op": "gte", "value": 900 }] }
      ],
      "outcome": "reject"
    }
  ]
}
```

A rule with `rule_id` replaces a rule the session shows (it keeps its phase); a rule without one is new, and the session shows it afterwards. Rules you didn't list and locked rules stay exactly as they were, and the rebuilt rules run the same checks as the console.

The bounds you set on blanks hold in the template view; a rule edited whole takes any value its field allows, so lock a rule, or mint without `advanced`, to keep a value within bounds.

The Advanced view is on every plan. The rules inside keep the document's own line, as in the console: on Free, any-of and none-of matching, spend and request limits and named lists are Pro.

A rule with no conditions matches every request ("Every request"), so a last rule such as "Otherwise → Review" catches what the rules above it let through. A condition can also test whether a field holds a value at all: **is empty** and **isn't empty** (`is_empty`, `is_not_empty`, with `"value": true`).

A rule, or a group inside it, matches when **all** of its conditions hold, **any** one of them, or **none** of them (`"match": "none"`, the NOT group). A condition on a missing fact doesn't hold, so it counts toward "none of these".

## Full control

Rules are read top to bottom within each phase, and the first rule that matches decides. The order is part of what a rule does, so a session that edits rules usually needs to move them too. Add `rules.manage: true` to give the session full control over every rule it shows:

```json
{
  "show": [
    { "rule_id": "orders-over-limit", "fields": [{ "path": "when.0.value", "min": 50, "max": 5000 }] },
    { "rule_id": "rul_default_covered_by_mandate" },
    { "rule_id": "known-bad-bots", "locked": true }
  ],
  "advanced": true,
  "manage": true
}
```

| On each rule that isn't locked | How |
| --- | --- |
| Move it | Drag the handle at the start of the row, focus the handle and press the up and down arrow keys, or **Move up** and **Move down** in the row's **⋯** menu |
| Turn it off | **Turn off** in the **⋯** menu, on every rule (`can_turn_off` isn't needed) |
| Duplicate it | **Duplicate** in the **⋯** menu: the copy goes right below the original when you save |
| Delete it | **Delete** in the **⋯** menu, with **Undo** on the status line until you save |
| Edit its values | Every number, word and yes-or-no value is an input; a rule you listed with `fields` keeps those bounds |
| Edit its logic | With `advanced`, a tap on the rule's name (or **Edit** in the **⋯** menu) opens its conditions and outcome, the default rows included. Changing a default row's conditions or outcome makes it your own rule, with a new id |

Everything stays a draft until **Save** (or **Preview** and **Publish** in a `publish` session). A save sends the changes beside any others:

```json
{
  "base_version": 5,
  "remove": ["rul_01M7Q4ZM8TA1ZE6PD3RJZV7WMX"],
  "order": ["rul_default_no_mandate_or_approval", "rul_01M7Q4ZN0QGR3B8WJ8Y7K6V5T4", "rul_default_covered_by_mandate"],
  "add": [{ "copy_of": "rul_01M7Q4ZN0QGR3B8WJ8Y7K6V5T4" }]
}
```

| Field | Detail |
| --- | --- |
| `order` | Every rule the session shows that is still there, in the new order. Rules you didn't list keep their places, and a locked rule keeps its place among the shown rules. A rule never changes phase by moving |
| `remove` | Rules to delete. A rule can't be changed and deleted in the same save |
| `add[].copy_of` | A copy of a shown rule, placed right below it |
| `rules[].after` | With `advanced`: a new rule placed right below this shown rule, in the same phase |

Any of these from a session without full control is `400 rules_embed_out_of_scope`. A locked rule shows "Locked in this admin" and has no handle.

Each phase ends with its built-in rows ("Otherwise → Challenge"): what happens when no rule matched. They always run last and can't be deleted, and a full-control session picks their outcome from the row's own list (the view marks them `editable`, with their `key` and `choices`).

A save sends `fallback`, such as `{ "uncovered": "reject" }`; it's stored on the policy document as `fallback` and a row set back to its built-in outcome is left out.

A rule with no conditions above the built-in rows means they never run, and the component says so under them. That rule's **⋯** menu offers **Use as fallback**: its outcome goes into the phase's built-in rows and the rule is deleted, in one draft.

A session with full control lists no row for a rule its drafts deleted. Your next mint may still list that rule: a rule missing from the policy is left out of the session rather than refused.

Full control is on every plan, conditions and outcomes included. Mandate limits are a fixed set of rows, so `manage` is refused for them.

With full control the session shows every rule of the policy by default, the ones you didn't list too (`visibility: "all"`), and each can be changed as a listed rule can. Set `visibility: "session"` to show only the rules you list and the ones the session adds, as the live demos do for their visitors. Without `manage`, `session` is the default; `all` then shows the other rules read-only.

## Mandate limits

The `mandate_limits` kind shows your account's limits for the sub-agents your agents hand grants to, as "Mandate rules": the overall cap and a sub-agent's budget settings, then the rows that reject, then the rows that ask. Mint it with a key that has the `mandate` scope, and list rows by their fixed IDs:

```json
{
  "widget": "rules",
  "object_id": "mandate_limits",
  "mode": "publish",
  "rules": {
    "show": [
      { "rule_id": "cap", "fields": [{ "path": "amount", "min": 500, "max": 10000 }] },
      { "rule_id": "budget", "fields": [{ "path": "at_limit", "values": ["continue", "ask"] }] },
      { "rule_id": "allowed_mcc", "locked": true },
      { "rule_id": "named_merchants", "locked": true },
      { "rule_id": "refuse_over_cap", "fields": [{ "path": "value", "min": 0, "max": 50 }] },
      { "rule_id": "refuse_over_share", "fields": [{ "path": "value", "min": 0, "max": 50 }], "can_turn_off": true },
      { "rule_id": "ask_over_cap" }
    ],
    "saves": "publish"
  }
}
```

| Row ID | Row | Right side | Blank |
| --- | --- | --- | --- |
| `cap` | Overall cap **2,400** USD |  | `amount` |
| `budget` | Share: **Flexible share** · At the limit: **Keep going** |  | `allocation`: `shared` (Flexible share), `reserved` (Reserved); `at_limit`: `stop` (Stop), `ask` (Ask me), `continue` (Keep going) |
| `allowed_mcc` | Not an allowed kind of merchant (MCC) | Reject |  |
| `named_merchants` | Not a named merchant | Reject |  |
| `blocked_mcc` | A blocked kind of merchant (MCC) | Reject |  |
| `blocked_merchants` | A blocked merchant | Reject |  |
| `refuse_over_cap` | Over **20**% past the overall cap | Reject | `value` |
| `refuse_over_share` | Over **20**% past a sub-agent's limit | Reject | `value` |
| `ask_over_cap` | Otherwise over the overall cap | Review |  |

`refuse_over_share` applies when `at_limit` is `ask`: a person is asked past a sub-agent's limit, and past the margin it's rejected (off: asked at any amount over).

Each rule row names the field it stands for on a second line (`allowed_mcc · miss`, `over_limit.budget = ask`).

With `advanced: true`, a margin row whose `value` is a blank also offers its unit: a fixed amount in the cap's currency instead of a percentage (your `min` and `max` bound the percentage; a fixed amount is at most the cap). The merchant lists and MCC ranges themselves are never shown or edited in the element: set them with [`PUT /v1/mandate/settings/limits`](https://provenanceauth.com/docs/api/grants.md#put-v1-mandate-settings-limits).

Nothing replays for mandate limits, so a publish session shows **Save draft** and **Publish** only, and there's no trial run. What a published version does is in [mandate limits](https://provenanceauth.com/docs/mandate/guides/subagent-limits.md).

To fill the inputs from outside the element (a "Load a scenario" button on your page), call `loadValues` on it. The values load as unsaved edits, checked against their bounds like typed ones; **Save** or **Publish** sends them:

```js
document.querySelector("provenance-rules").loadValues(
  { budget: { at_limit: "ask" }, refuse_over_share: { value: 20 } },
  { refuse_over_share: true },
);
```

`loadValues` works for every kind: rows by `rule_id`, blanks by `path`.

## On a phone: the hosted rules page

When there's no web admin to drop a tag into (a phone, a no-code admin, an email to a manager), mint a link instead. [`POST /v1/embed/links`](https://provenanceauth.com/docs/api/embeds.md#post-v1-embed-links) takes the same body as the session, plus `session_ttl`, and returns a page on Provenance's console with your branding, laid out for phones:

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/embed/links \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "widget": "rules", "object_id": "checkout", "mode": "edit", "rules": { "show": [ { "rule_id": "rul_default_no_mandate_or_approval", "locked": true } ] }, "session_ttl": 1800 }'
```

**Node**

```ts
const link = await prov.embed.createLink({
  widget: "rules",
  objectId: "checkout",
  mode: "edit",
  rules: { show: [{ ruleId: "orders-over-limit", fields: [{ path: "when.0.value", min: 50, max: 5000 }] }] },
  sessionTtl: 1800,
});
// link.url opens once within 15 minutes; the page then works for 30 minutes.
```

**Python**

```python
link = prov.embed.create_link(
    widget="rules",
    object_id="checkout",
    mode="edit",
    rules={"show": [{"rule_id": "orders-over-limit", "fields": [{"path": "when.0.value", "min": 50, "max": 5000}]}]},
    session_ttl=1800,
)
```

**Go**

```go
link, err := embed.CreateLink(ctx, pv.EmbedLinkParams{
	Widget:     pv.WidgetRules,
	ObjectID:   "checkout",
	Mode:       "edit",
	SessionTTL: 1800,
	Rules:      &pv.RulesEmbedScope{Show: []pv.RulesEmbedShow{{RuleID: "known-bad-bots", Locked: true}}},
})
```

The link opens once, within 15 minutes, and the page then works for `session_ttl` seconds (up to 60 minutes) in the browser that opened it. It shows the same element with the same scope: the same rows, blanks, saves, previews and publishes, each attributed to the page's session and the key that minted the link. The response echoes the scope as stored. See [the hosted page](https://provenanceauth.com/docs/embeds/hosted-page.md) for how links open.

The page renews its token every 15 minutes at most. The rules it added and a preview it took hold across renewals, for as long as the page works.

## Per-visitor drafts in sandbox

A demo or a test run where many people share one sandbox account needs each person's changes kept to themselves. Mint each person's session with `rules.draft_group` set to your own id for them (a demo session id, say), with `saves: "draft"`:

| What happens | Detail |
| --- | --- |
| Their saves | Drafts in that group, with `draft_group` on the version |
| What they read | Their group's newest draft, else the live rules. Never another group's draft, which also never causes a `409` |
| A fresh session for the same group | Reads the group's draft and the rules the group added, so your server can mint a new session every 15 minutes |
| Publishing | A `publish` session publishes only its own group's drafts; another group's reads as `404` |
| Your version list | Leaves the groups' drafts out; `GET /v1/authorize/policies/versions?draft_group=…` lists one group's |
| Cleanup | A group's unpublished drafts are deleted 24 hours after they were saved |

To decide with a person's draft, pass its version and group on the assess call, from your server:

**curl**

```bash
curl -s -X POST $PROVENANCE_API/v1/authorize/checkout_assessments \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "cart": { "order_id": "ord_1042", "total": 10000, "currency": "USD", "merchant_id": "brightbox", "origin": "https://brightbox.example", "items": [] }, "policy_version": 7, "draft_group": "demo-session-81f2" }'
```

**Node**

```ts
const assessment = await prov.authorize.assessments.create({ cart, policyVersion: 7, draftGroup: "demo-session-81f2" });
// assessment.policy.version is 7: the group's draft decided.
```

**Python**

```python
assessment = prov.authorize.assessments.create(cart=cart, policy_version=7, draft_group="demo-session-81f2")
```

[`POST /v1/mandate/assessments`](https://provenanceauth.com/docs/api/intent-tokens.md#post-v1-mandate-assessments) takes the same two fields for agents' rules. Both are sandbox only: in live, `policy_version` is `400 parameter_invalid` and the call never falls back to the live rules. A draft in another group, or a grouped draft without its group, is `400`; a version that doesn't exist (or was cleaned up) is `404`.

## Build the scope in the console

On **Rules**, **Orders**, **Agent actions** or **Captures**, open **Embed in your admin**. Pick the rules your team sees, lock a rule or let them turn it off, mark the values they change with the lowest and highest they may pick, choose the templates they may add, and what they can do: view, edit and save drafts, or edit and publish after a preview.

**Advanced view** adds `advanced: true` to an editing session, and **Full control** adds `manage: true`. On **Your agents**, **Mandate limits** builds the scope for your account's limits instead of the agents' rules.

The page writes the mint code with that scope (curl, Node, Python and Go), shows a live preview of exactly what your team gets, and **Copy link** copies a hosted page link. Nothing is saved there: the scope lives in your server's code.

## Events

| Event | When | Detail |
| --- | --- | --- |
| `pv:ready` | The session opened | `widget`, `object_id`, `mode` |
| `pv:rules_saved` | A change was saved | `version`, `draft` |
| `pv:rules_published` | A draft was published from the element | `version`, `trial` |
| `pv:rules_conflict` | A newer version was saved elsewhere; the rules reloaded | `latest_version` |
| `pv:token_refresh_failed` | `getToken()` couldn't renew the session | `widget` |
| `pv:error` | The element couldn't start, or a save, preview or publish was refused | `code`, `message` |

## Embed or your own

|  | This embed | The hosted rules page | Your own UI on the API |
| --- | --- | --- | --- |
| What it is | `<provenance-rules>` in your admin | A page Provenance hosts, opened by a link | Your screen calling the policy path from your backend |
| Fits | A web admin you control | Phones, a no-code admin, an email to a manager | Full control of the look and flow |
| Work | Mint a session, drop the tag | Mint a link | Build the screen, its wording and validation |
| Scope | Passed on each mint | Passed on each link | Whatever your key can do |

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| `400` [`rules_embed_rule_missing`](https://provenanceauth.com/docs/platform/errors.md#rules_embed_rule_missing) | A listed rule isn't in the policy | List IDs from the policy, or save the rule first. |
| `403` [`insufficient_scope`](https://provenanceauth.com/docs/platform/errors.md#insufficient_scope) | The key lacks the kind's product scope | Mint checkout rules with an Authorize key, agents' rules with a Mandate key. |
| `401` [`embed_token_invalid`](https://provenanceauth.com/docs/platform/errors.md#embed_token_invalid) | The session expired, is for another widget, or is a `view` session that tried to save | Mint a new one (with `mode: "edit"` to save), or give the element `getToken()`. |
| `400` [`rules_embed_out_of_scope`](https://provenanceauth.com/docs/platform/errors.md#rules_embed_out_of_scope) | A save changed something the scope doesn't allow, or sent whole rules without the Advanced view | Change only the blanks, within their bounds, on rules the session shows; mint a wider scope (or `advanced: true`) to allow more. |
| `400` [`rules_embed_backtest_required`](https://provenanceauth.com/docs/platform/errors.md#rules_embed_backtest_required) | A publish without a preview of exactly that draft | Preview the draft's rules, then publish with the `backtest_id` within 10 minutes. |
| `409` [`policy_version_conflict`](https://provenanceauth.com/docs/platform/errors.md#policy_version_conflict) | A newer version or draft was saved first | Read the rules again and save on the latest. |
| `402` [`plan_required`](https://provenanceauth.com/docs/platform/errors.md#plan_required) | The rules as saved need a higher plan, or a preview or trial run below Pro | See [what each plan includes](https://provenanceauth.com/docs/mandate/guides/policy-builder.md#what-each-plan-includes). |
| `503` [`rules_embed_unavailable`](https://provenanceauth.com/docs/platform/errors.md#rules_embed_unavailable) | The rules couldn't be read | Retry shortly. |

## See also

- [Embeds](https://provenanceauth.com/docs/embeds.md)
- [Admin results and requests](https://provenanceauth.com/docs/embeds/admin-tools.md)
- [Policy builder](https://provenanceauth.com/docs/mandate/guides/policy-builder.md)
