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): publish peer CoS archives with their primary index
[._.]/ Adam Eivy5b6658e0f768
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex f2e7e0d668..746b0e861e 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -96,6 +96,7 @@ Admission inventory (`withBackupAssetPublication`):| Code Animation generated HTML, package import and repair revisions, production stage-run artifacts, Blender film publication and the soundtrack mux install (`codeAnimation/index.js`, `projects.js`, `stages.js`, `blenderRender.js`, `sound.js`) | Covered (#9982 partial): write-once revision trees and run artifacts land first, and the revision, run or history row that first names them commits under the lease; the mux's in-place install over an already-named render takes it too || Code Animation export staging and output acceptance (`codeAnimation/export.js`, `codeAnimation/acceptance.js`) | Reference-only: staging directories and worker workspaces are scratch no row names, and acceptance names a render that was already durable || Peer asset, draft-body and bible pulls, share bucket asset import and the peer library sweep (`sharing/peerSyncAssets.js`, `importer.js`, `peerMediaLibrarySync.js`) | Covered (#9982 partial): downloads run outside admission; the write that lands the bytes with its sidecar, poster and `media_assets` row, the draft or bible replacement, the bucket's asset copy and the sweep's index rebuild each take the lease |+| Peer CoS archive imports (`sharing/peerCosSync.js`) | Covered (#9982 partial): verified downloads stage outside admission; final files, index reconciliation and present-but-unindexed recovery take one lease || ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease || YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease || Digital twin documents, enrichment answers/lists, peer document sync and genome upload/delete (`digital-twin-documents.js`, `digital-twin-enrichment.js`, `digital-twin-sync.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion; enrichment provider work stays outside, while peer sync holds the lease from its meta merge through tombstone reaping and document copying |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex fa7eb2d9ff..e974984274 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -368,6 +368,13 @@ export const BACKUP_ASSET_OWNERS = Object.freeze(['services/sharing/peerSyncAssets.js', 'services/sharing/importer.js', 'services/sharing/peerMediaLibrarySync.js',],},+ {+ // Verified peer archive bytes stay in scratch until files and the primary+ // agentId-to-date index can publish under the same lease.+ id: 'peer-cos-archive-import',+ status: 'admitted',+ modules: ['services/sharing/peerCosSync.js'],+ },{// The ChatGPT zip import extracts assets before any row names them; each// conversation's archived transcript and the memory row that names it (anddiff --git a/server/services/sharing/peerCosSync.backupAdmission.test.js b/server/services/sharing/peerCosSync.backupAdmission.test.jsnew file mode 100644index 0000000000..c331f7fe9f--- /dev/null+++ b/server/services/sharing/peerCosSync.backupAdmission.test.js@@ -0,0 +1,124 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createHash } from 'node:crypto';+import { EventEmitter } from 'node:events';++const state = vi.hoisted(() => ({ beforeDownload: null, beforeWrite: null, staged: null, failIndex: false, manifestHash: '' }));+const root = await mkdtemp(join(tmpdir(), 'peer-cos-publication-'));+const agentsDir = join(root, 'agents');+const indexPath = join(agentsDir, 'index.json');+const date = '2026-01-01';+const agentId = 'agent-example';+const peer = { instanceId: 'peer-example', name: 'Example peer', address: '192.0.2.10', port: 5555, fullSync: true };+const files = { 'metadata.json': '{"id":"agent-example","status":"completed"}', 'output.txt': 'Example output', 'prompt.txt': 'Example prompt' };+const sha = value => createHash('sha256').update(value).digest('hex');+const entries = Object.entries(files).map(([file, content]) => ({ date, agentId, file, sha256: sha(content) }));++vi.mock('../../lib/fileUtils.js', async original => {+ const actual = await original();+ return { ...actual, PATHS: { ...actual.PATHS, cos: root }, atomicWrite: async (path, data) => {+ await state.beforeWrite?.(path);+ await actual.atomicWrite(path, data);+ if (!path.startsWith(root)) state.staged?.(path);+ } };+});+vi.mock('../cosState.js', () => ({ AGENTS_DIR: agentsDir }));+vi.mock('../instances.js', () => ({ getPeers: async () => [peer] }));+vi.mock('./peerSyncShared.js', () => ({ findPeerById: async () => peer, FORCE_REVALIDATE_EVERY: 50, peerSyncEvents: new EventEmitter() }));+vi.mock('./peerSyncAssets.js', () => ({ inflightPulls: new Set(), inflightKey: (...parts) => parts.join(':'), ASSET_PULL_TIMEOUT_MS: 1000,+ fetchCappedAssetBuffer: async (_peer, url) => {+ const filename = new URL(url).searchParams.get('file');+ await state.beforeDownload?.(filename);+ return Buffer.from(files[filename]);+ } }));+vi.mock('../../lib/peerHttpClient.js', () => ({ peerFetch: async () => ({ ok: true }),+ readPeerBody: async () => ({ schemaVersion: 1, manifestHash: state.manifestHash, entries }) }));+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission() {} }));+vi.mock('../cosAgentIndex.js', async original => {+ const actual = await original();+ return { ...actual, addAgentArchivesToIndex: async pairs => {+ if (state.failIndex) throw new Error('Example index unavailable');+ return actual.addAgentArchivesToIndex(pairs);+ } };+});++const { syncCosHistoryFromPeer } = await import('./peerCosSync.js');+const { loadAgentIndex } = await import('../cosAgentIndex.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };+const turn = () => new Promise(resolve => setImmediate(resolve));+async function readIndex() { return JSON.parse(await readFile(indexPath, 'utf8')); }+async function assertComplete() {+ expect(await readIndex()).toEqual({ [agentId]: date });+ for (const [filename, content] of Object.entries(files)) {+ expect(await readFile(join(agentsDir, date, agentId, filename), 'utf8')).toBe(content);+ }+}+async function seedArchive() {+ await mkdir(join(agentsDir, date, agentId), { recursive: true });+ for (const [name, body] of Object.entries(files)) await writeFile(join(agentsDir, date, agentId, name), body);+}++let caseNumber = 0;+beforeEach(async () => {+ state.beforeDownload = null; state.beforeWrite = null; state.staged = null; state.failIndex = false;+ state.manifestHash = sha(`case-${++caseNumber}`);+ await rm(agentsDir, { recursive: true, force: true }); await mkdir(agentsDir);+ await writeFile(indexPath, '{}');+ (await loadAgentIndex()).clear();+});+afterAll(async () => { await rm(root, { recursive: true, force: true }); });++describe('peer CoS archive bytes and primary index under a backup cut', () => {+ it('downloads outside admission and keeps staged bytes out of a held snapshot', async () => {+ const downloading = deferred(); const finishDownload = deferred(); const staged = deferred();+ const scratchFiles = [];+ state.beforeDownload = async name => { if (name === 'metadata.json') { downloading.resolve(); await finishDownload.promise; } };+ state.staged = path => { scratchFiles.push(path); if (path.endsWith('prompt.txt')) staged.resolve(); };+ const importing = syncCosHistoryFromPeer(peer);+ await downloading.promise;+ const release = await acquireBackupSnapshotCut();+ try {+ finishDownload.resolve(); await staged.promise; await turn();+ expect(await readIndex()).toEqual({});+ expect(existsSync(join(agentsDir, date, agentId))).toBe(false);+ } finally { release(); }+ expect(await importing).toEqual({ pulled: 3, missing: 0 });+ await assertComplete();+ expect(scratchFiles).toHaveLength(3);+ expect(scratchFiles.some(path => existsSync(path))).toBe(false);+ });++ it('drains final archive writes through the durable primary index commit', async () => {+ const reached = deferred(); const finish = deferred();+ state.beforeWrite = async path => { if (path === indexPath) { reached.resolve(); await finish.promise; } };+ const importing = syncCosHistoryFromPeer(peer);+ await reached.promise;+ expect(await readFile(join(agentsDir, date, agentId, 'output.txt'), 'utf8')).toBe(files['output.txt']);+ expect(await readIndex()).toEqual({});+ let acquired = false;+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });+ try { await turn(); expect(acquired, 'snapshot must not split peer archive files from their index').toBe(false); }+ finally { finish.resolve(); }+ await importing;+ const release = await cut;+ try { await assertComplete(); } finally { release(); }+ });++ it('holds present-but-unindexed recovery outside a cut and retries a failed index merge', async () => {+ await seedArchive();+ state.failIndex = true;+ await syncCosHistoryFromPeer(peer);+ expect(await readIndex()).toEqual({});+ state.failIndex = false;+ const release = await acquireBackupSnapshotCut();+ const recovering = syncCosHistoryFromPeer(peer);+ try { await turn(); expect(await readIndex()).toEqual({}); }+ finally { release(); }+ expect(await recovering).toEqual({ pulled: 0 });+ await assertComplete();+ });+});diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.jsindex 6fb837766a..a89d05955b 100644--- a/server/services/sharing/peerCosSync.js+++ b/server/services/sharing/peerCosSync.js@@ -11,9 +11,11 @@import { isMachineLocalCosTask } from '../../lib/cosFederationPolicy.js';import { join } from 'path';import { existsSync } from 'fs';-import { readdir } from 'fs/promises';+import { mkdtemp, readFile, readdir } from 'fs/promises';+import { tmpdir } from 'os';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { createHash } from 'crypto';-import { PATHS, atomicWrite, ensureDir, sha256File, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';+import { PATHS, atomicWrite, ensureDir, rmGuarded, sha256File, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';import { isPlainObject } from '../../lib/objects.js';import { logFailureWithStack } from '../../lib/failureLogging.js';import { peerBaseUrl } from '../../lib/peerUrl.js';@@ -155,7 +157,7 @@ const lastCosHistoryManifestHash = new Map(); // peerInstanceId → manifestHashconst cosHistoryUnchangedSkips = new Map(); // peerInstanceId → countconst cosHistorySweepInFlight = new Set(); // peerInstanceId-async function pullMissingCosArchives(senderInstanceId, missing) {+async function pullMissingCosArchives(senderInstanceId, missing, stagingRoot) {if (!isStr(senderInstanceId) || !Array.isArray(missing) || missing.length === 0) return [];const peer = await findPeerById(senderInstanceId);if (!peer) {@@ -165,7 +167,7 @@ async function pullMissingCosArchives(senderInstanceId, missing) {const base = peerBaseUrl(peer);const landed = [];for (const entry of missing) {- const pair = await pullOneCosArchiveFile(peer, base, entry).catch((err) => {+ const pair = await pullOneCosArchiveFile(peer, base, entry, stagingRoot).catch((err) => {logFailureWithStack(`⚠️ peerSync: cos-archive pull ${entry?.agentId}/${entry?.file} from ${peer.name || senderInstanceId} failed`, err);return null;});@@ -174,7 +176,7 @@ async function pullMissingCosArchives(senderInstanceId, missing) {return landed;}-async function pullOneCosArchiveFile(peer, base, entry) {+async function pullOneCosArchiveFile(peer, base, entry, stagingRoot) {const { date, agentId, file, sha256 } = entry || {};// Re-validate segments here even though the diff already did.if (!COS_ARCHIVE_DATE_RE.test(date || '') || !COS_AGENT_ID_RE.test(agentId || '') || !COS_ARCHIVE_FILES.includes(file)) return null;@@ -193,12 +195,13 @@ async function pullOneCosArchiveFile(peer, base, entry) {console.error(`⚠️ peerSync: cos archive ${safeLabel} hash mismatch — discarding (got ${bufHash.slice(0, 8)}, want ${String(sha256).slice(0, 8)})`);return null;}- const destDir = join(cosAgentsDir(), date, agentId);+ // Network and integrity checks run outside admission. Keep verified bytes+ // in scratch until the whole sweep can publish files and its index together.+ const destDir = join(stagingRoot, date, agentId);await ensureDir(destDir);- await atomicWrite(join(destDir, file), buffer);- peerSyncEvents.emit('asset-arrived', { filename: safeLabel, kind: 'cos-archive', peerId: peer.instanceId });- console.log(`📥 peerSync: pulled cos archive ${safeLabel} from ${peer.name || peer.instanceId} (${buffer.length} bytes)`);- return { date, agentId };+ const stagedPath = join(destDir, file);+ await atomicWrite(stagedPath, buffer);+ return { date, agentId, file, stagedPath };} finally {inflightPulls.delete(key);}@@ -214,7 +217,7 @@ async function pullOneCosArchiveFile(peer, base, entry) {* overwrites a locally-owned id.*/async function reconcileCosHistoryIndex(entries) {- if (!Array.isArray(entries) || entries.length === 0) return;+ if (!Array.isArray(entries) || entries.length === 0) return true;// One {date, agentId} pair per agent (entries carry up to 3 files per agent).const seen = new Set();const pairs = [];@@ -225,9 +228,10 @@ async function reconcileCosHistoryIndex(entries) {pairs.push({ date: e.date, agentId: e.agentId });}const mod = await import('../cosAgentIndex.js').catch(() => null);- if (!mod?.addAgentArchivesToIndex) return;- await mod.addAgentArchivesToIndex(pairs).catch((err) => {+ if (!mod?.addAgentArchivesToIndex) return false;+ return mod.addAgentArchivesToIndex(pairs).then(() => true, err => {logFailureWithStack('⚠️ peerSync: cos-history index merge failed', err);+ return false;});}@@ -286,35 +290,50 @@ export async function syncCosHistoryFromPeer(peer) {}const missing = await diffCosHistoryManifestAgainstLocal(manifest.entries);if (missing.length === 0) {- // Everything the manifest references is already on disk — reconcile the- // index BEFORE caching the hash so a present-but-unindexed archive (e.g. a- // prior sweep landed the bytes but crashed before the index persisted)- // becomes visible, instead of being skipped forever by the unchanged- // short-circuit above.- await reconcileCosHistoryIndex(manifest.entries);- lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);- return { pulled: 0 };+ // Repair present-but-unindexed archives under admission as well.+ return await withBackupAssetPublication(async () => {+ if (await reconcileCosHistoryIndex(manifest.entries)) {+ lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);+ }+ return { pulled: 0 };+ });}- const requested = missing.length;- await pullMissingCosArchives(peer.instanceId, missing);- // Re-diff: a resolved pull does NOT mean every byte landed (peer dropped,- // 404, size-cap reject) — this is the authoritative signal.- const stillMissing = await diffCosHistoryManifestAgainstLocal(manifest.entries);- const pulled = requested - stillMissing.length;- if (stillMissing.length === 0) {- // Full manifest now present — reconcile the index from the manifest (every- // referenced agent, incl. its metadata.json, is confirmed on disk) before- // caching the hash so the arrivals show in the history UI.- await reconcileCosHistoryIndex(manifest.entries);- lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);- console.log(`📥 peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled} archive file(s)`);- } else {- // Partial pull — do NOT record the hash, so the next tick re-diffs and- // retries the still-missing files; the index is reconciled once the- // manifest is fully present (above), never from a half-pulled agent.- console.error(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${requested}, ${stillMissing.length} still missing; retrying next tick`);+ const stagingRoot = await mkdtemp(join(tmpdir(), 'portos-cos-archive-sync-'));+ try {+ const staged = await pullMissingCosArchives(peer.instanceId, missing, stagingRoot);+ return await withBackupAssetPublication(async () => {+ for (const entry of staged) {+ const { date, agentId, file, stagedPath } = entry;+ const safeLabel = `${date}/${agentId}/${file}`;+ const destDir = join(cosAgentsDir(), date, agentId);+ try {+ const buffer = await readFile(stagedPath);+ await ensureDir(destDir);+ await atomicWrite(join(destDir, file), buffer);+ peerSyncEvents.emit('asset-arrived', { filename: safeLabel, kind: 'cos-archive', peerId: peer.instanceId });+ console.log(`📥 peerSync: pulled cos archive ${safeLabel} from ${peer.name || peer.instanceId} (${buffer.length} bytes)`);+ } catch (err) {+ logFailureWithStack(`⚠️ peerSync: cos-archive publication ${safeLabel} failed`, err);+ }+ }+ // A resolved download does not prove publication. Re-diff before the+ // index commit, while the same lease still protects landed bytes.+ const stillMissing = await diffCosHistoryManifestAgainstLocal(manifest.entries);+ const pulled = missing.length - stillMissing.length;+ if (stillMissing.length === 0) {+ if (await reconcileCosHistoryIndex(manifest.entries)) {+ lastCosHistoryManifestHash.set(peer.instanceId, manifest.manifestHash);+ }+ console.log(`📥 peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled} archive file(s)`);+ } else {+ // Partial bytes remain unindexed and retryable on the next sweep.+ console.error(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${missing.length}, ${stillMissing.length} still missing; retrying next tick`);+ }+ return { pulled, missing: stillMissing.length };+ });+ } finally {+ await rmGuarded(stagingRoot, { recursive: true, force: true });}- return { pulled, missing: stillMissing.length };} finally {cosHistorySweepInFlight.delete(peer.instanceId);}