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: consolidate XML-entity decoders into shared server/lib/xmlEntities.js (#1876)
[._.]/ Adam Eivya492727ab23b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 923209f1c3..fe77a529ca 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -55,3 +55,4 @@- **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)- **[issue-1837] On-disk JSON writes are now crash-safe across ~50 service/route files** — ~73 persistence sites used a raw `writeFile(path, JSON.stringify(data, null, 2))`, which truncates the JSON file if the process crashes mid-write (leaving an unparseable half-record on disk). Each was swapped to the canonical `atomicWrite` helper (`server/lib/fileUtils.js`), which writes to a temp file and atomically renames it over the target so readers never see a partial write. Covers brain storage, run/agent metadata, decision log, meatspace (calendar/alcohol/nicotine/health/post), mortal-loom store, identity goals, image/video sidecars, GitHub/Google/Obsidian configs, taste/usage/genome/epigenetic stores, and the scaffolding routes. Sites that intentionally append a trailing newline keep their exact byte output (passed as a pre-stringified string), and `videoGen/local.js`'s `{ flag: 'wx' }` exclusive-create write is left as-is (atomicWrite can't replicate exclusive-create). (#1837)- **[issue-1846] Replaced vacuous inline-copy tests with coverage of real production logic** — `subAgentSpawner.test.js` had four `describe` blocks that re-implemented production logic inline and tested the copies, so the real code could regress while the suite stayed green: an inline `ERROR_PATTERNS`/`categorizeError`, an inline `resolveFailedTaskStatus` (which omitted the `MAX_TOTAL_SPAWNS` short-circuit and `compaction` metadata that the real `resolveFailedTaskUpdate` has), and stub `exitCodeMessages`/`buildSpawnArgs` literals exported from no production module. The error-classification and retry-decision blocks now live in `agentErrorAnalysis.test.js` against the real exported `ERROR_PATTERNS` (via `analyzeAgentFailure`) and a new pure `resolveFailedTaskDecision` helper extracted from `resolveFailedTaskUpdate` (the async wrapper delegates to it and just stamps timestamps + creates the investigation task — behavior-preserving); the exit-code block is replaced by a new `agentRunTracking.test.js` covering the real `extractErrorFromOutput` mapping; and the redundant spawn-args stub is dropped since `agentCliSpawning.test.js` already covers the real `buildCliSpawnConfig`. The genuine imported-helper tests (`isTruthyMeta`/`isFalsyMeta`/`applyAppWorktreeDefault`) are kept. (#1846)+- **[issue-1876] Consolidated four private XML-entity decoders into a shared `server/lib/xmlEntities.js`** — `decodeXmlEntities`/`decodeEntities`/inline `stripHtml` had drifted into near-identical copies across `appleHealthXmlParser.js`, `claudeChangelog.js`, `pinterestFeed.js`, `feeds.js`, and `messageGmailSync.js`, so an entity-handling fix had to be applied in up to five places. The most complete implementation (named + decimal `&#NN;` + hex `&#xNN;` via a single double-decode-safe pass, out-of-range-tolerant) is promoted to a shared, barrel-registered helper that also takes an optional extra-named-entity map (`{ nbsp: ' ', zwnj: '' }`) for the mail-specific entities Gmail's HTML-to-text needs; every call site now imports it. Behavior-preserving (each site's existing tests pass on the shared single-pass decoder); covered by a new `xmlEntities.test.js`. (#1876)diff --git a/server/lib/README.md b/server/lib/README.mdindex a4e7cec82d..25d60119c5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -182,6 +182,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `jsonExtract.js` | Pull JSON blocks out of LLM responses. || `taskParser.js` | Parse `TASKS.md` format. |+| `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |## Curated static datadiff --git a/server/lib/index.js b/server/lib/index.jsindex a99ca861d0..6f474f9512 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -164,6 +164,7 @@ export * from './vectorMath.js';// === Extraction & parsing ===export * from './jsonExtract.js';export * from './taskParser.js';+export * from './xmlEntities.js';// === Curated static data ===export * from './curatedGenomeMarkers.js';diff --git a/server/lib/pinterestFeed.js b/server/lib/pinterestFeed.jsindex f7fada1ad8..d50d15b1e3 100644--- a/server/lib/pinterestFeed.js+++ b/server/lib/pinterestFeed.js@@ -14,6 +14,8 @@* the download/persist orchestration in `services/moodBoard/pinterest.js`.*/+import { decodeXmlEntities } from './xmlEntities.js';+import { ServerError } from './errorHandler.js';// Explicit allow-list of Pinterest's REGISTRABLE domains. A registrable-label@@ -95,10 +97,10 @@ export function normalizePinterestFeedUrl(input) {// Minimal HTML-entity decode for URLs/titles pulled out of the feed (the// feed escapes `&` as `&` inside attribute values, which would corrupt an-// image URL's query string if left encoded).+// image URL's query string if left encoded). Trims, like the rest of the feed+// extractors. Numeric refs (`'`, `'`) are handled by the shared decoder.const decodeEntities = (s) => (typeof s === 'string'- ? s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')- .replace(/"/g, '"').replace(/�?39;/g, "'").trim()+ ? decodeXmlEntities(s).trim(): s);// Non-greedy single-tag text extractor (CDATA-aware). Mirrors feeds.js's@@ -111,10 +113,7 @@ const extractTag = (xml, tag) => {return m ? m[1].trim() : '';};-const stripHtml = (html) => html- .replace(/<[^>]+>/g, ' ')- .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')- .replace(/"/g, '"').replace(/�?39;/g, "'")+const stripHtml = (html) => decodeXmlEntities(html.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim();diff --git a/server/lib/xmlEntities.js b/server/lib/xmlEntities.jsnew file mode 100644index 0000000000..dba9fab6b5--- /dev/null+++ b/server/lib/xmlEntities.js@@ -0,0 +1,61 @@+/**+ * Shared XML / HTML entity decoder.+ *+ * A single dependency-free decoder for the entity references that appear in the+ * various feeds and exports PortOS parses (Apple Health `export.xml`, GitHub+ * release Atom feeds, Pinterest/RSS/Atom feeds, Gmail HTML bodies). It replaces+ * what used to be four near-identical private copies (issue #1876).+ *+ * Handles, in a single left-to-right pass:+ * - the five predefined named entities (`&` `<` `>` `"` `'`)+ * - decimal numeric refs (`&#NN;`)+ * - hex numeric refs (`&#xNN;` / `&#XNN;`)+ * - any extra named entities supplied by the caller (e.g. ` `, `‌`)+ *+ * Single-pass is intentionally double-decode-safe: because `&` is consumed+ * in the same scan as everything else, a literal `&lt;` in the source+ * decodes to `<` (not `<`) — the scanner does not re-examine the `&` it just+ * emitted. Unknown entities and out-of-range numeric code points are left+ * untouched rather than dropped or thrown on, so one malformed reference can't+ * corrupt or abort the surrounding parse.+ */++const NAMED_ENTITIES = {+ amp: '&',+ lt: '<',+ gt: '>',+ quot: '"',+ apos: "'",+};++const ENTITY_RE = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g;++/**+ * Decode the XML/HTML entities in a string.+ *+ * @param {string} str - Raw text that may contain entity references.+ * @param {Object<string,string>} [extraEntities] - Optional extra named-entity+ * map (without the surrounding `&`/`;`), merged on top of the predefined five.+ * Lets callers decode feed-specific entities such as `{ nbsp: ' ', zwnj: '' }`+ * while sharing the numeric-reference and double-decode handling.+ * @returns {string} Decoded string. Non-strings and entity-free input are+ * returned unchanged.+ */+export function decodeXmlEntities(str, extraEntities) {+ if (typeof str !== 'string' || str.indexOf('&') === -1) return str;+ return str.replace(ENTITY_RE, (match, code) => {+ if (code[0] === '#') {+ const cp = code[1] === 'x' || code[1] === 'X'+ ? parseInt(code.slice(2), 16)+ : parseInt(code.slice(1), 10);+ // Leave out-of-range / non-Unicode code points untouched — String+ // .fromCodePoint throws a RangeError for cp < 0 or > 0x10FFFF. A malformed+ // numeric entity in one record must not fail the whole parse/import.+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;+ }+ if (extraEntities && Object.prototype.hasOwnProperty.call(extraEntities, code)) {+ return extraEntities[code];+ }+ return NAMED_ENTITIES[code] ?? match;+ });+}diff --git a/server/lib/xmlEntities.test.js b/server/lib/xmlEntities.test.jsnew file mode 100644index 0000000000..a652218920--- /dev/null+++ b/server/lib/xmlEntities.test.js@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest';+import { decodeXmlEntities } from './xmlEntities.js';++describe('decodeXmlEntities', () => {+ it('returns the input unchanged when there are no entities', () => {+ expect(decodeXmlEntities('plain text')).toBe('plain text');+ expect(decodeXmlEntities('')).toBe('');+ });++ it('returns non-strings unchanged', () => {+ expect(decodeXmlEntities(undefined)).toBe(undefined);+ expect(decodeXmlEntities(null)).toBe(null);+ expect(decodeXmlEntities(42)).toBe(42);+ });++ it('decodes the five predefined named 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 numeric references', () => {+ expect(decodeXmlEntities(''')).toBe("'");+ expect(decodeXmlEntities(''')).toBe("'"); // leading-zero form+ expect(decodeXmlEntities('café')).toBe('café');+ });++ it('decodes hex numeric references (XML-conformant lowercase x)', () => {+ expect(decodeXmlEntities('café')).toBe('café');+ expect(decodeXmlEntities('😀')).toBe(String.fromCodePoint(0x1f600)); // emoji, multi-byte+ });++ it('leaves unknown named entities untouched', () => {+ expect(decodeXmlEntities('&bogus;')).toBe('&bogus;');+ expect(decodeXmlEntities(' ')).toBe(' '); // not predefined without extras+ });++ it('does not throw and leaves out-of-range numeric references untouched', () => {+ expect(() => decodeXmlEntities('�')).not.toThrow();+ expect(decodeXmlEntities('�')).toBe('�');+ expect(decodeXmlEntities('�')).toBe('�'); // just past U+10FFFF+ expect(decodeXmlEntities('')).toBe(String.fromCodePoint(0x10ffff)); // max valid+ });++ it('is double-decode safe in a single pass (&lt; → <, not <)', () => {+ expect(decodeXmlEntities('&lt;')).toBe('<');+ expect(decodeXmlEntities('a &amp; b')).toBe('a & b');+ });++ it('applies caller-supplied extra named entities, including empty-string targets', () => {+ expect(decodeXmlEntities('one two', { nbsp: ' ' })).toBe('one two');+ expect(decodeXmlEntities('zero‌width', { zwnj: '' })).toBe('zerowidth');+ // extras compose with the predefined set in one pass+ expect(decodeXmlEntities('a & b', { nbsp: ' ' })).toBe('a & b');+ });+});diff --git a/server/services/appleHealthXmlParser.js b/server/services/appleHealthXmlParser.jsindex 7e099557f2..16a4de6d4c 100644--- a/server/services/appleHealthXmlParser.js+++ b/server/services/appleHealthXmlParser.js@@ -18,6 +18,7 @@import { Writable } from 'stream';import { StringDecoder } from 'string_decoder';+import { decodeXmlEntities } from '../lib/xmlEntities.js';const RECORD_TAG = '<Record';@@ -28,37 +29,11 @@ const RECORD_TAG = '<Record';// preserving the "skip the bad record, keep importing" contract sax provided.const MAX_OPEN_TAG = 64 * 1024;-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);- // Leave out-of-range / non-Unicode code points untouched — String- // .fromCodePoint throws a RangeError for cp < 0 or > 0x10FFFF, which,- // running inside the stream's synchronous write, would reject the entire- // import. A malformed entity in one record must not fail the whole upload.- return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;- }- return NAMED_ENTITIES[code] ?? match;- });-}+// Apple Health source/device names occasionally carry `&` and friends. The+// decoder lives in the shared `server/lib/xmlEntities.js` (named + decimal/hex+// numeric, double-decode-safe, out-of-range-tolerant); re-exported here because+// this module's tests and callers reference `decodeXmlEntities` by this path.+export { decodeXmlEntities };const ATTR_RE = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;diff --git a/server/services/claudeChangelog.js b/server/services/claudeChangelog.jsindex 891373c1de..821498bd73 100644--- a/server/services/claudeChangelog.js+++ b/server/services/claudeChangelog.js@@ -9,6 +9,7 @@import { join } from 'path'import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'+import { decodeXmlEntities } from '../lib/xmlEntities.js'const FEED_URL = 'https://github.com/anthropics/claude-code/releases.atom'const STATE_FILE = join(PATHS.data, 'claude-changelog.json')@@ -22,18 +23,9 @@ const defaultState = () => ({entries: []})-// Decode the five XML predefined entities (the only ones a text feed uses-// outside CDATA). `&` is intentionally last so a literal "&lt;" in the-// source decodes to "<" rather than being double-decoded to "<".-function decodeXmlEntities(s) {- return s- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, "'")- .replace(/'/g, "'")- .replace(/&/g, '&')-}+// Entity decoding is the shared `server/lib/xmlEntities.js` single-pass decoder+// (named + numeric). It is double-decode-safe — a literal "&lt;" decodes to+// "<", not "<" — which preserves the guard this feed used to chain manually.// Pull the first <tag>…</tag> text from an <entry> block. CDATA-wrapped// content (GitHub wraps release notes in <![CDATA[…]]>) is returned verbatim;diff --git a/server/services/feeds.js b/server/services/feeds.jsindex 8d18025a54..1e0dad5343 100644--- a/server/services/feeds.js+++ b/server/services/feeds.js@@ -14,6 +14,7 @@ import dns from 'dns/promises';import net from 'net';import { PATHS, createCachedStore } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { decodeXmlEntities } from '../lib/xmlEntities.js';const FEEDS_FILE = join(PATHS.data, 'feeds.json');const MAX_ITEMS_PER_FEED = 100;@@ -80,7 +81,7 @@ const extractAtomLink = (xml) => {/*** Strip HTML tags from a string for plain text display.*/-const stripHtml = (html) => html.replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").trim();+const stripHtml = (html) => decodeXmlEntities(html.replace(/<[^>]+>/g, '')).trim();/*** Parse RSS 2.0 feed XML into normalized items.diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 45da46eb03..4881bc736c 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -7,6 +7,7 @@ import { gmail } from '@googleapis/gmail';import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';import { getAuthenticatedClient } from './googleAuth.js';+import { decodeXmlEntities } from '../lib/xmlEntities.js';function makeExternalId(gmailId) {return 'api-gmail-' + crypto.createHash('md5').update(gmailId).digest('hex').slice(0, 12);@@ -27,7 +28,7 @@ function decodeBase64Url(str) {* Convert HTML to readable plain text by stripping style/script/head blocks, then tags.*/function htmlToText(html) {- return html+ const stripped = html.replace(/<head\b[^>]*>[\s\S]*?<\/head>/gi, '').replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '').replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')@@ -36,14 +37,10 @@ function htmlToText(html) {.replace(/<\/div>/gi, '\n').replace(/<\/tr>/gi, '\n').replace(/<\/li>/gi, '\n')- .replace(/<[^>]*>/g, '')- .replace(/ /g, ' ')- .replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, "'")- .replace(/‌/g, '')+ .replace(/<[^>]*>/g, '');+ // Shared decoder handles the named + numeric entities; ` `/`‌` are+ // mail-specific so they're passed as extra entities (space / zero-width strip).+ return decodeXmlEntities(stripped, { nbsp: ' ', zwnj: '' }).replace(/\n{3,}/g, '\n\n').replace(/[ \t]+/g, ' ').trim();