Policy as code for AI agents · OPA · Cedar
Your AI policy is a PDF. Your agent never reads it.
Turn the rule into a decision every tool call must pass before it runs: allow, deny, or a named human decides. Default deny. Versioned. Tested. A receipt for every call.
Which policy version allowed your agent's last production change?
PDF · p.14AI Acceptable Use Policy
Agents may not change production without a named approver.
Compiled to the highlighted rule, right.
Already shipped · Open source · Evidence-rated
Policy as code is not a roadmap item here. It ships, with tests, under open license.
Policy as code for AI agents means expressing governance rules in a machine-evaluated language such as OPA Rego or Cedar, so a policy decision point outside the model evaluates every proposed tool call against the principal, action, resource and context, returns allow, deny or require approval, and records the policy version behind each decision.
Last updated Tested against AI SAFE² v3.1 · safe2 CLI 1.1.0 · Gateway v3.0 · NEXUS v0.6By Vincent Sullivan
package csi.agent.toolcallimport rego.v1 allowed_tools := {"repo.read", "tests.run", "deploy", "payments.refund", "email.send", "agent.delegate"} decision := {"verdict": "deny", "reason": "no accountable human"} if { not input.origin.user} else := {"verdict": "deny", "reason": "delegation depth > 2"} if { input.delegation.depth > 2} else := {"verdict": "deny", "reason": "tool not on allowlist"} if { not input.tool in allowed_tools} else := {"verdict": "deny", "reason": "refund over hard limit"} if { input.action == "refund" input.params.amount > 5000} else := {"verdict": "escalate", "reason": "refund over 500"} if { input.action == "refund" input.params.amount > 500} else := {"verdict": "escalate", "reason": "production change"} if { input.env == "prod" input.action in {"write", "deploy"}} else := {"verdict": "escalate", "reason": "external send"} if { input.action == "send_external"} else := {"verdict": "allow", "reason": "within scope"} if { input.action in {"read", "test", "deploy", "refund", "delegate"}} else := {"verdict": "deny", "reason": "no rule matched"}
// Cedar answers permit or deny. The harness maps// "permitted only with a valid approval" to ESCALATE. forbid (principal, action, resource)when { !context.has_origin_user }; forbid (principal, action, resource)when { context.delegation_depth > 2 }; permit (principal is Agent, action in [Action::"read", Action::"test"], resource); permit (principal is Agent, action == Action::"deploy", resource)when { context.env != "prod" || context.approval_valid }; forbid (principal, action == Action::"refund", resource)when { context.amount > 5000 };Try a tool call
- decision
- escalate
- reason
- production change
- policy_version
- toolcall.v14
- actor
- agent:ops-02
- originating_user
- m.chen@acme.example
- tool
- deploy
- env
- prod
- delegation_depth
- 1
- params_hash
- sha256:…
- correlation_id
- …
Same branch order as the Rego · Pack ships with its tests
Should agent guardrails be policy as code?
Built for teams whose agents touch production, money, or data
Disclosure: the starter policies on this page are illustrative examples with tests; production policy should fit your schema, tools, and approvers.
02 · Where you are
Three questions about your AI policy
Tap the answer closest to true today.
Where does your AI policy live?
The agent never reads it. Pick the three highest-consequence rules and compile them first. See the translation steps.
A prompt is advice to the model. The first injected instruction overrides it. Read the prompt-policy path.
Good. Is it tested, versioned and on the receipt? See how to test.
Is there a decision point before tools run?
Then you have a PDP. Confirm every tool path hits it, including direct calls. That is test 1.
Scattered checks give scattered answers. One decision point, many enforcement points. See PDP vs PEP.
Then the model decides for itself. The starter pack is a working first gate.
Can it say "needs approval"?
Three verdicts: allow, deny, escalate. Check that approvals are scoped and expire.
Two verdicts push everything into deny or allow. Teams then loosen deny. Add escalate, as the OPA or Cedar answer explains.
Try it in the playground above. A production deploy should escalate, not pass.
03 · What changes
What is a policy decision point for AI agents?
The PDP decides. Enforcement points around each tool ask it and obey. The model is neither.
- PDP
- Policy decision point. Evaluates the request against versioned policy and returns a verdict with a reason.
- PEP
- Policy enforcement point. Sits in front of a tool, asks the PDP, and blocks, runs or holds the call.
- On-behalf-of identity
- The agent acts for a human. Both identities travel with the request, and both appear on the receipt.
- Principal, action, resource, context
- The four inputs every decision needs: who, what, on what, and under which conditions.
- Three-way decision
- Allow, deny, escalate. Escalate routes to a named human with the consequence in view.
- Policy version
- Every verdict records which policy produced it, so an audit can replay the decision.
| Model | Decides on | Good for agents when | Breaks when |
|---|---|---|---|
| RBAC | Roles | Agents have a few fixed jobs | The same agent needs different rights per task |
| ABAC | Attributes of principal, resource and context | Decisions depend on environment, amount or time | Attributes are stale or self-reported by the agent |
| ReBAC | Relationships between entities | Access follows ownership, teams or tenants | Delegation chains add relationships nobody reviewed |
| Capabilities | Unforgeable, scoped tokens | Each task gets exactly the rights it needs | Tokens are passed whole down a delegation chain |
04 · The evidence
Why prompts and PDFs fail as policy
of developers trust AI output in Stack Overflow's 2025 survey. A rule the model is asked to follow inherits that trust level.
Stack Overflow · 2025 surveygateway risk tiers in the AI SAFE² reference gateway, AUTO, MEDIUM, HIGH and CRITICAL, each with its own human authorization rule.
AI SAFE² gateway READMEOPA versions in NEXUS CI. Policies must pass opa check --strict and opa test; file presence no longer counts.
05 · Abuse paths
What happens when policy lives in the prompt?
If the answer is a prompt, what happens the first time the model ignores it?
Prompt-policy override
- AssetProduction
- ActorText in a ticket the agent reads
- Path"Approval already granted, proceed" outranks the system prompt
- ResultAn unapproved deploy, with no policy version to cite
Delegation laundering
- AssetPayments
- ActorA sub-agent four hops down
- PathEach hop re-asks with less context until a check passes
- ResultA refund no rule would allow at depth one
Approval fatigue
- AssetHuman attention
- ActorA policy that escalates everything
- PathReviewers click approve to clear the queue
- ResultA rubber stamp on the one action that mattered
06 · Architecture
How do you turn a written AI policy into code?
Models propose. Infrastructure decides. Evidence proves. Five steps from a sentence in a PDF to a tested rule.
- Pick the ruleStart with the clause whose violation costs most: production, money, data leaving.
- Name the inputsPrincipal, action, resource, context. If the agent can set an input, do not trust it.
- Write the decisionAllow, deny or escalate, in Rego or Cedar, default deny.
- Test itUnit, negative, mutation and shadow tests in CI.
- Enforce and recordPEPs at each tool. A receipt with the policy version for every call.
Where the gate sits
The PDP is one component of the harness. See where the decision point sits in the harness, and how MCP calls are bound by the MCP security profile.
Consumers get the same three answers in Agency Check: the same three-answer doctrine for consumers.
07 · Controls
Which policy controls map to AI SAFE²?
| Job | Control | AI SAFE² anchor | Shipped artifact |
|---|---|---|---|
| Prevent | Default deny. Tool allowlist. Hard limits on money and scope. | CP.4 Agentic Control Plane Governance | NEXUS OPA policies |
| Constrain | Delegation depth limit. On-behalf-of identity required. | CP.4 · CP.9 Agent Replication Governance | NEXUS |
| Detect | Shadow-mode evaluation of new policy against live traffic before enforcing. | P4 Engage and Monitor | Starter pack tests |
| Respond | Escalate with consequence shown, scoped approval, expiry. | CP.10 HEAR Doctrine | gateway HITL circuit breaker |
| Recover | Roll back to the previous policy version in one change. | P3 Fail-Safe and Recovery | Versioned policy bundle |
| Prove | Receipt per call with policy version, inputs hash and verdict. | P2 Audit and Inventory | developer-workflow decision record |
08 · How to test
How do you test policy as code for AI agents?
Four kinds of test. The starter pack ships the first two; the sprint adds the rest for your schema.
1. Unit tests per branch E3
One test per verdict path: no human, deep delegation, unknown tool, hard limit, soft limit, production change, external send, allow.
Pass
opa test . -v green on every branch.Fail
Any branch without a test.2. Negative tests E3
Inputs no rule covers must fall through to deny.
Pass
An unmatched action returns "no rule matched".Fail
Anything unmatched returns allow.3. Mutation tests E3
Flip one comparison or limit at a time and re-run the suite.
Pass
Every mutation breaks at least one test.Fail
A mutation survives: the tests do not pin that rule.4. Shadow tests E3
Run the new policy beside the current one on live traffic and diff the verdicts.
Pass
Every changed verdict is expected and reviewed before enforcement.Fail
Unexplained changes reach enforcement.09 · Proof in public
We did the work in public. Check it.
Every number below links to the file that proves it. Fork it, run it, try to break it.
README.md
19MCP profile controlsCP.5.MCP, MCP-1 to MCP-19, aligned to MCP 2026-07-28.00-cross-pillar/cp5_mcp_server_security.md
64scanner detection rulesJSON and SARIF output, fail-under gate in CI.scanner/README.md
22governed examplesClaude Code, Codex, Cursor, LangGraph, CrewAI, AutoGen, OpenClaw and more.examples/README.md
189NEXUS-A2A tests in the merge gateAgent-to-agent governance with OPA policies. Every PR must pass all of them.NEXUS/CONTRIBUTING.md
E0-E5evidence classesApplied to our own claims, in public, under Evidence Assurance v1.0.AISM/EVIDENCE-ASSURANCE.md
32frameworks mappedNIST AI RMF, ISO/IEC 42001, EU AI Act, OWASP and more, in the control dataset.safe2/data/ai-safe2-controls-v3.0.json
$0to read, run, fork or auditMIT and CC-BY-SA. NEXUS ships under Apache 2.0. No gate on the code.LICENSE
They define the risk. We ship the enforcement.
These bodies are the mapping targets, not the competition. AI SAFE² maps to them, then ships the code they leave to you.
| Who | Defines the risk | Maps to compliance | Open enforcement code for named agent stacks | Rates its own evidence in public | Published bypass process |
|---|---|---|---|---|---|
| OWASP GenAI Security Project | Yes | Partial | Not its scope | No | No |
| NIST AI RMF | Yes | Yes, it is the target | Not its scope | No | No |
| MITRE ATLAS | Yes | Partial | Not its scope | No | No |
| CSA MAESTRO and Agentic Control Plane | Yes | Partial | Not its scope | No | No |
| Runtime security vendors | Partial | Partial | Closed, own product only | Vendor reports | Some, through bug bounties |
| AI SAFE² | Yes, 161 controls | Yes, 32 frameworks | Yes, 22 examples, CLI, gateway | Yes, E0-E5 | Yes, Challenge Lab |
As of October 2026 · Got one wrong? Send the link. We correct it the same week.
Challenge Lab · C0 to C5 claim maturity
Break it.
Preregistered scenarios. Explicit invalidation criteria. A valid bypass or a grader defect is a high-value contribution, and it goes into the public record.
Or run it on yours, now
$ pip install "ai-safe2[all]==1.1.0" $ safe2 doctor . $ safe2 gate project . --fail-under 70 $ safe2 scan mcp https://your-host/mcp
Four commands. No sales call. If the gate fails, you just learned something your current vendor did not tell you.
Install line from MIGRATION.md. Commands from the safe2 CLI reference.
10 · Tools
OPA or Cedar for AI agent policy?
| Question | OPA Rego | Cedar |
|---|---|---|
| Verdicts | Any shape; returns allow, deny or escalate directly | Permit or deny; the harness maps "permit with valid approval" to escalate |
| Schema | Optional | Validated against a declared schema |
| Testing | opa test built in | Validation plus test harness of your choice |
| Best for | Rich context, many data sources, custom outputs | Clear permit and forbid rules that must be analyzable |
| Used here | NEXUS policies, the starter pack | The starter pack |
CSI analysis · October 2026
11 · Start here
Get the starter policy pack
The policies on this page, with their tests, ready for your CI.
Free · Starter Policy Pack
toolcall.rego, Rego v1, three verdictstoolcall_test.rego, unit and negative teststoolcall.cedarwith its schema- A README with the input shape
$ opa check --strict . $ opa test . -v
Productized sprint
Policy-to-Enforcement Sprint
- Scope
- One high-consequence agent workflow and the written policy that governs it.
- Deliverables
- Policies in Rego or Cedar for your schema, unit, negative and mutation tests in your CI, PEPs at each tool, and signed receipts.
- Timeline
- Two to four weeks.
- Risk reversal
- Policies ship with tests that run in your CI. If they do not run, we fix them.
- Starter Policy PackFree, result on this page
- Free 8-minute AI governance assessmentScore your AI risk
- Strategic Certainty SessionA fixed-scope working session
- Policy-to-Enforcement SprintCustom quote
- Secure AI Development ArchitectureEnterprise program
Would a pack you can run against your own tool calls this week help?
The policy already exists. It just has never been asked a question by your agent.
13 · FAQ
Straight answers on policy as code for AI agents
OPA or Cedar?
Both work. Cedar answers permit or deny, so the harness maps "permitted only with a valid approval" to ESCALATE. Rego can return the three-way verdict directly.
Are these production policies?
They are starter policies with tests. Production policy fits your schema, your tools and your approvers. That is the sprint.
Can static policy handle delegation chains?
Not alone, and the critics are right about that. Pair policy with live identity, delegation state and task context. The playground's depth limit is the simplest version of that idea.
Is the receipt in the playground real?
The fields are the receipt schema. The values are made up, and the hashes are computed in your browser from the inputs you chose.
Doesn't escalating slow everything down?
Only if everything escalates. Reads, tests and in-scope work are allowed. Escalation is reserved for production changes, money over a limit and data leaving, and each approval is scoped and expires.
14 · Sources and method
Sources, method and update log
External sources
CSI files cited
Method
External statistics name the publisher, year and sample. CSI claims link the repository file behind them and carry a rating under AI SAFE² Evidence Assurance v1.0: E1 for a specification, E2 for shipped code, E3 for a defined test with positive and negative cases. Vendor behavior comes from each vendor's current documentation, opened on the date shown.
Update log
- : page published. Vendor controls, repository counts and install line verified the same day.
Tested versions
AI SAFE² v3.1 · CP.5.MCP MCP-1 to MCP-19 · safe2 CLI 1.1.0 · Gateway v3.0 · NEXUS v0.6 · Evidence Assurance v1.0

Vincent Sullivan, founder and CEO of Cyber Strategy Institute. Twenty-two years as a U.S. Air Force cyber officer, finishing as Technical Director at U.S. Cyber Command. Author of the AI SAFE² framework.