Field guide / 17 min
Add guardrails with hooks and rules
Observe lifecycle events with trusted commands; control escalation with testable prefix rules.
Hooks run trusted command or MCP-tool handlers at lifecycle events such as PreToolUse, PostToolUse, Stop, and SessionStart. Rules decide whether matching command prefixes are allowed, prompted, or forbidden outside the sandbox. Hooks are stable; rules remain experimental and the most restrictive matching decision wins.
Verified terminal sequence
- ›
/hooks - $
codex execpolicy check --pretty --rules ~/.codex/rules/default.rules -- gh pr view 7888
Working principles
Trust exact hook code
Non-managed hooks are trusted by definition hash; changed hooks must be reviewed again.
Rules match argv prefixes
Write narrow prefixes with positive and negative examples; do not rely on vague shell-string matching.
Guardrail, not fortress
Matching command hooks launch concurrently, so one hook cannot stop another from starting. Command and MCP-tool handlers run; prompt and agent handlers are parsed but skipped.
Field procedure
- 01
Choose the enforcement surface
Use AGENTS.md for guidance, hooks for lifecycle actions, rules for command escalation, and CI for authoritative checks.
- 02
Create one hook
Start with a read-only validation or logging command and a narrow matcher.
- 03
Review it in /hooks
Inspect source, exact command, and trust state before allowing execution.
- 04
Write a prefix rule
Include match and not_match examples and the safest decision that fits the command.
- 05
Test with execpolicy
Run codex execpolicy check before depending on the experimental rule in real work.
PASS / FAIL
Acceptance checklist
- Hook source and hash are reviewed.
- Matcher scope is narrow.
- Rule examples pass.
- CI still enforces critical invariants.
WATCH / REJECT
Failure patterns
- Bypassing hook trust in normal interactive work.
- Claiming prompt or agent hook handlers run today.
- Using experimental rules as the only destructive-action defense.