# Bellona Session Timeline and Audit Bundle Runbook

Runbook date: 2026-04-22

Scope: `180.C.08.08`

This runbook documents the supported Phase 180 gateway flow for reading a
session timeline and producing an audit bundle from the current first-stage
store. It reflects the gateway implementation as of `180.C.08`: timeline reads
are available over HTTP and through `app.timeline.queryTimeline()`, while audit
bundle export is a documented operator procedure built from the durable gateway
store and registered as an `audit-export` artifact. A dedicated audit export
HTTP endpoint is not implemented yet.

## Implementation Surfaces

| Surface                    | Current support                                                                                                                                                                                               |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Timeline service           | `app.timeline.queryTimeline(query)` merges session lifecycle, command client events, approval records, artifact metadata, and audit-backed stream events.                                                     |
| Timeline HTTP API          | `GET /v1/timeline` accepts query parameters and returns `RemoteGatewayTimelineQueryResult`.                                                                                                                   |
| Artifact metadata registry | `POST /v1/artifacts` registers screenshots, renders, logs, browser traces, exports, and diagnostic bundles. `purpose: "export"` maps to protocol artifact kind `audit-export`.                                |
| Durable first-stage store  | `BELLONA_REMOTE_GATEWAY_STORE_FILE` persists sessions, commands, command events, approval requests/decisions, artifacts, pairing codes, device snapshots, and hash-chained audit entries in atomic JSON form. |
| Audit log                  | `app.auditLog.getEntries(type?)` returns hash-chained `RemoteAuditEntry` records in process. Durable audit bundle export should use the persistent store snapshot when available.                             |

## Reading A Session Timeline

Start the gateway with a durable store when the timeline needs to survive a
process restart or become part of an audit bundle:

```bash
export BELLONA_REMOTE_GATEWAY_STORE_FILE=.local/bellona/remote-gateway.store.json
BELLONA_REMOTE_GATEWAY_PORT=4097 pnpm nx start @bellona/remote-gateway
```

Read the full session timeline with a bounded page size:

```bash
SESSION_ID=session:example-remote-control

curl -fsS \
  "http://127.0.0.1:4097/v1/timeline?sessionId=${SESSION_ID}&limit=200" \
  | jq '.events[] | {
      occurredAt,
      kind,
      type,
      source,
      commandId,
      auditSequence,
      artifactIds,
      evidenceIds
    }'
```

Use narrower filters when reviewing a specific command, approval, stream, or
artifact:

```bash
curl -fsS \
  "http://127.0.0.1:4097/v1/timeline?sessionId=${SESSION_ID}&kind=command,approval&limit=100"

curl -fsS \
  "http://127.0.0.1:4097/v1/timeline?commandId=command:blender-scene-query-001&kind=command"

curl -fsS \
  "http://127.0.0.1:4097/v1/timeline?artifactId=artifact:audit-bundle-000001&kind=artifact"
```

Supported query parameters:

| Parameter            | Meaning                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------- |
| `sessionId`          | Restrict events to one remote-control session.                                                    |
| `commandId`          | Restrict events to one command.                                                                   |
| `deviceId`           | Restrict events to one remote device.                                                             |
| `actorParticipantId` | Restrict events to one participant when the source event carries actor attribution.               |
| `streamId`           | Restrict stream events derived from `evidence.captured` audit metadata.                           |
| `artifactId`         | Restrict events that reference the artifact id.                                                   |
| `approvalRequestId`  | Restrict approval request and decision events for one approval request.                           |
| `kind`               | Repeat or comma-separate `session`, `command`, `approval`, `stream`, and `artifact`.              |
| `type`               | Repeat or comma-separate exact event types such as `command.received` or `artifact.registered`.   |
| `after` / `before`   | ISO timestamp bounds.                                                                             |
| `limit` / `offset`   | Pagination controls. `limit` defaults to `200` and is capped at `1000`; `offset` defaults to `0`. |

Timeline events are sorted by `occurredAt` ascending. When timestamps are tied,
the service applies a deterministic source order: session lifecycle, audit log,
artifact store, command store, then approval store. Each event includes the
source-specific identifiers available for correlation, including `commandId`,
`deviceId`, `auditEntryId`, `auditSequence`, `approvalRequestId`, `streamId`,
`artifactIds`, `evidenceIds`, and normalized metadata.

Expected command review patterns:

- Allowed command: `command.received`, `command.dispatched`, optional
  `command.progress`, `command.result`, then `command.completed`.
- Policy-denied command: `command.received`, then `policy.denied`; no host
  dispatch should appear.
- Failed command: `command.received`, `command.dispatched`, then
  `command.failed` or a `command.error` client event.
- Approval command: `command.received`, `approval.requested`, then after the
  decision `approval.decided`, `command.dispatched`, and final result or failure
  events.
- Stream evidence: `evidence.captured` events appear as `stream` events only
  when the audit metadata contains `streamId`. A dedicated stream store is a
  later Phase 180 item.
- Artifact evidence: when an artifact store is configured, `artifact` events are
  sourced from stored artifact metadata. Without an artifact store, the timeline
  falls back to audit-backed `artifact.registered` entries.

## Exporting An Audit Bundle

Audit bundles are exported from the first-stage store snapshot. The export
should include the timeline page used for review, filtered audit records,
artifact metadata, approval records, command dispatch records, command client
events, and a checksum manifest. The current gateway does not copy artifact
binaries; the bundle records artifact IDs, URIs, media types, byte sizes,
redaction status, and SHA-256 hashes so a later artifact store can retrieve the
binary evidence.

When the gateway opens an older first-stage store, schema version `1` and `2`
snapshots are migrated to the current schema before export. Include the store's
record version stamps and migration history in the bundle so reviewers can see
which device, session, command, approval, and audit record sets were migrated.

Prerequisites:

- Start the gateway with `BELLONA_REMOTE_GATEWAY_STORE_FILE`.
- Make sure the session is paused, stopped, or otherwise quiescent before
  exporting when an exact endpoint-in-time bundle is required.
- Ensure retained artifact/log metadata is already redacted where required.
- Install `jq`, `shasum`, and `zip` in the operator shell.

Create a bundle directory and capture the review timeline:

```bash
SESSION_ID=session:example-remote-control
GATEWAY_URL=http://127.0.0.1:4097
STORE_FILE=.local/bellona/remote-gateway.store.json
EXPORT_DIR=.local/bellona/audit-export/${SESSION_ID}

mkdir -p "${EXPORT_DIR}"

curl -fsS "${GATEWAY_URL}/v1/timeline?sessionId=${SESSION_ID}&limit=1000" \
  > "${EXPORT_DIR}/timeline.json"
```

Filter the durable store snapshot into an audit bundle JSON document:

```bash
jq --arg sessionId "${SESSION_ID}" '
  {
    schemaVersion: 1,
    bundleKind: "bellona-remote-audit-bundle",
    sessionId: $sessionId,
    exportedAt: (now | todateiso8601),
    gatewayStore: {
      schemaVersion,
      storage,
      createdAt,
      updatedAt,
      recordVersionStamps,
      migrationHistory
    },
    sessions: [
      .sessions[] | select(.id == $sessionId)
    ],
    auditEntries: [
      .auditEntries[] | select(.sessionId == $sessionId)
    ],
    artifacts: [
      .artifacts[] | select(.sessionId == $sessionId)
    ],
    commands: [
      .commands[] | select(.command.sessionId == $sessionId)
    ],
    commandEvents: [
      .commandEvents[]
      | select(
          .sessionId == $sessionId
          or .progress?.sessionId == $sessionId
          or .result?.sessionId == $sessionId
        )
    ],
    approvalRequests: [
      .approvalRequests[] | select(.sessionId == $sessionId)
    ],
    approvalDecisions: [
      .approvalDecisions[] | select(.sessionId == $sessionId)
    ]
  }
' "${STORE_FILE}" > "${EXPORT_DIR}/audit-bundle.json"
```

Create checksums and a ZIP archive:

```bash
(
  cd "${EXPORT_DIR}"
  shasum -a 256 timeline.json audit-bundle.json > manifest.sha256
  zip -q audit-bundle.zip timeline.json audit-bundle.json manifest.sha256
)

BUNDLE_SHA256=$(shasum -a 256 "${EXPORT_DIR}/audit-bundle.zip" | awk '{print $1}')
BUNDLE_SIZE=$(wc -c < "${EXPORT_DIR}/audit-bundle.zip" | tr -d ' ')
```

Register the bundle metadata with the gateway artifact registry. Use a URI that
points to where the ZIP was retained. For local first-stage development, a
`file://` URI can identify the operator-local bundle; production storage should
use the future artifact/object-store URI.

```bash
BUNDLE_URI="file://${PWD}/${EXPORT_DIR}/audit-bundle.zip"

jq -n \
  --arg sessionId "${SESSION_ID}" \
  --arg uri "${BUNDLE_URI}" \
  --arg sha256 "${BUNDLE_SHA256}" \
  --argjson byteSize "${BUNDLE_SIZE}" \
  '{
    purpose: "export",
    sessionId: $sessionId,
    uri: $uri,
    mediaType: "application/zip",
    byteSize: $byteSize,
    sha256: $sha256,
    redactionStatus: "not-required",
    metadata: {
      exportKind: "audit-bundle-v1",
      includes: [
        "timeline",
        "auditEntries",
        "artifacts",
        "commands",
        "commandEvents",
        "approvalRequests",
        "approvalDecisions"
      ]
    }
  }' \
  | curl -fsS -X POST "${GATEWAY_URL}/v1/artifacts" \
      -H 'content-type: application/json' \
      --data-binary @-
```

Confirm that the registered audit-export artifact appears in the timeline:

```bash
curl -fsS "${GATEWAY_URL}/v1/artifacts?sessionId=${SESSION_ID}&kind=audit-export" \
  | jq '.artifacts[] | {id, kind, uri, sha256, byteSize, redactionStatus}'

curl -fsS "${GATEWAY_URL}/v1/timeline?sessionId=${SESSION_ID}&kind=artifact&type=artifact.registered" \
  | jq '.events[] | select(.metadata.artifactKind == "audit-export")'
```

## Review Checklist

Before treating an audit bundle as review-ready:

- The `auditEntries` array is non-empty for the session.
- Audit entry `sequence` values are contiguous inside the gateway store. The
  persistent store validates sequence and hash-chain links on startup.
- Every audit entry includes `actorChain` and normalized actor metadata
  (`actorChainId`, `actorRootActorId`, `actorTerminalActorId`, `actorIds`,
  `actorStableIds`, and `actorKinds`) so delegated human, orchestrator,
  specialist, and adapter attribution survives bundle export.
- Every command under review has a matching `commandId` in timeline and audit
  data.
- Denied commands show no later `command.dispatched` event for that command.
- Approved commands include `approval.requested`, `approval.decided`, and the
  post-approval dispatch/result path.
- Artifact records include `sha256`, `byteSize`, `mediaType`, `uri`, and
  `redactionStatus`.
- The registered export artifact's `sha256` matches `audit-bundle.zip`.
- Sensitive tokens, cookies, personal paths, and denied window titles have been
  redacted before retaining logs, traces, screenshots, or metadata.

## Current Limitations

- No public `GET /v1/audit` or `POST /v1/audit/export` endpoint exists yet.
- The artifact registry stores metadata only. It does not upload or copy binary
  evidence.
- Stream timeline events are derived from `evidence.captured` audit entries with
  `streamId` metadata until a dedicated stream store lands.
- The first-stage JSON store is suitable for development and CI evidence. It is
  not the final production database, retention engine, or object store.
- Bundle redaction is an operator responsibility in this task. Later export code
  must automate redaction and record redaction evidence in audit metadata.
