Course 3 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e3-m5-l3) and the earlier lessons.
You'll leave with an audit.events table that refuses edits from every role, a hash chain you can verify from outside the database, an actor chain on every event that says who acted on whose behalf, payload digests keyed with a secret the database never sees, and aip-audit verify | trail | prove.
In one screen
- Use it on Monday: Make the audit table append-only, chain each row to the one before it by hash, and copy the latest hash somewhere the database owner can't reach.
- The picture: One row per thing that happened, append-only by trigger for every role, each carrying the hash of the one before, content kept only as a digest keyed outside the database.
- The decision: Activity in clear, content never: the trail keeps who, what and which identifiers, so its reader can't confirm a guess about a ticket.
- You'll run:
uv run pytest -q tests/unit/test_audit_verify.py tests/unit/test_audit_digest.py:5 passed, no database needed, covering the anchor rules and an amount (152.40) nobody can confirm without the key.
Why this matters
When attackers took over the release pipeline of LiteLLM, the open-source gateway this platform uses, in October 2026, they deleted run logs along the way (E1 lesson 3.4).
A trail the attacker can edit tells you whatever the attacker wants. This lesson builds one that the application can't edit, that the database owner can't edit without detection once its latest hash is copied elsewhere, and that you can check from outside the database.
The idea
Sooner or later the CISO (chief information security officer) asks: what did every agent access last Tuesday, and on whose behalf? This lesson builds the record that answers it, and aip-audit trail, which filters it by person, agent or subject.
It doesn't filter by date yet, and it prints only the time of day: a date filter, and the date in the output, are what you'd add for your auditors.
The journal from lesson 5.2 holds the content of every turn. The audit trail holds something smaller and harder: one row per thing that happened, with three properties.
- Append-only, enforced by the database. The application role has
SELECTandINSERTon the table and nothing else. Triggers refuseUPDATE,DELETEandTRUNCATEfor every role, the owner included. - Hash-chained. Each row carries the hash of the row before it. The database computes the hash in a trigger, so the caller can't choose it. A verifier written in Python recomputes the chain independently.
- Activity without content. A row says who, what and which identifiers:
user:u-tom>agent:support>agent:ticket-reader,tickets_read ticket_id=T-1042. Arguments and results are kept only as a keyed digest: an HMAC-SHA256, a fingerprint that only someone holding the secret key can compute or check, with the key kept outside the database. The ticket text, with its hidden instructions and fake account number, never enters the trail, and a reader of the trail can't confirm a guess about it.
event n-1 ── hash(n-1) ──┐
v
event n: seq, at, type, actor, subject, payload_digest, prev_hash = hash(n-1)
hash(n) = sha256( length-prefixed fields of event n )
payload_digest = hmac-sha256( AIP_AUDIT_KEY, canonical payload )
Change one field of one event and its hash no longer matches. Delete one and the sequence has a hole. The chain alone catches both.
Two attacks it can't catch, and I want you to hear this before you build it. The table's owner (or any superuser) can disable the triggers and rewrite the chain consistently from the first edited row. Or cut the last ten events: what remains is a clean, shorter chain.
Both need an anchor, a (seq, hash) pair copied earlier to a place the database owner doesn't control. Seq 0 is the empty chain, whose hash is the genesis value of 64 zeros; seq n is the event numbered n. The verifier prints the head in that form and takes it back with --anchor.
The simplest version is a scheduled job that copies the head verify prints to storage the database owner can't write, for example an object-store bucket with a write-once retention lock. Running that for real comes back in E6 module 4: lessons 4.1 and 4.2 copy the head every hour to storage the server can't rewrite (an S3 bucket under Object Lock in 4.2), and the lab in 4.3 checks a restore against it. Here we make sure the check exists.
And every property above comes with a test that attacks it, because a chain nobody has tried to break proves nothing.
Build it
This part builds the trail itself: the table and the triggers that guard it, the keyed digest, the verifier, and the command an auditor runs. Part 2 makes the harness write to it. You need a new secret, the audit key, and the migration:
git checkout e3-m5-l3 && uv sync --all-extras
git diff --stat=72 e3-m5-l2..e3-m5-l3 -- src agents data
infra/compose/init/init-secrets.sh
(cd infra/compose && docker compose up -d --wait --force-recreate postgres)
uv run alembic upgrade heads
src/aip/approvals/store.py | 17 +++-
src/aip/audit/__init__.py | 4 +-
src/aip/audit/cli.py | 54 ++++++++++++
src/aip/audit/migrations/0001_audit.py | 60 ++++++++++++++
src/aip/audit/trail.py | 109 +++++++++++++++++++++++++
src/aip/harness/loop.py | 16 +++-
src/aip/rights/types.py | 7 +-
7 files changed, 262 insertions(+), 5 deletions(-)
kept existing .env; added: AIP_AUDIT_KEY
Pinned in docs/VERSIONS.md (12 November 2026): Postgres 17 (pgvector image 0.8.7-pg17), psycopg 3.3.8, alembic 1.20.1, Python 3.12.
On a stack you've used since lesson 4.3, init-secrets.sh keeps your .env, adds only the audit key and prints names, never values. If your aip database has seen a later tag, reset it first with the owner command from lesson 4.3.
Step 1: The table, and the database that guards it
What to notice. Two trigger functions do the work. chain, below, runs before every insert and fills in the sequence number, the time and both hashes itself. refuse raises on any edit. It's in Full code, with the triggers, the table, the canonical function that lays out each row for hashing, and the grants.
From src/aip/audit/migrations/0001_audit.py:
op.execute("""
CREATE FUNCTION audit.chain() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE last audit.events;
BEGIN
PERFORM pg_advisory_xact_lock(hashtext('audit.events')); -- one writer at a time
SELECT * INTO last FROM audit.events ORDER BY seq DESC LIMIT 1;
NEW.seq := coalesce(last.seq, 0) + 1; -- whatever the caller sent
NEW.at := clock_timestamp();
NEW.prev_hash := coalesce(last.hash, repeat('0', 64));
NEW.hash := encode(sha256(convert_to(audit.canonical(NEW), 'UTF8')), 'hex');
RETURN NEW;
END $$""")
Five decisions sit in this migration.
The trigger chain overwrites seq, at, prev_hash and hash whatever the caller sent. The application can't backdate an event, skip a number or pick a hash.
pg_advisory_xact_lock makes the writes take turns. Without it, two concurrent inserts would read the same last row, claim the same prev_hash, and fork the chain. The lock is released at commit.
canonical length-prefixes every field: 5:hello, not hello plus a separator. With a separator, someone could move characters from the actor into the subject and keep the same string.
refuse raises for UPDATE, DELETE and TRUNCATE. TRUNCATE needs its own statement-level trigger: a row-level DELETE trigger doesn't fire on it.
The migration's last line (in Full code) is the one people forget. aip_app, the role the application connects as (created by the init script you met in lesson 4.3), gets SELECT, INSERT and nothing else. So "the app cannot edit the audit trail" is a grant, checked by Postgres, and the triggers are a second wall for the owner.
Step 2: The key, the digest, and the proof
What to notice. Three small functions. audit_key (in Full code) refuses to start without a key of at least 32 bytes. digest_of turns any payload into the same canonical JSON, then an HMAC. proves is the only place the key is used to check something.
From src/aip/audit/trail.py:
def digest_of(payload: Any, key: bytes) -> str:
"""HMAC-SHA256: without the key, '152.40' cannot be confirmed by hashing guesses."""
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
return hmac.new(key, canonical.encode(), hashlib.sha256).hexdigest()
def proves(row: dict, payload: Any, key: bytes) -> bool:
"""Does this payload (kept elsewhere, under access control) match what the event recorded?"""
return hmac.compare_digest(row["payload_digest"], digest_of(payload, key))
Here's the problem the key solves. Many payloads hold very little: an invoice id, an amount, four_eyes. With a plain SHA-256, anyone who can read audit.events (a database administrator, a backup, an export to the BI team) could hash candidate payloads until one matched, and learn the amount. With HMAC, only the key holder can check a guess, and the key never enters Postgres.
audit_key fails closed: no key, or a short one, and the platform doesn't start, rather than run unaudited because someone forgot a variable. digest_of uses sorted keys and fixed separators, so any process gets the same digest. proves compares with compare_digest, which takes the same time wherever the first difference is.
What to notice. record hands the database four columns and placeholders for the other four; canonical writes each field as its length, a colon and the value, in the trigger's order.
From src/aip/audit/trail.py:
def record(self, event_type: str, actor: str, subject: str, payload_digest: str) -> None:
self.db.execute("INSERT INTO audit.events (event_type, actor, subject, payload_digest, "
"seq, at, prev_hash, hash) VALUES (%s, %s, %s, %s, 0, now(), '', '')",
(event_type, actor, subject, payload_digest)) # the trigger fills the rest
def canonical(row: dict) -> str:
at = row["at"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
fields = [str(row["seq"]), at, row["event_type"], row["actor"], row["subject"],
row["payload_digest"], row["prev_hash"]]
return "".join(f"{len(v)}:{v}" for v in fields)
Audit loads the key at construction, so a missing key stops the service at startup, not at the first refund. record sends placeholders for the four columns the trigger owns.
canonical is the Python twin of the SQL function: same fields, same order, same timestamp format. The verifier doesn't trust the trigger's arithmetic; it redoes it. The chain covers the digest as stored, so verify needs no key and anyone can run it. Proving content is a separate act, for the key holder only.
Step 3: The verifier
What to notice. The walk starts from the genesis value and stops at the first bad row, naming it. The anchor is checked only after the walk.
From src/aip/audit/trail.py:
def verify(rows: list[dict], anchor: tuple[int, str] | None = None) -> Verdict:
"""Recompute the chain in Python, independently of the trigger that wrote it.
anchor = (seq, hash) published elsewhere earlier: catches a tail cut off the end."""
prev = GENESIS
for n, row in enumerate(rows, start=1):
if row["seq"] != n:
return Verdict(False, n - 1, prev, f"seq {n} missing (found {row['seq']})")
if row["prev_hash"] != prev:
return Verdict(False, n - 1, prev, f"seq {n}: link to the previous event broken")
if hashlib.sha256(canonical(row).encode()).hexdigest() != row["hash"]:
return Verdict(False, n - 1, prev, f"seq {n}: content does not match its hash")
prev = row["hash"]
if anchor: # seq 0 is the empty chain; seq n is the row with seq n
seq, expected = anchor
at = GENESIS if seq == 0 else rows[seq - 1]["hash"] if 0 < seq <= len(rows) else None
if at != expected:
return Verdict(False, len(rows), prev, f"anchor at seq {seq} not found")
return Verdict(True, len(rows), prev)
Three checks per row: no hole in the sequence, a link to the previous hash, content that matches its own hash. The first failure stops the walk and names the event.
The anchor check comes after the walk, and compares the anchor's hash with the event at that number (or the genesis value for seq 0, so the head an empty trail prints verifies too). If you published 412:<hash> yesterday and today the chain is only 400 long, or event 412 has a different hash, the anchor isn't found. tests/unit/test_audit_verify.py holds both cases, with no database.
The content rule. audit_subject (in Full code) decides what a row may say: the tool name and the arguments named *_id or *_ids. A reply body, a refund reason, an email address never reach the trail.
Your turn (15 min)
Delete the body of verify in src/aip/audit/trail.py (keep the signature and the docstring) and write it again from what you just read, without scrolling back. Then run uv run pytest -q tests/unit/test_audit_verify.py: both pass. With the body deleted, both fail, so a pass means your version does the job. (Solution: Check yourself, Your turn.)
Step 4: The command line an auditor runs
What to notice. verify prints the head in the same SEQ:HASH form that --anchor reads back, and its exit code is 0 or 1, so a scheduled job can run it.
From src/aip/audit/cli.py:
with connect() as db:
if args.cmd == "verify":
anchor = None
if args.anchor:
seq, h = args.anchor.split(":")
anchor = (int(seq), h)
result = verify(load(db), anchor)
print(f"{'OK' if result.ok else 'BROKEN'}: {result.events} events verified, "
f"head {result.events}:{result.head}" +
(f"\n{result.problem}" if result.problem else ""))
return 0 if result.ok else 1
Three subcommands, three questions. verify: is the chain intact? It prints the head as SEQ:HASH with the full 64-character hash, the form --anchor takes back. A shortened head would never match, and every check against an intact chain would fail. trail: what did agents do, by actor or subject? prove: does this payload match that event? Only prove needs the key, and it exits with 1 on a mismatch, so a script can use it.
The CLI is registered in pyproject.toml as aip-audit = "aip.audit.cli:main", next to aip-rights from module 3.
Check yourself
- A colleague wants to drop the key:
digest_ofwould return a plainhashlib.sha256of the canonical JSON. Predict which of the five unit tests fail, and decide whether you'd accept the change. Two fail:test_a_low_entropy_payload_cannot_be_confirmed_without_the_key(the digest now equals the plain hash) andtest_whoever_holds_the_key_can_prove_what_an_event_recorded(a wrong key now "proves" too). Reject it: anyone who can readaudit.eventscould hash guesses like152.40until one matches, and learn the amount.
Your turn. The reference is the listing above, src/aip/audit/trail.py at e3-m5-l3; git diff e3-m5-l3 -- src/aip/audit/trail.py shows where yours differs. What people miss: three checks per row in this order (no hole in seq, the link to the previous hash, the row's own hash over canonical(row)), stop at the first failure and name it, and check the anchor only after the walk, with seq 0 meaning the genesis value.
Part 2: who acted, and the attack
Where we left off
The trail exists and can be verified from outside the database, but nothing writes to it yet. This part records who acted on whose behalf, as a chain like user:u-sarah>agent:support>agent:ticket-reader, makes the harness and the approvals write every call and decision, then attacks the trail the way someone with the owner's role would.
Step 5: Who acted, on whose behalf
What to notice. ResolvedAgent gets one new field, via, and a property, actor, that writes the person first and every agent after.
From src/aip/rights/types.py:
via: tuple[str, ...] = () # parent agents, for a sub-agent: the actor chain
@property
def actor(self) -> str:
"""Who acts, on whose behalf: user:u-tom>agent:support>agent:ticket-reader."""
return ">".join([f"user:{self.subject}", *(f"agent:{a}" for a in (*self.via, self.name))])
You met via in lesson 2.4: resolve_subagent appends the parent's name. Here it pays off: the child's actor reads user:u-tom>agent:support>agent:ticket-reader. The person is always first.
Step 6: Where the harness records a tool call
The harness records every tool call as it returns, and the end of every turn. Let's follow one call into the trail: the ticket-reader reading T-1042 for Tom, the turn you'll run in step 8.
1. The call returns, and run_call picks its event. One line picks the event, the next records it. The subject comes from audit_subject, which keeps the tool name and the arguments named *_id or *_ids, and nothing else:
From src/aip/harness/loop.py:
event = "tool.held" if held else "tool.unknown" if tool is None else "tool.call"
self.record(event, resolved, audit_subject(name, args), {"args": args, "result": out.content})
For Tom's read, the event is tool.call, the subject is tickets_read ticket_id=T-1042, and the payload is the arguments and the ticket's text.
2. record turns the payload into a digest. It adds who acted, from step 5, and hands the rest to the Audit of part 1:
From src/aip/harness/loop.py:
def record(self, event: str, resolved: ResolvedAgent, subject: str, payload) -> None:
if self.audit:
self.audit.record(event, resolved.actor, subject, self.audit.digest(payload))
So the ticket's text never reaches the trail: only its keyed digest does.
3. The row an auditor sees. Who, what, which ticket, and nothing of what it said (your time will differ):
3 10:26:52 tool.call user:u-tom>agent:support>agent:ticket-reader tickets_read ticket_id=T-1042
Every tool call ends in exactly one of three events:
tool.call: it ran, or was refused with an error the model can read.tool.held: it became a proposal.tool.unknown: not granted or not existing; both mean "did not run".
tool.held gets its own event because a held call hasn't happened yet: an auditor must not count it as done.
4. The end of the turn. run_turn opens with turn.run and closes with turn.end, recorded right after the journal's finish:
From src/aip/harness/loop.py:
self.record("turn.end", resolved, f"conversation:{conversation_id}",
{"turn": turn_id, "stop": result.stop_reason, "answer": result.answer,
"cost_usd": result.cost_usd})
Like every payload, this one reaches the trail only as a digest: the answer and the cost of each turn stay out of sight of anyone reading the trail, and prove can confirm them later for whoever holds the key. (What that cost covers after a crash is in What breaks.)
The approvals record in the same chain
The approvals store from lesson 4.3 records proposals and decisions through the same Audit, with the proposal's id in the subject:
From src/aip/approvals/store.py:
def record(self, event: str, actor: str, p: dict, payload) -> None:
if self.audit:
self.audit.record(event, actor, f"proposal:{p['id']} " +
audit_subject(p["tool"], p["args"]), self.audit.digest(payload))
So approval.proposed, approved, rejected and executed land in the same chain as the tool calls.
The executed event's actor reads user:u-sarah>agent:support>approved-by:user:u-dana>platform:approvals. Sarah asked, through the support agent, Dana approved, and the platform's approvals code ran it. The approvals store builds that string itself, from the proposal's requester and agent and the person who decided (in Full code). It's the same order as every other actor in the trail: the person first, whoever acts now last. E4 puts the same chain in the delegated token for that call.
Step 7: Prove it, with attacks
What to notice. Both tests attack as the table's owner, with the trigger switched off, inside a transaction that's rolled back afterward. The assertion is the verifier's exact message.
The first test's name says superuser, but it connects as the owner, aip. That's enough, because a table's owner can switch off its triggers.
From tests/integration/test_audit.py:
def test_a_superuser_edit_with_triggers_off_is_caught_by_the_verifier(audit):
with connect(admin=True) as owner:
with owner.transaction(force_rollback=True): # undo the attack after the test
owner.execute("ALTER TABLE audit.events DISABLE TRIGGER no_edit")
seq = owner.execute("SELECT max(seq) - 1 AS s FROM audit.events").fetchone()["s"]
owner.execute("UPDATE audit.events SET actor = 'user:someone-else' WHERE seq = %s",
(seq,))
verdict = verify(load(owner))
assert not verdict.ok and verdict.problem == f"seq {seq}: content does not match its hash"
def test_a_deleted_event_breaks_the_chain(audit):
with connect(admin=True) as owner:
with owner.transaction(force_rollback=True):
owner.execute("ALTER TABLE audit.events DISABLE TRIGGER no_edit")
seq = owner.execute("SELECT max(seq) - 1 AS s FROM audit.events").fetchone()["s"]
owner.execute("DELETE FROM audit.events WHERE seq = %s", (seq,))
verdict = verify(load(owner))
assert not verdict.ok and verdict.problem.startswith(f"seq {seq} missing")
Each test attacks the trail the way someone would. Two are above; the rest are in Full code:
- The app tries to edit and gets
InsufficientPrivilege; the owner hits the trigger. - The app inserts a row with a sequence number and hash of its own choosing. The row is stored, but the trigger overwrites both, so the chain stays valid.
- The owner disables the trigger and edits an actor: the verifier names the event.
- A deleted event shows as a missing number.
- The last one cuts the tail. Hold that thought for the Try it below.
The attacks run inside transaction(force_rollback=True), in the test's own database (aip_test_<hash>), never the shared aip one.
The key, tested on its own
The chain proves nothing was edited. The key protects what the payloads say. It gets its own unit tests, with no database at all.
What to notice. No database here: just the digest, with and without the key.
From tests/unit/test_audit_digest.py:
def test_a_low_entropy_payload_cannot_be_confirmed_without_the_key():
payload = {"args": {"invoice_id": "INV-2240", "amount_eur": 152.40}, "level": "four_eyes"}
plain = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"))
.encode()).hexdigest()
keyed = digest_of(payload, KEY)
assert keyed != plain # guessing amounts no longer works
assert keyed != digest_of(payload, bytes.fromhex("22" * 32))
assert len(keyed) == 64 and keyed == digest_of(payload, KEY)
def test_whoever_holds_the_key_can_prove_what_an_event_recorded():
row = {"payload_digest": digest_of({"turn": "t1", "message": "Refund T-1038"}, KEY)}
assert proves(row, {"turn": "t1", "message": "Refund T-1038"}, KEY)
assert not proves(row, {"turn": "t1", "message": "Refund T-1039"}, KEY)
assert not proves(row, {"turn": "t1", "message": "Refund T-1038"}, bytes(32))
The first test is the guessing attack, written down: the plain SHA-256 of the refund payload is not what the trail stores. The second is the investigator's side: with the key, the right payload matches and a one-character change doesn't. A third test, in Full code, makes sure a missing or short key stops everything.
$ uv run pytest -q tests/integration/test_audit.py tests/unit/test_audit_digest.py tests/unit/test_audit_verify.py
.............. [100%]
14 passed in 3.15s
Try it (5 min). Predict first. The owner switches the trigger off and deletes the last event, not one in the middle. What does
verifysay with no anchor, and with the head you saved before the cut? Then runuv run pytest -q tests/integration/test_audit.py -k cut_tail -vand readtest_a_cut_tail_needs_an_anchor_published_elsewherein Full code. (Answer: Check yourself, Try it 1.)
Step 8: Ask the auditor's questions
Now the shared aip database, on purpose. The tests above used databases of their own. aip-audit reads the shared one, so that's where the events must land for you to see them.
To make one turn of Tom's, we call one of the tests as a plain function: test_a_turn_leaves_who_what_and_on_whose_behalf_but_no_content, which plays exactly that turn (E3 has no chat interface to type into). connect() uses a test database only when pytest's fixture sets one up; called outside pytest, the function gets no fixture, so the events land in the shared aip database.
Try it (2 min). Tom's turn delegates to the ticket-reader, which reads T-1042. Before you look at the trail below, predict the order of its six events: where does the support agent's
delegate_ticket_readercall land, before or after the ticket-reader's own events? (Answer: right under the output.)
Here is the trail freshly migrated, then after that turn:
$ uv run aip-audit verify
OK: 0 events verified, head 0:0000000000000000000000000000000000000000000000000000000000000000
$ uv run python -c "import tests.integration.test_audit as t; t.test_a_turn_leaves_who_what_and_on_whose_behalf_but_no_content()"
$ uv run aip-audit verify
OK: 6 events verified, head 6:31c348f3406693d5617a786a5146221f58cf1b5f3ac2c34bde897856146a92ef
$ uv run aip-audit trail --actor u-tom --last 6
1 10:26:52 turn.run user:u-tom>agent:support conversation:c-3abf18e0
2 10:26:52 turn.run user:u-tom>agent:support>agent:ticket-reader conversation:72ec3a0b-b02e-46c0-ac0f-7e0756e01252:1:ticket-reader
3 10:26:52 tool.call user:u-tom>agent:support>agent:ticket-reader tickets_read ticket_id=T-1042
4 10:26:52 turn.end user:u-tom>agent:support>agent:ticket-reader conversation:72ec3a0b-b02e-46c0-ac0f-7e0756e01252:1:ticket-reader
5 10:26:52 tool.call user:u-tom>agent:support delegate_ticket_reader ticket_ids=['T-1042']
6 10:26:52 turn.end user:u-tom>agent:support conversation:c-3abf18e0
Times (UTC), conversation ids and the head hash change from run to run; the shape doesn't. Tom asked, the support agent delegated, the ticket-reader read T-1042 for Tom, and nothing of T-1042's content is in those six lines. The delegation (5) comes after the work it caused (2 to 4) because a tool call is recorded when it returns.
Now keep the head as an anchor and check against it, and against an event that doesn't exist yet:
$ HEAD=$(uv run aip-audit verify | sed -n 's/.*head //p'); echo "$HEAD"
6:31c348f3406693d5617a786a5146221f58cf1b5f3ac2c34bde897856146a92ef
$ uv run aip-audit verify --anchor "$HEAD"
OK: 6 events verified, head 6:31c348f3406693d5617a786a5146221f58cf1b5f3ac2c34bde897856146a92ef
$ uv run aip-audit verify --anchor 7:0000000000000000000000000000000000000000000000000000000000000000; echo "exit $?"
BROKEN: 6 events verified, head 6:31c348f3406693d5617a786a5146221f58cf1b5f3ac2c34bde897856146a92ef
anchor at seq 7 not found
exit 1
Copied somewhere the database owner can't write, that 6: line is your anchor. The same test file also checks that a head verify prints is accepted by verify --anchor.
What breaks
A digest anyone can reverse by guessing. Control: HMAC with a key outside the database (step 2). What's left is the key itself: treat it like any production secret, and plan rotation. A new key applies to new events, so keep the old key, with the sequence number where you switched, to prove old events.
An audit that runs without its key. Control: Audit() fails closed at startup.
An anchor the verifier can't read back. Control: the full SEQ:HASH printed, and seq 0 accepted for an empty trail (step 3).
The trail can over-report after a crash. Picture the order inside one tool step from lesson 5.2:
- The tool runs, under the step's idempotency key (
<turn id>:<step>). run_callrecords itstool.callevent.- The process dies before the journal writes the step's row.
- On resume the step has no row, so it runs again with the same key. A system that honors the key does the effect once; the trail gets a second
tool.callrow.
One effect, two rows. That's the safe direction for an audit, but say it in your runbook so nobody reads it as a double refund.
Cost goes the other way. The turn.end payload carries cost_usd, the number lesson 1.2 started counting: what this run of the turn spent, sub-agents included, each call counted once by the run that made it. Say the first run spends USD 0.03 and dies; the resumed run spends USD 0.01. The resumed run's turn.end carries 0.01, and the crashed run never reached its own turn.end. So the turn's whole cost, 0.04, is only in the gateway's spend log (the gateway records the cost of every model call it serves), not in the trail.
One writer at a time. The advisory lock serializes every audit insert on the platform. Here it costs nothing measurable; at thousands of events per second it's your ceiling. Measure before you shard the chain (one per tenant or per day, each anchored).
Triggers off. A consistent rewrite by the owner (or a superuser) verifies clean; only an anchor from before it catches it. That's why the head must leave the database (E6 lesson 4.3), and why the run logs the LiteLLM attackers deleted along the way are the detail to remember (part 1).
Decide
Default: an append-only table in the platform's own Postgres, written only by a trigger that chains the hashes, SELECT, INSERT for the app role, refusal triggers for everyone, actor chains and identifiers in clear, the payload as an HMAC keyed outside the database, a verifier outside the database, and the head published daily to storage the database owner can't modify.
Pick the alternative (a managed append-only store, or object storage with a write-once retention lock) when your auditors require it, or when nobody should hold Postgres superuser alone. Keep the actor chain, the keyed digest and the content rule either way.
Check yourself
- The app role holds only
SELECT, INSERT. Why keep theno_edittrigger too? The owner runs migrations and holds every grant. The trigger makes an owner edit fail loudly unless it's disabled first, and disabling it is an act a stricter setup can log. - You publish the head once a day, at 00:00 UTC. At 15:00 someone with the owner's role disables the trigger and deletes the 40 events written since midnight. The next morning you run
verify --anchorwith last midnight's head. What does it say, and what would you change? OK. The anchor names an event from before the cut, and it's still there with the same hash, so the shorter chain verifies. Events written after the last published head can vanish without a trace: the time between two publications is your exposure. Publish more often, or after every batch of events that matters, such as approvals. - Why does
verifyneed no key, whileprovedoes? The chain covers the digest as stored, so anyone can recompute it. Confirming what a digest contains is the part that must stay with the key holder. - Why record
user:u-tom>agent:support>agent:ticket-readerand not justagent:ticket-reader? The person is the accountable party. Without the chain, "on whose behalf?" has no answer.
Try it 1. Without the anchor: OK. A shorter chain with no hole and no broken link is a valid chain. With the anchor: BROKEN, because the event the anchor names is gone. That's the whole case for copying the head somewhere the owner can't write.
Transcript
Audit trail day. We build a record the application can't change, keep its content unguessable, and check it from outside. All right, back in lesson three point one, I promised you an answer to one question from the chief information security officer. What did every agent access today, and on whose behalf? The journal from lesson five point two has the content.
So now we build the record that answers the question: one the application can't change, and that the owner can't change without it showing, once the head is published. Everything important happens in the database, so let's start there. The application sends four fields. The trigger fills in the sequence number, the time, the previous hash and the hash, whatever the caller sent.
And an advisory lock makes inserts take turns, so the chain can't fork. Then two refusal triggers: one for update and delete, and a separate one for truncate. Why separate? Because a row trigger doesn't fire on truncate. And the last line is the one people skip: the app role gets select and insert, and nothing else. So "the app can't edit the trail" is a grant Postgres checks, and the triggers are a second wall, for the owner.
Now, the trail keeps no content, only a digest of it. But a plain hash of "refund a hundred fifty-two forty" hides nothing, right? Anyone who can read the table tries amounts until one matches. So the digest is keyed: an HMAC, a hash only someone holding the key can compute, with a key that lives outside the database, in the environment or a secret manager.
On a laptop, that's the compose secrets file. If there's no key, the audit refuses to start, so it fails closed. And whoever does hold the key can prove what an event recorded. The audit loads its key once, at startup. And record sends placeholders for the four columns the trigger owns. Then here's the canonical form in Python: same fields, same order, same timestamp format as the SQL function.
Now, why lengths? With a separator, someone could move characters from one field into the next and keep the same string. With lengths, they can't. And the twin is on purpose, by the way. The verifier doesn't trust the trigger's arithmetic, so it redoes it, outside the database, and it needs no key, because the chain covers the digest as stored.
So the verifier does three checks per event. There's no hole in the sequence, the link points at the previous hash, and the content matches its own hash. The first failure stops it, and it tells you which event. Then the anchor check, which we'll need in a minute. And down here, the content rule. The tool name goes in, and anything ending in underscore id.
A reply body, a refund reason, an email address, none of that reaches the trail. Now the command line, and it has three questions. Verify: is the chain intact? Trail: what did agents do, by person or by subject? And prove: does this payload match that event? Only prove needs the key. Okay, now the part I want you to hear clearly.
Someone with superuser rights can turn the triggers off and rewrite the chain from one point onwards, consistently. Or cut the last events off the end. Both verify as OK. So the only thing that catches them is an anchor: a sequence number and its hash, copied earlier to somewhere the database owner can't write. Verify prints the head in exactly that form, with the full hash, so publishing it is one line, and tomorrow you check against it.
Sequence zero is the empty chain, all zeros, so even an empty trail has a head you can publish. And in E6, you keep the head off the server and check a restore against it. Now, who acted, and on whose behalf? You met "via" in lesson two point four: a sub-agent's rights remember the agents above it. So the ticket-reader working for Tom signs as user Tom, then support, then ticket-reader.
The person always comes first. And in the loop, every tool call ends in exactly one event: it ran, it was held, or it was unknown. The turn's last event carries what this run of the turn cost, sub-agents included. Each call is counted once, by the run that made it, and it sits inside a digest, like everything else. All right, the tests, and each one is an attack.
The app tries to edit and gets refused by the grants. The owner tries and hits the trigger. A forged insert loses its chosen number and hash. And a superuser turns the trigger off and edits an actor, and the verifier names the event. Then the ones without a database. The plain hash of the refund isn't what we store. The key proves the right payload and rejects a wrong one, no key means no audit, and an anchor is compared with the event at its own number.
Fourteen pass. Now, the tests used their own database. Ours is empty: zero events, and the head is all zeros. So let's give it one turn of Tom's, the same turn the test runs, and then ask the two questions. Is the chain intact? Yes, six events. What did Tom's agents do? Tom asked, the support agent delegated, and the ticket-reader read T-1042 for Tom.
And notice, nothing about what T-1042 says is in those lines. The hidden note, the fake account, you won't find them here. So let's keep the head, the way you'd publish it. We check against it, and it's found. Now an anchor for an event that doesn't exist yet. Not found, and the exit code says so, so a scheduled job can alert on it.
So that's the trail. The app can't edit it, and the owner can't edit it quietly. A reader can't guess what's inside it, and you can check it from outside. Next up, lesson five point four: we take the same agent and port it to two frameworks, to see which of these rules they can hold for you. See you there.
Going deeper
Part 1
Decision records in docs/decisions/: 0306 (the audit trail and its anchor), 0307 (migrations and roles: the app gets SELECT, INSERT only), 0310 (keyed digests).
Free, and worth your time
- Russ Cox, "Transparent Logs for Skeptical Clients" (long essay, 2019): from a hash chain to proofs that a log is complete and only ever appended to. https://research.swtch.com/tlog
Part 2
The same shape in tokens. Uber's agent identity post (May 2026) describes the actor chain for tokens: every hop exchanges its token (OAuth 2.0 Token Exchange, RFC 8693) and carries the human initiator plus every intermediate agent. Here the chain is a string in the audit row. E4 lesson 4.2 puts it in a signed token.
The test that holds the order of an executed approval's actor: test_an_executed_approval_is_audited_with_the_whole_chain_executor_last in tests/integration/test_approvals.py.
Decision records in docs/decisions/: 0305 (each call counted once, by the run that made it; the cost after a crash), 0310 (keyed digests and key rotation).
Full code
Part 1
The complete listings this part shortened above, byte for byte from the tag.
src/aip/audit/trail.py, lines 20-70:
def audit_key() -> bytes:
"""The digest key lives outside the database: whoever reads the trail cannot guess payloads.
AIP_AUDIT_KEY (hex, at least 32 bytes) from the environment or a secret manager;
on a laptop, from infra/compose/.env (never committed). No key, no audit: fail closed."""
value = os.environ.get("AIP_AUDIT_KEY")
if value is None and COMPOSE_ENV.is_file():
env = dict(line.split("=", 1) for line in COMPOSE_ENV.read_text().splitlines()
if "=" in line and not line.startswith("#"))
value = env.get("AIP_AUDIT_KEY")
if not value:
raise RuntimeError("no audit key: set AIP_AUDIT_KEY (openssl rand -hex 32)")
try:
key = bytes.fromhex(value)
except ValueError:
key = b""
if len(key) < 32:
raise RuntimeError("AIP_AUDIT_KEY must be at least 32 bytes, hex-encoded")
return key
def digest_of(payload: Any, key: bytes) -> str:
"""HMAC-SHA256: without the key, '152.40' cannot be confirmed by hashing guesses."""
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
return hmac.new(key, canonical.encode(), hashlib.sha256).hexdigest()
def proves(row: dict, payload: Any, key: bytes) -> bool:
"""Does this payload (kept elsewhere, under access control) match what the event recorded?"""
return hmac.compare_digest(row["payload_digest"], digest_of(payload, key))
class Audit:
def __init__(self, connect: Callable[[], psycopg.Connection], key: bytes | None = None) -> None:
self.key = key or audit_key()
self.db = connect()
def digest(self, payload: Any) -> str:
return digest_of(payload, self.key)
def record(self, event_type: str, actor: str, subject: str, payload_digest: str) -> None:
self.db.execute("INSERT INTO audit.events (event_type, actor, subject, payload_digest, "
"seq, at, prev_hash, hash) VALUES (%s, %s, %s, %s, 0, now(), '', '')",
(event_type, actor, subject, payload_digest)) # the trigger fills the rest
def canonical(row: dict) -> str:
at = row["at"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
fields = [str(row["seq"]), at, row["event_type"], row["actor"], row["subject"],
row["payload_digest"], row["prev_hash"]]
return "".join(f"{len(v)}:{v}" for v in fields)
src/aip/audit/migrations/0001_audit.py, lines 10-56:
def upgrade() -> None:
op.execute("CREATE SCHEMA audit")
op.execute("""
CREATE TABLE audit.events (
seq bigint PRIMARY KEY,
at timestamptz NOT NULL,
event_type text NOT NULL,
actor text NOT NULL,
subject text NOT NULL,
payload_digest text NOT NULL CHECK (payload_digest ~ '^[0-9a-f]{64}$'),
prev_hash text NOT NULL,
hash text NOT NULL
)""")
# Length-prefixed fields: no separator can be smuggled inside a value.
op.execute("""
CREATE FUNCTION audit.canonical(e audit.events) RETURNS text LANGUAGE sql IMMUTABLE AS $$
SELECT string_agg(length(v)::text || ':' || v, '' ORDER BY n)
FROM unnest(ARRAY[e.seq::text,
to_char(e.at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'),
e.event_type, e.actor, e.subject, e.payload_digest, e.prev_hash])
WITH ORDINALITY AS f(v, n)
$$""")
op.execute("""
CREATE FUNCTION audit.chain() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE last audit.events;
BEGIN
PERFORM pg_advisory_xact_lock(hashtext('audit.events')); -- one writer at a time
SELECT * INTO last FROM audit.events ORDER BY seq DESC LIMIT 1;
NEW.seq := coalesce(last.seq, 0) + 1; -- whatever the caller sent
NEW.at := clock_timestamp();
NEW.prev_hash := coalesce(last.hash, repeat('0', 64));
NEW.hash := encode(sha256(convert_to(audit.canonical(NEW), 'UTF8')), 'hex');
RETURN NEW;
END $$""")
op.execute("""
CREATE FUNCTION audit.refuse() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'audit.events is append-only (% refused)', TG_OP;
END $$""")
op.execute("CREATE TRIGGER chain BEFORE INSERT ON audit.events "
"FOR EACH ROW EXECUTE FUNCTION audit.chain()")
op.execute("CREATE TRIGGER no_edit BEFORE UPDATE OR DELETE ON audit.events "
"FOR EACH ROW EXECUTE FUNCTION audit.refuse()")
op.execute("CREATE TRIGGER no_truncate BEFORE TRUNCATE ON audit.events "
"FOR EACH STATEMENT EXECUTE FUNCTION audit.refuse()")
op.execute("GRANT USAGE ON SCHEMA audit TO aip_app")
op.execute("GRANT SELECT, INSERT ON audit.events TO aip_app") # no UPDATE, no DELETE
src/aip/audit/trail.py, lines 73-109:
@dataclass
class Verdict:
ok: bool
events: int
head: str
problem: str = ""
def verify(rows: list[dict], anchor: tuple[int, str] | None = None) -> Verdict:
"""Recompute the chain in Python, independently of the trigger that wrote it.
anchor = (seq, hash) published elsewhere earlier: catches a tail cut off the end."""
prev = GENESIS
for n, row in enumerate(rows, start=1):
if row["seq"] != n:
return Verdict(False, n - 1, prev, f"seq {n} missing (found {row['seq']})")
if row["prev_hash"] != prev:
return Verdict(False, n - 1, prev, f"seq {n}: link to the previous event broken")
if hashlib.sha256(canonical(row).encode()).hexdigest() != row["hash"]:
return Verdict(False, n - 1, prev, f"seq {n}: content does not match its hash")
prev = row["hash"]
if anchor: # seq 0 is the empty chain; seq n is the row with seq n
seq, expected = anchor
at = GENESIS if seq == 0 else rows[seq - 1]["hash"] if 0 < seq <= len(rows) else None
if at != expected:
return Verdict(False, len(rows), prev, f"anchor at seq {seq} not found")
return Verdict(True, len(rows), prev)
def load(db: psycopg.Connection) -> list[dict]:
return db.execute("SELECT * FROM audit.events ORDER BY seq").fetchall()
def audit_subject(tool: str, args: dict) -> str:
"""The tool and the identifiers it touched (arguments named *_id or *_ids), nothing else."""
ids = [f"{k}={v}" for k, v in sorted(args.items()) if k.endswith(("_id", "_ids"))]
return " ".join([tool, *ids])
src/aip/audit/cli.py, lines 13-50:
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="aip-audit")
sub = ap.add_subparsers(dest="cmd", required=True)
v = sub.add_parser("verify", help="recompute the hash chain")
v.add_argument("--anchor", help="SEQ:HASH published elsewhere earlier")
t = sub.add_parser("trail", help="what agents did, on whose behalf")
t.add_argument("--actor", default="", help="e.g. u-sarah or agent:support")
t.add_argument("--subject", default="", help="e.g. T-1042 or refunds_issue")
t.add_argument("--last", type=int, default=30)
p = sub.add_parser("prove", help="does a payload kept elsewhere match an event? needs the key")
p.add_argument("--seq", type=int, required=True)
p.add_argument("--payload", required=True, help="the JSON payload, exactly as recorded")
args = ap.parse_args(argv)
with connect() as db:
if args.cmd == "verify":
anchor = None
if args.anchor:
seq, h = args.anchor.split(":")
anchor = (int(seq), h)
result = verify(load(db), anchor)
print(f"{'OK' if result.ok else 'BROKEN'}: {result.events} events verified, "
f"head {result.events}:{result.head}" +
(f"\n{result.problem}" if result.problem else ""))
return 0 if result.ok else 1
if args.cmd == "prove":
row = db.execute("SELECT * FROM audit.events WHERE seq = %s", (args.seq,)).fetchone()
ok = bool(row) and proves(row, json.loads(args.payload), audit_key())
print(f"{'MATCHES' if ok else 'DOES NOT MATCH'}: event {args.seq}")
return 0 if ok else 1
rows = db.execute(
"SELECT * FROM (SELECT * FROM audit.events WHERE actor LIKE %s AND subject LIKE %s "
"ORDER BY seq DESC LIMIT %s) r ORDER BY seq",
(f"%{args.actor}%", f"%{args.subject}%", args.last)).fetchall()
for r in rows:
print(f"{r['seq']:>5} {r['at']:%H:%M:%S} {r['event_type']:18} {r['actor']:48} "
f"{r['subject']}")
return 0
Part 2
The complete listings this part shortened above, byte for byte from the tag.
tests/integration/test_audit.py, lines 29-78:
@pytest.mark.parametrize("sql", ["UPDATE audit.events SET actor = 'user:nobody'",
"DELETE FROM audit.events", "TRUNCATE audit.events"])
def test_nobody_edits_the_trail_not_the_app_and_not_the_owner(audit, sql):
with connect() as app, pytest.raises(psycopg.errors.InsufficientPrivilege):
app.execute(sql)
with connect(admin=True) as owner, pytest.raises(psycopg.errors.RaiseException,
match="append-only"):
owner.execute(sql)
def test_the_caller_cannot_choose_the_sequence_or_the_hash(audit):
with connect() as app:
app.execute("INSERT INTO audit.events VALUES (999999, '2001-01-01', 't', 'user:x', 's', "
"%s, 'forged', 'forged')", ("0" * 64,))
last = app.execute("SELECT * FROM audit.events ORDER BY seq DESC LIMIT 1").fetchone()
assert last["seq"] != 999999 and last["hash"] != "forged"
with connect() as db:
assert verify(load(db)).ok
def test_a_superuser_edit_with_triggers_off_is_caught_by_the_verifier(audit):
with connect(admin=True) as owner:
with owner.transaction(force_rollback=True): # undo the attack after the test
owner.execute("ALTER TABLE audit.events DISABLE TRIGGER no_edit")
seq = owner.execute("SELECT max(seq) - 1 AS s FROM audit.events").fetchone()["s"]
owner.execute("UPDATE audit.events SET actor = 'user:someone-else' WHERE seq = %s",
(seq,))
verdict = verify(load(owner))
assert not verdict.ok and verdict.problem == f"seq {seq}: content does not match its hash"
def test_a_deleted_event_breaks_the_chain(audit):
with connect(admin=True) as owner:
with owner.transaction(force_rollback=True):
owner.execute("ALTER TABLE audit.events DISABLE TRIGGER no_edit")
seq = owner.execute("SELECT max(seq) - 1 AS s FROM audit.events").fetchone()["s"]
owner.execute("DELETE FROM audit.events WHERE seq = %s", (seq,))
verdict = verify(load(owner))
assert not verdict.ok and verdict.problem.startswith(f"seq {seq} missing")
def test_a_cut_tail_needs_an_anchor_published_elsewhere(audit):
with connect(admin=True) as owner:
head = verify(load(owner))
anchor = (head.events, head.head) # e.g. posted to another system daily
with owner.transaction(force_rollback=True):
owner.execute("ALTER TABLE audit.events DISABLE TRIGGER no_edit")
owner.execute("DELETE FROM audit.events WHERE seq = %s", (head.events,))
assert verify(load(owner)).ok # a clean shorter chain: invisible
assert not verify(load(owner), anchor=anchor).ok
tests/unit/test_audit_digest.py, lines 1-35:
import hashlib
import json
import pytest
from aip.audit.trail import audit_key, digest_of, proves
KEY = bytes.fromhex("11" * 32)
def test_a_low_entropy_payload_cannot_be_confirmed_without_the_key():
payload = {"args": {"invoice_id": "INV-2240", "amount_eur": 152.40}, "level": "four_eyes"}
plain = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"))
.encode()).hexdigest()
keyed = digest_of(payload, KEY)
assert keyed != plain # guessing amounts no longer works
assert keyed != digest_of(payload, bytes.fromhex("22" * 32))
assert len(keyed) == 64 and keyed == digest_of(payload, KEY)
def test_whoever_holds_the_key_can_prove_what_an_event_recorded():
row = {"payload_digest": digest_of({"turn": "t1", "message": "Refund T-1038"}, KEY)}
assert proves(row, {"turn": "t1", "message": "Refund T-1038"}, KEY)
assert not proves(row, {"turn": "t1", "message": "Refund T-1039"}, KEY)
assert not proves(row, {"turn": "t1", "message": "Refund T-1038"}, bytes(32))
def test_no_key_no_audit(monkeypatch, tmp_path):
monkeypatch.delenv("AIP_AUDIT_KEY", raising=False)
monkeypatch.setattr("aip.audit.trail.COMPOSE_ENV", tmp_path / "missing.env")
with pytest.raises(RuntimeError, match="AIP_AUDIT_KEY"):
audit_key()
monkeypatch.setenv("AIP_AUDIT_KEY", "too-short")
with pytest.raises(RuntimeError, match="32 bytes"):
audit_key()
src/aip/rights/types.py, lines 46-63:
@dataclass(frozen=True)
class ResolvedAgent:
name: str
principal: Principal
instructions: str
model: str = "smart"
tools: frozenset[str] = frozenset()
sources: frozenset[str] = frozenset()
skills: frozenset[str] = frozenset()
subagents: frozenset[str] = frozenset()
approvals: Mapping[str, str] = field(default_factory=FrozenMap) # tool -> none|self|four_eyes
limits: Limits = field(default_factory=Limits)
via: tuple[str, ...] = () # parent agents, for a sub-agent: the actor chain
@property
def actor(self) -> str:
"""Who acts, on whose behalf: user:u-tom>agent:support>agent:ticket-reader."""
return ">".join([f"user:{self.subject}", *(f"agent:{a}" for a in (*self.via, self.name))])
src/aip/harness/loop.py, lines 179-192:
def run_call(self, resolved, conversation_id, tools, call_id, name, args, history, key,
stopped=lambda: False) -> dict:
tool, held = tools.get(name), None
level = tool and required_approval(tool, resolved, tainted(history))
if tool and level != "none":
out = self.hold(resolved, conversation_id, tool, args, level, key)
held = None if out.error else level
else:
out = self.call_tool(resolved, tool, name, args, key=key, stopped=stopped)
event = "tool.held" if held else "tool.unknown" if tool is None else "tool.call"
self.record(event, resolved, audit_subject(name, args), {"args": args, "result": out.content})
return {"message": {"role": "tool", "tool_call_id": call_id, "content": out.content},
"tainted": out.tainted, "held": held, "cost_usd": out.cost_usd,
"unpriced_calls": out.unpriced_calls}
src/aip/harness/loop.py, lines 171-177:
result.tainted = tainted(history)
self.journal.finish(turn_id, result.stop_reason, history)
self.record("turn.end", resolved, f"conversation:{conversation_id}",
{"turn": turn_id, "stop": result.stop_reason, "answer": result.answer,
"cost_usd": result.cost_usd})
emit("end", reason=result.stop_reason)
return result
src/aip/approvals/store.py, lines 145-146 (the executed event's actor):
self.record(f"approval.{status}", f"user:{p['requester']}>agent:{p['agent']}" # who asked, through
f">approved-by:user:{p['decided_by']}>platform:approvals", p, result) # what; code runs it
Sources
The sources for both parts are at the end of part 2.
- LiteLLM, security incident of 21 October 2026 and the attack-chain write-up, https://docs.litellm.ai/blog/security-incident-oct-21-2026 and https://docs.litellm.ai/blog/security-incident-oct-21-2026-attack-chain (checked 12 Nov 2026)
- Uber engineering, "Solving the agent identity crisis", 21 May 2026, https://www.uber.com/blog/solving-the-agent-identity-crisis/ (checked 12 Nov 2026)
- RFC 8693, OAuth 2.0 Token Exchange, https://www.rfc-editor.org/rfc/rfc8693 (checked 15 Nov 2026)
- RFC 2104, HMAC: Keyed-Hashing for Message Authentication, https://www.rfc-editor.org/rfc/rfc2104 (checked 15 Nov 2026)
- PostgreSQL 17 documentation, CREATE TRIGGER (row and statement triggers, TRUNCATE) and advisory locks, https://www.postgresql.org/docs/17/sql-createtrigger.html, https://www.postgresql.org/docs/17/explicit-locking.html#ADVISORY-LOCKS, and TRUNCATE ("will not fire any ON DELETE triggers"), https://www.postgresql.org/docs/17/sql-truncate.html (checked 15 Nov 2026)
- Reference repository ai-platform, branch series, tag e3-m5-l3: src/aip/audit/, src/aip/harness/loop.py, src/aip/rights/types.py, src/aip/approvals/store.py, tests/integration/test_audit.py, tests/unit/test_audit_digest.py, tests/unit/test_audit_verify.py; decision records 0305 (cost on resume), 0306 (audit trail), 0307 (migrations and roles) and 0310 (keyed digests) in docs/decisions/; docs/VERSIONS.md