diff --git a/content/core/mcp.mdx b/content/core/mcp.mdx index 7f53292..e2388c3 100644 --- a/content/core/mcp.mdx +++ b/content/core/mcp.mdx @@ -137,6 +137,47 @@ To apply exactly what was previewed, pass the returned `candidateRuleset` as `ru Watch import accepts up to 2,000 records per array, with Unix-second timestamps and an explicit side. Repeated records are skipped. Check `stageError` for partial success. For a full Health export, use [Upload Apple Watch data](/core/biometrics/#explore-vitals-and-import-watch-data) instead of putting the archive in model context. +## Personal stage models + +Available in core development revision `09e10015`; check your installed build. + +| Tool | Purpose | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | +| `get_stage_models` | List a side's library, newest first, with IDs and selected/active flags. | +| `preview_stage_model` | Read-only comparison with Watch stages and the rules; stores nothing. Pass an inline model or omit it to preview the selected model. | +| `add_stage_model` | Store a model without selecting it. Identical uploads return the existing ID. | +| `select_stage_model` | Select a library ID, with an explicit `active` choice; returns the previous selection for restoration. | +| `set_stage_model_active` | Turn the selected model on, or use `active: false` to return to the rules while keeping it selected. | + +Preview defaults to seven recent nights (1–30 supported). Scores on the model's +training nights are **in-sample**, not independent validation. Missing Watch labels +mean no agreement score. Review the preview before approving selection or activation, +one side at a time; activating changes the stages shown for stored nights too. + +Inline models are capped at **256 KB of JSON**. A full training forest is about +1–2 MB: upload it over REST, without selecting it, then use the tools for library +management. Replace `POD_IP`, the side, and the candidate path: + +```bash +jq -n --slurpfile m candidate.json '{side:"left", model:$m[0]}' | + curl --fail-with-body -X POST http://POD_IP:3000/api/sleep-stages/models \ + -H 'Content-Type: application/json' --data-binary @- +``` + +Keep the returned ID and inspect `get_stage_models`. To preview a large candidate +before changing the selection, send the same model via +`POST /api/sleep-stages/model/preview` with `side`, `model`, and `nights`. +The MCP preview takes an inline model or the selected model, not an arbitrary library +ID. After reviewing that preview, use `select_stage_model` with the uploaded ID and +the intended `active` state. Subsequent previews can omit the model. + +Unknown feature contracts and models that fail their embedded test vectors are +rejected. The older `PUT /api/sleep-stages/model` replaces the side's model and +preserves its active state (inactive on first upload); it is deliberately not exposed through MCP. See +[Personal stage models](/core/personal-stage-models/) for training and REST routes. + +**Pinned sources:** [MCP personal-model contract](https://github.com/sleepypod/core/blob/09e10015ea75dab14456bf0dd58cea120d73b2ff/src/mcp/README.md#personal-stage-models) · [Tool schemas and size limit](https://github.com/sleepypod/core/blob/09e10015ea75dab14456bf0dd58cea120d73b2ff/src/mcp/tools/stageModels.ts) + ## Biometric calibration | Tool | Purpose | diff --git a/content/core/personal-stage-models.mdx b/content/core/personal-stage-models.mdx index a060729..8310477 100644 --- a/content/core/personal-stage-models.mdx +++ b/content/core/personal-stage-models.mdx @@ -7,7 +7,7 @@ description: 'Train a sleep-stage model from your own nights with the Apple Watc A personal stage model is a classifier trained on your own nights: the Pod's heart rate, HRV, breathing, and movement are the inputs, and the stages your Apple Watch recorded on the same nights are the labels. It is scored with Cohen's kappa (κ) against the Watch on nights it never saw, beside two baselines: the Pod's [sleep-stage rules](/core/settings/sleep-stages/) and the bundled challenger model that ships in the iOS app. -This is a development preview. The Pod side is pinned to core development revision `14a7cda7` and the phone side to iOS development revision `3fe45f1a`, both on `dev` as of October 20, 2026. Neither side is on `main` yet; availability depends on your installed build. +This is a development preview. The Pod side is pinned to core development revision `09e10015` and the phone side to iOS development revision `3fe45f1a`, from the development branches; availability depends on your installed build. ## Explore models in the training workspace @@ -66,17 +66,17 @@ Useful flags: | `--work DIR` | Working directory (default `./personal-models`) | | `--keep-snapshot` | Keep the database snapshot after the run; it is deleted by default | -**Footprint.** A run leaves the dataset and the exported models, about 0.8 MB, in the work directory. The database snapshot is about 75 MB and is deleted after the run unless you pass `--keep-snapshot`. The Pod keeps one model row per side, replaced on every upload; a depth 8 forest is about 2 MB. +**Footprint.** A run leaves the dataset and the exported models, about 0.8 MB, in the work directory. The database snapshot is about 75 MB and is deleted after the run unless you pass `--keep-snapshot`. The Pod keeps a model library per side and one selected model. The script’s legacy upload replaces the selection and preserves its active state (a first upload defaults to inactive). A depth 8 forest is about 2 MB. ## What the Pod does with it -The Pod stores the model and evaluates it with its own TypeScript, computing the same feature contracts from a night's vitals and movement. Three routes under `/api`: +The Pod stores the model and evaluates it with its own TypeScript, computing the same feature contracts from a night's vitals and movement. Routes under `/api`: -| Method | Path | Purpose | -| ------ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| GET | `/sleep-stages/model` | The side's stored model and when it was uploaded | -| PUT | `/sleep-stages/model` | Store a model for a side, or `null` to remove it. The Pod refuses a model that names an unknown feature contract or fails any of its own test vectors, so a converter mismatch is caught at upload | -| POST | `/sleep-stages/model/preview` | Stage recent nights with the stored model (or one sent inline) and score it against the Watch beside the side's rules on the same nights | +| Method | Path | Purpose | +| ------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| GET | `/sleep-stages/model` | The side's selected model, upload time, and active flag | +| PUT | `/sleep-stages/model` | Replace the selected model, preserving its active state (inactive on first upload), or `null` to remove it. The Pod refuses a model that names an unknown feature contract or fails any of its own test vectors, so a converter mismatch is caught at upload | +| POST | `/sleep-stages/model/preview` | Stage recent nights with the stored model (or one sent inline) and score it against the Watch beside the side's rules on the same nights | ```bash curl --fail -X POST http://POD_IP:3000/api/sleep-stages/model/preview \ @@ -85,7 +85,24 @@ curl --fail -X POST http://POD_IP:3000/api/sleep-stages/model/preview \ Preview scores are in-sample when the previewed nights were also in the training set, which they are after a normal run: the earlier depth 4 contract B forest that scored κ 0.20 leave-one-night-out reached κ 0.33 when the Pod previewed its own training nights. Treat the preview as a check that the Pod evaluates the model the same way the Mac did, not as independent validation; the held-out κ from training is the number to compare. -The stored model is scored beside the rules; it does not replace the Pod's live classifier. The classifier is pinned to the hashed biometrics manifest through the [profile system](/core/settings/biometric-calibration/), and switching engines there is a migration of its own. Nights in [Sleep](/core/biometrics/) keep using the saved rules. +The selected model can stage the side's nights when active. The saved rules remain +available and are the fallback for nights the model cannot stage. Turning the model +off returns to the rules without removing the selection; stage reads identify the +source with `stagedBy`. + +For a candidate that should not replace the selection immediately, use the library: + +| Method | Path | Purpose | +| ------ | ------------------------------- | ------------------------------------------------------ | +| GET | `/sleep-stages/models` | List a side's models and selected/active flags. | +| POST | `/sleep-stages/models` | Add `{side, model}` without selecting; returns an ID. | +| PUT | `/sleep-stages/models/selected` | Select `{side, id, active}` after reviewing a preview. | +| PUT | `/sleep-stages/model/active` | Set `{side, active}`; `false` returns to the rules. | + +For agent-assisted library management and the full-forest curl upload, see +[MCP personal stage models](/core/mcp/#personal-stage-models). Inline MCP models +have a 256 KB limit; full forests go through the REST upload. Training with +`--no-upload` lets you review and add a candidate before selecting or activating it. ## On the iPhone @@ -108,4 +125,6 @@ sleepypod is not a medical device. Stage estimates, from the rules or from a per --- -**Source reference:** [Training script](https://github.com/sleepypod/core/blob/14a7cda7/scripts/train-personal-models.py) · [Model routes](https://github.com/sleepypod/core/blob/14a7cda7/src/server/routers/sleepStages.ts) · [Pod evaluator](https://github.com/sleepypod/core/blob/14a7cda7/src/lib/personal-stage-model.ts) · [Calibration research](https://github.com/sleepypod/core/blob/14a7cda7/docs/research/sleep-stage-calibration/README.md) · [iOS design](https://github.com/sleepypod/ios/blob/3fe45f1a/docs/design/on-device-stage-training.md) · [Portable model on iOS](https://github.com/sleepypod/ios/blob/3fe45f1a/Sleepypod/Services/PortableStageModel.swift) · [Stage models screen](https://github.com/sleepypod/ios/blob/3fe45f1a/Sleepypod/Views/Data/StageComparisonView.swift) +**Source reference:** [Training script](https://github.com/sleepypod/core/blob/14a7cda7/scripts/train-personal-models.py) · [Model routes](https://github.com/sleepypod/core/blob/09e10015ea75dab14456bf0dd58cea120d73b2ff/src/server/routers/sleepStages.ts) · [Pod evaluator](https://github.com/sleepypod/core/blob/14a7cda7/src/lib/personal-stage-model.ts) · [Calibration research](https://github.com/sleepypod/core/blob/14a7cda7/docs/research/sleep-stage-calibration/README.md) · [iOS design](https://github.com/sleepypod/ios/blob/3fe45f1a/docs/design/on-device-stage-training.md) · [Portable model on iOS](https://github.com/sleepypod/ios/blob/3fe45f1a/Sleepypod/Services/PortableStageModel.swift) · [Stage models screen](https://github.com/sleepypod/ios/blob/3fe45f1a/Sleepypod/Views/Data/StageComparisonView.swift) + +**Activation source:** [Selected-model default](https://github.com/sleepypod/core/blob/09e10015ea75dab14456bf0dd58cea120d73b2ff/src/db/schema.ts#L127-L135) diff --git a/content/developers/training.mdx b/content/developers/training.mdx index 1e9206f..ae9a79a 100644 --- a/content/developers/training.mdx +++ b/content/developers/training.mdx @@ -5,15 +5,16 @@ description: 'Watch sleep-stage training, compare models and sleep timelines, an # ML training workspace -The [sleepypod training app](https://github.com/sleepypod/training) is a local -research workspace for sleep-stage models. The repository is public and anyone +The [sleepypod training app](https://github.com/sleepypod/training/tree/8874faf632a252b6078e6d0f7dc9882bffa8d386) is a local +research workspace for sleep, movement, and snore experiments. The repository is public and anyone can clone it. The browser dashboard runs on your computer, alongside Python training with scikit-learn, NumPy, and SciPy. ## Set up and train -You need a Mac or Linux computer on the same network as your pod, an Apple Watch -that tracks sleep, and at least five nights of Watch sleep stages. +You need a Mac or Linux computer on the same network as your pod. Sleep-stage training also +needs an Apple Watch that tracks sleep and at least five nights of Watch sleep stages; the +movement and snore workflows don't. 1. **Install the tools.** With [Homebrew](https://brew.sh): `brew install node@24 git jq`. The guided script offers to install [uv](https://docs.astral.sh/uv/), which brings its own Python. @@ -47,8 +48,12 @@ arrives and models are fitted, and the dashboard stays open after training compl ## Explore a run +Use the **Sleep / Movement / Snore** switch above the sidebar to choose a research +workflow. The run list shows only that kind. Sleep runs have five tabs: + - **Overview:** pipeline progress, held-out scores, per-night results, and review checks. - **Nights:** aligned Pod, candidate, baseline, and Watch sleep stages, disagreement navigation, and stage-duration comparisons. +- **Weeks:** stage minutes per night grouped into local ISO weeks, a source selector, and weekly averages with differences from Watch. Only intervals shared by every displayed source count; missing nights are gaps, not zero. - **Data:** label coverage, input distributions, and per-night summaries. - **Log:** detailed events, configuration, failures, and the candidate download. @@ -76,7 +81,7 @@ predictions on the final model's own training data. /> These unmodified captures contain only synthetic data. The -[training README](https://github.com/sleepypod/training#training-workspace) +[training README](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/README.md#training-workspace) also includes screenshots and setup instructions. ## Reopen results and save models @@ -97,6 +102,55 @@ Raw data and fitted artifacts stay in the ignored local `data/` directory. This research workflow does not upload or activate models. It uses retrospective whole-night features; its scores do not prove prospective or clinical validity. +## Movement experiments + +`scripts/movement.py session|train` labels a scripted session from timed cues, +then compares a classifier built from raw piezo and capacitance with the pod's +per-minute movement score. Run from the training repository after setup: + +```bash +uv run --locked python scripts/movement.py session --side left --pod POD_IP --out data/movement/session-1.json +# Wait about 45 minutes for the pod to write the data before training. +uv run --locked python scripts/movement.py train --session data/movement/session-1.json --pod POD_IP --out data/runs/movement-001 +``` + +The session cues stillness, arm and leg movements, turning over, and sitting up. +macOS can speak the cues; `--cue print` prints them. A text schedule and stopwatch +can also supply manually recorded cue times in the same session format. Align +those times to the pod using known knocks; this is manual preparation, not an +automatic knock-alignment mode in `movement.py`. + +The **Movement** view compares moving recall and false alarms while still, shows +per-class recall and a confusion matrix, and aligns labels, predictions, and pod +flags by session. The pod score has one value per minute and cannot identify +movement types. Repeat `--session` to evaluate across sessions; one-session +validation is optimistic, and deliberate cued movements are not natural sleep movements. + +## Snore-band research + +`scripts/piezo_bandwidth.py session|analyze|night` tests whether raw piezo carries +energy in the 16–30 Hz and 60–100 Hz bands: + +```bash +uv run --locked python scripts/piezo_bandwidth.py session --side left --pod POD_IP --out data/bandwidth/steps.json +uv run --locked python scripts/piezo_bandwidth.py analyze --steps data/bandwidth/steps.json --pod POD_IP --out data/bandwidth/session +uv run --locked python scripts/piezo_bandwidth.py night --start 2026-10-22T23:00-07:00 --end 2026-10-23T07:00-07:00 --pod POD_IP --out data/bandwidth/night +``` + +Replace the example night with your recording window. The session times empty-bed, +pump, lying-still, humming, imitated-snore, and knock steps. Analyze after the pod's +archives become available; if coverage ends early, retry into a fresh output directory. +The **Snore** view shows the band gate and per-step energy, or a night's band energy, +pump activity, coverage, and storage. These are vibration measurements, not detected snores. + +## Research findings + +Findings and their limitations live in the training repository's knowledge base: + +- [Light-sleep confusion](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/knowledge/evaluation/light-sleep-confusion-2026-10-21.md). +- [Piezo bandwidth gate: both bands passed on one pod with imitated snoring](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/knowledge/evaluation/piezo-bandwidth-2026-10-22.md). +- [Sequence decoding: the 10-night gains did not hold on 13 nights](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/knowledge/evaluation/sequence-decoding-2026-10-21.md). + ## Put a model on the pod Uploading is a separate, deliberate step, one side at a time: @@ -111,8 +165,10 @@ Uploading is a separate, deliberate step, one side at a time: The pod refuses models whose feature contract it does not know or whose embedded test vectors it does not reproduce. The -[training README](https://github.com/sleepypod/training#use-a-trained-model-on-the-pod) +[training README](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/README.md#use-a-trained-model-on-the-pod) has the exact commands. The [core personal-model workflow](/core/personal-stage-models/) trains and uploads in one step instead. -**Source reference:** [Training README](https://github.com/sleepypod/training/blob/c5daa6a/README.md) · [Quickstart script](https://github.com/sleepypod/training/blob/c5daa6a/scripts/quickstart.sh) · [Training pipeline](https://github.com/sleepypod/training/blob/c5daa6a/scripts/train.py) · [Dashboard](https://github.com/sleepypod/training/blob/c5daa6a/scripts/dashboard.py) +**Source reference:** [Training README](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/README.md) · [Quickstart script](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/scripts/quickstart.sh) · [Training pipeline](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/scripts/train.py) · [Dashboard](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/scripts/dashboard.py) + +**Research workflow sources:** [Movement script and session format](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/scripts/movement.py) · [Piezo bandwidth script](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/scripts/piezo_bandwidth.py) · [Clock alignment contract](https://github.com/sleepypod/training/blob/8874faf632a252b6078e6d0f7dc9882bffa8d386/docs/overnight-capture.md) diff --git a/content/ios/using-the-app.mdx b/content/ios/using-the-app.mdx index 4853279..e2d45dd 100644 --- a/content/ios/using-the-app.mdx +++ b/content/ios/using-the-app.mdx @@ -93,3 +93,45 @@ The Watch’s night no longer has to fit entirely inside the bed’s recorded wi **Pinned source references:** [Health sync and rebuild](https://github.com/sleepypod/ios/blob/ce1d455cb69b00413f8d84630052c1878d9a5f5b/Sleepypod/Services/HealthSyncService.swift) · [Health settings and confirmation](https://github.com/sleepypod/ios/blob/ce1d455cb69b00413f8d84630052c1878d9a5f5b/Sleepypod/Views/Settings/HealthAccessView.swift) · [Watch matching and scoring](https://github.com/sleepypod/ios/blob/ce1d455cb69b00413f8d84630052c1878d9a5f5b/Sleepypod/Services/WatchComparison.swift) · [Comparison charts](https://github.com/sleepypod/ios/blob/ce1d455cb69b00413f8d84630052c1878d9a5f5b/Sleepypod/Views/Data/WatchComparisonView.swift) + +## Experimental overnight recordings + +These features are pinned to iOS development revision `7a9696b`; availability +depends on your installed build. Existing screenshots show earlier revisions. + +### Watch movement + +On the Watch, open sleepypod, choose 1–12 hours, and tap **Record tonight**. +Grant Motion & Fitness access when asked. The app uses `CMSensorRecorder` to +request overnight wrist acceleration at 50 Hz. In the morning, tap **Send to iPhone**; +WatchConnectivity queues the transfer to **Settings → Watch movement**, where you +can share the file to a computer. Nothing is uploaded automatically. + +The summary uses **two-second bins**, not one-second bins. Missing bins mean no data, +not stillness; raw readings are optional and off by default. Watch movement is a +movement label, not a sleep-stage input. **Experimental:** real-device overnight +background recording, battery use, and delivery remain unverified. + +**Pinned sources:** [Recording and file format](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/docs/watch-motion-format.md) · [Recorder](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/SleepypodWatch/MotionRecorder.swift) · [Summary bins](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/Shared/WatchMotion/WatchMotionFile.swift) + +### Snore detection (Beta) + +Open **Settings → Health → Snore detection** and choose **Start listening**. +This is opt-in and requires microphone access. Put the iPhone on the nightstand, +plugged in, with sleepypod open. Knock three times on the bed frame after starting +and before stopping to provide timing markers for alignment with the pod. + +Apple's built-in sound classifier runs on the iPhone. Audio buffers are processed +only in memory: raw audio, transcripts, and embeddings are never saved or sent. +The saved JSON contains snore times and confidence, listening coverage, +interruptions, knock times, and session/device/classifier metadata. Session files +and their folder are excluded from iCloud and computer backups. Nothing is uploaded +automatically; export a session manually through the share sheet. + +Calls and other audio interruptions leave gaps in coverage. No detection outside +listening coverage means no recording, not no snoring. Confidence is the peak +classifier score, not a calibrated probability, and audio alone cannot identify +which sleeper snored. **Experimental:** real-bedroom detection quality, overnight +background behavior, and battery use have not been measured. Snoring is not a diagnosis. + +**Pinned sources:** [Session format and limitations](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/docs/snore-capture.md) · [In-memory audio processing](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/Sleepypod/Services/Snore/SnoreAudioCapture.swift) · [Storage and backup exclusion](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/Sleepypod/Services/Snore/SnoreCaptureService.swift) · [Controls and manual sharing](https://github.com/sleepypod/ios/blob/7a9696b9945945bae24409ff26768b47a0ecc24a/Sleepypod/Views/Settings/SnoreCaptureView.swift)