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 creative catalog stores after unreadable reads (#6973)

[._.]/ Adam Eivybb209d63fe37
diff --git a/server/services/albums/file.js b/server/services/albums/file.js
index 770b38305a..6e98371f1f 100644
--- a/server/services/albums/file.js
+++ b/server/services/albums/file.js
@@ -20,7 +20,8 @@ import {
const ALBUMS_FILE = join(PATHS.data, 'albums.json');
async function loadAll() {
- const raw = await readJSONFile(ALBUMS_FILE, []);
+ // Albums are durable user records; never save an empty fallback over unreadable bytes.
+ const raw = await readJSONFile(ALBUMS_FILE, [], { strict: true });
return (Array.isArray(raw) ? raw : []).map(sanitizeAlbum).filter(Boolean);
}
diff --git a/server/services/artists/file.js b/server/services/artists/file.js
index 72231f0a11..5e557205cf 100644
--- a/server/services/artists/file.js
+++ b/server/services/artists/file.js
@@ -20,7 +20,8 @@ import {
const ARTISTS_FILE = join(PATHS.data, 'artists.json');
async function loadAll() {
- const raw = await readJSONFile(ARTISTS_FILE, []);
+ // Artists are durable user records; never save an empty fallback over unreadable bytes.
+ const raw = await readJSONFile(ARTISTS_FILE, [], { strict: true });
return (Array.isArray(raw) ? raw : []).map(sanitizeArtist).filter(Boolean);
}
diff --git a/server/services/authors/file.js b/server/services/authors/file.js
index 0d52117458..bfc4ce7e50 100644
--- a/server/services/authors/file.js
+++ b/server/services/authors/file.js
@@ -23,7 +23,8 @@ import {
const AUTHORS_FILE = join(PATHS.data, 'authors.json');
async function loadAll() {
- const raw = await readJSONFile(AUTHORS_FILE, []);
+ // Authors are durable user records; never save an empty fallback over unreadable bytes.
+ const raw = await readJSONFile(AUTHORS_FILE, [], { strict: true });
return (Array.isArray(raw) ? raw : []).map(sanitizeAuthor).filter(Boolean);
}
diff --git a/server/services/creativeCatalogJsonWriteback.test.js b/server/services/creativeCatalogJsonWriteback.test.js
new file mode 100644
index 0000000000..b13673ee0e
--- /dev/null
+++ b/server/services/creativeCatalogJsonWriteback.test.js
@@ -0,0 +1,166 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'creative-catalog-writeback-'));
+const fault = vi.hoisted(() => ({ path: null }));
+
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (...args) => String(args[0]) === fault.path
+ ? Promise.reject(Object.assign(new Error('injected read denial'), { code: 'EACCES' }))
+ : actual.readFile(...args),
+ };
+});
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+const albums = await import('./albums/file.js');
+const artists = await import('./artists/file.js');
+const authors = await import('./authors/file.js');
+const tracks = await import('./tracks/file.js');
+const timeline = await import('./videoTimeline/local.js');
+const { writersRoomStore, _resetWritersRoomStore } = await import('./writersRoom/store.js');
+const { PATHS } = await import('../lib/fileUtils.js');
+
+const timestamp = '2026-01-01T00:00:00.000Z';
+const writersRoomRoot = join(PATHS.data, 'writers-room');
+
+const stores = [
+ {
+ name: 'album catalog',
+ path: join(PATHS.data, 'albums.json'),
+ seed: [{
+ id: 'album-existing', title: 'Existing album', artistId: '', artist: '', description: '', genre: '',
+ releaseYear: null, coverImageUrl: '', trackIds: [], createdAt: timestamp, updatedAt: timestamp,
+ deleted: false, deletedAt: null,
+ }],
+ mutate: () => albums.createAlbum({ title: 'New album' }),
+ preserved: data => data.some(record => record.id === 'album-existing' && record.title === 'Existing album'),
+ initialized: data => data.some(record => record.title === 'New album'),
+ },
+ {
+ name: 'artist catalog',
+ path: join(PATHS.data, 'artists.json'),
+ seed: [{
+ id: 'artist-existing', name: 'Existing artist', genre: '', bio: '', musicalStyle: '',
+ physicalDescription: '', portraitStyle: '', portraitImageUrl: '', createdAt: timestamp,
+ updatedAt: timestamp, deleted: false, deletedAt: null,
+ }],
+ mutate: () => artists.createArtist({ name: 'New artist' }),
+ preserved: data => data.some(record => record.id === 'artist-existing' && record.name === 'Existing artist'),
+ initialized: data => data.some(record => record.name === 'New artist'),
+ },
+ {
+ name: 'author catalog',
+ path: join(PATHS.data, 'authors.json'),
+ seed: [{
+ id: 'auth-existing', name: 'Existing author', writingStyle: '', bio: '', physicalDescription: '',
+ headshotStyle: '', headshotImageUrl: '', createdAt: timestamp, updatedAt: timestamp,
+ deleted: false, deletedAt: null,
+ }],
+ mutate: () => authors.createAuthor({ name: 'New author' }),
+ preserved: data => data.some(record => record.id === 'auth-existing' && record.name === 'Existing author'),
+ initialized: data => data.some(record => record.name === 'New author'),
+ },
+ {
+ name: 'track catalog',
+ path: join(PATHS.data, 'tracks.json'),
+ seed: [{
+ id: 'track-existing', title: 'Existing track', albumId: '', artistId: '', artist: '', concept: '',
+ lyrics: '', prompt: '', engine: '', modelId: '', durationSec: null, audioFilename: '',
+ chiptuneScore: null, chiptunePrompt: '', createdAt: timestamp, updatedAt: timestamp,
+ deleted: false, deletedAt: null,
+ }],
+ mutate: () => tracks.createTrack({ title: 'New track' }),
+ preserved: data => data.some(record => record.id === 'track-existing' && record.title === 'Existing track'),
+ initialized: data => data.some(record => record.title === 'New track'),
+ },
+ {
+ name: 'video timeline projects',
+ path: join(PATHS.data, 'video-projects.json'),
+ seed: [{
+ id: 'project-existing', name: 'Existing timeline', createdAt: timestamp, updatedAt: timestamp,
+ schemaVersion: 2, segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [],
+ }],
+ mutate: () => timeline.createProject('New timeline'),
+ preserved: data => data.some(record => record.id === 'project-existing' && record.name === 'Existing timeline'),
+ initialized: data => data.some(record => record.name === 'New timeline'),
+ },
+ {
+ name: 'Writers Room folders',
+ path: join(writersRoomRoot, 'folders.json'),
+ seed: [{
+ id: 'wr-folder-existing', name: 'Existing folder', parentId: null, sortOrder: 0,
+ createdAt: timestamp, updatedAt: timestamp,
+ }],
+ mutate: () => writersRoomStore().writeFolder({
+ id: 'wr-folder-new', name: 'New folder', parentId: null, sortOrder: 1,
+ createdAt: timestamp, updatedAt: timestamp,
+ }),
+ preserved: data => data.some(record => record.id === 'wr-folder-existing' && record.name === 'Existing folder'),
+ initialized: data => data.some(record => record.id === 'wr-folder-new'),
+ },
+ {
+ name: 'Writers Room exercises',
+ path: join(writersRoomRoot, 'exercises.json'),
+ seed: [{
+ id: 'wr-ex-existing', workId: 'wr-work-existing', status: 'finished',
+ startedAt: timestamp, finishedAt: timestamp,
+ }],
+ mutate: () => writersRoomStore().writeExercise({
+ id: 'wr-ex-new', workId: 'wr-work-new', status: 'running', startedAt: timestamp,
+ }),
+ preserved: data => data.some(record => record.id === 'wr-ex-existing' && record.status === 'finished'),
+ initialized: data => data.some(record => record.id === 'wr-ex-new'),
+ },
+];
+
+beforeEach(() => {
+ fault.path = null;
+ _resetWritersRoomStore();
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+});
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+// These service/store boundaries uniquely prove that each owned path refuses to
+// persist its fallback. Real temporary files pin the bytes; only the read fault is injected.
+describe.each(stores)('$name durable write-back', store => {
+ it.each(['{"truncated":', '', '{"records":{}}'])(
+ 'preserves unreadable bytes (%j) and can retry after repair',
+ async (bytes) => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ writeFileSync(store.path, bytes);
+
+ await expect(store.mutate()).rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+
+ writeFileSync(store.path, JSON.stringify(store.seed));
+ await store.mutate();
+ const saved = JSON.parse(readFileSync(store.path, 'utf8'));
+ expect(store.preserved(saved)).toBe(true);
+ },
+ );
+
+ it('preserves existing bytes on an injected filesystem read failure', async () => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ const bytes = JSON.stringify(store.seed);
+ writeFileSync(store.path, bytes);
+ fault.path = store.path;
+
+ await expect(store.mutate()).rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+ });
+
+ it('initializes an absent file through the mutation boundary', async () => {
+ await store.mutate();
+ expect(store.initialized(JSON.parse(readFileSync(store.path, 'utf8')))).toBe(true);
+ });
+});
diff --git a/server/services/tracks/file.js b/server/services/tracks/file.js
index 223c925158..70478f5515 100644
--- a/server/services/tracks/file.js
+++ b/server/services/tracks/file.js
@@ -20,7 +20,8 @@ import {
const TRACKS_FILE = join(PATHS.data, 'tracks.json');
async function loadAll() {
- const raw = await readJSONFile(TRACKS_FILE, []);
+ // Tracks are durable user records; never save an empty fallback over unreadable bytes.
+ const raw = await readJSONFile(TRACKS_FILE, [], { strict: true });
return (Array.isArray(raw) ? raw : []).map(sanitizeTrack).filter(Boolean);
}
diff --git a/server/services/videoTimeline/local.crud.test.js b/server/services/videoTimeline/local.crud.test.js
index 16a810aff4..abed118e6e 100644
--- a/server/services/videoTimeline/local.crud.test.js
+++ b/server/services/videoTimeline/local.crud.test.js
@@ -57,9 +57,12 @@ describe('loading a v1 project', () => {
expect(onDisk()[0].segments).toBeUndefined();
});
- it('lists a corrupt file as empty rather than crashing', async () => {
- writeFileSync(PROJECTS_FILE, JSON.stringify({ projects: [] }));
- expect(await listProjects()).toEqual([]);
+ it('rejects a corrupt non-array root without changing its bytes', async () => {
+ const bytes = JSON.stringify({ projects: [] });
+ writeFileSync(PROJECTS_FILE, bytes);
+
+ await expect(listProjects()).rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });
+ expect(readFileSync(PROJECTS_FILE, 'utf8')).toBe(bytes);
});
});
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index eef7c8a0ea..ff339bc8aa 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -86,14 +86,15 @@ export function getRenderJobStatus(jobId) {
// ids) use this and normalize just what they need — normalizing every project
// on every request is pure waste on a library of any size.
const loadRawProjects = async () => {
- const raw = await readJSONFile(PROJECTS_FILE, []);
+ // Timeline projects are durable user edits; a mutator must never persist an
+ // empty fallback over a present-but-unreadable project file.
+ const raw = await readJSONFile(PROJECTS_FILE, [], { strict: true });
return Array.isArray(raw) ? raw : [];
};
export const loadProjects = async () => {
- // Defend against a hand-edited / corrupted JSON state file. Without this,
- // a non-array root would crash every CRUD path with "x.findIndex is not a
- // function" instead of degrading gracefully to an empty list.
+ // The strict raw read rejects a corrupt or non-array root before any CRUD
+ // path can mistake it for an empty project library and write that fallback.
// Every read upgrades v1 (`clips`-only) projects to the v2 lane shape in
// memory, so the rest of the service only ever sees `segments`/`overlays`/
// `audio`. The on-disk upgrade is migration 296; this keeps a project the
diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.js
index aa9de755f8..59fd4a700c 100644
--- a/server/services/writersRoom/store.js
+++ b/server/services/writersRoom/store.js
@@ -51,7 +51,8 @@ import {
function makeFileBackend() {
const loadFolders = async () => {
await ensureDir(wrRoot());
- const raw = await readJSONFile(wrFoldersFile(), []);
+ // Folder metadata is durable user state, even on the test/escape-hatch backend.
+ const raw = await readJSONFile(wrFoldersFile(), [], { strict: true });
return Array.isArray(raw) ? raw : [];
};
const saveFolders = async (folders) => {
@@ -60,7 +61,8 @@ function makeFileBackend() {
};
const loadExercises = async () => {
await ensureDir(wrRoot());
- const raw = await readJSONFile(wrExercisesFile(), []);
+ // Exercise history must not be replaced by an empty fallback after a failed read.
+ const raw = await readJSONFile(wrExercisesFile(), [], { strict: true });
return Array.isArray(raw) ? raw : [];
};
const saveExercises = async (exercises) => {