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: preserve Apple Health source observations on reimport
Adam Eivy768f6694b49a
diff --git a/server/lib/README.md b/server/lib/README.mdindex d054698a7b..442c26da64 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -118,6 +118,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `cronValidation.js` | Cron syntax + field-range validation (pure, import-free, browser-safe). `isValidCronExpression` / `findCronExpressionError` (a user-facing reason string) / `isValidCronField` / `isCronShaped` (5-token SHAPE only — the named-cadence detector, never a stand-in for validity), plus `CRON_FIELD_NAMES` / `CRON_FIELD_BOUNDS`. ONE implementation shared by `services/eventScheduler.js`, the CoS schedule + per-app task-type save routes, the app-override schema in `validation.js`, and the browser cron editor via `client/src/utils/cronHelpers.js` (#6634). Syntax validity is deliberately separate from whether an occurrence exists in the scheduler bounded search window — a leap-day cron is valid. || `recurrenceValidation.js` | Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron. || `appleHealthValidation.js` | Apple Health import payloads. |+| `appleHealthPoints.js` | `healthPointOrigin` and `healthPointKey`: legacy-aware importer/source identity shared by health ingestion and daily source selection. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). || `catalogExtractionDraft.js` | Extraction-only six-type graph schema, strict grounded-output parsing, and conservative chunk identity/edge reconciliation. || `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |diff --git a/server/lib/appleHealthPoints.js b/server/lib/appleHealthPoints.jsnew file mode 100644index 0000000000..4f097c1a8c--- /dev/null+++ b/server/lib/appleHealthPoints.js@@ -0,0 +1,10 @@+/** Legacy XML points carry src (including null); legacy HAE points do not. */+export function healthPointOrigin(point) {+ return point.origin ?? (Object.prototype.hasOwnProperty.call(point, 'src') ? 'xml' : 'hae');+}++/** Identity within one metric: HAE is already device-merged; XML is per source. */+export function healthPointKey(point) {+ const origin = healthPointOrigin(point);+ return JSON.stringify([origin, origin === 'xml' ? (point.src ?? null) : null, point.date]);+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 30e8573f9e..0e281bc763 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -31,6 +31,7 @@ export * as managedVisitorValidation from './managedVisitorValidation.js';export * as agentValidation from './agentValidation.js';export * as agentContextValidation from './agentContextValidation.js';export * as appleHealthValidation from './appleHealthValidation.js';+export * from './appleHealthPoints.js';export * as brainValidation from './brainValidation.js';export * from './brainThreads.js';export * from './humanActions.js';diff --git a/server/services/appleHealthIngest.integration.test.js b/server/services/appleHealthIngest.integration.test.jsnew file mode 100644index 0000000000..06c0d82aa3--- /dev/null+++ b/server/services/appleHealthIngest.integration.test.js@@ -0,0 +1,101 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync } from 'node:fs';+import { mkdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const dataRoot = mkdtempSync(join(tmpdir(), 'portos-health-replay-'));+vi.mock('../lib/fileUtils.js', async () =>+ makePathsProxy(await vi.importActual('../lib/fileUtils.js'), { dataRoot }));++const { PATHS } = await import('../lib/fileUtils.js');+const { ingestHealthData, readDayFile } = await import('./appleHealthIngest.js');+const { importAppleHealthXml } = await import('./appleHealthXml.js');+const { getDailyAggregates } = await import('./appleHealthQuery.js');++const day = '2026-01-02';+const timestamp = `${day} 08:00:00 +0000`;+const payload = (name, data) => ({ data: { metrics: [{ name, data }] } });+const aggregate = (metric) => getDailyAggregates(metric, day, day);++async function importSteps(watch = 120) {+ const path = join(dataRoot, 'export.xml');+ await writeFile(path, `<HealthData>+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count" startDate="${timestamp}" value="${watch}"/>+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Phone" unit="count" startDate="${timestamp}" value="80"/>+ </HealthData>`);+ await importAppleHealthXml(path);+}++beforeEach(async () => {+ await rm(dataRoot, { recursive: true, force: true });+ await mkdir(PATHS.health, { recursive: true });+});+afterAll(() => rm(dataRoot, { recursive: true, force: true }));++describe('health ingestion replay through stored daily aggregates', () => {+ it('preserves device observations and HAE precedence across XML reimports', async () => {+ await importSteps();+ expect(await aggregate('step_count')).toMatchObject([{ value: 120 }]);+ await importSteps();+ expect((await readDayFile(day)).metrics.step_count).toHaveLength(2);+ expect(await aggregate('step_count')).toMatchObject([{ value: 120 }]);++ // A correction replaces only the same device's observation.+ await importSteps(150);+ expect((await readDayFile(day)).metrics.step_count).toHaveLength(2);+ expect(await aggregate('step_count')).toMatchObject([{ value: 150 }]);++ await ingestHealthData(payload('step_count', [{ date: timestamp, qty: 200 }]));+ await importSteps(160);+ const stored = (await readDayFile(day)).metrics.step_count;+ expect(stored).toHaveLength(3);+ expect(stored).toEqual(expect.arrayContaining([+ expect.objectContaining({ origin: 'xml', src: 'Watch', qty: 160 }),+ expect.objectContaining({ origin: 'xml', src: 'Phone', qty: 80 }),+ expect.objectContaining({ origin: 'hae', qty: 200 }),+ ]));+ expect(await aggregate('step_count')).toMatchObject([{ value: 200 }]);+ });++ it('deduplicates fresh HAE batches and persists repair of existing duplicate points', async () => {+ const point = { date: timestamp, qty: 50 };+ const batch = payload('active_energy', [point, point, { ...point, qty: 60 }]);+ expect(await ingestHealthData(batch)).toMatchObject({ recordsIngested: 1, recordsUpdated: 1, recordsSkipped: 1 });+ expect((await readDayFile(day)).metrics.active_energy).toHaveLength(1);+ expect(await aggregate('active_energy')).toMatchObject([{ value: 60 }]);++ // Older versions persisted identical duplicates on the first batch and+ // skipped writing the canonical set when a later replay changed no value.+ const savedPoint = { ...point, origin: 'hae' };+ await writeFile(join(PATHS.health, `${day}.json`), JSON.stringify({+ date: day, metrics: { active_energy: [savedPoint, savedPoint] },+ }));+ const replay = payload('active_energy', [point, point]);+ expect(await ingestHealthData(replay)).toMatchObject({ recordsIngested: 0, recordsUpdated: 0, recordsSkipped: 2, daysAffected: 1 });+ expect((await readDayFile(day)).metrics.active_energy).toEqual([savedPoint]);+ expect(await aggregate('active_energy')).toMatchObject([{ value: 50 }]);+ expect(await ingestHealthData(replay)).toMatchObject({ recordsIngested: 0, recordsUpdated: 0, recordsSkipped: 2, daysAffected: 0 });+ });++ it('upgrades legacy origins without dropping a different source at the same timestamp', async () => {+ await writeFile(join(PATHS.health, `${day}.json`), JSON.stringify({+ date: day, metrics: { step_count: [+ { date: timestamp, qty: 100, src: 'Watch' },+ { date: timestamp, qty: 70, src: null },+ { date: timestamp, qty: 180 },+ ] },+ }));+ await importSteps(150);+ await ingestHealthData(payload('step_count', [{ date: timestamp, qty: 200 }]));+ const points = (await readDayFile(day)).metrics.step_count;+ expect(points).toHaveLength(4);+ expect(points).toEqual(expect.arrayContaining([+ expect.objectContaining({ origin: 'xml', src: 'Watch', qty: 150 }),+ expect.objectContaining({ src: null, qty: 70 }),+ expect.objectContaining({ origin: 'hae', qty: 200 }),+ ]));+ expect(await aggregate('step_count')).toMatchObject([{ value: 200 }]);+ });+});diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.jsindex 1edc194172..b0cbd96be6 100644--- a/server/services/appleHealthIngest.js+++ b/server/services/appleHealthIngest.js@@ -2,13 +2,14 @@* Apple Health Ingest Service** Handles JSON ingest from Health Auto Export app, deduplication by- * metric+timestamp, and day-partitioned file storage at data/health/YYYY-MM-DD.json.+ * metric+origin+source+timestamp, and day-partitioned file storage at data/health/YYYY-MM-DD.json.*/import { invalidateMeatspace } from './meatspaceEvents.js';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';+import { healthPointKey } from '../lib/appleHealthPoints.js';// === Module State ===@@ -146,44 +147,41 @@ export async function writeDayFile(dateStr, data, changedMetrics = Object.keys(d/*** 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.+ * Replace only the same origin/source/timestamp. Different XML devices and+ * HAE observations coexist so the query layer can choose the day's source.** @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();+ // Use the same identity on a first import, replay, and legacy day file.+ const pointsByKey = new Map();for (const point of existing) {- pointsByDate.set(point.date, point);+ pointsByKey.set(healthPointKey(point), point);}let added = 0;let updated = 0;- // Process new points: update if date exists, otherwise add+ // Process new points: update the matching observation, otherwise add.for (const newPoint of newPoints) {- if (pointsByDate.has(newPoint.date)) {+ const key = healthPointKey(newPoint);+ if (pointsByKey.has(key)) {// Check if the point actually changed- const oldPoint = pointsByDate.get(newPoint.date);+ const oldPoint = pointsByKey.get(key);if (JSON.stringify(oldPoint) !== JSON.stringify(newPoint)) {- pointsByDate.set(newPoint.date, newPoint);+ pointsByKey.set(key, newPoint);updated++;}// If identical, count as a dupe (neither added nor updated)} else {- pointsByDate.set(newPoint.date, newPoint);+ pointsByKey.set(key, newPoint);added++;}}- const result = Array.from(pointsByDate.values());+ const result = Array.from(pointsByKey.values());return { added, updated, result };}@@ -194,7 +192,7 @@ export function upsertPoints(existing, newPoints) {* @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<Object>} { added, updated, totalPoints }+ * @returns {Promise<Object>} { added, updated, totalPoints, changed }*/export async function mergeIntoDay(dateStr, metricName, newPoints) {return queueHealthDayMutation(dateStr, async () => {@@ -203,12 +201,15 @@ export async function mergeIntoDay(dateStr, metricName, newPoints) {const { added, updated, result } = upsertPoints(existing, newPoints);- if (added > 0 || updated > 0) {+ // Repair duplicate identities left by older first-import behavior even+ // when every incoming value already matches the canonical point.+ const changed = added > 0 || updated > 0 || result.length !== existing.length;+ if (changed) {dayData.metrics[metricName] = result;await writeDayFile(dateStr, dayData, [metricName]);}- return { added, updated, totalPoints: result.length };+ return { added, updated, totalPoints: result.length, changed };});}@@ -261,7 +262,7 @@ export async function ingestHealthData(payload) {recordsIngested += result.added;recordsUpdated += result.updated;recordsSkipped += (points.length - result.added - result.updated);- if (result.added > 0 || result.updated > 0) affectedDays.add(dateStr);+ if (result.changed) affectedDays.add(dateStr);}}diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.jsindex ef18af601c..c97da4301c 100644--- a/server/services/appleHealthQuery.js+++ b/server/services/appleHealthQuery.js@@ -8,6 +8,7 @@import { readdir } from 'fs/promises';import { PATHS } from '../lib/fileUtils.js';import { readDayFile } from './appleHealthIngest.js';+import { healthPointOrigin } from '../lib/appleHealthPoints.js';import { getDailyAlcohol } from './meatspaceAlcohol.js';import { getDailyNicotine } from './meatspaceNicotine.js';import { getBloodTests } from './meatspaceHealth.js';@@ -77,12 +78,10 @@ export async function getAvailableDateRange() {export function pickDaySumPoints(points, getValue) {if (points.length === 0) return points;- const originOf = (p) => p.origin ?? (Object.prototype.hasOwnProperty.call(p, 'src') ? 'xml' : 'hae');-- const haePoints = points.filter((p) => originOf(p) === 'hae');+ const haePoints = points.filter((p) => healthPointOrigin(p) === 'hae');if (haePoints.length > 0) return haePoints;- const xmlPoints = points.filter((p) => originOf(p) === 'xml');+ const xmlPoints = points.filter((p) => healthPointOrigin(p) === 'xml');if (xmlPoints.length === 0) return points;const bySrc = new Map();