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(backup): admit CoS recording compression and purge
[._.]/ Adam Eivyeba9cd6299d7
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 06fe7df655..f2e7e0d668 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -105,6 +105,7 @@ Admission inventory (`withBackupAssetPublication`):| Pipeline audio mux (music, voice, generated cues, silent strip), including Creative Director stitch/final assembly | Covered (#9982 partial): encoding runs outside admission; replacement of the already-recorded video and rollback hold the lease. CD final/rough-cut rows only reference the existing history entry || 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 || 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 1f164f83cd..fa7eb2d9ff 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -406,6 +406,14 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'admitted',modules: ['services/timeCapsule.js'],},+ {+ // Compression verifies staging outside admission; publishing gzip, recording+ // its manifest and removing plain bytes take one lease before the state lock.+ // Purge leases its intent manifest and both unlinks (file-primary records).+ id: 'cos-recording-compression-and-purge',+ status: 'admitted',+ modules: ['services/cosAgentStorage.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/cosAgentStorage.js b/server/services/cosAgentStorage.jsindex c030df6bb0..b2f3f9c443 100644--- a/server/services/cosAgentStorage.js+++ b/server/services/cosAgentStorage.js@@ -8,6 +8,7 @@ import { pipeline } from 'node:stream/promises';import { Writable, Transform } from 'node:stream';import { z } from 'zod';import { atomicWrite, createWriteStreamGuarded, unlinkGuarded } from '../lib/fileUtils.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { ServerError } from '../lib/errorHandler.js';import { AGENTS_DIR, loadConfig, saveConfig, withConfigLock, withStateLock, readAgentsStateForSafetyCheck } from './cosState.js';import { cosEvents } from './cosEvents.js';@@ -186,7 +187,7 @@ async function compress(entry, signal, revalidate) {const verifying = pipeline(createReadStream(temporary), gunzip, { signal });const [actual] = await Promise.all([hashStream(gunzip, signal), verifying]);if (actual !== expected) throw new Error('Recording verification failed');- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const fresh = await revalidate();if (!fresh || signal.aborted) return 0;const zipped = await info(temporary);@@ -198,11 +199,11 @@ async function compress(entry, signal, revalidate) {await atomicWrite(join(entry.dir, MANIFEST), { ...fresh.storage, disposition: 'compressed', sha256: expected, originalBytes: fresh.raw.size, compressedAt: new Date().toISOString() });await unlinkGuarded(source);return Math.max(0, fresh.raw.size + (fresh.gzip?.size || 0) - zipped.size);- });+ }));})().finally(() => unlinkGuarded(temporary).catch(err => { if (err.code !== 'ENOENT') throw err; }));}async function purge(entry, signal, revalidate) {- return withStateLock(async () => {+ return withBackupAssetPublication(() => withStateLock(async () => {const fresh = await revalidate();if (!fresh || signal.aborted) return 0;// Persist intent before unlink. A crash leaves an explicit disposition and@@ -215,7 +216,7 @@ async function purge(entry, signal, revalidate) {}return reclaimed;})().catch(err => { err.reclaimedBytes = reclaimed; throw err; });- });+ }));}export async function startAgentStorage({ token, confirmation }, { automatic = false } = {}) {if (controller) throw new ServerError('Recording maintenance already running', { status: 409, code: 'CONFLICT' });diff --git a/server/services/cosAgentStorage.test.js b/server/services/cosAgentStorage.test.jsindex 60406021c0..94ca233f0a 100644--- a/server/services/cosAgentStorage.test.js+++ b/server/services/cosAgentStorage.test.js@@ -27,14 +27,25 @@ vi.mock('node:fs', async importOriginal => {});vi.mock('../lib/fileUtils.js', async importOriginal => {const actual = await importOriginal();- return { ...actual, createWriteStreamGuarded: async (...args) => {+ return { ...actual, atomicWrite: async (path, data) => {+ await actual.atomicWrite(path, data);+ if (path.endsWith('raw-storage.json')) await fixture.afterManifest?.();+ }, createWriteStreamGuarded: async (...args) => {if (fixture.failWrite) throw new Error('disk full');await fixture.onWrite?.();return actual.createWriteStreamGuarded(...args);} };});+vi.mock('../lib/backupSnapshotBoundary.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, withBackupAssetPublication: work => {+ fixture.onAdmission?.();+ return fixture.bypassAdmission ? work() : actual.withBackupAssetPublication(work);+ } };+});vi.mock('./codexSummaryRepair.js', () => ({ repairCodexTaskSummary: async () => null }));const storage = await import('./cosAgentStorage.js');+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');const { pruneOldAgentArchives } = await import('./cosAgentIndex.js');const { default: routes } = await import('../routes/dataManager.js');const app = express();@@ -62,6 +73,7 @@ beforeEach(async () => {await rm(fixture.root, { recursive: true, force: true }); await mkdir(fixture.root);fixture.state = {}; fixture.config = {}; fixture.trusted = true;fixture.failWrite = false; fixture.corruptVerification = false; fixture.onWrite = null;+ fixture.afterManifest = null; fixture.onAdmission = null; fixture.bypassAdmission = false;});afterAll(() => rm(fixture.root, { recursive: true, force: true }));@@ -155,3 +167,67 @@ it('rechecks opt-in policy before automatic publication and does no deletion byexpect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);expect(await readFile(join(dir, 'metadata.json'), 'utf8')).toContain('example-model');});++const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const settleTurn = () => new Promise(resolve => setImmediate(resolve));+const startStorageAction = async action => {+ const preview = await storage.previewAgentStorage({ action });+ await storage.startAgentStorage({ token: preview.token, ...(action === 'purge' ? { confirmation: 'PURGE RAW RECORDINGS' } : {}) });+};+const expectSettledRecording = async (dir, action) => {+ const manifest = JSON.parse(await readFile(join(dir, 'raw-storage.json'), 'utf8'));+ expect(manifest.disposition).toBe(action === 'compress' ? 'compressed' : 'purged');+ const names = await readdir(dir);+ expect(names).not.toContain('raw.txt');+ if (action === 'compress') expect(gunzipSync(await readFile(join(dir, 'raw.txt.gz'))).toString()).toBe(source);+ else expect(names).not.toContain('raw.txt.gz');+ expect(names.some(name => name.endsWith('.tmp'))).toBe(false);+};++it.each(['compress', 'purge'])('%s waits out an open backup cut before changing bytes or manifest', async action => {+ const dir = await seed();+ const reached = deferred(); fixture.onAdmission = reached.resolve;+ const release = await acquireBackupSnapshotCut();+ try {+ await startStorageAction(action);+ await reached.promise;+ await settleTurn();+ expect(await readFile(join(dir, 'raw.txt'), 'utf8')).toBe(source);+ expect(await readdir(dir)).not.toContain('raw-storage.json');+ expect(await readdir(dir)).not.toContain('raw.txt.gz');+ } finally { release(); }+ expect((await settled()).state).toBe('completed');+ await expectSettledRecording(dir, action);+});++it.each(['compress', 'purge'])('%s drains the file-primary manifest and byte deletion together', async action => {+ const dir = await seed();+ const reached = deferred(); const commit = deferred();+ fixture.afterManifest = async () => { reached.resolve(); await commit.promise; };+ await startStorageAction(action);+ await reached.promise;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try { await settleTurn(); expect(cutReady).toBe(false); }+ finally { commit.resolve(); }+ const release = await cut;+ try { await expectSettledRecording(dir, action); }+ finally { release(); }+ expect((await settled()).state).toBe('completed');+});++it('negative control publishes compressed bytes and manifest during an open cut', async () => {+ const dir = await seed(); fixture.bypassAdmission = true;+ const copiedNames = await readdir(dir);+ const release = await acquireBackupSnapshotCut();+ try {+ await startStorageAction('compress');+ await settled();+ await expectSettledRecording(dir, 'compress');+ expect(copiedNames).not.toContain('raw.txt.gz');+ } finally { release(); }+});