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: mutex-guard getChangesSince, atomic compactLog, remove JSONL dead code, narrow cursor lock scope
Adam Eivyd8c276ef46c2
diff --git a/server/services/brainSync.js b/server/services/brainSync.jsindex 00636275f4..4c3daa0716 100644--- a/server/services/brainSync.js+++ b/server/services/brainSync.js@@ -12,9 +12,6 @@ import * as brainStorage from './brainStorage.js';// Entity types stored as JSON (have records with IDs)const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories', 'links'];-// JSONL types (append-only logs)-const JSONL_TYPES = ['digests', 'reviews'];-/*** Apply remote changes from a peer instance.* @param {Array} changes - Array of change objects from brainSyncLog@@ -26,18 +23,6 @@ export async function applyRemoteChanges(changes) {for (const change of changes) {const { op, type, id, record } = change;- if (JSONL_TYPES.includes(type)) {- // JSONL types: append if ID doesn't exist- if (op === 'create' && record) {- const result = await brainStorage.applyRemoteJsonl(type, { ...record, id });- if (result.applied) inserted++;- else skipped++;- } else {- skipped++;- }- continue;- }-if (!ENTITY_TYPES.includes(type)) {skipped++;continue;diff --git a/server/services/brainSync.test.js b/server/services/brainSync.test.jsindex 504d6da236..39f7c57161 100644--- a/server/services/brainSync.test.js+++ b/server/services/brainSync.test.js@@ -1,11 +1,10 @@import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('./brainStorage.js', () => ({- applyRemoteRecord: vi.fn(),- applyRemoteJsonl: vi.fn()+ applyRemoteRecord: vi.fn()}));-import { applyRemoteRecord, applyRemoteJsonl } from './brainStorage.js';+import { applyRemoteRecord } from './brainStorage.js';import { applyRemoteChanges } from './brainSync.js';describe('brainSync', () => {@@ -45,24 +44,14 @@ describe('brainSync', () => {expect(result.deleted).toBe(1);});- it('routes JSONL types through applyRemoteJsonl', async () => {- applyRemoteJsonl.mockResolvedValue({ applied: true });-- const result = await applyRemoteChanges([- { op: 'create', type: 'digests', id: 'd1', record: { digestText: 'Today...' } }- ]);-- expect(applyRemoteJsonl).toHaveBeenCalledWith('digests', { digestText: 'Today...', id: 'd1' });- expect(result.inserted).toBe(1);- });-- it('skips JSONL non-create ops', async () => {+ it('skips unsupported types like digests and reviews', async () => {const result = await applyRemoteChanges([+ { op: 'create', type: 'digests', id: 'd1', record: { digestText: 'Today...' } },{ op: 'update', type: 'reviews', id: 'r1', record: {} }]);- expect(applyRemoteJsonl).not.toHaveBeenCalled();- expect(result.skipped).toBe(1);+ expect(applyRemoteRecord).not.toHaveBeenCalled();+ expect(result.skipped).toBe(2);});it('skips unknown entity types', async () => {@@ -99,7 +88,6 @@ describe('brainSync', () => {.mockResolvedValueOnce({ applied: true }) // create people.mockResolvedValueOnce({ applied: true }) // delete projects.mockResolvedValueOnce({ applied: false, reason: 'local_newer' }); // update ideas- applyRemoteJsonl.mockResolvedValue({ applied: true }); // create digestconst result = await applyRemoteChanges([{ op: 'create', type: 'people', id: 'p1', record: { name: 'A' } },@@ -109,19 +97,8 @@ describe('brainSync', () => {{ op: 'create', type: 'bogus', id: 'x1', record: { foo: 1 } }]);- expect(result.inserted).toBe(2); // people + digest+ expect(result.inserted).toBe(1); // peopleexpect(result.deleted).toBe(1);- expect(result.skipped).toBe(2); // local_newer + unknown type- });-- it('counts duplicate JSONL as skipped', async () => {- applyRemoteJsonl.mockResolvedValue({ applied: false, reason: 'duplicate' });-- const result = await applyRemoteChanges([- { op: 'create', type: 'reviews', id: 'r1', record: { reviewText: 'X' } }- ]);-- expect(result.skipped).toBe(1);- expect(result.inserted).toBe(0);+ expect(result.skipped).toBe(3); // local_newer + digests + unknown type});});diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.jsindex 1d50e032f1..f143328c58 100644--- a/server/services/brainSyncLog.js+++ b/server/services/brainSyncLog.js@@ -5,7 +5,7 @@* Used for peer-to-peer brain sync protocol.*/-import { readFile, writeFile, appendFile, mkdir } from 'fs/promises';+import { readFile, writeFile, appendFile, mkdir, rename } from 'fs/promises';import { existsSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';@@ -81,30 +81,32 @@ export async function appendChange(op, type, id, record, originInstanceId) {/*** Get changes since a given sequence number*/-// Note: reads entire file into memory. Bounded by periodic compactLog() in syncOrchestrator-// which drops entries below the minimum peer cursor after each sync cycle.+// Mutex-guarded to prevent reading a partially-written file during compaction.+// Bounded by periodic compactLog() in syncOrchestrator.export async function getChangesSince(sinceSeq, limit = 100) {- await ensureDir();- if (!existsSync(SYNC_LOG_FILE)) {- return { changes: [], maxSeq: currentSeq, hasMore: false };- }+ return withLock(async () => {+ await ensureDir();+ if (!existsSync(SYNC_LOG_FILE)) {+ return { changes: [], maxSeq: currentSeq, hasMore: false };+ }- const content = await readFile(SYNC_LOG_FILE, 'utf-8');- const lines = content.trim().split('\n').filter(l => l.trim());- const changes = [];+ const content = await readFile(SYNC_LOG_FILE, 'utf-8');+ const lines = content.trim().split('\n').filter(l => l.trim());+ const changes = [];- for (const line of lines) {- const entry = safeJSONParse(line, null);- if (!entry || entry.seq <= sinceSeq) continue;- changes.push(entry);- if (changes.length >= limit) break;- }+ for (const line of lines) {+ const entry = safeJSONParse(line, null);+ if (!entry || entry.seq <= sinceSeq) continue;+ changes.push(entry);+ if (changes.length >= limit) break;+ }- const maxSeq = changes.length > 0 ? changes[changes.length - 1].seq : sinceSeq;- const lastLineEntry = lines.length > 0 ? safeJSONParse(lines[lines.length - 1], null) : null;- const hasMore = lastLineEntry ? maxSeq < lastLineEntry.seq : false;+ const maxSeq = changes.length > 0 ? changes[changes.length - 1].seq : sinceSeq;+ const lastLineEntry = lines.length > 0 ? safeJSONParse(lines[lines.length - 1], null) : null;+ const hasMore = lastLineEntry ? maxSeq < lastLineEntry.seq : false;- return { changes, maxSeq, hasMore };+ return { changes, maxSeq, hasMore };+ });}/**@@ -130,7 +132,9 @@ export async function compactLog(minSeq) {}const newContent = kept.length > 0 ? kept.join('\n') + '\n' : '';- await writeFile(SYNC_LOG_FILE, newContent);+ const tmp = `${SYNC_LOG_FILE}.tmp`;+ await writeFile(tmp, newContent);+ await rename(tmp, SYNC_LOG_FILE);console.log(`🔄 Compacted sync log: dropped ${dropped}, kept ${kept.length}`);return dropped;});diff --git a/server/services/brainSyncLog.test.js b/server/services/brainSyncLog.test.jsindex eedcabae30..e5be6708ed 100644--- a/server/services/brainSyncLog.test.js+++ b/server/services/brainSyncLog.test.js@@ -5,7 +5,8 @@ vi.mock('fs/promises', () => ({readFile: vi.fn(),writeFile: vi.fn(),appendFile: vi.fn(),- mkdir: vi.fn()+ mkdir: vi.fn(),+ rename: vi.fn()}));vi.mock('fs', () => ({existsSync: vi.fn()@@ -19,7 +20,7 @@ vi.mock('../lib/fileUtils.js', () => ({}}));-import { readFile, writeFile, appendFile, mkdir } from 'fs/promises';+import { readFile, writeFile, appendFile, mkdir, rename } from 'fs/promises';import { existsSync } from 'fs';import {initSyncLog,@@ -180,6 +181,7 @@ describe('brainSyncLog', () => {'{"seq":1,"op":"create"}\n{"seq":2,"op":"update"}\n{"seq":3,"op":"delete"}\n');writeFile.mockResolvedValue();+ rename.mockResolvedValue();const dropped = await compactLog(2);expect(dropped).toBe(1);@@ -188,6 +190,7 @@ describe('brainSyncLog', () => {expect(written).toContain('"seq":2');expect(written).toContain('"seq":3');expect(written).not.toContain('"seq":1,');+ expect(rename).toHaveBeenCalledTimes(1);});it('returns 0 when file does not exist', async () => {diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 3e818a8112..b451f26788 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -114,20 +114,31 @@ export async function syncWithPeer(peer) {const peerId = peer.instanceId;- const brainResult = await withCursors(async (cursors) => {+ // Read cursor snapshot outside lock so network I/O doesn't block other peers+ const brainCursor = await withCursors(async (cursors) => {if (!cursors[peerId]) cursors[peerId] = {};- const result = await syncBrainFromPeer(peer, cursors[peerId]);- cursors[peerId].brainSeq = result.brainSeq;+ return { ...cursors[peerId] };+ });++ const brainResult = await syncBrainFromPeer(peer, brainCursor);++ await withCursors(async (cursors) => {+ if (!cursors[peerId]) cursors[peerId] = {};+ cursors[peerId].brainSeq = brainResult.brainSeq;cursors[peerId].lastSyncAt = new Date().toISOString();- return result;});- const memoryResult = await withCursors(async (cursors) => {+ const memoryCursor = await withCursors(async (cursors) => {if (!cursors[peerId]) cursors[peerId] = {};- const result = await syncMemoryFromPeer(peer, cursors[peerId]);- cursors[peerId].memorySeq = result.memorySeq;+ return { ...cursors[peerId] };+ });++ const memoryResult = await syncMemoryFromPeer(peer, memoryCursor);++ await withCursors(async (cursors) => {+ if (!cursors[peerId]) cursors[peerId] = {};+ cursors[peerId].memorySeq = memoryResult.memorySeq;cursors[peerId].lastSyncAt = new Date().toISOString();- return result;});const total = brainResult.totalApplied + memoryResult.totalApplied;