> ## Documentation Index
> Fetch the complete documentation index at: https://docs.akhara.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Company name is Akhara AI (never Rubric AI). Keep lowercase rubric/rubrics only when meaning grading criteria.
> Expert Review (docs path talent/) is enterprise BYO experts for audit and review: invite customer specialists; do not pitch Akhara recruiting or a public expert career portal. RLHF and domain writing are secondary work types.
> Prefer concrete API examples against public hosts: Environments eval API https://agi.akhara.ai, Control plane PDP https://api.akhara.dev, Evaluation https://app.akhara.ai / https://api.akhara.ai, Expert Review portal https://talent.akhara.ai.
> Do not invent a public hostname for private orchestrators or env API internals.
> Do not confuse control-plane latches with Environments confirmation latches.
> Environments SDK/API examples: curl against https://agi.akhara.ai. Evaluation SDK: from akhara import Akhara and AKHARA_API_KEY.
> Start with /llms.txt for the docs index and OpenAPI links; fetch individual pages as .md exports.

# Audit & Provenance APIs

> Access audit logs, track data lineage, and maintain compliance with full provenance tracking.

## Overview

The Audit & Provenance APIs provide programmatic access to audit logs and data lineage tracking. Use these endpoints to build compliance dashboards, integrate with SIEM systems, and trace the complete history of any sample or evaluation.

**Base URL:** `https://api.akhara.ai/v1/audit`

***

## List Audit Logs

Query audit logs with filtering and pagination.

<EndpointBlock method="GET" path="/v1/audit/logs" />

### Query Parameters

| Parameter       | Type    | Description                                                          |
| --------------- | ------- | -------------------------------------------------------------------- |
| `event_type`    | string  | Filter by event type (e.g., `sample.phi_accessed`)                   |
| `actor_id`      | string  | Filter by user who performed action                                  |
| `resource_type` | string  | Filter by resource type: `sample`, `dataset`, `evaluation`, `review` |
| `resource_id`   | string  | Filter by specific resource ID                                       |
| `start_time`    | string  | Start of time range (ISO 8601)                                       |
| `end_time`      | string  | End of time range (ISO 8601)                                         |
| `limit`         | integer | Results per page (1-1000)                                            |
| `after`         | string  | Pagination cursor                                                    |

### Example Request

<CodeGroup>
  ```python Python theme={null}
  from akhara import Akhara
  from datetime import datetime, timedelta

  client = Akhara()

  # Get PHI access logs from the last 7 days
  logs = client.audit.list(
      event_type="sample.phi_accessed",
      start_time=datetime.now() - timedelta(days=7),
      limit=100
  )

  for log in logs:
      print(f"{log.timestamp}: {log.actor.email}")
      print(f"  Resource: {log.resource.type}/{log.resource.id}")
      print(f"  Fields: {log.context.get('fields_accessed')}")
  ```

  ```bash cURL theme={null}
  curl "https://api.akhara.ai/v1/audit/logs?event_type=sample.phi_accessed&limit=100" \
    -H "Authorization: Bearer rb_live_xxxxxxxx"
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "object": "list",
  "data": [
    {
      "id": "log_8f3k2m9x",
      "timestamp": "2024-01-15T14:32:18.042Z",
      "event_type": "sample.phi_accessed",
      "actor": {
        "type": "user",
        "id": "user_abc123",
        "email": "dr.smith@hospital.org",
        "ip_address": "192.168.1.42",
        "user_agent": "Mozilla/5.0..."
      },
      "resource": {
        "type": "sample",
        "id": "smp_xyz789",
        "project": "proj_triage_v2",
        "dataset": "ds_q1_calls"
      },
      "context": {
        "fields_accessed": ["transcript", "patient_age"],
        "access_justification": "Clinical review assignment",
        "session_id": "sess_m8k2p"
      },
      "org_id": "org_healthcare_inc"
    }
  ],
  "has_more": true,
  "next_cursor": "log_7g2j1n8w"
}
```

***

## Get Audit Log

Retrieve a specific audit log entry.

<EndpointBlock method="GET" path="/v1/audit/logs/{log_id}" />

### Example Request

<CodeGroup>
  ```python Python theme={null}
  log = client.audit.get("log_8f3k2m9x")

  print(f"Event: {log.event_type}")
  print(f"Actor: {log.actor.email}")
  print(f"Time: {log.timestamp}")
  print(f"Context: {log.context}")
  ```

  ```bash cURL theme={null}
  curl "https://api.akhara.ai/v1/audit/logs/log_8f3k2m9x" \
    -H "Authorization: Bearer rb_live_xxxxxxxx"
  ```
</CodeGroup>

***

## Stream Audit Logs

Stream audit logs in real-time via Server-Sent Events.

<EndpointBlock method="GET" path="/v1/audit/stream" />

### Query Parameters

| Parameter     | Type  | Description                 |
| ------------- | ----- | --------------------------- |
| `event_types` | array | Event types to subscribe to |
| `projects`    | array | Filter to specific projects |

### Example Request

<CodeGroup>
  ```python Python theme={null}
  # Stream PHI access events in real-time
  for event in client.audit.stream(
      event_types=["sample.phi_accessed", "dataset.exported"]
  ):
      print(f"[{event.timestamp}] {event.event_type}: {event.actor.email}")
      
      if event.event_type == "sample.phi_accessed":
          # Alert on PHI access
          send_alert(event)
  ```

  ```bash cURL theme={null}
  curl -N "https://api.akhara.ai/v1/audit/stream?event_types=sample.phi_accessed" \
    -H "Authorization: Bearer rb_live_xxxxxxxx" \
    -H "Accept: text/event-stream"
  ```
</CodeGroup>

### SSE Format

```
event: audit_log
data: {"id": "log_xyz", "event_type": "sample.phi_accessed", ...}

event: audit_log
data: {"id": "log_abc", "event_type": "dataset.exported", ...}
```

***

## Get Resource Provenance

Retrieve the complete history and lineage of a resource.

<EndpointBlock method="GET" path="/v1/audit/provenance/{resource_type}/{resource_id}" />

### Path Parameters

| Parameter       | Type   | Description                                 |
| --------------- | ------ | ------------------------------------------- |
| `resource_type` | string | `sample`, `dataset`, `evaluation`, `review` |
| `resource_id`   | string | Resource ID                                 |

### Query Parameters

| Parameter         | Type    | Description                                               |
| ----------------- | ------- | --------------------------------------------------------- |
| `include_related` | boolean | Include related resources (e.g., evaluations of a sample) |
| `depth`           | integer | Levels of related resources to include (1-5)              |

### Example Request

<CodeGroup>
  ```python Python theme={null}
  # Get complete provenance of a sample
  provenance = client.audit.get_provenance(
      resource_type="sample",
      resource_id="smp_abc123",
      include_related=True,
      depth=3
  )

  print(f"Sample: {provenance.resource.id}")
  print(f"Created: {provenance.created_at}")
  print(f"Created by: {provenance.created_by.email}")

  print("\nHistory:")
  for event in provenance.history:
      print(f"  {event.timestamp}: {event.event_type}")

  print("\nEvaluations:")
  for eval in provenance.related.evaluations:
      print(f"  {eval.id}: {eval.score}%")

  print("\nReviews:")
  for review in provenance.related.reviews:
      print(f"  {review.id} by {review.reviewer.name}")
  ```

  ```bash cURL theme={null}
  curl "https://api.akhara.ai/v1/audit/provenance/sample/smp_abc123?include_related=true&depth=3" \
    -H "Authorization: Bearer rb_live_xxxxxxxx"
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "resource": {
    "type": "sample",
    "id": "smp_abc123",
    "dataset": "ds_xyz789",
    "project": "proj_triage_v2"
  },
  "created_at": "2024-01-10T08:00:00Z",
  "created_by": {
    "type": "user",
    "id": "user_engineer1",
    "email": "engineer@company.com"
  },
  "source": {
    "type": "api_upload",
    "request_id": "req_m8k2p"
  },
  "history": [
    {
      "timestamp": "2024-01-10T08:00:00Z",
      "event_type": "sample.created",
      "actor": {"email": "engineer@company.com"}
    },
    {
      "timestamp": "2024-01-12T10:30:00Z",
      "event_type": "sample.evaluated",
      "actor": {"type": "system"},
      "context": {"evaluation": "eval_def456"}
    },
    {
      "timestamp": "2024-01-15T14:30:00Z",
      "event_type": "sample.reviewed",
      "actor": {"email": "dr.smith@hospital.org"},
      "context": {"review": "rev_xyz789"}
    }
  ],
  "related": {
    "evaluations": [
      {
        "id": "eval_def456",
        "name": "Weekly Triage Eval",
        "scores": {
          "triage_accuracy": 45.0,
          "red_flag_detection": 100.0
        },
        "completed_at": "2024-01-12T10:45:00Z"
      }
    ],
    "reviews": [
      {
        "id": "rev_xyz789",
        "reviewer": {
          "id": "user_dr_smith",
          "name": "Dr. Sarah Smith",
          "credentials": ["MD"]
        },
        "grades": {
          "triage_accuracy": "under_triaged"
        },
        "override_value": 35.0,
        "submitted_at": "2024-01-15T14:30:00Z"
      }
    ]
  },
  "data_lineage": {
    "origin": {
      "system": "production_triage_api",
      "call_id": "call_prod_12345",
      "ingested_at": "2024-01-10T08:00:00Z"
    },
    "transformations": []
  }
}
```

***

## Verify Log Integrity

Verify the cryptographic integrity of audit logs (Enterprise).

<EndpointBlock method="POST" path="/v1/audit/verify" />

### Request Body

| Parameter    | Type   | Required | Description                 |
| ------------ | ------ | -------- | --------------------------- |
| `start_time` | string | Yes      | Start of verification range |
| `end_time`   | string | Yes      | End of verification range   |
| `project`    | string | No       | Filter to specific project  |

### Example Request

<CodeGroup>
  ```python Python theme={null}
  verification = client.audit.verify_integrity(
      start_time="2024-01-01T00:00:00Z",
      end_time="2024-01-31T23:59:59Z"
  )

  print(f"Verified: {verification.valid}")
  print(f"Entries checked: {verification.entry_count}")
  print(f"Chain hash: {verification.chain_hash}")
  print(f"Verification time: {verification.verification_time_ms}ms")

  if not verification.valid:
      print(f"Errors: {verification.errors}")
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.akhara.ai/v1/audit/verify" \
    -H "Authorization: Bearer rb_live_xxxxxxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "start_time": "2024-01-01T00:00:00Z",
      "end_time": "2024-01-31T23:59:59Z"
    }'
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "valid": true,
  "start_time": "2024-01-01T00:00:00Z",
  "end_time": "2024-01-31T23:59:59Z",
  "entry_count": 15847,
  "chain_hash": "sha256:a1b2c3d4e5f6...",
  "first_entry_hash": "sha256:1a2b3c4d5e6f...",
  "last_entry_hash": "sha256:f6e5d4c3b2a1...",
  "verification_time_ms": 1234,
  "verified_at": "2024-02-01T10:00:00Z"
}
```

***

## Generate Compliance Report

Generate pre-formatted compliance reports.

<EndpointBlock method="POST" path="/v1/audit/reports" />

### Request Body

| Parameter     | Type   | Required | Description                         |
| ------------- | ------ | -------- | ----------------------------------- |
| `report_type` | string | Yes      | Report type (see below)             |
| `start_time`  | string | Yes      | Report period start                 |
| `end_time`    | string | Yes      | Report period end                   |
| `format`      | string | No       | `pdf`, `csv`, `json` (default: pdf) |
| `project`     | string | No       | Filter to specific project          |

### Report Types

| Type              | Description                                        |
| ----------------- | -------------------------------------------------- |
| `hipaa_access`    | All PHI access with user, time, justification      |
| `user_activity`   | Complete user action summary                       |
| `security_events` | Failed logins, key revocations, permission changes |
| `data_lifecycle`  | Dataset creation, modification, deletion           |
| `review_summary`  | Human review activity and outcomes                 |

### Example Request

<CodeGroup>
  ```python Python theme={null}
  # Generate HIPAA access report
  report = client.audit.generate_report(
      report_type="hipaa_access",
      start_time="2024-01-01T00:00:00Z",
      end_time="2024-03-31T23:59:59Z",
      format="pdf"
  )

  # Wait for generation
  report.wait()

  # Download
  report.download("hipaa_q1_2024.pdf")

  print(f"Report ID: {report.id}")
  print(f"Pages: {report.page_count}")
  print(f"Events covered: {report.event_count}")
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.akhara.ai/v1/audit/reports" \
    -H "Authorization: Bearer rb_live_xxxxxxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "report_type": "hipaa_access",
      "start_time": "2024-01-01T00:00:00Z",
      "end_time": "2024-03-31T23:59:59Z",
      "format": "pdf"
    }'
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "id": "report_xyz789",
  "object": "audit_report",
  "report_type": "hipaa_access",
  "status": "completed",
  "period": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-03-31T23:59:59Z"
  },
  "format": "pdf",
  "event_count": 2847,
  "page_count": 45,
  "download_url": "https://api.akhara.ai/v1/audit/reports/report_xyz789/download",
  "expires_at": "2024-04-07T00:00:00Z",
  "created_at": "2024-04-01T10:00:00Z"
}
```

***

## Configure SIEM Export

Set up real-time log forwarding to SIEM systems.

<EndpointBlock method="POST" path="/v1/audit/exports" />

### Request Body

| Parameter     | Type   | Required | Description                                  |
| ------------- | ------ | -------- | -------------------------------------------- |
| `name`        | string | Yes      | Export configuration name                    |
| `destination` | string | Yes      | `splunk`, `datadog`, `sumo_logic`, `webhook` |
| `config`      | object | Yes      | Destination-specific configuration           |
| `event_types` | array  | No       | Filter to specific events (default: all)     |
| `projects`    | array  | No       | Filter to specific projects                  |

### Example: Splunk Integration

<CodeGroup>
  ```python Python theme={null}
  export = client.audit.create_export(
      name="Splunk Production",
      destination="splunk",
      config={
          "hec_endpoint": "https://splunk.example.com:8088",
          "hec_token": "your-hec-token",
          "index": "rubric_audit",
          "source_type": "akhara:audit"
      },
      event_types=["*.phi_accessed", "*.exported", "user.*"]
  )

  print(f"Export configured: {export.id}")
  print(f"Status: {export.status}")
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.akhara.ai/v1/audit/exports" \
    -H "Authorization: Bearer rb_live_xxxxxxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Splunk Production",
      "destination": "splunk",
      "config": {
        "hec_endpoint": "https://splunk.example.com:8088",
        "hec_token": "your-hec-token",
        "index": "rubric_audit"
      }
    }'
  ```
</CodeGroup>

### Example: Webhook Integration

```python theme={null}
export = client.audit.create_export(
    name="Custom SIEM Webhook",
    destination="webhook",
    config={
        "url": "https://your-siem.example.com/ingest",
        "headers": {
            "Authorization": "Bearer your-siem-token"
        },
        "batch_size": 100,
        "batch_interval_seconds": 60
    },
    event_types=["sample.phi_accessed", "evaluation.completed"]
)
```

***

## Event Types Reference

### User Events

* `user.login`: User authenticated
* `user.logout`: User session ended
* `user.invite`: User invited to org
* `user.role_changed`: User role modified
* `user.removed`: User removed from org

### Data Events

* `dataset.created`: Dataset created
* `dataset.updated`: Dataset modified
* `dataset.deleted`: Dataset deleted
* `dataset.exported`: Dataset exported
* `sample.created`: Sample added
* `sample.viewed`: Sample accessed
* `sample.phi_accessed`: PHI fields accessed
* `sample.deleted`: Sample deleted

### Evaluation Events

* `evaluation.created`: Evaluation started
* `evaluation.completed`: Evaluation finished
* `evaluation.failed`: Evaluation errored
* `evaluation.cancelled`: Evaluation cancelled

### Review Events

* `review.assigned`: Task assigned
* `review.submitted`: Review completed
* `review.overridden`: AI score overridden

### Admin Events

* `project.created`: Project created
* `project.settings_changed`: Project modified
* `api_key.created`: API key generated
* `api_key.revoked`: API key revoked

***

## Related

<CardGroup cols={2}>
  <Card title="Audit Logs (Concepts)" icon="scroll" href="/evaluation/api-reference/authentication/audit-logs">
    Understanding audit logging
  </Card>

  <Card title="RBAC" icon="lock" href="/evaluation/api-reference/authentication/rbac">
    Access control configuration
  </Card>
</CardGroup>
