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
address review (codex): self-heal the cos-history index + never overwrite a local agent id
[._.]/ Adam Eivy0aace7b1917d
diff --git a/server/services/cosAgents.indexMerge.test.js b/server/services/cosAgents.indexMerge.test.jsindex cfd139bc9c..a9dc5b6ab2 100644--- a/server/services/cosAgents.indexMerge.test.js+++ b/server/services/cosAgents.indexMerge.test.js@@ -42,6 +42,11 @@ describe('addAgentArchivesToIndex (#1650)', () => {// Re-adding the same pair is a no-op.expect(await addAgentArchivesToIndex([{ agentId: 'agent-x', date: '2026-06-20' }])).toBe(0);+ // A pre-existing agentId is NEVER overwritten, even with a different date —+ // a peer id-collision must not repoint a locally-owned agent's bucket.+ expect(await addAgentArchivesToIndex([{ agentId: 'agent-x', date: '2026-07-01' }])).toBe(0);+ expect((await loadAgentIndex()).get('agent-x')).toBe('2026-06-20');+// Invalid entries are skipped: empty id, malformed date, empty object.expect(await addAgentArchivesToIndex([{ agentId: '', date: '2026-06-20' },diff --git a/server/services/cosAgents.js b/server/services/cosAgents.jsindex b545693ebc..5bbd3b8eb7 100644--- a/server/services/cosAgents.js+++ b/server/services/cosAgents.js@@ -67,9 +67,15 @@ async function saveAgentIndex() {* Merge a batch of {agentId, date} pairs into the agent index. Used by the* peer-sync CoS-history receiver (#1650): after pulling a peer's completed-agent* archives onto local disk, the date-bucket index must learn the new agentIds so- * the history UI lists them. Idempotent union — re-registering an existing entry- * is a no-op, and only valid YYYY-MM-DD-bucketed pairs are accepted. Returns the- * number of NEW entries added.+ * the history UI lists them. Idempotent union — only valid YYYY-MM-DD-bucketed+ * pairs are accepted. Returns the number of NEW entries added.+ *+ * A pre-existing agentId is treated as already-owned and is NEVER overwritten,+ * even when the incoming `date` differs: agent ids are generated independently+ * per instance, so an id collision (or a restored local archive) must not be able+ * to repoint a local agent's bucket at a peer's date — that would make+ * `getAgent()` read the wrong (or non-existent) directory and hide the local+ * agent's own history. First write wins; the local entry is authoritative.*/export async function addAgentArchivesToIndex(pairs) {if (!Array.isArray(pairs) || pairs.length === 0) return 0;@@ -80,7 +86,7 @@ export async function addAgentArchivesToIndex(pairs) {const date = pair?.date;if (typeof agentId !== 'string' || !agentId) continue;if (typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;- if (idx.get(agentId) === date) continue; // already indexed at this bucket+ if (idx.has(agentId)) continue; // already owned — never overwrite (id is authoritative)idx.set(agentId, date);added += 1;}diff --git a/server/services/sharing/cosHistorySync.test.js b/server/services/sharing/cosHistorySync.test.jsindex 25bd51e911..7e0a1e0b87 100644--- a/server/services/sharing/cosHistorySync.test.js+++ b/server/services/sharing/cosHistorySync.test.js@@ -189,6 +189,21 @@ describe('syncCosHistoryFromPeer', () => {expect(pairs).toContainEqual({ date: '2026-06-20', agentId: 'agent-abc' });});+ it('reconciles the index from the manifest even when every file is already present (crash-recovery)', async () => {+ // Simulate a prior sweep that landed the bytes but never persisted the index.+ const meta = '{"id":"agent-abc"}';+ await seedArchive('2026-06-20', 'agent-abc', { 'metadata.json': meta });+ const entries = [{ date: '2026-06-20', agentId: 'agent-abc', file: 'metadata.json', sha256: sha(meta) }];+ vi.mocked(peerFetch).mockResolvedValue(manifestRes({ schemaVersion: 1, manifestHash: sha('present'), entries }));++ const r = await syncCosHistoryFromPeer(PEER);+ expect(r).toEqual({ pulled: 0 }); // nothing to pull — but the index must still be repaired+ expect(addAgentArchivesToIndex).toHaveBeenCalledTimes(1);+ expect(vi.mocked(addAgentArchivesToIndex).mock.calls[0][0]).toContainEqual({ date: '2026-06-20', agentId: 'agent-abc' });+ // No byte route should have been hit — everything was already on disk.+ expect(vi.mocked(peerFetch).mock.calls.every(([u]) => u.includes('cos-history-manifest'))).toBe(true);+ });+it('withholds the manifest hash on a partial pull (corrupt byte) so it retries', async () => {const meta = 'META';const out = 'OUT';diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 420e68022d..585ba9cae9 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -3182,6 +3182,33 @@ async function pullOneCosArchiveFile(peer, base, entry) {}}+/**+ * Merge the manifest's completed-agent archives into the local agentId→date+ * index so the CoS history UI lists them. Called ONLY when the manifest's files+ * are confirmed present on disk (the diff returned empty), so every referenced+ * agent — including its metadata.json — exists; a half-pulled agent is never+ * indexed. Dynamic import keeps cosAgents out of peerSync's static graph (mirrors+ * reconcileMediaLibraryIndex). addAgentArchivesToIndex unions and never+ * overwrites a locally-owned id.+ */+async function reconcileCosHistoryIndex(entries) {+ if (!Array.isArray(entries) || entries.length === 0) return;+ // One {date, agentId} pair per agent (entries carry up to 3 files per agent).+ const seen = new Set();+ const pairs = [];+ for (const e of entries) {+ const key = `${e.date}/${e.agentId}`;+ if (seen.has(key)) continue;+ seen.add(key);+ pairs.push({ date: e.date, agentId: e.agentId });+ }+ const mod = await import('../cosAgents.js').catch(() => null);+ if (!mod?.addAgentArchivesToIndex) return;+ await mod.addAgentArchivesToIndex(pairs).catch((err) => {+ console.log(`⚠️ peerSync: cos-history index merge failed: ${err.message}`);+ });+}+/*** Receiver-pull the standalone completed-agent history from ONE full-sync peer.* Best-effort + idempotent (every guard returns rather than throws), mirroring@@ -3234,32 +3261,32 @@ 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 };}const requested = missing.length;- const landed = await pullMissingCosArchives(peer.instanceId, missing);- // Merge the agentId→date index so the CoS history UI lists the arrivals.- // Dynamic import keeps cosAgents out of peerSync's static graph (mirrors- // reconcileMediaLibraryIndex). Idempotent union, never overwrites.- if (landed.length > 0) {- const mod = await import('../cosAgents.js').catch(() => null);- if (mod?.addAgentArchivesToIndex) {- await mod.addAgentArchivesToIndex(landed).catch((err) => {- console.log(`⚠️ peerSync: cos-history index merge failed: ${err.message}`);- });- }- }+ 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 instead of being marked done.+ // retries the still-missing files; the index is reconciled once the+ // manifest is fully present (above), never from a half-pulled agent.console.log(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${requested}, ${stillMissing.length} still missing; retrying next tick`);}return { pulled, missing: stillMissing.length };