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: admit CoS archive lifecycle and retry primary index writes
[._.]/ Adam Eivy83118e44fda4
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 746b0e861e..cf16236ade 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -107,6 +107,7 @@ Admission inventory (`withBackupAssetPublication`):| Music Video Making-of export (`makingOf.js`, `makingOfVisuals.js`) | Reference-only: reads existing assets and transforms buffers for the ZIP response; no durable file or row writes || Time Capsule snapshots (`timeCapsule.js`) | Covered (#9982 partial): snapshot creation and deletion lease the file and index entry together, acquiring before the shared index write tail || CoS raw recording compression and purge (`cosAgentStorage.js`) | Covered (#9982 partial): verified gzip publication, storage manifest and plain-file removal share a lease; purge intent and unlinks also share a lease because the manifest is file-primary |+| CoS agent archive/index publication (`cosAgentLifecycle.js`, `cosAgentArchive.js`, `cosAgentIndex.js`) | Covered (#9982 partial): completion, zombie/stale archival, deletion and legacy layout migration lease directory changes through state and index publication; state-locked workflows acquire admission first || Durable replacement/deletion owners not yet classified | Outstanding (#9982) || Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) || Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex e974984274..eedb713337 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -407,8 +407,8 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([modules: ['services/dataManager.js', 'routes/uploads.js', 'routes/attachments.js'],},{- // Snapshot JSON and its index entry are one pair, including unlink-before-- // index deletion. Acquire before the index tail so queued writes drain.+ // Snapshot JSON and its index entry are one pair. Deletion persists index+ // removal before unlink; admission precedes the index tail so writes drain.id: 'time-capsule-snapshot-index',status: 'admitted',modules: ['services/timeCapsule.js'],@@ -421,6 +421,14 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'admitted',modules: ['services/cosAgentStorage.js'],},+ {+ // Completion, zombie/stale archival and deletion pair moved/removed trees+ // with state, the primary date index and completion projection. Admission+ // precedes the state lock. Legacy layout migration owns the same pair.+ id: 'cos-agent-archive-and-index-publication',+ status: 'admitted',+ modules: ['services/cosAgentLifecycle.js', 'services/cosAgentArchive.js', 'services/cosAgentIndex.js'],+ },// Anything the sweep did not reach. A new asset owner lands here until it is// classified; the claim cannot become `global` while this entry exists.{ id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },diff --git a/server/services/cosAgentArchive.js b/server/services/cosAgentArchive.jsindex a994545104..693da08cd8 100644--- a/server/services/cosAgentArchive.js+++ b/server/services/cosAgentArchive.js@@ -9,6 +9,7 @@* (#3450) — callers import from here directly.*/+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { writeFile, rename, readdir, rm } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';@@ -22,7 +23,7 @@ import { loadAgentIndex, saveAgentIndex, recordArchivedAgentOrder } from './cosA// (metadata.json) by completeAgent(), so removing them from state.json only// reduces the size of the in-memory state and the state.json file.export async function archiveStaleAgents() {- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const state = await loadState();const retentionMs = state.config.completedAgentRetentionMs ?? 86400000;const cutoff = Date.now() - retentionMs;@@ -85,12 +86,12 @@ export async function archiveStaleAgents() {console.log(`📦 Archived ${staleIds.length} stale agents from state.json (retained on disk)`);cosEvents.emit('agents:changed', { action: 'auto-archive', archived: staleIds.length });return { archived: staleIds.length };- });+ }));}// Clear completed agents from state, cache, and diskexport async function clearCompletedAgents() {- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const state = await loadState();const idx = await loadAgentIndex();@@ -107,6 +108,13 @@ export async function clearCompletedAgents() {const dates = new Set(idx.values());const totalCleared = idx.size + stateCompleted.filter(id => !idx.has(id)).length;+ // Remove durable references before bytes; a failed index write must leave+ // the old archive trees readable and its in-memory lookup retryable.+ const previousEntries = [...idx];+ idx.clear();+ try { await saveAgentIndex(); }+ catch (err) { for (const [id, date] of previousEntries) idx.set(id, date); throw err; }+const removals = [...dates].map(date => {const dateDir = join(AGENTS_DIR, date);return existsSync(dateDir)@@ -115,10 +123,6 @@ export async function clearCompletedAgents() {});await Promise.all(removals);- // Clear index- idx.clear();- await saveAgentIndex();-return { cleared: totalCleared };- });+ }));}diff --git a/server/services/cosAgentArchives.backupAdmission.test.js b/server/services/cosAgentArchives.backupAdmission.test.jsnew file mode 100644index 0000000000..b2aacae48f--- /dev/null+++ b/server/services/cosAgentArchives.backupAdmission.test.js@@ -0,0 +1,169 @@+/** Real archive trees, primary index and state snapshots under synthetic cuts. */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+const fixture = await vi.hoisted(async () => {+ const { mkdtemp } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ return { root: await mkdtemp(join(tmpdir(), 'cos-archive-backup-')), state: null, beforeIndex: null, bypass: false };+});+vi.mock('./cosState.js', () => ({+ AGENTS_DIR: fixture.root,+ loadState: async () => structuredClone(fixture.state),+ saveState: async state => { fixture.state = structuredClone(state); await writeFile(join(fixture.root, 'state.json'), JSON.stringify(state)); },+ withStateLock: createFileWriteQueue(),+ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: fixture.state.agents }),+}));+vi.mock('../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, atomicWrite: async (path, data) => {+ if (path === join(fixture.root, 'index.json')) await fixture.beforeIndex?.();+ return actual.atomicWrite(path, data);+ } };+});+vi.mock('../lib/backupSnapshotBoundary.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, withBackupAssetPublication: work => fixture.bypass ? work() : actual.withBackupAssetPublication(work) };+});+vi.mock('./domainUsage.js', () => ({ recordDomainUsage: async () => {} }));+vi.mock('./codexSummaryRepair.js', () => ({ repairCodexTaskSummary: async () => null }));+vi.mock('./cosRunnerClient.js', () => ({ getActiveAgentsFromRunner: async () => [] }));+const deferred = () => {+ let resolve; const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const settle = () => new Promise(resolve => setImmediate(resolve));+let api;+let index;+let acquireCut;+const date = '2001-01-01';+const id = 'agent-example';+const readIndex = async () => JSON.parse(await readFile(join(fixture.root, 'index.json'), 'utf8'));+const assertIndexedTrees = async () => {+ for (const [agentId, bucket] of Object.entries(await readIndex())) {+ expect(await readFile(join(fixture.root, bucket, agentId, 'output.txt'), 'utf8')).toBe('Example preserved output');+ expect(JSON.parse(await readFile(join(fixture.root, bucket, agentId, 'metadata.json'), 'utf8')).id).toBe(agentId);+ }+};+async function seed({ completed = false, indexed = false } = {}) {+ fixture.state.agents[id] = { id, status: completed ? 'completed' : 'running', startedAt: `${date}T01:00:00Z`,+ ...(completed ? { completedAt: `${date}T02:00:00Z`, result: { success: true } } : {}), metadata: {} };+ const dir = indexed ? join(fixture.root, date, id) : join(fixture.root, id);+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, 'output.txt'), 'Example preserved output');+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(fixture.state.agents[id]));+ if (indexed) { (await index.loadAgentIndex()).set(id, date); await index.saveAgentIndex(); }+}+beforeEach(async () => {+ vi.resetModules(); fixture.beforeIndex = null; fixture.bypass = false;+ fixture.state = { agents: {}, config: { completedAgentRetentionMs: 1 }, stats: { tasksCompleted: 0, errors: 0 } };+ await rm(fixture.root, { recursive: true, force: true }); await mkdir(fixture.root);+ await writeFile(join(fixture.root, 'index.json'), '{}');+ ({ acquireBackupSnapshotCut: acquireCut } = await import('../lib/backupSnapshotBoundary.js'));+ index = await import('./cosAgentIndex.js');+ api = { ...await import('./cosAgentLifecycle.js'), ...await import('./cosAgentArchive.js') };+});+afterAll(() => rm(fixture.root, { recursive: true, force: true }));+const cases = [+ { name: 'completion', setup: () => seed(), run: () => api.completeAgent(id, { success: true }) },+ { name: 'zombie archive', setup: () => seed(), run: () => api.cleanupZombieAgents() },+ { name: 'stale archive', setup: () => seed({ completed: true }), run: () => api.archiveStaleAgents() },+ { name: 'single deletion', setup: () => seed({ completed: true, indexed: true }), run: () => api.deleteAgent(id) },+ { name: 'clear completed', setup: () => seed({ completed: true, indexed: true }), run: () => api.clearCompletedAgents() },+];+describe.each(cases)('$name', ({ setup, run }) => {+ it('keeps archive trees and the primary index behind an open cut', async () => {+ await setup();+ const beforeIndex = await readIndex();+ const beforeState = structuredClone(fixture.state);+ const beforeNames = await readdir(fixture.root);+ const release = await acquireCut();+ const work = run();+ try { await settle(); await settle(); expect(await readIndex()).toEqual(beforeIndex); expect(fixture.state).toEqual(beforeState); expect(await readdir(fixture.root)).toEqual(beforeNames); }+ finally { release(); }+ await work; await assertIndexedTrees();+ });++ it('drains directory changes through the last primary-index commit', async () => {+ await setup();+ const reached = deferred(); const commit = deferred();+ fixture.beforeIndex = async () => { reached.resolve(); await commit.promise; };+ const work = run(); await Promise.race([reached.promise, work.then(() => { throw new Error('workflow missed index seam'); })]);+ let ready = false;+ const cut = acquireCut().then(release => { ready = true; return release; });+ try { await settle(); expect(ready).toBe(false); }+ finally { commit.resolve(); }+ await work;+ const release = await cut;+ try { await assertIndexedTrees(); } finally { release(); }+ });+});+it('legacy migration holds moved directories and its new index in one publication', async () => {+ await seed({ completed: true });+ await rm(join(fixture.root, 'index.json'));+ const reached = deferred(); const commit = deferred();+ fixture.beforeIndex = async () => { reached.resolve(); await commit.promise; };+ const work = index.loadAgentIndex(); await Promise.race([reached.promise, work.then(() => { throw new Error('migration missed index seam'); })]);+ let ready = false;+ const cut = acquireCut().then(release => { ready = true; return release; });+ try { await settle(); expect(ready).toBe(false); } finally { commit.resolve(); }+ await work;+ const release = await cut;+ try { await assertIndexedTrees(); } finally { release(); }+});+it('index publication failure remains retryable for peer reconciliation', async () => {+ const pairs = [{ agentId: id, date }];+ fixture.beforeIndex = async () => { throw new Error('synthetic index write failure'); };+ await expect(index.addAgentArchivesToIndex(pairs)).rejects.toThrow('synthetic index write failure');+ expect(await readIndex()).toEqual({});+ fixture.beforeIndex = null;+ expect(await index.addAgentArchivesToIndex(pairs)).toBe(0);+ expect(await readIndex()).toEqual({ [id]: date });+});+it('negative control exposes an index naming a relocated tree missing from the earlier copy', async () => {+ await seed(); fixture.bypass = true;+ const copiedNames = await readdir(fixture.root);+ const release = await acquireCut();+ try {+ await api.completeAgent(id, { success: true });+ const bucket = (await readIndex())[id];+ expect(bucket).toBeTruthy(); expect(copiedNames).not.toContain(bucket);+ } finally { release(); }+});++describe.each([+ { name: 'single deletion', run: () => api.deleteAgent(id) },+ { name: 'clear completed', run: () => api.clearCompletedAgents() },+])('$name failure', ({ run }) => {+ it('retains indexed archive bytes and retries after a primary-index write failure', async () => {+ await seed({ completed: true, indexed: true });+ fixture.beforeIndex = async () => { throw new Error('synthetic index write failure'); };+ await expect(run()).rejects.toThrow('synthetic index write failure');+ await assertIndexedTrees();+ expect((await index.loadAgentIndex()).get(id)).toBe(date);+ fixture.beforeIndex = null;+ await run();+ expect(await readIndex()).toEqual({});+ });+});++it('does not let a cold reader queue its shared initialization ahead of an admitted publisher', async () => {+ await seed({ completed: true });+ await rm(join(fixture.root, 'index.json'));+ const { withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');+ const entered = deferred(); const proceed = deferred();+ const publisher = withBackupAssetPublication(async () => {+ entered.resolve(); await proceed.promise;+ return index.loadAgentIndex();+ });+ await entered.promise;+ const cut = acquireCut();+ const reader = index.loadAgentIndex();+ proceed.resolve();+ await publisher;+ const release = await cut;+ try { await assertIndexedTrees(); } finally { release(); }+ await reader;+});diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.jsindex 70d8ea1020..ce19115327 100644--- a/server/services/cosAgentFeedback.js+++ b/server/services/cosAgentFeedback.js@@ -283,6 +283,10 @@ export async function submitAgentFeedback(agentId, feedback) {});}+ // Lazy index migration takes backup admission. Resolve it before the state+ // lock so a cut cannot invert admission/state-lock order during first access.+ const idx = await loadAgentIndex();+// The durable reference is removed only after the source metadata write. Keep// that small store mutation outside the CoS state lock so a database/file I/O// round trip never serializes unrelated agent state updates.@@ -317,8 +321,7 @@ export async function submitAgentFeedback(agentId, feedback) {return { success: true, agent: state.agents[agentId], feedbackData, clearPendingRef: archived.kind === 'found' };}- // Agent not in state — look up from disk via index- const idx = await loadAgentIndex();+ // Agent not in state — look up from disk via the preloaded indexconst dateStr = idx.get(agentId);if (!dateStr) throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.jsindex 6d5cf13daf..fc6dc87e36 100644--- a/server/services/cosAgentIndex.js+++ b/server/services/cosAgentIndex.js@@ -10,6 +10,7 @@* (#3450) — callers import from here directly.*/+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';@@ -32,6 +33,13 @@ let agentIndexPromise = null;// Load agent index from disk (lazy init, singleton promise prevents concurrent migrations)export async function loadAgentIndex() {+ if (agentIndex) return agentIndex;+ // Acquire before sharing the lazy-init promise. Otherwise an already-admitted+ // publisher could await a cold reader queued behind the cut it must drain.+ return withBackupAssetPublication(loadAgentIndexLeased);+}++async function loadAgentIndexLeased() {if (agentIndex) return agentIndex;if (agentIndexPromise) return agentIndexPromise;@@ -68,6 +76,7 @@ export async function saveAgentIndex() {const obj = Object.fromEntries(agentIndex);await atomicWrite(INDEX_FILE, obj).catch(err => {console.error(`❌ Failed to save agent index: ${err.message}`);+ throw err;});// The completion-order projection is a subset of this keyspace, so every// delete / retention prune / clear-completed sweep drops its rows here rather@@ -108,16 +117,20 @@ export async function addAgentArchivesToIndex(pairs) {if (!Array.isArray(pairs) || pairs.length === 0) return 0;const idx = await loadAgentIndex();let added = 0;+ let valid = false;for (const pair of pairs) {const agentId = pair?.agentId;const date = pair?.date;if (typeof agentId !== 'string' || !agentId) continue;if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;+ valid = true;if (idx.has(agentId)) continue; // already owned — never overwrite (id is authoritative)idx.set(agentId, date);added += 1;}- if (added > 0) await saveAgentIndex();+ // A failed prior save can leave a valid pair in memory only. Persist again+ // before the peer receiver may mark that manifest reconciled.+ if (valid) await saveAgentIndex();return added;}@@ -134,6 +147,10 @@ export function getAgentDir(agentId, dateString) {// Migrate flat agent-* directories into YYYY-MM-DD date buckets// Runs once when index.json doesn't exist. Idempotent — no-op if already migrated.async function migrateAgentsToDateBuckets() {+ return withBackupAssetPublication(migrateAgentsToDateBucketsLeased);+}++async function migrateAgentsToDateBucketsLeased() {const index = new Map();if (!existsSync(AGENTS_DIR)) {diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 9064165b5f..434425f343 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -10,6 +10,7 @@* (#3450) — callers import from here directly.*/+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { readFile, writeFile, rename, readdir, rm, stat } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';@@ -131,7 +132,7 @@ async function archiveCompletedAgent(agentId, agent) {}// Update index — deliberately NOT gated on the in-memory map already holding- // this entry. `saveAgentIndex` swallows its own write errors, so a failed write+ // this entry. A failed `saveAgentIndex` leaves the map updated, so a failed write// leaves the map correct while index.json on disk is missing the agent; after a// restart the archive would be unreachable from history. Re-running the write// is cheap (a small map, atomically written) and repairs exactly that.@@ -148,7 +149,7 @@ export async function completeAgent(agentId, result = {}) {// tail below (budget ledger + `agent:completed`) is skipped too — see #3384.let alreadyCompleted = false;- const completed = await withStateLock(async () => {+ const completed = await withBackupAssetPublication(() => withStateLock(async () => {const state = await loadState();if (!state.agents[agentId]) {@@ -212,7 +213,7 @@ export async function completeAgent(agentId, result = {}) {await archiveCompletedAgent(agentId, state.agents[agentId]);return state.agents[agentId];- });+ }));// A duplicate completion never runs the completion tail: re-recording the// domain-usage action would double-charge the daily budget, and re-emitting@@ -684,7 +685,7 @@ export async function cleanupZombieAgents() {.map((row) => [row.id, row]),);- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const state = await loadState();const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');const cleaned = [];@@ -794,12 +795,12 @@ export async function cleanupZombieAgents() {}return { cleaned, count: cleaned.length };- });+ }));}// Delete a single agent from state and diskexport async function deleteAgent(agentId) {- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const state = await loadState();const idx = await loadAgentIndex();@@ -812,17 +813,18 @@ export async function deleteAgent(agentId) {delete state.agents[agentId];await saveState(state);- // Remove from disk (date-bucketed or flat)+ // Persist reference removal before deleting bytes. Failed index writes+ // retain both the disk tree and its cached lookup for a safe retry.const agentDir = getAgentDir(agentId);+ const previousDate = idx.get(agentId);+ idx.delete(agentId);+ try { await saveAgentIndex(); }+ catch (err) { if (inIndex) idx.set(agentId, previousDate); throw err; }if (existsSync(agentDir)) {await rm(agentDir, { recursive: true }).catch(() => {});}- // Remove from index- idx.delete(agentId);- await saveAgentIndex();-cosEvents.emit('agents:changed', { action: 'deleted', agentId });return { success: true, agentId };- });+ }));}