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: honor intentional empty-string clears in memory/message/task merges (#1826)
[._.]/ Adam Eivydb5862230204
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 643a823fd1..d36dfd68e0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; the freshness check is now throttled to at most once per second (the hot path between checks is a clock comparison, no syscall), so a rebuild re-syncs the served HTML with the on-disk chunks within the throttle window instead of paying a stat per navigation. The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)- **External API model/metadata fetches now time out instead of stalling callers indefinitely** — `_fetchGeminiModels` (Gemini model refresh in `aiToolkit/providers.js`) made a `fetch` with no `AbortSignal`, unlike every other provider model-fetch in that file, so a hung Google endpoint could block a model-refresh request forever; it now uses the same `AbortSignal.timeout(8000)`. `fetchCivitaiModel` and `searchCivitaiLoras` (`server/lib/civitai.js`) likewise passed no signal, so a Civitai hang stalled LoRA metadata/search callers; both now default to `AbortSignal.timeout(10000)` and accept a caller-provided `signal` override. (#1827)+- **Absent-vs-cleared merge bugs that silently restored values the user just cleared** — three spots conflated "field absent" with "field intentionally cleared to empty". Clearing a memory's content to `""` now reindexes BM25 (so the old text no longer stays searchable) and regenerates the summary, instead of a falsy gate skipping both (`memory.js`). A genuinely empty-body email refresh now overwrites the cached body instead of `||` collapsing back to the stale text (`messageSync.js`, both the thread-match and original-message paths). And clearing a CoS task's legacy direct field (`context`/`model`/`provider`/`app`) to `""` now persists as `""` rather than `|| undefined` deleting the key — `null` still drops it (`cosTaskStore.js`). (#1826)- **Unguarded async `child_process` handlers can no longer crash the Node process** — several `close`/`error` event handlers were `async` and `await`ed disk writes / completion bookkeeping with no `try/catch`, so a single failed write (e.g. a full disk) or a throwing completion hook surfaced as an unhandled rejection and took down the whole server. Wrapped the at-risk handler bodies in `server/services/runner.js` (both `close` and `error`), `videoTimeline/local.js`, `agentCliSpawning.js` (both `close` and `error`), and both the CLI `close` handler and the detached `processStream().catch` in `aiToolkit/runner.js`. The recovery paths now still settle callers waiting on `onComplete` with failure metadata (so a finalization failure surfaces as a failed run instead of hanging forever), with the completion hook isolated from `onComplete` so a throwing `onRunFailed` can't block the caller from settling. Also replaced the two silent recovery-critical `.catch(() => {})` swallows in `cos-runner/index.js` with logged failures so a lost completion-metadata write is visible instead of silently dropping a finished task. (#1825)- Catalog "Appears in" panel no longer renders dangling chips that deep-link to soft-deleted universe/series/creative-director targets — the detail page filters refs to live targets only (the orphan stays recoverable via the "Orphaned" album). Also fixed a stale resolver bug where soft-deleted Creative Director projects (#1564) wrongly resolved as live, and extended orphan-bucket detection so a deleted CD project's ex-cast surfaces as orphaned rather than unlinked. (#1812)diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex affec06656..372e2ca8e3 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -324,9 +324,13 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat...tasks[taskIndex].metadata,...(updates.metadata || {})};- // Handle legacy fields that may be passed directly in updates+ // Handle legacy fields that may be passed directly in updates. Use ?? not ||+ // so an intentional clear to "" is preserved as "" rather than dropped: || maps+ // every falsy value (incl. "") to undefined, which the cleanup pass below then+ // deletes, conflating "cleared" with "absent" (absent-vs-cleared, CLAUDE.md).+ // Only null becomes undefined (→ deleted); absent fields never enter this loop.for (const f of LEGACY_DIRECT_FIELDS) {- if (updates[f] !== undefined) updatedMetadata[f] = updates[f] || undefined;+ if (updates[f] !== undefined) updatedMetadata[f] = updates[f] ?? undefined;}// Clear blocked/failure metadata when transitioning out of blocked statusdiff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex e34d1aebba..e9f0fd453f 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -311,6 +311,24 @@ describe('cosTaskStore.updateTask', () => {expect(updated.metadata.updatedAt).toBe(new Date(T1).toISOString());});+ it('preserves a legacy direct field cleared to empty string (absent-vs-cleared, #1826)', async () => {+ // `context` is a LEGACY_DIRECT_FIELD. Clearing it to "" is an intentional edit+ // and must persist as "" — the `|| undefined` form mapped "" to undefined and+ // the cleanup pass then deleted the key, conflating "cleared" with "absent".+ await addTask({ description: 'ctx', id: 'task-ctx', context: 'original context' }, 'user');+ const updated = await updateTask('task-ctx', { context: '' }, 'user');+ expect(updated.metadata.context).toBe('');+ // And it survives a round-trip through markdown serialization.+ const reloaded = await getTaskById('task-ctx');+ expect(reloaded.metadata.context).toBe('');+ });++ it('still drops a legacy direct field set to null', async () => {+ await addTask({ description: 'ctx2', id: 'task-ctx2', context: 'original' }, 'user');+ const updated = await updateTask('task-ctx2', { context: null }, 'user');+ expect(updated.metadata.context).toBeUndefined();+ });+it('returns an error object when the file is missing', async () => {const result = await updateTask('task-x', { status: 'completed' }, 'user');expect(result.error).toBe('Task file not found');diff --git a/server/services/memory.js b/server/services/memory.jsindex bb3264a6b5..a158505a49 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -174,8 +174,12 @@ export async function updateMemory(id, updates) {}}- // Update summary if content changed- if (updates.content && !updates.summary) {+ // Update summary if content changed. Gate on "is a string", not truthiness:+ // clearing content to "" is an intentional edit that must regenerate (clear)+ // the summary, not leave the stale one behind (absent-vs-cleared, CLAUDE.md).+ // The typeof check keeps null/undefined/absent out of generateSummary (which+ // would throw on .length) while still treating "" as a present-but-empty clear.+ if (typeof updates.content === 'string' && !updates.summary) {memory.summary = generateSummary(updates.content);}@@ -190,8 +194,11 @@ export async function updateMemory(id, updates) {await saveIndex(index);}- // Update BM25 index if content changed- if (updates.content || updates.tags) {+ // Update BM25 index if content or tags changed. Gate on shape, not truthiness:+ // clearing content to "" (a string) must reindex so the now-empty document+ // stops matching its old terms, and clearing tags to [] (Array.isArray) must+ // reindex too (absent-vs-cleared, CLAUDE.md). null/undefined/absent are skipped.+ if (typeof updates.content === 'string' || Array.isArray(updates.tags)) {memoryBM25.indexMemory({id: memory.id,content: memory.content,diff --git a/server/services/memory.test.js b/server/services/memory.test.jsindex d1fcd203ac..84839ea5e0 100644--- a/server/services/memory.test.js+++ b/server/services/memory.test.js@@ -518,6 +518,38 @@ describe('memory service', () => {expect(result.summary).toBe('explicit summary');});+ it('should regenerate summary when content is cleared to empty string', async () => {+ // Absent-vs-cleared: clearing content to "" is an intentional edit and must+ // refresh the (now-empty) summary, not leave the stale one behind (#1826).+ const mockMemory = { id: 'mem-1', type: 'fact', content: 'old', summary: 'old summary', category: 'other', tags: [], importance: 0.5, relatedMemories: [], status: 'active', sourceAppId: null };+ readJSONFile.mockImplementation((path, def) => {+ if (path.includes('memory.json')) return Promise.resolve({ ...mockMemory });+ if (path.includes('index.json')) return Promise.resolve({ version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', type: 'fact', category: 'other', tags: [], summary: 'old summary', importance: 0.5, createdAt: '', status: 'active', sourceAppId: null }] });+ return Promise.resolve(def);+ });++ const result = await updateMemory('mem-1', { content: '' });++ expect(generateSummary).toHaveBeenCalledWith('');+ expect(result.summary).toBe('');+ });++ it('should not regenerate summary (or throw) when content is absent', async () => {+ // The string-typed gate must keep a content-less update out of generateSummary,+ // which would throw on `undefined.length` (#1826).+ const mockMemory = { id: 'mem-1', type: 'fact', content: 'old', summary: 'old summary', category: 'other', tags: [], importance: 0.5, relatedMemories: [], status: 'active', sourceAppId: null };+ readJSONFile.mockImplementation((path, def) => {+ if (path.includes('memory.json')) return Promise.resolve({ ...mockMemory });+ if (path.includes('index.json')) return Promise.resolve({ version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', type: 'fact', category: 'other', tags: [], summary: 'old summary', importance: 0.5, createdAt: '', status: 'active', sourceAppId: null }] });+ return Promise.resolve(def);+ });++ const result = await updateMemory('mem-1', { status: 'archived' });++ expect(generateSummary).not.toHaveBeenCalled();+ expect(result.summary).toBe('old summary');+ });+it('should return null for non-existent memory', async () => {readJSONFile.mockImplementation((path, def) => Promise.resolve(def));@@ -552,6 +584,37 @@ describe('memory service', () => {expect(memoryBM25.indexMemory).toHaveBeenCalled();});+ it('should reindex BM25 when content is cleared to empty string', async () => {+ // Absent-vs-cleared: clearing content to "" must reindex so the now-empty+ // document stops matching its old terms — the falsy-gated version skipped+ // the reindex and left the old text searchable (#1826).+ const mockMemory = { id: 'mem-1', type: 'fact', content: 'searchable old text', summary: 'old', category: 'other', tags: [], importance: 0.5, relatedMemories: [], status: 'active', sourceAppId: null };+ readJSONFile.mockImplementation((path, def) => {+ if (path.includes('memory.json')) return Promise.resolve({ ...mockMemory });+ if (path.includes('index.json')) return Promise.resolve({ version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', type: 'fact', category: 'other', tags: [], summary: 'old', importance: 0.5, createdAt: '', status: 'active', sourceAppId: null }] });+ return Promise.resolve(def);+ });++ await updateMemory('mem-1', { content: '' });++ expect(memoryBM25.indexMemory).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'mem-1', content: '' })+ );+ });++ it('should not reindex BM25 when neither content nor tags are in the update', async () => {+ const mockMemory = { id: 'mem-1', type: 'fact', content: 'test', summary: 'test', category: 'other', tags: [], importance: 0.5, relatedMemories: [], status: 'active', sourceAppId: null };+ readJSONFile.mockImplementation((path, def) => {+ if (path.includes('memory.json')) return Promise.resolve({ ...mockMemory });+ if (path.includes('index.json')) return Promise.resolve({ version: 1, lastUpdated: '', count: 1, memories: [{ id: 'mem-1', type: 'fact', category: 'other', tags: [], summary: 'test', importance: 0.5, createdAt: '', status: 'active', sourceAppId: null }] });+ return Promise.resolve(def);+ });++ await updateMemory('mem-1', { category: 'engineering' });++ expect(memoryBM25.indexMemory).not.toHaveBeenCalled();+ });+it('should emit memory:updated event', async () => {const emitSpy = vi.spyOn(cosEvents, 'emit');const mockMemory = { id: 'mem-1', type: 'fact', content: 'test', summary: 'test', category: 'other', tags: [], importance: 0.5, relatedMemories: [], status: 'active', sourceAppId: null };diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex a4df2f72be..66e6cdf121 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -242,7 +242,11 @@ export async function refreshMessage(accountId, messageId) {const extId = makeExternalId(threadMsg.date || message.date || '', threadMsg.from || message.from?.name || '', message.subject || '');const existing = existingMap.get(extId);if (existing) {- existing.bodyText = threadMsg.body || existing.bodyText;+ // Use ?? not ||: a genuinely empty-body message (body === '') is a valid+ // full extraction and must overwrite the old text, not collapse back to it+ // (absent-vs-cleared, CLAUDE.md). Only an absent body (null/undefined) keeps+ // the prior text.+ existing.bodyText = threadMsg.body ?? existing.bodyText;existing.bodyFull = true;if (!existing.threadId) existing.threadId = threadKey;if (threadMsg.to?.length) existing.to = threadMsg.to;@@ -277,7 +281,9 @@ export async function refreshMessage(accountId, messageId) {// Update the original message too if it wasn't matched by externalIdif (!updatedMessages.find(m => m.id === message.id)) {- message.bodyText = detail[0]?.body || message.bodyText;+ // ?? not ||: an empty extracted body ('') is a valid clear, not a fall-back+ // to the stale text (absent-vs-cleared, CLAUDE.md).+ message.bodyText = detail[0]?.body ?? message.bodyText;message.bodyFull = true;if (!message.threadId) message.threadId = threadKey;updatedMessages.push(message);diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.jsindex f95b49e13d..3791f72265 100644--- a/server/services/messageSync.test.js+++ b/server/services/messageSync.test.js@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+import { createHash } from 'crypto';// Mock fs/promises before importing the modulevi.mock('fs/promises', () => ({@@ -41,15 +42,16 @@ vi.mock('./messageGmailSync.js', () => ({}));vi.mock('./messagePlaywrightSync.js', () => ({- syncPlaywright: vi.fn()+ syncPlaywright: vi.fn(),+ refreshMessageDetail: vi.fn()}));import { readdir, unlink } from 'fs/promises';import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus } from './messageSync.js';+import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage } from './messageSync.js';import { getAccount, updateSyncStatus } from './messageAccounts.js';import { syncGmail } from './messageGmailSync.js';-import { syncPlaywright } from './messagePlaywrightSync.js';+import { syncPlaywright, refreshMessageDetail } from './messagePlaywrightSync.js';const VALID_UUID = '11111111-1111-1111-1111-111111111111';const VALID_UUID_2 = '22222222-2222-2222-2222-222222222222';@@ -508,3 +510,59 @@ describe('getSyncStatus', () => {expect(await getSyncStatus(VALID_UUID)).toBeNull();});});++// ─── refreshMessage (absent-vs-cleared body merge, #1826) ───++describe('refreshMessage', () => {+ // Mirror makeExternalId() in messageSync.js so a crafted detail entry matches+ // an existing cached message by externalId (exercising the in-place merge path).+ const makeExternalId = (date, sender, subject) =>+ 'pw-' + createHash('md5').update(`${date}|${sender}|${subject}`).digest('hex').slice(0, 12);++ it('overwrites cached body with an empty extracted body (clear), not the stale text', async () => {+ const extId = makeExternalId('2026-01-01', 'Alice', 'Hi');+ readFile.mockResolvedValue(JSON.stringify({+ syncCursor: null,+ messages: [{ id: 'msg-1', externalId: extId, bodyText: 'stale body', from: { name: 'Alice' }, subject: 'Hi', date: '2026-01-01' }]+ }));+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });+ refreshMessageDetail.mockResolvedValue([{ from: 'Alice', date: '2026-01-01', body: '' }]);++ const result = await refreshMessage(VALID_UUID, 'msg-1');++ const merged = result.find(m => m.externalId === extId);+ expect(merged.bodyText).toBe('');+ expect(merged.bodyFull).toBe(true);+ });++ it('keeps the cached body when the extracted body is absent (null/undefined)', async () => {+ const extId = makeExternalId('2026-01-01', 'Alice', 'Hi');+ readFile.mockResolvedValue(JSON.stringify({+ syncCursor: null,+ messages: [{ id: 'msg-1', externalId: extId, bodyText: 'keep me', from: { name: 'Alice' }, subject: 'Hi', date: '2026-01-01' }]+ }));+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });+ refreshMessageDetail.mockResolvedValue([{ from: 'Alice', date: '2026-01-01' }]); // no body key++ const result = await refreshMessage(VALID_UUID, 'msg-1');++ const merged = result.find(m => m.externalId === extId);+ expect(merged.bodyText).toBe('keep me');+ });++ it('clears the original message body when the extracted body is empty (fallback path)', async () => {+ // No externalId on the cached message → it is not matched in the loop and+ // falls through to the original-message update (line ~284).+ readFile.mockResolvedValue(JSON.stringify({+ syncCursor: null,+ messages: [{ id: 'msg-1', bodyText: 'stale original', from: { name: 'Bob' }, subject: 'Re: x', date: '2026-02-01' }]+ }));+ getAccount.mockResolvedValue({ id: VALID_UUID, type: 'outlook' });+ refreshMessageDetail.mockResolvedValue([{ from: 'Carol', date: '2026-03-01', body: '' }]);++ const result = await refreshMessage(VALID_UUID, 'msg-1');++ const original = result.find(m => m.id === 'msg-1');+ expect(original.bodyText).toBe('');+ });+});