# Meditation Libraries — Features and Capabilities

> The meditation libraries (`libs/meditation/`) are a suite of eight
> platform-agnostic TypeScript packages forming the shared engine layer for any
> meditation application in the Oshun monorepo. They are consumed primarily by
> the Tara and Lilith applications but are deliberately content-agnostic — any
> app that needs audio playback, timers, breathing guidance, session tracking,
> progress analytics, or offline content management can use them. The six engine
> packages ship with React hook factories, interchangeable storage backends, and
> platform abstractions that work across web browsers and React Native;
> `meditation-core` provides shared types and utilities, and
> `meditation-analytics` provides standalone event tracking.

---

This document describes what each library can do from a feature perspective —
the capabilities a product engineer or UI developer would reach for when
building a meditation experience. For type-level detail (enums, config defaults,
exact API signatures), see `specifications.md`. For the architectural rationale
behind the design choices, see `architecture.md`.

The built-in data counts in this document (10 breathing patterns, 12 timer
presets, 6 bell constants, 7 ambient-sound constants with 3 curated mixes, 26
achievements, 26 milestones, and the 0.85×–1.25× playback-rate policy) have been
verified against the source code. Tara owns the App Store-safe meditation
product and Lilith owns its broader consciousness experience surfaces; both are
consumers of these shared engine libraries.

---

## 1. Audio Player Engine

**Package:** `@oshun/meditation-player`

The audio player engine handles all sound reproduction in meditation apps:
streaming and local audio playback, multi-layer audio mixing (voice over
background music and ambient sounds), real-time visualization, adaptive bitrate
streaming, audio session management, and integration with the operating system's
media controls.

### 1.1 Core Playback

- **Track loading and formats** — Load audio tracks from URLs; the supported
  formats are MP3, AAC, M4A, OGG, WAV, and FLAC, with four quality levels (low,
  medium, high, lossless) so a track can ship multiple sources to balance audio
  fidelity against bandwidth usage.
- **Playback controls** — Play, pause, seek, stop, and volume operations with
  all state changes emitted as typed events for reactive UI updates.
- **Playback rate** — Variable-speed playback constrained to a
  quality-preserving 0.85×–1.25× range in 0.05× steps, with pitch preservation
  always requested from the media backend. Guided meditation narration degrades
  quickly outside this narrow window — breath cues, room tone, and vocal
  formants stop sounding natural — so the shared
  `@oshun/contracts/tara/playback-rate` policy rejects rates outside it. Useful
  for slightly slowing familiar content while learning a technique (0.90×) or
  speeding it up (1.15×).
- **Seeking and resume** — Seek to any position within a loaded track with
  immediate position update. Resume position is persisted so users return to
  where they left off after closing the app.
- **Content markers** — Timed markers embedded in audio tracks trigger events at
  specific playback positions, enabling chapter navigation and synchronized UI
  state changes (e.g., revealing a body-scan diagram as that region is mentioned
  in the audio).
- **Error recovery** — Typed error codes (load failure, playback failure,
  network error, decode error, permission denied) allow programmatic error
  handling so the UI can display appropriate messages or retry automatically.

### 1.2 Playback Queue

- **Ordered queue** — Manage an ordered list of tracks for sequential playback,
  with add, remove, reorder, and clear operations operable during active
  playback without interruption.
- **Shuffle mode** — Randomizes queue ordering for random meditation selection
  from a collection.
- **Repeat modes** — Repeat-none, repeat-one, and repeat-all. Repeat-one is
  useful for ambient music tracks intended to loop indefinitely during sleep.
- **Auto-advance** — Automatically advances to the next queued track when the
  current track completes. Queue events notify listeners of track transitions
  and queue completion.

### 1.3 Background Audio

Background playback is essential to meditation apps: users typically close their
eyes and do not actively watch the screen, so audio must continue when the app
is minimized or the screen locks.

- **Background playback** — Audio continues when the app is minimized, the
  screen is locked, or the user switches to another app.
- **Lock screen controls** — The device lock screen displays now-playing
  information (title, teacher, artwork, elapsed and remaining time) and provides
  playback controls (play/pause, skip) without requiring the user to unlock the
  device. Implemented via the Web Media Session API on browsers, iOS MediaPlayer
  framework, and Android MediaSession on native.
- **Remote command handling** — Hardware media buttons (earphone play/pause
  button, Bluetooth remote controls) are intercepted and routed to the player.
- **Platform abstraction** — A background handler abstract base class with web
  and noop (no-operation) implementations. A factory function automatically
  selects the correct implementation at runtime. React Native implementations
  can be slotted in as platform-specific adapters.

### 1.4 Audio Session Management

Audio session management ensures the app plays nicely with other audio on the
device — pausing music when a call arrives, ducking when Siri activates, and
never surprising the user with sudden loud audio.

- **Session categories** — The audio session category is configured to
  `playback` so the OS treats the app's audio as primary media (pausing other
  audio when this starts, resuming it when this stops).
- **Interruption handling** — When an audio interruption occurs (incoming phone
  call, Siri activation, another app taking audio focus), the player pauses and
  records the interruption. When the interruption ends, playback resumes
  automatically.
- **Audio route changes** — When headphones are disconnected (unplugged or
  Bluetooth device turned off), playback pauses automatically to prevent sudden
  loud audio from the device speakers — a critical privacy and comfort feature.
- **Focus state tracking** — Audio focus states (gained, lost, lost transiently,
  ducked) are tracked and emitted as events, enabling UI indicators of focus
  status and correct behavior in multi-app scenarios.

### 1.5 Multi-Layer Audio Mixing

Multi-layer mixing enables guided meditations to play simultaneously with
background music and ambient sounds, with voice taking precedence. A user can
adjust the ambient rain independently of the instructor's voice without either
interrupting the session.

- **Layer types** — Four audio layer types: voice (guided instruction
  narration), background music, ambient sounds (nature/noise), and effects
  (bells, chimes).
- **Per-layer volume** — Independent volume control for each layer. A user can
  turn down the ambient rain while keeping the instructor's voice at full
  volume.
- **Ducking** — When the voice layer becomes active, background and ambient
  layers automatically reduce volume (duck) so the instructor's voice is clearly
  audible. The duck level and fade timing are configurable.
- **Volume automation** — Time-based volume automation with automation points
  allows programmatic volume changes over time — fading in gentle music at the
  start of a session and fading out at the end.
- **Crossfade transitions** — Smooth crossfade between tracks on any layer with
  configurable duration and easing curve, preventing jarring audio cuts.
- **Layer fade** — Per-layer fade-in and fade-out with configurable duration for
  smooth layer transitions.

### 1.6 Audio Visualization

Audio visualization gives UI animations a data source that is always in sync
with what the user hears, rather than looping pre-baked animations on a fixed
timer.

- **Frequency analysis** — Real-time Fast Fourier Transform (FFT) analysis of
  the audio output produces frequency domain data. This drives waveform and
  spectrum visualizations synchronized to what the user hears.
- **Beat detection** — A beat detection algorithm identifies rhythmic pulses in
  music, enabling UI animations that pulse in time with the music.
- **Standard frequency bands** — A `getStandardFrequencyBands()` helper exposes
  seven named frequency ranges (sub-bass 20–60 Hz, bass 60–250 Hz, low-mid
  250–500 Hz, mid 500–2000 Hz, upper-mid 2000–4000 Hz, presence 4000–6000 Hz,
  brilliance 6000–20000 Hz) so common visualization effects do not require
  consumers to write FFT math.
- **Configurable resolution** — Adjustable FFT size and smoothing coefficient
  balance visualization detail against CPU usage.

### 1.7 Audio Caching

Caching prevents buffering pauses during session playback and ensures recently
used content is available without a network round-trip.

- **Cache management** — Downloaded audio files are cached locally with
  configurable size limits and automatic **LRU** (least-recently-used) eviction
  when the cache is full.
- **Preloading** — Upcoming queue tracks are preloaded into cache based on queue
  position, ensuring seamless transitions without buffering pauses.
- **Service Worker integration** — On the web, a Service Worker cache adapter
  stores audio files in the browser cache so they are available when the device
  goes offline.
- **Cache statistics** — Cache hit rate, total size, and entry count are
  reported for monitoring and storage management UI.

### 1.8 Adaptive Streaming

Adaptive streaming ensures playback continues smoothly even on weak connections
by downgrading audio quality before a buffer stall occurs.

- **Network quality monitoring** — Real-time network quality assessment measures
  latency, bandwidth, and packet loss to determine current connection health.
- **Adaptive bitrate selection** — Audio quality (bitrate) adjusts automatically
  based on network conditions. If the connection degrades, the player switches
  to a lower bitrate to prevent buffering. When conditions improve, it switches
  back up.
- **Buffer management** — Buffer health is monitored at the segment level.
  Buffer starvation (running out of buffered audio) triggers preemptive quality
  reduction before playback is interrupted.
- **Configurable thresholds** — Quality switching thresholds are configurable to
  tune the balance between audio quality and buffering risk per deployment.

---

## 2. Meditation Timer

**Package:** `@oshun/meditation-timer`

The timer library provides a precise countdown timer with multi-phase structure,
configurable bells, ambient sound mixing, background operation, and haptic
feedback. It is used in Tara's timer mode and as the timing backbone for
unguided sessions.

### 2.1 Core Timer

- **Drift-corrected countdown** — The timer compares against wall-clock
  timestamps rather than accumulating tick increments, compensating for
  JavaScript timer imprecision over 30–60+ minute sessions. Without drift
  correction, a 60-minute timer could finish seconds early or late.
- **Multi-phase structure** — Three phases: Preparation (an optional lead-in
  countdown before the main session, giving the user time to settle), Meditation
  (the main countdown), and Wind-down (a gentle ending period before the session
  completes). Each phase emits distinct events and has independent
  configuration.
- **State machine** — Rigorous state management enforces valid transitions: Idle
  → Preparing → Running → Paused → Winding Down → Completed. Invalid transitions
  are rejected with typed errors.
- **Session tracking** — The timer accumulates actual active time, pause time,
  and total elapsed time throughout the session, producing a complete session
  record at completion.

### 2.2 Timer Presets

Presets give users a one-tap starting point for the most common session lengths
without requiring manual configuration. There are 12 built-in presets organized
into five collections:

| Collection | Presets                                                                                             |
| ---------- | --------------------------------------------------------------------------------------------------- |
| Quick      | Mindful Moment (1 min), Quick Break (3 min), Short Session (5 min)                                  |
| Standard   | Standard Session (10 min), Extended Session (15 min), Deep Practice (20 min), Long Session (30 min) |
| Extended   | Extended Practice (45 min), Full Hour (60 min)                                                      |
| Pomodoro   | Focus Work (25 min), Short Break (5 min)                                                            |
| Sleep      | Sleep Timer (30 min, no ending bell)                                                                |

Each preset carries a full timer configuration — preparation/wind-down phases,
bell choices, and recurring interval bells (the 20-minute preset rings a soft
chime every 10 minutes, the hour preset every 15). The nine single-duration
presets (1/3/5/10/15/20/30/45/60 minutes) are re-exported by name from the
package entry point; the Pomodoro and Sleep presets are part of the full
`ALL_PRESETS` collection. `createCustomPreset()` builds user-defined presets
with configuration overrides, and a `PresetManager` tracks custom presets and
favorites.

### 2.3 Bell System

Bells are non-verbal markers that orient the practitioner to elapsed time
without breaking concentration. Six built-in bell-sound constants are provided:
Tibetan Bowl, Singing Bowl, Gong, Temple Bell, Chime, and Soft Tone. The
`BellType` union additionally allows `nature-chime`, `crystal-bowl`, `zen-bell`,
a plain `bell`, and `custom`. Each constant carries its own volume and fade-out
duration.

- **Bell trigger types** — Five triggers: start of session, end of session,
  interval marks (every N minutes during the session), a warning bell before the
  end, and a preparation-end bell.
- **Interval bells** — A 30-minute session might have interval bells every 10
  minutes, allowing practitioners to track elapsed time without checking the
  screen.
- **Independent volume** — Bell volume is controlled separately from ambient
  sound volume and master volume.
- **Preview** — Bell sounds can be previewed before starting so users choose
  their preferred bell before settling in.

### 2.4 Ambient Sound System

The ambient sound system allows background soundscapes to accompany a timer
session — rain, ocean waves, or binaural beats — with multi-layer mixing so
users can combine sounds to their preference.

Seven built-in ambient-sound constants are provided: Rain, Ocean, Forest, Fire,
White noise, Pink noise, Brown noise. These are the most common picks from a
broader 27-value sound-type catalog (which also covers light/heavy rain,
thunderstorm, ocean waves, river, stream, waterfall, birds, crickets, wind,
campfire, coffee shop, city, singing bowls, Om, temple, and alpha/theta/delta
binaural beats).

- **Multi-layer mixing** — Multiple ambient sounds play simultaneously with
  per-layer volume control, enabling combinations like ocean waves + white noise
  or rain + forest. Up to eight concurrent layers are supported.
- **Three curated mixes** — Peaceful (rain + singing bowls), Focus (brown noise
  - fire), Sleep (ocean + delta binaural). One-tap ambient setups for the most
    common use cases.
- **Custom mixes** — Users build their own named mixes from the current layers
  via `createMixFromCurrent`, and the timer can store a mix in a preset for
  reuse.

### 2.5 Background Timer Operation

Like the audio player, the timer must continue running when the user's screen
locks or the app is backgrounded — the whole point of a meditation timer is that
the user can put the phone down.

- **Background continuation** — The timer continues running when the app is
  backgrounded or the device screen is locked, using platform-specific
  background task mechanisms.
- **System notifications** — A persistent notification displays the remaining
  time and timer status while the app is in the background, so the user can
  glance at the notification bar for a time check without opening the app.
- **Platform abstraction** — Web and noop background handler implementations
  with automatic factory-based selection.

### 2.6 Haptic Feedback

Haptic feedback lets practitioners receive phase cues through vibration alone,
eyes closed, without audio — useful in shared environments or for those who
practice without sound.

- **Haptic patterns** — Configurable vibration patterns for timer events: start,
  bell rings, phase changes, completion.
- **Intensity levels** — Light, medium, heavy haptic intensity for each event,
  allowing fine-tuned tactile experience.
- **Haptic types** — Impact (physical collision feel), notification (alert
  feel), and selection (light tap feel) haptic types.
- **Platform abstraction** — Web Vibration API and noop implementations. React
  Native implementations attach to the platform haptic engine.

---

## 3. Breathing Exercise Engine

**Package:** `@oshun/meditation-breathing`

The breathing engine runs controlled breathing exercises with precise phase
timing, real-time visual and haptic guidance, and support for custom patterns.
It is the foundation for Tara's breathing exercises section.

### 3.1 Core Exercise Runner

The exercise runner advances through phases automatically and emits
high-frequency tick events that drive smooth, 60 fps UI animations.

- **Phase progression** — The engine advances through breathing phases
  automatically. The phase vocabulary is `inhale`, `hold-in` (hold after
  inhale), `exhale`, `hold-out` (hold after exhale), and `rest`; each phase has
  a configurable duration, label, and optional instruction text. A pattern
  defines whichever subset of phases it needs.
- **Cycle tracking** — Counts completed breath cycles with per-cycle events
  enabling cycle milestone notifications (e.g., "halfway there" at 25 cycles).
- **Completion modes** — Cycle-based (stop after N cycles), duration-based (stop
  after N minutes), or manual (continue until manually stopped).
- **State management** — Lifecycle states: Idle → Running → Paused → Completed.
  All transitions emit typed events.
- **High-frequency tick events** — Sub-second tick events provide smooth
  animation data for the breathing visualization UI, enabling fluid circle
  expansion/contraction at 60 fps.
- **Countdown events** — Pre-phase countdown events fire before each phase
  transition, giving the user a brief warning so they can prepare for the
  inhale/exhale change.

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

The engine ships with 10 carefully curated patterns, each with documented
physiological rationale so the feature is not just a set of arbitrary timers.

**Box Breathing (4-4-4-4)** — Four equal phases of 4 seconds each. Used by Navy
SEALs and first responders for rapid stress management and grounding under
pressure. The equal-duration "box" shape gives the technique its name.

**4-7-8 Breathing** — Developed by Dr. Andrew Weil, based on pranayama
techniques. 4-second inhale, 7-second breath hold, 8-second exhale. The extended
hold allows oxygen to diffuse to more tissues; the long exhale activates the
vagus nerve for deep relaxation and sleep onset.

**Coherent Breathing (5-0-5-0)** — Equal 5-second inhale and exhale (5 breaths
per minute) for heart-brain coherence. A breathing frequency near 0.1 Hz
maximizes **HRV** (heart rate variability) — a key indicator of autonomic
nervous system health and emotional regulation.

**Energizing Breath (2-0-4-0)** — A quick 2-second inhale and slower 4-second
exhale to boost energy and alertness — a caffeine-free morning wake-up routine.

**Calming Breath (4-0-2-0)** — A long 4-second inhale and quick 2-second exhale
to rapidly soothe the nervous system, effective for acute stress.

**2:1 Ratio (4-0-8-0)** — A 4-second inhale and 8-second exhale (a 1:2
inhale-to-exhale ratio), deeply engaging the **parasympathetic** ("rest and
digest") branch of the autonomic nervous system for stress recovery.

**Alternate Nostril (Nadi Shodhana)** — A six-phase visualization of the
traditional **pranayama** (yogic breath control) practice: inhale left, hold,
exhale right, inhale right, hold, exhale left (each phase 4 seconds). Believed
in yogic tradition to balance the nadis (energy channels) on each side of the
body, promoting mental clarity and balance.

**Wim Hof Power Breathing** — A single power breath is a fast 2-second inhale
and 2-second exhale; the technique's protocol (described in the pattern's
instructions) is 30 such breaths followed by an exhale hold and a 15-second
recovery hold, repeated for three rounds. Developed by Dutch extreme athlete Wim
Hof, it raises blood oxygen while lowering CO2. Marked an advanced pattern.

**Sleep Breathing (4-7-8-2)** — A gentle bedtime variant of 4-7-8 with a short
2-second post-exhale rest, guiding the nervous system toward sleep onset.

**Focus Breathing (4-2-4-2)** — Balanced 4-second inhale and exhale with short
2-second holds between them; the moments of stillness enhance sustained
concentration during work or study.

### 3.3 Pattern Organization and Discovery

Patterns are organized into five collections: Beginner, Relaxation, Focus,
Energy, and Meditation. Each pattern carries a difficulty rating for progressive
skill building. Lookup functions find patterns by ID, category, or difficulty.

### 3.4 Custom Pattern Builder

The `BreathingPatternBuilder` fluent API constructs custom patterns phase by
phase:
`createPatternBuilder().name('My Pattern').inhale(5).holdIn(2).exhale(7) .holdOut(0).build()`.
The hold and rest methods skip any phase with a zero-second duration. A
`fromRatio(inhale, holdIn, exhale, holdOut)` shortcut and a
`createPatternFromRatio` factory build a pattern from a four-part ratio, and
`repeat(n)` repeats the accumulated phases. Convenience constructors
`createBoxBreathing(seconds)` and `createCoherentBreathing(seconds)` produce
those two patterns at a custom phase length. `build()` throws if no phases have
been added.

### 3.5 Visualization

Because the breathing visualization must update at display refresh rate (60
fps), the `VisualizationProvider` outputs a rich state snapshot on every tick
rather than just phase and progress values.

- **Real-time animation data** — Continuous output: current phase, phase
  progress (0.0–1.0), cycle progress, a breathing-circle scale value, target
  scale, opacity, hex color, rotation, pulse, the recommended easing, a label,
  and a formatted timer string. This drives a smooth expanding/contracting
  circle or sphere animation.
- **Easing functions** — Five easing curves are available — linear, ease-in,
  ease-out, ease-in-out, and sine — applied to phase progress for
  natural-feeling animation. Inhale uses ease-out, exhale uses ease-in, holds
  use linear, and rest uses sine.
- **Phase colors** — Each phase (inhale / hold / exhale / rest) is assigned a
  distinct configurable color, providing instant visual phase identification.
- **Color interpolation** — Smooth color interpolation between phase colors for
  gradient transitions at phase boundaries.
- **Platform-agnostic output** — Visualization data is renderer-agnostic: the
  same output drives CSS animations on web, Canvas/WebGL on web, and React
  Native Animated on mobile.

### 3.6 Audio Guidance

- **Phase cues** — Audio cues (spoken prompts or tonal sounds) triggered at each
  phase boundary: "Inhale," "Hold," "Exhale," "Rest."
- **Guidance player** — A dedicated audio guidance player triggers cues at phase
  transitions, synchronized with the exercise runner's phase events.
- **Configurable audio** — Audio guidance can be enabled or disabled
  independently of visual guidance. Volume is controlled separately.

### 3.7 Haptic Feedback

- **Phase-synchronized haptics** — Distinct vibration patterns at phase
  transitions allow eyes-closed, screen-free practice. A short buzz signals
  "inhale," a longer pattern signals "exhale."
- **Per-phase intensity** — Each phase can have a different haptic intensity,
  creating distinguishable tactile patterns for each breath phase.

### 3.8 Session History

- **Session recording** — Completed exercise sessions are automatically recorded
  with pattern used, duration, and cycle count.
- **Storage backends** — In-memory (testing/SSR) and localStorage persistence.
- **History statistics** — Aggregate statistics across all breathing sessions:
  total practice time, most-used patterns, practice frequency.
- **Session retrieval** — Query all sessions, today's sessions, this week's
  sessions, or sessions for a specific pattern, for history display.

---

## 4. Session Management

**Package:** `@oshun/meditation-session`

The session management library handles the lifecycle of individual meditation
sessions — creating them, tracking their state, persisting them through
interruptions, recording analytics events, and scheduling recurring sessions.

### 4.1 Session Lifecycle

- **Session types** — Ten session types: `timer`, `breathing`, `guided`,
  `ambient`, `body-scan`, `visualization`, `mindfulness`, `sleep`, `focus`, and
  `custom`, each carrying appropriate configuration metadata.
- **State machine** — Sessions move through `idle`, `preparing`, `active`,
  `paused`, `completing`, `completed`, `cancelled`, and `interrupted` states.
  Each pause records its timestamp and duration; each interruption records a
  categorized reason (phone call, alarm, notification, app backgrounded, low
  battery, connection lost, and others).
- **Interruption tracking** — Each interruption is recorded with its reason,
  timestamp, and duration, and whether the session was resumed afterward.
  Accumulated pause time is subtracted from total elapsed time to yield actual
  active meditation time.
- **Session results** — A `SessionResult` on completion includes a
  `completionStatus` (`full` / `partial` / `minimal` / `abandoned`), completion
  percentage, active duration, total pause time, pause count, interruption
  count, a `countsTowardStreak` flag, and any achievements or milestones earned.

### 4.2 Session Persistence

Real-world meditation sessions are frequently interrupted — a notification, a
call, or simply closing the app by accident. Auto-save and crash recovery ensure
the session is not lost. Three interchangeable storage backends are provided:

| Backend      | Use case                                                         |
| ------------ | ---------------------------------------------------------------- |
| In-memory    | Testing and server-side rendering; no persistent storage         |
| LocalStorage | Browser key-value storage for small apps or simple persistence   |
| IndexedDB    | Browser structured storage for larger datasets and range queries |

- **Auto-save** — At configurable intervals, session state is persisted so that
  if the app crashes or the browser tab is closed, the session can be recovered
  on next launch.
- **Session recovery** — On startup, the persistence manager checks for an
  in-progress session and offers to restore it, allowing users to resume a
  meditation they were interrupted during.

### 4.3 Session Analytics

- **Event recording** — All session lifecycle events (start, pause, resume,
  complete, abandon) are recorded with timestamps and metadata.
- **Aggregated analytics** — Computed metrics: total session count, total
  meditation time, average session duration, completion rate, abandonment rate.
- **Pluggable trackers** — An analytics tracker interface allows integration
  with any analytics backend (Segment, Mixpanel, custom). A console tracker
  (developer console) and in-memory tracker are provided for development and
  testing.

### 4.4 Session Scheduling

- **Recurring schedules** — Define meditation schedules with day-of-week
  recurrence patterns and a specific time of day. A 9:00 AM Monday/Wednesday/
  Friday schedule fires reminders on those days.
- **Reminder notifications** — Configurable reminder notifications delivered a
  set number of minutes before the scheduled session time.
- **Upcoming session queries** — Query upcoming scheduled sessions within a date
  range for calendar display and pre-session preparation.
- **iCal export** — Scheduled sessions can be exported in iCal (.ics) format for
  import into external calendar applications (Google Calendar, Apple Calendar,
  Outlook), enabling meditation sessions to appear alongside other appointments.

---

## 5. Progress and Achievement Tracking

**Package:** `@oshun/meditation-progress`

The progress library is the single source of truth for a user's meditation
history, streaks, statistics, achievements, and milestones. Every completed
session is fed through this library, which updates all derived state atomically.

### 5.1 Session Recording

- **Atomic updates** — Recording a completed session triggers all dependent
  updates in one operation: streak recalculation, achievement evaluation,
  milestone checking. The operation returns a combined result with updated
  streak, newly unlocked achievements, and triggered milestones. This ensures
  the completion screen always has all necessary information in a single call.
- **Session history** — All historical sessions are queryable with pagination,
  date range filtering, and session type filtering.

### 5.2 Streak Tracking

Streaks are the primary daily habit mechanism. They must handle real-world
complications — different timezones, missed days, travel — without frustrating
users who practice consistently.

- **Current streak** — Counts consecutive calendar days on which at least one
  qualifying session was recorded.
- **Longest streak** — Lifetime personal record streak length.
- **Timezone awareness** — Day boundaries are calculated in the user's local
  timezone, not UTC. A user in Tokyo who meditates at 11 PM and then again at 1
  AM the next day has correctly completed two separate days of practice.
- **Minimum duration** — A configurable minimum session duration (e.g., 2
  minutes) must be met for a session to count toward streak maintenance.
- **Forgiveness days** — A configurable number of days per period are forgiven
  when the streak would otherwise break, accommodating occasional life events.
- **Streak freezes** — The user can manually freeze their streak for a defined
  period (e.g., while traveling). The streak is preserved without practice being
  required.
- **Streak events** — Events fire on streak extension, streak break (reset to
  zero), and new personal record (current streak exceeded longest streak).

### 5.3 Statistics

Statistics give users insight into when and how they practice — helping them
identify natural rhythms and scheduling gaps.

- **Predefined date ranges** — Nine ranges: Today, Yesterday, This Week, Last
  Week, This Month, Last Month, This Year, Last Year, and All Time.
- **Custom date ranges** — Arbitrary start and end dates for focused analysis.
- **Time-of-day distribution** — Sessions bucketed into early morning (5–9am),
  morning (9am–noon), afternoon (noon–5pm), evening (5–9pm), and night
  (9pm–5am), helping users understand their natural practice patterns.
- **Day-of-week distribution** — Which days of the week see the most practice,
  useful for identifying scheduling gaps.
- **Session type breakdown** — Statistical split across all ten session types,
  with both session counts and accumulated time per type.
- **Total and average metrics** — Total session count, total meditation time,
  average / median / longest / shortest session duration, average sessions per
  week and per day, a consistency score, and completion rate.

### 5.4 Achievement System

The achievement system provides a gamified reward layer with 26 built-in
achievements spanning five rarity tiers. Achievements are evaluated
automatically every time a session is recorded.

- **Built-in achievements** — 26 built-in achievements: first-session
  achievements (first meditation, first breathing exercise, first guided
  meditation), session-count achievements (10, 50, 100, 500, 1000), total-time
  achievements (1, 10, 50, 100, 500 hours), streak achievements (3, 7, 14, 30,
  60, 100, 365 days), exploration achievements (try 3 session types, try all
  10), consistency achievements (10 sessions before 7am, 10 after 10pm), and
  special achievements (a perfect week, a 60+-minute marathon session). Each
  carries a point value from 10 to 2000.
- **Rarity tiers** — Common, Uncommon, Rare, Epic, Legendary. Most users earn
  Common achievements in their first week; Legendary achievements (year-long
  streak, 500 hours, 1000 sessions) require months or years of consistent
  practice and are hidden until unlocked.
- **Automatic evaluation** — Every time a session is recorded, the achievement
  evaluator checks all unearned achievements against their criteria. Multiple
  achievements can be earned in a single session.
- **Category organization** — Achievements are organized by category — streak,
  time, sessions, exploration, consistency, special — for grouped display in the
  achievements gallery.

### 5.5 Milestone System

Milestones are progress markers distinct from achievements — they mark
quantitative thresholds with celebration messages rather than specific
behaviors. There are 26 built-in milestones across four categories.

- **Built-in milestones** — 26 built-in progress markers across four categories:
  total-minutes milestones (100 up to 50,000 minutes), session-count milestones
  (10 up to 1,000), streak milestones (7 up to 365 days), and active-days
  milestones (7 up to 365 days). Each carries a celebration message.
- **Progress tracking** — Percentage-based progress toward each milestone,
  enabling "You're 73% of the way to your next milestone" display.
- **Milestone notifications** — When a milestone is reached, a notification is
  sent so the user is informed even if they are not actively in the app.

### 5.6 Data Export

- **Multi-format export** — Progress data is exportable as JSON or CSV for
  personal records and data portability.
- **Selective export** — Choose which data types to include — sessions,
  statistics, streak, achievements, milestones — and optionally restrict to a
  date range or completed sessions only.

### 5.7 Multi-Device Sync

- **Cross-device synchronization** — Progress data synchronizes across multiple
  devices so the web app and mobile app always show the same history.
- **Conflict detection** — When the same session exists with different data on
  two devices (e.g., edited on both while offline), a conflict is detected.
- **Resolution strategies** — Configurable resolution: local-wins, remote-wins,
  merge (combines non-conflicting changes), or manual (presents conflicts for
  user resolution).
- **Sync state tracking** — Sync status (idle, syncing, error, success) with a
  last-sync timestamp, a pending-change count, and an online flag, suitable for
  displaying a sync indicator in the UI.

---

## 6. Offline Content Management

**Package:** `@oshun/meditation-offline`

The offline library manages downloading, storing, versioning, and retrieving
meditation audio files so they are available when the device has no internet
connection. It also detects network conditions and suggests what content to
download proactively.

### 6.1 Download Queue

- **Priority-based queue** — Downloads are queued with five priority levels:
  Critical, High, Normal, Low, and Background. Higher-priority downloads proceed
  before lower-priority ones when concurrent download slots are filled.
- **Concurrent download limits** — Configurable maximum simultaneous downloads
  prevent overwhelming the network connection or device I/O.
- **Retry logic** — Failed downloads are retried with configurable retry counts
  and exponential backoff. After the maximum retries, the download is marked
  permanently failed and the user is notified.
- **Pause and resume** — Both individual downloads and the entire queue can be
  paused and resumed. Partial downloads are preserved so resuming continues from
  where it stopped, not from zero.
- **Cancellation** — Individual downloads can be cancelled via AbortSignal with
  proper cleanup of partial files and metadata.
- **Queue state tracking** — Real-time counts of pending, in-progress,
  completed, and failed items for a download progress indicator.

### 6.2 Storage Management

Three interchangeable storage backends are available — the same storage
interface is implemented by all three, so switching from in-memory (development)
to IndexedDB (production) requires changing only the constructor argument:

| Backend      | Characteristics                                                  |
| ------------ | ---------------------------------------------------------------- |
| IndexedDB    | Recommended for production; supports larger datasets and queries |
| localStorage | Simple browser key-value storage                                 |
| In-memory    | Testing and server-side rendering                                |

- **Storage limits** — Configurable maximum total storage size and maximum item
  count. When limits are approached, cleanup strategies reclaim space.
- **Cleanup strategies** — Five strategies: least-used (evict content not
  recently played), oldest-first (evict content downloaded longest ago),
  largest-first (evict the largest files when space is tight), expired-first
  (evict time-limited content past its expiry), and a custom strategy hook.
- **Storage info** — Real-time reporting of used space, available space, and
  item count for a storage management UI.
- **Content metadata tracking** — Downloaded content metadata (local file path,
  download date, content version, file size) is stored separately from the audio
  files for fast querying without reading large binary files.

### 6.3 Content Versioning

Content versioning ensures that users always have the correct version of a
downloaded file — when a meditation track is updated on the server, outdated
local copies are identified and updated according to the user's chosen policy.

- **Version tracking** — Each downloaded content item tracks a semantic version
  (major.minor.patch). When remote content is updated, the version increments.
- **Update policies** — Four policies: Manual (never update automatically),
  Notify (flag available updates without downloading), Auto on Wi-Fi, and Auto
  Always.
- **Manifest fetching** — A remote content manifest lists the current version of
  every available content item. The offline manager periodically fetches the
  manifest and compares it to local versions to identify available updates.
- **Version utilities** — `createVersion`, `incrementVersion`, `isValidVersion`,
  `sortVersions`, `getLatestVersion`, `filterVersionRange`.

### 6.4 Smart Download Suggestions

The suggestion engine analyzes listening history to recommend what to download
before going offline — so users are prepared for a flight or a commute without
needing to curate a download list manually.

- **Behavior-based suggestions** — The suggestion engine analyzes the user's
  listening history (play count, completion rate, last played, category
  preferences) to recommend what to download before going offline.
- **Scoring weights** — Eight configurable scoring weights — frequently used,
  favorites, course progress, similar content, popularity, new content, small
  size, and preferences match — combine into a confidence score for each
  suggestion.
- **Suggestion reasons** — Each suggestion includes a reason from a fixed set
  (frequently used, favorite, course progress, similar content, popular, new
  release, expiring soon, small size, recommended) plus a human-readable
  explanation string.
- **Quick and full modes** — Quick suggestions return a fast set for immediate
  display. Full catalog analysis scores every undownloaded item against user
  preferences for comprehensive recommendations.

### 6.5 Network State Detection

- **Online/offline detection** — Automatic detection of network connectivity
  changes with events fired on state change.
- **Connection type identification** — WiFi, cellular, Ethernet, or unknown.
  WiFi connections are treated as unmetered; cellular as potentially metered.
- **Download behavior policies** — Configurable per connection type: WiFi-only
  (block downloads on cellular), allow metered (allow cellular downloads up to a
  configured size limit), always download.
- **Automatic queue management** — When the device goes offline, the download
  queue pauses automatically. When the device comes back online on a qualifying
  connection type, the queue resumes automatically.

### 6.6 Content Integrity

- **Checksum verification** — Downloaded audio files are verified against a
  checksum after download to detect network corruption or partial writes.
- **Automatic resume on restart** — In-progress downloads at app shutdown are
  automatically resumed on next startup.
- **File cleanup** — Content deletion manages both the audio file and the
  metadata record so no orphaned files remain in storage.

---

## 7. Core Types

**Package:** `@oshun/meditation-core`

The core library provides shared type definitions and utilities that the other
meditation libraries can build on. It has no runtime dependencies and no
`eventemitter3` usage — it is a pure TypeScript types-and-utilities package.

- **Session models** — `MeditationSession`, `SessionState`, `SessionType`,
  `SessionResult`, `PauseRecord`, `InterruptionRecord`.
- **Branded primitives** — `SessionId`, `TrackId`, `ContentId`, `TeacherId`,
  `CourseId`, `DurationSeconds`, `DurationMilliseconds`, `Timestamp`,
  `Percentage`, `ByteSize`, `DateString`, `TimeString`, `UrlString`,
  `LocaleCode`. These prevent accidental misuse of raw string/number values
  across library boundaries.
- **Audio models** — `AudioTrack`, `PlaybackState`.
- **Content models** — `ContentItem`, `ContentKind`, `ContentMetadata`,
  `ContentVersion`, `LocalizedText`, `MeditationCategory`.
- **Common utilities** — A `duration` module (seconds/milliseconds conversion,
  percentage clamping, `splitSeconds`), a `dates` module (`dateString`,
  `dateRange`, `addDays`, `compareDateStrings`), a `format` module
  (`formatDuration`, `formatMinutes`, `slugify`, `titleCase`), and a
  `validation` module (`localeCode`, `urlString`, integer-range checks).

---

## 8. Analytics

**Package:** `@oshun/meditation-analytics`

A small, dependency-free analytics library for privacy-conscious event tracking.
It is separate from the session package's own `SessionAnalyticsManager` (which
computes period aggregates): `meditation-analytics` is for outbound event
emission to external analytics backends, while `SessionAnalyticsManager` is for
internal aggregate computation stored locally.

- **Session event tracking** — An `AnalyticsClient` emits events from a fixed
  11-name vocabulary: session started/paused/resumed/completed/interrupted,
  content started/completed, timer completed, breathing completed, download
  completed, and streak updated. Each event carries a timestamp, an anonymous
  ID, optional session and content IDs, and a properties bag.
- **Consent gating** — Tracking is gated on both an `enabled` flag and a
  `consentGranted` flag; either can be toggled at runtime, and no event is
  emitted unless both are true.
- **Privacy-conscious by design** — Events are keyed by an `anonymousId`, never
  personally identifiable content. Captured fields are behavioural — durations,
  completion ratios, session type.
- **Session summaries** — `summarizeSession` derives a session's duration and a
  clamped completion ratio from start/end times and elapsed seconds;
  `trackSessionSummary` emits the matching `session_completed` or
  `session_interrupted` event.
- **Pluggable providers** — An `AnalyticsProvider` interface (`identify` /
  `track` / `flush`) is compatible with Segment, Mixpanel, or a custom backend;
  a built-in `MemoryAnalyticsProvider` is provided for testing.

---

## 9. Cross-Platform Architecture

### 9.1 Platform Abstraction Pattern

All platform-dependent features (audio session management, background timers,
haptics, lock screen controls) are defined as abstract base classes with a clear
interface contract. Concrete implementations exist for three targets:

- **Web** — Uses Web APIs: Web Audio API, Media Session API, Vibration API,
  Service Workers, Notification API, IndexedDB, localStorage.
- **Noop** — No-operation implementations that silently do nothing, for testing,
  server-side rendering, and unsupported platforms.
- **React Native** (pluggable) — The interface allows React Native
  implementations to be added as platform-specific adapters without modifying
  the core library.

Factory functions automatically select the correct implementation at runtime by
detecting the environment (`typeof window`, `navigator.mediaSession`, etc.).

### 9.2 Typed Event System

The six engine libraries (player, timer, breathing, session, progress, offline)
use `eventemitter3` for event emissions, with each primary class typed by an
event map. Event data includes state-change events, progress events
(elapsed/remaining/percentage normalized), error events (typed error codes with
messages), and lifecycle events. The `meditation-analytics` package does not use
`eventemitter3`.

### 9.3 Storage Backend Pattern

Libraries that persist data provide interchangeable storage backends
implementing the same TypeScript interface — making them testable in isolation
(in-memory), functional in simple web apps (localStorage), and production-ready
in full apps (IndexedDB). The session and offline packages provide all three
backends; the breathing history and progress packages provide in-memory and
localStorage backends. Factory functions create pre-configured backend
instances.

### 9.4 Type Safety

- **Branded types** — Prevent accidental misuse of primitive values. A function
  accepting `SessionId` will not accept a raw `string` even though both are
  strings at runtime.
- **Discriminated unions** — Event types use discriminated union shapes so
  `switch (event.type)` enables exhaustive handling with TypeScript's narrowing.
- **Const assertions** — Configuration defaults exported as `const` assertions
  for narrowed type inference, preventing accidental widening to `string`.

---

## 10. React Hook Integration

All libraries export hook factory functions following a **dependency injection**
pattern. React itself is an optional peer dependency —
`setReactHooks({useState, useEffect, useCallback, useRef})` must be called once
to register React's hooks. This means the libraries work in non-React
environments (React Native, Vue adapters, vanilla JavaScript) without bundling
React.

### 10.1 Player Hooks

| Hook                  | Purpose                                                               |
| --------------------- | --------------------------------------------------------------------- |
| `usePlayer`           | Player state, controls (play, pause, stop, seek, load), current track |
| `usePlaybackProgress` | Real-time elapsed time, remaining time, and percentage progress       |
| `useQueue`            | Queue state and controls (add, remove, reorder, clear, skip)          |
| `useVisualization`    | Real-time frequency and beat data for visualizations                  |
| `useAudioSession`     | Audio session state including interruptions and route changes         |
| `useMixer`            | Multi-layer mixer state and controls                                  |

### 10.2 Timer Hooks

| Hook                 | Purpose                                                        |
| -------------------- | -------------------------------------------------------------- |
| `useMeditationTimer` | Complete timer state and controls (start, pause, resume, stop) |
| `useTimerState`      | Current phase, running status, and configuration observation   |
| `useTimerProgress`   | Elapsed, remaining, and per-phase progress in real time        |
| `useTimerPresets`    | Preset library access, selection, and custom preset creation   |

### 10.3 Breathing Hooks

| Hook                    | Purpose                                                     |
| ----------------------- | ----------------------------------------------------------- |
| `useBreathingExercise`  | Exercise controls (start, pause, resume, stop) and pattern  |
| `useBreathingState`     | Active phase, cycle count, and session progress             |
| `useBreathingAnimation` | Real-time animation data for circle/sphere/wave rendering   |
| `useBreathingPatterns`  | Pattern catalog plus lookup by ID, category, and difficulty |

### 10.4 Session Hooks

| Hook                 | Purpose                                                                          |
| -------------------- | -------------------------------------------------------------------------------- |
| `useSessionManager`  | Session lifecycle controls (create, start, pause, resume, complete)              |
| `useCurrentSession`  | Current session object for active meditation display                             |
| `useSessionProgress` | Real-time elapsed time, completion percentage, pause status                      |
| `useSessionState`    | Current session state value only                                                 |
| `useScheduler`       | Schedule CRUD (create/update/delete/enable/disable) and upcoming session queries |

### 10.5 Progress Hooks

| Hook                 | Purpose                                                      |
| -------------------- | ------------------------------------------------------------ |
| `useStreak`          | Current streak, longest streak, and configuration            |
| `useStatistics`      | Statistics for configurable date ranges                      |
| `useAchievements`    | Achievement list with unlock status and category filtering   |
| `useMilestones`      | Milestone list with progress percentages                     |
| `useSync`            | Sync status, last sync time, and manual sync trigger         |
| `useProgressTracker` | Combined tracker with session recording and all sub-features |

### 10.6 Offline Hooks

| Hook                    | Purpose                                                     |
| ----------------------- | ----------------------------------------------------------- |
| `useOfflineContent`     | A single content item's offline state with download actions |
| `useOfflineContentById` | Offline state for a specific content ID                     |
| `useAllOfflineContent`  | List of all offline-available content                       |
| `useDownloadProgress`   | Real-time download progress for active downloads            |
| `useNetworkState`       | Current network state (online/offline, connection type)     |
| `useQueueState`         | Queue state with pending, active, and completed item counts |
| `useStorageInfo`        | Storage usage (used space, available space, item count)     |
| `useSuggestions`        | Smart download suggestions for recommending content         |

---

## Library Summary

| Library   | Package                       | Primary Capabilities                                                                                                          |
| --------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Core      | `@oshun/meditation-core`      | Shared types, branded primitives, common utilities                                                                            |
| Player    | `@oshun/meditation-player`    | Audio playback, queue, background audio, multi-layer mixing, visualization, adaptive streaming, caching                       |
| Timer     | `@oshun/meditation-timer`     | Countdown timer, multi-phase structure, presets, bells, ambient sounds, background operation, haptics                         |
| Breathing | `@oshun/meditation-breathing` | 10 breathing patterns, custom builder, visualization, audio and haptic guidance, session history                              |
| Session   | `@oshun/meditation-session`   | Session lifecycle, persistence (3 backends), analytics, recurring schedules, iCal export                                      |
| Progress  | `@oshun/meditation-progress`  | Streaks (timezone-aware, forgiveness, freezes), statistics, achievements (5 rarities), milestones, export, multi-device sync  |
| Offline   | `@oshun/meditation-offline`   | Priority download queue, storage management, content versioning, smart suggestions, network detection, integrity verification |
| Analytics | `@oshun/meditation-analytics` | Consent-gated session event tracking, privacy-conscious behavioural metrics, session summaries, pluggable providers           |
