Writing policies¶
Who this page is for: someone who has run the getting started page and now wants to write a real policy. After reading it you will be able to build a multi-agent policy rule by rule, and you will know why each rule is there. Every output below came from running the policy shown.
We build four policies, each a small step from the last:
- one rule,
- a safe default and a secrets rule,
- conditions and approvals,
- a team of agents with delegation and budgets.
Step 1: one rule¶
A policy needs version: 1. Each rule needs an id and an effect. This rule lets any role call fs.read.
A call that no rule matches is denied, because defaults.effect is deny unless you say otherwise. That is the right default: you list what is allowed, and everything else stays closed.
But look at what the rule allows:
The rule is named read-workspace but it allows reading any file. A rule is only as narrow as its conditions.
Step 2: narrow the rule, add a deny¶
version: 1
defaults:
effect: deny
rules:
- id: read-workspace
tools: ["fs.read", "fs.list"]
when:
args.path: { glob: "/workspace/**" }
effect: allow
- id: no-secrets
tools: ["*"]
when:
any:
- args.path: { glob: "**/.env*" }
- args.path: { glob: "**/*.pem" }
effect: deny
reason: Secret files are off limits
Two things changed:
read-workspacenow has awhencondition.args.pathis thepathargument of the call, andglob: "/workspace/**"means "anything under/workspace". The condition is data, not code: nothing in a policy is ever evaluated as Python.no-secretsapplies totools: ["*"], every tool.any:means "at least one of these". It denies.envfiles and.pemkeys wherever they are.
castellan check step2.yaml --role anyone --tool fs.read --args '{"path":"/workspace/notes.txt"}' # ALLOW
castellan check step2.yaml --role anyone --tool fs.read --args '{"path":"/etc/passwd"}' # DENY (default)
castellan check step2.yaml --role anyone --tool fs.read --args '{"path":"/workspace/.env"}'
ALLOW rule=read-workspace source=policy reason=rule 'read-workspace' matched
DENY rule=- source=default reason=no rule matched; default is deny
DENY rule=no-secrets source=policy reason=Secret files are off limits
The last call matches both rules: /workspace/.env is inside the workspace, and it is a secret. explain shows how Castellan settled it:
DENY rule=no-secrets source=policy reason=Secret files are off limits
Rule trace
┏━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
┃ Rule ┃ Matched ┃ Detail ┃
┡━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
│ read-workspace │ yes │ matched │
│ no-secrets │ yes │ matched │
└────────────────┴─────────┴─────────┘
Deny always beats allow, whatever the order of the rules or their priority. That is why a deny rule is a safe place to put "never, whoever asks".
Step 3: conditions and approvals¶
version: 1
defaults:
effect: deny
rules:
- id: read-workspace
tools: ["fs.read", "fs.list"]
when:
args.path: { glob: "/workspace/**" }
effect: allow
- id: no-secrets
tools: ["*"]
when:
any:
- args.path: { glob: "**/.env*" }
- args.path: { glob: "**/*.pem" }
effect: deny
reason: Secret files are off limits
- id: small-payments
tools: ["payments.*"]
when:
all:
- args.amount: { lte: 100 }
- args.currency: { in: [USD, EUR] }
effect: ask
approver: human
reason: Payments always need a human
The new rule, small-payments, shows three more ideas:
tools: ["payments.*"]matchespayments.send,payments.refundand so on. In tool names*stops at a dot;**does not.all:requires every condition. Here the amount must be at most 100 and the currency must be USD or EUR.effect: askdoes not allow the call; it asksapprover: humanfirst.reasonis the message the caller sees.
castellan check step3.yaml --role anyone --tool payments.send --args '{"amount":50,"currency":"EUR"}' # exit 2
castellan check step3.yaml --role anyone --tool payments.send --args '{"amount":500,"currency":"EUR"}' # exit 1
castellan check step3.yaml --role anyone --tool payments.send --args '{"currency":"EUR"}' # exit 1
ASK rule=small-payments source=policy reason=Payments always need a human
DENY rule=- source=default reason=no rule matched; default is deny
DENY rule=- source=default reason=no rule matched; default is deny
Two surprises, both deliberate:
- A 500 payment is denied, not asked. The rule only matches small payments; larger ones match nothing and fall to the default. Writing "ask for small, deny for large" is a statement about what does not match.
- A payment with no
amountis denied. A condition on a path that is missing is false (the one exception isexists: false), so a call cannot skip a check by leaving out the argument.
Step 4: a team¶
Real systems have several agents. Castellan models each one by its role and lets one agent delegate to another. This is the full team policy:
version: 1
defaults:
effect: deny
agents:
planner:
can_delegate_to: [researcher, coder, reviewer]
max_delegation_depth: 2
researcher: {}
coder: {}
reviewer: {}
rules:
- id: no-secrets
description: Never touch secret files, whoever asks
tools: ["*"]
when:
any:
- args.path: { glob: "**/.env*" }
- args.path: { glob: "**/*.pem" }
effect: deny
reason: Secret files are off limits
- id: read-workspace
agents: [researcher, coder, reviewer]
tools: ["fs.read", "fs.list"]
when:
args.path: { glob: "/workspace/**" }
effect: allow
- id: write-needs-review
agents: [coder]
tools: ["fs.write", "fs.delete"]
when:
args.path: { glob: "/workspace/**" }
effect: ask
approver: role:reviewer
reason: A reviewer must approve every write
- id: shallow-web
agents: [researcher]
tools: ["web.search", "web.fetch"]
when:
agent.depth: { lte: 2 }
effect: allow
- id: small-payments-only
tools: ["payments.*"]
when:
all:
- args.amount: { lte: 100 }
- args.currency: { in: [USD, EUR] }
effect: ask
approver: human
budgets:
run:
max_tool_calls: 200
per_role:
researcher: { max_tool_calls: 80 }
coder: { max_tool_calls: 60 }
approvals:
ttl_seconds: 600
audit:
path: ./castellan-audit.jsonl
Why each part is there:
agents
: Declares the roles and who may delegate to whom. planner can create researcher, coder and reviewer agents, and max_delegation_depth: 2 stops delegation chains from growing deeper than two levels. The others delegate to nobody. Every role named in a rule should be declared here, and the linter checks that.
no-secrets
: The same "never" rule as in step 2, now guarding the whole team.
read-workspace
: agents: [researcher, coder, reviewer] limits the rule to those roles. The planner has no tool rule at all: it plans and delegates, but cannot touch files itself.
write-needs-review
: Coder writes pause for an approver. approver: role:reviewer says any reviewer agent in the same run may approve. An agent can never approve its own request.
shallow-web
: Researchers may search the web only while agent.depth is at most 2. A researcher spawned too deep gets nothing. Conditions can read the caller (agent.*), the tool (tool.*), the arguments (args.*), the run (run.*) and the clock (time.*).
budgets
: run caps all tool calls in a run, whatever the agent; per_role adds limits per role. See budgets.
Now run it. This script starts a run as the planner, delegates two sub-agents with narrow grants, and makes calls:
import secrets
from agent_castellan import Guard, PermissionDenied, ToolCall
guard = Guard.from_file("team.yaml", key=secrets.token_bytes(32))
planner = guard.start_run("planner", on_behalf_of="alice")
researcher, _ = guard.delegate(planner, "researcher", tools=["web.*"], ttl_seconds=600)
coder, _ = guard.delegate(planner, "coder", tools=["fs.*"], ttl_seconds=600)
def show(who, name, tool, **args):
d = guard.authorize(who, ToolCall(tool=tool, args=args))
print(f"{name:10} {tool:12} -> {d.effect.value:5} rule={d.rule_id} source={d.source}")
show(researcher, "researcher", "web.search", query="castellan")
show(researcher, "researcher", "fs.read", path="/workspace/notes.md")
show(coder, "coder", "fs.read", path="/workspace/.env")
show(coder, "coder", "fs.write", path="/workspace/app.py", content="x")
show(coder, "coder", "web.search", query="castellan")
try:
guard.delegate(researcher, "coder", tools=["fs.read"], ttl_seconds=60)
except PermissionDenied as exc:
print("researcher cannot delegate:", exc)
researcher web.search -> allow rule=shallow-web source=policy
researcher fs.read -> deny rule=None source=grant
coder fs.read -> deny rule=no-secrets source=policy
coder fs.write -> ask rule=write-needs-review source=policy
coder web.search -> deny rule=None source=default
researcher cannot delegate: role 'researcher' may not delegate to 'coder' at depth 1
Read the source column: it tells you which stage decided.
researcher fs.readis allowed by the policy, but the researcher's grant only listsweb.*, so the grant denied it. The planner decided how much to hand down, and the researcher cannot take more.coder fs.readof.envis stopped byno-secretseven though the coder holdsfs.*.coder web.searchis denied by default: no rule lets a coder search the web.- The last line is the
agentssection at work. The researcher has nocan_delegate_to, so it cannot create any agent.
Test the policy¶
A policy this size deserves tests. Save team.test.yaml next to team.yaml and run it:
The testing and linting guide explains the file format and the linter.
Habits that keep policies safe¶
- Default to deny and add the narrowest allow you can.
- Put "never" in a deny rule with a
reason. It cannot be overridden. - Give every
askrule an approver and make sure that role can exist in a run. - Match roles, not agent ids. Ids change every run.
- Test the deny cases, not only the allow cases.
- Lint in CI. See testing and linting.
Pitfalls¶
- Broad globs.
tools: ["*"]witheffect: allowand nowhenallows everything; the linter flags it asL003. - Case. Tool names are lower-cased before matching, so write patterns in lower case.
- Path tricks. Castellan resolves
..in path-like arguments before matching, but only for argument names it recognizes as paths (path,file,dir, anything ending in_path, and a few others). A path hidden in an argument with an unusual name is treated as plain text. The policy language reference lists the names. - Role approvers.
role:<role>approvers are accepted by the language and the linter, butGuard.approvecannot yet satisfy them (it does not know the approver's role). Usehumanoragent:<id>approvers for now.
Where to go next¶
- Policy language reference: every key and operator.
- Multi-agent delegation: how grants work in depth.
- Approvals: the retry pattern after an
ask.