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

refactor([shared-tolerant-fetch-json-helper]): hoist parse sentinel, fix barrel order, defer remaining clients

[._.]/ Adam Eivyf78560600300
diff --git a/PLAN.md b/PLAN.md
index 819f9f0a05..cf8b825e3a 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,6 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
+- [ ] [tolerant-fetch-json-additional-clients] **Adopt the shared `readResponseJson` helper in the remaining fetch-based clients.** The `[shared-tolerant-fetch-json-helper]` PR promoted `server/lib/readResponseJson.js` and migrated the originally-scoped clients, but a reuse-review sweep surfaced more fetch-based clients with the same unguarded `await response.json()` crash risk (an HTML/non-JSON error body throws `Unexpected token <`): `server/services/memoryClassifier.js:274`, `server/services/calendarApiSync.js:96`, `server/services/messageApiSync.js:74`, `server/services/insightsService.js:197`, and `server/services/localLlmPlayground.js:114` (all unguarded), plus `server/services/codeReview.js:166` which currently uses a `.catch(() => null)` band-aid that silently swallows the real error. Migrate each to `readResponseJson(response)` (object callers) with the appropriate `{ fallback, emptyValue }` for array endpoints; for `codeReview.js`, decide whether to surface the error text via the function-fallback form. Deferred out of the helper PR to keep it within its stated single-file-list scope. Surfaced by /simplify reuse review (2026-06-01).
- [ ] [cos-agent-output-write-amplification] **`appendAgentOutput` write-amplification — already batched via `appendAgentOutputLines`, audit non-runner producers.** CLAUDE.md documents the streaming-producers convention (batched variant + ~250ms debounce + drain on completion); the runner path uses it. Verify every producer that calls `appendAgentOutput` directly (`server/services/cosAgents.js:216`) is human-pace, not a hot loop. If any hot producer is still calling the per-line variant, migrate it. Likely a no-op audit; capture it so the convention doesn't silently drift.
- [ ] [subagent-spawner-top-level-side-effects] **`subAgentSpawner.js` top-level side effects — move init into an explicit `initSpawner()`.** Module-load (`server/services/subAgentSpawner.js:153`) wires event listeners + timers, which interferes with test isolation (each test import re-arms them). Wrap the init block in `export function initSpawner()` and call it from `server/index.js` after dependencies are ready. Treat as a refactor — needs care that no consumer relies on the import-time wiring.
- [ ] [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.
diff --git a/server/lib/index.js b/server/lib/index.js
index 9a67ff0b15..75fcddf51b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -111,8 +111,8 @@ export * from './httpsState.js';
export * from './networkExposure.js';
export * from './peerHttpClient.js';
export * from './peerSelfHost.js';
-export * from './readResponseJson.js';
export * from './peerUrl.js';
+export * from './readResponseJson.js';
export * from './sharingOrigin.js';
export * from './syncIntegrity.js';
export * from './syncWire.js';
diff --git a/server/lib/readResponseJson.js b/server/lib/readResponseJson.js
index 64be5d5731..c2f8bd04c9 100644
--- a/server/lib/readResponseJson.js
+++ b/server/lib/readResponseJson.js
@@ -1,5 +1,10 @@
import { safeJSONParse } from './fileUtils.js';
+// Private sentinel marking a failed parse — distinct from any value `safeJSONParse`
+// can return for a valid body (including `null`/`{}`/`[]`). Module-level so it
+// isn't reallocated per call.
+const PARSE_FAILED = Symbol('parse-failed');
+
/**
* Read a fetch `Response` body as JSON, tolerating a non-JSON body.
*
@@ -31,11 +36,10 @@ import { safeJSONParse } from './fileUtils.js';
export async function readResponseJson(response, { fallback = {}, emptyValue = {} } = {}) {
const text = await response.text();
if (!text) return emptyValue;
- // Parse with a private sentinel so a successful parse is distinguishable from
- // a parse failure, and the (possibly function) fallback is only materialized
+ // Parse against the sentinel so a successful parse is distinguishable from a
+ // parse failure, and the (possibly function) fallback is only materialized
// when the body genuinely isn't JSON — never eagerly on every success.
- const FAILED = Symbol('parse-failed');
- const parsed = safeJSONParse(text, FAILED);
- if (parsed !== FAILED) return parsed;
+ const parsed = safeJSONParse(text, PARSE_FAILED);
+ if (parsed !== PARSE_FAILED) return parsed;
return typeof fallback === 'function' ? fallback(text) : fallback;
}