BuilderIO/agent-native / packages/core/docs
agent-native-docs
UnverifiedHow to look up version-matched Agent-Native framework docs and source in node_modules. Use before coding against @agent-native/core APIs or advanced features.
content/audit-log.mdx
View on GitHub---
title: "Audit Log"
description: "A durable, append-only record of who changed what app data, when, and whether it was you or the agent — captured automatically at the action seam."
---
# Audit Log
Every agent-native app gets an audit log out of the box: a durable, complete, access-scoped, append-only record of **who mutated what app data, when, from where, and — when it was the agent — in which run.** Capture is automatic at the action seam; you write no code for it.
Because the agent can change data on your behalf, the headline question an audit log answers here isn't just "who edited this record" — it's **"was that me or the agent, and which turn caused it?"** No other system in the framework can answer that.
## Audit vs. observability vs. tracking {#which}
Three systems record "what happened," for three different reasons. Pick by the question you're asking:
| System | The question it answers | Fidelity | Audience |
| ---------------------------------------- | ------------------------------------------------------ | -------------------------------- | ----------------------------- |
| **Audit Log** (this page) | "Who changed this record, when, and was it the agent?" | **Complete, durable, scoped** | User, admin, the agent itself |
| **[Observability](/docs/observability)** | "Why did the agent do that, and what did it cost?" | Sampled span telemetry | Developer |
| **[Tracking](/docs/tracking)** | "How are people using the product?" | Fire-and-forget to external SaaS | PM / growth |
An audit log that's sampled or shipped off to an analytics provider is useless — the whole point is that it's complete, local, and queryable. So it's its own subsystem, not a mode of the other two.
## What's captured automatically {#captured}
When any **mutating** action runs (anything that isn't a read-only `GET`), the framework appends one row to `agent_audit_log` with:
- **Action** — the action name (e.g. `delete-recording`).
- **Actor** — `agent`, `human`, or `system`, plus the actor's email — populated **even for agent calls**, so you get "the agent, acting for alice@, …". The email is the account the call runs as. It does not say who approved the call.
- **Run linkage** — the agent `threadId` / `turnId` that triggered the call (a tool call), so a mutation traces back to the exact agent turn.
- **Surface** — `tool` (agent), `frontend`, `http`, `cli`, `mcp`, `webmcp`, or `a2a`. These are agent protocols, so a call over `mcp`, `webmcp`, or `a2a` records as `agent` acting for you, not as you.
- **Outcome** — `success`, `error` (with an error code), or `denied` (blocked by a human-approval gate).
- **Inputs** — the call arguments, with credential-shaped values [redacted](#privacy).
- **Target & owner** — the resource the action changed, used to [scope reads](#reading).
No wiring needed — the capture hooks into `defineAction` transparently. Read-only actions are skipped, and a few high-frequency framework actions (app-state sync, context-xray, navigation) are skipped by default to avoid flooding the log.
<DataModel
id="doc-block-auditlog1"
title="agent_audit_log"
summary="One append-only row per mutating action call. 'caller' is the actual column name for what the prose above calls the surface."
entities={[
{
id: "auditLog",
name: "agent_audit_log",
note: "Append-only — no update or delete action exists for these rows.",
fields: [
{ name: "id", type: "text", pk: true },
{ name: "created_at", type: "integer", nullable: false },
{
name: "action",
type: "text",
nullable: false,
note: "The action name, e.g. delete-recording.",
},
{
name: "caller",
type: "enum",
nullable: false,
note: "tool | frontend | http | cli | mcp | webmcp | a2a — the surface that invoked the action.",
},
{
name: "actor_kind",
type: "enum",
nullable: false,
note: "agent | human | service | system — service for the organization's own service principals, agent for other tool, mcp, webmcp, and a2a calls.",
},
{ name: "actor_email", type: "text", nullable: true },
{ name: "org_id", type: "text", nullable: true },
{
name: "thread_id",
type: "text",
nullable: true,
note: "Agent conversation thread, when caller is the agent loop.",
},
{ name: "turn_id", type: "text", nullable: true },
{
name: "target_type",
type: "text",
nullable: true,
note: "Set via audit.target on the action.",
},
{ name: "target_id", type: "text", nullable: true },
{
name: "status",
type: "enum",
nullable: false,
note: "success | error | denied — default 'success'.",
},
{ name: "summary", type: "text", nullable: true },
{
name: "input",
type: "text",
nullable: true,
note: "Redacted call arguments, JSON-encoded.",
},
{ name: "error_code", type: "text", nullable: true },
{
name: "owner_email",
type: "text",
nullable: true,
note: "Scopes who can read this event.",
},
{
name: "visibility",
type: "enum",
nullable: false,
note: "private | org | public — default 'private'.",
},
{
name: "reported_client_name",
type: "text",
nullable: true,
note: "The name an MCP client sent in clientInfo with this tools/call request. Self-reported.",
},
{
name: "reported_client_version",
type: "text",
nullable: true,
note: "The version an MCP client sent in clientInfo with this tools/call request. Self-reported.",
},
{
name: "oauth_client_id",
type: "text",
nullable: true,
note: "The OAuth client the MCP credential was issued to.",
},
{
name: "approval",
type: "enum",
nullable: true,
note: "agent-chat | a2a-review | mcp-client-accepted. Records the authorization signal; MCP client acceptance does not verify who responded.",
},
],
},
]}
/>
### Principal, client, and approval {#attribution}
An agent call records four separate facts. None of them stands in for another.
- **Principal**: `actor_email` is the account the call runs as. It is not evidence that anyone approved the call.
- **Execution source**: `caller` names the surface. A call over `mcp`, `webmcp`, or `a2a` has `actor_kind` `agent`, or `service` for the organization's own service principals.
- **Client**: for an `mcp` call, `reported_client_name` and `reported_client_version` hold what the client sent in MCP `clientInfo` with that individual `tools/call` request. The client chooses these values, so treat them as self-reported. `oauth_client_id` is the OAuth client the credential was issued to, when it has one. Values sent only in the earlier `initialize` message are not carried forward.
- **Approval signal**: `approval` records the authorization signal associated with that exact call. `agent-chat` records a person's approval in agent chat. `a2a-review` records the owner's approval of a paused A2A call on its review page. `mcp-review` records the signed-in owner's approval of a direct MCP call on its review page. `mcp-client-accepted` records that the MCP client accepted its elicitation; the server cannot verify who responded. A call that needed no approval leaves `approval` empty.
Older rows are never rewritten. Rows written before these columns existed have empty client and approval fields, even when the call was approved. Older `mcp`, `webmcp`, and `a2a` rows stored as `human` or `system` are read back as `agent`, so filters and exports treat them like newer rows.
## Declare what an action changed {#target}
By default an event is scoped to the **actor** — you see your own changes and the agent's changes on your behalf. To make a change to a _shared_ resource also appear in the **owner's** trail, and to label events by resource, declare a `target`:
```ts
export default defineAction({
description: "Delete a recording.",
schema: z.object({ id: z.string() }),
audit: {
target: (args, result) => ({
type: "recording",
id: args.id,
// Optional — defaults to the actor. Set when editing someone else's resource.
ownerEmail: result?.ownerEmail,
visibility: "org",
}),
summary: (args) => `Deleted recording ${args.id}`,
},
run: async (args, ctx) => {
/* ...delete... */
},
});
```
Everything in `audit` is optional. The minimum useful addition is `target: () => ({ type, id })`.
### Tuning capture {#tuning}
| Option | Effect |
| -------------------- | --------------------------------------------------------------- |
| `audit.target` | Label the event with the resource and scope reads to its owner. |
| `audit.summary` | A short human-readable line for the event. |
| `audit.onRead` | Audit a sensitive **read** (secret access, bulk export). |
| `audit.enabled` | `true` forces capture on; `false` opts a noisy mutation out. |
| `audit.recordInputs` | `false` skips capturing the (already redacted) arguments. |
## Reading the trail {#reading}
Three read actions are available to the agent **and** the frontend in every app, scoped in SQL to the caller — they never return another tenant's rows:
- **`list-audit-events`** — filter by `targetType` / `targetId`, `actorKind` (`agent` | `human` | `system`), `status`, `threadId` / `turnId`, `action`, `sinceMs`, and `limit`.
- **`get-audit-event`** — one event by id, including its redacted input payload.
- **`export-audit-events`** — bulk-export the trail as CSV or NDJSON instead of hand-paging `list-audit-events`, for offline compliance pulls. Takes the same filters as `list-audit-events` (minus `limit`) plus `format` (`csv` | `ndjson`, default `csv`) and `maxRows` (default 5000, hard cap 10000), and returns `{ content, rowCount, truncated, format }` — `truncated: true` means more rows matched than `maxRows` allowed. It's itself a sensitive read, audited via `audit: { onRead: true }`.
CSV output prefixes formula-like values in every exported column with an apostrophe before escaping, reducing the risk of spreadsheet formula execution.
Build an activity feed or a "who changed this" line by calling `list-audit-events` from the UI with `useActionQuery` — never hand-write a fetch to the audit table:
```tsx
import { useActionQuery } from "@agent-native/core/client/hooks";
const { data } = useActionQuery("list-audit-events", {
targetType: "recording",
targetId: recordingId,
});
// data.events → [{ action, actorKind, actorEmail, turnId, status, summary, createdAt }, …]
```
The agent can call the same action — ask it "what did you change on this recording?" and it answers from the trail.
## Export to a SIEM (OCSF) {#ocsf}
**`export-audit-ocsf`** returns the organization's trail as [OCSF](https://schema.ocsf.io) 1.9.0 API Activity events (`class_uid` 6003), oldest first, for a SIEM to pull on a schedule. Owners and admins only, and it reads the same `org` and `admins` events as the organization audit log, never anyone's private rows.
| Input | Meaning |
| -------- | ------------------------------------------------------------ |
| `since` | Only events at or after this ISO 8601 timestamp or epoch ms. |
| `until` | Only events before this ISO 8601 timestamp or epoch ms. |
| `cursor` | The `nextCursor` from the previous page. |
| `limit` | Events per page, up to 500 (default 100). |
It returns `{ events, hasMore, nextCursor }`. Store every returned `nextCursor` and send it back on the next pull, including when `events` is empty; empty pages advance the ready watermark. The cursor replays a five-minute overlap to catch late commits, so deduplicate across pulls by `metadata.uid`. The newest five seconds are held back so a late-written row is never skipped.
Each event maps `status` to `status_id` (`success` is Success; `error` and `denied` are Failure, with `denied` also `action_id` Denied and a higher `severity_id`), the actor to `actor.user` (a service principal is type Service), the action to `api.operation`, and the target to `resources`. Run, task, parent-task, thread, turn, and app ids have no OCSF field, so they sit under `unmapped`. The reported client name and version, the OAuth client id, and the approval also sit under `unmapped`. The client name is not put in an `actor` field because a SIEM would read it as verified. Call arguments are never exported.
## Privacy & retention {#privacy}
- **Redaction** — before any inputs are stored, credential-shaped keys and values (tokens, secrets, passwords, bearer strings) are stripped and oversized payloads truncated. The audit log never becomes a secondary store of secrets. Keep `summary` text free of sensitive data too.
- **Append-only** — there is no update or delete action for audit rows. The only deletion is the retention purge, which makes the log trustworthy as an audit trail.
- **Tenant isolation** — reads are scoped to the caller's identity and org; with no identity, nothing matches.
Configure via environment:
- `AGENT_NATIVE_AUDIT_RETENTION_DAYS` — how long rows are kept (default `365`; `0` = keep forever).
- `AGENT_NATIVE_AUDIT_ENABLED=false` — global kill switch.
## What's next
- [**Actions**](/docs/actions-overview) — the `defineAction` seam where capture happens
- [**Human-in-the-Loop Approvals**](/docs/actions-access-control#needs-approval) — gated actions, recorded as `denied`
- [**Security & Data Scoping**](/docs/security) — the ownership model audit reads reuse
- [**Observability**](/docs/observability) — agent-run telemetry (the other "what happened")
- [**Toolkit piece: History Kit**](/docs/toolkit-history) — the version-history timeline and undo/redo UI built on this trail
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |