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
give the read-merge-write settings document one owner so the strict-read fix stops drifting copy by copy
[._.]/ Adam Eivy0d0658095aba
diff --git a/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.mdindex bbfc79a912..69a8f8d60d 100644--- a/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md+++ b/docs/decisions/2026-08-14-strict-json-reads-for-counted-values.md@@ -191,3 +191,33 @@ every later load. Deep-clone a default that callers mutate (the neighbouring- The remaining ~200 swallowing call sites are documented above by categoryrather than individually, so a future reader can classify a *new* call sitewithout re-deriving the rule.++## Addendum (2026-09-07): the shared primitives, and the copies the grep missed++The audit above was driven by grepping `readJSONFile` / `tryReadFile` call+sites. Two members of the class sat outside that grep:++- **`createCachedStore` (`server/lib/jsonIo.js`)** read with a bare+ `readFile` + `safeJSONParse(content, default)`, and every one of its five+ consumers (`platformAccounts`, `socialAccounts`, `agentPersonalities`,+ `automationScheduler`, `feeds`) mutates through `mutate`, which persists+ whatever `load` returned. A corrupt accounts or schedules file therefore+ became the empty default on the next mutation. `load()` is now strict+ (`readJSONFileStrict`, rejecting with `Unreadable JSON file: <path>`); its+ boot-time consumer already runs under a `.catch` in `bootstrap.js`, and the+ scheduled ones inside `eventScheduler`'s handler guard.+- **Four `getSettings`/`updateSettings` pairs** (`brainJournal`,+ `youtubeIngest`, `activityDigest`, `modelPersonality`) copied+ `goalScorecard`'s pre-fix shape and were never converted, because "config /+ settings reads" were classified as safe without checking the write-back.+ Rule 2 above already said the base of a write back is in the class; the+ category note was read as an exemption. All five settings documents now go+ through one owner, `createSettingsStore` (`server/lib/settingsStore.js`),+ whose strict read and serialized `update` cannot drift copy by copy.++Placement rule going forward: a flat settings document with shipped defaults+and a PATCH surface is a `createSettingsStore`; a mutable document edited in+place is a `createCachedStore`; a per-record collection is a+`createCollectionStore`. A new hand-rolled `readJSONFile(...)` ++`atomicWrite(...)` pair on the same path is the signal to reach for one of+those instead.diff --git a/server/lib/README.md b/server/lib/README.mdindex ac1a59443b..0750610b80 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -270,7 +270,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. || `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. || `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |-| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |+| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |+| `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. || `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. || `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. || `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. |diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 848c253455..a13290f510 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -1627,6 +1627,39 @@ describe('createCachedStore', () => {store.invalidateCache();expect((await store.load()).n).toBe(42);});++ // Strict-read regression (#4115). Every consumer (accounts, feeds, schedules,+ // personalities) mutates through `mutate`, which persists whatever `load`+ // returned — so a corrupt file that read as the default was rewritten as the+ // default on the next mutation, deleting every record it held. Corrupt JSON is+ // the portable "present but unreadable" (same `ok: false` branch as EACCES).+ describe('strict reads (#4115)', () => {+ const CORRUPT = '{"accounts": {"a": 1},';++ it('load rejects on a corrupt file instead of fabricating the default', async () => {+ const file = join(dir, 'x.json');+ await writeFile(file, CORRUPT);+ const store = createCachedStore(file, { accounts: {} }, { context: 'accounts' });+ await expect(store.load()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('mutate leaves a corrupt file byte-for-byte intact', async () => {+ const file = join(dir, 'x.json');+ await writeFile(file, CORRUPT);+ const store = createCachedStore(file, { accounts: {} });+ await expect(store.mutate((data) => { data.accounts.b = 2; })).rejects.toThrow(/Unreadable JSON file/);+ expect(await readFile(file, 'utf-8'), 'the default must never be written over the file we could not read').toBe(CORRUPT);+ });++ it('recovers once the file is repaired', async () => {+ const file = join(dir, 'x.json');+ await writeFile(file, CORRUPT);+ const store = createCachedStore(file, { accounts: {} });+ await expect(store.load()).rejects.toThrow(/Unreadable JSON file/);+ await writeFile(file, JSON.stringify({ accounts: { a: 1 } }));+ expect((await store.mutate((data) => { data.accounts.b = 2; })).accounts).toEqual({ a: 1, b: 2 });+ });+ });});describe('watchForFile', () => {diff --git a/server/lib/index.js b/server/lib/index.jsindex 78a90b7d35..40344072e1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -255,6 +255,7 @@ export * from './forgeIssueState.js';export * from './portosEnv.js';export * from './homePath.js';export * from './jsonIo.js';+export * from './settingsStore.js';export * from './mimeTypes.js';export * from './pathContainment.js';export * from './paths.js';diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.jsindex 2679e8ce3b..4ad73d23a6 100644--- a/server/lib/jsonIo.js+++ b/server/lib/jsonIo.js@@ -1,5 +1,4 @@/** JSON, JSONL, and cached-store file IO helpers. */-import { existsSync } from 'fs';import { open, readFile, readdir, stat } from 'fs/promises';import { basename, dirname } from 'path';import { appendFileGuarded, atomicWrite, ensureDir, sleep } from './fileCore.js';@@ -531,6 +530,14 @@ export async function writeJSONLines(filePath, values) {* @param {string} [options.context=''] - Context label for error logging* @returns {{ load, save, mutate, invalidateCache }}*+ * `load()` is STRICT (#4115): a present-but-unreadable or corrupt file rejects+ * with `Unreadable JSON file: <path>` instead of reading as `defaultValue`,+ * because `mutate` persists whatever `load` returned — a swallowed default+ * would be written over the real file on the next mutation. Only a genuinely+ * absent file (ENOENT) yields the default. For a flat settings document with+ * shipped defaults and a PATCH surface, use `createSettingsStore`+ * (`settingsStore.js`) instead.+ ** Writes are serialized through a single-tail `createFileWriteQueue` so two* concurrent `save()` calls can't interleave their `atomicWrite` + cache* assignment. For read-modify-write, use `mutate(fn)` — it runs the whole@@ -552,13 +559,15 @@ export function createCachedStore(filePath, defaultValue, { ttl = 2000, contextconst now = Date.now();if (cache && (now - cacheTimestamp) < ttl) return cache;await ensureDir(dir);- if (!existsSync(filePath)) {- cache = cloneDefault();- cacheTimestamp = now;- return cache;+ // Strict (#4115): `mutate` is load → fn → persist over this value, so a+ // present-but-unreadable file must reject here rather than read as the+ // default and be overwritten by the very next write. ENOENT is the one+ // errno that proves absence and still yields the default.+ const { ok, value } = await readJSONFileStrict(filePath, null, { logError: true });+ if (!ok) {+ throw new Error(`Unreadable JSON file: ${filePath}${context ? ` (${context})` : ''}`);}- const content = await readFile(filePath, 'utf-8');- cache = safeJSONParse(content, cloneDefault(), { context });+ cache = value === null ? cloneDefault() : value;cacheTimestamp = now;return cache;};diff --git a/server/lib/settingsStore.js b/server/lib/settingsStore.jsnew file mode 100644index 0000000000..95dcdb8e92--- /dev/null+++ b/server/lib/settingsStore.js@@ -0,0 +1,76 @@+/**+ * File-backed settings document with shipped defaults.+ *+ * One owner for the `read → merge defaults → PATCH → write back` shape every+ * per-feature settings file shares (`journal-settings.json`,+ * `youtube-ingest-settings.json`, `activity-digest-settings.json`,+ * `goal-scorecard-settings.json`, `model-personality/settings.json`). Five+ * services hand-rolled it, and the #4115 strict-read fix reached exactly one of+ * them — the other four kept reading a corrupt file as the shipped defaults and+ * writing those defaults over the user's settings on the next PATCH. Owning the+ * shape here means the posture cannot drift copy by copy again.+ *+ * Contract:+ * - `get()` reads STRICT: a present-but-unreadable or non-object file rejects+ * with `Unreadable JSON file: <path>` instead of reading as the defaults. A+ * genuinely absent file (ENOENT) is a trustworthy first-run empty and yields+ * the defaults. The stored object is merged OVER `defaults` (shallow — these+ * documents are flat), then passed through `normalize` when given.+ * - `update(patch)` is `get → apply patch → atomicWrite`, serialized on one+ * tail so two concurrent PATCHes cannot interleave and drop each other's+ * keys. `undefined` values in `patch` are ABSENT (the key is left alone);+ * `null` is an explicit clear and is written. Because it starts from `get()`,+ * an unreadable file makes `update` reject before any byte is written — the+ * file survives intact for the user to repair.+ * - Which keys a client may set is the caller's policy: filter the request+ * body before calling `update` (`goalScorecard`'s `CLIENT_SETTABLE` pick),+ * so server-managed fields stay writable by the service itself.+ *+ * `filePath` may be a function so a store can resolve `PATHS` lazily (test+ * suites re-root `PATHS.data` after module load; see `modelPersonality.js`).+ *+ * For a mutable document that is cached and edited in place (accounts, feeds,+ * schedules) use `createCachedStore` (`jsonIo.js`); for a per-record collection+ * use `createCollectionStore` (`collectionStore.js`).+ */++import { atomicWrite, readJSONFile } from './fileUtils.js';+import { createFileWriteQueue } from './fileWriteQueue.js';+import { isPlainObject } from './objects.js';++/**+ * @template T+ * @param {string | (() => string)} filePath - Settings file, or a resolver for it.+ * @param {T} defaults - Shipped defaults (flat object); the stored file is merged over it.+ * @param {{ normalize?: (settings: T) => T }} [options]+ * `normalize` runs on every read after the defaults merge — the place to+ * repair a hand-edited value that would otherwise corrupt a consumer.+ * @returns {{ get: () => Promise<T>, update: (patch?: Partial<T>) => Promise<T>, path: () => string }}+ */+export function createSettingsStore(filePath, defaults, { normalize = null } = {}) {+ const path = typeof filePath === 'function' ? filePath : () => filePath;+ const queueWrite = createFileWriteQueue();++ async function get() {+ // Strict (#4115): `update` writes this value back, so a swallowed unreadable+ // file would become the shipped defaults on disk. `allowArray: false` makes+ // an array-shaped file an unreadable one — we cannot merge it, so we must+ // not replace it either.+ const stored = await readJSONFile(path(), null, { allowArray: false, strict: true });+ const merged = { ...defaults, ...(isPlainObject(stored) ? stored : {}) };+ return normalize ? normalize(merged) : merged;+ }++ function update(patch = {}) {+ return queueWrite(async () => {+ const next = { ...(await get()) };+ for (const [key, value] of Object.entries(patch)) {+ if (value !== undefined) next[key] = value;+ }+ await atomicWrite(path(), next);+ return next;+ });+ }++ return { get, update, path };+}diff --git a/server/lib/settingsStore.test.js b/server/lib/settingsStore.test.jsnew file mode 100644index 0000000000..3701fdaeec--- /dev/null+++ b/server/lib/settingsStore.test.js@@ -0,0 +1,119 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createSettingsStore } from './settingsStore.js';++/**+ * `createSettingsStore` is the one owner of the `read → merge defaults → PATCH →+ * write back` shape five services used to hand-roll. The contract that matters+ * most is the strict half (#4115): a present-but-unreadable file must never be+ * read as the shipped defaults, because `update` writes whatever `get` returned+ * straight back over the file. Corrupt JSON is the portable way to produce+ * "present but unreadable" — it fails the parse identically on every platform+ * and needs no privileges.+ */+describe('createSettingsStore', () => {+ const DEFAULTS = { enabled: false, provider: null, historyCap: 200 };+ const CORRUPT = '{"enabled": true,';+ let dir;+ let file;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'settings-store-test-'));+ file = join(dir, 'nested', 'settings.json');+ });++ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ it('reads an absent file as the shipped defaults without creating it', async () => {+ const store = createSettingsStore(file, DEFAULTS);+ expect(await store.get()).toEqual(DEFAULTS);+ expect(existsSync(file)).toBe(false);+ });++ it('merges the stored file over the defaults so new default keys appear', async () => {+ writeFileSync(join(dir, 'flat.json'), JSON.stringify({ provider: 'p1' }));+ const store = createSettingsStore(join(dir, 'flat.json'), DEFAULTS);+ expect(await store.get()).toEqual({ enabled: false, provider: 'p1', historyCap: 200 });+ });++ it('update persists the patch, returns the merged result, and creates missing directories', async () => {+ const store = createSettingsStore(file, DEFAULTS);+ const next = await store.update({ enabled: true });+ expect(next).toEqual({ ...DEFAULTS, enabled: true });+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ ...DEFAULTS, enabled: true });+ expect(await store.get()).toEqual(next);+ });++ it('treats undefined patch values as absent and null as an explicit clear', async () => {+ const store = createSettingsStore(file, DEFAULTS);+ await store.update({ provider: 'p1', historyCap: 50 });+ const next = await store.update({ provider: null, historyCap: undefined, enabled: undefined });+ expect(next).toEqual({ enabled: false, provider: null, historyCap: 50 });+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ enabled: false, provider: null, historyCap: 50 });+ });++ it('runs normalize on every read, after the defaults merge', async () => {+ writeFileSync(join(dir, 'flat.json'), JSON.stringify({ historyCap: 'abc' }));+ const store = createSettingsStore(join(dir, 'flat.json'), DEFAULTS, {+ normalize: (s) => (Number.isInteger(s.historyCap) ? s : { ...s, historyCap: DEFAULTS.historyCap }),+ });+ expect((await store.get()).historyCap).toBe(200);+ // update starts from the normalized read, so the repaired value is what lands on disk.+ await store.update({ enabled: true });+ expect(JSON.parse(readFileSync(join(dir, 'flat.json'), 'utf8'))).toEqual({ enabled: true, provider: null, historyCap: 200 });+ });++ it('resolves a function filePath lazily on every call', async () => {+ let current = join(dir, 'a.json');+ const store = createSettingsStore(() => current, DEFAULTS);+ await store.update({ provider: 'a' });+ current = join(dir, 'b.json');+ await store.update({ provider: 'b' });+ expect(JSON.parse(readFileSync(join(dir, 'a.json'), 'utf8')).provider).toBe('a');+ expect(JSON.parse(readFileSync(join(dir, 'b.json'), 'utf8')).provider).toBe('b');+ expect(store.path()).toBe(join(dir, 'b.json'));+ });++ describe('strict reads (#4115)', () => {+ it('get rejects on a corrupt file instead of fabricating the defaults', async () => {+ writeFileSync(join(dir, 'flat.json'), CORRUPT);+ const store = createSettingsStore(join(dir, 'flat.json'), DEFAULTS);+ await expect(store.get()).rejects.toThrow(/Unreadable JSON file/);+ });++ it('update leaves a corrupt file byte-for-byte intact', async () => {+ const target = join(dir, 'flat.json');+ writeFileSync(target, CORRUPT);+ const store = createSettingsStore(target, DEFAULTS);+ await expect(store.update({ enabled: true })).rejects.toThrow(/Unreadable JSON file/);+ expect(+ readFileSync(target, 'utf8'),+ 'writing defaults over settings we failed to read is the data loss this prevents'+ ).toBe(CORRUPT);+ });++ it('refuses an array-shaped file rather than spreading its indexes into the settings', async () => {+ const target = join(dir, 'flat.json');+ writeFileSync(target, '["enabled"]');+ const store = createSettingsStore(target, DEFAULTS);+ await expect(store.get()).rejects.toThrow(/Unreadable JSON file/);+ await expect(store.update({ enabled: true })).rejects.toThrow(/Unreadable JSON file/);+ expect(readFileSync(target, 'utf8')).toBe('["enabled"]');+ });+ });++ it('serializes concurrent updates so no patch is lost', async () => {+ const store = createSettingsStore(file, { n: 0, a: null, b: null });+ const [first, second] = await Promise.all([+ store.update({ a: 'A' }),+ store.update({ b: 'B' }),+ ]);+ expect(first).toMatchObject({ a: 'A' });+ expect(second).toMatchObject({ a: 'A', b: 'B' });+ expect(await store.get()).toEqual({ n: 0, a: 'A', b: 'B' });+ });+});diff --git a/server/services/activityDigest.js b/server/services/activityDigest.jsindex e9d9401da0..8df3570b6e 100644--- a/server/services/activityDigest.js+++ b/server/services/activityDigest.js@@ -20,7 +20,8 @@*/import { join } from 'path';-import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { PATHS } from '../lib/fileUtils.js';+import { createSettingsStore } from '../lib/settingsStore.js';import { buildMarkers } from '../lib/markedSection.js';import { getUserTimezone } from './userTimezone.js';import { getDaySummary } from './humanActivity.js';@@ -56,24 +57,20 @@ const CLIENT_SETTABLE = ['enabled', 'provider', 'model', 'runTime', 'catchUpDays// ─── Settings ────────────────────────────────────────────────────────────────-export async function getSettings() {- await ensureDir(PATHS.brain);- const loaded = await readJSONFile(SETTINGS_FILE, null);- return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };-}+// Strict read + serialized PATCH live in the store (#4115): a corrupt file+// rejects instead of reading as DEFAULT_SETTINGS and being overwritten.+const settingsStore = createSettingsStore(SETTINGS_FILE, DEFAULT_SETTINGS);++export const getSettings = settingsStore.get;// Persist a partial update. Only client-settable keys are honored from// `partial`; `internal` carries server-managed fields (lastRunDate/lastRunAt).export async function updateSettings(partial = {}, internal = {}) {- const current = await getSettings();- const next = { ...current };- for (const key of CLIENT_SETTABLE) {- if (partial[key] !== undefined) next[key] = partial[key];- }- if (internal.lastRunDate !== undefined) next.lastRunDate = internal.lastRunDate;- if (internal.lastRunAt !== undefined) next.lastRunAt = internal.lastRunAt;- await atomicWrite(SETTINGS_FILE, next);- return next;+ return settingsStore.update({+ ...Object.fromEntries(CLIENT_SETTABLE.map((key) => [key, partial[key]])),+ lastRunDate: internal.lastRunDate,+ lastRunAt: internal.lastRunAt,+ });}// ─── Pure helpers (exported for unit tests — no I/O) ─────────────────────────diff --git a/server/services/brainJournal.js b/server/services/brainJournal.jsindex d9b4cf8ba0..d6d7ea0d5e 100644--- a/server/services/brainJournal.js+++ b/server/services/brainJournal.js@@ -25,7 +25,7 @@import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';-import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { createSettingsStore } from '../lib/settingsStore.js';import { ServerError } from '../lib/errorHandler.js';import { replaceMarkedSection } from '../lib/markedSection.js';import * as brainStorage from './brainStorage.js';@@ -52,24 +52,14 @@ const DEFAULT_SETTINGS = {autoSync: true,};-const queueSettingsWrite = createFileWriteQueue();-// ─── Settings ──────────────────────────────────────────────────────────────-export async function getSettings() {- await ensureDir(PATHS.brain);- const loaded = await readJSONFile(SETTINGS_FILE, null);- return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };-}+// Strict read + serialized PATCH live in the store (#4115): a corrupt file+// rejects instead of reading as DEFAULT_SETTINGS and being overwritten.+const settingsStore = createSettingsStore(SETTINGS_FILE, DEFAULT_SETTINGS);-export async function updateSettings(partial) {- return queueSettingsWrite(async () => {- const current = await getSettings();- const next = { ...current, ...partial };- await atomicWrite(SETTINGS_FILE, next);- return next;- });-}+export const getSettings = settingsStore.get;+export const updateSettings = settingsStore.update;// ─── Store ─────────────────────────────────────────────────────────────────diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.jsindex 6fd5113072..62cdc11346 100644--- a/server/services/brainJournal.test.js+++ b/server/services/brainJournal.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';-import { mkdirSync, rmSync } from 'fs';+import { mkdirSync, rmSync, readFileSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -132,6 +132,19 @@ describe('brainJournal', () => {autoSync: true,});});++ // Strict-read regression (#4115): the journal was one of four settings+ // stores the original audit missed — a corrupt journal-settings.json read+ // as DEFAULT_SETTINGS and the next PATCH wrote those defaults over the+ // user's vault/folder choice. The store now rejects and leaves the file.+ it('refuses to overwrite an unreadable settings file with the defaults', async () => {+ const file = join(TEMP_ROOT, 'journal-settings.json');+ const corrupt = '{"obsidianVaultId": "vault-1",';+ writeFileSync(file, corrupt);+ await expect(journal.getSettings()).rejects.toThrow(/Unreadable JSON file/);+ await expect(journal.updateSettings({ obsidianFolder: 'Journal' })).rejects.toThrow(/Unreadable JSON file/);+ expect(readFileSync(file, 'utf8')).toBe(corrupt);+ });});describe('getJournal / listJournals', () => {diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsindex 7d2cc4916e..f5976317fc 100644--- a/server/services/goalScorecard.js+++ b/server/services/goalScorecard.js@@ -27,6 +27,7 @@import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { createSettingsStore } from '../lib/settingsStore.js';import { todayInTimezone, localDayRangeUtc } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { localDayKey, listEvents } from './humanActivity.js';@@ -380,24 +381,16 @@ export function formatScorecardDigestLine(scorecard) {// ─── Settings / rules I/O ────────────────────────────────────────────────────-export async function getSettings() {- await ensureDir(INSIGHTS_DIR);- // Strict (#4115): `updateSettings` is `getSettings → merge → atomicWrite`, so a- // swallowed unreadable file writes DEFAULT_SETTINGS over the user's configured- // provider/model/week-start on the next settings PATCH.- const loaded = await readJSONFile(SETTINGS_FILE, null, { strict: true });- return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };-}+// Strict read + serialized PATCH live in the store (#4115): a swallowed+// unreadable file would otherwise write DEFAULT_SETTINGS over the user's+// configured provider/model/week-start on the next settings PATCH.+const settingsStore = createSettingsStore(SETTINGS_FILE, DEFAULT_SETTINGS);++export const getSettings = settingsStore.get;+// Only client-settable keys are honored; managed fields never come from a PUT.export async function updateSettings(partial = {}) {- const current = await getSettings();- const next = { ...current };- for (const key of CLIENT_SETTABLE) {- if (partial[key] !== undefined) next[key] = partial[key];- }- await ensureDir(INSIGHTS_DIR);- await atomicWrite(SETTINGS_FILE, next);- return next;+ return settingsStore.update(Object.fromEntries(CLIENT_SETTABLE.map((key) => [key, partial[key]])));}// User-editable per-goal mapping overrides. Shape: { [goalId]: { keywords?,diff --git a/server/services/modelPersonality.js b/server/services/modelPersonality.jsindex a555681af1..c651a5e2a3 100644--- a/server/services/modelPersonality.js+++ b/server/services/modelPersonality.js@@ -20,6 +20,7 @@ import { randomUUID } from 'crypto';import { join } from 'path';import { PATHS, atomicWrite, readJSONFile } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { createSettingsStore } from '../lib/settingsStore.js';import { resolveProviderAndModel, runPromptThroughProvider, assertProvider } from './promptRunner.js';import {PERSONALITY_TAXONOMY_VERSION,@@ -44,23 +45,22 @@ export const ALIGNMENT_SKIPPED_NO_TRAITS =const resultsFile = () => join(PATHS.data, 'model-personality', 'results.json');const settingsFile = () => join(PATHS.data, 'model-personality', 'settings.json');-export async function getSettings() {- const stored = await readJSONFile(settingsFile(), {});- const merged = { ...DEFAULT_SETTINGS, ...(stored && typeof stored === 'object' ? stored : {}) };+// Strict read + serialized PATCH live in the store (#4115): a corrupt file+// rejects instead of reading as DEFAULT_SETTINGS and being overwritten.+const settingsStore = createSettingsStore(settingsFile, DEFAULT_SETTINGS, {// Guard hand-edited settings: a malformed historyCap would flow into// `list.slice(0, historyCap)` and silently wipe the whole history// (`slice(0, 'abc')` → `[]`). Same rule as backup.js's settings guards.- if (!Number.isInteger(merged.historyCap) || merged.historyCap < 1 || merged.historyCap > 1000) {- merged.historyCap = DEFAULT_SETTINGS.historyCap;- }- return merged;-}+ normalize: (merged) => {+ if (!Number.isInteger(merged.historyCap) || merged.historyCap < 1 || merged.historyCap > 1000) {+ merged.historyCap = DEFAULT_SETTINGS.historyCap;+ }+ return merged;+ },+});-export async function updateSettings(patch = {}) {- const next = { ...(await getSettings()), ...patch };- await atomicWrite(settingsFile(), JSON.stringify(next, null, 2));- return next;-}+export const getSettings = settingsStore.get;+export const updateSettings = settingsStore.update;export async function getHistory(limit) {const stored = await readJSONFile(resultsFile(), []);diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.jsindex c3f8e6c84f..758090b965 100644--- a/server/services/youtubeIngest.js+++ b/server/services/youtubeIngest.js@@ -50,6 +50,7 @@ import { safeChildProcessOptions } from '../lib/processEnv.js';import { attachSseClient as attachSse, broadcastSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { vttToPlainText } from '../lib/vttTranscript.js';import { createMutex } from '../lib/asyncMutex.js';+import { createSettingsStore } from '../lib/settingsStore.js';import { downloadAudioToTempMp3 } from './ytdlpAudioImport.js';import { downloadVideoIntoLibrary } from './videoDownload.js';import { YOUTUBE_VIDEO_URL_RE } from '../lib/youtubeUrl.js';@@ -114,17 +115,12 @@ const DEFAULT_SETTINGS = {// ─── Settings ──────────────────────────────────────────────────────────────-export async function getSettings() {- await ensureDir(PATHS.brain);- const loaded = await readJSONFile(SETTINGS_FILE, null);- return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };-}+// Strict read + serialized PATCH live in the store (#4115): a corrupt file+// rejects instead of reading as DEFAULT_SETTINGS and being overwritten.+const settingsStore = createSettingsStore(SETTINGS_FILE, DEFAULT_SETTINGS);-export async function updateSettings(partial) {- const next = { ...(await getSettings()), ...partial };- await atomicWrite(SETTINGS_FILE, next);- return next;-}+export const getSettings = settingsStore.get;+export const updateSettings = settingsStore.update;/*** Which Obsidian vault transcripts go to: the explicit setting when present,