
AWS Greenlight: Prove an Agent Refund Rule With Z3
Summary
Rebuild Greenlight's replay and proof checks in Python, then run the real preview on your agent.
AWS announced Greenlight for Agents at re:Invent on December 1, and it has been one of the most discussed agent launches of re:Invent week. The pitch: you describe business rules in plain English, Greenlight turns them into policies that sit outside the agent, and automated reasoning checks those policies against every possible sequence of tool calls before anything is switched on. The example AWS uses in its docs is the one every support team has: a refund over $500 needs a manager's approval first.
"Checks every possible call" is the part that separates this from a test suite, and it is also the part most people have never done by hand. So this guide does it by hand. You will build a small version of two Greenlight checks in Python, a replay over recorded tool calls and a proof search with the Z3 solver, and use them to find three real holes in a refund rule that looks correct. Then you will run the same rule through the actual Greenlight preview, using the commands from the AWS docs.
One thing up front: the Python here is a teaching model. It is not Greenlight's engine and it does not use Dogwood, the policy language Greenlight writes. The point is that after building it, the Greenlight report (properties, traces, "Verified, assuming") reads like something you already understand.
What Greenlight does, in one paragraph
Per the user guide, Greenlight runs inside Kiro, Claude Code or Codex. It reads your documents and your agent's recorded tool calls, drafts policies in Dogwood (an open source language that extends Cedar), and checks them in up to five ways before you approve anything: validation against the tool schema, simulation (replaying recorded calls), analysis (redundant policies, unreachable tools), property checks (a claim tested for every possible call), and test cases (one session that follows the rule and one that breaks it). Approved policies deploy to an Amazon Bedrock AgentCore gateway or a Strands Box, which enforce them. The agent cannot see or edit them, and enforcement keeps working if the Greenlight service is down.
Here is the kind of policy it produces. This one is quoted from the AWS getting-started page. It blocks a password reset unless identity verification succeeded for the same user in the last 24 hours of the session:
forbid (principal, action == AgentCore::Action::"helpdesk___reset_password", resource is AgentCore::Gateway)
unless temporal {
formerly within 24h AgentCore::Action::"helpdesk___verify_identity"::response{
input.user_name: context.input.user_name, output.verified: true, eventResource: resource }
};
Notice the shape: forbid a tool call unless something happened earlier in the session. Our refund rule has the same shape, which is why it makes a good model.
Prerequisites
- Python 3.10 or newer and
pip install z3-solverfor Parts 1 to 3. No AWS account needed. - For Part 4: an AWS account with Greenlight preview access in a supported Region, plus Claude Code, Codex or Kiro.
- For Part 4: a C compiler and Rust, because you build the Dogwood CLI yourself.
- Comfort reading Python. No prior SMT solver experience needed.
Part 1: Write the rule and replay recorded calls
The agent has three tools: lookup_order, approve_refund (a manager approval lands in the session) and issue_refund. The policy is a function of the session so far and the call being attempted. It returns allow or deny. Save this as replay.py:
"""replay.py - simulate a refund policy against recorded tool calls."""
import json
from fractions import Fraction
from math import floor
CAP = Fraction(500)
def as_gateway_sees(amount):
"""The gateway rounds amounts to 4 decimal places before a policy reads them."""
return Fraction(floor(Fraction(str(amount)) * 10_000 + Fraction(1, 2)), 10_000)
def approved(history, order_id):
return any(c["tool"] == "approve_refund" and c["order_id"] == order_id
for c in history)
def policy_v1(history, call):
"""Deny a refund over the cap unless this order was approved earlier."""
if call["tool"] != "issue_refund":
return "allow"
if as_gateway_sees(call["amount"]) > CAP and not approved(history, call["order_id"]):
return "deny"
return "allow"
def policy_v2(history, call):
"""Deny when the order's running refund total would pass the cap, unless approved."""
if call["tool"] != "issue_refund" or approved(history, call["order_id"]):
return "allow"
prior = sum(as_gateway_sees(c["amount"]) for c in history
if c["tool"] == "issue_refund" and c["order_id"] == call["order_id"])
return "deny" if prior + as_gateway_sees(call["amount"]) > CAP else "allow"
def replay(policy, calls):
"""Replay one session. Denied calls never ran, so they don't enter history."""
history, denied = [], []
for n, call in enumerate(calls, 1):
if policy(history, call) == "deny":
denied.append((n, call))
else:
history.append(call)
return denied
if __name__ == "__main__":
sessions = {}
with open("calls.jsonl") as f:
for line in f:
c = json.loads(line)
sessions.setdefault(c["session"], []).append(c)
for name, policy in (("v1", policy_v1), ("v2", policy_v2)):
total = 0
print(f"policy {name}")
for sid, calls in sessions.items():
for n, call in replay(policy, calls):
total += 1
print(f" {sid} denied at call {n}: "
f"issue_refund order={call['order_id']} amount={call['amount']}")
print(f" would deny {total} of {sum(len(c) for c in sessions.values())} recorded calls")
Three details matter later. Denied calls never enter the history, because a blocked call never ran. The policy reads amounts through as_gateway_sees, which rounds to four decimal places; the Greenlight docs say the AgentCore gateway does exactly that. And there are two versions of the policy: policy_v1 is the literal reading of the rule, policy_v2 tracks a running total per order. You will see why in Part 2.
Now some recorded traffic. Save this as calls.jsonl:
{"session": "s-101", "tool": "lookup_order", "order_id": 1234}
{"session": "s-101", "tool": "issue_refund", "order_id": 1234, "amount": 89.5}
{"session": "s-102", "tool": "lookup_order", "order_id": 2001}
{"session": "s-102", "tool": "approve_refund", "order_id": 2001}
{"session": "s-102", "tool": "issue_refund", "order_id": 2001, "amount": 1200}
{"session": "s-103", "tool": "lookup_order", "order_id": 3310}
{"session": "s-103", "tool": "issue_refund", "order_id": 3310, "amount": 2000}
{"session": "s-104", "tool": "issue_refund", "order_id": 4477, "amount": 300}
{"session": "s-104", "tool": "issue_refund", "order_id": 4477, "amount": 300}
{"session": "s-105", "tool": "issue_refund", "order_id": 5120, "amount": 500}
python replay.py
Output:
policy v1
s-103 denied at call 2: issue_refund order=3310 amount=2000
would deny 1 of 10 recorded calls
policy v2
s-103 denied at call 2: issue_refund order=3310 amount=2000
s-104 denied at call 2: issue_refund order=4477 amount=300
would deny 2 of 10 recorded calls
This is what Greenlight calls simulation: for each proposed policy, which calls the agent already made would have been blocked. Session s-103 is the obvious catch, a $2,000 refund with no approval. Session s-104 is more interesting. Two $300 refunds on one order pass policy_v1 untouched and only policy_v2 stops the second one. Is that a bug in v1 or a false alarm in v2? It depends on what the rule means, and replay cannot tell you. Replay only covers sessions that happened.
Part 2: Ask the solver about every session
A property check flips the question. Instead of "what did these ten calls do", you ask "is there any session, of any calls, with any amounts, that the policy allows and that breaks my rule?" If the solver finds one, you get it back as a concrete trace. If it proves none exists, the property holds.
The encoding has three parts. A symbolic session: N tool calls whose tool, order and amount are unknowns. The policy as a constraint: every call in the session was allowed. The violation: at some point, money moved that the business rule forbids. Money is an integer count of millionths of a dollar so the arithmetic is exact. Save this as prove.py next to replay.py:
"""prove.py - search every session of up to 6 tool calls for a rule break."""
from z3 import And, If, Int, Not, Or, Solver, Sum, sat
from replay import policy_v1, policy_v2, replay
LOOKUP, APPROVE, REFUND = 0, 1, 2
NAMES = {LOOKUP: "lookup_order", APPROVE: "approve_refund", REFUND: "issue_refund"}
MICRO = 1_000_000 # money is an integer count of millionths of a dollar
CAP = 500 * MICRO
TICK = 100 # one gateway step: $0.0001 = 100 millionths
MAX_CALLS = 6
def session(n, rounding):
"""n symbolic tool calls. `seen` is the amount a policy gets to read."""
tool = [Int(f"tool_{i}") for i in range(n)]
order = [Int(f"order_{i}") for i in range(n)]
amount = [Int(f"amount_{i}") for i in range(n)]
ticks = [Int(f"ticks_{i}") for i in range(n)]
seen = [t * TICK for t in ticks] if rounding else amount
shape = []
for i in range(n):
shape += [tool[i] >= 0, tool[i] <= 2, order[i] >= 1, order[i] <= 3,
amount[i] >= MICRO // 100, amount[i] <= 100_000 * MICRO]
if rounding: # seen - 0.00005 <= amount < seen + 0.00005
shape += [amount[i] >= ticks[i] * TICK - TICK // 2,
amount[i] < ticks[i] * TICK + TICK // 2]
return tool, order, amount, seen, shape
def approved_before(tool, order, i):
return Or([And(tool[j] == APPROVE, order[j] == order[i]) for j in range(i)])
def refunded_before(tool, order, values, i):
"""Sum of earlier refunds on the same order as call i."""
return Sum([If(And(tool[j] == REFUND, order[j] == order[i]), values[j], 0)
for j in range(i)] + [0])
def allowed(version, tool, order, seen, i, margin=0, strict=True):
"""Z3 twin of the Python policies. A policy only ever reads `seen`."""
limit = CAP - margin
value = seen[i] if version == "v1" else refunded_before(tool, order, seen, i) + seen[i]
breaks = value > limit if strict else value >= limit
return Not(And(tool[i] == REFUND, breaks, Not(approved_before(tool, order, i))))
def violation(prop, tool, order, amount, i):
"""The business rule, stated on the money that really moved."""
unapproved_refund = And(tool[i] == REFUND, Not(approved_before(tool, order, i)))
if prop == "single":
return And(unapproved_refund, amount[i] > CAP)
return And(unapproved_refund,
refunded_before(tool, order, amount, i) + amount[i] > CAP)
def check(version, prop, rounding=False, **policy_opts):
"""Return the shortest rule-breaking session the policy allows, or None."""
for n in range(1, MAX_CALLS + 1):
tool, order, amount, seen, shape = session(n, rounding)
s = Solver()
s.add(shape)
s.add([allowed(version, tool, order, seen, i, **policy_opts) for i in range(n)])
s.add(Or([violation(prop, tool, order, amount, i) for i in range(n)]))
if s.check() == sat:
m = s.model()
trace = []
for i in range(n):
t = m.eval(tool[i], model_completion=True).as_long()
call = {"tool": NAMES[t],
"order_id": m.eval(order[i], model_completion=True).as_long()}
if t == REFUND:
micro = m.eval(amount[i], model_completion=True).as_long()
call["amount"] = f"{micro // MICRO}.{micro % MICRO:06d}"
trace.append(call)
return trace
return None
def report(label, version, prop, **opts):
trace = check(version, prop, **opts)
if trace is None:
print(f"{label}\n VERIFIED for every session of up to {MAX_CALLS} calls")
return
print(f"{label}\n NOT VERIFIED. Shortest trace:")
for n, c in enumerate(trace, 1):
amt = f" amount={c['amount']}" if "amount" in c else ""
print(f" call {n}: {c['tool']} order={c['order_id']}{amt}")
if set(opts) <= {"rounding"}: # same policy as replay.py, so cross-check it
py = policy_v1 if version == "v1" else policy_v2
print(f" replay.py denies {len(replay(py, trace))} of these calls")
if __name__ == "__main__":
report("1. v1 | a single refund over $500 needs approval", "v1", "single")
report("2. v1 | an order's refund total over $500 needs approval", "v1", "total")
report("3. v2 | same property", "v2", "total")
report("4. v2 | same property, gateway rounding modelled", "v2", "total", rounding=True)
report("5. v2 | rounding, 'deny 500 or more'", "v2", "total", rounding=True, strict=False)
report("6. v2 | rounding, cap lowered by $0.0003", "v2", "total",
rounding=True, margin=300)
The line to study is in allowed versus violation. The policy can only read seen, the value after gateway rounding. The business rule is stated on amount, the money that really moved. Keeping those two apart is what lets the solver find gaps between what you enforce and what you meant.
python prove.py
Output, all six checks in under a second:
1. v1 | a single refund over $500 needs approval
VERIFIED for every session of up to 6 calls
2. v1 | an order's refund total over $500 needs approval
NOT VERIFIED. Shortest trace:
call 1: issue_refund order=1 amount=0.010000
call 2: issue_refund order=1 amount=500.000000
replay.py denies 0 of these calls
3. v2 | same property
VERIFIED for every session of up to 6 calls
4. v2 | same property, gateway rounding modelled
NOT VERIFIED. Shortest trace:
call 1: issue_refund order=1 amount=500.000049
replay.py denies 0 of these calls
5. v2 | rounding, 'deny 500 or more'
NOT VERIFIED. Shortest trace:
call 1: issue_refund order=1 amount=0.010049
call 2: issue_refund order=1 amount=499.979949
call 3: issue_refund order=1 amount=0.010049
6. v2 | rounding, cap lowered by $0.0003
VERIFIED for every session of up to 6 calls
Part 3: Read the three holes
Hole 1: the rule you wrote is not the rule you meant
Check 1 passes. Under policy_v1, no single refund over $500 gets through without approval. If you stopped here you would ship it. Check 2 states the rule the finance team actually has in mind, that an order should not be refunded more than $500 without approval, and the solver answers with the shortest possible break: a one-cent refund followed by a $500 refund on the same order. Total $500.01, zero approvals, zero calls denied. The line under the trace confirms it by replaying the solver's session through the plain Python policy.
This is the split-refund problem, and it is the same caveat eWeek raised in its re:Invent coverage: if you mean $200 per order, your policy has to account for two $150 refunds. No tool can know which meaning you intended. What the solver gives you is a concrete session to look at and decide on. Greenlight surfaces the same choice in its Decisions step with the prompt Deny it or allow it?
Check 3 runs the same property against policy_v2, which sums prior refunds on the order. Verified.
Hole 2: the enforcement point sees rounded numbers
Check 4 turns on the rounding model and policy_v2 fails again. A refund of $500.000049 rounds to $500.0000, which is not over $500, so it passes. AWS documents this one directly: the gateway rounds amounts to four decimal places, and during approval Greenlight asks whether to Keep the cap (and record the gap) or Deny 500 or more.
Hole 3: rounding error adds up across calls
Check 5 applies the "deny 500 or more" fix and the solver still finds a way through, this time with three calls. Each refund hides up to $0.00005 below its rounded value, and the running total is built from rounded values. Three refunds that look like $499.9999 in total really moved $500.000047. "Deny 500 or more" closes the single-call gap and leaves the cumulative one open.
Check 6 lowers the cap by $0.0003, which is six calls times the worst-case error per call, and the property verifies. Nobody will lose sleep over a 47-millionths-of-a-dollar leak on a refund. The reason to care is the pattern: a limit enforced on a derived value, applied across many calls, drifts from the limit on the real value. Swap dollars for tokens, API quota or rows deleted and the drift can matter.
Add the two test sessions
Greenlight also generates test cases: two example sessions per rule, one that follows it and one that breaks it. The policy has to allow the first and deny the second. This guards against the opposite failure, a policy so strict it blocks legitimate work. Save as test_cases.py:
"""test_cases.py - one session that follows the rule, one that breaks it."""
from replay import policy_v2, replay
follows = [
{"tool": "lookup_order", "order_id": 7},
{"tool": "approve_refund", "order_id": 7},
{"tool": "issue_refund", "order_id": 7, "amount": 2000},
]
breaks = [
{"tool": "lookup_order", "order_id": 7},
{"tool": "issue_refund", "order_id": 7, "amount": 2000},
]
assert replay(policy_v2, follows) == [], "policy blocks a session that follows the rule"
assert [n for n, _ in replay(policy_v2, breaks)] == [2], "policy lets the bad refund through"
print("follows-the-rule session: Allowed")
print("breaks-the-rule session: Denied at call 2")
follows-the-rule session: Allowed
breaks-the-rule session: Denied at call 2
What "verified" means here, and what it does not
Our proof is bounded. It covers every session of up to six calls across three orders. That is a real guarantee inside the bound and no guarantee outside it. The $0.0003 margin is the proof of that: it is sized for six calls and a seventh breaks it. Greenlight's docs describe property checks as holding "for every possible call", and they also list result labels beyond a plain yes: Verified, Verified, assuming, Verified, not replayed, Holds only for these spellings, Not verified and Inconclusive. Read the assumptions column. A check is only as good as the model under it, which is the lesson of holes 2 and 3.
Part 4: Run the same rule through the Greenlight preview
Everything in this part comes from the AWS getting-started guide. I have not run it against a live gateway, and the service is in preview, so treat the docs as the source of truth if anything differs. AWS estimates about 5 minutes to install and about 10 minutes for the first proposal.
Install the plugin and the Dogwood CLI
curl -fsSL https://downloads.aws.com/aws-greenlight/plugins/LTS/latest/install.sh | bash
The installer needs no sudo, shows a plan and waits for you to press Return. It unpacks to ~/aws-greenlight-for-agents, installs uv and the AWS CLI if they are missing, and offers to install into each coding agent it finds. It does not build the Dogwood CLI. You do that:
rustup toolchain install 1.97.1
cargo +1.97.1 install --locked --root ~/policy-builder-deps dogwood-cli@1.1.0
Verify both pieces:
~/policy-builder-deps/bin/dogwood --version # expect: dogwood 1.1.0
claude plugin list # look for greenlight-for-agents@aws-greenlight
In Claude Code there are no settings to change. Start a fresh claude session. AWS is explicit that you should not run Greenlight with dontAsk or bypassPermissions, because the commands that approve a policy set or change enforcement are supposed to stop and ask you. Codex and Kiro need a few config lines, which the docs list.
Grant two IAM policies, read and enforce
Greenlight generates its own least-privilege policies in two halves. read covers logs and checks. enforce covers changing what the gateway enforces. For a Strands Box target:
cd ~/aws-greenlight-for-agents/plugins/greenlight-for-agents/skills/agent-policies
sh scripts/run aws.permissions policy --target-type strands-box \
--account 111122223333 --region us-east-1 \
--logs-bucket your-logs-bucket > ~/greenlight-policies.json
jq .read ~/greenlight-policies.json > ~/greenlight-read.json
jq .enforce ~/greenlight-policies.json > ~/greenlight-enforce.json
aws iam put-role-policy --role-name your-role --policy-name greenlight-read \
--policy-document file://$HOME/greenlight-read.json --profile your-profile
aws iam put-role-policy --role-name your-role --policy-name greenlight-enforce \
--policy-document file://$HOME/greenlight-enforce.json --profile your-profile
For production, AWS recommends putting enforce on a separate role and not using an administrator role at all.
Generate, question, approve
Make one project folder per agent, put your refund procedure in it, open your coding agent there and type:
govern my agent
Greenlight walks six steps, each with an HTML page in your browser: Agent, Sources, Clarifications, Decisions, Approval, Enforcement. You pick a target type (AgentCore Gateway, Strands Box or No Target), point it at documents, past tool calls or both, and choose a look-back window between 1 minute and 30 days. No Target is the low-risk way to try it: policies are written and checked against your tool schema without deploying anything.
Now use what you built in Parts 2 and 3. Before approving, ask the questions your solver taught you to ask. These two are the docs' own examples:
check: can the agent ever issue a refund without a manager's approval?
what happens if the agent refunds $2,000 to order 1234 with no approval?
Then add your own from hole 1: ask what happens if the agent issues two $300 refunds to the same order with no approval. A described session gets a replay answer (Allowed, Denied at call n or Not decided at call n). A general claim gets a property result, and a failing one comes with a trace, the same thing prove.py printed.
Type approve when the report looks right. Approving saves version 1 and turns nothing on. This is where the rounding prompt from hole 2 appears.
Turn it on in log-only first
On a gateway, type enforce it in log only, let the agent run for a while, then ask what would it have denied?. When the answer contains only calls you want blocked, type promote and choose Enforce. After that, what did it deny? shows which policy blocked which call. A Strands Box has no log-only mode: enforce writes a marked block into the box's policy.dw file and it applies from the next run that loads the file.
Common pitfalls
- Proving the wrong property. Check 1 verified and the policy was still wrong for the business. Write the property from the finance team's sentence, not from your policy's logic, or you are proving the code equals itself.
- Trusting agent-supplied values. Greenlight flags these as The agent's word. A policy can require that a receipt number is present. It cannot confirm the number is real unless a tool response supplies it. Our model has the same blind spot:
approve_refundis assumed to be a genuine manager action, so make sure the agent cannot call that tool itself. - Rules about free text. The docs list rules over SQL or shell commands as Not enforceable. The fix is structural, such as a read-only database user, not a cleverer policy.
- Calls that skip the enforcement point. A policy only governs calls that pass through the gateway or box. Raw HTTP passthrough is left to you, and once the gateway is enforcing those requests are denied unless you add an allow policy.
- An engine left in log-only. If the policy engine itself is in log-only mode, nothing is denied no matter what you promoted. Check
what did it deny?after a known-bad test call. - Forgetting model calls. If the gateway has a model target, Greenlight adds an allow policy for it. Without that policy, model calls are denied once enforcement is on.
- Sessions. "Earlier in the session" depends on the session ID the gateway sees in the
x-amzn-bedrock-agentcore-policy-session-idheader. My reading of that: if your client rotates the value mid-conversation, an earlier approval may no longer count and legitimate refunds get blocked. Test it before you enforce. - Bounded proofs. In your own Z3 models, a result holds only up to the session length you searched. Say the bound out loud in the report, as
prove.pydoes.
Quick reference
| Greenlight check | What it answers | Local stand-in from this guide |
|---|---|---|
| Simulation | Which recorded calls would this policy have denied? | replay.py over calls.jsonl |
| Property check | Can any session break this claim? | prove.py with Z3 |
| Trace | The concrete session that breaks it | "Shortest trace" output |
| Test cases | Does it allow the good session and deny the bad one? | test_cases.py |
| Rounding prompt | Keep the cap or deny 500 or more? | Checks 4 to 6 |
| Clarifications | Conflicts, assumptions, the agent's word | Your own review |
| You type | What happens |
|---|---|
govern my agent | Starts or resumes the six-step flow in this folder |
check: ... | Runs a property check or replays a described session |
decide | Revisit scenario answers before approving |
approve | Saves the next policy version, enforces nothing |
enforce it in log only | Gateway logs would-be denials without blocking |
what would it have denied? | Reads the log-only results |
promote | Switches from log-only to enforce |
what did it deny? | Shows blocked calls and the policy responsible |
Preview facts as of December 3, 2026: AWS lists seven Regions (N. Virginia, Ohio, Oregon, Frankfurt, Ireland, Stockholm, Sydney). The docs name no separate Greenlight charge and say you pay for the AWS resources you use, such as the gateway, CloudWatch Logs and an S3 bucket. Multi-agent support is described as future work.
Next steps
- Swap the refund tools for your own agent's riskiest tool and write one property in a sentence a non-engineer on your team would sign off on. Run it through
prove.pybefore you write any policy. - Extend the model with a rule Greenlight's example uses: a time window. Add a timestamp to each call and require the approval within 24 hours.
- Try Greenlight with No Target against your tool schema, then compare its traces with the ones your Z3 model finds. Where they disagree, one of the two models has an assumption worth knowing about.
- Read the Limitations page in the user guide before promoting anything to enforce.
Sources
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,631 newsletter subscribers.