Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: Apple Health re-sync updates frozen values with latest write wins (#8449)
[._.]/ Adam Eivyd51d8fc69684
diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.jsindex d9e4042467..43fdd15b54 100644--- a/server/services/appleHealthIngest.js+++ b/server/services/appleHealthIngest.js@@ -7,6 +7,16 @@import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';++// === Module State ===++/**+ * Per-date write queue to serialize read-modify-write cycles.+ * Keyed by date string (YYYY-MM-DD) so different days fan out in parallel+ * while writes to the same day serialize.+ */+const queueDayWrite = createKeyedFileWriteQueue();// === Pure Functions ===@@ -64,30 +74,71 @@ export async function writeDayFile(dateStr, data) {}/**- * Merge new data points into an existing day file, deduplicating by date string.+ * Upsert data points into a metric array.+ * For each new point, if an existing point has the same date, replace it.+ * Otherwise append the new point.+ *+ * @param {Array} existing - Existing points for the metric+ * @param {Array} newPoints - New points to upsert+ * @returns {Object} { added: number of new points, updated: number of replaced points }+ */+export function upsertPoints(existing, newPoints) {+ if (!existing.length) {+ return { added: newPoints.length, updated: 0, result: [...newPoints] };+ }++ // Build a map of existing points by date for O(1) lookup and update+ const pointsByDate = new Map();+ for (const point of existing) {+ pointsByDate.set(point.date, point);+ }++ let added = 0;+ let updated = 0;++ // Process new points: update if date exists, otherwise add+ for (const newPoint of newPoints) {+ if (pointsByDate.has(newPoint.date)) {+ // Check if the point actually changed+ const oldPoint = pointsByDate.get(newPoint.date);+ if (JSON.stringify(oldPoint) !== JSON.stringify(newPoint)) {+ pointsByDate.set(newPoint.date, newPoint);+ updated++;+ }+ // If identical, count as a dupe (neither added nor updated)+ } else {+ pointsByDate.set(newPoint.date, newPoint);+ added++;+ }+ }++ const result = Array.from(pointsByDate.values());+ return { added, updated, result };+}++/**+ * Merge new data points into an existing day file, using upsert (latest write wins).+ * Serializes writes per date to prevent concurrent read-modify-write races.** @param {string} dateStr - YYYY-MM-DD string* @param {string} metricName - Health metric name* @param {Array} newPoints - Array of data point objects from the metric- * @returns {Promise<number>} Count of newly added (unique) points+ * @returns {Promise<Object>} { added, updated, totalPoints }*/export async function mergeIntoDay(dateStr, metricName, newPoints) {- const dayData = await readDayFile(dateStr);-- const existing = dayData.metrics[metricName] || [];-- // Build a Set of existing full date strings for fast dedup lookup- const existingDates = new Set(existing.map(p => p.date));+ return queueDayWrite(dateStr, async () => {+ const dayData = await readDayFile(dateStr);+ const existing = dayData.metrics[metricName] || [];- // Only keep points not already present- const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));+ const { added, updated, result } = upsertPoints(existing, newPoints);- if (uniquePoints.length > 0) {- dayData.metrics[metricName] = existing.concat(uniquePoints);- await writeDayFile(dateStr, dayData);- }+ if (added > 0 || updated > 0) {+ dayData.metrics[metricName] = result;+ await writeDayFile(dateStr, dayData);+ }- return uniquePoints.length;+ return { added, updated, totalPoints: result.length };+ });}// Health Auto Export uses short names; normalize to match XML import names@@ -102,12 +153,13 @@ const METRIC_NAME_ALIASES = {* Iterates all metrics, groups data points by day, and merges into day files.** @param {Object} payload - Validated health ingest payload- * @returns {Promise<Object>} Summary: { metricsProcessed, recordsIngested, recordsSkipped, daysAffected }+ * @returns {Promise<Object>} Summary: { metricsProcessed, recordsIngested, recordsUpdated, recordsSkipped, daysAffected }*/export async function ingestHealthData(payload) {const metrics = payload.data.metrics || [];let metricsProcessed = 0;let recordsIngested = 0;+ let recordsUpdated = 0;let recordsSkipped = 0;const affectedDays = new Set();@@ -130,15 +182,17 @@ export async function ingestHealthData(payload) {// Merge each day's points into the corresponding day filefor (const [dateStr, points] of byDay) {- const added = await mergeIntoDay(dateStr, metricName, points);- recordsIngested += added;- recordsSkipped += (points.length - added);- if (added > 0) affectedDays.add(dateStr);+ const result = await mergeIntoDay(dateStr, metricName, points);+ recordsIngested += result.added;+ recordsUpdated += result.updated;+ recordsSkipped += (points.length - result.added - result.updated);+ if (result.added > 0 || result.updated > 0) affectedDays.add(dateStr);}}const daysAffected = affectedDays.size;- console.log(`🍎 Health ingest: ${recordsIngested} records across ${daysAffected} days (${recordsSkipped} dupes skipped)`);+ const updateMsg = recordsUpdated > 0 ? ` ${recordsUpdated} updated,` : '';+ console.log(`🍎 Health ingest: ${recordsIngested} added,${updateMsg} ${recordsSkipped} dupes, ${daysAffected} days affected`);- return { metricsProcessed, recordsIngested, recordsSkipped, daysAffected };+ return { metricsProcessed, recordsIngested, recordsUpdated, recordsSkipped, daysAffected };}diff --git a/server/services/appleHealthIngest.test.js b/server/services/appleHealthIngest.test.jsnew file mode 100644index 0000000000..83622a61ef--- /dev/null+++ b/server/services/appleHealthIngest.test.js@@ -0,0 +1,425 @@+/**+ * Apple Health Ingest Service Tests+ *+ * Tests for upsert logic: latest write wins, data updates correctly,+ * identical points are skipped, and concurrent writes serialize per-date.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';++// Mock PATHS to use a temp directory+const tempDirs = [];+beforeEach(async () => {+ const tempDir = await mkdtemp(join(tmpdir(), 'portos-ahIngest-test-'));+ tempDirs.push(tempDir);+ // Override PATHS.health for this test+ Object.defineProperty(PATHS, 'health', {+ value: tempDir,+ configurable: true,+ });+});++afterEach(async () => {+ for (const dir of tempDirs) {+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+ tempDirs.length = 0;+});++const { extractDateStr, upsertPoints, mergeIntoDay, ingestHealthData } = await import('./appleHealthIngest.js');++describe('extractDateStr', () => {+ it('extracts YYYY-MM-DD from an Apple Health timestamp', () => {+ expect(extractDateStr('2024-01-15 08:30:00 -0800')).toBe('2024-01-15');+ expect(extractDateStr('2024-12-31 23:59:59 +0000')).toBe('2024-12-31');+ });++ it('returns null for invalid dates', () => {+ expect(extractDateStr('not-a-date')).toBeNull();+ expect(extractDateStr('')).toBeNull();+ expect(extractDateStr(null)).toBeNull();+ expect(extractDateStr(undefined)).toBeNull();+ });+});++describe('upsertPoints', () => {+ it('adds new points when existing array is empty', () => {+ const newPoints = [+ { date: '2024-01-15 00:00:00 -0800', qty: 300 },+ { date: '2024-01-15 12:00:00 -0800', qty: 500 },+ ];+ const result = upsertPoints([], newPoints);++ expect(result.added).toBe(2);+ expect(result.updated).toBe(0);+ expect(result.result).toHaveLength(2);+ expect(result.result[0].qty).toBe(300);+ expect(result.result[1].qty).toBe(500);+ });++ it('updates existing point when date matches', () => {+ const existing = [+ { date: '2024-01-15 00:00:00 -0800', qty: 300 },+ ];+ const newPoints = [+ { date: '2024-01-15 00:00:00 -0800', qty: 9000 },+ ];+ const result = upsertPoints(existing, newPoints);++ expect(result.added).toBe(0);+ expect(result.updated).toBe(1);+ expect(result.result).toHaveLength(1);+ expect(result.result[0].qty).toBe(9000);+ });++ it('skips identical points without counting as added or updated', () => {+ const existing = [+ { date: '2024-01-15 00:00:00 -0800', qty: 300 },+ ];+ const newPoints = [+ { date: '2024-01-15 00:00:00 -0800', qty: 300 },+ ];+ const result = upsertPoints(existing, newPoints);++ expect(result.added).toBe(0);+ expect(result.updated).toBe(0);+ expect(result.result).toHaveLength(1);+ expect(result.result[0].qty).toBe(300);+ });++ it('mixes adds, updates, and skips correctly', () => {+ const existing = [+ { date: '2024-01-15 00:00:00 -0800', qty: 300 }, // will be updated+ { date: '2024-01-15 06:00:00 -0800', qty: 400 }, // will be skipped (identical)+ ];+ const newPoints = [+ { date: '2024-01-15 00:00:00 -0800', qty: 9000 }, // update+ { date: '2024-01-15 06:00:00 -0800', qty: 400 }, // skip (identical)+ { date: '2024-01-15 12:00:00 -0800', qty: 500 }, // add+ ];+ const result = upsertPoints(existing, newPoints);++ expect(result.added).toBe(1);+ expect(result.updated).toBe(1);+ expect(result.result).toHaveLength(3);+ // Check the values+ expect(result.result.find(p => p.date === '2024-01-15 00:00:00 -0800').qty).toBe(9000);+ expect(result.result.find(p => p.date === '2024-01-15 06:00:00 -0800').qty).toBe(400);+ expect(result.result.find(p => p.date === '2024-01-15 12:00:00 -0800').qty).toBe(500);+ });+});++describe('mergeIntoDay', () => {+ it('creates a new day file when it does not exist', async () => {+ const result = await mergeIntoDay('2024-01-15', 'step_count', [+ { date: '2024-01-15 00:00:00 -0800', qty: 9000 },+ ]);++ expect(result.added).toBe(1);+ expect(result.updated).toBe(0);+ expect(result.totalPoints).toBe(1);++ // Verify file was written+ const dayPath = join(PATHS.health, '2024-01-15.json');+ const content = await import('fs/promises').then(m => m.readFile(dayPath, 'utf-8'));+ const data = JSON.parse(content);+ expect(data.metrics.step_count).toHaveLength(1);+ expect(data.metrics.step_count[0].qty).toBe(9000);+ });++ it('updates an existing day value with a larger value', async () => {+ const dayPath = join(PATHS.health, '2024-01-15.json');+ await writeFile(dayPath, JSON.stringify({+ date: '2024-01-15',+ metrics: {+ step_count: [+ { date: '2024-01-15 08:00:00 -0800', qty: 300 },+ ],+ },+ updated: new Date().toISOString(),+ }), 'utf-8');++ // Re-sync with more complete data+ const result = await mergeIntoDay('2024-01-15', 'step_count', [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ ]);++ expect(result.added).toBe(0);+ expect(result.updated).toBe(1);+ expect(result.totalPoints).toBe(1);++ const content = await import('fs/promises').then(m => m.readFile(dayPath, 'utf-8'));+ const data = JSON.parse(content);+ expect(data.metrics.step_count[0].qty).toBe(9000);+ });++ it('does not rewrite file when ingesting identical point', async () => {+ const dayPath = join(PATHS.health, '2024-01-15.json');+ const originalTime = new Date('2024-01-01T00:00:00Z').toISOString();+ await writeFile(dayPath, JSON.stringify({+ date: '2024-01-15',+ metrics: {+ step_count: [+ { date: '2024-01-15 08:00:00 -0800', qty: 300 },+ ],+ },+ updated: originalTime,+ }), 'utf-8');++ // Ingest identical point+ const result = await mergeIntoDay('2024-01-15', 'step_count', [+ { date: '2024-01-15 08:00:00 -0800', qty: 300 },+ ]);++ expect(result.added).toBe(0);+ expect(result.updated).toBe(0);++ const content = await import('fs/promises').then(m => m.readFile(dayPath, 'utf-8'));+ const data = JSON.parse(content);+ // File should not have been rewritten, so updated timestamp should still match original+ expect(data.updated).toBe(originalTime);+ });++ it('handles multiple metrics in same day', async () => {+ await mergeIntoDay('2024-01-15', 'step_count', [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ ]);++ await mergeIntoDay('2024-01-15', 'heart_rate', [+ { date: '2024-01-15 10:00:00 -0800', qty: 72 },+ ]);++ const dayPath = join(PATHS.health, '2024-01-15.json');+ const content = await import('fs/promises').then(m => m.readFile(dayPath, 'utf-8'));+ const data = JSON.parse(content);++ expect(data.metrics.step_count).toHaveLength(1);+ expect(data.metrics.step_count[0].qty).toBe(9000);+ expect(data.metrics.heart_rate).toHaveLength(1);+ expect(data.metrics.heart_rate[0].qty).toBe(72);+ });+});++describe('ingestHealthData', () => {+ it('ingests new data and reports added records', async () => {+ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ { date: '2024-01-15 18:00:00 -0800', qty: 5000 },+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(2);+ expect(result.recordsUpdated).toBe(0);+ expect(result.recordsSkipped).toBe(0);+ expect(result.daysAffected).toBe(1);+ });++ it('updates existing values and reports separately', async () => {+ const dayPath = join(PATHS.health, '2024-01-15.json');+ await writeFile(dayPath, JSON.stringify({+ date: '2024-01-15',+ metrics: {+ step_count: [+ { date: '2024-01-15 08:00:00 -0800', qty: 300 }, // partial value+ ],+ },+ updated: new Date().toISOString(),+ }), 'utf-8');++ // Re-sync with complete data+ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 }, // updated+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(0);+ expect(result.recordsUpdated).toBe(1);+ expect(result.recordsSkipped).toBe(0);+ expect(result.daysAffected).toBe(1);+ });++ it('distinguishes dupes (identical) from updates', async () => {+ const dayPath = join(PATHS.health, '2024-01-15.json');+ const originalTime = new Date('2024-01-01T00:00:00Z').toISOString();+ await writeFile(dayPath, JSON.stringify({+ date: '2024-01-15',+ metrics: {+ step_count: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ ],+ },+ updated: originalTime,+ }), 'utf-8');++ // Re-sync with identical data+ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 }, // identical+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(0);+ expect(result.recordsUpdated).toBe(0);+ expect(result.recordsSkipped).toBe(1); // counted as dupe+ });++ it('mixes additions, updates, and dupes in one ingest', async () => {+ const dayPath = join(PATHS.health, '2024-01-15.json');+ const originalTime = new Date('2024-01-01T00:00:00Z').toISOString();+ await writeFile(dayPath, JSON.stringify({+ date: '2024-01-15',+ metrics: {+ step_count: [+ { date: '2024-01-15 08:00:00 -0800', qty: 300 }, // will be updated+ { date: '2024-01-15 12:00:00 -0800', qty: 400 }, // will be skipped (dupe)+ ],+ },+ updated: originalTime,+ }), 'utf-8');++ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 }, // update+ { date: '2024-01-15 12:00:00 -0800', qty: 400 }, // dupe (identical)+ { date: '2024-01-15 18:00:00 -0800', qty: 500 }, // add+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(1); // 1 added+ expect(result.recordsUpdated).toBe(1); // 1 updated+ expect(result.recordsSkipped).toBe(1); // 1 dupe (identical)+ });++ it('handles multiple days and metrics', async () => {+ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-14 08:00:00 -0800', qty: 8000 },+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ ],+ },+ {+ name: 'heart_rate',+ data: [+ { date: '2024-01-14 10:00:00 -0800', qty: 70 },+ { date: '2024-01-15 10:00:00 -0800', qty: 72 },+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.metricsProcessed).toBe(2);+ expect(result.recordsIngested).toBe(4);+ expect(result.daysAffected).toBe(2);++ // Verify both day files exist+ const content14 = await import('fs/promises').then(m =>+ m.readFile(join(PATHS.health, '2024-01-14.json'), 'utf-8')+ );+ const data14 = JSON.parse(content14);+ expect(data14.metrics.step_count).toHaveLength(1);+ expect(data14.metrics.heart_rate).toHaveLength(1);++ const content15 = await import('fs/promises').then(m =>+ m.readFile(join(PATHS.health, '2024-01-15.json'), 'utf-8')+ );+ const data15 = JSON.parse(content15);+ expect(data15.metrics.step_count).toHaveLength(1);+ expect(data15.metrics.heart_rate).toHaveLength(1);+ });++ it('normalizes metric name aliases', async () => {+ const payload = {+ data: {+ metrics: [+ {+ name: 'heart_rate_variability', // HAE short name+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 25 },+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(1);++ const dayPath = join(PATHS.health, '2024-01-15.json');+ const content = await import('fs/promises').then(m => m.readFile(dayPath, 'utf-8'));+ const data = JSON.parse(content);+ // Should be stored under the normalized name+ expect(data.metrics.heart_rate_variability_sdnn).toHaveLength(1);+ });++ it('skips records with invalid date strings', async () => {+ const payload = {+ data: {+ metrics: [+ {+ name: 'step_count',+ data: [+ { date: '2024-01-15 08:00:00 -0800', qty: 9000 },+ { date: 'invalid-date', qty: 5000 },+ { date: '2024-01-15 18:00:00 -0800', qty: 2000 },+ ],+ },+ ],+ },+ };++ const result = await ingestHealthData(payload);++ expect(result.recordsIngested).toBe(2);+ expect(result.recordsSkipped).toBe(1); // invalid-date+ });+});diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.jsindex d4d178af31..f02619796f 100644--- a/server/services/appleHealthXml.js+++ b/server/services/appleHealthXml.js@@ -8,8 +8,9 @@import { createReadStream } from 'fs';import { unlink } from 'fs/promises';-import { extractDateStr, readDayFile, writeDayFile } from './appleHealthIngest.js';+import { extractDateStr, readDayFile, writeDayFile, upsertPoints } from './appleHealthIngest.js';import { createAppleHealthRecordStream } from './appleHealthXmlParser.js';+import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';// === Mapping Tables ===@@ -205,8 +206,16 @@ function aggregateSleepAnalysis(points) {const FLUSH_INTERVAL = 200000; // Flush to disk every 200K records to stay under memory limits+/**+ * Per-date write queue to serialize read-modify-write cycles.+ * Keyed by date string (YYYY-MM-DD) so different days fan out in parallel+ * while writes to the same day serialize.+ */+const queueDayWrite = createKeyedFileWriteQueue();+/*** Flush accumulated day buckets to disk: aggregate, merge with existing, write, clear.+ * Uses upsert to handle re-imports that update existing day totals.** @param {Object} dayBuckets - { [dateStr]: { [metricName]: [...dataPoints] } }* @returns {Promise<Set<string>>} Set of date strings that were flushed@@ -216,31 +225,33 @@ async function flushDayBuckets(dayBuckets) {const allDates = Object.keys(dayBuckets);for (const dateStr of allDates) {- const metrics = dayBuckets[dateStr];-- // Aggregate step_count: sum all qty values into single daily total- if (metrics.step_count) {- metrics.step_count = aggregateStepCount(metrics.step_count);- }-- // Aggregate sleep_analysis: sum stage durations into daily summary- if (metrics.sleep_analysis) {- metrics.sleep_analysis = aggregateSleepAnalysis(metrics.sleep_analysis);- }-- const dayData = await readDayFile(dateStr);-- for (const [metricName, newPoints] of Object.entries(metrics)) {- const existing = dayData.metrics[metricName] || [];- const existingDates = new Set(existing.map(p => p.date));- const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));- if (uniquePoints.length > 0) {- dayData.metrics[metricName] = existing.concat(uniquePoints);+ await queueDayWrite(dateStr, async () => {+ const metrics = dayBuckets[dateStr];++ // Aggregate step_count: sum all qty values into single daily total+ if (metrics.step_count) {+ metrics.step_count = aggregateStepCount(metrics.step_count);+ }++ // Aggregate sleep_analysis: sum stage durations into daily summary+ if (metrics.sleep_analysis) {+ metrics.sleep_analysis = aggregateSleepAnalysis(metrics.sleep_analysis);}- }- await writeDayFile(dateStr, dayData);- flushedDates.add(dateStr);+ const dayData = await readDayFile(dateStr);++ for (const [metricName, newPoints] of Object.entries(metrics)) {+ const existing = dayData.metrics[metricName] || [];+ const { result } = upsertPoints(existing, newPoints);+ if (result.length > 0) {+ dayData.metrics[metricName] = result;+ }+ }++ await writeDayFile(dateStr, dayData);+ flushedDates.add(dateStr);+ });+delete dayBuckets[dateStr];}diff --git a/server/services/appleHealthXml.test.js b/server/services/appleHealthXml.test.jsindex b952051f18..7ee1e6f707 100644--- a/server/services/appleHealthXml.test.js+++ b/server/services/appleHealthXml.test.js@@ -133,3 +133,64 @@ describe('importAppleHealthXml temp-file lifecycle', () => {expect(trace).toEqual(['close', 'unlink']);});});++describe('importAppleHealthXml upsert behavior', () => {+ let dir;+ let xmlPath;+ let readCalls;+ let writeCalls;++ beforeEach(async () => {+ streams.length = 0;+ trace.length = 0;+ parser.impl = null;+ readCalls = [];+ writeCalls = [];++ // Track calls to readDayFile and writeDayFile+ store.writeDayFile = async (dateStr, data) => {+ writeCalls.push({ dateStr, data: JSON.parse(JSON.stringify(data)) });+ };++ dir = await mkdtemp(join(tmpdir(), 'portos-ahxml-upsert-'));+ xmlPath = join(dir, 'export.xml');+ });++ afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+ });++ it('updates step count when re-importing with a higher total', async () => {+ const XML_PARTIAL = `<?xml version="1.0" encoding="UTF-8"?>+<HealthData locale="en_US">+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count" startDate="2025-01-15 08:00:00 -0800" endDate="2025-01-15 08:05:00 -0800" value="100"/>+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count" startDate="2025-01-15 08:10:00 -0800" endDate="2025-01-15 08:15:00 -0800" value="50"/>+</HealthData>`;++ await writeFile(xmlPath, XML_PARTIAL, 'utf-8');+ await importAppleHealthXml(xmlPath, null);++ // Should have written one day with aggregated step count+ expect(writeCalls).toHaveLength(1);+ expect(writeCalls[0].dateStr).toBe('2025-01-15');+ // The aggregation should sum to 150+ expect(writeCalls[0].data.metrics.step_count[0].qty).toBe(150);+ });++ it('updates day with aggregated sleep analysis from re-import', async () => {+ const XML_SLEEP = `<?xml version="1.0" encoding="UTF-8"?>+<HealthData locale="en_US">+ <Record type="HKCategoryTypeIdentifierSleepAnalysis" sourceName="iPhone" value="HKCategoryValueSleepAnalysisAsleep" startDate="2025-01-14 23:00:00 -0800" endDate="2025-01-15 07:00:00 -0800"/>+ <Record type="HKCategoryTypeIdentifierSleepAnalysis" sourceName="iPhone" value="HKCategoryValueSleepAnalysisAwake" startDate="2025-01-15 07:00:00 -0800" endDate="2025-01-15 07:10:00 -0800"/>+</HealthData>`;++ await writeFile(xmlPath, XML_SLEEP, 'utf-8');+ await importAppleHealthXml(xmlPath, null);++ // Should have written two days with sleep analysis+ expect(writeCalls).toHaveLength(2);+ // Check that sleep_analysis was aggregated+ const day15 = writeCalls.find(c => c.dateStr === '2025-01-15');+ expect(day15.data.metrics.sleep_analysis).toBeDefined();+ });+});