Partner Integration Guide

Let your agents act. Keep a person on the hook.

Everything a platform needs to embed ClearedBy: one org per merchant, agents that propose instead of act, reviewers who approve inside your product, and an executor that only runs what was signed off. Written for the backend engineer who builds it and the product person who owns it. New here? Start with the 15-minute quickstart; every signature is in the API reference.

API v1 @clearedby/sdk 0.1.1 @clearedby/react 0.1.0 Updated 24 Sep 2026
On this page
  1. Overview
  2. Concepts
  3. One-time setup
  4. Worked example: Black Friday tags
  5. Building the review UI
  6. Executor security rules
  7. Approval rules for merchants
  8. Claims vs verified evidence
  9. Cancel, withdraw, undo
  10. Webhooks reference
  11. Data protection
  12. Error codes
  13. Limits
  14. Testing and go-live

01Overview

ClearedBy is the approval layer between your AI agent and the merchant's store. The agent never writes to Shopify directly. It proposes a change, the merchant's rules decide whether a person needs to see it, a person approves it inside your product, and ClearedBy issues a signed authorisation. Your executor carries out exactly that change and reports back what happened.

Think of it as a harness around the agent. The agent can be as capable as you like, because what it can actually do is bounded by what a rule or a person signed off:

  1. Propose. Your agent describes the change: the action, the exact parameters and its case for doing it.
  2. Policy. The merchant's approval rules clear small, safe changes on their own, reject what's never allowed, and hold the rest for a person.
  3. Human. A reviewer sees the held change in your app and approves, rejects, escalates or sends it back for a revision.
  4. Signed authorisation. Every approval produces an Ed25519-signed receipt naming the org, the action and the exact parameters. It can't be altered or reused for a different change.
  5. You execute. Your executor verifies the authorisation, checks the store's current state, and makes the change with its own Shopify credentials.
  6. Report. The executor reports what happened, item by item. ClearedBy compares that with what was approved and keeps a tamper-evident record of the whole chain.
The life of one change Six steps left to right: your agent proposes, ClearedBy applies the policy, your reviewer decides, ClearedBy issues a signed authorisation, your executor executes, and your executor reports back. Small reversible changes skip the reviewer. A reviewer can send a change back to the agent to revise. small, reversible changes clear on their own YOUR AGENT CLEAREDBY YOUR REVIEWER CLEAREDBY YOUR EXECUTOR YOUR EXECUTOR 1 2 3 4 5 6 Propose POST /v1/gate params + proof Policy clear, hold or reject Human approve, reject, send back Authorise signed receipt (Ed25519) Execute verifyDispatch, then Shopify Report POST complete per-item results sent back with a reason: the agent revises and resubmits
Grey steps run in your systems. Green steps run in ClearedBy. Nothing reaches the store without a signed authorisation from step 4.

What you build, and what ClearedBy does

You buildClearedBy does
The agent, and the code that turns its intent into a proposalValidates the proposal against the Shopify action catalogue and the merchant's stores
The review screens in your product (or you drop in our @clearedby/react components)Applies the merchant's rules, works out who can approve, checks each decision against that person's authority
The executor that holds your Shopify write credentialsSigns every approval, delivers it to your executor, retries, and lets you check it hasn't been cancelled
The "Your approval rules" settings screenTurns plain settings into a policy, and makes looser changes wait for the merchant's owner
Nothing: no audit codeKeeps a signed, tamper-evident record of every proposal, decision, cancellation and result

Your merchants never sign up for ClearedBy, never log in to it and never see it. The whole integration runs through the API with no dashboard work, for you or for them.

02Concepts

Partner

That's you: the platform embedding ClearedBy. You get a partner key (cb_partner_...) from us. It lives on your servers only. It sets your account-wide settings (where approvals are sent, where alerts go), creates orgs, manages reviewers and rules, reads clearances for your review UI, attaches verified evidence, mints decision tokens, and can cancel. It can't propose changes and it can't approve anything.

Org: one per merchant company

Create one ClearedBy org for each company you serve, identified by your own external_id. An org has a base currency, a list of stores, reviewers and approval rules. Each org gets its own requester keys (cb_live_...), which your agents and your executor use for that merchant. A partner key only sees the orgs it created. Any other org id returns 404 not_found.

Reviewers (external_subject)

A reviewer is a person at the merchant who can approve. You identify them with your own id for that person, the external_subject. Each reviewer has a role (owner, admin or reviewer) and an authority: a map from action name to the largest amount they may approve, in minor units of the org's currency.

authority
{ "shopify.refund.create": 50000, "*": 0 }
// refunds up to £500.00 (in a GBP org), and any action that carries no amount

Keys are exact action names or *. There are no prefix patterns: shopify.* is not a wildcard here. Actions with no params.amount (tags, stock, prices, product edits) count as zero, so "*": 0 lets someone approve all of those but no money. Reviewers you provision have no ClearedBy login and get no email from us unless you add "email" to their channels.

Stores

An org lists the Shopify stores its keys may act on (shop_domains, each a permanent *.myshopify.com domain, up to 50). Every shopify.* proposal names its store in params.store, and ClearedBy refuses a store that isn't on the list. So a key for one merchant company can never act on another company's store, even though both are yours.

Approval rules

Every new org starts with a set of plain-English approval rules, already switched on (see section 7). You show them as sliders and toggles. You can make them stricter yourself. Making them looser needs an OK from one of the merchant's owners or admins.

Clearances

Each proposal becomes a clearance (a work item) with an id. It moves through these statuses:

StatusMeaningFinal?
pendingHeld, waiting for a person.No
escalatedHanded to a more senior person, or escalated because nobody decided in time.No
clearedApproved, by a rule or a person. Carries a signed receipt. Your executor may act.Yes, until revoked
rejectedRefused, by a rule or a person.Yes
sent_backReturned to the agent to revise, with a reason. The agent resubmits as a new, linked clearance.Yes, for this attempt
expiredNobody answered in time. Nothing happens: a lapsed request is never approved automatically.Yes
revokedApproved, then cancelled before it ran.Yes
withdrawnPulled back by the side that asked, while still open.Yes

Receipts

Every approval carries an Authorisation Receipt: a small JSON document, signed with Ed25519 by ClearedBy, that names the org, the action, the exact parameters (and their hash), who approved, who it is for (the audience) and when it expires (10 minutes after issue). Anyone can check it offline against our public keys at https://app.clearedby.com/.well-known/clearedby-keys. Change one character of the parameters and the signature breaks. Whether it has since been cancelled is a separate, online question: GET /v1/receipts/:receipt_id/status.

Evidence provenance

Agents attach their case for a change as proof: a reason, a confidence and evidence cards. ClearedBy labels all of it Agent says. Facts your backend looked up itself, and attaches with your partner key, are labelled Verified by your name. Figures ClearedBy computes (batch counts, the largest price drop, the currency check, running totals) are labelled Checked by ClearedBy. See section 8.

The three credentials

CredentialWho holds itWhat it can do
cb_partner_...Your backend onlyPartner settings. Provision orgs, reviewers, keys and rules; list, revoke and rotate org keys; manage webhook subscriptions. Read clearances and org signing secrets (with ?org_id=). Attach verified evidence. Mint decision tokens. Revoke and withdraw. Erasure and retention. Can't propose or approve.
cb_live_...One or more per merchant org: your agent, your executorPropose (POST /v1/gate), dry-run, read, report completions, build undos, subscribe to webhooks, revoke its own approvals, withdraw its own requests. Can't approve.
cb_dt_...Your backend, for a few secondsA decision token naming one reviewer: single use, valid for up to 5 minutes. The only credential that can record a person's decision.

Because no key can approve, a compromised agent can at worst propose. And the agent that asked for a change can never approve it.

03One-time setup checklist

No dashboard is involved at any point. The base URL is https://app.clearedby.com. Bodies are JSON, unknown fields are rejected, and every error uses the envelope {"error": {"code", "message", "hint"}}.

Once, for your platform

  • Get your partner key from ClearedBy and store it in your secret manager. Never ship it to a browser or give it to an agent.
  • Stand up your executor endpoint: an https URL that receives signed approvals (section 6).
  • Stand up your events endpoint: an https URL that receives webhooks (section 10).
  • Register your executor, your alert contact and your retention window once, with PATCH /v1/partner/settings (below). From then on every org you create sends its approvals to your executor, with no per-org or per-request setup.

Partner settings

GET and PATCH /v1/partner/settings (SDK: partner.getSettings(), partner.updateSettings()) hold your account-wide settings. They apply to every org you own. PATCH takes any subset of the fields, and null clears one.

FieldWhat it does
execution_urlYour executor. Every cleared item in your orgs is dispatched here, as a signed v2 envelope with the receipt, unless something more specific names a destination (see where approvals are sent).
notify_urlThe same for the other verdicts: rejected, expired and sent_back. These dispatches authorise nothing; use them to tell your agent or your UI. They are not the lifecycle webhooks (decision.pending and so on), which you still subscribe to per org.
alert_emailWhere operational alerts about your orgs are emailed (see partner alerts).
alert_webhook_urlWhere alerts are POSTed. The first time you set it, the response includes alert_webhook_secret, once.
rotate_alert_webhook_secrettrue mints a new alert secret and returns it once. The old one stops working.
retention_days1 to 3,650. How long readable data is kept (section 11). Partner orgs keep history indefinitely until you set it.
themeYour design tokens for the embeddable review components: colors (primary, primaryText, surface, surfaceAlt, border, text, mutedText, success, warning, danger), radius, fontFamily, fontSize, spacing, shadow and a dark variant. Plain CSS values only. Replaces the stored theme; null clears it. A merchant can have its own override with PATCH /v1/partner/orgs/:id {"theme"}. See matching your app's design.

URLs must be public https addresses. ClearedBy checks them when you set them, DNS included: a private, loopback, link-local or cloud-metadata address, or a host that doesn't resolve, returns 400 blocked_destination.

partner-settings.ts (run once)
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const s = await partner.updateSettings({
  execution_url: 'https://exec.yourapp.example/clearedby/on-decision',
  notify_url: 'https://exec.yourapp.example/clearedby/on-verdict',
  alert_email: 'platform-oncall@yourapp.example',
  alert_webhook_url: 'https://ops.yourapp.example/clearedby/alerts',
  retention_days: 90,
})
if (s.alert_webhook_secret) await secrets.put('cb:alert-secret', s.alert_webhook_secret)   // shown once

// Later: s.recent_alerts lists the last 20 alerts and where each was delivered.

A single merchant company can override the partner defaults with PATCH /v1/partner/orgs/:org_id and {"execution_url": ..., "notify_url": ...}; null removes the override, and the org response shows it (null means your default applies).

For each merchant company

  1. Create the org with partner.createOrg() (POST /v1/partner/orgs): external_id, name, currency and shop_domains. Store the one-time api_key.
  2. Mint a second key for your executor with partner.createOrgKey() (POST /v1/partner/orgs/:org_id/keys), so agent and executor keys can be rotated separately.
  3. Fetch the org's signing secret with GET /v1/signing-secrets?org_id= and your partner key (SDK: partner.getSigningSecret(orgId)). It's stable per org; your executor uses it to check dispatch signatures.
  4. Add reviewers with partner.upsertReviewer() (PUT /v1/partner/orgs/:org_id/reviewers/:external_subject). Add at least two people with refund authority if the merchant wants two-person approval for large refunds.
  5. Subscribe to webhooks with partner.createWebhook(orgId, ...) (POST /v1/webhooks?org_id= with your partner key; the org key works too). Store the one-time secret.
  6. Show the approval rules (partner.getRules()). They're already on.
  7. Dry-run one proposal with check() (POST /v1/gate?dry=1) to confirm the store and rules are set up.
  8. Check dispatch end to end once: propose a small change the default rules clear on their own (a tag change on a few products in a test org). Your execution_url receives it, and delivery(id) (GET /v1/gate/:id/delivery) then shows delivered: true.

With the SDK, the whole onboarding is one function you call from your own signup or "connect store" flow:

onboard-merchant.ts
import { ClearedByPartner } from '@clearedby/sdk'
import { secrets } from './your-secret-store'   // your own encrypted storage

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

export async function onboardMerchant(shop: { id: string; name: string; currency: string; domains: string[] }) {
  // 1. The org. Idempotent on external_id: a repeat returns the same org, created: false, no key.
  const org = await partner.createOrg({
    external_id: `shop_${shop.id}`,
    name: shop.name,
    currency: shop.currency,              // ISO 4217, e.g. 'GBP'
    shop_domains: shop.domains,           // permanent *.myshopify.com domains
  })
  if (!org.created) return org.org_id    // already onboarded
  await secrets.put(`cb:${org.org_id}:agent`, org.api_key!)    // shown once

  // 2. A separate key for the executor.
  const exec = await partner.createOrgKey(org.org_id, { name: 'executor' })
  await secrets.put(`cb:${org.org_id}:executor`, exec.api_key)

  // 3. The org's dispatch signing secret (stable per org). Approvals already route to
  //    your partner execution_url: nothing to configure per org.
  await secrets.put(`cb:${org.org_id}:signing`, await partner.getSigningSecret(org.org_id))

  // 4. Lifecycle webhooks for this org (pending, escalated, sent back, ...), with the partner key.
  const hook = await partner.createWebhook(org.org_id, {
    url: 'https://api.yourapp.example/clearedby/events',
    events: ['decision.pending', 'decision.escalated', 'decision.sent_back', 'decision.cleared',
             'decision.rejected', 'decision.expired', 'decision.completed', 'decision.revoked', 'decision.withdrawn'],
  })
  await secrets.put(`cb:${org.org_id}:whsec`, hook.secret)   // shown once

  return org.org_id
}

Rotating and revoking org keys

You manage every org's cb_live_ keys with your partner key; the merchant never has to.

  • See them: partner.listOrgKeys(orgId) (GET /v1/partner/orgs/:org_id/keys) lists each key's name, prefix, last_used_at and whether it is active. Never the secret.
  • Rotate one: partner.rotateOrgKey(orgId, keyId, { graceSeconds: 3600 }) (POST .../keys/:key_id/rotate) returns a new key with the same name and agent binding, once. The old key keeps working for the grace period (up to 24 hours; default 0, which stops it at once), so deploy the new key, then let the old one lapse.
  • Revoke one: partner.revokeOrgKey(orgId, keyId) (DELETE .../keys/:key_id). Its next request gets 401. Do this at once if a key leaks.
rotate-executor-key.ts
const keys = await partner.listOrgKeys(orgId)
const current = keys.find((k) => k.active && k.name === 'executor')!
const next = await partner.rotateOrgKey(orgId, current.key_id, { graceSeconds: 3600 })
await secrets.put(`cb:${orgId}:executor`, next.api_key)   // shown once
// Redeploy the executor within the hour; after next.replaced.revokes_at the old key is refused.

04Worked example: the Black Friday tag cleanup

Acme Outdoor asks your assistant to get the catalogue ready for Black Friday: take last year's bf-2025 tag off every product that still has it, and add black-friday. That's 1,240 products. We'll follow it from the first proposal to the undo the following week.

The cast: Sam (user_17) owns the store. Priya (user_22) runs merchandising. Your agent proposes, your backend enriches and decides, your executor writes to Shopify.

1. Create the org and the reviewers

Run onboardMerchant() from the setup checklist, then add the two people. Authority is in minor units, and "*": 0 covers every action that carries no amount, such as tag changes.

reviewers.ts
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const orgId = await onboardMerchant({ id: '8841', name: 'Acme Outdoor', currency: 'GBP', domains: ['acme-outdoor.myshopify.com'] })

await partner.upsertReviewer(orgId, 'user_17', {
  display_name: 'Sam R.',          // shown in the audit trail; initials are fine
  role: 'owner',
  authority: { '*': 0, 'shopify.refund.create': 50000 },   // all non-money actions, refunds up to £500
})
await partner.upsertReviewer(orgId, 'user_22', {
  display_name: 'Priya K.',
  role: 'reviewer',
  authority: { 'shopify.product.tags.update': 0, 'shopify.product.update': 0, 'shopify.inventory.set': 0 },
})

A PUT replaces the person's whole record, so it's safe to repeat. Removing someone (partner.removeReviewer(orgId, 'user_22')) stops their authority at once and keeps their history.

2. Check the rules

The default rules are already on. Tag changes touching up to 200 products go through on their own, so a 1,240-product change will wait for a person.

rules.ts
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

const rules = await partner.getRules(orgId)
for (const line of rules.summary) console.log(line.sentence)
// "Tag changes to up to 200 products go through on their own; bigger batches need your OK"
// "Refunds over £25 need your OK"
// ... one line per setting, already in plain English

3. The agent proposes

The agent reads the current tags and builds a shopify.product.tags.update proposal. Each change carries the complete tag list before and after, not a delta. Three details matter:

  • An idempotency key. If the call times out and your code retries it, the same key replays the first answer instead of creating a second clearance. Keys last 24 hours. The same key with a different body is refused (422 idempotency_key_reused).
  • subject_id rules. A proposal about a shopper (refunds, orders, customers, or any params with customer_id, customer or email) must name the shopper in context.subject_id, or partner orgs refuse it with 422 subject_id_required. A tag change isn't about a shopper, so it doesn't need one. A refund would carry context: { subject_id: 'gid://shopify/Customer/7208314339542' }.
  • batch_id. One call takes up to 10,000 changes. Bigger jobs are split into several calls that share context.batch_id, and GET /v1/gate?batch_id= finds them all again.
agent-propose.ts
import { ClearedBy, type GateInput } from '@clearedby/sdk'

const cb = new ClearedBy({ apiKey: await secrets.get(`cb:${orgId}:agent`) })
const STORE = 'acme-outdoor.myshopify.com'

// Read-only Shopify access is fine for the agent: it only needs to describe the change.
const products = await shopifyRead.productsWithTag(STORE, 'bf-2025')      // 1,240 products
const changes = products.map((p) => ({
  product_id: p.id,                                  // gid://shopify/Product/...
  label: p.title,                                    // what the reviewer sees
  before: p.tags,                                    // the complete current list
  after: [...p.tags.filter((t) => t !== 'bf-2025'), 'black-friday'],
}))

const input: GateInput = {
  action: 'shopify.product.tags.update',
  params: { store: STORE, count: changes.length, changes },
  audience: 'https://exec.yourapp.example',          // the receipt will name your executor
  context: {
    batch_id: 'bf-2026-tags',
    summary: `Swap bf-2025 for black-friday on ${changes.length} products`,
    requested_by_subject: 'user_22',                 // optional: the person who asked the assistant
  },
  proof: {
    reason: 'Priya asked to prepare Black Friday tags. Last year\'s tag is still on these products.',
    confidence: 0.95,
    evidence: [
      { type: 'threshold', value: { label: 'Products touched', value: changes.length, limit: 200, unit: 'products', status: 'over' } },
      { type: 'table', value: { columns: ['Product', 'Removed', 'Added'],
          rows: changes.slice(0, 50).map((c) => [c.label, 'bf-2025', 'black-friday']) } },   // keep tables to ~50 rows
    ],
  },
  idempotencyKey: `bf-2026-tags:${jobId}:v1`,
}

const r = await cb.gate(input)
// r.status === 'pending' (1,240 is over the 200-product limit), r.id is the clearance id
No dispatch URL in the proposal

The agent doesn't say where the approval goes. When the change clears, ClearedBy sends it to your partner execution_url (or the org's override), signed with the org's signing secret and carrying the receipt. A gate call can still name a one-off destination with a top-level on_decision.cleared.url; that wins for that request only.

4. Your backend attaches verified evidence

ClearedBy fires decision.pending within a second or two. Your backend looks at Shopify itself and attaches what it found, with the partner key. The reviewer will see it badged Verified by your name, next to the agent's own claims.

on-pending.ts
import { ClearedByPartner } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

export async function onPending(evt: { org_id: string; data: { id: string; action: string } }) {
  if (evt.data.action !== 'shopify.product.tags.update') return
  const item = await partner.get(evt.org_id, evt.data.id)
  const { store, changes } = item.params as { store: string; changes: { product_id: string }[] }

  const live = await shopifyRead.tagAudit(store, 'bf-2025')     // your own Shopify lookup
  await partner.attachEvidence(evt.org_id, evt.data.id, [{
    type: 'catalogue_check',
    label: 'Shopify catalogue check',
    value: { products_with_bf_2025: live.count, proposed: changes.length, in_clearance_collection: live.inClearance },
    source_ref: `shopify:${store}:tag:bf-2025`,
  }])
}

Attaching evidence doesn't re-evaluate the clearance or unlock anything. It gives the person deciding facts they can trust.

5. The reviewer sends it back

Sam opens the request in your app. Your verified check shows 40 of the products are in the Clearance collection, which shouldn't get a Black Friday tag. Sam taps Send back and types why. Your backend turns the click into a decision:

decide.ts
// Only offer the buttons this person can use.
const perms = await partner.permissions(orgId, itemId, 'user_17')
// perms.can -> ['clear', 'reject', 'send_back', 'escalate']

// Sam clicked "Send back". Mint a token naming Sam, pinned to this item, then decide.
const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17', workItemId: itemId })
await partner.decide(itemId, { decision: 'send_back', reason: 'Leave out the 40 products in the Clearance collection' }, { token })

external_subject must come from your own session for the signed-in user, never from the browser's request body. ClearedBy checks that person's authority itself, so your backend can't approve on someone's behalf beyond what they're allowed.

6. The agent revises and resubmits

The agent learns about the send-back from a sent_back dispatch to your notify_url, from the decision.sent_back webhook (your backend wakes it), or from wait(). It regenerates the proposal and resubmits it against the original, so the whole chain stays one lineage. Each sent-back clearance accepts exactly one resubmission, for the same action. The default rules allow three send-backs, after which the next one becomes a rejection.

agent-revise.ts
const settled = await cb.status(r.id)              // or react to decision.sent_back
if (settled.status === 'sent_back') {
  // settled.reason === 'Leave out the 40 products in the Clearance collection'
  const clearance = new Set(await shopifyRead.collectionProductIds(STORE, 'clearance'))
  const revised = changes.filter((c) => !clearance.has(c.product_id))   // 1,200 products

  const r2 = await cb.resubmit(r.id, {
    ...input,
    params: { store: STORE, count: revised.length, changes: revised },
    idempotencyKey: `bf-2026-tags:${jobId}:v2`,     // a new key for the new attempt
  })
  // r2.status === 'pending', r2.attempt === 2, r2.parent_item_id === r.id
}

7. Approve with a decision token

Sam approves the revised change. Same two calls, with clear:

approve.ts
const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17', workItemId: r2.id })
const result = await partner.decide(r2.id, { decision: 'clear' }, { token })
// result.status === 'cleared' (or 'pending' if the rule needs a second, different approver)
// result.receipt is the signed Authorisation Receipt

A token works once and for at most 5 minutes (2 by default). If ClearedBy refuses the decision, for example 403 no_authority, the token isn't used up.

8. Your executor receives and verifies the dispatch

ClearedBy POSTs a signed v2 envelope to your executor straight after the decision. verifyDispatch checks the timestamped HMAC signature over the raw body, the envelope, and the Ed25519 receipt bound to this org, clearance, action and parameters. With checkStatus: true it also asks whether the approval has been revoked since. Reply fast and do the work in a job.

executor/on-decision.ts (Express)
import express from 'express'
import { verifyDispatch, DispatchVerificationError, ReceiptRevokedError } from '@clearedby/sdk/dispatch'

const app = express()

// Read the body as TEXT: the signature is over the exact bytes received.
app.post('/clearedby/on-decision', express.text({ type: 'application/json' }), async (req, res) => {
  let v
  try {
    const claimedOrg = String(JSON.parse(req.body).org_id)   // only to pick the secret; verified below
    v = await verifyDispatch(req.body, req.headers, {
      secret: await secrets.get(`cb:${claimedOrg}:signing`),
      orgId: claimedOrg,                                       // the signed body must name this org
      jwksUrl: 'https://app.clearedby.com/.well-known/clearedby-keys',
      audience: 'https://exec.yourapp.example',                // the receipt must name you
      checkStatus: true,                                       // has it been revoked since?
    })
  } catch (err) {
    if (err instanceof ReceiptRevokedError) return res.status(200).json({ status: 'revoked' })      // don't execute, don't retry
    if (err instanceof DispatchVerificationError && err.code === 'status_unavailable') return res.status(503).end()  // fail closed; ClearedBy retries
    return res.status(401).json({ error: err instanceof DispatchVerificationError ? err.code : 'bad_request' })
  }

  if (v.envelope.verdict !== 'cleared') return res.status(200).json({ status: 'noted' })   // rejected / expired / sent_back authorise nothing

  const id = v.envelope.work_item_id
  // Record "executing" BEFORE touching Shopify: a unique index on work_item_id.
  if (!(await jobs.claim(id))) return res.status(409).json({ status: 'already_executed' })

  await queue.add('clearedby-exec', {
    orgId: v.envelope.org_id, id,
    action: v.envelope.action,
    params: v.params,                      // the RECEIPT's signed params: execute only these
    receiptId: v.receipt!.receipt_id,
  })
  res.status(202).json({ status: 'accepted' })
})

Delivery is at-least-once. Every attempt carries a freshly minted receipt with a new nonce, so dedupe on work_item_id, never on the nonce. A 409 {"status":"already_executed"} counts as delivered and stops the retries.

9. Execute, checking the current state

Approval happened at decision time, and the store may have moved on since. For each product, read its tags now. Write the approved after only when the live tags still equal the approved before. Otherwise skip it: someone changed that product after the proposal, and you must not overwrite their change.

executor/run-job.ts
import { ClearedBy, type CompletionItem } from '@clearedby/sdk'

type TagChange = { product_id: string; before: string[]; after: string[] }
const same = (a: string[], b: string[]) => a.length === b.length && [...a].sort().join('\u0000') === [...b].sort().join('\u0000')

export async function runTagJob(job: { orgId: string; id: string; params: Record<string, unknown>; receiptId: string }) {
  const cb = new ClearedBy({ apiKey: await secrets.get(`cb:${job.orgId}:executor`) })
  const store = job.params.store as string
  const items: CompletionItem[] = []
  let reported = 0

  // Report progress in slices; each report has a stable completion id, so a retry is a safe replay.
  const report = async (status: 'partial' | 'done') => {
    const slice = items.slice(reported)
    reported = items.length
    return cb.complete(job.id, {
      status,
      completionId: status === 'done' ? `${job.id}:final` : `${job.id}:upto:${reported}`,
      items: slice,
      deliveryReceiptId: job.receiptId,
    })
  }

  for (const c of job.params.changes as TagChange[]) {
    const live = await shopifyWrite.getProductTags(store, c.product_id)       // null if deleted
    if (live === null) { items.push({ key: c.product_id, status: 'failed', error: 'product deleted' }); continue }
    if (!same(live, c.before)) { items.push({ key: c.product_id, status: 'skipped', error: 'tags changed since approval' }); continue }
    await shopifyWrite.setProductTags(store, c.product_id, c.after)
    items.push({ key: c.product_id, status: 'done', before: live, after: c.after })
    if (items.length - reported >= 500) await report('partial')
  }
  return report('done')
}

10. Report per-item results

The final report closes the clearance. ClearedBy links it to the receipt it relied on and compares it with what was approved:

response from the final complete()
{
  "recorded": true, "status": "done", "tier": 1,
  "completion_id": "01K...:final", "idempotent_replay": false,
  "receipt_id": "01K...", "receipt_hash": "...", "delivery_receipt_id": "01K...",
  "diverged": false,
  "items":  { "reported": 200, "done": 196, "failed": 1, "skipped": 3, "unknown": 0 },
  "totals": { "approved": 1200, "done": 1196, "failed": 1, "skipped": 3, "unreported": 0 }
}

If you touched a product that wasn't approved, or wrote a value other than the approved after, the clearance is flagged diverged: true for good. A report is Tier 1 (self-reported). Pass a Shopify object id as externalRef (for example a bulk operation GID) to earn the verifiable Tier 3 label.

11. Undo it the week after

On Monday, Priya asks the assistant to put the tags back. The agent asks ClearedBy to build the undo from the record: the same action, only the 1,196 products reported done, with before and after swapped. It goes through the rules like any other change: 1,196 products is over the 200 limit, so Sam sees it, marked Reverts.

agent-undo.ts
const undo = await cb.buildUndo(r2.id)        // { action, params, reverts: r2.id, keys }
const u = await cb.gate({
  ...undo,
  audience: 'https://exec.yourapp.example',
  context: { batch_id: 'bf-2026-tags-undo', summary: 'Put the pre-Black Friday tags back' },
  idempotencyKey: `undo:${r2.id}`,
})
// When it clears, the same executor runs it. The state check in step 9 already does the
// right thing: the undo's "before" is what you wrote, so any product someone re-tagged
// by hand since is skipped rather than overwritten.

Refunds and order cancellations can't be undone (422 not_reversible). A discount is undone by disabling it, which needs the discount's GID as the original completion's externalRef.

05Building the review UI

Your merchants review inside your product. You have two ways to build it: drop in our React components, or call the API from your own backend. Either way, the partner key never reaches the browser: the browser talks to your server, your server talks to ClearedBy.

Option A: @clearedby/react and the partner proxy

  • Server half, @clearedby/sdk/partner-proxy: createPartnerProxy({ partnerKey, resolveUser }) returns handle(request), a Web Fetch handler you export as a Next.js App Router route (expressHandler(proxy) for Express). You supply resolveUser(req), which maps your signed-in session to { org_id, external_subject }, or null for a 401. The org and the person come only from there. The proxy serves a fixed list of routes (queue, item, history, permissions, decide, cancel, rules, accept and theme) and nothing else. It reads with a cached read token for that person and decides with a fresh single-use decision token pinned to the item. No key, token or receipt is ever returned to the browser, and writes must be same-origin JSON.
  • Client half, @clearedby/react: ClearedByProvider, headless hooks (useApprovalQueue, useApproval, usePermissions, useDecide, useHistory, useRules, useRulesProposal, useRevoke, useRevalidate) and default components:
    • ApprovalQueue and ApprovalCard;
    • ReviewPanel, which shows the action in plain English, a paged before/after table for batches and the evidence badged Verified by you, Checked automatically or Agent says;
    • DecisionBar, which shows only the permitted decisions and asks for a note where one is needed;
    • RulesSummary, with Looks good and Adjust, spot-check "How often", and the owner's OK for a looser change;
    • History and CancelButton.
    Open views refresh every 15 s while the tab is visible, pause while it's hidden and back off on errors. Call useRevalidate() when your own webhook-driven push says something changed.
app/api/clearedby/[...path]/route.ts + app/approvals.tsx
// app/api/clearedby/[...path]/route.ts
import { createPartnerProxy } from '@clearedby/sdk/partner-proxy'

const proxy = createPartnerProxy({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  resolveUser: async (req) => {
    const s = await getSession(req)                 // your auth
    return s ? { org_id: s.clearedbyOrgId, external_subject: s.userId } : null
  },
})
export const GET = proxy.handle, POST = proxy.handle, PUT = proxy.handle

// app/approvals.tsx
'use client'
import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react'
import '@clearedby/react/styles.css'

export function Approvals() {
  const [id, setId] = useState<string | null>(null)
  return (
    <ClearedByProvider basePath="/api/clearedby">
      <ApprovalQueue onSelect={(item) => setId(item.id)} selectedId={id} />
      {id && <ReviewPanel id={id} />}           {/* includes DecisionBar, CancelButton, History */}
    </ClearedByProvider>
  )
}

A runnable Next.js app is in examples/partner-approvals-next in the public ClearedBy/clearedby-js repo. Every component, hook, prop, label, theme token and proxy option is in the UI components reference.

Read tokens. If you build your own proxy, POST /v1/auth/decision-token {"scope": "read"} gives you a token that reads as that reviewer. It is reusable for up to 15 minutes and can never decide (403 token_scope). On GET /v1/gate, /detail, /events and /permissions, reviewer defaults to that person, naming anyone else is 403, and another org's item is 404.

Matching your app's design

The components are meant to look like part of your product, not like ClearedBy. By default they inherit your page's font and text colour. Specify your design tokens once, as data, and you're done: no CSS to write, and every component in every org picks them up.

Way to give us your tokensHow
Through the APIPATCH /v1/partner/settings {"theme": {...}}, plus an optional per-org override with PATCH /v1/partner/orgs/:id {"theme": {...}}. GET /v1/partner/orgs/:id/theme returns the merged result. The provider fetches it through your proxy (GET /theme) and applies it as --cb-* variables.
From your existing configImporters in @clearedby/react/theme: fromShadcn(globalsCss | element), fromTailwind(resolvedConfig) and fromDesignTokens(w3cJson) turn what you already have into a theme.
From the command linenpx @clearedby/react theme --from app/globals.css prints the theme. Add --push to save it with CLEAREDBY_PARTNER_KEY, and --org <id> for one merchant.
In code<ClearedByProvider theme={...}> overrides the stored theme token by token. colorScheme can be auto, class (a .dark ancestor), light or dark.
With your AI coding agentThe @clearedby/react README has a copy-paste prompt, with the schema inline, that finds your tokens and produces the theme JSON.

Only plain CSS colours, lengths, font lists and shadows are accepted. url(), var(), expression(), ;, {, } and similar are refused with 400, so a theme can never inject CSS.

terminal
# Generate a theme from your shadcn/ui CSS variables and save it to your partner settings
npx @clearedby/react theme --from app/globals.css --push
PATCH /v1/partner/settings
{ "theme": {
  "colors": { "primary": "#6b3fd4", "primaryText": "#ffffff", "surface": "#ffffff", "border": "#e4e1ee",
              "text": "#1c1a24", "mutedText": "#6b6780", "danger": "#dc2626" },
  "radius": "10px", "fontFamily": "Inter, system-ui, sans-serif",
  "dark": { "colors": { "surface": "#16151c", "text": "#f4f2fa" } } } }

Deeper customisation

When tokens aren't enough, there are three further levels, and you can mix them:

LevelHowUse it when
1. CSS variablesSet --cb-color-primary, --cb-color-surface, --cb-color-border, --cb-radius, --cb-font, --cb-space-md, --cb-shadow and the rest in your own stylesheet. The default stylesheet uses only cb-* classes (no element selectors, resets or globals), and its fallbacks work on dark pages.You want to adjust a token for one page or one part of your app.
2. Class overridesclassName on each component, classNames for its parts (on a component or on the provider), and unstyled, which drops every default class.You use Tailwind or shadcn/ui and want your own utility classes on every part.
3. Your own componentsPass your design system's primitives to the provider: components={{ Button, Input, Textarea, Select, Badge, Dialog }}. Buttons get a variant (primary, secondary, danger or ghost).You want buttons, inputs and dialogs that are exactly your design system's.

labels overrides the words, so the copy matches your product's voice and language ("Approve" or "Looks good", "Send back" or "Ask for changes"). For a fully custom UI, use the headless hooks and render everything yourself; they carry the same permission-aware logic.

app/approvals.tsx
import { ClearedByProvider, ApprovalQueue } from '@clearedby/react'
import { MyButton, MyBadge, MyDialog } from '@/components/ui'  // your design system

<ClearedByProvider
  basePath="/api/clearedby"
  components={{ Button: MyButton, Badge: MyBadge, Dialog: MyDialog }}                 // level 3
  labels={{ decisions: { clear: 'Approve', send_back: 'Ask for changes' } }}
  classNames={{ card: 'rounded-xl hover:bg-muted', heading: 'text-lg font-semibold' }}  // level 2
>
  <ApprovalQueue />
</ClearedByProvider>

Option B: your own UI on the API Available now

Build four small endpoints on your server. Each one works out the signed-in person's org and external_subject from your session, then calls ClearedBy with the partner key:

Your endpointClearedBy callSDK
InboxGET /v1/gate?org_id=&status=pending,escalated&reviewer=<subject>partner.list(orgId, { status: ['pending','escalated'], reviewer })
One requestGET /v1/gate/:id/detail?org_id=&include=eventspartner.get(orgId, id, { include: ['events'] })
Which buttonsGET /v1/gate/:id/permissions?org_id=&reviewer=<subject>partner.permissions(orgId, id, subject)
DecidePOST /v1/auth/decision-token, then POST /v1/gate/:id/decidepartner.createDecisionToken(), partner.decide()
server/approvals.ts
import { ClearedByPartner, ClearedByApiError, type PartnerDecision } from '@clearedby/sdk'

const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })

export async function inbox(session: Session) {
  const { orgId, subject } = whoIs(session)          // from YOUR session, never from the request
  return partner.list(orgId, { status: ['pending', 'escalated'], reviewer: subject, include: ['params', 'proof'] })
}

export async function openItem(session: Session, id: string) {
  const { orgId, subject } = whoIs(session)
  const [item, perms] = await Promise.all([
    partner.get(orgId, id, { include: ['events'] }),
    partner.permissions(orgId, id, subject),
  ])
  return { item, buttons: perms.can, needsReason: perms.reason_required, why: perms.cannot }
}

export async function decide(session: Session, id: string, decision: PartnerDecision, reason?: string) {
  const { orgId, subject } = whoIs(session)
  const { token } = await partner.createDecisionToken({ orgId, externalSubject: subject, workItemId: id })
  try {
    return await partner.decide(id, { decision, reason }, { token })
  } catch (e) {
    if (e instanceof ClearedByApiError && e.code === 'not_pending') return { status: 'already_decided' as const }
    throw e
  }
}

Show only the buttons in can. The permissions endpoint runs the same checks as the decision, in the same order, so a button you show won't be refused for a reason it didn't mention. reject and send_back need a reason of at least 4 characters. escalate is always available on an open item: pass escalateTo (an external_subject) or leave it out and ClearedBy picks the most senior person who can cover it.

Show what matters in the detail view: summary, the exact params (for batches, a before/after table), evidence.verified then evidence.claims with their badges, expires_at, escalation, dual_review (who has approved so far), and for resubmissions parent_item_id and the reason it was sent back.

Polling vs webhooks

Use webhooks. Don't hammer the list. decision.pending arrives within a second or two of the proposal, and GET /v1/gate/:id/detail already returns the item when it does. Treat each event as "this item changed": refresh that one item, and update your own inbox.

NeedDo this
Show new requests to reviewersReact to decision.pending and decision.escalated. Refresh the one item.
Remove decided requests from inboxesReact to decision.cleared, .rejected, .sent_back, .expired, .withdrawn.
A reviewer opens the inbox pageOne list call when the page loads, then rely on events.
An agent waiting for its own answerGET /v1/gate/:id/wait (long-poll up to 55 s, 204 means ask again), or your own event routing. Not a tight status() loop.
Belt and bracesA reconcile sweep every few minutes over status=pending,escalated, paging with next_cursor.

Rate limits: the partner key allows 600 requests a minute. A cb_live_ key allows 60 a minute, shared with your agents' gate calls, which is another reason to read with the partner key and to avoid polling.

06Executor security rules

Your executor is the only thing that changes the store, so it's the one place these rules must hold. Every rule is a MUST.

  1. Verify every dispatch with verifyDispatch before doing anything, over the raw body bytes. Pass orgId, jwksUrl and audience. Reject on any error. For cleared, it proves the Ed25519 receipt authorises exactly this org, clearance, action and parameters.
  2. Execute only cleared, and only from the receipt's parameters (the params that verifyDispatch returns). Never from data, from the agent, or from anything else in the request. rejected, expired and sent_back authorise nothing.
  3. Check the status right before anything irreversible (refunds, cancellations, payouts): checkStatus: true. An approval can be revoked after the dispatch left ClearedBy. A revoked one throws ReceiptRevokedError: don't execute, reply 2xx. If the status can't be checked (status_unavailable), fail closed and reply non-2xx so ClearedBy retries. If your job runs long after the dispatch arrived, check again when it starts.
  4. Dedupe on work_item_id with a unique index, and record "executing" before calling Shopify. Never dedupe on the receipt nonce or receipt_id: each delivery has new ones.
  5. Answer 409 {"status":"already_executed"} to a repeat. ClearedBy records it as delivered and stops retrying.
  6. Re-check the current state of every item before writing. Write only when the live value still equals the approved before, and report the rest as skipped. For an undo, the same check protects changes people made by hand.
  7. Never exceed the approved amount. A receipt authorises up to what was approved, at decision time. Re-check the refundable amount on the order. If less is refundable now, refund less (or stop) and report partial or failed. Send an idempotency key derived from work_item_id with the Shopify mutation.
  8. Keep Shopify write credentials away from agents. The agent gets read-only access at most, and a cb_live_ key that can only propose. Only the executor holds the write token. Use a separate cb_live_ key for the executor, and keep the partner key out of both.
  9. Report what happened with POST /v1/gate/:id/complete, with a stable completionId, per-item results, and the deliveryReceiptId you verified. A 2xx to the dispatch only proves you received it.

Verification error codes from verifyDispatch: missing_signature, malformed_signature, timestamp_out_of_tolerance (more than 300 s from now), bad_signature, malformed_envelope, unsupported_version, params_hash_mismatch, delivery_id_mismatch, org_mismatch, missing_receipt, no_keys, receipt_invalid (with receiptReason), receipt_mismatch, and with checkStatus: receipt_revoked, status_unavailable.

Must Why the receipt, not just the signature

Dispatches to your execution_url are HMAC-signed with the org's signing secret, which any holder of one of that org's API keys can read, including your agent's key. The Ed25519 receipt is signed by ClearedBy alone and no API key can forge it. That's why verifyDispatch refuses a cleared dispatch without a valid receipt, and why you pass audience.

Missed deliveries? GET /v1/gate/:id/delivery shows attempts, the last status and whether ClearedBy gave up. POST /v1/gate/:id/redeliver sends it again with a fresh receipt, under the same delivery_id. Both use the org key. A runnable reference receiver is in examples/dispatch-receiver.

07Approval rules for non-technical merchants

Your merchants don't need to know what a policy is. Every org you create starts with approval rules you can show as Your approval rules, with sliders and toggles. ClearedBy turns the settings into a policy. You never write YAML.

The one rule to remember: you can make a merchant's rules stricter on your own, but making them looser needs an OK from one of the merchant's owners or admins.

The settings

Amounts here are in major units of the org's currency (25 = £25, $25 or ¥25), unlike reviewer authority, which is in minor units.

SettingDefaultWhat it means to the merchant
tags_auto_max_products200Tag changes to up to this many products go through on their own. 0 = always ask. (0 to 10,000)
inventory_auto_max_items50Stock updates for up to this many items go through on their own. 0 = always ask.
price_changes"always_review"Or "review_drops_over_pct": price rises, and drops of up to price_drop_review_pct, go through on their own.
price_drop_review_pct30The drop (0 to 100%) used by "review_drops_over_pct". ClearedBy works out the largest drop itself.
discounts"always_review"New discounts always need an OK. (The only option for now.)
refund_auto_max25Refunds up to this amount go through on their own. 0 = every refund needs an OK.
refund_dual_above250Refunds over this need two people. null = never. At least refund_auto_max.
refund_daily_auto_cap250Once this much has been refunded in 24 hours, every further refund needs an OK. null = no cap.
refund_per_order_cap25Refunds on one order adding up to more than this in 30 days need an OK, so one big refund can't be split into small ones. null = no cap.
order_cancel"always_review"Cancelling an order always needs an OK. (The only option for now.)
timeout_hours72Requests nobody answers in time are cancelled, never approved automatically. 1 to 720.
spot_checksfalseOccasional random spot-checks: now and then, something that would go through on its own is held for an OK anyway.
spot_check_pct5How often, when spot-checks are on: 1 to 25 (%). Kept while they're off.

Anything that isn't a Shopify catalogue action always needs a person. The defaults are the same numbers in every currency, so for a currency with a small unit (¥25 is very little) they're strict: raise them with the merchant's OK.

Plain-English summaries

GET /v1/partner/orgs/:org_id/rules (SDK: partner.getRules(orgId)) returns the settings plus a summary: one sentence per setting, amounts already formatted in the merchant's currency. key tells you which slider a line belongs to. Show the sentences as they are.

GET /v1/partner/orgs/:org_id/rules
{
  "settings": { "tags_auto_max_products": 200, "refund_auto_max": 25, "refund_dual_above": 250, "...": "..." },
  "summary": [
    { "key": "refund_auto_max", "action_label": "Refunds", "sentence": "Refunds over £25 need your OK" },
    { "key": "refund_dual_above", "action_label": "Refunds", "sentence": "Refunds over £250 need two people to approve" }
  ],
  "active_version": 2,
  "currency": "GBP",
  "refund_approvers": 2
  // "pending_proposal": { ... } while a looser change waits for an owner
}

Stricter vs looser

Send only what changed with PUT /v1/partner/orgs/:org_id/rules (partner.setRules()). ClearedBy compares the result with the current rules, setting by setting:

  • Stricter or the same (a lower limit, a new cap, "always ask", more spot-checks): switched on at once. 200 {"status":"active"}.
  • Looser, or a mix: saved as a proposal, not switched on. 202 {"status":"needs_owner_approval", "proposal_id", "summary_diff"}. An owner or admin accepts it with their decision token: POST .../rules/:proposal_id/accept (partner.acceptRules()). A newer PUT replaces a waiting proposal (409 proposal_superseded for the old one).

timeout_hours counts neither way: a lapsed request is cancelled, so a longer or shorter wait never lets anything through.

rules-save.ts
const res = await partner.setRules(orgId, { refund_auto_max: 50 })
if (res.status === 'needs_owner_approval') {
  // show res.summary_diff: "Refunds over £25 need your OK" -> "Refunds over £50 need your OK"
  // if the person saving is an owner or admin and taps "Yes, change it":
  const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17' })   // not pinned to an item
  await partner.acceptRules(orgId, res.proposal_id, { token })
}

Spot-checks

Suggested copy: a toggle "Occasional spot-checks" ("Now and then, we'll ask you to double-check something that would normally go through automatically"), and when it's on, a "How often" choice:

ShowSend
About 1 in 10{ "spot_checks": true, "spot_check_pct": 10 }
About 1 in 20{ "spot_checks": true, "spot_check_pct": 5 }
About 1 in 50{ "spot_checks": true, "spot_check_pct": 2 }

Turning spot-checks on, or checking more often, is stricter and switches on at once. Turning them off, or checking less often, needs the merchant's OK. Orgs created before spot-checks were a setting already spot-check about 1 in 20, and GET /rules shows them that way.

Only one approver so far

"Two people" can't happen with one person. Until a second person has refund authority, refunds over refund_dual_above need one OK, and the summary says so ("...will need two people to approve once you add a second approver"). As soon as you add a second reviewer with refund authority, two-person approval switches on by itself; that's stricter, so it needs nobody's OK. If you remove a reviewer and fewer than two approvers are left, large refunds go back to one OK, so they don't wait for someone who doesn't exist. refund_approvers tells you how many there are now.

Suggested UI copy

MomentSay
First look, after onboardingYour approval rules. "Your assistant can make some changes on its own. Anything bigger waits for you." Then one line per summary entry, and [Looks good] [Adjust]. Looks good needs no API call: the rules are already on.
200 active"Saved. Your new rules are on."
202, and the person is an owner or adminThis makes your rules less strict. Show each summary_diff line as before → after, with [Yes, change it] [Cancel].
202, and the person isn't"Your store owner needs to approve this change." Show the same diff to an owner or admin next time they're in (pending_proposal).
An approved change that hasn't runCancel before it runs
A request still waitingWithdraw request
A change that has runUndo (only for reversible changes)

08Claims vs verified evidence

Everything an agent sends in proof is its own word. It may be right, but nothing has checked it. ClearedBy keeps that apart from facts that have been checked, so reviewers and rules can tell the difference.

provenanceWhere it comes fromBadge to show
agent_claimThe agent's proof.evidence on POST /v1/gate. Always this, whatever the agent sends: a verified: true or provenance field is dropped.Agent says
partner_verifiedYour backend attached it with the partner key, POST /v1/gate/:id/evidence.Verified by verifier_name
clearedby_computedClearedBy worked it out: a batch's count, a price update's largest drop, the currency check, and each running total a rule used.Checked by ClearedBy

Each item also has verified_by, verified_at and sha256 (of the canonical JSON of its value). The detail view returns them split as evidence.verified and evidence.claims.

Attaching verified facts

partner.attachEvidence(orgId, itemId, items), or POST /v1/gate/:id/evidence?org_id= with the partner key. 1 to 20 items per call, up to 64 KB, up to 100 per clearance, only while it's pending or escalated. The org's cb_live_ key gets 403 partner_key_required: the key your agent holds must not be able to vouch for its own claims. Each attach puts the items' hashes (never their values) on the signed record, so a later change to a stored value shows as "integrity": "mismatch".

Requiring verified evidence in a rule

A rule can refuse to clear on its own until some evidence is verified:

policy
rules:
  - match: shopify.refund.create
    when: amount <= 100
    verdict: auto
    requires_verified: [order_lookup]   # held for a person unless verified evidence of this type exists
  - match: shopify.refund.create
    verdict: review

Your partner key can't make gate calls, so at proposal time the only verified evidence is what ClearedBy computes. A rule that requires a type only you can attach therefore always holds the request for a person, who then sees your verified facts. That's the intended pattern. Attaching evidence never re-evaluates a request or unlocks clear.

Rendering it

  • Show evidence.verified first, then evidence.claims.
  • Badge every item from its provenance. Never style an agent claim as verified, even if its value says verified: true.
  • If integrity is mismatch, warn the reviewer: the fact was changed after it was attached.
  • Where a claim and a verified fact disagree (the agent says "£40, not refunded", your lookup says "£400, already refunded"), put them side by side.

09Cancel, withdraw, undo

Approved isn't the same as done. There are three ways to take something back, depending on how far it got.

Where it isUseWho may
Still waiting (pending, escalated)Withdraw: POST /v1/gate/:id/withdraw, optional reasonThe side that asked: the org key, or your partner key with org_id. Reviewers reject instead.
Approved, not yet done (cleared, no final report)Revoke: POST /v1/gate/:id/revoke, reason 4 to 2,000 charactersYour partner key with org_id; the org key; or a decision token for an owner, admin, or a reviewer whose authority covers the action.
Done (final done or partial report)Undo: GET /v1/gate/:id/undo builds the inverse proposal, then submit it with POST /v1/gateThe org key. The undo goes through the rules like any change.
cancel.ts
// Withdraw an open request (partner key)
await partner.withdraw(orgId, id, 'no longer needed')

// Cancel an approved change before it runs, as the partner...
const rv = await partner.revoke(orgId, id, 'customer cancelled the order')
// ...or as the reviewer who clicked "Cancel before it runs"
const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17', workItemId: id })
await partner.revoke(orgId, id, 'changed my mind', { token })

// rv.dispatch tells you whether your executor may already have it:
// 'cancelled' (stopped in time) | 'in_flight' | 'delivered' | 'gave_up' | 'none'

A revoke stops queued and retrying deliveries, makes redeliver answer 409 revoked, mints no new receipts, and makes every receipt for the clearance answer revoked at the status endpoint within about five seconds. If the dispatch had already been delivered or was in_flight, your executor must catch it with the status check (rule 3 in section 6). A partial completion doesn't block a revoke: it stops the remaining items (stopped_partial: true), and anything your executor reports afterwards is accepted and flagged after_revoke: true, so the record shows what really happened. Once a done or failed report exists, revoke answers 409 already_executed: propose the undo instead.

Reversibility classes

ActionClassUndo
shopify.product.updateReversibleSame action, each field's before and after swapped
shopify.product.tags.updateReversibleSame action, before and after swapped
shopify.price.updateReversibleSame action, before and after swapped
shopify.inventory.setReversible (check sales in between)Same action, before and after swapped. Sales since the change move the real count, so a person should look.
shopify.discount.createCompensableshopify.discount.disable. Needs the discount's GID as the completion's externalRef, else 422 needs_external_ref. Orders that already used it keep it.
shopify.discount.disableCompensableRe-create it yourself (422 unsupported)
shopify.refund.createIrreversibleNone (422 not_reversible)
shopify.order.cancelIrreversibleNone (422 not_reversible)

buildUndo includes only items reported done, using the before/after you reported. A done report without items covers the whole batch. A partial report without items can't be undone automatically (409 reverts_not_completed), because nobody knows which changes ran. The undo carries a top-level reverts field that ClearedBy checks (same org, cleared, completed, the right inverse action). Rules can match it; the merchant rules treat an undo like any other change of its size. To send every undo to a person in a hand-written policy:

policy
- match: shopify.*
  when: reverts
  verdict: review

10Webhooks reference

ClearedBy sends three kinds of outbound messages. Don't mix them up:

MessagePurposeSignature header
Dispatch (on_decision)Tells your executor to act. Carries the receipt. Section 6.clearedby-signature: t=<unix>,v1=<hex>
Webhook (org events)Tells your backend something changed. For inboxes, notifications and evidence. This section.X-ClearedBy-Signature: sha256=<hex>
Callback (callback_url on a gate call)Resumes one waiting agent run. Optional.X-ClearedBy-Signature: sha256=<hex> (org signing secret)

Where approvals are sent (dispatch routing)

For each decided item, ClearedBy POSTs the v2 dispatch to the first of these that is set:

  1. The request: a top-level on_decision.<verdict>.url on that gate call.
  2. The policy: the judging policy's on_decision.<verdict>.url (only hand-written policies have one; the merchant approval rules don't).
  3. The org override: PATCH /v1/partner/orgs/:org_id with execution_url (for cleared) or notify_url (for the others).
  4. Your partner default: execution_url for cleared, notify_url for rejected, expired and sent_back.

If none is set, nothing is dispatched for that verdict. The org and partner URLs are read when each attempt is sent, so changing them takes effect at once, needs no new policy version and no owner approval, and applies to retries still pending. Deliveries to them are always the v2 envelope, signed with the org signing secret, with no extra headers; cleared ones carry the receipt. A revoked item is never dispatched, whichever URL applies: you learn about revocations from decision.revoked and the receipt status endpoint.

Subscribing

POST /v1/webhooks with the org's key, or with your partner key and ?org_id= (SDK: partner.createWebhook(orgId, ...), listWebhooks(orgId), deleteWebhook(orgId, id)): { url, events, filters? }. The URL must be https on a public address. filters can narrow by action_prefix, policy or mode. The response includes the signing secret (whsec_...), shown once. GET /v1/webhooks lists subscriptions with their failed_count. Subscriptions are per org: create one for each org when you onboard it. (Your partner notify_url is different: it receives dispatches for rejected, expired and sent-back verdicts, not these events.)

Events

EventWhenPayload
decision.pendingA request is held for a person, including resubmissions.Light
decision.escalatedEscalated by a reviewer, or because nobody decided in time. Adds escalated_to (null on timeout), escalated_by, and reason: "timeout" when it timed out.Light
decision.sent_backA reviewer sent it back. Adds decided_by. The instruction is reason on the detail view.Light
decision.revokedAn approval was cancelled before it ran. Adds revoked_at, revoked_by, reason, dispatch, receipt_id.Light
decision.withdrawnAn open request was withdrawn. Adds withdrawn_at, withdrawn_by, reason.Light
decision.clearedApproved, by a rule or a person.Full: params, context, attestation, receipt
decision.rejectedRejected, by a rule, a person or a timeout.Full
decision.expiredNobody answered in time.Full
decision.completedYour executor reported a result. completion_status, tier, diverged, item_counts, totals, after_revoke.Completion
a light lifecycle event
{
  "event": "decision.pending",
  "org_id": "01K...",
  "occurred_at": "2026-11-20T10:00:01.000Z",
  "data": {
    "id": "01K...", "action": "shopify.product.tags.update", "status": "pending", "org_id": "01K...",
    "mode": "enforce", "rule": "rules[1]: shopify.product.tags.update", "attempt": 2, "parent_item_id": "01K...",
    "batch_id": "bf-2026-tags", "expires_at": "2026-11-23T10:00:00.000Z",
    "routed_to": [ { "user_id": "01K...", "external_subject": "user_17" } ]
  }
}

Light events carry no params or context: fetch GET /v1/gate/:id/detail when you need them.

Verifying the signature

Every webhook is signed with X-ClearedBy-Signature: sha256=<hex HMAC-SHA256(secret, raw body)>. Compute it over the exact bytes you received. There's no timestamp in the signature, so treat an event as a prompt to re-read the clearance, which is the source of truth, and dedupe on event + data.id.

events.ts
import { createHmac, timingSafeEqual } from 'node:crypto'

export function verifyWebhook(rawBody: string, header: string | undefined, secret: string): boolean {
  if (!header || !header.startsWith('sha256=')) return false
  const got = Buffer.from(header.slice(7), 'hex')
  const want = createHmac('sha256', secret).update(rawBody).digest()
  return got.length === want.length && timingSafeEqual(got, want)
}

app.post('/clearedby/events', express.text({ type: 'application/json' }), async (req, res) => {
  const orgId = String(JSON.parse(req.body).org_id)
  if (!verifyWebhook(req.body, req.header('x-clearedby-signature'), await secrets.get(`cb:${orgId}:whsec`))) return res.status(401).end()
  res.status(200).end()                          // ack first; 10 s timeout
  const evt = JSON.parse(req.body)
  if (await seen.add(`${evt.event}:${evt.data.id}`)) await route(evt)   // your handlers: onPending, refresh inbox...
})

Timing and retries

What happenedWhen the webhook (and any dispatch) is sent
Held for a person (decision.pending)In the background just after the proposal is saved. Usually within 1 to 2 seconds.
A person decided, escalated, sent back, revoked or withdrewImmediately after the decision is saved, usually within 1 to 2 seconds.
Cleared or rejected automatically by a ruleImmediately after the proposal is saved, usually within 1 to 2 seconds. The gate's own response already carries the verdict and receipt.
Timed out (expired or escalated)Timeouts are checked every minute, then sent immediately.
Your executor reported (decision.completed)Immediately after the report is saved.

Nothing is sent before the change it describes is saved, so a handler that calls GET /v1/gate/:id/detail or the receipt status endpoint straight away sees the new state. If that first attempt can't be made (or fails), the retry schedule below takes over, starting about a minute later. Each event and dispatch is sent once per attempt, never twice in parallel.

Any 2xx within 10 seconds counts as delivered. Anything else is retried after 1, 4 and 16 minutes, then hourly, up to 6 attempts in total; retries are picked up every 5 minutes, so real delays round up. If more than 20 events in a row fail every attempt, the subscription is switched off and you get a partner alert. A dispatch that runs out of retries raises one too. Dispatches follow the same schedule, and also accept 409 as delivered. Webhooks are never sent for dashboard test items.

Partner alerts

When something breaks in one of your orgs, ClearedBy tells you, not the merchant: an email to alert_email and one POST to alert_webhook_url, whichever you've set.

kindWhenWhat to do
webhook_subscription_deactivatedA webhook subscription failed 21 deliveries in a row and was switched off.Fix the endpoint, then create the subscription again.
outbound_credential_disabledAn outbound credential failed 21 deliveries in a row and was disabled.Fix the endpoint the credential signs for.
dispatch_gave_upA dispatch to your executor (or any dispatch URL) ran out of retries, or was interrupted mid-send.Fix the executor, then POST /v1/gate/:id/redeliver.
usage_80An org reached 80% of its monthly soft cap (default 1,000,000 gated items). Once per org per month.Nothing is blocked. Expected growth: ask ClearedBy to raise the cap. Unexpected: look for a runaway agent loop.
usage_100An org reached 100% of its monthly soft cap. Once per org per month.Nothing is blocked: gate calls keep working. Same as above.
POST alert_webhook_url
content-type: application/json
x-clearedby-signature: sha256=<hex HMAC-SHA256(alert_webhook_secret, raw body)>
clearedby-event: partner.alert

{ "event": "partner.alert", "org_id": "01K...", "external_id": "shop_8841",
  "kind": "webhook_subscription_deactivated",
  "detail": { "subscription_id": "01K...", "url": "https://...", "consecutive_failures": 21 },
  "occurred_at": "2026-09-24T10:00:00.000Z" }

Verify it with the same verifyWebhook() as above, using your alert_webhook_secret. The alert POST is sent once, with no retries, so also check recent_alerts on GET /v1/partner/settings: the last 20 alerts, with delivered_to showing where each one went. Lost the secret? PATCH with rotate_alert_webhook_secret: true.

11Data protection

You decide what goes to ClearedBy; we process it on your instructions, as your processor or sub-processor. Protection comes from four things: send only what reviewers need, tag every request with its data subject, erase on request, and set a retention window. The contract terms are in the DPA.

Send references, not profiles

  • Use an order id or a customer GID, not a name, email, phone number or address.
  • Send amounts and reasons. Summarise a chat in proof.reason rather than pasting the transcript; trim any quoted customer message to the relevant sentence.
  • Never send payment card data, passwords, government ids, health data or other special-category data.
  • For reviewers, use an external_subject that isn't an email, and leave out email unless you want us to email them.

The subject_id rule

If a proposal is about a shopper, context.subject_id must say which shopper. That's what makes their data erasable. A proposal counts as being about a shopper when the action is under shopify.refund.*, shopify.order.* or shopify.customer.*, or when params contains a customer_id, customer or email key (up to 4 levels deep). The value is a non-empty string of up to 256 characters; for Shopify use the customer GID, gid://shopify/Customer/<id>. In partner orgs a proposal without it fails with 422 subject_id_required (or 422 invalid_subject_id) and nothing is recorded. The same check runs on dry runs.

Erasure API

Both calls take the subject_id in the body, never the URL, are synchronous (the data is overwritten when you get the 200), and are safe to retry.

erasure.ts
// One merchant company
await partner.eraseSubject(orgId, 'gid://shopify/Customer/7208314339542')
// -> { org_id, external_id, items_redacted: 3, attestation_seq: 118 }

// Every org you own (a shopper wrote to you directly)
const all = await partner.eraseSubjectEverywhere('gid://shopify/Customer/7208314339542')
if (!all.complete) { /* retry: it's idempotent */ }

Erasure overwrites the matching clearances' params, context, reviewer notes, receipts, and the copies in webhook and replay logs, then records a signed redaction entry holding a hash of the id, never the id. It doesn't reach anything you or your merchants copied out of ClearedBy (your own logs, webhook receivers), and backups until they age out.

Retention

PATCH /v1/partner/settings
{ "retention_days": 90 }     # 1 to 3650, or null to keep history indefinitely

It applies to every org you own. A daily job overwrites readable data older than the window, the same way erasure does. Requests still waiting for a person are never purged, and the webhook delivery log is pruned to the same window. Idempotency replays are always deleted after 24 hours.

What we store

DataPersonal data?Erasable?
Proposals: action, params, context, proofWhatever you sendYes, by subject_id or by age
Reviewer notes, completion details, attached evidence valuesPossiblyYes, with the clearance
Signed receipts (include the params)YesYes. Replaced by a tombstone that keeps the hash
Webhook deliveries, idempotency replaysCopies of the aboveYes, with the clearance
The tamper-evident recordHashes of params and context, not the plaintext. Reviewers appear as an internal id and hashes of their email and external_subjectCan't be changed; holds nothing readable to erase
Reviewers: display name, optional email, role, authorityYes (merchant staff)Removing a reviewer stops their authority; ask us to erase their record
KeysNo: stored as hashes onlyn/a

12Error codes

Every error is {"error": {"code": "...", "message": "...", "hint": "...", "details": {...}}} with the HTTP status below (hint and details are optional). Branch on code, not on message. With the SDK, catch ClearedByApiError (also exported under its older name, ClearedByError) and read .status, .code, .hint and .details.

StatusCodeWhen, and what to do
Credentials (any endpoint)
401unauthorizedThe key is missing, malformed, unknown or revoked.
401invalid_tokenThe decision token is malformed, unknown, expired or already used. Mint a new one.
403forbiddenThe right kind of credential for a different job: a key trying to decide, a non-owner token accepting rules, a reviewer trying to withdraw, a person who isn't in the org.
403token_scopeThe decision token is pinned to a different clearance.
403user_deprovisionedThat reviewer was removed and can't decide or revoke.
403partner_key_requiredEvidence attach with an org key. Only the partner key can attach verified evidence.
403agent_inactive, agent_mismatchThe key is bound to a registered agent that is inactive, or context.agent_id names a different agent.
429rate_limitedSlow down and retry after a few seconds. See limits.
Proposals: POST /v1/gate (and ?dry=1)
400invalid_bodyNot JSON, an unknown field, or a field of the wrong type. The message names the field.
422reserved_context_keycontext set a key ClearedBy owns: on_decision, on_decision_override, on_decision_attestation, agent_verified, test, or anything starting cb_. Use the top-level fields instead.
422unknown_actionA shopify.* action that isn't in the catalogue. details.valid_actions lists them.
422invalid_paramsParams fail the action's schema, or context.batch_id isn't a string. details.issues has each path.
422count_mismatchcount doesn't equal changes.length. Leave count out and ClearedBy fills it in.
413batch_too_largeMore than 10,000 changes. Split the job and share a batch_id.
422store_not_allowedparams.store isn't one of the org's shop_domains. Nothing is recorded.
422store_not_configuredA partner org with no stores registered. PATCH /v1/partner/orgs/:org_id first.
422subject_id_required, invalid_subject_idA shopper-related proposal without a valid context.subject_id.
422idempotency_key_reusedThe same Idempotency-Key with a different body within 24 hours.
409idempotency_in_progressA request with this key is still running. Retry shortly for the replay.
422no_active_policyThe named policy isn't active, or the org has none.
404parent_not_foundResubmit: no such parent clearance.
409parent_not_sent_backResubmit: the parent wasn't sent back.
409parent_already_resubmittedEach sent-back clearance takes one resubmission. Use an idempotency key so a network retry replays instead.
422resubmit_action_mismatchA resubmission must keep the parent's action.
404reverts_not_foundUndo: the target isn't in this org.
409reverts_not_cleared, reverts_not_completedUndo: the target wasn't approved, or has no done/partial report (or a partial one without items).
422not_reversible, wrong_inverseUndo: refunds and cancellations can't be undone; or the action isn't the target's inverse (expected_action in the message).
Decisions: POST /v1/auth/decision-token, POST /v1/gate/:id/decide, permissions
400invalid_bodyUnknown decision, a missing or short reason for reject/send_back, or escalate_to without escalate.
404not_foundThe reviewer or clearance isn't in that org (including a clearance in one of your other orgs).
409not_pendingAlready decided. Refresh the item.
409already_decidedAnother reviewer decided at the same moment. Refresh the item.
403no_authorityThe person's authority doesn't cover this action at this amount. They can still escalate.
403self_approvalcontext.agent_user names this person.
403requester_cannot_approveTwo-person rule: the person who asked (requested_by_subject) can't be one of the two approvers.
409already_approvedTwo-person rule: this person already approved; a different one is needed.
401passkey_required_not_supported_for_partnerThe rule needs a passkey-signed approval, which a decision in your app can't give. Don't use attest: passkey in partner orgs.
422escalate_target_not_foundescalate_to isn't an active reviewer in the org, or is the person escalating.
422escalate_target_lacks_authorityescalate_to can't cover the action at this amount. Nothing changes.
(in cannot)revision_cap_reachedPermissions only: a send-back would be recorded as the policy's final verdict instead.
Evidence: POST /v1/gate/:id/evidence
409not_pendingAlready decided: evidence can only be attached while it's waiting.
409evidence_limitThe clearance already holds 100 attached items.
413evidence_too_largeOne call's evidence is over 64 KB.
Cancel: revoke and withdraw
400reason_requiredRevoke needs a reason of at least 4 characters.
409not_clearedRevoke: not approved, or already revoked. Withdraw an open request instead.
409already_executedRevoke: a final report exists. Propose the undo.
409not_pendingWithdraw: already decided. Revoke an approved one instead.
Completion and undo: POST /v1/gate/:id/complete, GET /v1/gate/:id/undo
409not_clearedOnly an approved change can have been executed.
409completion_conflictThe same completion id with a different body.
409already_completedA done or failed report already closed it.
409item_already_doneAn item key already reported done in an earlier report.
400invalid_bodyThe same item key twice in one report, or Idempotency-Key and completion_id differ.
409nothing_to_undo, reverts_not_completedNo item was reported done, or a partial report has no items.
422needs_external_ref, unsupported, not_reversibleSee the reversibility table.
410redactedThe clearance was erased, so there's nothing to build an undo from.
Dispatch and receipts
409not_decidedRedeliver: still waiting for a decision.
409revokedRedeliver: the approval was revoked. It's never delivered again.
409in_flightRedeliver: a send is in progress. Retry in a few minutes.
404no_dispatchRedeliver: no dispatch applies to this verdict.
404no_receiptGET /v1/gate/:id/receipt: not approved in enforce mode, so there's no receipt.
400invalid_receipt_idGET /v1/receipts/:receipt_id/status: not a valid id.
Partner administration: /v1/partner/* and reads
400invalid_body, invalid_query, invalid_subjectValidation failed (an unknown currency, a custom storefront domain instead of *.myshopify.com, a bad external_subject, a missing org_id with the partner key...).
404not_foundThe org isn't yours, or the reviewer doesn't exist.
400blocked_destinationAn execution_url, notify_url or alert_webhook_url isn't a public https address (private, loopback, link-local or metadata IP, or a host that doesn't resolve).
404reviewer_not_foundThe reviewer query names nobody in the org.
409email_takenAnother reviewer in the org has that email.
409proposal_supersededA newer rules change replaced this proposal.
409already_activeThat rules proposal or policy version is already on.
403owner_approval_requiredYour partner key tried to switch on a policy that loosens the merchant's rules (or can't be compared). Use an owner or admin decision token.
Anything else
500internal_errorOur side. Safe to retry with the same idempotency key.

13Limits

LimitValue
Rate limits (a sliding minute; 429 rate_limited when exceeded)
Partner key600 requests a minute
Org key (cb_live_)60 requests a minute per key, all endpoints together
Receipt status (public)300 a minute per client IP
Redeliver1 per clearance per 30 s, 30 per org per minute
Sizes
Changes per proposal10,000 (413 batch_too_large above)
Items per completion report10,000
Verified evidence1 to 20 items and 64 KB per call; 100 per clearance
Stores per org50
external_id, external_subject1 to 200 characters of A-Z a-z 0-9 . _ : @ | + = -
subject_idUp to 256 characters
List page1 to 100 clearances (default 50); 1 to 500 orgs (default 100)
Evidence table cardsKeep to about 50 rows; the full list is already in params
Time
Receipt validity10 minutes from issue (30 s clock skew allowed). Each dispatch attempt carries a fresh one.
Decision token1 to 300 s (default 120), single use
Dispatch signature tolerance300 s between the signed timestamp and your clock
Your reply to a dispatch or webhook10 s, then it counts as a failed attempt
Retries6 attempts: now, then 1 min, 4 min, 16 min, 1 h, 1 h
Idempotency keys24 hours
Long-poll GET /v1/gate/:id/waitUp to 55 s, then 204
Waiting for a persontimeout_hours: 72 by default, 1 to 720
Send-backs3 per lineage in the merchant rules; the next one is recorded as a rejection
Retention window1 to 3,650 days, or none

14Testing and go-live

Dry runs

POST /v1/gate?dry=1 (SDK: cb.check(input)) runs every check a real proposal would (the catalogue schema, the store list, the subject_id rule) and evaluates the rules, but records nothing: no clearance, no webhook, no dispatch. The answer says which rule matched and why:

POST /v1/gate?dry=1
{
  "dry": true,
  "verdict": "review",
  "rule": "rules[1]: shopify.product.tags.update",
  "sampled": false,
  "trace": [ ... ],
  "policy": { "name": "shopify-starter", "version": 2 },
  "currency": { "code": "GBP", "source": "org" }
}

Use it in CI for every proposal shape your agent can produce, and in your settings screen to preview what a rules change would do.

A test org, not test flags

Create a separate org for testing (for example external_id: "test_acme") pointing at a development store, with your own team as reviewers. It behaves exactly like production, including receipts, webhooks and dispatches, and erasing or letting retention clear it later is easy. The ClearedBy dashboard has its own test items for people exploring the product; they never reach the signed record, never send webhooks and never dispatch, so they can't exercise your integration.

Test items are created only by the dashboard's "send a test item" button (/v1/test-item) and are never executable. A gate call can't mark itself as a test: context.test is refused with 422 reserved_context_key. GET /v1/gate/:id returns test: true for a test item, and the SDK's guard() throws TestItemError rather than running your function.

The example receivers

  • examples/dispatch-receiver: a complete executor endpoint. pnpm demo plays ClearedBy's side offline and shows a first delivery, a retry answered 409 already_executed, and a forged amount refused with receipt_mismatch.
  • examples/receipt-gated-mcp-server: a service that accepts receipts with no ClearedBy key at all, verifying offline with nonce replay protection and its own ceiling.
  • signDispatchPayload(secret, t, body) from @clearedby/sdk/dispatch lets your unit tests sign fake dispatches for your receiver.

Go-live checklist

  • The partner key is only on your servers, never in a browser bundle, an agent prompt or a log line.
  • Agents hold only their org's cb_live_ key and read-only Shopify access. Only the executor holds Shopify write access.
  • Every org has its currency and shop_domains set, and a dry run passes for each action you use.
  • Reviewers' authority keys are exact action names (shopify.refund.create, not refund.create), in minor units.
  • Shopper-related proposals carry context.subject_id with the customer GID.
  • Proposals carry an Idempotency-Key and an audience naming your executor.
  • The executor uses verifyDispatch with orgId, jwksUrl, audience, and checkStatus: true for refunds and cancellations.
  • The executor dedupes on work_item_id with a unique index written before execution, and answers 409 already_executed.
  • The executor checks live state before every write, never exceeds an approved amount, and reports per-item results with a stable completion id.
  • Your webhook handler verifies signatures, acks within 10 seconds, and re-reads clearances rather than trusting payloads.
  • Your review UI shows only the buttons from permissions.can, badges evidence by provenance, and takes external_subject from your session.
  • Your rules screen shows summary as-is and sends looser changes to an owner or admin.
  • retention_days is set, confirmed with us, and your erasure flow calls POST /v1/partner/erasure.
  • execution_url is set in your partner settings, and one small auto-cleared change has reached it (GET /v1/gate/:id/delivery shows delivered: true).
  • alert_email and/or alert_webhook_url are set, the alert secret is stored, and someone is paged by partner.alert.
  • You've run the whole worked example once in your test org, including a send-back, a revoke and an undo.

Something here doesn't match what you see? Tell your ClearedBy contact, with the clearance id.