Stop Wasting Tokens on AI Rules! Cupcake Enforces Policies Natively
Stop Wasting Tokens on AI Rules! Cupcake Enforces Policies Natively
Your AI agent just tried to force-push to production. Again. You spent hours crafting the perfect CLAUDE.md rules. You loaded up your AGENT.md with security guidelines. You even added custom instructions to Cursor's project settings. And yet—here you are, cleaning up a disaster that cost you sleep, credibility, and probably a few thousand dollars in incident response.
Sound familiar? You're not alone. Every developer experimenting with AI coding agents has felt that stomach-dropping moment when the agent "forgets" a critical rule. The brutal truth? Prompt-based rules are broken by design. They consume precious model context, get buried under conversation history, and fail precisely when you need them most—under pressure, with complex tasks, when the agent is "in the zone" and ignoring your carefully crafted constraints.
But what if your rules didn't live in the prompt at all? What if they sat between your agent and the runtime, intercepting every dangerous action before it touched your filesystem, your Git repository, or your production infrastructure? Enter Cupcake—the native policy enforcement layer that top engineering teams are quietly deploying to transform their AI agents from reckless assistants into disciplined, rule-following teammates. Built on battle-tested OPA/Rego and compiled to WebAssembly, Cupcake doesn't ask your agent to follow rules. It enforces them.
What is Cupcake?
Cupcake is an open-source policy enforcement layer for AI coding agents, developed by EQTYLab with agentic safety research support from the renowned security firm Trail of Bits. Officially released as open source on December 10, 2025, it represents a fundamental shift in how we govern autonomous AI systems—not through hopeful prompting, but through deterministic, code-based guardrails.
At its core, Cupcake intercepts agent events and evaluates them against user-defined rules written in Open Policy Agent (OPA) Rego language. These policies are compiled to WebAssembly (Wasm) for fast, sandboxed evaluation that runs in milliseconds. The result? Your agents can propose actions, but Cupcake decides whether they execute—without consuming a single model context token.
The project's evolution reveals deep technical insight. The EQTYLab team initially explored filesystem and OS-level monitoring of agent behavior, but pivoted in April 2025 after producing the feature request for Claude Code Hooks. This pivot toward native runtime integration—hooks directly in the agent action path—makes Cupcake fundamentally different from after-the-fact monitoring tools. It sits in the execution flow, not beside it.
Cupcake's architecture mirrors infrastructure-as-code principles: policies are separated by harness (policies/claude/, policies/cursor/, policies/factory/, policies/opencode/), ensuring clarity and full access to harness-specific capabilities. This terraform-like organization means your security rules live where they belong—in version-controlled, reviewable, testable code.
Key Features That Make Cupcake Dangerously Effective
Deterministic Rule-Following via OPA/Rego + WebAssembly
Cupcake's secret weapon is policy-as-code using the same OPA/Rego stack that secures Kubernetes deployments at Fortune 500 companies. Your rules aren't suggestions floating in prompt space—they're compiled programs that evaluate consistently every single time. The Wasm compilation ensures sub-millisecond evaluation for cached policies, with full sandboxing isolation.
Zero Context Token Consumption
Here's the feature that should make every AI engineer sit up straight: Cupcake policies run completely outside the model. They don't appear in your system prompt. They don't eat your context window. They don't get forgotten in long conversations. This is governance without the overhead that makes prompt-based rules so fragile.
Five-Tier Decision Engine
Cupcake doesn't just block or allow. It returns nuanced decisions that enable sophisticated automation:
- Allow with optional Context Injection — "Proceed, but remember you're on main branch"
- Modify — Sanitize commands, add safety flags, enforce conventions before execution
- Block with Feedback — Stop the action and explain why, enabling agent self-correction
- Warn — Log and display warnings without stopping workflow
- Require Review — Pause for human approval on sensitive operations
Multi-Harness Native Integration
Unlike bolt-on solutions, Cupcake provides first-class integrations for Claude Code, Cursor, Factory AI, and OpenCode—each using the agent's native event formats. Coming soon: AMP and Gemini CLI support, with hooks already requested from their respective teams.
Real-Time Signal Enrichment
Cupcake gathers Signals—live environmental facts like Git branch, CI status, database metadata—to make context-aware decisions. An action that's safe on a feature branch might be blocked on production. This isn't static rule-matching; it's dynamic, environment-sensitive governance.
LLM-as-Judge for Advanced Oversight
For scenarios requiring nuanced judgment, Cupcake Watchdog can interject a secondary LLM or agent evaluation. This hybrid approach combines deterministic speed with interpretive intelligence when you need it.
Enterprise Observability and Audit Trails
Every input, signal, and decision generates structured logs and evaluation traces. For AI SOCs and compliance teams, this isn't just nice-to-have—it's essential infrastructure for governing autonomous systems at scale.
Use Cases: Where Cupcake Shines in Production
1. Preventing Catastrophic Git Operations
Your agent suggests git push --force origin main at 2 AM. Without Cupcake, this executes if your prompt-based rules got buried in context. With Cupcake, a Rego policy intercepts the push, checks the branch, verifies CI status, and either blocks with feedback or requires human review. Production disasters prevented, not recovered from.
2. Securing MCP Tool Access
Model Context Protocol tools give agents superpowers—and super-responsibilities. Cupcake provides native governance for MCP tools like mcp__memory__* and mcp__github__*. Prevent unauthorized data exfiltration, restrict memory operations to approved contexts, and ensure GitHub actions follow your organization's security posture.
3. Sanitizing Dangerous FileSystem Operations
The classic rm -rf / scenario isn't just a meme—agents have suggested destructive operations in real workflows. Cupcake's granular tool control prevents specific tools or arguments entirely. But it goes further: Modify decisions can transform rm * into rm --interactive *, or redirect destructive operations to staging areas.
4. Enforcing Code Quality Gates
Block commits when tests fail. Prevent merges without review. Enforce linting after file edits through reactive automation—tasks you don't need the agent to conduct itself. Cupcake turns your existing CI/CD quality gates into pre-execution enforcement points.
5. Compliance and Audit Requirements
For regulated industries, "the agent made a mistake" isn't an acceptable incident explanation. Cupcake's enriched audit trails provide structured evidence of every decision, every signal considered, every policy evaluated. Your compliance team will actually thank you.
Step-by-Step Installation & Setup Guide
Prerequisites
Cupcake is built with Rust and distributed primarily through Nix for reproducible builds. You'll need:
- Nix with flakes enabled, OR
- Rust toolchain for manual compilation
- Your preferred AI coding agent (Claude Code, Cursor, Factory AI, or OpenCode)
Install Cupcake CLI via Nix (Recommended)
The fastest path to running Cupcake:
# Install directly from GitHub
nix profile install github:eqtylab/cupcake#cupcake-cli
# Verify installation
cupcake --help
# Or run without installing—perfect for CI/CD pipelines
nix run github:eqtylab/cupcake#cupcake-cli -- --help
NixOS System Installation
For NixOS users, add Cupcake to your system declaratively:
# In your flake.nix inputs
inputs.cupcake.url = "github:eqtylab/cupcake";
# In your environment.systemPackages or home.packages
inputs.cupcake.packages.${system}.cupcake-cli
This approach ensures bit-for-bit reproducible deployments across your development team and CI infrastructure.
Development Environment Setup
Contributing or customizing Cupcake? Enter the provided development shell:
# Clone the repository
git clone https://github.com/eqtylab/cupcake.git
cd cupcake
# Enter development shell with Rust toolchain, just, and dependencies
nix develop
# Build and test
cargo build --release
cargo test
Agent Harness Integration
After installing the CLI, configure your specific agent harness:
| Harness | Setup Command | Configuration Location |
|---|---|---|
| Claude Code | cupcake harness install claude |
~/.config/claude/settings.json |
| Cursor | cupcake harness install cursor |
.cursor/rules directory |
| Factory AI | cupcake harness install factory |
Project .factory/ directory |
| OpenCode | cupcake harness install opencode |
~/.opencode/config.yaml |
Each harness creates its policy directory structure automatically:
policies/
├── claude/
│ ├── security/
│ ├── git/
│ └── custom/
├── cursor/
├── factory/
└── opencode/
Writing Your First Policy
Create policies/claude/security/symlink-detection.rego:
package claude.security.symlink
import future.keywords.if
import future.keywords.in
default allow := false
# Block operations that create or follow symlinks in sensitive directories
allow if {
not input.action.path matches "^/etc/.*"
not input.action.tool == "fs_symlink"
}
deny contains msg if {
input.action.tool == "fs_symlink"
input.signals.cwd == "/etc"
msg := "Symlink creation blocked in /etc directory"
}
Compile and activate:
# Compile policy to Wasm
cupcake policy build policies/claude/security/
# Activate for current harness
cupcake policy activate --harness claude --policy security/symlink-detection
REAL Code Examples from the Repository
Let's examine actual patterns from Cupcake's implementation and documentation, with detailed explanations of how they work in production.
Example 1: Nix Flake Installation Pattern
The README provides this exact installation command:
# Install directly from GitHub using Nix
nix profile install github:eqtylab/cupcake#cupcake-cli
# Alternative: ephemeral execution without installation
# Perfect for CI pipelines or testing before committing
nix run github:eqtylab/cupcake#cupcake-cli -- --help
What's happening here? The github:eqtylab/cupcake#cupcake-cli syntax is a Nix flake reference. The #cupcake-cli selects the specific output (package) from the flake. nix profile install adds it to your user profile permanently, while nix run fetches, builds, and executes in one shot—no persistent installation. The trailing -- --help passes --help to the Cupcake CLI itself, not to Nix. This pattern ensures reproducible builds from exact Git commits, eliminating "works on my machine" deployment failures.
Example 2: NixOS System Integration
For declarative system management, the README specifies:
# In your flake.nix inputs section
inputs.cupcake.url = "github:eqtylab/cupcake";
# Then reference in your packages
inputs.cupcake.packages.${system}.cupcake-cli
Deep dive: This is Nix's pure functional package management in action. The inputs.cupcake.url pins the source. The ${system} interpolation selects the correct pre-built binary for your architecture (x86_64-linux, aarch64-darwin, etc.). Because Nix builds are content-addressed, identical inputs produce identical outputs—critical for security tooling where supply chain integrity matters. The SLSA Level 3 badge on the repository confirms this commitment to build provenance.
Example 3: Development Shell Entry
# Enter the development shell with all dependencies
nix develop
Behind the scenes: nix develop drops you into a shell where cargo, rustc, just (command runner), and all native dependencies are available—without polluting your global environment. The flake.nix defines this environment precisely, including specific Rust versions from rust-toolchain.toml. When you exit, everything vanishes. This is how Cupcake maintains contributor environment consistency across macOS, Linux, and NixOS systems.
Example 4: Policy Evaluation Flow (Conceptual Implementation)
While the README illustrates the architecture with this flow:
Agent → (proposed action) → Cupcake → (policy decision) → Agent runtime
The actual implementation involves JSON input packaging. Based on the documented behavior, a typical evaluation input looks like:
{
"action": {
"tool": "git",
"command": "push",
"args": ["--force", "origin", "main"]
},
"signals": {
"git_branch": "main",
"ci_status": "failing",
"timestamp": "2025-01-15T09:23:17Z",
"cwd": "/home/dev/project"
}
}
Evaluation against Rego policy:
package git.security
import future.keywords.if
default decision := {"action": "block"}
# Allow if not force-pushing to main
decision := {"action": "allow"} if {
not (input.action.command == "push"
input.action.args[_] == "--force"
input.signals.git_branch == "main")
}
# Block with feedback for dangerous operation
decision := {
"action": "block",
"feedback": "Force push to main blocked: CI is failing. Fix tests first."
} if {
input.action.command == "push"
input.action.args[_] == "--force"
input.signals.git_branch == "main"
input.signals.ci_status == "failing"
}
Critical insight: The input.signals.ci_status enrichment means Cupcake isn't just pattern-matching commands—it's making context-aware decisions using live environmental data. The agent receives structured feedback ("Fix tests first") enabling autonomous self-correction rather than mysterious failures.
Advanced Usage & Best Practices
Policy Composition Patterns
Organize policies by concern, not by harness alone:
policies/
├── _base/ # Shared utilities and default decisions
├── security/ # Cross-cutting security rules
├── compliance/ # Regulatory requirements
└── harnesses/ # Harness-specific adaptations
Use OPA's import to compose base policies into harness-specific implementations, avoiding dangerous copy-paste divergence.
Signal Enrichment Strategy
Custom signals are Cupcake's superpower. Extend beyond built-in Git/CI signals:
# Custom signal: check Jira ticket status
allow if {
input.signals.jira_ticket.status == "In Progress"
input.action.tool == "git"
input.action.command == "commit"
}
Integrate with your existing toolchain—PagerDuty on-call status, feature flag states, deployment freeze calendars.
Gradual Rollout with Warn Mode
Deploy new policies in Warn mode before enforcing:
decision := {"action": "warn", "message": "Would block: new policy active in 7 days"} if {
# Policy condition
}
Monitor logs, tune false positives, then switch to Block. This operational discipline prevents policy-induced developer friction.
LLM-as-Judge for Ambiguous Cases
Reserve Cupcake Watchdog for high-stakes, low-frequency decisions where Rego's determinism isn't sufficient:
decision := {"action": "watchdog", "reason": "Potential PII in commit message"} if {
regex.match(`\b\d{3}-\d{2}-\d{4}\b`, input.action.message)
}
The secondary LLM evaluates with full context, while your primary agent continues efficiently.
Comparison with Alternatives
| Capability | Cupcake | Prompt-Based Rules | Post-Hoc Monitoring | Custom Middleware |
|---|---|---|---|---|
| Context Token Usage | Zero | High (rules in prompt) | Zero | Zero |
| Evaluation Speed | Sub-millisecond | N/A (inference time) | Seconds (async) | Varies |
| Deterministic Decisions | ✅ Yes | ❌ No | ⚠️ Partial | ✅ If implemented |
| Agent Self-Correction | ✅ Structured feedback | ❌ Often ignored | ❌ After damage | ⚠️ Custom code |
| Multi-Harness Support | ✅ Native integrations | ❌ Per-agent rewrite | ⚠️ Generic only | ❌ Per-agent code |
| Policy-as-Code | ✅ OPA/Rego + Wasm | ❌ Natural language | ❌ Rules scattered | ⚠️ Custom DSL |
| Audit Trail | ✅ Structured logs | ❌ Buried in chat | ⚠️ System logs | ⚠️ Custom logging |
| Signal Enrichment | ✅ Built-in | ❌ Manual prompt | ⚠️ External query | ❌ Custom integration |
| Enterprise Governance | ✅ Designed for | ❌ Ad-hoc | ⚠️ Add-on | ❌ Build yourself |
The verdict: Prompt-based rules fail at scale. Post-hoc monitoring is damage control, not prevention. Custom middleware duplicates Cupcake's engineering effort without its ecosystem. For teams serious about AI agent governance, Cupcake represents the only comprehensive, production-ready solution that combines prevention, performance, and auditability.
FAQ: Developer Concerns Addressed
Does Cupcake consume prompt/context tokens?
No. This is Cupcake's architectural breakthrough. Policies execute in a separate Wasm runtime, completely outside the model's context window. The agent receives only the final decision and optional feedback—not the policy logic itself. Your 200K context window is preserved for actual code, not rule repetition.
Is Cupcake tied to a specific model or vendor?
No. Cupcake's harness architecture supports Claude Code, Cursor, Factory AI, and OpenCode today, with AMP and Gemini CLI coming soon. The TypeScript bindings (./cupcake-ts) enable integration with web-based frameworks like LangChain, Google ADK, NVIDIA NIM, and Vercel AI SDK. Model-agnostic by design.
How fast is policy evaluation?
Sub-millisecond for cached policies in typical setups. The WebAssembly compilation provides near-native execution speed with sandboxing isolation. Even complex policies with multiple signal enrichments complete faster than a single LLM token generation.
Can policies be tested without affecting live agents?
Yes. Cupcake supports dry-run evaluation against recorded agent actions. The policy studio at cupcake-policy-studio.vercel.app provides interactive testing with real harness formats.
What happens when Cupcake blocks an action?
The agent receives structured feedback explaining the block reason, enabling autonomous self-correction. For example: "Tests must pass before pushing. Run cargo test and fix failures." This isn't a dead end—it's a guided correction loop.
Is Cupcake production-ready for enterprise use?
With SLSA Level 3 build provenance, Apache 2.0 licensing, structured audit trails, and support for compliance workflows, Cupcake is designed for enterprise AI governance from day one. The Trail of Bits research partnership underscores its security credentials.
How do I contribute or request features?
See CONTRIBUTING.md in the repository. The Q1 2026 roadmap will incorporate community feedback from this open-source release.
Conclusion: The Future of Agent Governance is Code, Not Prompts
We've reached an inflection point in AI-assisted development. The agents are capable. They're fast. They're increasingly autonomous. But capability without control is liability, not productivity. Every hour spent crafting longer system prompts, every incident from "forgotten" rules, every nervous code review of AI-generated changes—these are symptoms of a governance model that doesn't scale.
Cupcake represents the inevitable evolution: from hoping your agent remembers rules, to encoding rules in enforceable, auditable, performant policy-as-code. The OPA/Rego foundation isn't trendy—it's proven at cloud-native scale. The WebAssembly execution isn't experimental—it's battle-tested in production security systems. The harness integrations aren't shallow wrappers—they're native, first-class partnerships with the agents you already use.
The teams that thrive with AI agents won't be those with the longest prompts. They'll be those with the most reliable guardrails—governance that works while they sleep, scales with their ambition, and proves its decisions when auditors come knocking.
Star Cupcake on GitHub. Install it with Nix. Write your first Rego policy. And finally—finally—stop worrying whether your agent will remember not to force-push at 2 AM. Make it follow the rules.
Follow Cupcake on X for regular updates on agentic security and policy enforcement patterns.
Outils recommandés
Explore on the BrightCoding network
Hand-picked resources from our other sites.
Stop Wasting Hours on Manual Security Audits: RAPTOR Does It Autonomously
RAPTOR transforms Claude Code into an autonomous offensive/defensive security agent that scans, validates, exploits, and patches vulnerabilities. Built by indus...
Memoria: The Git-Powered Memory Fix AI Agents Desperately Need
Memoria brings Git-level version control to AI agent memory with snapshots, branches, and rollback. Built on MatrixOne's Copy-on-Write engine, it eliminates hal...
AnythingLLM: The Privacy-First AI Document Revolution
Discover AnythingLLM, the revolutionary privacy-first AI platform that transforms documents into intelligent chat interfaces. Learn setup, advanced features, an...
Continuez votre lecture
Why Alexandrie is the Ultimate Markdown Note-Taking App
Why CrossPaste is the Ultimate Game Changer for Clipboard Management
Why Chandra is the Ultimate OCR Tool for Handwriting and Tables
Stop Coding Alone: OPC-Skills Gives Your AI Agent Superpowers
Commentaires 0
Aucun commentaire pour l'instant. Soyez le premier à réagir !