Sub topic 9
Policy rules and safe auto-approval
This chapter assumes you can read short Python programs, know how an agent calls tools, and have seen the risk table and approval gate from the earlier chapters. Here you will replace "ask a human for everything that isn't low risk" with a small policy layer. The layer decides which calls run automatically, which need a human, and which are never allowed.
Why a lookup table is not enough
The risk table from the previous chapters maps a tool name to a level. That works for a first version, but it treats every call to send_email the same. In practice, risk depends on the arguments and the context:
- Sending an email to a colleague at your own company is different from sending one to an unknown external address.
- Deleting a draft record is different from deleting a customer account.
- Refunding 5 dollars is different from refunding 5,000.
If the table says "high" for all of these, reviewers see many harmless requests. They start approving without reading, which is the failure mode covered in the next chapter. If the table says "low" for all of them, the dangerous cases run unchecked.
A policy is a set of rules that looks at the whole tool call and returns a decision. The decision has three possible outcomes:
| Outcome | Meaning | What the gate does |
|---|---|---|
| `allow` | Safe under the rules | Runs the call without a human |
| `ask` | Needs a person | Pauses and creates an approval request |
| `deny` | Never permitted | Rejects the call and tells the agent why |
The deny outcome matters. Some actions should not be one click away from approval, such as deleting a production database. Blocking them outright removes the chance that a tired reviewer approves them.
Where the policy sits
The policy runs after the model proposes a tool call and before anything executes. It replaces the single risk_of check in the gate.
Note that every path, including automatic ones, ends in an audit record. An auto-approved action still needs a trace of which rule allowed it.
Writing rules
Each rule has a name, a test that looks at the call, and an outcome. Rules are evaluated in order, and the first match wins. A final default rule catches everything else.
from dataclasses import dataclass
from typing import Callable
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
@dataclass(frozen=True)
class Rule:
name: str
matches: Callable[[ToolCall], bool]
outcome: str # "allow", "ask", or "deny"
COMPANY_DOMAIN = "@example.com"
RULES = [
Rule(
"never-drop-tables",
lambda c: c.name == "run_sql" and "drop table" in c.args.get("query", "").lower(),
"deny",
),
Rule(
"read-only-search",
lambda c: c.name == "search_docs",
"allow",
),
Rule(
"internal-email",
lambda c: c.name == "send_email"
and all(r.endswith(COMPANY_DOMAIN) for r in c.args.get("to", [])),
"allow",
),
Rule(
"small-refund",
lambda c: c.name == "issue_refund" and c.args.get("amount", 0) <= 20,
"allow",
),
Rule(
"any-refund",
lambda c: c.name == "issue_refund",
"ask",
),
]
def evaluate(call: ToolCall) -> tuple[str, str]:
for rule in RULES:
if rule.matches(call):
return rule.outcome, rule.name
return "ask", "default-ask"evaluate returns both the outcome and the name of the rule that matched. You will store that name in the audit record so you can later answer "why did this run without approval?"
The order matters. small-refund comes before any-refund, so refunds of 20 or less are allowed and larger ones fall through to ask. The deny rule comes first so nothing can allow a call it forbids.
Fail closed
The last line returns ask for anything no rule recognizes. This is the same idea as the earlier "unknown tools are high risk" default. A new tool added by a developer needs a human until someone writes a rule for it. If you default to allow, a forgotten rule silently becomes permission.
If a rule raises an exception, treat that as ask too. A policy bug should slow the system down, not open it up.
def safe_evaluate(call: ToolCall) -> tuple[str, str]:
try:
return evaluate(call)
except Exception:
return "ask", "policy-error"Common mistakes in rules
Rules that look at arguments are easy to get wrong. These are the errors that show up most often.
- Substring checks on untrusted text. The
drop tablecheck above catchesDROP TABLE usersbut notDROP/**/TABLE usersor a query built from pieces. Treat string matching as a safety net, not as a guarantee. For SQL, the stronger control is a database account that cannot drop tables at all. - Prefix and suffix tests on addresses.
endswith("@example.com")is correct, but"example.com" in addresswould also match[email protected]. Test the exact domain. - Missing arguments. In
small-refund,c.args.get("amount", 0)returns 0 when the amount is missing, so a malformed call counts as a small refund. Safer code treats a missing or non-numeric amount as not matching. - Wrong types. If the model passes
"amount": "5"as a string,"5" <= 20raises aTypeError. That is why thesafe_evaluatewrapper exists, but better rules check the type first. - Rules that depend on model-written justification. Do not write a rule such as "allow if the agent says this is safe". The model's own text is the thing you are guarding against.
Here is small-refund with those fixes:
def is_small_refund(c: ToolCall) -> bool:
if c.name != "issue_refund":
return False
amount = c.args.get("amount")
return isinstance(amount, (int, float)) and not isinstance(amount, bool) and 0 < amount <= 20The bool check is needed because True is an instance of int in Python and would otherwise pass as an amount of 1.
Adding context and budgets
Some rules depend on state outside the call. A refund of 20 dollars is fine once but not 500 times in a row. A common pattern is a budget that the policy tracks per run or per day.
from collections import defaultdict
class RefundBudget:
def __init__(self, limit: float):
self.limit = limit
self.spent = defaultdict(float) # run_id -> total auto-approved
def allows(self, run_id: str, amount: float) -> bool:
return self.spent[run_id] + amount <= self.limit
def record(self, run_id: str, amount: float) -> None:
self.spent[run_id] += amount
budget = RefundBudget(limit=50)
def evaluate_with_budget(call: ToolCall, run_id: str) -> tuple[str, str]:
if is_small_refund(call):
amount = call.args["amount"]
if budget.allows(run_id, amount):
budget.record(run_id, amount)
return "allow", "small-refund-within-budget"
return "ask", "small-refund-budget-exceeded"
return safe_evaluate(call)This version has a flaw worth knowing about. It records the spend when the policy decides, not when the refund succeeds. If the tool then fails, the budget is still reduced. That error is on the safe side, but it can block legitimate work. A production version records the spend in the same transaction as the action, and keeps the counter in a database so that two workers cannot both read the same remaining budget.
Other context that rules commonly use:
- Who the user is. An administrator's session may allow more than a guest's.
- Environment. Calls against a staging system can be allowed where the same call against production asks.
- Rate. More than N calls to the same tool in a minute switches the outcome to
ask. - Reversibility. Actions you can undo, such as creating a draft, are better candidates for
allowthan actions you cannot, such as sending a message.
Rules the model cannot change
Policy must live in code or configuration that the agent cannot edit. If the agent has a tool that writes to the rules file, or if rules are described in the prompt only, the policy is advisory. A prompt injection in a document the agent reads could then convince it to widen its own permissions.
Keep these boundaries:
- Rules are loaded from version-controlled configuration, not from model output.
- The tool list given to the agent contains no tool that edits rules or budgets.
- Changes to rules go through code review, like any other change to security behavior.
Reviewing auto-approvals
Auto-approval is a bet that the rules are right. You check the bet by looking at what the rules allowed. Log every decision with its rule name, then sample from the allow records on a schedule. Look for calls you would have wanted to review. Each one points to a rule that is too wide.
A useful way to introduce a new allow rule is shadow mode. For a trial period the rule returns ask to the user but also logs what it would have returned. If reviewers approve every shadowed call without edits or rejections, the rule is a candidate for promotion to allow. If they reject or edit some, the rule needs tightening first.
import logging
log = logging.getLogger("policy")
def evaluate_shadow(call: ToolCall, shadow_rules: list[Rule]) -> tuple[str, str]:
outcome, rule_name = safe_evaluate(call)
for rule in shadow_rules:
if rule.matches(call):
log.info("shadow match rule=%s would=%s actual=%s", rule.name, rule.outcome, outcome)
break
return outcome, rule_namePutting it into the gate
The gate from the earlier chapter changes in one place. It calls the policy instead of risk_of and handles the three outcomes.
def run_step(call, tools, ask_human, run_id):
outcome, rule_name = evaluate_with_budget(call, run_id)
if outcome == "deny":
return {"rejected": True, "reason": f"Blocked by policy rule {rule_name}"}
if outcome == "allow":
return tools[call.name](**call.args)
decision = ask_human(call)
action = decision["action"]
if action == "approve":
return tools[call.name](**call.args)
if action == "edit":
edited = ToolCall(call.name, decision["args"])
# The edited call must pass policy too; a human edit can still hit a deny rule.
if evaluate_with_budget(edited, run_id)[0] == "deny":
return {"rejected": True, "reason": "Edited call blocked by policy"}
return tools[edited.name](**edited.args)
return {"rejected": True, "reason": decision.get("reason", "")}Two details deserve attention. First, the deny reason goes back to the agent, so it can choose a different approach instead of retrying the same call. Second, edited calls are checked again, so an edit cannot be used to route around a deny rule.
Exercise
A rule allows send_email when "example.com" in address for every recipient. Name the flaw, give an address that exploits it, and write the safer test.
Show answer
The substring test also matches addresses on other domains that contain the text. For example, [email protected] contains "example.com" and would be auto-approved, so an email could go to an outside party. The safer test compares the exact domain: address.lower().endswith("@example.com"). A stricter version parses the address and compares the domain part for equality.
Exercise
Your small-refund rule allows refunds up to 20 dollars. Over one run, the agent issues 100 refunds of 20 dollars each. Which mechanism would stop this, and where should its counter be stored if you run several workers?
Show answer
A budget (or rate limit) per run or per day that switches the outcome to ask once the total passes a limit. With several workers the counter must live in shared storage such as a database, updated in the same transaction as the action. An in-memory counter in each worker would let every worker spend the full limit.
Exercise
Why does the gate evaluate the policy again on an edited call, and what outcome would you expect if a reviewer edits a SQL query so that it contains DROP TABLE?
Show answer
A human edit changes the action, so the original policy result no longer applies. Re-evaluating makes sure the edited call still satisfies every rule. A query containing DROP TABLE matches the never-drop-tables deny rule, so the gate returns a rejection with the reason "Edited call blocked by policy".