# Oshun Domain — Features

> **Oshun** (`libs/oshun/`) is the platform shell and cross-domain orchestration
> layer. Named after the Yoruba goddess of fresh water, creativity, and love,
> the Oshun shell provides the unified application surface that ties the product
> domains together: a voice-first AI assistant, a domain registry, typed domain
> adapter contracts, navigation primitives, offline support, achievement
> tracking, user-defined routines, and the shared UI and design-token system.
> The product domains the shell launches are Tara, Veritas, Nyx, Arete, Nisaba,
> and Metis; the embodiment adapters wrap Psyche, Aja, Sophia, Iris, Isis, and
> Lilith. Shell code imports from `@oshun/domain-*` and `@oshun/embodiment-*`
> adapter libraries rather than calling domain HTTP APIs directly, keeping the
> shell decoupled from domain implementation details. When a domain API changes,
> only its adapter needs updating; TypeScript catches breakage at compile time.

---

The Oshun feature set can be grouped into three broad concerns. First, the
**adapter layer** — domain adapters for each product domain and embodiment
adapters for each AI system — gives the shell a typed, version-safe way to
interact with every external service. Second, the **shell orchestration layer**
— the assistant, navigation, achievements, and routines — gives users a coherent
cross-domain experience on top of those adapters. Third, the **shared platform
layer** — auth, analytics, offline, UI, design tokens, and the BFF — provides
the infrastructure that every shell surface relies on.

The sections below cover each feature group in detail.

---

## Domain Adapters

Domain adapters are the typed contract layer between the Oshun shell and each
domain's REST API. They expose domain data and operations as strongly-typed
TypeScript interfaces, eliminating raw HTTP calls and untyped JSON parsing from
shell code. There is one adapter library per product domain. All four of the
active adapters (Tara, Veritas, Nyx, Arete) follow the same two-layer structure:
a typed HTTP client that mirrors the domain's REST API, and a canonical adapter
that wraps that client and adds shell-facing concerns (card composition, search,
launch resolution, cross-domain bridge helpers, and a versioned contract
descriptor). See [Architecture](./architecture.md) for a detailed walkthrough of
the pattern.

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

Tara is the meditation, breathwork, sleep, and ritual domain. Its adapter gives
the shell everything it needs to present and resume Tara content.

- **API Client** — Full TypeScript API client for the Tara meditation,
  breathwork, sleep, and ritual domain, with request/response types that match
  the Tara REST API and a runtime-agnostic `fetcher`.
- **Canonical Adapter** — Wraps the API client into a shell-facing canonical
  adapter with registry metadata, availability checks, home-card composition,
  search, and launch resolution.
- **Practice Taxonomy** — A rich content taxonomy: mood (7 values), theme (10
  values), duration band, practice tradition, and intended outcome, with
  inference helpers that derive taxonomy from titles, tags, and signals.
- **Session State Models** — `TaraSessionCompletionState` and
  `TaraSessionContinuationState` drive resume / restart / reflect / replay
  decisions for the continue rail.
- **Versioned Contract + Errors** — The adapter declares a versioned contract
  descriptor; failures raise `TaraDomainAdapterError` with a `code` of `http` /
  `network` / `parse`.

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

Veritas is the truth-first news, claim-checking, and source-credibility domain.
Its adapter surfaces claims, verdicts, and articles to the shell with full
credibility metadata.

- **API Client** — TypeScript client for the Veritas truth-first news,
  claim-checking, and source-credibility domain.
- **Claim and Verdict Types** — `VeritasClaim`, `VeritasClaimEvidence`, and
  `VeritasClaimDetail` with an eight-value `VeritasVerdict` enum (`verified` …
  `unverified`), evidence-stance enum, and a `VeritasCredibilityTier` for source
  credibility.
- **Article and Topic Types** — `VeritasArticleBrief` / `VeritasArticleFeedItem`
  with content-type and recommendation-reason enums, `VeritasContinueReading`,
  `VeritasTopic`, `VeritasCategory`, saved-article and followed-topic models.
- **Canonical Adapter** — Adds shell-facing card composition, search, launch
  resolution, retraction-cascade and correction-note helpers, and cross-domain
  relationship helpers (Sophia, Nisaba, Tara, Arete).
- **Versioned Contract + Errors** — Failures raise `VeritasDomainAdapterError`
  with a `code` of `http` / `network` / `parse`.

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

Nyx is the astronomical-event and celestial-object domain. Its adapter lets the
shell present tonight's sky highlights, observation logs, and event reminders.

- **API Client** — TypeScript client for Nyx astronomical-event and
  celestial-object lookup APIs.
- **Event Types** — `NyxAstronomicalEvent` and `NyxNightlyHighlight` with a
  24-value `NyxEventType` enum (eclipses, conjunctions, meteor showers, moon
  phases, ISS passes, solstices, equinoxes), visibility and importance enums,
  and `NyxObservingConditions`.
- **Object and Observation Types** — `NyxCelestialObject` (11-value object-type
  enum), `NyxObservationLog`, `NyxSavedObject`, `NyxContinueObservation`, and
  `NyxSkyMapSession` with a four-value sky-map mode enum.
- **Event Reminders** — `NyxEventReminder` with reminder cadence, channels (push
  / email / sms / external-calendar), and per-channel delivery routes.
- **Canonical Adapter** — Adds card composition, search, launch resolution
  across 17 launch screens, and cross-domain bridge moments. Failures raise
  `NyxDomainAdapterError`.

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

Arete is the goals, habits, journaling, balance, and AI-coaching domain. Its
adapter exposes the full self-improvement feature surface to the shell.

- **API Client** — TypeScript client for the Arete goals, habits, journaling,
  balance, and AI-coaching domain.
- **Goal and Habit Types** — `AreteGoal` with `AreteMilestone[]`, `AreteHabit`
  with completion tracking, and goal/habit category, horizon, status, and
  frequency enums.
- **Journal, Coach, and Balance Types** — `AreteJournalEntry` and
  `AreteJournalPrompt`, `AreteCoachInsight` (five-value insight-type enum),
  `AreteBalanceCheckIn` with eight wheel-of-life dimensions, `AreteStreakStats`,
  and `AreteAccountabilityReminder`.
- **Canonical Adapter** — Adds card composition, launch actions, streak-recovery
  and friction-taxonomy helpers, and cross-domain relationships (Tara, Nisaba,
  Metis, Veritas). Failures raise `AreteDomainAdapterError`, which also carries
  `statusCode` and `errorCode`.

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

Nisaba is the ancient-text analysis and cross-tradition scholarly research
domain. Its adapter is read-oriented: it surfaces a researcher's study progress
and bookmarks to the shell without exposing write operations.

- **API Client** — TypeScript read adapter for the Nisaba ancient-text analysis
  and cross-tradition scholarly research domain.
- **Passage and Reading Types** — Typed models for scholarly passages, saved
  passages, and continue-reading state, so the shell can surface a researcher's
  recent and bookmarked study material.
- **Concept Graph Linkages** — Typed concept-thread and concept-graph linkage
  models connecting passages, sources, and ideas across traditions.
- **Scholarly Search** — Typed search hits and search modes spanning passages,
  concepts, sources, and manuscripts for the shell search surface.
- **Study Workspace State** — Workspace entry, study reminder, research-type,
  and project-status types for tracking active research workspaces and resuming
  study sessions.

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

The domain registry is the static catalog the Oshun shell uses to discover and
launch domains. Rather than hardcoding domain entry points in each surface,
every surface reads the registry to know what domains exist, how to reach them,
what permissions they require, and how to present them when offline. This means
adding a new domain is a single registry change rather than a series of
scattered edits across surface code.

- **Domain Metadata** — Each registered domain has a `DomainMetadata` record:
  display name, route, accent color, icon token, taglines, capability tokens, an
  analytics namespace, a notification channel, a BFF base path, a deep-link
  prefix, and a shell narrative (tagline, summary, first-run summary).
- **Auth Policy** — A `DomainAuthPolicy` per domain: whether auth is required,
  the session kind (`customer` / `learner` / `reader` / `operator`), required
  scopes, and step-up actions.
- **Launch Contracts and Offline Fallbacks** — A `DomainLaunchContract` (icon,
  label, CTA, and a typed permission list) and a `DomainOfflineFallbackCard`
  with offline-mode copy per domain.
- **Admin Taxonomy** — A `DomainAdminTaxonomy` per domain: owner subsystem,
  review queues, audit category, and content classes.
- **Availability** — Each domain is `active`, `beta`, or `planned`;
  `getAvailableDomains` excludes `planned` domains.
- **Runtime Guards** — `isOshunDomainId`, `assertOshunDomainId`,
  `validateDomainReference`, and `validateCrossDomainReference` validate domain
  references; malformed input raises `DomainRegistryBoundaryError`.
- **Registered Domains** — Tara (active), Veritas (active), Arete (active), Nyx
  (beta), Nisaba (beta), and Metis (planned). The primary shell domain is Tara.

---

## AI Embodiment Adapters

Embodiment adapters are the canonical contract layer between the Oshun shell and
the AI systems that power its experience. These adapters define TypeScript
interfaces for interacting with Psyche (voice/avatar sessions), Aja (embodied
instruction), Sophia (grounded evidence), Iris (memory), Isis (generation
control), and Lilith (persona policy) without coupling the shell to their
internal APIs.

The reason these adapters live in `libs/oshun/` rather than in their respective
AI-system domains is that they express the _shell's view_ of each AI capability:
what data the shell needs to receive, what requests it needs to send, and what
safety or disclosure contracts it must uphold. The AI systems themselves
implement these interfaces; the shell consumes them.

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

Psyche manages real-time voice, avatar, video, and screen-share sessions. Its
adapter gives the shell typed models for the full session lifecycle, modality
negotiation, and multi-participant orchestration.

- **Session Lifecycle** — Types for creating, starting, pausing, resuming, and
  ending Psyche sessions. `PsycheEmbodimentSessionStatus` has eight values
  (`initializing`, `live`, `paused`, `resuming`, `ending`, `ended`, `failed`,
  `timed_out`); `PsycheSessionKind` is `video` / `voice` / `screen_share` /
  `chat` / `hybrid`.
- **Modalities and Emotion** — `PsycheModality` covers text, voice, avatar,
  video, screen-share, and translation; `PsycheEmotionState` is an eight-value
  enum (`neutral`, `happy`, `sad`, `angry`, `confused`, `frustrated`, `engaged`,
  `distracted`).
- **Persona, Voice, and Avatar Models** — `PsycheEmbodimentProfile`,
  `PsycheVoiceProfileSummary`, and `PsycheAvatarPackSummary` describe the
  persona and its embodiment assets, with readiness and quality state.
- **Multi-Participant Sessions** — `PsycheLiveSessionState` with participant
  summaries, a turn-state model, conference-bridge and translation summaries,
  and a synthetic-voice / synthetic-avatar disclosure state.
- **Pipeline Services** — `PsychePipelineService` enumerates the ASR, TTS, LLM,
  NLU, vision, avatar, emotion, knowledge, and tools services a session uses.

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

Aja provides embodied, step-by-step instruction capabilities. Its adapter
exposes only three high-level operations (demonstration plans, coaching
overlays, and session handoffs), each validated against Zod schemas to prevent
malformed payloads from reaching the AI system.

- **Embodied Demonstration** — `createDemonstrationPlan` produces a
  demonstration plan for embodied, step-by-step instruction.
- **Coaching Overlays** — `createCoachingOverlay` builds a coaching overlay over
  an active instruction session.
- **Session Handoffs** — `createSessionHandoff` carries an instruction session
  to another surface or persona.
- **Schema-Validated Contract** — Every request and response is validated
  against the Zod schemas in `@oshun/contracts/aja`, so malformed payloads are
  rejected at the adapter boundary.

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

Sophia retrieves grounded answers backed by citations and claim checks. Its
adapter is particularly important for features that need to surface evidence
trails — like Veritas claim verification or Nisaba source comparisons — without
embedding evidence-retrieval logic in shell code.

- **Grounded Answers and Evidence Packs** — `SophiaGroundedAnswer` and
  `SophiaEvidencePack` bundle an answer, its citations, evidence items, source
  summaries, and claim checks. `SophiaGroundingStatus` is `grounded` /
  `partially_grounded` / `unsupported` / `conflicting`.
- **Citations and Evidence** — `SophiaCitationTrail` and `SophiaEvidenceItem`
  attach excerpts to sources with a stance enum and confidence scores;
  `SophiaSourceSummary` carries reliability and scholarly-consensus signals.
- **Source Graph and Notebooks** — `SophiaSourceGraphPreview` previews entity
  relationships; `SophiaNotebookRecord` and `saveNotebookItems` support saved
  research collections.
- **Trace Exports** — `createTraceExport` produces a `SophiaTraceExportRecord`
  in one of four kinds (bibliography, evidence table, grounded report, review
  packet) and four formats (json, csv, markdown, pdf).
- Built on the `@sophia/client`, `@sophia/schemas`, and `@sophia/verification`
  packages.

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

Iris manages the user's persistent memory across sessions. Its adapter is the
only way the shell reads or writes memory — giving users meaningful control over
what the platform remembers by centralizing all memory access through a
consent-aware, privacy-first API.

- **Memory Scopes and Tiers** — `IrisMemoryScope` is an eleven-value enum
  (`assistant_profile`, `session`, `scene`, `pose`, `conversation`, `domain`,
  `cross_domain`, `notebook`, `operator_copilot`, `tenant`, `admin_review`).
  `IrisCanonicalMemoryTier` is `core` / `working` / `archival` / `episodic` /
  `semantic`; `IrisMemoryMode` is `durable` / `ephemeral` / `suppressed`.
- **Memory Retrieval** — `IrisMemorySearchInput` / `IrisMemorySearchResult`
  retrieve `IrisMemoryRecord`s with a search-strategy enum (`semantic`,
  `keyword`, `temporal`, `hybrid`, `adaptive`) for context injection.
- **Write Planning** — `IrisMemoryWriteInput` produces an `IrisMemoryWritePlan`
  that resolves storage target, required and missing consents, opt-out blocks,
  and any `IrisMemoryConflictSummary` before a write commits.
- **Consent and Privacy** — `IrisMemoryConsentSummary`,
  `IrisMemoryOptOutSummary`, and `IrisMemoryScopePolicy` model consent, opt-out
  categories (16 values), and per-scope policy. `IrisContinuityState` exposes
  the user-facing memory-on / limited / off indicator.
- **Memory Controls** — Review, deletion (soft and hard, single and bulk), and
  export (json / csv / markdown / portable) contracts for the memory-management
  UI. Privacy-first — users control what is remembered.

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

Isis governs the generative content factory: job submission, workflow and model
registries, environment promotion, and provider routing. Its adapter gives the
shell typed models for the full generative pipeline lifecycle, including
governance and safety controls.

- **Generation Types** — `IsisGenerationType` enumerates 15 job kinds
  (`text-to-image`, `image-to-image`, `text-to-video`, `text-to-3d`,
  `voice-synthesis`, `music-generation`, `upscaling`, `inpainting`,
  `blender-render`, `gaussian-splatting`, and more).
- **Job Status** — `IsisJobStatus` is `pending` / `queued` / `running` /
  `completed` / `failed` / `cancelled`; `IsisJobPriority` is `low` / `normal` /
  `high` / `urgent`.
- **Workflow and Model Registries** — Workflow registry specs (with engine,
  category, visibility, seed-policy, and identity-adapter enums) and model
  registry specs for the generative factory.
- **Environment Promotion and Release Gates** — Environment-promotion models,
  release-gate models, staging recipes, provenance bundles, and provider
  failover policy for moving generation artifacts between `development` /
  `staging` / `production`.
- **Provider Governance** — CivitAI intake and review pipeline specs and ComfyUI
  governance models.

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

Lilith enforces persona policy and content safety. Its adapter is the shell's
gateway to evaluating whether a response is appropriate for the active persona
and handling crisis escalation correctly.

- **Persona Policy Packs** — `LilithPersonaPolicyPack` bundles a persona's
  family and category, allowed domains and consumers, teaching styles and
  practice modes, tone guidance, allowed and forbidden topics, grounding
  requirement, memory envelope, and modality permissions.
- **Policy Selection and Evaluation** — `LilithPolicySelection` chooses a policy
  pack for a context; `LilithPolicyEvaluationResult` evaluates a user message
  and draft response, returning a safety assessment, topic-scope result, tone
  guidance, disclaimers, and a prompt overlay.
- **Safety and Crisis Handling** — `LilithSafetyAssessment` carries a content
  category, risk level, and a `LilithSafetyDisposition` (`allow`,
  `allow_with_disclaimer`, `redirect`, `escalate`, `block`) with crisis types
  and safety resources.
- **Voice-Clone Safety** — `LilithVoiceSafetyPolicy` governs voice-clone usage
  with a safety class, watermark requirement, consent requirement, and
  abuse-risk thresholds.

---

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

The voice-first AI assistant at the heart of the Oshun shell. The assistant
classifies user intent and routes to the correct domain, making the shell feel
like unified intelligence rather than a collection of separate applications.

The assistant deliberately avoids embedding an LLM client in its own code. The
`IntentResolver` is rule-based over per-domain intent definitions, which makes
its behavior predictable and testable. Durable memory and voice sessions are
delegated to Iris and Psyche respectively through bridge objects, keeping the
engine's own surface area small.

- **Intent Classification** — A rule-based `IntentResolver` classifies an
  utterance into a `ResolvedIntent` (category, name, domain, confidence, slots)
  using the per-domain intent definitions (`TARA_INTENTS`, `VERITAS_INTENTS`,
  `NYX_INTENTS`, `ARETE_INTENTS`, `NISABA_INTENTS`, `METIS_INTENTS`).
- **Domain Action Routing** — The `ActionRouter` dispatches a typed
  `DomainAction` (one of roughly 70 namespaced action types) to the matching
  `Assistant*Adapter`, then returns a `DomainActionResult`.
- **Multi-Turn Conversation State** — `AssistantSession` tracks turn history,
  active and recent domains, and a continuity context (disclosure, memory,
  grounding, pending handoff) so follow-up questions resolve in context.
- **Platform-Shell Split** — A session declares a `platformShell` of `customer`
  or `admin`; the assistant filters available actions and prompt framing to that
  shell.
- **Disambiguation** — When confidence falls below `intentConfidenceThreshold`
  (default 0.4), the assistant asks a clarifying question rather than routing to
  the wrong domain.
- **Disclosure Indicators** — Grounding, memory-state, and persona-identity
  indicators keep the AI-mediated nature, memory scope, and active persona
  visible.
- **Memory and Voice Bridges** — An Iris memory bridge connects the assistant to
  Iris memory continuity; a Psyche session bridge connects it to Psyche
  voice/avatar sessions.
- **Cross-Domain Continuity and Handoffs** — Context-handoff sanitization,
  cross-domain carryover, and persona handoffs carry conversation context
  between domains and personas.

---

## Shell Navigation (`@oshun/navigation`)

Unified route and deep-link contracts for the Oshun surfaces, keeping route
definitions and parameter types consistent across web, mobile, and desktop.

Without a navigation library, each surface would independently construct URL
strings and deep links, leading to divergence and hard-to-find breakage when
paths change. `@oshun/navigation` centralizes all route definitions in one place
and exposes typed builder and parser functions that every surface uses.

- **Route Map** — `OSHUN_ROUTE_MAP` defines six shell surfaces (home, explore,
  activity, library, assistant, profile) and its rooms — six defined, four
  shipped in V1.0 (Veritas and Metis are deferred to V1.2) — each with a mobile
  path, a web path, and a deep link, defined once in TypeScript.
- **Link Builders** — `buildDeepLink`, `buildWebLink`,
  `buildCanonicalDomainDeepLink` / `…ShellDeepLink`, and
  `buildCanonicalDomainWebLink` / `…ShellWebLink` produce correct URLs for each
  surface, eliminating string URL construction.
- **Deep-Link Parsing** — `parseCanonicalDeepLink`, `parseCanonicalWebLink`, and
  `parseDeepLink` parse `oshun://` deep links and `https://oshun.app` web links
  into typed route descriptors, returning `null` for unrecognized inputs.
- **Information Architecture** — Customer, admin, and tenant IA maps,
  platform-shell definitions, and a current-domain store.
- **Journey Models** — Typed cross-domain journeys (daypart, research-practice,
  story-source, sky-text, assistant-continuity) and a shared-concept-graph
  module model navigation between domains.

---

## Shell UI and Design System

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

React UI components shared across the Oshun shell surfaces. The library exports
roughly 21 components from `components/`, plus theme bindings (`theme/`) and
motion transitions (`motion/`).

- **Components** — `Badge`, `Box`, `Banner`, `BottomSheet`, `BottomNav`,
  `Button`, `Card`, `Chip`, `CommandPalette`, `DomainSwitcher`, and more, each
  with typed props.
- **Theme Bindings** — A `theme/` module connects components to the design-token
  themes.
- **Motion** — A `motion/` module provides shared transition definitions.

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

The typed token system underpinning the Oshun visual language. It is a pure
TypeScript token source (`tokens.ts`). The token system is not just a set of
colors and spacing values — it also ships structured UI-behavior contracts that
define semantic rules for how tokens should be applied (for example, when to use
a domain accent versus a brand color, and how to surface AI-identity
disclosure).

- **Color** — `OshunColorSchema` defines `neutral` (`ink`, `fog`), `brand`
  (`aqua`, `amber`), and `status` (`success`, `danger`) color scales — each an
  `OshunColorScale` with stops `50`–`950` — plus a `domain` record with a hex
  accent for each of the six domains.
- **Typography** — Font families (display / body / mono), a weight scale
  (`regular` 400 … `extrabold` 800), an 11-step type scale, and a typography
  ramp.
- **Spacing, Radius, Elevation, Motion** — A fine-grained spacing scale with
  `xxs`–`3xl` aliases, a radius scale, layered elevation tokens, and a motion
  set (`duration`, `easing`, `distance`, `scale`).
- **Themes** — `OshunThemeName` is `light` / `dark` / `highContrastLight` /
  `highContrastDark`; an `OshunTheme` bundles primitives, semantic colors,
  semantic token groups, spacing, radius, and typography.
- **UI-Behavior Contracts** — Structured behavior contracts — each with a scope,
  principles, semantic rules, roles, and prohibitions — for domain accents,
  grounded evidence, disclosure, assistant-persona switching, avatar/voice
  identity, review/approval states, trust signals, and admin states.
  `OshunV1Foundation` assembles the full foundation bundle.

---

## Shell Surfaces

The Oshun shell ships four surface targets. Each surface renders a different
presentation layer, but all share the same domain adapters, shell services, and
design tokens.

### Shell Core (`@oshun/shell-core`)

The shell runtime that the web and mobile applications build on. Its modules
cover home orchestration, domain navigation, the command surface, the
notification and message centers, the account switcher, onboarding and feature
education, the activity timeline, the help center, feedback capture, feature
experiments, calendar sync, the saved queue, public profiles, and status
banners.

### Desktop Shell (`@oshun/shell-desktop`)

Desktop-shell features for the Oshun application. Desktop users expect native
integrations — a system tray, global keyboard shortcuts, OS notifications, and
multi-window domain views — that are irrelevant on mobile. These features live
in a dedicated library so they do not bloat the web or mobile bundles.

- **Window Manager** — A `window-manager` module for multi-window domain views.
- **Tray Companion** — A `tray-companion` module for a persistent tray surface.
- **Shortcut Manager** — A `shortcut-manager` module for global keyboard
  shortcuts.
- **Notification Bridge** — A `notification-bridge` module for OS-level
  notification delivery.
- **Update, Widget, and Protocol** — An `update-manager`, a `widget-engine`, and
  a `protocol-handler` for app updates, desktop widgets, and deep-link protocol
  handling.

### Wearable Shell (`@oshun/shell-wearable`)

A minimal UI surface for smartwatch and wearable devices. Wearable screens are
small and interaction time is short, so this shell prioritizes at-a-glance
information and haptic feedback over rich content.

- **Complication Engine** — A `complication-engine` module for watch-face
  complications.
- **Companions** — `summary-companion`, `streak-companion`, and
  `reminder-companion` modules surface compact domain information.
- **Active-Session Surfaces** — An `active-session-surfaces` module for an
  in-progress session view.
- **Haptic Patterns** — A `haptic-patterns` module defines wearable haptic
  feedback.

---

## Analytics (`@oshun/analytics`)

A typed analytics-event surface for tracking shell usage across the Oshun
surfaces. The key design decision is that every event is typed end-to-end: the
`OshunEventPayloadMap` maps each event name to its payload type, so an event
with a wrong or missing payload is a TypeScript error, not a silent runtime
problem.

- **Typed Event Map** — `OshunEventPayloadMap` types every tracked event: each
  event name maps to a strongly-typed payload shape, so events with an incorrect
  payload are rejected at compile time. Shell events include `shell_opened`,
  `tab_viewed`, `route_transition_completed`, `domain_launch_requested` /
  `domain_launch_completed`, `search_executed`, `item_saved` / `item_unsaved`,
  the `nisaba_*` study events, the `public_auth_funnel_*` funnel events, and a
  large set of `studio_*` authoring-flow events.
- **Event Envelope** — Each tracked event is wrapped in an
  `AnalyticsEventEnvelope` with an id, name, owning `domain`, `occurredAt`
  timestamp, an `AnalyticsContext` (platform, app version, locale, session and
  user ids), and the typed payload.
- **Pluggable Sinks** — An `AnalyticsSink` implements `track` and optionally
  `identify` and `flush`; the client fans events out to one or more sinks.
- **Operational Manifests** — The library also ships dashboard, alert,
  evaluation, and release-taxonomy manifests used by the platform's
  observability and launch-readiness tooling.

---

## Authentication Client (`@oshun/auth-client`)

Client-side authentication and session handling for Oshun web and mobile
applications. The `AuthClient` manages the token lifecycle so domain adapters
and shell code never deal with raw tokens. Auth is a cross-cutting concern that
every domain adapter needs, so centralizing it here avoids duplicating token
refresh and secure storage logic across the application.

- **Sign-In and Sign-Up** — `signIn` handles both password and social-provider
  login; `signUp` registers a new account. Each path persists the resulting
  `AuthSession` to a pluggable `SessionStore`.
- **Token Refresh** — Access tokens are refreshed before expiry within a
  configurable refresh window, with a minimum refresh interval and in-flight
  de-duplication so concurrent callers share one refresh.
- **Sign-Out with Server Logout** — `signOut` calls the server logout endpoint
  with the refresh token (optionally `allDevices`), then clears the local
  session even if the server call fails. `signOutAll` revokes every session.
- **Secure Storage** — A `secure-storage` module backs token persistence; the
  library also ships session, profile, preferences, billing, consent, and
  data-rights stores plus an SSO coordinator and transport-security helpers.
- **Feature Gating** — `shell-feature-gating` and `metis-feature-gating` resolve
  entitlement-based feature access from the session.

---

## Offline Support (`@oshun/offline`)

A storage-backed cache and durable retry queue so users can access content and
queue mutations without a network connection. The offline layer is intentionally
agnostic about the underlying storage medium: the `OfflineStorage` interface can
be backed by `localStorage`, `AsyncStorage`, or any other key-value store,
making it work the same way on web and React Native.

- **Storage Abstraction** — An `OfflineStorage` interface (`get` / `set` /
  `remove` / `keys`) backs both the cache and the queue, so the same code runs
  on any key-value store.
- **Cache** — A `CacheEntry<T>` store with optional `expiresAt` expiry and a
  `CacheStats` summary of total and expired entries.
- **Sync Queue** — Mutations made while offline are recorded as `SyncQueueItem`s
  (id, type, payload, `attempts`, `nextAttemptAt`). When connectivity returns
  the queue replays and reports a `QueueProcessResult` (processed, failed,
  deferred, remaining) with a per-item outcome of `processed`,
  `retry_scheduled`, `failed`, or `deferred`.
- **Retry Policy** — A `RetryPolicy` (`maxAttempts`, `initialDelayMs`,
  `maxDelayMs`, `multiplier`) drives exponential-backoff retry scheduling.
- **Connectivity State** — A `connectivity` module exposes a `ConnectivityState`
  (`isOnline`, optional `isMetered`) that gates queue processing.

---

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

Cross-domain achievement, level, social-accountability, and challenge tracking
that recognizes users' progress across the Tara, Veritas, Nyx, and Arete domains
in a unified system. (`OshunDomainId` here is the four-domain set.)

Achievements are cross-domain by design: the system evaluates conditions against
a `CrossDomainUserStats` metric bag that spans all four active domains. A user
might unlock an achievement by completing Tara meditation sessions _and_
reaching a Veritas reading streak, which is impossible if each domain tracks
achievements in isolation.

- **Achievement Definition Schema** — `AchievementDefinition` carries conditions
  (each a metric, comparison operator, and target), a points value, a tier
  (`bronze` / `silver` / `gold` / `platinum`), a rarity (5 values), a 14-value
  category, and a `conditionMode` (`all` / `any`). Conditions are evaluated
  against a `CrossDomainUserStats` metric bag.
- **Levels** — A 15-level progression (`Newcomer` … `Ascended`) with per-level
  XP requirements and perks; helpers resolve level and tier from XP and points.
- **Progress and Unlock Events** — `AchievementProgressEvent` and
  `AchievementUnlockEvent` drive progress notifications and shell-level
  celebration moments.
- **Social Accountability** — `AccountabilityPartnership`,
  `AccountabilityInvite`, `AccountabilityCheckIn`, and `EncouragementMessage`
  model one-to-one accountability partnerships.
- **Group Challenges** — `ChallengeDefinition` with daily targets, milestones,
  and `ChallengeParticipation` / `ChallengeLeaderboardEntry` for group
  accountability.
- **Leaderboards** — `LeaderboardResult` with period, category, and scope
  (`global` / `friends`); friends scope supports opting out of social
  comparison.

---

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

User-defined morning and evening routines that sequence steps across the **Tara
and Arete domains** into a cohesive workflow. `RoutineStepDomain` is
`'tara' | 'arete'`; a morning routine might run a Tara meditation, then an Arete
morning review, then Arete daily planning — orchestrated by the shell without
user navigation.

The boundary between Tara and Arete within a routine is deliberate: Tara owns
practices (meditation, breathwork, body scan) while Arete owns intentions and
reflection (morning review, journaling, goal check). The routine engine bridges
them, driving transitions between steps and tracking overall completion without
either domain knowing about the other.

- **Routine Definition Schema** — `RoutineDefinition` is a template of ordered
  `RoutineStep`s; `RoutineStepType` is a 14-value union of Tara steps
  (`tara.meditation`, `tara.breathwork`, `tara.body_scan`) and Arete steps
  (morning review, daily planning, goal review, habit check, journal, evening
  reflection, balance check-in, shutdown ritual, gratitude, intention setting).
  Each step carries a discriminated `RoutineStepConfig`.
- **User Routines** — `UserRoutine` is a personalized instance of a definition
  with `enabled`, `notificationsEnabled`, `executionCount`, and
  `completionRate`.
- **Scheduling** — Routines carry a `scheduledTime` and a `RoutineFrequency`
  (`daily` / `weekdays` / `weekends` / `custom`); the recommender surfaces
  routines that fit the current time of day.
- **Execution Engine** — `RoutineExecution` tracks a live run step by step
  (`currentStepIndex`, per-step `RoutineStepExecution`, timing, and an
  `effectivenessScore`); `RoutineExecutionStatus` is `not_started` /
  `in_progress` / `paused` / `completed` / `abandoned`.
- **Templates and History** — A routine-template library,
  `RoutineRecommendation` scoring, and `RoutineHistorySummary` /
  `RoutineStreakInfo` for streak and completion history. The engine emits
  12-value `RoutineEvent`s.

---

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

The canonical cross-layer contract types live under `libs/contracts`
(`@oshun/contracts`) and are consumed by the Oshun shell adapters and the domain
service layers they connect to. These contracts sit in their own library rather
than inside any one domain or shell library so that both sides of a
domain-to-shell boundary can depend on them without creating circular imports.

The submodules that exist today are: `agent`, `aja`, `arete`, `common`,
`events`, `iris`, `living-scene`, `llm`, `metis`, `nisaba`, `nyx`, `tara`,
`tts`, `v3`, and `veritas`.

### `@oshun/contracts/iris` — Memory Continuation Contracts

The `iris` submodule exports memory continuation and entry contracts consumed by
the Oshun shell's memory surfaces.

### `@oshun/contracts/aja` — Embodied-Instruction Contracts

The `aja` submodule exports the Zod schemas for embodied instruction —
capabilities, demonstration, coaching overlay, and session handoff — that the
`@oshun/embodiment-aja` adapter validates every request and response against.

### `@oshun/contracts/events` — Domain Event Contracts

The `events` submodule defines per-domain event payload contracts, including
Concordia mediation events consumed by `@oshun/concordia-integration`.

---

## Shared Platform Services (out of domain scope)

Platform-wide identity, data-residency, audit, and observability services are
**not** part of the Oshun domain. They live under `libs/shared/` as
`@oshun/identity`, `@oshun/data-residency`, `@oshun/audit-platform`,
`@oshun/metrics`, and `@oshun/tracing`. The Oshun shell consumes shared
infrastructure (notably `@oshun/types` for versioned contract envelopes and
`@oshun/contracts` for cross-layer contract types), but those services are
documented with the shared platform, not here.

The boundary exists because platform services are shared across every product
domain, not just the Oshun shell. Placing them under a single domain's ownership
would give that domain inappropriate authority over platform-wide concerns.

---

## Shell Implementation Surface

Beyond the published `@oshun/*` libraries, the shell domain includes three
implementation surfaces that support the libraries above rather than exposing
their own feature set.

### Oshun BFF (`apps/oshun/bff`)

`@oshun/bff` is the backend-for-frontend that the web and mobile shells call. It
aggregates domain REST responses behind a single shell-shaped API so a surface
does not fan out to every domain API directly. It ships route modules for home,
domains, continue, search, library, activity, favorites, achievements, routines,
the assistant, cross-domain recommendations, per-domain routes, desktop and
wearable surfaces, auth, consent, data export and deletion, entitlements,
notifications, profile, health, and a large set of `admin-*` routes. Domain
adapters still own each domain's contract; the BFF composes across them for
shell screens.

### Legal Documents (`apps/oshun/legal`)

`apps/oshun/legal` holds the platform legal documents — currently
`terms-of-service.md` and `privacy-policy.md`. These are document sources, not a
running application.

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

The color-computation library underpinning `@oshun/design-tokens`. It handles
color-space conversion, contrast-ratio computation for the WCAG 2.1 AA checks
the UI primitives rely on, and perceptual color operations used to derive
semantic token scales. Design tokens consume its output; it has no shell UI of
its own.

### Render Farm (`@oshun/render-farm`)

The distributed render-farm coordinator from Phase 70.14
(`libs/oshun/render-farm`): render-job submission and queueing with priorities
and preemption decisions, worker assignment against GPU/resource requirements,
frame-range scheduling with checkpoints and frame previews, cost estimation and
quota evaluation (allocation limits, quota breaches), cloud-burst planning
across providers, job logs/progress, alerts, and dashboard snapshots. Bellona
build/render workers and Yemaya productions submit into it.

### Oshun CLI `(planned, Phase 18.9)`

A command-line shell surface alongside web, mobile, and desktop: authenticated
access to domain adapters, cross-domain search, asset retrieval, and
automation-friendly output for scripting against the platform. The CLI reuses
the same domain-adapter contracts as the other surfaces.

---

## Cross-Domain Integration Posture (Phases 18 and 48)

Two roadmap phases assign cross-domain integration duties to the shell domain
beyond individual adapters:

- **Production readiness and deduplication (Phase 18)** — the shell domain owns
  the cross-domain remediation posture: tracking critical production blockers
  across surfaces, driving deduplication of capabilities implemented
  independently by multiple domains (consolidating them into `@oshun/*` or the
  owning domain), and coordinating the test-coverage expansion strategy with
  Shared.
- **Neith engine integration (Phase 48)** — as domains migrate onto the Neith
  stack via `@neith/integration-maya`/`-yemaya`/`-isis`/`-sophia`/`-hathor`/
  `-bellona` (envelopes in `DOMAINS/neith/features.md`), the shell domain owns
  the user-facing integration: surfacing Neith-hosted experiences (including the
  Neith metaverse platform) through the shell's navigation, search, and
  domain-adapter contracts so migrated domains stay reachable from every
  surface.
- **Sovereign office suite (Phase 139)** — the shell surfaces the Neith office
  and collaboration suite (`@neith/docs-core`, writer/sheets/slides, notes,
  mail, calendar, PDF tools, knowledge AI) as first-class shell experiences:
  navigation entries, cross-domain search over workspace documents, and the same
  auth/entitlement contracts as other domain adapters.
- **Creator marketplace and asset store (Phase 165)** — the shell surfaces the
  Neith creator marketplace (`@neith/market-*`) to buyers and creators:
  storefront discovery, purchase/entitlement, download/library, and creator
  portal surfaced through the shell's navigation, search, and auth contracts.
  Neith owns the marketplace, catalog, and commerce backend; the shell owns the
  cross-surface user experience.

---

## Skill System (`@oshun/skill-system`, Phase 97)

The unified cross-domain skill framework (`libs/oshun/skill-system`): skills are
typed, governed units of capability that agents discover, compose, and execute
across domains. Modules cover skill **discovery** (finding applicable skills for
a task), **composition** (chaining skills across domains into larger workflows),
**execution** (running a skill with typed inputs/outputs), **generation**
(autonomous creation of new skills from observed workflows, Phase 97's
autonomous-generation envelope), **evolution** (versioning and improving skills
over time), **governance** (approval, permissions, and audit for skill
publication and use), **dependencies** (skill-to-skill dependency resolution),
**domain-adapters** and **domain-enhancements** (per-domain skill surfaces),
**agent-tree** (delegating skill execution across agent hierarchies), and
**mcp** (exposing skills as MCP tools). Iris consumes the framework for
assistant skills; Nous supplies the models behind generation.

---

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

`@oshun/concordia-integration` bridges the Concordia mediation system into the
wider Oshun platform (Phase 179.6). The library exports Zod schemas —
`ConcordiaNavItemSchema`, `ConcordiaEventSubscriptionSchema`,
`ConcordiaTelemetrySinkSchema`, and `ConcordiaIntegrationRegistrationSchema` —
plus the helpers `orderNavItems` and `subscriptionsForEventType`. Concordia
mediation event contracts live in `@oshun/contracts/events`. The Oshun Concordia
workbench route lives at `apps/oshun/web/src/app/studio/concordia-workbench/`.
