Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve independent partial settings saves (#11045)
Adam Eivyb56d5f2df124
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 6907110251..1473b7c737 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -481,11 +481,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdatesetFileGaps(paused && typeof resumeFileGaps === 'boolean' ? resumeFileGaps : false);}, [seriesId, series?.autopilot?.status, resumeIncludeVisual, resumeFileGaps]);// Persist a setting (clamped) so a later Resume picks it up server-side.- // patchSettingsSlice is a GET-merge-PUT, so two overlapping calls (a blur save- // racing start()'s save) can lose an update — a slow earlier PUT lands after a- // newer one and clobbers it. Serialize every write onto one tail promise so the- // cycles can't interleave; start() awaiting its own enqueued write transitively- // awaits any in-flight blur save. Returns the promise so start() can await it.+ // Keep same-control writes ordered so start() also waits for an in-flight+ // blur save. Independent settings patches are merged atomically server-side.const persistTailRef = useRef(Promise.resolve());const persistRounds = useCallback((patch) => {const next = persistTailRef.currentdiff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex ff1565a0c0..444b976e6a 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -729,7 +729,7 @@ export default function VideoGen() {}, []);const handleSavePythonPath = useCallback(async (path) => {- await patchSettingsSlice('imageGen.local', { pythonPath: path || undefined }, { silent: true })+ await patchSettingsSlice('imageGen.local', { pythonPath: path || null }, { silent: true }).then(() => refreshStatus()).catch((err) => toast.error(`Failed to save: ${err.message}`));}, [refreshStatus]);diff --git a/client/src/services/README.md b/client/src/services/README.mdindex c93f0b7a11..2d7a99ec08 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -66,7 +66,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing (`getSystemActivity` for the bounded snapshot, `getGpuTelemetry` for visible-only GPU samples) and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`, `getClaudeCodeModelUsage` (per-model token totals for all local Claude Code use, from CLI transcripts), `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. |+| `apiSystem.js` | Atomic partial settings saves (`patchSettingsSlice`, server-queued PATCH with no browser GET/merge), system info (CPU/memory/ports/alerts/active processing (`getSystemActivity` for the bounded snapshot, `getGpuTelemetry` for visible-only GPU samples) and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`, `getClaudeCodeModelUsage` (per-model token totals for all local Claude Code use, from CLI transcripts), `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. Also the Eidoverse world controls and its foundation ledger (`listEidoverseFoundations`, `recordEidoverseFoundation`, `packageEidoverseFoundationCandidate`, `promoteEidoverseFoundation`, `getEidoverseContributions`) — the last three answer 200 with a refusal verdict when a promote gate says no, so callers read `outcome` rather than catching. || `apiAuth.js` | Optional login password — status, login, set/clear password, list/revoke sessions, and read-only password-risk status. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 5598a84d4e..74078d0533 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -198,16 +198,8 @@ export const updateAiAssignment = (id, data, options) => request(`/settings/ai-aconst isPlainObject = (v) =>v != null && typeof v === 'object' && !Array.isArray(v);-// PUT /api/settings shallow-merges top-level keys only — patching-// `{ imageGen: { local: { pythonPath } } }` directly clobbers the rest of-// `imageGen`. patchSettingsSlice fetches current settings, walks to the slice-// at a dotted path, shallow-merges `partial` into it, and PUTs the rebuilt-// top-level key so sibling subkeys survive. `options` flows through to the-// final updateSettings (e.g. `{ silent: true }`).-//-// Non-object values along the path (a hand-edited settings.json with an-// unexpected primitive/array at a slice or parent) are treated as absent so-// they don't spread into character-indexed or numeric-indexed keys.+// The server merges this partial into the freshest persisted slice inside its+// write queue. No browser-side snapshot can overwrite an independent save.export const patchSettingsSlice = async (slicePath, partial, options = {}) => {if (typeof slicePath !== 'string' || !slicePath) {throw new Error('patchSettingsSlice: slicePath required');@@ -215,20 +207,14 @@ export const patchSettingsSlice = async (slicePath, partial, options = {}) => {if (!isPlainObject(partial)) {throw new Error('patchSettingsSlice: partial must be a plain object');}- const segments = slicePath.split('.');- if (!segments.every(Boolean)) {+ if (!slicePath.split('.').every(Boolean)) {throw new Error('patchSettingsSlice: slicePath has empty segments');}- const current = await getSettings({ silent: true }).catch(() => ({}));- let existing = current;- for (const seg of segments) existing = existing?.[seg];- let updated = { ...(isPlainObject(existing) ? existing : {}), ...partial };- for (let i = segments.length - 1; i > 0; i--) {- let parent = current;- for (let j = 0; j < i; j++) parent = parent?.[segments[j]];- updated = { ...(isPlainObject(parent) ? parent : {}), [segments[i]]: updated };- }- return updateSettings({ [segments[0]]: updated }, options);+ return request('/settings/slice', {+ ...options,+ method: 'PATCH',+ body: JSON.stringify({ slicePath, partial }),+ });};// Usage. `params` selects the cost-report window: { period } (7d|30d|90d|all)diff --git a/client/src/services/apiSystem.test.js b/client/src/services/apiSystem.test.jsindex d777b05877..255d252975 100644--- a/client/src/services/apiSystem.test.js+++ b/client/src/services/apiSystem.test.js@@ -1,141 +1,44 @@+// @vitest-environment nodeimport { describe, it, expect, vi, beforeEach } from 'vitest';+import { request } from './apiCore.js';+import { patchSettingsSlice } from './apiSystem.js';-vi.mock('./apiCore.js', () => ({- request: vi.fn(),-}));--let request;-let patchSettingsSlice;--beforeEach(async () => {- vi.resetModules();- ({ request } = await import('./apiCore.js'));- ({ patchSettingsSlice } = await import('./apiSystem.js'));- request.mockReset();-});--const mockSettings = (settings) => {- request.mockImplementation((path, opts) => {- if (path === '/settings' && (!opts || opts.method !== 'PUT')) {- return Promise.resolve(settings);- }- return Promise.resolve({ ok: true });- });-};+vi.mock('./apiCore.js', () => ({ request: vi.fn() }));+beforeEach(() => { request.mockReset(); });describe('patchSettingsSlice', () => {- it('preserves sibling subkeys when patching a deep slice', async () => {- mockSettings({- imageGen: {- mode: 'codex',- external: { sdapiUrl: 'http://x' },- local: { pythonPath: '/old', denoise: true },- codex: { enabled: true },- },+ it('sends only the partial mutation without reading or replacing settings', async () => {+ request.mockResolvedValue({ localLlm: { mtplx: { keepLoaded: true } } });+ const saved = await patchSettingsSlice('localLlm.mtplx', { keepLoaded: true }, { silent: true });+ expect(request).toHaveBeenCalledExactlyOnceWith('/settings/slice', {+ method: 'PATCH',+ body: JSON.stringify({ slicePath: 'localLlm.mtplx', partial: { keepLoaded: true } }),+ silent: true,});- await patchSettingsSlice('imageGen.local', { pythonPath: '/new' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- expect(putCall).toBeDefined();- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({- imageGen: {- mode: 'codex',- external: { sdapiUrl: 'http://x' },- local: { pythonPath: '/new', denoise: true },- codex: { enabled: true },- },- });- });-- it('preserves sibling top-level subkeys when patching a one-level slice', async () => {- mockSettings({- pipeline: {- imageGen: { provider: 'old' },- videoGen: { mode: 'i2v' },- },- unrelated: { keep: true },- });- await patchSettingsSlice('pipeline', { imageGen: { provider: 'new' } });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({- pipeline: {- imageGen: { provider: 'new' },- videoGen: { mode: 'i2v' },- },- });- // Top-level `unrelated` is never in the PUT body — the server merges by- // top-level key, so omitting it leaves it untouched on disk.- expect(body.unrelated).toBeUndefined();- });-- it('creates the slice path when it does not exist yet', async () => {- mockSettings({});- await patchSettingsSlice('writersRoom.imageGen', { foo: 'bar' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({ writersRoom: { imageGen: { foo: 'bar' } } });+ expect(saved.localLlm.mtplx.keepLoaded).toBe(true);});- it('falls back to an empty slice when getSettings rejects', async () => {- request.mockImplementation((path, opts) => {- if (path === '/settings' && (!opts || opts.method !== 'PUT')) {- return Promise.reject(new Error('boom'));- }- return Promise.resolve({ ok: true });- });- await patchSettingsSlice('imageGen.local', { pythonPath: '/x' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({ imageGen: { local: { pythonPath: '/x' } } });+ it('propagates failed server reads/writes without attempting a fallback PUT', async () => {+ request.mockRejectedValue(new Error('Settings unavailable'));+ await expect(patchSettingsSlice('imageGen.local', { pythonPath: null })).rejects.toThrow('Settings unavailable');+ expect(request).toHaveBeenCalledTimes(1);+ expect(request.mock.calls[0][1].method).toBe('PATCH');});- it('passes options through to updateSettings', async () => {- mockSettings({});- await patchSettingsSlice('backup', { destPath: '/tmp' }, { silent: true });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- expect(putCall[1].silent).toBe(true);+ it('preserves explicit empty and null clearing in the request', async () => {+ request.mockResolvedValue({});+ await patchSettingsSlice('imageGen.local', { pythonPath: null });+ expect(JSON.parse(request.mock.calls[0][1].body).partial).toEqual({ pythonPath: null });+ await patchSettingsSlice('localLlm.mtplx', { launch: {} });+ expect(JSON.parse(request.mock.calls[1][1].body).partial).toEqual({ launch: {} });});- it('throws on missing slicePath', async () => {+ it('rejects malformed arguments before sending a mutation', async () => {await expect(patchSettingsSlice('', {})).rejects.toThrow(/slicePath required/);- });-- it('throws on non-object partial', async () => {- await expect(patchSettingsSlice('imageGen', null)).rejects.toThrow(/plain object/);- await expect(patchSettingsSlice('imageGen', [])).rejects.toThrow(/plain object/);- await expect(patchSettingsSlice('imageGen', 'foo')).rejects.toThrow(/plain object/);- });-- it('throws on empty path segments', async () => {- await expect(patchSettingsSlice('imageGen..local', { x: 1 })).rejects.toThrow(/empty segments/);- await expect(patchSettingsSlice('imageGen.', { x: 1 })).rejects.toThrow(/empty segments/);- await expect(patchSettingsSlice('.imageGen', { x: 1 })).rejects.toThrow(/empty segments/);- });-- it('treats a non-object slice value as absent (does not spread strings into chars)', async () => {- mockSettings({ imageGen: { local: 'oops-not-an-object' } });- await patchSettingsSlice('imageGen.local', { pythonPath: '/x' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({ imageGen: { local: { pythonPath: '/x' } } });- });-- it('treats a non-object parent as absent', async () => {- mockSettings({ imageGen: 'oops' });- await patchSettingsSlice('imageGen.local', { pythonPath: '/x' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({ imageGen: { local: { pythonPath: '/x' } } });- });-- it('treats an array at the slice as absent', async () => {- mockSettings({ imageGen: { local: [1, 2, 3] } });- await patchSettingsSlice('imageGen.local', { pythonPath: '/x' });- const putCall = request.mock.calls.find(([, opts]) => opts?.method === 'PUT');- const body = JSON.parse(putCall[1].body);- expect(body).toEqual({ imageGen: { local: { pythonPath: '/x' } } });+ await expect(patchSettingsSlice('imageGen..local', {})).rejects.toThrow(/empty segments/);+ for (const partial of [null, [], 'invalid']) {+ await expect(patchSettingsSlice('imageGen.local', partial)).rejects.toThrow(/plain object/);+ }+ expect(request).not.toHaveBeenCalled();});});--// @vitest-environment nodediff --git a/docs/API.md b/docs/API.mdindex f2a24ae888..35e499edcb 100644--- a/docs/API.md+++ b/docs/API.md@@ -30,6 +30,23 @@ When adding an HTTP route, keep its request Zod schema in a reusable server librBuilding a native companion client? See [COMPANION_APP_API.md](./COMPANION_APP_API.md) — the stable, pre-auth-discoverable contract (discovery/identity, HTTP Basic auth vs. operator sessions, instance management, palette actions, daily-log, POST progress, and the iCloud-sync precedent) that the PortDeck app consumes. Basic auth alone does not grant peer management or host control — those need an operator session obtained via `POST /api/auth/login`, same as this section's [Security Model](#security-model) describes for host control below.+### Partial settings saves++`PATCH /api/settings/slice` accepts `{ slicePath, partial }`. It shallow-merges+the supplied keys at the selected slice inside the settings write queue, keeping+sibling settings and concurrent independent edits. Supplied objects and arrays+replace that key; explicit null/empty values clear fields where their schema allows.+Unreadable/malformed persisted settings and failed writes return errors.++Supported paths are `localLlm.ollama`, `localLlm.lmstudio`, `localLlm.llama`,+`localLlm.mtplx`, `localLlm.slotstream`, `imageGen.local`, `pipeline`,+`writersRoom`, `seriesAutopilot`, `pipelineEditorialChecks`, and `autoUpdate`.+Only the current controls' fields are accepted; credential/auth paths and+prototype-related keys are rejected. Execution-policy and changed executable+fields retain the same operator authority checks as `PUT /api/settings`,+including authorized local agents. Legacy PUT keeps its top-level replacement+semantics.+## Security ModelPortOS can execute host commands and access private files. It must remain on the user's private network; a reachable LAN or tailnet peer is not automatically trustworthy. It implements the following security measures:diff --git a/server/lib/README.md b/server/lib/README.mdindex 201088aaea..c01f080d4d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -668,7 +668,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `apiAccessPolicy.js` | Shared always-public path, gated non-`/api` prefix, and peer-credential federation surface (`PEER_API_SURFACE`, `isPeerApiRequestAllowed`) policy consumed by `authGate` and API discovery. || `apiCatalog.js` | Searchable projection of the Express route inventory (`getApiRouteCatalog()` from `apiRouteGraph.js`): domain, access, side-effect, contract coverage, summaries, and Express-to-OpenAPI path conversion. |-| `hostControlRoutes.js` | The audited `HOST_CONTROL_ROUTES` list of HTTP routes that execute on the host (app lifecycle, CoS agent queueing, git, scaffold, standardize, feature agents, loops, GSD, local review, provider execution config, autopilot start) plus `hostControlRouteFor` / `isHostControlRoute`; `authGate.js#hostControlRouteGate` applies `requireHostControl` to every entry. `hostControlBodyKeys` names the execution-policy keys of a `PUT /api/settings` / `PUT /api/cos/config` body (`HOST_CONTROL_SETTINGS_SLICES`, `HOST_CONTROL_OPEN_COS_CONFIG_KEYS`), and `hostControlSettingsPathsIn` / `changedHostControlSettingsPaths` the nested settings keys that pick an executable (`HOST_CONTROL_SETTINGS_PATHS`, gated only when the value changes). `voiceConfigHostControlPathsIn` / `changedVoiceConfigHostControlPaths` do the same for the voice agent's instructions and coding-agent switch (`HOST_CONTROL_VOICE_CONFIG_PATHS` on `PUT /api/voice/config`). All of these are gated by `authGate.js#hostControlBodyGate`. The socket twin is `HOST_CONTROL_SOCKET_EVENTS` in `services/socket.js`. |+| `hostControlRoutes.js` | The audited `HOST_CONTROL_ROUTES` list of HTTP routes that execute on the host (app lifecycle, CoS agent queueing, git, scaffold, standardize, feature agents, loops, GSD, local review, provider execution config, autopilot start) plus `hostControlRouteFor` / `isHostControlRoute`; `authGate.js#hostControlRouteGate` applies `requireHostControl` to every entry. `hostControlBodyKeys` names the execution-policy keys of a `PUT /api/settings`, `PATCH /api/settings/slice`, or `PUT /api/cos/config` body (`HOST_CONTROL_SETTINGS_SLICES`, `HOST_CONTROL_OPEN_COS_CONFIG_KEYS`), and `hostControlSettingsPathsIn` / `changedHostControlSettingsPaths` the nested settings keys that pick an executable (`HOST_CONTROL_SETTINGS_PATHS`, gated only when the value changes). `voiceConfigHostControlPathsIn` / `changedVoiceConfigHostControlPaths` do the same for the voice agent's instructions and coding-agent switch (`HOST_CONTROL_VOICE_CONFIG_PATHS` on `PUT /api/voice/config`). All of these are gated by `authGate.js#hostControlBodyGate`. The socket twin is `HOST_CONTROL_SOCKET_EVENTS` in `services/socket.js`. || `apiRouteGraph.js` | Static scan of the mounted HTTP route graph — `server/index.js` `app.use('/api/…', router)` mounts → route-module imports → `router.use(prefix, child)` → `router.<method>('<path>')`, including aliased mounts, local subrouters, factory returns and composed `toolkit.routes.<x>` routers. `buildApiRouteCatalog({ repoRoot? })` → `{ derivedFrom, mounts, routes: [{ method, path, mountPath, sources }], stats }`; `getApiRouteCatalog()` derives it on first use and caches it for the process (read by the API Explorer, the internal OpenAPI document and `apiRouteParity.test.js`); `scanRouteGraph()` adds `declarationKeys` / `duplicateDeclarationKeys` (`routeDeclarationKey`) for the coverage guard in `apiRouteGraph.test.js`. Never committed — see "Generated manifests" in `server/AGENTS.md`. || `socketEventCatalog.js` | Searchable projection of the cached Socket.IO inventory: direction, domain, and runtime-schema coverage. || `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. `blankCommentBodies(src)` is the complement — comments blanked, literal TEXT kept — for a caller that reads a message string and must not see a marker written in a comment beside it. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/logLevelConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. |diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.jsindex 820283e64d..3af7a1665c 100644--- a/server/lib/apiOperationContracts.js+++ b/server/lib/apiOperationContracts.js@@ -10,7 +10,7 @@ import { TTS_ENGINE_IDS } from './voiceEngines.js';import { cosToolCallSchema } from './cosToolContracts.js';import { agentContextMcpInboundSchema } from './agentContextValidation.js';import {- gitBranchBodySchema, gitBranchComparisonBodySchema, gitCommitBodySchema, gitCommitsBodySchema, gitDeleteBranchBodySchema,+ settingsSlicePatchSchema, gitBranchBodySchema, gitBranchComparisonBodySchema, gitCommitBodySchema, gitCommitsBodySchema, gitDeleteBranchBodySchema,logsQuerySchema, pm2ProcessNameSchema, gitDiffBodySchema, gitOptionalBranchBodySchema, gitPathBodySchema, gitRemoteBranchesBodySchema, gitStageBodySchema,} from './validation.js';@@ -31,6 +31,19 @@ const gitWriteOperation = (summary, schema) => ({});export const API_OPERATION_CONTRACTS = Object.freeze({+ '/api/settings/slice': {+ patch: {+ summary: 'Atomically merge a partial settings slice',+ description: 'Shallow merge at the allowlisted slice against the freshest persisted settings. Explicit values replace keys; legacy PUT semantics are unchanged. Executable and execution-policy changes require operator authority.',+ requestBody: jsonBody(settingsSlicePatchSchema),+ responses: {+ 200: { description: 'Saved settings with protected values redacted' },+ 400: { description: 'Invalid path, partial settings, or interpreter', 'x-portos-error-codes': ['VALIDATION_ERROR', 'INVALID_PYTHON_PATH'] },+ 403: { description: 'Caller lacks host authority for a protected change', 'x-portos-error-codes': ['HOST_CONTROL_FORBIDDEN'] },+ 500: { description: 'Persisted settings could not be read or written', 'x-portos-error-codes': ['INTERNAL_ERROR'] },+ },+ },+ },'/api/logs/{processName}': {get: {summary: 'Read or follow one PM2 process log',diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex dd7f88ce78..be82142741 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -139,7 +139,7 @@* account and change external state; they require operator authority.*/-import { canonicalStringify, isPlainObject } from './objects.js';+import { canonicalStringify, isPlainObject, POLLUTING_KEYS } from './objects.js';import { LLM_DRILL_TYPES } from './postDrillTypes.js';import { escapeRegExp } from './textUtils.js';@@ -781,7 +781,7 @@ export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([]);/**- * Nested `PUT /api/settings` keys, as dotted paths, that choose a binary+ * Nested settings mutation keys, as dotted paths, that choose a binary* PortOS spawns (the image-gen CLIs and the Python interpreter every local* media lane runs) or turn the Layered Intelligence `cmd` sources into a* full shell (#8751). Their parent slices stay open, so each is gated per@@ -853,6 +853,7 @@ const COMPILED_BODY_ROUTES = [// Enabling this feature now launches its registered host executable.['PUT /api/settings/features/eidoverse', (body) => bodyKeys(body)],['POST /api/local-llm/capability-tests/run', (body) => body?.testId === 'sandbox-repair' ? ['testId'] : []],+ ['PATCH /api/settings/slice', (body) => HOST_CONTROL_SETTINGS_SLICES.includes(body?.slicePath) ? [body.slicePath] : []],['PUT /api/settings', (body) => bodyKeys(body).filter((key) => HOST_CONTROL_SETTINGS_SLICES.includes(key)|| (key === 'instanceFeatures' && body.instanceFeatures?.eidoverse !== undefined))],['PUT /api/cos/config', (body) => bodyKeys(body).filter((key) => !HOST_CONTROL_OPEN_COS_CONFIG_KEYS.includes(key))],@@ -883,18 +884,29 @@ const valueAt = (object, path) => path.split('.').reduce(const isUnset = (value) => value === undefined || value === null || value === '' || value === false;const SETTINGS_WRITE = compileRoute('PUT /api/settings');+const SETTINGS_SLICE_WRITE = compileRoute('PATCH /api/settings/slice');++// Project the allowlisted one/two-segment slice payload into the same shape+// the legacy PUT gate compares. Invalid paths are rejected by route validation.+const settingsBody = (method, path, body) => {+ if (method?.toUpperCase() !== SETTINGS_SLICE_WRITE.method || !SETTINGS_SLICE_WRITE.pattern.test(path)) return body;+ if (typeof body?.slicePath !== 'string') return {};+ const segments = body.slicePath.split('.');+ if (segments.length > 2 || segments.some((key) => !key || POLLUTING_KEYS.has(key))) return {};+ return segments.reduceRight((value, key) => ({ [key]: value }), body.partial);+};-/** The HOST_CONTROL_SETTINGS_PATHS a `method path` body sets to a non-default value, for `PUT /api/settings`; [] elsewhere. */+/** The executable settings paths set by PUT or a slice PATCH; [] elsewhere. */export const hostControlSettingsPathsIn = (method, path, body) => (typeof method === 'string' && typeof path === 'string'- && method.toUpperCase() === SETTINGS_WRITE.method && SETTINGS_WRITE.pattern.test(path)- ? HOST_CONTROL_SETTINGS_PATHS.filter((key) => !isUnset(valueAt(body, key)))+ && [SETTINGS_WRITE, SETTINGS_SLICE_WRITE].some((entry) => method.toUpperCase() === entry.method && entry.pattern.test(path))+ ? HOST_CONTROL_SETTINGS_PATHS.filter((key) => !isUnset(valueAt(settingsBody(method, path, body), key))): []);/** Of `paths`, the ones whose value in `body` differs from the stored `current` settings. */-export const changedHostControlSettingsPaths = (paths, body, current) => (- paths.filter((key) => !Object.is(valueAt(body, key), valueAt(current, key)))+export const changedHostControlSettingsPaths = (paths, body, current, method = 'PUT', path = '/api/settings') => (+ paths.filter((key) => !Object.is(valueAt(settingsBody(method, path, body), key), valueAt(current, key))));const VOICE_CONFIG_WRITE = compileRoute('PUT /api/voice/config');diff --git a/server/lib/validation.js b/server/lib/validation.jsindex beab9c4107..4be72ba8ec 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -4,6 +4,8 @@ export { MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from './imageLimits.js';import { CREDENTIALS } from './credentialRegistry.js';import { DEFAULT_BACKUP_CRON, MIN_RETENTION_COUNT, MAX_RETENTION_COUNT } from './backupConfig.js';import { z } from 'zod';+import { POLLUTING_KEYS } from './objects.js';+import { pipelineEditorialChecksSettingsSchema } from './pipelineValidation.js';import { ServerError } from './errorHandler.js';import { isSafeGitRef } from './gitArgs.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap, presetProviderIdSchema, providerRefSchema } from './zodCompat.js';@@ -13,7 +15,7 @@ import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';import { APP_FEATURE_IDS, INSTANCE_FEATURE_IDS, INSTANCE_FEATURE_GROUP_IDS } from './instanceFeatureRegistry.js';import { MAX_MONTHLY_COST } from './subscriptionSavings.js';import { MAX_PLAN_TIER_LENGTH } from './subscriptionPlanTiers.js';-import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';+import { IMAGE_GEN_MODES, QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';import { FAL_IMAGE_MODEL_IDS } from './falImageModels.js';import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';import {@@ -2198,6 +2200,62 @@ export const localLlmSettingsSchema = z.object({}).strict().optional(),}).strict();+// Only slices written by patchSettingsSlice callers belong on this mutation+// surface. Credentials/auth and executable-policy parents have dedicated APIs.+const renderFormNumberSchema = z.union([+ z.number().finite(),+ z.string().max(30).refine((value) => value === '' || Number.isFinite(Number(value)), 'Must be numeric or empty'),+]);+const renderFormSettingsSchema = z.object({+ mode: z.enum(IMAGE_GEN_MODES).optional(),+ modelId: z.string().max(300).nullable().optional(),+ cloudModel: z.string().max(300).nullable().optional(),+ width: z.number().int().positive().max(MAX_IMAGE_EDGE).optional(),+ height: z.number().int().positive().max(MAX_IMAGE_EDGE).optional(),+ steps: renderFormNumberSchema.optional(),+ guidance: renderFormNumberSchema.optional(),+ cfgScale: renderFormNumberSchema.optional(),+ quantize: z.enum(['3', '4', '5', '6', '8']).optional(),+ seed: renderFormNumberSchema.optional(),+ negativePrompt: z.string().max(4000).optional(),+ extraStyle: z.string().max(4000).optional(),+}).strict();++export const settingsSlicePartialSchemas = Object.freeze({+ ...Object.fromEntries(Object.entries(localLlmSettingsSchema.shape)+ .map(([runtime, schema]) => [`localLlm.${runtime}`, schema.unwrap()])),+ 'imageGen.local': z.object({+ pythonPath: z.string().max(500).nullable().optional(),+ }).strict(),+ pipeline: z.object({ imageGen: renderFormSettingsSchema.nullable().optional() }).strict(),+ writersRoom: z.object({ imageGen: renderFormSettingsSchema.nullable().optional() }).strict(),+ seriesAutopilot: seriesAutopilotSettingsSchema.partial(),+ pipelineEditorialChecks: pipelineEditorialChecksSettingsSchema.partial(),+ autoUpdate: autoUpdateSettingsSchema,+});++// Check raw JSON before Zod can strip a dangerous key. Arrays can contain+// nested objects too; none may smuggle prototype-related property names.+const hasPollutingKey = (value) => value !== null && typeof value === 'object'+ && Object.entries(value).some(([key, child]) => POLLUTING_KEYS.has(key) || hasPollutingKey(child));++export const settingsSlicePatchSchema = z.preprocess((value, ctx) => {+ if (hasPollutingKey(value)) {+ ctx.addIssue({ code: 'custom', message: 'Prototype-related keys are forbidden' });+ }+ return value;+}, z.object({+ slicePath: z.enum(Object.keys(settingsSlicePartialSchemas)),+ partial: z.record(z.unknown()),+}).strict().superRefine(({ slicePath, partial }, ctx) => {+ const result = settingsSlicePartialSchemas[slicePath].safeParse(partial);+ if (!result.success) {+ for (const issue of result.error.issues) {+ ctx.addIssue({ ...issue, path: ['partial', ...issue.path] });+ }+ }+}));+// =============================================================================// LM STUDIO (server/routes/lmstudio.js)// =============================================================================diff --git a/server/routes/settings.js b/server/routes/settings.jsindex f875a85df1..fe3912fd78 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -26,7 +26,7 @@ import { storableAutoUpdateConfig } from '../lib/sharedSchemas.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, beeperSavedScopesSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';+import { settingsSlicePatchSchema, privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, beeperSavedScopesSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -406,98 +406,98 @@ router.delete('/orchestration-profiles/:id', asyncHandler(async (req, res) => {res.json(result);}));-// PUT /api/settings-router.put('/', asyncHandler(async (req, res) => {- if (req.body?.orchestrationProfiles !== undefined) {- validateRequest(orchestrationProfilesSettingsSchema, req.body.orchestrationProfiles);+// Shared validation keeps PATCH and legacy PUT on the same configuration contracts.+const validateSettingsPatch = async (body) => {+ if (body?.orchestrationProfiles !== undefined) {+ validateRequest(orchestrationProfilesSettingsSchema, body.orchestrationProfiles);}// Settings is a polymorphic store but the backup sub-object has a known// schema. Validate that slice when it's present so a malformed Backup-tab// save doesn't reach disk (the runtime guards downstream are belt-and-// suspenders, but per project convention all inputs are validated).- if (req.body?.untrustedContent !== undefined) {- validateRequest(untrustedContentSettingsSchema, req.body.untrustedContent);+ if (body?.untrustedContent !== undefined) {+ validateRequest(untrustedContentSettingsSchema, body.untrustedContent);}// Per-harness enablement and the credential-bootstrap app table (#7564):// both are read at composite-provider resolve time, so a malformed entry// would surface as a run that cannot spawn rather than a 400 here.- if (req.body?.harnesses !== undefined) {- validateRequest(harnessSettingsSchema, req.body.harnesses);+ if (body?.harnesses !== undefined) {+ validateRequest(harnessSettingsSchema, body.harnesses);}- if (req.body?.credentialBootstraps !== undefined) {- validateRequest(credentialBootstrapsSettingsSchema, req.body.credentialBootstraps);+ if (body?.credentialBootstraps !== undefined) {+ validateRequest(credentialBootstrapsSettingsSchema, body.credentialBootstraps);}- if (req.body?.backup !== undefined) {- validateRequest(backupConfigSchema.partial(), req.body.backup);+ if (body?.backup !== undefined) {+ validateRequest(backupConfigSchema.partial(), body.backup);}- if (req.body?.autoUpdate !== undefined) {- validateRequest(autoUpdateSettingsSchema, req.body.autoUpdate);+ if (body?.autoUpdate !== undefined) {+ validateRequest(autoUpdateSettingsSchema, body.autoUpdate);}- if (req.body?.sharingDisplayName !== undefined || req.body?.sharingBio !== undefined) {+ if (body?.sharingDisplayName !== undefined || body?.sharingBio !== undefined) {validateRequest(sharingSettingsPatchSchema.partial(), {- sharingDisplayName: req.body.sharingDisplayName,- sharingBio: req.body.sharingBio,+ sharingDisplayName: body.sharingDisplayName,+ sharingBio: body.sharingBio,});}// Per-feature AI provider assignments — validate each slice when present so// a malformed picker save can't write a non-string providerId/model to disk.- if (req.body?.autofixer !== undefined) {- validateRequest(autofixerSettingsSchema.partial(), req.body.autofixer);+ if (body?.autofixer !== undefined) {+ validateRequest(autofixerSettingsSchema.partial(), body.autofixer);}- if (req.body?.calendarSync !== undefined) {- validateRequest(featureProviderConfigSchema.partial(), req.body.calendarSync);+ if (body?.calendarSync !== undefined) {+ validateRequest(featureProviderConfigSchema.partial(), body.calendarSync);}- if (req.body?.codeReview !== undefined) {- validateRequest(codeReviewSettingsSchema.partial(), req.body.codeReview);+ if (body?.codeReview !== undefined) {+ validateRequest(codeReviewSettingsSchema.partial(), body.codeReview);}// Creative Director's treatment, plan, and scene-evaluation provider/model// pins — validate the slice when present so a malformed picker save can't// write a bad provider config.- if (req.body?.creativeDirector !== undefined) {- validateRequest(creativeDirectorSettingsSchema.partial(), req.body.creativeDirector);+ if (body?.creativeDirector !== undefined) {+ validateRequest(creativeDirectorSettingsSchema.partial(), body.creativeDirector);}// Music studio slice (#2911) — the chiptune provider pin + publish prefs.- if (req.body?.music !== undefined) {- validateRequest(musicSettingsSchema.partial(), req.body.music);+ if (body?.music !== undefined) {+ validateRequest(musicSettingsSchema.partial(), body.music);}- if (req.body?.federation !== undefined) {- validateRequest(federationSettingsSchema, req.body.federation);+ if (body?.federation !== undefined) {+ validateRequest(federationSettingsSchema, body.federation);// The schema only proves a route is well-SHAPED. A route naming a peer that// is unknown, switched off, not a media provider, not allowlisted for that// model, or outside the tailnet is well-shaped and permanently unusable —// and unattended work has no human at the moment it fails, so it would just// break every future Creative Director / Commission render in silence.// Refuse it here, where there IS a human. See routingPolicy.js.- await assertMediaRoutingConfig(req.body.federation.mediaRouting);+ await assertMediaRoutingConfig(body.federation.mediaRouting);}// Home location ({ lat, lon }) read by the weather_now voice tool. The schema// already makes both fields optional + nullable (clearing falls back to the// tool default), and the refine enforces both-or-neither — so validate the// whole slice rather than .partial()ing away that pairing rule.- if (req.body?.location !== undefined) {- validateRequest(locationSettingsSchema, req.body.location);+ if (body?.location !== undefined) {+ validateRequest(locationSettingsSchema, body.location);}- if (req.body?.networkSetupPreference !== undefined) {- validateRequest(networkSetupPreferenceSchema, req.body.networkSetupPreference);+ if (body?.networkSetupPreference !== undefined) {+ validateRequest(networkSetupPreferenceSchema, body.networkSetupPreference);}- if (req.body?.hideFirstRunCard !== undefined) {- validateRequest(hideFirstRunCardSchema, req.body.hideFirstRunCard);+ if (body?.hideFirstRunCard !== undefined) {+ validateRequest(hideFirstRunCardSchema, body.hideFirstRunCard);}- if (req.body?.embeddings !== undefined) {- validateRequest(settingsEmbeddingsSchema.partial(), req.body.embeddings);+ if (body?.embeddings !== undefined) {+ validateRequest(settingsEmbeddingsSchema.partial(), body.embeddings);}- if (req.body?.localLlm !== undefined) {- validateRequest(localLlmSettingsSchema, req.body.localLlm);+ if (body?.localLlm !== undefined) {+ validateRequest(localLlmSettingsSchema, body.localLlm);}// iMessage ingestion config (#2151) — validate the slice when present so a// malformed enabled/interval can't reach disk and break the sync scheduler.- if (req.body?.imessage !== undefined) {- validateRequest(imessageConfigSchema.partial(), req.body.imessage);+ if (body?.imessage !== undefined) {+ validateRequest(imessageConfigSchema.partial(), body.imessage);}// Signal ingestion config (#2154) — validate the slice when present so a// malformed enabled/interval can't reach disk and break the sync scheduler.- if (req.body?.signal !== undefined) {- validateRequest(signalConfigSchema.partial(), req.body.signal);+ if (body?.signal !== undefined) {+ validateRequest(signalConfigSchema.partial(), body.signal);}// Beeper Desktop bridge ingestion + connection config (#30) — validate the// slice when present so a malformed enabled/interval/baseUrl/budget can't@@ -510,84 +510,84 @@ router.put('/', asyncHandler(async (req, res) => {// `.partial()` was a no-op), and the schema's `superRefine` (SEC-2's// loopback-only `baseUrl` gate) returns a `ZodEffects`, which has no// `.partial()` method at all.- if (req.body?.beeperSavedScopes !== undefined) {- validateRequest(beeperSavedScopesSchema, req.body.beeperSavedScopes);+ if (body?.beeperSavedScopes !== undefined) {+ validateRequest(beeperSavedScopesSchema, body.beeperSavedScopes);}- if (req.body?.beeper !== undefined) {- validateRequest(beeperSettingsSchema, req.body.beeper);+ if (body?.beeper !== undefined) {+ validateRequest(beeperSettingsSchema, body.beeper);}// Spotify ingestion config (#2152) — validate the slice when present so a// malformed enabled/interval can't reach disk and break the sync scheduler.- if (req.body?.spotify !== undefined) {- validateRequest(spotifyConfigSchema.partial(), req.body.spotify);+ if (body?.spotify !== undefined) {+ validateRequest(spotifyConfigSchema.partial(), body.spotify);}// YouTube watch-history scrape config (#2153) — validate the slice when present// so a malformed enabled/interval can't reach disk and break the sync scheduler.- if (req.body?.youtube !== undefined) {- validateRequest(youtubeConfigSchema.partial(), req.body.youtube);+ if (body?.youtube !== undefined) {+ validateRequest(youtubeConfigSchema.partial(), body.youtube);}// LoRA training config (caption provider + training defaults) — validate// the slice when present so a malformed save can't write bad bounds the// trainer would then pass to the python child.- if (req.body?.loraTraining !== undefined) {- validateRequest(loraTrainingConfigSchema.partial(), req.body.loraTraining);+ if (body?.loraTraining !== undefined) {+ validateRequest(loraTrainingConfigSchema.partial(), body.loraTraining);}// Per-API external-access flags (voice/sdapi). Validate the slice when present// so a malformed toggle save can't write a non-boolean exposed/requireAuth to// disk (the registry would then silently treat it as its default).- if (req.body?.apiAccess !== undefined) {- validateRequest(apiAccessSettingsSchema.partial(), req.body.apiAccess);+ if (body?.apiAccess !== undefined) {+ validateRequest(apiAccessSettingsSchema.partial(), body.apiAccess);}- if (req.body?.instanceFeatures !== undefined) {- validateRequest(instanceFeatureSettingsSchema, req.body.instanceFeatures);+ if (body?.instanceFeatures !== undefined) {+ validateRequest(instanceFeatureSettingsSchema, body.instanceFeatures);}// Instance feature GROUP participation (#40) — same shape guard as the// per-feature slice above, keyed on the separate group id list.- if (req.body?.instanceFeatureGroups !== undefined) {- validateRequest(instanceFeatureGroupSettingsSchema, req.body.instanceFeatureGroups);+ if (body?.instanceFeatureGroups !== undefined) {+ validateRequest(instanceFeatureGroupSettingsSchema, body.instanceFeatureGroups);}// Local MCP agent-context opt-in. Validate the whole strict slice so an// unknown scope/profile cannot silently broaden what the server exposes.- if (req.body?.agentContext !== undefined) {- validateRequest(agentContextSettingsSchema, req.body.agentContext);+ if (body?.agentContext !== undefined) {+ validateRequest(agentContextSettingsSchema, body.agentContext);}// Editorial-check enable/config slice (#1284) — validate when present so a// malformed save can't write a non-boolean enabled / non-object config the// registry would then choke on.- if (req.body?.pipelineEditorialChecks !== undefined) {- validateRequest(pipelineEditorialChecksSettingsSchema.partial(), req.body.pipelineEditorialChecks);+ if (body?.pipelineEditorialChecks !== undefined) {+ validateRequest(pipelineEditorialChecksSettingsSchema.partial(), body.pipelineEditorialChecks);}// Privacy Center opt-out recheck config (#2145) — validate the slice when// present so a malformed cron / non-boolean autonomy toggle can't reach disk// and break the recheck scheduler. Both autonomy toggles default OFF.- if (req.body?.privacy !== undefined) {- validateRequest(privacySettingsSchema.partial(), req.body.privacy);+ if (body?.privacy !== undefined) {+ validateRequest(privacySettingsSchema.partial(), body.privacy);}// Scheduled Series Autopilot config (#2174) — validate the slice when present// so an invalid cron (rejected by the schema's isValidCronExpression refine) or// bad seriesId can't reach disk and leave an "enabled" schedule that never fires.// `.partial()` so a PUT that only carries { schedules } still validates.- if (req.body?.seriesAutopilot !== undefined) {- validateRequest(seriesAutopilotSettingsSchema.partial(), req.body.seriesAutopilot);+ if (body?.seriesAutopilot !== undefined) {+ validateRequest(seriesAutopilotSettingsSchema.partial(), body.seriesAutopilot);}// Grok Imagegen settings slice (#2859) — validate when present so a malformed// save can't write a bad aspect ratio (which lands verbatim in the grok// prompt) or a non-boolean enabled gate to disk. The imageGen parent stays// polymorphic; only the grok sub-slice has a schema here.- if (req.body?.imageGen?.grok !== undefined) {- validateRequest(imageGenGrokSettingsSchema.partial(), req.body.imageGen.grok);+ if (body?.imageGen?.grok !== undefined) {+ validateRequest(imageGenGrokSettingsSchema.partial(), body.imageGen.grok);}- if (req.body?.imageGen?.agy !== undefined) {- validateRequest(imageGenAgySettingsSchema.partial(), req.body.imageGen.agy);+ if (body?.imageGen?.agy !== undefined) {+ validateRequest(imageGenAgySettingsSchema.partial(), body.imageGen.agy);}- if (req.body?.imageGen?.fal !== undefined) {- validateRequest(imageGenFalSettingsSchema.partial(), req.body.imageGen.fal);+ if (body?.imageGen?.fal !== undefined) {+ validateRequest(imageGenFalSettingsSchema.partial(), body.imageGen.fal);}// Every local media lane spawns this interpreter (and image gen spawns the// `mflux-generate` beside it), so hold it to the guard the setup routes use:// a python basename, never an arbitrary binary (#8751). A cleared value// (`''`/`null`) falls back to interpreter discovery, so it stays allowed.- const localPython = req.body?.imageGen?.local?.pythonPath;+ const localPython = body?.imageGen?.local?.pythonPath;if (localPython != null && localPython !== '' && !isAllowedPython(localPython)) {throw new ServerError('imageGen.local.pythonPath must be a python interpreter (basename python/python3/python3.NN)', {status: 400, code: 'INVALID_PYTHON_PATH',@@ -597,39 +597,42 @@ router.put('/', asyncHandler(async (req, res) => {// target key or a non-enum backend can't persist a slice the render-target// resolver would then silently ignore (or worse, hand an invalid model id// to a cloud CLI's argv).- if (req.body?.renderDefaults !== undefined) {- validateRequest(renderDefaultsSettingsSchema, req.body.renderDefaults);+ if (body?.renderDefaults !== undefined) {+ validateRequest(renderDefaultsSettingsSchema, body.renderDefaults);}// Install-wide video render pin (#3231 Phase 4) — validate when present so a// non-enum backend can't persist a mode resolveVideoMode would choke on.- if (req.body?.videoGen !== undefined) {- validateRequest(videoGenSettingsSchema, req.body.videoGen);+ if (body?.videoGen !== undefined) {+ validateRequest(videoGenSettingsSchema, body.videoGen);}// Install-level Layered Intelligence settings (#2515) — validate the slice when// present so a malformed `trustShellSources` can't persist and silently unlock// full-shell custom `cmd` sources install-wide.- if (req.body.layeredIntelligence) {- validateRequest(layeredIntelligenceSettingsSchema.partial(), req.body.layeredIntelligence);+ if (body.layeredIntelligence) {+ validateRequest(layeredIntelligenceSettingsSchema.partial(), body.layeredIntelligence);}// Subscription plan prices — the same schema PUT /api/usage/subscriptions// enforces, so a legacy client or restore bundle can't write a junk family// key or an over-cap price through the generic settings endpoint. Without it// the value persists, reads back as "not priced", and is silently deleted by// the next save from the usage page.- if (req.body?.subscriptionCosts !== undefined) {- validateRequest(subscriptionCostsMapSchema, req.body.subscriptionCosts);+ if (body?.subscriptionCosts !== undefined) {+ validateRequest(subscriptionCostsMapSchema, body.subscriptionCosts);}// Plan tiers ride the same rails as the prices beside them, for the same// reason: an unvalidated key here would persist, read back as "no tier", and// be dropped by the next save from the Subscriptions page.- if (req.body?.subscriptionPlanTiers !== undefined) {- validateRequest(subscriptionPlanTiersMapSchema, req.body.subscriptionPlanTiers);+ if (body?.subscriptionPlanTiers !== undefined) {+ validateRequest(subscriptionPlanTiersMapSchema, body.subscriptionPlanTiers);}// Same schema PUT /api/usage/fleet-billing's store uses, so a restore dump// can't write an unbounded or non-string list through the generic endpoint.- if (req.body?.usageApiBilledInstanceIds !== undefined) {- validateRequest(usageApiBilledInstanceIdsSchema, req.body.usageApiBilledInstanceIds);+ if (body?.usageApiBilledInstanceIds !== undefined) {+ validateRequest(usageApiBilledInstanceIdsSchema, body.usageApiBilledInstanceIds);}+};++const saveSettingsPatch = async (body, slicePatch) => {// User-defined catalog types moved out of settings.json into PostgreSQL// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacy@@ -655,8 +658,8 @@ router.put('/', asyncHandler(async (req, res) => {subscriptionCosts: subscriptionCostsPatch,subscriptionPlanTiers: subscriptionPlanTiersPatch,usageApiBilledInstanceIds: apiBilledPatch,- ...settingsPatch- } = req.body || {};+ ...initialSettingsPatch+ } = body || {};// updateSettingsWith (not updateSettings) so the multi-owner `federation`// slice merges per sub-key and persisted write-only tokens the incoming patch// omits get re-injected — both against the freshest snapshot inside the write@@ -664,14 +667,26 @@ router.put('/', asyncHandler(async (req, res) => {// `actor: 'user'` is what separates a save made HERE — a human on the Settings// page — from every other `save()` caller (schedulers, sync hooks, feature// writes), which keep the `'system'` default in the operator-action ledger (#5594).+ let settingsPatch = initialSettingsPatch;let previousBeeperEnabled;let previousBeeperIntervalMinutes;let previousBeeperConnection;let previousBeeperGates;- let merged = await updateSettingsWith((current) => {+ let merged = await updateSettingsWith(async (current) => {// Read inside the queue, against the freshest persisted snapshot (same// reasoning as `mergeFederationSlice` above) — a stale pre-image here could// read a no-op as a flip, or a real flip as a no-op.+ if (slicePatch) {+ const { slicePath, partial } = slicePatch;+ const [root, child] = slicePath.split('.');+ const parent = isPlainObject(current[root]) ? current[root] : {};+ const existing = child ? parent[child] : current[root];+ // Shallow merge at exactly the selected slice: objects/arrays/null supplied+ // as values replace that key, including explicit clearing.+ const updated = { ...(isPlainObject(existing) ? existing : {}), ...partial };+ settingsPatch = { [root]: child ? { ...parent, [child]: updated } : updated };+ await validateSettingsPatch(settingsPatch);+ }previousBeeperEnabled = current?.beeper?.enabled === true;previousBeeperIntervalMinutes = current?.beeper?.intervalMinutes;previousBeeperConnection = JSON.stringify([current?.beeper?.baseUrl, current?.beeper?.allowNonLoopbackBaseUrl]);@@ -686,7 +701,7 @@ router.put('/', asyncHandler(async (req, res) => {mergeFederationSlice(next, current),current,);- }, { actor: 'user' });+ }, { actor: 'user', ...(slicePatch ? { requireReadable: true } : {}) });if (settingsPatch.instanceFeatures?.eidoverse !== undefined) {const { reconcileEidoverseRuntime } = await import('../services/eidoverseRuntime.js');await reconcileEidoverseRuntime()@@ -753,7 +768,18 @@ router.put('/', asyncHandler(async (req, res) => {// already emitted it — so an added/removed/edited schedule takes effect// immediately without a restart, and this route stays decoupled from the// autopilot pipeline graph.- res.json(sanitizeSettingsForResponse(merged));+ return sanitizeSettingsForResponse(merged);+};++// PUT remains a top-level replacement contract for whole-form and older callers.+router.put('/', asyncHandler(async (req, res) => {+ await validateSettingsPatch(req.body);+ res.json(await saveSettingsPatch(req.body));+}));++router.patch('/slice', asyncHandler(async (req, res) => {+ const patch = validateRequest(settingsSlicePatchSchema, req.body);+ res.json(await saveSettingsPatch({}, patch));}));export default router;diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex c0a5555721..ca9cee2b47 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -1,7 +1,27 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+const settingsDataRoot = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ return mkdtempSync(join(tmpdir(), 'portos-settings-routes-'));+});+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ const { makePathsProxy } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy({+ ...actual,+ tryReadFileStrict: vi.fn(actual.tryReadFileStrict),+ atomicWrite: vi.fn(actual.atomicWrite),+ }, { dataRoot: settingsDataRoot });+});+afterAll(async () => {+ const { rmSync } = await import('node:fs');+ rmSync(settingsDataRoot, { recursive: true, force: true });+});+const reconcileEidoverseRuntime = vi.hoisted(() => vi.fn(async () => ({ running: true })));vi.mock('../services/eidoverseRuntime.js', () => ({ reconcileEidoverseRuntime }));@@ -1457,3 +1477,146 @@ describe('autofixer settings slice', () => {expect((await request(app).get('/api/settings')).body.autofixer).toEqual(loaded.body.autofixer);});});+++// Real queued persistence through HTTP: a mock merge cannot prove independent+// requests retain each other's changes or refuse corrupt on-disk snapshots.+describe('Settings routes — atomic partial saves (#11045)', () => {+ let actual;+ let fs;+ let settingsFile;+ let fileUtils;+ let originalMutation;+ beforeEach(async () => {+ actual = await vi.importActual('../services/settings.js');+ fs = await import('node:fs');+ settingsFile = (await import('node:path')).join(settingsDataRoot, 'settings.json');+ fileUtils = await import('../lib/fileUtils.js');+ originalMutation = updateSettingsWith.getMockImplementation();+ updateSettingsWith.mockImplementation(actual.updateSettingsWith);+ vi.clearAllMocks();+ fs.writeFileSync(settingsFile, JSON.stringify({+ localLlm: { ollama: { disabled: true }, mtplx: { launch: { model: 'example-model' }, idleMinutes: 20 } },+ imageGen: { local: { pythonPath: '/example/python3', denoise: true }, codex: { enabled: true } },+ pipeline: { videoGen: { mode: 'i2v' } },+ secrets: { example: 'private-placeholder' },+ timezone: 'UTC',+ }));+ actual.__resetSettingsCache();+ });+ afterEach(() => {+ updateSettingsWith.mockImplementation(originalMutation);+ fileUtils.tryReadFileStrict.mockRestore();+ fileUtils.atomicWrite.mockRestore();+ });+ const patch = (app, slicePath, partial) => request(app).patch('/api/settings/slice').send({ slicePath, partial });+ const persisted = () => JSON.parse(fs.readFileSync(settingsFile, 'utf8'));++ it('retains sibling runtimes and keys when separate clients patch concurrently', async () => {+ const emitted = vi.fn();+ actual.settingsEvents.on('settings:updated', emitted);+ try {+ const responses = await Promise.all([+ patch(buildApp(), 'localLlm.ollama', { disabled: false }),+ patch(buildApp(), 'localLlm.mtplx', { idleMinutes: 5 }),+ patch(buildApp(), 'localLlm.mtplx', { keepLoaded: true }),+ ]);+ expect(responses.map((response) => response.status)).toEqual([200, 200, 200]);+ expect(persisted()).toMatchObject({+ localLlm: { ollama: { disabled: false }, mtplx: { launch: { model: 'example-model' }, idleMinutes: 5, keepLoaded: true } },+ timezone: 'UTC',+ });+ expect(emitted).toHaveBeenCalledTimes(3);+ const { recordUserAction } = await import('../services/userActions.js');+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({ type: 'settings.update', actor: 'user' }));+ } finally {+ actual.settingsEvents.off('settings:updated', emitted);+ }+ });++ it('keeps unrelated fields, permits explicit clearing, and reconciles saved settings', async () => {+ const app = buildApp();+ expect((await patch(app, 'imageGen.local', { pythonPath: null })).status).toBe(200);+ expect((await patch(app, 'localLlm.mtplx', { launch: {} })).status).toBe(200);+ expect((await patch(app, 'pipeline', { imageGen: { mode: 'external', quantize: '5', cfgScale: 7, steps: '' } })).status).toBe(200);+ expect((await patch(app, 'pipeline', { imageGen: null })).status).toBe(200);+ expect((await patch(app, 'seriesAutopilot', { schedules: [] })).status).toBe(200);+ expect(persisted()).toMatchObject({+ imageGen: { local: { pythonPath: null, denoise: true }, codex: { enabled: true } },+ localLlm: { mtplx: { launch: {}, idleMinutes: 20 } },+ pipeline: { imageGen: null, videoGen: { mode: 'i2v' } },+ seriesAutopilot: { schedules: [] },+ });+ const { setCodexParallelLimit } = await import('../services/mediaJobQueue/index.js');+ expect(setCodexParallelLimit).toHaveBeenCalled();+ const saved = await actual.getSettings();+ expect(saved.secrets.example).toBe('private-placeholder');+ });++ it('rejects invalid values, unapproved paths and credential/prototype keys without writes', async () => {+ const before = fs.readFileSync(settingsFile, 'utf8');+ for (const [path, partial] of [+ ['secrets.auth', { enabled: false }],+ ['imageGen', { hfToken: 'example-token' }],+ ['imageGen.local', { hfToken: 'example-token' }],+ ['imageGen.local', { pythonPath: '/example/sh' }],+ ['localLlm.mtplx', { idleMinutes: -1 }],+ ['localLlm.mtplx', { launch: { model: [] } }],+ ['autoUpdate', { enabled: 'yes' }],+ ['pipeline', { imageGen: { width: 'invalid' } }],+ ['pipelineEditorialChecks', { enabled: 'yes' }],+ ['seriesAutopilot', { schedules: [{ seriesId: 'example', cron: '99 99 * * *' }] }],+ ['localLlm.__proto__', {}],+ ['pipeline', JSON.parse('{"imageGen":{"constructor":{}}}')],+ ['pipeline', JSON.parse('{"__proto__":{"polluted":true}}')],+ ['pipeline', { imageGen: { steps: 'not-a-number' } }],+ ]) {+ expect((await patch(buildApp(), path, partial)).status, path).toBe(400);+ }+ expect(fs.readFileSync(settingsFile, 'utf8')).toBe(before);+ expect(fileUtils.atomicWrite).not.toHaveBeenCalled();+ });++ it('refuses malformed or unreadable persisted settings and recovers on a later valid read', async () => {+ const before = fs.readFileSync(settingsFile, 'utf8');+ fs.writeFileSync(settingsFile, '{ truncated');+ expect((await patch(buildApp(), 'localLlm.mtplx', { keepLoaded: true })).status).toBe(500);+ expect(fs.readFileSync(settingsFile, 'utf8')).toBe('{ truncated');+ fs.writeFileSync(settingsFile, before);+ fileUtils.tryReadFileStrict.mockResolvedValueOnce({ ok: false, value: null });+ expect((await patch(buildApp(), 'localLlm.mtplx', { keepLoaded: true })).status).toBe(500);+ expect(fileUtils.atomicWrite).not.toHaveBeenCalled();+ expect(fs.readFileSync(settingsFile, 'utf8')).toBe(before);+ expect((await patch(buildApp(), 'localLlm.mtplx', { keepLoaded: true })).status).toBe(200);+ expect(persisted().localLlm.mtplx.launch.model).toBe('example-model');+ });++ it('propagates persistence failures without emitting success or replacing state', async () => {+ const before = fs.readFileSync(settingsFile, 'utf8');+ const emitted = vi.fn();+ actual.settingsEvents.on('settings:updated', emitted);+ fileUtils.atomicWrite.mockRejectedValueOnce(new Error('Synthetic write failure'));+ try {+ expect((await patch(buildApp(), 'localLlm.mtplx', { keepLoaded: true })).status).toBe(500);+ expect(fs.readFileSync(settingsFile, 'utf8')).toBe(before);+ expect(emitted).not.toHaveBeenCalled();+ } finally {+ actual.settingsEvents.off('settings:updated', emitted);+ }+ });++ it('creates missing slices on a fresh install without spreading malformed parent values', async () => {+ fs.unlinkSync(settingsFile);+ expect((await patch(buildApp(), 'localLlm.mtplx', { idleMinutes: 5 })).status).toBe(200);+ expect(persisted().localLlm).toEqual({ mtplx: { idleMinutes: 5 } });+ fs.writeFileSync(settingsFile, JSON.stringify({ imageGen: 'legacy-malformed-parent' }));+ expect((await patch(buildApp(), 'imageGen.local', { pythonPath: '' })).status).toBe(200);+ expect(persisted().imageGen).toEqual({ local: { pythonPath: '' } });+ });++ it('keeps legacy PUT slice replacement semantics', async () => {+ const response = await request(buildApp()).put('/api/settings').send({ localLlm: { mtplx: { idleMinutes: 5 } } });+ expect(response.status).toBe(200);+ expect(persisted().localLlm).toEqual({ mtplx: { idleMinutes: 5 } });+ });+});diff --git a/server/services/authGate.js b/server/services/authGate.jsindex 247845f2c8..870d96fc76 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -285,7 +285,7 @@ export const hostControlBodyGate = async (req, res, next) => {if ((settingsNamed.length === 0 && voiceNamed.length === 0)|| hasHostControl(req.portosAuthContext, isLocalConnection(req.socket?.remoteAddress, req.headers))) return next();if (settingsNamed.length > 0- && changedHostControlSettingsPaths(settingsNamed, req.body, await getSettings()).length > 0) {+ && changedHostControlSettingsPaths(settingsNamed, req.body, await getSettings(), req.method, req.path).length > 0) {return requireHostControl(req, res, next);}if (voiceNamed.length > 0diff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex 389048df77..49aadc5a33 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -759,6 +759,10 @@ describe('mounted host-control trailing slashes (#8950)', () => {persist(req.body);res.json({ saved: true });});+ settings.patch('/slice', (req, res) => {+ persist(req.body);+ res.json({ saved: true });+ });app.use('/api/settings', settings);app.put('/api/settings/features/:featureId', (req, res) => {persist(req.body);@@ -770,6 +774,8 @@ describe('mounted host-control trailing slashes (#8950)', () => {const protectedBodies = [{ harnesses: {} },{ imageGen: { codex: { codexPath: '/example/codex' } } },+ // A PATCH-shaped extra field must not change how a legacy PUT is gated.+ { slicePath: 'pipeline', partial: {}, imageGen: { local: { pythonPath: '/example/python3' } } },];it('denies remote password-free dispatch and protected writes before either sink', async () => {@@ -792,6 +798,44 @@ describe('mounted host-control trailing slashes (#8950)', () => {expect(persist).toHaveBeenCalledExactlyOnceWith({ location: {} });});+ it('applies the PUT authority policy to slice patches, preserving delegated agents', async () => {+ const remote = await buildApp();+ const protectedPatches = [+ { slicePath: 'autoUpdate', partial: { enabled: true } },+ { slicePath: 'seriesAutopilot', partial: { schedules: [] } },+ { slicePath: 'imageGen.local', partial: { pythonPath: '/example/python3' } },+ ];+ for (const suffix of ['', '/', '//']) {+ for (const body of protectedPatches) {+ const response = await request(remote.app).patch('/api/settings/slice' + suffix).send(body);+ expect(response.status).toBe(403);+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');+ }+ }+ expect(remote.persist).not.toHaveBeenCalled();+ // The existing PUT allows data-only updates and clearing executable pins.+ expect((await request(remote.app).patch('/api/settings/slice').send({+ slicePath: 'localLlm.mtplx', partial: { keepLoaded: true },+ })).status).toBe(200);+ expect((await request(remote.app).patch('/api/settings/slice').send({+ slicePath: 'imageGen.local', partial: { pythonPath: null },+ })).status).toBe(200);+ const local = await buildApp('127.0.0.1');+ for (const body of protectedPatches) {+ expect((await request(local.app).patch('/api/settings/slice').send(body)).status).toBe(200);+ }+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'example-password' });+ const { resolveAgentApiEnv } = await import('./agentApiAuth.js');+ const { PORTOS_API_TOKEN: token } = await resolveAgentApiEnv();+ expect(token).toBeTruthy();+ for (const body of protectedPatches) {+ expect((await request(local.app).patch('/api/settings/slice')+ .set('Authorization', `Bearer ${token}`).send(body)).status).toBe(200);+ }+ expect(local.persist).toHaveBeenCalledTimes(6);+ });+it('requires operator authority to arm Eidoverse through either settings path', async () => {const remote = await buildApp();const body = { instanceFeatures: { eidoverse: { enabled: true } } };@@ -825,7 +869,7 @@ describe('mounted host-control trailing slashes (#8950)', () => {if (!allowed) expect(run.body.code).toBe('HOST_CONTROL_FORBIDDEN');}expect(runner.executeCliRun).toHaveBeenCalledTimes(allowed ? 3 : 0);- expect(persist).toHaveBeenCalledTimes(allowed ? 6 : 0);+ expect(persist).toHaveBeenCalledTimes(allowed ? 9 : 0);});});diff --git a/server/services/settings.js b/server/services/settings.jsindex 249784e649..3fc491ed3f 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -241,10 +241,10 @@ const diffSettings = (prev, next) => {** `actor` (#5594) names WHO is saving, and defaults to `'system'` — the honest* default, because most callers here are schedulers, sync hooks, and internal- * feature writes. Only `PUT /api/settings` passes `'user'`. `reloadSettings` does+ * feature writes. Settings HTTP mutations pass `'user'`. `reloadSettings` does* not call this at all, so a backup restore is excluded by construction.*/-const save = async (settings, { actor = 'system', skipUserAction = false } = {}) => {+const save = async (settings, { actor = 'system', skipUserAction = false } = {}, previousSettings) => {const cleaned = stripStoreKeys(settings);// Stamp `timezoneUpdatedAt` whenever the effective `timezone` actually// changes, so timezone-dependent schedulers can gate catch-up/re-evaluation@@ -255,7 +255,7 @@ const save = async (settings, { actor = 'system', skipUserAction = false } = {})// comparison is against the freshest persisted snapshot, and any prior// `timezoneUpdatedAt` on an unchanged-timezone save rides through untouched// via the merged object.- const prev = isPlainObject(cleaned) ? stripStoreKeys(await loadRaw()) : null;+ const prev = isPlainObject(cleaned) ? previousSettings ?? stripStoreKeys(await loadRaw()) : null;// Diff BEFORE the timezoneUpdatedAt stamp below, so a timezone change reports// `keysChanged: ['timezone']` rather than dragging in the derived stamp.const change = isPlainObject(prev) ? diffSettings(prev, cleaned) : null;@@ -382,8 +382,18 @@ export const updateSettings = (patch, options) => queueWrite(async () => {// between the external read and the queued write was clobbered by the caller's// stale pre-image. Here the read and the write share one queued turn, so the// mutator always sees the latest persisted snapshot.+// Pass { requireReadable: true } to refuse unreadable/malformed snapshots rather+// than using the legacy empty fallback; a confirmed absent file is still valid.export const updateSettingsWith = (mutate, options) => queueWrite(async () => {- const current = stripStoreKeys(await loadRaw());+ // Partial mutations must never turn a failed read into an empty base. Keep+ // ordinary readers/legacy writers compatible, but opt this contract into the+ // strict reader inside the same queued turn as the mutation and write.+ const strict = options?.requireReadable ? await readSettingsStrict() : null;+ if (strict?.corrupt) throw new Error('Cannot update settings: persisted settings are unreadable or malformed');+ const current = stripStoreKeys(strict+ ? await hydratePrivateKeys(strict.settings, PATHS.data)+ : await loadRaw());+ const previous = strict ? structuredClone(current) : undefined;const next = await mutate(current);// Guard the mutator's return BEFORE persisting: unlike the old// saveSettings(objectLiteral) callers, a mutator with a missing `return`@@ -392,5 +402,5 @@ export const updateSettingsWith = (mutate, options) => queueWrite(async () => {if (!isPlainObject(next)) {throw new TypeError('updateSettingsWith: mutate() must return a plain settings object');}- return save(next, options);+ return save(next, options, previous);});