# Prevent duplicate refunds when a request is retried

Send the same refund request twice for an eligible order and the sandbox shop refunds it once:
the second reply carries the first refund’s ID. Refunds are idempotent by order ID, so your
storefront’s webhook handler must reuse the order ID on retry.

<a id="duplicate-requests"></a>
<a id="what-if-the-same-request-arrives-twice"></a>
## How the refund key is tested

The [duplicate-request test in the source](https://github.com/Cernanto/cernanto/blob/v0.9.4/agents/examples/workflows/refund-desk.cern.md#tests)
requires the same request sent twice to refund once. This is the compiled test’s check:

`tests/refund-desk.test.ts`

```ts
const second = await submitRefundRequest({ body: { orderId, message } });
assert.equal(second.decision, 'refunded', `second: ${JSON.stringify(second)}`);
assert.equal(second.refundId, first.refundId, `same request refunds once: ${JSON.stringify(second)}`);
```

Run `cernanto tests examples/workflows/refund-desk` to print every test in the
[compiled package](https://github.com/Cernanto/cernanto/blob/v0.9.4/agents/examples/workflows/.cern/refund-desk.cern).

A crash between an external write and its journal entry can repeat the write, so
the payment service must also honor the key.
[Read the limits of idempotency for external writes.](/docs/runtime-and-guarantees#guarantees-and-limits)

## Change the refund window

Mara Voss asks to return an unused €29 desk pad delivered 45 days ago. The two recorded sandbox
runs below apply the policy to her order before and after one edit:

**Before**

within thirty days of delivery

Recorded decision: refused

**After**

within sixty days of delivery

Recorded decision: refunded

### Run this change yourself

The refund API listens on port 8085 on all network interfaces, so use a trusted network. Start
in the `agents` folder of your checkout with [the examples deployed](/install#full-collection)
and a coding assistant signed in. Place an order delivered 45 days ago and ask for the refund:

Shell

```sh
ORDER=$(cernanto call examples/sandbox/orders placeOrder --args '{"customerName":"Mara Voss","customerEmail":"mara.voss@example.net","items":[{"name":"Desk pad (blue)","quantity":1}],"total":29,"cardLastFour":"4242"}' -q | sed -E 's/^\{"id":"([^"]+)".*/\1/')
DELIVERED=$(node -e 'console.log(new Date(Date.now() - 45 * 864e5).toISOString().slice(0, 10))')
cernanto call examples/sandbox/orders markDelivered orderId="$ORDER" deliveredAt="$DELIVERED" -q > /dev/null
curl -s -X POST -H 'content-type: application/json' -d "{\"orderId\":\"$ORDER\",\"message\":\"The desk pad is unused, still in its wrap. Could I get a refund?\"}" http://127.0.0.1:8085/refund-requests
```

Output

```text
{"decision":"refused","reply":"Dear Mara Voss,\n\nThank you for writing to us about order A-1021.\n\nWe are unable to issue a refund for this order, as our policy allows refunds within thirty days of delivery..."}
```

In `examples/workflows/refund-desk.cern.md`, find “within thirty days of delivery” and change
thirty to sixty. Deploy the desk with `cernanto deploy examples/workflows/refund-desk`. The
compiler edits the code under that sentence and runs the desk’s tests live before it ships.
Then send the same request again:

Shell

```sh
curl -s -X POST -H 'content-type: application/json' -d "{\"orderId\":\"$ORDER\",\"message\":\"The desk pad is unused, still in its wrap. Could I get a refund?\"}" http://127.0.0.1:8085/refund-requests
```

Output

```text
{"decision":"refunded","reply":"Dear Mara Voss,\n\nThank you for writing to us about order A-1021.\n\nWe have refunded you €29 under our policy..."}
```

## Run the walkthrough

At compile time, the coding assistant turns the policy into TypeScript. At run time, code
checks the delivery date and the amount paid, and two model calls read what the customer asks
for and whether they say the item is unused. A third model call drafts the reply.
[Compare the compiled desk with a tool-calling loop.](https://github.com/Cernanto/cernanto/blob/v0.9.4/agents/examples/comparison/README.md)

The desk’s compiled code names five other agents, each a module the compiler generated from
that agent’s contract. The chat is an interface, bound to one implementor by its id.

In a Unix shell, [deploy the example collection and connect model access](/install#full-collection). Run these
commands from the checkout’s `agents/` directory. The sandbox supplies the orders and the
support channel.

[Read the English policy.](https://github.com/Cernanto/cernanto/blob/v0.9.4/agents/examples/workflows/refund-desk.cern.md)

<a id="refund-desk"></a>

Tier-one handling of return and refund requests under a written
policy, and the tree's OpenAPI server: the storefront posts the order
id and the customer's message to the desk's document, and gets the
decision and the reply to send. The policy is code, the words come
from the template `reply.md`, and two judgments read the customer's
message: what they ask for, and whether they say the item is unused.

The source is `../refund-desk.cern.md`; the document it implements is
`openapi.yaml` beside this file, which the desk serves itself on port 8085.

```
$ cernanto deploy examples/workflows/refund-desk
```

Inside the policy (delivered within thirty days, unused): a refund,
made once however many times the same request arrives. The shop's
seeded orders age out of the window, so place one delivered three
days ago:

```
$ ORDER=$(cernanto call examples/sandbox/orders placeOrder --args '{"customerName":"Jonas Berg","customerEmail":"jonas.berg@example.org","items":[{"name":"Ledger notebook","quantity":3}],"total":87,"cardLastFour":"4242"}' -q | sed -E 's/^\{"id":"([^"]+)".*/\1/')
$ DELIVERED=$(node -e 'console.log(new Date(Date.now() - 3 * 864e5).toISOString().slice(0, 10))')
$ cernanto call examples/sandbox/orders markDelivered orderId="$ORDER" deliveredAt="$DELIVERED" -q > /dev/null
$ curl -s -X POST -H 'content-type: application/json' -d "{\"orderId\":\"$ORDER\",\"message\":\"The notebooks arrived but I ordered the wrong size. They are unused, still in the box. Could I get a refund?\"}" http://127.0.0.1:8085/refund-requests
{"decision":"refunded","reply":"Dear Jonas Berg,\n\nThank you for writing to us about order A-1021.\n\nWe have refunded you €87 under our policy, as the notebooks were returned unused and in their original box..."}
```

Outside it: a refusal with the policy's reason.

```
$ curl -s -X POST -H 'content-type: application/json' \
    -d '{"orderId":"A-1001","message":"I would like to return the notebooks, unused, for a refund."}' \
    http://127.0.0.1:8085/refund-requests
{"decision":"refused","reply":"Dear Lena Fischer,\n\nThank you for writing to us about order A-1001.\n\nWe are unable to issue a refund for this order, as our policy allows refunds only within thirty days of delivery, and your order was delivered 83 days ago on 2026-07-06.\n\nKind regards,\nAcme Ledgers support"}
```

Unsettled (an exchange): a person on the support channel, and a
reply that says so.

```
$ curl -s -X POST -H 'content-type: application/json' \
    -d '{"orderId":"A-1008","message":"One of the two pens leaks. Can you exchange it?"}' \
    http://127.0.0.1:8085/refund-requests
{"decision":"escalated","reply":"Dear Jonas Berg,\n\nThank you for writing to us about order A-1008.\n\nAs your request involves an exchange, we have escalated your case to a colleague, who will be in touch within one working day.\n\nKind regards,\nAcme Ledgers support"}
$ cernanto call examples/sandbox/chat read chat="#support"
[... {"from":{"id":"@acme"},"text":"Refund desk: order A-1008 (Jonas Berg, jonas.berg@example.org) needs a person, because the customer asks for an exchange. The customer wrote: \"One of the two pens leaks. Can you exchange it?\""}]
```

An unknown order is the document's 404:

```
$ curl -s -X POST -H 'content-type: application/json' -d '{"orderId":"A-9999","message":"refund please"}' http://127.0.0.1:8085/refund-requests
{"error":{"kind":"terminal","message":"no order with id A-9999"}}
```

The same function serves the wire: `cernanto call examples/workflows/refund-desk
submitRefundRequest --args '{"body":{"orderId":"A-1012","message":"..."}}'`
answers the same, with the same refund id, because a refund is keyed
by its order. The desk's tests set each case up in the shop (an order
placed and marked delivered on the date the case needs) and prove the
four roads. `cernanto tests examples/workflows/refund-desk` shows them.

[Make it yours](/examples/refund-desk#run-this-change-yourself)









































































## The real form

The refund goes to Stripe and the orders live in a database; the chat
is a setting, `interfaces/chat/default`, as the support desk's README shows.

**The orders.** `orders.sql` beside this README holds the shop's
tables, the orders with the payment each paid with, their invoices and
the refunds made, seeded with the sandbox's rows. Load it into a free
Neon or Supabase database; in the real world the `payment_id` column
holds the Stripe payment the order paid with, a test-mode payment
intent id (`pi_…`), in place of the sandbox's placeholders:

**Manual setup**

```
$ psql "$DATABASE_URL" -f examples/workflows/refund-desk/orders.sql
```

**The refund.** The desk refunds the order's payment through Stripe
with the order id as the key, so the same order is refunded once
however often the storefront asks, and records the refund on the
order. The source changes its grants, the database and its schema where
the sandbox shop was and Stripe beside them:

```diff
 Uses:

-- examples/sandbox/orders
+- examples/connections/postgres
+- file:refund-desk/orders.sql
+- examples/connections/stripe
 - cernanto/decision
 - cernanto/llm
 - file:refund-desk/reply.md
 - interfaces/chat
 - cernanto/config
```

and two sentences say what the grants cannot, where the orders live
and that the refund is recorded on the order:

```diff
-fetch the order and, at the same time, decide what the customer asks
-for, a return, a refund, an exchange or something else, and whether
+fetch the order from the shop's database, whose tables the granted
+schema describes, and, at the same time, decide what the customer asks
+for, a return, a refund, an exchange or something else, and whether
```

```diff
-not say the item is unused are outside it. Inside the policy, refund
-the order, once however many times the request comes, and answer a
-reply drafted on the template. Outside the policy, refuse with the
+not say the item is unused are outside it. Inside the policy, refund
+the order's payment, once however many times the request comes, record
+the refund on the order, and answer a reply drafted on the template.
+Outside the policy, refuse with the
```

The tests set each case up in the database instead of the shop, paid
with the test-mode payment the configuration names under
`examples/connections/stripe/tests/payment`, and keep the amounts to a few cents so that
payment lasts:

```diff
 ## Tests

 Uses:

-- examples/sandbox/orders
+- examples/connections/postgres
+- cernanto/config

-The same request sent twice refunds once. A refund asked for an item
+The same request sent twice refunds once, and the refund is on the
+order. A refund asked for an item
 the customer says was used, on a recent order, is refused for that
 reason.
-Each test case is set up in the shop: place the order and mark it
-delivered on the date the case needs, within thirty days for a request
-the policy covers and earlier for one it does not.
+Each test case is set up in the database: insert the order, a few
+cents in total and paid with the test-mode payment the configuration
+names under `examples/connections/stripe/tests/payment`, delivered on the date
+the case needs, within thirty days for a request the policy covers and
+earlier for one it does not.
```

The compile prints the labels back:

```
examples/workflows/refund-desk  plan  reads Uses: examples/connections/postgres, file:refund-desk/orders.sql, examples/connections/stripe, cernanto/decision, cernanto/llm, file:refund-desk/reply.md, interfaces/chat, cernanto/config
examples/workflows/refund-desk  plan  reads Implements: openapi:refund-desk/openapi.yaml
examples/workflows/refund-desk  plan  reads the tests; Uses: examples/connections/postgres, cernanto/config
```

Then `cernanto deploy examples/workflows/refund-desk`: the Stripe key is
asked for on the first refund, the database url on the first read;
the examples' steps are in `examples/connections/stripe/README.md` and
`examples/connections/postgres/README.md`.

---

[Release source](https://github.com/Cernanto/cernanto/blob/v0.9.4/agents/examples/workflows/refund-desk/README.md) · [HTML page](https://cernanto.com/examples/refund-desk)

## Project

[GitHub](https://github.com/Cernanto/cernanto) · [npm](https://www.npmjs.com/package/cernanto)

[About](/about)

## Contact

[Project questions](https://github.com/Cernanto/cernanto/discussions) · [Report an issue](https://github.com/Cernanto/cernanto/issues)

[Licensing](mailto:legal@cernanto.com) · [Security](mailto:security@cernanto.com)

## Legal

[License](/license) · [Patents and trademarks](/license#patents)

[Privacy](/license#privacy)

Cernanto™ · Copyright © 2026 Cernanto
