Sub topic 12
Recording decisions for audit
This chapter assumes you have read the earlier chapters on approval gates, decision types, and binding an approval to the exact action. You should be comfortable with short Python programs, JSON, and hashing a payload with hashlib. The goal is to record approvals so that someone can later answer what the agent tried to do, who decided, what they saw, and what happened next.
What an audit trail is for
An approval gate protects you at the moment of the decision. An audit trail protects you afterward. It lets you:
- investigate an incident, such as an email that should not have gone out
- show a compliance reviewer that a human approved a risky action
- debug the workflow itself, for example by finding tools that are always rejected or reviewers who approve in two seconds
- replay the evidence when a user disputes what the agent did
An application log line such as approved send_email supports none of these. It does not say who approved, which arguments they saw, or whether those arguments were the ones that ran. An audit trail is a structured, append-only record designed to be read by someone who was not there.
What to record
Log each stage of the approval as its own event, not one row that is updated as the run progresses. A single approval produces at least three events:
- requested: the agent proposed an action and the gate paused.
- decided: a reviewer approved, rejected, or edited it, or the request expired.
- executed: the tool ran (or was skipped) and produced an outcome.
Separate events show gaps. A requested event with no decided event means the request is stuck. A decided event with no executed event means the resume step failed or was blocked by the fingerprint check.
| Field | Why it matters |
|---|---|
| `run_id`, `approval_id` | Links the events of one approval and ties them to the workflow run |
| `event` | `requested`, `decided`, or `executed` |
| `tool`, `risk` | Shows what was proposed and how the classifier rated it |
| `fingerprint` | Proves which exact action the event refers to, without storing secrets |
| `args` (redacted) | Lets a human read what was proposed |
| `reviewer` | Identifies who decided (a user ID, not a display name) |
| `action`, `reason` | The decision and the reviewer's explanation |
| `original_fingerprint` | For edits, the fingerprint of the agent's first proposal |
| `policy_version` | Which classification rules were active, so old decisions can be judged by old rules |
| `outcome` | Success, error, or skipped, plus an error code if any |
| `ts`, `seq` | When the event happened and its position in the log |
For an edit decision, record both the original proposal and the edited arguments. If you keep only the edited version, you lose the evidence that the agent proposed something different, and that evidence is often the most useful part of an investigation.
How the events fit together
Write the decided event before running the tool. If the process crashes between the two steps, the log still shows that a decision existed. If you write only after the tool runs, a crash loses the evidence of an action that may have taken effect.
An append-only log with tamper evidence
An audit log is only useful if people trust it. Two properties give that trust. First, entries are never updated or deleted by the application. Second, any change made after the fact is detectable. A hash chain provides the second property. Each entry stores the hash of the previous entry, so editing or removing one entry breaks every hash after it.
import hashlib
import json
import time
GENESIS = "0" * 64
def _entry_hash(prev_hash: str, event: dict) -> str:
body = json.dumps(event, sort_keys=True, separators=(",", ":"))
return hashlib.sha256((prev_hash + body).encode()).hexdigest()
class AuditLog:
def __init__(self):
self.entries = []
def append(self, event: dict) -> dict:
prev = self.entries[-1]["hash"] if self.entries else GENESIS
event = {**event, "seq": len(self.entries), "ts": time.time()}
entry = {"event": event, "prev": prev, "hash": _entry_hash(prev, event)}
self.entries.append(entry)
return entry
def verify(self) -> bool:
prev = GENESIS
for entry in self.entries:
if entry["prev"] != prev:
return False
if entry["hash"] != _entry_hash(prev, entry["event"]):
return False
prev = entry["hash"]
return TrueThis class keeps entries in memory so the example runs on its own. In production the same structure goes into a database table or a write-once store. Give the application's database role insert and select permission only, with no update or delete. A hash chain stored in a table the application can rewrite is weak, because someone with write access can recompute every hash. For stronger guarantees, periodically copy the latest hash to a separate system, such as a different account's storage bucket or a signed timestamp service.
Recording the three events
The next code connects the log to the gate. It reuses the fingerprint idea from the previous chapter and adds redaction, so secrets never reach the log.
import hashlib
import json
SENSITIVE_KEYS = {"password", "api_key", "token", "ssn"}
def fingerprint(name: str, args: dict) -> str:
payload = json.dumps({"name": name, "args": args}, sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()
def redact(args: dict) -> dict:
return {k: ("[redacted]" if k in SENSITIVE_KEYS else v) for k, v in args.items()}
def audited_step(log, run_id, approval_id, name, args, risk, ask_human, tools, policy_version="2026-11-01"):
base = {"run_id": run_id, "approval_id": approval_id, "tool": name, "policy_version": policy_version}
fp = fingerprint(name, args)
log.append({**base, "event": "requested", "risk": risk, "fingerprint": fp, "args": redact(args)})
decision = ask_human(name, args) # e.g. {"reviewer": "u-42", "action": "approve"}
final_args = decision.get("args", args) if decision["action"] == "edit" else args
final_fp = fingerprint(name, final_args)
log.append({
**base,
"event": "decided",
"reviewer": decision["reviewer"],
"action": decision["action"],
"reason": decision.get("reason", ""),
"original_fingerprint": fp,
"fingerprint": final_fp,
"args": redact(final_args),
})
if decision["action"] not in ("approve", "edit"):
log.append({**base, "event": "executed", "fingerprint": final_fp, "outcome": "skipped"})
return {"rejected": True, "reason": decision.get("reason", "")}
try:
result = tools[name](**final_args)
outcome = "success"
except Exception as exc:
log.append({**base, "event": "executed", "fingerprint": final_fp, "outcome": "error", "error": type(exc).__name__})
raise
log.append({**base, "event": "executed", "fingerprint": final_fp, "outcome": outcome})
return result
if __name__ == "__main__":
log = AuditLog()
tools = {"send_email": lambda to, body: f"sent to {to}"}
def reviewer(name, args):
return {"reviewer": "u-42", "action": "edit", "reason": "wrong recipient",
"args": {**args, "to": "[email protected]"}}
audited_step(log, "run-1", "appr-1", "send_email",
{"to": "[email protected]", "body": "Hello"}, "high", reviewer, tools)
for e in log.entries:
print(e["event"]["seq"], e["event"]["event"], e["event"].get("action", ""), e["event"].get("outcome", ""))
print("chain valid:", log.verify())
log.entries[1]["event"]["reviewer"] = "u-99" # simulated tampering
print("chain valid after edit:", log.verify())The script prints three events and chain valid: True, then chain valid after edit: False after the simulated tampering. The AuditLog class from the previous block must be in the same file.
Some details in this code are deliberate:
- The
fingerprintis computed on the real arguments, but the log stores the redacted version. A later investigator can recompute the hash from the original source and confirm a match without the log holding the secret. - The
decidedevent carries bothoriginal_fingerprintandfingerprint. For approve and reject they are equal. For edit they differ, which makes edits easy to query. - Rejections still produce an
executedevent with outcomeskipped. Every approval ends with the same final event type, which makes "which approvals never finished" a simple query. - Errors record the exception class name, not the message, because messages can contain argument values.
Timeouts, expiry, and system decisions
Not every decision comes from a person. When a request expires or is auto-approved by a policy rule, write a decided event anyway. Use a reserved reviewer value such as system:timeout or system:policy, and record the rule or TTL that applied.
def record_expiry(log, run_id, approval_id, name, fp, ttl_seconds):
log.append({
"run_id": run_id,
"approval_id": approval_id,
"tool": name,
"event": "decided",
"reviewer": "system:timeout",
"action": "expire",
"reason": f"no decision within {ttl_seconds}s",
"fingerprint": fp,
})This keeps one rule true throughout the log: every requested event is followed by exactly one decided event. Auto-approvals need the same treatment, with the policy_version field naming the rule that allowed them. Without it, you cannot tell afterward whether a human saw a low-risk action or no one did.
Common errors
- Logging only approvals. Rejections and edits show where the agent is wrong or the policy is too strict. Log every outcome.
- Updating a single row. A row that moves from
pendingtoapprovedloses the history, and it hides a decision that was changed later. - Storing raw arguments. Email bodies, tokens, and personal data copied into the audit log create a second sensitive data store with different retention rules. Redact by key name, and consider storing only a hash for fields that are large or private.
- Trusting a client-supplied reviewer identity. Take the reviewer ID from the authenticated session on the server, never from the request body.
- Using display names. Names change and collide. Use a stable user ID.
- Relying on local clocks. Take timestamps on the server that writes the log, in UTC. Rely on
seqfor ordering, since timestamps can tie. - Logging the model's explanation as the reason. The
reasonfield is the reviewer's. If you also keep the agent's stated justification, store it under a separate key so no one mistakes it for human judgment.
Retention and access
Decide in advance how long entries live and who may read them. Audit logs often contain business-sensitive details even after redaction, so restrict read access to a small group and log those reads as well. Retention is a policy question that depends on your industry and local law. If you must delete personal data on request, store references such as user IDs in the log and keep the personal details in a separate table you can purge. The chain then stays intact.
Exercises
Exercise
A reviewer edits the to field of an email from [email protected] to [email protected]. Which two fingerprints should the decided event contain, and why is the original one needed?
Show answer
It should contain original_fingerprint, the hash of the agent's proposal, and fingerprint, the hash of the edited action that will run. The original is needed to show that the agent proposed something different from what executed. Without it, the log would show only the edited action, and an investigator could not see that the agent's proposal was wrong or reconstruct what the reviewer changed.
Exercise
An approval has a requested event and a decided event with action approve, but no executed event. Name two possible causes, and say which log fields help you tell them apart.
Show answer
One cause is a crash or restart between the decision and the tool call. Another is that the fingerprint check at execution time blocked the action because the arguments no longer matched. The fingerprint in the decided event, compared with the fingerprint of the call the resume step attempted to run, shows a mismatch. The ts and seq values and the application's error logs for that run_id show whether the process stopped before the check.