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
refactor: replace sax dependency with a self-contained Apple Health Record parser (#1824)
[._.]/ Adam Eivyc9d7e02ed95e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 63e637a63f..643a823fd1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,3 +30,4 @@- **Split `server/lib/validation.js` (1,897-line multi-domain Zod barrel)** — the catch-all schema file that mixed 15+ unrelated domains is decomposed (continuing the #1151 `peerSyncValidation.js`/`creativeDirectorValidation.js` precedent) into four per-domain files: `agentValidation.js` (social-bot agent personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads, CoS Feature Agents), `cosValidation.js` (CoS tasks/jobs/loops/learning, the Review-Loop reviewer vocabulary + `normalizeReviewers`/`buildReviewWithArgs`, the Code-Review settings slice, and the task-metadata sanitizer), `mediaValidation.js` (LoRA training, local-LLM/Ollama/LM Studio management, CyberCity snapshots, media-collection bulk ops), and `pipelineValidation.js` (Writers Room, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). `validation.js` (~550 lines) keeps the app/process/provider, social-account, GitHub, backup/sharing, and document/legacy-export core plus the `validateRequest`/`validate`/`parsePagination` helpers, and re-exports the four new files (flat) so every existing deep `import { x } from '../lib/validation.js'` callsite keeps working unchanged; the barrel surfaces each as a namespace export. The new domain files import only `zodCompat.js` + leaf constant modules (never back through `validation.js`), keeping the transitional re-export cycle-safe under ESM. (#1831)- **Decomposed `server/services/sharing/peerSync.js` (4,004-line god file mixing 3 sync protocols)** — the single module that inlined per-record subscription CRUD + the outbound push path (951-line region) + the receiver path (909-line region) + standalone media-library sync + CoS-history/tasks sync is now split into one concern per file: `peerSyncShared.js` (state machine, constants, peer-capability helpers, the cross-cutting event bus), `peerSyncAssets.js` (asset manifest build/diff/hash + the receiver-side asset-pull worker, reused by every receive path), `peerSyncPush.js` (the `pushRecordToPeer` pipeline + payload builder + schema-gate bookkeeping), `peerSyncReceive.js` (`applyIncomingPush` + reverse-subscribe + merge dispatch), `peerMediaLibrarySync.js` (#1566 media-library sweep), and `peerCosSync.js` (#1650 CoS history + tasks). `peerSync.js` (~985 lines) stays the orchestrator — subscription CRUD, the debounced push scheduler, the `recordEvents`/`peer:online` listeners, and the boot-time `registerSubscriptionAdapter` wiring — and re-exports the extracted modules' public surface so every existing importer (routes, `sharing/index.js`, `dataSync`, the test suite) keeps working unchanged. The leaf-`peerSyncShared` design keeps the only module cycle (`peerSync` ↔ `peerSyncReceive`, both call-time-only) safe under ESM. Verified behavior-preserving: the full server suite produces byte-identical pass/fail results before and after (zero regressions, 15,092 tests), the DB suite is 156/156 green, and the server smoke-boots cleanly. (#1830)- **Decomposed `server/lib/editorial/checkRegistry.js` (7,474-line god file)** — the single module that held ~2,400 lines of shared infra plus a 68-entry `EDITORIAL_CHECKS` array (each embedding a full `run(ctx)` closure) is now split: shared infra lives in `checkInfra.js`, the 68 checks are grouped by category into `checks/*.js` (`naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`), and `checkRegistry.js` (~480 lines) stays the public entry point — assembling `EDITORIAL_CHECKS` from the per-category arrays and keeping the registry's lookup/state helpers. The check files import shared infra from `checkInfra.js` (not back through the registry) so the `EDITORIAL_CHECKS` spread can't hit a TDZ on the checks' eagerly-evaluated `configSchema`s. The editorial barrel's public API is byte-for-byte identical (173 exports, verified) and all editorial + runner tests pass unchanged. (#1829)+- **Dropped the `sax` dependency from the Apple Health XML importer** — the 500MB-export streaming path now uses a self-contained ~190-line `Record` parser (`server/services/appleHealthXmlParser.js`) that splits the byte stream on `<Record>` tag boundaries and parses attributes with a quote-aware scan, preserving the prior backpressure (caller pauses the source stream) and error-skip (malformed records dropped, not fatal) behavior. Per the PortOS "write small helpers yourself" policy; covered by new unit + chunk-boundary tests. Partial-ships the `sax` half of #1824; the client `three-fenestra` shader replacement is tracked separately. (#1824)diff --git a/server/package.json b/server/package.jsonindex 0acd3525a2..327a38cb98 100644--- a/server/package.json+++ b/server/package.json@@ -24,7 +24,6 @@"pdf-lib": "^1.17.1","pg": "8.22.0","pm2": "7.0.1",- "sax": "^1.6.0","sharp": "0.35.2","socket.io": "4.8.3","socket.io-client": "4.8.3",diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.jsindex 9afbabe05c..c592839de8 100644--- a/server/services/appleHealthXml.js+++ b/server/services/appleHealthXml.js@@ -1,15 +1,15 @@/*** Apple Health XML Import Service*- * SAX streaming parser for Apple Health exports (500MB+).+ * Dependency-free streaming parser for Apple Health exports (500MB+).* Normalizes HK identifiers to metric names matching JSON ingest format.* Emits WebSocket progress events every 10k records.*/-import sax from 'sax';import { createReadStream } from 'fs';import { unlink } from 'fs';import { extractDateStr, readDayFile, writeDayFile } from './appleHealthIngest.js';+import { createAppleHealthRecordStream } from './appleHealthXmlParser.js';// === Mapping Tables ===@@ -102,9 +102,9 @@ const SLEEP_STAGE_MAP = {/*** Normalize an XML Record node into a standard data point.- * Uses lowercase attribute names (sax non-strict lowercase mode).+ * Uses lowercase attribute names (matching the parser's lowercase-name mode).*- * @param {Object} node - SAX opentag node with lowercase attributes+ * @param {Object} node - Record node with lowercase attribute names* @returns {{ metricName: string, dateStr: string, dataPoint: Object }|null}*/export function normalizeXmlRecord(node) {@@ -248,8 +248,9 @@ async function flushDayBuckets(dayBuckets) {}/**- * Stream-parse an Apple Health export.xml file using SAX.- * Accumulates records in batches, flushing to disk periodically to avoid OOM.+ * Stream-parse an Apple Health export.xml file with the dependency-free+ * `<Record>` parser. Accumulates records in batches, flushing to disk+ * periodically to avoid OOM.** @param {string} filePath - Absolute path to the XML file (temp upload)* @param {Object|null} io - Socket.IO server instance for progress events@@ -266,53 +267,47 @@ export async function importAppleHealthXml(filePath, io = null) {const inputStream = createReadStream(filePath);await new Promise((resolve, reject) => {- const saxStream = sax.createStream(false, { lowercase: true });-- saxStream.on('opentag', (node) => {- if (node.name !== 'record') return;-- const normalized = normalizeXmlRecord(node);- if (!normalized) return;-- const { metricName, dateStr, dataPoint } = normalized;-- if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};- if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];- dayBuckets[dateStr][metricName].push(dataPoint);- allDays.add(dateStr);-- processedRecords++;-- if (processedRecords % 10000 === 0) {- io?.emit('health:xml:progress', { processed: processedRecords });- console.log(`🍎 XML import progress: ${processedRecords} records`);- }-- // Batch flush to prevent OOM — pause input stream, flush to disk, resume- if (processedRecords - lastFlush >= FLUSH_INTERVAL && !flushing) {- flushing = true;- lastFlush = processedRecords;- inputStream.pause();- flushDayBuckets(dayBuckets).then(() => {- console.log(`🍎 Flushed batch at ${processedRecords} records (${allDays.size} days total)`);- flushing = false;- inputStream.resume();- }).catch(reject);- }- });-- saxStream.on('error', function (e) {- console.error(`❌ XML parse error at record ${processedRecords}: ${e.message}`);- // Clear error and resume — Apple Health XML can have minor malformations- this._parser.error = null;- this._parser.resume();+ const parser = createAppleHealthRecordStream({+ onRecord: (node) => {+ const normalized = normalizeXmlRecord(node);+ if (!normalized) return;++ const { metricName, dateStr, dataPoint } = normalized;++ if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};+ if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];+ dayBuckets[dateStr][metricName].push(dataPoint);+ allDays.add(dateStr);++ processedRecords++;++ if (processedRecords % 10000 === 0) {+ io?.emit('health:xml:progress', { processed: processedRecords });+ console.log(`🍎 XML import progress: ${processedRecords} records`);+ }++ // Batch flush to prevent OOM — pause input stream, flush to disk, resume+ if (processedRecords - lastFlush >= FLUSH_INTERVAL && !flushing) {+ flushing = true;+ lastFlush = processedRecords;+ inputStream.pause();+ flushDayBuckets(dayBuckets).then(() => {+ console.log(`🍎 Flushed batch at ${processedRecords} records (${allDays.size} days total)`);+ flushing = false;+ inputStream.resume();+ }).catch(reject);+ }+ },});- saxStream.on('end', resolve);- saxStream.on('close', resolve);+ // Malformed records can't throw here — records missing required attributes+ // are dropped by normalizeXmlRecord, so minor XML malformations are skipped+ // rather than fatal (matching the prior sax error-skip behavior).+ parser.on('finish', resolve);+ parser.on('error', reject);inputStream.on('error', reject);- inputStream.pipe(saxStream);+ inputStream.pipe(parser);});console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${allDays.size} days — flushing remaining`);diff --git a/server/services/appleHealthXmlParser.js b/server/services/appleHealthXmlParser.jsnew file mode 100644index 0000000000..71f7a3136f--- /dev/null+++ b/server/services/appleHealthXmlParser.js@@ -0,0 +1,155 @@+/**+ * Apple Health XML Record Parser+ *+ * A dependency-free streaming parser for Apple Health `export.xml` files+ * (500MB+). Apple Health exports are machine-generated flat XML where every+ * sample is a self-contained `<Record .../>` element, so we only need to pull+ * the attributes off each `<Record>` opening tag — no general-purpose XML/DOM+ * parser required.+ *+ * This replaces the `sax` dependency (issue #1824): a ~Writable that splits the+ * byte stream on `<Record` tag boundaries, parses attributes with a quote-aware+ * scan, and invokes `onRecord({ name: 'record', attributes })` with lowercased+ * attribute names — matching what `sax.createStream(false, { lowercase: true })`+ * emitted on `opentag`. Backpressure is preserved by the caller pausing the+ * source read stream; malformed input is skipped rather than fatal (records with+ * missing required attributes are dropped downstream by `normalizeXmlRecord`).+ */++import { Writable } from 'stream';+import { StringDecoder } from 'string_decoder';++const RECORD_TAG = '<Record';++const NAMED_ENTITIES = {+ amp: '&',+ lt: '<',+ gt: '>',+ quot: '"',+ apos: "'",+};++/**+ * Decode the XML entities that can appear in attribute values (named + numeric).+ * Apple Health source/device names occasionally carry `&` and friends.+ *+ * @param {string} str - Raw attribute value+ * @returns {string} Decoded value (unchanged if it contains no entities)+ */+export function decodeXmlEntities(str) {+ if (!str || str.indexOf('&') === -1) return str;+ return str.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, code) => {+ if (code[0] === '#') {+ const cp = code[1] === 'x' || code[1] === 'X'+ ? parseInt(code.slice(2), 16)+ : parseInt(code.slice(1), 10);+ return Number.isFinite(cp) ? String.fromCodePoint(cp) : match;+ }+ return NAMED_ENTITIES[code] ?? match;+ });+}++const ATTR_RE = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;++/**+ * Parse the attribute string of an element's opening tag into a lowercased-key+ * map, decoding entity references in each value. Mirrors sax's lowercase mode:+ * attribute NAMES are lowercased; VALUES are preserved (the caller lowercases+ * the bits it needs).+ *+ * @param {string} openTag - The opening tag text, e.g. `<Record type="HK..." value="72">`+ * @returns {Object} Map of lowercased attribute name → decoded value+ */+export function parseAttributes(openTag) {+ const attrs = {};+ ATTR_RE.lastIndex = 0;+ let m;+ while ((m = ATTR_RE.exec(openTag)) !== null) {+ const key = m[1].toLowerCase();+ const raw = m[2] !== undefined ? m[2] : m[3];+ attrs[key] = decodeXmlEntities(raw);+ }+ return attrs;+}++/**+ * Find the index of the `>` that closes an opening tag, ignoring any `>` that+ * sits inside a quoted attribute value (legal in XML attribute values).+ *+ * @param {string} str - The working buffer+ * @param {number} from - Index to start scanning from (just past `<Record`)+ * @returns {number} Index of the closing `>`, or -1 if not yet in the buffer+ */+function findTagEnd(str, from) {+ let quote = null;+ for (let i = from; i < str.length; i++) {+ const c = str[i];+ if (quote) {+ if (c === quote) quote = null;+ } else if (c === '"' || c === "'") {+ quote = c;+ } else if (c === '>') {+ return i;+ }+ }+ return -1;+}++/**+ * Create a Writable stream that parses Apple Health `<Record>` elements out of a+ * piped XML byte stream and calls `onRecord` for each one. Non-`Record` content+ * (the DOCTYPE/DTD, `<Workout>`, `<ActivitySummary>`, `<MetadataEntry>` children,+ * the `<HealthData>` root) is skipped without buffering — only the in-flight+ * fragment around a `<Record>` boundary is retained, so memory stays flat across+ * a multi-hundred-MB file.+ *+ * @param {{ onRecord: (node: { name: 'record', attributes: Object }) => void }} opts+ * @returns {import('stream').Writable}+ */+export function createAppleHealthRecordStream({ onRecord }) {+ const decoder = new StringDecoder('utf8');+ let buffer = '';++ const drain = () => {+ let i = 0;+ // Index we must retain from because a *valid* record is only partially+ // buffered (token or opening tag split across a chunk boundary). -1 = none.+ let pending = -1;+ while (true) {+ const idx = buffer.indexOf(RECORD_TAG, i);+ if (idx === -1) break;+ // The char after `<Record` must be a tag boundary (whitespace, `/`, `>`),+ // so a longer element like `<RecordingDevice` can't be taken for a Record.+ const after = buffer[idx + RECORD_TAG.length];+ if (after === undefined) { pending = idx; break; } // token split — wait for more+ if (after !== ' ' && after !== '\t' && after !== '\n' && after !== '\r'+ && after !== '/' && after !== '>') {+ i = idx + RECORD_TAG.length; // false match (e.g. <RecordingDevice) — skip past+ continue;+ }+ const end = findTagEnd(buffer, idx + RECORD_TAG.length);+ if (end === -1) { pending = idx; break; } // opening tag not fully buffered — wait+ onRecord({ name: 'record', attributes: parseAttributes(buffer.slice(idx, end + 1)) });+ i = end + 1;+ }+ // Retain only the incomplete-record fragment, or a short tail so a `<Record`+ // token split across the next chunk boundary is still found. Rejected+ // false-matches are dropped, so junk can't accumulate in the buffer.+ buffer = pending !== -1+ ? buffer.slice(pending)+ : buffer.slice(Math.max(0, buffer.length - (RECORD_TAG.length - 1)));+ };++ return new Writable({+ write(chunk, _enc, cb) {+ buffer += decoder.write(chunk);+ drain();+ cb();+ },+ final(cb) {+ buffer += decoder.end();+ drain();+ cb();+ },+ });+}diff --git a/server/services/appleHealthXmlParser.test.js b/server/services/appleHealthXmlParser.test.jsnew file mode 100644index 0000000000..a2f8cfe76a--- /dev/null+++ b/server/services/appleHealthXmlParser.test.js@@ -0,0 +1,146 @@+import { describe, it, expect } from 'vitest';+import { Readable } from 'stream';+import { pipeline } from 'stream/promises';+import {+ decodeXmlEntities,+ parseAttributes,+ createAppleHealthRecordStream,+} from './appleHealthXmlParser.js';++// Drive the parser the way the import service does: pipe a source readable into+// it, collecting every emitted Record node.+async function parse(input, { chunkSize } = {}) {+ const records = [];+ const parser = createAppleHealthRecordStream({ onRecord: (n) => records.push(n) });+ const buf = Buffer.from(input, 'utf8');+ const source = chunkSize+ ? Readable.from((function* () {+ for (let i = 0; i < buf.length; i += chunkSize) yield buf.subarray(i, i + chunkSize);+ })())+ : Readable.from([buf]);+ await pipeline(source, parser);+ return records;+}++describe('decodeXmlEntities', () => {+ it('returns the input unchanged when there are no entities', () => {+ expect(decodeXmlEntities('plain text')).toBe('plain text');+ expect(decodeXmlEntities('')).toBe('');+ });++ it('decodes the named XML entities', () => {+ expect(decodeXmlEntities('A & B')).toBe('A & B');+ expect(decodeXmlEntities('<tag>')).toBe('<tag>');+ expect(decodeXmlEntities('say "hi"')).toBe('say "hi"');+ expect(decodeXmlEntities('it's')).toBe("it's");+ });++ it('decodes decimal and hex numeric character references', () => {+ expect(decodeXmlEntities(''')).toBe("'");+ expect(decodeXmlEntities('café')).toBe('café');+ expect(decodeXmlEntities('café')).toBe('café');+ });++ it('leaves unknown entities untouched', () => {+ expect(decodeXmlEntities('&bogus;')).toBe('&bogus;');+ });+});++describe('parseAttributes', () => {+ it('lowercases attribute names but preserves value case', () => {+ const attrs = parseAttributes('<Record Type="HKQuantityTypeIdentifierHeartRate" Value="72">');+ expect(attrs.type).toBe('HKQuantityTypeIdentifierHeartRate');+ expect(attrs.value).toBe('72');+ });++ it('handles single-quoted values and decodes entities', () => {+ const attrs = parseAttributes("<Record sourceName='Adam & Co' unit='count'>");+ expect(attrs.sourcename).toBe('Adam & Co');+ expect(attrs.unit).toBe('count');+ });++ it('returns an empty object for an attribute-less tag', () => {+ expect(parseAttributes('<Record>')).toEqual({});+ });+});++describe('createAppleHealthRecordStream', () => {+ const SAMPLE = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE HealthData [+<!ELEMENT Record (MetadataEntry)*>+<!ATTLIST Record type CDATA #REQUIRED>+]>+<HealthData locale="en_US">+ <ExportDate value="2024-01-15 08:30:00 -0800"/>+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count" value="1200" startDate="2024-01-15 08:00:00 -0800" endDate="2024-01-15 08:30:00 -0800"/>+ <Record type="HKQuantityTypeIdentifierHeartRate" value="72" startDate="2024-01-15 09:00:00 -0800">+ <MetadataEntry key="HKMetadataKeyHeartRateMotionContext" value="1"/>+ </Record>+ <Workout workoutActivityType="HKWorkoutActivityTypeRunning"/>+</HealthData>`;++ it('emits one node per Record opening tag with lowercased attribute names', async () => {+ const records = await parse(SAMPLE);+ expect(records).toHaveLength(2);+ expect(records[0].name).toBe('record');+ expect(records[0].attributes.type).toBe('HKQuantityTypeIdentifierStepCount');+ expect(records[0].attributes.value).toBe('1200');+ expect(records[1].attributes.type).toBe('HKQuantityTypeIdentifierHeartRate');+ expect(records[1].attributes.startdate).toBe('2024-01-15 09:00:00 -0800');+ });++ it('skips DTD declarations and non-Record elements', async () => {+ const records = await parse(SAMPLE);+ // Neither <!ATTLIST Record ...> / <!ELEMENT Record ...> nor <Workout> nor+ // <MetadataEntry> should be reported as a Record.+ expect(records.every((r) => r.attributes.type?.startsWith('HKQuantity'))).toBe(true);+ });++ it('reassembles records split across chunk boundaries (1-byte chunks)', async () => {+ const records = await parse(SAMPLE, { chunkSize: 1 });+ expect(records).toHaveLength(2);+ expect(records[0].attributes.value).toBe('1200');+ expect(records[1].attributes.value).toBe('72');+ });++ it('is robust to small chunk sizes that split UTF-8 multibyte values', async () => {+ const xml = '<HealthData><Record type="t" sourceName="café" startDate="x"/></HealthData>';+ const records = await parse(xml, { chunkSize: 3 });+ expect(records).toHaveLength(1);+ expect(records[0].attributes.sourcename).toBe('café');+ });++ it('does not treat a `>` inside an attribute value as the tag end', async () => {+ const xml = '<HealthData><Record type="a>b" value="1" startDate="x"/></HealthData>';+ const records = await parse(xml);+ expect(records).toHaveLength(1);+ expect(records[0].attributes.type).toBe('a>b');+ expect(records[0].attributes.value).toBe('1');+ });++ it('does not match a longer element name that merely starts with Record', async () => {+ const xml = '<HealthData><RecordingDevice id="1"/><Record type="t" startDate="x"/></HealthData>';+ const records = await parse(xml);+ expect(records).toHaveLength(1);+ expect(records[0].attributes.type).toBe('t');+ });++ it('does not match a longer element even when it trails at a chunk boundary', async () => {+ // <RecordingDevice ...> arriving in tiny chunks must not be retained or+ // mistaken for a Record; only the real <Record> is reported.+ const xml = '<HealthData><Record type="t" startDate="x"/><RecordingDevice id="9"/></HealthData>';+ const records = await parse(xml, { chunkSize: 2 });+ expect(records).toHaveLength(1);+ expect(records[0].attributes.type).toBe('t');+ });++ it('decodes entities in attribute values', async () => {+ const xml = '<HealthData><Record type="t" sourceName="A & B" startDate="x"/></HealthData>';+ const records = await parse(xml);+ expect(records[0].attributes.sourcename).toBe('A & B');+ });++ it('handles an empty stream without emitting anything', async () => {+ expect(await parse('')).toEqual([]);+ });+});diff --git a/server/services/claudeChangelog.js b/server/services/claudeChangelog.jsindex 0c834b7990..891373c1de 100644--- a/server/services/claudeChangelog.js+++ b/server/services/claudeChangelog.js@@ -50,8 +50,8 @@ function extractTag(entryXml, tag) {/*** Parse the GitHub releases Atom feed into flat entries. The feed is small* and flat (one level of <entry> under <feed>), so a focused extractor beats- * pulling in a streaming SAX parser — sax stays for the 500MB Apple Health- * export path where streaming actually matters (issue #1167).+ * pulling in a general XML parser — same dependency-free approach the streaming+ * Apple Health `<Record>` parser takes for the 500MB export path (issue #1167).*/function parseAtomFeed(xml) {const entries = []@@ -147,5 +147,5 @@ export async function getCachedChangelog() {}// Exposed for unit tests — the Atom parse is the regex-extractor that replaced-// sax on this path (issue #1167).+// a general XML parser on this path (issue #1167).export const __testing = { parseAtomFeed, stripHtml, extractVersion }