Guardrails in five layers
9 min read
By the end you can document and test a repository's intended control boundaries, identify uncovered routes and assign the next fix.
TL;DR
- A prompt is a request, not a control. Destructive actions need layers the agent cannot talk its way past: permissions, sandbox, secrets, hooks and telemetry.
- Least privilege is the spine and redundancy is the control. A sandbox bounds the processes it actually covers; other tools need their own controls, and every layer can have bugs.
- Keep production credentials out of the session, and send the agent's pull requests through the same gates as everyone else's.
What are the five layers?
A prompt is a request. A control is something the agent cannot talk its way past.
On April 24, 2026, PocketOS, a small car rental SaaS, lost its production database to a coding agent (Cursor powered by Claude Opus 4.6). During a routine task the agent hit a credentials mismatch, found an API token for Railway, the company's infrastructure platform, and invoked Volume Delete. The call took nine seconds. Afterward the agent wrote: "I guessed instead of verifying. I ran a destructive action without being asked." Railway says the legacy API path cascaded the delete so the backups looked gone, and that offsite disaster backups let it recover the data; accounts differ on how long that took. Appendix C has the sources.
PocketOS had a natural-language instruction, which is weaker than layer one. Three lessons get quoted from it, and all three are wrong:
- "The agent ignored its instructions." It did, as agents sometimes do; a prompt is never a hard control for a destructive action.
- "AI agents are unsafe." So is any automation that can reach production without enforced controls.
- "Do not use AI for database operations." That throws away real productivity when layers can bound the risk.
Underneath all five sits least privilege: at every level - the agent, its process, its credentials, its network - grant the minimum that lets the work happen.
| Layer | Blocks | Fails when | Would it have stopped PocketOS? |
|---|---|---|---|
| 1. Permissions | Covered actions the rules or classifier deny | A path is permitted, missed or misclassified | Could have, if a rule gated destructive calls |
| 2. Sandbox | Prohibited access by isolated processes | Off, bypassed through an uncovered tool, or defective | Could have, if it covered the destructive call |
| 3. Secrets | The agent holding a credential | A secret sits within reach | Could have: no production token in the session |
| 4. Hooks | Covered actions a blocking policy rejects | A rule is missing, editable or fails open | Could have: forced human approval |
| 5. Telemetry | Nothing; it detects afterwards | Nobody is alerted or responds | No; a tested alert and response could shorten detection and recovery |
A preventive control could have broken the chain only if it covered the destructive operation. Telemetry serves detection and response, not prevention. The public record does not establish a complete configuration audit. A second 2026 incident, at DataTalks.Club, involved Claude Code running terraform destroy against a stale state file. Both accounts motivate testing destructive-operation approval, credential scope, state and recovery rather than assuming those protections exist.
Layer 1: Permissions
Permissions answer one question: is this agent allowed to do this, right now?
Choose a permission mode for the work's risk, with explicit deny or approval rules for consequential actions. A classifier can reduce prompts for eligible actions; it supplements the runtime's rule checks. Cover each available route, including native file tools, shell commands and connected services. The policy needs as many clear, tested rules as that coverage requires; a shorter list is not inherently safer.
AGENTS.md explains the team's intent; it does not replace enforced permissions. Test an allowed and a prohibited action through the relevant tools, and recheck after configuration or version changes.
Layer 2: Sandbox
The kernel does not listen to the agent's reasoning, so injection cannot talk its way past it.
For routine repository work, start by permitting needed reads, limiting writes to the assigned workspace and temporary files, and restricting network access to what the task requires. Verify coverage: Claude Code's built-in sandbox wraps shell commands, while its native file tools, MCP servers and hooks run outside it. Native Windows commands are unsandboxed; WSL2 is a supported sandbox route. Whole-agent isolation may be needed when a tool-level boundary is insufficient.
Investigate legitimate failures before widening access. Grant the smallest justified exception and check it; do not turn repeated denials into a blanket allow. Defaults and supported platforms vary by agent and version (Chapter 1).
Layer 3: Secrets
The safest credential is the one the session never held.
Do not commit .env files or expose production credentials to the agent process. Keep runtime secrets in a vault with access scoped to the application or task. A shell sandbox's deny-read list protects only the reads it covers: in Claude Code it does not block the native Read tool. Apply file-tool permissions too, and account for inherited environment variables, MCP servers and hooks. Where secrets must be inaccessible to every route, keep them outside the agent's environment or isolate the whole process.
Layer 4: Hooks
Hooks are the precision instrument: a programmable gate for the categories your team cares about.
A hook is code that runs before the agent executes a given kind of action (pre-tool-use) and, against your rules, allows it, asks for confirmation or blocks it. Off-the-shelf plugins ship a baseline: secret leaks in diffs, SQL injection patterns, hardcoded credentials.
A policy hook needs protected configuration, an explicit blocking response and failure behavior that blocks the action. Test a missing, crashing or timed-out hook. Claude Code command and HTTP hooks can otherwise fail open; current versions support onFailure: "block" from v2.1.295 (Appendix C).
Your own rules go on top: any change to currency-conversion logic needs explicit approval; any commit touching the customer table needs a security reviewer. Reach for a hook when permissions are too coarse and the sandbox too blunt.
Layer 5: Telemetry
The first four layers aim to prevent; telemetry supports detection and response. Test the alert and the response, not just the log.
Record tool-call metadata and policy outcomes in a central store the security team owns. Capture arguments or results only where needed, with secrets and sensitive payloads redacted, access controlled and retention defined. Check what the harness actually exports; metrics alone are not a complete action log. Then "which sessions touched the payments service in the last thirty days" can be a query rather than a grep through local histories. Watch for:
- an edit outside the assigned task
- calls to hosts off the allowlist
- repeated permission denials: a bug in the rules or an injection attempt
- production credentials in context
Injection arrives through the work itself
Treat everything the agent reads as untrusted text, and do not count on the agent to spot the attack.
Anywhere the agent reads natural language is a surface: a Jira ticket whose acceptance criteria say "ignore all previous instructions"; an outside contributor's PR comment with an instruction hidden in a review note; an error message from a flaky third-party test; a harmless-looking repository whose planted error nudges the agent to run a "fix" that pulls in its real payload. I have watched an agent follow an instruction buried in a pasted log file because the operator did not think of a log file as untrusted input.
Constrain what the agent can do regardless of what it has read. An enforced sandbox blocks prohibited access on covered paths; a protected, blocking hook can gate the categories it recognizes. Check the routes neither covers. A poisoned AGENTS.md can change the agent on every session start, one more reason it is reviewed like code (Chapter 6).
Repository configuration is code that runs. Before trusting a cloned repository, read its agent settings, hooks, MCP servers and editor tasks. Microsoft's August 2026 analysis of the ChainDrop worm found it writing .claude/settings.json and .vscode/tasks.json into repositories so that later agent or editor activity would restart the payload. If you find such a change, stop running sessions and background jobs, revoke the credentials they could reach, preserve the evidence and involve whoever owns incidents before cleaning up. In CI, never run an agent with secrets or write access over untrusted pull-request content.
Beyond the five
Two ordinary practices catch what the layers do not.
- Environment separation. The agent does not hold production credentials by default. Production actions go through a separate gate - a human approval, a CI pipeline, a deploy script - that the agent triggers but does not execute end to end.
- Protected branches, CODEOWNERS and CI policy. The agent opens pull requests like any contributor; make sure its PRs flow through these rules, not around them.
In the loop
The rigor lives in the layers below execute; execute just runs the work.
Before Chapter 4's execute phase, establish which permission rules, hooks and sandbox restrictions cover each tool. Do not assume one sandbox protects all file writes or connected services. A blocked action needs diagnosis and, where justified, an authorized policy change; asking the agent to try another route is not the fix.
When it breaks
- Every layer is code, and code has bugs. In mid-2026 a red team disclosed two critical zero-click escapes of one vendor's kernel-backed sandbox (patched), and a permission check once skipped its deny rules on very long command chains. That is the argument for five layers.
- A log alone does not ensure a response. The PocketOS accounts describe a recorded deletion. They do not establish a tested alert-and-response path that could have prevented the loss.
Do this Monday
Create a control record for each intended boundary. Monitoring is evidence of detection, not evidence that a prohibited action is blocked. A separate subagent context is not a separate authority, and blocking one route does not block another: OpenAI's managed configuration notes that disabling Browser Use alone does not stop Computer Use driving the browser as a desktop app.
| Record | What to write |
|---|---|
| Intended boundary | The operation that must be prohibited or explicitly approved |
| Covered routes | Shell, native file tools, MCP and other connected services, signed-in browser sessions, desktop control and subprocesses; name exclusions |
| Enforcement | Configuration location, protection against unilateral edits, installed version |
| Verification | A benign probe, expected denial or approval, actual result and evidence |
| Failure behavior | What happens when the control is absent, cannot start, crashes or times out |
| Detection and response | Alert recipient, expected response and a tested alert; separate from blocking |
| Owner and date | Who checked it, when, and when it must be rechecked |
- [ ] Choose one consequential boundary in a repository and fill the record for every available route.
- [ ] Use harmless fixtures and a test environment to confirm an allowed action and the intended denial; do not probe destructive production actions.
- [ ] Test control failure and alert delivery. Record uncovered routes as gaps, with an owner and next action.
- [ ] Finish when another engineer can reproduce the probe and interpret its result. Recheck after version, policy or tool changes.
Go deeper
- Template: the scorecard above; for plugins that ship hooks, Appendix B.10, plugin vetting.
- Deep dive: Appendix D, Chapter 2 - the named vulnerability classes, sandbox escapes, per-agent sandbox defaults and what the platforms changed after the incidents.
- Sources: Appendix C.