Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: preserve restored CoS settings and runtime state (#8666)

[._.]/ Adam Eivyc642e14168a3
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 3e36a355a2..aa4955f818 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -168,3 +168,18 @@ Schema reconciliation follows the commit; a reconciliation failure explicitly
reports that replay committed and recovery still needs attention. Application
database operations drain before reset; new operations receive a temporary
maintenance error until replay and reconciliation finish (including failures).
+
+### Restoring CoS files in a running server
+
+A full live file restore or selective `cos` restore requires the CoS daemon and
+Persistent Mind to be stopped and active agents to be finished or stopped. The
+server rejects unsafe or unreadable ownership state before rsync starts, with
+`COS_RESTORE_BUSY`. Pausing the daemon alone is insufficient.
+
+The restore drains configuration writes, then runtime-state writes, and holds
+both queues through the transfer and cache reload. Both CoS caches are reloaded
+and the normal configuration-change event is emitted even after a partial rsync
+failure. Subsequent partial settings saves preserve restored fields. Transfer
+errors still report that files may have been overwritten; a cache-reload failure
+requires restarting PortOS before using CoS. Dry runs and selective restores
+outside the CoS state/config scope do not acquire this boundary.
diff --git a/server/services/backup.js b/server/services/backup.js
index 47d22ef207..8abf886d59 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1429,26 +1429,34 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
// file whose digest outlasts the default deadline emits no `-ii` heartbeat
// until it finishes (#7302), so this restore's idle floor scales to it.
const idleTimeoutMs = restoreIdleTimeoutMs(verification.largestFileBytes);
- const [transfer] = await Promise.allSettled([runRsync(srcDir, PATHS.data, flags, { idleTimeoutMs })]);
- const reconciliationError = !dryRun
- ? await reconcileLiveFileRestore(subdirFilter).then(
- () => null,
- error => error,
- )
- : null;
-
- if (transfer.status === 'rejected') {
- if (dryRun) throw transfer.reason;
- const partialRestoreError = new Error(
- `${transfer.reason.message}. Some files may already have been overwritten because file restore is not transactional.${reconciliationError ? ` ${reconciliationError.message}` : ''}`,
- { cause: transfer.reason },
- );
- if (transfer.reason?.code) partialRestoreError.code = transfer.reason.code;
- throw partialRestoreError;
- }
- if (reconciliationError) throw reconciliationError;
+ const restoreFiles = async () => {
+ const [transfer] = await Promise.allSettled([runRsync(srcDir, PATHS.data, flags, { idleTimeoutMs })]);
+ const reconciliationError = !dryRun
+ ? await reconcileLiveFileRestore(subdirFilter).then(
+ () => null,
+ error => error,
+ )
+ : null;
+
+ if (transfer.status === 'rejected') {
+ if (dryRun) throw transfer.reason;
+ const partialRestoreError = new Error(
+ `${transfer.reason.message}. Some files may already have been overwritten because file restore is not transactional.${reconciliationError ? ` ${reconciliationError.message}` : ''}`,
+ { cause: transfer.reason },
+ );
+ if (transfer.reason?.code) partialRestoreError.code = transfer.reason.code;
+ throw partialRestoreError;
+ }
+ if (reconciliationError) throw reconciliationError;
- return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value, verification };
+ return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value, verification };
+ };
+ const scope = subdirFilter?.split('/').filter(part => part && part !== '.').join('/');
+ if (!dryRun && (!scope || ['cos', 'cos/config.json', 'cos/state.json'].includes(scope))) {
+ const { withLiveCosRestore } = await import('./cosState.js');
+ return withLiveCosRestore(restoreFiles);
+ }
+ return restoreFiles();
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 1018975ffd..21fd464f24 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2201,11 +2201,15 @@ describe('getState and saveState', () => {
// snapshotId validation + rsync filter construction + settings cache re-sync.
// restoreSnapshot writes over the user's live data/ directory, so each of these
// is a data-loss-adjacent contract, not a style nit (issue #3917).
+vi.mock('./cosState.js', () => ({ withLiveCosRestore: vi.fn(fn => fn()) }));
+import { withLiveCosRestore } from './cosState.js';
+
describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () => {
beforeEach(() => {
spawn.mockReset();
reloadSettings.mockClear();
invalidateBrainCaches.mockClear();
+ withLiveCosRestore.mockClear();
});
// Drive a mocked rsync to a clean exit so restoreSnapshot resolves.
@@ -2314,6 +2318,22 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
});
});
+ describe('CoS restore ownership boundary', () => {
+ it.each([undefined, 'cos', 'cos/', 'cos/config.json', 'cos/state.json'])('holds the boundary for affected live scope %s', async subdirFilter => {
+ await runRestore('/dest', 'snap-1', { dryRun: false, subdirFilter });
+ expect(withLiveCosRestore).toHaveBeenCalledTimes(1);
+ });
+ it.each([{ dryRun: true }, { dryRun: false, subdirFilter: 'images' }, { dryRun: false, subdirFilter: 'cos/agents' }])('leaves unaffected scope alone: %j', async options => {
+ await runRestore('/dest', 'snap-1', options);
+ expect(withLiveCosRestore).not.toHaveBeenCalled();
+ });
+ it('refuses unsafe CoS restore before rsync', async () => {
+ withLiveCosRestore.mockRejectedValueOnce(new Error('Stop CoS before restoring'));
+ await expect(restoreSnapshot('/dest', 'snap-1', { dryRun: false, subdirFilter: 'cos' })).rejects.toThrow('Stop CoS');
+ expect(spawn).not.toHaveBeenCalled();
+ });
+ });
+
describe('settings cache re-sync', () => {
it('reloads settings after a live restore', async () => {
await runRestore('/dest', 'snap-1', { dryRun: false });
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 7f54594647..58bd4b80cc 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -22,6 +22,8 @@ import {
createDefaultPersistentMindThinkingPresets,
normalizePersistentMindThinkingPresets,
} from '../lib/persistentMindThinkingPresets.js';
+import { cosEvents } from './cosEvents.js';
+import { ServerError } from '../lib/errorHandler.js';
import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';
export const STATE_FILE = join(PATHS.cos, 'state.json');
@@ -267,6 +269,21 @@ async function recoverFromUnreadableState(content) {
// In-memory config cache. Every mutation goes through `withConfigLock` +
// `saveConfig`, so the cache stays consistent.
let configCache = null;
+// Enumerable symbols survive a caller's shallow copy but never reach JSON.
+// Reject delayed writeback of a pre-restore read, even if queued afterwards.
+const RESTORE_GENERATION = Symbol('cosRestoreGeneration');
+let restoreGeneration = 0;
+function stampGeneration(value) {
+ value[RESTORE_GENERATION] = restoreGeneration;
+ return value;
+}
+function assertCurrentGeneration(value) {
+ if (value[RESTORE_GENERATION] !== undefined && value[RESTORE_GENERATION] !== restoreGeneration) {
+ throw new ServerError('CoS files were restored. Read the current state before retrying this change.', {
+ status: 409, code: 'COS_RESTORE_STALE_WRITE',
+ });
+ }
+}
/**
* Read the raw persisted config object, and say where it came from.
@@ -306,7 +323,7 @@ export async function loadConfig() {
if (configCache) return configCache;
await ensureDirectories();
const { config, fromConfigFile } = await readPersistedConfig();
- configCache = mergeStoredConfig(config);
+ configCache = stampGeneration(mergeStoredConfig(config));
// Recovering settings out of a legacy state.json is a READ; nothing has
// written them to their own file yet. `saveState` strips `config` from
// state.json on the very next runtime write, so leaving the recovery in
@@ -327,7 +344,8 @@ export async function loadConfig() {
*/
export async function saveConfig(config) {
await ensureDirectories();
- configCache = config;
+ assertCurrentGeneration(config);
+ configCache = stampGeneration(config);
if (stateCache) stateCache.config = config;
await atomicWrite(CONFIG_FILE, config);
return config;
@@ -372,7 +390,7 @@ export async function loadState() {
if (!existsSync(STATE_FILE)) {
stateCache = Object.assign(structuredClone(DEFAULT_STATE), { config });
- return stateCache;
+ return stampGeneration(stateCache);
}
const content = await readFile(STATE_FILE, 'utf-8');
@@ -380,7 +398,7 @@ export async function loadState() {
if (!state) {
stateCache = Object.assign(await recoverFromUnreadableState(content), { config });
- return stateCache;
+ return stampGeneration(stateCache);
}
stateCache = {
@@ -394,7 +412,7 @@ export async function loadState() {
persistentMind: normalizePersistentMindState(state.persistentMind),
agents: state.agents ?? {}
};
- return stateCache;
+ return stampGeneration(stateCache);
}
// Read the persisted state for safety checks, bypassing both the cache and
@@ -444,14 +462,58 @@ export async function readAgentsStateForSafetyCheck() {
*/
export async function saveState(state) {
await ensureDirectories();
+ assertCurrentGeneration(state);
state.config = await loadConfig();
- stateCache = state;
+ stateCache = stampGeneration(state);
// Config lives in its own file; never re-serialize it onto the hot path.
const persisted = { ...state };
delete persisted.config;
await atomicWrite(STATE_FILE, persisted);
}
+/**
+ * Drain config, then runtime mutations and keep both queues until transfer and
+ * reload settle. This order matches config changes that consult runtime state;
+ * never acquire the config queue from inside the state queue.
+ * Callers must read their mutation's pre-image INSIDE its respective queue.
+ */
+export function withLiveCosRestore(transfer) {
+ return withConfigLock(() => withStateLock(async () => {
+ const persisted = await readStateForSafetyCheck();
+ const states = [stateCache, persisted.state].filter(Boolean);
+ const unsafe = !persisted.trusted || isDaemonRunning() || states.some(state =>
+ state.running || state.persistentMind?.started || state.persistentMind?.activeTurn
+ || (state.agents != null && !isPlainObject(state.agents))
+ || Object.values(state.agents ?? {}).some(agent =>
+ !['completed', 'failed', 'cancelled'].includes(agent?.status)));
+ if (unsafe) {
+ throw new ServerError('Stop the CoS daemon and Persistent Mind, and finish or stop active agents before restoring CoS files. Repair unreadable CoS state before retrying.', {
+ status: 409, code: 'COS_RESTORE_BUSY',
+ });
+ }
+
+ const [result] = await Promise.allSettled([Promise.resolve().then(transfer)]);
+ restoreGeneration += 1;
+ configCache = null;
+ stateCache = null;
+ const [reload] = await Promise.allSettled([loadState().then(state => {
+ cosEvents.emit('config:changed', state.config);
+ })]);
+ if (result.status === 'rejected') {
+ if (reload.status === 'rejected') {
+ const error = new Error(`${result.reason.message}. CoS cache reload failed: ${reload.reason.message}. Restart PortOS before using CoS.`, { cause: result.reason });
+ if (result.reason.code) error.code = result.reason.code;
+ throw error;
+ }
+ throw result.reason;
+ }
+ if (reload.status === 'rejected') {
+ throw new Error(`CoS cache reload failed: ${reload.reason.message}. Restart PortOS before using CoS.`, { cause: reload.reason });
+ }
+ return result.value;
+ }));
+}
+
// Resolve a single domain's autonomy mode (off | dry-run | execute) without
// importing cos.js (which would create circular deps). Domains gate their
// automatic behavior off this; an absent/invalid value resolves to `execute`.
diff --git a/server/services/cosState.test.js b/server/services/cosState.test.js
index d97fca16d2..e5bd741457 100644
--- a/server/services/cosState.test.js
+++ b/server/services/cosState.test.js
@@ -266,3 +266,94 @@ describe('config recovery', () => {
expect(quarantined('config.json')).toHaveLength(1);
});
});
+
+// Warm-process regression: queued writes must use the restored pre-images.
+describe('live CoS restore boundary', () => {
+ it('drains older writes and merges queued mutations over restored files', async () => {
+ writeConfig({ persistentMindPrompt: { instructions: 'Before restore' } });
+ writeState({ agents: {}, stats: { tasksCompleted: 2 } });
+ const store = await freshModule();
+ const staleState = { ...(await store.loadState()) };
+ const staleConfig = { ...(await store.loadConfig()) };
+ const changed = vi.fn();
+ (await import('./cosEvents.js')).cosEvents.once('config:changed', changed);
+ let finishOldWrite;
+ const oldWriteGate = new Promise(resolve => { finishOldWrite = resolve; });
+ const oldWrite = store.withStateLock(async () => {
+ const state = await store.loadState();
+ await oldWriteGate;
+ state.stats.tasksCompleted = 3;
+ await store.saveState(state);
+ });
+ let finishTransfer;
+ let transferStarted;
+ const started = new Promise(resolve => { transferStarted = resolve; });
+ const transferGate = new Promise(resolve => { finishTransfer = resolve; });
+ const restore = store.withLiveCosRestore(async () => {
+ expect(readJson(STATE_PATH).stats.tasksCompleted).toBe(3);
+ writeConfig({ persistentMindPrompt: { instructions: 'Restored instructions' } });
+ writeState({ agents: {}, stats: { tasksCompleted: 42 } });
+ transferStarted();
+ await transferGate;
+ return 'restored';
+ });
+ finishOldWrite();
+ await oldWrite;
+ await started;
+ const configWrite = store.withConfigLock(async () => {
+ await store.saveConfig({ ...(await store.loadConfig()), maxConcurrentAgents: 7 });
+ });
+ const stateWrite = store.withStateLock(async () => {
+ const state = await store.loadState();
+ state.stats.tasksFailed = 1;
+ await store.saveState(state);
+ });
+ finishTransfer();
+ await expect(restore).resolves.toBe('restored');
+ await Promise.all([configWrite, stateWrite]);
+ expect((await store.getConfig()).persistentMindPrompt.instructions).toBe('Restored instructions');
+ expect(readJson(CONFIG_PATH)).toMatchObject({ maxConcurrentAgents: 7, persistentMindPrompt: { instructions: 'Restored instructions' } });
+ expect(readJson(STATE_PATH).stats).toMatchObject({ tasksCompleted: 42, tasksFailed: 1 });
+ await expect(store.withStateLock(() => store.saveState(staleState))).rejects.toMatchObject({ code: 'COS_RESTORE_STALE_WRITE' });
+ await expect(store.withConfigLock(() => store.saveConfig(staleConfig))).rejects.toMatchObject({ code: 'COS_RESTORE_STALE_WRITE' });
+ expect(changed).toHaveBeenCalledWith(expect.objectContaining({ persistentMindPrompt: expect.objectContaining({ instructions: 'Restored instructions' }) }));
+ });
+
+ it('reloads partial transfer results while preserving the transfer failure', async () => {
+ writeConfig({ persistentMindPrompt: { instructions: 'Old' } });
+ writeState({ agents: {} });
+ const store = await freshModule();
+ await store.loadState();
+ const failure = new Error('rsync failed');
+ await expect(store.withLiveCosRestore(async () => {
+ writeConfig({ persistentMindPrompt: { instructions: 'Partial restore' } });
+ throw failure;
+ })).rejects.toBe(failure);
+ await store.withConfigLock(async () => store.saveConfig({ ...(await store.loadConfig()), maxConcurrentAgents: 8 }));
+ expect(readJson(CONFIG_PATH).persistentMindPrompt.instructions).toBe('Partial restore');
+ });
+
+ it.each([
+ { running: true, agents: {} },
+ { agents: { example: { status: 'running' } } },
+ { agents: { example: { status: 'paused' } } },
+ { agents: {}, persistentMind: { started: true } },
+ { agents: {}, persistentMind: { activeTurn: { id: 'example-turn' } } },
+ ])('refuses unsafe ownership before transferring: %j', async state => {
+ writeState(state);
+ const store = await freshModule();
+ const transfer = vi.fn();
+ await expect(store.withLiveCosRestore(transfer)).rejects.toMatchObject({ code: 'COS_RESTORE_BUSY' });
+ expect(transfer).not.toHaveBeenCalled();
+ expect(readJson(STATE_PATH)).toEqual(state);
+ });
+
+ it('refuses unreadable runtime records without overwriting them', async () => {
+ writeFileSync(STATE_PATH, '{broken');
+ const store = await freshModule();
+ const transfer = vi.fn();
+ await expect(store.withLiveCosRestore(transfer)).rejects.toMatchObject({ code: 'COS_RESTORE_BUSY' });
+ expect(transfer).not.toHaveBeenCalled();
+ expect(readFileSync(STATE_PATH, 'utf8')).toBe('{broken');
+ });
+});