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 sharing and backup records after unreadable reads (#6975)

[._.]/ Adam Eivy5a7da75fdb21
diff --git a/server/services/backup.js b/server/services/backup.js
index f3ad7f2c06..dc103410ef 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -684,6 +684,7 @@ export async function listSnapshots(destPath) {
const manifestPath = join(snapshotDir, 'manifest.json');
// logError:false — a snapshot taken before manifests existed legitimately
// has none; the null is handled below, so it isn't worth a warning per list.
+ // Read-only listing metadata; generateManifest rebuilds from snapshot bytes.
const manifest = await readJSONFile(manifestPath, null, { logError: false });
// Report a still-being-written snapshot rather than hiding it: the row is
// real and the user should see the run in flight, but download and restore
@@ -882,6 +883,8 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
// proceed rather than hard-failing. Only a manifest that IS present AND
// carries a mismatching hash refuses the restore.
const manifestPath = join(snapshotDir, 'manifest.json');
+ // Read-only verification metadata; preserve the legacy no-manifest behavior
+ // below. This path never writes the manifest back.
const manifest = await readJSONFile(manifestPath, null);
const expectedHash = manifest?.files?.['../portos-db.sql'];
if (expectedHash) {
@@ -963,7 +966,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
* Get current backup state from disk.
*/
export async function getState() {
- return readJSONFile(STATE_PATH, DEFAULT_STATE);
+ return readJSONFile(STATE_PATH, DEFAULT_STATE, { strict: true });
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 3d52ce373a..825cd4deef 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1334,7 +1334,7 @@ describe('getState and saveState', () => {
expect(await backup.getState()).toEqual(DEFAULTS);
});
- it('returns the default state when state.json holds invalid JSON', async () => {
+ it('rejects unreadable state instead of returning a saveable default', async () => {
const { mkdir, writeFile } = await import('fs/promises');
const { join } = await import('path');
await mkdir(join(tmpRoot, 'backup'), { recursive: true });
@@ -1342,7 +1342,7 @@ describe('getState and saveState', () => {
await writeFile(join(tmpRoot, 'backup', 'state.json'), '{"status":"ok","filesChanged":');
vi.spyOn(console, 'warn').mockImplementation(() => {});
- expect(await backup.getState()).toEqual(DEFAULTS);
+ await expect(backup.getState()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });
});
it('merges a patch into existing state and persists it to disk', async () => {
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index c09af79207..ac6bdd1a7f 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -176,12 +176,12 @@ function mergeObjectLWW(local, remote, timestampField = 'updatedAt') {
// --- Category: Goals ---
async function getGoalsSnapshot() {
- const data = await readJSONFile(GOALS_FILE, { goals: [] });
+ const data = await readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });
return { data, checksum: computeChecksum(data) };
}
async function applyGoalsRemote(remoteData) {
- const local = await readJSONFile(GOALS_FILE, { goals: [] });
+ const local = await readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });
// Merge goals array by ID with LWW on updatedAt
const { merged: mergedGoals, changed: goalsChanged } = mergeArraysByKey(
@@ -226,7 +226,7 @@ async function getCharacterSnapshot() {
async function applyCharacterRemote(remoteData) {
if (!remoteData) return { applied: false, count: 0 };
- const local = await readJSONFile(CHARACTER_FILE, null);
+ const local = await readJSONFile(CHARACTER_FILE, null, { strict: true });
if (!local) {
// No local character — accept remote entirely, but strip every derived field (an older
// peer still sends `level`): they're derived on read now (#2673/#2674), so a stored value
@@ -294,6 +294,7 @@ async function getMeatspaceSnapshot() {
// The files are independent — read them in parallel rather than one-at-a-time
// (this snapshot runs on every ~60s sync poll).
const contents = await Promise.all(
+ // Snapshot-only projection; the merge path reads its local inputs strictly.
filenames.map((filename) => readJSONFile(join(MEATSPACE_DIR, filename), null)),
);
const result = {};
@@ -310,7 +311,7 @@ async function applyMeatspaceRemote(remoteData) {
if (!remoteFile) continue;
const filePath = join(MEATSPACE_DIR, filename);
- const local = await readJSONFile(filePath, null);
+ const local = await readJSONFile(filePath, null, { strict: true });
if (config.type === 'object-lww') {
const { merged, changed } = mergeObjectLWW(local, remoteFile, 'updatedAt');
diff --git a/server/services/peerUsage.js b/server/services/peerUsage.js
index 456f3abcaa..7704b60a98 100644
--- a/server/services/peerUsage.js
+++ b/server/services/peerUsage.js
@@ -158,9 +158,9 @@ async function readSelfIdentity() {
}
async function readStore() {
- // Non-strict: this file is entirely derived, replicated state. A corrupt read
- // self-heals on the next sync cycle, which beats throwing on every poll.
- const raw = await readJSONFile(PEER_USAGE_FILE, null);
+ // Retirements are durable tombstones: peers cannot rebuild a deletion that
+ // has not propagated yet. Never replace an unreadable store with a new digest.
+ const raw = await readJSONFile(PEER_USAGE_FILE, null, { strict: true });
return {
instances: isPlainObject(raw?.instances) ? raw.instances : {},
tombstones: normalizeTombstones(raw?.tombstones, 'instanceId'),
diff --git a/server/services/providerQuotaShare.js b/server/services/providerQuotaShare.js
index 19dd4f3c1e..cf8cf05a62 100644
--- a/server/services/providerQuotaShare.js
+++ b/server/services/providerQuotaShare.js
@@ -26,6 +26,7 @@ const withLock = createMutex();
/** The cards this instance last read, newest-known per family. Never throws. */
export async function readLocalQuotaCards() {
+ // Read-only projection; this fallback is never used by the merge writer below.
const raw = await readJSONFile(PROVIDER_QUOTAS_FILE, null);
const quotas = sanitizeQuotaCards(isPlainObject(raw) ? raw.quotas : null);
return { quotas, capturedAt: latestFetchedAt(quotas) };
@@ -57,7 +58,7 @@ export async function recordLocalQuotaCards(cards) {
const incoming = sanitizeQuotaCards(cards);
if (!incoming.length) return null;
return withLock(async () => {
- const raw = await readJSONFile(PROVIDER_QUOTAS_FILE, null);
+ const raw = await readJSONFile(PROVIDER_QUOTAS_FILE, null, { strict: true });
const stored = sanitizeQuotaCards(isPlainObject(raw) ? raw.quotas : null);
const byFamily = new Map(stored.map((card) => [card.family, card]));
let changed = false;
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.js
index cdd65ca940..cd3cd3f1d7 100644
--- a/server/services/sharing/annotationsSync.js
+++ b/server/services/sharing/annotationsSync.js
@@ -148,7 +148,7 @@ export async function exportAnnotationsToBucket(bucket, localAnnotations, sender
// file, so a key dropped from bucket A doesn't tombstone the same key on
// bucket B (it may still be valid there).
const tombstoneTs = new Date().toISOString();
- const prior = await readJSONFile(recordPath, null, { logError: false });
+ const prior = await readJSONFile(recordPath, null, { logError: false, strict: true });
const priorKeys = prior && prior.annotations && typeof prior.annotations === 'object'
? Object.keys(prior.annotations)
: [];
diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.js
index 73005aeccb..4305745378 100644
--- a/server/services/sharing/buckets.js
+++ b/server/services/sharing/buckets.js
@@ -48,7 +48,7 @@ const sanitizeBucket = (raw) => {
async function readRegistry() {
await ensureDir(join(PATHS.data, 'sharing'));
- const raw = await readJSONFile(REGISTRY_PATH(), { buckets: [] }, { logError: false });
+ const raw = await readJSONFile(REGISTRY_PATH(), { buckets: [] }, { logError: false, strict: true });
const buckets = Array.isArray(raw.buckets) ? raw.buckets.map(sanitizeBucket).filter(Boolean) : [];
return { buckets };
}
@@ -150,7 +150,7 @@ export async function ensureBucketLayout(bucket) {
await ensureDir(join(base, 'assets', 'videos'));
await ensureDir(join(base, 'assets', 'blobs'));
const bucketJsonPath = join(base, 'bucket.json');
- const existing = await readJSONFile(bucketJsonPath, null, { logError: false });
+ const existing = await readJSONFile(bucketJsonPath, null, { logError: false, strict: true });
if (!existing) {
// bucket.json is the shared identity. Stamp the schema version at
// creation time so peers can tell at a glance which protocol the bucket
@@ -170,6 +170,7 @@ export async function ensureBucketLayout(bucket) {
/** Read the on-disk bucket.json so routes/UI can report producedBy + schema info. */
export async function readBucketJson(bucket) {
const bucketJsonPath = join(bucket.path, 'bucket.json');
+ // Read-only UI metadata; ensureBucketLayout uses its own strict creation guard.
return readJSONFile(bucketJsonPath, null, { logError: false });
}
@@ -210,8 +211,9 @@ export async function createBucket(input = {}) {
updatedAt: now,
});
state.buckets.push(bucket);
- await writeRegistry(state);
+ // Validate/read the shared identity before publishing the local registration.
await ensureBucketLayout(bucket);
+ await writeRegistry(state);
return bucket;
}
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index f6cc5cfc26..b053faf488 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -94,6 +94,8 @@ const ASSET_SOURCE_DIRS = Object.freeze({
* same hash since the hash derives from bytes and the key embeds mtime+size.
*/
async function loadAssetHashCache(bucketPath) {
+ // Rebuildable cache only: a miss hashes/copies the authoritative source bytes;
+ // the index owns no records, memberships, or deletion history.
const raw = await readJSONFile(bucketBlobIndexPath(bucketPath), {}, { logError: false });
return isPlainObject(raw) ? raw : {};
}
@@ -174,6 +176,7 @@ async function jobFromSidecar(jobId) {
if (typeof jobId !== 'string' || !jobId) return null;
if (basename(jobId) !== jobId) return null;
if (jobId.includes('/') || jobId.includes('\\') || jobId.includes('..')) return null;
+ // Input-only image metadata: copied into a new export, never written back here.
const sc = await readJSONFile(join(PATHS.images, `${jobId}.metadata.json`));
if (!sc) return null;
// Sidecar schema differs between paths:
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 5eac0213ad..1231fffe8f 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -68,7 +68,7 @@ const inboxPath = (bucketId) => join(PATHS.data, 'sharing', 'inbox', `${bucketId
async function readInbox(bucketId) {
await ensureDir(join(PATHS.data, 'sharing', 'inbox'));
- return readJSONFile(inboxPath(bucketId), { items: [] }, { logError: false });
+ return readJSONFile(inboxPath(bucketId), { items: [] }, { logError: false, strict: true });
}
async function writeInbox(bucketId, inbox) {
@@ -318,6 +318,7 @@ async function processAnnotationManifest(bucket, manifest) {
if (!recordId) return { applied: 0, missing: true, reason: 'no-record-id' };
if (!isSafeRecordId(recordId)) return { applied: 0, missing: true, reason: 'bad-record-id' };
const recordPath = bucketRecordPath(bucket.path, 'media-annotations', recordId);
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const record = await readJSONFile(recordPath, null, { logError: false });
if (!record) return { applied: 0, missing: true, reason: 'record-not-synced' };
// record.instanceId is the source-of-truth for the author; fall back to the
@@ -340,11 +341,12 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
if (!existsSync(mediaDir)) return;
const persistedPath = join(PATHS.data, 'media-jobs.json');
const [persisted, incoming] = await Promise.all([
- readJSONFile(persistedPath, { jobs: [] }, { logError: false }),
+ readJSONFile(persistedPath, { jobs: [] }, { logError: false, strict: true }),
Promise.all((recordIds || []).map(async (id) => {
if (!isSafeRecordId(id)) return null;
const recordPath = bucketRecordPath(bucketPath, 'media', id);
if (!existsSync(recordPath)) return null;
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
return readJSONFile(recordPath, null, { logError: false });
})),
]);
@@ -377,6 +379,7 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
async function missingDeclaredReviews(bucketPath, manifest) {
const refs = (Array.isArray(manifest.reviewRefs) ? manifest.reviewRefs : []).filter(isSafeRecordId);
const checks = await Promise.all(refs.map(async (sid) => {
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const r = await readJSONFile(bucketRecordPath(bucketPath, 'reviews', sid), null, { logError: false });
return r == null ? sid : null;
}));
@@ -391,6 +394,7 @@ async function missingDeclaredReviews(bucketPath, manifest) {
async function missingDeclaredOutlines(bucketPath, manifest) {
const refs = (Array.isArray(manifest.outlineRefs) ? manifest.outlineRefs : []).filter(isSafeRecordId);
const checks = await Promise.all(refs.map(async (sid) => {
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const r = await readJSONFile(bucketRecordPath(bucketPath, 'outlines', sid), null, { logError: false });
return r == null ? sid : null;
}));
@@ -403,10 +407,12 @@ async function readReferencedRecords(bucketPath, manifest) {
const resolveOne = async (id) => {
if (!isSafeRecordId(id)) return { kind: 'missing', id };
if (id.startsWith('ser-')) {
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const r = await readJSONFile(bucketRecordPath(bucketPath, 'series', id), null, { logError: false });
return r ? { kind: 'series', record: r } : { kind: 'missing', id };
}
if (id.startsWith('iss-')) {
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const r = await readJSONFile(bucketRecordPath(bucketPath, 'issues', id), null, { logError: false });
return r ? { kind: 'issues', record: r } : { kind: 'missing', id };
}
@@ -415,8 +421,10 @@ async function readReferencedRecords(bucketPath, manifest) {
return { kind: 'skip' };
}
// UUID-only — could be a universe or a media job. Try both.
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const uni = await readJSONFile(bucketRecordPath(bucketPath, 'universes', id), null, { logError: false });
if (uni) return { kind: 'universes', record: uni };
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const med = await readJSONFile(bucketRecordPath(bucketPath, 'media', id), null, { logError: false });
if (med) return { kind: 'media', record: med };
return { kind: 'missing', id };
@@ -707,6 +715,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const reviewMergeFailures = [];
for (const s of records.series) {
if (skipSeriesMerge.has(s.id) || !declaredReviews.has(s.id)) continue;
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const review = await readJSONFile(bucketRecordPath(bucket.path, 'reviews', s.id), null, { logError: false });
if (review) {
await mergeReviewFromSync(s.id, review).catch((err) => {
@@ -727,6 +736,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const outlineMergeFailures = [];
for (const s of records.series) {
if (skipSeriesMerge.has(s.id) || !declaredOutlines.has(s.id)) continue;
+ // Input-only bucket record: unreadable data is skipped/deferred, never written back here.
const outline = await readJSONFile(bucketRecordPath(bucket.path, 'outlines', s.id), null, { logError: false });
if (outline) {
await mergeOutlineFromSync(s.id, outline).catch((err) => {
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 8306f2c39a..639d51faf5 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -59,7 +59,7 @@ const cursorPath = (bucketId) => join(PATHS.data, 'sharing', 'cursors', `${bucke
*/
export async function readCursor(bucketId) {
await ensureDir(join(PATHS.data, 'sharing', 'cursors'));
- const raw = await readJSONFile(cursorPath(bucketId), { processedById: {}, processed: [] }, { logError: false });
+ const raw = await readJSONFile(cursorPath(bucketId), { processedById: {}, processed: [] }, { logError: false, strict: true });
return {
processedById: (raw.processedById && typeof raw.processedById === 'object') ? raw.processedById : {},
processed: Array.isArray(raw.processed) ? raw.processed : [],
@@ -287,6 +287,8 @@ export async function writeManifest(bucketPath, manifest) {
}
export async function readManifest(bucketPath, filename) {
+ // Input-only transport document: unreadable manifests are skipped/deferred,
+ // never merged back here. Exports rebuild manifests from authoritative records.
return readJSONFile(join(bucketPath, 'manifests', filename), null, { logError: false });
}
diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.js
index 171a7d0cbc..759ebf98a3 100644
--- a/server/services/sharing/subscriptions.js
+++ b/server/services/sharing/subscriptions.js
@@ -61,7 +61,7 @@ function subId({ bucketId, recordKind, recordId }) {
async function readState() {
await ensureDir(join(PATHS.data, 'sharing'));
- const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false });
+ const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false, strict: true });
const subs = Array.isArray(raw.subscriptions) ? raw.subscriptions : [];
return { subscriptions: subs };
}
@@ -217,6 +217,7 @@ export async function unsubscribe(id) {
const legacyName = legacySubscriptionFilename(sub);
const legacyPath = join(bucket.path, 'manifests', legacyName);
if (existsSync(legacyPath) && isStr(myInstanceId)) {
+ // Read-only ownership check before unlink; never saves a fallback document.
const legacy = await readJSONFile(legacyPath, null, { logError: false });
if (legacy && legacy.senderInstanceId === myInstanceId) {
await unlink(legacyPath).catch((err) => {
diff --git a/server/services/sharingDurability.test.js b/server/services/sharingDurability.test.js
new file mode 100644
index 0000000000..b189589961
--- /dev/null
+++ b/server/services/sharingDurability.test.js
@@ -0,0 +1,137 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdir, readFile, writeFile, rm } from 'fs/promises';
+import { dirname, join } from 'path';
+import { mockPathsDataRoot, mockNoPeers, mockNoPeerSync, mockTestIdentity } from '../lib/mockPathsDataRoot.js';
+
+// Keep the real parser/writer; inject an OS fault only for the targeted file.
+const faults = vi.hoisted(() => new Map());
+vi.mock('fs/promises', async (original) => {
+ const actual = await original();
+ return { ...actual, readFile: (...args) => faults.has(args[0])
+ ? Promise.reject(Object.assign(new Error('injected read fault'), { code: faults.get(args[0]) }))
+ : actual.readFile(...args) };
+});
+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-sharing-durability-' });
+vi.mock('../lib/fileUtils.js', async (original) => new Proxy(makeProxy(await original()), {
+ get: (target, key) => key === 'dataPath' ? (...parts) => join(tempRoot, ...parts) : target[key],
+}));
+vi.mock('./instances.js', () => mockNoPeers({}, { resolveEffectiveCategories: () => ({}), updatePeer: async () => {} }));
+vi.mock('./instanceIdentity.js', () => mockTestIdentity());
+vi.mock('./sharing/peerSync.js', () => mockNoPeerSync({}, {
+ getOutboundCoverageForPeer: async () => ({ universe: new Set(), pipeline: new Set(), mediaCollections: new Set() }),
+}));
+vi.mock('./mediaJobQueue/index.js', () => ({ getJob: () => null }));
+vi.mock('./sharing/annotationIdentity.js', () => ({ resolveBucketSourceName: async () => 'Test' }));
+vi.mock('../lib/peerHttpClient.js', () => ({ peerFetch: vi.fn(() => { throw new Error('Unexpected network request'); }) }));
+
+const backup = await import('./backup.js');
+const dataSync = await import('./dataSync.js');
+const peerUsage = await import('./peerUsage.js');
+const quotas = await import('./providerQuotaShare.js');
+const sync = await import('./syncOrchestrator.js');
+const buckets = await import('./sharing/buckets.js');
+const subscriptions = await import('./sharing/subscriptions.js');
+const manifests = await import('./sharing/manifest.js');
+const importer = await import('./sharing/importer.js');
+const annotations = await import('./sharing/annotationsSync.js');
+const { PATHS } = await import('../lib/fileUtils.js');
+const bucketPath = join(tempRoot, 'bucket');
+let bucket;
+const seed = async (path, value) => {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, typeof value === 'string' ? value : JSON.stringify(value));
+};
+const card = (family) => ({ family, limits: [{ key: 'weekly', percentUsed: 20 }], fetchedAt: '2026-09-01T00:00:00Z' });
+const incoming = { id: 'incoming', senderInstanceId: 'remote', kind: 'media', recordIds: ['job-new'], assetRefs: [] };
+
+beforeEach(async () => {
+ faults.clear();
+ annotations.__resetBucketAssetKeysCache();
+ subscriptions.__resetForTests();
+ await rm(tempRoot, { recursive: true, force: true });
+ await mkdir(bucketPath, { recursive: true });
+ bucket = await buckets.createBucket({ name: 'Bucket', path: bucketPath, mode: 'inbox' });
+ await seed(join(bucketPath, 'manifests', 'incoming.json'), incoming);
+ await seed(join(bucketPath, 'records', 'media', 'job-new.json'), { id: 'job-new', status: 'completed' });
+ await seed(join(bucketPath, 'assets', 'images', 'note.png'), 'image');
+ await seed(join(bucketPath, 'assets', 'images', 'new.png'), 'image');
+});
+afterAll(cleanup);
+
+// Each row pins a separate durable mutation boundary; rejection must preserve
+// bytes, and a repair must unblock the same queue/operation without a restart.
+const cases = [
+ ['backup state', () => join(tempRoot, 'backup/state.json'), { lastRun: 'old' },
+ () => backup.saveState({ status: 'ok' }), saved => expect(saved).toMatchObject({ lastRun: 'old', status: 'ok' })],
+ ['goals', () => join(PATHS.digitalTwin, 'goals.json'), { goals: [{ id: 'old' }] },
+ () => dataSync.applyRemote('goals', { goals: [{ id: 'new', updatedAt: '2026-09-02' }] }),
+ saved => expect(saved.goals.map(g => g.id)).toEqual(['old', 'new'])],
+ ['character', () => join(tempRoot, 'character.json'), { events: [{ id: 'old', timestamp: '2026-09-01' }], syncedTaskIds: ['old'] },
+ () => dataSync.applyRemote('character', { events: [{ id: 'new', timestamp: '2026-09-02' }], updatedAt: '2026-09-02', level: 99 }),
+ saved => { expect(saved.events.map(e => e.id)).toEqual(['old', 'new']); expect(saved.syncedTaskIds).toEqual(['old']); expect(saved).not.toHaveProperty('level'); }],
+ ['personal log', () => join(tempRoot, 'meatspace/daily-log.json'), { entries: [{ date: '2026-09-01' }], custom: true },
+ () => dataSync.applyRemote('meatspace', { 'daily-log.json': { entries: [{ date: '2026-09-02' }] } }),
+ saved => { expect(saved.entries).toHaveLength(2); expect(saved.custom).toBe(true); }],
+ ['personal config', () => join(tempRoot, 'meatspace/config.json'), { updatedAt: '2026-09-03', custom: true },
+ () => dataSync.applyRemote('meatspace', { 'config.json': { updatedAt: '2026-09-02', custom: false } }), saved => expect(saved.custom).toBe(true)],
+ ['peer retirements', () => peerUsage.PEER_USAGE_FILE, { instances: { retained: { capturedAt: '2026-09-01' } }, tombstones: [] },
+ () => peerUsage.forgetInstanceUsage('retired'), saved => { expect(saved.instances).toHaveProperty('retained'); expect(saved.tombstones).toEqual(expect.arrayContaining([expect.objectContaining({ instanceId: 'retired' })])); }],
+ ['quota families', () => quotas.PROVIDER_QUOTAS_FILE, { quotas: [card('old')] },
+ () => quotas.recordLocalQuotaCards([card('new')]), saved => expect(saved.quotas.map(c => c.family)).toEqual(['old', 'new'])],
+ ['bucket registry', () => join(tempRoot, 'sharing/buckets.json'), () => ({ buckets: [bucket] }),
+ async () => { const other = join(tempRoot, 'other'); await mkdir(other, { recursive: true }); return buckets.createBucket({ name: 'Other', path: other }); },
+ saved => expect(saved.buckets.map(b => b.name)).toEqual(['Bucket', 'Other'])],
+ ['bucket identity', () => join(bucketPath, 'bucket.json'), { id: 'original', schemaVersion: 1, custom: true },
+ () => buckets.ensureBucketLayout(bucket), saved => expect(saved).toEqual({ id: 'original', schemaVersion: 1, custom: true })],
+ ['subscriptions', () => join(tempRoot, 'sharing/subscriptions.json'), { subscriptions: [{ id: 'old', recordKind: 'series', recordId: 'old' }] },
+ () => subscriptions.adoptImportedSubscription({ bucketId: bucket.id, recordKind: 'series', recordId: 'new' }),
+ saved => expect(saved.subscriptions.map(s => s.recordId)).toEqual(['old', 'new'])],
+ ['sharing cursors', () => join(tempRoot, 'sharing/cursors', `${bucket.id}.json`), { processedById: { old: 'old-id' }, processed: ['legacy'] },
+ () => manifests.markProcessed(bucket.id, 'new', 'new-id'), saved => { expect(saved.processedById).toEqual({ old: 'old-id', new: 'new-id' }); expect(saved.processed).toEqual(['legacy']); }],
+ ['import inbox', () => join(tempRoot, 'sharing/inbox', `${bucket.id}.json`), { items: [{ manifestId: 'old' }] },
+ () => importer.processManifest(bucket.id, 'incoming.json'), saved => expect(saved.items.map(i => i.manifestId)).toEqual(['old', 'incoming'])],
+ ['import media jobs', () => join(tempRoot, 'media-jobs.json'), { jobs: [{ id: 'old' }], custom: true },
+ () => importer.processManifest(bucket.id, 'incoming.json'), saved => { expect(saved.jobs.map(j => j.id)).toEqual(['old', 'job-new']); expect(saved.custom).toBe(true); }],
+ ['annotation tombstones', () => join(bucketPath, 'records/media-annotations/test-instance.json'), { annotations: { 'image:note.png': { note: 'old' } } },
+ () => annotations.exportAnnotationsToBucket({ ...bucket, mode: 'auto-merge' }, { 'image:new.png': { note: 'new' } }, 'test-instance'),
+ saved => { expect(saved.annotations['image:note.png'].note).toBe(''); expect(saved.annotations['image:new.png'].note).toBe('new'); }],
+ ['sync cursors', () => join(tempRoot, 'instances_sync_cursors.json'), { old: { brainSeq: 42 } },
+ () => sync.syncWithPeer({ instanceId: 'new', name: 'Test' }), saved => { expect(saved.old).toEqual({ brainSeq: 42 }); expect(saved.new.lastSyncAt).toBeTruthy(); }],
+];
+
+describe.each(cases)('%s preserves unreadable data', (_name, getPath, fixture, mutate, retained) => {
+ it('preserves corrupt/empty bytes and read faults, then retries after repair', async () => {
+ const path = getPath();
+ for (const bytes of ['{"truncated":', 'not json', '']) {
+ await seed(path, bytes);
+ await expect(mutate()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });
+ expect(await readFile(path, 'utf8')).toBe(bytes);
+ }
+ await seed(path, typeof fixture === 'function' ? fixture() : fixture);
+ const original = await readFile(path, 'utf8');
+ faults.set(path, 'EACCES');
+ await expect(mutate()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });
+ faults.delete(path);
+ expect(await readFile(path, 'utf8')).toBe(original);
+ await mutate();
+ retained(JSON.parse(await readFile(path, 'utf8')));
+ });
+ it('initializes only when the file is absent', async () => {
+ const path = getPath();
+ await rm(path, { force: true });
+ await mutate();
+ expect(JSON.parse(await readFile(path, 'utf8'))).toBeTruthy();
+ });
+});
+
+// An unreadable shared identity must not leave a new local registry entry.
+it('does not register a bucket whose existing identity cannot be read', async () => {
+ const other = join(tempRoot, 'other');
+ const identityPath = join(other, 'bucket.json');
+ const registryPath = join(tempRoot, 'sharing/buckets.json');
+ await seed(identityPath, '{"id":');
+ const before = await readFile(registryPath, 'utf8');
+ await expect(buckets.createBucket({ name: 'Other', path: other })).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });
+ expect(await readFile(registryPath, 'utf8')).toBe(before);
+ expect(await readFile(identityPath, 'utf8')).toBe('{"id":');
+});
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index f3f24b3733..02f9ea4b9b 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -67,7 +67,7 @@ function emitSyncProgress(payload) {
// --- Cursor persistence ---
async function loadCursors() {
- return await readJSONFile(CURSORS_FILE, {});
+ return await readJSONFile(CURSORS_FILE, {}, { strict: true });
}
async function saveCursors(cursors) {