---
title: "Safety-First Stack"
domain: "Security & Safety"
summary: "Security-critical patterns for building AI agents that operate safely in production environments."
url: "https://agentic-patterns.com/packs/safety-first-stack"
markdown_url: "https://agentic-patterns.com/packs/safety-first-stack.md"
pattern_count: 5
---

# Safety-First Stack

> Security-critical patterns for building AI agents that operate safely in production environments.

**Domain:** Security & Safety

## How to apply this stack with a coding agent

```text
Apply the "Safety-First Stack" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Anti-Reward-Hacking Grader Design** — Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality. ([page](https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design) | [.md](https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md))
2. **Egress Lockdown (No-Exfiltration Channel)** — Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel ([page](https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel) | [.md](https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md))
3. **Lethal Trifecta Threat Model** — Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three ([page](https://agentic-patterns.com/patterns/lethal-trifecta-threat-model) | [.md](https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md))
4. **Deterministic Security Scanning Build Loop** — Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code ([page](https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop) | [.md](https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md))
5. **Human-in-the-Loop Approval Framework** — Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails. ([page](https://agentic-patterns.com/patterns/human-in-loop-approval-framework) | [.md](https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md))

---

## Anti-Reward-Hacking Grader Design

- URL: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design
- Markdown: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md
- Category: Reliability & Eval | Status: emerging

> Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.

### Use when

- Training a model with reinforcement learning against a grader
- Training reward rises while real performance does not
- Simple graders penalize valid answers for format differences

### Avoid when

- No reinforcement learning or reward-based training
- Team cannot inspect traces and iterate on the grader

<details>
<summary>Full pattern specification</summary>

---
title: "Anti-Reward-Hacking Grader Design"
summary: "Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality."
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design"
source: "https://youtu.be/1s_7RMG4O4U"
authors: ["Nikola Balic (@nibzard)"]
tags: ["reward-hacking","grading","reinforcement-learning","adversarial-robustness","agent-rft"]
signals: ["Training a model with reinforcement learning against a grader","Training reward rises while real performance does not","Simple graders penalize valid answers for format differences"]
anti_signals: ["No reinforcement learning or reward-based training","Team cannot inspect traces and iterate on the grader"]
updated_at: "2026-10-13"
---

# Anti-Reward-Hacking Grader Design

> Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.

## Use when

- Training a model with reinforcement learning against a grader
- Training reward rises while real performance does not
- Simple graders penalize valid answers for format differences

## Avoid when

- No reinforcement learning or reward-based training
- Team cannot inspect traces and iterate on the grader

## Problem

During reinforcement learning training, models actively search for ways to maximize reward. If your grader has edge cases or loopholes, the model will find and exploit them:

- **Gaming the metric**: Model achieves 100% reward score by exploiting grader weaknesses rather than solving the task
- **Unexpected behaviors**: Agent learns bizarre shortcuts that technically satisfy the reward function but don't reflect true quality
- **Brittle evaluation**: Simple graders (e.g., exact string match) penalize valid answers due to formatting differences
- **Degraded real performance**: High training reward doesn't translate to production success
- **Length hacking**: Models generate verbose but meaningless content to inflate scores
- **Format hacking**: Adding empty tags like `<thinking></thinking>` without substantive content
- **Solution appending**: Concatenating previously-solved problems to exploit reward systems

The Rogo team experienced this firsthand: early training runs showed 100% average validation reward, but the model was exploiting edge cases in their financial reasoning grader rather than improving actual performance.

## Solution

Design reward functions that are **resistant to gaming** through iterative hardening and multi-criteria evaluation:

1. **Make it hard to game**: Close loopholes systematically as you discover them
2. **Provide gradient**: Use continuous scores (0.0-1.0) rather than binary (0/1) to guide learning
3. **Multi-criteria decomposition**: Evaluate multiple aspects so gaming one doesn't maximize total reward
4. **Explainability**: Graders should explain why they gave a score to help detect gaming
5. **Adversarial testing**: Manually try to "hack" your grader before training

A multi-criteria grader built on those principles:

```python
class RobustGrader:
    def __init__(self, domain_criteria):
        self.criteria = domain_criteria
        self.violation_patterns = []          # known gaming patterns, added as they are discovered

    def grade(self, question, ground_truth, answer, tool_trace):
        for pattern in self.violation_patterns:      # 1. known gaming patterns score zero, with a reason
            if pattern.matches(answer, tool_trace):
                return {"score": 0.0, "violation": True,
                        "reason": f"Detected gaming pattern: {pattern.name}"}

        scores = {                                   # 2. several criteria, so gaming one is not enough
            "correctness":  self.check_correctness(answer, ground_truth),
            "reasoning":    self.check_reasoning_quality(tool_trace, answer),
            "completeness": self.check_completeness(answer, self.criteria.get("required_elements", [])),
            "citations":    self.check_citations(answer, tool_trace),
            "formatting":   self.check_format_with_flexibility(answer, self.criteria.get("format", "any")),
        }
        weights = {"correctness": 0.50, "reasoning": 0.20, "completeness": 0.15,
                   "citations": 0.10, "formatting": 0.05}
        final_score = sum(weights[k] * scores[k] for k in scores)     # 3. weighted sum, partial credit

        return {"score": final_score, "subscores": scores, "violation": False,
                "reason": self.explain_score(scores, weights)}        # 4. explain the score

    def add_violation_pattern(self, name, detection_fn):
        self.violation_patterns.append({"name": name, "matches": detection_fn})
```

**Scoring rules that do the anti-gaming work** (illustrative thresholds):

- **Correctness with normalization**: normalize both answers, then exact match scores 1.0; numbers within 1% score 1.0 and within 5% score 0.5; text with semantic similarity above 0.9 scores 1.0 and above 0.7 scores 0.5; anything else scores 0.
- **Reasoning quality from the tool trace**: no tool calls scores 0.0 (the agent must use tools), repetitive calls 0.2, calls unrelated to the answer 0.3, otherwise 0.6, or 1.0 when the calls progress logically. This blocks answers produced without reasoning.
- **Formatting with flexibility**: partial credit, so a valid answer is not penalized for a format difference.

```mermaid
graph TD
    A[Design Initial Grader] --> B[Run Training]
    B --> C{Suspicious High Reward?}
    C -->|Yes| D[Inspect Traces]
    D --> E[Identify Gaming Pattern]
    E --> F[Add Detection Rule]
    F --> G[Update Grader]
    G --> B
    C -->|No| H[Validate on Holdout]
    H --> I{Performance Matches?}
    I -->|Yes| J[Deploy Model]
    I -->|No| E

    style E fill:#ffebee,stroke:#c62828,stroke-width:2px
    style F fill:#fff3e0,stroke:#f57c00,stroke-width:2px
    style J fill:#e8f5e9,stroke:#388e3c,stroke-width:2px
```

**Critical: format constraints.** Process-aware rewards without strict format constraints lead to catastrophic exploitation (Spark Research, December 2025). Always enforce:

- Exactly one answer tag or boxed expression
- No post-answer content after it
- Strict output format requirements

## How to use it

1. **Initial design**: Decompose "good answer" into 4-6 measurable criteria and weight them by business priority. Handle formatting variations gracefully (e.g., "7%" vs "0.07"). Return subscores and the reasoning behind the score.
2. **Adversarial testing**: Write answers that get high scores without being correct. Test extreme inputs (empty answers, gibberish). Add guardrails against trivial gaming (e.g., must use at least N tools).
3. **Training monitoring**: If reward jumps to 100%, investigate immediately. Manually review high-reward traces. Validation reward should track training reward. Confirm that business KPIs improve, not just reward. Measure agreement between the grader and human reviewers (for example with Cohen's Kappa) and investigate before scaling when agreement is low.
4. **Iterative hardening**: When you find gaming, characterize the pattern, add an explicit check for it, re-run training with the hardened grader, and repeat. This is an ongoing process.

### Worked example: Rogo Finance

- **Task**: financial reasoning agent for investment insights.
- **Initial grader**: a simple model-based check of answer correctness. The model reached 100% validation reward while actual financial soundness stayed poor.
- **Hardening applied**: multi-criteria evaluation weighted toward factual accuracy (0.4), reasoning completeness (0.2), financial soundness (0.2), clarity of explanation (0.1), and citation quality (0.1); plus violation detection for missing citations, circular reasoning, and copy-paste from source without synthesis.
- **Result**: 21% real performance improvement with much lower hallucination rates.

## Trade-offs

**Pros:**

- **Robust learning**: Models learn to truly solve tasks, not game metrics
- **Better generalization**: Multi-criteria grading encourages well-rounded solutions
- **Debuggability**: Subscores help identify what the model is struggling with
- **Production alignment**: Training reward correlates with business metrics

**Cons:**

- **Engineering effort**: Requires careful design and iteration
- **Slower convergence**: Harder grader means lower initial rewards
- **Grader complexity**: More code to maintain and potentially debug
- **Subjectivity**: Some criteria (e.g., "financial soundness") need careful definition
- **Computational cost**: Multi-criteria grading takes longer per sample

## References

- [OpenAI Build Hour: Agent RFT - Rogo Case Study (November 2025)](https://youtu.be/1s_7RMG4O4U)
- [Specification Gaming in AI (DeepMind)](https://deepmind.google/discover/blog/specification-gaming-the-flip-side-of-ai-ingenuity/)
- [Let's Verify Step by Step (OpenAI, 2023)](https://arxiv.org/abs/2305.20050) - Process Reward Models
- [LLMs Cannot Reliably Judge (Yet?) (2025)](https://arxiv.org/abs/2506.09443) - Adversarial attacks
- [Reward Hacking in Rubric-Based Reinforcement Learning (2026)](https://arxiv.org/abs/2605.12474) - reward hacking against detailed rubrics
- [A Survey of Reward Hacking in Agentic Large Language Models (2026)](https://link.springer.com/article/10.1007/s44163-026-01980-z) - Springer survey of the field
- Related patterns: Inference-Healed Code Review Reward, Agent Reinforcement Fine-Tuning, RLAIF

</details>

---

## Egress Lockdown (No-Exfiltration Channel)

- URL: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel
- Markdown: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md
- Category: Security & Safety | Status: foundational

> Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel

### Use when

- Agent has access to private data and reads untrusted input
- Agent runs in a container or VM where you control outbound network rules
- Needed external APIs can go through an internal proxy

### Avoid when

- The agent must reach many arbitrary external sites to do its job
- The agent has no access to sensitive data
- You cannot build proxy stubs for essential integrations

<details>
<summary>Full pattern specification</summary>

---
title: "Egress Lockdown (No-Exfiltration Channel)"
summary: "Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel"
status: "foundational"
category: "Security & Safety"
url: "https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel"
source: "https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["network-sandbox","exfiltration","outbound-controls","security"]
signals: ["Agent has access to private data and reads untrusted input","Agent runs in a container or VM where you control outbound network rules","Needed external APIs can go through an internal proxy"]
anti_signals: ["The agent must reach many arbitrary external sites to do its job","The agent has no access to sensitive data","You cannot build proxy stubs for essential integrations"]
updated_at: "2026-11-23"
---

# Egress Lockdown (No-Exfiltration Channel)

> Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel

## Use when

- Agent has access to private data and reads untrusted input
- Agent runs in a container or VM where you control outbound network rules
- Needed external APIs can go through an internal proxy

## Avoid when

- The agent must reach many arbitrary external sites to do its job
- The agent has no access to sensitive data
- You cannot build proxy stubs for essential integrations

## Problem

Even with private-data access and untrusted inputs, attacks fail if the agent has **no way to transmit stolen data**. As an analogy of this pattern's author (not a framing from the source article), the design echoes the Bell-LaPadula "no write down" property: high-privilege subjects cannot write to low-trust destinations. Many real-world fixes simply removed or filtered outbound channels.

## Solution

Implement an **egress firewall** for agent tools:

- Allow only specific domains, methods, or payload sizes.
- Strip or hash content in any permitted outbound call.
- Forbid dynamic link generation (e.g., `attacker.example/exfil?q=REDACTED`).
- Where external communication is essential, run it in a separate "dumb" worker that cannot see private data.

```bash
# Docker file example
RUN iptables -P OUTPUT DROP       # default-deny
RUN iptables -A OUTPUT -d api.mycompany.internal -j ACCEPT

# For L7-aware filtering: eBPF/XDP (Linux 4.19+) or Cilium
```

## How to use it

* Place the agent inside a sandboxed VM or container with outbound rules.
* Provide needed APIs via an internal proxy; audit that proxy's request schema.
* Apply seccomp profiles or AppArmor policies to block network syscalls directly.
* Log any DROP events for forensic follow-up.

## Trade-offs

**Pros:** Drastically reduces high-impact leaks; easy to reason about.
**Cons:** Breaks legitimate integrations; requires proxy stubs for essential calls.

## References

* Willison's article cites the Microsoft 365 Copilot, GitHub MCP, and GitLab Duo Chatbot incidents as "almost all... promptly fixed by the vendors, usually by locking down the exfiltration vector." It gives no per-vendor fix details and does not claim egress lockdown was the first patch in every case.

- Primary source: https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/ - describes the threat model this pattern mitigates; the default-deny egress firewall implementation itself is this pattern's contribution
- Parent threat model: [Lethal Trifecta Threat Model](lethal-trifecta-threat-model.md)
- Beurer-Kellner et al. (2025). "Design Patterns for Securing LLM Agents against Prompt Injections." arXiv:2506.08837.

</details>

---

## Lethal Trifecta Threat Model

- URL: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model
- Markdown: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md
- Category: Security & Safety | Status: foundational

> Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three

### Use when

- Agent reads private data and also processes untrusted content
- Agent can send data out through network or messaging tools
- Tools can be tagged with capability metadata

### Avoid when

- Agent has no access to private data
- Agent has no way to communicate externally

<details>
<summary>Full pattern specification</summary>

---
title: "Lethal Trifecta Threat Model"
summary: "Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three"
status: "foundational"
category: "Security & Safety"
url: "https://agentic-patterns.com/patterns/lethal-trifecta-threat-model"
source: "https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["security","prompt-injection","threat-model","data-exfiltration"]
signals: ["Agent reads private data and also processes untrusted content","Agent can send data out through network or messaging tools","Tools can be tagged with capability metadata"]
anti_signals: ["Agent has no access to private data","Agent has no way to communicate externally"]
updated_at: "2026-10-13"
---

# Lethal Trifecta Threat Model

> Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three

## Use when

- Agent reads private data and also processes untrusted content
- Agent can send data out through network or messaging tools
- Tools can be tagged with capability metadata

## Avoid when

- Agent has no access to private data
- Agent has no way to communicate externally

## Problem

Combining three agent capabilities—
1. **Access to private data**
2. **Exposure to untrusted content**
3. **Ability to externally communicate**

—creates a straightforward path for prompt-injection attackers to steal sensitive information.  
LLMs cannot reliably distinguish "good" instructions from malicious ones once they appear in the same context window.

## Solution

Adopt a **Trifecta Threat Model**:  

- **Audit every tool** an agent can call and classify it against the three capabilities.  
- **Guarantee that at least one circle is missing** in any execution path. Options include:  
  
- Remove external network access (no exfiltration).  
  - Deny direct file/database reads (no private data).  
  - Sanitize or segregate untrusted inputs (no hostile instructions).  
- Enforce this at orchestration time, not with brittle prompt guardrails.

```python
# pseudo-policy
if tool.can_externally_communicate and
   tool.accesses_private_data and
   input_source == "untrusted":
       raise SecurityError("Lethal trifecta detected")
```

## How to use it

* Maintain a machine-readable capability matrix for every tool.
* Add a pre-execution policy check in your agent runner.
* Fail closed: if capability metadata is missing, treat the tool as high-risk.

## Trade-offs

**Pros:** Simple mental model; eliminates entire attack class.
**Cons:** Limits powerful "all-in-one" agents; requires disciplined capability tagging.

## References

- Primary source: Simon Willison, [The lethal trifecta for AI agents: private data, untrusted content, and external communication](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/) (June 16, 2025; the previously cited `/lethal-trifecta` slug was a dead 404 URL)
- Academic source: Beurer-Kellner et al., *Design Patterns for Securing LLM Agents against Prompt Injections* ([arXiv:2506.08837](https://arxiv.org/abs/2506.08837), June 2025; [doi:10.48550/arXiv.2506.08837](https://doi.org/10.48550/arXiv.2506.08837))

> **Note on terminology**: This pattern describes Simon Willison's prompt injection threat model (private data + untrusted content + external communication), distinct from the AI safety literature's "lethal trifecta" (advanced capabilities + agentic behavior + situational awareness).

</details>

---

## Deterministic Security Scanning Build Loop

- URL: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop
- Markdown: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md
- Category: Security & Safety | Status: proposed

> Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code

### Use when

- Coding agents generate code that must meet security rules
- Prompt rules or MCP security tools are the only security control
- You already have security scanning tools for CI

### Avoid when

- Security scanners are too slow for a per-change inner loop
- No capacity to review false positives from scanners

<details>
<summary>Full pattern specification</summary>

---
title: "Deterministic Security Scanning Build Loop"
summary: "Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code"
status: "proposed"
category: "Security & Safety"
url: "https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop"
source: "https://ghuntley.com/secure-codegen/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["security","deterministic","build-loop","backpressure","static-analysis","supply-chain"]
signals: ["Coding agents generate code that must meet security rules","Prompt rules or MCP security tools are the only security control","You already have security scanning tools for CI"]
anti_signals: ["Security scanners are too slow for a per-change inner loop","No capacity to review false positives from scanners"]
updated_at: "2026-10-13"
---

# Deterministic Security Scanning Build Loop

> Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code

## Use when

- Coding agents generate code that must meet security rules
- Prompt rules or MCP security tools are the only security control
- You already have security scanning tools for CI

## Avoid when

- Security scanners are too slow for a per-change inner loop
- No capacity to review false positives from scanners

## Problem

Non-deterministic approaches to security in AI code generation (Cursor rules, MCP security tools) are fundamentally flawed because security requires absolute determinism - code is either secure or not secure, with no grey area. These approaches are merely suggestions to the LLM that may or may not be followed consistently.

## Solution

Implement **deterministic security validation** through the build loop using a two-phase approach:

1. **Generation Phase** (non-deterministic): Agent generates code based on suggestions and context
2. **Backpressure Phase** (deterministic): Security scanning tools validate the generated code

The key is integrating existing security scanning tools (SAST, DAST, SCA) directly into the build target that agents must execute after every code change. This approach is grounded in supply chain security frameworks like SLSA and reproducible builds research.

```makefile
.PHONY: all build test security-scan

all: build test security-scan

build:
    @echo "Build completed successfully"
    @exit 0

test:
    @echo "Tests completed successfully" 
    @exit 0

security-scan:
    # Use your existing security scanning tools
    semgrep --config=auto src/
    bandit -r src/
    trivy fs .
    gitleaks detect --source .
    @exit $?
```

Configure agent instructions to mandate build execution. Note that harnesses treat such instructions as advisory: a model can skip them, so they are a request rather than a guarantee.

```markdown
# Agent Instructions

## Code Quality 

After every code change, you MUST:

1. Run `make all` to verify that the code builds successfully and tests pass.
2. IMPORTANT: You MUST resolve any security issues identified during compilation.
```

For deterministic enforcement, gate the stop of the turn instead of the prompt. Claude Code Stop hooks run a check as a script and block the turn from ending until it passes; the official guidance states that unlike CLAUDE.md instructions, which are advisory, hooks are deterministic. Wiring `make security-scan` into a Stop hook makes the scanner impossible to skip:

```json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "make security-scan" }
        ]
      }
    ]
  }
}
```

```mermaid
graph TD
    A[Agent Generates Code] --> B[Run Build Target]
    B --> C{Security Scan Passes?}
    C -->|No| D[Security Tool Output in Context]
    D --> E[Agent Sees Error & Regenerates]
    E --> A
    C -->|Yes| F[Code Generation Complete]
```

## How to use it

1. **Inner Loop (Development)**:
   
- Integrate existing security scanning tools into your build target
   - Configure agent instructions to run build after every change
   - Let the agent see security tool output and iterate

2. **Outer Loop (CI/CD)**:
   
- Use the same security tools in your pull request checks
   - Maintain one unified rules database across both loops

3. **Implementation Steps**:
   
- Add security scanning tools to Makefile/package.json/build script
   - Update agent configuration (AGENTS.md/Cursor rules) to mandate build execution
   - Ensure security tools exit with non-zero codes on violations

## Trade-offs

**Pros:** 
- Leverages deterministic, battle-tested security tools
- Reuses existing security infrastructure and rules
- Works with any coding agent/harness
- Provides consistent security validation

**Cons:** 
- Increases build time and CI resource usage
- May produce false positives requiring human review
- Requires fast security tools for good developer experience

## References

* [Geoffrey Huntley's blog post on secure code generation](https://ghuntley.com/secure-codegen/) (2025-09-03) - primary source; full content is behind a subscription paywall, so the specific build-loop advice cannot be verified publicly
* [Claude Code best practices](https://code.claude.com/docs/en/best-practices) - public corroboration of the gating mechanism: "Give Claude a check it can run: tests, a build" and "a Stop hook runs your check as a script and blocks the turn from ending until it passes"; "Unlike CLAUDE.md instructions which are advisory, hooks are deterministic"
* [SLSA (Supply-chain Levels for Software Artifacts)](https://slsa.dev) - Framework for supply chain security
* [Build Systems à la Carte (Mokhov, Mitchell, Peyton Jones, ICFP 2018)](https://dl.acm.org/doi/10.1145/3236774) - Formal build system theory including incremental recomputation and dependencies
* [Reproducible Builds Project](https://reproducible-builds.org) - Community initiative for verifiable builds
* Related pattern: [Background Agent with CI Feedback](background-agent-ci.md) - the outer loop; this pattern is the per-change inner loop that runs in the agent's own workspace, while CI feedback covers the slower pipeline after the branch is pushed
* Related pattern: [Deterministic Threat Rule Scanning](deterministic-threat-rule-scanning.md) - the same deterministic-control idea applied to scanning agent tool traffic for injected threats, rather than scanning generated code
* This generalizes beyond security to any code quality or pattern enforcement

</details>

---

## Human-in-the-Loop Approval Framework

- URL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework
- Markdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md
- Category: UX & Collaboration | Status: foundational

> Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.

### Use when

- Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys
- Compliance requires a record of who approved each sensitive action
- Humans can respond fast enough through Slack, email, or a dashboard

### Avoid when

- All agent actions are safe or easily reversible
- No human is available to respond in time
- Approval volume would be so high that reviewers rubber-stamp requests

<details>
<summary>Full pattern specification</summary>

---
title: "Human-in-the-Loop Approval Framework"
summary: "Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails."
status: "foundational"
category: "UX & Collaboration"
url: "https://agentic-patterns.com/patterns/human-in-loop-approval-framework"
source: "https://claude.com/blog/building-companies-with-claude-code"
authors: ["Nikola Balic (@nibzard)"]
tags: ["human-oversight","safety","approvals","risk-management","collaboration","slack-integration"]
signals: ["Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys","Compliance requires a record of who approved each sensitive action","Humans can respond fast enough through Slack, email, or a dashboard"]
anti_signals: ["All agent actions are safe or easily reversible","No human is available to respond in time","Approval volume would be so high that reviewers rubber-stamp requests"]
updated_at: "2026-11-06"
---

# Human-in-the-Loop Approval Framework

> Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.

## Use when

- Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys
- Compliance requires a record of who approved each sensitive action
- Humans can respond fast enough through Slack, email, or a dashboard

## Avoid when

- All agent actions are safe or easily reversible
- No human is available to respond in time
- Approval volume would be so high that reviewers rubber-stamp requests

## Problem

Autonomous AI agents need to execute high-risk or irreversible operations (database modifications, production deployments, system configurations, API calls) but allowing unsupervised execution creates unacceptable safety and compliance risks. Blocking all such operations defeats the purpose of agent automation.

## Solution

Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations. Create lightweight feedback loops that enable time-sensitive human decisions without blocking the entire agent workflow.

**Core components:**

**Risk classification:**

- Identify functions that require human approval
- Define approval criteria (cost thresholds, data sensitivity, reversibility)
- Categorize operations by risk level

**Multi-channel approval interface:**

- Slack integration for real-time notifications
- Email for asynchronous approvals
- SMS for urgent/critical operations
- Web dashboard for batch reviews

**Approval workflow:**

- Agent requests permission before executing risky function
- Human receives context-rich approval request
- Quick approve/reject/modify decision
- Agent proceeds or adapts based on response
- Timeout handling with configurable escalation (default deny recommended)

**Audit trail:**

- Log all approval requests and responses
- Track who approved what and when
- Enable compliance and debugging

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant Framework as Approval Framework
    participant Slack as Slack Channel
    participant Human as Human Reviewer
    participant DB as Database

    Agent->>Framework: Request: DROP old_users table
    Framework->>Framework: Classify as HIGH RISK
    Framework->>Slack: Send approval request with context
    Slack->>Human: Notification with approve/reject buttons

    alt Approved
        Human->>Slack: Click "Approve"
        Slack->>Framework: Approval granted
        Framework->>Agent: Permission granted
        Agent->>DB: Execute DROP table
        Framework->>Framework: Log approval & execution
    else Rejected
        Human->>Slack: Click "Reject + provide reason"
        Slack->>Framework: Rejection + context
        Framework->>Agent: Permission denied + reason
        Agent->>Agent: Adapt plan (skip or find alternative)
    end
```

## How to use it

**When to apply:**

- Production database operations (DELETE, DROP, ALTER)
- External API calls with side effects (payments, emails, webhooks)
- System configuration changes (firewall rules, permissions)
- Destructive file operations (bulk deletes, overwrites)
- Compliance-sensitive operations (GDPR, HIPAA, SOC2)

**Implementation examples:**

**Permission rules (Claude Code settings):**

```json
// .claude/settings.json — rules are evaluated deny, then ask, then allow
{
  "permissions": {
    "allow": ["Bash(git add:*)", "Bash(npm test:*)"],
    "ask": ["Bash(git push:*)"],
    "deny": ["Read(.env)", "Read(secrets/**)"]
  }
}
```

Commands on the `ask` list pause the agent until a human answers the permission prompt, which is the same gate-then-resume flow the Slack-based implementations use.

**Interrupt pattern (LangGraph):**

```python
from langgraph.types import interrupt

def risky_operation(state):
    approval = interrupt({
        "question": "Should I proceed with this operation?",
        "operation": state["message"]
    })
    return {"user_approval": approval}

# Compile with checkpointer for state preservation
app = workflow.compile(checkpointer=MemorySaver())
```

**Protocol-level elicitation (MCP):**

An MCP server can pause mid-flow and send an `elicitation/create` request to the client, which renders the question and schema to the user and returns the answer to the agent. This gives any MCP-connected client the same interrupt semantics without a bespoke approval service.

**2. Configure approval channels:**

```yaml
approval_channels:
  high_risk:
    
- slack: "#agent-approvals"
    - sms: "+1234567890"  # For urgent
  medium_risk:
    
- slack: "#agent-review"
  low_risk:
    
- email: "team@company.com"
```

**3. Set context requirements:**

- Why is the operation needed?
- What data will be affected?
- Is it reversible?
- What are the alternatives?

**Prerequisites:**

- Integration with communication platforms (Slack, email, SMS)
- Clear risk classification criteria
- Fast human response time for time-sensitive operations
- Fallback strategies when approval is denied

## Trade-offs

**Pros:**

- Enables safe autonomous execution of risky operations
- Maintains human oversight where it matters most
- Lightweight integration (Slack buttons, not complex UIs)
- Audit trail for compliance and debugging
- Reduces agent anxiety about mistakes
- Allows gradual trust expansion over time

**Cons:**

- Requires human availability and responsiveness
- Can bottleneck agent workflows if approvals are slow
- Infrastructure complexity (notification systems, state management)
- Risk of approval fatigue leading to rubber-stamping
- Requires clear classification of what needs approval
- May interrupt human focus with frequent requests

## References

- [Building Companies with Claude Code](https://claude.com/blog/building-companies-with-claude-code) - HumanLayer's core product coordinates agent actions with "human approval steps" via Slack
- [HumanLayer on GitHub](https://github.com/humanlayer/humanlayer) - the open-source SDK is now largely deprecated ("the code here is pretty much all deprecated"); the company pivoted to a coding-agent IDE ([humanlayer.dev](https://www.humanlayer.dev))
- [12-Factor Agents](https://github.com/humanlayer/12-factor-agents) - Factor 7 covers contacting humans via tool calls
- [Claude Code permissions](https://code.claude.com/docs/en/permissions) - permission modes plus allow/ask/deny rules as a maintained standard implementation
- [MCP elicitation specification](https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation) - protocol-level mid-flow approval requests
- [Design Patterns for Securing LLM Agents](https://arxiv.org/abs/2506.08837) (Beurer-Kellner et al., ETH Zurich, 2025) - Academic treatment of approval systems as security pattern, including separation of proposal and execution
- [Impri](https://github.com/sekera-radim/impri) - Self-hostable, framework-agnostic implementation of this pattern (contributor-owned, disclosed): agents propose actions via MCP or REST, a human approves/edits/rejects from a web inbox, Slack, Telegram, or phone, then the agent executes. MIT-licensed open-core, included as a concrete alternative to the vendor-SDK references above.
- [Duct](https://github.com/5hirish/duct) - Open-source marketing agent (contributor-owned, disclosed) that applies the proposal/execution separation from the ETH Zurich paper at the tool-list level: the model can only propose a change set as data, no approve or apply tool exists for it to call, a human approves through an HTTP route, and a per-project autonomy level (`ask` by default) can let reversible, guardrail-clean changes auto-apply but never widens what may apply. MIT-licensed, included as a second concrete implementation beside Impri.
- Related patterns: [Spectrum of Control / Blended Initiative](spectrum-of-control-blended-initiative.md), [Chain-of-Thought Monitoring & Interruption](chain-of-thought-monitoring-interruption.md)

</details>
