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([issue-1080]): re-vectorize synced-in brain records into memory
Adam Eivycd67dad250b0
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsxindex 3c12588350..c4d9a8199e 100644--- a/client/src/components/brain/tabs/BrainGraph.jsx+++ b/client/src/components/brain/tabs/BrainGraph.jsx@@ -2,7 +2,7 @@ import { useState, useEffect, useMemo, useRef, useCallback } from 'react';import { Canvas } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei';import * as THREE from 'three';-import {Search, AlertTriangle, Zap} from 'lucide-react';+import {Search, AlertTriangle, Zap, RefreshCw} from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';@@ -210,9 +210,12 @@ export default function BrainGraph() {}}, []);- const handleSync = async () => {+ // refresh:true re-embeds already-mapped records — the recovery path for+ // memory entries that diverged before synced-in records were re-vectorized+ // automatically (issue #1080). The default sync only embeds new records.+ const handleSync = async ({ refresh = false } = {}) => {setSyncing(true);- const stats = await api.syncBrainData().catch(err => {+ const stats = await api.syncBrainData({ refresh }).catch(err => {toast.error(err.message || 'Sync failed');return null;});@@ -256,7 +259,7 @@ export default function BrainGraph() {No embeddings found. Sync brain data to CoS memory to enable semantic similarity edges.</div><button- onClick={handleSync}+ onClick={() => handleSync()}disabled={syncing}className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-port-warning/20 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/30 transition-colors disabled:opacity-50">@@ -314,6 +317,18 @@ export default function BrainGraph() {>Re-layout</button>+ {/* Recovery action (issue #1080): re-embed already-synced records whose+ memory copy may be stale — e.g. a peer edited a record that this+ machine received via sync before auto re-vectorization existed. */}+ <button+ onClick={() => handleSync({ refresh: true })}+ disabled={syncing}+ title="Re-embed all brain records, including ones synced from peers, to refresh stale memory entries"+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors disabled:opacity-50"+ >+ {syncing ? <BrailleSpinner /> : <RefreshCw size={14} />}+ Refresh embeddings+ </button></div>{/* 3D Canvas */}diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex ddc5b0e67f..9b6a4b219f 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -197,8 +197,11 @@ export const reorderBrainBuckets = (ids) => request('/brain/buckets/reorder', {// Brain - Graphexport const getBrainGraph = () => request('/brain/graph');-// Brain - Bridge Sync (brain data to CoS memory system)-export const syncBrainData = () => request('/brain/bridge-sync', { method: 'POST' });+// Brain - Bridge Sync (brain data to CoS memory system).+// refresh:true re-embeds already-mapped records to heal memory entries that+// went stale before the per-record sync signal existed (issue #1080).+export const syncBrainData = ({ refresh = false } = {}) =>+ request('/brain/bridge-sync', { method: 'POST', body: JSON.stringify({ refresh }) });// Brain - Daily Logexport const listDailyLogs = (options = {}) => {diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex c750a253d0..65166f6974 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -474,6 +474,14 @@ export const brainSyncPushSchema = z.object({changes: z.array(brainSyncChangeSchema).min(1).max(1000)});+// Brain bridge-sync body (POST /api/brain/bridge-sync). `refresh` forces a+// re-embed of already-mapped records — the recovery path for memory entries+// that diverged before the per-record sync:applied signal existed (issue+// #1080). Optional + default-false so the existing no-body call is unchanged.+export const brainBridgeSyncSchema = z.object({+ refresh: z.boolean().optional().default(false)+});+// Daily log settings schema (PUT /api/brain/daily-log/settings body).// Only these three keys are persisted — strict() rejects unknown keys so// a typo or stray payload field can't corrupt the settings file.diff --git a/server/routes/brain.js b/server/routes/brain.jsindex fbbdf57382..58623e3488 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -37,6 +37,7 @@ import {bucketReorderSchema,brainSyncQuerySchema,brainSyncPushSchema,+ brainBridgeSyncSchema,dailyLogSettingsSchema} from '../lib/brainValidation.js';import * as githubCloner from '../services/githubCloner.js';@@ -963,12 +964,16 @@ router.get('/graph', asyncHandler(async (req, res) => {/*** POST /api/brain/bridge-sync- * Sync all brain data to CoS memory system (generates embeddings)+ * Sync all brain data to CoS memory system (generates embeddings).+ * Body: { refresh?: boolean } — refresh:true re-embeds already-mapped records+ * to heal memory entries that diverged before the per-record sync:applied+ * signal existed (issue #1080).* (Renamed from /sync to avoid conflict with federation sync)*/router.post('/bridge-sync', asyncHandler(async (req, res) => {- const stats = await syncAllBrainData();- console.log(`🧠🔗 Brain bridge sync complete: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.errors} errors`);+ const { refresh } = validateRequest(brainBridgeSyncSchema, req.body ?? {});+ const stats = await syncAllBrainData({ refresh });+ console.log(`🧠🔗 Brain bridge sync complete${refresh ? ' (refresh)' : ''}: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.errors} errors`);res.json(stats);}));diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 3afabdd462..5ead4fcab6 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -17,7 +17,7 @@ import * as brainStorage from './brainStorage.js';import * as memory from './memoryBackend.js';import * as embeddings from './memoryEmbeddings.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';-import { listJournals } from './brainJournal.js';+import { listJournals, getJournal } from './brainJournal.js';const BRIDGE_MAP_PATH = join(PATHS.brain, 'memory-bridge-map.json');@@ -208,9 +208,19 @@ export async function syncBrainRecord(brainType, record) {/*** Bulk sync all existing brain data into the memory system.* Used for initial migration and catch-up.- * Returns { synced, skipped, errors }.+ *+ * @param {object} [opts]+ * @param {boolean} [opts.dryRun=false] Report what would sync without writing.+ * @param {boolean} [opts.refresh=false] Re-embed records that ALREADY have a+ * bridge-map entry instead of skipping them. This is the recovery path for+ * records that diverged before the per-record sync:applied signal existed+ * (issue #1080): a peer's edit/delete of an already-mapped record used to+ * leave the local memory copy stale and searchable forever, and a normal+ * bulk sync skipped it precisely because it was mapped. `refresh` forces a+ * re-embed of every live record so a one-time catch-up heals the staleness.+ * @returns {Promise<{synced:number, skipped:number, errors:number}>}*/-export async function syncAllBrainData({ dryRun = false } = {}) {+export async function syncAllBrainData({ dryRun = false, refresh = false } = {}) {const map = await loadBridgeMap();const stats = { synced: 0, skipped: 0, errors: 0 };@@ -225,7 +235,7 @@ export async function syncAllBrainData({ dryRun = false } = {}) {continue;}const key = bridgeKey(type, record.id);- if (map[key] && !dryRun) {+ if (map[key] && !dryRun && !refresh) {stats.skipped++;continue;}@@ -243,18 +253,19 @@ export async function syncAllBrainData({ dryRun = false } = {}) {}}- // Daily log entries — one memory per day, initial/backfill import only;- // already-mapped records are skipped by this bulk sync. Content updates- // and deletions flow through the 'journals:upserted' / 'journals:deleted'- // event handlers instead (see initBridge).+ // Daily log entries — one memory per day. Without `refresh`, already-mapped+ // days are skipped (initial/backfill import only) and content updates /+ // deletions flow through the 'journals:upserted' / 'journals:deleted' and+ // 'sync:applied' event handlers instead (see initBridge). With `refresh`,+ // already-mapped days are re-embedded to heal pre-#1080 staleness.{const { records: journals } = await listJournals({ limit: 10000, includeContent: true });for (const record of journals) {const key = bridgeKey('journals', record.id);// Already-mapped days are skipped in both real and dry-run modes so// dry-run stats match actual-run stats (rather than claiming to- // re-sync every day every time).- if (map[key]) {+ // re-sync every day every time) — unless refresh is forcing a re-embed.+ if (map[key] && !refresh) {stats.skipped += 1;continue;}@@ -279,7 +290,7 @@ export async function syncAllBrainData({ dryRun = false } = {}) {const records = await getter(1000); // get allfor (const record of records) {const key = bridgeKey(type, record.id);- if (map[key] && !dryRun) {+ if (map[key] && !dryRun && !refresh) {stats.skipped++;continue;}@@ -300,6 +311,86 @@ export async function syncAllBrainData({ dryRun = false } = {}) {return stats;}+// ─── Synced-in record resync (issue #1080) ──────────────────────────────────+// Peer-synced brain writes go through brainStorage.applyRemoteRecord, which is+// deliberately event-silent (no brainEvents) to prevent cross-peer echo loops+// (#1077). That silence means the per-record bridge listeners below never fire+// for synced-in records, so a record created/edited/deleted on peer A was never+// re-vectorized into peer B's memory index — it stayed stale and searchable+// until a full bulk resync (which itself SKIPPED already-mapped records). The+// sync apply paths now emit a LOCAL-ONLY 'sync:applied' signal (it never feeds+// the sync log, so no echo) carrying the {type, id} of every applied change;+// we re-read each record's canonical state and re-embed or archive accordingly.++const RESYNC_DEBOUNCE_MS = 250;+const pendingResync = new Map(); // bridgeKey → { type, id } (dedups repeated touches)+let resyncTimer = null;++/**+ * Re-vectorize (or archive) a single brain record from its CANONICAL stored+ * state — used after a peer sync applies a change. Reading the store rather+ * than trusting an event payload makes this self-healing and order-independent:+ * whatever the final converged state is (live record, archived, or tombstoned),+ * the memory copy is brought into line.+ * - record present & not archived → upsert + re-embed (syncBrainRecord)+ * - record absent (tombstoned) or archived → archive the mapped memory entry+ * - type not mirrored by the bridge (links/buckets/inbox) → no-op+ */+export async function resyncBrainRecord(brainType, id) {+ if (!id || !TYPE_MAP[brainType]) return;+ // getById returns null for tombstones (deleted records), so a synced-in+ // delete naturally lands in the archive branch.+ const record = brainType === 'journals'+ ? await getJournal(id)+ : await brainStorage.getById(brainType, id);+ if (!record || record.archived) {+ const map = await loadBridgeMap();+ const memoryId = map[bridgeKey(brainType, id)];+ if (memoryId) {+ await memory.updateMemory(memoryId, { status: 'archived' });+ console.log(`🧠🔗 Archived synced-in brain→memory: ${brainType}/${id} → ${memoryId}`);+ }+ return;+ }+ await syncBrainRecord(brainType, record);+}++/**+ * Drain the pending resync queue sequentially. Sequential (not parallel) so a+ * large catch-up sync doesn't fire hundreds of concurrent embedding calls and+ * saturate the embedding backend. Exported for deterministic flushing in tests.+ */+export async function flushPendingResync() {+ resyncTimer = null;+ const batch = [...pendingResync.values()];+ pendingResync.clear();+ for (const { type, id } of batch) {+ await resyncBrainRecord(type, id).catch((err) => {+ console.error(`❌ Brain bridge resync failed for ${type}/${id}: ${err.message}`);+ });+ }+}++/**+ * Queue applied-change records for a debounced resync. Records touching a type+ * the bridge doesn't mirror are dropped here so they never schedule a flush.+ */+export function queueResync(records) {+ if (!Array.isArray(records)) return;+ for (const { type, id } of records) {+ if (!id || !TYPE_MAP[type]) continue;+ pendingResync.set(bridgeKey(type, id), { type, id });+ }+ if (pendingResync.size === 0 || resyncTimer) return;+ resyncTimer = setTimeout(() => {+ flushPendingResync().catch((err) => {+ console.error(`❌ Brain bridge resync flush failed: ${err.message}`);+ });+ }, RESYNC_DEBOUNCE_MS);+ // Don't keep the event loop alive just for a pending resync flush.+ if (typeof resyncTimer.unref === 'function') resyncTimer.unref();+}+// ─── Event Handlers ─────────────────────────────────────────────────────────// Entity stores emit "{type}:upserted" / "{type}:deleted" with the single// affected record. (An earlier version listened to the store-wide@@ -378,6 +469,14 @@ export function initBridge() {});});+ // Peer-synced records (issue #1080) — applyRemoteRecord is event-silent to+ // prevent echo loops, so the per-record listeners above never fire for+ // synced-in changes. The sync apply paths emit this local-only signal with+ // the touched {type, id}s; we re-read each from the store and re-embed or+ // archive. Debounced + sequential so a large catch-up doesn't saturate the+ // embedding backend.+ brainEvents.on('sync:applied', ({ records } = {}) => queueResync(records));+console.log('🧠🔗 Brain→Memory bridge initialized');}diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsnew file mode 100644index 0000000000..4bc3c71485--- /dev/null+++ b/server/services/brainMemoryBridge.test.js@@ -0,0 +1,184 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The bridge memoizes its parsed bridge-map in a module-level variable+// (loadBridgeMap caches), so each test resets the module registry and+// re-imports a fresh copy to stay isolated. Mocks are declared with+// vi.mock (hoisted) so they apply to every fresh import; shared mock fns+// live in module scope so assertions can reach them after re-import.++let bridgeFileContents = null; // null = file absent++const createMemory = vi.fn(async (data) => ({ id: `mem-${data.content?.slice(0, 6) || 'x'}` }));+const updateMemory = vi.fn(async () => ({ id: 'updated' }));+const updateMemoryEmbedding = vi.fn(async () => {});+const generateMemoryEmbedding = vi.fn(async () => [0.1, 0.2, 0.3]);+const getById = vi.fn();+const getAll = vi.fn(async () => []);+const getDigests = vi.fn(async () => []);+const getReviews = vi.fn(async () => []);+const listJournals = vi.fn(async () => ({ records: [] }));+const getJournal = vi.fn();++vi.mock('fs', () => ({ existsSync: vi.fn(() => bridgeFileContents !== null) }));+vi.mock('fs/promises', () => ({+ readFile: vi.fn(async () => bridgeFileContents ?? '{}'),+ writeFile: vi.fn(async (_path, data) => { bridgeFileContents = data; }),+}));+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { brain: '/tmp/test-brain' },+ ensureDir: vi.fn(async () => {}),+}));+vi.mock('./memoryBackend.js', () => ({ createMemory, updateMemory, updateMemoryEmbedding }));+vi.mock('./memoryEmbeddings.js', () => ({ generateMemoryEmbedding }));+vi.mock('./brainStorage.js', () => {+ const { EventEmitter } = require('events');+ return { brainEvents: new EventEmitter(), getById, getAll, getDigests, getReviews };+});+vi.mock('./brainJournal.js', () => ({ listJournals, getJournal }));++// Re-import a fresh bridge module (clears the cached bridge map).+async function loadBridge() {+ vi.resetModules();+ return import('./brainMemoryBridge.js');+}++beforeEach(() => {+ vi.clearAllMocks();+ bridgeFileContents = null;+});++describe('brainMemoryBridge — resyncBrainRecord (issue #1080)', () => {+ it('re-embeds a present, non-archived synced-in record', async () => {+ const bridge = await loadBridge();+ getById.mockResolvedValue({ id: 'p1', name: 'Alice', context: 'met at conf' });++ await bridge.resyncBrainRecord('people', 'p1');++ expect(getById).toHaveBeenCalledWith('people', 'p1');+ expect(createMemory).toHaveBeenCalledTimes(1); // no prior map → new vector+ });++ it('archives the mapped memory when the record is gone (tombstoned)', async () => {+ const bridge = await loadBridge();+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p2')]: 'mem-existing' });+ getById.mockResolvedValue(null); // getById returns null for tombstones++ await bridge.resyncBrainRecord('people', 'p2');++ expect(updateMemory).toHaveBeenCalledWith('mem-existing', { status: 'archived' });+ expect(createMemory).not.toHaveBeenCalled();+ });++ it('archives the mapped memory when the record is archived', async () => {+ const bridge = await loadBridge();+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('projects', 'pr1')]: 'mem-proj' });+ getById.mockResolvedValue({ id: 'pr1', name: 'X', status: 'done', archived: true });++ await bridge.resyncBrainRecord('projects', 'pr1');++ expect(updateMemory).toHaveBeenCalledWith('mem-proj', { status: 'archived' });+ });++ it('reads journals via getJournal, not getById', async () => {+ const bridge = await loadBridge();+ getJournal.mockResolvedValue({ id: '2026-06-09', date: '2026-06-09', content: 'a good day' });++ await bridge.resyncBrainRecord('journals', '2026-06-09');++ expect(getJournal).toHaveBeenCalledWith('2026-06-09');+ expect(getById).not.toHaveBeenCalled();+ expect(createMemory).toHaveBeenCalledTimes(1);+ });++ it('no-ops for a type the bridge does not mirror (links/buckets/inbox)', async () => {+ const bridge = await loadBridge();++ await bridge.resyncBrainRecord('links', 'l1');+ await bridge.resyncBrainRecord('inbox', 'i1');++ expect(getById).not.toHaveBeenCalled();+ expect(createMemory).not.toHaveBeenCalled();+ expect(updateMemory).not.toHaveBeenCalled();+ });++ it('no archive call when a deleted record was never mapped', async () => {+ const bridge = await loadBridge();+ getById.mockResolvedValue(null);++ await bridge.resyncBrainRecord('people', 'never-seen');++ expect(updateMemory).not.toHaveBeenCalled();+ expect(createMemory).not.toHaveBeenCalled();+ });+});++describe('brainMemoryBridge — queueResync debounce + dedup', () => {+ it('dedups repeated touches of the same record and drops unmirrored types', async () => {+ const bridge = await loadBridge();+ getById.mockResolvedValue({ id: 'p1', name: 'Alice' });++ bridge.queueResync([+ { type: 'people', id: 'p1' },+ { type: 'people', id: 'p1' }, // duplicate — collapses+ { type: 'links', id: 'l1' }, // unmirrored — dropped+ ]);+ await bridge.flushPendingResync(); // flush deterministically++ expect(getById).toHaveBeenCalledTimes(1);+ expect(getById).toHaveBeenCalledWith('people', 'p1');+ });++ it('processes the queue sequentially across multiple records', async () => {+ const bridge = await loadBridge();+ getById.mockImplementation(async (_type, id) => ({ id, name: id }));++ bridge.queueResync([+ { type: 'people', id: 'a' },+ { type: 'projects', id: 'b' },+ { type: 'ideas', id: 'c' },+ ]);+ await bridge.flushPendingResync();++ expect(getById).toHaveBeenCalledTimes(3);+ });++ it('ignores a non-array payload without throwing', async () => {+ const bridge = await loadBridge();++ expect(() => bridge.queueResync(undefined)).not.toThrow();+ expect(() => bridge.queueResync(null)).not.toThrow();+ await bridge.flushPendingResync();++ expect(getById).not.toHaveBeenCalled();+ });++ it('re-vectorizes when brainEvents emits sync:applied (end-to-end wiring)', async () => {+ const bridge = await loadBridge();+ const { brainEvents } = await import('./brainStorage.js');+ bridge.initBridge();+ getById.mockResolvedValue({ id: 'p1', name: 'Alice' });++ brainEvents.emit('sync:applied', { records: [{ type: 'people', id: 'p1' }] });+ await bridge.flushPendingResync();++ expect(getById).toHaveBeenCalledWith('people', 'p1');+ expect(createMemory).toHaveBeenCalledTimes(1);+ });+});++describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovery)', () => {+ it('skips already-mapped records by default but re-embeds them with refresh:true', async () => {+ const bridge = await loadBridge();+ getAll.mockImplementation(async (type) => (type === 'people' ? [{ id: 'p1', name: 'Alice' }] : []));+ // p1 already mapped — the pre-#1080 staleness scenario.+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p1')]: 'mem-old' });++ const normal = await bridge.syncAllBrainData();+ expect(normal.skipped).toBeGreaterThanOrEqual(1);+ expect(updateMemory).not.toHaveBeenCalled();++ const refreshed = await bridge.syncAllBrainData({ refresh: true });+ expect(refreshed.synced).toBeGreaterThanOrEqual(1);+ expect(updateMemory).toHaveBeenCalledWith('mem-old', expect.any(Object));+ });+});diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.jsindex b542f52aa8..f87de0413a 100644--- a/server/services/brainReconcile.js+++ b/server/services/brainReconcile.js@@ -30,6 +30,7 @@import { createHash } from 'crypto';import * as brainStorage from './brainStorage.js';+import { brainEvents } from './brainStorage.js';import * as brainSyncLog from './brainSyncLog.js';const { BRAIN_ENTITY_TYPES } = brainStorage;@@ -186,6 +187,15 @@ export async function applyBrainSnapshot(snapshot) {if (relayBatch.length > 0) {await brainSyncLog.appendChanges(relayBatch).catch(err => console.error(`⚠️ Brain reconcile relay append failed (${relayBatch.length} entries): ${err.message}`));+ // Local-only signal so the memory bridge re-vectorizes reconciled records+ // (issue #1080) — same mechanism as brainSync.applyRemoteChanges. Anti-+ // entropy snapshot merges are exactly the case where a record can change+ // without ever flowing through a per-record event, so the bridge would+ // otherwise never learn of the reconciled state. Local embedding only,+ // never re-fed to the sync log (no #1077 echo).+ brainEvents.emit('sync:applied', {+ records: relayBatch.map(({ type, id }) => ({ type, id })),+ });}console.log(`🔄 Brain reconcile applied: ${updated} upserted, ${deleted} deleted, ${skipped} skipped`);diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.jsindex 4516e6cbbc..4f290a2ac1 100644--- a/server/services/brainReconcile.test.js+++ b/server/services/brainReconcile.test.js@@ -1,11 +1,18 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+// Hoisted so the vi.mock factory (also hoisted) can reference it without a TDZ error.+const { brainEvents } = vi.hoisted(() => {+ const { EventEmitter } = require('events');+ return { brainEvents: new EventEmitter() };+});+// brainStorage is the data layer; mock it so the reconcile logic is tested in// isolation (matching the inline-copy / mock style used across sync tests).vi.mock('./brainStorage.js', () => ({BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'],getRawRecords: vi.fn(),applyRemoteRecord: vi.fn(),+ brainEvents,}));vi.mock('./brainSyncLog.js', () => ({appendChanges: vi.fn().mockResolvedValue([]),@@ -145,6 +152,41 @@ describe('applyBrainSnapshot', () => {expect(relayed.map(r => r.id)).toEqual(['x']);});+ it('emits a local-only sync:applied signal for reconciled records (issue #1080)', async () => {+ brainStorage.applyRemoteRecord+ .mockResolvedValueOnce({ applied: true })+ .mockResolvedValueOnce({ applied: false, reason: 'local_newer' });+ const seen = [];+ const listener = (payload) => seen.push(payload);+ brainEvents.on('sync:applied', listener);++ await applyBrainSnapshot({+ records: { links: {+ x: { id: 'x', updatedAt: '2026-01-02T00:00:00.000Z', title: 'X' },+ y: { id: 'y', updatedAt: '2026-01-01T00:00:00.000Z', title: 'Y' },+ } },+ });++ brainEvents.off('sync:applied', listener);+ expect(seen).toHaveLength(1);+ // Only the APPLIED record is signalled (the rejected LWW op is not).+ expect(seen[0].records).toEqual([{ type: 'links', id: 'x' }]);+ });++ it('does NOT emit sync:applied when nothing applies', async () => {+ brainStorage.applyRemoteRecord.mockResolvedValue({ applied: false, reason: 'local_newer' });+ const seen = [];+ const listener = (payload) => seen.push(payload);+ brainEvents.on('sync:applied', listener);++ await applyBrainSnapshot({+ records: { links: { y: { id: 'y', updatedAt: '2020-01-01T00:00:00.000Z', title: 'Y' } } },+ });++ brainEvents.off('sync:applied', listener);+ expect(seen).toHaveLength(0);+ });+it('skips records missing updatedAt (no LWW clock) and unknown types', async () => {brainStorage.applyRemoteRecord.mockResolvedValue({ applied: true });const res = await applyBrainSnapshot({diff --git a/server/services/brainSync.js b/server/services/brainSync.jsindex b0876059ad..1183506051 100644--- a/server/services/brainSync.js+++ b/server/services/brainSync.js@@ -10,6 +10,7 @@*/import * as brainStorage from './brainStorage.js';+import { brainEvents } from './brainStorage.js';import * as brainSyncLog from './brainSyncLog.js';const { BRAIN_ENTITY_TYPES } = brainStorage;@@ -70,6 +71,15 @@ export async function applyRemoteChanges(changes) {if (relayBatch.length > 0) {await brainSyncLog.appendChanges(relayBatch).catch(err => console.error(`⚠️ Sync log batch append failed (${relayBatch.length} entries): ${err.message}`));+ // Local-only signal so the memory bridge re-vectorizes synced-in records+ // (issue #1080). applyRemoteRecord is event-silent to prevent cross-peer+ // echo (#1077); this event drives ONLY local embedding and never feeds the+ // sync log, so it can't amplify. Carries just {type, id} — the bridge+ // re-reads canonical state. Emitted on the relay batch (applied changes+ // only) so a rejected LWW op doesn't trigger a needless re-embed.+ brainEvents.emit('sync:applied', {+ records: relayBatch.map(({ type, id }) => ({ type, id })),+ });}console.log(`🔄 Brain sync applied: ${inserted} inserted, ${updated} updated, ${deleted} deleted, ${skipped} skipped`);diff --git a/server/services/brainSync.test.js b/server/services/brainSync.test.jsindex 6a94de39fc..460f59f335 100644--- a/server/services/brainSync.test.js+++ b/server/services/brainSync.test.js@@ -1,7 +1,14 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+// Hoisted so the vi.mock factory (also hoisted) can reference it without a TDZ error.+const { brainEvents } = vi.hoisted(() => {+ const { EventEmitter } = require('events');+ return { brainEvents: new EventEmitter() };+});+vi.mock('./brainStorage.js', () => ({applyRemoteRecord: vi.fn(),+ brainEvents,BRAIN_ENTITY_TYPES: ['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets', 'journals', 'inbox'],}));@@ -136,6 +143,40 @@ describe('brainSync', () => {expect(result.inserted).toBe(0);});+ it('emits a local-only sync:applied signal carrying applied {type,id}s (issue #1080)', async () => {+ applyRemoteRecord.mockResolvedValue({ applied: true });+ const seen = [];+ const listener = (payload) => seen.push(payload);+ brainEvents.on('sync:applied', listener);++ await applyRemoteChanges([+ { op: 'create', type: 'people', id: 'p1', record: { name: 'A', updatedAt: '2026-01-01T00:00:00.000Z' } },+ { op: 'update', type: 'ideas', id: 'i1', record: { title: 'B', updatedAt: '2026-01-01T00:00:00.000Z' } },+ ]);++ brainEvents.off('sync:applied', listener);+ expect(seen).toHaveLength(1);+ // Carries only {type,id} — the bridge re-reads canonical state itself.+ expect(seen[0].records).toEqual([+ { type: 'people', id: 'p1' },+ { type: 'ideas', id: 'i1' },+ ]);+ });++ it('does NOT emit sync:applied when every change is rejected (no relay batch)', async () => {+ applyRemoteRecord.mockResolvedValue({ applied: false, reason: 'local_newer' });+ const seen = [];+ const listener = (payload) => seen.push(payload);+ brainEvents.on('sync:applied', listener);++ await applyRemoteChanges([+ { op: 'update', type: 'people', id: 'p1', record: { name: 'Old', updatedAt: '2020-01-01T00:00:00.000Z' } },+ ]);++ brainEvents.off('sync:applied', listener);+ expect(seen).toHaveLength(0);+ });+it('handles mixed operations correctly', async () => {applyRemoteRecord.mockResolvedValueOnce({ applied: true }) // create people