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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: isolate bible sync failures and serialize incoming writes (#6943)
[._.]/ Adam Eivy1bf7dccf5066
diff --git a/server/services/assetMounts.js b/server/services/assetMounts.jsindex 29ca3a1d94..8e3b94e341 100644--- a/server/services/assetMounts.js+++ b/server/services/assetMounts.js@@ -19,7 +19,7 @@ import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';import { ServerError, sendErrorResponse } from '../lib/errorHandler.js';import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePrefixes.js';-import { wrWorksDir } from './writersRoom/_shared.js';+import { wrWorksDir, WORK_ID_RE } from './writersRoom/_shared.js';import { escapeRegExp } from '../lib/textUtils.js';// `acceptRanges: true` is the serve-static default already, but we set it@@ -51,7 +51,8 @@ const CLIENT_ASSET_STATIC_OPTS = { immutable: true, maxAge: IMMUTABLE_MAX_AGE_MS// Metadata/import backups and regenerable analysis snapshots stay inaccessible.const writersRoomAssetsOnly = (req, res, next) => {const draft = /^\/[^/]+\/drafts\/[^/]+\.md$/.test(req.path);- const bible = /^\/wr-work-[0-9a-f-]+\/(characters|places|objects)\.json$/i.test(req.path);+ const bibleMatch = /^\/([^/]+)\/(characters|places|objects)\.json$/.exec(req.path);+ const bible = bibleMatch && WORK_ID_RE.test(bibleMatch[1]);if (!draft && !bible) return res.status(404).end();next();};diff --git a/server/services/bibleStore.js b/server/services/bibleStore.jsindex e91798ce64..454d6a7ca6 100644--- a/server/services/bibleStore.js+++ b/server/services/bibleStore.js@@ -9,10 +9,11 @@* directly from here, and the pure sanitizer names from lib/storyBible.js.*/-import { emitRecordUpdated } from './sharing/recordEvents.js';import { randomUUID } from 'crypto';import { join } from 'path';import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { emitRecordUpdated } from './sharing/recordEvents.js';+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { ServerError } from '../lib/errorHandler.js';import {SANITIZERS,@@ -22,6 +23,9 @@ import {mergeExtractedBible,} from '../lib/storyBible.js';+// Shared with peer bible commits: a local save and an incoming file cannot interleave.+export const withBibleWrite = createKeyCachedQueue();+const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;const ID_SUFFIX_RE = /^[0-9a-f-]+$/i;const FILE_NAME = Object.freeze({ character: 'characters.json', place: 'places.json', object: 'objects.json' });@@ -60,7 +64,7 @@ export function createBibleStore(opts) {async function save(workId, state) {await ensureDir(wrDir(workId));- await atomicWrite(filePath(workId), { ...state, updatedAt: nowIso() });+ await withBibleWrite(filePath(workId), () => atomicWrite(filePath(workId), { ...state, updatedAt: nowIso() }));emitRecordUpdated('writersRoomWork', workId);}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex aebcf5c6d4..317645b4bb 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -4445,6 +4445,13 @@ describe('peerSync', () => {await writeFile(file, JSON.stringify({ characters: [{ name: 'New cast member' }], updatedAt: '2026-06-03T00:00:00Z' }));expect((await pushRecordToPeer(await refresh(carrier))).pushed).toBe(true);expect(payloadOf(vi.mocked(peerFetch).mock.calls[0]).bibleManifest).toHaveLength(1);+ // A corrupt optional sibling must not hold the work and its prose hostage.+ vi.mocked(peerFetch).mockClear();+ await writeFile(file, '{');+ expect((await pushRecordToPeer(await refresh(carrier))).pushed).toBe(true);+ const withoutBible = payloadOf(vi.mocked(peerFetch).mock.calls[0]);+ expect(withoutBible.record.id).toBe(carrier.recordId);+ expect(withoutBible).not.toHaveProperty('bibleManifest');});it('pins the wire vocabulary older peers depend on', () => {@@ -4628,11 +4635,11 @@ describe('peerSync', () => {// No peer fetch in this test: diff returns a pending target with no registered peer.vi.mocked(diffWorkBibleManifest).mockResolvedValueOnce([own]);const result = await applyIncomingPush(payload);- expect(vi.mocked(diffWorkBibleManifest)).toHaveBeenLastCalledWith([own]);+ expect(vi.mocked(diffWorkBibleManifest)).toHaveBeenLastCalledWith([own], expect.any(Object));expect(result.bibleSyncPending).toBe(true);payload.bibleManifest = undefined;await applyIncomingPush(payload);- expect(vi.mocked(diffWorkBibleManifest)).toHaveBeenLastCalledWith([]);+ expect(vi.mocked(diffWorkBibleManifest)).toHaveBeenLastCalledWith([], expect.any(Object));});it('has a receiver-side carrier for every sidecar row', () => {diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex fc2cfb5ca8..9703dac677 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -463,9 +463,12 @@ export async function applyIncomingPush(payload) {: [];missingDraftBodies = await diffWorkBodyManifest(ownBodies, { includeMismatched: workMergeApplied });const ownBibles = Array.isArray(bibleManifest) ? bibleManifest.filter((e) => e?.workId === record.id) : [];- const missingBibles = await diffWorkBibleManifest(ownBibles).catch((err) => {+ const bibleDiffFailed = (err) => {pending.add('bibleSyncPending');console.error(`❌ peerSync: bible diff failed: ${err.message}`);+ };+ const missingBibles = await diffWorkBibleManifest(ownBibles, { onError: bibleDiffFailed }).catch((err) => {+ bibleDiffFailed(err);return [];});if (missingBibles.length) {diff --git a/server/services/writersRoom/bibleSync.js b/server/services/writersRoom/bibleSync.jsindex 31794b83fc..79ea0a1e26 100644--- a/server/services/writersRoom/bibleSync.js+++ b/server/services/writersRoom/bibleSync.js@@ -1,4 +1,6 @@/** File-primary Writers Room bibles: optional peer assets, independent LWW per file. */+import { z } from 'zod';+import { withBibleWrite } from '../bibleStore.js';import { readFile } from 'fs/promises';import { createHash } from 'crypto';import { join } from 'path';@@ -14,7 +16,8 @@ export const BIBLE_CONFLICT_KINDS = Object.freeze({ character: 'writersRoomCharaconst hash = (bytes) => createHash('sha256').update(bytes).digest('hex');const validTarget = (workId, kind) => typeof workId === 'string' && WORK_ID_RE.test(workId) && Object.hasOwn(BIBLE_FILES, kind);export const workBiblePath = (workId, kind) => validTarget(workId, kind) ? join(wrWorkDir(workId), `${BIBLE_FILES[kind]}.json`) : null;-const validDoc = (doc, kind) => isPlainObject(doc) && Array.isArray(doc[BIBLE_FILES[kind]]) && typeof doc.updatedAt === 'string' && Number.isFinite(Date.parse(doc.updatedAt));+const timestampSchema = z.string().datetime({ offset: true });+const validDoc = (doc, kind) => isPlainObject(doc) && Array.isArray(doc[BIBLE_FILES[kind]]) && timestampSchema.safeParse(doc.updatedAt).success;const parseDoc = (bytes, kind) => {const doc = JSON.parse(bytes.toString('utf8'));if (!validDoc(doc, kind)) throw new Error('Invalid Writers Room bible document');@@ -29,21 +32,30 @@ export async function buildWorkBibleManifest(work) {if (!WORK_ID_RE.test(work?.id || '') || work.deleted) return [];const manifest = [];for (const kind of Object.keys(BIBLE_FILES)) {- const bytes = await readBytes(workBiblePath(work.id, kind));- if (!bytes) continue;- const doc = parseDoc(bytes, kind);- manifest.push({ workId: work.id, kind, sha256: hash(bytes), updatedAt: doc.updatedAt });+ const entry = await readBibleManifestEntry(work.id, kind).catch((err) => {+ console.error(`❌ Writers Room ${kind} bible unavailable for sync: ${err.message}`);+ return null; // omission cannot delete the receiver's file; other assets still ship+ });+ if (entry) manifest.push(entry);}return manifest;}-export async function diffWorkBibleManifest(manifest) {+async function readBibleManifestEntry(workId, kind) {+ const bytes = await readBytes(workBiblePath(workId, kind));+ if (!bytes) return null;+ const doc = parseDoc(bytes, kind);+ return { workId, kind, sha256: hash(bytes), updatedAt: doc.updatedAt };+}++export async function diffWorkBibleManifest(manifest, { onError = (err) => { throw err; } } = {}) {const missing = [];for (const entry of Array.isArray(manifest) ? manifest : []) {if (!validTarget(entry?.workId, entry?.kind) || !/^[a-f0-9]{64}$/i.test(entry.sha256 || '') || !Number.isFinite(Date.parse(entry.updatedAt))) continue;const { workId, kind, sha256, updatedAt } = entry;- const bytes = await readBytes(workBiblePath(workId, kind));- if (!bytes || (hash(bytes) !== sha256 && compareNewerWins(updatedAt, parseDoc(bytes, kind).updatedAt))) {+ const local = await readBibleManifestEntry(workId, kind).catch((err) => { onError(err); return false; });+ if (local === false) continue; // unreadable incumbent stays intact; process the other files+ if (!local || (local.sha256 !== sha256 && compareNewerWins(updatedAt, local.updatedAt))) {missing.push({ workId, kind, sha256, updatedAt });}}@@ -54,6 +66,10 @@ export async function diffWorkBibleManifest(manifest) {export async function applyWorkBibleBytes(entry, bytes, source) {const path = workBiblePath(entry?.workId, entry?.kind);if (!path || hash(bytes) !== entry.sha256) return false;+ return withBibleWrite(path, () => commitWorkBible(entry, bytes, source, path));+}++async function commitWorkBible(entry, bytes, source, path) {const remote = parseDoc(bytes, entry.kind);if (remote.updatedAt !== entry.updatedAt) return false;const localBytes = await readBytes(path);@@ -65,9 +81,6 @@ export async function applyWorkBibleBytes(entry, bytes, source) {// Unlike record merges, file assets have no shared base: archive every replacement.await journalConflict({ kind: BIBLE_CONFLICT_KINDS[entry.kind], id: entry.workId, local, remote, source,hashes: { localHash: hash(localBytes), remoteHash: entry.sha256 } });- // Journal I/O may overlap another local edit; never overwrite moved bytes.- const current = await readBytes(path);- if (!current || hash(current) !== hash(localBytes)) return false;}await atomicWrite(path, bytes);emitRecordUpdated('writersRoomWork', entry.workId);@@ -81,8 +94,10 @@ export async function restoreWorkBible(workId, kind, patch) {const { getWorkForSync } = await import('./sync.js');const work = await getWorkForSync(workId);if (!work || work.deleted) throw Object.assign(new Error('Work not found'), { code: 'NOT_FOUND' });- const bytes = await readBytes(path);- const local = bytes ? parseDoc(bytes, kind) : {};- await atomicWrite(path, { ...local, ...patch, updatedAt: new Date().toISOString() });+ await withBibleWrite(path, async () => {+ const bytes = await readBytes(path);+ const local = bytes ? parseDoc(bytes, kind) : {};+ await atomicWrite(path, { ...local, ...patch, updatedAt: new Date().toISOString() });+ });emitRecordUpdated('writersRoomWork', workId);}diff --git a/server/services/writersRoom/bibleSync.test.js b/server/services/writersRoom/bibleSync.test.jsindex a41f560bb0..44851f2e23 100644--- a/server/services/writersRoom/bibleSync.test.js+++ b/server/services/writersRoom/bibleSync.test.js@@ -101,7 +101,13 @@ describe('bible asset delivery', () => {expect(await diffWorkBibleManifest([{ ...manifest[0], workId: '../other' }, { ...manifest[0], kind: 'analysis' }])).toEqual([]);writeFileSync(workBiblePath(WORK, 'character'), '{');await expect(diffWorkBibleManifest(manifest)).rejects.toThrow();- await expect(buildWorkBibleManifest({ id: WORK })).rejects.toThrow();+ expect(await buildWorkBibleManifest({ id: WORK })).toEqual([]);expect(readFileSync(workBiblePath(WORK, 'character'), 'utf8')).toBe('{');+ const errors = [];+ const place = { workId: WORK, kind: 'place', sha256: 'c'.repeat(64), updatedAt: remote.updatedAt };+ expect(await diffWorkBibleManifest([...manifest, place], { onError: (err) => errors.push(err) })).toEqual([place]);+ expect(errors).toHaveLength(1);+ write('character', doc('2026-02-01'));+ expect(await buildWorkBibleManifest({ id: WORK })).toEqual([]);});});