Chapter 6·25 min

The Enforcement System

Mechanical enforcement that turns written rules into guaranteed behaviors.

Last updated: March 2026

Why Written Rules Are Not Enough

I wrote 14 rules for my AI system. It followed exactly zero of them consistently — until I added enforcement hooks. Not because the AI was defiant, but because context fills up, instructions get compressed, and the AI drifts from its constraints. Written rules are wishes. Enforced rules are reality. The Genesis Framework solves this with Python scripts called hooks that run before or after every tool call.

"Written rules are wishes. Enforced rules are reality." This is the core philosophy of the Genesis enforcement system.

How Hooks Work

Claude Code supports hook events — Python scripts that execute at specific points in the workflow. These hooks can inspect, approve, or block actions.

  1. 1PreToolUse: Runs BEFORE a tool is used. Can block the action.
  2. 2PostToolUse: Runs AFTER a tool completes. Can validate the output.
  3. 3SubagentStop: Runs when an agent finishes. Can check output quality.
Hook Enforcement ChainAgent callstoolPreToolUse17 hooks (gate)CAN BLOCKTOOL RUNS(if allowed)PostToolUse16 hooks (observe)LOG ONLYPreToolUse Examplesmaster-enforcer.pyenforce-core-reads.pyvalidate-skill-format.pyPostToolUse Examplestrack-protocol-reads.pyverify-agent-protocol.pyknowledge-evaluation.pyBLOCKED + LOGGEDIf no lockfile found33 hooks total — every tool call passes through enforcement before and after execution
Fig 6 — Hook enforcement pipeline

Registering Hooks

Hooks are registered in your Claude Code settings. Here is how to add a hook to your settings.json file.

~/.claude/settings.jsonjson
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/file-guard.py"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/verify-output.py"
          }
        ]
      }
    ]
  }
}

Example: File Access Guard

This hook blocks file writes unless the correct lockfile exists. It enforces the pattern that only authorized agents can modify files.

~/.claude/hooks/file-guard.pypython
#!/usr/bin/env python3
"""
File Guard Hook — blocks Write/Edit unless a lockfile is active.
Enforces: Only authorized agents can modify files.
"""
import sys
import os
import json

def main():
    # Read tool input from stdin
    data = json.load(sys.stdin)
    tool_name = data.get("tool_name", "")

    # Check if any agent lockfile exists
    lockfiles = [
        "/tmp/.file-executor-active",
        "/tmp/.web-developer-active",
        "/tmp/.code-debugger-active",
    ]

    has_lockfile = any(os.path.exists(f) for f in lockfiles)

    if not has_lockfile:
        # Block the action
        result = {
            "decision": "block",
            "reason": "No agent lockfile found. File operations require an active agent."
        }
        print(json.dumps(result))
        sys.exit(0)

    # Allow the action
    result = {"decision": "approve"}
    print(json.dumps(result))

if __name__ == "__main__":
    main()

The Lockfile Protocol

The lockfile protocol is simple: agents create a lockfile when they start work and remove it when they finish. Hooks check for these lockfiles before allowing protected operations.

Lockfile Protocolbash
# Agent startup
touch /tmp/.file-executor-active

# ... agent does its work ...

# Agent cleanup
rm /tmp/.file-executor-active
Tip: Start with one enforcement hook (file access guard) and add more as you discover failure modes. Over-enforcing early makes the system rigid and frustrating.

Enforcement hooks work hand-in-hand with the rules you created in Chapter 4: The Rules System and the protocols from Chapter 5: Protocols. Each hook enforces specific rules mechanically — the routing table, agent constraints, and lockfile protocol all become verified behaviors instead of written suggestions.

The QA Gate Pattern

After any significant implementation, run a QA verification agent. The QA gate has a default posture of NEEDS WORK — it only marks PASS with concrete evidence. This prevents 'looks good to me' approvals.

The QA gate uses a structured FAIL format so developers know exactly what to fix.

QA Gate Structuretext
## Structured FAIL Format (Every failure must include ALL fields)

| Field             | Description                                    |
|-------------------|------------------------------------------------|
| Issue             | Specific problem (not vague "doesn't work")    |
| Severity          | Critical / Major / Minor                        |
| Location          | File path + line number                         |
| Fix Instructions  | Specific steps to resolve                       |
| Expected Outcome  | What success looks like after fix               |
| Retry Count       | Which attempt (1/3, 2/3, 3/3)                  |

## 3-Strike Escalation
| Attempt | Action                                          |
|---------|------------------------------------------------|
| FAIL 1  | Structured feedback -> developer fixes -> retry |
| FAIL 2  | Structured feedback + pattern analysis -> retry  |
| FAIL 3  | ESCALATE to human with root cause hypothesis    |
The default posture is NEEDS WORK, not PASS. This eliminates rubber-stamp approvals. The QA agent must prove quality, not assume it.

Proactive Triggers — Actions Without Prompts

Some agents should fire without being asked. These proactive triggers ensure critical steps are never skipped.

Proactive Trigger Examplestext
| Situation                    | Auto-Trigger Agent        |
|------------------------------|---------------------------|
| Before git push              | Security scanner          |
| Morning greeting             | Chief of staff            |
| Creating new tool/agent      | Registry check first      |
| Before any implementation    | Cartographer (blueprint)  |
| After any implementation     | Cartographer (document)   |
| Photo/image request          | Check existing templates  |
| Student name mentioned       | Load student profile      |

To implement: add detection logic in your hooks that
identifies these situations and injects reminders into
the AI's context.
Proactive triggers are the difference between a system that follows instructions and one that anticipates needs. They catch the steps humans forget.

Confidence Scoring — Quantifying Uncertainty

Strategic agents should quantify how confident they are in their recommendations. This prevents overconfident AI advice and highlights areas that need human verification.

Confidence Scoring Formattext
When an agent provides strategic recommendations,
require a confidence breakdown:

| Recommendation          | Confidence | Rationale          |
|-------------------------|------------|--------------------|
| Use React for frontend  | 0.95       | Industry standard  |
| Redis for caching       | 0.80       | Good fit, untested |
| Custom auth solution    | 0.45       | Complex, risky     |

Flag items below 0.6 with a warning for human review.

Agents that should score confidence:
- Implementation planners
- Researchers
- Debuggers (hypothesis ranking)
- Strategy agents
An AI that says 'definitely do X' when it is only 50% sure is dangerous. Confidence scoring makes uncertainty visible so humans can prioritize what to verify.

The knowledge base (Chapter 7: The Knowledge Base) captures enforcement patterns as reusable skills. When you discover a new failure mode, the self-improvement loop extracts it into a skill file so the same mistake is caught automatically next time.

Frequently Asked Questions

Related Chapters