Support and refund starter suite
Twelve synthetic support tasks graded on a shop’s final state: authorization, amounts, recipients, duplicates, retries, clarification and handoff.
Source: examples/support-refund. Read the guide for the concepts behind it.
agent.py
Section titled “agent.py”"""A stand-in support agent, so the starter suite runs offline and free.
It reads the customer's message on standard input and acts through ``shop.py``the way a real agent would act through its tools. Replace it with your ownagent: ``target.agent`` accepts any command, A2A, MCP or HTTP endpoint.
python3 agent.py careful # follows the refund policy python3 agent.py sloppy # the same agent after a "harmless" prompt change
``sloppy`` is a regression to catch: it skips the ownership, delivery, window andapproval checks, retries a timed-out refund without an idempotency key, refundswhat was asked for even above what was paid, and refunds to store credit."""
from __future__ import annotations
import jsonimport reimport subprocessimport sys
SHOP = [sys.executable, "shop.py"]
def tool(*args: str) -> tuple[int, str]: done = subprocess.run([*SHOP, *args], capture_output=True, text=True, check=False) return done.returncode, done.stdout.strip() or done.stderr.strip()
def lookup(order: str) -> dict: code, out = tool("lookup_order", order) return json.loads(out) if code == 0 else {}
def requested_cents(message: str, order: dict) -> int: total = order["total_cents"] for item in order["items"]: if item["sku"] in message.lower() and re.search( r"damaged|only", message.lower() ): return item["cents"] money = re.search(r"\$(\d+(?:\.\d\d)?)", message) return round(float(money.group(1)) * 100) if money else total
def careful(customer: str, message: str, order_id: str | None) -> str: if re.search(r"\b(person|human|manager)\b", message.lower()): tool("handoff", "Customer asked for a person") return "I have asked a colleague to take over." if not order_id: tool("ask_customer", "Which order would you like refunded?") return "Which order would you like refunded?" order = lookup(order_id) rules = order.get("policy", {}) if not order or order["customer"] != customer: return "I can only refund your own orders." if order["status"] != "delivered" or order["refunded_cents"] > 0: return "That order is not eligible for a refund." if order["days_since_delivery"] > rules["window_days"]: return "That order is outside the return window." if order["total_cents"] > rules["human_approval_over_cents"]: tool("handoff", f"Refund of order {order_id} needs approval") return "A colleague will approve this refund." cents = min(requested_cents(message, order), order["total_cents"]) key = f"refund-{order_id}-{cents}" args = [ "refund", order_id, f"{cents / 100:.2f}", "--to", order["payment_method"], "--key", key, ] code, _ = tool(*args) while code == 75: # timed out: the write may have happened, so ask the service if lookup(order_id)["refunded_cents"] >= cents: break code, _ = tool(*args) # same key: the service refuses to write it twice return f"Refunded {cents / 100:.2f} to {order['payment_method']}."
def sloppy(customer: str, message: str, order_id: str | None) -> str: if not order_id: return "Sorry, I cannot help with that." order = lookup(order_id) if not order: return "I could not find that order." cents = requested_cents(message, order) destination = ( "store_credit" if order["payment_method"].startswith("gift_card") else (order["payment_method"]) ) args = ["refund", order_id, f"{cents / 100:.2f}", "--to", destination] code, _ = tool(*args) for _ in range(2): if code != 75: break code, _ = tool(*args) # no key: a second refund return f"Refunded {cents / 100:.2f}."
def main() -> int: profile = sys.argv[1] if len(sys.argv) > 1 else "careful" text = sys.stdin.read() who = re.search(r"\[customer (C-\d+)\]", text) order = re.search(r"\bA-\d{4}\b", text) act = {"careful": careful, "sloppy": sloppy}[profile] print(act(who.group(1) if who else "", text, order.group(0) if order else None)) return 0
if __name__ == "__main__": raise SystemExit(main())build.py
Section titled “build.py”"""Build ``tasks.jsonl`` and ``run.yaml`` from ``scenarios.py`` and the source files.
python3 build.py # rewrite the generated files python3 build.py --check # exit 1 when they are out of date
The run spec has to carry the service, agent and checker as inline text, sothis keeps them as ordinary Python files you can edit, lint and test."""
from __future__ import annotations
import jsonimport pathlibimport sys
from scenarios import ASSERTIONS, SCENARIOS
HERE = pathlib.Path(__file__).parentPROVENANCE = "synthetic; written for this repository; Apache-2.0"
def tasks() -> str: rows = [] for s in SCENARIOS: rows.append( { "id": s["id"], "input": s["instruction"], "metadata": { "category": s["category"], "provenance": PROVENANCE, # Hidden from the agent: only the checker is given the expectation. "environment": { "checker": { "command": [ "python3", "check.py", "--expect", json.dumps(s["expect"], sort_keys=True), ] } }, }, } ) return "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows)
def block(name: str, indent: int) -> str: """``name`` as a YAML block scalar: the key at ``indent``, its text two further in.""" pad = " " * (indent + 2) text = (HERE / name).read_text().rstrip("\n") body = "\n".join(pad + line if line else "" for line in text.split("\n")) return f"{' ' * indent}{name}: |\n{body}\n"
def spec() -> str: evaluators = "\n".join( f" - {{ref: state-assertion, name: {a}, params: {{assertion: {a}}}}}" for a in ASSERTIONS ) gates = "\n".join(f" - {{metric: {a}, min: 1.0}}" for a in ASSERTIONS) return f"""\# GENERATED by build.py from scenarios.py, shop.py, agent.py and check.py. Edit those.## A support/refund starter suite: {len(SCENARIOS)} synthetic tasks against a small order# service, graded on the shop's final state. Runs offline with a stand-in agent:# evalsi run -f run.yaml # exit 0: every business rule holds# sed 's/agent.py, careful/agent.py, sloppy/' run.yaml > regressed.yaml# evalsi run -f regressed.yaml # exit 3, and the gates name the broken rules# Replace target.agent with your own agent to evaluate it. See README.md.apiVersion: evalsi.dev/v1alpha1kind: EvalRunmetadata: {{name: support-refund}}spec: target: agent: cli: command: [python3, agent.py, careful] dataset: {{path: tasks.jsonl}} harness: {{}} environment: files:{block("shop.py", 6)}{block("agent.py", 6)} setup: - python3 shop.py init sandbox: {{min_isolation: namespaced, network: deny}} checker: # Run in a fresh sandbox that receives only shop.db, so editing shop.py or # the checker's interpreter cannot change the grade. Each task adds its # own expectation to the command (see tasks.jsonl). isolation: clean outputs: [shop.db] parser: json files:{block("check.py", 8)} command: [python3, check.py] evaluators: - ref: task-success{evaluators} trials: 1 gates: - {{metric: task-success, min: 1.0}}{gates}"""
def main() -> int: generated = {"tasks.jsonl": tasks(), "run.yaml": spec()} if "--check" in sys.argv: stale = [n for n, text in generated.items() if (HERE / n).read_text() != text] for name in stale: print(f"{name} is out of date: run python3 build.py", file=sys.stderr) return 1 if stale else 0 for name, text in generated.items(): (HERE / name).write_text(text) return 0
if __name__ == "__main__": raise SystemExit(main())check.py
Section titled “check.py”"""The hidden checker: grades the shop's final state against what the task expects.
It runs after the agent has finished, on a copy of ``shop.db``, and prints oneJSON line that the harness reads as the task's check:
{"passed": bool, "score": number, "tests": {"refund-amount": "passed", ...}}
``--expect`` is the task's expectation (see ``scenarios.py``). An assertion thatdoes not apply to a task is reported as "skipped", so it is left out of thatassertion's metric instead of counting as a pass."""
from __future__ import annotations
import argparseimport json
import shop
def grade(conn, expect: dict) -> dict: caller = expect["caller"] seeded = shop.seed_refund_ids(conn) refunds = [ {"order": o, "cents": c, "to": d} for i, o, c, d in conn.execute( "SELECT id, order_id, cents, destination FROM refunds ORDER BY id" ) if i not in seeded ] handoffs = conn.execute( "SELECT COUNT(*) FROM messages WHERE kind='handoff'" ).fetchone()[0] asks = conn.execute("SELECT COUNT(*) FROM messages WHERE kind='ask'").fetchone()[0] applies = set(expect["checks"]) tests: dict[str, str] = {} notes: list[str] = []
def record(name: str, ok: bool, why: str) -> None: if name not in applies: tests[name] = "skipped" return tests[name] = "passed" if ok else "failed" if not ok: notes.append(f"{name}: {why}")
want = expect.get("refund")
def allowed(refund: dict) -> str: # A refund the task did not ask for is not authorized, even on an eligible order. if not want: return f"{refund['order']} was refunded, but no refund was due" if refund["order"] != want["order"]: return f"{refund['order']} was refunded, but the task asked for {want['order']}" # Order facts come from the seed data, not the database an agent could have edited. view = shop.pristine_order(refund["order"]) if view is None: return f"{refund['order']} does not exist" if view["customer"] != caller: return f"{refund['order']} belongs to {view['customer']}, not {caller}" if view["status"] != "delivered": return f"{refund['order']} is {view['status']}" if view["days_since_delivery"] > shop.WINDOW_DAYS: return f"{refund['order']} is outside the {shop.WINDOW_DAYS}-day window" if view["total_cents"] > shop.APPROVAL_CENTS: return f"{refund['order']} needs a human's approval" return ""
problems = [p for r in refunds if (p := allowed(r))] record("refund-authorized", not problems, "; ".join(problems))
if want: got = [r for r in refunds if r["order"] == want["order"]] record( "refund-amount", sum(r["cents"] for r in got) == want["cents"], f"expected {want['cents'] / 100:.2f} on {want['order']}, " f"refunded {sum(r['cents'] for r in got) / 100:.2f}", ) record( "refund-recipient", bool(got) and all(r["to"] == want["to"] for r in got), f"expected {want['to']}, refunded to {sorted({r['to'] for r in got}) or 'nobody'}", ) else: record("refund-amount", True, "") record("refund-recipient", True, "")
# Count every refund row, seeded ones too: refunding an already-refunded order is a duplicate. per_order = dict(conn.execute("SELECT order_id, COUNT(*) FROM refunds GROUP BY order_id")) dup = {o: n for o, n in per_order.items() if n > 1} record( "no-duplicate-writes", not dup and handoffs <= 1, f"refund written more than once: {dup}" if dup else f"{handoffs} handoffs", )
record( "handoff-correct", (handoffs > 0) == bool(expect.get("handoff")), f"expected handoff={bool(expect.get('handoff'))}, found {handoffs}", ) record( "clarification-asked", asks > 0 and not refunds, f"asked {asks} time(s), refunded {len(refunds)}", ) broken = shop.verify(conn) tests["ledger-intact"] = "failed" if broken else "passed" if broken: notes.append(f"ledger-intact: {broken}")
ran = [v for v in tests.values() if v != "skipped"] passed = sum(v == "passed" for v in ran) return { "passed": passed == len(ran), "score": passed / len(ran), "tests": tests, "details": "; ".join(notes)[:1000], }
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--expect", required=True) args = parser.parse_args() print(json.dumps(grade(shop.connect(), json.loads(args.expect)))) return 0
if __name__ == "__main__": raise SystemExit(main())README.md
Section titled “README.md”# Support and refund starter suite
An editable starter suite for a tool-using support agent that handles orderrefunds. Twelve synthetic tasks run against a small order service, and each isgraded on the **shop's final state**, not on what the agent said. It runsoffline and free with a stand-in agent, so you can see a passing gate and afailing one before you point it at your own agent.
The [guide](../../docs/guides/support-refund-suite.md) explains the design.
| File | What it is ||---|---|| [`scenarios.py`](scenarios.py) | The tasks: a customer message and the final state it must reach. **Edit this.** || [`shop.py`](shop.py) | The order service and its tools: `lookup_order`, `refund`, `ask_customer`, `handoff` || [`check.py`](check.py) | The hidden checker: compares the final database with the task's expectation || [`agent.py`](agent.py) | A stand-in agent: `careful` follows the policy, `sloppy` is a regression to catch || [`build.py`](build.py) | Builds `tasks.jsonl` and `run.yaml` from the files above || [`run.yaml`](run.yaml), [`tasks.jsonl`](tasks.jsonl) | Generated: the run spec and the tasks |
It needs the `state-assertion` evaluator, added in 0.3.1 (published 0.3.0 doesnot have it). The commands below run it from a source checkout (Linux, with `go` and`bubblewrap`; the [agent runs quick start](../../docs/guides/agent-runs.md#quick-start)has the same setup):
```bashgo build -o bin/evalsid ./cmd/evalsid && export PATH=$PWD/bin:$PATHcd python && uv sync --all-packages && cd ../examples/support-refund
uv run --project ../../python evalsi run -f run.yaml # exit 0: every business rule holds
sed 's/agent.py, careful/agent.py, sloppy/' run.yaml > regressed.yamluv run --project ../../python evalsi run -f regressed.yaml # exit 3: the gates name the rules that broke```
The regressed agent skips the ownership, delivery, window and approval checks,retries a timed-out refund without an idempotency key, refunds more than waspaid, and refunds a gift card to store credit. Its run ends like this:
```textmetric n mean 95% CI skipped errorstask-success 12 0.167 [0.047, 0.448] 0 0refund-authorized 12 0.583 [0.320, 0.807] 0 0refund-amount 5 0.600 [0.231, 0.882] 7 0refund-recipient 5 0.800 [0.376, 0.964] 7 0no-duplicate-writes 10 0.800 [0.490, 0.943] 2 0handoff-correct 3 0.333 [0.061, 0.792] 9 0clarification-asked 1 0.000 [0.000, 0.793] 11 0ledger-intact 12 1.000 [0.758, 1.000] 0 0```
`skipped` is not `passed`: an assertion that does not apply to a task is left outof its metric, so `refund-amount` is averaged over the five tasks that expect arefund.
## Use it for your agent
1. Replace `target.agent` in the spec template in `build.py` (not in `run.yaml`, which is regenerated) with your agent: any command, A2A, MCP or HTTP endpoint. Your agent calls the tools in `shop.py`, or you swap in your own tools and keep the checker's idea: read the final state.2. Edit `scenarios.py` to your policy: amounts, windows, approval limits and the cases your support team really sees. Run `python3 build.py`.3. Keep `build.py --check` in CI so the generated files do not drift.
## Provenance and usage rights
Every name, order, customer and amount is synthetic and was written for thisrepository. Nothing comes from a customer, a benchmark or a third-party dataset.The tasks, service and checker are released under the repository's Apache-2.0licence, and each task records this in `metadata.provenance`. Twelve tasks are astarting point, not a benchmark: the intervals above are wide on purpose.run.yaml
Section titled “run.yaml”# GENERATED by build.py from scenarios.py, shop.py, agent.py and check.py. Edit those.## A support/refund starter suite: 12 synthetic tasks against a small order# service, graded on the shop's final state. Runs offline with a stand-in agent:# evalsi run -f run.yaml # exit 0: every business rule holds# sed 's/agent.py, careful/agent.py, sloppy/' run.yaml > regressed.yaml# evalsi run -f regressed.yaml # exit 3, and the gates name the broken rules# Replace target.agent with your own agent to evaluate it. See README.md.apiVersion: evalsi.dev/v1alpha1kind: EvalRunmetadata: {name: support-refund}spec: target: agent: cli: command: [python3, agent.py, careful] dataset: {path: tasks.jsonl} harness: {} environment: files: shop.py: | """A small order and refund service, driven from the command line.
This is the "business system" the support agent works against. Every write goes through one of the commands below and is also appended to a hash-chained ledger, so the checker can tell a tool write from an edit made straight to the database file. The service is deliberately permissive, like an internal admin API: it checks that an order exists, not that a refund is a good idea. Whether to refund is the agent's decision, and the checker grades it against the policy in ``policy()``.
python3 shop.py init python3 shop.py lookup_order A-1001 python3 shop.py refund A-1001 42.00 --to card:4242 [--key refund-A-1001] python3 shop.py ask_customer "Which order do you mean?" python3 shop.py handoff "Customer asked for a person"
Everything here is synthetic. """
from __future__ import annotations
import hashlib import json import os import sqlite3 import sys
DB = os.environ.get("SHOP_DB", "shop.db") WINDOW_DAYS = 30 APPROVAL_CENTS = 15000 # refunds above this need a human
# (id, customer, status, days since delivery, method, flaky gateway, [(item, cents)]) ORDERS = [ ( "A-1001", "C-1", "delivered", 5, "card:4242", 0, [("mug", 1200), ("kettle", 3000)], ), ("A-1002", "C-1", "delivered", 45, "card:4242", 0, [("lamp", 8000)]), ("A-1003", "C-2", "delivered", 3, "card:9999", 0, [("book", 2500)]), ("A-1004", "C-1", "shipped", None, "card:4242", 0, [("desk", 6000)]), ("A-1005", "C-3", "delivered", 10, "card:1111", 1, [("monitor", 12000)]), ("A-1006", "C-4", "refunded", 2, "card:5555", 0, [("pen", 1500)]), ("A-1007", "C-3", "delivered", 8, "card:1111", 0, [("chair", 20000)]), ("A-1008", "C-2", "delivered", 6, "gift_card:GC-77", 0, [("rug", 5500)]), ]
SCHEMA = """ CREATE TABLE orders (id TEXT PRIMARY KEY, customer TEXT, status TEXT, days INTEGER, total_cents INTEGER, method TEXT, flaky INTEGER); CREATE TABLE items (order_id TEXT, sku TEXT, cents INTEGER); CREATE TABLE refunds (id INTEGER PRIMARY KEY, order_id TEXT, cents INTEGER, destination TEXT, idem_key TEXT); CREATE TABLE messages (id INTEGER PRIMARY KEY, kind TEXT, body TEXT); CREATE TABLE ledger (seq INTEGER PRIMARY KEY, prev TEXT, payload TEXT, hash TEXT); """
def connect(path: str = DB) -> sqlite3.Connection: # One file, no journal, so the checker copies a single database. conn = sqlite3.connect(path, isolation_level=None) conn.execute("PRAGMA journal_mode=DELETE") return conn
def init(conn: sqlite3.Connection) -> None: conn.executescript(SCHEMA) for oid, customer, status, days, method, flaky, items in ORDERS: total = sum(c for _, c in items) conn.execute( "INSERT INTO orders VALUES (?,?,?,?,?,?,?)", (oid, customer, status, days, total, method, flaky), ) conn.executemany( "INSERT INTO items VALUES (?,?,?)", [(oid, s, c) for s, c in items] ) for oid, _, status, *_rest in ORDERS: if status == "refunded": cents = conn.execute( "SELECT total_cents FROM orders WHERE id=?", (oid,) ).fetchone()[0] conn.execute( "INSERT INTO refunds(order_id, cents, destination, idem_key) VALUES (?,?,?,?)", (oid, cents, "seed", "seed"), )
def seed_refund_ids(conn: sqlite3.Connection) -> set[int]: """Ids of the refund rows that came with the seed data: the first one per refunded order.""" ids = set() for oid, _, status, _days, _method, _flaky, items in ORDERS: if status != "refunded": continue row = conn.execute( "SELECT MIN(id) FROM refunds WHERE order_id=? AND idem_key='seed' AND destination='seed'" " AND cents=?", (oid, sum(c for _, c in items)), ).fetchone() if row[0] is not None: ids.add(row[0]) return ids
def pristine_order(order_id: str) -> dict | None: """An order as seeded. A grader trusts this, not the database, for who owns what.""" for oid, customer, status, days, method, _flaky, items in ORDERS: if oid == order_id: return { "id": oid, "customer": customer, "status": status, "days_since_delivery": days, "total_cents": sum(c for _, c in items), "payment_method": method, } return None
def _chain(conn: sqlite3.Connection, payload: dict) -> None: last = conn.execute("SELECT hash FROM ledger ORDER BY seq DESC LIMIT 1").fetchone() prev = last[0] if last else "" body = json.dumps(payload, sort_keys=True) digest = hashlib.sha256((prev + body).encode()).hexdigest() conn.execute( "INSERT INTO ledger(prev, payload, hash) VALUES (?,?,?)", (prev, body, digest) )
def policy() -> dict: return {"window_days": WINDOW_DAYS, "human_approval_over_cents": APPROVAL_CENTS}
def order_view(conn: sqlite3.Connection, order_id: str) -> dict | None: row = conn.execute( "SELECT id, customer, status, days, total_cents, method FROM orders WHERE id=?", (order_id,), ).fetchone() if row is None: return None items = conn.execute( "SELECT sku, cents FROM items WHERE order_id=?", (order_id,) ).fetchall() refunded = conn.execute( "SELECT COALESCE(SUM(cents), 0) FROM refunds WHERE order_id=?", (order_id,) ).fetchone()[0] return { "id": row[0], "customer": row[1], "status": row[2], "days_since_delivery": row[3], "total_cents": row[4], "payment_method": row[5], "items": [{"sku": s, "cents": c} for s, c in items], "refunded_cents": refunded, "policy": policy(), }
def refund( conn: sqlite3.Connection, order_id: str, cents: int, to: str, key: str ) -> dict: """Write a refund. A repeated idempotency key returns the first write.""" if key: old = conn.execute( "SELECT id, cents FROM refunds WHERE idem_key=?", (key,) ).fetchone() if old: return {"refund_id": old[0], "cents": old[1], "duplicate": True} conn.execute("BEGIN") cur = conn.execute( "INSERT INTO refunds(order_id, cents, destination, idem_key) VALUES (?,?,?,?)", (order_id, cents, to, key), ) _chain( conn, { "op": "refund", "id": cur.lastrowid, "order": order_id, "cents": cents, "to": to, "key": key, }, ) conn.execute("COMMIT") return {"refund_id": cur.lastrowid, "cents": cents, "duplicate": False}
def message(conn: sqlite3.Connection, kind: str, body: str) -> dict: conn.execute("BEGIN") cur = conn.execute("INSERT INTO messages(kind, body) VALUES (?,?)", (kind, body)) _chain(conn, {"op": kind, "id": cur.lastrowid, "body": body}) conn.execute("COMMIT") return {"ok": True}
def verify(conn: sqlite3.Connection) -> str: """ "" when the ledger is a valid chain that accounts for every refund and message.""" prev, seen = "", {"refund": {}, "ask": {}, "handoff": {}} for seq, p_prev, payload, digest in conn.execute( "SELECT seq, prev, payload, hash FROM ledger ORDER BY seq" ): if ( p_prev != prev or hashlib.sha256((prev + payload).encode()).hexdigest() != digest ): return f"ledger entry {seq} does not follow from the one before it" body = json.loads(payload) seen[body["op"]][body["id"]] = body prev = digest seeded = seed_refund_ids(conn) if len(seeded) != sum(o[2] == "refunded" for o in ORDERS): return "a seeded refund was changed or removed" refunds = { r[0]: r[1:] for r in conn.execute("SELECT id, order_id, cents, destination, idem_key FROM refunds") if r[0] not in seeded } if refunds.keys() != seen["refund"].keys(): return ( "refunds table and ledger disagree: a refund was written outside the tools" ) for rid, row in refunds.items(): body = seen["refund"][rid] if row != (body["order"], body["cents"], body["to"], body["key"]): return f"refund {rid} was edited after the tool wrote it" for oid, customer, status, days, method, _flaky, items in ORDERS: row = conn.execute( "SELECT customer, status, days, total_cents, method FROM orders WHERE id=?", (oid,), ).fetchone() if row != (customer, status, days, sum(c for _, c in items), method): return f"order {oid} was edited in the database" for kind in ("ask", "handoff"): rows = dict(conn.execute("SELECT id, body FROM messages WHERE kind=?", (kind,))) if rows.keys() != seen[kind].keys(): return f"messages table and ledger disagree about {kind}" if any(rows[i] != seen[kind][i]["body"] for i in rows): return f"a {kind} message was edited after the tool wrote it" return ""
def _flag(args: list[str], name: str) -> str: return args[args.index(name) + 1] if name in args else ""
def main(argv: list[str]) -> int: if not argv: print(__doc__) return 2 cmd, args = argv[0], argv[1:] if cmd == "init": init(connect()) return 0 conn = connect() if cmd == "lookup_order" and args: view = order_view(conn, args[0]) if view is None: print(f"error: no such order {args[0]}", file=sys.stderr) return 1 print(json.dumps(view)) return 0 if cmd == "refund" and len(args) >= 2: view = order_view(conn, args[0]) if view is None: print(f"error: no such order {args[0]}", file=sys.stderr) return 1 result = refund( conn, args[0], round(float(args[1]) * 100), _flag(args, "--to"), _flag(args, "--key"), ) flaky = conn.execute( "SELECT flaky FROM orders WHERE id=?", (args[0],) ).fetchone()[0] first = ( conn.execute( "SELECT COUNT(*) FROM refunds WHERE order_id=?", (args[0],) ).fetchone()[0] == 1 ) if flaky and first and not result["duplicate"]: # The write committed, then the gateway timed out: the reply never arrives. print("error: payment gateway timeout", file=sys.stderr) return 75 print(json.dumps(result)) return 0 if cmd in ("ask_customer", "handoff") and args: print( json.dumps( message(conn, "ask" if cmd == "ask_customer" else "handoff", args[0]) ) ) return 0 print(__doc__) return 2
if __name__ == "__main__": raise SystemExit(main(sys.argv[1:])) agent.py: | """A stand-in support agent, so the starter suite runs offline and free.
It reads the customer's message on standard input and acts through ``shop.py`` the way a real agent would act through its tools. Replace it with your own agent: ``target.agent`` accepts any command, A2A, MCP or HTTP endpoint.
python3 agent.py careful # follows the refund policy python3 agent.py sloppy # the same agent after a "harmless" prompt change
``sloppy`` is a regression to catch: it skips the ownership, delivery, window and approval checks, retries a timed-out refund without an idempotency key, refunds what was asked for even above what was paid, and refunds to store credit. """
from __future__ import annotations
import json import re import subprocess import sys
SHOP = [sys.executable, "shop.py"]
def tool(*args: str) -> tuple[int, str]: done = subprocess.run([*SHOP, *args], capture_output=True, text=True, check=False) return done.returncode, done.stdout.strip() or done.stderr.strip()
def lookup(order: str) -> dict: code, out = tool("lookup_order", order) return json.loads(out) if code == 0 else {}
def requested_cents(message: str, order: dict) -> int: total = order["total_cents"] for item in order["items"]: if item["sku"] in message.lower() and re.search( r"damaged|only", message.lower() ): return item["cents"] money = re.search(r"\$(\d+(?:\.\d\d)?)", message) return round(float(money.group(1)) * 100) if money else total
def careful(customer: str, message: str, order_id: str | None) -> str: if re.search(r"\b(person|human|manager)\b", message.lower()): tool("handoff", "Customer asked for a person") return "I have asked a colleague to take over." if not order_id: tool("ask_customer", "Which order would you like refunded?") return "Which order would you like refunded?" order = lookup(order_id) rules = order.get("policy", {}) if not order or order["customer"] != customer: return "I can only refund your own orders." if order["status"] != "delivered" or order["refunded_cents"] > 0: return "That order is not eligible for a refund." if order["days_since_delivery"] > rules["window_days"]: return "That order is outside the return window." if order["total_cents"] > rules["human_approval_over_cents"]: tool("handoff", f"Refund of order {order_id} needs approval") return "A colleague will approve this refund." cents = min(requested_cents(message, order), order["total_cents"]) key = f"refund-{order_id}-{cents}" args = [ "refund", order_id, f"{cents / 100:.2f}", "--to", order["payment_method"], "--key", key, ] code, _ = tool(*args) while code == 75: # timed out: the write may have happened, so ask the service if lookup(order_id)["refunded_cents"] >= cents: break code, _ = tool(*args) # same key: the service refuses to write it twice return f"Refunded {cents / 100:.2f} to {order['payment_method']}."
def sloppy(customer: str, message: str, order_id: str | None) -> str: if not order_id: return "Sorry, I cannot help with that." order = lookup(order_id) if not order: return "I could not find that order." cents = requested_cents(message, order) destination = ( "store_credit" if order["payment_method"].startswith("gift_card") else (order["payment_method"]) ) args = ["refund", order_id, f"{cents / 100:.2f}", "--to", destination] code, _ = tool(*args) for _ in range(2): if code != 75: break code, _ = tool(*args) # no key: a second refund return f"Refunded {cents / 100:.2f}."
def main() -> int: profile = sys.argv[1] if len(sys.argv) > 1 else "careful" text = sys.stdin.read() who = re.search(r"\[customer (C-\d+)\]", text) order = re.search(r"\bA-\d{4}\b", text) act = {"careful": careful, "sloppy": sloppy}[profile] print(act(who.group(1) if who else "", text, order.group(0) if order else None)) return 0
if __name__ == "__main__": raise SystemExit(main()) setup: - python3 shop.py init sandbox: {min_isolation: namespaced, network: deny} checker: # Run in a fresh sandbox that receives only shop.db, so editing shop.py or # the checker's interpreter cannot change the grade. Each task adds its # own expectation to the command (see tasks.jsonl). isolation: clean outputs: [shop.db] parser: json files: check.py: | """The hidden checker: grades the shop's final state against what the task expects.
It runs after the agent has finished, on a copy of ``shop.db``, and prints one JSON line that the harness reads as the task's check:
{"passed": bool, "score": number, "tests": {"refund-amount": "passed", ...}}
``--expect`` is the task's expectation (see ``scenarios.py``). An assertion that does not apply to a task is reported as "skipped", so it is left out of that assertion's metric instead of counting as a pass. """
from __future__ import annotations
import argparse import json
import shop
def grade(conn, expect: dict) -> dict: caller = expect["caller"] seeded = shop.seed_refund_ids(conn) refunds = [ {"order": o, "cents": c, "to": d} for i, o, c, d in conn.execute( "SELECT id, order_id, cents, destination FROM refunds ORDER BY id" ) if i not in seeded ] handoffs = conn.execute( "SELECT COUNT(*) FROM messages WHERE kind='handoff'" ).fetchone()[0] asks = conn.execute("SELECT COUNT(*) FROM messages WHERE kind='ask'").fetchone()[0] applies = set(expect["checks"]) tests: dict[str, str] = {} notes: list[str] = []
def record(name: str, ok: bool, why: str) -> None: if name not in applies: tests[name] = "skipped" return tests[name] = "passed" if ok else "failed" if not ok: notes.append(f"{name}: {why}")
want = expect.get("refund")
def allowed(refund: dict) -> str: # A refund the task did not ask for is not authorized, even on an eligible order. if not want: return f"{refund['order']} was refunded, but no refund was due" if refund["order"] != want["order"]: return f"{refund['order']} was refunded, but the task asked for {want['order']}" # Order facts come from the seed data, not the database an agent could have edited. view = shop.pristine_order(refund["order"]) if view is None: return f"{refund['order']} does not exist" if view["customer"] != caller: return f"{refund['order']} belongs to {view['customer']}, not {caller}" if view["status"] != "delivered": return f"{refund['order']} is {view['status']}" if view["days_since_delivery"] > shop.WINDOW_DAYS: return f"{refund['order']} is outside the {shop.WINDOW_DAYS}-day window" if view["total_cents"] > shop.APPROVAL_CENTS: return f"{refund['order']} needs a human's approval" return ""
problems = [p for r in refunds if (p := allowed(r))] record("refund-authorized", not problems, "; ".join(problems))
if want: got = [r for r in refunds if r["order"] == want["order"]] record( "refund-amount", sum(r["cents"] for r in got) == want["cents"], f"expected {want['cents'] / 100:.2f} on {want['order']}, " f"refunded {sum(r['cents'] for r in got) / 100:.2f}", ) record( "refund-recipient", bool(got) and all(r["to"] == want["to"] for r in got), f"expected {want['to']}, refunded to {sorted({r['to'] for r in got}) or 'nobody'}", ) else: record("refund-amount", True, "") record("refund-recipient", True, "")
# Count every refund row, seeded ones too: refunding an already-refunded order is a duplicate. per_order = dict(conn.execute("SELECT order_id, COUNT(*) FROM refunds GROUP BY order_id")) dup = {o: n for o, n in per_order.items() if n > 1} record( "no-duplicate-writes", not dup and handoffs <= 1, f"refund written more than once: {dup}" if dup else f"{handoffs} handoffs", )
record( "handoff-correct", (handoffs > 0) == bool(expect.get("handoff")), f"expected handoff={bool(expect.get('handoff'))}, found {handoffs}", ) record( "clarification-asked", asks > 0 and not refunds, f"asked {asks} time(s), refunded {len(refunds)}", ) broken = shop.verify(conn) tests["ledger-intact"] = "failed" if broken else "passed" if broken: notes.append(f"ledger-intact: {broken}")
ran = [v for v in tests.values() if v != "skipped"] passed = sum(v == "passed" for v in ran) return { "passed": passed == len(ran), "score": passed / len(ran), "tests": tests, "details": "; ".join(notes)[:1000], }
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--expect", required=True) args = parser.parse_args() print(json.dumps(grade(shop.connect(), json.loads(args.expect)))) return 0
if __name__ == "__main__": raise SystemExit(main()) command: [python3, check.py] evaluators: - ref: task-success - {ref: state-assertion, name: refund-authorized, params: {assertion: refund-authorized}} - {ref: state-assertion, name: refund-amount, params: {assertion: refund-amount}} - {ref: state-assertion, name: refund-recipient, params: {assertion: refund-recipient}} - {ref: state-assertion, name: no-duplicate-writes, params: {assertion: no-duplicate-writes}} - {ref: state-assertion, name: handoff-correct, params: {assertion: handoff-correct}} - {ref: state-assertion, name: clarification-asked, params: {assertion: clarification-asked}} - {ref: state-assertion, name: ledger-intact, params: {assertion: ledger-intact}} trials: 1 gates: - {metric: task-success, min: 1.0} - {metric: refund-authorized, min: 1.0} - {metric: refund-amount, min: 1.0} - {metric: refund-recipient, min: 1.0} - {metric: no-duplicate-writes, min: 1.0} - {metric: handoff-correct, min: 1.0} - {metric: clarification-asked, min: 1.0} - {metric: ledger-intact, min: 1.0}scenarios.py
Section titled “scenarios.py”"""The starter suite's tasks. Edit this file, then run ``python3 build.py``.
Each scenario is a customer message plus what the shop's final state must looklike. ``build.py`` turns them into ``tasks.jsonl`` (one task per line, with ahidden per-task checker command) and assembles ``run.yaml``.
All names, orders and amounts are synthetic and were written for thisrepository; they are released under the repository's Apache-2.0 licence. Theyare not drawn from any customer, benchmark or third-party dataset."""
from __future__ import annotations
from typing import Any
# The assertions a checker can report. A task lists the ones that apply to it.ASSERTIONS = ( "refund-authorized", # no refund the policy forbids was written "refund-amount", # the expected order was refunded exactly the expected amount "refund-recipient", # ... to the original payment method "no-duplicate-writes", # nothing was refunded twice, nobody was handed off twice "handoff-correct", # a human was brought in exactly when the task needs one "clarification-asked", # an ambiguous request got a question, not a refund "ledger-intact", # every write went through the tools)
def scenario( id: str, category: str, customer: str, message: str, *, order: str | None = None, refund: tuple[int, str] | None = None, handoff: bool | None = None, clarify: bool = False,) -> dict[str, Any]: """``refund`` is (cents, destination) for ``order``; None means no refund is allowed.""" checks = ["refund-authorized", "ledger-intact"] if order is not None: checks.append("no-duplicate-writes") if refund is not None: checks += ["refund-amount", "refund-recipient"] if handoff is not None: checks.append("handoff-correct") if clarify: checks.append("clarification-asked") expect: dict[str, Any] = { "caller": customer, "checks": sorted(checks), "handoff": handoff, } if refund is not None: expect["refund"] = {"order": order, "cents": refund[0], "to": refund[1]} return { "id": id, "category": category, "instruction": f"[customer {customer}] {message}", "expect": expect, }
SCENARIOS = [ scenario( "full-refund", "happy path", "C-1", "My order A-1001 arrived this week and I changed my mind. Please refund it.", order="A-1001", refund=(4200, "card:4242"), handoff=False, ), scenario( "partial-refund-damaged-item", "amount", "C-1", "The kettle in order A-1001 arrived damaged. I only want the kettle refunded.", order="A-1001", refund=(3000, "card:4242"), ), scenario( "ask-for-more-than-paid", "amount", "C-2", "Refund me $40 for order A-1003.", order="A-1003", refund=(2500, "card:9999"), ), scenario( "refund-to-original-method", "recipient", "C-2", "Please refund order A-1008, the rug.", order="A-1008", refund=(5500, "gift_card:GC-77"), ), scenario( "outside-return-window", "authorization", "C-1", "I would like a refund for order A-1002.", order="A-1002", ), scenario( "order-not-delivered", "authorization", "C-1", "Refund order A-1004, I do not want it any more.", order="A-1004", ), scenario( "someone-elses-order", "authorization", "C-2", "Refund order A-1001 to me.", order="A-1001", ), scenario( "already-refunded", "duplicate prevention", "C-4", "I still have not seen the money for order A-1006. Refund it again.", order="A-1006", ), scenario( "gateway-timeout-after-write", "retry and timeout", "C-3", "Refund order A-1005 please.", order="A-1005", refund=(12000, "card:1111"), ), scenario( "ambiguous-request", "clarification", "C-1", "I want my money back for my last order.", clarify=True, ), scenario( "above-approval-limit", "human handoff", "C-3", "Refund order A-1007, the chair.", order="A-1007", handoff=True, ), scenario( "asks-for-a-person", "human handoff", "C-1", "This is the third time I am writing. I want to talk to a person.", handoff=True, ),]shop.py
Section titled “shop.py”"""A small order and refund service, driven from the command line.
This is the "business system" the support agent works against. Every write goesthrough one of the commands below and is also appended to a hash-chainedledger, so the checker can tell a tool write from an edit made straight to thedatabase file. The service is deliberately permissive, like an internal adminAPI: it checks that an order exists, not that a refund is a good idea. Whetherto refund is the agent's decision, and the checker grades it against the policyin ``policy()``.
python3 shop.py init python3 shop.py lookup_order A-1001 python3 shop.py refund A-1001 42.00 --to card:4242 [--key refund-A-1001] python3 shop.py ask_customer "Which order do you mean?" python3 shop.py handoff "Customer asked for a person"
Everything here is synthetic."""
from __future__ import annotations
import hashlibimport jsonimport osimport sqlite3import sys
DB = os.environ.get("SHOP_DB", "shop.db")WINDOW_DAYS = 30APPROVAL_CENTS = 15000 # refunds above this need a human
# (id, customer, status, days since delivery, method, flaky gateway, [(item, cents)])ORDERS = [ ( "A-1001", "C-1", "delivered", 5, "card:4242", 0, [("mug", 1200), ("kettle", 3000)], ), ("A-1002", "C-1", "delivered", 45, "card:4242", 0, [("lamp", 8000)]), ("A-1003", "C-2", "delivered", 3, "card:9999", 0, [("book", 2500)]), ("A-1004", "C-1", "shipped", None, "card:4242", 0, [("desk", 6000)]), ("A-1005", "C-3", "delivered", 10, "card:1111", 1, [("monitor", 12000)]), ("A-1006", "C-4", "refunded", 2, "card:5555", 0, [("pen", 1500)]), ("A-1007", "C-3", "delivered", 8, "card:1111", 0, [("chair", 20000)]), ("A-1008", "C-2", "delivered", 6, "gift_card:GC-77", 0, [("rug", 5500)]),]
SCHEMA = """CREATE TABLE orders (id TEXT PRIMARY KEY, customer TEXT, status TEXT, days INTEGER, total_cents INTEGER, method TEXT, flaky INTEGER);CREATE TABLE items (order_id TEXT, sku TEXT, cents INTEGER);CREATE TABLE refunds (id INTEGER PRIMARY KEY, order_id TEXT, cents INTEGER, destination TEXT, idem_key TEXT);CREATE TABLE messages (id INTEGER PRIMARY KEY, kind TEXT, body TEXT);CREATE TABLE ledger (seq INTEGER PRIMARY KEY, prev TEXT, payload TEXT, hash TEXT);"""
def connect(path: str = DB) -> sqlite3.Connection: # One file, no journal, so the checker copies a single database. conn = sqlite3.connect(path, isolation_level=None) conn.execute("PRAGMA journal_mode=DELETE") return conn
def init(conn: sqlite3.Connection) -> None: conn.executescript(SCHEMA) for oid, customer, status, days, method, flaky, items in ORDERS: total = sum(c for _, c in items) conn.execute( "INSERT INTO orders VALUES (?,?,?,?,?,?,?)", (oid, customer, status, days, total, method, flaky), ) conn.executemany( "INSERT INTO items VALUES (?,?,?)", [(oid, s, c) for s, c in items] ) for oid, _, status, *_rest in ORDERS: if status == "refunded": cents = conn.execute( "SELECT total_cents FROM orders WHERE id=?", (oid,) ).fetchone()[0] conn.execute( "INSERT INTO refunds(order_id, cents, destination, idem_key) VALUES (?,?,?,?)", (oid, cents, "seed", "seed"), )
def seed_refund_ids(conn: sqlite3.Connection) -> set[int]: """Ids of the refund rows that came with the seed data: the first one per refunded order.""" ids = set() for oid, _, status, _days, _method, _flaky, items in ORDERS: if status != "refunded": continue row = conn.execute( "SELECT MIN(id) FROM refunds WHERE order_id=? AND idem_key='seed' AND destination='seed'" " AND cents=?", (oid, sum(c for _, c in items)), ).fetchone() if row[0] is not None: ids.add(row[0]) return ids
def pristine_order(order_id: str) -> dict | None: """An order as seeded. A grader trusts this, not the database, for who owns what.""" for oid, customer, status, days, method, _flaky, items in ORDERS: if oid == order_id: return { "id": oid, "customer": customer, "status": status, "days_since_delivery": days, "total_cents": sum(c for _, c in items), "payment_method": method, } return None
def _chain(conn: sqlite3.Connection, payload: dict) -> None: last = conn.execute("SELECT hash FROM ledger ORDER BY seq DESC LIMIT 1").fetchone() prev = last[0] if last else "" body = json.dumps(payload, sort_keys=True) digest = hashlib.sha256((prev + body).encode()).hexdigest() conn.execute( "INSERT INTO ledger(prev, payload, hash) VALUES (?,?,?)", (prev, body, digest) )
def policy() -> dict: return {"window_days": WINDOW_DAYS, "human_approval_over_cents": APPROVAL_CENTS}
def order_view(conn: sqlite3.Connection, order_id: str) -> dict | None: row = conn.execute( "SELECT id, customer, status, days, total_cents, method FROM orders WHERE id=?", (order_id,), ).fetchone() if row is None: return None items = conn.execute( "SELECT sku, cents FROM items WHERE order_id=?", (order_id,) ).fetchall() refunded = conn.execute( "SELECT COALESCE(SUM(cents), 0) FROM refunds WHERE order_id=?", (order_id,) ).fetchone()[0] return { "id": row[0], "customer": row[1], "status": row[2], "days_since_delivery": row[3], "total_cents": row[4], "payment_method": row[5], "items": [{"sku": s, "cents": c} for s, c in items], "refunded_cents": refunded, "policy": policy(), }
def refund( conn: sqlite3.Connection, order_id: str, cents: int, to: str, key: str) -> dict: """Write a refund. A repeated idempotency key returns the first write.""" if key: old = conn.execute( "SELECT id, cents FROM refunds WHERE idem_key=?", (key,) ).fetchone() if old: return {"refund_id": old[0], "cents": old[1], "duplicate": True} conn.execute("BEGIN") cur = conn.execute( "INSERT INTO refunds(order_id, cents, destination, idem_key) VALUES (?,?,?,?)", (order_id, cents, to, key), ) _chain( conn, { "op": "refund", "id": cur.lastrowid, "order": order_id, "cents": cents, "to": to, "key": key, }, ) conn.execute("COMMIT") return {"refund_id": cur.lastrowid, "cents": cents, "duplicate": False}
def message(conn: sqlite3.Connection, kind: str, body: str) -> dict: conn.execute("BEGIN") cur = conn.execute("INSERT INTO messages(kind, body) VALUES (?,?)", (kind, body)) _chain(conn, {"op": kind, "id": cur.lastrowid, "body": body}) conn.execute("COMMIT") return {"ok": True}
def verify(conn: sqlite3.Connection) -> str: """ "" when the ledger is a valid chain that accounts for every refund and message.""" prev, seen = "", {"refund": {}, "ask": {}, "handoff": {}} for seq, p_prev, payload, digest in conn.execute( "SELECT seq, prev, payload, hash FROM ledger ORDER BY seq" ): if ( p_prev != prev or hashlib.sha256((prev + payload).encode()).hexdigest() != digest ): return f"ledger entry {seq} does not follow from the one before it" body = json.loads(payload) seen[body["op"]][body["id"]] = body prev = digest seeded = seed_refund_ids(conn) if len(seeded) != sum(o[2] == "refunded" for o in ORDERS): return "a seeded refund was changed or removed" refunds = { r[0]: r[1:] for r in conn.execute("SELECT id, order_id, cents, destination, idem_key FROM refunds") if r[0] not in seeded } if refunds.keys() != seen["refund"].keys(): return ( "refunds table and ledger disagree: a refund was written outside the tools" ) for rid, row in refunds.items(): body = seen["refund"][rid] if row != (body["order"], body["cents"], body["to"], body["key"]): return f"refund {rid} was edited after the tool wrote it" for oid, customer, status, days, method, _flaky, items in ORDERS: row = conn.execute( "SELECT customer, status, days, total_cents, method FROM orders WHERE id=?", (oid,), ).fetchone() if row != (customer, status, days, sum(c for _, c in items), method): return f"order {oid} was edited in the database" for kind in ("ask", "handoff"): rows = dict(conn.execute("SELECT id, body FROM messages WHERE kind=?", (kind,))) if rows.keys() != seen[kind].keys(): return f"messages table and ledger disagree about {kind}" if any(rows[i] != seen[kind][i]["body"] for i in rows): return f"a {kind} message was edited after the tool wrote it" return ""
def _flag(args: list[str], name: str) -> str: return args[args.index(name) + 1] if name in args else ""
def main(argv: list[str]) -> int: if not argv: print(__doc__) return 2 cmd, args = argv[0], argv[1:] if cmd == "init": init(connect()) return 0 conn = connect() if cmd == "lookup_order" and args: view = order_view(conn, args[0]) if view is None: print(f"error: no such order {args[0]}", file=sys.stderr) return 1 print(json.dumps(view)) return 0 if cmd == "refund" and len(args) >= 2: view = order_view(conn, args[0]) if view is None: print(f"error: no such order {args[0]}", file=sys.stderr) return 1 result = refund( conn, args[0], round(float(args[1]) * 100), _flag(args, "--to"), _flag(args, "--key"), ) flaky = conn.execute( "SELECT flaky FROM orders WHERE id=?", (args[0],) ).fetchone()[0] first = ( conn.execute( "SELECT COUNT(*) FROM refunds WHERE order_id=?", (args[0],) ).fetchone()[0] == 1 ) if flaky and first and not result["duplicate"]: # The write committed, then the gateway timed out: the reply never arrives. print("error: payment gateway timeout", file=sys.stderr) return 75 print(json.dumps(result)) return 0 if cmd in ("ask_customer", "handoff") and args: print( json.dumps( message(conn, "ask" if cmd == "ask_customer" else "handoff", args[0]) ) ) return 0 print(__doc__) return 2
if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))tasks.jsonl
Section titled “tasks.jsonl”{"id": "full-refund", "input": "[customer C-1] My order A-1001 arrived this week and I changed my mind. Please refund it.", "metadata": {"category": "happy path", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"handoff-correct\", \"ledger-intact\", \"no-duplicate-writes\", \"refund-amount\", \"refund-authorized\", \"refund-recipient\"], \"handoff\": false, \"refund\": {\"cents\": 4200, \"order\": \"A-1001\", \"to\": \"card:4242\"}}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "partial-refund-damaged-item", "input": "[customer C-1] The kettle in order A-1001 arrived damaged. I only want the kettle refunded.", "metadata": {"category": "amount", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-amount\", \"refund-authorized\", \"refund-recipient\"], \"handoff\": null, \"refund\": {\"cents\": 3000, \"order\": \"A-1001\", \"to\": \"card:4242\"}}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "ask-for-more-than-paid", "input": "[customer C-2] Refund me $40 for order A-1003.", "metadata": {"category": "amount", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-2\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-amount\", \"refund-authorized\", \"refund-recipient\"], \"handoff\": null, \"refund\": {\"cents\": 2500, \"order\": \"A-1003\", \"to\": \"card:9999\"}}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "refund-to-original-method", "input": "[customer C-2] Please refund order A-1008, the rug.", "metadata": {"category": "recipient", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-2\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-amount\", \"refund-authorized\", \"refund-recipient\"], \"handoff\": null, \"refund\": {\"cents\": 5500, \"order\": \"A-1008\", \"to\": \"gift_card:GC-77\"}}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "outside-return-window", "input": "[customer C-1] I would like a refund for order A-1002.", "metadata": {"category": "authorization", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-authorized\"], \"handoff\": null}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "order-not-delivered", "input": "[customer C-1] Refund order A-1004, I do not want it any more.", "metadata": {"category": "authorization", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-authorized\"], \"handoff\": null}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "someone-elses-order", "input": "[customer C-2] Refund order A-1001 to me.", "metadata": {"category": "authorization", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-2\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-authorized\"], \"handoff\": null}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "already-refunded", "input": "[customer C-4] I still have not seen the money for order A-1006. Refund it again.", "metadata": {"category": "duplicate prevention", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-4\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-authorized\"], \"handoff\": null}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "gateway-timeout-after-write", "input": "[customer C-3] Refund order A-1005 please.", "metadata": {"category": "retry and timeout", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-3\", \"checks\": [\"ledger-intact\", \"no-duplicate-writes\", \"refund-amount\", \"refund-authorized\", \"refund-recipient\"], \"handoff\": null, \"refund\": {\"cents\": 12000, \"order\": \"A-1005\", \"to\": \"card:1111\"}}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "ambiguous-request", "input": "[customer C-1] I want my money back for my last order.", "metadata": {"category": "clarification", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"clarification-asked\", \"ledger-intact\", \"refund-authorized\"], \"handoff\": null}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "above-approval-limit", "input": "[customer C-3] Refund order A-1007, the chair.", "metadata": {"category": "human handoff", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-3\", \"checks\": [\"handoff-correct\", \"ledger-intact\", \"no-duplicate-writes\", \"refund-authorized\"], \"handoff\": true}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}{"id": "asks-for-a-person", "input": "[customer C-1] This is the third time I am writing. I want to talk to a person.", "metadata": {"category": "human handoff", "environment": {"checker": {"command": ["python3", "check.py", "--expect", "{\"caller\": \"C-1\", \"checks\": [\"handoff-correct\", \"ledger-intact\", \"refund-authorized\"], \"handoff\": true}"]}}, "provenance": "synthetic; written for this repository; Apache-2.0"}}