Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
199 commits
Select commit Hold shift + click to select a range
dfd8dbc
test: audit coverage and fix calibration trigger ordering (#697)
ng Sep 6, 2026
7351643
chore(deps): Update @base-ui/react all non-major dependencies (#699)
renovate[bot] Sep 7, 2026
64c70e6
feat(streaming): expose LPS diagnostic subscriptions (#701)
ng Sep 7, 2026
e8c742f
fix(deploy): require prebuilt updates and stage local builds over SSH…
ng Sep 9, 2026
101bbbc
fix(deploy): support explicit GitHub forks for branch builds (#705)
ng Sep 9, 2026
45a3ddd
chore(deps): Update @types/node all non-major dependencies (#710)
renovate[bot] Sep 14, 2026
6b661b2
chore(deps): Update @formatjs/intl-localematcher all non-major depend…
renovate[bot] Sep 21, 2026
d07adbb
fix(homekit): preserve pairings on shutdown and remove redundant powe…
ng Sep 25, 2026
3ca513b
fix(install): make SSH setup work on a stock Pod 4 (#717)
jasonlarue Sep 25, 2026
f2d1ec1
UI: single-sleeper view in away mode, ambient labels, alarm editor ov…
jasonlarue Sep 25, 2026
93998a7
fix(biometrics): pin RAW frames so the cold archive actually fills (#…
jasonlarue Sep 26, 2026
839deea
fix(sleep-detector): raw-unit, rise-only presence for Pod 3/4 capSense
jasonlarue Sep 24, 2026
ae89830
feat(sleep-detector): persist in-progress sessions across restarts
jasonlarue Sep 24, 2026
5b474cd
feat(sleep-detector): self-adjusting presence baseline, no scheduled …
jasonlarue Sep 24, 2026
a5625c6
feat(biometrics): single-sleeper mode when one side is in away mode
jasonlarue Sep 24, 2026
df5874b
fix(sleep-detector): restore every side's replay watermark after restart
jasonlarue Sep 25, 2026
65a43ed
fix(sleep-detector): persist the presence hysteresis latch
jasonlarue Sep 25, 2026
a81777c
fix(piezo-processor): keep single-sleeper vitals until they are written
jasonlarue Sep 25, 2026
d4344a3
fix(sleep-detector): seed from the published baseline when state is lost
jasonlarue Sep 25, 2026
61ce9ba
fix(biometrics): preserve vitals retries and flush during idle input
ng Sep 26, 2026
cfbe5b8
Fix Pod 3/4 presence: raw-unit rise, self-adjusting baseline, reboot-…
ng Sep 26, 2026
08c55fa
test(biometrics): cover single-sleeper page routing (#721)
ng Sep 26, 2026
4dac123
test(biometrics): cover side-toggle navigation branches (#722)
ng Sep 26, 2026
3d92989
Run CI on merge_group so the dev merge queue can gate on required che…
ng Sep 27, 2026
52f6979
ci: stop failing the test gate on Codecov upload errors (#725)
ng Sep 27, 2026
a7e33ab
docs: consolidate project guidance in AGENTS.md (#723)
ng Sep 27, 2026
3916398
chore(deps): Update @tanstack/react-query all non-major dependencies …
renovate[bot] Sep 28, 2026
97df464
feat: coordinate temperature ownership and persistent manual holds (#…
ng Sep 28, 2026
3a5d9be
perf: cache weekly temperature schedule occurrences (#729)
ng Sep 28, 2026
234ecb8
Merge main into dev to reconcile squash-merged release #720
ng Sep 28, 2026
980a33b
Merge main into dev to reconcile squash-merged release #730
ng Sep 28, 2026
399d9bd
feat: redesign the web UI around what needs attention on each screen,…
ng Sep 29, 2026
d39ed1a
feat(ui): split the sidebar footer into health and full-length issues…
ng Sep 29, 2026
a7e1b65
chore(deps): Update @eslint/json dependency @eslint/json to v2 (#651)
renovate[bot] Sep 29, 2026
c176812
chore(deps): Update @vitejs/plugin-react dependency @vitejs/plugin-re…
renovate[bot] Sep 29, 2026
17d5369
feat: add an Eight Sleep-style Now/Night/Dawn temperature stepper (#740)
ng Sep 29, 2026
6d1b64f
docs: refresh README stepper capture and guide links (#743)
ng Sep 29, 2026
fad75e6
feat(ui): fold System β†’ Pipeline into Health's data path (#742)
ng Sep 29, 2026
2c9669a
fix(ui): make the Tonight timeline readable by merging schedule steps…
ng Sep 29, 2026
7139437
fix(ui): keep the temperature-control picker labels on one line on ph…
ng Sep 29, 2026
3831405
feat(ui): pod health dot on the phone System tab (#746)
ng Sep 29, 2026
e99323d
chore Lock file maintenance (#747)
renovate[bot] Sep 29, 2026
e4951f7
docs: link first-time Pod root-access walkthrough (#748)
ng Sep 30, 2026
a0f41b5
ci: back-merge main into dev after each release (#750)
ng Sep 30, 2026
d6788a4
Merge main into dev to reconcile squash-merged release #749
github-actions[bot] Sep 30, 2026
f7287cf
fix(piezo): repair the firmware's lost-sample markers (#736)
jasonlarue Sep 30, 2026
a488e46
fix(sleep-detector): Pod 3/4 movement above sensor noise, breathing f…
jasonlarue Sep 30, 2026
4ac7105
fix(health): pump reads unknown, not stalled, on pods without pump da…
jasonlarue Sep 30, 2026
203705f
fix(gestures): a temperature tap replaces the firmware's own adjustme…
jasonlarue Sep 30, 2026
ae38a4a
feat(ui): skeleton cards that load data before first paint (#751)
ng Sep 30, 2026
fbfcabd
fix(hardware): read a neutral firmware target as off while its countd…
ng Oct 1, 2026
d727e23
fix(homekit): round the requested temperature to whole Β°F so 28Β°C can…
ng Oct 1, 2026
0835c29
fix(api): keep a freshly mutated side's powered state on the status f…
ng Oct 1, 2026
069af10
fix(temperature): wait for the first firmware status before the recon…
ng Oct 1, 2026
a9e4602
test(hardware): assert stall-guard inputs and complete the stall-supp…
ng Oct 1, 2026
cc2e073
fix(hardware): derive a side's power from its commanded target, not t…
ng Oct 1, 2026
7eecbed
fix(temperature): treat device_state as unpowered until the firmware …
ng Oct 1, 2026
c44e17c
feat(mcp): intent-shaped MCP server over the tRPC API (#753)
ng Oct 1, 2026
f377d2a
feat(schedule): draw curves as steps over the measured bed temperatur…
ng Oct 1, 2026
7efcdc0
Merge main into dev to reconcile squash-merged release #761
github-actions[bot] Oct 1, 2026
0f69aff
docs: slim the README now that sleepypod.github.io hosts the guides (…
ng Oct 1, 2026
d4510c3
fix(ci): publish branch builds to one prerelease so feature branches …
ng Oct 2, 2026
959f12b
fix(ci): install feature branches from the Build & Package artifact a…
ng Oct 2, 2026
5a96282
feat(demo): hosted demo mode backed by in-browser fake pod data (#765)
ng Oct 2, 2026
74e05e0
test(automation): cover BiometricsSignalReader and #664 codecov gaps …
ng Oct 2, 2026
210beb4
fix(hardware): clear Pod timer when powering off (#713)
arubacao Oct 2, 2026
3cbbc1b
Merge main into dev to reconcile squash-merged release #769
github-actions[bot] Oct 3, 2026
0348650
Merge main into dev to reconcile squash-merged release #771
github-actions[bot] Oct 4, 2026
8b9ea0b
fix(alarms): alarm fixes β€” snooze, wake window and warm-up (#766)
jasonlarue Oct 5, 2026
698a579
fix(demo): add system.getSensorSource demo handler (#781)
ng Oct 5, 2026
0e5d4c4
test(alarms): cover missing branches from alarm fixes (#779)
ng Oct 5, 2026
571d558
fix(hardware): recover DAC connections after firmware restarts (#782)
ng Oct 6, 2026
fb76d05
feat(health): report V8 heap and native memory counters alongside RSS…
ng Oct 6, 2026
29bc210
chore(deps): Update @modelcontextprotocol/sdk all non-major dependenc…
renovate[bot] Oct 6, 2026
4f3991a
perf(system): probe firmware once per process for the sensor source c…
ng Oct 6, 2026
c29fc0b
test(hooks): kill useSensorStream surviving mutants (#591 hit list) (…
ng Oct 6, 2026
ff43df9
perf(temperature): take cron-parser and per-call ORM reads off the co…
ng Oct 6, 2026
0aeb906
fix(piezo-processor): no vitals while the bed reads empty (#768)
jasonlarue Oct 6, 2026
4d15c84
feat(base): add experimental adjustable-base controls, schedules and …
ng Oct 6, 2026
0e8e51e
fix(base): prevent 2D fallback flicker during 3D loading (#784)
ng Oct 6, 2026
2adc177
fix(hardware): prevent false pump stalls during startup (#786)
ng Oct 7, 2026
969d352
fix(installer): separate socket discovery from hardware identity (#785)
ng Oct 7, 2026
58ac83f
feat(settings): separate solo bed setup from partner away mode (#767)
jasonlarue Oct 7, 2026
13f0735
feat(temp): 3D thermal bed, temperature Stage and sweep-mode piezo (#…
ng Oct 8, 2026
d6e8806
feat(schedules): maintain temperature after a curve ends (#789)
ng Oct 8, 2026
c7fbe0c
test: cover release #783 gaps in Stage, Base and piezo views (#790)
ng Oct 8, 2026
19bb185
feat(settings): 24-hour time format, stored on the pod (#788)
ng Oct 8, 2026
4d8d19d
Merge main into dev to reconcile squash-merged release #783
github-actions[bot] Oct 8, 2026
c790e94
chore(deps): Update @lingui/babel-plugin-lingui-macro linguijs monore…
renovate[bot] Oct 8, 2026
624e625
chore(deps): Update @eslint/css dependency @eslint/css to v2 (#775)
renovate[bot] Oct 8, 2026
5eee4d5
chore(deps): drop redundant @babel/preset-typescript that blocks Babe…
ng Oct 8, 2026
a8a0ae3
Merge main into dev to reconcile squash-merged release #792
github-actions[bot] Oct 8, 2026
2c28d2e
feat(stage): make the Stage the Temperature screen default, with tone…
ng Oct 8, 2026
0d8ae98
fix(stage): say Off once in the side panel instead of twice (#795)
ng Oct 8, 2026
9f3d5ba
feat(schedule): curve deep links, smooth curves and leaner set points…
ng Oct 9, 2026
8b52e84
feat(temp): shared notice banners and toasts, and an away card state …
ng Oct 9, 2026
8077afa
Merge main into dev to reconcile squash-merged release #797
github-actions[bot] Oct 9, 2026
6d457ef
fix: fail clearly when the Pod has no build instead of crash-looping …
ng Oct 10, 2026
74110f7
fix: prevent priming from triggering false pump leak alerts (#798)
ng Oct 10, 2026
76a9110
Merge main into dev to reconcile squash-merged release #800
github-actions[bot] Oct 10, 2026
025ceae
fix: stop flashing the stalled-pipeline banner before the latest vita…
ng Oct 10, 2026
fa2f339
feat: ingest Apple Watch reference sleep stages for classifier calibr…
ng Oct 11, 2026
d091a11
feat: sleep-stage dataset builder joining Watch stages with pod vital…
ng Oct 11, 2026
0fd1a85
fix: end sessions when the bed empties to a new level and score movem…
ng Oct 11, 2026
9441c62
fix: make the Stage's SCHEDULED label readable at 80Β° (#806)
ng Oct 11, 2026
84293dd
feat: per-side tabs inside Settings sections replace the global side …
ng Oct 11, 2026
e7c3b2f
feat: away mode toggle in the side card and Stage panel (#808)
ng Oct 11, 2026
cf46b5d
fix(sleep): classify stages with the side's piezo calibration quality…
ng Oct 12, 2026
83394a3
chore(deps): Update @lingui/swc-plugin dependency @lingui/swc-plugin …
renovate[bot] Oct 12, 2026
339925c
chore(deps): Update @semantic-release/git dependency @semantic-releas…
renovate[bot] Oct 12, 2026
84c09b7
fix: let cap-sense occupancy relax piezo presence re-entry so quiet s…
ng Oct 12, 2026
a50eb71
feat(sleep): let users define the sleep stage classification rules (#…
ng Oct 12, 2026
16fecf7
chore(deps): Update @base-ui/react all non-major dependencies (#818)
renovate[bot] Oct 12, 2026
ea3a598
fix(build): pin @babel/runtime to 7.29.7 so Turbopack resolves mqtt's…
ng Oct 12, 2026
add1507
fix(sleep): do not classify the week view at full quality while calib…
ng Oct 12, 2026
3e9027e
feat: import Apple Watch heart rate into the pod and overlay it on th…
ng Oct 12, 2026
6253b97
feat(biometrics): explore vitals and import Apple Watch data (#821)
ng Oct 12, 2026
0cd3151
feat(sleep): sleep stage rules as sentences with quick adjust, previe…
ng Oct 13, 2026
0922bc0
feat(mcp): sleep-stage rule inspection, dry-run preview and apply aga…
ng Oct 13, 2026
2a42ce9
feat(mcp): build and save a sleep curve from pod data (#825)
ng Oct 14, 2026
7e58793
feat(curves): save named curves on the pod (#827)
ng Oct 14, 2026
4ea6aa5
feat(schedule): optional notes on curves (#832)
ng Oct 14, 2026
d4df234
fix(biometrics): accept same-origin Watch uploads and use a button fo…
ng Oct 14, 2026
e681908
fix(security): reject unknown Host headers so DNS-rebinding pages can…
ng Oct 14, 2026
b18e100
fix(stream): gate the sensor WebSocket handshake on the Host/Origin a…
ng Oct 14, 2026
0e7e865
feat(biometrics): add versioned calibration profiles, references and …
ng Oct 14, 2026
35e6141
feat(biometrics): add retained backtest replay engine and isolated pa…
ng Oct 14, 2026
d5dd2dd
feat(biometrics): add prospective shadow runtime, coordinator host an…
ng Oct 14, 2026
f905a77
feat(biometrics): add calibration UI, browser tests and docs (#831)
ng Oct 14, 2026
cbc5387
feat: experimental presence auto-on with person-vs-pet occupancy clas…
ng Oct 14, 2026
9a806e5
Merge main into dev to reconcile squash-merged release #820
github-actions[bot] Oct 14, 2026
a9d10d4
feat(schedule): schedule library with switchable curves (#835)
ng Oct 14, 2026
87e4c36
fix(scripts): grant journal read access to sleepypod service user (#801)
onemec Oct 15, 2026
c2eb532
fix(sensors): prevent false high TEC and slow fan warnings on idling …
onemec Oct 15, 2026
2a062e3
feat(calibration): one-page biometric calibration (design 2a) (#836)
ng Oct 18, 2026
593bb89
fix(biometrics): stop Next truncating Health export uploads at 10 MB …
ng Oct 18, 2026
c8a4243
feat(biometrics): export frozen calibration datasets and fit profiles…
ng Oct 18, 2026
36f1dc3
fix(biometrics): reject oversized bundle entries before writing and b…
ng Oct 18, 2026
928d7ec
feat(biometrics): let the HR estimator report nothing instead of a we…
ng Oct 18, 2026
1dc8a07
feat(storage): eMMC endurance card and RAM-only journal (#838)
ng Oct 18, 2026
02b1287
feat(biometrics): import Watch breathing rate and HRV from Health upl…
ng Oct 18, 2026
a11a599
feat(biometrics): read-only analysis snapshot export (DB backup + RAW…
ng Oct 18, 2026
53ec586
feat(biometrics): pod-vs-Apple-Watch deviation report (API + MCP comp…
ng Oct 18, 2026
d5a1a26
feat(biometrics): archive pod biometrics off the pod for long-term Wa…
ng Oct 18, 2026
1365e5a
fix(biometrics): archive same-second calibration runs as separate row…
ng Oct 18, 2026
82f23d4
feat(biometrics): night-by-night deviation from Apple Watch on the ca…
ng Oct 18, 2026
f7e3a1e
test(hooks): kill useCurveTemplates.ts surviving mutants (#591 hit li…
ng Oct 19, 2026
3adf8e9
feat(storage): add flash write insights and recording controls (#854)
ng Oct 19, 2026
6afc8a4
fix(gestures): set a tap's normal and while-ringing actions independe…
jasonlarue Oct 19, 2026
9a0b43b
Personal stage models: train off the pod on the phone's feature contr…
ng Oct 20, 2026
8317589
chore: delete the pod snapshot after a personal-model training run (#…
ng Oct 20, 2026
14a7cda
feat: pin the personal forest at depth 8 from a held-out sweep (#858)
ng Oct 20, 2026
bae14c2
feat: stage a side's nights with its personal model when switched on …
ng Oct 21, 2026
8a385aa
feat(piezo-processor): beat-to-beat heartbeat detection (#848)
jasonlarue Oct 21, 2026
e251556
feat(sleep): manage personal models and compare Watch sleep data (#860)
ng Oct 22, 2026
09e1001
feat(mcp): personal stage model tools (#864)
ng Oct 23, 2026
50216dd
fix: internet access toggle after a reboot, and no false 'firewall ru…
jasonlarue Oct 23, 2026
5cb54f2
feat(alarms): snooze length on the alarm, with Snooze taper (#861)
jasonlarue Oct 23, 2026
60f6093
fix(training): preview candidates safely and preserve Watch label gap…
ng Oct 24, 2026
16daf32
fix(biometrics): render Watch-only nights and stable reference sample…
ng Oct 24, 2026
502457d
fix(piezo): bound heartbeat retries with ordered backoff (#865)
ng Oct 25, 2026
47034d4
fix(deps): upgrade Next.js to 16.4.3 for three security advisories (#…
jasonlarue Oct 25, 2026
56e61fc
fix(biometrics): register sensHealth, frzWater, and lps as known reco…
onemec Oct 28, 2026
733068b
feat(settings): add Europe/Bucharest to the timezone options (#874)
MihaiSprinceana Oct 28, 2026
82105c6
fix: enforce patched Node.js in development and pod installs (#868)
ng Oct 29, 2026
bed309b
chore(deps): Update @babel/runtime all non-major dependencies (#853)
renovate[bot] Oct 29, 2026
00be07e
fix(renovate): remove invalid 'fix' from matchUpdateTypes (#875)
onemec Oct 29, 2026
6e736b9
chore(deps): Update @stryker-mutator/core stryker-js monorepo to v10 …
renovate[bot] Oct 29, 2026
1fbb953
feat(ui): surface frzWater tank level and sensHealth cover disconnect…
ng Oct 29, 2026
d2881f0
Merge main into dev to reconcile squash-merged release #878
github-actions[bot] Oct 30, 2026
991d8e1
fix(firewall): block every Eight Sleep domain and stop the stock log …
ng Oct 30, 2026
f60b421
feat(search): sidebar command palette with ⌘K and BM25 ranking (#882)
ng Oct 30, 2026
a0cf0de
Merge main into dev to reconcile squash-merged release #886
github-actions[bot] Oct 30, 2026
4750c3b
fix(firewall): apply telemetry blocking on the first update from olde…
ng Oct 30, 2026
35f2057
fix(firewall): let Settings allow internet again and keep the choice …
ng Oct 30, 2026
c67189b
Merge main into dev to reconcile squash-merged release #889
github-actions[bot] Oct 30, 2026
46486ec
fix(firewall): blackhole Eight Sleep names with NXDOMAIN, not 0.0.0.0…
ng Oct 30, 2026
29afbb7
fix(firewall): mask the stock firmware updater and watchdog; make fir…
ng Oct 30, 2026
1333aac
Merge main into dev to reconcile squash-merged release #893
github-actions[bot] Oct 30, 2026
4d6f0a9
fix(firewall): mask the stock dac app and use conntrack in the boot r…
ng Oct 31, 2026
7df3724
Merge main into dev to reconcile squash-merged release #895
github-actions[bot] Oct 31, 2026
9ce5966
docs(readme): add Python modules, docs and live demo badges (#896)
ng Oct 31, 2026
7ddf0dd
docs(readme): refresh web, iOS and dial images from the docs site (#897)
ng Oct 31, 2026
409918a
docs: cross-reference seedypod from the README and ADR 0023 (#898)
ng Oct 31, 2026
f4b3edb
fix(biometrics): stop a stale heart-rate level from doubling a whole …
ng Nov 1, 2026
48c033a
feat(search): search the docs site from the command palette (#900)
ng Nov 1, 2026
6cf0c24
Merge main into dev to reconcile squash-merged release #901
github-actions[bot] Nov 1, 2026
b5711fd
test: keep #828's real-Python and byte-pinning tests out of Stryker s…
ng Nov 2, 2026
9a4a1e0
test: kill bridge.ts and useSensorStream.ts surviving mutants (#591 h…
ng Nov 2, 2026
6179822
feat(sleep-stages): podContext feature contract for personal stage mo…
ng Nov 3, 2026
e3b06eb
feat(biometrics): let wearables report optional metrics with their de…
ng Nov 5, 2026
546b8a5
feat(biometrics): import and overlay optional Watch RMSSD (#909)
ng Nov 6, 2026
36b1408
feat(biometrics): group the vitals legend by device (#910)
ng Nov 6, 2026
bc473bb
feat(biometrics): show Apple Watch blood oxygen in its own vitals row…
ng Nov 6, 2026
800e7eb
feat(biometrics): store Apple Watch movement on the pod and overlay i…
ng Nov 6, 2026
a2a75ea
fix(biometrics): find Apple Watch readings by device so a renamed sou…
ng Nov 6, 2026
9606f5a
feat(scripts): add sp-welcome, a logo and live facts screen for the p…
ng Nov 7, 2026
11d2064
fix: read biometrics telemetry from rawmem NATS subjects (#917)
ng Nov 8, 2026
ab2088d
feat: make the NATS subject prefix a setting the UI and MCP can chang…
ng Nov 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions app/api/biometrics/watch-motion/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { biometricsDb } from '@/src/db'
import { getWatchMotionFile } from '@/src/biometrics/references/watch-motion'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

/** The stored, trimmed canonical file: byte-for-byte what training imports. */
export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }): Promise<Response> {
const { id } = await params
if (!/^[1-9]\d{0,15}$/.test(id)) return Response.json({ error: 'Invalid id' }, { status: 400 })
const file = getWatchMotionFile(biometricsDb, Number(id))
if (file === null) return Response.json({ error: 'Not found' }, { status: 404 })
return new Response(file, { headers: { 'Content-Type': 'application/json' } })
}
168 changes: 168 additions & 0 deletions app/api/biometrics/watch-motion/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// @vitest-environment node
import { createHash } from 'node:crypto'
import { beforeEach, expect, it, vi } from 'vitest'

const state = vi.hoisted(() => ({ db: null as unknown, raw: null as { exec: (sql: string) => void } | null }))
vi.mock('@/src/db', async () => {
const Database = (await import('better-sqlite3')).default
const { drizzle } = await import('drizzle-orm/better-sqlite3')
const { migrate } = await import('drizzle-orm/better-sqlite3/migrator')
const schema = await import('@/src/db/biometrics-schema')
const raw = new Database(':memory:')
const db = drizzle(raw, { schema })
migrate(db, { migrationsFolder: 'src/db/biometrics-migrations' })
state.db = db
state.raw = raw
return { biometricsDb: db }
})

const { POST, GET } = await import('./route')
const { GET: GET_ONE } = await import('./[id]/route')

const FROM = 1_793_618_344_598
const TO = FROM + 8 * 3600_000
const FIRST_BIN = Math.floor(FROM / 2000) * 2000 // overlaps the start edge, so it is kept

function file(version: 'watch-motion-v1' | 'watch-motion-v2', starts: number[], extra: Record<string, unknown> = {}) {
const axes = version === 'watch-motion-v2' ? { meanX: starts.map(() => 0.1), meanY: starts.map(() => -0.2), meanZ: starts.map(() => 0.97) } : {}
return {
version, recordedFromMs: FROM, recordedToMs: TO, timeZone: 'America/Los_Angeles', utcOffsetSeconds: -28800,
sampleRateHz: 50, binSeconds: 2, jerkThresholdGPerSecond: 1, device: 'Apple Watch Β· watchOS 26.6',
bins: { startMs: starts, samples: starts.map(() => 100), meanMagnitude: starts.map(() => 1), magnitudeVariance: starts.map((_, i) => i * 1e-6),
maxJerk: starts.map((_, i) => i % 7), movingSamples: starts.map((_, i) => i % 3), ...axes },
...extra,
}
}
const night = Array.from({ length: 90 }, (_, i) => FIRST_BIN + i * 2000)
/** The same file with a bin prepended to every column, as the Watch recorder's leftovers. */
function withStray(f: ReturnType<typeof file>, startMs: number) {
return { ...f, bins: Object.fromEntries(Object.entries(f.bins).map(([column, values]) => [column, [column === 'startMs' ? startMs : 1, ...values]])) }
}

const post = (body: unknown, side = 'left', headers: Record<string, string> = {}) => POST(new Request(`http://pod/api/biometrics/watch-motion?side=${side}`, {
method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body),
}))

beforeEach(() => state.raw?.exec('DELETE FROM watch_motion_captures'))

it('accepts a v1 file and serves the stored canonical file back byte-for-byte', async () => {
const response = await post(file('watch-motion-v1', night))
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toEqual({ id: expect.any(Number), side: 'left', version: 'watch-motion-v1', recordedFromMs: FROM, recordedToMs: TO, bins: 90, trimmedBins: 0, status: 'created' })
const stored = await GET_ONE(new Request('http://pod'), { params: Promise.resolve({ id: String(body.id) }) })
expect(stored.headers.get('content-type')).toBe('application/json')
const text = await stored.text()
expect(JSON.parse(text)).toEqual(file('watch-motion-v1', night))
// Keys sorted at every level, like the iOS encoder.
expect(text.indexOf('"binSeconds"')).toBeLessThan(text.indexOf('"bins"'))
expect(text.indexOf('"magnitudeVariance"')).toBeLessThan(text.indexOf('"startMs"'))
const [listed] = await (await GET(new Request('http://pod/api/biometrics/watch-motion?side=left'))).json()
expect(listed).toMatchObject({ id: body.id, sha256: createHash('sha256').update(text).digest('hex'), bins: 90, trimmedBins: 0 })
})

it('accepts a v2 file with axis means', async () => {
const response = await post(file('watch-motion-v2', night), 'right')
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toMatchObject({ side: 'right', version: 'watch-motion-v2', bins: 90, status: 'created' })
const stored = JSON.parse(await (await GET_ONE(new Request('http://pod'), { params: Promise.resolve({ id: String(body.id) }) })).text())
expect(stored.bins.meanZ).toHaveLength(90)
})

it('trims a stray bin from an earlier recording and counts it', async () => {
const stray = FROM - 20 * 3600_000 - (FROM - 20 * 3600_000) % 2000
const after = Math.ceil(TO / 2000) * 2000
const response = await post(file('watch-motion-v2', [stray, stray + 2000, ...night, after]))
expect(await response.json()).toMatchObject({ bins: 90, trimmedBins: 3, status: 'created' })
const [listed] = await (await GET(new Request(`http://pod/api/biometrics/watch-motion?startDate=${FROM}&endDate=${new Date(TO).toISOString()}`))).json()
expect(listed).toMatchObject({ bins: 90, trimmedBins: 3, recordedFromMs: FROM })
const stored = JSON.parse(await (await GET_ONE(new Request('http://pod'), { params: Promise.resolve({ id: String(listed.id) }) })).text())
expect(stored.bins.startMs[0]).toBe(FIRST_BIN)
expect(stored.bins.meanX).toHaveLength(90)
// Each kept bin keeps its own values.
expect(stored.bins.maxJerk).toEqual(night.map((_, i) => (i + 2) % 7))
})

it('reports unchanged for identical content and replaced for new content of the same night', async () => {
const first = await (await post(file('watch-motion-v1', night))).json()
// A fixed app resending without the stray bin stores the same trimmed file.
const again = await (await post(withStray(file('watch-motion-v1', night), FIRST_BIN - 40 * 3600_000))).json()
expect(again).toMatchObject({ id: first.id, status: 'unchanged', trimmedBins: 1 })
const replaced = await (await post(file('watch-motion-v2', night))).json()
expect(replaced).toMatchObject({ id: first.id, status: 'replaced', version: 'watch-motion-v2' })
expect(await (await GET(new Request('http://pod/api/biometrics/watch-motion'))).json()).toHaveLength(1)
// The other side is a separate capture.
expect(await (await post(file('watch-motion-v1', night), 'right')).json()).toMatchObject({ status: 'created' })
})

it('rejects raw readings, oversize bodies and invalid files', async () => {
const rawResponse = await post(file('watch-motion-v1', night, { raw: [[FROM, 0, 0, 1]] }))
expect(rawResponse.status).toBe(400)
expect(await rawResponse.json()).toEqual({ error: 'raw readings are not accepted' })

expect((await post('x', 'left', { 'content-length': String(8 * 1024 * 1024 + 1) })).status).toBe(413)
const chunk = new Uint8Array(1)
Object.defineProperty(chunk, 'byteLength', { value: 8 * 1024 * 1024 + 1 })
const stream = new ReadableStream({ start(controller) {
controller.enqueue(chunk)
controller.close()
} })
const streamed = await POST(new Request('http://pod/api/biometrics/watch-motion?side=left', { method: 'POST', body: stream, duplex: 'half' } as RequestInit))
expect(streamed.status).toBe(413)

const mismatched = file('watch-motion-v1', night)
mismatched.bins.maxJerk.pop()
const cases: Array<[unknown, RegExp]> = [
[mismatched, /bins\.maxJerk differ/],
[file('watch-motion-v1', night, { version: 'watch-motion-v3' }), /version/],
[file('watch-motion-v1', night, { binSeconds: 1 }), /binSeconds/],
[file('watch-motion-v2', night, { bins: { ...file('watch-motion-v1', night).bins } }), /v2 requires/],
[file('watch-motion-v1', night, { bins: file('watch-motion-v2', night).bins }), /v1 must not/],
[file('watch-motion-v1', [FIRST_BIN, FIRST_BIN + 1000]), /multiple of 2000/],
[file('watch-motion-v1', [FIRST_BIN + 2000, FIRST_BIN]), /strictly increasing/],
[file('watch-motion-v1', [FIRST_BIN, FIRST_BIN + 2000], { bins: { ...file('watch-motion-v1', [FIRST_BIN, FIRST_BIN + 2000]).bins, movingSamples: [1, -1] } }), /movingSamples/],
[file('watch-motion-v1', [FIRST_BIN, FIRST_BIN + 2000], { bins: { ...file('watch-motion-v1', [FIRST_BIN, FIRST_BIN + 2000]).bins, samples: [1.5, 2] } }), /samples/],
[file('watch-motion-v1', [FIRST_BIN - 3600_000]), /No bins fall inside/],
[file('watch-motion-v1', night, { recordedToMs: FROM }), /recordedToMs must be after/],
[file('watch-motion-v1', night, { extra: 1 }), /extra/],
]
for (const [body, message] of cases) {
const response = await post(body)
expect(response.status, String(message)).toBe(400)
expect((await response.json()).error).toMatch(message)
}
// JSON.parse turns 1e999 into Infinity.
const infinite = JSON.stringify(file('watch-motion-v1', [FIRST_BIN])).replace('"maxJerk":[0]', '"maxJerk":[1e999]')
expect((await post(infinite)).status).toBe(400)
expect((await post('{not json')).status).toBe(400)
expect((await post('')).status).toBe(400)
expect((await POST(new Request('http://pod/api/biometrics/watch-motion', { method: 'POST', body: '{}' }))).status).toBe(400)
expect(await (await GET(new Request('http://pod/api/biometrics/watch-motion'))).json()).toEqual([])
})

it('rejects cross-origin and DNS-rebinding uploads but accepts the same-origin web app', async () => {
for (const origin of ['http://evil', 'http://192.168.1.88:8080', 'null']) {
const response = await post(file('watch-motion-v1', night), 'left', { origin, host: '192.168.1.88:3000' })
expect(response.status).toBe(403)
}
const rebound = await post(file('watch-motion-v1', night), 'left', { origin: 'http://attacker.example.com:3000', host: 'attacker.example.com:3000' })
expect(rebound.status).toBe(403)
expect(await (await GET(new Request('http://pod/api/biometrics/watch-motion'))).json()).toEqual([])
const same = await post(file('watch-motion-v1', night), 'left', { origin: 'http://192.168.1.88:3000', host: '192.168.1.88:3000' })
expect(same.status).toBe(200)
})

it('lists by overlap and validates list and fetch parameters', async () => {
await post(file('watch-motion-v1', night))
const list = (query: string) => GET(new Request(`http://pod/api/biometrics/watch-motion?${query}`))
expect(await (await list(`startDate=${TO}`)).json()).toEqual([])
expect(await (await list(`endDate=${FROM - 1}`)).json()).toEqual([])
expect(await (await list(`startDate=${TO - 1}&endDate=${TO + 1}&side=left`)).json()).toHaveLength(1)
expect(await (await list('side=right')).json()).toEqual([])
expect((await list('side=middle')).status).toBe(400)
expect((await list('startDate=yesterday')).status).toBe(400)
expect((await list(`startDate=${TO}&endDate=${FROM}`)).status).toBe(400)
expect((await GET_ONE(new Request('http://pod'), { params: Promise.resolve({ id: '999' }) })).status).toBe(404)
expect((await GET_ONE(new Request('http://pod'), { params: Promise.resolve({ id: '../x' }) })).status).toBe(400)
})
103 changes: 103 additions & 0 deletions app/api/biometrics/watch-motion/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { z } from 'zod'
import { biometricsDb } from '@/src/db'
import { rejectUnknownHost } from '@/src/lib/hostAllowlist'
import {
listWatchMotion, parseWatchMotion, saveWatchMotion, WATCH_MOTION_MAX_BYTES, WatchMotionError,
} from '@/src/biometrics/references/watch-motion'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

const sideQuery = z.object({ side: z.enum(['left', 'right']) })
/** ISO 8601 text or Unix milliseconds. */
const dateParam = z.string().transform((value, ctx) => {
const date = new Date(/^\d+$/.test(value) ? Number(value) : value)
if (Number.isNaN(date.getTime())) {
ctx.addIssue({ code: 'custom', message: 'must be ISO 8601 or Unix milliseconds' })
return z.NEVER
}
return date
})
const listQuery = z.object({ side: z.enum(['left', 'right']).optional(), startDate: dateParam.optional(), endDate: dateParam.optional() }).strict()

/** Same check as watch-upload: Next reports the 0.0.0.0 bind address in request.url, so compare Origin with Host. */
function isSameOrigin(request: Request): boolean {
const origin = request.headers.get('origin')
if (origin === null) return true
try {
return new URL(origin).host === request.headers.get('host')
}
catch {
return false
}
}

class TooLarge extends Error {}

/** The body as text, refusing to buffer more than the limit even without a Content-Length. */
async function readBody(request: Request): Promise<string> {
if (Number(request.headers.get('content-length')) > WATCH_MOTION_MAX_BYTES) throw new TooLarge()
if (!request.body) return ''
const chunks: Uint8Array[] = []
let bytes = 0
const reader = request.body.getReader()
for (;;) {
const { done, value } = await reader.read()
if (done) break
bytes += value.byteLength
if (bytes > WATCH_MOTION_MAX_BYTES) {
await reader.cancel()
throw new TooLarge()
}
chunks.push(value)
}
return Buffer.concat(chunks).toString('utf8')
}

/**
* One night's watch-motion-v1/v2 file from the iOS app, as-is. Stored as a
* movement label only (see docs/biometrics-reference-imports.md).
*/
export async function POST(request: Request): Promise<Response> {
const rejectedHost = rejectUnknownHost(request)
if (rejectedHost) return rejectedHost
if (!isSameOrigin(request)) return Response.json({ error: 'Cross-origin upload is not allowed' }, { status: 403 })
const query = sideQuery.safeParse(Object.fromEntries(new URL(request.url).searchParams))
if (!query.success) return Response.json({ error: 'Specify side=left|right' }, { status: 400 })
let body: string
try {
body = await readBody(request)
}
catch (error) {
if (error instanceof TooLarge) return Response.json({ error: 'Upload exceeds 8 MiB' }, { status: 413 })
return Response.json({ error: 'Upload interrupted' }, { status: 400 })
}
if (!body) return Response.json({ error: 'Send the watch-motion JSON file as the request body' }, { status: 400 })
try {
const parsed = parseWatchMotion(body)
const { capture, status } = saveWatchMotion(biometricsDb, query.data.side, parsed)
return Response.json({
id: capture.id,
side: capture.side,
version: capture.version,
recordedFromMs: capture.recordedFromMs,
recordedToMs: capture.recordedToMs,
bins: capture.bins,
trimmedBins: parsed.trimmedBins,
status,
})
}
catch (error) {
if (error instanceof WatchMotionError) return Response.json({ error: error.message }, { status: error.status })
return Response.json({ error: 'Could not store the recording' }, { status: 500 })
}
}

/** Capture metadata overlapping [startDate, endDate], oldest first. */
export async function GET(request: Request): Promise<Response> {
const query = listQuery.safeParse(Object.fromEntries(new URL(request.url).searchParams))
if (!query.success) return Response.json({ error: 'Use side=left|right and startDate/endDate as ISO 8601 or Unix milliseconds' }, { status: 400 })
const { side, startDate, endDate } = query.data
if (startDate && endDate && startDate > endDate) return Response.json({ error: 'startDate must be before or equal to endDate' }, { status: 400 })
return Response.json(listWatchMotion(biometricsDb, { side, start: startDate, end: endDate }))
}
10 changes: 6 additions & 4 deletions app/api/biometrics/watch-upload/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,18 @@ it('imports Watch breathing rate and HRV, skips records sleepypod wrote to Healt
const xml = `<HealthData>${[
record('RespiratoryRate', 'Apple Watch', 14.5, 'count/min'),
record('HeartRateVariabilitySDNN', 'Apple Watch', 48, 'ms'),
record('HeartRateVariabilityRMSSD', 'Apple Watch', 0.032, 's'),
record('OxygenSaturation', 'Apple Watch', 0.97, '%'),
// The pod's own readings written back by the iOS app, even from a source named like a Watch.
record('RespiratoryRate', 'sleepypod', 99, 'count/min'),
record('HeartRateVariabilitySDNN', 'sleepypod design', 99, 'ms'),
record('HeartRate', 'sleepypod Watch', 99, 'count/min'),
].join('')}</HealthData>`
const request = () => new Request('http://pod/api/biometrics/watch-upload?side=left&days=7', { method: 'POST', body: xml })
expect(await (await POST(request())).json()).toEqual({ stages: 0, vitals: 0, breathing: 1, hrv: 1, rejectedStageBatches: 0,
matchedStages: 0, matchedVitals: 0, matchedBreathing: 1, matchedHrv: 1 })
expect(requests.map(r => [r.metric, r.side, r.samples?.map(s => s.value)])).toEqual([['breathing_rate', 'left', [14.5]], ['hrv_sdnn', 'left', [48]]])
expect(await (await POST(request())).json()).toMatchObject({ breathing: 0, hrv: 0, matchedBreathing: 1, matchedHrv: 1 })
expect(await (await POST(request())).json()).toEqual({ stages: 0, vitals: 0, breathing: 1, hrv: 1, rmssd: 1, oxygen: 1, rejectedStageBatches: 0,
matchedStages: 0, matchedVitals: 0, matchedBreathing: 1, matchedHrv: 1, matchedRmssd: 1, matchedOxygen: 1 })
expect(requests.map(r => [r.metric, r.side, r.samples?.map(s => s.value)])).toEqual([['breathing_rate', 'left', [14.5]], ['hrv_sdnn', 'left', [48]], ['hrv_rmssd', 'left', [32]], ['blood_oxygen', 'left', [97]]])
expect(await (await POST(request())).json()).toMatchObject({ breathing: 0, hrv: 0, matchedBreathing: 1, matchedHrv: 1, matchedRmssd: 1 })
})

it('rejects malformed files and cleans up after parser failure', async () => {
Expand Down
4 changes: 2 additions & 2 deletions app/api/biometrics/watch-upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
const MAX_BYTES = 512 * 1024 * 1024
const options = z.object({ side: z.enum(['left', 'right']), days: z.coerce.number().int().min(1).max(90).default(30) })
const resultSchema = z.object({ stages: z.number(), vitals: z.number(), breathing: z.number(), hrv: z.number(), rejectedStageBatches: z.number(),
matchedStages: z.number(), matchedVitals: z.number(), matchedBreathing: z.number(), matchedHrv: z.number() })
const resultSchema = z.object({ stages: z.number(), vitals: z.number(), breathing: z.number(), hrv: z.number(), rmssd: z.number().default(0), oxygen: z.number().default(0), rejectedStageBatches: z.number(),
matchedStages: z.number(), matchedVitals: z.number(), matchedBreathing: z.number(), matchedHrv: z.number(), matchedRmssd: z.number().default(0), matchedOxygen: z.number().default(0) })
const shared = globalThis as typeof globalThis & { watchUploadBusy?: boolean }

/**
Expand Down
5 changes: 4 additions & 1 deletion docs/DEBUGGING.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ reads red/amber while the bed is occupied, the ingest pipeline has stalled.
in-app equivalent of the `biometrics pipeline` section of `sp-status`
(`docs/nats-frame-readers.md` β†’ "Surfacing the selection in the app"). On
NATS firmware, stop here: there are no `.RAW` files to inspect, and an
empty `/persistent/biometrics` is expected.
empty `/persistent/biometrics` is expected. If no frames arrive and
**Publishing prefixes** lists one marked "(not read)", set **Subject
prefix** to it, then **Restart biometrics modules** (an MCP agent:
`get_sensor_source`, then `set_device_settings` with `natsSubjectPrefix`).
1. Confirm `RAW_DATA_DIR` matches the tmpfs hot dir (`/persistent/biometrics`,
per ADR-0018). A mismatch makes readers see an empty directory while frank
writes fine β€” the classic silent failure (`docs/sleep-detector.md` Β§9).
Expand Down
Loading
Loading