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
fail loudly when a collection's type index.json is unreadable instead of resetting its config slot (#7261)
[._.]/ Adam Eivyaf63dc10926b
diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex 291a9f4b0e..44d50e77aa 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -83,7 +83,7 @@import { join } from 'path';import { readdir, lstat, rm } from 'fs/promises';-import { atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';+import { atomicWrite, readJSONFile, readJSONFileStrict, unreadableStoreError, ensureDir } from './fileUtils.js';import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.js';import { isVitestRunner } from './runtimeEnv.js';@@ -189,11 +189,22 @@ export function createCollectionStore({/*** Load the type-level index.json. Returns the default shape (with the- * code-expected `schemaVersion`) when the file is missing — does NOT write+ * code-expected `schemaVersion`) when the file is ABSENT — does NOT write* to disk. Use `saveTypeIndex` / `saveOne` to persist.+ *+ * Strict (#7261): every `config`-slot writer starts from this read and writes+ * the result back, so a swallowed present-but-unreadable index (EACCES, EIO,+ * truncated bytes, a cloud-sync conflict copy) would persist the shipped+ * `defaultTypeIndexConfig` over real user state AND stamp the code's current+ * `schemaVersion` over records still in the old on-disk layout. Throwing here+ * means `idealoomLists.updateSettings` and universeBuilder's run writers+ * reject BEFORE any byte is written, leaving the file intact for repair;+ * request-path callers surface it as a 5xx (`unreadableStoreError` carries+ * `status: 500`). Same posture as `settingsStore.get()`.*/async function loadTypeIndex() {- const raw = await readJSONFile(typeIndexPath(), null, { logError: false });+ const { ok, value: raw } = await readJSONFileStrict(typeIndexPath(), null, { allowArray: false });+ if (!ok) throw unreadableStoreError(typeIndexPath());if (!isPlainObject(raw)) return buildEmptyTypeIndex();return {schemaVersion: Number.isInteger(raw.schemaVersion) ? raw.schemaVersion : schemaVersion,@@ -266,6 +277,14 @@ export function createCollectionStore({* Load one record by id. Returns `null` when the record dir is missing or* the on-disk JSON fails to parse; runs the configured `sanitizeRecord` on* the parsed payload (sanitizer can also return `null` to reject).+ *+ * Non-strict by design (unlike `loadTypeIndex` above, #7261): a per-record+ * read is not a read-modify-write of shared state — `saveOneNow` writes a+ * record the caller already holds in full, so an unreadable neighbor can+ * never be overwritten by defaults. The "which ids failed" signal a strict+ * read would carry is already preserved by `loadAllResult` below, and a+ * corrupt single record must not take down a collection-wide load. Callers+ * that need to tell "absent" from "corrupt" use `loadAllResult`.*/async function loadOne(id) {if (!isValidId(id)) return null;@@ -282,7 +301,8 @@ export function createCollectionStore({* compare the raw on-disk shape to the sanitized shape (e.g. detect "this* record's nested ids need persisting" — sanitize mints missing ids on the* fly but doesn't persist them until the next write). Returns the parsed- * JSON or `null`; ignores the sanitizer entirely.+ * JSON or `null`; ignores the sanitizer entirely. Non-strict for the same+ * reason as `loadOne` above.*/async function loadOneRaw(id) {if (!isValidId(id)) return null;@@ -404,27 +424,47 @@ export function createCollectionStore({* expected `schemaVersion`. Returns a status object rather than throwing so* `server/index.js` can log all collections in one pass.*- * ok=true — on-disk version matches code (or type index is missing,- * which is treated as a fresh install — the next write- * stamps the correct version).- * ok=false — on-disk version is older OR newer than code. Older → a- * pending migration didn't run. Newer → code rolled back- * below a forward-only migration.+ * ok=true — on-disk version matches code (`reason: 'match'`), or the type+ * index is ABSENT (`reason: 'missing'`), which is treated as a+ * fresh install — the next write stamps the correct version.+ * ok=false — on-disk version is older (`reason: 'older'`) or newer+ * (`reason: 'newer'`) than code. Older → a pending migration+ * didn't run. Newer → code rolled back below a forward-only+ * migration. OR the file is present but could not be read+ * (`reason: 'unreadable'`, `onDisk: null`).+ *+ * The `unreadable` verdict exists because this gate is the ONE boot-time check+ * that catches a skipped or rolled-back storage migration (#7261). Reporting+ * "fresh install" for a file we could not read would silence that alarm for a+ * collection whose records are still in the old layout — and the next write+ * would then stamp the current version over it, falsifying the marker+ * permanently.*/async function verifySchemaVersion() {- const raw = await readJSONFile(typeIndexPath(), null, { logError: false });+ const { ok: readable, value: raw } = await readJSONFileStrict(typeIndexPath(), null, { allowArray: false, logError: false });+ if (!readable) {+ return {+ ok: false,+ onDisk: null,+ expected: schemaVersion,+ type,+ reason: 'unreadable',+ message: `collection "${type}": index.json at ${typeIndexPath()} exists but could not be read or parsed — repair or delete it and restart. Until then the storage-version check for this collection cannot run.`,+ };+ }if (!isPlainObject(raw) || raw.schemaVersion == null) {return {ok: true,onDisk: null,expected: schemaVersion,type,+ reason: 'missing',message: `collection "${type}": no index.json (fresh install) — first write will stamp schemaVersion=${schemaVersion}`,};}const onDisk = Number.isInteger(raw.schemaVersion) ? raw.schemaVersion : null;if (onDisk === schemaVersion) {- return { ok: true, onDisk, expected: schemaVersion, type, message: `collection "${type}" @ v${schemaVersion}` };+ return { ok: true, onDisk, expected: schemaVersion, type, reason: 'match', message: `collection "${type}" @ v${schemaVersion}` };}if (onDisk != null && onDisk < schemaVersion) {return {@@ -432,6 +472,7 @@ export function createCollectionStore({onDisk,expected: schemaVersion,type,+ reason: 'older',message: `collection "${type}": on-disk v${onDisk}, code expects v${schemaVersion} — a migration didn't run. Check scripts/migrations/ and run \`npm run migrations\`.`,};}@@ -440,6 +481,7 @@ export function createCollectionStore({onDisk,expected: schemaVersion,type,+ reason: 'newer',message: `collection "${type}": on-disk v${onDisk}, code expects v${schemaVersion} — code rolled back below a forward-only migration. Roll forward or restore from a backup.`,};}diff --git a/server/lib/collectionStore.test.js b/server/lib/collectionStore.test.jsindex cd4601d9ad..7356bca27f 100644--- a/server/lib/collectionStore.test.js+++ b/server/lib/collectionStore.test.js@@ -412,6 +412,83 @@ describe('verifySchemaVersion', () => {expect(status.onDisk).toBe(5);expect(status.message).toMatch(/rolled back/);});++ // #7261 — a present-but-unreadable index must NOT read as "fresh install".+ // That verdict is what silences the one boot-time gate that catches a skipped+ // or rolled-back storage migration, after which the next write stamps the+ // current version over records still in the old layout.+ it('reports unreadable (not "fresh install") for a truncated index.json', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ writeFileSync(join(dir, 'index.json'), '{"schemaVersion": 2, "config": {');+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(false);+ expect(status.reason).toBe('unreadable');+ expect(status.onDisk).toBeNull();+ expect(status.message).toMatch(/could not be read or parsed/);+ expect(status.message).not.toMatch(/fresh install/);+ });++ it('reports unreadable for an array-shaped index.json', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ writeFileSync(join(dir, 'index.json'), '[]');+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(false);+ expect(status.reason).toBe('unreadable');+ });++ it('tags the absent and matching verdicts with their own reasons', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ expect((await store.verifySchemaVersion()).reason).toBe('missing');+ await store.saveTypeIndex({});+ expect((await store.verifySchemaVersion()).reason).toBe('match');+ });+});++describe('unreadable type index (#7261)', () => {+ const TRUNCATED = '{"schemaVersion": 2, "config": {"settings": {"obsidianVaultId": "vault-1"}}';+ const indexPath = () => join(dir, 'index.json');++ it('loadTypeIndex throws instead of returning shipped defaults', async () => {+ const store = createCollectionStore({+ dir,+ type: 'widgets',+ schemaVersion: 3,+ defaultTypeIndexConfig: { settings: { obsidianVaultId: null } },+ });+ writeFileSync(indexPath(), TRUNCATED);+ await expect(store.loadTypeIndex()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('saveTypeIndex rejects and leaves the file byte-identical', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ writeFileSync(indexPath(), TRUNCATED);+ await expect(store.saveTypeIndex({ config: { settings: { autoSync: true } } })).rejects.toThrow(/Unreadable JSON file/);+ expect(await readFile(indexPath(), 'utf8')).toBe(TRUNCATED);+ });++ it('does not stamp the code schemaVersion over an unreadable index', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 7 });+ writeFileSync(indexPath(), TRUNCATED);+ await expect(store.saveTypeIndex({})).rejects.toThrow();+ expect(await readFile(indexPath(), 'utf8')).not.toMatch(/"schemaVersion":\s*7/);+ });++ it('still records writes normally once the index is repaired', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ writeFileSync(indexPath(), TRUNCATED);+ await expect(store.loadTypeIndex()).rejects.toThrow();+ await atomicWrite(indexPath(), { schemaVersion: 3, type: 'widgets', config: { settings: { obsidianVaultId: 'vault-1' } } });+ const saved = await store.saveTypeIndex({ config: { extra: true } });+ expect(saved.schemaVersion).toBe(3);+ expect(saved.config.settings.obsidianVaultId).toBe('vault-1');+ });++ it('leaves per-record reads and writes unaffected', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ writeFileSync(indexPath(), TRUNCATED);+ await store.saveOne('rec-1', { id: 'rec-1', name: 'one' });+ expect(await store.loadOne('rec-1')).toEqual({ id: 'rec-1', name: 'one' });+ });});describe('verifyCollectionVersions', () => {diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.jsindex aea56680e4..16eae97831 100644--- a/server/routes/universeBuilder/index.test.js+++ b/server/routes/universeBuilder/index.test.js@@ -20,6 +20,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn().mockResolvedValue(undefined),atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ // collectionStore reads the type index strictly (#7261) — the in-memory+ // store always yields a trustworthy read, so ok is unconditionally true.+ readJSONFileStrict: vi.fn(async (path, fallback) => ({ ok: true, value: fileStore.has(path) ? fileStore.get(path) : fallback })),+ unreadableStoreError: (filePath) => Object.assign(new Error(`Unreadable JSON file: ${filePath}`), { status: 500, code: 'UNREADABLE_STORE' }),// sanitizeFilename: strip path components so a traversal attempt diverges// from the input (the route 400s when safe !== input).sanitizeFilename: vi.fn((f) => String(f).replace(/^.*[\\/]/, '').replace(/\.\./g, '')),diff --git a/server/services/idealoomLists.test.js b/server/services/idealoomLists.test.jsindex ad9b1848cb..095eb59613 100644--- a/server/services/idealoomLists.test.js+++ b/server/services/idealoomLists.test.js@@ -1,7 +1,7 @@import { describe, it, expect, afterAll, vi } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';import { tmpdir } from 'os';-import { join } from 'path';+import { join, dirname } from 'path';import { makePathsProxy } from '../lib/mockPathsDataRoot.js';var tempRoot; // eslint-disable-line no-var@@ -78,3 +78,25 @@ describe('IdeaLoom local lists', () => {}});});++// #7261 — the type index's `config.settings` slot IS the user's vault binding,+// read-modify-written on every toggle. An unreadable index must reject the+// write rather than persist DEFAULT_SETTINGS over the binding.+describe('IdeaLoom settings against an unreadable index.json', () => {+ const indexPath = () => join(getTempRoot(), 'brain', 'idealoom-lists', 'index.json');+ const TRUNCATED = '{"schemaVersion": 1, "config": {"settings": {"obsidianVaultId": "vault-1", "enabled": true}';++ it('leaves the file byte-identical and does not persist shipped defaults', async () => {+ mkdirSync(dirname(indexPath()), { recursive: true });+ writeFileSync(indexPath(), TRUNCATED);++ await expect(lists.getSettings()).rejects.toThrow(/Unreadable JSON file/);+ await expect(lists.updateSettings({ autoSync: true })).rejects.toThrow(/Unreadable JSON file/);++ expect(readFileSync(indexPath(), 'utf8')).toBe(TRUNCATED);++ // Repairing the file restores normal behavior — the binding survived.+ writeFileSync(indexPath(), JSON.stringify({ schemaVersion: 1, type: 'idealoom-lists', config: { settings: { enabled: true, obsidianVaultId: 'vault-1', autoSync: false } } }));+ expect(await lists.updateSettings({ autoSync: true })).toEqual({ enabled: true, obsidianVaultId: 'vault-1', autoSync: true });+ });+});diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex fe0a454880..35acd3ac8f 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -14,6 +14,10 @@ vi.mock('../lib/fileUtils.js', () => ({ensureDir: vi.fn().mockResolvedValue(undefined),atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ // collectionStore reads the type index strictly (#7261) — the in-memory+ // store always yields a trustworthy read, so ok is unconditionally true.+ readJSONFileStrict: vi.fn(async (path, fallback) => ({ ok: true, value: fileStore.has(path) ? fileStore.get(path) : fallback })),+ unreadableStoreError: (filePath) => Object.assign(new Error(`Unreadable JSON file: ${filePath}`), { status: 500, code: 'UNREADABLE_STORE' }),}));let uuidCounter = 0;diff --git a/server/services/universeBuilder/store.test.js b/server/services/universeBuilder/store.test.jsindex e372135aab..ba7eb64a87 100644--- a/server/services/universeBuilder/store.test.js+++ b/server/services/universeBuilder/store.test.js@@ -10,7 +10,7 @@*/import { describe, it, expect, beforeEach, afterAll } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { vi } from 'vitest';@@ -141,6 +141,23 @@ describe('universe store facade — file backend', () => {expect((await s.loadRuns()).map((r) => r.universeId)).toEqual(['u-B']);});+ // #7261 — the run log lives in the type index's `config` slot, read-modify-+ // written on every append. An unreadable index must reject the write rather+ // than silently restart the history from an empty array.+ it('run writers reject on an unreadable index.json and leave it byte-identical', async () => {+ const s = getUniverseStore(passthroughSanitize);+ await s.appendRun({ id: 'r-keep', universeId: 'u-1', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:00.000Z' });++ const indexPath = join(TEST_DATA_ROOT, 'universes', 'index.json');+ const truncated = readFileSync(indexPath, 'utf8').slice(0, -3);+ writeFileSync(indexPath, truncated);++ await expect(s.appendRun({ id: 'r-new', universeId: 'u-1', jobIds: [], promptCount: 2, createdAt: '2026-01-02T00:00:00.000Z' })).rejects.toThrow(/Unreadable JSON file/);+ await expect(s.removeRunsForUniverses(['u-1'])).rejects.toThrow(/Unreadable JSON file/);+ await expect(s.loadRuns()).rejects.toThrow(/Unreadable JSON file/);+ expect(readFileSync(indexPath, 'utf8')).toBe(truncated);+ });+it('loadRuns returns newest-first (created_at DESC, id DESC) to match the PG backend', async () => {const s = getUniverseStore(passthroughSanitize);await s.appendRun({ id: 'r-old', universeId: 'u-1', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:00.000Z' });