Skip to content

Policy language

Policies are YAML files of rules: a condition, an effect, a reason. This page lists every field and condition, the shipped packs rule by rule, grants and their limits, business rules, imported policies, and how to roll out a change.

The document

FieldValuesDefaultMeaning
keytextrequiredUnique id. A project pack with the key of a shipped pack replaces it.
name, descriptiontext""For people.
versioninteger1The first stored version number. Saving a changed body stores a new immutable version; decisions record the version in force.
modeobserve | enforceobserveThe mode the pack is bound in when first loaded. Afterwards the binding decides (agentfox policy enforce / observe).
default_effectan effectallowThe verdict when no rule fires.
fail_modeopen | closedopenWhat a detector timeout or error does to this pack's checks: see fail_mode.
scope{agents: [globs], environments: [names]}{}Which agents and environments the pack applies to at runtime. Empty means all.
ruleslist[]The rules.

A rule

FieldDefaultMeaning
idrequiredUnique within the pack, dotted by family: billing.large_export. Decisions, findings and the explanation name it.
description""For authors.
whenmatches everythingA condition. Every field present must match; absent fields are ignored.
effectblockSee effects.
reasongeneratedShown to the caller and written to the audit log. Write it for a person. When empty, one is generated from what matched.
severitymediumcritical, high, medium or low. Becomes the finding's severity.
controls[]Control ids this rule is evidence for, in the compliance catalog.
enabledtrueA disabled rule never fires (and lint says so).
redactionmaskThe style used when the effect is redact, mask or tokenize.
overridablefalseWhether a narrower level of the hierarchy may weaken this rule.

Effects

When several rules fire, across all bound packs, the strongest effect wins:

allow < tokenize < mask < redact < abstain < escalate < block
EffectWhat happens when enforced
allowNothing. A rule that allows cannot cancel a stronger rule elsewhere.
tokenize, mask, redactThe matched spans are replaced and the call goes on with the rewritten content.
abstainThe answer is withheld without treating the user as an attacker.
escalateAn approval is created and the call waits for a person (ApprovalRequired, HTTP 202).
blockRefused (PolicyViolation, agentfox.Blocked, HTTP 403).

In observe a pack still evaluates and records what it would have done: the decision's verdict is allow and its effective_verdict is the strongest effect that fired. That difference is what agentfox findings reports as "would have been blocked".

How a tool call is decided

  1. Which agent is calling, and is it stopped (quarantine or kill switch)?
  2. Does it hold a grant for the tool, and do the arguments fit its limits? No grant: refused.
  3. What is the tool's impact, and the provenance of its arguments? Untrusted values in an irreversible call escalate.
  4. Composition (a value from one tool passed into a higher-impact one), declared intent, loops and budget.
  5. What the detectors found in the arguments, under each detection rule's pack mode.

The strongest effect wins and is written to the audit chain. Steps 2 and 3 read no text, so they hold when a detector misses. Content is checked on nine surfaces.

Provenance

LevelThe value came from
noneNo external origin.
userThe user's message.
retrievedA retrieved document.
tool_resultAnother tool's output, such as a fetched page.
subagentAnother agent.
memoryThe agent's long-term memory.

Ordered from most to least trusted; everything after user is untrusted. auto() reads it from the conversation (a value copied out of a role="tool" message is a tool result); over HTTP the caller declares it (provenance, X-AgentFox-Trust), and what is declared is believed.

Conditions (when)

KeyTypeMatches when
surfacelistThe content is on one of these surfaces: input, output, tool_args, tool_result, retrieved, memory_write, agent_message, completion, reasoning. See surfaces.
environmentlistThe call's environment is listed.
agentglobThe agent slug matches, e.g. support-*.
risk_tierlistThe agent's risk tier is listed: minimal, limited, high, prohibited.
toolglobThe tool key matches, e.g. billing.* or mcp:helpdesk/*.
tool_impactlistThe tool's declared impact is listed: read, write, high_impact, irreversible.
tool_knownboolfalse matches a tool the registry has never seen.
detectionobjectAt least min_count (default 1) detections scored at or above min_score (default 0.5) whose entity equals entity (e.g. PII.CREDIT_CARD) or starts with entity_prefix (e.g. INJECTION). Entity types are listed in Detectors.
argumentobjectThe tool argument at path (dotted, with [0] for list items) compared with value by op: eq, ne, gt, gte, lt, lte, in, not_in, contains (case-insensitive substring), matches (regular-expression search). A missing argument never matches.
taint_exceedslevelThe worst provenance of the call's content or arguments is above this level, in the order none < user < retrieved < tool_result < subagent < memory.
capabilitystateThe grant check came out denied (no grant), constraint_violated (a grant, but an argument outside its limit), requires_approval or granted.
action_operationlistWhat an SQL, shell or HTTP argument does: read, write, destructive, admin, unknown.
blast_radius_at_leastlevelThe estimated blast radius is at least this, in the order none < bounded < unknown < unbounded < catastrophic.
action_reversibleboolThe analysed action is (or is not) reversible.
action_riskglobAny risk code found in the call matches, e.g. sql.*, shell.destructive, remote-code-execution, unscoped-table, control_flow.*, crescendo.trajectory_drift. Codes appear in a decision's explanation.
budget_exceededboolThe agent's call, token, spend or depth budget is exhausted.
loop_detectedboolThe loop governor saw a repeating call with no progress.
intent_declaredboolThe caller did (or did not) declare a task intent.
detector_degradedboolA detector timed out, errored or was skipped for budget on this call.
completion_requireslistOn the completion surface: any named fact was not reported as true by the caller. Scope the rule with surface: [completion].
exprtextAn escape hatch: a Python expression over agent, surface, tool, impact, risk_tier, environment, n_detections, max_score, prior_tool_count, taint, with no builtins. Lint cannot reason about it and it does not compile to Rego meaningfully; avoid it.

Refusals that are not policy rules

Some refusals happen whatever mode your packs are in, because they are facts about the call rather than opinions: a capability check with no grant (default deny once the agent holds any grant, and always in the SDK and gateway), a critical action risk such as shell.destructive or sql.unbounded_mutation, an SQL argument that cannot be analysed because the [sql] extra is missing (analysis.unavailable, which fails closed), composed privilege escalation, and MCP schema drift. With tool-containment demoted to observe, both of these still block:

Output
db.query PolicyViolation [('analysis.unavailable', 'enforce')]
shell.run PolicyViolation [('shell.destructive', 'enforce')]

With sqlglot installed (pip install "agentfox[sql]") the same DELETE FROM tickets is analysed and refused as sql.unbounded_mutation instead.

The shipped packs

agentfox init loads agent-integrity, baseline, eu-ai-act-high-risk and tool-containment, every one watching (observe) until you turn it to blocking with agentfox policy enforce <key>; a pack someone switched to blocking stays blocking when init or up runs again. In policy packs the mode is the one the file declares; in policy list it is the one in force. coding-agent is loaded only for agents with coding-agent hooks installed (agentfox admin hooks install, see Coding agents).

bash
agentfox policy packs
agentfox policy list
Output
pack                 origin   mode     rules  file
agent-integrity      shipped  observe  3      …/agentfox/packs/agent-integrity/policies/agent-integrity.yaml
baseline             shipped  observe  13     …/agentfox/packs/baseline/policies/baseline.yaml
coding-agent         shipped  observe  10     …/agentfox/packs/coding-agent/policies/coding-agent.yaml
eu-ai-act-high-risk  shipped  observe  7      …/agentfox/packs/eu-ai-act/policies/eu-ai-act-high-risk.yaml
tool-containment     shipped  enforce  26     …/agentfox/packs/tool-containment/policies/tool-containment.yaml

policy               version  mode     rules
agent-integrity      v1       observe  3
baseline             v1       observe  13
eu-ai-act-high-risk  v1       observe  7
tool-containment     v1       observe  26

Capability packs

Each shipped policy file lives in a capability pack: a directory with a pack.yaml (id, version, maturity, owners, compliance mappings, vocabulary) and the policies, controls, business-ladder templates, red-team probes, golden cases and fixtures one use case needs. Besides these four, AgentFox ships eu-ai-act (which carries eu-ai-act-high-risk and the risk classes), compliance/catalog (the control catalog), payments/refunds and customer-support. Your own go in .agentfox/packs/; only stable packs load unless pack_maturity says otherwise.

bash
agentfox policy packs list
agentfox policy packs show payments/refunds
agentfox policy packs test
agentfox policy packs new payments/chargebacks
agentfox policy packs validate .agentfox/packs/payments/chargebacks

baseline: content guardrails (observe)

Detection-driven rules on every surface. Ships in observe: read what it would have done, then promote it.

RuleEffectSeverityWhat it does
injection.directblockhighInjection or jailbreak in the user's input, score 0.7 or more.
injection.indirectblockcriticalInjection in retrieved content or a tool result, at the lower bar of 0.6: an instruction has no business being in data.
injection.system_prompt_leakblockmediumAn attempt to extract the system prompt, on any surface.
injection.memory_and_agent_messageblockcriticalInjection in a memory write or a message from another agent.
injection.adopted_in_reasoningblockcriticalInstruction-like text in the model's own reasoning, at 0.4: evidence the model took the payload up.
secrets.blockblockcriticalA credential anywhere, in either direction, at 0.9.
pii.outbound_redactredact (mask)mediumPersonal data in a response is masked before it is delivered.
pii.inbound_tokenizetokenizemediumPersonal data in a prompt is replaced with tokens before it reaches the model.
pii.high_sensitivityblockcriticalA US Social Security number, anywhere.
pii.memory_and_agent_messageredact (mask)mediumPersonal data in a memory write or an inter-agent message is masked.
safety.harmblockhighUnsafe content (harm, self-harm, illicit, harassment, extremism).
schema.violationblockmediumA response that does not match the output schema it was declared with.
pipeline.degraded_high_riskescalatemediumA high-risk or prohibited-tier agent served while detectors were degraded.

tool-containment: what an agent may do

Rules about the action and where its arguments came from, which hold when a detector misses. The file declares enforce, but agentfox init binds it watching like every pack; agentfox policy enforce tool-containment starts it blocking. The pack cannot be loaded with control_plane.tamper removed or disabled.

Its mode also decides two checks the enforcer makes itself, listed under Tool containment on the Policies page: capability.default_deny (a tool the agent was not granted; agentfox.auto() applies it once the agent holds any grant) and composition.escalation (a value a lower-impact tool returned, used by a tool that changes more). While the pack watches, or where it is not applied, both are recorded as would-block and the call goes through. A limit or "Ask first" a person set on a grant applies at once, whatever the mode.

RuleEffectSeverityWhat it does
taint.irreversible_toolescalatecriticalAn irreversible tool whose arguments came from anything other than the user.
taint.high_impact_toolescalatehighThe same for a high-impact tool.
taint.write_from_tool_resultescalatemediumA write whose arguments were copied out of a tool result, a sub-agent or memory.
capability.deniedblockhighNo grant for this tool: default deny. The reason names the command that fixes it.
capability.constraint_violatedblockhighA grant exists, but an argument is outside a limit it declares.
capability.approval_requiredescalatemediumThe grant says a person signs off, or an argument's provenance is worse than the grant allows.
intent.undeclared_irreversibleescalatemediumAn irreversible tool call with no declared task.
budget.exceededblockmediumThe agent ran out of calls, tokens, spend or recursion depth.
loop.runawayblockmediumThe agent is repeating the same tool call without progress.
completion.unverified_claimescalatehighThe agent says it is finished without reporting that the work was verified.
completion.irreversible_unconfirmedblockcriticalA run with a destructive or admin action ends without confirmation that it succeeded.
tool.not_declaredescalatehighA tool the registry has never seen: invented by the model, or real and undeclared.
action.remote_code_executionblockcriticalA download piped straight into a shell or interpreter.
secrets.credential_fileblockhighA command touching .env, an SSH key, cloud credentials, a kubeconfig or a service-account file.
action.supply_chain_publishescalatehighPublishing a package or image.
action.infrastructure_mutationescalatehighterraform, kubectl, helm or a cloud CLI changing live infrastructure.
action.history_rewriteescalatemediumA hard reset, force clean or dropped stash.
control_plane.tamperblockcriticalA command that would switch AgentFox's own enforcement off. The pack refuses to load without it.
cascade.reaches_destructiveblockcriticalA harmless-looking call that reaches a destructive tool through its declared triggers.
cascade.reaches_notificationescalatehighA call whose declared triggers reach only a message that cannot be recalled (a tool declared effect: communication), and nothing more destructive.
cascade.cycleblockcriticalThe declared trigger graph loops.
cascade.blast_radiusescalatehighThe declared trigger graph is unusually deep or wide.
access.unscoped_tableblockcriticalA query on a table with per-customer rows and no predicate binding it to the caller.
access.undeclared_tableescalatehighA query on a table with no scope declaration.
injection.in_tool_argumentsblockcriticalInjection inside tool arguments (see the note under the table).
secrets.in_tool_argumentsblockcriticalA credential inside tool arguments.

eu-ai-act-high-risk (observe)

Measures for agents classified high (and a hard stop for prohibited). They only fire for agents whose risk tier says so. The article mappings are drafts, not legal advice.

RuleEffectSeverityWhat it does
eu.art14.human_oversightescalatehighAny irreversible tool call by a high-risk agent goes to a person.
eu.art14.no_covert_actionblockcriticalContent telling a high-risk agent to act without informing the user.
eu.art15.no_degraded_enforcementblockhighA high-risk agent served while detectors were degraded.
eu.art15.injection_resistanceblockcriticalInjection against a high-risk agent, at 0.5.
eu.art10.special_category_datablockcriticalPersonal data in a high-risk agent's prompt.
eu.art50.impersonationescalatemediumReview of an answer that claims to be a person ("I'm a real person", "I am not a bot"): the disclosure.claims_human risk. Lexical, so it escalates rather than blocks.
eu.art5.prohibited_tierblockcriticalAn agent classified prohibited is refused on every call.

coding-agent (observe)

Lower thresholds for an agent that reads diffs and runs shell commands on a developer's machine.

RuleEffectSeverityWhat it does
code.injection_in_fetched_contentblockcriticalInjection in a tool result or fetched content, at 0.5 rather than 0.6.
code.secret_in_fetched_contentblockhighA credential coming back from a tool, at 0.7: once it is in context it can leak later.
code.injection_adoptedescalatecriticalA directive in the model's reasoning, at 0.3.
code.injection_in_operator_turnescalatemediumInjection in the operator's own turn, usually a pasted log or issue.
code.pii_out_of_a_developer_machineescalatehighPersonal data in a tool call's arguments from a coding session.

Write and load your own

Put a YAML file in .agentfox/policies/ at the root of your repository. agentfox init (safe to run again) loads it alongside the shipped packs, and it travels with the code through review like anything else. A file whose key equals a shipped pack's replaces that pack. It is loaded watching, whatever its mode: says; promote it with agentfox policy enforce <key>. agentfox init --server (an account) does not load these files: a setup key only maps the agent, so it lists them and prints the command that loads each one with your account key.

.agentfox/policies/support-desk.yaml
key: support-desk
name: Support desk rules
description: Rules for the agents that answer customer tickets.
version: 1
mode: enforce
fail_mode: open
scope:
  agents: ["support-*"]

rules:
  - id: email.outside_domain
    description: Email to an address outside example.com needs a person.
    when:
      tool: email.send
      argument: {path: to, op: matches, value: "@(?!example\\.com$)"}
    effect: escalate
    severity: high
    reason: "Email to a recipient outside example.com; a person must approve it."

  - id: billing.large_export
    description: Exports over 10,000 rows are refused.
    when:
      tool: "billing.*"
      argument: {path: rows, op: gt, value: 10000}
    effect: block
    severity: high
    reason: "Billing exports are capped at 10,000 rows."

  - id: crm.write_from_untrusted
    description: A CRM write whose arguments came from a web page or a tool result.
    when:
      tool: "crm.*"
      tool_impact: [write, high_impact, irreversible]
      taint_exceeds: user
    effect: escalate
    severity: high
    reason: "CRM write carries data the user did not type."

  - id: output.card_number
    description: A card number never goes back to a customer.
    when:
      surface: [output]
      detection: {entity: PII.CREDIT_CARD, min_score: 0.9}
    effect: block
    severity: critical
    reason: "Card number in a reply to a customer."

Check it, load it

bash
agentfox policy validate .agentfox/policies/support-desk.yaml
agentfox init
agentfox policy lint
Output
valid — support-desk v1, 4 rules, mode=enforce
  controls: []
  compiles to 73 lines of Rego
…
  ✓ 5 policy packs loaded
      agent-integrity          observe  recorded, nothing blocked
      baseline                 observe  recorded, nothing blocked
      eu-ai-act-high-risk      observe  recorded, nothing blocked
      support-desk             observe  recorded, nothing blocked
      tool-containment         observe  recorded, nothing blocked
…
no policy issues

policy validate FILE checks one file offline: the schema, the effects and operators, that it compiles, and the full lint. policy lint FILE… lints files before they are loaded; with no file it lints every bound pack and every hierarchy layer together, so run it after init too. Lint catches a rule whose conditions can never be true, a condition naming a value no request carries (surface: [input, toolargs] still fires on input, but toolargs is a typo), duplicate ids, over-broad globs, rules with no conditions, and illegal loosening. Both exit 1 on critical or high findings, so either can gate a pull request:

.agentfox/policies/typos.yaml
key: typos
name: A pack with mistakes
mode: observe
rules:
  - id: pii.reply
    when:
      surface: [outputs]
      detection: {entity_prefix: PII}
    effect: redact
  - id: tools.everything
    when:
      tool: "*"
    effect: escalate
Output
$ agentfox policy validate .agentfox/policies/typos.yaml
invalid: typos — 1 blocking finding(s)
…
$ agentfox policy lint .agentfox/policies/typos.yaml
severity  code             rule              level  message
high      unreachable      pii.reply         org    'pii.reply' can never fire: every value in `surface` is unknown
                                                    (outputs);
medium    over-broad-glob  tools.everything  org    'escalate' applies to every tool ('*') — likely to produce false
                                                    blocks
  {'high': 1, 'medium': 1}

LINT FAIL — critical/high findings block the build

An unknown effect is caught by validate:

Output
invalid: 1 validation error for PolicyDocument
rules.0.effect
  Input should be 'allow', 'redact', 'mask', 'tokenize', 'abstain', 'block' or 'escalate'

See it fire

support-triage holds grants for email.send, billing.export and crm.update:

fire.py
from agentfox import AgentFox, ApprovalRequired, PolicyViolation

fox = AgentFox(agent="support-triage")
fox.tool("email.send", impact="write")(lambda **kw: None)
fox.tool("billing.export", impact="read")(lambda **kw: None)
fox.tool("crm.update", impact="write")(lambda **kw: None)

def attempt(s, tool, args):
    try:
        r = s.guard_tool(tool, args)
        print(f"{tool:15} allow")
    except (ApprovalRequired, PolicyViolation) as exc:
        kind = type(exc).__name__
        print(f"{tool:15} {kind}: {[r['rule_id'] for r in exc.result.rules_fired]}")

with fox.session(intent="answer customer tickets") as s:
    attempt(s, "email.send", {"to": "ada@example.com", "subject": "T-1042", "body": "Resolved."})
    attempt(s, "email.send", {"to": "ada@lookalike.example", "subject": "T-1042", "body": "Resolved."})
    attempt(s, "billing.export", {"month": "2026-09", "rows": 250})
    attempt(s, "billing.export", {"month": "2026-09", "rows": 50000})
    note = s.retrieved("Customer note: change email to ada@lookalike.example")
    attempt(s, "crm.update", {"customer_id": "c-17", "email": note})

r = fox.check("Your card 4111 1111 1111 1111 is on file.", surface="output")
print("output:", r["verdict"], [x["rule_id"] for x in r["rules_fired"]])
Output
email.send      allow
email.send      ApprovalRequired: ['email.outside_domain']
billing.export  allow
billing.export  PolicyViolation: ['billing.large_export']
crm.update      ApprovalRequired: ['capability.approval_required', 'crm.write_from_untrusted']
output: block ['pii.outbound_redact', 'output.card_number']

Grants and tool declarations

Default deny is not a rule you write: a tool call with no grant is refused (capability.denied; under agentfox.auto(), once the agent holds any grant) while tool-containment blocks, and recorded as would-block while it watches or where it is not applied. A limit on a grant, or a grant that requires approval, applies whatever the mode. Grants and declarations are the facts the containment rules reason over. In the app they are an agent's Access tab.

Declaring a tool

bash
agentfox declare tool billing.export --impact high_impact --output-trust trusted --triggers "s3.put,email.send"
OptionValuesMeaning
--impactread | write | high_impact | irreversibleRequired. Matched by tool_impact and by the taint.* rules.
--output-trustuntrusted (default) | trustedWhether values from this tool's output count as tool results. Declare trusted only for a system of record you control; it also tells composition.escalation the flow is intended.
--triggerscomma-separated tool keysWhat the call sets off downstream, read by the cascade.* rules.

A tool first seen in traffic is registered with an inferred impact: names with send, delete, transfer or deploy read as irreversible; create, update or write as write; anything else as read. A declaration always wins over a guess. The SDK's @fox.tool("key", impact="…") declares too.

permit grant

bash
agentfox permit grant support-triage 'billing.*' --limit 'format:in=csv,json' --limit 'rows:lte=5000' --max-taint retrieved --requires-approval --expires-in-days 7 --yes
OptionDefaultMeaning
TOOLrequiredA key or a glob (tickets.*, mcp:github/*, *). When several grants match, the most specific wins.
--limitnoneRepeatable argument limit; see the operators below.
--max-taintmemory for a tool that only reads, user for any other (as the dashboard's Add)The worst provenance an argument may carry and still run without approval: none, user, retrieved, tool_result, subagent, memory. Above it the call escalates. Within it, the taint.* rules defer to the grant; composition.escalation does not.
--requires-approvaloffEvery matching call goes to a person first.
--expires-in-daysno expiryThe grant stops matching after N days.
--actionevery actionLimit the grant to named actions on the tool. Repeatable.
--granted-byyouWho is accountable, recorded in the audit chain.

The agent must already exist (it appears the first time it sends traffic). Every grant and revocation (agentfox permit revoke CAP_ID) is on the audit chain. agentfox policy proposals from-traffic drafts grants from recorded calls; limits are learned only from calls no detector or provenance rule flagged, and a tool declaration needs a second approver.

Limit operators

path=value means equal; path:op=value uses an operator. Values are read as JSON where possible (1000 is a number, "1000" a string). A dotted path reaches nested arguments (recipient.country:eq=GB). A missing argument compares as null, so it fails an equality, list or numeric limit. An unknown operator is refused before anything is written.

OperatorExampleHolds when the argument is
(none) or eqregion=euexactly that value
nestatus:ne=closedanything but that value
lt, lterows:lte=5000below / at most, numerically
gt, gtepriority:gte=2above / at least, numerically
informat:in=csv,jsonone of a comma-separated list
not_inqueue:not_in=legal,securitynone of the list
containssubject:contains=tickettext containing it, case-insensitively
matchesto:matches=@example\.com$text matching a regular expression (search)

Taint scope

taint_scope (Configuration) decides what provenance the rules see for a tool call. The recorded decision always keeps the session value and notes which scope was applied.

ValueWhat policy seesTrade-off
session (default)The worst provenance anywhere in the run so far, plus the call's own arguments.Contains injections that steer an argument without copying text. Escalates more honest calls.
argumentOnly what this call's arguments were copied from.Lets honest calls through after the agent read the web. Misses an injection whose text never lands in an argument.

Business rules (threshold ladders)

A ladder bands one numeric tool argument into outcomes. It runs on the tool_args surface, after grants: a call with no grant is refused before the ladder matters. Its fired rule id is business.<key>.

credit-ladder.yaml
key: billing-credit-ladder
tool: billing.credit
field: arguments.amount
unit: USD
owner: finance
mode: observe
bands:
  - upto: 50
    outcome: allow
  - upto: 500
    outcome: verify
    verify:
      check: billing.credit_history
      expect: {credits_last_90d: {op: lt, value: 3}}
      on_fail: escalate
  - upto: 5000
    outcome: escalate
    approver_role: finance-lead
  - outcome: block
    reason: credits above $5,000 go through the finance system
FieldDefaultMeaning
keyrequiredUnique id. Applying the same key again replaces the ladder and bumps its version.
name, description, owner""For people. owner names who to ask when two ladders disagree.
toolevery toolLimit the ladder to one tool (a glob). Without it, every tool call carrying the field.
agentevery agentScope to one registered agent (also --agent on apply).
fieldrequiredDotted path into the request. Tool arguments are under arguments.
unitcountUSD, EUR, GBP, JPY, USD_CENTS, EUR_CENTS, GBP_CENTS, count, days.
modeobserveThe ladder's own mode, whatever mode the packs are in. --mode on apply overrides it.
bandsrequiredOrdered by upto, ascending. Each covers values above the previous upto, up to and including its own. The last band omits upto.
Band fieldMeaning
uptoInclusive upper bound. Omitted on the last band.
outcomeallow (default), verify, escalate, block, redact.
reason, labelShown in the decision.
approver_roleWho may approve an escalate.
verifyRequired for a verify band: check (the check key), arguments, expect (what passing looks like; absent means truthy), on_pass (default allow), on_fail and on_error (default escalate), timeout_ms (5000). AgentFox does not run the check: your code does, with agentfox.capabilities.business.run_verification.
  • When several ladders match, the strictest outcome wins. A ladder never loosens a security verdict.
  • A missing field, a negative value, text that is not a number, or a value in another currency escalates. It never passes.
  • agentfox policy rules check reports where two ladders on the same field disagree (and ladders in different units as critical), exiting 1, so it works as a CI step. policy lint does not look at ladders.
You want toRun
Save or replace a ladderagentfox policy rules apply credit-ladder.yaml
Read back the resolved bandsagentfox policy rules show billing-credit-ladder
Try values at each boundaryagentfox policy rules test billing-credit-ladder 50,50.01,5000.01
Find disagreements between laddersagentfox policy rules check
Every kind of guardrail, and one in detailagentfox policy rules explain threshold_ladder
Turn a written policy into ladders (observe)agentfox policy compile billing-policy.md --apply

policy compile is deterministic (no model). It lists every assumption it made and the sentences it cannot express; --apply saves only the threshold ladders, in observe.

Imported policies

agentfox policy import FILE prints a plan of what a policy written for another engine becomes; --apply saves it in observe. It reads rule files (apiVersion: governance.toolkit/v1) and policy manifests (agent_control_specification_version, with their Rego from beside the manifest or --bundle; Rego is read, never executed). Over HTTP: POST /api/import/agent-governance/plan, then /api/import/agent-governance (skip leaves items out).

SourceBecomes
denyblock
require_approvalescalate
warn, logrecorded when they fire
default_action: denya default-deny block rule, with allow rules on the tool or agent name carved out of it
default_action: allowunmatched calls pass; the plan says so first
prioritiesdropped: the strongest effect wins, so an allow never overrides a block
==, !=, in [...], contains, startswith, endswith, numeric comparisons, and, orconditions; an or or in list on the tool becomes one rule per branch
regex or substring on message texta custom pattern rule that detects, plus a policy rule acting on it
Rego input, output, pre_tool_call, post_tool_callthe input, output, tool-argument and tool-result surfaces

Not translated, and absent from the import: comparisons of two fields (unless both are tool, agent, surface or environment), negations, rate limits, conditions on context or budget, more than one argument comparison in a condition, Cedar policies, annotations, and conditional verdict rules in Rego.

The effective policy

agentfox policy effective resolves what is in force for a subject and says which layer each rule came from:

bash
agentfox policy effective --agent support-triage
Output
effective policy in development — default allow
  layers:
    org:*(extend)  baseline  observe
    org:*(extend)  eu-ai-act-high-risk  observe
    org:*(extend)  support-desk  enforce
    org:*(extend)  tool-containment  enforce

rule                                 effect    mode     from   overrides
access.undeclared_table              escalate  enforce  org:*  —
access.unscoped_table                block     enforce  org:*  —
…
billing.large_export                 block     enforce  org:*  —
…

Each layer is listed with its own mode, and each rule with the mode it is applied under: enforce rules block, observe rules are recorded as the effective verdict only.

Hierarchy: org, team, agent, user

A policy saved through the API can be placed at a level (org, team, agent, user), with a scope_id (which team, agent or user; * for all) and a compose mode:

composeMeaning
extend (default)Add rules; the broader levels' rules still apply.
restrictTighten only. A rule with the same id and a weaker effect is rejected.
overrideMay weaken a rule, but only one the broader level marked overridable: true.

Packs loaded by agentfox init are bound at org:* with extend. To place one elsewhere, post it to POST /api/policies with level, scope_id and compose. Here a finance team tightens PII redaction to a block, and an agent layer tries to switch off injection.direct:

python
import httpx
B = "http://127.0.0.1:18732"
for f, level, scope, compose in [("finance-team.yaml", "team", "finance", "restrict"),
                                  ("loosen.yaml", "agent", "payments-ops", "override")]:
    r = httpx.post(f"{B}/api/policies", json={"body": open(f).read(), "level": level,
                   "scope_id": scope, "compose": compose, "notes": "docs example"})
    print(r.status_code, r.json())
Output
201 {'key': 'finance-team', 'version': 1, 'version_id': 'pvr_01m469r2pmpz4qds25'}
201 {'key': 'payments-ops-exceptions', 'version': 1, 'version_id': 'pvr_01m469r2q1s0kh1bq6'}
bash
agentfox policy effective --agent payments-ops --team finance
agentfox policy lint
Output
effective policy in development — default allow
  layers:
    org:*(extend)  baseline  observe
    …
    team:finance(restrict)  finance-team  observe
    agent:payments-ops(override)  payments-ops-exceptions  observe
…
injection.direct                     block     observe  org:*         —
pii.outbound_redact                  block     observe  team:finance  org:*
…
rejected layer rules
  injection.direct at agent:payments-ops — cannot loosen 'block' (from org) to 'allow' — the upstream rule is not marked
overridabl

severity  code               rule              level  message
critical  illegal-loosening  injection.direct  agent  weakens 'block' from org:* to 'allow' without an 'overridable:
                                                      true' grant
  {'critical': 1}

LINT FAIL — critical/high findings block the build

What the runtime enforces

The enforcer resolves the hierarchy the same way policy effective does, for each request:

  • A layer applies only to the subject its level and scope_id name. An agent's team is its owner_team (set with PATCH /api/agents/{slug} or when registering it); an agent with no team gets only team layers scoped to *. In the example above, team:finance does not apply to support-triage.
  • A rule rejected as an illegal loosening is not enforced; the broader rule stands. A granted override replaces the broader rule, so an allow there really loosens it.
  • A rule that a narrower layer tightened stays in force beside the tighter one, each under its own pack's mode. A team that trials a stricter rule in observe does not switch off the org's enforced rule.
  • user layers scoped to a specific user apply only where the caller identifies the user, which the runtime does not do today; a user layer scoped to * applies to everyone.

fail_mode and the enforcement budget

What happens when a detector times out or errors is decided by two settings, and the stricter wins: the deployment-wide fail_mode (AGENTFOX_FAIL_MODE, or fail_mode in agentfox.toml) and each pack's own fail_mode. With open (the default) the call proceeds and the gap is recorded. A degraded call is blocked as pipeline.fail_closed when the deployment says closed and the decision is enforcing, or when a pack that is bound in enforce says closed and has an enabled detection rule on the surface being checked (its coverage depended on the detectors that did not finish). tool-containment and eu-ai-act-high-risk ship with closed. Details and an example are in Detectors: budget and failure.

An LLM judge that does not answer (unreachable, an error, a timeout) is a degraded check like any other. The judgment posture's "On a judge outage: deny the request" (off by default) adds one more block, as pipeline.judge_outage: only when the decision is enforcing and an enforcing pack has a rule on that surface the judge's findings could fire. It never loosens a closed fail mode. A payload the egress gate refused to send (pii_egress set to block) is not an outage.

Roll out a change

Simulate against recorded traffic

agentfox policy simulate --file replays recorded decisions against a candidate and exits 1 if anything would newly block. Here the export cap is lowered from 10,000 rows to 100:

bash
agentfox policy simulate --file candidate.yaml
Output
support-desk simulated against 6 decisions
  unchanged        5
  newly blocked    1
  newly escalated  0
  newly allowed    0
    would block support-triage tool_args billing.export — Billing exports are capped at 100 rows.

This change would block production traffic. Review before promoting to enforce.

Options: --agent, --since-days (default 30), --limit (default 1000).

Versions and the simulate gate

Saving a policy (POST /api/policies, or Save new version in the editor) stores an immutable new version and never changes what is in force, whatever mode: the YAML says. A policy saved for the first time goes live in observe. POST /api/policies/{key}/mode with mode: enforce answers 409 unless a simulation of exactly that version's rules was recorded; demoting to observe never needs one.

Promote and demote

bash
agentfox policy enforce baseline
agentfox policy observe baseline
Output
baseline → enforce
baseline → observe

Both are audited. agentfox.auto() in its default mode follows the change with no code change; policy enforce names any agentfox.auto(..., mode="observe") line in the project, which never blocks, and the edit that fixes it. The key can also be a library applied per agent (basic, baseline, tool-containment from the dashboard's Libraries): every agent's copy is switched. A shipped pack the workspace never loaded is loaded in that mode.

Canary

A new version can take a percentage of traffic before it takes all of it. Canaries are run over the API (there is no CLI command): POST /api/policies/{key}/canary/start with optional steps (default [10, 25, 50, 100]), max_block_rate_delta (0.15), max_block_rate_drop, min_dwell_seconds and min_sample (20); /canary/advance checks health and advances, holds, or rolls back when the candidate blocks more, or less, than stable by more than the threshold; /canary/rollback stops it.

Output
201 {
 "id": "cny_01m469sp29fkvhqj65",
 "status": "rolling",
 "percent": 10,
 "step_index": 0,
 "steps": [
  10,
  50,
  100
 ],
 "stable_version": 1,
 "candidate_version": 2,
 "max_block_rate_delta": 0.15,
 "max_block_rate_drop": 0.15,
 "min_dwell_seconds": 3600,
 …
 "gate": {
  "action": "hold",
  "reason": "waiting for 20 decisions in each cohort (stable 0, candidate 0)"
 }
}

Rego export and the OPA engine

Every pack compiles to a Rego module: GET /api/policies/{key}/rego, and policy validate reports the line count. The native engine is the default. Setting policy_engine = "opa" with opa_url evaluates through an OPA sidecar instead, and falls back to the native engine if the sidecar is unreachable. The OPA path was not exercised for this page.

Output
# Generated by AgentFox from policy 'support-desk' v1.
# Do not edit — regenerate from the declarative source.
package agentfox.platform.policy.support_desk

import rego.v1

default verdict := "allow"

# Exports over 10,000 rows are refused.
fired contains out if {
    glob.match("billing.*", [], input.tool)
    input.arguments.rows > 10000
    out := {
        "rule_id": "billing.large_export",
        "effect": "block",
…

Change proposals

AgentFox proposes changes to its own configuration instead of making them: grants and tool declarations from traffic (proposals from-traffic), rule cut-offs from false-positive labels (proposals from-labels). A loosening is never applied by automation.

StatusMeaning
proposedFiled, not yet checked.
provenReplayed against recorded calls; awaiting approval (or a second approver).
approvedReady to apply. Only an approved change can be applied.
canaryApplied to part of the traffic; apply settles it when the canary ends.
applied, verifiedIn force; verify records whether it did what it promised.
rejected, rolled_back, supersededNot in force.

A tool declaration applies to the whole organisation, so it needs two different approvers: the same person approving twice is refused. Apply, rollback and verify need the policy_production permission (owner, admin, security). The CLI takes --actor on every decision.

Hand-off conditions

agentfox declare escalation sets when a conversation must go to a person (omit --agent for the default). Conditions you do not name keep these defaults:

ConditionDefault
explicit_requeston: asking for a person always qualifies
sentiment_below-0.6
confidence_below0.35
repeated_failure2
repeated_abstention2
turn_depth8
regulated_topicslegal, medical, financial_advice, complaint, discrimination
urgent_flagsself_harm, urgency, legal_threat, regulatory, discrimination (self_harm cannot be switched off)

In observe (the default) the hourly escalation.scan job raises a missed_escalation finding for each conversation that qualified. In enforce the conversation is handed off on the turn that first qualifies. --sla-minutes is how long a hand-off may wait before handoff_sla_breach.

Knowledge boundaries

agentfox declare boundary AGENT --systems … --coverage-months N --answerable … --out-of-scope … says what an agent may answer from. The question is checked before the model is called; the answer is withheld with an abstain verdict. Question types are fact, aggregate, prediction, opinion, procedure (--answerable defaults to fact, aggregate, procedure). Boundaries start in observe; agentfox test boundary shows the refusal without changing anything.

Abstention kindWhen
unknowableA projection or opinion rather than a recorded fact.
out_of_coverageAbout a period outside the data's coverage.
out_of_domainA topic declared out of scope.
unsupported_question_typeA question type the agent is not set up to answer.
out_of_scope_entityOnly when the caller sends known_entities: the question names an identifier-shaped token not among them.

Commands

You want toRun
See which packs exist and where they came fromagentfox policy packs
See each bound pack's modeagentfox policy list
Check one fileagentfox policy validate FILE
Lint everything bound (CI gate)agentfox policy lint
What is in force for an agentagentfox policy effective --agent support-triage
Replay traffic against a candidateagentfox policy simulate --file candidate.yaml
Start or stop enforcingagentfox policy enforce baseline
Draft grants from recorded callsagentfox policy proposals from-traffic

Troubleshooting

My pack is not in policy list
Files in .agentfox/policies/ are loaded by agentfox init, run from the repository root. policy packs shows what is on disk; policy list shows what is bound.
A rule never fires
Run agentfox policy lint for unreachable conditions. Check the pack's scope, the surface (each detector runs only on some surfaces), and that min_score is not above what the detector produces: the decision's explanation shows each match's score.
It fires but nothing is blocked
The pack is in observe. Look at effective_verdict, then agentfox policy enforce KEY.
tool-containment will not load
A replacement pack removed or disabled control_plane.tamper. That is refused by design.

Limits

  • Rules see what the detectors and the registry give them. A wrong impact declaration or a missed detection is not fixed by a better rule.
  • The runtime does not know the end user, so user layers scoped to one user never apply at runtime (above).
  • The completion surface needs the caller to report facts; over HTTP there is no field for them, so completion_requires rules always see them as unmet there.