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([issue-1167]): drop ws direct dep (native WebSocket) + sax from the changelog path
[._.]/ Adam Eivy7ab536cc260f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6f77e5beee..22c59964f7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,8 @@## Changed+- **[issue-1167] Trimmed two dependencies' footprint** — the Moltworld real-time connection now uses the runtime's built-in WebSocket instead of a third-party library, and the Claude Code changelog feed parses with a small built-in extractor. No behavior change.+- **[issue-1154] Library hygiene for the genome + writers-room internals** — the curated SNP marker dataset now loads from a data file instead of a hardcoded array, and the writers-room storage factory moved out of the shared sanitizer library. No behavior change.- **[issue-1153] Internal cleanup of the local video-generation service** — the progress-parsing and finalize steps of the video generator moved into a separately-tested helper module. No behavior change.diff --git a/server/package.json b/server/package.jsonindex de39edec95..9e07669dc9 100644--- a/server/package.json+++ b/server/package.json@@ -25,7 +25,6 @@"sharp": "0.34.5","socket.io": "4.8.3","socket.io-client": "4.8.3",- "ws": "8.21.0","zod": "^4.4.3"},"devDependencies": {diff --git a/server/services/claudeChangelog.js b/server/services/claudeChangelog.jsindex 72c7a71042..0c834b7990 100644--- a/server/services/claudeChangelog.js+++ b/server/services/claudeChangelog.js@@ -7,7 +7,6 @@*/import { join } from 'path'-import sax from 'sax'import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'@@ -23,62 +22,53 @@ 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, '&')+}++// Pull the first <tag>…</tag> text from an <entry> block. CDATA-wrapped+// content (GitHub wraps release notes in <![CDATA[…]]>) is returned verbatim;+// plain text is entity-decoded. Returns '' when the tag is absent.+function extractTag(entryXml, tag) {+ const m = entryXml.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'i'))+ if (!m) return ''+ const inner = m[1]+ const cdata = inner.match(/<!\[CDATA\[([\s\S]*?)\]\]>/)+ if (cdata) return cdata[1]+ return decodeXmlEntities(inner.trim())+}++/**+ * 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).+ */function parseAtomFeed(xml) {- return new Promise((resolve, reject) => {- const parser = sax.parser(true, { trim: true })- const entries = []- let current = null- let tag = null- let inFeed = false- let settled = false-- parser.onopentag = (node) => {- tag = node.name- if (tag === 'feed') inFeed = true- if (tag === 'entry' && inFeed) {- current = { title: '', link: '', updated: '', content: '' }- }- if (current && tag === 'link' && node.attributes.href) {- current.link = node.attributes.href- }- }-- parser.ontext = (text) => {- if (!current || !tag) return- if (tag === 'title') current.title += text- if (tag === 'updated') current.updated += text- if (tag === 'content') current.content += text- }-- parser.oncdata = (cdata) => {- if (!current || !tag) return- if (tag === 'content') current.content += cdata- }-- parser.onclosetag = (name) => {- if (name === 'entry' && current) {- entries.push(current)- current = null- }- tag = null- }-- parser.onerror = (err) => {- if (!settled) {- settled = true- reject(err)- }- }-- parser.onend = () => {- if (!settled) {- settled = true- resolve(entries)- }- }-- parser.write(xml).close()- })+ const entries = []+ const entryRe = /<entry[^>]*>([\s\S]*?)<\/entry>/gi+ let match+ while ((match = entryRe.exec(xml)) !== null) {+ const block = match[1]+ // <link href="…"/> — Atom links carry the URL in the href attribute.+ const linkMatch = block.match(/<link\b[^>]*\bhref="([^"]*)"/i)+ entries.push({+ title: extractTag(block, 'title'),+ link: linkMatch ? decodeXmlEntities(linkMatch[1]) : '',+ updated: extractTag(block, 'updated'),+ content: extractTag(block, 'content'),+ })+ }+ return entries}function extractVersion(title) {@@ -120,7 +110,7 @@ export async function checkChangelog() {}const xml = await response.text()- const allEntries = await parseAtomFeed(xml)+ const allEntries = parseAtomFeed(xml)const entries = allEntries.slice(0, MAX_ENTRIES).map(e => ({version: extractVersion(e.title),@@ -155,3 +145,7 @@ export async function checkChangelog() {export async function getCachedChangelog() {return readJSONFile(STATE_FILE, defaultState())}++// Exposed for unit tests — the Atom parse is the regex-extractor that replaced+// sax on this path (issue #1167).+export const __testing = { parseAtomFeed, stripHtml, extractVersion }diff --git a/server/services/claudeChangelog.test.js b/server/services/claudeChangelog.test.jsnew file mode 100644index 0000000000..fe18e6ac25--- /dev/null+++ b/server/services/claudeChangelog.test.js@@ -0,0 +1,62 @@+import { describe, it, expect } from 'vitest';+import { __testing } from './claudeChangelog.js';++const { parseAtomFeed, stripHtml, extractVersion } = __testing;++// Issue #1167 replaced the sax streaming parser on this path with a focused+// regex extractor. These pin the GitHub releases.atom shapes it must handle.+const SAMPLE = `<?xml version="1.0" encoding="UTF-8"?>+<feed xmlns="http://www.w3.org/2005/Atom">+ <id>tag:github.com,2008:https://github.com/anthropics/claude-code/releases</id>+ <title>Release notes from claude-code</title>+ <entry>+ <id>tag:github.com,2008:Repository/1/v1.2.3</id>+ <updated>2026-06-10T12:00:00Z</updated>+ <link rel="alternate" type="text/html" href="https://github.com/anthropics/claude-code/releases/tag/v1.2.3"/>+ <title>v1.2.3</title>+ <content type="html"><p>Fixed a bug &amp; added a feature</p></content>+ </entry>+ <entry>+ <id>tag:github.com,2008:Repository/1/v1.2.2</id>+ <updated>2026-06-09T08:30:00Z</updated>+ <link rel="alternate" type="text/html" href="https://github.com/anthropics/claude-code/releases/tag/v1.2.2"/>+ <title>v1.2.2</title>+ <content type="html"><![CDATA[<h2>What's Changed</h2><p>CDATA content with <b>html</b></p>]]></content>+ </entry>+</feed>`;++describe('claudeChangelog parseAtomFeed (regex extractor, issue #1167)', () => {+ it('extracts every entry with title, href link, updated, and content', () => {+ const entries = parseAtomFeed(SAMPLE);+ expect(entries).toHaveLength(2);+ expect(entries[0]).toEqual({+ title: 'v1.2.3',+ link: 'https://github.com/anthropics/claude-code/releases/tag/v1.2.3',+ updated: '2026-06-10T12:00:00Z',+ // entity-escaped HTML content is decoded (literal &amp; → &)+ content: '<p>Fixed a bug & added a feature</p>',+ });+ });++ it('returns CDATA-wrapped content verbatim (no entity decoding inside CDATA)', () => {+ const entries = parseAtomFeed(SAMPLE);+ expect(entries[1].content).toBe("<h2>What's Changed</h2><p>CDATA content with <b>html</b></p>");+ expect(entries[1].title).toBe('v1.2.2');+ });++ it('returns [] for a feed with no entries', () => {+ expect(parseAtomFeed('<feed></feed>')).toEqual([]);+ expect(parseAtomFeed('')).toEqual([]);+ });++ it('tolerates a missing link / content (empty strings, no throw)', () => {+ const xml = '<feed><entry><title>v9.9.9</title><updated>2026-01-01T00:00:00Z</updated></entry></feed>';+ expect(parseAtomFeed(xml)[0]).toEqual({ title: 'v9.9.9', link: '', updated: '2026-01-01T00:00:00Z', content: '' });+ });++ it('downstream stripHtml + extractVersion still behave on the parsed fields', () => {+ const [first] = parseAtomFeed(SAMPLE);+ expect(extractVersion(first.title)).toBe('1.2.3');+ expect(stripHtml(first.content)).toBe('Fixed a bug & added a feature');+ });+});diff --git a/server/services/moltworldWs.js b/server/services/moltworldWs.jsindex 93af21a813..6c98e00e8f 100644--- a/server/services/moltworldWs.js+++ b/server/services/moltworldWs.js@@ -15,7 +15,12 @@* hello_ack - server acknowledged our hello*/-import WebSocket from 'ws';+// Uses Node's built-in WHATWG `WebSocket` (global since Node 22, stable in+// Node 24) — no `ws` dependency. The browser-style API differs from `ws`:+// events arrive via addEventListener with an event object (message text is+// `evt.data`), there's no `.terminate()` (native `.close()` is safe in the+// CONNECTING state, unlike `ws`), and there's no `.removeAllListeners()` —+// we track our handlers per-socket and removeEventListener them in cleanup.import EventEmitter from 'events';import * as platformAccounts from './platformAccounts.js';import * as agentActivity from './agentActivity.js';@@ -24,6 +29,9 @@ export const moltworldWsEvents = new EventEmitter();// Connection statelet ws = null;+// The event listeners attached to the current `ws` — native WebSocket has no+// `.removeAllListeners()`, so cleanupWs() removes exactly what we added.+let wsListeners = null;let reconnectTimer = null;let reconnectAttempts = 0;let connectedAt = null;@@ -130,11 +138,19 @@ function handleMessage(raw) {function cleanupWs() {if (ws) {- ws.removeAllListeners();- if (ws.readyState === WebSocket.OPEN) {+ // Native WebSocket has no removeAllListeners() — detach exactly the+ // handlers we registered in doConnect so a torn-down socket can't fire+ // 'close'/'error' into the reconnect logic after we've abandoned it.+ if (wsListeners) {+ for (const [type, handler] of Object.entries(wsListeners)) {+ ws.removeEventListener(type, handler);+ }+ wsListeners = null;+ }+ // close() is valid (and a no-op) in OPEN and CONNECTING alike for the+ // native WebSocket — no terminate()/throw split like `ws` needed.+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {ws.close();- } else if (ws.readyState === WebSocket.CONNECTING) {- ws.terminate(); // terminate() is safe for CONNECTING state; close() throws}ws = null;}@@ -163,7 +179,7 @@ function doConnect() {const instance = new WebSocket('wss://moltworld.io/ws');ws = instance;- instance.on('open', () => {+ const onOpen = () => {clearTimeout(timeout);connectedAt = Date.now();reconnectAttempts = 0;@@ -178,31 +194,44 @@ function doConnect() {});resolve();- });+ };- instance.on('message', (raw) => handleMessage(String(raw)));+ // Native WebSocket delivers the frame payload on `evt.data` (a string for+ // text frames); `ws` passed the raw buffer as the first arg.+ const onMessage = (evt) => handleMessage(String(evt.data));- instance.on('close', (code) => {+ const onClose = (evt) => {clearTimeout(timeout);- console.log(`🌐 Moltworld WS: closed (code=${code})`);+ console.log(`🌐 Moltworld WS: closed (code=${evt.code})`);ws = null;+ wsListeners = null;if (currentStatus !== 'disconnected') {scheduleReconnect();}- });+ };- instance.on('error', (err) => {+ // Native WebSocket fires a generic Event on error (no `.message`); the+ // useful detail arrives in the subsequent close event. Synthesize a stable+ // message so logs/rejections stay informative.+ const onError = (evt) => {clearTimeout(timeout);- console.error(`🌐 Moltworld WS: error: ${err.message}`);+ const detail = evt?.message || evt?.error?.message || 'connection error';+ console.error(`🌐 Moltworld WS: error: ${detail}`);cleanupWs();if (isReconnecting) {// Continue backoff loop on reconnect failuresscheduleReconnect();} else {setStatus('disconnected');- reject(new Error(`WebSocket connection failed: ${err.message}`));+ reject(new Error(`WebSocket connection failed: ${detail}`));}- });+ };++ wsListeners = { open: onOpen, message: onMessage, close: onClose, error: onError };+ instance.addEventListener('open', onOpen);+ instance.addEventListener('message', onMessage);+ instance.addEventListener('close', onClose);+ instance.addEventListener('error', onError);});}