← Back to Guides
GuideFor: AI Engineers, ML Engineers, Platform Engineers, AI Systems Architects

Gated Execution: Why Your Agent Should Never Act Without Permission

Valid output is not safe output. The Gated Execution layer is the firewall between what the model proposes and what the system actually does - default-deny policy, dry runs, and approvals that survive a restart.

Updated
#harness-engineering#gated-execution#human-in-the-loop#llm-agents#ai-safety#production-ai-systems

The Agent That Deleted the Database

This incident is a composite, built from failure patterns rather than one team's postmortem, but every step in it is ordinary.

A team deployed an agent with access to their production database. The task was routine: archive records older than 90 days.

The agent generated a DELETE query. The validation layer checked it - valid SQL, correct schema, proper syntax. The harness executed it.

The WHERE clause read WHERE created_at < NOW() - INTERVAL '90 days'. Correct logic.

What the agent missed: the column created_at was NULL for 40% of records due to a migration bug three months earlier. NULL comparisons in SQL return NULL, not TRUE or FALSE. So NULL < date evaluates to NULL, which is falsy - and those records were skipped.

Except the agent had also generated a fallback condition: OR created_at IS NULL. To handle edge cases, it said.

Every record with a NULL created_at was deleted. 40% of the database. Gone.

The SQL was valid. The logic was coherent. The output passed validation. The execution gate did not exist.

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
model: "Model proposes\nDELETE ... WHERE created_at < 90 days\nOR created_at IS NULL" {class: yellow}
valid: "Validator: valid SQL, correct schema - pass" {class: green}
gate: "Execution gate: missing" {class: grey; style.stroke-dash: 4}
db: "Production database\n40% of records deleted" {class: red}
model -> valid
valid -> gate
gate -> db

The dashed box is the whole story. Every check that existed asked whether the statement was well-formed, and nothing asked how many rows it would touch.

This is Part 4 of the Harness Engineering series. Part 1 introduced the seven-layer Harness Architecture. Part 2 covered Normalization. Part 3 covered Context Engineering. This article goes deep on Layer 4 - Gated Execution - the policy layer between model output and real-world action.

This series grew into a book: Harness Engineering for Production AI Systems. Chapter 9, "Gated Execution," covers this layer.

17 November 2026: fixed a bug that ranked CRITICAL policy violations as LOW, made the policy engine default-deny with an explicit needs-approval verdict, rebuilt the approval gate as a checkpointed interrupt bound to the exact action, stopped failed checks from widening into human review, and added a section on the locks that sit below the gate. Every gate now has its own diagram.


The Model Proposes. The Gate Decides.

That's the whole principle of Gated Execution, and it cannot be stated too many times.

Validation tells you the output is structurally correct, and the repair rung it passed at tells the gate how much that pass is worth. Gated Execution asks a different question: should this action execute at all, given what we know about its consequences?

Structural validity and semantic safety are completely orthogonal. The DELETE query above was structurally valid. It was semantically catastrophic. No validator would have caught it - because validators check format, not consequence.

The gate checks consequence. It sits between model intent and system action. Nothing with real-world side effects executes without passing through it - and that only holds if it sits where every call actually passes. A permission callback that auto-approved tools skip is not that place. The Claude Agent SDK's own docs say that "Auto-approved tools never reach canUseTool", and point to a PreToolUse hook for checks that must see every call. The step before the gate is narrowing what the model can ask for before the gate sees it.

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
model: "Model: proposes an action" {class: yellow}
validator: "Validator: is it well-formed?" {class: green}
gate: "Gate: should it run at all?" {class: violet}
world: "Tools, databases, APIs" {class: blue}
model -> validator: "proposal"
validator -> gate: "valid proposal"
gate -> world: "only allowed actions"

The validator and the gate ask different questions, so they're different boxes. Every arrow into the blue box starts at the gate. That's what "nothing executes without passing through it" means in practice.

Without the gate, your agent is a technically proficient actor with no judgment and no accountability. With the gate, it's a system you can trust.


Why This Layer Is Non-Negotiable for Agentic Systems

For simple LLM applications - a chatbot, a summarizer, a classifier - gated execution is less critical. The worst outcome is a bad response, which is correctable.

For agentic systems, the calculus changes entirely. Agents act. They write files, call APIs, send emails, modify databases, trigger workflows, spend money. These actions have consequences that range from annoying to irreversible.

The three properties that make agentic actions dangerous:

Irreversibility. A deleted record, a sent email, a financial transaction, a deployed infrastructure change - these cannot be trivially undone. The cost of a false positive (executing an action that shouldn't have been executed) is asymmetrically higher than the cost of a false negative (blocking an action that was safe).

Cascading effects. One agent action often triggers downstream consequences. A write to a database propagates to dependent services. An API call triggers a webhook chain. An infrastructure change affects everything running on that infrastructure. The agent doesn't see the cascade; it only sees the immediate action.

Confidence calibration failure. You can't read an LLM's certainty off its output. A model that is 60% confident in a destructive action produces output with the same tone and formatting as one that is 99% confident. There is no built-in hesitation, no "are you sure?" - unless you build one. A worked example of a handler contract in a banking chatbot builds exactly that hesitation - the classifier's label only acts once its confidence clears a per-intent threshold.

d2
grid-rows: 1
grid-gap: 14
classes: {
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
irrev: "Irreversibility\na sent email stays sent" {class: red}
cascade: "Cascading effects\none write, many services" {class: red}
calib: "No visible hesitation\n60% and 99% read the same" {class: red}

Any one of the three makes a wrong action expensive. Agents usually have all three at once, which is why the gate can't be optional for them.


The Three Gate Types

A production gate is not a single check. It's a tiered system that applies different scrutiny to actions based on their risk profile.

Gate Type 1: Policy Validation

The first gate is deterministic. It evaluates proposed actions against a defined ruleset before any execution occurs.

Three properties make this gate trustworthy, and the code below has all of them. It denies by default: an action type that no rule covers never executes. Its verdict has three values, not two, so "this needs a human" is a different outcome from "this is forbidden". And its risk levels are ordered numbers. An earlier version of this code compared risk levels as strings, and "critical" > "low" is False in Python, so its most dangerous violations reported themselves as LOW.

python
from dataclasses import dataclass, fieldfrom enum import IntEnumfrom typing import Callableclass RiskLevel(IntEnum):    LOW = 1    MEDIUM = 2    HIGH = 3    CRITICAL = 4class Verdict(IntEnum):    # Ordered so max() picks the strictest verdict    ALLOW = 0    NEEDS_APPROVAL = 1    DENY = 2@dataclassclass PolicyRule:    name: str    applies_to: set[str]  # action types this rule covers    risk_level: RiskLevel    check: Callable[[dict], Verdict]    reason: str@dataclassclass Decision:    verdict: Verdict    risk: RiskLevel    reasons: list[str] = field(default_factory=list)class PolicyEngine:    def __init__(self):        self.rules: list[PolicyRule] = []    def add_rule(self, rule: PolicyRule):        self.rules.append(rule)    def evaluate(self, action: dict) -> Decision:        kind = action.get("type")        matching = [r for r in self.rules if kind in r.applies_to]        if not matching:            # Default deny: an action type no rule covers never executes            return Decision(Verdict.DENY, RiskLevel.CRITICAL,                            [f"no policy covers action type {kind!r}"])        decision = Decision(Verdict.ALLOW, RiskLevel.LOW)        for rule in matching:            verdict = rule.check(action)            if verdict is not Verdict.ALLOW:                decision.verdict = max(decision.verdict, verdict)                decision.risk = max(decision.risk, rule.risk_level)                decision.reasons.append(rule.reason)        return decision# Ceilings come from the tool registry, never from the proposed actionCOST_CEILING_USD = {"sql": 5, "api_call": 100, "send_email": 1}def unscoped_delete(a: dict) -> Verdict:    q = a.get("query", "").upper()    return Verdict.DENY if "DELETE" in q and "WHERE" not in q else Verdict.ALLOWdef within_budget(a: dict) -> Verdict:    cost = a.get("estimated_cost_usd")    if cost is None:        return Verdict.DENY  # a missing estimate is not a zero estimate    return Verdict.ALLOW if cost <= COST_CEILING_USD[a["type"]] else Verdict.DENYengine = PolicyEngine()engine.add_rule(PolicyRule(    name="no_unscoped_delete", applies_to={"sql"},    risk_level=RiskLevel.CRITICAL, check=unscoped_delete,    reason="DELETE without WHERE clause is not permitted",))engine.add_rule(PolicyRule(    name="budget_guard", applies_to={"sql", "api_call", "send_email"},    risk_level=RiskLevel.HIGH, check=within_budget,    reason="Missing cost estimate, or estimate over the registry ceiling",))engine.add_rule(PolicyRule(    name="external_comms_need_approval", applies_to={"send_email"},    risk_level=RiskLevel.HIGH, check=lambda a: Verdict.NEEDS_APPROVAL,    reason="External communications require explicit approval",))

Run three proposals through it:

python
proposals = {    "unscoped DELETE": {"type": "sql", "query": "DELETE FROM orders",                        "estimated_cost_usd": 1},    "send_email": {"type": "send_email", "estimated_cost_usd": 0.01},    "shell command": {"type": "shell", "cmd": "rm -rf /"},}for label, action in proposals.items():    d = engine.evaluate(action)    print(f"{label:<16} {d.verdict.name:<15} {d.risk.name}")
text
unscoped DELETE  DENY            CRITICALsend_email       NEEDS_APPROVAL  HIGHshell command    DENY            CRITICAL

Be honest about what these rules catch. The incident's DELETE had a WHERE clause, so no_unscoped_delete would have let it through. A substring match is also easy to sidestep: TRUNCATE, or a WHERE hidden in a comment, passes it. Rules like this are cheap tripwires. What stops the incident is the dry run below. In production the rule set itself usually lives in a policy language built for default-deny decisions, such as Cedar or OPA's Rego, rather than in lambdas. The cost estimate is still the model's own number, so a per-run ceiling needs to reserve the worst case before each call rather than trust it.

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  orange: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
action: "Proposed action" {class: yellow}
engine: "PolicyEngine.evaluate\nstrictest verdict of the matching rules" {class: violet}
out: "" {
  grid-rows: 1
  grid-gap: 14
  allow: "ALLOW\nto Gate 2" {class: green}
  approve: "NEEDS_APPROVAL\nto Gate 3" {class: orange}
  deny: "DENY\nincl. no matching rule" {class: red}
}
action -> engine
engine -> out

The red box is the default. An action has to match a rule to reach either of the other two, so a tool you forgot to write a rule for fails closed instead of open.

Policy validation is fast, deterministic, and auditable. Every rule is a documented business decision. Every violation is logged with a reason. This is your first line of defense. It runs inside one agent, so once you operate many agents, rules for egress, registration and revocation belong in the fleet layer above the agent gate.

Gate Type 2: Dry-Run Preview

For actions that pass policy validation but still carry non-trivial risk, execute a dry run before the real thing.

A dry run simulates the action and reports its projected consequences without committing them. SQL databases support this with transactions that are rolled back - for data changes, at least: some engines commit DDL implicitly, and sequences and side effects outside the database don't roll back. Infrastructure tools support it with plan modes (Terraform plan, Ansible --check). File operations can be simulated by reporting what would change without writing.

python
class DryRunGate:    def __init__(self, db):        self.db = db  # a DB-API connection, not in autocommit mode    def preview(self, action: dict) -> dict:        if action.get("type") == "sql":            return self._preview_sql(action)        # file_write, api_call, ...: one previewer per action type        return {"previewable": False,                "reason": f"No dry-run support for {action.get('type')}"}    def _preview_sql(self, action: dict) -> dict:        # Run the real statement, read the row count, then roll back.        # This sees what a rewritten SELECT would miss: the actual rows        # the statement touches. Set a statement timeout in production.        cur = self.db.cursor()        try:            cur.execute(action["query"])            return {"previewable": True, "rows_affected": cur.rowcount}        except Exception as e:            return {"previewable": True, "error": str(e)}        finally:            self.db.rollback()

Running the real statement and rolling it back is more faithful than rewriting the DELETE into a SELECT. It counts exactly the rows the statement would touch, whatever its WHERE clause turns out to mean. It still won't show what triggers or cascades do downstream, so a preview of a table with heavy foreign-key fan-out should report those tables too.

The dry-run output feeds back to the human approval step - or to an automated semantic check that evaluates whether the projected consequences match the intended task.

The database incident above would have been caught by a dry run. On a 1,000-row copy of that table, with 400 NULL dates, 50 genuinely old records and the rest recent, the incident's DELETE previews like this, and the table is untouched afterwards:

text
{'previewable': True, 'rows_affected': 450}

The task said "archive records older than 90 days", and about 50 were. A preview nine times that size is wildly inconsistent with the stated intent, and an automated check comparing expected against previewed impact would have flagged it instantly.

d2
direction: down
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
stmt: "DELETE ... OR created_at IS NULL" {class: yellow}
txn: "Inside a transaction\nexecute, read rowcount, ROLLBACK" {class: blue}
compare: "Compare with intent\nexpected about 50, previewed 450" {class: green}
block: "9x the intended scope:\nblock before anything commits" {class: red}
stmt -> txn
txn -> compare: "rows_affected = 450"
compare -> block

The rollback is what makes the number free. You learn the real blast radius from the database itself, and the only thing that ever commits is the decision to stop.

Without this gate: structurally valid output executes with real-world consequences that nobody previewed. The model passed the policy check. The damage happened anyway.

Gate Type 3: Human-in-the-Loop

For irreversible or high-impact actions, no automated check is sufficient. You need a human.

The design challenge is calibration. Too many approval requests and the agent becomes slower than doing the task manually - defeating its purpose. Too few and you're one confident mistake away from a production incident.

An approval can take minutes or hours, so the gate can't be a coroutine waiting on a future in one process. A deploy, a restart or a second worker would lose every pending request. Current frameworks handle this by suspending the run: they checkpoint its state, hand the request to a human, and resume from the checkpoint when the answer arrives. LangGraph does it with interrupt() and Command(resume=...). LangChain wraps the same mechanism as HumanInTheLoopMiddleware, with approve, edit and reject decisions. In the OpenAI Agents SDK, "the run records an approval interruption instead of executing the tool" and resumes from saved run state. Here is the shape in LangGraph, checked against langgraph 1.2.22:

python
import hashlibimport jsonfrom typing import TypedDictfrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.graph import END, START, StateGraphfrom langgraph.types import Command, interruptclass RunState(TypedDict):    action: dict    risk: str  # from PolicyEngine.evaluate, never from the action    preview: dict    result: strdef action_hash(action: dict) -> str:    return hashlib.sha256(json.dumps(action, sort_keys=True).encode()).hexdigest()def approval_gate(state: RunState) -> dict:    action = state["action"]    # The run is checkpointed and suspended here: no coroutine waits,    # and a restart or deploy does not lose the pending approval.    answer = interrupt({        "action_hash": action_hash(action),        "summary": f"{action['type']} on {action.get('target', '?')}",        "risk": state["risk"],        "preview": state["preview"],    })    # Bind the approval to the exact action that was shown    approved = answer.get("approved") is True    if not approved or answer.get("action_hash") != action_hash(action):        return {"result": "denied"}    # Re-check the facts on resume: the world moved while the reviewer read    if fresh_preview(action) != state["preview"]:        return {"result": "stale: re-preview and ask again"}    return {"result": f"executed, approved by {answer['approver']}"}def fresh_preview(action: dict) -> dict:    return {"rows_affected": 42}  # stand-in for DryRunGate.preview(action)builder = StateGraph(RunState)builder.add_node("approval_gate", approval_gate)builder.add_edge(START, "approval_gate")builder.add_edge("approval_gate", END)graph = builder.compile(checkpointer=InMemorySaver())  # durable saver in productionconfig = {"configurable": {"thread_id": "refund-881"}}action = {"type": "sql", "target": "records", "query": "DELETE ..."}first = graph.invoke(    {"action": action, "risk": "CRITICAL",     "preview": {"rows_affected": 42}, "result": ""}, config)pending = first["__interrupt__"][0].valueprint("paused, waiting on:", pending["summary"])resumed = graph.invoke(    Command(resume={"approved": True, "approver": "oncall@example.com",                    "action_hash": pending["action_hash"]}),    config,)print(resumed["result"])
text
paused, waiting on: sql on recordsexecuted, approved by oncall@example.com

Three details in that node carry most of the safety:

  • The approval is bound to a hash of the exact action. A reviewer who approved "delete 42 rows" has not approved a different query that happens to share a summary line.
  • The risk shown to the reviewer comes from the policy engine. The model never gets to choose its own tier.
  • The facts are re-checked on resume. The preview was taken before the pause, and an approval that resumes on stale facts approves a world that no longer exists.
d2
direction: down
classes: {
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
gate: "1. interrupt(): checkpoint and suspend\nhash, risk, preview sent to reviewer" {class: violet}
wait: "Run is stored, not running\nsurvives restarts and deploys" {class: grey}
resume: "2. Command(resume=answer)" {class: violet}
checks: "3. Same hash? Same facts as the preview?" {class: violet}
out: "" {
  grid-rows: 1
  grid-gap: 14
  exec: "Both yes: execute" {class: green}
  stop: "Either no: deny or re-ask" {class: red}
}
gate -> wait -> resume -> checks
checks -> out

The grey box is the difference from a blocking wait. Nothing is running while the human decides, so there is nothing to lose. A timeout becomes a scheduled job that resumes the run with a denial.

Default deny on timeout is a critical design decision. If no human responds within the timeout window, the action does not execute. The agent waits, reports the timeout, and the task is flagged for human review. Optimism is not the right default for irreversible actions.


The Risk Classification Matrix

Not every action needs every gate. A practical classification system maps action types to required gates:

Action TypePolicy CheckDry RunHuman Approval
Read-only queries✅--
File reads✅--
Low-impact writes (logs, drafts)✅✅-
Database writes (non-bulk)✅✅-
External API calls (idempotent)✅✅-
Bulk database operations✅✅✅
Send email / external communication✅✅✅
Financial transactions✅✅✅
Infrastructure changes✅✅✅
Irreversible deletes✅✅✅

Start conservative - require human approval for every row that has a check mark in the last column. Relax a category only when a person decides to, from the logged record of what the gate refused and what reviewers approved in that category. The model's confidence never moves a tier, and neither does a quiet month: a clean track record tells you how often the agent is wrong, not what being wrong costs.

The goal is not zero human involvement. The goal is the right amount of human involvement - concentrated where consequences are highest.


The Full Gated Execution Flow

The three gates don't run in isolation - they form a sequential decision pipeline. Every proposed action passes through them in order, with each gate deciding whether to pass, block, or escalate. Escalate needs care: a failed check must never get a wider path than its passing twin.

d2
grid-rows: 6
grid-columns: 2
grid-gap: 46
classes: {
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
  none: {style: {opacity: 0}}
}
a: "1. Model proposes action" {class: yellow}
n0: "" {class: none}
g1: "2. Gate 1: policy verdict" {class: green}
b1: "DENY, or no matching rule:\nblock" {class: red}
g2: "3. Gate 2: dry-run preview" {class: green}
b2: "Delta too high, or preview error:\nblock (never widen to review)" {class: red}
g3: "4. Gate 3: human approval\nif NEEDS_APPROVAL or risk HIGH+" {class: violet}
b3: "Denied, timed out, or stale\non resume: block" {class: red}
ex: "5. Execute the approved action" {class: teal}
n4: "" {class: none}
log: "6. Audit log: every path above" {class: blue}
n5: "" {class: none}
a -> g1
g1 -> b1
g1 -> g2: "ALLOW / NEEDS_APPROVAL"
g2 -> b2
g2 -> g3: "matches intent"
g3 -> b3
g3 -> ex: "approved, same hash"
ex -> log

Read the right-hand column top to bottom: each red box is a way a check can fail, and every one of them blocks. A failed dry run doesn't get handed to a human as a consolation path. In a mode with no reviewer, or where policy says no human may approve this amount, a failed check that "escalates" becomes an approval route that its clean twin never had. A low-risk action that passes Gates 1 and 2 skips the approval step and executes directly.

Every path through this diagram ends in the audit log - passes, blocks, and timeouts all. The audit trail is not optional. It's what you show your security team, your compliance auditors, and your post-incident reviewers.


The Named Pattern: Consequence-Proportional Gating

I call this Consequence-Proportional Gating: the scrutiny applied to an action scales with the severity of its potential consequences, not with the model's confidence in the action.

This distinction matters. Model confidence is a poor proxy for safety. A model can be highly confident in a catastrophically wrong action - the database incident is exactly this case. Consequence-Proportional Gating ignores model confidence and focuses entirely on what happens if the action is wrong.

High consequence + low reversibility = maximum scrutiny. Low consequence + high reversibility = minimum scrutiny.

d2
grid-rows: 2
grid-columns: 2
grid-gap: 12
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
  red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
lo_rev: "Low consequence, reversible\npolicy check only\n(read a file, draft a note)" {class: green}
hi_rev: "High consequence, reversible\npolicy + dry run\n(non-bulk DB write)" {class: yellow}
lo_irr: "Low consequence, irreversible\npolicy + dry run\n(post a log line externally)" {class: yellow}
hi_irr: "High consequence, irreversible\nall three gates\n(bulk delete, payment, email)" {class: red}

Model confidence appears nowhere on either axis. The quadrant is set by what the action does to the world, and that doesn't change with how sure the model sounds.

This is the same principle underlying surgical checklists, nuclear reactor procedures, and aviation pre-flight protocols. The rigor is proportional to the cost of failure, not the probability of success.


What Observability Looks Like for This Layer

Policy violation rate by rule - which policy rules trigger most often? A high rate on a specific rule means either the rule is miscalibrated or the model is systematically attempting actions outside its sanctioned scope.

Dry-run delta - the difference between what the model predicted an action would affect and what the dry run shows it would actually affect. A consistently high delta signals the model is poor at estimating the scope of its own actions for that action type.

Approval rate and timeout rate - what fraction of human approval requests are approved vs. denied? What fraction time out? A high timeout rate means your notification system is too slow or your reviewers are overwhelmed. A high denial rate means either your gate threshold is too low or the model is systematically proposing unsafe actions.

Time-to-approval - how long do human approval requests take on average? This is your human-in-the-loop latency. If it exceeds the user's acceptable wait time, you need to either automate more approvals for low-risk actions or add more reviewers.

Log every gate decision - pass or block - with the full action, the gate that evaluated it, and the outcome. This is your safety audit trail.

d2
grid-rows: 2
grid-columns: 3
grid-gap: 12
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
g1: "Gate 1: policy" {class: green}
g2: "Gate 2: dry run" {class: green}
g3: "Gate 3: approval" {class: violet}
m1: "Violation rate by rule" {class: grey}
m2: "Dry-run delta" {class: grey}
m3: "Approval, denial, timeout\nrates; time-to-approval" {class: grey}

Each gate has its own metric, so a change in behaviour points at one gate rather than at "the agent".

The Gate Is Not the Only Lock

A gate in the harness is one lock on the door. OWASP's guidance on Excessive Agency puts the others beside it: "Implement authorization in downstream systems rather than relying on an LLM to decide if an action is allowed or not." Four of them are worth building whatever your gate looks like:

  • Least-privilege credentials. Give the agent a database role with no DELETE privilege on the table, and route archiving through a reviewed stored procedure that enforces the 90-day rule itself. Then the opening incident can't happen even if every harness check is skipped.
  • Complete mediation. The gate only protects the paths that go through it. Put it where every tool call passes, as a hook or middleware on the executor, not as a callback that some calls bypass.
  • Framework primitives over hand-rolled ones. interrupt() with a checkpointer, HumanInTheLoopMiddleware, SDK permission hooks, and policy engines like Cedar or OPA already handle persistence, resumption and audit. Use them for the plumbing, and keep your own code for the consequence rules only you know.
  • Tool metadata is a hint, not a control. The MCP specification lets servers annotate tools, but says that "clients MUST consider tool annotations to be untrusted unless they come from trusted servers." A tool that calls itself read-only still goes through the gate.
d2
grid-columns: 1
grid-gap: 10
classes: {
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
}
harness: "Harness gate: policy, dry run, approval" {class: violet}
mediation: "Executor hook: every tool call passes here" {class: blue}
creds: "Downstream authorization: least-privilege credentials" {class: green}

Read it bottom up. The green layer holds even when the two above it fail, which is why it's the one to build first if you can only build one.



What to Build First

First: Policy validation on all write operations. Before any action with side effects executes, run it through a policy engine - a worked default-deny interceptor for LangGraph is this gate implemented against a specific runtime, with the same deny-by-default posture. Start with default deny and three rules: no unscoped deletes, no external communications without approval, no action without a cost estimate under its registry ceiling. Add rules as you observe the model's failure patterns.

Second: Dry-run preview for database and file operations. Add transaction-wrapped previews for SQL. Add what-would-change reporting for file writes. Surface the preview to whatever decision mechanism comes next (automated check or human).

Third: Human approval for irreversible actions. Wire up a notification channel (Slack, email, PagerDuty) for high-risk action approvals, on top of your framework's interrupt-and-resume mechanism. Default deny on timeout.

Fourth: Risk classification matrix. Document which action types require which gates. Make it explicit. Update it as you learn from production.

Fifth: Automated semantic consequence check. Add a lightweight check that evaluates dry-run output against the stated task intent. Flags large discrepancies between expected and actual impact automatically, without requiring human review - and make sure a gate reads every flag it raises.

d2
grid-columns: 1
grid-gap: 8
classes: {
  green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
  violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
  grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
s1: "1. Default-deny policy on all writes" {class: green}
s2: "2. Dry-run preview for SQL and files" {class: green}
s3: "3. Checkpointed human approval" {class: violet}
s4: "4. Written risk matrix" {class: grey}
s5: "5. Automated intent-vs-preview check" {class: grey}

The two green steps alone would have stopped the opening incident. Steps 3 to 5 are what let you widen the agent's reach without widening its blast radius.


The Principle

The model doesn't know what it doesn't know. It doesn't know that your database has a migration bug. It doesn't know that the email list includes a journalist. It doesn't know that the infrastructure change will cascade to three dependent services.

The gate knows, or can find out, before it's too late.

Gated Execution is not about distrust of the model. It's about the fundamental asymmetry between the cost of blocking a safe action (temporary delay) and the cost of executing an unsafe one (potentially irreversible damage).

Consequence-Proportional Gating is the practice. The gate is the mechanism. Together they are what separate an agent that assists from one that causes incidents.

Build the gate before you give the agent write access. Because an agent without a gate is not an agent. It's a liability.


What's Next in This Series

Going deeper: Chapter 9 of the book

This is Part 4 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 9, "Gated Execution," which covers why fail-closed is three separate decisions, how the gate protocol generalises so that an admission gate can be registered too, what a human review tier really costs, tuning bands from the refusal record rather than from incidents, and why a model must not choose its own tier.

The code for that chapter is the ch09-gated-execution tag of the companion repository. Its tests need no model and no API key.

For a chapter-length treatment on this blog, including where it departs from the book, see AI Agent Approval Gates: Failed Checks Must Never Widen, Part 9 of the chapter-by-chapter guide to the book.


References

  1. Weidinger, L., Mellor, J., Rauh, M., et al. (2021). Ethical and social risks of harm from Language Models. arXiv:2112.04359. https://arxiv.org/abs/2112.04359

  2. Amodei, D., Olah, C., Steinhardt, J., et al. (2016). Concrete Problems in AI Safety. arXiv:1606.06565. https://arxiv.org/abs/1606.06565

  3. Perez, E., Huang, S., Song, F., et al. (2022). Red Teaming Language Models with Language Models. arXiv:2202.03286. https://arxiv.org/abs/2202.03286

  4. Anthropic. Claude Agent SDK: permissions. https://code.claude.com/docs/en/agent-sdk/permissions

  5. OpenAI. Guardrails and human review. https://developers.openai.com/api/docs/guides/agents/guardrails-approvals

  6. Fowler, M. (2014). Circuit Breaker. martinfowler.com. https://martinfowler.com/bliki/CircuitBreaker.html (further reading)

  7. Hendrycks, D., Carlini, N., Schulman, J., & Steinhardt, J. (2021). Unsolved Problems in ML Safety. arXiv:2109.13916. https://arxiv.org/abs/2109.13916

  8. Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 9, "Gated Execution." https://harness.ranjankumar.in/

  9. OWASP GenAI Security Project. (2025). LLM06:2025 Excessive Agency. https://genai.owasp.org/llmrisk/llm062025-excessive-agency/

  10. Model Context Protocol. Specification 2026-07-28: Tools. https://modelcontextprotocol.io/specification/2026-07-28/server/tools

  11. LangChain. Human-in-the-loop. https://docs.langchain.com/oss/python/langchain/human-in-the-loop

  12. LangGraph. Interrupts. https://docs.langchain.com/oss/python/langgraph/interrupts

References 1-3 and 7 are background reading on AI safety; they are not cited for specific claims above.


AI Security

Agentic AI

Follow for more technical deep dives on AI/ML systems, production engineering, and building real-world applications:


Books by Ranjan Kumar

Federated AI Agents cover

Federated AI Agents

Right-Sized AI cover

Right-Sized AI

Harness Engineering for Production AI Systems cover

Harness Engineering

The 7 GenAI Architectures cover

The 7 GenAI Architectures

Building Real-World Agentic AI Systems with LangGraph cover

Building Real-World Agentic AI Systems

The ChatML Handbook cover

The ChatML Handbook

The Chat Templates Handbook cover

The Chat Templates Handbook

Comments