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
feat(instances): add granular per-peer sync categories for federation data sharing
Adam Eivye6943e58f4fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1955d26ede..230ade016b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@## Added- Time Capsule Snapshots for Digital Twin — create versioned archives of your complete digital twin (documents, traits, goals, genome, autobiography, test history) to track identity evolution over time. Includes create, view, compare, and delete functionality with a dedicated tab at `/digital-twin/time-capsule`+- Granular per-peer data sync categories for PortOS Federation — enable/disable sync independently for Brain, Memory, Goals, Character, Digital Twin, and Meatspace data per peer instance. All categories disabled by default. Expandable sync categories panel on each peer card with enable/disable all controls. Snapshot-based sync with entity-level merge using last-writer-wins conflict resolution — never loses data from either side## Changeddiff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 3e09bfd370..1c461d6cf9 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -5,7 +5,8 @@ import {Cpu, HardDrive, Activity, Bot, MonitorSmartphone, Tag,ArrowUpRight, ArrowDownLeft, ArrowLeftRight,Database, Brain, CheckCircle2, AlertCircle, Clock,- RefreshCcw, RefreshCcwDot, Timer+ RefreshCcw, RefreshCcwDot, Timer,+ Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight} from 'lucide-react';import toast from 'react-hot-toast';import socket from '../services/socket';@@ -276,15 +277,124 @@ function SyncStatusBadge({ label, icon: Icon, localSeq: _localSeq, peerSeq, curs);}+// Sync category metadata for UI display+const SYNC_CATEGORY_META = [+ { key: 'brain', label: 'Brain', icon: Brain, description: 'People, projects, ideas, admin, memories, links' },+ { key: 'memory', label: 'Memory', icon: Database, description: 'CoS agent memories (PostgreSQL)' },+ { key: 'goals', label: 'Goals', icon: Target, description: 'Life goals, milestones, progress tracking' },+ { key: 'character', label: 'Character', icon: Sword, description: 'XP, HP, level, events, character sheet' },+ { key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, chronotype, longevity, feedback' },+ { key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' }+];++function SyncCategoriesPanel({ peer, onRefresh }) {+ const [expanded, setExpanded] = useState(false);+ const categories = peer.syncCategories || {};+ const enabledCount = Object.values(categories).filter(Boolean).length;++ const toggleCategory = async (key) => {+ const newValue = !categories[key];+ const anyCatEnabled = Object.values({ ...categories, [key]: newValue }).some(Boolean);+ await updatePeer(peer.id, {+ syncCategories: { [key]: newValue },+ syncEnabled: anyCatEnabled+ }).catch(() => null);+ onRefresh();+ };++ const toggleAll = async (enable) => {+ const updated = {};+ for (const { key } of SYNC_CATEGORY_META) {+ updated[key] = enable;+ }+ await updatePeer(peer.id, {+ syncCategories: updated,+ syncEnabled: enable+ }).catch(() => null);+ onRefresh();+ };++ return (+ <div className="mt-2 pt-2 border-t border-port-border/50">+ <button+ onClick={() => setExpanded(!expanded)}+ className="flex items-center gap-1.5 w-full text-left group"+ >+ {expanded ? <ChevronDown size={12} className="text-gray-500" /> : <ChevronRight size={12} className="text-gray-500" />}+ <RefreshCcw size={12} className={enabledCount > 0 ? 'text-port-accent' : 'text-gray-500'} />+ <span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium group-hover:text-gray-400 transition-colors">+ Sync Categories+ </span>+ <span className={`text-[10px] ml-auto ${enabledCount > 0 ? 'text-port-accent' : 'text-gray-600'}`}>+ {enabledCount}/{SYNC_CATEGORY_META.length}+ </span>+ </button>++ {expanded && (+ <div className="mt-2 space-y-1">+ <div className="flex justify-end gap-2 mb-1.5">+ <button+ onClick={() => toggleAll(true)}+ className="text-[10px] text-port-accent hover:text-port-accent/80 transition-colors"+ >+ Enable all+ </button>+ <button+ onClick={() => toggleAll(false)}+ className="text-[10px] text-gray-500 hover:text-gray-400 transition-colors"+ >+ Disable all+ </button>+ </div>+ {SYNC_CATEGORY_META.map(({ key, label, icon: Icon, description }) => (+ <button+ key={key}+ onClick={() => toggleCategory(key)}+ className="flex items-center gap-2 w-full px-2 py-1.5 rounded hover:bg-port-bg/50 transition-colors text-left"+ >+ <div className={`w-3 h-3 rounded-sm border flex-shrink-0 flex items-center justify-center transition-colors ${+ categories[key]+ ? 'bg-port-accent border-port-accent'+ : 'border-gray-600 bg-transparent'+ }`}>+ {categories[key] && <Check size={8} className="text-white" />}+ </div>+ <Icon size={12} className={categories[key] ? 'text-port-accent' : 'text-gray-500'} />+ <div className="flex-1 min-w-0">+ <span className={`text-xs ${categories[key] ? 'text-white' : 'text-gray-400'}`}>{label}</span>+ <p className="text-[10px] text-gray-600 truncate">{description}</p>+ </div>+ </button>+ ))}+ </div>+ )}+ </div>+ );+}+function SyncStatusSection({ peer, syncStatus }) {if (!syncStatus || !peer.instanceId) return null;const cursor = syncStatus.cursors?.[peer.instanceId];const remoteSyncSeqs = peer.remoteSyncSeqs;+ const categories = peer.syncCategories || {};// No sync data available at allif (!cursor && !remoteSyncSeqs) return null;+ // Only show delta-based status for enabled categories+ const showBrain = categories.brain;+ const showMemory = categories.memory;++ // Show snapshot category sync status from checksums+ const checksums = cursor?.checksums || {};+ const syncedSnapshots = SYNC_CATEGORY_META+ .filter(m => m.key !== 'brain' && m.key !== 'memory')+ .map(m => m.key)+ .filter(cat => categories[cat] && checksums[cat]);++ if (!showBrain && !showMemory && syncedSnapshots.length === 0) return null;+return (<div className="mt-2 pt-2 border-t border-port-border/50"><div className="flex items-center gap-1.5 mb-1.5">@@ -295,20 +405,37 @@ function SyncStatusSection({ peer, syncStatus }) {)}</div><div className="grid grid-cols-2 gap-x-3 gap-y-0.5">- <SyncStatusBadge- label="Brain"- icon={Brain}- localSeq={syncStatus.local?.brainSeq}- peerSeq={remoteSyncSeqs?.brainSeq}- cursorSeq={cursor?.brainSeq}- />- <SyncStatusBadge- label="Memory"- icon={Database}- localSeq={syncStatus.local?.memorySeq}- peerSeq={remoteSyncSeqs?.memorySeq}- cursorSeq={cursor?.memorySeq}- />+ {showBrain && (+ <SyncStatusBadge+ label="Brain"+ icon={Brain}+ localSeq={syncStatus.local?.brainSeq}+ peerSeq={remoteSyncSeqs?.brainSeq}+ cursorSeq={cursor?.brainSeq}+ />+ )}+ {showMemory && (+ <SyncStatusBadge+ label="Memory"+ icon={Database}+ localSeq={syncStatus.local?.memorySeq}+ peerSeq={remoteSyncSeqs?.memorySeq}+ cursorSeq={cursor?.memorySeq}+ />+ )}+ {syncedSnapshots.map(cat => {+ const meta = SYNC_CATEGORY_META.find(m => m.key === cat);+ if (!meta) return null;+ const CatIcon = meta.icon;+ return (+ <div key={cat} className="flex items-center gap-1.5 text-xs">+ <CatIcon size={12} className="text-gray-500" />+ <span className="text-gray-500">{meta.label}:</span>+ <CheckCircle2 size={11} className="text-port-success" />+ <span className="text-port-success">synced</span>+ </div>+ );+ })}</div></div>);@@ -352,11 +479,6 @@ function PeerCard({ peer, onRefresh, syncStatus }) {onRefresh();};- const handleSyncToggle = async () => {- await updatePeer(peer.id, { syncEnabled: !peer.syncEnabled }).catch(() => null);- onRefresh();- };-const saveName = async () => {if (!name.trim()) return;const result = await updatePeer(peer.id, { name: name.trim() }).catch(() => null);@@ -407,13 +529,6 @@ function PeerCard({ peer, onRefresh, syncStatus }) {>{peer.enabled ? 'ON' : 'OFF'}</button>- <button- onClick={handleSyncToggle}- className={`p-1 transition-colors ${peer.syncEnabled !== false ? 'text-port-accent hover:text-port-accent/80' : 'text-gray-600 hover:text-white'}`}- title={peer.syncEnabled !== false ? 'Disable sync' : 'Enable sync'}- >- {peer.syncEnabled !== false ? <RefreshCcw size={13} /> : <RefreshCcwDot size={13} />}- </button>{confirmRemove ? (<div className="flex items-center gap-1"><button onClick={handleRemove} className="text-port-error hover:text-port-error/80 text-xs">Yes</button>@@ -463,12 +578,7 @@ function PeerCard({ peer, onRefresh, syncStatus }) {</div>)}- {peer.syncEnabled === false && (- <div className="mt-1 flex items-center gap-1.5 text-xs text-gray-500">- <RefreshCcwDot size={12} />- <span>Sync disabled</span>- </div>- )}+ <SyncCategoriesPanel peer={peer} onRefresh={onRefresh} /><SyncStatusSection peer={peer} syncStatus={syncStatus} />diff --git a/server/index.js b/server/index.jsindex 606246cf2e..885c7ebfb4 100644--- a/server/index.js+++ b/server/index.js@@ -53,6 +53,7 @@ import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';import databaseRoutes from './routes/database.js';import searchRoutes from './routes/search.js';+import dataSyncRoutes from './routes/dataSync.js';import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';import meatspaceRoutes from './routes/meatspace.js';@@ -256,6 +257,7 @@ app.use('/api/jira', jiraRoutes);app.use('/api/health', appleHealthRoutes);app.use('/api/insights', insightsRoutes);app.use('/api/instances', instancesRoutes);+app.use('/api/sync', dataSyncRoutes);app.use('/api/meatspace', meatspaceRoutes);app.use('/api/review', reviewRoutes);app.use('/api/github', githubRoutes);diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsnew file mode 100644index 0000000000..d844d6b7d5--- /dev/null+++ b/server/routes/dataSync.js@@ -0,0 +1,47 @@+/**+ * Data Sync Routes+ *+ * Endpoints for snapshot-based data sync between PortOS peer instances.+ * Each category returns its full data + checksum for merge-based sync.+ */++import { Router } from 'express';+import { z } from 'zod';+import * as dataSync from '../services/dataSync.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';++const router = Router();++const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace']);++// GET /api/sync/:category/checksum — return checksum only (lightweight)+router.get('/:category/checksum', asyncHandler(async (req, res) => {+ const category = categoryParam.parse(req.params.category);+ const result = await dataSync.getChecksum(category);+ if (!result) throw new ServerError('Category not found', { status: 404 });+ res.json(result);+}));++// GET /api/sync/:category/snapshot — return category data + checksum+router.get('/:category/snapshot', asyncHandler(async (req, res) => {+ const category = categoryParam.parse(req.params.category);+ const snapshot = await dataSync.getSnapshot(category);+ if (!snapshot) throw new ServerError('Category not found', { status: 404 });+ res.json(snapshot);+}));++// POST /api/sync/:category/apply — apply remote data with merge+router.post('/:category/apply', asyncHandler(async (req, res) => {+ const category = categoryParam.parse(req.params.category);+ const { data } = req.body;+ if (!data) throw new ServerError('Missing data field', { status: 400 });+ const result = await dataSync.applyRemote(category, data);+ res.json(result);+}));++// GET /api/sync/categories — list supported sync categories+router.get('/', asyncHandler(async (req, res) => {+ res.json({ categories: dataSync.getSupportedCategories() });+}));++export default router;diff --git a/server/routes/instances.js b/server/routes/instances.jsindex e0e1920a52..61e98fca8a 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -22,10 +22,20 @@ const addPeerSchema = z.object({name: z.string().optional()});+const syncCategoriesSchema = z.object({+ brain: z.boolean().optional(),+ memory: z.boolean().optional(),+ goals: z.boolean().optional(),+ character: z.boolean().optional(),+ digitalTwin: z.boolean().optional(),+ meatspace: z.boolean().optional()+}).optional();+const updatePeerSchema = z.object({name: z.string().optional(),enabled: z.boolean().optional(),- syncEnabled: z.boolean().optional()+ syncEnabled: z.boolean().optional(),+ syncCategories: syncCategoriesSchema});const announceSchema = z.object({diff --git a/server/services/dataSync.js b/server/services/dataSync.jsnew file mode 100644index 0000000000..59ec8d1715--- /dev/null+++ b/server/services/dataSync.js@@ -0,0 +1,313 @@+/**+ * Data Sync Service+ *+ * Snapshot-based sync for JSON file data between PortOS peer instances.+ * Supports per-category sync with entity-level merge and LWW conflict resolution.+ * No data is ever lost — unique records from both sides are kept (union semantics).+ */++import crypto from 'crypto';+import { writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';++// --- Category Definitions ---++const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');+const CHARACTER_FILE = join(PATHS.data, 'character.json');+const IDENTITY_FILE = join(PATHS.digitalTwin, 'identity.json');+const CHRONOTYPE_FILE = join(PATHS.digitalTwin, 'chronotype.json');+const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');+const FEEDBACK_FILE = join(PATHS.digitalTwin, 'feedback.json');+const MEATSPACE_DIR = PATHS.meatspace;++const MEATSPACE_FILES = {+ 'daily-log.json': { arrayKey: 'entries', idField: 'date' },+ 'blood-tests.json': { arrayKey: 'tests', idField: 'date' },+ 'epigenetic-tests.json': { arrayKey: 'tests', idField: 'date' },+ 'eyes.json': { arrayKey: 'exams', idField: 'date' },+ 'config.json': { type: 'object-lww' }+};++// --- Checksum Helper ---++function computeChecksum(data) {+ return crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');+}++// --- Merge Helpers ---++/**+ * Merge two arrays of records by a key field. LWW by timestampField when both+ * sides have the same record. Records unique to either side are kept (union).+ */+function mergeArraysByKey(localArr, remoteArr, idField, timestampField) {+ const localMap = new Map();+ for (const item of localArr) {+ localMap.set(item[idField], item);+ }++ let changed = false;+ for (const remoteItem of remoteArr) {+ const key = remoteItem[idField];+ const localItem = localMap.get(key);++ if (!localItem) {+ // New record from remote — add it+ localMap.set(key, remoteItem);+ changed = true;+ } else if (timestampField) {+ // Both have it — LWW+ const localTs = localItem[timestampField] || '';+ const remoteTs = remoteItem[timestampField] || '';+ if (remoteTs > localTs) {+ localMap.set(key, remoteItem);+ changed = true;+ }+ }+ }++ return { merged: Array.from(localMap.values()), changed };+}++/**+ * LWW merge for single objects. Remote wins if its updatedAt is newer.+ */+function mergeObjectLWW(local, remote, timestampField = 'updatedAt') {+ if (!local) return { merged: remote, changed: true };+ if (!remote) return { merged: local, changed: false };+ const localTs = local[timestampField] || '';+ const remoteTs = remote[timestampField] || '';+ if (remoteTs > localTs) {+ return { merged: remote, changed: true };+ }+ return { merged: local, changed: false };+}++// --- Category: Goals ---++async function getGoalsSnapshot() {+ const data = await readJSONFile(GOALS_FILE, { goals: [] });+ return { data, checksum: computeChecksum(data) };+}++async function applyGoalsRemote(remoteData) {+ const local = await readJSONFile(GOALS_FILE, { goals: [] });++ // Merge goals array by ID with LWW on updatedAt+ const { merged: mergedGoals, changed: goalsChanged } = mergeArraysByKey(+ local.goals || [],+ remoteData.goals || [],+ 'id',+ 'updatedAt'+ );++ // Merge top-level metadata (birthDate, lifeExpectancy, timeHorizons) via LWW+ // Use the most recent goal's updatedAt as proxy for file freshness+ const localMaxTs = Math.max(0, ...(local.goals || []).map(g => new Date(g.updatedAt || 0).getTime()));+ const remoteMaxTs = Math.max(0, ...(remoteData.goals || []).map(g => new Date(g.updatedAt || 0).getTime()));+ const metaSource = remoteMaxTs > localMaxTs ? remoteData : local;++ const merged = {+ ...local,+ birthDate: metaSource.birthDate ?? local.birthDate,+ lifeExpectancy: metaSource.lifeExpectancy ?? local.lifeExpectancy,+ timeHorizons: metaSource.timeHorizons ?? local.timeHorizons,+ goals: mergedGoals+ };++ if (goalsChanged || remoteMaxTs > localMaxTs) {+ await ensureDir(PATHS.digitalTwin);+ await writeFile(GOALS_FILE, JSON.stringify(merged, null, 2));+ console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);+ return { applied: true, count: mergedGoals.length };+ }+ return { applied: false, count: 0 };+}++// --- Category: Character ---++async function getCharacterSnapshot() {+ const data = await readJSONFile(CHARACTER_FILE, null);+ if (!data) return { data: null, checksum: 'empty' };+ return { data, checksum: computeChecksum(data) };+}++async function applyCharacterRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };++ const local = await readJSONFile(CHARACTER_FILE, null);+ if (!local) {+ // No local character — accept remote entirely+ await ensureDir(PATHS.data);+ await writeFile(CHARACTER_FILE, JSON.stringify(remoteData, null, 2));+ console.log(`🔄 Character sync: accepted remote character`);+ return { applied: true, count: 1 };+ }++ // Merge events by ID (union — never lose events)+ const { merged: mergedEvents, changed: eventsChanged } = mergeArraysByKey(+ local.events || [],+ remoteData.events || [],+ 'id',+ 'timestamp'+ );++ // Sort events chronologically+ mergedEvents.sort((a, b) => (a.timestamp || '').localeCompare(b.timestamp || ''));++ // Merge synced ticket/task arrays (union by value)+ const mergedTickets = [...new Set([...(local.syncedJiraTickets || []), ...(remoteData.syncedJiraTickets || [])])];+ const mergedTasks = [...new Set([...(local.syncedTaskIds || []), ...(remoteData.syncedTaskIds || [])])];++ // Scalar fields: take from whichever is more recent+ const localTs = local.updatedAt || '';+ const remoteTs = remoteData.updatedAt || '';+ const scalarSource = remoteTs > localTs ? remoteData : local;++ const merged = {+ ...local,+ name: scalarSource.name ?? local.name,+ class: scalarSource.class ?? local.class,+ avatarPath: scalarSource.avatarPath ?? local.avatarPath,+ xp: Math.max(local.xp || 0, remoteData.xp || 0),+ hp: scalarSource.hp,+ maxHp: scalarSource.maxHp,+ level: Math.max(local.level || 1, remoteData.level || 1),+ events: mergedEvents,+ syncedJiraTickets: mergedTickets,+ syncedTaskIds: mergedTasks,+ updatedAt: remoteTs > localTs ? remoteTs : localTs+ };++ if (eventsChanged || remoteTs > localTs) {+ await ensureDir(PATHS.data);+ await writeFile(CHARACTER_FILE, JSON.stringify(merged, null, 2));+ console.log(`🔄 Character sync: merged ${mergedEvents.length} events`);+ return { applied: true, count: mergedEvents.length };+ }+ return { applied: false, count: 0 };+}++// --- Category: Digital Twin ---++const DIGITAL_TWIN_FILES = {+ identity: { path: IDENTITY_FILE, timestampField: 'updatedAt' },+ chronotype: { path: CHRONOTYPE_FILE, timestampField: 'updatedAt' },+ longevity: { path: LONGEVITY_FILE, timestampField: 'updatedAt' },+ feedback: { path: FEEDBACK_FILE, timestampField: 'updatedAt' }+};++async function getDigitalTwinSnapshot() {+ const result = {};+ for (const [key, { path }] of Object.entries(DIGITAL_TWIN_FILES)) {+ result[key] = await readJSONFile(path, null);+ }+ return { data: result, checksum: computeChecksum(result) };+}++async function applyDigitalTwinRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ await ensureDir(PATHS.digitalTwin);++ let totalApplied = 0;+ for (const [key, { path, timestampField }] of Object.entries(DIGITAL_TWIN_FILES)) {+ const remoteFile = remoteData[key];+ if (!remoteFile) continue;++ const local = await readJSONFile(path, null);+ const { merged, changed } = mergeObjectLWW(local, remoteFile, timestampField);+ if (changed) {+ await writeFile(path, JSON.stringify(merged, null, 2));+ totalApplied++;+ }+ }++ if (totalApplied > 0) {+ console.log(`🔄 Digital twin sync: updated ${totalApplied} files`);+ }+ return { applied: totalApplied > 0, count: totalApplied };+}++// --- Category: Meatspace ---++async function getMeatspaceSnapshot() {+ const result = {};+ for (const [filename] of Object.entries(MEATSPACE_FILES)) {+ const filePath = join(MEATSPACE_DIR, filename);+ result[filename] = await readJSONFile(filePath, null);+ }+ return { data: result, checksum: computeChecksum(result) };+}++async function applyMeatspaceRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ await ensureDir(MEATSPACE_DIR);++ let totalApplied = 0;+ for (const [filename, config] of Object.entries(MEATSPACE_FILES)) {+ const remoteFile = remoteData[filename];+ if (!remoteFile) continue;++ const filePath = join(MEATSPACE_DIR, filename);+ const local = await readJSONFile(filePath, null);++ if (config.type === 'object-lww') {+ const { merged, changed } = mergeObjectLWW(local, remoteFile, 'updatedAt');+ if (changed) {+ await writeFile(filePath, JSON.stringify(merged, null, 2));+ totalApplied++;+ }+ } else {+ // Array merge+ const localArr = local?.[config.arrayKey] || [];+ const remoteArr = remoteFile[config.arrayKey] || [];+ const { merged, changed } = mergeArraysByKey(localArr, remoteArr, config.idField, null);++ if (changed) {+ // Sort by idField (usually date)+ merged.sort((a, b) => (a[config.idField] || '').localeCompare(b[config.idField] || ''));+ const mergedFile = { ...(local || {}), [config.arrayKey]: merged };+ await writeFile(filePath, JSON.stringify(mergedFile, null, 2));+ totalApplied++;+ }+ }+ }++ if (totalApplied > 0) {+ console.log(`🔄 Meatspace sync: updated ${totalApplied} files`);+ }+ return { applied: totalApplied > 0, count: totalApplied };+}++// --- Public API ---++const CATEGORIES = {+ goals: { getSnapshot: getGoalsSnapshot, applyRemote: applyGoalsRemote },+ character: { getSnapshot: getCharacterSnapshot, applyRemote: applyCharacterRemote },+ digitalTwin: { getSnapshot: getDigitalTwinSnapshot, applyRemote: applyDigitalTwinRemote },+ meatspace: { getSnapshot: getMeatspaceSnapshot, applyRemote: applyMeatspaceRemote }+};++export function getSupportedCategories() {+ return Object.keys(CATEGORIES);+}++export async function getChecksum(category) {+ const cat = CATEGORIES[category];+ if (!cat) return null;+ const snapshot = await cat.getSnapshot();+ return { checksum: snapshot.checksum };+}++export async function getSnapshot(category) {+ const cat = CATEGORIES[category];+ if (!cat) return null;+ return cat.getSnapshot();+}++export async function applyRemote(category, remoteData) {+ const cat = CATEGORIES[category];+ if (!cat) return { applied: false, count: 0 };+ return cat.applyRemote(remoteData);+}diff --git a/server/services/instances.js b/server/services/instances.jsindex 25b8c75336..37a02a42c2 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -115,6 +115,18 @@ function validName(name, fallback) {return name.trim();}+// Default sync categories — all disabled until explicitly enabled per-peer+const DEFAULT_SYNC_CATEGORIES = {+ brain: false,+ memory: false,+ goals: false,+ character: false,+ digitalTwin: false,+ meatspace: false+};++export { DEFAULT_SYNC_CATEGORIES };+export async function addPeer({ address, port = DEFAULT_PEER_PORT, name }) {const peer = await withData(async (data) => {const entry = {@@ -128,7 +140,8 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name }) {lastHealth: null,status: 'unknown',enabled: true,- syncEnabled: true,+ syncEnabled: false,+ syncCategories: { ...DEFAULT_SYNC_CATEGORIES },consecutiveFailures: 0,nextProbeAt: null,directions: ['outbound']@@ -163,6 +176,9 @@ export async function updatePeer(id, updates) {if (updates.name !== undefined) peer.name = validName(updates.name, peer.name);if (updates.enabled !== undefined) peer.enabled = updates.enabled;if (updates.syncEnabled !== undefined) peer.syncEnabled = updates.syncEnabled;+ if (updates.syncCategories !== undefined) {+ peer.syncCategories = { ...(peer.syncCategories || DEFAULT_SYNC_CATEGORIES), ...updates.syncCategories };+ }instanceEvents.emit('peers:updated', data.peers);return peer;});@@ -342,7 +358,8 @@ export async function handleAnnounce({ address, port, instanceId, name }) {lastHealth: null,status: 'online',enabled: true,- syncEnabled: true,+ syncEnabled: false,+ syncCategories: { ...DEFAULT_SYNC_CATEGORIES },consecutiveFailures: 0,nextProbeAt: null,directions: ['inbound']diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 93d2136b53..d63b51244c 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -1,7 +1,8 @@/*** Sync Orchestrator*- * Unified coordinator for brain + memory sync between PortOS peer instances.+ * Unified coordinator for all data sync between PortOS peer instances.+ * Supports per-category sync: brain, memory, goals, character, digitalTwin, meatspace.* Maintains per-peer cursors and triggers sync on peer connect + interval.*/@@ -9,10 +10,11 @@ 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';-import { getPeers } from './instances.js';+import { getPeers, DEFAULT_SYNC_CATEGORIES } from './instances.js';import * as brainSync from './brainSync.js';import * as brainSyncLog from './brainSyncLog.js';import * as memorySync from './memorySync.js';+import * as dataSync from './dataSync.js';import { getBackendName } from './memoryBackend.js';const CURSORS_FILE = dataPath('instances_sync_cursors.json');@@ -196,6 +198,43 @@ function detectCursorReset(cursor, peer) {return corrected;}+/**+ * Resolve effective sync categories for a peer.+ * Returns object with boolean flags for each category.+ * Falls back to legacy behavior: if syncCategories is absent but syncEnabled is true,+ * enable brain + memory for backward compatibility with older peers.+ */+function getEffectiveCategories(peer) {+ if (peer.syncCategories) return peer.syncCategories;+ // Legacy fallback: peers without syncCategories but with syncEnabled get brain+memory+ if (peer.syncEnabled !== false) {+ return { ...DEFAULT_SYNC_CATEGORIES, brain: true, memory: true };+ }+ return { ...DEFAULT_SYNC_CATEGORIES };+}++/**+ * Sync a snapshot-based data category from a peer.+ * Fetches checksum first to avoid full data transfer when unchanged.+ */+async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums) {+ // Lightweight checksum check first+ const checksumRes = await fetchPeer(peer, `/api/sync/${category}/checksum`);+ if (!checksumRes?.checksum) return { totalApplied: 0, checksum: null };++ const lastChecksum = cachedChecksums?.[category] ?? null;+ if (lastChecksum && lastChecksum === checksumRes.checksum) {+ return { totalApplied: 0, checksum: checksumRes.checksum };+ }++ // Checksum changed — fetch full snapshot+ const snapshot = await fetchPeer(peer, `/api/sync/${category}/snapshot`);+ if (!snapshot?.data) return { totalApplied: 0, checksum: null };++ const result = await dataSync.applyRemote(category, snapshot.data);+ return { totalApplied: result.applied ? result.count : 0, checksum: snapshot.checksum };+}+/*** Sync all data from a single peer*/@@ -208,6 +247,8 @@ export async function syncWithPeer(peer) {if (syncingPeers.has(peerId)) return { brain: { totalApplied: 0 }, memory: { totalApplied: 0 } };syncingPeers.add(peerId);+ const categories = getEffectiveCategories(peer);+// Read cursor snapshot outside lock so network I/O doesn't block other peers// Also detect and reset stale cursors (e.g. peer DB was rebuilt)const cursor = await readCursors((cursors) => {@@ -216,52 +257,99 @@ export async function syncWithPeer(peer) {});try {- const brainResult = await syncBrainFromPeer(peer, cursor);+ // --- Brain sync (delta-based) ---+ let brainResult = { brainSeq: cursor.brainSeq ?? 0, totalApplied: 0 };+ if (categories.brain) {+ brainResult = await syncBrainFromPeer(peer, cursor);+ }- // Save brain cursor immediately so progress is preserved if memory sync fails- await withCursors(async (cursors) => {- if (!cursors[peerId]) cursors[peerId] = {};- cursors[peerId].brainSeq = brainResult.brainSeq;- cursors[peerId].lastSyncAt = new Date().toISOString();- });+ // --- Memory sync (delta-based, PostgreSQL only) ---+ let memoryResult = { memorySeq: cursor.memorySeq ?? '0', totalApplied: 0 };+ if (categories.memory) {+ const isPostgres = getBackendName() === 'postgres';+ if (isPostgres) {+ memoryResult = await syncMemoryFromPeer(peer, cursor);+ }+ }- const isPostgres = getBackendName() === 'postgres';- const memoryResult = isPostgres- ? await syncMemoryFromPeer(peer, cursor)- : { memorySeq: cursor.memorySeq ?? '0', totalApplied: 0 };+ // --- Snapshot-based category syncs (parallel) ---+ const dataCategoryResults = {};+ const enabledDataCats = dataSync.getSupportedCategories().filter(cat => categories[cat]);+ const cachedChecksums = cursor.checksums || {};++ if (enabledDataCats.length > 0) {+ const settled = await Promise.allSettled(+ enabledDataCats.map(cat =>+ syncDataCategoryFromPeer(peer, peerId, cat, cachedChecksums)+ .catch(err => {+ console.error(`⚠️ ${cat} sync with ${peer.name} failed: ${err.message}`);+ return { totalApplied: 0, checksum: null };+ })+ )+ );+ for (let i = 0; i < enabledDataCats.length; i++) {+ const result = settled[i].status === 'fulfilled' ? settled[i].value : { totalApplied: 0, checksum: null };+ dataCategoryResults[enabledDataCats[i]] = result;+ }+ }+ // --- Single consolidated cursor write ---await withCursors(async (cursors) => {if (!cursors[peerId]) cursors[peerId] = {};- if (isPostgres) cursors[peerId].memorySeq = memoryResult.memorySeq;+ if (categories.brain) cursors[peerId].brainSeq = brainResult.brainSeq;+ if (memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;+ if (!cursors[peerId].checksums) cursors[peerId].checksums = {};+ for (const [cat, result] of Object.entries(dataCategoryResults)) {+ if (result.checksum) cursors[peerId].checksums[cat] = result.checksum;+ }cursors[peerId].lastSyncAt = new Date().toISOString();});- const total = brainResult.totalApplied + memoryResult.totalApplied;- if (total > 0) {- console.log(`🔄 Synced with ${peer.name}: ${brainResult.totalApplied} brain, ${memoryResult.totalApplied} memory changes`);+ // Log summary+ const parts = [];+ if (brainResult.totalApplied > 0) parts.push(`${brainResult.totalApplied} brain`);+ if (memoryResult.totalApplied > 0) parts.push(`${memoryResult.totalApplied} memory`);+ for (const [cat, result] of Object.entries(dataCategoryResults)) {+ if (result.totalApplied > 0) parts.push(`${result.totalApplied} ${cat}`);+ }+ if (parts.length > 0) {+ console.log(`🔄 Synced with ${peer.name}: ${parts.join(', ')} changes`);}- return { brain: brainResult, memory: memoryResult };+ return { brain: brainResult, memory: memoryResult, ...dataCategoryResults };} finally {syncingPeers.delete(peerId);}}+/**+ * Check if a peer has any sync category enabled+ */+function hasAnySyncEnabled(peer) {+ if (peer.syncEnabled === false) return false;+ const cats = getEffectiveCategories(peer);+ return Object.values(cats).some(Boolean);+}+/*** Sync with all online peers*/export async function syncAllPeers() {const peers = await getPeers();- const online = peers.filter(p => p.enabled && p.syncEnabled !== false && p.status === 'online' && p.instanceId);+ const online = peers.filter(p => p.enabled && hasAnySyncEnabled(p) && p.status === 'online' && p.instanceId);await Promise.allSettled(online.map(p => syncWithPeer(p)));// Compact sync log below the minimum peer cursor to bound log growth- // Include all enabled peers (not just online) so offline peers don't lose unsynced entries+ // Include all enabled peers with brain sync (not just online) so offline peers don't lose unsynced entriesconst cursors = await loadCursors();- const allEnabledIds = new Set(peers.filter(p => p.enabled && p.instanceId).map(p => p.instanceId));+ const brainEnabledIds = new Set(+ peers+ .filter(p => p.enabled && p.instanceId && getEffectiveCategories(p).brain)+ .map(p => p.instanceId)+ );const seqs = Object.entries(cursors)- .filter(([id]) => allEnabledIds.has(id))+ .filter(([id]) => brainEnabledIds.has(id)).map(([, c]) => c.brainSeq ?? 0);if (seqs.length > 0) {const minSeq = Math.min(...seqs);@@ -275,7 +363,7 @@ export async function syncAllPeers() {export function initSyncOrchestrator() {// Sync immediately when a peer comes onlinepeerOnlineHandler = (peer) => {- if (peer.syncEnabled === false) return;+ if (!hasAnySyncEnabled(peer)) return;syncWithPeer(peer).catch(err => {console.error(`❌ Sync with ${peer.name} failed: ${err.message}`);});diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex 059c007011..318ccfe828 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -2,7 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock all dependenciesvi.mock('./instances.js', () => ({- getPeers: vi.fn()+ getPeers: vi.fn(),+ DEFAULT_SYNC_CATEGORIES: {+ brain: false, memory: false, goals: false,+ character: false, digitalTwin: false, meatspace: false+ }}));vi.mock('./brainSyncLog.js', () => ({getChangesSince: vi.fn(),@@ -18,6 +22,11 @@ vi.mock('./memorySync.js', () => ({vi.mock('./memoryBackend.js', () => ({getBackendName: vi.fn(() => 'postgres')}));+vi.mock('./dataSync.js', () => ({+ getSnapshot: vi.fn().mockResolvedValue({ data: {}, checksum: 'abc' }),+ applyRemote: vi.fn().mockResolvedValue({ applied: false, count: 0 }),+ getSupportedCategories: vi.fn(() => ['goals', 'character', 'digitalTwin', 'meatspace'])+}));vi.mock('./instanceEvents.js', () => ({instanceEvents: { on: vi.fn(), removeListener: vi.fn() }}));