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: silence no-op federation sync heartbeats (#7944)
[._.]/ Adam Eivy7dc8e8386f50
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 33bae794fe..960a4d62ab 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -44,6 +44,7 @@ const withLock = createMutex();let syncTimer = null;let peerOnlineHandler = null;const syncingPeers = new Set();+let lastOnlinePeerIds = null;// 0 = "never swept this process" — runTombstoneSweep() always runs the FIRST// tick after boot (or after a restart) regardless of this value, then waits// out the full interval before the next one. Reset alongside the timer in@@ -725,7 +726,7 @@ const emptyCoverage = () => ({ universe: new Set(), pipeline: new Set(), mediaCo/*** Sync all data from a single peer*/-export async function syncWithPeer(peer) {+export async function syncWithPeer(peer, { logStart = true, onCategoryFailure } = {}) {if (!peer.instanceId) return { brain: { totalApplied: 0 }, memory: { totalApplied: 0 } };const peerId = peer.instanceId;@@ -760,6 +761,7 @@ export async function syncWithPeer(peer) {const categoryFailures = [];const recordCategoryFailure = (category, err) => {categoryFailures.push(`${category}: ${err?.message ?? String(err)}`);+ onCategoryFailure?.(category, err);};// Null unless EVERY attempted category failed — the cursor write and the// terminal `complete` emit must agree on that verdict.@@ -784,7 +786,9 @@ export async function syncWithPeer(peer) {const categories = getEffectiveCategories(peer);const enabledNames = Object.entries(categories).filter(([, on]) => on).map(([k]) => k);- console.log(`🔄 Sync starting with ${peerLogLabel(peer)}: categories=${enabledNames.join(',') || 'none'}`);+ if (logStart) {+ console.log(`🔄 Sync starting with ${peerLogLabel(peer)}: categories=${enabledNames.join(',') || 'none'}`);+ }emitSyncProgress({ phase: 'start', peerId });// Read cursor snapshot outside lock so network I/O doesn't block other peers@@ -995,15 +999,38 @@ export async function syncAllPeers() {const peers = await getPeers();const online = peers.filter(p => p.enabled && hasAnySyncEnabled(p) && p.status === 'online' && p.instanceId);- if (online.length > 0) {- const names = online.map(p => peerLogLabel(p)).join(', ');- console.log(`🔄 Sync cycle: ${online.length} peer${online.length === 1 ? '' : 's'} online (${names})`);+ const onlinePeerIds = [...new Set(online.map(p => p.instanceId))].sort();+ const membershipChanged = lastOnlinePeerIds !== null+ && (onlinePeerIds.length !== lastOnlinePeerIds.length+ || onlinePeerIds.some((peerId, index) => peerId !== lastOnlinePeerIds[index]));+ lastOnlinePeerIds = onlinePeerIds;++ if (membershipChanged) {+ if (online.length > 0) {+ const names = online.map(p => peerLogLabel(p)).join(', ');+ console.log(`🔄 Sync cycle: ${online.length} peer${online.length === 1 ? '' : 's'} online (${names})`);+ } else {+ console.log('🔄 Sync cycle: peer membership changed (0 online)');+ }}- const settled = await Promise.allSettled(online.map(p => syncWithPeer(p)));+ let cycleFailed = false;+ const settled = await Promise.allSettled(online.map(p => syncWithPeer(p, {+ // The periodic path cannot know whether a sync will change data until it+ // finishes. Keep the start line only for an observable membership change.+ logStart: membershipChanged,+ onCategoryFailure: () => { cycleFailed = true; },+ })));+ for (let i = 0; i < settled.length; i++) {+ const result = settled[i];+ if (result.status === 'rejected') {+ cycleFailed = true;+ logFailureWithStack(`❌ Sync with ${peerLogLabel(online[i])} failed`, result.reason);+ }+ }- // Aggregate per-cycle change counts across peers so the heartbeat is loud- // about totals even when individual per-peer logs short-circuit on no-op.+ // Aggregate applied counts so the cycle summary can stay quiet unless a+ // category changed, failed, or online peer membership changed.let cycleChanges = 0;for (const r of settled) {if (r.status !== 'fulfilled' || !r.value) continue;@@ -1013,7 +1040,7 @@ export async function syncAllPeers() {cycleChanges += v?.totalApplied || 0;}}- if (online.length > 0) {+ if (cycleChanges > 0 || cycleFailed || membershipChanged) {console.log(`🔄 Sync cycle complete: ${cycleChanges} change${cycleChanges === 1 ? '' : 's'} applied across ${online.length} peer${online.length === 1 ? '' : 's'}`);}@@ -1055,6 +1082,7 @@ export function initSyncOrchestrator() {// tombstone sweeps on the first tick — see their interval constants above.lastTombstoneSweepAt = 0;lastBrainSweepAt = 0;+ lastOnlinePeerIds = null;// Sync immediately when a peer comes onlinepeerOnlineHandler = (peer) => {if (!hasAnySyncEnabled(peer)) return;@@ -1161,6 +1189,7 @@ async function runBrainTombstoneSweep() {export function stopSyncOrchestrator() {lastTombstoneSweepAt = 0;lastBrainSweepAt = 0;+ lastOnlinePeerIds = null;if (peerOnlineHandler) {instanceEvents.removeListener('peer:online', peerOnlineHandler);peerOnlineHandler = null;diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 0fe8351369..058be16a20 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -1216,6 +1216,108 @@ describe('syncOrchestrator', () => {});describe('syncAllPeers', () => {+ afterEach(async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['goals', 'character', 'digitalTwin', 'meatspace']);+ });++ const brainOnlyPeer = { ...mockPeer, syncCategories: { brain: true, usage: false } };+ const serveBrainNoOp = () => mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };+ return { ok: true, json: async () => ({}) };+ });++ it('emits no per-tick logs for unchanged no-op cycles', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue([]);+ getPeers.mockResolvedValue([brainOnlyPeer]);+ serveBrainNoOp();+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ await syncAllPeers();+ await syncAllPeers();++ expect(logSpy).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ } finally {+ logSpy.mockRestore();+ errorSpy.mockRestore();+ }+ });++ it('logs a cycle when online peer membership changes', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue([]);+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ getPeers.mockResolvedValue([]);++ try {+ await syncAllPeers();+ getPeers.mockResolvedValue([brainOnlyPeer]);+ serveBrainNoOp();+ await syncAllPeers();++ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sync cycle: 1 peer online'));+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sync starting with test-peer'));+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sync cycle complete: 0 changes applied across 1 peer'));+ } finally {+ logSpy.mockRestore();+ }+ });++ it('keeps the cycle summary when a sync applies changes', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue([]);+ getPeers.mockResolvedValue([brainOnlyPeer]);+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/api/brain/reconcile/checksum')) return { ok: true, json: async () => ({ checksum: 'local-cksum' }) };+ if (url.includes('/api/brain/sync')) return {+ ok: true,+ json: async () => ({ changes: [{ seq: 1, op: 'create', type: 'people', id: 'p1', record: {} }], maxSeq: 1, hasMore: false }),+ };+ return { ok: true, json: async () => ({}) };+ });+ applyBrainChanges.mockResolvedValueOnce({ inserted: 1, updated: 0, deleted: 0, skipped: 0 });+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});++ try {+ await syncAllPeers();++ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Synced with test-peer: 1 brain changes'));+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sync cycle complete: 1 change applied across 1 peer'));+ } finally {+ logSpy.mockRestore();+ }+ });++ it('keeps category failure lines and the cycle summary visible', async () => {+ const dataSync = await import('./dataSync.js');+ dataSync.getSupportedCategories.mockReturnValue(['usage']);+ dataSync.getChecksum.mockResolvedValue({ checksum: 'local' });+ dataSync.applyRemote.mockRejectedValue(new Error('peer refused the usage snapshot'));+ getPeers.mockResolvedValue([{ ...mockPeer, syncCategories: { usage: true } }]);+ mockFetch.mockImplementation(async (url) => {+ if (url.includes('/checksum')) return { ok: true, json: async () => ({ checksum: 'remote' }) };+ if (url.includes('/snapshot')) return { ok: true, json: async () => ({ data: { instances: {} }, checksum: 'remote' }) };+ return { ok: true, json: async () => ({}) };+ });+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ await syncAllPeers();++ expect(errorSpy.mock.calls.some(([message]) => String(message).includes('usage sync with test-peer failed'))).toBe(true);+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sync cycle complete: 0 changes applied across 1 peer'));+ } finally {+ logSpy.mockRestore();+ errorSpy.mockRestore();+ }+ });+it('iterates online peers with instanceId', async () => {const onlinePeer = { ...mockPeer };const offlinePeer = { ...mockPeer, name: 'offline', status: 'offline', instanceId: 'p2' };