# Audit Logs & Error Codes

> Canonical JSON error envelope, field-level validation diagnostics, the 4xx applied=false guarantee, reference error codes, and immutable organization audit logs with NDJSON export.

Every plane in OvertCMS Core—Delivery, Agent, and Admin—speaks a single canonical error envelope and records all security and editorial mutations into an immutable audit log.

## Canonical Error Envelope

All non-`2xx` JSON responses use the exact `ErrorEnvelope` shape:

```json
{
  "error": {
    "code": "validation_error",
    "message": "entry validation failed",
    "retryable": false,
    "applied": false,
    "issues": [
      {
        "field": "title",
        "label": "Title",
        "code": "max_length",
        "message": "value length 142 exceeds maximum 120 graphemes",
        "constraint": {
          "maxLength": 120,
          "actualLength": 142,
          "lengthUnit": "graphemes"
        },
        "instruction": "Concise headline under 80 characters."
      }
    ]
  }
}
```

### Envelope Fields

| Field | Type | Meaning |
| :--- | :--- | :--- |
| `error.code` | `string` | Stable machine-readable snake_case error code. |
| `error.message` | `string` | Human-readable summary of the failure. |
| `error.retryable` | `boolean` | `true` for transient errors (`429`, `500`, `503`); `false` for deterministic client/validation errors (`400`, `401`, `403`, `404`, `409`, `422`). |
| `error.applied` | `boolean` | Explicitly reports whether state changed. **`domain.WriteError` strictly enforces `applied: false` on every `4xx` response.** |
| `error.issues` | `ValidationIssue[]` | Optional list of field-level validation issues including `field`, `label`, `code`, `message`, `constraint`, `instruction`, and `searchEndpoint` (for reference fields so AI agents know where to search valid IDs). |
| `error.details` | `object` | Optional structured metadata for conflict resolution (e.g., `breakingChanges`, `affectedEntriesCount`, `confirmField`, `referencedBy`, `idempotencyKey`, `retryAfter`). |

---

## Common Error Codes Reference

<AccordionGroup>
  <Accordion title="400 Bad Request (Malformed Syntax & Query Parameters)">
    - `bad_request` — Generic malformed request.
    - `empty_body` — Required JSON request body was empty.
    - `body_too_large` — Control-plane JSON request exceeded `1 MiB` (`MaxJSONBodyBytes`).
    - `invalid_json` — Invalid JSON syntax, unknown field, or trailing payload.
    - `invalid_cursor` — Malformed keyset cursor or cursor sort order mismatch.
    - `invalid_query_param` / `invalid_depth` — Invalid boolean, integer, or depth parameter.
    - `invalid_idempotency_key` — `Idempotency-Key` exceeded `128` characters or contained control characters.
    - `self_reference_not_supported` — `?parent=` or `?tree=true` called on a PostType without a self-referencing field.
    - `import_line_too_long` / `import_limit_exceeded` — NDJSON archive exceeded `64 MiB`/line or `100,000` records.
  </Accordion>

  <Accordion title="401 Unauthorized (Authentication & Credential Failures)">
    - `unauthorized` — Missing Admin authentication.
    - `invalid_credentials` — Wrong email or password.
    - `invalid_token` — Expired/invalid Access JWT or API key sent to Admin Plane.
    - `invalid_refresh_token`, `session_revoked`, `session_expired` — Invalid or inactive refresh session.
    - `session_compromised` — Replayed rotated refresh token; **entire session family revoked**.
    - `invalid_api_key`, `api_key_revoked`, `api_key_expired` — Invalid, revoked, or expired `ocms_...` API key (or human token/cookie sent to Agent Plane).
    - `invalid_mfa_challenge`, `invalid_totp_code`, `invalid_recovery_code`, `mfa_not_enabled` — Second-factor verification failures.
    - `webauthn_cloned_credential`, `webauthn_assertion_failed`, `invalid_webauthn_credential` — WebAuthn/Passkey assertion failures or non-monotonic `signCount`.
    - `invalid_preview_token` — Missing, expired, or entry-mismatched `X-Preview-Token`.
  </Accordion>

  <Accordion title="403 Forbidden (RBAC, Scopes, CSRF & Step-Up MFA)">
    - `forbidden` / `insufficient_permissions` — Human role lacks required RBAC capability.
    - `forbidden_not_owner` — `writer` attempted to edit an entry created by another actor.
    - `insufficient_scope` — API key lacks the required scope (e.g., `entries:publish` or `schema:write`).
    - `post_type_not_allowed` — User or API key is not permitted access to the target PostType.
    - `publish_permission_required` / `publish_scope_required` — Attempted publish/schedule mutation without publish privileges.
    - `site_not_allowed` — API key belongs to a different site.
    - `ip_not_allowed` — Client IP is not in the API key's `allowedIps` CIDR allowlist.
    - `step_up_mfa_required` — Sensitive Admin action requires fresh MFA verification within `OVERTCMS_STEP_UP_MFA_TTL`.
    - `user_disabled` — User account is disabled.
    - `csrf_cross_site`, `csrf_origin_missing`, `csrf_origin_mismatch` — Cookie-authenticated Admin mutation failed CSRF Origin validation.
    - `idempotency_key_forbidden` — `Idempotency-Key` belongs to another actor.
  </Accordion>

  <Accordion title="404 Not Found & 405 Method Not Allowed">
    - `not_found` — Unmatched route.
    - `method_not_allowed` — Unsupported HTTP method on a matched route.
    - `site_not_found`, `post_type_not_found`, `component_not_found`, `entry_not_found`, `singleton_not_found`, `media_not_found`, `webhook_not_found`, `webhook_delivery_not_found`, `api_key_not_found`, `operation_not_found`, `user_not_found`.
  </Accordion>

  <Accordion title="409 Conflict (Concurrency, Drift, Confirmations & Uniqueness)">
    - `version_conflict` — Optimistic lock failed (`If-Match` / `expectedVersion` / `expectedEtag` mismatch).
    - `schema_drift_detected` — `If-Schema-Fingerprint` failed due to a breaking schema change or unknown fingerprint.
    - `breaking_schema_change_confirmation_required` — Schema update has breaking changes; inspect `details.breakingChanges` and `details.affectedEntriesCount`, then retry with `confirmBreakingChange: true`.
    - `live_takedown_confirmation_required` — Unpublishing, archiving, or trashing a `published` entry requires `confirmUnpublish: true`.
    - `idempotency_key_conflict` — Same `Idempotency-Key` reused with a different method, path, or body.
    - `operation_in_progress` — Concurrent request with the same `Idempotency-Key` is currently executing (`Retry-After: 1`).
    - `slug_already_exists`, `unique_field_conflict`, `singleton_already_exists`, `component_already_exists`, `post_type_already_exists`, `user_already_exists`.
    - `entry_trashed`, `invalid_status_transition`, `invalid_delivery_status`, `upload_already_processing_or_completed`.
    - `setup_already_completed`, `last_owner_protected`, `invitation_already_accepted`.
  </Accordion>

  <Accordion title="422 Unprocessable Entity (Validation, HTML, References & Media)">
    - `validation_error` — One or more field-level issues in `error.issues`.
    - `capability_disabled` — PostType capability (`draft`, `publish`, `schedule`, `delete`) is disabled.
    - `schedule_in_past`, `invalid_unpublish_time`, `invalid_locale`, `invalid_status`.
    - `reference_not_found`, `reference_cycle_detected`.
    - `placeholder_link_detected`, `disallowed_html_tag`, `disallowed_html_attribute`, `disallowed_h1`, `unsafe_url`, `cms_block_not_allowed`, `cms_block_invalid_props`, `component_not_ai_writable`.
    - `patch_target_not_found`, `patch_target_ambiguous`, `invalid_patch_op`.
    - `media_empty`, `media_too_large`, `media_unsupported_type`, `media_content_mismatch`, `media_ssrf_blocked`, `media_upload_missing`.
  </Accordion>

  <Accordion title="429 & 5xx (Retryable Rate Limits & Availability)">
    - `429 rate_limited` (`retryable: true`) — API key RPM, daily write cap, daily media byte cap, or Admin auth rate limit exceeded (includes `Retry-After` when applicable).
    - `503 agent_writes_paused` (`retryable: true`) — Site's `agentWritesPaused` kill switch is active.
    - `503 service_unavailable` (`retryable: true`) — Database not ready (`/readyz`) or media storage unconfigured.
    - `500 internal_error` (`retryable: true`) — Unexpected server error or recovered panic.
  </Accordion>
</AccordionGroup>

---

## Immutable Audit Logs

Every significant security, schema, entry, media, API key, user, and webhook action is synchronously recorded in the append-only `audit_logs` table before the response returns.

### Audit Record Schema

```json
{
  "id": "0193a8b6-7c1e-7000-a001-000000000042",
  "organizationId": "0193a8b0-0000-7000-8000-000000000000",
  "siteId": "0193a8b0-0000-7000-8000-000000000001",
  "actorKind": "api_key",
  "actorId": "0193a8b1-...",
  "actorName": "Blog Automation Agent",
  "action": "entry.published",
  "resourceType": "entry",
  "resourceId": "0193a8b2-...",
  "diffSummary": {
    "postType": "posts",
    "slug": "hello-overtcms",
    "version": 2
  },
  "ipAddress": "10.20.4.18",
  "userAgent": "overt-agent-sdk/1.0",
  "idempotencyKey": "publish-hello-overtcms-001",
  "createdAt": "2026-11-25T15:30:00Z"
}
```

### Tracked Actor Kinds

- `user` — Authenticated human operator on the Admin Plane.
- `api_key` — Scoped programmatic API key on the Agent Plane.
- `mcp` — AI client invoking tools through `/mcp`.
- `system` — Automated background jobs (such as `OvertCMS Scheduler`).

### Recorded Audit Actions

| Domain | Action Names |
| :--- | :--- |
| **Auth & Sessions** | `auth.setup_owner`, `auth.login.success`, `auth.login.failed`, `auth.oidc.login`, `auth.session.refreshed`, `auth.session.compromised`, `auth.logout`, `auth.sessions.revoked_all` |
| **MFA & Passkeys** | `auth.mfa.totp_enrolled`, `auth.mfa.verified`, `auth.mfa.failed`, `auth.mfa.step_up`, `auth.webauthn.registered`, `auth.webauthn.deleted` |
| **Org, Sites & Users** | `org.mfa_policy_updated`, `site.updated`, `site.agent_writes_paused`, `site.agent_writes_resumed`, `user.invited`, `user.invite_accepted`, `user.profile_updated`, `user.role_updated` |
| **API Keys & Webhooks** | `api_key.created`, `api_key.revoked`, `webhook.created`, `webhook.updated`, `webhook.deleted`, `webhook.delivery_replayed` |
| **Schema** | `component.created`, `component.updated`, `component.deleted`, `post_type.created`, `post_type.updated`, `post_type.deleted` |
| **Entries** | `entry.created`, `entry.updated`, `entry.published`, `entry.unpublished`, `entry.scheduled`, `entry.schedule_failed`, `entry.archived`, `entry.trashed`, `entry.restored`, `entry.restore_version`, `entry.purged` |
| **Media** | `media.uploaded`, `media.deleted` |

### Querying & Exporting Audit Logs

Users with the `audit:read` capability (`owner` and `admin`) can query and stream audit trails on the Admin Plane:

- **Cursor-paginated query**: `GET /admin-api/v1/audit-logs`
  - Query filters: `siteId`, `action`, `actorId`, `resourceType`, `resourceId`, `limit` (default `50`, max `200`), and `cursor`.
- **SIEM / Compliance NDJSON Export**: `GET /admin-api/v1/audit-logs/export`
  - Accepts the same filters and streams matching `AuditLog` records as newline-delimited JSON (`application/x-ndjson`), paginated internally in chunks of 200 up to **100,000 events** per export stream.

<Note>
  Every HTTP response also carries an `X-Request-ID` header that matches the `request_id` attribute in structured `slog` logs—making it effortless to correlate client errors, server logs, and `audit_logs` rows via `idempotencyKey` and timestamp.
</Note>
