Skip to content

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

address review: cache instanceId, mutex remote writes, static rename import, simplify sync logic

Adam Eivy367e4a9cceb6
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 1728738477..4e3a436869 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -14,9 +14,20 @@ import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
import EventEmitter from 'events';
import { readJSONFile, safeJSONParse } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
import { getSelf } from './instances.js';
import * as brainSyncLog from './brainSyncLog.js';
+const withRemoteLock = createMutex();
+let cachedInstanceId = null;
+
+async function getInstanceId() {
+ if (!cachedInstanceId) {
+ cachedInstanceId = (await getSelf())?.instanceId ?? 'unknown';
+ }
+ return cachedInstanceId;
+}
+
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DATA_DIR = join(__dirname, '../../data/brain');
@@ -189,7 +200,7 @@ export async function create(type, recordData) {
const data = await loadJsonStore(type);
const id = generateId();
const timestamp = now();
- const originInstanceId = (await getSelf())?.instanceId ?? 'unknown';
+ const originInstanceId = await getInstanceId();
const record = {
...recordData,
@@ -219,6 +230,7 @@ export async function update(type, id, updates) {
const record = {
...data.records[id],
...updates,
+ // Preserve immutable fields — originInstanceId tracks the creating instance
originInstanceId: data.records[id].originInstanceId,
createdAt: data.records[id].createdAt,
updatedAt: now()
@@ -572,25 +584,27 @@ export async function getLinkByUrl(url) {
* Apply a remote record to a JSON store (last-writer-wins by updatedAt)
*/
export async function applyRemoteRecord(type, id, record, op) {
- const data = await loadJsonStore(type);
+ return withRemoteLock(async () => {
+ const data = await loadJsonStore(type);
- if (op === 'delete') {
- if (!data.records[id]) return { applied: false, reason: 'not_found' };
- delete data.records[id];
- } else {
- const existing = data.records[id];
- if (existing && existing.updatedAt >= record.updatedAt) {
- return { applied: false, reason: 'local_newer' };
+ if (op === 'delete') {
+ if (!data.records[id]) return { applied: false, reason: 'not_found' };
+ delete data.records[id];
+ } else {
+ const existing = data.records[id];
+ if (existing && existing.updatedAt >= record.updatedAt) {
+ return { applied: false, reason: 'local_newer' };
+ }
+ data.records[id] = { ...record };
}
- data.records[id] = { ...record };
- }
- await ensureBrainDir();
- await writeFile(FILES[type], JSON.stringify(data, null, 2));
- caches[type].data = data;
- caches[type].timestamp = Date.now();
+ await ensureBrainDir();
+ await writeFile(FILES[type], JSON.stringify(data, null, 2));
+ caches[type].data = data;
+ caches[type].timestamp = Date.now();
- return { applied: true };
+ return { applied: true };
+ });
}
/**
@@ -615,8 +629,7 @@ export async function applyRemoteJsonl(type, record) {
* Backfill originInstanceId on records missing it (run once at startup)
*/
export async function backfillOriginInstanceId() {
- const self = await getSelf();
- const instanceId = self?.instanceId ?? 'unknown';
+ const instanceId = await getInstanceId();
const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories', 'links'];
let totalBackfilled = 0;
diff --git a/server/services/brainSync.js b/server/services/brainSync.js
index 2e2ac493bd..00636275f4 100644
--- a/server/services/brainSync.js
+++ b/server/services/brainSync.js
@@ -51,7 +51,7 @@ export async function applyRemoteChanges(changes) {
if (!record) { skipped++; continue; }
const result = await brainStorage.applyRemoteRecord(type, id, record, op);
if (result.applied) {
- if (op === 'create' && result.reason !== 'local_newer') inserted++;
+ if (op === 'create') inserted++;
else updated++;
} else {
skipped++;
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 522f35de29..1d50e032f1 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -81,6 +81,8 @@ 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.
export async function getChangesSince(sinceSeq, limit = 100) {
await ensureDir();
if (!existsSync(SYNC_LOG_FILE)) {
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index de8f0258bd..80b4715bac 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -14,6 +14,15 @@ import * as notifications from './notifications.js';
import { DEFAULT_MEMORY_CONFIG, generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';
import { getSelf } from './instances.js';
+let cachedInstanceId = null;
+
+async function getInstanceId() {
+ if (!cachedInstanceId) {
+ cachedInstanceId = (await getSelf())?.instanceId ?? 'unknown';
+ }
+ return cachedInstanceId;
+}
+
/**
* Convert a database row to the memory object format matching the file-based API
*/
@@ -71,7 +80,7 @@ export async function createMemory(data, embedding = null) {
const summary = data.summary || generateSummary(data.content);
const now = new Date().toISOString();
- const originInstanceId = (await getSelf())?.instanceId ?? 'unknown';
+ const originInstanceId = await getInstanceId();
const memory = await withTransaction(async (client) => {
const result = await client.query(
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index edce4faf3f..3e818a8112 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -5,7 +5,7 @@
* Maintains per-peer cursors and triggers sync on peer connect + interval.
*/
-import { writeFile } from 'fs/promises';
+import { writeFile, rename } from 'fs/promises';
import { readJSONFile, ensureDir, PATHS, dataPath } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { instanceEvents } from './instanceEvents.js';
@@ -32,7 +32,6 @@ async function saveCursors(cursors) {
await ensureDir(PATHS.data);
const tmp = `${CURSORS_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(cursors, null, 2));
- const { rename } = await import('fs/promises');
await rename(tmp, CURSORS_FILE);
}
@@ -111,7 +110,7 @@ async function syncMemoryFromPeer(peer, cursor) {
* Sync all data from a single peer
*/
export async function syncWithPeer(peer) {
- if (!peer.instanceId) return;
+ if (!peer.instanceId) return { brain: { totalApplied: 0 }, memory: { totalApplied: 0 } };
const peerId = peer.instanceId;