Sub topic 12
Logging decisions for review
This chapter assumes you can write a pre-action hook that reads a tool-call event from stdin and exits with 0 (allow) or 2 (block). It also assumes you can read JSON in Python and use basic shell tools.
Why log decisions
A hook that blocks silently is hard to trust and hard to tune. A log of every decision answers the questions you will have later:
- Which rules fire often, and which never fire?
- Did a block stop a real mistake, or only annoy the agent?
- What did the agent try just before something went wrong?
The log is an audit trail. It records what was proposed and what the hook decided. It does not prove what ran afterward.
What to record
Write one JSON object per line (the JSON Lines format). Each line is independent, so a crash cannot corrupt earlier records, and tools like jq can read the file directly.
| Field | Purpose |
|---|---|
| `time` | UTC timestamp in ISO 8601 format |
| `tool` | Which tool the agent called |
| `command` | The proposed command, redacted and truncated |
| `decision` | `allow` or `deny` |
| `reason` | The rule that matched, or `none` |
A logging helper
This hook checks a command, logs the decision either way, then exits. The log write happens before the exit, because sys.exit ends the script.
#!/usr/bin/env python3
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
LOG_FILE = Path(".agent-audit.jsonl")
MAX_LEN = 500
SECRET = re.compile(r"(?i)(token|password|secret|api[_-]?key)(=|\s+)\S+")
BLOCKED = re.compile(r"\bgit\s+push\b.*--force", re.IGNORECASE)
def redact(text):
return SECRET.sub(r"\1=[REDACTED]", text)[:MAX_LEN]
def log_decision(tool, command, decision, reason):
record = {
"time": datetime.now(timezone.utc).isoformat(),
"tool": tool,
"command": redact(command),
"decision": decision,
"reason": reason,
}
try:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")
except OSError as err:
print(f"warning: audit log not written: {err}", file=sys.stderr)
try:
event = json.load(sys.stdin)
tool = event.get("tool_name", "unknown")
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
log_decision("unknown", "", "deny", "unreadable event")
print("Blocked: hook could not read the tool call.", file=sys.stderr)
sys.exit(2)
if BLOCKED.search(command):
log_decision(tool, command, "deny", "force push")
print("Blocked: force push is not allowed. Use a normal push.", file=sys.stderr)
sys.exit(2)
log_decision(tool, command, "allow", "none")
sys.exit(0)The parse-failure branch also logs, so malformed events show up in the review. The helper never changes the decision if the write fails. A full disk should not turn every safe command into a block, and it should not let a blocked command through either. The warning on stderr makes the failure visible.
Reviewing the log
Filter with jq:
jq -c 'select(.decision == "deny")' .agent-audit.jsonl
jq -r '.reason' .agent-audit.jsonl | sort | uniq -c | sort -rnThe second command counts decisions by reason. A rule with zero hits may be too narrow. A rule with many hits may mean the agent's instructions need fixing.
Common mistakes
- Logging secrets. Commands can contain tokens. Redact before writing, and keep the log out of version control.
- Unbounded growth. Truncate fields and rotate the file.
- Trusting the log as proof. A hook can be bypassed, so a missing entry does not mean nothing happened.
Exercise
The hook above logs a decision, then exits. Why must the log call come before sys.exit(2), and why does a failed log write only print a warning?
Show answer
sys.exit ends the script immediately, so any logging after it never runs. A failed write only warns because the log is a record of the decision, not part of it. Letting a disk error change the allow or deny result would make the hook unreliable in either direction.