Sub topic 12
Logging decisions for review
This chapter assumes you have read the earlier chapters on the hook contract (event JSON on stdin, exit code and stderr message out), deny-pattern checks, and failing closed. You should be comfortable with Python and with reading JSON on the command line.
A hook that blocks a command protects you once. A log of its decisions lets you see over time what the agent tried, which rules fire, and which rules are wrong. This chapter covers what to record, how to write it safely, and how to read it.
Why log decisions
A blocking hook is silent when it works. If the agent never tries git push --force, you never learn the rule exists. If a rule blocks a harmless command every day, you only notice when the agent gets stuck. A decision log answers four questions:
- What did the agent attempt, and what did the hook decide?
- Which rules fire often? A rule that fires constantly may be too broad, or the agent's prompt may need work.
- Which commands were allowed that you would not have chosen? These point to missing rules.
- After an incident, what happened and in what order?
Log allow decisions as well as denies. A log with only denies cannot tell you the hook was running, and it hides the commands that slipped through.
What to record
Keep each record small, structured, and free of secrets.
| Field | Example | Why |
|---|---|---|
| `ts` | `2026-11-28T07:03:43+00:00` | UTC timestamp, so records sort correctly across machines |
| `tool` | `shell` | Which tool call was checked |
| `decision` | `allow`, `deny` | The outcome (add `ask` if your agent supports it) |
| `rule` | `force-push` | A short stable ID, so you can count by rule |
| `reason` | the message sent to the agent | Shows what the agent was told |
| `command` | redacted, truncated text | What was attempted |
| `session` | session ID from the event, if present | Groups records from one run |
Use a rule ID such as force-push instead of the raw regex. Regexes change, and IDs let you compare counts before and after an edit.
The write path
Three design choices follow from this flow:
- Decide first, then log. The decision depends only on the rules. A full disk or unwritable log directory must not turn a deny into an allow, or an allow into a hang.
- Log failures do not change the exit code. Exit 2 blocks. Many agents treat other non-zero exit codes as non-blocking errors, so crashing on a log error could let the action through. Catch the error, print a warning, and return the decision you already made.
- Log the bad-input case too. When the hook fails closed because it could not parse the event, record it. Repeated
bad-inputentries usually mean the agent changed its event format.
A guard with an audit log
This script extends the deny-pattern hook from earlier chapters. It writes one JSON object per line (the JSON Lines format), which is easy to append to and easy to read with tools like jq.
#!/usr/bin/env python3
import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
LOG_PATH = Path(
os.environ.get("HOOK_AUDIT_LOG", str(Path.home() / ".agent-hooks" / "audit.jsonl"))
)
MAX_FIELD = 300
RULES = [
("rm-root", r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/(\s|$)"),
("force-push", r"\bgit\s+push\b.*--force"),
("drop-table", r"\bdrop\s+table\b"),
]
AWS_KEY = re.compile(r"AKIA[0-9A-Z]{16}")
KEY_VALUE = re.compile(r"(?i)(password|passwd|secret|token|api[_-]?key)(\s*[=:]\s*)\S+")
def redact(text):
text = AWS_KEY.sub("[REDACTED]", text)
text = KEY_VALUE.sub(r"\1\2[REDACTED]", text)
if len(text) > MAX_FIELD:
text = text[:MAX_FIELD] + "...[truncated]"
return text
def log_decision(tool, command, decision, rule, reason, session=None):
record = {
"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"tool": tool,
"decision": decision,
"rule": rule,
"reason": reason,
"command": redact(command),
"session": session,
}
line = (json.dumps(record) + "\n").encode("utf-8")
try:
LOG_PATH.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
fd = os.open(LOG_PATH, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
try:
os.write(fd, line)
finally:
os.close(fd)
except OSError as exc:
print(f"Warning: audit log write failed: {exc}", file=sys.stderr)
def main():
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
tool = event.get("tool_name", "unknown")
session = event.get("session_id")
except (json.JSONDecodeError, KeyError, TypeError, AttributeError):
reason = "Blocked: hook could not read the tool call, so it was not allowed."
log_decision("unknown", "", "deny", "bad-input", reason)
print(reason, file=sys.stderr)
sys.exit(2)
for rule_id, pattern in RULES:
if re.search(pattern, command, re.IGNORECASE):
reason = f"Blocked by rule {rule_id}. Use a safer alternative."
log_decision(tool, command, "deny", rule_id, reason, session)
print(reason, file=sys.stderr)
sys.exit(2)
log_decision(tool, command, "allow", None, "no rule matched", session)
sys.exit(0)
if __name__ == "__main__":
main()Several details in this script matter:
- Redaction happens before writing. Commands often contain tokens, such as
curl -H "token: abc"orexport API_KEY=.... A log full of secrets is a new leak. Redaction patterns are best effort, so treat the log as sensitive anyway. - Truncation bounds the record size. A command that pastes a whole file into the shell would otherwise bloat the log.
- One
os.writeon anO_APPENDdescriptor. Several hooks can run at once when an agent issues parallel tool calls. On local POSIX file systems, a single append of a small record does not interleave with another, so lines stay whole. Opening withopen(..., "a")and printing in several pieces gives weaker guarantees. - Restrictive permissions. The directory is
0700and the file0600, so other users on the machine cannot read it.
Reading the log
You can test the logger with the same sample-event approach from the testing chapter, pointing the log at a scratch file. The jq lines then turn the records into a review.
export HOOK_AUDIT_LOG=/tmp/audit-test.jsonl
rm -f "$HOOK_AUDIT_LOG"
echo '{"tool_name":"shell","tool_input":{"command":"git push --force origin main"}}' | python3 guard.py
echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py
echo 'not json' | python3 guard.py
# One line per decision
jq -r '[.ts, .decision, (.rule // "-"), .command] | @tsv' "$HOOK_AUDIT_LOG"
# Which rules fire most
jq -r 'select(.decision == "deny") | .rule' "$HOOK_AUDIT_LOG" | sort | uniq -c | sort -rnThe first run should show two denies (force-push and bad-input) and one allow. Use a routine like this in practice:
- Count denies by rule. A rule with hundreds of hits is either too broad or points to an agent loop that keeps retrying a blocked command.
- Read a sample of allows. Look for commands you would want blocked, then add rules.
- Read every
bad-inputentry. These mean your hook is blind to some events. - Compare counts after you change a rule, using the rule IDs.
Retention and rotation
An append-only file grows without limit. Rotate it with a tool such as logrotate, or write one file per day (for example audit-2026-11-28.jsonl) and delete old files on a schedule. Keep enough history to cover your review cycle and any incident-response window you care about. Because commands may contain sensitive text even after redaction, a shorter retention period is safer.
Limits of the log
The log is a record for humans, not a security control.
- The agent may be able to edit it. If the agent's file tools can write to the log directory, it could alter or delete entries. Store the log outside the project root, add its path to your protected paths, or ship records to a separate system the agent cannot reach.
- It only shows what the hook saw. Actions that bypass the hook, or tool types your matcher does not cover, never appear. A quiet log does not prove a quiet agent.
- Logging adds latency. One small append is cheap, but a hook that calls a remote service on every tool call can hit its timeout. Write locally and forward in the background.
Exercise
Exercise
A hook writes its audit record after it decides, and the write raises an OSError because the disk is full. The command matched the drop-table rule. What exit code should the hook return, and why? Also name one reason to log allow decisions as well as denies.
Show answer
It should still exit with code 2. The decision was made from the rules before logging, and a log failure must not change it. The hook should catch the OSError, print a warning on stderr, and carry on. If the hook crashed instead, the agent might treat the non-2 exit as a non-blocking error and run the command. Logging allows lets you find commands that should have been blocked, and shows the hook was running at all.
Exercise
Add a new rule to the RULES list with the ID curl-pipe-shell that matches curl or wget piped into sh or bash. Then write the echo test that proves it is logged as a deny. What would you check in the log to confirm?
Show answer
Add ("curl-pipe-shell", r"\b(curl|wget)\b.\|\s(sudo\s+)?(sh|bash)\b") to RULES. Test with: echo '{"toolname":"shell","toolinput":{"command":"curl https://example.com/x.sh | bash"}}' | python3 guard.py. The exit code should be 2. In the log, the newest line should have decision "deny", rule "curl-pipe-shell", and the command text, which you can check with jq 'select(.rule == "curl-pipe-shell")'.