# Meditation Shared Libraries -- Features and Capabilities

> **Canonical source:** the canonical features document for this domain is
> [`deep-dive/features.md`](./deep-dive/features.md), rendered in the docs
> center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

> Cross-platform meditation engine libraries: audio playback with multi-layer
> mixing and adaptive streaming, configurable timers with bells and ambient
> sounds, breathing exercise guidance with visualization and haptic feedback,
> session lifecycle management with persistence, progress tracking with streaks
> and achievements, and offline content management with smart download
> suggestions. All libraries are platform-agnostic and consumable by any
> meditation application.

---

## Table of Contents

1. [Audio Player Engine](#1-audio-player-engine)
2. [Meditation Timer](#2-meditation-timer)
3. [Breathing Exercise Engine](#3-breathing-exercise-engine)
4. [Session Management](#4-session-management)
5. [Progress and Achievement Tracking](#5-progress-and-achievement-tracking)
6. [Offline Content Management](#6-offline-content-management)
7. [Cross-Platform Architecture](#7-cross-platform-architecture)
8. [React Integration](#8-react-integration)

---

## 1. Audio Player Engine

### 1.1 Core Playback

| Capability         | Description                                                                                                                             |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| Track loading      | Load meditation audio tracks from multiple source formats (MP3, AAC, OGG) with quality selection (low, medium, high)                    |
| Play/pause/stop    | Standard playback controls with state machine guaranteeing valid transitions between idle, loading, playing, paused, and stopped states |
| Seeking            | Seek to any position within a loaded track with immediate playback position update                                                      |
| Volume control     | Master volume adjustment with smooth transitions and independent per-layer volume controls                                              |
| Playback rate      | Adjustable playback speed for guided meditations with rate options                                                                      |
| Content markers    | Timed content markers embedded in tracks for triggering events at specific playback positions (chapter breaks, instruction points)      |
| Event-driven state | All state changes, progress updates, and errors emitted as typed events for reactive UI updates                                         |
| Error recovery     | Typed error codes (load failure, playback failure, network error, decode error, permission denied) with programmatic error handling     |

### 1.2 Playback Queue

| Capability         | Description                                                                            |
| ------------------ | -------------------------------------------------------------------------------------- |
| Ordered playback   | Sequential track queue with add, remove, reorder, and clear operations                 |
| Shuffle mode       | Queue shuffle for randomized meditation playlist playback                              |
| Repeat modes       | Repeat-none, repeat-one, and repeat-all modes for continuous listening                 |
| Queue manipulation | Runtime queue modification (add tracks, remove tracks, reorder) during active playback |
| Auto-advance       | Automatic advancement to the next track when the current track completes               |
| Queue events       | Events emitted for queue changes, track transitions, and queue completion              |

### 1.3 Background Audio

| Capability           | Description                                                                                                                               |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Background playback  | Continued audio playback when the application moves to the background on mobile and desktop                                               |
| Lock screen controls | Configurable lock screen media controls (play, pause, skip forward, skip backward, seek) for controlling playback without opening the app |
| Now-playing display  | Now-playing information (title, artist, artwork, duration, progress) displayed on lock screen and system media widgets                    |
| Remote commands      | Handling of hardware media button events and system remote control commands                                                               |
| Platform abstraction | Abstract handler with web and noop implementations, plus a factory for automatic platform detection                                       |
| Artwork support      | Album art and meditation imagery display on lock screen and notification media controls                                                   |

### 1.4 Audio Session Management

| Capability            | Description                                                                                                |
| --------------------- | ---------------------------------------------------------------------------------------------------------- |
| Session categories    | Audio session category configuration (playback, ambient, solo ambient) for proper system audio behavior    |
| Interruption handling | Graceful response to audio interruptions (phone calls, alarms, other apps) with automatic pause and resume |
| Audio route changes   | Detection and response to audio route changes (headphones connected/disconnected, Bluetooth switch)        |
| Focus state tracking  | Audio focus state management (gained, lost, lost transiently, ducked) for multi-app audio coordination     |
| Platform abstraction  | Web and noop audio session manager implementations with automatic platform selection                       |

### 1.5 Multi-Layer Audio Mixing

| Capability            | Description                                                                                                                           |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Layer types           | Four audio layer types: voice (guided instruction), background music, ambient sounds, and effects                                     |
| Per-layer volume      | Independent volume control for each audio layer                                                                                       |
| Crossfade transitions | Smooth crossfade transitions between tracks with configurable duration and curve                                                      |
| Ducking               | Automatic volume reduction (ducking) of background layers when voice guidance is active, with configurable duck level and fade timing |
| Volume automation     | Time-based volume automation with automation points for programmatic volume changes over time                                         |
| Layer fade            | Per-layer fade in and fade out with configurable duration for smooth layer transitions                                                |
| Mixer events          | Events emitted for all mixer state changes, layer additions, removals, and volume adjustments                                         |

### 1.6 Audio Visualization

| Capability               | Description                                                                                            |
| ------------------------ | ------------------------------------------------------------------------------------------------------ |
| Frequency analysis       | Real-time audio frequency spectrum analysis for visual effects synchronized to playback                |
| Beat detection           | Beat detection algorithm for rhythmic visual effects during music playback                             |
| Standard frequency bands | Pre-defined frequency band segmentation (sub-bass, bass, low-mid, mid, high-mid, presence, brilliance) |
| Utility functions        | Helper functions for frequency-to-decibel conversion, bin-to-frequency mapping, and band selection     |
| Configurable resolution  | Adjustable FFT size and smoothing for balancing visualization detail against performance               |

### 1.7 Audio Caching

| Capability                 | Description                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------- |
| Cache management           | Audio file caching with configurable size limits and automatic eviction of least-used entries |
| Preloading                 | Intelligent preloading of upcoming tracks based on queue position for seamless transitions    |
| Service Worker integration | Browser Service Worker cache adapter for web-based audio caching with offline support         |
| Cache statistics           | Cache hit rate, size, and entry count statistics for monitoring cache effectiveness           |
| Download progress          | Per-file download progress reporting during cache population                                  |

### 1.8 Adaptive Streaming

| Capability                 | Description                                                                                  |
| -------------------------- | -------------------------------------------------------------------------------------------- |
| Network quality monitoring | Real-time network quality assessment using latency, bandwidth, and packet loss measurements  |
| Adaptive bitrate selection | Automatic audio quality adjustment based on current network conditions                       |
| Buffer management          | Buffer health monitoring with segment-level tracking and starvation prevention               |
| Streaming sessions         | Session-level streaming state management with quality history and performance metrics        |
| Configurable thresholds    | Customizable quality switching thresholds for balancing audio quality against buffering risk |

---

## 2. Meditation Timer

### 2.1 Core Timer

| Capability          | Description                                                                                                             |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Countdown timer     | Precise countdown timer with configurable duration from 1 minute to 60+ minutes                                         |
| Multi-phase support | Three-phase timer structure: preparation (pre-meditation), meditation (main session), and wind-down (closing)           |
| Phase transitions   | Automatic phase advancement with distinct events for each phase change                                                  |
| Tick events         | Configurable tick interval for real-time UI updates of elapsed time, remaining time, and progress percentage            |
| State machine       | Rigorous state management (idle, preparing, running, paused, winding down, completed) with valid transition enforcement |
| Session tracking    | Automatic session data accumulation recording actual pause time, active time, and total time                            |

### 2.2 Timer Presets

| Capability         | Description                                                                                           |
| ------------------ | ----------------------------------------------------------------------------------------------------- |
| 9 built-in presets | Pre-configured timer durations: 1, 3, 5, 10, 15, 20, 30, 45, and 60 minutes                           |
| Preset categories  | Presets organized into quick (1-5 min), standard (10-20 min), and extended (30-60 min) collections    |
| Custom presets     | User-defined custom presets with full timer configuration including phases, bells, and ambient sounds |
| Preset manager     | Preset management system for creating, storing, retrieving, and organizing presets                    |
| Preset by ID       | Direct preset lookup by unique identifier for programmatic access                                     |

### 2.3 Bell System

| Capability             | Description                                                                                         |
| ---------------------- | --------------------------------------------------------------------------------------------------- |
| 6 built-in bell sounds | Tibetan bowl, singing bowl, gong, temple bell, chime, and soft tone bell sounds                     |
| Bell triggers          | Configurable bell triggers: start of session, end of session, interval marks, and phase transitions |
| Interval bells         | Recurring bells at specified time intervals throughout the meditation (e.g., every 5 minutes)       |
| Bell volume            | Independent bell volume control separate from ambient sound and master volume                       |
| Bell player            | Dedicated bell playback engine with event emissions for bell ring events                            |

### 2.4 Ambient Sound System

| Capability         | Description                                                                                        |
| ------------------ | -------------------------------------------------------------------------------------------------- |
| 7 built-in sounds  | Rain, ocean waves, forest sounds, fire crackling, white noise, pink noise, and brown noise         |
| Multi-layer mixing | Layered ambient sound playback with independent volume control per layer                           |
| 3 curated mixes    | Pre-built ambient sound mixes: Peaceful (rain + forest), Focus (brown noise), Sleep (ocean + rain) |
| Custom mixes       | User-defined ambient mixes combining any available sounds at custom volume levels                  |
| Ambient categories | Sound categorization into nature, noise, and mix categories for organized browsing                 |

### 2.5 Background Timer Operation

| Capability                 | Description                                                                                     |
| -------------------------- | ----------------------------------------------------------------------------------------------- |
| Background continuation    | Timer continues running when the application is backgrounded or the screen is locked            |
| Timer notifications        | System notification display showing remaining time and timer status while in background         |
| Notification configuration | Customizable notification title, body, and update interval for background timer display         |
| Platform abstraction       | Web and noop background handler implementations with factory-based automatic platform selection |

### 2.6 Haptic Feedback

| Capability              | Description                                                                                   |
| ----------------------- | --------------------------------------------------------------------------------------------- |
| Timer event haptics     | Haptic feedback patterns for timer start, bell rings, phase changes, and completion           |
| Intensity levels        | Configurable haptic intensity levels (light, medium, heavy) for personalized tactile feedback |
| Haptic types            | Multiple haptic feedback types including impact, notification, and selection haptics          |
| Platform abstraction    | Web Vibration API and noop haptic manager implementations with factory selection              |
| Per-event configuration | Independent haptic enable/disable and intensity settings for each timer event type            |

---

## 3. Breathing Exercise Engine

### 3.1 Core Exercise Runner

| Capability        | Description                                                                                                 |
| ----------------- | ----------------------------------------------------------------------------------------------------------- |
| Phase progression | Automatic progression through breathing phases: inhale, hold after inhale, exhale, and rest after exhale    |
| Cycle tracking    | Cycle counting with per-cycle and per-phase progress reporting                                              |
| Completion modes  | Two completion modes: cycle-based (target number of cycles) and duration-based (target total time)          |
| State management  | Exercise lifecycle states (idle, running, paused, completed) with typed event emissions for all transitions |
| Tick events       | High-frequency tick events for smooth UI animation updates during breathing exercises                       |
| Countdown events  | Pre-phase countdown events for preparing the user for upcoming phase transitions                            |
| Error handling    | Typed error events for exercise configuration problems and runtime issues                                   |

### 3.2 Built-in Breathing Patterns (10)

| Pattern            | Description                                                                                                       |
| ------------------ | ----------------------------------------------------------------------------------------------------------------- |
| Box Breathing      | Equal-duration four-phase breathing (4-4-4-4 seconds) used by military and first responders for stress management |
| 4-7-8 Breathing    | Dr. Andrew Weil's relaxation technique with 4-second inhale, 7-second hold, 8-second exhale for sleep and anxiety |
| Coherent Breathing | 5.5-second inhale and exhale cycle optimized for heart rate variability improvement                               |
| Energizing Breath  | Quick-cycle breathing pattern designed to increase alertness and energy                                           |
| Calming Breath     | Extended exhale pattern that activates the parasympathetic nervous system for calm                                |
| 2:1 Ratio          | Two-to-one inhale-to-exhale ratio breathing for balanced relaxation                                               |
| Alternate Nostril  | Nadi Shodhana pranayama pattern for balancing left and right brain hemispheres                                    |
| Wim Hof Method     | Wim Hof breathing protocol with rapid breathing cycles followed by retention                                      |
| Sleep Breathing    | Breathing pattern specifically optimized for falling asleep with progressively slower cycles                      |
| Focus Breathing    | Breathing rhythm designed to enhance concentration and mental clarity                                             |

### 3.3 Pattern Organization

| Capability         | Description                                                                             |
| ------------------ | --------------------------------------------------------------------------------------- |
| Pattern categories | Patterns organized into beginner, relaxation, focus, energy, and meditation collections |
| Difficulty ratings | Each pattern rated by difficulty level for progressive skill building                   |
| Pattern lookup     | Find patterns by ID, category, or difficulty for programmatic pattern selection         |
| Category browsing  | Browse pattern collections by purpose (relaxation, focus, energy) for guided selection  |

### 3.4 Custom Pattern Builder

| Capability               | Description                                                                                                     |
| ------------------------ | --------------------------------------------------------------------------------------------------------------- |
| Fluent builder API       | Chain-based pattern builder for constructing custom breathing patterns phase by phase                           |
| Phase configuration      | Per-phase duration, label, and instruction text customization                                                   |
| Ratio-based creation     | Pattern creation from simple ratio specifications (e.g., 4:7:8 for the phases)                                  |
| Convenience constructors | Quick-create functions for common pattern types (box breathing, coherent breathing) with customizable durations |
| Pattern validation       | Automatic validation that custom patterns have valid phase durations and configurations                         |

### 3.5 Visualization

| Capability               | Description                                                                                               |
| ------------------------ | --------------------------------------------------------------------------------------------------------- |
| Real-time animation data | Continuous visualization state output with progress percentage and easing function application            |
| Easing functions         | Built-in easing functions (linear, ease-in, ease-out, ease-in-out) for natural breathing animation curves |
| Phase colors             | Customizable color assignments per breathing phase for visual phase distinction                           |
| Color interpolation      | Smooth color interpolation between phases for gradient-style visual transitions                           |
| Visualization provider   | Dedicated visualization data provider that transforms exercise state into animation-ready output          |
| Platform-agnostic        | Visualization data suitable for any rendering target (circle, sphere, bar, wave, etc.)                    |

### 3.6 Audio Guidance

| Capability         | Description                                                                             |
| ------------------ | --------------------------------------------------------------------------------------- |
| Phase cues         | Audio cues synchronized with breathing phase transitions (inhale, hold, exhale prompts) |
| Guidance player    | Dedicated audio guidance player that plays cues at phase boundaries                     |
| Audio cue types    | Multiple audio cue types for different phases and transition points                     |
| Configurable audio | Enable/disable and volume control for audio guidance independent of other audio         |

### 3.7 Haptic Feedback

| Capability                 | Description                                                                            |
| -------------------------- | -------------------------------------------------------------------------------------- |
| Phase-synchronized haptics | Haptic feedback patterns timed to breathing phase transitions for eyes-closed practice |
| Intensity configuration    | Per-phase haptic intensity customization for distinguishing phases by touch            |
| Haptic manager             | Dedicated breathing haptic manager with event-based activation                         |

### 3.8 Session History

| Capability         | Description                                                                                               |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| Session recording  | Automatic recording of completed breathing exercise sessions with pattern, duration, and cycle count      |
| History storage    | Multiple storage backends (in-memory, localStorage) for breathing session persistence                     |
| History statistics | Aggregate statistics across all breathing sessions including total time, favorite patterns, and frequency |
| Session retrieval  | Query historical sessions with filtering by date range and pattern type                                   |

---

## 4. Session Management

### 4.1 Session Lifecycle

| Capability            | Description                                                                                          |
| --------------------- | ---------------------------------------------------------------------------------------------------- |
| Session creation      | Create meditation sessions with typed configuration (audio, timing, notification settings)           |
| Session types         | Support for multiple session types: guided, unguided, breathing, timer, and body scan meditations    |
| Lifecycle management  | Complete state machine: create, start, pause, resume, complete, and abandon operations               |
| Interruption tracking | Recording of session interruptions with categorized reasons (phone call, notification, manual pause) |
| Pause tracking        | Detailed pause tracking with individual pause start/end times and accumulated pause duration         |
| Completion status     | Granular completion status reporting (completed, abandoned, interrupted) with completion percentage  |
| Session results       | Rich session result objects containing timing data, interruption history, and completion metrics     |
| Event emissions       | Typed events for every session state transition enabling reactive UI and analytics integration       |

### 4.2 Session Persistence

| Capability                | Description                                                                           |
| ------------------------- | ------------------------------------------------------------------------------------- |
| Multiple storage backends | Three interchangeable storage backends: in-memory, localStorage, and IndexedDB        |
| Auto-save                 | Automatic session state persistence at configurable intervals for crash recovery      |
| Session recovery          | Restore interrupted sessions from persistent storage to continue after app restart    |
| Persistence manager       | Dedicated persistence manager coordinating save operations with configurable behavior |
| Factory functions         | Convenience factory functions for creating storage backends and persistence managers  |

### 4.3 Session Analytics

| Capability           | Description                                                                                              |
| -------------------- | -------------------------------------------------------------------------------------------------------- |
| Event recording      | Analytics event recording for session lifecycle events (start, pause, resume, complete, abandon)         |
| Aggregated analytics | Computed aggregate analytics including total sessions, total time, average duration, and completion rate |
| Pluggable trackers   | Pluggable analytics tracker interface for integration with external analytics services                   |
| Console tracker      | Built-in console analytics tracker for development and debugging                                         |
| In-memory storage    | In-memory analytics storage for testing and server-side rendering environments                           |

### 4.4 Session Scheduling

| Capability                | Description                                                                                |
| ------------------------- | ------------------------------------------------------------------------------------------ |
| Recurring schedules       | Create recurring meditation schedules with day-of-week recurrence patterns                 |
| Reminder notifications    | Configurable notification reminders before scheduled sessions                              |
| Upcoming session queries  | Query upcoming scheduled sessions within a date range for calendar display                 |
| Schedule CRUD             | Full create, read, update, delete operations for scheduled sessions                        |
| iCal generation           | Export meditation schedules in iCal format for integration with calendar applications      |
| Multiple storage backends | In-memory and localStorage storage backends for schedule persistence                       |
| Recurrence logic          | Day-of-week based recurrence with time-of-day specification for weekly meditation routines |
| Trigger evaluation        | Evaluate scheduled sessions against current time to determine which reminders should fire  |

---

## 5. Progress and Achievement Tracking

### 5.1 Session Recording

| Capability        | Description                                                                                                   |
| ----------------- | ------------------------------------------------------------------------------------------------------------- |
| Session intake    | Record completed meditation sessions with type, duration, start time, end time, and completion status         |
| Automatic updates | Recording a session automatically updates streaks, checks for new achievements, and evaluates milestones      |
| Combined results  | Single recording operation returns updated streak data, newly unlocked achievements, and triggered milestones |
| Session history   | Query historical sessions with pagination, date range filtering, and type filtering                           |

### 5.2 Streak Tracking

| Capability         | Description                                                                            |
| ------------------ | -------------------------------------------------------------------------------------- |
| Current streak     | Real-time current streak calculation showing consecutive days of meditation practice   |
| Longest streak     | Lifetime longest streak tracking for personal record display                           |
| Timezone awareness | Streak calculation respects user timezone to correctly determine day boundaries        |
| Minimum duration   | Configurable minimum session duration for a session to count toward streak maintenance |
| Forgiveness days   | Configurable forgiveness window allowing missed days without breaking the streak       |
| Freeze tokens      | Streak freeze token system for planned breaks that preserve streak without practicing  |
| Streak events      | Events emitted for streak increases, streak breaks, and new personal records           |

### 5.3 Statistics

| Capability                | Description                                                                           |
| ------------------------- | ------------------------------------------------------------------------------------- |
| Predefined date ranges    | Built-in date ranges: today, this week, this month, this year, and all time           |
| Custom date ranges        | Arbitrary date range specification for focused statistical analysis                   |
| Time-of-day distribution  | Session distribution analysis showing which hours of the day the user meditates most  |
| Day-of-week distribution  | Session distribution across days of the week for identifying weekly patterns          |
| Session type breakdown    | Statistical breakdown by session type (guided, unguided, breathing, timer)            |
| Total and average metrics | Total session count, total meditation time, and average session duration calculations |
| Trend analysis            | Period-over-period comparison for tracking improvement over time                      |

### 5.4 Achievement System

| Capability             | Description                                                                                              |
| ---------------------- | -------------------------------------------------------------------------------------------------------- |
| Built-in achievements  | Pre-defined achievement set with diverse criteria covering session count, duration, streaks, and variety |
| Achievement categories | Achievements organized by category for grouped display (consistency, duration, exploration, mastery)     |
| Rarity tiers           | Achievement rarity classification (common, uncommon, rare, epic, legendary) for progressive difficulty   |
| Automatic evaluation   | Achievements automatically checked against criteria when new sessions are recorded                       |
| Unlock tracking        | Precise unlock timestamp and triggering session recorded for each earned achievement                     |
| Achievement events     | Events emitted when new achievements are unlocked for UI celebration triggers                            |

### 5.5 Milestone System

| Capability           | Description                                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------------------------- |
| Built-in milestones  | Pre-defined milestone definitions for significant progress markers (first session, 100 hours, 365-day streak) |
| Milestone categories | Milestone categorization for organized display and progressive goal visualization                             |
| Notification support | Milestone trigger notifications for celebrating significant accomplishments                                   |
| Progress tracking    | Percentage-based progress tracking toward next milestone with estimated completion                            |

### 5.6 Data Export

| Capability           | Description                                                                                 |
| -------------------- | ------------------------------------------------------------------------------------------- |
| Multi-format export  | Progress data export in multiple formats for backup and data portability                    |
| Selective export     | Choose which data types to include in exports (sessions, streaks, achievements, statistics) |
| Export configuration | Configurable export options controlling format, date range, and included data types         |

### 5.7 Multi-Device Sync

| Capability                     | Description                                                                                   |
| ------------------------------ | --------------------------------------------------------------------------------------------- |
| Cross-device synchronization   | Sync meditation progress data across multiple devices                                         |
| Conflict detection             | Automatic detection of conflicting data when the same session is modified on multiple devices |
| Conflict resolution strategies | Configurable conflict resolution strategies for handling sync conflicts                       |
| Sync state tracking            | Sync status tracking (synced, syncing, pending, error) for UI status display                  |
| Sync events                    | Events emitted for sync start, completion, conflict, and error states                         |

---

## 6. Offline Content Management

### 6.1 Download Queue

| Capability           | Description                                                                                        |
| -------------------- | -------------------------------------------------------------------------------------------------- |
| Priority-based queue | Download queue with priority levels (low, normal, high, critical) for ordering download importance |
| Concurrent downloads | Configurable concurrent download limit for balancing download speed against resource usage         |
| Retry logic          | Automatic retry with configurable retry count and backoff for failed downloads                     |
| Pause and resume     | Individual download and entire queue pause/resume with state preservation                          |
| Cancellation         | Download cancellation via AbortSignal with cleanup of partial downloads                            |
| Queue events         | Events for download start, progress, completion, failure, and queue state changes                  |
| Queue state tracking | Overall queue state reporting (items pending, in progress, completed, failed)                      |

### 6.2 Storage Management

| Capability                | Description                                                                                                    |
| ------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Multiple storage backends | Three storage backends: IndexedDB (large datasets), localStorage (simple persistence), and in-memory (testing) |
| Storage limits            | Configurable storage limits with maximum total size and maximum item count enforcement                         |
| Cleanup strategies        | Automatic storage cleanup with configurable strategies (LRU, oldest first, largest first) for reclaiming space |
| Storage info              | Real-time storage usage information (used space, available space, item count)                                  |
| Content metadata tracking | Downloaded content metadata management with local file path, download date, and version tracking               |

### 6.3 Content Versioning

| Capability         | Description                                                                                                          |
| ------------------ | -------------------------------------------------------------------------------------------------------------------- |
| Version tracking   | Content version tracking with semantic versioning (major.minor.patch) for each downloaded item                       |
| Version comparison | Version comparison utilities for determining if updates are available                                                |
| Update policies    | Configurable update policies (always update, only major updates, manual only) for controlling when downloads refresh |
| Manifest fetching  | Remote content manifest fetching to check for available updates across the content catalog                           |
| Version filtering  | Version range filtering for finding content within specific version ranges                                           |
| Version utilities  | Helper functions for creating, incrementing, validating, sorting, and comparing version strings                      |

### 6.4 Smart Download Suggestions

| Capability                 | Description                                                                                         |
| -------------------------- | --------------------------------------------------------------------------------------------------- |
| Behavior-based suggestions | Download recommendations based on user listening patterns and preferences                           |
| Usage statistics analysis  | Content usage statistics (play count, completion rate, last played) feeding into suggestion scoring |
| Configurable scoring       | Adjustable scoring weights for different suggestion factors (popularity, recency, user affinity)    |
| Suggestion reasons         | Each suggestion includes a human-readable reason explaining why it was recommended                  |
| Quick suggestions          | Fast suggestion generation for immediate UI display without full catalog analysis                   |
| Catalog analysis           | Full catalog analysis scoring all available content against user preferences and behavior           |

### 6.5 Network State Detection

| Capability               | Description                                                                             |
| ------------------------ | --------------------------------------------------------------------------------------- |
| Online/offline detection | Automatic detection of network connectivity state changes                               |
| Connection type          | Network connection type identification (WiFi, cellular, Ethernet, unknown)              |
| Network preferences      | Configurable download behavior based on connection type (WiFi-only, allow metered data) |
| Metered data policies    | Respect for metered data connections with configurable policies per priority level      |

### 6.6 Content Integrity

| Capability            | Description                                                                          |
| --------------------- | ------------------------------------------------------------------------------------ |
| Checksum verification | Downloaded content integrity verification using checksums to detect corruption       |
| Automatic resume      | Resume interrupted downloads automatically on application startup                    |
| Content verification  | Pluggable content verifier interface for custom integrity checking implementations   |
| File cleanup          | Managed file deletion with proper cleanup of associated metadata and storage records |

---

## 7. Cross-Platform Architecture

### 7.1 Platform Abstraction Pattern

| Capability             | Description                                                                                                 |
| ---------------------- | ----------------------------------------------------------------------------------------------------------- |
| Abstract base classes  | Platform-interacting features defined as abstract base classes with clear interface contracts               |
| Web implementations    | Browser-specific implementations using Web Audio API, Media Session API, Vibration API, and Service Workers |
| Noop implementations   | No-operation implementations for testing, server-side rendering, and unsupported platforms                  |
| Factory functions      | Automatic platform detection factory functions that select the correct implementation at runtime            |
| React Native readiness | Architecture designed for React Native implementations to be added as platform-specific adapters            |

### 7.2 Event System

| Capability          | Description                                                                                            |
| ------------------- | ------------------------------------------------------------------------------------------------------ |
| Typed events        | All libraries use typed event emissions via eventemitter3 with discriminated union event data payloads |
| Event listeners     | Type-safe event listener registration with specific data types per event                               |
| State change events | Consistent state change event pattern across all libraries for predictable UI integration              |
| Error events        | Standardized error event pattern with typed error codes and descriptive messages                       |
| Progress events     | Normalized progress events (elapsed, remaining, percentage) for timers, downloads, and playback        |

### 7.3 Storage Backend Pattern

| Capability               | Description                                                                                    |
| ------------------------ | ---------------------------------------------------------------------------------------------- |
| In-memory storage        | Every library provides an in-memory storage backend for testing and server-side rendering      |
| localStorage storage     | Browser localStorage backends for simple client-side persistence of small datasets             |
| IndexedDB storage        | Browser IndexedDB backends for structured persistence of larger datasets (sessions, downloads) |
| Interchangeable backends | All storage backends implement the same interface for swappable persistence strategies         |
| Factory functions        | Convenience factory functions for creating pre-configured storage instances                    |

### 7.4 Type Safety

| Capability           | Description                                                                                                                    |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Branded types        | Branded types prevent accidental misuse: SessionId, TrackId, ContentId, DurationSeconds, Timestamp, Percentage, ByteSize, etc. |
| Type inference       | TypeScript type inference from configurations for compile-time safety without runtime overhead                                 |
| Discriminated unions | Event types use discriminated unions for exhaustive event handling in switch statements                                        |
| Const assertions     | Configuration defaults exported as const assertions for narrowed type inference                                                |

---

## 8. React Integration

### 8.1 Hook Factory Pattern

| Capability            | Description                                                                                                                          |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| createUse\* factories | All libraries export hook factory functions (createUsePlayer, createUseMeditationTimer, etc.) rather than direct hooks               |
| Dependency injection  | React dependency injection via setReactHooks({useState, useEffect, useCallback, useRef}) avoids requiring React as a hard dependency |
| Non-React support     | Libraries usable in non-React environments (React Native, Vue adapters, vanilla JS) since React is an optional peer dependency       |
| All-in-one factories  | Each library provides a create\*Hooks bundle function that returns all hooks for that library                                        |

### 8.2 Player Hooks

| Capability          | Description                                                                           |
| ------------------- | ------------------------------------------------------------------------------------- |
| usePlayer           | Player state, controls (play, pause, stop, seek, load), and current track information |
| usePlaybackProgress | Real-time playback progress with elapsed time, remaining time, and percentage         |
| useQueue            | Queue state and controls (add, remove, reorder, clear, skip next, skip previous)      |
| useVisualization    | Real-time audio visualization data for frequency spectrum and beat display            |
| useAudioSession     | Audio session state including interruptions and route changes                         |
| useMixer            | Multi-layer mixer state and controls (add layer, remove layer, set layer volume)      |

### 8.3 Timer Hooks

| Capability         | Description                                                                 |
| ------------------ | --------------------------------------------------------------------------- |
| useMeditationTimer | Complete timer state and controls (start, pause, resume, stop, load preset) |
| useTimerState      | Timer state observation (current phase, running status, configuration)      |
| useTimerProgress   | Real-time timer progress with elapsed, remaining, and phase progress        |
| useTimerPresets    | Access to preset library with preset selection and custom preset creation   |

### 8.4 Breathing Hooks

| Capability            | Description                                                                            |
| --------------------- | -------------------------------------------------------------------------------------- |
| useBreathingExercise  | Exercise state and controls (start, pause, resume, stop) with pattern selection        |
| useBreathingState     | Current exercise state including active phase, cycle count, and session progress       |
| useBreathingAnimation | Real-time animation data for driving breathing circle, sphere, or wave visualizations  |
| useBreathingPatterns  | Access to built-in pattern catalog with category filtering and custom pattern creation |

### 8.5 Session Hooks

| Capability         | Description                                                                                    |
| ------------------ | ---------------------------------------------------------------------------------------------- |
| useSessionManager  | Session manager state and lifecycle controls (create, start, pause, resume, complete, abandon) |
| useCurrentSession  | Current session state observation for UI display of active meditation                          |
| useSessionProgress | Real-time session progress (elapsed time, completion percentage, pause status)                 |
| useSessionState    | Session state machine observation for conditional UI rendering                                 |
| useScheduler       | Schedule management with create, update, delete, and upcoming session query                    |

### 8.6 Progress Hooks

| Capability         | Description                                                                                                |
| ------------------ | ---------------------------------------------------------------------------------------------------------- |
| useStreak          | Current streak, longest streak, and streak configuration display                                           |
| useStatistics      | Statistics for configurable date ranges with distribution breakdowns                                       |
| useAchievements    | Achievement list with unlock status, earned dates, and category filtering                                  |
| useMilestones      | Milestone list with progress percentages and notification state                                            |
| useSync            | Sync status, last sync time, and manual sync trigger                                                       |
| useProgressTracker | Combined progress tracker with session recording and all sub-feature access                                |
| Convenience hooks  | Pre-bound convenience hooks (useStreak, useStatistics, etc.) available after calling setProgressReactHooks |

### 8.7 Offline Hooks

| Capability            | Description                                                                        |
| --------------------- | ---------------------------------------------------------------------------------- |
| useOfflineManager     | Offline manager state and control for initializing and configuring offline support |
| useOfflineContent     | List of all offline-available content with metadata and status                     |
| useOfflineContentById | Single content item offline status lookup by content ID                            |
| useDownloadStatus     | Download status observation for a specific content item                            |
| useDownloadProgress   | Real-time download progress for active downloads                                   |
| useAllOfflineContent  | Complete list of all downloaded content for library display                        |
| useNetworkState       | Current network state (online/offline, connection type) for UI indicators          |
| useQueueState         | Download queue state with pending, active, and completed item counts               |
| useStorageInfo        | Storage usage information (used space, available space, item count)                |
| useSuggestions        | Smart download suggestions for recommending content to download                    |

---

## Library Summary

| Library   | Package                       | Capability Area                                                                                        |
| --------- | ----------------------------- | ------------------------------------------------------------------------------------------------------ |
| Player    | `@oshun/meditation-player`    | Audio playback, queue, background audio, session management, mixing, visualization, caching, streaming |
| Timer     | `@oshun/meditation-timer`     | Countdown timer, phases, presets, bells, ambient sounds, background operation, haptics                 |
| Breathing | `@oshun/meditation-breathing` | Breathing exercises, 10 patterns, custom builder, visualization, audio guidance, haptics, history      |
| Session   | `@oshun/meditation-session`   | Session lifecycle, persistence, analytics, scheduling, recurring reminders                             |
| Progress  | `@oshun/meditation-progress`  | Streaks, statistics, achievements, milestones, export, multi-device sync                               |
| Offline   | `@oshun/meditation-offline`   | Download queue, storage management, versioning, suggestions, network detection                         |
