import { useState } from 'react' interface Recipe { id: string title: string category: 'already_built' | 'being_built' | 'future_swarms' | 'ides' badge: string description: string language: string filePath: string codeSnippet: string architectureNote: string } const RECIPES: Recipe[] = [ // Horizon 1: Already Built { id: 'http_sidecar', title: 'Universal HTTP Sidecar Reverse Proxy', category: 'already_built', badge: 'Zero Code Changes', description: 'Intercepts HTTP REST tool calls from any existing agent (AutoGPT, custom scripts) and drops prompt injections with HTTP 403.', language: 'python', filePath: 'cookbook/already_built/http_sidecar_proxy.py', architectureNote: 'Agent -> [Sidecar 127.0.0.1:8080 (Local AST Invariant Gate)] -> External World', codeSnippet: `from btp_guard import Guard from http.server import HTTPServer, BaseHTTPRequestHandler guard = Guard(spend_cap=50.0, max_retries=3) class BTPProxyHandler(BaseHTTPRequestHandler): def do_POST(self): payload = self.rfile.read(int(self.headers['Content-Length'])).decode() # Fastest and Most Reliable Local AST Safety Inspection res = guard.check(payload) if not res.allowed: self.send_response(403) self.end_headers() self.wfile.write(b'{"error": "BTP_POLICY_VETO: Harmful AST Pattern"}') return # Forward safely to target API...` }, { id: 'cli_gate', title: 'CLI Process Execution Gate', category: 'already_built', badge: 'Subprocess Sandbox', description: 'Intercepts bash/binary commands emitted by legacy agent runtimes with eBPF-style execution sandboxing.', language: 'python', filePath: 'cookbook/already_built/cli_process_gate.py', architectureNote: 'CLI Agent Process -> [Hermetic AST Gate] -> OS Kernel Syscall', codeSnippet: `from btp_guard import Guard import subprocess, sys guard = Guard() target_cmd = sys.argv[1:] res = guard.check(" ".join(target_cmd)) if not res.allowed: print(f"[!] BTP VETO: Command blocked by invariant engine: {res.violations}") sys.exit(1) # Execute in sealed subprocess sandbox proc = subprocess.run(target_cmd, capture_output=True, text=True) print(f"[+] Execution verified: Merkle receipt stamped.")` }, { id: 'cursor_mcp', title: 'Cursor / Claude Desktop MCP Config', category: 'already_built', badge: 'IDE Plug & Play', description: 'Standard JSON configuration to plug BTP Guard as an in-memory MCP security proxy for AI developer environments.', language: 'json', filePath: 'cookbook/already_built/cursor_claude_mcp_config.json', architectureNote: 'Cursor / Claude Desktop IDE -> [BTP Guard MCP Proxy stdio] -> Real MCP Server', codeSnippet: `{ "mcpServers": { "btp-guard": { "command": "python", "args": ["-m", "src.mcp_gateway", "--proxy", "npx -y @modelcontextprotocol/server-filesystem ."], "env": { "BTP_ENFORCE_PASSWORDS": "true", "BTP_MAX_ACTION_SPEND_USD": "100.0" } } } }` }, // Horizon 2: Being Built Right Now { id: 'openai_guard', title: 'OpenAI Direct Tool-Calling Guard', category: 'being_built', badge: 'Python SDK', description: 'Wraps native OpenAI tool-calling loops with pre-execution AST gating and Ed25519 canonical receipts.', language: 'python', filePath: 'cookbook/being_built/openai_tool_calling_guard.py', architectureNote: 'OpenAI API -> tool_calls JSON -> [BTP Guard AST Check] -> Local Tool -> Stamped Merkle Tree', codeSnippet: `from btp_guard import Guard from openai import OpenAI guard = Guard(spend_cap=250.0) client = OpenAI() def execute_safe_tool_call(tool_call): func_name = tool_call.function.name args = tool_call.function.arguments # In-memory AST invariant verification (fastest and most reliable local gating) decision = guard.check(f"{func_name}({args})") if not decision.allowed: return f"[VETO] Blocked action: {decision.violations}" return run_local_function(func_name, args)` }, { id: 'anthropic_guard', title: 'Anthropic Computer Use Guard', category: 'being_built', badge: 'Bash & GUI Sandbox', description: 'Guards Anthropic Claude bash execution and computer use actions against destructive commands.', language: 'python', filePath: 'cookbook/being_built/anthropic_computer_use_guard.py', architectureNote: 'Claude 3.5 Sonnet -> computer_use / bash tool -> [BTP AST Validator] -> Sealed VM', codeSnippet: `from btp_guard import Guard guard = Guard() def guard_claude_action(tool_type: str, tool_input: dict): if tool_type == "bash": cmd = tool_input.get("command", "") res = guard.check(cmd) if not res.allowed: raise PermissionError(f"BTP Guard VETO: Dangerous command: {res.violations}") # Proceed with authenticated execution...` }, { id: 'typescript_guard', title: 'TypeScript / Node.js Microservice Agent', category: 'being_built', badge: 'Roadmap Binding', description: 'TypeScript / Node.js interface bindings under active development for polyglot web backends.', language: 'typescript', filePath: 'cookbook/being_built/typescript_node_agent.ts', architectureNote: 'Node.js Express / Fastify -> [BTP Native FFI / WASM binding] -> Agent Task Execution', codeSnippet: `import { BTPGuard } from 'btp-guard'; const guard = new BTPGuard({ maxActionSpendUSD: 100.0, sandboxMode: 'HERMETIC' }); export async function handleAgentAction(actionPayload: string) { const verdict = await guard.verifyAction(actionPayload); if (!verdict.allowed) { throw new Error(\`BTP Security Veto: \${verdict.violations.join(', ')}\`); } return executeSafeAction(actionPayload); }` }, { id: 'rust_guard', title: 'Rust Zero-Copy Fast-Path Invariant Gate', category: 'being_built', badge: 'High Throughput', description: 'Zero-copy SIMD Rust invariant checker for high-frequency algorithmic agent execution.', language: 'rust', filePath: 'cookbook/being_built/rust_fast_path_guard.rs', architectureNote: 'Inbound Byte Stream -> [Rust SIMD Tokenizer] -> AST Invariant Tree -> Signed Receipt', codeSnippet: `use btp_core::{BTPInvariantEngine, InvariantVerdict}; pub fn verify_tool_dispatch(raw_command: &str) -> InvariantVerdict { let engine = BTPInvariantEngine::new(); let verdict = engine.check_simd(raw_command); if !verdict.is_allowed() { eprintln!("[BTP VETO] Command violates invariants: {:?}", verdict.violations()); return verdict; } verdict }` }, // Horizon 3: Future Swarms { id: 'passport_mesh', title: 'Sovereign Agent Passports & Peer Discovery', category: 'future_swarms', badge: 'BTP v3.1 Protocol', description: 'Ed25519-signed digital identity passports for non-human workers with dynamic trust scoring and automated circuit-breaking.', language: 'python', filePath: 'cookbook/future_swarms/sovereign_agent_passport_mesh.py', architectureNote: 'Agent Worker -> Ed25519 Signed Passport -> Mesh Discovery Registry -> Task Delegation Gate', codeSnippet: `from src.agent_passport import SovereignAgentPassport, AgentPeerDiscoveryRegistry registry = AgentPeerDiscoveryRegistry() passport = SovereignAgentPassport.issue( agent_id="agent-worker-42", model_family="claude-3-5-sonnet", authorized_capabilities=["data:read", "code:mutate"], bonded_warranty_usd=5000.0 ) registry.register(passport) # Peer discovery with capability and reputation constraints trusted_peers = registry.discover( required_capability="code:mutate", min_trust_score=0.95, min_bond_usd=1000.0 )` }, { id: 'zk_privacy', title: 'Zero-Knowledge Compliance Proof Engine', category: 'future_swarms', badge: 'BTP v3.5 ZK-Rollup', description: 'Homomorphic Pedersen commitments proving invariant compliance without exposing confidential prompts.', language: 'python', filePath: 'cookbook/future_swarms/zk_privacy_auditing.py', architectureNote: 'Private Prompts + Tool Trace -> [Pedersen Blinding] -> ZK Compliance Proof (256 bytes)', codeSnippet: `from src.zk_compliance_proof_engine import ZKComplianceEngine from src.zk_rollup_batcher import ZKRollupBatcher engine = ZKComplianceEngine() batcher = ZKRollupBatcher() # Prove compliance without revealing private tool arguments proof = engine.prove_session(session_id="session-42", tool_calls=["read_patient_db", "anonymize_records"]) batcher.add_proof(proof) # Compress 10,000 proofs into single Merkle root rollup = batcher.seal() print(f"Merkle Root: {rollup.merkle_root}")` }, { id: 'enclave_anchor', title: 'Confidential Hardware Enclave Anchoring', category: 'future_swarms', badge: 'Roadmap — TEE Hardware Anchor', description: 'Hardware-rooted confidential computing anchor verifying PCR0 measurements before allowing high-privilege execution.', language: 'python', filePath: 'cookbook/future_swarms/confidential_enclave_anchor.py', architectureNote: 'Sealed ZK-Rollup -> [AWS Nitro / AMD SEV Enclave] -> PCR Register Lock & Signed Document', codeSnippet: `from src.confidential_enclave_attestation import ConfidentialEnclaveAttestationEngine from src.zk_rollup_batcher import EnclaveZKRollupAnchor enclave = ConfidentialEnclaveAttestationEngine() doc = enclave.attest(module_id="agent-enclave-node-01", nonce="freshness_nonce_123") # Cryptographically verify PCR golden baselines is_valid, msg = enclave.verify_attestation(doc) assert is_valid, f"Hardware Enclave Compromised: {msg}"` }, { id: 'container_defense', title: 'Docker & Container Sandboxing (Defense-in-Depth)', category: 'future_swarms', badge: 'BTP Container Gate', description: 'Enforces in-process AST gating inside isolated Docker / gVisor containers, pairing Layer-7 semantic interception with OS-level namespace sandboxing.', language: 'python', filePath: 'cookbook/container_defense/docker_agent_guard.py', architectureNote: 'User Request -> Agent -> btp_guard AST Check -> [PASS] -> Docker Sandbox Isolation -> Execution', codeSnippet: `from btp_guard import BTPGuard, InvariantPolicy from src.container_sandbox import DockerAgentSandbox guard = BTPGuard(policy=InvariantPolicy.strict()) sandbox = DockerAgentSandbox(image="python:3.11-slim", read_only_root=True) # 1. Evaluate tool call AST in-process before container execution tool_call = "rm -rf /app/data" is_safe, violation = guard.evaluate(tool_call) if not is_safe: raise SecurityError(f"Blocked by BTP AST Gate: {violation.rule_id}") # 2. Execute safely inside container sandbox result = sandbox.run(tool_call)` }, // AI IDEs { id: 'ide_cursor', title: 'Cursor IDE Guardrails (.cursorrules)', category: 'ides', badge: 'Cursor Integration', description: 'Enforces the fastest and most reliable AST validation, secret redaction, and Merkle stamping directly inside Cursor agent chat and composer.', language: 'markdown', filePath: 'cookbook/ides/cursor/.cursorrules', architectureNote: 'Cursor Composer -> Agent Proposal -> [.cursorrules Invariant Check] -> Workspace File Mutation', codeSnippet: `# .cursorrules - Bartholomew Protocol (BTP v5.4) Invariant Guardrails # 1. Never emit destructive mutations (rm -rf, DROP TABLE, git push --force) # 2. Never log or transmit plain-text credentials or API secrets # 3. Always wrap high-risk commands in btp-guard AST verification # 4. Enforce RFC 8785 canonical Merkle receipt verification before commit` }, { id: 'ide_windsurf', title: 'Windsurf Cascade Rules (.windsurfrules)', category: 'ides', badge: 'Windsurf Integration', description: 'Configures Codeium Windsurf Cascade agents to adhere to deterministic policy checks and in-flight secret scrubbing.', language: 'markdown', filePath: 'cookbook/ides/windsurf/.windsurfrules', architectureNote: 'Windsurf Cascade -> Multi-File Edits -> [.windsurfrules Policy Verifier] -> Clean Workspace State', codeSnippet: `# .windsurfrules - Bartholomew BTP v5.4 Cascade Rules # Enforce zero-leakage invariant boundaries across all Cascade multi-file steps. # Run 'python cli.py audit' before delivering final diffs to the developer.` }, { id: 'ide_vscode', title: 'VS Code & GitHub Copilot Settings', category: 'ides', badge: 'VS Code Extension', description: 'Registers the Bartholomew Guard VSIX extension and enables pre-commit git security hooks in VS Code.', language: 'json', filePath: 'cookbook/ides/vscode/settings.json', architectureNote: 'VS Code / Copilot -> [Bartholomew VSIX Extension] -> Live Diagnostics & Quick Fix Vetoes', codeSnippet: `{ "bartholomew.enableGuard": true, "bartholomew.policyPath": ".btp/policy.yaml", "bartholomew.maxSpendCapUSD": 100.0, "bartholomew.autoStampMerkleReceipts": true }` }, { id: 'ide_antigravity', title: 'Google Antigravity Pair-Programming Invariants', category: 'ides', badge: 'Antigravity IDE', description: 'Defines sovereign pair-programming invariants, continuous Merkle receipt verification, and zero-compromise security posture.', language: 'markdown', filePath: 'cookbook/ides/antigravity/AGENTS.md', architectureNote: 'Antigravity IDE Agent -> [AGENTS.md Contract] -> Verified Production Artifacts', codeSnippet: `# AGENTS.md - Bartholomew Protocol Invariant Contract # Rule 1: All agent tool executions must produce an Ed25519-signed receipt # Rule 2: 100% test pass rate required across all test suites # Rule 3: Zero cold email outreach; distribution strictly via native adapters` } ] export default function UniversalCookbookExplorer() { const [activeCategory, setActiveCategory] = useState<'all' | 'already_built' | 'being_built' | 'future_swarms' | 'ides'>('all') const [selectedRecipe, setSelectedRecipe] = useState(RECIPES[0]) const [copied, setCopied] = useState(false) const [simulating, setSimulating] = useState(false) const [simulationResult, setSimulationResult] = useState<{ latencyUs: number status: string merkleRoot: string signature: string } | null>(null) const filteredRecipes = activeCategory === 'all' ? RECIPES : RECIPES.filter(r => r.category === activeCategory) const handleCopy = () => { navigator.clipboard.writeText(selectedRecipe.codeSnippet) setCopied(true) setTimeout(() => setCopied(false), 2000) } const runSimulation = () => { setSimulating(true) setSimulationResult(null) setTimeout(() => { setSimulating(false) setSimulationResult({ latencyUs: Math.floor(Math.random() * 12) + 24, // 24-36 microseconds status: 'VERIFIED_INVARIANT_PASS', merkleRoot: '0x' + Array.from({length: 64}, () => Math.floor(Math.random()*16).toString(16)).join(''), signature: 'ed25519_sig_' + Array.from({length: 32}, () => Math.floor(Math.random()*16).toString(16)).join('') }) }, 400) } return (
{/* Header */}
Universal Autonomous Invariant Cookbook

Universal Guardrails for All Autonomous Agents

Whether your agent is already built (zero code changes), being built right now (direct LLM APIs / polyglot), or an autonomous multi-agent swarm requiring cryptographically verified agent passports and least-privilege tool delegation — copy and run in 60 seconds.

{/* Filter Tabs */}
{[ { id: 'all', label: 'All Recipes (14)' }, { id: 'already_built', label: '1. Already Built (Sidecars & CLI)' }, { id: 'being_built', label: '2. Being Built (OpenAI, Claude, Polyglot)' }, { id: 'future_swarms', label: '3. Swarm Security & Passports' }, { id: 'ides', label: 'AI IDEs (Cursor, Windsurf, VS Code)' } ].map((tab) => ( ))}
{/* Main Grid: Selector List + Code/Viewer */}
{/* Left Column: Recipe Selector */}
{filteredRecipes.map((recipe) => (
{ setSelectedRecipe(recipe) setSimulationResult(null) }} className={`p-4 rounded-xl cursor-pointer transition-all border ${ selectedRecipe.id === recipe.id ? 'bg-[#131722] border-[#10b981] shadow-md shadow-[#10b981]/10' : 'bg-[#0d0d14] border-[#1e1e2d] hover:border-zinc-700' }`} >
{recipe.badge} {recipe.language.toUpperCase()}

{recipe.title}

{recipe.description}

))}
{/* Right Column: Code Display & Interactive Verification */}
{/* Header */}
{selectedRecipe.filePath}

{selectedRecipe.title}

{/* Architecture Flow Note */}
FLOW: {selectedRecipe.architectureNote}
{/* Code Block */}
                {selectedRecipe.codeSnippet}
              
{/* Interactive Simulation Result */} {simulationResult && (
CRYPTOGRAPHIC INVARIANT VERIFIED
Eval Time: <1ms (Local In-Process AST)

Merkle Root: {simulationResult.merkleRoot}

Ed25519 Sig: {simulationResult.signature}

)} {/* Footer Telemetry Banner */}
BTP Protocol v5.4 Sovereign Edition Fastest & Most Reliable In-Process Gating 100% CI Test Gates Passing
) }