14A.6 Agent Inventory, Risk and Autonomy Classification, and Policy-as-Code

Ship & get hiredLesson 6 of 108,894 words6 parts
Module 14A · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A company with one agent can keep its rules in one person's head. A company with twenty agents cannot. Someone has to answer three questions at any time: which agents do we run, and who owns each one?, how dangerous is each one, and what controls does that danger require?, and what is each agent actually allowed to do, and can we prove it? This lesson answers them with small, runnable tools. You will build an agent inventory with a validator, a risk and autonomy classifier that maps each agent to a tier and the controls that tier requires, and a policy engine where tool and data access rules are versioned data with default deny and tests. You will also see how the same policies look in two real policy languages (OPA's Rego and Cedar) and where policies are enforced (the tool dispatcher, a tool gateway, an MCP gateway), and you will finish with an eval of the policy layer itself. It builds on the autonomy levels of 08A.1, the approval gates of 08A.12 and the security basics of 08A.5. The general AI-system governance machinery (change tiers, access control, audit logs) is taught in 11C.4, Part 2; this lesson specialises it for agents.

What you'll learn

  • What belongs in an agent inventory: owner, purpose, model, tools, data, autonomy level, risk tier, approvals, eval evidence and review date, and why each field exists
  • The lifecycle of an inventory entry: register, review, retire, and what "retire" must actually switch off
  • A risk tiering rubric (impact x autonomy x data sensitivity, with floors) and how to map each tier to required controls
  • Policy-as-code for tool and data access: policies as versioned data, default deny, "forbid wins", failing closed, and tests for the policies themselves
  • How the same idea looks in OPA/Rego and Cedar, two real policy engines, and how to choose between a hand-rolled engine and one of them
  • Enforcement points (tool dispatcher, tool gateway, MCP gateway) and the audit trail every decision leaves
  • How to evaluate the policy layer: a table of requests with expected decisions, and a mutation check

What you don't need

  • API keys. Every program here is standard-library Python that makes no network calls.
  • Docker, a policy server or any local service. The OPA and Cedar snippets are labelled illustrative and are not run in this lesson; you can read them without installing anything.
  • A compliance background. This lesson is engineering. What the NIST AI RMF and ISO/IEC 42001 are is in 12.9, 6.8 to 6.11 (and 14A.7 links the vendor and data side).

Setup

Python 3.11 or newer and nothing else (standard library only). As of 1 December 2026 there is nothing to install. Save each code block under the file name in its first comment (the two JSON files are named in the sentence before them, because JSON has no comments) and run it with python3 <file>. The outputs below were produced with Python 3.14 by running exactly these files, with warnings turned into errors (python3 -W error). The dates in the examples are fixed so the output reproduces; in CI you would use today's date.


What you must be able to do after this lesson#

  • Write an agent inventory entry with every required field and run a validator that fails on missing owners, stale reviews and retired agents that still hold tools
  • Compute an agent's risk tier from impact, autonomy and data sensitivity, and apply the floors that can only raise it
  • Map a risk tier to its cumulative required controls, review cadence and approvals
  • Write tool and data access rules as versioned policy data with default deny, forbid wins and fail closed
  • Test a policy set with a table of requests and a mutation check, and read the hash-chained audit log
  • Choose an enforcement point (tool dispatcher, tool gateway, MCP gateway, backend scopes) that no call can bypass, and list what every decision must log

Why this matters for an AI engineer#

The first agent you ship is a project. The tenth is a portfolio, and a portfolio is where things go wrong quietly: an agent whose owner left the company, an agent still holding a refund tool after its feature was cancelled, a prototype that someone pointed at production data, a model alias that changed under a "no change" deploy. None of these needs a clever attack. They need nobody to be keeping a list. Governance sounds like paperwork, but at this scale it is mostly a small data file, a few scripts that run in CI, and a policy layer that says no by default.

You'll hear... You'll understand it after...
"How many agents do we even have?" Part 1: the inventory
"Who owns this agent? Who approved it?" 1.2 The fields and 1.4 Ownership
"Is this a high-risk agent?" Part 2: risk and autonomy classification
"What controls does a high-risk agent need?" 2.5 From tier to required controls
"Policy as code" Part 3
"Should we use OPA or Cedar?" Part 4
"Where do we enforce it, and what do we log?" Part 5
"How do we know the policies work?" Part 6: Evaluate it

Part 1: The agent inventory#

This part extends 11C.4, 2.2 (the inventory of every AI artefact) with an agent-specific entry: autonomy, tier, approvals, a lifecycle and a validator that runs in CI.

1.1 What it is and why agents need their own#

An agent inventory is the single list of every agent your organisation runs, with the facts you need to govern each one. 11C.4, section 2.2 teaches the broader "AI system inventory" that also lists prompts, indexes, keys and routes. This lesson zooms in on the agent row, because agents differ from other AI features in three ways that change what you must record:

  • They act. A chat feature that is wrong wastes a reader's time. An agent that is wrong can send an email or move money. So the inventory records tools and autonomy, not just the model.
  • They multiply quietly. Anyone can wire a model to a tool in an afternoon. Without a registry, the real number of agents is "more than we know".
  • Their power is configuration. The same model is a harmless suggester at autonomy level 1 and an unattended operator at level 4 (08A.1, 2.2). The level lives in code and config, so it can change without anyone noticing unless it is written down and checked.

1.2 The fields#

Each entry answers a question that a reviewer, an auditor or an incident responder will ask.

Field The question it answers Example
id Which agent is this? One stable name used everywhere (logs, policies, budgets) support-bot
owner Who gets paged, who answers for it, who approves changes? A team, not a person team-support
purpose What is it for, in one sentence? (Anything outside this is out of scope.) "Look up orders, open tickets and issue small refunds"
provider, model What runs it? An exact pinned model id, not a floating alias (11C.5) openai, gpt-6-luna
tools What can it do? The list the policy layer enforces (08A.7) orders_get, refund_issue
data_classes What kinds of data can it see? Classes are defined in 14A.7 internal, personal
autonomy How much may it do alone? The level from 08A.1: 1 suggest, 2 assist, 3 act with approval, 4 act autonomously 3
risk_tier How dangerous is it? Computed and recorded (Part 2) high
approvals Who signed off, and when? (11C.4, 2.3) eng-lead, privacy-owner
eval_evidence What proves it works, and where is the report? evals/support_bot_2026-10.json
controls Which required controls are in place? (Checked against the tier) approval_gate, kill_switch
status Where is it in its life? proposed, active or retired active
reviewed_on When did a human last confirm all of this is still true? 2026-10-29

Two notes on fields. First, record what is true, not what is hoped. tools is the list the agent can actually call, and the policy layer reads it. Second, one inventory, many readers. The same file feeds the cost dashboards (11B.6 attributes spend to id and owner), the policy engine, the audit report and the on-call runbook.

Here is the example inventory used in the rest of the lesson. Save it as agent_inventory.json. It has five agents, and three of them have deliberate problems for the checker to find.

json
[
  {
    "id": "faq-bot",
    "owner": "team-docs",
    "purpose": "Answer product questions from public documentation",
    "provider": "anthropic",
    "model": "claude-sonnet-5-5",
    "tools": ["kb_search"],
    "data_classes": ["public"],
    "autonomy": 1,
    "risk_tier": "low",
    "approvals": [{"by": "docs-lead", "on": "2026-09-14"}],
    "eval_evidence": "evals/faq_bot_2026-09.json",
    "controls": ["inventory", "tracing"],
    "status": "active",
    "reviewed_on": "2026-09-14"
  },
  {
    "id": "support-bot",
    "owner": "team-support",
    "purpose": "Look up orders, open tickets and issue small refunds",
    "provider": "openai",
    "model": "gpt-6-luna",
    "tools": ["orders_get", "kb_search", "ticket_create", "refund_issue"],
    "data_classes": ["internal", "personal"],
    "autonomy": 3,
    "risk_tier": "high",
    "approvals": [{"by": "eng-lead", "on": "2026-10-28"}, {"by": "privacy-owner", "on": "2026-10-29"}],
    "eval_evidence": "evals/support_bot_2026-10.json",
    "controls": ["inventory", "tracing", "eval_gate", "tool_allowlist", "budget_limits", "audit_log",
                 "approval_gate", "policy_as_code", "red_team_in_ci", "kill_switch"],
    "status": "active",
    "reviewed_on": "2026-10-29"
  },
  {
    "id": "cost-cleaner",
    "owner": "team-platform",
    "purpose": "Shut down idle cloud servers to save money",
    "provider": "anthropic",
    "model": "claude-sonnet-5-5-latest",
    "tools": ["servers_list", "server_stop", "server_delete"],
    "data_classes": ["internal"],
    "autonomy": 4,
    "risk_tier": "medium",
    "approvals": [],
    "eval_evidence": "",
    "controls": ["inventory", "tracing", "budget_limits"],
    "status": "active",
    "reviewed_on": "2026-02-03"
  },
  {
    "id": "hr-helper",
    "owner": "",
    "purpose": "Draft replies to employee questions",
    "provider": "openai",
    "model": "gpt-6-luna",
    "tools": ["kb_search"],
    "data_classes": ["personal", "secrets"],
    "autonomy": 2,
    "risk_tier": "medium",
    "approvals": [{"by": "hr-lead", "on": "2026-08-01"}],
    "eval_evidence": "evals/hr_helper_2026-08.json",
    "controls": ["inventory", "tracing", "eval_gate", "tool_allowlist", "budget_limits", "audit_log"],
    "status": "active",
    "reviewed_on": "2026-11-20"
  },
  {
    "id": "old-summarizer",
    "owner": "team-docs",
    "purpose": "Summarize long documents (replaced by faq-bot tooling)",
    "provider": "anthropic",
    "model": "claude-opus-4-5-20251101",
    "tools": ["kb_search"],
    "data_classes": ["internal"],
    "autonomy": 1,
    "risk_tier": "low",
    "approvals": [{"by": "docs-lead", "on": "2025-11-02"}],
    "eval_evidence": "evals/old_summarizer.json",
    "controls": ["inventory"],
    "status": "retired",
    "reviewed_on": "2026-06-01"
  }
]

1.3 The lifecycle: register, review, retire#

An entry has a life, and each step has an owner and an action.

flowchart LR
    P["proposed<br/>entry written, not yet approved"] -->|"checks pass and approvers sign"| A["active<br/>tools granted by policy"]
    A -->|"scheduled or triggered review"| A
    A -->|"feature cancelled, replaced or unsafe"| R["retired<br/>access revoked, record kept"]
    A -->|"risk tier rises"| P

Register. Before an agent gets a tool or a key, someone writes the entry. A new entry starts as proposed. It becomes active only when the validator passes and the required approvals are in (the number depends on the tier, Part 2). Registering first is the point: it is cheaper to ask "what tier is this?" before the agent exists than after it is in use.

Review. An active agent is re-confirmed on a schedule that depends on its tier: here every 365, 180, 90 or 30 days for low, medium, high and critical. A review checks that the tools, data classes and autonomy level in the file still match reality, that the eval evidence is recent, and that the owner is still the owner. Some events trigger a review immediately, whatever the date: a new tool, a new data class, a model change, an autonomy increase, an incident, or a provider notice (11C.5 covers model retirements). A change that raises the risk tier sends the entry back to proposed.

Retire. Retiring is the step most teams skip. "We stopped using it" is not enough, because the agent's credentials, tool grants and scheduled jobs still exist. Retire means: set status to retired, revoke every tool and key, remove its schedules, and keep the record so an audit can still answer "what was this and who approved it?". The checker below flags any retired entry that still lists tools.

1.4 Ownership is a team with a pager#

The owner field is the most important and the most often wrong. Three rules:

  1. A team, not a person. People change jobs. A team alias with an on-call rotation does not. (A named approver is a person, because approval is a decision on a date.)
  2. The owner can turn it off. Owning an agent means having the authority and the means to use the kill switch (08A.5, 11B.7). A "owner" who cannot is a contact, not an owner.
  3. Author is not approver. The person who built the agent cannot be its only approver. 11C.4, 2.4 explains the separation of duties; the inventory's approvals list is where you check it.

When a team is reorganised, ownership changes are a normal change event: the new owner re-reviews and signs. An entry with an empty owner is a failure, not a warning.


Part 2: Risk and autonomy classification#

2.1 Three factors#

Not every agent deserves the same effort. A bot that searches public docs and a bot that issues refunds should not carry the same paperwork. A risk tier says how much control an agent needs. A useful tier has to depend on what can go wrong, and three things decide that:

Factor The question Scale used here
Impact What is the worst single action the agent can take? 1 none (read-only), 2 small and reversible, 3 money, people or customer-visible and hard to undo, 4 irreversible, regulated or safety-relevant
Autonomy How much does it do without a human? The four levels of 08A.1: 1 suggest, 2 assist, 3 act with approval, 4 act autonomously
Data sensitivity What is the most sensitive data it can see? 1 public, 2 internal, 3 personal, 4 sensitive (health, finance, government ids, children's data). The classes are defined in 14A.7

Impact comes from the tools, not from the model: it is the worst tool the agent can call. Autonomy comes from the configuration. Sensitivity comes from the data it is wired to. None of them is a property of the model, which is why the same model can be a low-tier and a critical-tier agent.

2.2 The rubric#

Multiply the three factors. The product rises quickly when two factors are high together, which is the behaviour you want: a read-only agent on personal data (1 x 1 x 3 = 3) is low, and an autonomous agent with money-moving tools on personal data (3 x 4 x 3 = 36) is not. Then apply floors, rules that can only raise the tier, for combinations a product underrates.

Product Tier
1 to 6 low
7 to 18 medium
19 to 36 high
above 36 critical
Floor Why
Impact 4 with autonomy 3 or 4 is critical Irreversible actions need the heaviest review whenever the agent can take them
Sensitive data with autonomy 3 or 4 is at least high Regulated data plus action is where regulators look
Impact 3 or more with autonomy 4 is at least high Money or people affected with no human before the action
Secrets in the data classes is an error Credentials never belong in prompts, tools or logs, so there is no tier for it

The numbers are a starting rubric, not a law. What matters is that your organisation writes one down, applies it to every agent the same way and changes it on purpose (a rubric change is itself a reviewed change). Compare it with the four action tiers in 08A.12, 2.1 and 08A.14, 2.4: those classify a single tool call at run time. The tier here classifies the whole agent at design time. They fit together: an agent's tier decides which controls it must have, and its tool-call tiers decide which individual calls need a human.

2.3 The classifier#

python
# risk.py: risk tier = impact x autonomy x data sensitivity, with floors and a control map (stdlib only)
IMPACT = {  # worst single action the agent can take
    1: "none: read-only, nothing leaves the system",
    2: "small and reversible: a draft, a ticket, a note",
    3: "money, people or customer-visible, hard to undo",
    4: "irreversible, regulated or safety-relevant",
}
DATA = {"public": 1, "internal": 2, "personal": 3, "sensitive": 4}   # "secrets" is never allowed (see below)
TIERS = ["low", "medium", "high", "critical"]

# Controls are cumulative: a higher tier needs everything the lower tiers need.
CONTROLS_ADDED_AT = {
    "low":      ["inventory", "tracing"],
    "medium":   ["eval_gate", "tool_allowlist", "budget_limits", "audit_log"],
    "high":     ["approval_gate", "policy_as_code", "red_team_in_ci", "kill_switch"],
    "critical": ["change_board", "independent_review", "autonomy_cap_3"],
}
REVIEW_EVERY_DAYS = {"low": 365, "medium": 180, "high": 90, "critical": 30}


def required_controls(tier):
    out = []
    for t in TIERS[: TIERS.index(tier) + 1]:
        out += CONTROLS_ADDED_AT[t]
    return out


def impact_from_tools(tools, tool_impact):
    """Impact is the worst tool the agent can call. Unknown tools count as 4 (fail closed)."""
    return max((tool_impact.get(t, 4) for t in tools), default=1)


def score(impact, autonomy, data_classes):
    if "secrets" in data_classes:
        raise ValueError("secrets must never reach an agent's prompts, tools or logs")
    sensitivity = max((DATA[c] for c in data_classes), default=1)
    return impact * autonomy * sensitivity, sensitivity


def classify(impact, autonomy, data_classes):
    """Return (tier, product, why). Product bands first, then floors that can only raise the tier."""
    product, sensitivity = score(impact, autonomy, data_classes)
    tier = "low" if product <= 6 else "medium" if product <= 18 else "high" if product <= 36 else "critical"
    why = [f"{impact} x {autonomy} x {sensitivity} = {product}"]

    def floor(minimum, reason):
        nonlocal tier
        if TIERS.index(tier) < TIERS.index(minimum):
            tier = minimum
            why.append(f"floor: {reason} -> at least {minimum}")

    if impact == 4 and autonomy >= 3:
        floor("critical", "irreversible impact with act-with-approval or autonomy")
    if sensitivity == 4 and autonomy >= 3:
        floor("high", "sensitive data with act-with-approval or autonomy")
    if impact >= 3 and autonomy == 4:
        floor("high", "money or people affected with no human before the action")
    return tier, product, why

impact_from_tools is deliberate about unknown tools: a tool nobody has classified counts as impact 4. That is "fail closed": the cost of forgetting to classify is more review, not less.

Here is what it says about four agents of the kind you will meet.

python
# classify_examples.py
import risk

for label, impact, autonomy, classes in [
    ("FAQ bot, public docs, suggests only",          1, 1, ["public"]),
    ("Support bot, small refunds with approval",     3, 3, ["internal", "personal"]),
    ("Cost cleaner, autonomous, can delete servers", 4, 4, ["internal"]),
    ("Health triage, drafts only, sensitive data",   2, 2, ["sensitive"]),
]:
    tier, product, why = risk.classify(impact, autonomy, classes)
    print(f"{label:46s} {tier:8s} {'; '.join(why)}")
Output · real4 lines
FAQ bot, public docs, suggests only            low      1 x 1 x 1 = 1
Support bot, small refunds with approval       high     3 x 3 x 3 = 27
Cost cleaner, autonomous, can delete servers   critical 4 x 4 x 2 = 32; floor: irreversible impact with act-with-approval or autonomy -> at least critical
Health triage, drafts only, sensitive data     medium   2 x 2 x 4 = 16

The cost cleaner is the lesson in one line. Its product (4 x 4 x 2 = 32) is only "high", but the floor lifts it to critical, because it can take irreversible actions with nobody in the loop. The health triage agent shows the reverse: with sensitive data but drafts only, it stays at the medium tier (2 x 2 x 4 = 16), and it would jump to high the day someone raised its autonomy to 3.

2.4 Autonomy is part of the classification, and it is the cheapest lever#

Look at what lowers an agent's tier: not a better model, but a lower autonomy level or a narrower tool list. Take the cost cleaner (critical, 4 x 4 x 2 = 32 with the floor). Remove server_delete from its tools and impact drops from 4 to 3: the product is 3 x 4 x 2 = 24, which is high. Keep server_delete but drop autonomy to 2, so the agent only proposes deletions for a human to run, and the product is 4 x 2 x 2 = 16, medium (we ran both through risk.classify to be sure). Dropping only to autonomy 3 does not help: with an irreversible tool and a human approving each action, the impact-4 floor still says critical, because the floor is about what the agent can do once approved. This is why classification and design are one conversation: the review that assigns a tier is also where the team asks "do we need that tool, and do we need it unattended?".

08A.1, 2.7 shows how to earn a higher level with measured results. The inventory is where that decision is recorded: an autonomy increase is a change that triggers a review, new approvals and a new tier computation.

2.5 From tier to required controls#

The tier is useful only because it decides what you must do. Controls are cumulative: each tier needs everything below it.

Tier Controls added at this tier Review cadence Approvals
low inventory entry, tracing (03.12) every 365 days owner
medium eval gate before release (10A.8), tool allow-list, budget limits (11B.6), audit log every 180 days owner
high approval gate for writes (08A.12), policy-as-code enforcement (Part 3), red-team suite in CI (12.8), kill switch every 90 days two named approvers (for example engineering lead and privacy owner)
critical change board review (T4 in 11C.4, 2.3), independent review, autonomy capped at 3 unless the board signs an exception every 30 days the board

The checker applies this table. Save the next file as inventory_check.py. For every active agent it computes the tier from the tools, autonomy and data, takes the higher of the computed and the declared tier, and then checks the controls, evidence, approvals and review date that tier needs.

python
# inventory_check.py: validate the agent inventory and compare it with the risk rubric (stdlib only)
import json
import sys
from datetime import date

import risk

TODAY = date(2026, 12, 1)          # fixed so the output reproduces; use date.today() in CI
REQUIRED = ["id", "owner", "purpose", "provider", "model", "tools", "data_classes", "autonomy",
            "risk_tier", "approvals", "eval_evidence", "controls", "status", "reviewed_on"]
TOOL_IMPACT = {"kb_search": 1, "orders_get": 1, "servers_list": 1, "ticket_create": 2,
               "refund_issue": 3, "server_stop": 3, "server_delete": 4}   # your tool catalogue


def check_entry(e):
    problems = []
    missing = [f for f in REQUIRED if f not in e]
    if missing:
        return [f"missing fields: {', '.join(missing)}"]
    if not e["owner"].strip():
        problems.append("no owner")
    if e["autonomy"] not in (1, 2, 3, 4):
        problems.append(f"autonomy {e['autonomy']} is not 1..4")
    if e["risk_tier"] not in risk.TIERS:
        problems.append(f"unknown risk tier {e['risk_tier']!r}")
    if "latest" in e["model"]:
        problems.append(f"floating model alias {e['model']!r}: pin a snapshot")
    if e["status"] == "retired":
        if e["tools"]:
            problems.append("retired but still holds tool access: revoke it")
        return problems
    # the declared tier must be at least what the rubric computes
    try:
        tier, _, why = risk.classify(risk.impact_from_tools(e["tools"], TOOL_IMPACT), e["autonomy"], e["data_classes"])
    except ValueError as err:
        problems.append(str(err))
        tier = e["risk_tier"]
    if e["risk_tier"] in risk.TIERS and risk.TIERS.index(e["risk_tier"]) < risk.TIERS.index(tier):
        problems.append(f"declared tier {e['risk_tier']} is below computed tier {tier} ({'; '.join(why)})")
    effective = max(e["risk_tier"], tier, key=risk.TIERS.index) if e["risk_tier"] in risk.TIERS else tier
    # tier -> required controls
    lacking = [c for c in risk.required_controls(effective) if c not in e["controls"]]
    if lacking:
        problems.append(f"tier {effective} needs controls: {', '.join(lacking)}")
    if effective != "low" and not e["eval_evidence"]:
        problems.append("no eval evidence")
    if effective in ("high", "critical") and len(e["approvals"]) < 2:
        problems.append("high tier needs two approvals")
    age = (TODAY - date.fromisoformat(e["reviewed_on"])).days
    if age > risk.REVIEW_EVERY_DAYS[effective]:
        problems.append(f"review overdue: {age} days since last review, limit {risk.REVIEW_EVERY_DAYS[effective]}")
    return problems


def check_inventory(entries):
    report, ids = {}, set()
    for e in entries:
        report[e.get("id", "?")] = check_entry(e)
        if e.get("id") in ids:
            report[e["id"]].append("duplicate id")
        ids.add(e.get("id"))
    return report


if __name__ == "__main__":
    with open(sys.argv[1] if len(sys.argv) > 1 else "agent_inventory.json") as f:
        entries = json.load(f)
    report = check_inventory(entries)
    for agent_id, problems in report.items():
        print(f"{agent_id:15s} {'ok' if not problems else ''}")
        for p in problems:
            print(f"    - {p}")
    sys.exit(1 if any(report.values()) else 0)

Run it on the example inventory:

bash
python3 -W error inventory_check.py; echo "exit=$?"
Output · real, with the date fixed at 2026-12-0115 lines
faq-bot         ok
support-bot     ok
cost-cleaner    
    - floating model alias 'claude-sonnet-5-5-latest': pin a snapshot
    - declared tier medium is below computed tier critical (4 x 4 x 2 = 32; floor: irreversible impact with act-with-approval or autonomy -> at least critical)
    - tier critical needs controls: eval_gate, tool_allowlist, audit_log, approval_gate, policy_as_code, red_team_in_ci, kill_switch, change_board, independent_review, autonomy_cap_3
    - no eval evidence
    - high tier needs two approvals
    - review overdue: 301 days since last review, limit 30
hr-helper       
    - no owner
    - secrets must never reach an agent's prompts, tools or logs
old-summarizer  
    - retired but still holds tool access: revoke it
exit=1

Read it entry by entry.

  • faq-bot and support-bot pass. support-bot computes to 3 x 3 x 3 = 27, high, and it has all ten controls for that tier, two approvals and a review 33 days old.
  • cost-cleaner is a typical "prototype that grew". Someone declared it medium. The rubric says critical. It uses a floating alias, has no evals, no approvals and no policy layer, and was last reviewed 301 days ago. Each line is a ticket.
  • hr-helper fails for two reasons that no tier can fix: nobody owns it, and its data classes include secrets. Credentials in an agent's data are an error, not a risk level.
  • old-summarizer is retired but still holds kb_search. Retirement did not revoke access.

The non-zero exit code is the feature: run this in CI on every change to the inventory and on a schedule, so an overdue review fails a build instead of waiting for an audit.


Part 3: Policy-as-code for tool and data access#

This part extends 08A.14, 2.10 (one policy layer wrapped around one tool registry) by pulling the rules out into data that covers every agent, reads agent facts from the inventory, and has tests of its own.

3.1 What it is and why#

A policy is a rule about who may do what. Policy-as-code means those rules are written in a machine-readable form, kept in version control, reviewed like code, tested like code and enforced by software, not by a paragraph in a document or an instruction in a prompt. It solves three problems that appear as soon as there is more than one agent:

  • Scattered rules. Without a policy layer, "support-bot may refund up to 100" is an if statement in one tool, a sentence in a prompt and a belief in a manager's head. They drift apart. One policy file is one place to read, review and change.
  • Prompts are not enforcement. A prompt asks the model to behave. A policy decision is made by code that the model cannot talk to (08A.12, 1.3).
  • No evidence. An auditor asking "what was allowed on 14 October, and who changed it?" needs a git history and a decision log, not recollection.

Policy-as-code is the next step after the policy layer sketched in 08A.14, 2.10: that lesson wraps one tool registry in checks; here the rules are pulled out into data that applies to every agent and reads agent facts from the inventory.

3.2 The five rules of a good policy layer#

  1. Policies are data. Not code paths. A reviewer can read a policy file without reading the engine, and the engine can be replaced without rewriting the policies.
  2. Default deny. Nothing is allowed unless a policy says so. The safe failure is "the agent could not do a thing it should have", which is visible and fixable, not "the agent did a thing nobody allowed".
  3. Forbid wins. An explicit forbid beats any permit. That lets you write "never delete customers, for any agent, in any environment" once, and be sure a later permit cannot undo it.
  4. Fail closed. A missing argument, an unknown condition or a malformed policy file means deny (or refuse to load), never allow. A policy that raises an exception inside the request path must also end in deny.
  5. Policies have tests. A policy is code that decides who may move money. It gets a test suite, including tests that try to break it.

3.3 The policies#

Save this as policies.json. It says what the agents in the inventory may do. Read each entry as a sentence.

json
[
  {"id": "P1-read-tools", "effect": "permit", "agent": {"min_autonomy": 1},
   "tools": ["kb_search", "orders_get"], "note": "any registered, active agent may read"},
  {"id": "P2-tickets", "effect": "permit", "agent": {"ids": ["support-bot"]},
   "tools": ["ticket_create"], "when": {"max_data_class": "personal"}},
  {"id": "P3-small-refunds", "effect": "permit", "agent": {"ids": ["support-bot"], "min_autonomy": 3},
   "tools": ["refund_issue"], "when": {"max_amount": 100, "env_in": ["prod", "staging"]}},
  {"id": "F1-never", "effect": "forbid", "tools": ["customer_delete", "shell_exec", "server_delete"],
   "note": "no agent, in any environment"},
  {"id": "F2-secrets", "effect": "forbid", "when": {"data_class_in": ["secrets"]},
   "note": "secrets never pass through a tool call"}
]
  • P1-read-tools: any registered, active agent with autonomy at least 1 may call the two read tools.
  • P2-tickets: only support-bot may create tickets, and only if the request involves no data above personal.
  • P3-small-refunds: only support-bot, and only at autonomy 3 or more, may issue refunds, only up to an amount of 100, and only in prod or staging.
  • F1-never and F2-secrets are forbids. No agent may call those three tools, and no tool call may carry secrets.

3.4 The engine#

This is a policy decision point (PDP): a function that takes a request and returns allow or deny with the reasons. It is deliberately small so you can read all of it. It looks agent facts up in the inventory (so an unregistered or retired agent is denied before any policy is read), it applies forbids first, then permits, then default deny, and it validates the policy file at load time. It also contains an audit log whose records are chained by hash, and an enforce function that is the enforcement point: the one place a tool function can run.

python
# policy_engine.py: a tiny policy decision point. Policies are data; the default is deny (stdlib only)
import hashlib
import json

ORDER = ["public", "internal", "personal", "sensitive", "secrets"]
AGENT_KEYS = {"ids", "min_autonomy", "max_autonomy", "risk_tiers"}
WHEN_KEYS = {"max_amount", "env_in", "data_class_in", "max_data_class"}


def load_policies(path):
    with open(path) as f:
        policies = json.load(f)
    seen = set()
    for p in policies:                      # a bad policy file must fail at load time, not at 3 a.m.
        if p["id"] in seen:
            raise ValueError(f"duplicate policy id {p['id']}")
        seen.add(p["id"])
        if p["effect"] not in ("permit", "forbid"):
            raise ValueError(f"{p['id']}: effect must be permit or forbid")
        if not (set(p.get("agent", {})) <= AGENT_KEYS and set(p.get("when", {})) <= WHEN_KEYS):
            raise ValueError(f"{p['id']}: unknown condition key")
        if p["effect"] == "permit" and not p.get("tools"):
            raise ValueError(f"{p['id']}: a permit must name its tools (no wildcard permits)")
    return policies


def agent_matches(sel, agent):
    return ((not sel.get("ids") or agent["id"] in sel["ids"])
            and agent["autonomy"] >= sel.get("min_autonomy", 1)
            and agent["autonomy"] <= sel.get("max_autonomy", 4)
            and (not sel.get("risk_tiers") or agent["risk_tier"] in sel["risk_tiers"]))


def when_holds(when, request):
    ctx, args = request.get("context", {}), request.get("args", {})
    classes = ctx.get("data_classes", [])
    if "max_amount" in when:                # a missing or non-numeric amount fails closed
        amount = args.get("amount")
        if not isinstance(amount, (int, float)) or amount > when["max_amount"]:
            return False
    if "env_in" in when and ctx.get("env") not in when["env_in"]:
        return False
    if "data_class_in" in when and not any(c in when["data_class_in"] for c in classes):
        return False
    if "max_data_class" in when and any(ORDER.index(c) > ORDER.index(when["max_data_class"]) for c in classes):
        return False
    return True


def decide(policies, inventory, request):
    """Return {"effect", "reasons", "matched"}. Order: unknown agent, forbid, permit, default deny."""
    agent = inventory.get(request["agent"])
    if agent is None:
        return {"effect": "deny", "reasons": ["agent is not in the inventory"], "matched": []}
    if agent["status"] != "active":
        return {"effect": "deny", "reasons": [f"agent status is {agent['status']}"], "matched": []}
    hits = {"permit": [], "forbid": []}
    for p in policies:
        tool_ok = request["tool"] in p.get("tools", [request["tool"]])   # no "tools" key = every tool
        if tool_ok and agent_matches(p.get("agent", {}), agent) and when_holds(p.get("when", {}), request):
            hits[p["effect"]].append(p["id"])
    if hits["forbid"]:
        return {"effect": "deny", "reasons": ["a forbid policy matched"], "matched": hits["forbid"]}
    if hits["permit"]:
        return {"effect": "allow", "reasons": ["a permit policy matched"], "matched": hits["permit"]}
    return {"effect": "deny", "reasons": ["no policy permits this (default deny)"], "matched": []}


class AuditLog:
    """Append-only list where every record carries the hash of the previous one (tamper-evident)."""
    def __init__(self):
        self.records = []

    def append(self, request, decision):
        prev = self.records[-1]["hash"] if self.records else "genesis"
        # copy through JSON: if we kept a reference, the caller editing its request later would rewrite history
        body = json.loads(json.dumps({"request": request, "decision": decision, "prev": prev}))
        digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
        self.records.append({**body, "hash": digest})

    def verify(self):
        prev = "genesis"
        for r in self.records:
            body = {"request": r["request"], "decision": r["decision"], "prev": prev}
            if r["prev"] != prev or r["hash"] != hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest():
                return False
            prev = r["hash"]
        return True


def enforce(policies, inventory, audit, request, tool_fn):
    """The enforcement point: nothing runs unless decide() says allow. Denials are returned, not raised."""
    decision = decide(policies, inventory, request)
    audit.append(request, decision)
    if decision["effect"] != "allow":
        return {"ok": False, "error": f"denied: {decision['reasons'][0]}", "matched": decision["matched"]}
    return {"ok": True, "result": tool_fn(**request.get("args", {}))}

Three details are worth reading twice.

  • load_policies refuses wildcard permits. A permit must name its tools. Wildcards are allowed for forbids (F2-secrets applies to every tool) but never for permits. This is the "default deny" rule applied to policy authors: you cannot accidentally allow everything with one line.
  • when_holds fails closed on conditions. If a policy caps amount and the request has no numeric amount, the condition is false, so a permit does not match. (Part 4 shows the opposite danger: the same rule applied to a forbid fails open.)
  • AuditLog.append copies the request through JSON. The first version of this file stored a reference to the caller's dictionary. The demo then changed amount in that same dictionary for a second call, which silently rewrote the first record, and verify() reported the chain broken. An audit log that holds references to mutable objects is not an audit log. Copy on write.

3.5 Run it#

python
# demo_policy.py: run a handful of requests through the engine and the enforcement point
import json
from pathlib import Path

import policy_engine as pe

inventory = {a["id"]: a for a in json.loads(Path("agent_inventory.json").read_text())}
policies = pe.load_policies("policies.json")
audit = pe.AuditLog()

def case(label, agent, tool, args=None, **ctx):
    req = {"agent": agent, "tool": tool, "args": args or {}, "context": {"env": "prod", "data_classes": ["personal"], **ctx}}
    d = pe.decide(policies, inventory, req)
    audit.append(req, d)
    print(f"{label:38s} {d['effect']:5s} {d['matched'] or d['reasons'][0]}")

case("support-bot reads an order", "support-bot", "orders_get", {"order_id": "A17"})
case("support-bot refunds 80", "support-bot", "refund_issue", {"amount": 80})
case("support-bot refunds 100.01", "support-bot", "refund_issue", {"amount": 100.01})
case("support-bot refund with no amount", "support-bot", "refund_issue", {})
case("support-bot refund in dev env", "support-bot", "refund_issue", {"amount": 5}, env="dev")
case("faq-bot tries a refund (autonomy 1)", "faq-bot", "refund_issue", {"amount": 5})
case("faq-bot opens a ticket", "faq-bot", "ticket_create")
case("support-bot deletes a customer", "support-bot", "customer_delete")
case("support-bot, secret in context", "support-bot", "orders_get", data_classes=["secrets"])
case("unknown agent", "shadow-agent", "kb_search")
case("retired agent", "old-summarizer", "kb_search")
case("tool nobody wrote a rule for", "support-bot", "export_all_orders")

print("\nenforcement point:")
req = {"agent": "support-bot", "tool": "refund_issue", "args": {"amount": 40}, "context": {"env": "prod", "data_classes": ["personal"]}}
print(" ", pe.enforce(policies, inventory, audit, req, lambda amount: f"refunded {amount}"))
req["args"]["amount"] = 4000
print(" ", pe.enforce(policies, inventory, audit, req, lambda amount: f"refunded {amount}"))

print(f"\naudit records: {len(audit.records)}, chain valid: {audit.verify()}")
audit.records[3]["decision"]["effect"] = "allow"       # someone edits history
print(f"after editing record 3: chain valid: {audit.verify()}")
Output · real19 lines
support-bot reads an order             allow ['P1-read-tools']
support-bot refunds 80                 allow ['P3-small-refunds']
support-bot refunds 100.01             deny  no policy permits this (default deny)
support-bot refund with no amount      deny  no policy permits this (default deny)
support-bot refund in dev env          deny  no policy permits this (default deny)
faq-bot tries a refund (autonomy 1)    deny  no policy permits this (default deny)
faq-bot opens a ticket                 deny  no policy permits this (default deny)
support-bot deletes a customer         deny  ['F1-never']
support-bot, secret in context         deny  ['F2-secrets']
unknown agent                          deny  agent is not in the inventory
retired agent                          deny  agent status is retired
tool nobody wrote a rule for           deny  no policy permits this (default deny)

enforcement point:
  {'ok': True, 'result': 'refunded 40'}
  {'ok': False, 'error': 'denied: no policy permits this (default deny)', 'matched': []}

audit records: 14, chain valid: True
after editing record 3: chain valid: False

Check each row against the policies. 80 is under the cap and allowed. 100.01 is not. A refund with no amount is denied rather than treated as zero. A refund in dev is denied because P3 lists only prod and staging. The FAQ bot's refund fails the autonomy floor and its ticket request fails because P2 names only support-bot. customer_delete hits F1-never even though support-bot has other permits. The unknown and retired agents are stopped by the inventory before any policy is read. The last row, a tool nobody wrote a rule for, shows default deny doing its job: a new tool is unusable until someone writes a permit for it, which is exactly when a human should be thinking about it.

The two enforce rows show the enforcement point: with 40 the tool function ran and returned a result, and with 4000 it never ran. A denial returns a message the model can read ("denied: ...") instead of raising, so the agent can explain it or ask a human (08A.7 shows how error results should be shaped).

The last two lines are the audit chain: 14 records were written, verify() says the chain is intact, and after someone edits record 3 it says it is not. Each record stores the hash of the one before it, so changing history breaks every later hash. This is tamper-evident, not tamper-proof: someone who can rewrite the whole file can rewrite the whole chain. Real systems also ship records to write-once storage (11C.4, 2.5).

3.6 Tests for policies#

A policy file is changed by people under time pressure, and a typo in a policy is a security bug. So the policies get tests, and the tests are not "does it allow the thing I want" but "does it deny everything else".

python
# test_policy.py: tests for the policies themselves (run: python3 -m unittest -v test_policy)
import copy
import json
from pathlib import Path
import unittest

import policy_engine as pe

INV = {a["id"]: a for a in json.loads(Path("agent_inventory.json").read_text())}
POLICIES = pe.load_policies("policies.json")


def req(agent, tool, args=None, env="prod", classes=("personal",)):
    return {"agent": agent, "tool": tool, "args": args or {}, "context": {"env": env, "data_classes": list(classes)}}


def effect(request, policies=POLICIES):
    return pe.decide(policies, INV, request)["effect"]


class DefaultDeny(unittest.TestCase):
    def test_unlisted_tool_is_denied(self):
        self.assertEqual(effect(req("support-bot", "export_all_orders")), "deny")

    def test_unknown_and_retired_agents_are_denied(self):
        self.assertEqual(effect(req("shadow-agent", "kb_search")), "deny")
        self.assertEqual(effect(req("old-summarizer", "kb_search")), "deny")

    def test_empty_policy_set_denies_everything(self):
        self.assertEqual(effect(req("support-bot", "kb_search"), []), "deny")


class Conditions(unittest.TestCase):
    def test_refund_cap_boundary(self):
        self.assertEqual(effect(req("support-bot", "refund_issue", {"amount": 100})), "allow")
        self.assertEqual(effect(req("support-bot", "refund_issue", {"amount": 100.01})), "deny")

    def test_missing_or_wrong_type_amount_fails_closed(self):
        self.assertEqual(effect(req("support-bot", "refund_issue", {})), "deny")
        self.assertEqual(effect(req("support-bot", "refund_issue", {"amount": "40"})), "deny")

    def test_autonomy_floor(self):
        self.assertEqual(effect(req("faq-bot", "refund_issue", {"amount": 5})), "deny")

    def test_environment_condition(self):
        self.assertEqual(effect(req("support-bot", "refund_issue", {"amount": 5}, env="dev")), "deny")


class ForbidWins(unittest.TestCase):
    def test_forbid_beats_a_broad_permit(self):
        broad = POLICIES + [{"id": "T-oops", "effect": "permit", "tools": ["customer_delete"]}]
        self.assertEqual(effect(req("support-bot", "customer_delete"), broad), "deny")

    def test_secrets_forbid_applies_to_allowed_tools(self):
        self.assertEqual(effect(req("support-bot", "orders_get", classes=("secrets",))), "deny")


class PolicyFiles(unittest.TestCase):
    def write(self, tmp, policies):
        path = tmp / "p.json"
        path.write_text(json.dumps(policies))
        return str(path)

    def test_bad_policy_files_fail_at_load_time(self):
        import pathlib
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            tmp = pathlib.Path(d)
            for bad in (
                [{"id": "a", "effect": "allow", "tools": ["x"]}],                       # wrong effect word
                [{"id": "a", "effect": "permit"}],                                       # wildcard permit
                [{"id": "a", "effect": "permit", "tools": ["x"], "when": {"maxamount": 1}}],  # typo'd key
                [{"id": "a", "effect": "forbid"}, {"id": "a", "effect": "forbid"}],      # duplicate id
            ):
                with self.assertRaises(ValueError):
                    pe.load_policies(self.write(tmp, bad))


class Audit(unittest.TestCase):
    def test_chain_detects_edits_and_later_mutation_of_the_request(self):
        log, r = pe.AuditLog(), req("support-bot", "kb_search")
        for _ in range(3):
            log.append(r, pe.decide(POLICIES, INV, r))
        r["tool"] = "something_else"                 # caller mutates its own dict afterwards
        self.assertTrue(log.verify())
        tampered = copy.deepcopy(log)
        tampered.records[1]["request"]["agent"] = "someone-else"    # edit history
        self.assertFalse(tampered.verify())


if __name__ == "__main__":
    unittest.main()

Run it:

bash
python3 -W error -m unittest -v test_policy
Output · real16 lines
test_chain_detects_edits_and_later_mutation_of_the_request (test_policy.Audit.test_chain_detects_edits_and_later_mutation_of_the_request) ... ok
test_autonomy_floor (test_policy.Conditions.test_autonomy_floor) ... ok
test_environment_condition (test_policy.Conditions.test_environment_condition) ... ok
test_missing_or_wrong_type_amount_fails_closed (test_policy.Conditions.test_missing_or_wrong_type_amount_fails_closed) ... ok
test_refund_cap_boundary (test_policy.Conditions.test_refund_cap_boundary) ... ok
test_empty_policy_set_denies_everything (test_policy.DefaultDeny.test_empty_policy_set_denies_everything) ... ok
test_unknown_and_retired_agents_are_denied (test_policy.DefaultDeny.test_unknown_and_retired_agents_are_denied) ... ok
test_unlisted_tool_is_denied (test_policy.DefaultDeny.test_unlisted_tool_is_denied) ... ok
test_forbid_beats_a_broad_permit (test_policy.ForbidWins.test_forbid_beats_a_broad_permit) ... ok
test_secrets_forbid_applies_to_allowed_tools (test_policy.ForbidWins.test_secrets_forbid_applies_to_allowed_tools) ... ok
test_bad_policy_files_fail_at_load_time (test_policy.PolicyFiles.test_bad_policy_files_fail_at_load_time) ... ok

----------------------------------------------------------------------
Ran 11 tests in 0.007s

OK

The tests cover the five rules from 3.2: default deny (an unlisted tool, an unknown agent, an empty policy set), conditions that fail closed (the cap boundary, a missing amount, a string amount), forbid beating a deliberately broad permit, bad policy files refused at load, and the audit chain detecting edits. Run them in CI on every change to policies.json. The most useful habit: when an incident shows a request that should have been denied, add it as a test first, then fix the policy.


Part 4: OPA (Rego) and Cedar, the real engines#

Deep-dive

The engine above is a teaching tool. For a real system you will often want a maintained policy engine with a proper language, tooling and a community. Two are widely used. This part shows the same policies in each and what to check before you choose. Everything here was checked against the projects' official documentation on 1 December 2026, and the snippets are illustrative and not run in this lesson: installing and running a policy engine is outside the keyless, no-services scope.

4.1 Open Policy Agent and Rego#

Open Policy Agent (OPA) is a general-purpose policy engine. It is a CNCF graduated project (announced 4 February 2021, CNCF announcement). Its policy language is Rego, which the docs describe as a declarative language for reasoning over structured data such as API requests and configuration (policy language docs). A rule reads as "name is value if the body is true". The request arrives as the input document, other data (such as your inventory) can be loaded as data, and the docs show the default-deny pattern as default allow := false followed by allow if { ... } rules.

The same policies as above, in Rego. Rego has no built-in "forbid wins", so the example writes it explicitly with a forbidden rule that each allow rule checks.

rego
# agents_tools.rego -- illustrative, not run in this lesson (OPA 1.x syntax as in the docs)
package agents.tools

default allow := false

# P1: any active agent may call the read tools
allow if {
    agent := data.agents[input.agent]
    agent.status == "active"
    input.tool in {"kb_search", "orders_get"}
    not forbidden
}

# P3: small refunds, support-bot only, autonomy 3 or more, prod or staging
allow if {
    agent := data.agents[input.agent]
    agent.status == "active"
    input.agent == "support-bot"
    agent.autonomy >= 3
    input.tool == "refund_issue"
    is_number(input.args.amount)
    input.args.amount <= 100
    input.context.env in {"prod", "staging"}
    not forbidden
}

# F1 and F2
forbidden if input.tool in {"customer_delete", "shell_exec", "server_delete"}
forbidden if "secrets" in input.context.data_classes

Tests are Rego too. Per the docs, a test is a rule whose name starts with test_, and opa test runs them; the with keyword overrides input and data for one expression:

rego
# agents_tools_test.rego -- illustrative, not run in this lesson
package agents.tools_test

import data.agents.tools

agents := {"support-bot": {"status": "active", "autonomy": 3}}

test_refund_at_cap_allowed if {
    tools.allow with input as {"agent": "support-bot", "tool": "refund_issue",
        "args": {"amount": 100}, "context": {"env": "prod", "data_classes": ["personal"]}}
        with data.agents as agents
}

test_refund_over_cap_denied if {
    not tools.allow with input as {"agent": "support-bot", "tool": "refund_issue",
        "args": {"amount": 100.01}, "context": {"env": "prod", "data_classes": ["personal"]}}
        with data.agents as agents
}

You would run them with opa test . -v. What OPA gives you beyond the stdlib engine: a real language with rich built-ins, a test runner, bundles for distributing policy, decision logging, and integrations across the cloud-native world (it is widely used for Kubernetes admission and API authorization). What it costs: a new language for the team to learn, and an engine to run, either embedded or as a sidecar or service.

4.2 Cedar#

Cedar is a language for writing authorization policies and making authorization decisions based on them (Cedar docs). Its reference implementation is written in Rust under the Apache-2.0 licence (repository), and Amazon Verified Permissions is a managed service that uses it. Cedar joined the CNCF as a Sandbox project (per AWS's announcement and InfoQ's report, January 2026; we found no later maturity change, so check the CNCF landscape for the current level).

Unlike Rego, Cedar bakes the semantics we built by hand into the language. The evaluation rules on the docs page are: no request is allowed unless a permit policy grants it (default deny); if any forbid policy is satisfied the result is deny, even if a permit is also satisfied (forbid wins); and if no policy is satisfied the result is deny. A policy has a scope (principal, action, resource) and optional when and unless conditions.

cedar
// agent_policies.cedar -- illustrative, not run in this lesson
permit (
    principal == Agent::"support-bot",
    action == Action::"call_tool",
    resource == Tool::"refund_issue"
)
when {
    principal.autonomy >= 3 &&
    context.amount <= 100 &&
    ["prod", "staging"].contains(context.env)
};

forbid (
    principal,
    action == Action::"call_tool",
    resource
)
when {
    ["customer_delete", "shell_exec", "server_delete"].contains(resource.name)
};

4.3 Which to use#

Your own small engine (this lesson) OPA and Rego Cedar
Best for One service, few policies, teaching, no new dependency Many services, mixed policy types (infrastructure, APIs, agents), a platform team Application-level authorization with a fixed model of principals, actions and resources
Language JSON data, Python code Rego, general-purpose and powerful, a learning curve Cedar, small and restricted by design (analysable)
Default deny and forbid wins Written by you Written by you (default allow := false, a forbidden rule) Built into the evaluation
Tests unittest opa test Written by you against the engine's API
Operational cost None An engine to run (embedded or service) A library, or a managed service

A reasonable path: start with the small engine or with a provider's built-in permission features while you have one or two agents, and move to OPA or Cedar when policies need to be shared across services or reviewed by a team that is not the agent's developers. The concepts (data, default deny, forbid wins, fail closed, tests) transfer unchanged. Keep the inventory as the source of agent facts, whichever engine reads them.


Part 5: Enforcement points and the audit trail#

This part extends 08A.14, 2.1 (defence in depth for agents) and 12.6 (least-privilege credentials per tool) with where a policy decision is actually enforced and what each decision logs.

A policy that nobody enforces is a document. A policy enforcement point (PEP) is the place in the call path where the decision is applied, and its defining property is that no tool call can happen without passing through it. There are four natural places, from nearest the agent to farthest.

Enforcement point Where it sits Strength Weakness
Tool dispatcher In the agent's own process: the function that runs a tool after the model asks (08A.7, 1.2). enforce() in Part 3 is this Simple, has full context about the request Only protects agents that use this code; a second agent written differently skips it
Tool gateway A shared service between agents and tools: every agent's tool call goes through one proxy One place for all agents, all languages; policy and audit are central A new moving part; must be the only path to the tools
MCP gateway The same idea for the Model Context Protocol: a gateway in front of many MCP servers that authenticates the agent, applies policy per server and tool, and logs. 08E.3 teaches gateways, OAuth and many servers Covers every MCP tool the organisation exposes, including third-party servers Only governs MCP traffic, not tools called in other ways
Backend authorization The tool's own system (the database, the payments API) checks the credential the agent holds, with scopes narrowed per agent (12.6, 2.2) The last line of defence; works even if everything above is bypassed Coarse: it knows the credential, not the agent's purpose or the argument values

Use more than one. The dispatcher gives rich, argument-level checks. The gateway gives organisation-wide coverage and audit. The backend scopes limit the damage if a layer above has a bug. This is defence in depth (08A.14, 2.1) applied to policy.

The enforcement point's own rules.

  • Be the only path. If the agent can also call the tool another way (a direct SDK client with its own credentials), the policy is decoration. Give the agent credentials that work only through the gateway.
  • Fail closed. If the engine times out, errors or cannot load policies, deny. A fail-open gateway turns an outage of the policy service into a free pass.
  • Pass in the facts. The request carries the agent id (from authentication, not from the model's text), the tool, the arguments and the context (environment, data classes). Agent attributes such as autonomy and tier come from the inventory, never from the request, because the request is what an attacker influences.
  • Return a readable denial. The model should hear "denied: no policy permits this" and be able to ask a human, not crash.

What every decision logs. An audit record answers "who tried what, with which arguments, what was decided, and by which policy". Log the agent id, tool, a hash or redacted copy of the arguments (not secrets or raw personal data, see 14A.7), the decision, the matched policy ids, a timestamp and the policy file's version (a git commit id). With the version, "what was allowed on 14 October" becomes a lookup. Log denials as carefully as allows: a spike in denials for one agent is often the first sign of prompt injection or of a bug (11A.3 covers audit logs and alerting, and 11C.4, 2.5 the append-only requirement).


Part 6: Evaluate it#

This lesson's claims are testable: the policy layer allows what it should and denies everything else, the tiering rubric puts agents in the right tier, and the inventory matches what actually runs. Evaluation has two layers, as in 08A.1, Part 4: deterministic checks of your own governance code (cheap, run on every commit), and measurements of a real model's behaviour under those controls (sampled, with intervals).

6.1 Where to read first#

Start with the concept lessons, then the tooling.

Then the DeepEval lessons (required track):

Then the optional Inspect lessons:

6.2 What to measure for this lesson#

What How Typical pass rule
Policy conformance A table of (request, expected decision) cases, including everything that must be denied Zero mismatches. This tests your policy code, not the model
Policy test sensitivity (mutation) Break a policy on purpose (raise a cap, delete a forbid) and confirm the table notices Every mutation fails at least one case
Tier accuracy Agents with a known right tier, run through the classifier Every agent at or above its expected tier. A lower tier is a failure; a higher one is a discussion
Inventory completeness Agent ids seen in gateway logs versus ids in the inventory Zero unregistered ids making tool calls
Agent attempts under policy Run a real or scripted agent over tasks and count calls that policy denied Reported with an interval. A rising denial rate is a signal of drift or an attack, not a pass or fail by itself
Cost per successful task Spend divided by successes (10A.7, 5.6) Reported with success, so control layers are not mistaken for free

6.3 A concrete tiny eval#

Inputs: twelve requests with the expected decision for each, including edge cases (the cap boundary, a missing amount, a wrong environment, an unregistered agent). Metric: mismatches between expected and actual decisions. Pass rule: zero mismatches on the real policies, and at least one mismatch for every deliberate mutation of the policies. An eval that cannot fail proves nothing.

python
# policy_eval.py
import copy
import json
from pathlib import Path

import policy_engine as pe

INV = {a["id"]: a for a in json.loads(Path("agent_inventory.json").read_text())}
POLICIES = pe.load_policies("policies.json")


def req(agent, tool, args=None, env="prod", classes=("personal",)):
    return {"agent": agent, "tool": tool, "args": args or {}, "context": {"env": env, "data_classes": list(classes)}}


CASES = [   # (name, request, expected)
    ("read order",              req("support-bot", "orders_get", {"order_id": "A17"}), "allow"),
    ("refund at cap",           req("support-bot", "refund_issue", {"amount": 100}), "allow"),
    ("refund just over cap",    req("support-bot", "refund_issue", {"amount": 100.01}), "deny"),
    ("refund huge",             req("support-bot", "refund_issue", {"amount": 5000}), "deny"),
    ("refund no amount",        req("support-bot", "refund_issue"), "deny"),
    ("refund in dev",           req("support-bot", "refund_issue", {"amount": 5}, env="dev"), "deny"),
    ("low-autonomy refund",     req("faq-bot", "refund_issue", {"amount": 5}), "deny"),
    ("delete customer",         req("support-bot", "customer_delete"), "deny"),
    ("secrets in context",      req("support-bot", "orders_get", classes=("secrets",)), "deny"),
    ("unregistered agent",      req("shadow-agent", "kb_search"), "deny"),
    ("retired agent",           req("old-summarizer", "kb_search"), "deny"),
    ("tool with no rule",       req("support-bot", "export_all_orders"), "deny"),
]


def run(policies):
    return [name for name, r, expected in CASES if pe.decide(policies, INV, r)["effect"] != expected]


def mutate(policies, kind):
    p = copy.deepcopy(policies)
    if kind == "raise the cap":
        next(x for x in p if x["id"] == "P3-small-refunds")["when"]["max_amount"] = 1000
    elif kind == "drop the forbid on deletes":
        p = [x for x in p if x["id"] != "F1-never"] + [{"id": "M", "effect": "permit", "tools": ["customer_delete"]}]
    elif kind == "drop the env check":
        del next(x for x in p if x["id"] == "P3-small-refunds")["when"]["env_in"]
    elif kind == "add a broad read permit":
        p.append({"id": "M", "effect": "permit", "tools": ["export_all_orders"]})
    return p


print("real policies, mismatches:", run(POLICIES) or "none")
for kind in ["raise the cap", "drop the forbid on deletes", "drop the env check", "add a broad read permit"]:
    caught = run(mutate(POLICIES, kind))
    print(f"mutation {kind!r:32s} caught by: {caught or 'NOTHING (the eval is blind to this)'}")
Output · real5 lines
real policies, mismatches: none
mutation 'raise the cap'                  caught by: ['refund just over cap']
mutation 'drop the forbid on deletes'     caught by: ['delete customer']
mutation 'drop the env check'             caught by: ['refund in dev']
mutation 'add a broad read permit'        caught by: ['tool with no rule']

All four mutations are caught, and each is caught by a different case, which is the sign that the table covers different failure modes. The "forbid dropped" mutation also adds a broad permit so that deleting the forbid really does allow the call; without that, default deny would hide the mutation, which is itself a nice demonstration that default deny is a safety net. Try your own mutation (Exercise 3) and see whether the table notices.


Common misconceptions#

  • "An inventory is a spreadsheet for auditors." The useful one is a file that code reads: CI validates it and the policy engine takes agent facts from it. A list nobody enforces goes stale.
  • "Risk tier is a property of the model." It comes from the tools, the autonomy level and the data the agent can reach. The same model can be a low-tier and a critical-tier agent.
  • "A high tier means we cannot ship it." It means the agent needs more controls and more approvals first. Many valuable agents are high tier and run safely.
  • "The prompt says it must not do that, so policy is covered." A prompt is a request. A policy decision is made by code that runs whatever the model says.
  • "Default deny will block our developers." It blocks unreviewed access. The cost is one permit line and a test when a new tool is added, which is the moment a person should look anyway.
  • "We use OPA, so we are safe." An engine enforces the policies you write, at the points you wire it in. Policies can still be too broad, and an agent with a second path to the tool bypasses any engine.
  • "Retiring an agent means deleting the code." Retiring means revoking tools and keys and keeping the record. A deleted repository with live credentials is still an agent.
  • "Policy tests prove the agent is safe." They prove the decision function is right for the requests you tried. What the agent will ask for is measured by evals.

Key takeaways#

  • An agent inventory records, per agent: owner (a team), purpose, pinned model, tools, data classes, autonomy level, risk tier, approvals, eval evidence and a review date.
  • The inventory is data that code reads, validated in CI, with a lifecycle of register, review and retire. Retire means revoke access and keep the record.
  • Risk tier = impact x autonomy x data sensitivity, with floors that only raise it. Impact comes from tools, autonomy from configuration, sensitivity from the data. Secrets are an error, not a tier.
  • The tier decides the controls, cumulatively: more evals, approvals, red teaming, policy enforcement, kill switches and review as the tier rises.
  • Policy-as-code means policies are versioned data with default deny, forbid wins, fail closed and tests. Agent facts come from the inventory.
  • OPA/Rego and Cedar are real engines; the concepts transfer. Cedar builds default deny and forbid-wins into the language; in Rego you write them. A missing attribute can make a forbid silently not fire.
  • Enforce at a point that cannot be bypassed (dispatcher, tool gateway, MCP gateway, backend scopes), fail closed, and log every decision with the policy version.
  • Evaluate the policy layer with a table of requests and a mutation check, and keep policy tests separate from model evals.

Terms introduced in this lesson#

Term Meaning
Agent inventory The single data file listing every agent with its owner, purpose, model, tools, data, autonomy, risk tier, approvals, evidence and review date
Shadow agent An agent that runs but is not in the inventory
Orphan agent An agent whose owner is gone or whose review is overdue, but whose access still works
Registration Writing an inventory entry before an agent gets tools; the entry starts as proposed
Review A scheduled or triggered check that an entry still matches reality
Retirement Setting an agent's status to retired, revoking its tools and keys, and keeping the record
Risk tier A label (low, medium, high, critical) saying how much control an agent needs
Risk floor A rule that raises a tier for a combination the product underrates
Required controls The cumulative list of controls a tier must have in place
Policy-as-code Access rules written as versioned, reviewed, tested, machine-enforced data
Default deny Nothing is allowed unless a policy explicitly permits it
Forbid wins An explicit forbid overrides any permit
Fail closed When the answer is unknown or an error occurs, the result is deny
Policy decision point (PDP) The function that returns allow or deny for a request
Policy enforcement point (PEP) The place in the call path where the decision is applied, and which no call can skip
Tool gateway A shared proxy through which every agent's tool calls pass, applying policy and audit centrally
MCP gateway A gateway in front of many MCP servers that authenticates, applies policy per tool and logs
Rego The declarative policy language of Open Policy Agent
Cedar A policy language with permit and forbid policies and built-in default deny and forbid-wins semantics
Tamper-evident log A log where each record includes the previous record's hash, so edits are detectable
Policy mutation check Deliberately breaking a policy to confirm the policy eval notices

Exercises#

  1. A new agent. Add a reporting-bot to agent_inventory.json: autonomy 2, read-only tools, internal data, owner team-data. What tier does the checker compute, and which controls does it need? Make the checker pass. Hint: put orders_get and kb_search in tools (both impact 1), compute 1 x 2 x 2 = 4, which is low, so it needs only inventory and tracing. Set reviewed_on to a date within 365 days and add one approval.
  2. Climb the ladder. Raise faq-bot to autonomy 3 and give it refund_issue and ticket_create. What does the checker say now? List every new requirement. Hint: impact becomes 3 (3 x 3 x 1 = 9, medium) and the checker will ask for the medium-tier controls. Add personal data and the product becomes 27, high, which needs two approvals, red teaming and a kill switch.
  3. Break the policies. Invent a fifth mutation of policies.json for policy_eval.py (for example, change min_autonomy on P3 from 3 to 1). Does the table catch it? If not, add the case that does. Hint: this mutation survives. No case has an agent named in P3's ids at a low autonomy level, because support-bot is at 3 in the inventory. Give policy_eval.py a per-case inventory override (a copy of INV where support-bot has autonomy 2) and add a case that expects deny.
  4. A tool gateway. Write gateway.py with a function call_tool(agent_id, tool, args) that looks the agent up in the inventory, builds the request and calls enforce. Make it fail closed when policy_engine.decide raises. Hint: wrap the call in try/except Exception and return the same shape as a denial. Test it by passing decide a policy list that contains a malformed entry that bypassed load_policies, such as {"id": "x", "effect": "permit", "tools": ["kb_search"], "agent": {"min_autonomy": "high"}}: comparing a number with a string raises TypeError, and the gateway must turn that into a denial.
  5. Rego by hand. Translate P2-tickets (only support-bot, data classes at most personal) into Rego, and write one passing and one failing test_ rule. You do not need to run it. Hint: Rego has no ordering of strings, so write the allowed set explicitly: every c in input.context.data_classes { c in {"public", "internal", "personal"} }. Check the syntax against the OPA policy language page.
  6. Drift report. Write a script that takes a list of agent ids seen in gateway logs and the inventory, and prints unregistered ids, registered-but-silent ids and ids whose log activity shows tools not listed in the inventory. Hint: three set operations (seen - registered, registered - seen, and used_tools - listed_tools per agent). Silent active agents are candidates for retirement.

Check yourself#

  1. Why is the owner field a team and not a person?
  2. Name the ten fields an agent inventory entry should have, or at least eight of them.
  3. What three actions does "retire" require, beyond changing a status field?
  4. What are the three factors of the risk rubric, and where does each come from?
  5. Why does the rubric multiply the factors instead of taking the maximum?
  6. What is a risk floor, and why does the cost cleaner example need one?
  7. Name the four properties of a good policy layer besides "policies are data".
  8. In Cedar, why can a missing attribute make a forbid policy fail open?
  9. Give two differences between a tool dispatcher and a tool gateway as enforcement points.
  10. What should a policy audit record contain, and why include the policy file's version?

Further resources#


← 14A.5 — The Incident Process for AI Systems | Module 14A overview | 14A.7 — Data, Vendor and Supply-Chain Governance, plus NIST AI RMF and ISO/IEC 42001 Awareness →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close