Skip to content

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

test([tolerant-fetch-json-additional-clients]): pin calendar/message non-JSON masquerade guards

[._.]/ Adam Eivy4634b67be7eb
diff --git a/PLAN.md b/PLAN.md
index 1daef062af..5527f54ff9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -5,7 +5,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
## Next Up
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
-- [ ] [conflict-journal-media-collections] **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ. Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.
+
+- [ ] [insights-callprovider-nonjson-test] **Add a regression test for `insightsService.callProviderAISimple`'s non-JSON-body guard.** The `[tolerant-fetch-json-additional-clients]` PR fixed a masquerade-as-empty-success bug where a non-JSON/blank 200 body returned `{ text: '' }`, and `refreshCrossDomainNarrative`/`generateInsightThemes` then overwrote `narrative.json`/`themes.json` with nothing. The fix (`{ fallback: null, emptyValue: null }` + null guard → `{ error }`) got dedicated tests for the sibling calendar/message paths (`calendarApiSync.test.js`, `messageApiSync.test.js`) but NOT for insights, because `callProviderAISimple` is unexported and the only public entry (`refreshCrossDomainNarrative`) needs genome+taste+health context mocked to reach the LLM call. Either export `callProviderAISimple` for a focused unit test, or stand up the context mock and assert: a 200-with-HTML body returns `{ error }` (no `narrative.json` write), while a valid `{ choices:[{message:{content:''}}] }` still returns `{ text: '' }`. Deferred from the review loop on PR #616 (claude flagged the coverage gap, rated non-blocking). **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ. Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.
- [ ] [conflict-journal-issues] **Issue-level conflict journaling.** The share-bucket importer hook (`server/services/sharing/importer.js` `applyAutoMerge`→`mergeOne`) is gated to `universe`/`series`; child issues ride LWW silently. Extend the journal to issues (needs the issue merge path to thread a `source` + call `maybeJournalBeforeOverwrite`).
- [ ] [conflict-journal-deep-diff] **`diffSummary` is top-level shallow only.** `conflictJournal.diffSummary` compares top-level fields via canonicalStringify, so the UI shows "categories differ" rather than which variation/canon entry changed. Add per-field deep diffing for richer InlineDiff rendering in the Conflicts tab.
- [ ] [series-merge-season-rehoming] **Series merge re-homes issues un-grouped.** `recordMerge.mergeSeries` re-points the loser series' issues to the survivor via `issues.reassignIssuesToSeries`, which sets `seasonId: null` (seasons are series-scoped). The moved issues land un-grouped and the user must re-assign them to a survivor season. A smarter merge could map loser seasons → survivor seasons by number and preserve issue→season grouping.
diff --git a/server/services/calendarApiSync.test.js b/server/services/calendarApiSync.test.js
new file mode 100644
index 0000000000..bacbd599dd
--- /dev/null
+++ b/server/services/calendarApiSync.test.js
@@ -0,0 +1,57 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the token source and the HTTP client so the sync runs offline.
+vi.mock('./messageTokenExtractor.js', () => ({
+ getToken: vi.fn(),
+ clearTokenCache: vi.fn(),
+}));
+vi.mock('../lib/fetchWithTimeout.js', () => ({
+ fetchWithTimeout: vi.fn(),
+}));
+
+import { getToken } from './messageTokenExtractor.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { syncOutlookCalendarApi } from './calendarApiSync.js';
+
+const ACCOUNT = { id: 'acc-1', email: '[email protected]' };
+const okResponse = (body) => ({ ok: true, status: 200, text: async () => body });
+
+describe('syncOutlookCalendarApi — malformed-body masquerade guard', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getToken.mockResolvedValue({ token: 'fake-token' });
+ });
+
+ // The regression this guards: a non-JSON 200 body used to become
+ // { events: [], status: 'success' }, and calendarSync.js prunes every cached
+ // event absent from a "success" fetch — so a transient HTML error page would
+ // wipe the calendar cache. It must surface as api-error (no prune) instead.
+ it('returns api-error (not empty success) on a non-JSON 200 body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse('<html><body>502 Bad Gateway</body></html>'));
+ const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);
+ expect(result).toEqual({ events: [], status: 'api-error' });
+ });
+
+ it('returns api-error on a blank 200 body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(''));
+ const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);
+ expect(result.status).toBe('api-error');
+ });
+
+ // A legitimately-empty calendar still reports success (so the reconcile can
+ // prune correctly) — the guard must not conflate valid-empty with malformed.
+ it('still reports success for a valid empty { value: [] } body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [] })));
+ const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);
+ expect(result.status).toBe('success');
+ expect(result.events).toEqual([]);
+ });
+
+ it('parses events from a valid populated body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [{ Id: 'evt-1', Subject: 'Standup' }] })));
+ const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);
+ expect(result.status).toBe('success');
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0].title).toBe('Standup');
+ });
+});
diff --git a/server/services/messageApiSync.test.js b/server/services/messageApiSync.test.js
new file mode 100644
index 0000000000..3d9bdc06ba
--- /dev/null
+++ b/server/services/messageApiSync.test.js
@@ -0,0 +1,56 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the token source and the HTTP client so the sync runs offline.
+vi.mock('./messageTokenExtractor.js', () => ({
+ getToken: vi.fn(),
+ clearTokenCache: vi.fn(),
+}));
+vi.mock('../lib/fetchWithTimeout.js', () => ({
+ fetchWithTimeout: vi.fn(),
+}));
+
+import { getToken } from './messageTokenExtractor.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { syncOutlookApi } from './messageApiSync.js';
+
+const ACCOUNT = { id: 'acc-1', email: '[email protected]' };
+const okResponse = (body) => ({ ok: true, status: 200, text: async () => body });
+
+describe('syncOutlookApi — malformed-body masquerade guard', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getToken.mockResolvedValue({ token: 'fake-token' });
+ });
+
+ // The regression this guards: a non-JSON 200 body used to become
+ // { messages: [], status: 'success' }, a truthy result that suppressed the
+ // Playwright fallback in messageSync.js (and mid-pagination would prune still
+ // -valid cached messages). It must return null to preserve the fallback.
+ it('returns null (triggering the Playwright fallback) on a non-JSON 200 body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse('<html><body>502 Bad Gateway</body></html>'));
+ const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });
+ expect(result).toBeNull();
+ });
+
+ it('returns null on a blank 200 body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(''));
+ const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });
+ expect(result).toBeNull();
+ });
+
+ // A legitimately-empty inbox still reports success (no spurious fallback).
+ it('still reports success for a valid empty { value: [] } body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [] })));
+ const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });
+ expect(result.status).toBe('success');
+ expect(result.messages).toEqual([]);
+ });
+
+ it('parses messages from a valid populated body', async () => {
+ fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [{ Id: 'msg-1', Subject: 'Hello' }] })));
+ const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'unread' });
+ expect(result.status).toBe('success');
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].subject).toBe('Hello');
+ });
+});