Technical

AI Agent Audit Trail: What to Log and How Long to Keep It

A practical design for audit trails of AI agents in ERP and commerce systems: which events to record, how to store them so they can't be quietly changed, how long to keep them, and how to use them to investigate an incident.

Kalvyai Engineering · · 8 min read

AI Agent Audit Trail: What to Log and How Long to Keep It (cover)
On this page

An AI agent that only reads data is low risk. Once it can create a purchase order, update a price, or send a customer email, you need to answer one question quickly and with evidence: what happened, and why?

This post covers how we design audit trails for agents that work inside Odoo, ERPNext and Shopify. It covers what to log, how to store it, how long to keep it, and how to use it when something goes wrong.

Why the ERP's own change log is not enough

Odoo's chatter tracking and ERPNext's document version history already record field changes on many documents. That is useful, but it answers only what changed and which user account changed it. For an agent, that user account is usually a service user, so every change looks the same.

The ERP log cannot tell you:

  • What the agent was asked to do, and by whom.
  • What data it read before deciding.
  • Which model and prompt version produced the decision.
  • Whether a human approved the action, and what that human was shown.
  • What the agent tried and failed to do.

Keep the ERP's tracking switched on. Treat the agent audit trail as a separate layer that links to ERP records by ID.

The unit of logging: the run

Group everything under a run: one task from trigger to finish. For example, "process the vendor bill that arrived by email at 09:14" is one run. A run contains ordered steps: model calls, tool calls, approval requests and outcomes.

Every event carries:

  • run_id: the same for all events in the task.
  • step: a sequence number within the run.
  • parent_step: when one step caused another, such as a tool call made because of a model response.
  • ts: a UTC timestamp.

With these four fields you can rebuild a timeline. Without them you are reading interleaved log lines and guessing.

What to log

Inputs

  • Trigger: what started the run (scheduled job, webhook, user request, incoming email) and its source ID.
  • Requesting principal: the human or system on whose behalf the agent acts. This differs from the service account the agent uses to call the ERP.
  • Task instruction: the actual text or structured request.
  • Context references: IDs of the records and documents the agent was given, such as purchase.order 4812 or the hash of an attached PDF. Store references and hashes, not full copies, unless you need the copy as evidence.

Model calls

  • Provider, model name and model version string.
  • Prompt template ID and version. Put templates under version control so invoice_matcher@v14 means one exact text.
  • Tool definitions offered to the model, also versioned.
  • The model's response, including any tool calls it requested.
  • Token counts and cost.

When behaviour changes, the cause is usually one of three things: a new model version, an edited prompt, or different input data. If you log all three, you can tell which one it was.

Tool calls

This is the most important part. For each tool call, record:

  • Tool name and version.
  • Arguments exactly as sent.
  • Whether the call was read-only or a write.
  • The target system and record IDs.
  • The result or error, and the latency.
  • Whether the call was blocked by a policy check (permission, budget, value limit) before it ran.

Blocked and failed calls matter as much as successful ones. An agent that tries to refund the wrong order ten times and is stopped each time is a problem you want to know about.

Approvals

An approval record is only useful if it shows what the approver actually saw. Log:

  • The proposed action as a structured diff (record, field, old value, new value).
  • The agent's stated reason, as presented to the approver.
  • Who was asked, who decided, when, and through which channel.
  • The decision (approved, rejected, edited) and any comment.
  • If the approver edited the proposal, both the original and the final version.
  • A hash of the proposal, checked again at execution time, so you can prove the executed action matches the approved one.

That last point catches a quiet failure. A proposal can be approved, and then the underlying record changes before the agent writes to it.

Outcomes

  • Records created, updated or cancelled, with IDs and before and after values for changed fields.
  • External side effects: emails or WhatsApp messages sent, payment or refund API calls, files written.
  • Final run status: completed, failed, cancelled, or waiting for approval.
  • A short summary of what the agent says it did. Compare this with what the logs show it did.

Cost and budget

Record tokens and cost per model call, plus the budget remaining after each call. When a run loops or a prompt grows, this is often the first signal. If you need a hard spending ceiling in Odoo, our AI Base app lets you plug any AI model into Odoo with a hard monthly cap.

A minimal event schema

One event type with a typed payload keeps storage and querying simple:

JSON
{
  "event_id": "0b9f3c2e-6d0a-4e7b-9a51-2f6c1d8e7a10",
  "run_id": "run_2024_000913",
  "step": 7,
  "parent_step": 6,
  "ts": "2024-05-14T09:14:22.481Z",
  "type": "tool_call",
  "agent": "bill_processor@v3",
  "principal": "user:ap_clerk_02",
  "payload": {
    "tool": "erp.update_record@v2",
    "mode": "write",
    "target": {"system": "odoo", "model": "account.move", "id": 22817},
    "args": {"invoice_date": "2024-05-10", "ref": "INV-88412"},
    "policy": {"checked": ["value_limit", "field_allowlist"], "result": "allowed"},
    "result": {"status": "ok", "latency_ms": 184}
  },
  "prev_hash": "9d1e...",
  "hash": "4a7c..."
}

The type field takes a small fixed set of values: run_start, model_call, tool_call, approval_request, approval_decision, outcome and run_end.

Storage: append-only and tamper-evident

An audit trail that can be edited is not evidence. Two controls do most of the work.

  1. Append-only at the database level. The application role can insert but not update or delete.
  2. A hash chain. Each event stores the hash of the previous event in the same run. If someone alters or removes an event, the chain breaks.

In PostgreSQL:

PostgreSQL
CREATE TABLE agent_audit_event (
    event_id     uuid PRIMARY KEY,
    run_id       text        NOT NULL,
    step         integer     NOT NULL,
    parent_step  integer,
    ts           timestamptz NOT NULL,
    type         text        NOT NULL,
    agent        text        NOT NULL,
    principal    text,
    payload      jsonb       NOT NULL,
    prev_hash    text,
    hash         text        NOT NULL,
    UNIQUE (run_id, step)
) PARTITION BY RANGE (ts);

CREATE INDEX ON agent_audit_event (run_id, step);
CREATE INDEX ON agent_audit_event USING gin ((payload -> 'target'));

CREATE OR REPLACE FUNCTION agent_audit_block_change() RETURNS trigger AS $$
BEGIN
    RAISE EXCEPTION 'agent_audit_event is append-only';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER agent_audit_immutable
    BEFORE UPDATE OR DELETE ON agent_audit_event
    FOR EACH ROW EXECUTE FUNCTION agent_audit_block_change();

REVOKE UPDATE, DELETE ON agent_audit_event FROM agent_app;

Monthly partitions solve retention. Expiring old data means dropping a whole partition, done by a separate admin role under a documented procedure, rather than deleting rows.

For stronger guarantees, ship events to storage outside the ERP database, such as an object store with write-once settings. Then a compromised ERP server cannot rewrite history.

Logging tool calls without slowing the agent

Wrap every tool in one place so no call can skip the log. The write should succeed before a write-mode tool runs, so you never have an action without a record.

Python
import hashlib, json, time, uuid
from datetime import datetime, timezone

def _hash(event: dict, prev_hash: str | None) -> str:
    body = json.dumps(event, sort_keys=True, default=str)
    return hashlib.sha256(((prev_hash or "") + body).encode()).hexdigest()

def audited_tool(name, mode):
    def wrap(fn):
        def inner(run, *, target, **args):
            step = run.next_step()
            event = {
                "event_id": str(uuid.uuid4()),
                "run_id": run.id,
                "step": step,
                "parent_step": run.current_parent,
                "ts": datetime.now(timezone.utc).isoformat(),
                "type": "tool_call",
                "agent": run.agent,
                "principal": run.principal,
                "payload": {"tool": name, "mode": mode,
                            "target": target, "args": redact(args)},
            }
            policy = run.policy.check(name, mode, target, args)
            event["payload"]["policy"] = policy
            if policy["result"] != "allowed":
                event["payload"]["result"] = {"status": "blocked"}
                run.audit.append(event, _hash)
                raise PermissionError(policy["reason"])
            start = time.monotonic()
            try:
                result = fn(target=target, **args)
                event["payload"]["result"] = {"status": "ok"}
                return result
            except Exception as exc:
                event["payload"]["result"] = {"status": "error", "error": str(exc)[:500]}
                raise
            finally:
                event["payload"]["result"]["latency_ms"] = int((time.monotonic() - start) * 1000)
                run.audit.append(event, _hash)
        return inner
    return wrap

This shows the structure, not a finished library. For write tools, a stricter pattern is to append an intent event before the call and a result event after it. That way a crash mid-call still leaves a trace.

What not to log

An audit trail full of personal data becomes a liability of its own.

  • Redact secrets always: API keys, tokens, passwords, full card numbers.
  • Minimise personal data: log customer IDs, not names, addresses and phone numbers, when the ID is enough to look them up.
  • Hash large documents: store a SHA-256 of the PDF the agent read, plus a pointer to where the document lives, not the document itself.
  • Separate full prompt bodies: full prompts and responses help debugging but often contain personal data. Store them in a separate table with shorter retention and tighter access.

Write down which fields are redacted and why. Reviewers will ask.

How long to keep it

There is no single correct number. Set retention per category, driven by legal requirements and by how long it takes you to notice problems.

Category

Typical driver

Suggested approach

Approvals and outcomes on financial records

Accounting and tax rules

Same period as the financial records themselves, as your local law requires

Tool call events (args, results, policy checks)

Incident investigation

Long enough to cover your slowest detection path, such as a quarterly reconciliation

Full prompt and response bodies

Debugging, model evaluation

Short; keep them only as long as you actively use them, in line with data protection rules

Cost and token metrics

Budgeting

Aggregate monthly, then drop per-call detail

Two practical rules:

  1. Retention must outlast detection. If a wrong price is usually caught at month-end close, keeping detailed events for two weeks is useless.
  2. Approvals live as long as the records they approved. If a payment record exists, the evidence of who authorised the agent to make it should too.

Making it useful when something goes wrong

A log nobody can query in a hurry is only an archive. Design for the incident.

Start from the business record

Incidents are reported as "invoice 22817 has the wrong date", not "run 913 misbehaved". So the first query goes from a record to the runs that touched it:

SQL
SELECT run_id, step, ts, type, payload -> 'args' AS args,
       payload -> 'result' ->> 'status' AS status
FROM agent_audit_event
WHERE payload -> 'target' @> '{"model": "account.move", "id": 22817}'
ORDER BY ts;

Also write the run_id into the ERP record itself, for example as a note in the chatter or a custom field. Then an ERP user can find the run without database access.

Investigation steps

  1. Find the run from the affected record, as above.
  2. Rebuild the timeline by ordering all events for that run_id by step.
  3. Check the inputs. Was the source data wrong (a bad PDF, a stale price list), or did the agent misread correct data?
  4. Check the versions. Did the model, prompt template or tool definition change recently? Compare with the last run that behaved correctly.
  5. Check the approval. Was the action approved? Did the approver see the field that turned out to be wrong? Does the executed action's hash match the approved proposal?
  6. Measure the blast radius. Search for other runs with the same agent version and prompt version in the same period, and list every record they wrote.
  7. Fix and record the fix. Corrections should also be logged, linked to the original run.

Find similar runs

SQL
SELECT DISTINCT e.run_id, e.payload -> 'target' AS target
FROM agent_audit_event e
JOIN agent_audit_event m
  ON m.run_id = e.run_id AND m.type = 'model_call'
WHERE m.payload ->> 'prompt_template' = 'invoice_matcher@v14'
  AND e.type = 'tool_call'
  AND e.payload ->> 'mode' = 'write'
  AND e.ts >= now() - interval '7 days';

Replay

If you log the context references, prompt version and tool results, you can replay a run in a test environment. Feed it the same inputs with a fixed tool layer that returns the recorded results. Replay shows whether a prompt fix actually changes the decision, before you deploy it.

A short checklist

  • Every event has run_id, step and a UTC timestamp.
  • Model, prompt and tool versions are logged on every model call.
  • Every tool call is logged, including blocked and failed ones.
  • Approvals store what the approver saw and a hash checked at execution.
  • The table is append-only and hash-chained; retention works by dropping partitions.
  • Secrets are never logged; personal data is minimised.
  • You can go from an ERP record to its runs in one query.

How Kalvyai can help

We build AI agents that work inside Odoo, ERPNext and Shopify with human approvals, budgets and an audit trail designed in from the start. See how we approach it on our AI agents page, and browse our ready-made apps at store.kalvyai.com.

If you already run an agent and can't answer "what did it do, and why?", get in touch. We can review your current logging and design a trail that holds up when something goes wrong.

Share this article

  • AI agents
  • audit trail
  • Odoo
  • ERPNext
  • observability
  • governance

Kalvyai Engineering · Engineering team

The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.

Comments

No comments yet. Questions and corrections are welcome.

Rate this post or leave a comment

Your rating (optional)
Not rated

Comments appear after an editor approves them. See our privacy notice.

Read next

AI Bank Reconciliation: Suggested Matches a Person Confirms (cover)Technical
Kalvyai EngineeringAI agents

AI Bank Reconciliation: Suggested Matches a Person Confirms

How an AI matcher suggests bank reconciliation matches from descriptions and amounts, explains each one, sorts them by confidence, and leaves the final confirmation to a person.

7 min read

Claude Tool Use for ERP Tasks: Safe Read and Write Actions (cover)Technical
Kalvyai EngineeringAI agents

Claude Tool Use for ERP Tasks: Safe Read and Write Actions

How to give Claude function calling access to your ERP without giving it the keys: narrow tools, argument validation in code, approval gates for writes, and a log entry for every call. Includes a Python example against Odoo.

6 min read

Newsletter

Get new guides in your inbox.

Practical notes on Odoo, ERPNext, Shopify and AI agents, written by the engineers who build them. No spam, and you can ask to stop at any time.

Prefer a feed? Subscribe by RSS. We use your email only to send new articles. See our privacy policy.