Home › Study guides › CCDV-P › Domain 7 › Lesson 7.1
CCDV-P · Domain 7 · 11% of the exam · Lesson 7.1 · 20 min read New in the December 7, 2026 guide release (v1.0)
Runtime guardrail systems: layers matched to what an agent can break
Match guardrail layers to an agent's risk profile: filters, PII redaction, PreToolUse hooks, sandboxes, approval gates, refusal fallbacks and measured error rates.
Written against skill 7.1 of the official CCDV-P exam guide (Version 1.0, effective November 2026). An independent resource, not affiliated with Anthropic; the practice questions are written from scratch.
7.1.1 Why a rule in the prompt did not stop the breaker
Kestrel Energy runs the electricity network for 1.4 million customers. Its control room uses an operations agent built on the Agent SDK. The agent reads outage tickets, runs diagnostic commands against the grid-management systems and proposes switching operations to restore power. It reaches those systems through one MCP server, gridops, with three tools: read_ticket, run_diagnostic and operate_switch. In normal weather it handles about 2,600 tickets a week; in a storm week, 14,000.
During a storm in the pilot, the agent proposed re-closing a breaker on a feeder where a line crew held a clearance, the permit that says people are working on that line. The system prompt said, in capitals, never to switch a device under an active clearance. The model had read the ticket, but the clearance sat in a different system it never queried. A control-room operator caught the proposal because she happened to read it closely. Nothing in the design required her to.
Tamsin, the staff engineer who owns the agent, drew the lesson in her incident review. A prompt shapes what the model is likely to propose. It cannot make any outcome impossible. What makes an outcome impossible is code that runs outside the model, at the moment of action, and refuses. A runtime guardrail system is the set of such controls around a production agent: filters on what goes in and out, enforcement on every tool call, isolation for what tools can reach, and human gates where judgement is needed.
7.1.2 Match the layers to the risk profile
Here is the question that separates a guardrail design from a guardrail shopping list: what can each action break, and can it be undone? An agent's risk profile is that answer, tool by tool. A read that leaks personal data, a command that overloads a system and a switching operation that energises a line with a crew on it are three different risks, and they need different layers.
| Kestrel action | What it can break | Layers that apply |
|---|---|---|
read_ticket |
Customer personal data reaches the model and the logs | Redaction before the model and before storage |
run_diagnostic |
Load on live systems, a disguised write command, data leaving the sandbox | Command allowlist in a hook, sandbox with a narrow network path |
operate_switch |
Safety of field crews, supply to thousands of homes; cannot be undone | Deterministic interlock, human approval, fail closed |
| Messages to operators | Wrong or unsafe instructions, personal data in shift notes | Output filter, structured switching plan |
Memorise the shape of this table, not its rows: reversibility and blast radius decide how hard a layer must be. A reversible, low-impact action can live with a probabilistic filter that is right 98% of the time. An irreversible one needs a check that is right every time, which means code, not a model's judgement.
The layers sit at fixed points on the path from ticket to grid. Each catches something the others miss, and none depends on the model having behaved.
Kestrel's guardrail layers on one ticket
gridops server refuses unsafe switching7.1.3 Filters and redactors on the way in and out
Why redact at all, when the model is trustworthy with data? Because the model is not the only reader. Everything that enters a prompt can end up in traces, debugging stores and evaluation sets, read by people who never needed it. Kestrel's tickets carry names, phone numbers, street addresses and a medical-priority flag for customers on life-support equipment.
PII redaction, removing personally identifiable information, happens at two points. The first is before the model, and the rule is to remove what the task does not need. The agent needs the service point and feeder to locate a fault, and it needs to know that a life-support customer is affected. It does not need the customer's name or phone number. So Kestrel's ticket adapter replaces the name and phone number with tokens and keeps the life-support flag as a plain yes or no.
One ticket at three stages
Raw ticket
What the model sees
What the log keeps
The second point is before storage. Agent SDK telemetry is structural by default: durations, model names and tool names, with no prompt text or tool content. Variables such as OTEL_LOG_USER_PROMPTS and OTEL_LOG_TOOL_CONTENT opt content in, and the docs advise leaving them unset unless your pipeline is approved to hold that data. Tool results need the same care. A PostToolUse hook can replace a tool's output with updatedToolOutput before Claude sees it, so a diagnostic that dumps a customer list can be masked in one place.
Input filters screen what arrives. Anthropic's guidance is a harmlessness screen: a small, fast model such as Claude Haiku 5.5 classifies the input with structured outputs before the main conversation sees it. The same pattern screens tool output for embedded instructions. If the screen itself returns stop_reason: "refusal", treat that as a harmful verdict, because there is no verdict to read. Output filters check what leaves: Kestrel's operator notes go through a PII pattern check, and any switching step must match a structured plan the code validated, never free text.
7.1.4 Hooks, interlocks and approval gates for irreversible actions
Here is the question the exam loves: the prompt already forbids the dangerous action, so what else is needed? A control that does not depend on the model reading and obeying the prompt. Think of a railway signal box. The signalman knows not to set a green signal into an occupied section, but the interlocking physically locks that lever whatever he believes. Deterministic enforcement is the software version: a check in code that gives the same answer every time for the same facts.
The Agent SDK's first enforcement point is the PreToolUse hook, a callback your code registers that runs before every matching tool call. It returns a permissionDecision of allow, deny, ask or defer; when several hooks disagree, deny wins over defer, then ask, then allow. A hook's allow does not skip the deny and ask rules, and the permissions page says a deny rule applies in every permission mode, bypassPermissions included. Treat that as a backstop, not a reason to run a production agent in a mode that approves nearly everything else. In Claude Code itself, a command hook does the same job by returning that JSON or by exiting with code 2.
Look at two lines in Kestrel's guard: the two lookups against systems of record, and on_failure="block" on the matcher.
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
def deny(reason):
return {"hookSpecificOutput": {"hookEventName": "PreToolUse",
"permissionDecision": "deny", "permissionDecisionReason": reason}}
async def guard_switching(input_data, tool_use_id, context):
args = input_data["tool_input"]
device = args.get("device_id", "")
if device not in feeder_devices(args.get("ticket_id", "")): # ticket scope, from the network model
return deny("Device is not on this ticket's feeder")
if has_active_clearance(device): # crew permit, from the clearance system
return deny("Active crew clearance on this device")
return {} # no decision: the ask rule sends it to the operator
options = ClaudeAgentOptions(hooks={"PreToolUse": [
HookMatcher(matcher="mcp__gridops__operate_switch",
hooks=[guard_switching], on_failure="block")]}) # a crashed guard blocks
That last line matters more than it looks. By default, a PreToolUse callback that throws lets the call continue to the normal permission flow, so a guard that crashes fails open. Setting on_failure="block" makes it fail closed. For the same reason, the gridops server repeats the clearance check before it executes anything. The hook protects this agent; the server's interlock protects the grid from every client, including a future agent nobody has reviewed.
The approval gate comes after the interlocks. Kestrel puts an ask rule on operate_switch in the project's .claude/settings.json, which sends every call to the SDK's canUseTool callback (can_use_tool in Python), wired to the control-room console. Ask rules are checked before the permission mode and the allow rules, so neither can approve the call first. The trap is the opposite wiring: a tool listed by bare name in allowed_tools is auto-approved and never reaches canUseTool, so approval logic placed there is silently skipped. A hook runs for auto-approved calls too. Note also what a PostToolUse hook cannot do: the tool has already run, so for a switching operation it can only report.
7.1.5 Sandboxes that give tools without exposing production
Kestrel's agent needs a shell to parse diagnostic dumps, and web access to read vendor manuals for relay models. Neither needs a route to the live grid. The question is how to give the agent useful tools without giving a mistaken or manipulated agent a path to production. The answer is sandboxing: run the agent inside a boundary that limits which files it can write and which hosts it can reach.
Kestrel runs the production agent in a hardened container, following the Agent SDK's secure deployment guidance: --network none, a read-only root filesystem, all Linux capabilities dropped, and a non-root user. The only way out is a Unix socket to a proxy on the host. That proxy allows two destinations: a diagnostics gateway that accepts only run_diagnostic requests against a read replica, and the vendor documentation site. Grid credentials live behind the gateway, never inside the container.
| Isolation option | When it wins | What it costs |
|---|---|---|
| Claude Code sandbox (Seatbelt on macOS, bubblewrap on Linux) | Engineers running Claude Code against the agent's code and test data | Covers shell commands only; MCP servers, hooks and file tools follow other rules |
| Hardened container with a proxy socket | Production agents processing untrusted content | Image and proxy to maintain; the allowlist is the real policy |
| gVisor or a microVM | Multi-tenant or high-risk workloads needing kernel isolation | Slower system calls, more operational work |
On engineers' machines, the built-in Claude Code sandbox applies the same idea to shell commands and the processes they start. A local proxy checks each hostname against sandbox.network.allowedDomains, which starts empty. Two settings turn it into a hard boundary: sandbox.allowUnsandboxedCommands: false removes the escape hatch that lets a failed command retry outside the sandbox, and sandbox.failIfUnavailable stops Claude Code from quietly running unsandboxed.
The docs are blunt about the limits. By default the proxy decides from the hostname the client supplies and does not inspect TLS, so code inside can sometimes reach other hosts through domain fronting. Broad entries such as github.com open exfiltration paths. An allowlist is only as safe as its widest entry, so Kestrel's lists a single documentation host, not the vendor's whole domain.
7.1.6 When a guardrail fires: refusals, safe fallbacks and measured error rates
Every guardrail eventually fires, sometimes rightly and sometimes not, and the model can decline too. What the operator sees next is part of the design. Kestrel's rule is the safe state: when anything in the path is unsure or unavailable, nothing switches and a person gets the ticket with the reason attached.
A model refusal is the first case. It arrives as HTTP 200 with stop_reason: "refusal", and stop_details.category names the policy area, such as cyber. Benign security work can trigger that category, and a request to probe protection relays can look like attack tooling. A refusal can also arrive mid-stream, after partial output, which you discard. The documented remedy is a retry on another model: the API's fallbacks parameter (beta) does it server-side, or your client can. The exception is reasoning_extraction, where you change the prompt instead.
Kestrel's path when the model declines
stop_reason is refusalThe second case is the guardrails' own errors. A false positive blocks something legitimate; a false negative lets something harmful through. You cannot tune what you do not measure. So Kestrel keeps a labelled set of 400 real and seeded tool calls, runs every layer against it on each change, and samples blocked and passed calls from production for review. A new rule runs in shadow mode first, logging what it would block before it blocks anything.
| Layer | False positive rate | False negative rate | Decision |
|---|---|---|---|
| Diagnostic command screen (classifier) | 7% of legitimate commands blocked | 2 of 50 seeded write commands passed | Replace with an allowlist of read-only command families |
| Switching interlock (code) | 0.5%, stale clearance data | 0 of 40 seeded cases | Keep; fix the data feed, not the rule |
| Operator approval gate | n/a | 3 of 12 seeded bad proposals approved | Show the evidence beside each request; audit approval speed |
The cost of each error decides the target. For switching, a false negative can injure a crew, so the target is zero, reached with deterministic checks rather than a threshold. False positives there cost minutes, so they go to the operator, not to a dead end. For diagnostics, 7% false positives were pushing operators to work around the agent, which is a safety problem of its own. The gate's row shows the quietest failure: operators approving in seconds are a rubber stamp, not a control.
7.1.7 The exam traps
Every trap here puts a control in the wrong place or trusts it more than the evidence allows.
- ✗ Strengthening the system prompt after an agent nearly took an irreversible action. ✓ Enforce the condition in code outside the model, in a
PreToolUsehook and in the tool server. A prompt changes what is likely; an interlock decides what is possible. - ✗ Logging or alerting after the action as the control for a destructive tool. ✓ Prevent before execution. A
PostToolUsehook runs after the tool has run, so it detects rather than prevents. - ✗ Putting approval logic in
canUseToolwhile the tool is listed inallowed_tools. ✓ Use anaskrule or aPreToolUsehook, which still apply to auto-approved calls. Auto-approved calls never reach the callback. - ✗ Letting a guard fail open when its lookup errors or crashes. ✓ Fail closed for irreversible actions: deny on uncertainty and set the hook matcher to block on failure.
- ✗ Giving the agent's sandbox network access to production "for diagnostics", or allowlisting whole platforms. ✓ Route the one needed read through a gateway, keep credentials outside, and allowlist the narrowest hosts.
- ✗ Loosening a filter's threshold for everything because users complain about blocks. ✓ Measure false positives and false negatives per layer on labelled data, tune each to its cost, and send false positives on high-risk actions to a person.
7.1.8 Put it together: build and measure a switching guard
You now have every piece. A risk profile ranks the actions, filters guard the boundaries, interlocks hold the irreversible actions, a sandbox surrounds the tools, and each layer has a measured error rate. The fastest way to own them is to build one guard, measure it, and watch it fail open.
The rest of the domain builds on this. Threat defense and adversarial testing (7.2) attacks these layers on purpose to find the paths you missed, and identity, secrets and audit (7.3) gives the agent its own credentials and records every decision your guards make.
Key takeaways
- ✓ A prompt rule shapes what the model proposes but cannot make an outcome impossible; guardrails are controls outside the model.
- ✓ Choose layers from the risk profile: what each action can break and whether it can be undone decides how hard the control must be.
- ✓ Redact personal data before the model and before storage, and filter inputs, tool output and outputs with cheap, structured checks.
- ✓ Enforce irreversible actions with a fail-closed
PreToolUsehook and the same interlock in the tool server, then a human gate no allow rule or mode can skip. - ✓ Sandbox the agent so tools and web access have no route to production: narrow allowlists, a proxy, credentials kept outside.
- ✓ Treat a refusal as a normal response that ends in a fallback model or a person, and fall back to a safe state when any layer is unsure.
- ✓ Measure false positive and false negative rates per layer and tune each to the cost of the error it allows.
Check your understanding
4 questions written for this lesson. Every answer option is explained, including the ones you did not pick. Nothing is stored.
CCDV-P practice questions are being written
There is no CCDV-P question bank on this site yet. The practice questions are being written now. Until they are ready, work through the free study guide: every lesson ends with questions that check your understanding, and every answer option is explained.
Back to Domain 7 → The CCDV-P exam guide →
The CCDV-P course will hold the same study guide as a book, for reading in the app.
Sources
- Hooks reference (Claude Code)
- Intercept and control agent behavior with hooks (Agent SDK)
- Configure permissions (Agent SDK)
- Configure the sandboxed Bash tool
- Securely deploying AI agents
- Observability with OpenTelemetry (Agent SDK)
- Refusals and fallback
- Stop reasons and fallback
- Mitigate jailbreaks and prompt injections
- The CCDV-P exam guide, summarised