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(restore): refresh CoS archive lookup before releasing file restore

[._.]/ Adam Eivyb00dd6793dc5
diff --git a/server/services/backup.js b/server/services/backup.js
index 74fc0c4dc4..0e5e5699c1 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1620,7 +1620,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
return restoreFiles();
};
const restoreWithCosBoundary = async () => {
- if (!dryRun && (!scope || ['cos', 'cos/config.json', 'cos/state.json'].includes(scope))) {
+ if (!dryRun && (!scope || ['cos', 'cos/config.json', 'cos/state.json', 'cos/agents'].includes(scope) || scope.startsWith('cos/agents/'))) {
const { withLiveCosRestore } = await import('./cosState.js');
return withLiveCosRestore(restoreWithMediaBoundary);
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index ffbfbb6049..7b284b236d 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -3120,7 +3120,7 @@ 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 => {
+ it.each([undefined, 'cos', 'cos/', 'cos/config.json', 'cos/state.json', 'cos/agents', 'cos/agents/', 'cos/agents/index.json'])('holds the boundary for affected live scope %s', async subdirFilter => {
await runRestore('/dest', 'snap-1', { dryRun: false, subdirFilter });
expect(withLiveCosRestore).toHaveBeenCalledTimes(1);
});
diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.js
index fc6dc87e36..9898dfd9d6 100644
--- a/server/services/cosAgentIndex.js
+++ b/server/services/cosAgentIndex.js
@@ -67,6 +67,30 @@ async function loadAgentIndexLeased() {
return agentIndexPromise;
}
+/**
+ * Refresh the primary lookup after a live file restore. The caller holds the
+ * snapshot cut, which has drained lazy migrations and archive publishers, and
+ * the CoS restore queues. Never call loadAgentIndex here: missing-index
+ * migration would wait for admission behind the cut this restore owns.
+ * Clear both singleton slots before reading so a failed reload cannot retain
+ * a mapping to files the transfer has already replaced.
+ */
+export async function reloadAgentIndexAfterRestore() {
+ agentIndex = null;
+ agentIndexPromise = null;
+ const content = await readFile(INDEX_FILE, 'utf8').catch(error => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ // Defer absent-index migration until the first reader after cut release.
+ if (content === null) return;
+ const parsed = JSON.parse(content);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('Restored CoS agent index must be an object');
+ }
+ agentIndex = new Map(Object.entries(parsed));
+}
+
// Persist agent index to disk via the shared atomicWrite helper (temp file + rename,
// with Windows backup-swap fallback). Without atomic semantics a mid-write crash
// truncates index.json and on next boot the date-bucket migration would silently
diff --git a/server/services/cosState.js b/server/services/cosState.js
index d89a23103d..9b7646d1cb 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -503,9 +503,12 @@ export function withLiveCosRestore(transfer) {
restoreGeneration += 1;
configCache = null;
stateCache = null;
- const [reload] = await Promise.allSettled([loadState().then(state => {
+ const [reload] = await Promise.allSettled([(async () => {
+ const { reloadAgentIndexAfterRestore } = await import('./cosAgentIndex.js');
+ await reloadAgentIndexAfterRestore();
+ const state = await loadState();
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 });
diff --git a/server/services/cosState.test.js b/server/services/cosState.test.js
index 8057378fd9..74d0f8021c 100644
--- a/server/services/cosState.test.js
+++ b/server/services/cosState.test.js
@@ -334,6 +334,73 @@ describe('live CoS restore boundary', () => {
expect(changed).toHaveBeenCalledWith(expect.objectContaining({ persistentMindPrompt: expect.objectContaining({ instructions: 'Restored instructions' }) }));
});
+ it.each([false, true])('reloads a warm archive index after transfer (partial failure: %s)', async fails => {
+ writeState({ agents: {} });
+ const store = await freshModule();
+ const index = await import('./cosAgentIndex.js');
+ const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+ const indexPath = join(COS_DIR, 'agents', 'index.json');
+ mkdirSync(join(COS_DIR, 'agents'), { recursive: true });
+ writeFileSync(indexPath, JSON.stringify({ 'agent-example': '2026-01-01' }));
+ await index.loadAgentIndex();
+ expect(index.getAgentDir('agent-example')).toBe(join(COS_DIR, 'agents', '2026-01-01', 'agent-example'));
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const transfer = store.withLiveCosRestore(async () => {
+ writeFileSync(indexPath, JSON.stringify({ 'agent-example': '2026-02-02' }));
+ if (fails) throw new Error('partial transfer');
+ });
+ if (fails) await expect(transfer).rejects.toThrow('partial transfer');
+ else await transfer;
+ expect(index.getAgentDir('agent-example')).toBe(join(COS_DIR, 'agents', '2026-02-02', 'agent-example'));
+ expect((await index.loadAgentIndex()).get('agent-example')).toBe('2026-02-02');
+ } finally { release(); }
+ });
+
+ it('lets an archive publication queued behind restore use the restored index', async () => {
+ writeState({ agents: {} });
+ const store = await freshModule();
+ const index = await import('./cosAgentIndex.js');
+ const { acquireBackupSnapshotCut, withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');
+ const indexPath = join(COS_DIR, 'agents', 'index.json');
+ mkdirSync(join(COS_DIR, 'agents'), { recursive: true });
+ writeFileSync(indexPath, JSON.stringify({ 'agent-old': '2026-01-01' }));
+ await index.loadAgentIndex();
+ const release = await acquireBackupSnapshotCut();
+ let entered = false;
+ const writer = withBackupAssetPublication(async () => {
+ entered = true;
+ return index.addAgentArchivesToIndex([{ agentId: 'agent-new', date: '2026-03-03' }]);
+ });
+ try {
+ await store.withLiveCosRestore(async () => {
+ writeFileSync(indexPath, JSON.stringify({ 'agent-restored': '2026-02-02' }));
+ });
+ expect(entered).toBe(false);
+ } finally { release(); }
+ await writer;
+ expect(readJson(indexPath)).toEqual({ 'agent-restored': '2026-02-02', 'agent-new': '2026-03-03' });
+ });
+
+ it('clears a removed index without running migration behind the restore cut', async () => {
+ writeState({ agents: {} });
+ const store = await freshModule();
+ const index = await import('./cosAgentIndex.js');
+ const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+ const indexPath = join(COS_DIR, 'agents', 'index.json');
+ mkdirSync(join(COS_DIR, 'agents'), { recursive: true });
+ writeFileSync(indexPath, JSON.stringify({ 'agent-example': '2026-01-01' }));
+ await index.loadAgentIndex();
+ const release = await acquireBackupSnapshotCut();
+ try {
+ await store.withLiveCosRestore(async () => { rmSync(indexPath); });
+ expect(existsSync(indexPath)).toBe(false);
+ expect(index.getAgentDir('agent-example')).toBe(join(COS_DIR, 'agents', 'agent-example'));
+ } finally { release(); }
+ expect((await index.loadAgentIndex()).size).toBe(0);
+ expect(existsSync(indexPath)).toBe(true);
+ });
+
it('reloads partial transfer results while preserving the transfer failure', async () => {
writeConfig({ persistentMindPrompt: { instructions: 'Old' } });
writeState({ agents: {} });