# Consumer BFF API Contract

Consumer-facing OSHUN BFF contract for the web shell.

## Base Contract

- Base URL: `http://localhost:4010` in development or
  `NEXT_PUBLIC_OSHUN_BFF_URL`
- Canonical paths are available both at root (`/home`) and the compatibility
  `/v1/*` aliases (`/v1/home`)
- Protected routes require `Authorization: Bearer <token>`
- Domain-scoped routes require at least one `domain:*` or `domain:{domainId}`
  scope
- Aggregation routes return short-lived private cache headers and
  `x-oshun-cache: hit|miss`

## Shared Aggregation Semantics

These routes share the same operational contract:

- `generatedAt`: server timestamp for the envelope
- `authorizedDomains`: domains enabled by the caller's token scopes
- `pagination`: cursor envelope with `limit`, `nextCursor`, `hasMore`, and
  `total`
- `domainStatus`: per-domain `ok | degraded | forbidden`
- `errors`: normalized downstream call failures with `domain`, `stage`, and
  `message`; entries are trimmed, empty messages fall back to a canonical
  adapter-failure message, duplicates collapse, and ordering is deterministic
- `partialFailure`: `true` when any normalized downstream failure leaves the BFF
  returning a partial payload
- `trace`: request-scoped traceability envelope with `correlationId`, `route`,
  `partialFailure`, `failureCount`, `degradedDomains`, and `degradedStages`

Shared response headers:

- `x-correlation-id`: request correlation ID echoed by the BFF
- `x-oshun-partial-response`: `true|false`
- `x-oshun-partial-failure-count`: normalized degraded-domain failure count
- `x-oshun-degraded-domains`: comma-separated degraded domains when present
- `x-oshun-degraded-stages`: comma-separated degraded stages when present

## Home

### `GET /home`

Cross-domain home feed with three strips:

- `highlights`: recommended or headline items
- `continue`: resumable items
- `favorites`: saved favorites summary strip

Query parameters:

- `highlightsLimit`, `highlightsCursor`
- `continueLimit`, `continueCursor`
- `favoritesLimit`, `favoritesCursor`

Key response fields:

- `userId`
- `highlights`, `continue`, `favorites`
- `pagination.highlights`, `pagination.continue`, `pagination.favorites`

Each feed item includes:

- `id`
- `domain`
- `kind`
- `title`
- `meta`

## Continue / Resume

### `GET /continue`

Unified resume feed across authorized domains.

Query parameters:

- `limit`
- `cursor`

Key response fields:

- `userId`
- `items`
- `pagination`

Each item includes:

- `id`
- `domain`
- `kind`
- `title`
- `meta`

## Universal Search

### `GET /search`

Cross-domain search across authorized shell domains.

Query parameters:

- `q` or `query`
- `domain=all|tara|veritas|nyx|arete|nisaba`
- `limit`
- `cursor`

Key response fields:

- `userId`
- `query`
- `domainFilter`
- `results`
- `pagination`

Each result includes:

- `id`
- `domain`
- `kind`
- `title`
- `summary`
- `score`

### `GET /search/suggestions`

Search suggestions and recent-search support for the same domain surface.

Query parameters:

- `q` or `query`
- `domain=all|tara|veritas|nyx|arete|nisaba`
- `limit`
- `cursor`

Key response fields:

- `userId`
- `query`
- `domainFilter`
- `recent`
- `suggestions`
- `pagination`

Each suggestion includes:

- `query`
- `source` as `recent | trending | derived`
- `score`

## Library

### `GET /library`

Unified saved-content and favorites feed.

Query parameters:

- `domain=all|tara|veritas|nyx|arete`
- `limit`
- `cursor`

Key response fields:

- `userId`
- `domainFilter`
- `items`
- `pagination`

Each library item includes:

- `key`
- `itemId`
- `domain`
- `kind`
- `itemType`
- `title`
- `summary`
- `savedAt`
- `domainMeta`

Current sources:

- Tara favorites
- Veritas saved articles
- Nyx saved sky objects

## Activity

### `GET /activity`

Unified activity timeline assembled from continue state first, with
highlight/recommended fallback when a domain has no resumable item.

Query parameters:

- `limit`
- `cursor`

Key response fields:

- `userId`
- `timeline`
- `pagination`

Each timeline entry includes:

- `id`
- `domain`
- `kind`
- `title`
- `detail`
- `occurredAt`

## Notifications

### `GET /notifications`

Unified notifications feed derived from aggregation signals plus user read and
preference state.

Query parameters:

- `inbox=all|unread|priority`
- `domain=all|tara|veritas|nyx|arete|nisaba`
- `limit`
- `cursor`

Key response fields:

- `userId`
- `inboxFilter`
- `domainFilter`
- `counts.total`
- `counts.unread`
- `counts.priority`
- `counts.visible`
- `notifications`
- `pagination`

Each notification includes:

- `id`
- `domain`
- `kind`
- `priority`
- `title`
- `body`
- `timestamp`
- `read`

Behavior notes:

- semantic cross-domain duplicates are deduplicated
- read-state writes and notification preference writes invalidate cached feeds

### `GET /notifications/preferences`

Reads per-domain notification preferences.

Key response fields:

- `userId`
- `revision`
- `authorizedDomains`
- `scopeAuthorized`
- `preferences`

### `PATCH /notifications/preferences/domains/:domainId`

Updates one domain's notification preference state for
`tara|veritas|nyx|arete|nisaba|metis`.

Allowed patch fields:

- `enabled`
- `priorityOnly`
- `kinds.reminder`
- `kinds.update`
- `kinds.event`
- `kinds.insight`

## Profile

### `GET /profile`

Returns the authenticated shell profile envelope.

Key response fields:

- `generatedAt`
- `revision`
- `id`
- `email`
- `displayName`
- `initials`
- `plan`
- `verified`
- `stats`
- `domainConnections`

`stats` currently includes:

- `streakDays`
- `savedItems`
- `activeDomains`

Each `domainConnections` item includes:

- `id`
- `label`
- `accent`
- `status`

### `PATCH /profile`

Updates profile fields.

Allowed patch fields:

- `displayName`
- `email`

Invalid or empty payloads return `400` with `reason=invalid_profile_payload`.

## Preferences

### `GET /preferences`

Returns the authenticated shell preference envelope.

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `preferences.theme`
- `preferences.language`
- `preferences.accessibility.timezone`
- `preferences.accessibility.calendar`
- `preferences.notifications.pushEnabled`
- `preferences.notifications.emailDigestEnabled`
- `preferences.notifications.quietHoursEnabled`

### `PATCH /preferences`

Updates shell preferences.

Allowed patch fields:

- `theme` as `system | light | dark`
- `language` as `en | es | fr | de | ja | ar | zh | pt | ko | hi`
- `accessibility.timezone` as an IANA timezone id
- `accessibility.calendar` as
  `gregory | buddhist | chinese | hebrew | indian | islamic | japanese | persian`
- `notifications.pushEnabled`
- `notifications.emailDigestEnabled`
- `notifications.quietHoursEnabled`

Invalid or empty payloads return `400` with
`reason=invalid_preferences_payload`.

## Recommendations

### `GET /recommendations`

Returns the cross-domain recommendation feed used by consumer shells.

Query parameters:

- `limit`
- `cursor`

Key response fields:

- `generatedAt`
- `userId`
- `items`
- `pagination`
- `domainBreakdown`
- `errors`
- `partialFailure`

Each recommendation includes:

- `id`
- `domain`
- `itemType`
- `title`
- `subtitle`
- `explanation`
- `reason`
- `score`
- `meta`

### `POST /v1/recommendations/feedback`

Records user feedback for a recommendation.

Required body fields:

- `itemId`
- `domain`
- `signal=hide|less|more`

Optional body fields:

- `itemType`
- `reason`

## Favorites

### `GET /favorites`

Returns Tara favorites for the authenticated user.

Query parameters:

- `limit`
- `cursor`

Key response fields:

- `generatedAt`
- `userId`
- `items`
- `pagination`

Each item currently includes:

- `meditationId`
- `title`
- `durationMinutes`
- `category`
- `favoritedAt`

### `POST /favorites/:meditationId`

Adds a Tara favorite and returns a toggle receipt with:

- `result.meditationId`
- `result.favorited`
- `result.favoritedAt`

### `DELETE /favorites/:meditationId`

Removes a Tara favorite and returns the same toggle receipt shape.

## Assistant

### `POST /v1/assistant/sessions`

Creates a shell assistant session.

Optional body fields:

- `inputMode=text|voice`
- `locale`
- `timezone`
- `deviceType=mobile|tablet|web`
- `appVersion`

Response fields:

- `sessionId`
- `createdAt`
- `authorizedDomains`

### `POST /v1/assistant/sessions/:sessionId/message`

Processes one assistant turn.

Required body fields:

- `text`

Optional body fields:

- `inputMode=text|voice`
- `voiceTranscriptConfidence`
- `locale`

Response fields:

- `sessionId`
- `turnCount`
- `response.text`
- `response.ssml`
- `response.cards`
- `response.suggestedActions`
- `response.navigateTo`
- `response.shouldSpeak`
- `response.confidence`

### `GET /v1/assistant/sessions`

Lists session summaries with:

- `sessionId`
- `createdAt`
- `lastActivityAt`
- `turnCount`

### `DELETE /v1/assistant/sessions/:sessionId`

Ends an assistant session and returns `204`.

## Routines

### `GET /v1/routines/templates`

Returns routine templates for `morning|evening|custom`, optionally filtered by
`type`.

### `GET /v1/routines/recommendations`

Returns personalized routine recommendations.

Optional query parameters:

- `availableMinutes`
- `preferQuick`
- `limit`

Response fields:

- `timeOfDay`
- `recommendations`

### `GET /v1/routines`

Lists user routines.

### `POST /v1/routines`

Creates a routine from either:

- `templateId`

Or:

- `name`
- `type`
- `steps`

Optional creation fields include `description`, `frequency`, `customDays`,
`scheduledTime`, and `notificationsEnabled`.

### `PUT /v1/routines/:routineId`

Updates editable routine fields such as `name`, `description`, `scheduledTime`,
`frequency`, `customDays`, `enabled`, and `notificationsEnabled`.

### `DELETE /v1/routines/:routineId`

Deletes a routine and returns `204`.

### Routine Execution Lifecycle

- `POST /v1/routines/:routineId/start`
- `POST /v1/routines/executions/:execId/advance`
- `POST /v1/routines/executions/:execId/pause`
- `POST /v1/routines/executions/:execId/resume`
- `POST /v1/routines/executions/:execId/abandon`
- `GET /v1/routines/executions/active`
- `GET /v1/routines/history`
- `GET /v1/routines/summary`

Execution responses return the `execution` envelope, while history and summary
return `executions` and `summary` respectively.

## Session Audio

### `GET /sessions/:sessionId/audio`

Returns Tara session audio metadata and stream variants.

Optional query parameters:

- `quality=low|standard|high|lossless`

Key response fields:

- `sessionId`
- `title`
- `artist`
- `album`
- `artworkUrl`
- `durationSeconds`
- `tracks.primary`
- `tracks.variants`
- `tracks.preview`
- `markers`
- `resumePositionSeconds`

## Device Tokens

### `GET /v1/device-tokens`

Lists registered device tokens with:

- `platform`
- `tokenType`
- `deviceId`
- `appVersion`
- `registeredAt`
- `lastActiveAt`

### `POST /v1/device-tokens`

Registers a push token.

Required body fields:

- `token`

Optional body fields:

- `platform=ios|android|web`
- `tokenType=expo|fcm|apns|web-push`
- `deviceId`
- `appVersion`

### `DELETE /v1/device-tokens`

Unregisters a push token.

Required body fields:

- `token`

## Nisaba

All Nisaba consumer routes require `domain:*` or `domain:nisaba`.

### `GET /nisaba/passages/daily`

Returns the authenticated user's daily Nisaba passage envelope.

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `passage`
- `compareTargets`
- `notebooks`
- `groundedEvidenceViews`

`passage` includes:

- `passageId`
- `reference`
- `title`
- `excerpt`
- `body`
- `tradition`
- `language`
- `sourceName`
- `compareTargetCount`
- `annotationCount`
- `saved`
- `hasHighlights`
- `progressPercent`
- `lastReadAt`
- `daily`
- `readingStats`
- `relatedConcepts`
- `launch.targetPath`
- `launch.shellPath`

`compareTargets` launch directly into Nisaba compare flows for the current
passage and selected target passage.

### `GET /nisaba/passages/:passageId`

Returns the same passage envelope for an explicit passage id.

### `GET /nisaba/passages/:passageId/annotations`

Lists revisioned annotations for a passage.

Query parameters:

- `visibility=all|private|shared`
- `status=all|active|archived`
- `notebookId`
- `limit`
- `cursor`

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `passageId`
- `filters`
- `annotations`
- `pagination`

Each annotation includes:

- `annotationId`
- `passageId`
- `author.userId`
- `author.displayName`
- `selection.excerpt`
- `selection.startOffset`
- `selection.endOffset`
- `note`
- `color`
- `visibility`
- `status`
- `tags`
- `notebookIds`
- `evidenceViewIds`
- `createdAt`
- `updatedAt`

Unknown passage ids return `404`. Unknown notebook or evidence references in
annotation writes also return `404`.

### `POST /nisaba/passages/:passageId/annotations`

Creates an annotation.

Required body fields:

- `selection.excerpt`
- `selection.startOffset`
- `selection.endOffset`
- `note`
- `color=amber|azure|violet|sage`
- `visibility=private|shared`

Optional body fields:

- `tags`
- `notebookIds`
- `evidenceViewIds`

### `PATCH /nisaba/passages/:passageId/annotations/:annotationId`

Updates any subset of:

- `note`
- `color`
- `visibility`
- `status=active|archived`
- `tags`
- `notebookIds`
- `evidenceViewIds`

### `GET /nisaba/passages/:passageId/compare`

Returns the Nisaba compare workspace envelope.

Query parameters:

- `targetPassageId`

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `compareId`
- `summary`
- `notes`
- `passage`
- `targetPassage`
- `availableTargets`
- `alignments`
- `notebooks`
- `launch`

Each alignment includes:

- `alignmentId`
- `lens`
- `leftExcerpt`
- `rightExcerpt`
- `summary`
- `annotationIds`
- `evidenceViewIds`

### `GET /nisaba/notebooks`

Lists Nisaba notebooks.

Query parameters:

- `status=all|active|archived`
- `limit`
- `cursor`

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `statusFilter`
- `notebooks`
- `pagination`

Each notebook summary includes:

- `notebookId`
- `title`
- `summary`
- `tags`
- `status`
- `linkedPassageId`
- `itemCount`
- `passageCount`
- `annotationCount`
- `evidenceViewCount`
- `compareItemCount`
- `updatedAt`
- `launch`

### `POST /nisaba/notebooks`

Creates a notebook.

Required body fields:

- `title`
- `summary`

Optional body fields:

- `tags`
- `linkedPassageId`

If `linkedPassageId` is supplied, it must resolve to an existing passage.

### `GET /nisaba/notebooks/:notebookId`

Returns the notebook detail envelope. `notebook.items` contains notebook item
launch metadata for `passage`, `annotation`, `grounded-evidence-view`, and
`compare` resources.

### `PATCH /nisaba/notebooks/:notebookId`

Updates any subset of:

- `title`
- `summary`
- `tags`
- `status=active|archived`

### `POST /nisaba/notebooks/:notebookId/items`

Adds an item to a notebook.

Required body fields:

- `kind=passage|annotation|grounded-evidence-view|compare`
- `refId`

### `GET /nisaba/passages/:passageId/grounded-evidence`

Returns the grounded evidence view envelope for Nisaba reading and compare
flows.

Query parameters:

- `view=reader|compare|source_lineage`
- `targetPassageId`

Key response fields:

- `generatedAt`
- `userId`
- `revision`
- `viewId`
- `viewKind`
- `title`
- `query`
- `groundingStatus`
- `confidence`
- `answer`
- `warnings`
- `subject`
- `citations`
- `sources`
- `claimChecks`
- `notebooks`
- `launch`
- `evidencePack`

`evidencePack` includes:

- `evidencePackId`
- `title`
- `summary`
- `groundingStatus`
- `citations`
- `evidence`
- `sources`
- `claimChecks`
- `notebooks`
- `sourceGraph`
- `tags`
- `generatedAt`
- `processingTimeMs`

## Errors

Common auth and validation failures:

- `401` with `reason=missing_auth_context` when the token is absent or invalid
- `403` with `reason=domain_scope_missing` when the caller lacks required domain
  scope
- `400` with route-specific reasons for invalid cursors, limits, filters, or
  patch payloads

## Source of Truth

- OpenAPI: `apps/oshun/bff/openapi/oshun-bff.openapi.yaml`
- Contract tests:
  `apps/oshun/bff/src/__tests__/contract/shell-bff-contract.test.ts`
