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]): address codex+claude review — single-flight flush + refresh reconcile
Adam Eivy697d18c1469a
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsxindex c4d9a8199e..0d0ce93f0a 100644--- a/client/src/components/brain/tabs/BrainGraph.jsx+++ b/client/src/components/brain/tabs/BrainGraph.jsx@@ -221,7 +221,8 @@ export default function BrainGraph() {});setSyncing(false);if (stats) {- toast.success(`Synced ${stats.synced} records (${stats.skipped} skipped)`);+ const archivedNote = stats.archived ? `, ${stats.archived} archived` : '';+ toast.success(`Synced ${stats.synced} records (${stats.skipped} skipped${archivedNote})`);// Reload graph data to pick up new embeddingsconst fresh = await api.getBrainGraph().catch(() => null);if (fresh) setGraphData(fresh);diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 58623e3488..15f002a893 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -973,7 +973,7 @@ router.get('/graph', asyncHandler(async (req, res) => {router.post('/bridge-sync', asyncHandler(async (req, res) => {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`);+ console.log(`🧠🔗 Brain bridge sync complete${refresh ? ' (refresh)' : ''}: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.archived} archived, ${stats.errors} errors`);res.json(stats);}));diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 91eb4aa8f3..f6b4704f36 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -977,6 +977,17 @@ describe('Brain Routes', () => {expect(response.body.synced).toBe(5);expect(response.body.skipped).toBe(2);expect(response.body.errors).toBe(0);+ // No body → refresh defaults false (issue #1080).+ expect(syncAllBrainData).toHaveBeenCalledWith({ refresh: false });+ });++ it('passes refresh:true through for the recovery re-embed path (issue #1080)', async () => {+ syncAllBrainData.mockResolvedValue({ synced: 3, skipped: 0, errors: 0, archived: 1 });++ const response = await request(app).post('/api/brain/bridge-sync').send({ refresh: true });+ expect(response.status).toBe(200);+ expect(response.body.archived).toBe(1);+ expect(syncAllBrainData).toHaveBeenCalledWith({ refresh: true });});it('should return 500 when sync fails', async () => {diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 5ead4fcab6..d7ecaf750c 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -218,11 +218,14 @@ export async function syncBrainRecord(brainType, record) {* 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}>}+ * In refresh mode a reconcile pass also archives memory entries whose brain+ * record was deleted/archived on a peer before this fix (orphaned map keys+ * the live-record walks can't reach) — reported as `archived`.+ * @returns {Promise<{synced:number, skipped:number, errors:number, archived:number}>}*/export async function syncAllBrainData({ dryRun = false, refresh = false } = {}) {const map = await loadBridgeMap();- const stats = { synced: 0, skipped: 0, errors: 0 };+ const stats = { synced: 0, skipped: 0, errors: 0, archived: 0 };// Entity stores (JSON-based)const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories'];@@ -308,6 +311,37 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})}}+ // Refresh-mode reconcile (issue #1080 recovery): the live-record walks above+ // re-embed edited records, but they iterate ONLY live records — getAll /+ // listJournals strip tombstones and archived entities are skipped — so a+ // record DELETED or ARCHIVED on a peer BEFORE this fix shipped leaves an+ // orphaned bridge-map entry whose memory copy stays active and searchable.+ // The going-forward sync:applied path archives those, but it can't reach the+ // pre-fix backlog. Walk the bridge map and archive any mapped entry whose+ // canonical record no longer resolves as live. Only for deletable, bridge-+ // mirrored stores: digests/reviews are append-only (never deleted) and+ // links/buckets/inbox aren't mirrored, so neither can orphan a memory entry.+ if (refresh && !dryRun) {+ const reconcilableTypes = new Set(['people', 'projects', 'ideas', 'admin', 'memories', 'journals']);+ for (const mapKey of Object.keys(map)) {+ const sep = mapKey.indexOf(':');+ if (sep === -1) continue;+ const type = mapKey.slice(0, sep);+ const id = mapKey.slice(sep + 1);+ if (!reconcilableTypes.has(type)) continue;+ const record = type === 'journals'+ ? await getJournal(id)+ : await brainStorage.getById(type, id);+ if (record && !record.archived) continue; // still live — already re-embedded above+ const archived = await archiveMappedMemory(type, id).catch(err => {+ console.error(`❌ Failed to archive stale ${type}/${id}: ${err.message}`);+ stats.errors++;+ return false;+ });+ if (archived) stats.archived++;+ }+ }+return stats;}@@ -325,6 +359,21 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})const RESYNC_DEBOUNCE_MS = 250;const pendingResync = new Map(); // bridgeKey → { type, id } (dedups repeated touches)let resyncTimer = null;+let resyncFlushing = false; // single-flight guard so two flushes can't overlap++/**+ * Archive the memory entry mapped to a brain record (if any). Used when the+ * canonical record is gone (tombstoned), archived, or otherwise should no+ * longer be searchable.+ */+async function archiveMappedMemory(brainType, id) {+ const map = await loadBridgeMap();+ const memoryId = map[bridgeKey(brainType, id)];+ if (!memoryId) return false;+ await memory.updateMemory(memoryId, { status: 'archived' });+ console.log(`🧠🔗 Archived brain→memory: ${brainType}/${id} → ${memoryId}`);+ return true;+}/*** Re-vectorize (or archive) a single brain record from its CANONICAL stored@@ -344,36 +393,49 @@ export async function resyncBrainRecord(brainType, id) {? 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}`);- }+ await archiveMappedMemory(brainType, id);return;}await syncBrainRecord(brainType, record);}/**- * Drain the pending resync queue sequentially. Sequential (not parallel) so a+ * Drain the pending resync queue sequentially. Single-flight + re-draining:+ * only one flush runs at a time (the `resyncFlushing` guard), and it loops+ * until the queue is empty so records enqueued mid-flush are still processed —+ * without a second flush running concurrently. 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.+ * saturate the embedding backend; single-flight also prevents two flushes from+ * both creating a memory for the same not-yet-mapped record (duplicate entries).+ * 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}`);- });+ if (resyncTimer) { clearTimeout(resyncTimer); resyncTimer = null; }+ if (resyncFlushing) return; // an in-flight flush will pick up newly-queued items+ resyncFlushing = true;+ try {+ // The queue only grows during an `await` below; the loop re-checks size at+ // the top of each pass, and the gap between the final size===0 check and+ // clearing `resyncFlushing` contains no await — so nothing can be stranded.+ while (pendingResync.size > 0) {+ 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}`);+ });+ }+ }+ } finally {+ resyncFlushing = false;}}/*** 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.+ * No timer is armed while a flush is in flight — that flush re-drains the queue+ * itself, so a second concurrent flush can never start.*/export function queueResync(records) {if (!Array.isArray(records)) return;@@ -381,7 +443,7 @@ export function queueResync(records) {if (!id || !TYPE_MAP[type]) continue;pendingResync.set(bridgeKey(type, id), { type, id });}- if (pendingResync.size === 0 || resyncTimer) return;+ if (pendingResync.size === 0 || resyncTimer || resyncFlushing) return;resyncTimer = setTimeout(() => {flushPendingResync().catch((err) => {console.error(`❌ Brain bridge resync flush failed: ${err.message}`);diff --git a/server/services/brainMemoryBridge.test.js b/server/services/brainMemoryBridge.test.jsindex 4bc3c71485..04a8224cfe 100644--- a/server/services/brainMemoryBridge.test.js+++ b/server/services/brainMemoryBridge.test.js@@ -152,6 +152,33 @@ describe('brainMemoryBridge — queueResync debounce + dedup', () => {expect(getById).not.toHaveBeenCalled();});+ it('single-flights overlapping flushes so a record is never embedded twice', async () => {+ const bridge = await loadBridge();+ // Slow embed for p1 — while the first flush is awaiting it, a second+ // sync:applied for the SAME not-yet-mapped record arrives. Without the+ // single-flight guard, a second flush would start and createMemory twice.+ let resolveFirst;+ const gate = new Promise((r) => { resolveFirst = r; });+ let calls = 0;+ getById.mockImplementation(async (_type, id) => {+ calls += 1;+ if (id === 'p1' && calls === 1) await gate; // hold the first resync open+ return { id, name: id };+ });++ bridge.queueResync([{ type: 'people', id: 'p1' }]);+ const inFlight = bridge.flushPendingResync(); // begins, awaits the gate on p1+ // Same record re-queued mid-flush + a direct flush attempt (the re-arm path).+ bridge.queueResync([{ type: 'people', id: 'p1' }]);+ const second = bridge.flushPendingResync(); // must early-return (guard), not run concurrently+ resolveFirst();+ await Promise.all([inFlight, second]);++ // p1 was mapped by the first create; the re-drain sees it mapped → update,+ // not a second create. Exactly one memory created for p1.+ expect(createMemory).toHaveBeenCalledTimes(1);+ });+it('re-vectorizes when brainEvents emits sync:applied (end-to-end wiring)', async () => {const bridge = await loadBridge();const { brainEvents } = await import('./brainStorage.js');@@ -181,4 +208,35 @@ describe('brainMemoryBridge — syncAllBrainData refresh mode (issue #1080 recovexpect(refreshed.synced).toBeGreaterThanOrEqual(1);expect(updateMemory).toHaveBeenCalledWith('mem-old', expect.any(Object));});++ it('refresh reconcile archives a mapped entry whose record was deleted on a peer pre-fix', async () => {+ const bridge = await loadBridge();+ // p-gone is mapped but its canonical record no longer resolves (deleted/+ // tombstoned on a peer before the fix) — getAll won't surface it, so only+ // the reconcile pass can retire its stale, still-searchable memory entry.+ getAll.mockResolvedValue([]);+ getById.mockResolvedValue(null);+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p-gone')]: 'mem-orphan' });++ // Default mode does NOT reconcile (no archival).+ await bridge.syncAllBrainData();+ expect(updateMemory).not.toHaveBeenCalled();++ const refreshed = await bridge.syncAllBrainData({ refresh: true });+ expect(updateMemory).toHaveBeenCalledWith('mem-orphan', { status: 'archived' });+ expect(refreshed.archived).toBe(1);+ });++ it('refresh reconcile leaves live mapped records alone (no spurious archive)', async () => {+ const bridge = await loadBridge();+ getAll.mockImplementation(async (type) => (type === 'people' ? [{ id: 'p1', name: 'Alice' }] : []));+ getById.mockResolvedValue({ id: 'p1', name: 'Alice' }); // still live+ bridgeFileContents = JSON.stringify({ [bridge.bridgeKey('people', 'p1')]: 'mem-live' });++ const refreshed = await bridge.syncAllBrainData({ refresh: true });++ // Re-embedded (update via syncBrainRecord), never archived.+ expect(refreshed.archived).toBe(0);+ expect(updateMemory).not.toHaveBeenCalledWith('mem-live', { status: 'archived' });+ });});