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 pipeline sidecar stores (#6974)

[._.]/ Adam Eivy983d1f13edbb
diff --git a/server/services/askConversations.js b/server/services/askConversations.js
index ccfbca14bc..6769d3fbb3 100644
--- a/server/services/askConversations.js
+++ b/server/services/askConversations.js
@@ -70,7 +70,7 @@ function truncateTitle(text) {
}
async function readConversation(id) {
- const data = await readJSONFile(pathFor(id), null, { logError: false });
+ const data = await readJSONFile(pathFor(id), null, { logError: false, strict: true });
if (!data || typeof data !== 'object' || data.id !== id) return null;
return data;
}
diff --git a/server/services/bibleStore.js b/server/services/bibleStore.js
index d5ac7a5cdd..65f33309fb 100644
--- a/server/services/bibleStore.js
+++ b/server/services/bibleStore.js
@@ -57,7 +57,7 @@ export function createBibleStore(opts) {
async function load(workId) {
const fallback = { [listKey]: [], updatedAt: null };
- const parsed = await readJSONFile(filePath(workId), fallback);
+ const parsed = await readJSONFile(filePath(workId), fallback, { strict: true });
if (!parsed || !Array.isArray(parsed[listKey])) return fallback;
return { ...parsed, [listKey]: sanitizeBibleList(parsed[listKey], kind, { idPrefix }) };
}
diff --git a/server/services/creative/creativeRunLedger.js b/server/services/creative/creativeRunLedger.js
index 56a125a958..baf32ab214 100644
--- a/server/services/creative/creativeRunLedger.js
+++ b/server/services/creative/creativeRunLedger.js
@@ -79,7 +79,7 @@ export async function appendCreativeLedgerEntry(projectId, entry, { dir } = {})
const record = { at: new Date().toISOString(), ...entry };
await ledgerQueue(file, async () => {
await ensureDir(dir || DEFAULT_LEDGER_DIR);
- const existing = await readJSONFile(file, [], { logError: false });
+ const existing = await readJSONFile(file, [], { logError: false, strict: true });
const list = Array.isArray(existing) ? existing : [];
list.push(record);
const trimmed = list.length > MAX_LEDGER_ENTRIES ? list.slice(-MAX_LEDGER_ENTRIES) : list;
@@ -96,6 +96,6 @@ export async function appendCreativeLedgerEntry(projectId, entry, { dir } = {})
* @returns {Promise<Array<object>>}
*/
export async function readCreativeLedger(projectId, { dir } = {}) {
- const existing = await readJSONFile(fileFor(projectId, dir), [], { logError: false });
+ const existing = await readJSONFile(fileFor(projectId, dir), [], { logError: false, strict: true });
return Array.isArray(existing) ? existing : [];
}
diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.js
index 593a2152d2..cc5335c4b9 100644
--- a/server/services/pipeline/continuityBible.js
+++ b/server/services/pipeline/continuityBible.js
@@ -185,7 +185,7 @@ const emptyLedger = () => ({ schemaVersion: SCHEMA_VERSION, status: 'none', fact
async function readLedger(seriesId) {
// `null` = file absent (distinct from a present-but-empty ledger).
- const raw = await readJSONFile(ledgerPath(seriesId), null);
+ const raw = await readJSONFile(ledgerPath(seriesId), null, { strict: true });
if (raw == null || typeof raw !== 'object') return null;
return raw;
}
diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.js
index eb5b3c6889..1f49e4ebe9 100644
--- a/server/services/pipeline/editorialScore.js
+++ b/server/services/pipeline/editorialScore.js
@@ -332,7 +332,7 @@ function sanitizeLedger(raw, seriesId) {
}
async function readLedger(seriesId) {
- const raw = await readJSONFile(ledgerPath(seriesId), null);
+ const raw = await readJSONFile(ledgerPath(seriesId), null, { strict: true });
return raw == null ? emptyLedger(seriesId) : sanitizeLedger(raw, seriesId);
}
diff --git a/server/services/pipeline/manuscriptComments.js b/server/services/pipeline/manuscriptComments.js
index e15380e937..a758fe0c00 100644
--- a/server/services/pipeline/manuscriptComments.js
+++ b/server/services/pipeline/manuscriptComments.js
@@ -204,7 +204,7 @@ function sanitizeReview(raw) {
export async function readReview(seriesId) {
// `null` = file absent (distinct from a present-but-empty review).
- const raw = await readJSONFile(reviewPath(seriesId), null);
+ const raw = await readJSONFile(reviewPath(seriesId), null, { strict: true });
return raw == null ? emptyReview() : sanitizeReview(raw);
}
diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.js
index 0e25f3141b..cd386276c0 100644
--- a/server/services/pipeline/reverseOutline.js
+++ b/server/services/pipeline/reverseOutline.js
@@ -192,7 +192,7 @@ const emptyOutline = () => ({ schemaVersion: SCHEMA_VERSION, status: 'none', plo
async function readOutline(seriesId) {
// `null` = file absent (distinct from a present-but-empty outline).
- const raw = await readJSONFile(outlinePath(seriesId), null);
+ const raw = await readJSONFile(outlinePath(seriesId), null, { strict: true });
if (raw == null || typeof raw !== 'object') return null;
return raw;
}
diff --git a/server/services/projectFileStore.js b/server/services/projectFileStore.js
index 88ef3e4d0a..40a4a1cb22 100644
--- a/server/services/projectFileStore.js
+++ b/server/services/projectFileStore.js
@@ -16,7 +16,7 @@ export function createProjectFileStore({ file, kind, idPrefix, logEmoji, logLabe
const sync = makeSyncKind(kind);
async function loadAll() {
- const raw = await readJSONFile(file, []);
+ const raw = await readJSONFile(file, [], { strict: true });
return Array.isArray(raw) ? raw : [];
}
diff --git a/server/services/projectSidecarJsonWriteback.test.js b/server/services/projectSidecarJsonWriteback.test.js
new file mode 100644
index 0000000000..86f7dd4006
--- /dev/null
+++ b/server/services/projectSidecarJsonWriteback.test.js
@@ -0,0 +1,280 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { makePathsProxy, createTempDataRoot } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = createTempDataRoot('project-sidecar-writeback-');
+const readFault = vi.hoisted(() => ({ path: null }));
+
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (...args) => String(args[0]) === readFault.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 }));
+
+vi.mock('./sharing/recordEvents.js', () => ({ emitRecordUpdated: vi.fn() }));
+vi.mock('./pipeline/series.js', () => ({
+ seriesStore: () => ({ recordDir: (id) => join(TEST_DATA_ROOT, 'pipeline-series', id) }),
+ getSeries: vi.fn(async (id) => ({ id, name: 'Test series' })),
+ listSeries: vi.fn(async () => []),
+}));
+vi.mock('./pipeline/seriesCanon.js', () => ({
+ getSeriesCanon: vi.fn(async () => ({
+ characters: [{ id: 'char-existing', name: 'Mara', physicalDescription: 'Green eyes', locked: true }],
+ places: [],
+ objects: [],
+ })),
+}));
+vi.mock('./pipeline/arcPlanner.js', () => ({
+ collectManuscriptSections: vi.fn(async () => []),
+ sectionsCorpus: vi.fn(() => ''),
+ REPLACEMENT_STRATEGIES: new Set(['delta', 'full-page']),
+ replacementStrategyForCategory: (category) => category === 'comic-structure' ? 'full-page' : 'delta',
+}));
+vi.mock('./stageRunner.js', () => ({
+ runStagedLLM: vi.fn(),
+ resolveStageContext: vi.fn(),
+}));
+vi.mock('../lib/contextBudget.js', () => ({
+ manuscriptContentBudgetChars: vi.fn(() => 100_000),
+ estimateTokens: vi.fn(() => 0),
+}));
+vi.mock('./pipeline/manuscriptReview.js', () => ({
+ getReview: vi.fn(async () => ({ comments: [] })),
+}));
+
+const ask = await import('./askConversations.js');
+const characters = await import('./writersRoom/characters.js');
+const creativeLedger = await import('./creative/creativeRunLedger.js');
+const continuityBible = await import('./pipeline/continuityBible.js');
+const editorialScore = await import('./pipeline/editorialScore.js');
+const manuscriptComments = await import('./pipeline/manuscriptComments.js');
+const reverseOutline = await import('./pipeline/reverseOutline.js');
+const { createProjectFileStore } = await import('./projectFileStore.js');
+
+const ASK_ID = 'ask_000000001_deadbeef';
+const WORK_ID = 'wr-work-acde';
+const SERIES_ID = 'ser-sidecar';
+const NOW = '2026-09-11T00:00:00.000Z';
+
+const paths = {
+ ask: join(TEST_DATA_ROOT, 'ask-conversations', `${ASK_ID}.json`),
+ bible: join(TEST_DATA_ROOT, 'writers-room', 'works', WORK_ID, 'characters.json'),
+ creativeLedger: join(TEST_DATA_ROOT, 'creative-ledger', 'project-sidecar.json'),
+ continuityBible: join(TEST_DATA_ROOT, 'pipeline-series', SERIES_ID, 'continuity-bible.json'),
+ editorialScore: join(TEST_DATA_ROOT, 'pipeline-editorial-health', `${SERIES_ID}.json`),
+ manuscriptComments: join(TEST_DATA_ROOT, 'pipeline-series', SERIES_ID, 'manuscript-review.json'),
+ reverseOutline: join(TEST_DATA_ROOT, 'pipeline-series', SERIES_ID, 'reverse-outline.json'),
+ projectFileStore: join(TEST_DATA_ROOT, 'project-file-store.json'),
+};
+
+const projectStore = createProjectFileStore({
+ file: paths.projectFileStore,
+ kind: 'testProject',
+ idPrefix: 'test-project',
+ logEmoji: 'test',
+ logLabel: 'Test',
+ logic: {
+ buildProjectRecord: (input, { id, now }) => ({ id, name: input.name, createdAt: now, updatedAt: now }),
+ applyProjectPatch: (project, patch) => ({ ...project, ...patch }),
+ mergeProjectRecord: (local, remote) => ({ next: remote || local, inserted: !local, remoteWins: true, changed: true }),
+ },
+});
+
+const seedComment = (id = 'comment-existing') => ({
+ id,
+ problem: 'Existing finding',
+ status: 'open',
+ severity: 'medium',
+ createdAt: NOW,
+ updatedAt: NOW,
+});
+
+const durableStores = [
+ {
+ name: 'Ask conversation',
+ path: paths.ask,
+ seed: {
+ id: ASK_ID,
+ title: 'Existing conversation',
+ mode: 'ask',
+ createdAt: NOW,
+ updatedAt: NOW,
+ promoted: false,
+ turns: [{ id: 'turn-existing', role: 'user', content: 'Existing turn', createdAt: NOW }],
+ },
+ mutate: () => ask.appendTurn(ASK_ID, { role: 'assistant', content: 'New turn' }),
+ preserved: (data) => data.turns.some((turn) => turn.id === 'turn-existing'),
+ initialize: async () => {
+ const created = await ask.createConversation({ title: 'Initialized' });
+ return JSON.parse(readFileSync(ask.__test.pathFor(created.id), 'utf8')).title === 'Initialized';
+ },
+ },
+ {
+ name: 'writers-room bible',
+ path: paths.bible,
+ seed: {
+ characters: [{ id: 'wr-char-acde', name: 'Existing character', source: 'user', createdAt: NOW, updatedAt: NOW }],
+ updatedAt: NOW,
+ },
+ mutate: () => characters.createCharacter(WORK_ID, { name: 'New character' }),
+ preserved: (data) => data.characters.some((character) => character.id === 'wr-char-acde'),
+ initialize: async () => {
+ await characters.createCharacter(WORK_ID, { name: 'Initialized character' });
+ return JSON.parse(readFileSync(paths.bible, 'utf8')).characters[0].name === 'Initialized character';
+ },
+ },
+ {
+ name: 'creative run ledger',
+ path: paths.creativeLedger,
+ seed: [{ tool: 'existing.tool', outcome: 'executed', at: NOW }],
+ mutate: () => creativeLedger.appendCreativeLedgerEntry(
+ 'project-sidecar',
+ { tool: 'new.tool', outcome: 'planned' },
+ { dir: dirname(paths.creativeLedger) },
+ ),
+ preserved: (data) => data.some((entry) => entry.tool === 'existing.tool'),
+ initialize: async () => {
+ await creativeLedger.appendCreativeLedgerEntry(
+ 'project-sidecar',
+ { tool: 'initialized.tool', outcome: 'executed' },
+ { dir: dirname(paths.creativeLedger) },
+ );
+ return JSON.parse(readFileSync(paths.creativeLedger, 'utf8'))[0].tool === 'initialized.tool';
+ },
+ },
+ {
+ name: 'editorial trend ledger',
+ path: paths.editorialScore,
+ seed: {
+ schemaVersion: 1,
+ seriesId: SERIES_ID,
+ snapshots: [{ runId: 'existing-run', at: NOW, score: 95, ready: true, open: 1, openBySeverity: { high: 0, medium: 1, low: 0 }, openByCategory: { pacing: 1 } }],
+ },
+ mutate: () => editorialScore.recordTrendSnapshot(SERIES_ID, { runId: 'new-run', comments: [] }),
+ preserved: (data) => data.snapshots.some((snapshot) => snapshot.runId === 'existing-run'),
+ initialize: async () => {
+ await editorialScore.recordTrendSnapshot(SERIES_ID, { runId: 'initialized-run', comments: [] });
+ return JSON.parse(readFileSync(paths.editorialScore, 'utf8')).snapshots[0].runId === 'initialized-run';
+ },
+ },
+ {
+ name: 'manuscript review',
+ path: paths.manuscriptComments,
+ seed: { schemaVersion: 1, comments: [seedComment()] },
+ mutate: () => manuscriptComments.mergeReviewFromSync(SERIES_ID, {
+ schemaVersion: 1,
+ comments: [seedComment('comment-new')],
+ }),
+ preserved: (data) => data.comments.some((comment) => comment.id === 'comment-existing'),
+ initialize: async () => {
+ await manuscriptComments.mergeReviewFromSync(SERIES_ID, {
+ schemaVersion: 1,
+ comments: [seedComment('comment-initialized')],
+ });
+ return JSON.parse(readFileSync(paths.manuscriptComments, 'utf8')).comments[0].id === 'comment-initialized';
+ },
+ },
+ {
+ name: 'generic project file store',
+ path: paths.projectFileStore,
+ seed: [{ id: 'project-existing', name: 'Existing project', createdAt: NOW, updatedAt: NOW }],
+ mutate: () => projectStore.createProject({ name: 'New project' }),
+ preserved: (data) => data.some((project) => project.id === 'project-existing'),
+ initialize: async () => {
+ await projectStore.createProject({ name: 'Initialized project' });
+ return JSON.parse(readFileSync(paths.projectFileStore, 'utf8'))[0].name === 'Initialized project';
+ },
+ },
+];
+
+const generatedSidecars = [
+ {
+ name: 'continuity bible',
+ path: paths.continuityBible,
+ repair: { schemaVersion: 1, seriesId: SERIES_ID, status: 'none', facts: [] },
+ mutate: () => continuityBible.generateContinuityBible(SERIES_ID, { force: true }),
+ initialized: (data) => data.status === 'complete' && data.facts.some((fact) => fact.subject === 'Mara'),
+ },
+ {
+ name: 'reverse outline',
+ path: paths.reverseOutline,
+ repair: { schemaVersion: 1, seriesId: SERIES_ID, status: 'complete', generatedAt: '2026-09-10T00:00:00.000Z', plotlines: [], scenes: [] },
+ mutate: () => reverseOutline.mergeOutlineFromSync(SERIES_ID, {
+ schemaVersion: 1,
+ status: 'complete',
+ generatedAt: '2026-09-11T00:00:00.000Z',
+ plotlines: [],
+ scenes: [],
+ }),
+ initialized: (data) => data.generatedAt === '2026-09-11T00:00:00.000Z',
+ },
+];
+
+beforeEach(() => {
+ readFault.path = null;
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+});
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe.each(durableStores)('$name durable write-back', (store) => {
+ it.each(['{"truncated":', ''])('preserves unreadable bytes (%j), then retries without losing valid records', async (bytes) => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ writeFileSync(store.path, bytes);
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+
+ writeFileSync(store.path, JSON.stringify(store.seed));
+ await store.mutate();
+ expect(store.preserved(JSON.parse(readFileSync(store.path, 'utf8')))).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);
+ readFault.path = store.path;
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+ });
+
+ it('initializes an absent file through its creation boundary', async () => {
+ expect(await store.initialize()).toBe(true);
+ });
+});
+
+describe.each(generatedSidecars)('$name generated sidecar', (store) => {
+ it.each(['{"truncated":', ''])('refuses to rebuild over unreadable bytes (%j) and retries after repair', async (bytes) => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ writeFileSync(store.path, bytes);
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+
+ writeFileSync(store.path, JSON.stringify(store.repair));
+ await store.mutate();
+ expect(store.initialized(JSON.parse(readFileSync(store.path, 'utf8')))).toBe(true);
+ });
+
+ it('preserves existing bytes on an injected filesystem read failure', async () => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ const bytes = JSON.stringify(store.repair);
+ writeFileSync(store.path, bytes);
+ readFault.path = store.path;
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+ });
+
+ it('initializes an absent file through the rebuild boundary', async () => {
+ await store.mutate();
+ expect(store.initialized(JSON.parse(readFileSync(store.path, 'utf8')))).toBe(true);
+ });
+});