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
test: harden settings.json direct-write suites against getSettings read-cache (#2225)
Adam Eivy8b61ecdcfc8f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 57b4e7eec9..3e220da264 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -125,6 +125,8 @@- **`getSettings()` now serves from an in-memory cache instead of re-reading settings.json on every call.** `getSettings()` is invoked 100+ times across the codebase (several per request), each previously doing a fresh filesystem read + JSON.parse of app-wide, rarely-changing data. It now memoizes the parsed settings, populated lazily on first read and refreshed off the `settings:updated` event that every `save()`/`updateSettings()`/`updateSettingsWith()` already emits — so app-driven writes keep the cache coherent while write paths still read fresh off disk inside their write queue for the read-merge-write, preserving write-ordering guarantees. Mirrors the existing `settings:updated`-invalidated cache in `sharing/annotationIdentity.js`. Alongside it, a few independent per-file read loops are now parallelized (`digital-twin-analysis.validateCompleteness`, editorial series-health's series+settings load) and hot page derivations memoized (`Review` grouping/sorting, `Tribe` care-queue), cutting redundant work on socket-driven re-renders.+- **[issue-2225] Test suites that write settings.json directly are now hardened against the `getSettings()` read-cache.** The cache added in the perf change above only refreshes off the `settings:updated` event `save()` emits, so a test that writes settings.json straight to disk (bypassing `save()`) can read a stale cache after a prior `getSettings()` warmed it. Two suites already patched this inline (`authGate.test.js`, `publicApiIntegration.test.js`); two more (`auth.test.js`, `settings.secretsStrip.test.js`) only passed because their `vi.resetModules()` incidentally discarded the cache after each write — an unasserted ordering that a future warm-then-direct-write would silently regress. A new shared test util `server/lib/settingsTestUtil.js` exposes `bindSettingsFile(dataRoot)` → `writeSettingsFile` / `mergeSettingsFile`, which do the disk write **and** the cache reset (via the required dynamic import of `__resetSettingsCache`, since a static import binds to a pre-`resetModules` instance) in one place. All four suites now route through it, so future direct-writers get correct invalidation for free. Footgun-removal only — no behavior change. (`server/lib/settingsTestUtil.js`, `server/lib/authGate.test.js`, `server/routes/publicApiIntegration.test.js`, `server/routes/auth.test.js`, `server/routes/settings.secretsStrip.test.js`)+- **Branch & PR reconciliation now runs on any managed app as a Chief-of-Staff scheduled task — not just PortOS.** The branch reconciler (finish this machine's unfinished local git work: delete fully-merged orphaned branches + their worktrees, open PRs for pushed-but-unopened work, resolve merge conflicts, drive the review loop, and auto-merge when a PR is green) used to be a PortOS-only feature with its own daily cron, `/api/branch-reconcile` route, `settings.branchReconcile` toggle, and a dedicated Settings tab — hardwired to the PortOS checkout. It is now a first-class per-app CoS task type, **`branch-reconcile`**, configured like every other improvement task (per-app enable, provider/model, cadence, cooldown, budget) under Chief of Staff → task scheduling. It runs `perpetual` (drain-until-done): each dispatch runs the deterministic, peer-safe cleanup + classification against the *app's* repo, dispatches the coordinator agent only while actionable in-flight branches remain, then parks on a daily recheck — so no agent is burned on a no-op run. A progress-signature convergence guard ensures the drain only re-dispatches when the actionable set actually *changed* since the last run (a branch advanced NEEDS_PR→IN_REVIEW→merged, or a new/removed branch): a cycle that leaves the same branches in the same states (a branch judged "not ready", a PR blocked on human review or red CI) parks instead of re-spawning an identical coordinator back-to-back. The peer-safety guarantee is unchanged (only local `refs/heads/` are ever touched; a federated peer's branch exists here only as a remote-tracking ref and is structurally invisible), and the per-behavior toggles (`cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge`) are now per-app task-metadata overrides. Off by default; enabling it on an app is the user's explicit consent to let it drive PRs on a schedule. The old dedicated scheduler, route, settings key, and Settings tab are removed; a migration (`scripts/migrations/170-branch-reconcile-to-cos-task.js`) carries a previously-enabled `branchReconcile` opt-in into the new task (cron→recheckCron, actions→per-app metadata) scoped to the PortOS app, and drops the dead settings key — so an install that had it on keeps reconciling instead of silently stopping. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.diff --git a/server/lib/README.md b/server/lib/README.mdindex 5b1fb1c39c..d006a562d2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -270,4 +270,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |+| `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. || `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`). |diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex ad70338eeb..e380be8200 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -1,7 +1,8 @@import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { readFileSync, writeFileSync } from 'fs';+import { writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from './mockPathsDataRoot.js';+import { bindSettingsFile } from './settingsTestUtil.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-authgate-' });@@ -10,6 +11,11 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});+// Direct settings.json writes that also drop the getSettings() read cache —+// see server/lib/settingsTestUtil.js for why the reset is required here+// (a prior setPassword() warms the cache; a bypass-save() write leaves it stale).+const { mergeSettingsFile } = bindSettingsFile(tempRoot);+const resetSettings = () => {writeFileSync(join(tempRoot, 'settings.json'), '{}\n');writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');@@ -18,18 +24,7 @@ const resetSettings = () => {// Merge an apiAccess block into settings.json (preserving any auth secrets a// prior setPassword() call wrote). setPassword persists secrets to the same// file, so read-modify-write rather than clobbering.-// getSettings() memoizes the parsed file and only refreshes off the-// `settings:updated` event that save() emits. This helper writes settings.json-// directly (bypassing save()), so a prior getSettings — e.g. from setPassword —-// would leave the cache stale on this apiAccess block. Drop the cache so the-// subsequent authGate read observes the freshly-written file.-const writeApiAccess = async (apiAccess) => {- const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));- raw.apiAccess = apiAccess;- writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');- const { __resetSettingsCache } = await import('../services/settings.js');- __resetSettingsCache();-};+const writeApiAccess = (apiAccess) => mergeSettingsFile({ apiAccess });beforeEach(() => {vi.resetModules();diff --git a/server/lib/index.js b/server/lib/index.jsindex 68352f2201..4a85db345e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -237,4 +237,5 @@ export * from './zodCompat.js';// === Test support (consumed by *.test.js files) ===export * from './mockPathsDataRoot.js';+export * from './settingsTestUtil.js';export * from './testHelper.js';diff --git a/server/lib/settingsTestUtil.js b/server/lib/settingsTestUtil.jsnew file mode 100644index 0000000000..bc11839e97--- /dev/null+++ b/server/lib/settingsTestUtil.js@@ -0,0 +1,65 @@+/**+ * Test-only helpers for suites that write `data/settings.json` DIRECTLY on disk+ * (bypassing `saveSettings`/`updateSettings`).+ *+ * Why this exists: `getSettings()` in `server/services/settings.js` memoizes the+ * parsed settings.json in a module-level cache and only refreshes it off the+ * `settings:updated` event that `save()`/`updateSettings()`/`updateSettingsWith()`+ * emit. A test that writes settings.json directly (e.g. to flip `apiAccess`,+ * seed `secrets`, or reset to `{}`) does NOT go through `save()`, so any prior+ * `getSettings()` — commonly warmed by a `setPassword()` call — leaves the cache+ * stale and the code under test reads pre-write values. Route every direct write+ * through this helper so the cache is dropped in one place and future+ * direct-writers get correct invalidation for free. This mirrors the production+ * `reloadSettings()` contract (re-sync the cache after an out-of-band write) —+ * see the read-cache comment block in `server/services/settings.js`.+ *+ * `__resetSettingsCache` is loaded via a DYNAMIC import inside each helper, NOT+ * a static top-of-file import: suites `vi.resetModules()` between builds, so the+ * app under test binds a FRESH `settings.js` instance each time. A static import+ * here would bind to a stale pre-reset instance whose cache the app never reads,+ * making the reset a silent no-op.+ *+ * `bindSettingsFile(dataRoot)` binds the temp data dir (from `mockPathsDataRoot`)+ * once and returns `{ writeSettingsFile, mergeSettingsFile }` so call sites stay+ * short. This is a dedicated util rather than a method on `mockPathsDataRoot` so+ * the generic path-mock harness stays decoupled from the settings service.+ */++import { readFileSync, writeFileSync } from 'fs';+import { join } from 'path';++const settingsPath = (dataRoot) => join(dataRoot, 'settings.json');++// Serialize with a trailing newline to match `save()`'s on-disk format.+const persist = (dataRoot, obj) => {+ writeFileSync(settingsPath(dataRoot), JSON.stringify(obj, null, 2) + '\n');+};++const dropCache = async () => {+ const { __resetSettingsCache } = await import('../services/settings.js');+ __resetSettingsCache();+};++/**+ * Bind a temp data root to the settings direct-write helpers.+ * @param {string} dataRoot - the temp dir standing in for `PATHS.data`.+ * @returns {{ writeSettingsFile: (obj: object) => Promise<void>,+ * mergeSettingsFile: (patch: object) => Promise<void> }}+ */+export function bindSettingsFile(dataRoot) {+ // Write the FULL settings object, then invalidate the read cache.+ const writeSettingsFile = async (obj) => {+ persist(dataRoot, obj);+ await dropCache();+ };+ // Shallow-merge `patch` over the current on-disk settings (read-modify-write),+ // then invalidate — for suites that flip one top-level key (e.g. `apiAccess`)+ // while preserving secrets a prior `setPassword()` wrote to the same file.+ const mergeSettingsFile = async (patch) => {+ const raw = JSON.parse(readFileSync(settingsPath(dataRoot), 'utf-8'));+ persist(dataRoot, { ...raw, ...patch });+ await dropCache();+ };+ return { writeSettingsFile, mergeSettingsFile };+}diff --git a/server/routes/auth.test.js b/server/routes/auth.test.jsindex 7ece4818e7..60682b1209 100644--- a/server/routes/auth.test.js+++ b/server/routes/auth.test.js@@ -3,6 +3,7 @@ import express from 'express';import { writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { bindSettingsFile } from '../lib/settingsTestUtil.js';import { request } from '../lib/testHelper.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-auth-routes-' });@@ -12,9 +13,16 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});-const resetSettings = () => {- writeFileSync(join(tempRoot, 'settings.json'), '{}\n');+// Reset settings.json through the shared helper so the getSettings() read cache+// is dropped on every reset — see server/lib/settingsTestUtil.js. This suite+// passes today only because buildApp()'s vi.resetModules() incidentally discards+// the cache AFTER this write; routing through the helper makes the invalidation+// an explicit invariant so a future warm-then-direct-write can't regress silently.+const { writeSettingsFile } = bindSettingsFile(tempRoot);++const resetSettings = async () => {writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');+ await writeSettingsFile({});};const buildApp = async () => {@@ -28,8 +36,8 @@ const buildApp = async () => {return app;};-beforeEach(() => {- resetSettings();+beforeEach(async () => {+ await resetSettings();});afterAll(() => {diff --git a/server/routes/publicApiIntegration.test.js b/server/routes/publicApiIntegration.test.jsindex 73a2d1da56..7dbaa5df9f 100644--- a/server/routes/publicApiIntegration.test.js+++ b/server/routes/publicApiIntegration.test.js@@ -9,11 +9,12 @@* else is the production code path.*/import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { writeFileSync, readFileSync } from 'fs';+import { writeFileSync } from 'fs';import { join } from 'path';import express from 'express';import { request } from '../lib/testHelper.js';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { bindSettingsFile } from '../lib/settingsTestUtil.js';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-publicapi-' });@@ -36,21 +37,16 @@ vi.mock('../services/voice/tts-piper.js', () => ({listPiperVoices: vi.fn(async () => [{ name: 'en_GB-jenny_dioco-medium' }]),}));+// Direct settings.json writes that also drop the getSettings() read cache —+// see server/lib/settingsTestUtil.js for why the reset is required here+// (a prior setPassword() warms the cache; a bypass-save() write leaves it stale).+const { mergeSettingsFile } = bindSettingsFile(tempRoot);+const resetSettings = (extra = {}) => {writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(extra, null, 2) + '\n');writeFileSync(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}\n');};-// getSettings() memoizes the parsed file and only refreshes off save()'s-// `settings:updated` event. This helper writes settings.json directly, so a-// prior getSettings (e.g. from setPassword) would leave the cache stale on this-// apiAccess block — drop the cache so the app built next reads the fresh file.-const setApiAccess = async (apiAccess) => {- const raw = JSON.parse(readFileSync(join(tempRoot, 'settings.json'), 'utf-8'));- raw.apiAccess = apiAccess;- writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(raw, null, 2) + '\n');- const { __resetSettingsCache } = await import('../services/settings.js');- __resetSettingsCache();-};+const setApiAccess = (apiAccess) => mergeSettingsFile({ apiAccess });const buildApp = async () => {const { authGate } = await import('../lib/authGate.js');diff --git a/server/routes/settings.secretsStrip.test.js b/server/routes/settings.secretsStrip.test.jsindex 00bccc9f1c..bf59f6514d 100644--- a/server/routes/settings.secretsStrip.test.js+++ b/server/routes/settings.secretsStrip.test.js@@ -1,8 +1,9 @@import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import express from 'express';-import { writeFileSync, readFileSync } from 'fs';+import { readFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { bindSettingsFile } from '../lib/settingsTestUtil.js';import { request } from '../lib/testHelper.js';// Regression for the auth-disable-bypass: a `PUT /api/settings` body@@ -19,9 +20,14 @@ vi.mock('../lib/fileUtils.js', async () => {return makeProxy(actual);});-const seedSettings = (settings) => {- writeFileSync(join(tempRoot, 'settings.json'), JSON.stringify(settings, null, 2) + '\n');-};+// Seed settings.json through the shared helper so the getSettings() read cache+// is dropped on every seed — see server/lib/settingsTestUtil.js. This suite+// passes today only because buildApp()'s vi.resetModules() incidentally discards+// the cache AFTER this write; routing through the helper makes the invalidation+// an explicit invariant so a future warm-then-direct-write can't regress silently.+const { writeSettingsFile } = bindSettingsFile(tempRoot);++const seedSettings = (settings) => writeSettingsFile(settings);const readSettingsFile = () => {const raw = readFileSync(join(tempRoot, 'settings.json'), 'utf8');@@ -37,8 +43,8 @@ const buildApp = async () => {return app;};-beforeEach(() => {- seedSettings({});+beforeEach(async () => {+ await seedSettings({});});afterAll(() => {@@ -47,7 +53,7 @@ afterAll(() => {describe('PUT /api/settings — secrets-strip', () => {it('drops a `secrets` key from the incoming body', async () => {- seedSettings({+ await seedSettings({timezone: 'UTC',secrets: { auth: { enabled: true, passwordHash: 'preserved-hash', salt: 'preserved-salt' } },});@@ -67,7 +73,7 @@ describe('PUT /api/settings — secrets-strip', () => {});it('drops an empty `secrets: {}` (which would otherwise wipe nested secrets via shallow merge)', async () => {- seedSettings({+ await seedSettings({secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' }, telegram: { token: 't' } },});const app = await buildApp();@@ -92,7 +98,7 @@ describe('PUT /api/settings — secrets-strip', () => {// status routes, so stripping the raw values is non-breaking.describe('GET /api/settings — external token redaction', () => {it('omits imageGen.hfToken and civitai.apiKey while preserving siblings', async () => {- seedSettings({+ await seedSettings({timezone: 'UTC',imageGen: { hfToken: 'hf_secret123', defaultModel: 'flux' },civitai: { apiKey: 'civ_secret456', autoDownload: true },@@ -113,7 +119,7 @@ describe('GET /api/settings — external token redaction', () => {});it('leaves settings without those keys unchanged', async () => {- seedSettings({ timezone: 'UTC', imageGen: { defaultModel: 'flux' } });+ await seedSettings({ timezone: 'UTC', imageGen: { defaultModel: 'flux' } });const app = await buildApp();const res = await request(app).get('/api/settings');expect(res.status).toBe(200);@@ -122,7 +128,7 @@ describe('GET /api/settings — external token redaction', () => {});it('does not spread a malformed array-valued civitai into index keys', async () => {- seedSettings({ civitai: ['legacy-junk'] });+ await seedSettings({ civitai: ['legacy-junk'] });const app = await buildApp();const res = await request(app).get('/api/settings');expect(res.status).toBe(200);@@ -133,7 +139,7 @@ describe('GET /api/settings — external token redaction', () => {it('also redacts the tokens from the PUT /api/settings save response', async () => {// Tokens already persisted; an unrelated save must not echo them back —// otherwise the leak just moves from initial load to the save round-trip.- seedSettings({+ await seedSettings({imageGen: { hfToken: 'hf_secret123', defaultModel: 'flux' },civitai: { apiKey: 'civ_secret456' },});@@ -155,7 +161,7 @@ describe('GET /api/settings — external token redaction', () => {// re-inject the persisted token so an unrelated slice save doesn't silently// delete the credential.it('preserves a persisted hfToken when a PUT replaces imageGen without it', async () => {- seedSettings({ imageGen: { hfToken: 'hf_keepme', mode: 'local' } });+ await seedSettings({ imageGen: { hfToken: 'hf_keepme', mode: 'local' } });const app = await buildApp();const res = await request(app).put('/api/settings')@@ -170,7 +176,7 @@ describe('GET /api/settings — external token redaction', () => {});it('preserves a persisted civitai.apiKey when a PUT replaces civitai without it', async () => {- seedSettings({ civitai: { apiKey: 'civ_keepme', autoDownload: true } });+ await seedSettings({ civitai: { apiKey: 'civ_keepme', autoDownload: true } });const app = await buildApp();const res = await request(app).put('/api/settings')@@ -182,7 +188,7 @@ describe('GET /api/settings — external token redaction', () => {});it('leaves a persisted token untouched when the PUT omits its parent entirely', async () => {- seedSettings({ imageGen: { hfToken: 'hf_keepme' }, timezone: 'UTC' });+ await seedSettings({ imageGen: { hfToken: 'hf_keepme' }, timezone: 'UTC' });const app = await buildApp();const res = await request(app).put('/api/settings').send({ timezone: 'America/Los_Angeles' });expect(res.status).toBe(200);