Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
fd70934
feat(sleep): hybrid HMM emission over HR + RMSSD + ENMO + skin temp
mistral-vibe Nov 18, 2026
435b2c9
feat(sleep): three-level self-calibration — nightly + 7d rolling + lo…
mistral-vibe Nov 18, 2026
a5ca173
feat(sleep): AASM-aligned wake rules + multi-night calibration for sk…
mistral-vibe Nov 18, 2026
204da9f
fix(sleep): motion baseline from the stable core of the night, not th…
mistral-vibe Nov 18, 2026
98c5829
fix(review): address CodeRabbit findings on #756
mistral-vibe Nov 18, 2026
065c203
feat(sleep): weak HR-only wake bonus for quiet wakefulness (issue #59…
mistral-vibe Nov 18, 2026
90a879b
feat(sleep): persist nightly ENMO median and self-calibrate motion ac…
mistral-vibe Nov 18, 2026
2d07484
test(sleep): pin HMM provenance, cardio parity and flag invalidation
mikenrafter Nov 19, 2026
54658d1
feat(sleep): persist HMM provenance and key workers by staging choice
mikenrafter Nov 19, 2026
f5bbee7
test(sleep): pin cardio parity fixture timezone
mikenrafter Nov 19, 2026
5c86dfe
test(sleep): cover vendor fallback and imported worker choices
mikenrafter Nov 19, 2026
b6b1d9b
fix(sleep): preserve every HMM input path and cardio goldens
mikenrafter Nov 19, 2026
2873fea
fix(sleep): retain provenance on no-sleep reads
mikenrafter Nov 19, 2026
65ad82b
merge #763 stack onto main
abdulsaheel Nov 21, 2026
f5b133a
hmm: absent motion stays neutral, gap holds state, recalibrate baseli…
abdulsaheel Nov 21, 2026
8eaf804
hmm: clamp measured enmo at 0, no wake smoothing across fallback seconds
abdulsaheel Nov 21, 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
4 changes: 4 additions & 0 deletions docs/lexicon.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@
- Layout sibling: the previous or next unit in the target's enclosing vertical layout. Transforms and viewport clipping preserve this relation.
- Placeholder: replacement text bars, an empty ring track or a muted plot sine, painted over the existing surface. Icons, images and card titles keep their source paint.
- Unscoped guide content: a page-wide selector, such as every pressable row. It does not identify a particular control on a neighbouring step.

## Sleep staging

- Staging provenance: a night's requested method, effective method and observed seconds that retained the original labels after an HMM abstention. `hmm_cardio` means HMM and cardio both contributed; `hmm_vendor_staged` means HMM and a paired device both contributed. An absent field means unknown; it does not mean cardio or zero fallback. Avoid calling the requested method the effective method.
35 changes: 33 additions & 2 deletions lib/compute/derivation_engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2684,6 +2684,7 @@ class _BaselineHistoryCache {
'rhr',
'resp_rate',
'skin_temp_adc',
'enmo_median_night',
'readiness',
// The readiness composite z — later days' scores are calibrated against
// its spread (`calibratedReadinessScore`).
Expand Down Expand Up @@ -4453,7 +4454,9 @@ class DerivationEngine {
// rows, which the signature check rejects. Read after, it would attach the
// newer revision to rows that predate it and certify a stale ceiling.
final ceilingInput = await _ceilingInputRevision(dayId);
final candidate = await _sleepCandidateForDay(dayId, stats: stats, union: union);
final useHmmStages = await _hmmStagesOn();
final candidate = await _sleepCandidateForDay(dayId, stats: stats, union: union,
useHmmStages: useHmmStages);
final dayStart = _localDayLabelToSec(dayId);
final dayEnd = _localNextDayLabelToSec(dayId);

Expand Down Expand Up @@ -4570,6 +4573,7 @@ class DerivationEngine {
sleepOffsetSec: candidate.present ? candidate.sleepOffsetSec : 0,
);
final prepared = candidate.toPreparedDay(
useHmmStages: useHmmStages,
daySub: daySub,
napSub: napSub,
sleepSub: sleepSub,
Expand Down Expand Up @@ -4727,7 +4731,9 @@ class DerivationEngine {
String dayId, {
_PrepareStats? stats,
_PrepareUnion? union,
bool? useHmmStages,
}) async {
final hmmStages = useHmmStages ?? await _hmmStagesOn();
// A user sleep override is the source of truth — never serve the cached auto
// candidate, and don't cache the override result (so a later edit / clear is
// not shadowed by a stale artifact). The auto path keeps its finalized cache.
Expand Down Expand Up @@ -4931,6 +4937,7 @@ class DerivationEngine {
vendorNights: vendorNights,
activeWearable: stagingWearable,
prefixContext: prefixContext,
useHmmStages: hmmStages,
);
if (revisions != null && !debugDisableStagedSleepCache) stagingKey = inputKey(false);
if (checkpointPlan != null) {
Expand Down Expand Up @@ -6782,6 +6789,7 @@ class DerivationEngine {
);
await _derivePreparedDay(
PreparedDerivationDay(
useHmmStages: await _hmmStagesOn(),
date: day.date,
endSec: day.endSec,
confidence: day.confidence,
Expand Down Expand Up @@ -6894,6 +6902,23 @@ class DerivationEngine {
sleepRrTsMs: sleepSub.rrTsMs,
sleepRrMs: sleepSub.rrMs,
sleepSkinTemp: sleepSub.skinTemp,
// Per-second ENMO over the sleep window (gravity vector magnitude − 1 g),
// for the hybrid HMM input. Absent accel (0,0,0 sentinel) -> 0.0, which
// the classifier reads as "no motion evidence", never "still".
sleepEnmo: [
for (var i = 0; i < sleepSub.tsSec.length; i++)
sleepSub.accelPresentAt(i)
? math.max(
0.0,
math.sqrt(
sleepSub.ax[i] * sleepSub.ax[i] +
sleepSub.ay[i] * sleepSub.ay[i] +
sleepSub.az[i] * sleepSub.az[i],
) -
1.0,
)
: -1.0, // absent sentinel (CodeRabbit #756): measured zero motion is >= 0
],
sleepJson: day.sleepJson,
hypnoStages: day.hypnoStages,
sleepOnsetSec: day.sleepOnsetSec,
Expand All @@ -6910,7 +6935,7 @@ class DerivationEngine {
// guess — sleep-onset latency only means what people think it means on a
// forced window.
sleepSource: day.sleepSource,
useHmmStages: await _hmmStagesOn(),
useHmmStages: day.useHmmStages,
);
final withHistory = _attachHistory(input, history);

Expand Down Expand Up @@ -7764,6 +7789,10 @@ class DerivationEngine {
// EVERY day (even during the bootstrap window where skin_temp_z is null)
// so the baseline fills and z begins computing from ~day 4.
'skin_temp_adc': sc('skin_temp_adc'),
// The night's stable-core ENMO median, only for HMM-restaged nights
// (null otherwise -> no series row, history fills from HMM nights).
if (((bundle['sleep'] as Map?)?['stager_enmo_median'] as num?)?.toDouble() case final v?)
if (v >= 0) 'enmo_median_night': v,
'dip_pct': sc('dip_pct'),
// Headline 0–21 strain (for trend/sparkline); raw TRIMP kept too.
// Written even when NULL: an abstaining day must overwrite a value a
Expand Down Expand Up @@ -8386,6 +8415,8 @@ class DerivationEngine {
// mismatch that left z permanently null. The raw mean is stored every day so
// this series fills and z starts computing once ≥3 days exist.
m['skin_temp_adc_history'] = before('skin_temp_adc');
// Per-night stable-core ENMO medians (written only for HMM-staged nights).
m['enmo_history'] = before('enmo_median_night');
// TS-03/TS-04 — the observed ceiling this day's ZONES are banded on. A max,
// not a window (see [maxBefore]), and strictly before today so a day is
// never banded on a ceiling its own session set.
Expand Down
8 changes: 8 additions & 0 deletions lib/compute/derive_prepare.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ class PreparedDerivationDay {
final int sleepOnsetSec;
final int sleepOffsetSec;
final String sleepSource;

/// Captured before staging so the cache and bundle worker use one choice.
final bool useHmmStages;
final Substrate daySub;
final Substrate sleepSub;

Expand Down Expand Up @@ -78,6 +81,7 @@ class PreparedDerivationDay {
required this.sleepSub,
Substrate? napSub,
this.sleepSource = 'auto',
this.useHmmStages = false,
this.tonightSleepOnsetSec = 0,
this.tonightSleepOffsetSec = 0,
this.tonightPending = false,
Expand All @@ -95,6 +99,7 @@ class PreparedDerivationDay {
'sleep_onset_sec': sleepOnsetSec,
'sleep_offset_sec': sleepOffsetSec,
'sleep_source': sleepSource,
if (useHmmStages) 'use_hmm_stages': true,
'day_sub': daySub.toJson(),
'sleep_sub': sleepSub.toJson(),
'nap_sub': napSub.toJson(),
Expand Down Expand Up @@ -124,6 +129,7 @@ class PreparedDerivationDay {
hypnoStages: strs('hypno_stages'),
sleepOnsetSec: (m['sleep_onset_sec'] as num?)?.toInt() ?? 0,
sleepOffsetSec: (m['sleep_offset_sec'] as num?)?.toInt() ?? 0,
useHmmStages: m['use_hmm_stages'] == true,
sleepSource: m['sleep_source'] as String? ?? 'auto',
tonightSleepOnsetSec:
(m['tonight_sleep_onset_sec'] as num?)?.toInt() ?? 0,
Expand Down Expand Up @@ -271,6 +277,7 @@ class SleepSessionCandidate {
int tonightSleepOnsetSec = 0,
int tonightSleepOffsetSec = 0,
bool tonightPending = false,
bool useHmmStages = false,
Map<InputSignal, List<OwnedSpan>> ownership = const {},
Map<InputSignal, List<String>> priority = const {},
}) => PreparedDerivationDay(
Expand All @@ -292,6 +299,7 @@ class SleepSessionCandidate {
sleepOnsetSec: sleepOnsetSec,
sleepOffsetSec: sleepOffsetSec,
sleepSource: sleepSource,
useHmmStages: useHmmStages,
daySub: daySub,
napSub: napSub,
sleepSub: sleepSub,
Expand Down
Loading
Loading