# Oshun Domain — Technical Specifications

> Technical specification for the Oshun platform shell: the domain registry, the
> typed domain-adapter and embodiment-adapter contracts, the shell assistant,
> navigation routes, the typed analytics event surface, design tokens, the
> offline sync queue, achievements, and routines.
>
> This document describes what exists in `libs/oshun/*` and `apps/oshun/*`.
> Every type, enum, route, and event below is traceable to source.

---

This document is the authoritative reference for the exact types, enums,
interfaces, and configuration constants that make up the Oshun shell. It is
organized to mirror the library structure in `libs/oshun/`: start with the
domain registry and domain adapters, then the embodiment adapters, then the
shell-level services (assistant, navigation, analytics, design tokens, offline,
achievements, routines), and finally the backend-for-frontend and supporting
libraries.

Use the [Features doc](./features.md) for conceptual context and
[Architecture](./architecture.md) for structural diagrams. This document goes
directly to the types.

---

## Technology Stack

The following table summarizes the key technology choices for the Oshun shell
libraries. Every `libs/oshun/*` library is at version `0.1.0`.

| Layer               | Technology                                                   |
| ------------------- | ------------------------------------------------------------ |
| Language            | TypeScript                                                   |
| Module format       | ESM (`.js`-suffixed relative imports)                        |
| UI Framework        | React (`apps/oshun/web`), React Native (`apps/oshun/mobile`) |
| Build               | Nx with `tsup` / esbuild per library                         |
| Testing             | Vitest (`*.test.ts`, `*.spec.ts`)                            |
| Versioned contracts | `@oshun/types` contract-version helpers                      |
| Color science       | `@oshun/color-science` (ACES-based)                          |

---

## Domain Registry (`@oshun/domain-registry`)

The registry is the static catalog of the Oshun product domains the shell can
launch. It exports the domain-id union, the per-domain metadata table, and
runtime guard/validation helpers. Source: `libs/oshun/domain-registry/src/`.

### Domain Identifiers

The six known domain ids and their union type. `OshunDomainId` is derived from
the `OshunDomain` type in `@oshun/navigation` by excluding the `'oshun'` shell
itself.

```typescript
type OshunDomainId = 'tara' | 'veritas' | 'nyx' | 'arete' | 'nisaba' | 'metis';

const OSHUN_DOMAIN_IDS = ['tara', 'veritas', 'nyx', 'arete', 'nisaba', 'metis'];
```

`OshunDomainId` is `Exclude<OshunDomain, 'oshun'>`, where `OshunDomain` is
defined in `@oshun/navigation`.

### `DomainAvailability`

Controls which domains `getAvailableDomains` surfaces to the shell. Domains with
`planned` availability are registered but excluded from navigation and the
launcher until they go to beta or active.

This is separate from **release scope**, which is the other filter those
selectors apply: a room can be `active` and still be held out of the shipping
release (Veritas is `active` and deferred to V1.2). Availability is "is this
room finished"; release scope is "does this release ship it".

```typescript
type DomainAvailability = 'active' | 'beta' | 'planned';
```

Current registry values: `tara` = active, `veritas` = active, `arete` = active,
`nyx` = beta, `nisaba` = beta, `metis` = planned.

### `DomainMetadata`

The full metadata record for a registered domain. The shell reads these fields
to build domain cards, navigation items, offline fallbacks, and first-run
onboarding copy.

Each domain in `DOMAIN_REGISTRY` is a `DomainMetadata` record:

| Field                   | Type                        | Meaning                                                         |
| ----------------------- | --------------------------- | --------------------------------------------------------------- |
| `id`                    | `OshunDomainId`             | Canonical domain id                                             |
| `displayName`           | `string`                    | Display title                                                   |
| `route`                 | `string`                    | Shell route, e.g. `/domains/tara`                               |
| `auth`                  | `DomainAuthPolicy`          | Session, scopes, step-up actions                                |
| `analytics-id`          | `string`                    | Analytics namespace, e.g. `oshun.domain.tara`                   |
| `notification-channel`  | `string`                    | Notification channel id                                         |
| `assistant-context-key` | `string`                    | Key the assistant uses for domain context                       |
| `bff-base-path`         | `string`                    | BFF API base path                                               |
| `deep-link-prefix`      | `string`                    | e.g. `oshun://tara`                                             |
| `admin-taxonomy`        | `DomainAdminTaxonomy`       | Owner subsystem, review queues, audit category, content classes |
| `name`                  | `string`                    | Short name                                                      |
| `tagline`               | `string`                    | One-line tagline                                                |
| `icon`                  | `string`                    | Icon reference token                                            |
| `accentColor`           | `string`                    | Hex accent color                                                |
| `launch`                | `DomainLaunchTargets`       | `defaultPath`, optional `quickActionPath`                       |
| `launchContract`        | `DomainLaunchContract`      | Icon, label, CTA, permissions                                   |
| `offlineFallback`       | `DomainOfflineFallbackCard` | Offline-mode card copy                                          |
| `shellNarrative`        | `DomainShellNarrative`      | Tagline, summary, first-run summary                             |
| `capabilities`          | `readonly string[]`         | Capability tokens                                               |
| `availability`          | `DomainAvailability`        | `active` / `beta` / `planned`                                   |

### `DomainAuthPolicy`

Declares the authentication requirements for a domain. The shell reads this
before launching a domain to determine whether a sign-in step-up is needed.

```typescript
interface DomainAuthPolicy {
  required: boolean;
  sessionKind: 'customer' | 'learner' | 'reader' | 'operator';
  scopes: readonly string[];
  stepUpActions: readonly string[];
}
```

`sessionKind` is `reader` for Nisaba, `learner` for Metis, `customer` for Tara,
Veritas, Nyx, and Arete.

### `DomainLaunchContract` and `DomainLaunchPermission`

These types model what the shell shows the user when they are about to launch a
domain for the first time — the icon, label, call-to-action copy, and any
OS-level permissions the domain will request.

```typescript
interface DomainLaunchContract {
  icon: string;
  label: string;
  cta: string;
  permissions: DomainLaunchPermission[];
}

interface DomainLaunchPermission {
  id: DomainLaunchPermissionId;
  label: string;
  required: boolean;
  rationale: string;
}

type DomainLaunchPermissionId =
  | 'notifications'
  | 'audio'
  | 'location'
  | 'calendar'
  | 'camera'
  | 'storage';
```

### `DomainAdminTaxonomy`

Administrative metadata the platform operations team uses for routing review
queues and audit trails. Not shown to end users.

```typescript
interface DomainAdminTaxonomy {
  ownerSubsystem: string;
  primaryQueues: readonly string[];
  auditCategory: string;
  contentClasses: readonly string[];
}
```

### `DomainOfflineFallbackCard` and `DomainShellNarrative`

These types provide the copy the shell shows when a domain is unavailable
(offline) or when a user encounters it for the first time.

```typescript
interface DomainOfflineFallbackCard {
  title: string;
  body: string;
  cta: string;
  secondaryCta: string;
  cacheHint: string;
}

interface DomainShellNarrative {
  tagline: string;
  summary: string;
  firstRunSummary: string;
}
```

### `OshunShellDomainConfiguration`

The resolved shell configuration, derived from the registry at startup. The
`primaryDomain` is always `'tara'`.

```typescript
interface OshunShellDomainConfiguration {
  primaryDomain: OshunDomainId;
  enabledDomains: OshunDomainId[];
  companionDomains: OshunDomainId[];
  betaDomains: OshunDomainId[];
  domainCount: number;
}
```

`OSHUN_SHELL_PRIMARY_DOMAIN` is `'tara'`.

### Registry Functions

The public API for reading from the registry:

`getDomainMetadata`, `listDomainMetadata` (all six — the registry-contents
accessor), `getAvailableDomains` (excludes `planned` **and** release-deferred
rooms), `getShellNavigationDomains` (release-scoped),
`listV1ScopedDomainMetadata`, `listDeferredDomainMetadata`,
`getDefaultShellDomainConfiguration`, `buildShellDomainConfiguration`,
`getDomainLaunchContract`, `getDomainOfflineFallback`,
`getDomainShellNarrative`, `buildDomainLaunchLinks`, `isKnownDomain`.

### Registry Guards (`guards.ts`)

Type guards and validation helpers that prevent malformed domain references from
propagating through the shell. Invalid references throw
`DomainRegistryBoundaryError`, which carries a
`DomainReferenceValidationIssue[]`
(`{ field, value, reason: 'missing' | 'invalid-domain' | 'invalid-shape' }`).

Exported guards: `isOshunDomainId`, `assertOshunDomainId`, `parseOshunDomainId`,
`validateDomainReference`, `isDomainMetadata`, `assertDomainMetadata`,
`validateCrossDomainReference`.

---

## Domain-Adapter Contract Pattern

Each product-domain adapter (`@oshun/domain-*`) follows the same two-layer
structure. The audited adapters are Tara, Veritas, Nyx, Arete, Nisaba, and
Metis.

1. **API adapter** — a typed HTTP client (`client.ts`) implementing a raw
   `*ApiAdapter` interface that mirrors the domain REST API. Tara, Veritas, Nyx,
   and Arete clients accept a runtime-agnostic `fetcher` and `baseUrl`.
2. **Canonical adapter** — `canonical-adapter.ts` wraps the API adapter and adds
   shell-facing concerns: a versioned contract descriptor, registry metadata, an
   availability check, home-card composition, search, launch resolution, and
   cross-domain bridge helpers. The canonical adapter type extends the raw
   `*ApiAdapter`.

Adapters expose card models (`card-model.ts`), launch actions
(`launch-actions.ts`), deep links (`deep-links.ts`), and cross-domain
relationship helpers (`*-relationship.ts`). Each adapter declares a versioned
contract via `buildOshunContractVersionDescriptor` from `@oshun/types`, e.g.
`NYX_DOMAIN_ADAPTER_CONTRACT` (`oshun.domain.nyx.adapter`, version `1.0.0`).

Every canonical adapter exposes the same shell-facing interface:
`getContractDescriptor()`, `getMetadata()` (returns `DomainMetadata`),
`getAvailability()`, `getHomeCards(ctx)`, `getContinueItems(ctx)`,
`search(input)`, and `launch(input)`, plus domain-specific operations.

### Nyx Adapter (`@oshun/domain-nyx`)

Astronomical events and celestial-object lookup.

`NyxApiAdapter` operations: `getNightlyHighlights`, `getEventDetail`,
`getContinueObservation`, `searchObjects`, `getObjectDetail`,
`getObservationLogs`, `logObservation`, `getSavedObjects`, `saveObject`,
`unsaveObject`, `getEventReminders`, `setEventReminder`, `toggleEventReminder`,
`getHealth`.

The core types model an astronomical event with its full observability context:

- `NyxAstronomicalEvent` — `eventId`, `type` (`NyxEventType`), `title`,
  `description`, `startTime`, `peakTime`, `endTime`, `durationMinutes`,
  `visibility` (`NyxEventVisibility`), `importance` (`NyxEventImportance`),
  `objects` (`NyxEventObject[]`), `magnitude`, `visibilityRegions`,
  `observingConditions` (`NyxObservingConditions`).
- `NyxCelestialObject` — `objectId`, `name`, `type` (`NyxCelestialObjectType`),
  `constellation`, `magnitude`, `description`, `observingTips`, `aliases`.
- `NyxNightlyHighlight`, `NyxObservationLog`, `NyxSavedObject`,
  `NyxContinueObservation`, `NyxSkyMapSession`, `NyxEventReminder`.

Enums: `NyxEventType` (24 values incl. `solar_eclipse`, `lunar_eclipse`,
`planetary_conjunction`, `meteor_shower`, `full_moon`, `iss_pass`, `solstice`,
`equinox`, `other`), `NyxEventVisibility` (`global` | `regional` | `local` |
`not_visible`), `NyxEventImportance` (`major` | `moderate` | `minor`),
`NyxCelestialObjectType` (11 values), `NyxSkyMapMode` (`explore` | `guided` |
`event-tracking` | `ar`).

The canonical adapter adds `NyxLaunchMode` (`embedded_pwa` | `native`),
`NyxRitualMoment` (6 values), bridge moments from Tara/Arete/Veritas/Nisaba, and
`NyxLaunchScreen` (17 screen ids). Errors raise `NyxDomainAdapterError` with a
`code` of `http` | `network` | `parse`.

### Tara Adapter (`@oshun/domain-tara`)

Meditation, breathwork, sleep, and ritual practice.

`TaraApiAdapter` operations: `getRecommendedSessions`, `getContinueSession`,
`getCourseProgress`, `getFavorites`, `addFavorite`, `removeFavorite`,
`getSessionAudio`, `getHealth`.

The core types are structured around a discriminated union over practice
subtypes, allowing the shell to handle meditation, breathing, sleep, and
transition content with compile-time exhaustiveness checking:

Core types: `TaraMeditationContent` (a discriminated union over
`meditationSubtype`: guided / breathing / sleep / transition),
`TaraRitualDefinition`, `TaraMeditationSessionRecord`,
`TaraSessionRecommendation`, `TaraContinueSession`, `TaraCourseProgress`,
`TaraFavoriteItem`, `TaraSessionAudioMeta`, `TaraContentTaxonomy`,
`TaraSessionCompletionState`, `TaraSessionContinuationState`.

Taxonomy enums: `TaraMoodTaxonomy` (7 values), `TaraThemeTaxonomy` (10 values),
`TaraDurationBand` (`micro` | `short` | `standard` | `long` | `retreat`),
`TaraPracticeTradition` (`secular` | `buddhist` | `yogic` | `vedic` | `tibetan`
| `advaita`), `TaraIntendedOutcome` (10 values), `TaraBreathingPattern` (5
values), `TaraSleepMode` (5 values), `TaraTransitionTrigger` (6 values),
`TaraRitualMoment` (6 values). The library also exports label/order maps for
each taxonomy and constants `TARA_SESSION_CHECKPOINT_THRESHOLD_PERCENT` (5) and
`TARA_SESSION_RECENT_COMPLETION_WINDOW_HOURS` (12). Errors raise
`TaraDomainAdapterError`.

### Veritas Adapter (`@oshun/domain-veritas`)

Truth-first news, claims, and source credibility.

`VeritasApiAdapter` operations: `getTrendingArticles`, `getArticleBrief`,
`getContinueReading`, `getTopClaims`, `getClaimDetail`, `getTrendingTopics`,
`getCategories`, `getSavedArticles`, `saveArticle`, `unsaveArticle`,
`getFollowedTopics`, `followTopic`, `unfollowTopic`, `getHealth`.

Core types: `VeritasClaim`, `VeritasClaimEvidence`, `VeritasClaimDetail`,
`VeritasArticleBrief`, `VeritasArticleFeedItem`, `VeritasContinueReading`,
`VeritasTopic`, `VeritasCategory`, `VeritasSavedArticle`,
`VeritasFollowedTopic`, `VeritasSourceSummary`.

Enums: `VeritasVerdict` (`verified` | `likely_true` | `disputed` | `misleading`
| `mostly_false` | `false` | `unverifiable` | `unverified`),
`VeritasEvidenceStance` (`supports` | `refutes` | `neutral` | `inconclusive`),
`VeritasCredibilityTier` (`high` | `medium` | `low` | `unknown`),
`VeritasClaimType` (7 values), `VeritasArticleContentType` (7 values),
`VeritasFeedRecommendationReason` (6 values). Errors raise
`VeritasDomainAdapterError`.

### Arete Adapter (`@oshun/domain-arete`)

Goals, habits, journaling, balance check-ins, and AI coaching.

`AreteApiAdapter` operations: `getGoals`, `getGoalDetail`, `createGoal`,
`updateGoalProgress`, `getHabits`, `getHabitDetail`, `createHabit`,
`logHabitCompletion`, `getJournalEntries`, `getJournalPrompts`,
`createJournalEntry`, `getContinueCheckIn`, `getCoachInsights`,
`dismissInsight`, `getLatestBalanceCheckIn`, `submitBalanceCheckIn`,
`getStreakStats`, `saveItem`, `unsaveItem`, `getReminders`, `toggleReminder`,
`getHealth`.

Core types: `AreteGoal` + `AreteMilestone`, `AreteHabit` +
`AreteHabitCompletion`, `AreteJournalEntry` + `AreteJournalPrompt`,
`AreteCoachInsight`, `AreteBalanceCheckIn` + `AreteBalanceScore`,
`AreteContinueCheckIn`, `AreteStreakStats`, `AreteAccountabilityReminder`.

Enums: `AreteGoalCategory` (9 values), `AreteGoalHorizon` (`short` | `mid` |
`long`), `AreteGoalStatus` (`active` | `paused` | `completed` | `archived`),
`AreteHabitFrequency` (4 values), `AreteHabitCategory` (8 values),
`AreteJournalPromptCategory` (7 values), `AreteSentiment` (`positive` |
`neutral` | `negative` | `mixed`), `AreteInsightType` (5 values),
`AreteBalanceDimension` (8 values). Errors raise `AreteDomainAdapterError`,
which carries `statusCode` and `errorCode`.

### Nisaba Adapter (`@oshun/domain-nisaba`)

Primary-text reading, translation comparison, and scholarly research. This is a
read-oriented adapter; unlike the other domain adapters, it does not expose
mutation operations to the shell.

The canonical adapter (`NisabaDomainAdapter`) exposes `getContractDescriptor`,
`getMetadata`, `getAvailability`, `getHomeCards`, `getContinueItems`, `search`,
`launch`, `toggleSavedPassage`, `setStudyReminderState`, and
`getBridgeCompanions`. The underlying `NisabaApiAdapter` adds passage, search,
saved-passage, study-reminder, concept-thread, and workspace operations.

Core types: `NisabaPassageSummary`, `NisabaSavedPassage`,
`NisabaContinueReading`, `NisabaStudyReminder`, `NisabaConceptThread`,
`NisabaWorkspaceEntry`, `NisabaSearchHit`, `NisabaContinueItem`,
`NisabaSearchResult`, `NisabaBridgeCompanion`, `NisabaDomainAvailability`.

Enums: `NisabaExperienceMode` (`web_first` | `mobile_companion`),
`NisabaStudyMoment` (6 values incl. `contemplative_reading`, `source_lineage`,
`claim_grounding`), `NisabaBridgeSourceDomain` (`tara` | `arete` | `veritas` |
`nyx`), `NisabaBridgeEntityKind` (6 values), `NisabaSearchMode`,
`NisabaSearchEntityKind`, `NisabaWorkspaceKind`, `NisabaResearchType`,
`NisabaProjectStatus`, `NisabaLaunchScreen` (16 screen ids).

Role-scoped adapter views: `createNisabaReadAdapterRegistry` returns a
`NisabaReadAdapterRegistry` with `shell`, `admin`, and `assistant` views.
`NISABA_ADAPTER_READ_CAPABILITIES` lists 15 capabilities;
`NISABA_ADAPTER_ROLE_CAPABILITIES` maps each role to its allowed subset.

### Metis Adapter (`@oshun/domain-metis`)

Courses, tutoring, and adaptive learning. Metis is `planned` in the registry.
The `@oshun/domain-metis` library is a thin re-export of `@metis/api-client`; it
exposes `createMetisDomainAdapter` and `createMetisDomainReadAdapterRegistry`.
The domain types and adapter contract live in the Metis domain library, not in
`libs/oshun`.

---

## Embodiment-Adapter Contracts

Embodiment adapters wrap the AI systems that power the shell experience: Psyche
(voice/avatar sessions), Sophia (evidence retrieval), Iris (memory), Isis
(generation control), Lilith (persona policy), and Aja (embodied instruction).
Each is a `libs/oshun/*` library that types a raw `*ApiAdapter` plus a canonical
adapter. They follow the same two-layer pattern as the domain adapters, but the
domain they abstract is an AI capability rather than a product-domain service.

### Psyche Embodiment Adapter (`@oshun/embodiment-psyche`)

Multi-participant voice, avatar, video, screen-share, and translation sessions.
Disclosure of synthetic voice/avatar identity is a first-class part of the
model.

`PsycheEmbodimentApiAdapter` operations include `getPersona`,
`getDisclosureConfig`, `getEmbodimentPack`, `getAvatarModel`, `getVoiceProfile`,
`listSessions`, `createSession`, `getSession`, `startSession`, `pauseSession`,
`resumeSession`, `deleteSession`, `listParticipants`, `getTurnConfig`,
`getSpeakingQueue`, `getPipelineConfig`, `getPipelineState`,
`getConferenceBridge`, `getTranslationState`, `getHealth`.

Shell-facing model: `PsycheEmbodimentProfile`, `PsycheSessionCapabilities`,
`PsycheLiveSessionState`, `PsycheSessionRequest`, `PsycheSessionPlan`,
`PsycheParticipantSummary`, `PsycheTurnStateSummary`,
`PsycheEmbodimentDisclosurePolicy` / `…DisclosureState`,
`PsycheVoiceProfileSummary`, `PsycheAvatarPackSummary`.

Enums (selected): `PsycheSessionKind` (`video` | `voice` | `screen_share` |
`chat` | `hybrid`), `PsycheEmbodimentSessionStatus` (8 values), `PsycheModality`
(`text` | `voice` | `avatar` | `video` | `screen_share` | `translation`),
`PsycheEmotionState` (8 values), `PsycheDisclosureMode` (`always_on` |
`contextual` | `on_request`), `PsychePipelineService` (`asr` | `tts` | `llm` |
`nlu` | `vision` | `avatar` | `emotion` | `knowledge` | `tools`),
`PsycheTurnControlMode`, `PsycheConferencingPlatform`, `PsycheAvatarModelType`,
`PsycheVoiceProfileType`.

### Sophia Evidence Adapter (`@oshun/evidence-sophia`)

Grounded answers, evidence packs, citations, source graphs, and notebooks. Built
on `@sophia/client`, `@sophia/schemas`, and `@sophia/verification`.

`SophiaEvidenceApiAdapter` operations: `searchCorpus`, `generateGroundedAnswer`,
`getSource`, `getClaimVerification`, `getFactCheckReport`, `getSourceGraph`,
`listNotebooks`, `saveNotebookItems`, `createTraceExport`, `getHealth`.

Core types: `SophiaEvidencePack`, `SophiaGroundedAnswer`, `SophiaCitationTrail`,
`SophiaEvidenceItem`, `SophiaClaimCheck`, `SophiaSourceSummary`,
`SophiaSourceGraphPreview`, `SophiaNotebookRecord`, `SophiaTraceExportRecord`.

Enums: `SophiaEvidenceConsumer` (9 values), `SophiaGroundingStatus` (`grounded`
| `partially_grounded` | `unsupported` | `conflicting`),
`SophiaAnswerGroundingState` (5 values), `SophiaCitationPolicy` (`required` |
`preferred` | `optional`), `SophiaEvidenceStance` (5 values),
`SophiaTraceExportKind` (4 values), `SophiaTraceExportFormat` (`json` | `csv` |
`markdown` | `pdf`).

### Iris Memory Adapter (`@oshun/memory-iris`)

Memory continuity, retrieval, write planning, consent, opt-outs, deletion, and
export. Built against an `IrisMemoryApiAdapter` that wraps the Iris core and
archival memory stores.

Core types: `IrisMemoryRecord`, `IrisMemorySearchInput` / `…SearchResult`,
`IrisMemoryWriteInput` / `IrisMemoryWritePlan`, `IrisContinuityState`,
`IrisMemoryReviewInput` / `…ReviewResult`, `IrisMemoryScopePolicy`,
`IrisMemoryConsentSummary`, `IrisMemoryOptOutSummary`, `IrisAssistantProfile`,
`IrisMemoryConflictSummary`, `IrisMemoryDeleteRequest` / `…DeleteSummary`,
`IrisMemoryExportRequest` / `…ExportRecord`.

Memory-scope and tier enums describe the complete taxonomy of memory storage
levels, from fine-grained ephemeral session context all the way to tenant-wide
and admin-review scopes:

```typescript
type IrisMemoryScope =
  | 'assistant_profile'
  | 'session'
  | 'scene'
  | 'pose'
  | 'conversation'
  | 'domain'
  | 'cross_domain'
  | 'notebook'
  | 'operator_copilot'
  | 'tenant'
  | 'admin_review';

type IrisCanonicalMemoryTier =
  | 'core'
  | 'working'
  | 'archival'
  | 'episodic'
  | 'semantic';
type IrisMemoryMode = 'durable' | 'ephemeral' | 'suppressed';
```

Other enums: `IrisMemoryConsumer` (10 values), `IrisMemoryDomain` (7 values),
`IrisSearchStrategy` (`semantic` | `keyword` | `temporal` | `hybrid` |
`adaptive`), `IrisMemoryPrivacyStatus` (4 values), `IrisConsentType` (13
values), `IrisLegalBasis` (6 values), `IrisOptOutCategory` (16 values),
`IrisMemoryConflictRule` (6 values), `IrisMemoryExportFormat` (`json` | `csv` |
`markdown` | `portable`).

### Isis Generation Control Adapter (`@oshun/generation-control-isis`)

Governs generative jobs, workflow/model registries, environment promotion, and
provider routing for the Isis generative factory.

Enums (selected): `IsisJobStatus` (`pending` | `queued` | `running` |
`completed` | `failed` | `cancelled`), `IsisJobPriority` (`low` | `normal` |
`high` | `urgent`), `IsisGenerationType` (15 values incl. `text-to-image`,
`image-to-video`, `text-to-3d`, `voice-synthesis`, `blender-render`,
`gaussian-splatting`), `IsisWorkflowEngine` (`comfyui` | `blender` | `unreal` |
`godot` | `custom`), `IsisWorkflowCategory` (12 values),
`IsisControlPlaneEnvironment` (`development` | `staging` | `production` |
`test`), `IsisWorkflowSeedPolicy`, `IsisWorkflowIdentityAdapter`,
`IsisModelType`. The library also ships provenance, staging-recipe,
release-gate, environment-promotion, CivitAI intake/review, and ComfyUI
governance models.

### Lilith Persona Policy Adapter (`@oshun/persona-policy-lilith`)

Persona policy packs, tone guidance, content-safety evaluation, topic-scope
checks, crisis handling, and voice-clone safety for the Lilith persona system.

Core types: `LilithPersonaPolicyPack`, `LilithPolicySelection`,
`LilithPolicyEvaluationInput` / `…EvaluationResult`, `LilithToneGuidance`,
`LilithSafetyAssessment`, `LilithTopicScopeResult`, `LilithVoiceSafetyPolicy`,
`LilithPromptOverlay`.

Enums (selected): `LilithPersonaCategory` (11 values), `LilithPersonaFamily` (7
values), `LilithTeachingStyle` (12 values), `LilithPracticeMode` (5 values),
`LilithGroundingRequirement` (`not_needed` | `recommended` | `required`),
`LilithSafetyDisposition` (`allow` | `allow_with_disclaimer` | `redirect` |
`escalate` | `block`), `LilithRiskLevel` (5 values), `LilithContentCategory` (5
values), `LilithVoiceSafetyClass` (4 values), `LilithMemoryEnvelope` (`none` |
`session` | `scoped` | `durable`), `LilithModalityPermission` (7 values).

### Aja Embodied-Instruction Adapter (`@oshun/embodiment-aja`)

Embodied demonstration, coaching overlays, and session handoffs. The canonical
adapter validates every request and response against the Zod schemas exported by
`@oshun/contracts/aja`: `EmbodiedInstructionCapabilitiesSchema`,
`EmbodiedInstructionDemonstrationRequest/ResponseSchema`,
`EmbodiedInstructionCoachingOverlayRequest/ResponseSchema`, and
`EmbodiedInstructionSessionHandoffRequest/ResponseSchema`. It exposes
`getContractDescriptor`, `getMetadata`, `getAvailability`, `getCapabilities`,
`createDemonstrationPlan`, `createCoachingOverlay`, and `createSessionHandoff`.

---

## Shell Assistant (`@oshun/shell-assistant`)

A voice-first, cross-domain assistant. It classifies intent, routes to a domain
adapter, and renders responses. Source: `libs/oshun/shell-assistant/src/`.

### Domain Identifier

```typescript
type OshunDomainId = 'tara' | 'veritas' | 'nyx' | 'arete' | 'nisaba' | 'metis';
const ALL_DOMAIN_IDS: readonly OshunDomainId[] = [
  /* the six above */
];
```

### Sessions

`AssistantSession` carries `id` (branded `AssistantSessionId`), `userId`,
timestamps, `turnCount`, `domainContext`, `continuity`, `conversationHistory`
(`AssistantTurn[]`), and `metadata`. `AssistantSessionMetadata` records
`inputMode` (`voice` | `text`), `locale`, `timezone`, `deviceType`,
`appVersion`, and an optional `platformShell` (`customer` | `admin`, defaulting
to `customer`).

`AssistantSessionContinuity` bundles a `disclosure` context, a `memory` context
(`scope` of `off` | `session` | `profile`), a `grounding` context (`mode` of
`none` | `recommended` | `required`), and a `pendingHandoff`
(`AssistantDomainHandoff` or `null`).

### Intent Classification

These are the exact types used when classifying a user utterance into a routable
intent. The `confidence` field drives the disambiguation behavior: when it falls
below `intentConfidenceThreshold` (default 0.4), the assistant asks a clarifying
question instead of routing.

```typescript
type AssistantIntentCategory =
  | 'domain_action'
  | 'cross_domain_query'
  | 'navigation'
  | 'status_inquiry'
  | 'preference_change'
  | 'greeting'
  | 'farewell'
  | 'help'
  | 'clarification'
  | 'general_conversation'
  | 'unknown';

interface ResolvedIntent {
  category: AssistantIntentCategory;
  name: string;
  domain: OshunDomainId | 'cross_domain' | null;
  confidence: number;
  slots: Record<string, SlotValue>;
  requiresConfirmation: boolean;
}
```

`SlotValue` has a `type` of `string` | `number` | `boolean` | `date` | `time` |
`duration` | `entity`. Per-domain intent definitions are exported as
`TARA_INTENTS`, `VERITAS_INTENTS`, `NYX_INTENTS`, `ARETE_INTENTS`,
`NISABA_INTENTS`, `METIS_INTENTS`, plus `CROSS_DOMAIN_INTENTS` and
`CONVERSATIONAL_INTENTS`; `inferDomainFromText` and `getIntentsForDomain` are
the lookup helpers.

### Domain Actions

`DomainActionType` is a literal union of roughly 70 namespaced actions across
Tara, Veritas, Nyx, Arete, Nisaba, Metis, achievements, wearable, desktop, and
cross-domain (e.g. `tara.start_meditation`, `nyx.tonight_sky`,
`achievement.summary`, `cross_domain.search`). `DomainAction` carries `type`,
`domain`, `params`, and `description`; `DomainActionResult` adds `success`,
`data`, optional `error`, and `executionTimeMs`.

### Responses

The response type is what the shell UI renders after intent classification and
action routing complete. The `navigateTo` field, when present, causes the shell
to push a new route after rendering the response.

```typescript
interface AssistantResponse {
  text: string;
  ssml?: string;
  cards: AssistantResponseCard[];
  suggestedActions: SuggestedAction[];
  navigateTo?: NavigationTarget;
  shouldSpeak: boolean;
  confidence: number;
}
```

`AssistantResponseCard.type` is a 17-value union (`meditation`, `article`,
`event`, `goal`, `course`, `assessment`, `tutoring`, etc.). `NavigationTarget`
is `{ domain: OshunDomainId; path: string; params?: Record<string, string> }`.

### Engine Configuration

The default configuration values below represent the production-tuned thresholds
for session limits, intent routing, and domain-call timeout behavior.

```typescript
interface AssistantEngineConfig {
  maxTurnsPerSession: number;
  maxSessionDurationMs: number;
  intentConfidenceThreshold: number;
  confirmationThreshold: number;
  defaultLocale: string;
  enableVoiceResponse: boolean;
  enableCrossDomainSearch: boolean;
  maxConcurrentDomainCalls: number;
  domainCallTimeoutMs: number;
  systemPromptVersion: string;
}
```

`DEFAULT_ASSISTANT_CONFIG`: `maxTurnsPerSession` 50, `maxSessionDurationMs` 30
min, `intentConfidenceThreshold` 0.4, `confirmationThreshold` 0.7,
`maxConcurrentDomainCalls` 4, `domainCallTimeoutMs` 5000.

The engine consumes an `AssistantDomainAdapters` record with one
`Assistant*Adapter` per domain. `AssistantEngine`, `InMemorySessionStore`,
`IntentResolver`, `ActionRouter`, and `ResponseFormatter` are the exported
runtime classes; `createAssistantEngine` is the factory.

### Telemetry Events

These events are emitted by the engine at each stage of the request lifecycle
and are consumed by `@oshun/analytics` for observability.

```typescript
type AssistantEventType =
  | 'session.created'
  | 'session.ended'
  | 'turn.started'
  | 'turn.completed'
  | 'turn.failed'
  | 'intent.classified'
  | 'action.executed'
  | 'action.failed'
  | 'voice.transcribed'
  | 'voice.synthesized'
  | 'navigation.triggered'
  | 'error.occurred';
```

### Additional Assistant Subsystems

The library also ships: a platform-shell split (`customer` / `admin`),
invocation points and keyboard shortcuts, context handoff with sanitization,
grounding / memory / persona indicators, transcript controls, cross-domain
carryover, interaction modes, persona handoffs, avatar mode, safe fallbacks, an
Iris memory bridge, and a Psyche session bridge
(`PSYCHE_SESSION_PROTOCOL_VERSION`).

---

## Navigation (`@oshun/navigation`)

Unified deep-link and route contracts for the Oshun surfaces. Source:
`libs/oshun/navigation/src/routes.ts`.

### Constants

These constants establish the URL scheme and canonical web origin for all
deep-link and web-link construction and parsing.

```typescript
const OSHUN_SCHEME = 'oshun';
const OSHUN_WEB_ORIGIN = 'https://oshun.app';

const OSHUN_SHELL_SURFACES = [
  'home',
  'explore',
  'activity',
  'library',
  'assistant',
  'profile',
  'search',
];

type OshunShellSurface = (typeof OSHUN_SHELL_SURFACES)[number];
type OshunDomain = 'tara' | 'veritas' | 'nyx' | 'arete' | 'nisaba' | 'metis';
type OshunTabRoute = Exclude<OshunShellSurface, 'assistant' | 'search'>;
```

### Route Map

`OSHUN_ROUTE_MAP` is an `OshunUnifiedRouteMap` with a `shell` record (six
surfaces: home, explore, activity, library, assistant, profile — each with
`mobilePath`, `webPath`, and `deepLink`) and a `domain` record (six domains —
each with `mobilePath`, `webPath` `/domains/<domain>`, and `deepLinkBase`
`oshun://<domain>`). `OSHUN_TAB_PATHS` and `OSHUN_DOMAIN_BASE_PATHS` are derived
path maps.

### Link Builders and Parsers

Builders eliminate string URL construction in surface code: `buildTabPath`,
`buildDomainPath`, `buildCanonicalDomainDeepLink`,
`buildCanonicalShellDeepLink`, `buildCanonicalDomainWebLink` (`/d/<domain>`
form), `buildCanonicalShellWebLink` (`/app/<surface>` form), `buildDeepLink`,
`buildWebLink`.

Parsers return a typed descriptor or `null` (never throw) for unrecognized
inputs: `parseCanonicalDeepLink`, `parseCanonicalWebLink`, `parseDeepLink`. The
web parser accepts `/app/<surface>`, bare `/<surface>`, `/d/<domain>`, and
`/domains/<domain>` paths.

The library also exports information-architecture maps (`customer-ia`,
`admin-ia`, `admin-ia-bindings`, `tenant-ia`, `platform-shells`), the
current-domain store, daypart journeys, the research-practice, story-source,
sky-text, and assistant-continuity journeys, and a shared-concept-graph module.

---

## Analytics (`@oshun/analytics`)

A typed analytics-event surface. Source: `libs/oshun/analytics/src/types.ts`.

### Core Types

```typescript
type OshunDomain =
  | 'oshun'
  | 'tara'
  | 'veritas'
  | 'nyx'
  | 'arete'
  | 'nisaba'
  | 'metis'
  | 'yemaya';
type OshunPlatform = 'ios' | 'android' | 'web' | 'pwa' | 'server';
type OshunShellTab = 'home' | 'explore' | 'activity' | 'library' | 'profile';
```

The event surface is a typed `OshunEventPayloadMap` — each key is an event name
and the value is that event's payload shape. `OshunEventName` is
`keyof OshunEventPayloadMap`. An `AnalyticsEventEnvelope<TName>` wraps an event
with `id`, `name`, `domain`, `occurredAt`, `context` (`AnalyticsContext`), and a
typed `payload`.

### Representative Shell Events

The events listed below are the most common shell-level tracking points. The
full set is larger and includes studio authoring-flow events.

`shell_opened`, `tab_viewed`, `route_transition_completed`,
`home_continuation_impression` / `…clicked`, `recommendation_impression` /
`recommendation_tap` / `recommendation_feedback`,
`cross_domain_recommendations_served`, `domain_launch_requested` /
`domain_launch_completed`, `search_executed` / `search_zero_results` /
`search_result_opened`, `item_saved` / `item_unsaved`,
`activity_reentry_opened`, the `nisaba_*` study/inspector events,
`auth_signed_in` / `auth_signed_out`, and the `public_auth_funnel_*` funnel
events. The map additionally defines an extensive set of `studio_*`
request/completed/audit-event triples for studio authoring flows.

### Sinks and Client

`AnalyticsSink` requires `track(event)` and optionally `identify` and `flush`.
`AnalyticsClientOptions` carries `context`, `sinks`, and optional `now` and
`randomId` overrides. The library also ships dashboard, alert, evaluation, and
release-taxonomy manifests and a singleton client.

---

## Design Tokens (`@oshun/design-tokens`)

The typed token system underpinning the Oshun visual language. Source:
`libs/oshun/design-tokens/src/tokens.ts`.

### Token Schema

`OshunTokenSchema` groups `color`, `spacing`, `radius`, `typography`, `motion`,
and `elevation`. `oshunTokenSchema` is the concrete instance.

- **Color** — `OshunColorSchema` has `neutral` (`ink`, `fog`), `brand` (`aqua`,
  `amber`), `status` (`success`, `danger`), and a `domain` record with a hex
  accent for each of the six domains. Each scale is an `OshunColorScale` with
  stops `50`–`950`.
- **Spacing** — `oshunSpacingScale` is a fine-grained px scale; the schema
  exposes the aliases `xxs`–`3xl`.
- **Radius** — `sm` 8, `md` 12, `lg` 16, `xl` 24, `pill` 999.
- **Typography** — `family` (display / body / mono), `weight` (`regular` 400 …
  `extrabold` 800), an 11-step `scale`, and `oshunTypographyRamp`.
- **Motion** — `oshunMotionDurationScale` / `oshunMotionTokens` define
  `duration` (`instant` 50ms … `slower` 500ms), `easing`, `distance`, `scale`.
- **Elevation** — `oshunElevationTokens` (`none`, `xs`, `sm`, `md`, `lg`, `xl`,
  `inner`).

### Themes

`OshunThemeName` is `light` | `dark` | `highContrastLight` | `highContrastDark`.
An `OshunTheme` bundles `primitives`, `semantic`, `semanticTokens`, `spacing`,
`radius`, and `typography`. `OshunThemeMode` is `light` | `dark`;
`OshunThemeResolutionOptions` adds an optional `highContrast` flag.

### UI-Behavior Token Sets

Beyond raw tokens, the library defines structured UI-behavior contracts — each
with `scope`, `principles`, semantic rules, `roles`, and a `prohibited` list.
These contracts describe how tokens must be applied to specific UI contexts, not
just what the raw values are.

Behavior contracts cover: domain accents (`oshunDomainAccentBehavior`), grounded
evidence, disclosure, assistant-persona switching, avatar/voice identity,
review/approval states, trust signals, and admin states. `OshunV1Foundation` is
the assembled foundation bundle.

---

## Shared UI (`@oshun/ui`)

Shared UI primitives, theme bindings, and motion transitions for the React shell
surfaces. Source: `libs/oshun/ui/src/` — `components/`, `theme/`, `motion/`.

---

## Offline Sync Queue (`@oshun/offline`)

A storage-backed cache and durable retry queue for mutations made while offline.
Source: `libs/oshun/offline/src/types.ts`.

The storage interface is intentionally narrow so the same implementation runs on
every platform target without modification:

```typescript
interface OfflineStorage {
  get(key: string): Promise<string | null>;
  set(key: string, value: string): Promise<void>;
  remove(key: string): Promise<void>;
  keys(prefix?: string): Promise<string[]>;
}

interface CacheEntry<T> {
  value: T;
  expiresAt: number | null;
  updatedAt: number;
}

interface SyncQueueItem<TPayload = unknown> {
  id: string;
  type: string;
  payload: TPayload;
  createdAt: number;
  attempts: number;
  nextAttemptAt: number;
}

interface RetryPolicy {
  maxAttempts: number;
  initialDelayMs: number;
  maxDelayMs: number;
  multiplier: number;
}

interface ConnectivityState {
  isOnline: boolean;
  isMetered?: boolean;
}
```

Queue processing returns a `QueueProcessResult` (`processed`, `failed`,
`deferred`, `remaining`, plus per-item `QueueProcessItemResult`). A single item
outcome is `processed` | `retry_scheduled` | `failed` | `deferred`. Modules:
`cache`, `connectivity`, `retry`, `storage`, `queue`.

---

## Shell Achievements (`@oshun/shell-achievements`)

Cross-domain achievements, levels, social accountability, and group challenges.
Source: `libs/oshun/shell-achievements/src/types.ts`.

`OshunDomainId` here is `'tara' | 'veritas' | 'nyx' | 'arete'` — achievements
span only these four domains.

### Achievement Model

`AchievementDefinition` carries `achievementId`, `name`, `description`,
`category` (`AchievementCategory`, 14 values), `tier` (`AchievementTier`:
`bronze` | `silver` | `gold` | `platinum`), `rarity` (`AchievementRarity`, 5
values), `icon`, `points`, `domains`, `conditions` (`AchievementCondition[]`),
`conditionMode` (`all` | `any`), optional `seasonalStart`/`seasonalEnd`,
optional `secret`, and `tags`. `AchievementCondition` has `metric`, `operator`
(`gte` | `lte` | `eq` | `gt` | `lt`), `target`, and an optional `domain`.

`UserAchievement` tracks `progress` (0–100), `unlocked`, `unlockedAt`,
`acknowledged`, and per-condition progress. `CrossDomainUserStats` is the metric
bag the engine evaluates conditions against, with per-domain counters for Tara,
Veritas, Nyx, and Arete plus cross-domain totals; `DEFAULT_CROSS_DOMAIN_STATS`
zeroes it.

### Levels

`LEVEL_DEFINITIONS` is a 15-level table (`Newcomer` … `Ascended`) with
`xpRequired`, `cumulativeXp`, and per-level `perks`. Helpers:
`resolveLevelFromXp`, `xpToNextLevel`, `resolveTierFromPoints` (platinum ≥ 5000,
gold ≥ 2000, silver ≥ 500), `evaluateCondition`, `getStatValue`.

### Social Accountability and Challenges

`AccountabilityPartnership`, `AccountabilityInvite`, `AccountabilityCheckIn`,
`EncouragementMessage` model one-to-one accountability; `ChallengeDefinition`,
`ChallengeTarget`, `ChallengeMilestone`, `ChallengeParticipation`,
`ChallengeLeaderboardEntry` model group challenges. `LeaderboardResult` carries
`LeaderboardEntry[]` with `LeaderboardPeriod`, `LeaderboardCategory`, and
`LeaderboardScope`.

### Achievement Engine Configuration

`AchievementEngineConfig` (`DEFAULT_ACHIEVEMENT_ENGINE_CONFIG`:
`statsRefreshIntervalMs` 60s, `maxRecentUnlocks` 10, `maxNextClosest` 5,
`inviteExpiryMs` 7 days, `maxPartnerships` 10, `maxActiveChallenges` 5). The
engine consumes an `AchievementDomainAdapters` record (Tara, Veritas, Nyx,
Arete) of metric-collection adapters and emits `AchievementEvent`s
(`AchievementUnlockEvent`, `AchievementProgressEvent`, `PartnershipEvent`,
`ChallengeEvent`).

---

## Shell Routines (`@oshun/shell-routines`)

User-defined morning/evening routines. Source:
`libs/oshun/shell-routines/src/types.ts`. Routines sequence steps across **Tara
and Arete only** — `RoutineStepDomain` is `'tara' | 'arete'`.

### Step Model

`RoutineStepType` is a 14-value union: Tara steps (`tara.meditation`,
`tara.breathwork`, `tara.body_scan`) and Arete steps (`arete.morning_review`,
`arete.daily_planning`, `arete.goal_review`, `arete.habit_check`,
`arete.journal`, `arete.evening_reflection`, `arete.balance_checkin`,
`arete.shutdown_ritual`, `arete.gratitude`, `arete.intention_setting`).
`RoutineStepConfig` is a discriminated union of per-step config interfaces.
`getStepDomain` resolves a step type to its domain.

`RoutineType` is `morning` | `evening` | `custom`; `RoutineFrequency` is `daily`
| `weekdays` | `weekends` | `custom`. `RoutineStepStatus` is `pending` |
`in_progress` | `completed` | `skipped` | `failed`; `RoutineExecutionStatus` is
`not_started` | `in_progress` | `paused` | `completed` | `abandoned`.

### Definitions and Execution

`RoutineDefinition` is a template (ordered `RoutineStep[]`, `scheduledTime`,
`frequency`, `tags`, `isDefault`); `UserRoutine` is a personalized instance with
`enabled`, `executionCount`, and `completionRate`. `RoutineExecution` tracks a
live run (`currentStepIndex`, `RoutineStepExecution[]`, timing, and
`effectivenessScore`). `RoutineRecommendation`, `RoutineHistorySummary`, and
`RoutineStreakInfo` cover recommendation and history.

### Routine Engine Configuration

`RoutineEngineConfig` (`DEFAULT_ROUTINE_ENGINE_CONFIG`: `maxActiveRoutines` 10,
`maxStepsPerRoutine` 15, `stepTimeoutMs` 30s, `maxConcurrentSteps` 1,
`enablePersonalization` true, `defaultMeditationDurationMinutes` 10). The engine
consumes `RoutineDomainAdapters` (`tara`, `arete`) and emits `RoutineEvent`s.
`RoutineEventType` is a 12-value union (`routine.created`, `execution.started`,
`step.completed`, etc.).

---

## Shell Surfaces

The shell ships dedicated surface libraries. All three share the domain
adapters, shell services, and design tokens; only the presentation and
platform-integration code differs.

- **`@oshun/shell-core`** — shell runtime: home orchestration, domain
  navigation, command surface, notification/message centers, account switcher,
  onboarding/feature education, activity timeline, help center, feedback
  capture, feature experiments, calendar sync, saved queue, public profiles.
- **`@oshun/shell-desktop`** — desktop shell: window manager, tray companion,
  global shortcut manager, update manager, OS notification bridge, widget
  engine, protocol handler.
- **`@oshun/shell-wearable`** — wearable shell: complication engine, haptic
  patterns, summary / streak / reminder companions, active-session surfaces.

`apps/oshun/web` and `apps/oshun/mobile` are the web and React Native shell
applications; `apps/oshun/bff` is the backend-for-frontend.

---

## Backend-for-Frontend (`apps/oshun/bff`)

`@oshun/bff` aggregates domain REST responses behind a single shell-shaped API.
A single BFF endpoint replaces a fan-out of up to six domain API calls per shell
screen, keeping the shell applications thin. It exposes route modules under
`src/routes/` — including `home`, `domains`, `continue`, `search` (with
suggestions and domain filter), `library`, `activity`, `favorites`,
`achievements`, `routines`, `assistant`, `cross-domain-recommendations`,
`recommendations`, per-domain routes (`arete`, `nisaba`, `nyx`, `veritas`),
`desktop`, `wearable`, `auth`, `consent`, `data-export`, `data-deletion`,
`entitlements`, `notifications`, `profile`, `health`, and a large set of
`admin-*` routes. Domain integration goes through
`src/adapters/domain-service-adapters.ts` (with a mock variant for tests).
`src/openapi/` holds the API schema.

---

## Color Science (`@oshun/color-science`)

The color-computation library underpinning `@oshun/design-tokens`. It implements
an ACES-based color pipeline: ACES 2065-1 and ACEScg color spaces, XYZ-D60
conversions, ACES output transforms, look-modification transforms, reference
gamut compression, camera IDTs, an OCIO v2 integration, and OCIO config
generation. Source: `libs/oshun/color-science/src/lib/`.

---

## Concordia Integration (`@oshun/concordia-integration`)

Navigation hooks, event subscriptions, and telemetry sinks bridging the
Concordia mediation system into the Oshun shell (Phase 179.6). The library
exports Zod schemas — `ConcordiaNavItemSchema`,
`ConcordiaEventSubscriptionSchema`, `ConcordiaTelemetrySinkSchema`,
`ConcordiaIntegrationRegistrationSchema` — and the helpers `orderNavItems` and
`subscriptionsForEventType`. The Oshun Concordia workbench route lives at
`apps/oshun/web/src/app/studio/concordia-workbench/`.

---

## Versioned Contracts

Domain adapters version their shell-facing payloads using the contract-version
helpers from `@oshun/types` (`libs/shared/types/src/contracts.ts`):
`buildOshunContractVersionDescriptor`, `versionOshunContractPayload`, and the
`OshunVersionedContractEnvelope` type. Each adapter declares one descriptor —
for example `NYX_DOMAIN_ADAPTER_CONTRACT` (`oshun.domain.nyx.adapter`, version
`1.0.0`, `minimumCompatibleVersion` `1.0.0`) — and exports versioned-payload
type aliases for its metadata, availability, continue-items, search-results, and
launch-resolution payloads.

---

## Shared Contract Submodules (`@oshun/contracts`)

`@oshun/contracts` (`libs/contracts`) holds canonical cross-layer contract
types. Submodules that exist today: `agent`, `aja`, `arete`, `common`, `events`,
`iris`, `living-scene`, `llm`, `metis`, `nisaba`, `nyx`, `tara`, `tts`, `v3`,
and `veritas`. Notable consumers: `@oshun/embodiment-aja` validates against the
`aja` Zod schemas; the `iris` submodule exports memory continuation and entry
contracts. The `events` submodule defines per-domain event payloads, including
Concordia events.

---

## V2 Platform Service Contracts

The V2 fighting-game project treats Oshun as its platform spine: identity,
entitlements, audit retention, and service observability are all owned by Oshun
libraries and consumed by V2 services under `V2/services/`. Each V2 service is a
deterministic composition layer over an Oshun library; none of them may touch
the rollback netcode path, so every surface fixes `mayInfluenceRollback: false`.
This section documents the four Oshun-owned cross-domain contracts.

### V2 Entitlement Claim Contract (`@oshun/identity`)

The **V2 Entitlement Claim Contract** lets cross-product unlocks (titles,
badges, card borders, cosmetics earned in sibling products) surface inside V2
without leaking the activity that produced them. The contract lives in
`libs/shared/identity/src/v2-entitlement-claims.ts` and `@oshun/identity` is the
single source of truth; the V2 service `@v2/cross-product-entitlement` depends
on it at `workspace:*` and exposes `buildV2CrossProductEntitlementSurface`.

Claims from default-on issuers — Lilith meditation-streak titles, Shakti
certification badges, and Calliope fan-club tiers — are approved automatically
(`approved-default-on`) and may surface on lobby, title, and badge surfaces.
Claims from sensitive issuers — Aphrodite-derived grants — must be marked
`sensitive-adult` and require an explicit per-grant opt-in with the
out-of-context warning accepted; absent that,
`evaluateV2CrossProductEntitlementClaim` returns
`blocked-missing-per-grant-opt-in` or `blocked-warning-not-accepted`. Even when
opted in, Aphrodite grants stay `private-inventory`
(`aphroditeImplicitLobbyTitleBadgeBlocked: true`), and the source activity is
always redacted (`sourceActivityRedacted: true`). The Unreal client mirrors this
contract with `FV2CrossProductEntitlementClaim` /
`FV2CrossProductEntitlementDecision` and the `BuildCrossProductEntitlementClaim`
/ `EvaluateCrossProductEntitlementClaim` blueprint nodes, which enforce the same
Aphrodite-sensitive rules.

Source: `libs/shared/identity/src/v2-entitlement-claims.ts`,
`apps/v2/cross-product-entitlement/src/cross-product-entitlement.ts`.

### V2 Identity Binding Contract (`@oshun/identity`)

The **V2 Identity Binding Contract** makes `@oshun/identity` the canonical
account authority for the V2 project, replacing the old V2-only publisher
account abstraction (`v2PublisherAccountAbstractionReplaced: true`). It lives in
`libs/shared/identity/src/v2-account-binding.ts`; the V2 service
`@v2/oshun-identity-binding` depends on `@oshun/identity` at `workspace:*` and
exposes `buildV2OshunIdentityBindingSurface`.

Every platform account — PSN, Xbox Live, Nintendo Account, and Steam — binds to
exactly one Oshun identity. A platform binding carries a `linkedOshunAccountId`,
and `validateV2OshunIdentityAccountState` rejects any platform account whose
`linkedOshunAccountId` points at a different Oshun account. Sensitive actions
(account merge, platform rebind, region change, DSR requests) gate on verified
two-factor and recovery-ready state; region changes carry a 90-day cooldown and
platform rebinds a 30-day cooldown. The Unreal layer mirrors the contract with
`FV2OshunIdentityAccountBinding` (built by `BuildOshunIdentityBinding`) and the
persistence save header (`FV2SaveHeader` with `OshunAccountId`,
`IdentitySourcePackageName`), whose conflict resolver blocks cross-account save
merges. The binding stays off rollback (`mayInfluenceRollback: false`).

Source: `libs/shared/identity/src/v2-account-binding.ts`,
`apps/v2/oshun-identity-binding/src/oshun-identity-binding.ts`.

### Audit Publication and Retention (`@oshun/audit-platform`)

Oshun owns the canonical audit ledger for the V2 project. The contract is
simple: **V2 publishes** audit events through `@oshun/audit-platform`, and
**Oshun retains and exports** them. The shared publisher
(`libs/shared/audit-platform/src/v2-audit-publication.ts`) accepts three
publication kinds — `moderation`, `anti-cheat`, and `DSR` — built by
`buildV2AuditPublicationRequest` onto canonical actions
(`v2.moderation.decision_published`, `v2.anti_cheat.review_published`,
`v2.dsr.workflow_published`) and tagged with per-kind retention policies. Three
V2 services publish into it: `@v2/kuanyin-first-line-moderation` (moderation
decisions), `@v2/nous-anti-cheat-classifiers` (anti-cheat reviews), and
`@v2/themis-privacy-dsr-routing` (data-subject requests, which replaced the
standalone DSR ops console). Each publication fixes `v2Publishes: true` /
`oshunRetainsAndExports: true` so the retained record and the
investigation/regulator export live in one Oshun-owned platform rather than in
per-service silos. The cross-domain contract is documented in
`V2/docs/integration/v2-audit-platform-routing.md`.

### Service Observability (`@oshun/metrics` + `@oshun/tracing`)

Observability is **required from day one** for every V2 service. Every package
under `V2/services` depends on `@oshun/metrics` and `@oshun/tracing` at
`workspace:*`, and the shared Node adapter (`apps/v2/oshun-adapter`) wires a
metrics registry (`createRegistry`, the `handler_duration_seconds` histogram)
and a lightweight tracer (`createLightweightTracer`, consumer spans with
`SpanStatus.OK` / `SpanStatus.ERROR`) around every handler. On the Unreal side,
`V2Services` carries the `EV2OshunDomain::Metrics` and `EV2OshunDomain::Tracing`
adapters and an `FV2ServiceObservabilityBinding` with `bRequiredFromDayOne`;
`BuildRequiredObservabilityBindings` / `ValidateRequiredObservabilityBindings`
assert both bindings exist for every V2 service. Crucially, observability is
kept **off rollback** — the bindings fix `bMayInfluenceRollback = false`, so
metrics and tracing never perturb the deterministic simulation. The integration
contract is documented in `V2/docs/integration/v2-service-observability.md`.

---

## Integration Points

The table below summarizes the external dependencies of the Oshun shell — what
it calls, and why. All calls to domain APIs go through typed adapters; the shell
does not call domain servers directly.

| System                                                      | Direction                         | Purpose                                                  |
| ----------------------------------------------------------- | --------------------------------- | -------------------------------------------------------- |
| Domain REST APIs                                            | shell → domains                   | Domain adapters call domain HTTP APIs                    |
| `@oshun/bff`                                                | shell apps → BFF                  | Aggregated, shell-shaped API                             |
| `@oshun/types`                                              | shell → shared                    | Versioned contract envelope helpers, platform primitives |
| `@oshun/contracts`                                          | shell → contracts                 | Canonical cross-layer contract types and Zod schemas     |
| `@metis/api-client`                                         | `@oshun/domain-metis` → Metis     | Metis adapter re-export                                  |
| `@sophia/client`, `@sophia/schemas`, `@sophia/verification` | `@oshun/evidence-sophia` → Sophia | Evidence retrieval and verification                      |

---

## Acceptance Criteria

The following criteria define correctness for the Oshun shell. They are written
as testable assertions against the actual runtime behavior, not documentation
promises.

- The domain registry knows exactly six domains, and `listDomainMetadata()`
  still returns all six for admin and taxonomy callers. The member-facing
  selectors are release-scoped: `getShellNavigationDomains()` and
  `getAvailableDomains()` return only the four V1.0 rooms (Tara, Nyx, Arete,
  Nisaba), because Veritas and Metis are deferred to V1.2 — see
  `libs/oshun/navigation/src/release-scope.ts`. `getAvailableDomains` excludes
  any with `availability === 'planned'`.
- Registry guards reject malformed domain references with
  `DomainRegistryBoundaryError` carrying structured issues.
- Each canonical domain adapter implements `getContractDescriptor`,
  `getMetadata`, `getAvailability`, `getHomeCards`, `getContinueItems`,
  `search`, and `launch`, and declares a versioned contract descriptor.
- The shell assistant resolves intent into a `ResolvedIntent`, routes a
  `DomainAction` whose `type` is a member of `DomainActionType`, and returns an
  `AssistantResponse`.
- Navigation builders and parsers round-trip canonical deep links and web links;
  parsers return `null` for unrecognized inputs.
- Analytics events are accepted only when their payload matches the
  corresponding `OshunEventPayloadMap` entry.
- The offline queue replays `SyncQueueItem`s under a `RetryPolicy` and reports a
  `QueueProcessResult`.
- Achievement conditions evaluate against `CrossDomainUserStats`; routines
  sequence Tara/Arete steps under the routine engine.
- Every library builds, type-checks, and passes its Vitest suite.
