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

fix: preserve personal records after unreadable JSON reads (#6972)

[._.]/ Adam Eivy0688667eb9ce
diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.js
index 7ee7ce138e..d9e4042467 100644
--- a/server/services/appleHealthIngest.js
+++ b/server/services/appleHealthIngest.js
@@ -46,7 +46,7 @@ export function dedupKey(metricName, dateString) {
*/
export async function readDayFile(dateStr) {
const filePath = join(PATHS.health, `${dateStr}.json`);
- return readJSONFile(filePath, { date: dateStr, metrics: {} });
+ return readJSONFile(filePath, { date: dateStr, metrics: {} }, { strict: true });
}
/**
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index dde53e18fc..18fcbc8825 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -183,7 +183,7 @@ async function loadStories() {
// on a missing file, so `data.stories.push(...)` / the deletedStories rewrite
// below would otherwise mutate the module-level DEFAULT_DATA and leak the
// previous caller's stories into the next fresh-install read.
- return readJSONFile(STORIES_FILE, structuredClone(DEFAULT_DATA));
+ return readJSONFile(STORIES_FILE, structuredClone(DEFAULT_DATA), { strict: true });
}
async function saveStories(data) {
@@ -193,7 +193,7 @@ async function saveStories(data) {
async function loadConfig() {
await ensureDir(DATA_DIR);
- return readJSONFile(CONFIG_FILE, DEFAULT_CONFIG);
+ return readJSONFile(CONFIG_FILE, DEFAULT_CONFIG, { strict: true });
}
async function saveConfig(config) {
diff --git a/server/services/brainJournal.js b/server/services/brainJournal.js
index d6d7ea0d5e..72f0e0759d 100644
--- a/server/services/brainJournal.js
+++ b/server/services/brainJournal.js
@@ -93,7 +93,7 @@ async function loadObsidianLocations() {
return obsidianLocationsCache;
}
await ensureDir(PATHS.brain);
- obsidianLocationsCache = await readJSONFile(OBSIDIAN_LOCATIONS_FILE, {});
+ obsidianLocationsCache = await readJSONFile(OBSIDIAN_LOCATIONS_FILE, {}, { strict: true });
obsidianLocationsCacheTime = Date.now();
return obsidianLocationsCache;
}
diff --git a/server/services/brainParity.js b/server/services/brainParity.js
index 1376cc1279..48e27bb656 100644
--- a/server/services/brainParity.js
+++ b/server/services/brainParity.js
@@ -279,7 +279,7 @@ export async function checkPeerBrainParity(peer) {
}
async function loadReports() {
- const stored = await readJSONFile(REPORTS_FILE, {});
+ const stored = await readJSONFile(REPORTS_FILE, {}, { strict: true });
return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {};
}
diff --git a/server/services/character.js b/server/services/character.js
index 9b0ddaaf2b..8d2e36b767 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -181,7 +181,7 @@ export function createDefaultCharacter() {
// Read the persisted record (no derived fields), creating the default on first access.
// Mutating paths build on this so they never re-persist a derived age-level.
async function loadRawCharacter() {
- const data = await readJSONFile(CHARACTER_FILE, null);
+ const data = await readJSONFile(CHARACTER_FILE, null, { strict: true });
if (data) return data;
const character = createDefaultCharacter();
await ensureDir(PATHS.data);
@@ -254,7 +254,7 @@ export async function updateCharacterFields(patch = {}) {
// persisted, and new peers ignore the remote level (applyCharacterRemote no longer merges it),
// so this projection is invisible to same-version installs.
export async function getWireCharacter() {
- const raw = await readJSONFile(CHARACTER_FILE, null);
+ const raw = await readJSONFile(CHARACTER_FILE, null, { strict: true });
if (!raw) return null;
// Strip every derived field a hand-edited or legacy character.json might be carrying before
// it goes out on the wire: `level` is then re-added below as the legacy xp-derived value,
diff --git a/server/services/dailyDriver.js b/server/services/dailyDriver.js
index c6b3224ec9..2ffbd7708e 100644
--- a/server/services/dailyDriver.js
+++ b/server/services/dailyDriver.js
@@ -36,7 +36,7 @@ export function computeDriverState(record, today) {
}
async function load() {
- return (await readJSONFile(FILE, null)) || {};
+ return (await readJSONFile(FILE, null, { strict: true })) || {};
}
async function save(record) {
diff --git a/server/services/dailyReview.js b/server/services/dailyReview.js
index 18584ce6cd..5861bb5a10 100644
--- a/server/services/dailyReview.js
+++ b/server/services/dailyReview.js
@@ -8,7 +8,7 @@ const REVIEW_DIR = join(PATHS.calendar, 'daily-reviews');
async function loadReview(date) {
await ensureDir(REVIEW_DIR);
- return readJSONFile(join(REVIEW_DIR, `${date}.json`), null);
+ return readJSONFile(join(REVIEW_DIR, `${date}.json`), null, { strict: true });
}
async function saveReview(date, data) {
@@ -145,6 +145,7 @@ export async function getDailyReviewHistory(startDate, endDate) {
const loaded = await Promise.all(
inRange.map(async reviewDate => {
+ // Read-only history projection; confirmations use the strict loadReview path.
const data = await readJSONFile(join(REVIEW_DIR, `${reviewDate}.json`), null);
if (!data) return null;
const confirmations = Object.values(data.confirmations || {});
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index 87eaa51d01..cc0dc9ec52 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -771,17 +771,17 @@ export async function getDigitalTwinSnapshot() {
// cadence or have prompts enabled without local opt-in. Only the stories sync.
const [identity, chronotype, longevity, feedback, taste, tasteObserved, chronotypeObserved, meta, documents, stories, socialAccounts] =
await Promise.all([
- readJSONFile(IDENTITY_FILE, null),
- readJSONFile(CHRONOTYPE_FILE, null),
- readJSONFile(LONGEVITY_FILE, null),
- readJSONFile(FEEDBACK_FILE, null),
- readJSONFile(TASTE_FILE, null),
- readJSONFile(TASTE_OBSERVED_FILE, null),
- readJSONFile(CHRONOTYPE_OBSERVED_FILE, null),
- readJSONFile(META_FILE, null),
+ readJSONFile(IDENTITY_FILE, null, { strict: true }),
+ readJSONFile(CHRONOTYPE_FILE, null, { strict: true }),
+ readJSONFile(LONGEVITY_FILE, null, { strict: true }),
+ readJSONFile(FEEDBACK_FILE, null, { strict: true }),
+ readJSONFile(TASTE_FILE, null, { strict: true }),
+ readJSONFile(TASTE_OBSERVED_FILE, null, { strict: true }),
+ readJSONFile(CHRONOTYPE_OBSERVED_FILE, null, { strict: true }),
+ readJSONFile(META_FILE, null, { strict: true }),
readMarkdownDocuments(),
- readJSONFile(AUTOBIO_STORIES_FILE, null),
- readJSONFile(SOCIAL_ACCOUNTS_FILE, null),
+ readJSONFile(AUTOBIO_STORIES_FILE, null, { strict: true }),
+ readJSONFile(SOCIAL_ACCOUNTS_FILE, null, { strict: true }),
]);
const data = { identity, chronotype, longevity, feedback, taste, tasteObserved, chronotypeObserved, meta, documents, autobiography: { stories }, socialAccounts };
return { data, checksum: computeChecksum(data) };
@@ -791,7 +791,7 @@ export async function getDigitalTwinSnapshot() {
async function applyMerge(path, remote, mergeFn, { dir } = {}) {
if (remote === undefined || remote === null) return 0;
- const local = await readJSONFile(path, null);
+ const local = await readJSONFile(path, null, { strict: true });
const { merged, changed } = mergeFn(local, remote);
if (!changed) return 0;
if (dir) await ensureDir(dir);
@@ -813,7 +813,7 @@ async function applyMerge(path, remote, mergeFn, { dir } = {}) {
* `createdAt` superseded the tombstone.
*/
async function readSuppressedDocuments() {
- const meta = await readJSONFile(META_FILE, null);
+ const meta = await readJSONFile(META_FILE, null, { strict: true });
if (!isPlainObject(meta)) return new Set();
const live = new Set(
(Array.isArray(meta.documents) ? meta.documents : [])
@@ -881,7 +881,7 @@ async function applyDocuments(documents, suppressed) {
async function applyTaste(remoteTaste) {
if (!isPlainObject(remoteTaste)) return 0;
- const local = await readJSONFile(TASTE_FILE, null);
+ const local = await readJSONFile(TASTE_FILE, null, { strict: true });
const { merged, changed } = mergeTaste(local, remoteTaste);
if (!changed) return 0;
await atomicWrite(TASTE_FILE, merged);
diff --git a/server/services/goalCalendarScheduler.js b/server/services/goalCalendarScheduler.js
index 2475fc8c80..a750bd5357 100644
--- a/server/services/goalCalendarScheduler.js
+++ b/server/services/goalCalendarScheduler.js
@@ -28,7 +28,7 @@ function resolveTimeSlotMinute(timeSlot) {
}
async function loadGoals() {
- return readJSONFile(GOALS_FILE, { goals: [] });
+ return readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });
}
async function saveGoals(data) {
diff --git a/server/services/insightsService.js b/server/services/insightsService.js
index 256a0b5b1d..babf7acc0b 100644
--- a/server/services/insightsService.js
+++ b/server/services/insightsService.js
@@ -302,6 +302,7 @@ export async function getGenomeHealthCorrelations() {
* Returns { available: false, reason: 'not_generated' } if no cache exists.
*/
export async function getThemeAnalysis() {
+ // Cache: explicit generation replaces themes entirely from authoritative source records.
const cached = await readJSONFile(THEMES_FILE, null);
if (!cached) {
return { available: false, reason: 'not_generated' };
@@ -388,6 +389,7 @@ Example format:
* Returns { available: false, reason: 'not_generated' } if no cache exists.
*/
export async function getCrossDomainNarrative() {
+ // Read-only presentation; refresh uses a separate strict read to retain the prior narrative.
const cached = await readJSONFile(NARRATIVE_FILE, null);
if (!cached) {
return { available: false, reason: 'not_generated' };
@@ -409,7 +411,7 @@ export async function getCrossDomainNarrative() {
*/
export async function refreshCrossDomainNarrative(providerId, model) {
// Load existing narrative for diff support
- const existingNarrative = await readJSONFile(NARRATIVE_FILE, null);
+ const existingNarrative = await readJSONFile(NARRATIVE_FILE, null, { strict: true });
const provider = providerId
? await getProviderById(providerId)
diff --git a/server/services/meatspace.js b/server/services/meatspace.js
index 91489d4899..4862ed56a0 100644
--- a/server/services/meatspace.js
+++ b/server/services/meatspace.js
@@ -66,7 +66,7 @@ async function ensureMeatspaceDir() {
}
async function loadConfig() {
- return readJSONFile(CONFIG_FILE, structuredClone(DEFAULT_CONFIG));
+ return readJSONFile(CONFIG_FILE, structuredClone(DEFAULT_CONFIG), { strict: true });
}
async function saveConfig(config) {
@@ -282,7 +282,7 @@ async function migrateBirthDateFromGoals(config) {
return queueConfigWrite(async () => {
const freshConfig = await loadConfig();
if (freshConfig.birthDate) return freshConfig;
- const goals = await readJSONFile(GOALS_FILE, null);
+ const goals = await readJSONFile(GOALS_FILE, null, { strict: true });
if (!goals?.birthDate) return freshConfig;
freshConfig.birthDate = goals.birthDate;
freshConfig.updatedAt = new Date().toISOString();
@@ -324,7 +324,7 @@ export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {
// Keep goals.json in sync for backward compatibility
if (syncGoals) {
- const goals = await readJSONFile(GOALS_FILE, null);
+ const goals = await readJSONFile(GOALS_FILE, null, { strict: true });
if (goals) {
goals.birthDate = birthDate;
goals.updatedAt = new Date().toISOString();
@@ -340,6 +340,7 @@ export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {
export async function getDeathClock() {
const [config, longevity] = await Promise.all([
loadConfig(),
+ // Read-only longevity input; this service never persists the projection.
readJSONFile(LONGEVITY_FILE, null)
]);
@@ -357,6 +358,7 @@ export async function getDeathClock() {
export async function getLEV() {
const [longevity, config] = await Promise.all([
+ // Read-only longevity input; this service never persists the projection.
readJSONFile(LONGEVITY_FILE, null),
loadConfig()
]);
diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.js
index ec1201ecfe..123e50ee58 100644
--- a/server/services/meatspaceAlcohol.js
+++ b/server/services/meatspaceAlcohol.js
@@ -162,6 +162,7 @@ export async function getAlcoholSummary() {
const [log, config] = await Promise.all([
loadDailyLog(),
+ // Read-only summary input; mutations of this config belong to meatspace.js.
readJSONFile(CONFIG_FILE, { sex: 'male' })
]);
@@ -324,7 +325,7 @@ export async function removeDrink(date, index) {
// === Custom Drink Buttons ===
async function loadCustomDrinks() {
- const data = await readJSONFile(CUSTOM_DRINKS_FILE, null, { allowArray: false });
+ const data = await readJSONFile(CUSTOM_DRINKS_FILE, null, { allowArray: false, strict: true });
if (!data || typeof data !== 'object' || Array.isArray(data)) {
// Return defaults in-memory without writing — persist only on explicit mutations
return { drinks: DEFAULT_DRINK_BUTTONS.map(d => ({ ...d })) };
diff --git a/server/services/meatspaceCalendar.js b/server/services/meatspaceCalendar.js
index 8efbfe6c57..f5a1564226 100644
--- a/server/services/meatspaceCalendar.js
+++ b/server/services/meatspaceCalendar.js
@@ -185,7 +185,7 @@ export function computeActivityBudgets(deathDate, activities) {
// === File I/O ===
async function loadActivities() {
- return readJSONFile(ACTIVITIES_FILE, { activities: [] });
+ return readJSONFile(ACTIVITIES_FILE, { activities: [] }, { strict: true });
}
async function saveActivities(data) {
@@ -218,7 +218,7 @@ const DEFAULT_EVENTS = [
];
async function loadEvents() {
- return readJSONFile(EVENTS_FILE, { events: [] });
+ return readJSONFile(EVENTS_FILE, { events: [] }, { strict: true });
}
async function saveEvents(data) {
diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.js
index a43a3612c7..ef59a7a9b2 100644
--- a/server/services/meatspaceNicotine.js
+++ b/server/services/meatspaceNicotine.js
@@ -271,7 +271,7 @@ export async function removeNicotine(date, index) {
// === Custom Product Buttons ===
async function loadCustomProducts() {
- const data = await readJSONFile(CUSTOM_PRODUCTS_FILE, null, { allowArray: false });
+ const data = await readJSONFile(CUSTOM_PRODUCTS_FILE, null, { allowArray: false, strict: true });
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return { products: DEFAULT_PRODUCTS.map(p => ({ ...p })) };
}
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index dbc8df90f6..b610485437 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -328,7 +328,7 @@ async function ensureMeatspaceDir() {
export async function getPostConfig() {
const baseDefaults = structuredClone(DEFAULT_CONFIG);
- const config = await readJSONFile(CONFIG_FILE, baseDefaults);
+ const config = await readJSONFile(CONFIG_FILE, baseDefaults, { strict: true });
return deepMerge(baseDefaults, config);
}
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index b0aa1af91d..8d2da1a329 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -354,7 +354,7 @@ const ELEMENTS_SONG = {
// =============================================================================
async function loadMemoryItems() {
- const data = await readJSONFile(MEMORY_ITEMS_FILE, { items: [] }, { allowArray: false });
+ const data = await readJSONFile(MEMORY_ITEMS_FILE, { items: [] }, { allowArray: false, strict: true });
const items = data?.items && Array.isArray(data.items) ? data.items : [];
// Ensure built-in Elements Song is always present and content stays current
diff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.js
index 967f0d1df1..375f2e8dae 100644
--- a/server/services/meatspacePostMorse.js
+++ b/server/services/meatspacePostMorse.js
@@ -55,7 +55,7 @@ async function loadMorseProgress() {
const raw = await readJSONFile(
MORSE_FILE,
{ kochLevel: null, settings: null, rounds: [] },
- { allowArray: false },
+ { allowArray: false, strict: true },
);
// `allowArray: false` only rejects a root array — a bare JSON scalar
// (corrupted file) still parses, and the field assignments below would
diff --git a/server/services/meatspacePostReview.js b/server/services/meatspacePostReview.js
index d77ed86d37..0879931022 100644
--- a/server/services/meatspacePostReview.js
+++ b/server/services/meatspacePostReview.js
@@ -59,7 +59,7 @@ function intervalForStage(stage) {
// =============================================================================
async function loadReviewSchedule() {
- const data = await readJSONFile(REVIEW_SCHEDULE_FILE, { skills: {} }, { allowArray: false });
+ const data = await readJSONFile(REVIEW_SCHEDULE_FILE, { skills: {} }, { allowArray: false, strict: true });
const skills = data?.skills && typeof data.skills === 'object' ? data.skills : {};
return { skills };
}
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index a7360ad5a8..87db3603b8 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -733,7 +733,7 @@ export async function importToPortOS() {
const report = { added: {}, skipped: {} };
const mergeById = async (mlArr, localPath, pathDir) => {
- const local = await readJSONFile(localPath, []);
+ const local = await readJSONFile(localPath, [], { strict: true });
const localArr = Array.isArray(local) ? local : [];
const seen = new Set(localArr.map(x => x.id).filter(Boolean));
let added = 0, skipped = 0;
@@ -750,7 +750,7 @@ export async function importToPortOS() {
// Goals live in a wrapper object, not a bare array
const goalsPath = dataPath('digital-twin', 'goals.json');
- const localGoals = await readJSONFile(goalsPath, { goals: [] });
+ const localGoals = await readJSONFile(goalsPath, { goals: [] }, { strict: true });
const seenGoalIds = new Set((localGoals.goals || []).map(g => g.id));
let gAdded = 0, gSkipped = 0;
for (const g of (store.goals || [])) {
diff --git a/server/services/personalStoreReadSafety.test.js b/server/services/personalStoreReadSafety.test.js
new file mode 100644
index 0000000000..2addfc7af7
--- /dev/null
+++ b/server/services/personalStoreReadSafety.test.js
@@ -0,0 +1,160 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { dirname, join } from 'path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const fault = vi.hoisted(() => ({ path: null }));
+vi.mock('fs/promises', async (original) => {
+ const fs = await original();
+ return { ...fs, readFile: (...args) => String(args[0]) === fault.path
+ ? Promise.reject(Object.assign(new Error('injected read failure'), { code: 'EACCES' }))
+ : fs.readFile(...args) };
+});
+vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {
+ dataRoot: () => lazyTempDataRoot('portos-personal-read-safety-'),
+}));
+vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), {
+ dataRoot: () => lazyTempDataRoot('portos-personal-read-safety-'),
+}));
+vi.mock('./userTimezone.js', () => ({ getUserTimezone: async () => 'UTC', userLocalToday: async () => '2026-01-02' }));
+vi.mock('./characterSkills.js', () => ({ getCharacterSkills: async () => [] }));
+vi.mock('./characterMetrics.js', () => ({ getCharacterMetrics: async () => [] }));
+vi.mock('./characterSignals.js', () => ({ createSignalContext: () => () => null }));
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: async () => ({ user: { tasks: [] }, cos: { tasks: [] } }) }));
+vi.mock('./jira.js', () => ({}));
+vi.mock('./providers.js', () => ({ getActiveProvider: async () => null, getProviderById: async () => null }));
+vi.mock('./aiProvider.js', () => ({ callProviderAISimple: vi.fn(), parseLLMJSON: vi.fn() }));
+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));
+vi.mock('../lib/db.js', () => ({ query: async () => ({ rows: [] }), ensureSchema: async () => {} }));
+vi.mock('./brainStorage.js', async () => {
+ const { EventEmitter } = await import('events');
+ return { brainEvents: new EventEmitter(), now: () => new Date().toISOString(),
+ getAll: async () => [], get: async () => null };
+});
+vi.mock('./obsidian.js', () => ({}));
+vi.mock('./notifications.js', () => ({ addNotification: vi.fn(), NOTIFICATION_TYPES: {}, exists: async () => false }));
+vi.mock('./calendarSync.js', () => ({}));
+vi.mock('./calendarAccounts.js', () => ({}));
+vi.mock('./identity.js', () => ({ addProgressEntry: vi.fn(), getGoals: async () => ({ goals: [] }) }));
+
+vi.mock('./cosAgentLifecycle.js', () => ({ getAgents: async () => [] }));
+vi.mock('./digital-twin-meta.js', () => ({ loadMeta: async () => ({}), saveMeta: vi.fn() }));
+vi.mock('./taste-questionnaire.js', () => ({ invalidateTasteProfileCache: vi.fn() }));
+
+import { PATHS } from '../lib/fileUtils.js';
+import { mergeIntoDay } from './appleHealthIngest.js';
+import { saveStory, updateConfig } from './autobiography.js';
+import { updateCharacterFields } from './character.js';
+import { markDriverHandled } from './dailyDriver.js';
+import { confirmEvent } from './dailyReview.js';
+import { updateBirthDate } from './meatspace.js';
+import { addCustomDrink } from './meatspaceAlcohol.js';
+import { addActivity, addLifeEvent } from './meatspaceCalendar.js';
+import { addCustomProduct } from './meatspaceNicotine.js';
+import { setKochLevel } from './meatspacePostMorse.js';
+import { saveStoredPostSession, saveStoredTrainingRun } from './postRunStore.js';
+import { aggregateTwinEvidence } from './twinEnrichment.js';
+import { listJournals, _clearObsidianLocationsCacheForTest } from './brainJournal.js';
+
+import { updatePostConfig } from './meatspacePost.js';
+import { createMemoryItem } from './meatspacePostMemory.js';
+import { applySessionToReviewSchedule } from './meatspacePostReview.js';
+import { onTaskCompleted } from './productivity.js';
+import { recordUserAction } from './userActions.js';
+import { getDigitalTwinSnapshot, applyDigitalTwinRemote } from './digital-twin-sync.js';
+
+const cases = [
+ ['POST config', () => join(PATHS.meatspace, 'post-config.json'), () => updatePostConfig({ enabled: true })],
+ ['memory items', () => join(PATHS.meatspace, 'post-memory-items.json'), () => createMemoryItem({ title: 'Example', lines: ['Example line'] })],
+ ['review schedule', () => join(PATHS.meatspace, 'post-review-schedule.json'), () => applySessionToReviewSchedule({ masteredSkills: [{ skillId: 'example' }] })],
+ ['productivity', () => join(PATHS.cos, 'productivity.json'), () => onTaskCompleted({ completedAt: '2026-01-02T00:00:00Z', result: { success: true } })],
+ ['user actions', () => join(PATHS.data, 'user-action-events.json'), () => recordUserAction({ type: 'cos.task.create', dedupeKey: 'example', actor: 'user' })],
+ ['health day', () => join(PATHS.health, '2026-01-02.json'), () => mergeIntoDay('2026-01-02', 'steps', [{ date: '2026-01-02T12:00:00Z', qty: 1 }])],
+ ['autobiography stories', () => join(PATHS.digitalTwin, 'autobiography/stories.json'), () => saveStory({ promptId: 'childhood-0', content: 'Example memory' })],
+ ['autobiography config', () => join(PATHS.digitalTwin, 'autobiography/config.json'), () => updateConfig({ enabled: true })],
+ ['character', () => join(PATHS.data, 'character.json'), () => updateCharacterFields({ name: 'Example character' })],
+ ['daily driver', () => join(PATHS.data, 'daily-driver.json'), markDriverHandled],
+ ['daily review', () => join(PATHS.calendar, 'daily-reviews/2026-01-02.json'), () => confirmEvent('2026-01-02', { eventId: 'example', happened: false })],
+ ['meatspace config', () => join(PATHS.meatspace, 'config.json'), () => updateBirthDate('2000-01-01', { syncGoals: false })],
+ ['custom drinks', () => join(PATHS.meatspace, 'custom-drinks.json'), () => addCustomDrink({ name: 'Example', oz: 12, abv: 5 })],
+ ['custom nicotine', () => join(PATHS.meatspace, 'custom-nicotine-products.json'), () => addCustomProduct({ name: 'Example', nicotineMg: 1 })],
+ ['activities', () => join(PATHS.meatspace, 'activities.json'), () => addActivity({ name: 'Example', hoursPerWeek: 1 })],
+ ['life events', () => join(PATHS.meatspace, 'life-events.json'), () => addLifeEvent({ name: 'Example', date: '2026-01-02' })],
+ ['Morse progress', () => join(PATHS.meatspace, 'post-morse-progress.json'), () => setKochLevel({ kochLevel: 3 })],
+ ['POST sessions', () => join(PATHS.meatspace, 'post-sessions.json'), () => saveStoredPostSession({ id: 'example-run', date: '2026-01-02' })],
+ ['POST training', () => join(PATHS.meatspace, 'post-training-log.json'), () => saveStoredTrainingRun({ id: 'example-run', localDay: '2026-01-02', attempts: [{ id: 'example-attempt', skill: 'memory' }] })],
+ ['taste evidence', () => join(PATHS.digitalTwin, 'taste-observed.json'), aggregateTwinEvidence],
+];
+
+beforeEach(async () => {
+ fault.path = null;
+ _clearObsidianLocationsCacheForTest();
+ await rm(PATHS.data, { recursive: true, force: true });
+ await mkdir(PATHS.data, { recursive: true });
+});
+afterAll(cleanupTempDataRoots);
+
+async function seed(path, bytes) {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, bytes);
+}
+
+describe.each(cases)('%s persistence boundary', (_name, pathFor, mutate) => {
+ it('preserves unreadable bytes, rejects read faults, then initializes only when absent', async () => {
+ const path = pathFor();
+ for (const bytes of ['{"retained":', '', 'not json']) {
+ await seed(path, bytes);
+ await expect(mutate()).rejects.toThrow(/Unreadable JSON file/);
+ expect(await readFile(path, 'utf8')).toBe(bytes);
+ }
+ await seed(path, '{}');
+ fault.path = path;
+ await expect(mutate()).rejects.toThrow(/Unreadable JSON file/);
+ fault.path = null;
+ expect(await readFile(path, 'utf8')).toBe('{}');
+ await rm(path);
+ await mutate();
+ expect(JSON.parse(await readFile(path, 'utf8'))).toBeTruthy();
+ });
+});
+
+it('retains existing autobiography records while appending after a repair', async () => {
+ const path = join(PATHS.digitalTwin, 'autobiography/stories.json');
+ await seed(path, '{');
+ await expect(saveStory({ promptId: 'example', content: 'New story' })).rejects.toThrow();
+ const existing = { id: 'retained-story', content: 'Earlier story', customField: 'preserve' };
+ await seed(path, JSON.stringify({ stories: [existing], usedPrompts: ['prior'], deletedStories: [{ id: 'deleted' }] }));
+ await saveStory({ promptId: 'example', content: 'New story' });
+ const saved = JSON.parse(await readFile(path, 'utf8'));
+ expect(saved.stories[0]).toEqual(existing);
+ expect(saved.stories).toHaveLength(2);
+ expect(saved.deletedStories).toEqual([{ id: 'deleted' }]);
+});
+
+it('retains the user interpretation while rebuilding taste evidence', async () => {
+ const path = join(PATHS.digitalTwin, 'taste-observed.json');
+ await seed(path, JSON.stringify({ interpretation: { text: 'Retained interpretation' } }));
+ await aggregateTwinEvidence();
+ expect(JSON.parse(await readFile(path, 'utf8')).interpretation).toEqual({ text: 'Retained interpretation' });
+});
+
+it('does not cache a failed Obsidian map load and retries after repair', async () => {
+ const path = join(PATHS.brain, 'journal-obsidian-locations.json');
+ await seed(path, '{');
+ await expect(listJournals()).rejects.toThrow(/Unreadable JSON file/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ await seed(path, '{}');
+ await expect(listJournals()).resolves.toEqual({ records: [], total: 0 });
+});
+
+it('blocks Digital Twin merge and export on unreadable local records, then preserves repaired history', async () => {
+ const path = join(PATHS.digitalTwin, 'autobiography/stories.json');
+ const incoming = { autobiography: { stories: { stories: [{ id: 'incoming', content: 'New', createdAt: '2026-02-01' }] } } };
+ await seed(path, '{');
+ await expect(getDigitalTwinSnapshot()).rejects.toThrow(/Unreadable JSON file/);
+ await expect(applyDigitalTwinRemote(incoming)).rejects.toThrow(/Unreadable JSON file/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ await seed(path, JSON.stringify({ stories: [{ id: 'retained', content: 'Earlier', createdAt: '2026-01-01' }] }));
+ await applyDigitalTwinRemote(incoming);
+ expect(JSON.parse(await readFile(path, 'utf8')).stories.map(story => story.id).sort()).toEqual(['incoming', 'retained']);
+});
diff --git a/server/services/postRunStore.js b/server/services/postRunStore.js
index 366e72f708..ffa60fc373 100644
--- a/server/services/postRunStore.js
+++ b/server/services/postRunStore.js
@@ -20,7 +20,7 @@ const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
const TRAINING_FILE = join(MEATSPACE_DIR, 'post-training-log.json');
-async function loadFileSessions({ strict = false } = {}) {
+async function loadFileSessions({ strict = true } = {}) {
const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false, strict });
if (strict && (!isPlainObject(raw) || !Array.isArray(raw.sessions))) {
throw new Error(`POST sessions malformed: ${SESSIONS_FILE}`);
@@ -28,7 +28,7 @@ async function loadFileSessions({ strict = false } = {}) {
return Array.isArray(raw?.sessions) ? raw.sessions : [];
}
-async function loadFileTraining({ strict = false } = {}) {
+async function loadFileTraining({ strict = true } = {}) {
const raw = await readJSONFile(TRAINING_FILE, { entries: [] }, { allowArray: false, strict });
if (strict && !Array.isArray(raw?.entries)) {
throw new Error(`POST training log malformed: ${TRAINING_FILE}`);
diff --git a/server/services/productivity.js b/server/services/productivity.js
index 92f33219cb..1e30ae6484 100644
--- a/server/services/productivity.js
+++ b/server/services/productivity.js
@@ -37,7 +37,7 @@ const DEFAULT_PRODUCTIVITY = {
*/
export async function loadProductivity() {
await ensureDir(DATA_DIR);
- const data = await readJSONFile(PRODUCTIVITY_FILE, null);
+ const data = await readJSONFile(PRODUCTIVITY_FILE, null, { strict: true });
// Clone the defaults on every read: callers (onTaskCompleted) mutate the
// nested pattern maps in place, so handing back the module-level constant
// would leak one call's counters into the next "no file yet" read.
diff --git a/server/services/twinEnrichment.js b/server/services/twinEnrichment.js
index 9eea93fc63..26b29cf873 100644
--- a/server/services/twinEnrichment.js
+++ b/server/services/twinEnrichment.js
@@ -335,10 +335,11 @@ function daysAgoIso(days, now) {
// ---------------------------------------------------------------------------
export async function getTasteEvidence() {
- return readJSONFile(TASTE_OBSERVED_FILE, null);
+ return readJSONFile(TASTE_OBSERVED_FILE, null, { strict: true });
}
export async function getChronotypeEvidence() {
+ // Authoritative rebuild: aggregation replaces this histogram from activity rows; no prior fields are retained.
return readJSONFile(CHRONOTYPE_OBSERVED_FILE, null);
}
@@ -440,6 +441,7 @@ export async function getObservedEvidence() {
const [taste, chronotype, statedChronotype] = await Promise.all([
getTasteEvidence(),
getChronotypeEvidence(),
+ // Read-only comparison: this stated record is never written by this service.
readJSONFile(join(DIR, 'chronotype.json'), null),
]);
// Only treat the stated chronotype as a real answer once it's been derived —
diff --git a/server/services/userActions.js b/server/services/userActions.js
index eb52e6c4d1..5672661d8b 100644
--- a/server/services/userActions.js
+++ b/server/services/userActions.js
@@ -299,7 +299,7 @@ function retentionCutoff(now = Date.now()) {
const queueWrite = createFileWriteQueue();
async function loadFileEvents() {
- const raw = await readJSONFile(eventsFile(), { events: [] }, { allowArray: false });
+ const raw = await readJSONFile(eventsFile(), { events: [] }, { allowArray: false, strict: true });
return Array.isArray(raw?.events) ? raw.events : [];
}
diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.js
index 3f621f6cab..71498a242d 100644
--- a/server/services/weeklyDigest.js
+++ b/server/services/weeklyDigest.js
@@ -48,6 +48,8 @@ function getDigestPath(weekId) {
*/
async function loadDigest(weekId) {
const path = getDigestPath(weekId);
+ // Derived snapshot: generation rebuilds the target week from agent records; this read
+ // only presents it or supplies a previous-week comparison, never a write-back base.
return readJSONFile(path, null);
}