Files
kuentagym/api/test/vitals.test.js
T
dsantillan f7b884be81
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Salud: dos dispositivos, una caminata — el cubo guarda sus fuentes y muestra una
"En mi Apple Salud me dice 946 y en opengym 1700 y pico", y antes 499 contra 840. Ese factor —1,80 y
1,68— es la prueba: una suma de valores acumulados daría 12× o 24× al final del día, no 1,8×. Lo que
da 1,8× es **sumar dos dispositivos**. HealthKit de-duplica la misma caminata entre el Apple Watch y
el iPhone, la app Salud la cuenta una vez, y un payload que trae los dos como puntos separados no la
ha de-duplicado nadie. La tarjeta estaba leyendo dos cosas, exactamente como se sospechó.

Ahora cada cubo —una hora, y el día cuando el teléfono manda un total por día— **guarda sus fuentes
por separado y muestra una**: la que más reportó en ese cubo, después la más nueva, después la más
grande. No es una suma, no es un promedio y no es "el máximo": es el agregado propio de un
dispositivo, o sea el número que ese dispositivo muestra.

Y la elección es **por hora**, no por día, que es lo que hace correctas las dos situaciones a la vez:
una hora que solo registró el teléfono es del teléfono (no se pierde nada), y una hora que
registraron los dos se cuenta una vez (no se duplica nada). Con la elección por día, el caso
"caminata sin el reloj" se habría perdido.

Tres cosas que había que cuidar y están cubiertas por tests:

  · **Un payload sin `source`** —casi todos, y en iOS 27+ es lo normal para datos acumulados— vive en
    una sola fuente sin nombre, así que un cubo es el cubo y nada cambia para quien tiene un solo
    dispositivo. Los 22 tests que ya existían pasaron sin tocarlos, que es la evidencia de eso.
  · **Un cubo guardado antes de esto** se adopta como la fuente sin nombre en vez de tirarse: una
    actualización no pierde el día que ya tenía, y las dos compiten por cantidad de muestras.
  · **Reemplazar una hora borra solo la de esa fuente.** La hora en curso crece en cada envío de un
    automatismo de cinco minutos y por eso se reemplaza, pero reemplazar el cubo entero es cómo un
    dispositivo borraría en silencio el reporte del otro — que es lo contrario de lo que esto hace.

La hoja lo dice al final: `N días con datos · Apple Watch, iPhone · se usa Apple Watch`, para que el
número se pueda cotejar contra el dispositivo que lo produjo.

Cinco tests del merge más el orden de desempate. Mutation-check de las dos mitades: sin aplicar la
fuente ganadora fallan cuatro, y si reemplazar una hora borra la del otro dispositivo fallan tres.
API 267 en verde, frontend 1705, build OK.
2026-09-23 18:29:56 -04:00

667 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* The merge rule is the whole point of vitals.js: an automation that runs every five minutes
must not turn a day of steps into three days of steps. These tests are all about that, plus
the shapes HAE actually sends (day-grouped totals, raw samples, Min/Avg/Max heart rate,
aggregated and segmented sleep, blood pressure, a metric that is selected but empty).
Every merge is given an explicit `now`, because the dedupe ledger is pruned against the wall
clock: a test that let the real clock in would delete its own fixtures the moment they were a
few days old, and start passing for the wrong reason. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, parseHaeDate,
normalizeDoc, pickSource, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS
} from '../vitals.js';
const NOW = Date.parse('2026-05-01T23:30:00Z');
const merge = (doc, payload, now = NOW) => mergeVitals(doc, payload, now);
const at = (day, time = '00:00:00', off = '+0000') => `${day} ${time} ${off}`;
/** One metric, one payload. */
const metric = (name, units, data) => ({ data: { metrics: [{ name, units, data }] } });
/* ---------- parsing ---------- */
test('parses both HAE date spellings, including the 12-hour one with a narrow no-break space', () => {
const a = parseHaeDate('2026-05-01 13:04:05 +0200');
assert.equal(a.day, '2026-05-01');
assert.equal(a.time, '13:04:05');
assert.equal(a.ms, Date.parse('2026-05-01T13:04:05+02:00'));
// U+202F between the time and the meridiem — what HAE writes on a 12-hour phone.
const b = parseHaeDate('2026-05-01 1:04:05\u202fPM -0700');
assert.equal(b.time, '13:04:05');
assert.equal(b.ms, Date.parse('2026-05-01T13:04:05-07:00'));
// The two hours a naive modulo gets wrong.
assert.equal(parseHaeDate('2026-05-01 12:00:00\u202fAM +0000').time, '00:00:00');
assert.equal(parseHaeDate('2026-05-01 12:30:00\u202fPM +0000').time, '12:30:00');
// No offset at all means UTC, not "whatever the server is".
assert.equal(parseHaeDate('2026-05-01 08:00:00').ms, Date.parse('2026-05-01T08:00:00Z'));
assert.equal(parseHaeDate('not a date'), null);
assert.equal(parseHaeDate('2026-13-45 08:00:00 +0000'), null);
assert.equal(parseHaeDate(undefined), null);
});
test('parsePayload accepts v2 (wrapped in data), the older flat shape, and drops empty metrics', () => {
const v2 = parsePayload({
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 100, date: at('2026-05-01', '09:00:00') }] },
{ name: 'basal_body_temperature', units: 'degC', data: null }
],
workouts: []
}
});
assert.equal(v2.metrics.length, 2);
assert.equal(v2.metrics[1].points.length, 0, 'a selected-but-empty metric parses to no points');
const flat = parsePayload({ metrics: [{ name: 'weight_body_mass', units: 'kg', data: [{ qty: 80, date: at('2026-05-01', '07:00:00') }] }] });
assert.equal(flat.metrics[0].points[0].fields.qty, 80);
assert.throws(() => parsePayload({ hello: 'world' }), e => e.code === 'shape');
assert.throws(() => parsePayload(null), e => e.code === 'shape');
assert.throws(() => parsePayload({ data: { metrics: [], workouts: [] } }), e => e.code === 'empty');
// A datapoint with no readable date, or with no numbers at all, is not a datapoint.
const junk = parsePayload(metric('foo', 'x', [{ qty: 1, date: 'nonsense' }, { date: at('2026-05-01') }]));
assert.equal(junk.metrics[0].points.length, 0);
});
/* ---------- the merge rule ---------- */
test('raw samples: disjoint windows accumulate, overlapping ones do not double count', () => {
const p = (t, qty) => ({ qty, date: at('2026-05-01', t) });
// "Since Last Sync": each run carries only what happened since the last one.
let doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [p('09:00:00', 300), p('09:05:00', 700)]))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
const inc = merge(doc, parsePayload(metric('step_count', 'count', [p('09:10:00', 200), p('09:15:00', 800)])));
doc = inc.doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 2000, 'new samples add on');
assert.equal(inc.stats.points, 2);
// "Today": every run re-sends the whole day, with the two samples since the last run added.
const today = metric('step_count', 'count', [
p('09:00:00', 300), p('09:05:00', 700), p('09:10:00', 200), p('09:15:00', 800),
p('09:20:00', 1000), p('09:25:00', 500)
]);
const first = merge(doc, parsePayload(today));
assert.equal(first.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 'only the two new samples count');
assert.equal(first.stats.points, 2);
assert.equal(first.stats.duplicates, 4);
const again = merge(first.doc, parsePayload(today));
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 3500, 're-sending changes nothing');
assert.equal(again.stats.points, 0);
assert.equal(again.stats.duplicates, 6);
});
test('day-grouped payloads replace the day: a growing total never adds up', () => {
const grouped = sum => metric('step_count', 'count', [{ qty: sum, date: at('2026-05-01') }]);
let doc = merge(emptyVitals(), parsePayload(grouped(1200))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1200);
// Ten more syncs through the day, each carrying the day's total so far — "Time Grouping: Days".
for (const total of [1400, 2600, 4100, 9800]) doc = merge(doc, parsePayload(grouped(total))).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800, 'replaced, not accumulated');
const same = merge(doc, parsePayload(grouped(9800)));
assert.equal(same.stats.duplicates, 1);
assert.equal(same.stats.points, 0, 'the same total again is a no-op');
assert.equal(same.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
// A day-grouped payload covering several days corrects each of them independently.
const multi = merge(same.doc, parsePayload(metric('step_count', 'count', [
{ qty: 9800, date: at('2026-05-01') }, { qty: 3000, date: at('2026-04-30') }
])));
assert.equal(multi.doc.metrics.step_count.days['2026-04-30'].f.qty.sum, 3000);
assert.equal(multi.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 9800);
});
test('a day total and raw samples for the same day are kept apart by their own payload shape', () => {
// Two metrics in one payload, one grouped by day and one raw: each takes its own branch.
const body = {
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 5000, date: at('2026-05-01') }] },
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 52, date: at('2026-05-01', '06:30:00') }] }
]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 5000);
assert.equal(doc.metrics.resting_heart_rate.days['2026-05-01'].f.qty.sum, 52);
});
test('the day key is the phone\'s own date, not the server\'s', () => {
// 23:30 in Manila is the previous day in UTC. The sample belongs to the phone's day.
const { doc } = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '23:30:00', '+0800') }
])));
assert.deepEqual(Object.keys(doc.metrics.step_count.days), ['2026-05-01']);
});
/* ---------- the shapes HAE actually sends ---------- */
test('heart rate keeps Min/Avg/Max per day instead of pretending they are one number', () => {
const body = metric('heart_rate', 'bpm', [
{ date: at('2026-05-01', '09:00:00'), Min: 58, Avg: 72, Max: 96, source: 'Apple Watch' },
{ date: at('2026-05-01', '10:00:00'), Min: 55, Avg: 68, Max: 88, source: 'Apple Watch' }
]);
const { doc } = merge(emptyVitals(), parsePayload(body));
const day = doc.metrics.heart_rate.days['2026-05-01'];
assert.equal(day.f.Avg.n, 2);
assert.equal(Math.round(day.f.Avg.sum), 140);
assert.equal(day.f.Min.min, 55);
assert.equal(day.f.Max.max, 96);
assert.deepEqual(doc.metrics.heart_rate.sources, ['Apple Watch']);
});
test('sleep: both the aggregated night and the segmented one land as hours per day', () => {
const aggregated = metric('sleep_analysis', 'hr', [{
date: at('2026-05-01', '07:00:00'),
sleepStart: at('2026-04-30', '23:10:00'), sleepEnd: at('2026-05-01', '06:55:00'),
inBed: 8.2, asleep: 7.4, core: 4.1, deep: 1.2, rem: 2.1, awake: 0.8, source: 'Apple Watch'
}]);
const { doc } = merge(emptyVitals(), parsePayload(aggregated));
// Keyed by the day the metric's own `date` names — the morning you woke up.
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.asleep.last, 7.4);
assert.equal(doc.metrics.sleep_analysis.days['2026-05-01'].f.deep.last, 1.2);
const segments = [
{ startDate: at('2026-05-01', '22:10:00'), endDate: at('2026-05-01', '22:50:00'), qty: 0.67, value: 'asleepCore' },
{ startDate: at('2026-05-01', '23:10:00'), endDate: at('2026-05-01', '23:25:00'), qty: 1.33, value: 'asleepDeep' }
];
const seg = merge(emptyVitals(), parsePayload(metric('sleep_analysis', 'hr', segments))).doc;
// Segments carry no `date`, only startDate/endDate, so the day comes from the segment start.
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2);
assert.equal(seg.metrics.sleep_analysis.days['2026-05-01'].f.qty.n, 2);
const repeat = merge(seg, parsePayload(metric('sleep_analysis', 'hr', segments)));
assert.equal(repeat.stats.duplicates, 2, 'the same segments again are the same segments');
assert.equal(repeat.doc.metrics.sleep_analysis.days['2026-05-01'].f.qty.sum, 2, 'and do not add up twice');
});
test('blood pressure keeps both numbers, and an unknown metric is stored rather than dropped', () => {
const body = {
data: {
metrics: [
{ name: 'blood_pressure_systolic', units: 'mmHg', data: [{ date: at('2026-05-01', '08:00:00'), systolic: 128, diastolic: 82 }] },
{ name: 'walking_steadiness', units: '%', data: [{ date: at('2026-05-01', '08:00:00'), qty: 91 }] }
]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.systolic.last, 128);
assert.equal(doc.metrics.blood_pressure_systolic.days['2026-05-01'].f.diastolic.last, 82);
assert.equal(doc.metrics.walking_steadiness.days['2026-05-01'].f.qty.last, 91);
});
/* ---------- workouts ---------- */
test('workouts dedupe on name+start+end, newest first, and a re-send adds nothing', () => {
const w = (name, start, end, energy) => ({
name, start, end,
activeEnergy: { qty: energy, units: 'kcal' },
distance: { qty: 3.2, units: 'km' },
heartRateData: [{ date: at('2026-05-01', '18:00:00'), Avg: 128 }, { date: at('2026-05-01', '18:05:00'), Avg: 136, Max: 172 }]
});
const body = {
data: {
workouts: [
w('Walking', at('2026-05-01', '17:00:00'), at('2026-05-01', '18:00:00'), 210),
w('Functional Strength Training', at('2026-05-01', '07:00:00'), at('2026-05-01', '07:45:00'), 320)
]
}
};
const first = merge(emptyVitals(), parsePayload(body));
assert.equal(first.stats.workouts, 2);
assert.equal(first.doc.workouts[0].name, 'Walking', 'newest first (17:00 after 07:00)');
assert.equal(first.doc.workouts[0].durMin, 60);
assert.equal(first.doc.workouts[0].fields.activeEnergy.qty, 210);
assert.equal(first.doc.workouts[0].avgHr, 132, 'average of the heart-rate samples');
assert.equal(first.doc.workouts[0].maxHr, 172);
assert.equal(first.doc.workouts[1].name, 'Functional Strength Training');
assert.equal(first.doc.workouts[1].fields.activeEnergy.qty, 320);
const again = merge(first.doc, parsePayload(body));
assert.equal(again.stats.workouts, 0);
assert.equal(again.stats.duplicates, 2);
assert.equal(again.doc.workouts.length, 2);
});
/* ---------- two devices, one walk ----------
*
* Reported live: the Health app said 946 steps and the card said 1,700 — a ratio of about 1.8, which
* is the share of the day only one of the two devices was recording. HealthKit de-duplicates the
* same walk across an iPhone and an Apple Watch; a payload that carries both as separate points has
* been de-duplicated by nobody, so adding them counts the walk twice. Each bucket now keeps its
* sources apart and shows the one that reported most in it. */
const bySource = (name, source, points) => ({
name, units: 'count',
data: points.map(([time, qty]) => ({ qty, date: at('2026-05-01', time), source }))
});
test('the same hour from two devices is counted once, not twice', () => {
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', 'Apple Watch', [['08:00:00', 120], ['09:00:00', 220]]),
bySource('step_count', 'iPhone', [['08:00:00', 90], ['09:00:00', 140]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
// 946 against 1,700: the watch was on the wrist for both hours, so the day is the watch's.
assert.equal(day.f.qty.sum, 340, 'the day is one device, not the sum of two');
assert.equal(day.n, 2);
assert.equal(day.h['08'].f.qty.sum, 120);
assert.equal(day.h['09'].f.qty.sum, 220);
assert.equal(day.src, 'Apple Watch', 'and the bucket says which device it used');
// Both are still remembered as having reported — the footer of the sheet lists them.
assert.deepEqual(doc.metrics.step_count.sources, ['iPhone', 'Apple Watch']);
});
test('an hour only the phone recorded is the phone\'s hour', () => {
// The choice is per bucket, and that is what makes the disjoint case right: a walk without the
// watch is not lost, because nothing competes with it in those hours.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', 'Apple Watch', [['14:00:00', 500]]),
bySource('step_count', 'iPhone', [['09:00:00', 400], ['14:00:00', 60]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['09'].f.qty.sum, 400, 'the phone had that hour to itself');
assert.equal(day.h['09'].src, 'iPhone');
assert.equal(day.h['14'].f.qty.sum, 500, 'and the watch won the hour it shares');
assert.equal(day.h['14'].src, 'Apple Watch');
assert.equal(day.f.qty.sum, 900, 'so the day is both, each counted once');
});
test('two day totals for one day is one day, and the larger one is the truth', () => {
// Days grouping with a point per source: replacing is what the day rule does, and picking the
// larger is what HealthKit would show — the union of both devices is not the smaller total.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
{ name: 'step_count', units: 'count', data: [
{ qty: 946, date: at('2026-05-01'), source: 'Apple Watch' },
{ qty: 754, date: at('2026-05-01'), source: 'iPhone' }
] }
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 946, 'not 1,700');
assert.equal(day.src, 'Apple Watch');
assert.equal(day.own, true);
// A newer, larger total from either device replaces it, as a day always did.
const later = merge(doc, parsePayload({
data: { metrics: [{ name: 'step_count', units: 'count', data: [
{ qty: 1200, date: at('2026-05-01'), source: 'Apple Watch' },
{ qty: 1300, date: at('2026-05-01'), source: 'iPhone' }
] }] }
})).doc.metrics.step_count.days['2026-05-01'];
assert.equal(later.f.qty.sum, 1300, 'the day is one of them, never both added');
assert.equal(later.src, 'iPhone');
});
test('a payload with no source at all behaves exactly as it always did', () => {
// Every metric HAE sends without a `source` (iOS 27+ omits it for cumulative data, and older
// exports never had it) lives in one unnamed source, so one bucket is the whole story.
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
bySource('step_count', undefined, [['08:00:00', 120], ['09:00:00', 220]]),
bySource('step_count', undefined, [['14:00:00', 500]])
] }
})).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 840, 'three samples, one device, added');
assert.equal(day.src, null, 'no source to name');
assert.equal(day.n, 3);
});
test('an hour stored before sources existed competes like any other', () => {
// An upgrade must not throw away what it already had: an aggregate with no sources is adopted as
// the unnamed source, and the two then compete on samples like any pair — the day does not silently
// become whatever the phone sent last.
// A fresh copy each time: `mergeVitals` is pure in what it *returns*, but the buckets it is given
// are the ones it writes into, so a second merge off the same object would see the first one's work.
const legacy = () => normalizeDoc({ metrics: { step_count: { units: 'count', days: {
'2026-05-01': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } },
h: { '08': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } } } } }
} } } });
const doc = merge(legacy(), parsePayload({
data: { metrics: [{ name: 'step_count', units: 'count', data: [{ qty: 4, date: at('2026-05-01', '15:00:00'), source: 'iPhone' }] }] }
}), NOW).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['08'].f.qty.sum, 900, 'the hour it already had is untouched');
assert.equal(day.h['15'].f.qty.sum, 4, 'the phone\'s sample landed in its own hour');
assert.equal(day.f.qty.sum, 904, 'the day is both hours, each counted once');
// The day's own source is *undecided* here on purpose: a legacy day with no hours has nothing to
// attribute, so the reader reports null rather than inventing a device.
assert.equal(day.src, undefined);
// Same hour, both sources: the one with more samples that hour wins. Three new samples do not
// outweigh an aggregate of twelve, so the hour it already had stands...
const three = merge(legacy(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' },
{ qty: 500, date: at('2026-05-01', '08:05:00'), source: 'Apple Watch' },
{ qty: 500, date: at('2026-05-01', '08:10:00'), source: 'Apple Watch' }
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(three.h['08'].f.qty.sum, 900, 'twelve samples beat three');
assert.equal(three.h['08'].f.qty.n, 12);
// ...and a device that genuinely reports more of the hour does take it.
const caughtUp = merge(legacy(), parsePayload(metric('step_count', 'count', Array.from({ length: 14 },
(_, i) => ({ qty: 60, date: at('2026-05-01', `08:${String(i * 4).padStart(2, '0')}:00`), source: 'Apple Watch' }))))).doc
.metrics.step_count.days['2026-05-01'];
assert.equal(caughtUp.h['08'].src, 'Apple Watch', 'fourteen samples against twelve');
assert.equal(caughtUp.h['08'].f.qty.sum, 840);
});
test('the source a bucket shows is picked by samples, then recency, then size', () => {
const bucket = s => ({ s });
assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 1, f: {} }, b: { n: 3, lastTs: 0, f: {} } })), 'b', 'most samples');
assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 9, f: {} }, b: { n: 2, lastTs: 1, f: {} } })), 'a', 'then newest');
assert.equal(pickSource(bucket({
a: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 10 } } },
b: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 99 } } }
})), 'b', 'then the larger total');
assert.equal(pickSource({}), null);
assert.equal(pickSource({ s: {} }), null);
});
/* ---------- hours: the detail a day total throws away ---------- */
test('an hourly payload keeps its hours, and the day is exactly their sum', () => {
// "Time Grouping: Hours": every datapoint sits on the hour, so each one is that hour's total.
const hours = qty9 => metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: qty9, date: at('2026-05-01', '09:00:00') }
]);
const day = d => d.metrics.step_count.days['2026-05-01'];
const first = merge(emptyVitals(), parsePayload(hours(800)));
assert.equal(day(first.doc).f.qty.sum, 1300, 'the day is the sum of its hours');
assert.equal(day(first.doc).h['08'].f.qty.sum, 500);
assert.equal(day(first.doc).h['09'].f.qty.sum, 800);
assert.equal(day(first.doc).h['09'].f.qty.n, 1);
// The hour in progress grows on every run of a five-minute automation: replaced, never added,
// because 500 + 900 + 1,340 steps in one hour is a number the watch never recorded.
const grown = merge(first.doc, parsePayload(hours(1500)));
assert.equal(day(grown.doc).h['09'].f.qty.sum, 1500);
assert.equal(day(grown.doc).f.qty.sum, 2000, 'and the day moves with it');
assert.equal(grown.stats.duplicates, 1, 'the finished hour was an exact repeat');
assert.equal(grown.stats.points, 1);
const again = merge(grown.doc, parsePayload(hours(1500)));
assert.equal(again.stats.points, 0);
assert.equal(again.stats.duplicates, 2);
assert.equal(day(again.doc).f.qty.sum, 2000);
});
test('a raw sample that happens to sit on the hour does not wipe that hour', () => {
// Both stamps are real samples ("Since Last Sync" at a 5-minute cadence), and the first one is
// exactly on the hour. Reading that timestamp as an hour *total* would delete the samples
// already stored in 09 — which is why the rule is decided from the payload, not the point.
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 300, date: at('2026-05-01', '09:00:00') },
{ qty: 700, date: at('2026-05-01', '09:05:00') }
]))).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.h['09'].f.qty.sum, 1000);
assert.equal(day.h['09'].f.qty.n, 2);
assert.equal(day.f.qty.sum, 1000);
// ...and the same payload again is a no-op, on both levels.
const again = merge(doc, parsePayload(metric('step_count', 'count', [
{ qty: 300, date: at('2026-05-01', '09:00:00') },
{ qty: 700, date: at('2026-05-01', '09:05:00') }
])));
assert.equal(again.stats.duplicates, 2);
assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000);
});
test('the phone\'s own day total is the day, and hours never get added to it', () => {
const hours = metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') }
]);
let doc = merge(emptyVitals(), parsePayload(hours)).doc;
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1400);
// A second automation grouped by Days sends the day itself: it is the number the Health app
// shows, so it becomes the day — and the hours stay for the sheet to draw.
const total = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }])));
doc = total.doc;
assert.equal(total.stats.points, 1);
assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1500);
assert.equal(Object.keys(doc.metrics.step_count.days['2026-05-01'].h).length, 2, 'the hours rode along');
// Then hour points arrive for the same day. The day does NOT become their sum: the declared total
// already contains the hours below it, and adding them is exactly how 499 steps became 840. The
// sum rides beside it instead, so a disagreement between the two is visible rather than silent.
doc = merge(doc, parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') },
{ qty: 200, date: at('2026-05-01', '10:00:00') }
]))).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 1500, 'the phone\'s total is still the day');
assert.equal(day.own, true);
assert.equal(Object.keys(day.h).length, 3, 'and the hours still landed');
assert.equal(day.hsum.qty, 1600, 'with their sum beside them, for the screen to compare');
// A newer total replaces it, as it always did.
assert.equal(merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1700, date: at('2026-05-01') }]))).doc
.metrics.step_count.days['2026-05-01'].f.qty.sum, 1700);
});
test('a day stored before hours existed keeps its samples when the first hour arrives', () => {
// A document written by an older version: the day has an aggregate and no hours, so its samples
// cannot be placed in an hour. Rebuilding the day from the hours it does not have would throw
// 2,000 steps away; the sample is added to the day the old way and the hour is what it is.
const legacy = normalizeDoc({
metrics: { step_count: { days: { '2026-05-01': { n: 4, lastTs: 0, f: { qty: { n: 4, sum: 2000, min: 100, max: 900, last: 900 } } } } } }
});
const r = merge(legacy, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-01', '09:05:00') }])));
const day = r.doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 2300, 'nothing already stored was lost');
assert.equal(day.f.qty.n, 5);
assert.equal(day.h['09'].f.qty.sum, 300, 'and the hour holds only what has a time of its own');
});
test('vitalsHours answers for one metric and one day, and invents nothing', () => {
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 500, date: at('2026-05-01', '08:00:00') },
{ qty: 900, date: at('2026-05-01', '09:00:00') }
]))).doc;
const got = vitalsHours(doc, { metric: 'step_count', day: '2026-05-01' });
assert.deepEqual(got.hours.map(x => x.h), ['08', '09'], 'oldest hour first');
assert.equal(got.units, 'count');
assert.equal(got.hours[0].f.qty.sum, 500);
assert.equal(got.hours[0].f.qty.avg, 500);
assert.ok(got.hours[0].ts > 0);
// A day the automation never grouped by hour — a day total, or a day that does not exist — is
// an empty list rather than a fabricated one; the screen says why instead of drawing zeros.
const grouped = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }]))).doc;
assert.deepEqual(vitalsHours(grouped, { metric: 'step_count', day: '2026-05-01' }).hours, []);
assert.deepEqual(vitalsHours(doc, { metric: 'step_count', day: '2026-04-01' }).hours, []);
assert.deepEqual(vitalsHours(doc, { metric: 'not_a_metric', day: '2026-05-01' }).hours, []);
assert.equal(vitalsHours(doc, { metric: 'step_count', day: 'not-a-day' }).day, null);
assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null);
});
test('a midnight total inside an hourly payload is the day, not hour zero', () => {
// The shape that produced "the watch says 499 and the app says 840": HAE sends the day's total
// stamped at midnight *and* the hours, in one payload. Read as hour 00, the total is added to the
// hours and the day doubles; read as what it is, the day is 499 and the hours are its shape.
const p = (qty, time) => ({ qty, date: at('2026-05-01', time) });
const payload = metric('step_count', 'count', [
p(499, '00:00:00'), // the day's own total, stamped at midnight
p(120, '08:00:00'), p(220, '09:00:00') // and two hours of it
]);
const doc = merge(emptyVitals(), parsePayload(payload)).doc;
const day = doc.metrics.step_count.days['2026-05-01'];
assert.equal(day.f.qty.sum, 499, 'the day is the total, not 499 + 340');
assert.equal(day.own, true);
assert.equal(day.h['00'], undefined, 'and the midnight point did not become hour 00');
assert.deepEqual(Object.keys(day.h).sort(), ['08', '09']);
assert.equal(day.hsum.qty, 340, 'the sum of the hours is kept beside it');
// The same payload again is a no-op on the day, and the hours converge.
const grew = merge(doc, parsePayload(metric('step_count', 'count', [
p(499, '00:00:00'), p(120, '08:00:00'), p(260, '09:00:00')
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(grew.f.qty.sum, 499);
assert.equal(grew.h['09'].f.qty.sum, 260);
// A genuine 00:00 bucket — a handful of steps, less than the rest of the day — stays hour 00.
const small = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
p(3, '00:00:00'), p(300, '08:00:00'), p(400, '09:00:00')
]))).doc.metrics.step_count.days['2026-05-01'];
assert.equal(small.f.qty.sum, 703, 'a real first hour is summed like any other');
assert.equal(small.h['00'].f.qty.sum, 3);
assert.equal(small.own, undefined);
});
test('the receipt records what arrived, so a wrong number can be explained', () => {
const doc = merge(emptyVitals(), parsePayload({
data: { metrics: [
{ name: 'step_count', units: 'count', data: [
{ qty: 120, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' },
{ qty: 220, date: at('2026-05-01', '09:00:00'), source: 'Apple Watch' },
{ qty: 90, date: at('2026-05-01', '09:30:00'), source: 'iPhone' }
] }
] }
}), NOW).doc;
const r = doc.shape.step_count;
assert.equal(r.points, 3);
assert.equal(r.stamps, 'mixed', 'a payload with an hour and a real instant says so');
assert.equal(r.field, 'qty');
assert.deepEqual(r.sources, ['Apple Watch', 'iPhone']);
assert.equal(r.sum, 430);
assert.equal(r.newest.value, 90);
assert.equal(r.tail.length, 3);
assert.equal(r.head.length, 3);
assert.equal(r.at, NOW);
// Hour-stamped and day-stamped payloads are labelled too, because that is the question the
// receipt exists to answer.
const hourly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 120, date: at('2026-05-01', '08:00:00') }, { qty: 220, date: at('2026-05-01', '09:00:00') }
]))).doc;
assert.equal(hourly.shape.step_count.stamps, 'hour');
const dayly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 499, date: at('2026-05-01') }]))).doc;
assert.equal(dayly.shape.step_count.stamps, 'day');
// Replaced on every sync, never accumulated.
const again = merge(dayly, parsePayload(metric('heart_rate', 'bpm', [{ Avg: 62, date: at('2026-05-01', '09:00:00') }]))).doc;
assert.equal(again.shape.step_count.points, 1, 'the metric that did not arrive keeps its receipt');
assert.equal(again.shape.heart_rate.field, 'Avg');
// It survives a reload of the file, and it is not read by anything that computes a number.
assert.equal(normalizeDoc(JSON.parse(JSON.stringify(again))).shape.step_count.points, 1);
});
test('the hourly detail is pruned after a week while the day aggregates live on', () => {
const start = Date.parse('2026-05-06T12:00:00Z');
const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [
{ qty: 100, date: at('2026-05-05', '08:00:00') },
{ qty: 200, date: at('2026-05-06', '08:00:00') }
])), start).doc;
assert.ok(doc.metrics.step_count.days['2026-05-05'].h, 'hours are stored while they are recent');
// A week later the sheet can still ask for today and yesterday, and nothing it could show is
// older than this: 24 buckets × every metric × every day of the year is what this avoids.
const later = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 300, date: at('2026-05-13', '08:00:00') }])), Date.parse('2026-05-13T12:00:00Z')).doc;
assert.equal(later.metrics.step_count.days['2026-05-05'].h, undefined, 'the hours of an old day are gone');
assert.equal(later.metrics.step_count.days['2026-05-05'].f.qty.sum, 100, 'the day itself stays');
assert.ok(later.metrics.step_count.days['2026-05-06'].h, 'and a day inside the window keeps its own');
assert.ok(HOURS_KEPT_DAYS >= 2 && HOURS_KEPT_DAYS <= RETENTION_DAYS);
});
/* ---------- housekeeping ---------- */
test('the dedupe ledger and the day buckets are both pruned, so the file stays bounded', () => {
// Five past the hour on purpose: a sample that sits exactly on the hour is indistinguishable
// from an hour bucket HAE grouped itself, and that shape has no ledger (see the hour tests).
const first = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:05:00') }])), NOW);
const seen = first.doc.metrics.step_count.seen;
assert.equal(Object.keys(seen).length, 1);
assert.equal(seen[Object.keys(seen)[0]], Date.parse('2026-05-01T09:05:00Z'));
// A sync a week later: last week's sample can no longer be a repeat, so its ledger row goes
// while the day it belongs to stays.
const later = merge(first.doc, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-08', '09:05:00') }])), Date.parse('2026-05-08T12:00:00Z')).doc;
assert.equal(Object.keys(later.metrics.step_count.seen).length, 1, 'the stale ledger row is gone');
assert.deepEqual(Object.keys(later.metrics.step_count.days), ['2026-05-01', '2026-05-08']);
// Days past retention are dropped.
const old = new Date(NOW - (RETENTION_DAYS + 30) * 86400000).toISOString().slice(0, 10);
const withOld = normalizeDoc({ metrics: { step_count: { days: { [old]: { n: 1, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } } } });
const pruned = merge(withOld, parsePayload(metric('step_count', 'count', [{ qty: 10, date: at('2026-05-01', '09:00:00') }]))).doc;
assert.equal(pruned.metrics.step_count.days[old], undefined);
assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365);
});
test('dropMetric forgets one metric, days and all, and touches nothing else', () => {
const doc = merge(emptyVitals(), parsePayload({
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 9000, date: at('2026-05-01') }, { qty: 8000, date: at('2026-04-30') }] },
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Avg: 70 }] }
],
workouts: [{ name: 'Walking', start: at('2026-05-01', '10:00:00'), end: at('2026-05-01', '11:00:00') }]
}
}), NOW).doc;
const gone = dropMetric(doc, 'step_count');
assert.equal(gone.found, true);
assert.equal(gone.days, 2, 'and it says how much it took');
assert.equal(gone.doc.metrics.step_count, undefined);
assert.ok(gone.doc.metrics.heart_rate, 'the other metric is untouched');
assert.equal(gone.doc.workouts.length, 1, 'and a workout is not a health metric');
// The input document is not modified: this is a pure function like the merge.
assert.ok(doc.metrics.step_count);
// A metric that is not there, and a profile with no file at all, are both answers rather than
// errors — the screen says "nothing stored" instead of failing at the person.
assert.deepEqual(dropMetric(doc, 'never_heard_of_it'), { doc, days: 0, found: false });
assert.deepEqual(dropMetric(null, 'step_count'), { doc: null, days: 0, found: false });
});
test('normalizeDoc survives a hand-edited or half-written file', () => {
const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' });
assert.deepEqual(d.workouts, []);
assert.deepEqual(Object.keys(d.metrics), ['heart_rate']);
assert.deepEqual(d.metrics.heart_rate.days, {});
assert.deepEqual(d.metrics.heart_rate.sources, []);
assert.equal(d.metrics.heart_rate.units, '');
assert.deepEqual(normalizeDoc(null).metrics, {});
});
/* ---------- reading it back ---------- */
test('vitalsSeries gives per-field totals, averages and a window, oldest day first', () => {
const body = {
data: {
metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 4000, date: at('2026-04-30') }, { qty: 6000, date: at('2026-05-01') }] },
{ name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Min: 55, Avg: 70, Max: 90 }] }
],
workouts: [{ name: 'Walking', start: at('2026-05-01', '09:00:00'), end: at('2026-05-01', '09:30:00'), activeEnergy: { qty: 100, units: 'kcal' } }]
}
};
const { doc } = merge(emptyVitals(), parsePayload(body));
const s = vitalsSeries(doc, { days: 90, now: NOW });
assert.deepEqual(s.metrics.step_count.days.map(d => d.day), ['2026-04-30', '2026-05-01']);
assert.deepEqual(s.metrics.step_count.days.map(d => d.f.qty.sum), [4000, 6000]);
assert.equal(s.metrics.heart_rate.days[0].f.Avg.avg, 70);
assert.equal(s.metrics.step_count.units, 'count');
assert.equal(s.workouts.length, 1);
// A one-day window keeps only the day inside it.
const narrow = vitalsSeries(doc, { days: 1, now: NOW });
assert.deepEqual(narrow.metrics.step_count.days.map(d => d.day), ['2026-05-01']);
});