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

bound the brain graph to a focus/neighborhood view so it stops crashing at scale

[._.]/ Adam Eivyfef042bfa48b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 24f25bcd97..ec9146b458 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -115,6 +115,10 @@
- **[issue-1422] Re-planning a goal that has scheduled calendar blocks no longer silently strands those calendar events, and a malformed AI plan now fails fast.** Accepting a new AI-generated plan (either *Generate Plan* phases or *Decompose into Tasks*) replaces a goal's milestones wholesale — but if you'd already pushed those milestones onto your calendar as time blocks, the old blocks were left pointing at milestones that no longer existed. Accepting now refuses with a clear message asking you to unschedule first, so your calendar can't drift out of sync with your plan. Separately, both *Generate Plan* and *Decompose into Tasks* now validate the AI's proposal the moment it comes back — a garbled response surfaces a clear error up front instead of looking fine in the review screen and only breaking when you try to accept it.
+- **Brain graph no longer crashes the tab at scale — it loads a bounded view and you navigate by search + focus.** With a large brain (~1500 nodes) the graph tried to render the *entire* graph at once, and a server bug made that catastrophic: shared-tag edges were computed all-pairs per tag with no per-node cap, ballooning to **>1,000,000 edges** that the synchronous force layout and three.js renderer choked on — the tab froze and crashed within ~a minute. The graph is now **bounded by design**: it lands on an **overview** of the most-connected memories, a **search box** jumps to any memory across the whole brain, and **double-clicking a node** (or its "Explore connections" button) re-focuses on that node's neighborhood with a **breadcrumb trail + Back / Overview** to retrace. Each view is capped (≤ ~150 nodes, a few hundred edges) so the renderer stays fast, and the shared-tag edge computation is now capped per node (top-8) at the source, so the million-edge explosion can't recur. New endpoints: `GET /api/brain/graph?focus=&limit=` (overview vs. neighborhood) and `GET /api/brain/graph/search-index`. (`server/services/brainGraph.js`, `server/routes/brain.js`, `client/src/components/brain/tabs/BrainGraph.jsx`, `client/src/lib/brainGraphFocus.js`)
+
+- **Brain graph: embedding refresh now shows it's working, can be targeted, and an isolated node can always be cleared.** (1) The only feedback for the long server-side re-embed was a tiny braille spinner inside the button — easy to miss, so the page looked frozen; it now raises a persistent loading toast that stays up for the duration and swaps in place to the success/error result. (2) Rather than always re-embedding *everything*, the graph now reports **how many records are missing an embedding** and offers a fast **"N missing · Embed"** backfill that processes only those (unmapped records, or records whose memory vector is NULL because generation failed); the heavyweight re-embed-all is now a separate **"Refresh all"** gated behind an inline confirm (it can run for minutes). New endpoint `GET /api/brain/embeddings/status` + `onlyMissing` on `POST /api/brain/bridge-sync`. (3) Selecting a node *isolates* it by dimming the rest — but dimmed nodes still capture clicks, so clicking "empty space" to clear often re-selected a dark node and `onPointerMissed` ignores any orbit drag, leaving the user stuck (the detail panel's × sits below the fold). There's now an always-visible **Clear selection** button on the canvas plus an **Esc** handler. (`server/services/brainMemoryBridge.js`, `server/services/memoryDB.js`, `server/services/memory.js`, `client/src/components/brain/tabs/BrainGraph.jsx`)
+
- **The Chief of Staff 3D avatar no longer slowly zooms itself in until you reload.** The full-bleed background avatar keeps a constant apparent size by moving the camera back as the panel grows (`CoSBackgroundCamera` derives `camera.position.z` from the live-measured canvas height). But a transient *zero / pre-layout / hidden* size reading — which fires when the agent panel collapses and re-expands, when the EventLog mounts on the "working on task" transition, or from tab-occlusion ResizeObserver frames — collapsed the scale factor to its floor and slammed the camera to its closest (most zoomed-in) position, which `OrbitControls` then latched with no guaranteed correction. Over a busy night of state transitions the avatar ended up "zoomed way in," fixable only by a page reload. The camera-distance math is now a pure, unit-tested helper that returns `null` for any degenerate (non-finite or sub-pixel) measurement, so those frames leave the camera at its last good framing instead of yanking it in. (`client/src/components/cos/CoSBackgroundCamera.jsx`)
- **`./update.sh` now tells you where to open PortOS — and the boot banner stops pointing at a dead `:5555`.** When a Tailscale cert is present, the user-facing `:5555` speaks HTTPS only, so a plain `http://localhost:5555` (the URL muscle memory reaches for, and the one you're left guessing after an update) just fails to connect — and `update.sh`/`update.ps1` printed no URL at all, so you'd end up on the Vite dev server at `:5554` by accident. Both update scripts now print the working access URL on completion (via the same `print-access-url.js` banner `setup.sh` already uses), leading with the loopback HTTP mirror `http://localhost:5553` that works with no cert warning. The server's own startup banner is reordered to match — it now leads with the local mirror URL instead of burying it under the remote Tailscale lines — and it no longer advertises a bogus Tailscale hostname (e.g. `https://undefined.<tailnet>.ts.net:5555`, produced when a cert was provisioned while MagicDNS was down) as "trusted." (`update.sh`, `update.ps1`, `server/index.js`)
diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsx
index cbd71ae8a4..656b87f431 100644
--- a/client/src/components/brain/tabs/BrainGraph.jsx
+++ b/client/src/components/brain/tabs/BrainGraph.jsx
@@ -2,11 +2,14 @@ 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, RefreshCw} from 'lucide-react';
+import {AlertTriangle, Zap, RefreshCw, X, ChevronRight, ArrowLeft, Compass} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';
import { buildGraph } from '../../../lib/graphSimulation';
+import { pushFocus, popFocus, currentFocusId } from '../../../lib/brainGraphFocus';
+import EntityCombobox from '../../EntityCombobox';
+import InlineConfirmRow from '../../ui/InlineConfirmRow';
import BrailleSpinner from '../../BrailleSpinner';
const EDGE_COLORS = {
@@ -65,7 +68,7 @@ function GraphEdges({ simEdges, selectedId }) {
);
}
-function GraphScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
+function GraphScene({ graph, selectedId, adjacentIds, onSelect, onFocus, onHover }) {
const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
const selNode = selectedId ? graph.idMap.get(selectedId) : null;
@@ -93,6 +96,7 @@ function GraphScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
scale={radius}
position={[node.x, node.y, node.z]}
onClick={(e) => { e.stopPropagation(); onSelect(node); }}
+ onDoubleClick={(e) => { e.stopPropagation(); onFocus(node); }}
onPointerOver={(e) => { e.stopPropagation(); onHover(node); }}
onPointerOut={() => onHover(null)}
>
@@ -119,13 +123,18 @@ function GraphScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
export default function BrainGraph() {
const [graphData, setGraphData] = useState(null);
const [loading, setLoading] = useState(true);
+ const [subLoading, setSubLoading] = useState(false);
const [selectedNode, setSelectedNode] = useState(null);
const [fullRecord, setFullRecord] = useState(null);
const [hoveredNode, setHoveredNode] = useState(null);
const [tooltipPos, setTooltipPos] = useState({ x: 0, y: 0 });
const [layoutKey, setLayoutKey] = useState(0);
- const [searchQuery, setSearchQuery] = useState('');
const [syncing, setSyncing] = useState(false);
+ const [confirmingRefresh, setConfirmingRefresh] = useState(false);
+ const [searchIndex, setSearchIndex] = useState([]);
+ const [searchValue, setSearchValue] = useState('');
+ const [focusTrail, setFocusTrail] = useState([]);
+ const [embeddingStatus, setEmbeddingStatus] = useState(null);
const [typeFilters, setTypeFilters] = useState(() =>
Object.fromEntries(BRAIN_TYPES.map(t => [t, true]))
);
@@ -133,23 +142,63 @@ export default function BrainGraph() {
const graphRef = useRef(null);
const dragStartRef = useRef(null);
+ const focusId = currentFocusId(focusTrail);
+
+ // Initial load: bounded overview + lightweight search index + embedding gaps.
useEffect(() => {
- api.getBrainGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));
+ let cancelled = false;
+ Promise.all([
+ api.getBrainGraph().catch(() => null),
+ api.getBrainGraphSearchIndex().catch(() => ({ nodes: [] })),
+ api.getEmbeddingsStatus().catch(() => null)
+ ]).then(([graph, index, status]) => {
+ if (cancelled) return;
+ setGraphData(graph);
+ setSearchIndex(index?.nodes || []);
+ setEmbeddingStatus(status);
+ }).finally(() => { if (!cancelled) setLoading(false); });
+ return () => { cancelled = true; };
}, []);
- // Filter nodes based on type toggles and search
+ // Load a bounded view (overview when focusId is null, else that node's
+ // neighborhood) and reconcile the breadcrumb trail.
+ const loadView = useCallback(async (targetFocusId, { trail } = {}) => {
+ setSubLoading(true);
+ const data = await api.getBrainGraph(targetFocusId ? { focus: targetFocusId } : {}).catch(() => null);
+ setSubLoading(false);
+ if (!data || data.notFound) {
+ toast.error('Could not load those connections');
+ return false;
+ }
+ setGraphData(data);
+ if (trail !== undefined) setFocusTrail(trail);
+ setSelectedNode(targetFocusId ? (data.nodes.find(n => n.id === targetFocusId) || null) : null);
+ return true;
+ }, []);
+
+ const focusNode = useCallback(async (node) => {
+ if (!node?.id || node.id === focusId) return;
+ const nextTrail = pushFocus(focusTrail, { id: node.id, label: node.label || node.id });
+ await loadView(node.id, { trail: nextTrail });
+ }, [focusId, focusTrail, loadView]);
+
+ const goBack = useCallback(async () => {
+ const { trail, focusId: prevFocus } = popFocus(focusTrail);
+ await loadView(prevFocus, { trail });
+ }, [focusTrail, loadView]);
+
+ const goToOverview = useCallback(async () => {
+ await loadView(null, { trail: [] });
+ }, [loadView]);
+
+ // Filter the (already bounded) loaded nodes by type toggles.
const filteredData = useMemo(() => {
if (!graphData?.nodes?.length) return null;
- const query = searchQuery.toLowerCase();
- const filteredNodes = graphData.nodes.filter(n => {
- if (!typeFilters[n.brainType]) return false;
- if (query && !n.label.toLowerCase().includes(query) && !n.summary?.toLowerCase().includes(query)) return false;
- return true;
- });
+ const filteredNodes = graphData.nodes.filter(n => typeFilters[n.brainType]);
const nodeIds = new Set(filteredNodes.map(n => n.id));
const filteredEdges = graphData.edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target));
return { nodes: filteredNodes, edges: filteredEdges };
- }, [graphData, typeFilters, searchQuery]);
+ }, [graphData, typeFilters]);
const graph = useMemo(() => {
if (!filteredData?.nodes?.length) return null;
@@ -202,6 +251,17 @@ export default function BrainGraph() {
setHoveredNode(node);
}, []);
+ // Escape always clears selection. Clicking "empty space" is unreliable for
+ // un-isolating: unselected nodes are only dimmed (not removed), so they still
+ // capture clicks, and onPointerMissed ignores any orbit drag — leaving the
+ // user stuck on an isolated node with no obvious way out.
+ useEffect(() => {
+ if (!selectedNode) return;
+ const onKey = (e) => { if (e.key === 'Escape') setSelectedNode(null); };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [selectedNode]);
+
const handlePointerMissed = useCallback((e) => {
const start = dragStartRef.current;
if (!start) return;
@@ -212,21 +272,36 @@ export default function BrainGraph() {
// 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 } = {}) => {
+ // automatically (issue #1080). onlyMissing:true embeds just the records that
+ // lack an embedding (cheap; no confirm). Default sync only embeds new records.
+ const handleSync = async ({ refresh = false, onlyMissing = false } = {}) => {
setSyncing(true);
- // silent:true — this catch owns the error toast, so suppress the helper's
- // own toast to avoid a duplicate (CLAUDE.md: custom catch ⇒ silent).
- const stats = await api.syncBrainData({ refresh }, { silent: true }).catch(err => {
- toast.error(err.message || 'Sync failed');
+ setConfirmingRefresh(false);
+ // The server has no progress stream for this, so a persistent loading toast
+ // is the only honest signal that work is in flight. A fixed id lets the
+ // success/error call swap the same toast in place.
+ const toastId = 'brain-embeddings-sync';
+ toast.loading(
+ refresh
+ ? 'Refreshing embeddings — re-embedding all brain records. This can take a while…'
+ : onlyMissing
+ ? 'Embedding records that are missing embeddings…'
+ : 'Syncing brain data to memory…',
+ { id: toastId }
+ );
+ // silent:true — this catch owns the error toast (CLAUDE.md: custom catch ⇒ silent).
+ const stats = await api.syncBrainData({ refresh, onlyMissing }, { silent: true }).catch(err => {
+ toast.error(err.message || 'Sync failed', { id: toastId });
return null;
});
setSyncing(false);
if (stats) {
const archivedNote = stats.archived ? `, ${stats.archived} archived` : '';
- toast.success(`Synced ${stats.synced} records (${stats.skipped} skipped${archivedNote})`);
- // Reload graph data to pick up new embeddings
- const fresh = await api.getBrainGraph().catch(() => null);
+ toast.success(`Synced ${stats.synced} records (${stats.skipped} skipped${archivedNote})`, { id: toastId });
+ // Refresh the missing-embeddings count and reload the current view to pick
+ // up the new edges.
+ api.getEmbeddingsStatus().then(setEmbeddingStatus).catch(() => {});
+ const fresh = await api.getBrainGraph(focusId ? { focus: focusId } : {}).catch(() => null);
if (fresh) setGraphData(fresh);
}
};
@@ -244,7 +319,7 @@ export default function BrainGraph() {
);
}
- if (!graphData || !graphData.nodes?.length) {
+ if (!graphData?.nodes?.length) {
return (
<div className="text-center py-12 text-gray-500">
No brain entities to graph. Add people, projects, ideas, admin items, or memories to see relationships.
@@ -252,6 +327,8 @@ export default function BrainGraph() {
);
}
+ const missingCount = embeddingStatus?.missing || 0;
+
return (
// Full-bleed tab: own the scroll (the Brain wrapper is overflow-hidden) and
// restore the edge padding the shared wrapper no longer provides (#1177).
@@ -264,7 +341,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({ onlyMissing: true })}
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"
>
@@ -274,10 +351,64 @@ export default function BrainGraph() {
</div>
)}
- {/* Controls bar */}
+ {/* Search — jump to any memory across the whole brain (not just the
+ loaded view) and focus its neighborhood. */}
+ <div className="flex items-center gap-2">
+ <EntityCombobox
+ items={searchIndex.map(n => ({ id: n.id, name: n.label, subtitle: DESTINATIONS[n.brainType]?.label || n.brainType }))}
+ value={searchValue}
+ onChange={setSearchValue}
+ onPick={(item) => { focusNode({ id: item.id, label: item.name }); setSearchValue(''); }}
+ inputId="brain-graph-search"
+ noun="memory"
+ placeholder="Search memories to explore…"
+ className="flex-1 min-w-[200px]"
+ />
+ {missingCount > 0 && (
+ <button
+ onClick={() => handleSync({ onlyMissing: true })}
+ disabled={syncing}
+ title={`${missingCount} of ${embeddingStatus?.total ?? '?'} records have no embedding yet — embed just those (fast)`}
+ className="flex items-center gap-1.5 px-3 py-2 min-h-[36px] text-xs whitespace-nowrap bg-port-warning/15 text-port-warning border border-port-warning/30 rounded-lg hover:bg-port-warning/25 transition-colors disabled:opacity-50"
+ >
+ {syncing ? <BrailleSpinner /> : <Zap size={14} />}
+ {missingCount} missing · Embed
+ </button>
+ )}
+ </div>
+
+ {/* Breadcrumb trail + controls bar */}
<div className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg px-4 py-2 flex-wrap">
+ {/* Breadcrumb */}
+ <div className="flex items-center gap-1 text-xs min-w-0">
+ {focusTrail.length > 0 && (
+ <button
+ onClick={goBack}
+ title="Back"
+ className="flex items-center gap-1 px-2 py-1 text-gray-400 hover:text-white rounded transition-colors"
+ >
+ <ArrowLeft size={13} />
+ </button>
+ )}
+ <button
+ onClick={goToOverview}
+ disabled={focusTrail.length === 0}
+ className={`px-1.5 py-1 rounded transition-colors ${focusTrail.length === 0 ? 'text-white font-medium' : 'text-gray-400 hover:text-white'}`}
+ >
+ Overview
+ </button>
+ {focusTrail.map((entry, i) => (
+ <span key={entry.id} className="flex items-center gap-1 min-w-0">
+ <ChevronRight size={12} className="text-gray-600 shrink-0" />
+ <span className={`px-1 truncate max-w-[140px] ${i === focusTrail.length - 1 ? 'text-white font-medium' : 'text-gray-500'}`}>
+ {entry.label}
+ </span>
+ </span>
+ ))}
+ </div>
+
{/* Type filter checkboxes */}
- <div className="flex items-center gap-3">
+ <div className="flex items-center gap-3 ml-auto">
{BRAIN_TYPES.map(type => {
const dest = DESTINATIONS[type];
return (
@@ -300,20 +431,8 @@ export default function BrainGraph() {
})}
</div>
- {/* Search */}
- <div className="flex-1 min-w-[140px] max-w-xs relative">
- <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Filter nodes..."
- className="w-full bg-port-bg border border-port-border rounded-lg pl-8 pr-3 py-1.5 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
- />
- </div>
-
{/* Stats + re-layout */}
- <span className="text-sm text-gray-400 ml-auto">
+ <span className="text-sm text-gray-400">
{filteredData?.nodes?.length || 0} nodes &middot; {filteredData?.edges?.length || 0} edges
</span>
<button
@@ -323,19 +442,31 @@ 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. */}
+ memory copy may be stale. Confirmed first — it re-embeds every record
+ and can run for many minutes. The cheaper "Embed missing" above is the
+ usual path; this is the heavy reset. */}
<button
- onClick={() => handleSync({ refresh: true })}
- disabled={syncing}
- title="Re-embed all brain records, including ones synced from peers, to refresh stale memory entries"
+ onClick={() => setConfirmingRefresh(true)}
+ disabled={syncing || confirmingRefresh}
+ title="Re-embed ALL brain records, including ones synced from peers. Slow — use 'Embed missing' for the common case."
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
+ Refresh all
</button>
</div>
+ {confirmingRefresh && (
+ <InlineConfirmRow
+ tone="warning"
+ question={`Re-embed all ${embeddingStatus?.total ?? ''} brain records? This can take several minutes.`}
+ confirmText="Refresh all"
+ cancelText="Cancel"
+ onConfirm={() => handleSync({ refresh: true })}
+ onCancel={() => setConfirmingRefresh(false)}
+ />
+ )}
+
{/* 3D Canvas */}
<div
className="relative bg-port-card border border-port-border rounded-lg overflow-hidden"
@@ -356,17 +487,39 @@ export default function BrainGraph() {
selectedId={selectedNode?.id}
adjacentIds={adjacentIds}
onSelect={handleSelect}
+ onFocus={focusNode}
onHover={handleHover}
/>
</Canvas>
)}
- {!graph && filteredData?.nodes?.length === 0 && (
+ {!graph && (
<div className="flex items-center justify-center h-full text-gray-500 text-sm">
No nodes match the current filters.
</div>
)}
+ {/* Loading overlay while switching focus */}
+ {subLoading && (
+ <div className="absolute inset-0 flex items-center justify-center bg-port-bg/60 z-20">
+ <BrailleSpinner text="Loading connections" />
+ </div>
+ )}
+
+ {/* Always-reachable un-isolate control. Dimmed nodes still capture
+ clicks, so clicking "empty space" can't be relied on to clear the
+ selection — give the user an unmissable exit (also bound to Esc). */}
+ {selectedNode && (
+ <button
+ onClick={() => setSelectedNode(null)}
+ title="Clear selection (Esc)"
+ className="absolute top-3 right-3 z-10 flex items-center gap-1.5 px-3 py-1.5 text-xs bg-port-bg/90 border border-port-border text-gray-300 hover:text-white rounded-lg transition-colors"
+ >
+ <X size={14} />
+ Clear selection
+ </button>
+ )}
+
{/* Legend */}
<div className="absolute bottom-3 left-3 bg-port-bg/90 border border-port-border rounded-lg p-3 text-xs space-y-1.5 pointer-events-none">
{BRAIN_TYPES.map(t => (
@@ -409,6 +562,7 @@ export default function BrainGraph() {
{hoveredNode.summary && (
<p className="text-[10px] text-gray-400 mt-0.5 line-clamp-2">{hoveredNode.summary}</p>
)}
+ <p className="text-[10px] text-gray-600 mt-1">Double-click to explore connections</p>
</div>
)}
</div>
@@ -453,12 +607,24 @@ export default function BrainGraph() {
<p className="text-sm text-gray-300">{selectedNode.summary}</p>
)}
</div>
- <button
- onClick={() => setSelectedNode(null)}
- className="text-gray-500 hover:text-white transition-colors p-1 shrink-0"
- >
- &times;
- </button>
+ <div className="flex flex-col items-end gap-2 shrink-0">
+ <button
+ onClick={() => setSelectedNode(null)}
+ title="Clear selection (Esc)"
+ className="text-gray-500 hover:text-white transition-colors p-1"
+ >
+ &times;
+ </button>
+ {selectedNode.id !== focusId && (
+ <button
+ onClick={() => focusNode(selectedNode)}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs bg-port-accent/20 text-port-accent border border-port-accent/30 rounded-lg hover:bg-port-accent/30 transition-colors whitespace-nowrap"
+ >
+ <Compass size={13} />
+ Explore connections
+ </button>
+ )}
+ </div>
</div>
{connectedNodes.length > 0 && (
<div>
@@ -471,6 +637,8 @@ export default function BrainGraph() {
const node = graphRef.current?.idMap.get(cn.id);
if (node) setSelectedNode(node);
}}
+ onDoubleClick={() => focusNode(cn)}
+ title="Click to select · double-click to explore its connections"
className="w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-port-border/50 transition-colors"
>
<span className="inline-block w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: BRAIN_TYPE_HEX[cn.brainType] }} />
diff --git a/client/src/components/ui/InlineConfirmRow.jsx b/client/src/components/ui/InlineConfirmRow.jsx
index 46e5ad3ccb..d72fe98749 100644
--- a/client/src/components/ui/InlineConfirmRow.jsx
+++ b/client/src/components/ui/InlineConfirmRow.jsx
@@ -5,13 +5,17 @@
//
// Tones pre-compose full Tailwind class names — the JIT scans for complete
// tokens, so `bg-port-${tone}/10` would NOT generate the utility. Spell it out.
-// Only `error` ships today (every confirm row is destructive); add a map entry
-// when a non-destructive tone is actually needed.
+// `error` for destructive confirms; `warning` for expensive-but-safe confirms
+// (e.g. a long-running re-embed) where the action isn't destructive.
const TONES = {
error: {
wrapper: 'bg-port-error/10 border-port-error/30',
confirm: 'bg-port-error text-white hover:bg-port-error/80',
},
+ warning: {
+ wrapper: 'bg-port-warning/10 border-port-warning/30',
+ confirm: 'bg-port-warning text-black hover:bg-port-warning/80',
+ },
};
// Layout variants share the same tone + button styling and differ only in the
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5542f6d622..ec275ccfc8 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -58,6 +58,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
+| `brainGraphFocus.js` | Pure focus-trail (breadcrumb) transitions for BrainGraph re-focus navigation. |
| `graphSimulation.js` | 3D force simulation parameters for BrainGraph / CyberCity. |
## Generic UI / collection utilities
diff --git a/client/src/lib/brainGraphFocus.js b/client/src/lib/brainGraphFocus.js
new file mode 100644
index 0000000000..9d746dbe7e
--- /dev/null
+++ b/client/src/lib/brainGraphFocus.js
@@ -0,0 +1,33 @@
+// Pure focus-trail transitions for the Brain Graph's re-focus navigation.
+// The trail is the breadcrumb path from the overview to the current focus:
+// [] = overview, and the last entry is always the node currently focused.
+// Kept side-effect-free so it can be unit-tested without React/three.
+
+/**
+ * Push a node onto the trail when focusing it. No-op (returns the same trail)
+ * when it's already the current focus, so re-clicking the focused node doesn't
+ * stack duplicates.
+ * @param {{id:string,label:string}[]} trail
+ * @param {{id:string,label?:string}} node
+ */
+export function pushFocus(trail, node) {
+ if (!node?.id) return trail;
+ if (trail.length && trail[trail.length - 1].id === node.id) return trail;
+ return [...trail, { id: node.id, label: node.label || node.id }];
+}
+
+/**
+ * Pop the current focus. Returns the trimmed trail and the focusId to load next
+ * (the new last entry, or null for the overview).
+ * @param {{id:string,label:string}[]} trail
+ * @returns {{ trail: {id:string,label:string}[], focusId: string|null }}
+ */
+export function popFocus(trail) {
+ const next = trail.slice(0, -1);
+ return { trail: next, focusId: next.length ? next[next.length - 1].id : null };
+}
+
+/** The currently-focused node id, or null when showing the overview. */
+export function currentFocusId(trail) {
+ return trail.length ? trail[trail.length - 1].id : null;
+}
diff --git a/client/src/lib/brainGraphFocus.test.js b/client/src/lib/brainGraphFocus.test.js
new file mode 100644
index 0000000000..b83bc81ea6
--- /dev/null
+++ b/client/src/lib/brainGraphFocus.test.js
@@ -0,0 +1,56 @@
+import { describe, it, expect } from 'vitest';
+import { pushFocus, popFocus, currentFocusId } from './brainGraphFocus.js';
+
+describe('pushFocus', () => {
+ it('appends a node to an empty trail', () => {
+ expect(pushFocus([], { id: 'a', label: 'A' })).toEqual([{ id: 'a', label: 'A' }]);
+ });
+
+ it('appends to a non-empty trail', () => {
+ const trail = [{ id: 'a', label: 'A' }];
+ expect(pushFocus(trail, { id: 'b', label: 'B' })).toEqual([
+ { id: 'a', label: 'A' },
+ { id: 'b', label: 'B' }
+ ]);
+ });
+
+ it('is a no-op when re-focusing the current node (no duplicate)', () => {
+ const trail = [{ id: 'a', label: 'A' }];
+ expect(pushFocus(trail, { id: 'a', label: 'A' })).toBe(trail);
+ });
+
+ it('falls back to id when label is missing', () => {
+ expect(pushFocus([], { id: 'x' })).toEqual([{ id: 'x', label: 'x' }]);
+ });
+
+ it('ignores a node with no id', () => {
+ const trail = [{ id: 'a', label: 'A' }];
+ expect(pushFocus(trail, {})).toBe(trail);
+ });
+});
+
+describe('popFocus', () => {
+ it('pops to the previous focus', () => {
+ const trail = [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }];
+ expect(popFocus(trail)).toEqual({ trail: [{ id: 'a', label: 'A' }], focusId: 'a' });
+ });
+
+ it('pops the last entry back to the overview (null focus)', () => {
+ const trail = [{ id: 'a', label: 'A' }];
+ expect(popFocus(trail)).toEqual({ trail: [], focusId: null });
+ });
+
+ it('handles an already-empty trail', () => {
+ expect(popFocus([])).toEqual({ trail: [], focusId: null });
+ });
+});
+
+describe('currentFocusId', () => {
+ it('is null for the overview', () => {
+ expect(currentFocusId([])).toBeNull();
+ });
+
+ it('is the last trail entry id when focused', () => {
+ expect(currentFocusId([{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }])).toBe('b');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c12d70c4c2..afda301779 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -32,6 +32,7 @@ export * from './videoTilingOptions.js';
export * from './wrImageDefaults.js';
// === Graph & sim ===
+export * from './brainGraphFocus.js';
export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 79013539e5..f6cf423365 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -207,16 +207,30 @@ export const reorderBrainBuckets = (ids) => request('/brain/buckets/reorder', {
body: JSON.stringify({ ids })
});
-// Brain - Graph
-export const getBrainGraph = () => request('/brain/graph');
+// Brain - Graph. Bounded by design: no `focus` returns an overview of the
+// most-connected nodes; a `focus` returns that node's neighborhood. The full
+// graph is never returned (it crashes the browser at scale).
+export const getBrainGraph = ({ focus, limit } = {}) => {
+ const params = new URLSearchParams();
+ if (focus) params.set('focus', focus);
+ if (limit) params.set('limit', limit);
+ const qs = params.toString();
+ return request(`/brain/graph${qs ? `?${qs}` : ''}`);
+};
+// Lightweight {id,label,brainType} list of every node, for the search box.
+export const getBrainGraphSearchIndex = () => request('/brain/graph/search-index');
+// Count of active records missing an embedding (powers "Embed missing").
+export const getEmbeddingsStatus = () => request('/brain/embeddings/status');
// 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).
+// onlyMissing:true is the cheap targeted backfill — embeds only records lacking
+// an embedding, skipping everything healthy.
// `options` (e.g. { silent: true }) passes through to the request helper so a
// caller with its own error toast doesn't get a duplicate from the helper.
-export const syncBrainData = ({ refresh = false } = {}, options = {}) =>
- request('/brain/bridge-sync', { method: 'POST', body: JSON.stringify({ refresh }), ...options });
+export const syncBrainData = ({ refresh = false, onlyMissing = false } = {}, options = {}) =>
+ request('/brain/bridge-sync', { method: 'POST', body: JSON.stringify({ refresh, onlyMissing }), ...options });
// Brain - Daily Log
export const listDailyLogs = (options = {}) => {
diff --git a/docs/plans/2026-06-18-brain-graph-bounded-focus-navigation.md b/docs/plans/2026-06-18-brain-graph-bounded-focus-navigation.md
new file mode 100644
index 0000000000..27d797aca6
--- /dev/null
+++ b/docs/plans/2026-06-18-brain-graph-bounded-focus-navigation.md
@@ -0,0 +1,149 @@
+# Brain Graph: confirm refresh-embeddings + bounded focus/navigation rendering
+
+## Context
+
+The Brain → Graph tab (`client/src/components/brain/tabs/BrainGraph.jsx`) crashes the
+browser tab within ~1 minute at the user's scale: **1505 nodes · 1,090,055 edges**.
+
+Two root causes, plus a UX gap:
+
+1. **Edge explosion (server bug).** `server/services/brainGraph.js:89-117` computes
+ `shared_tag` edges all-pairs within each tag bucket at a permissive Jaccard ≥ 0.3
+ with **no per-node cap**. Semantic edges are already capped (top-3/node ≥ 0.8 in
+ `memoryDB.js:792-805`) and linked edges are tiny — so essentially all ~1.08M edges
+ are `shared_tag` noise.
+2. **Synchronous O(N²) force layout + full-graph render.** `buildGraph()`
+ (`client/src/lib/graphSimulation.js`) runs the force sim synchronously on the main
+ thread over every node and edge, and `BrainGraph.jsx` renders one `<mesh>` per node +
+ a 1M-segment `<lineSegments>`. The endpoint (`GET /api/brain/graph`) has no
+ filtering/pagination and dumps the entire graph.
+3. **No confirmation** on the expensive **Refresh embeddings** button, which re-embeds
+ every record (tens of minutes at this scale).
+
+**Goal:** never load or render the whole graph. Land on a bounded **overview** of the
+most-connected memories, **search** to jump to any memory, and **click a node to
+re-focus** on its neighborhood (replacing the view, with a back trail). Bound the loaded
+set so the existing force sim/three.js renderer stays fast. Add an inline confirmation to
+the refresh button.
+
+UX decisions (confirmed with user): default view = **overview of top ~100 memories**;
+node click = **re-focus (replace view)** with a back/history trail.
+
+## Part 1 — Refresh-embeddings confirmation (small)
+
+In `BrainGraph.jsx`, gate `handleSync({ refresh: true })` behind an inline confirm.
+
+- Reuse **`client/src/components/ui/InlineConfirmRow.jsx`** (matches the user's stated
+ preference for inline confirm rows over the two-click-arm pattern — see memory
+ `feedback_confirmation_ux`). Do **not** add a `window.confirm`.
+- New state `confirmingRefresh`. The "Refresh embeddings" button sets it true; render an
+ `InlineConfirmRow` in the controls area: question ≈ *"Re-embed all N brain records?
+ This can take several minutes."* (N from `graphData`/search-index count), tone
+ `warning`, confirm "Refresh", cancel "Cancel". `onConfirm` → existing
+ `handleSync({ refresh: true })`; `onCancel` clears the flag.
+- Keep the persistent `toast.loading` already added. The plain **Sync Now** (new-records)
+ path stays un-gated — it's cheap and only appears when there are no embeddings.
+
+## Part 2 — Bounded focus/neighborhood graph (core)
+
+### Server
+
+**`server/services/brainGraph.js`** — refactor `getBrainGraphData()` into bounded modes.
+Extract the node-loading + tag-index build into a shared internal helper (cheap: iterates
+records, no edge enumeration). Then:
+
+- `getBrainGraphSearchIndex()` → `{ nodes: [{ id, label, brainType }] }` for all
+ non-archived records, **no edges**. Powers the search box. Lightweight (~1505 small
+ objects).
+- `getBrainGraphOverview({ limit = 100 })` → rank all nodes by a **cheap connectivity
+ proxy** (linked-degree from `memory_links` + semantic top-K degree + co-tag degree
+ derived from the tag-index bucket sizes — none of which enumerate all pairs), take the
+ top `limit`, then compute the **induced subgraph** (all three edge types restricted to
+ that node set — O(limit²) ≈ 10K max). Return `{ nodes, edges, hasEmbeddings, mode:'overview' }`.
+- `getBrainGraphNeighborhood({ focusId, limit = 80 })` → collect the focus node's direct
+ neighbors: linked (memory_links for the focus's bridged memory id), semantic
+ (single-node pgvector KNN — reuse the `<=>` LATERAL pattern from `memoryDB.js:792`
+ scoped to one `a.id`; add a `getNeighbors(memoryId, k)` to `memoryDB.js` /
+ `memoryBackend.js` near the existing `getRelated`), and shared_tag (tag-index entries
+ sharing ≥ 0.3 with focus, top-K by weight). Cap to `limit`, then return focus + neighbors
+ with the **induced edges among that set** so neighbor↔neighbor links show.
+ `{ nodes, edges, hasEmbeddings, focusId, mode:'neighborhood' }`.
+- **Per-node `shared_tag` cap (fixes the explosion at the source):** wherever shared_tag
+ edges are produced, keep only each node's top-K (≈ 8) strongest by weight. Apply in the
+ induced-subgraph builder so even a worst-case bucket can't reproduce the blow-up.
+
+**`server/routes/brain.js`** (currently `GET /graph` at ~925) — replace the single dump:
+- `GET /api/brain/graph` → `?focus=<id>` present ⇒ neighborhood; absent ⇒ overview.
+ Optional `?limit=`. Validate query params with a Zod schema in
+ `server/lib/validation.js` (coerced ints, bounded; `focus` optional string).
+- `GET /api/brain/graph/search-index` → search index.
+- Confirm `BrainGraph.jsx` is the only consumer of the old payload before changing shape
+ (the explore found `getBrainGraph` used only there); update accordingly.
+
+No on-disk format change → **no migration**. This is a read-only endpoint, so no
+`schemaVersions` gate is needed; other installs simply get the improved endpoint
+(distribution-model safe).
+
+### Client
+
+**`client/src/services/apiBrain.js`** (and re-export rules per the catalog):
+- `getBrainGraph({ focus, limit } = {})` → builds `URLSearchParams` (follow the
+ `getBrainProjects`/`getBrainLinks` param pattern in the same file).
+- `getBrainGraphSearchIndex()` → `/brain/graph/search-index`.
+
+**`client/src/components/brain/tabs/BrainGraph.jsx`** — introduce focus state:
+- State: `focusId` (null = overview), `focusTrail` (array of `{ id, label }` for back
+ nav), `searchIndex`. On mount: fetch search index + overview in parallel.
+- **Search box:** reuse **`client/src/components/EntityCombobox.jsx`** over `searchIndex`
+ (map to `{ id, name: label, subtitle: brainType }`); `onPick` → `focusNode(id)`.
+- **Re-focus action** (keeps the cheap in-view selection separate from the expensive
+ refetch): single click still **selects** a node (detail panel + neighbor highlight
+ within the loaded set — current behavior, including the Esc / "Clear selection" exit
+ just added). Add an explicit **"Explore connections"** button in the detail panel and a
+ **double-click** handler that call `focusNode(node.id)`: push the current focus onto
+ `focusTrail`, fetch that node's neighborhood, replace the view, and select the new
+ focus. Connection rows in the detail panel that point outside the loaded set also
+ trigger `focusNode`.
+- **Trail / reset UI:** a compact breadcrumb ("Overview › A › B") with a Back control and
+ a "Back to overview" reset (clears `focusId`, reloads overview). Place near the controls
+ bar or as a canvas overlay next to the existing "Clear selection" button.
+- Type filters + label search keep filtering **within the loaded subgraph** (current
+ client-side `filteredData` logic is retained, now operating on ≤ ~150 nodes).
+- Because every mode is bounded (≤ ~150 nodes, few hundred edges), the existing
+ synchronous `buildGraph` force sim and per-node-mesh rendering are fine — **no web
+ worker or instancedMesh rewrite needed** (note both as deferred options if counts ever
+ grow).
+
+### Optional follow-up (defer, capture in PLAN.md if skipped)
+- Web-worker / async force sim and `<instancedMesh>` node rendering — only if a single
+ neighborhood ever needs to exceed a few hundred nodes.
+- Short-lived server cache for the overview ranking if recompute-per-request shows latency.
+- Multi-hop (`depth=2`) neighborhood expansion.
+
+## Critical files
+
+- `server/services/brainGraph.js` — modes + per-node shared_tag cap (core change)
+- `server/services/memoryDB.js` / `server/services/memoryBackend.js` — add single-node
+ `getNeighbors(memoryId, k)` (reuse the existing `<=>` KNN query)
+- `server/routes/brain.js` — `GET /graph` (focus/overview) + `/graph/search-index`
+- `server/lib/validation.js` — Zod query schema for the graph route
+- `client/src/services/apiBrain.js` — `getBrainGraph(params)` + `getBrainGraphSearchIndex`
+- `client/src/components/brain/tabs/BrainGraph.jsx` — focus state, trail, search, confirm
+- Reused as-is: `client/src/components/ui/InlineConfirmRow.jsx`,
+ `client/src/components/EntityCombobox.jsx`
+
+## Verification
+
+- **Server tests:** add/extend `server/services/brainGraph.test.js` — mock `brainStorage`
+ + `memoryBackend`; assert overview returns ≤ limit nodes with an induced edge set,
+ neighborhood returns focus + capped neighbors, and the per-node shared_tag cap holds
+ (feed a pathological all-same-tag fixture → bounded edge count, not C(N,2)). Run
+ `cd server && npm test`.
+- **Client:** extract the focus-trail transition into a small pure helper and unit-test it
+ (`cd client && npm test`); BrainGraph itself has no harness (R3F canvas).
+- **Manual (`npm run dev`, Brain → Graph):** overview loads fast with ~100 nodes (no
+ freeze); search jumps to a memory; double-click / "Explore connections" re-centers and
+ the trail + Back work; Esc / "Clear selection" still un-isolates; "Refresh embeddings"
+ shows the inline confirm, then the persistent loading toast on confirm. Confirm the tab
+ no longer crashes at full scale.
+- Run `/simplify` on the diff before committing (per project workflow).
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index afb12f5910..65be89e359 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -485,9 +485,20 @@ export const brainSyncPushSchema = z.object({
// 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.
+// #1080). `onlyMissing` is the cheap targeted backfill: embed just the records
+// that lack an embedding (unmapped, or mapped to a NULL-embedding memory) and
+// skip everything healthy. Both optional + default-false so the existing
+// no-body call is unchanged.
export const brainBridgeSyncSchema = z.object({
- refresh: z.boolean().optional().default(false)
+ refresh: z.boolean().optional().default(false),
+ onlyMissing: z.boolean().optional().default(false)
+});
+
+// Brain graph query (GET /api/brain/graph?focus=<id>&limit=<n>). No `focus`
+// returns the bounded overview; a `focus` returns that node's neighborhood.
+export const brainGraphQuerySchema = z.object({
+ focus: z.string().min(1).optional(),
+ limit: z.coerce.number().int().min(1).max(250).optional()
});
// Daily log settings schema (PUT /api/brain/daily-log/settings body).
diff --git a/server/routes/brain.js b/server/routes/brain.js
index 00e0741755..7268ef59c5 100644
--- a/server/routes/brain.js
+++ b/server/routes/brain.js
@@ -38,11 +38,16 @@ import {
brainSyncQuerySchema,
brainSyncPushSchema,
brainBridgeSyncSchema,
+ brainGraphQuerySchema,
dailyLogSettingsSchema
} from '../lib/brainValidation.js';
import * as githubCloner from '../services/githubCloner.js';
-import { getBrainGraphData } from '../services/brainGraph.js';
-import { syncAllBrainData } from '../services/brainMemoryBridge.js';
+import {
+ getBrainGraphSearchIndex,
+ getBrainGraphOverview,
+ getBrainGraphNeighborhood
+} from '../services/brainGraph.js';
+import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';
import * as brainSyncLog from '../services/brainSyncLog.js';
import * as brainSync from '../services/brainSync.js';
import * as brainReconcile from '../services/brainReconcile.js';
@@ -919,11 +924,26 @@ router.delete('/buckets/:id', asyncHandler(async (req, res) => {
// =============================================================================
/**
- * GET /api/brain/graph
- * Get brain entity graph data for visualization
+ * GET /api/brain/graph/search-index
+ * Lightweight {id,label,brainType} list of every node, for the client search
+ * box. No edges — cheap even at thousands of nodes.
+ */
+router.get('/graph/search-index', asyncHandler(async (_req, res) => {
+ const data = await getBrainGraphSearchIndex();
+ res.json(data);
+}));
+
+/**
+ * GET /api/brain/graph?focus=<id>&limit=<n>
+ * Bounded graph data for visualization. No `focus` → an overview of the most-
+ * connected nodes; a `focus` → that node's neighborhood. Never the full graph
+ * (which crashes the browser at scale).
*/
router.get('/graph', asyncHandler(async (req, res) => {
- const data = await getBrainGraphData();
+ const { focus, limit } = validateRequest(brainGraphQuerySchema, req.query);
+ const data = focus
+ ? await getBrainGraphNeighborhood({ focusId: focus, limit })
+ : await getBrainGraphOverview({ limit });
res.json(data);
}));
@@ -940,12 +960,23 @@ router.get('/graph', asyncHandler(async (req, res) => {
* (Renamed from /sync to avoid conflict with federation sync)
*/
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.archived} archived, ${stats.errors} errors`);
+ const { refresh, onlyMissing } = validateRequest(brainBridgeSyncSchema, req.body ?? {});
+ const stats = await syncAllBrainData({ refresh, onlyMissing });
+ const mode = onlyMissing ? ' (missing-only)' : refresh ? ' (refresh)' : '';
+ console.log(`🧠🔗 Brain bridge sync complete${mode}: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.archived} archived, ${stats.errors} errors`);
res.json(stats);
}));
+/**
+ * GET /api/brain/embeddings/status
+ * How many active brain records lack an embedding — powers the
+ * "N missing · Embed missing" affordance on the graph.
+ */
+router.get('/embeddings/status', asyncHandler(async (_req, res) => {
+ const coverage = await getEmbeddingCoverage();
+ res.json(coverage);
+}));
+
/**
* GET /api/brain/sync?since={seq}&limit=100
* Get brain changes since a given sequence number (for peers to pull)
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index d1a3aab521..5da340df4b 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -74,12 +74,15 @@ vi.mock('../services/brain.js', () => ({
// Mock the brain graph service
vi.mock('../services/brainGraph.js', () => ({
- getBrainGraphData: vi.fn()
+ getBrainGraphSearchIndex: vi.fn(),
+ getBrainGraphOverview: vi.fn(),
+ getBrainGraphNeighborhood: vi.fn()
}));
// Mock the brain memory bridge
vi.mock('../services/brainMemoryBridge.js', () => ({
- syncAllBrainData: vi.fn()
+ syncAllBrainData: vi.fn(),
+ getEmbeddingCoverage: vi.fn()
}));
// Mock the brain sync log service
@@ -125,8 +128,8 @@ vi.mock('../services/brainJournal.js', () => ({
// Import mocked modules
import * as brainService from '../services/brain.js';
-import { getBrainGraphData } from '../services/brainGraph.js';
-import { syncAllBrainData } from '../services/brainMemoryBridge.js';
+import { getBrainGraphSearchIndex, getBrainGraphOverview, getBrainGraphNeighborhood } from '../services/brainGraph.js';
+import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';
import { getChangesSince } from '../services/brainSyncLog.js';
import { getBrainChecksum, getBrainSnapshot } from '../services/brainReconcile.js';
import { applyRemoteChanges } from '../services/brainSync.js';
@@ -947,24 +950,53 @@ describe('Brain Routes', () => {
// ===========================================================================
describe('GET /api/brain/graph', () => {
- it('should return graph data', async () => {
- const mockGraph = { nodes: [{ id: '1', label: 'Test' }], edges: [], hasEmbeddings: false };
- getBrainGraphData.mockResolvedValue(mockGraph);
+ it('returns the bounded overview when no focus is given', async () => {
+ const mockGraph = { nodes: [{ id: '1', label: 'Test' }], edges: [], hasEmbeddings: false, mode: 'overview' };
+ getBrainGraphOverview.mockResolvedValue(mockGraph);
const response = await request(app).get('/api/brain/graph');
expect(response.status).toBe(200);
expect(response.body.nodes).toHaveLength(1);
expect(response.body.hasEmbeddings).toBe(false);
+ expect(getBrainGraphOverview).toHaveBeenCalled();
+ expect(getBrainGraphNeighborhood).not.toHaveBeenCalled();
+ });
+
+ it('returns a node neighborhood when a focus is given', async () => {
+ getBrainGraphNeighborhood.mockResolvedValue({ nodes: [{ id: 'f' }], edges: [], hasEmbeddings: true, mode: 'neighborhood', focusId: 'f' });
+
+ const response = await request(app).get('/api/brain/graph?focus=f&limit=20');
+ expect(response.status).toBe(200);
+ expect(response.body.mode).toBe('neighborhood');
+ expect(getBrainGraphNeighborhood).toHaveBeenCalledWith({ focusId: 'f', limit: 20 });
});
it('should return 500 when service throws', async () => {
- getBrainGraphData.mockRejectedValue(new Error('Graph build failed'));
+ getBrainGraphOverview.mockRejectedValue(new Error('Graph build failed'));
const response = await request(app).get('/api/brain/graph');
expect(response.status).toBe(500);
});
});
+ describe('GET /api/brain/graph/search-index', () => {
+ it('returns the lightweight node index', async () => {
+ getBrainGraphSearchIndex.mockResolvedValue({ nodes: [{ id: '1', label: 'A', brainType: 'memories' }] });
+ const response = await request(app).get('/api/brain/graph/search-index');
+ expect(response.status).toBe(200);
+ expect(response.body.nodes).toHaveLength(1);
+ });
+ });
+
+ describe('GET /api/brain/embeddings/status', () => {
+ it('returns embedding coverage', async () => {
+ getEmbeddingCoverage.mockResolvedValue({ total: 10, missing: 3 });
+ const response = await request(app).get('/api/brain/embeddings/status');
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ total: 10, missing: 3 });
+ });
+ });
+
// ===========================================================================
// BRIDGE SYNC (renamed from /sync)
// ===========================================================================
@@ -979,8 +1011,8 @@ 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 });
+ // No body → refresh + onlyMissing default false (issue #1080).
+ expect(syncAllBrainData).toHaveBeenCalledWith({ refresh: false, onlyMissing: false });
});
it('passes refresh:true through for the recovery re-embed path (issue #1080)', async () => {
@@ -989,7 +1021,16 @@ describe('Brain Routes', () => {
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 });
+ expect(syncAllBrainData).toHaveBeenCalledWith({ refresh: true, onlyMissing: false });
+ });
+
+ it('passes onlyMissing:true through for the targeted backfill path', async () => {
+ syncAllBrainData.mockResolvedValue({ synced: 2, skipped: 8, errors: 0, archived: 0 });
+
+ const response = await request(app).post('/api/brain/bridge-sync').send({ onlyMissing: true });
+ expect(response.status).toBe(200);
+ expect(response.body.synced).toBe(2);
+ expect(syncAllBrainData).toHaveBeenCalledWith({ refresh: false, onlyMissing: true });
});
it('should return 500 when sync fails', async () => {
diff --git a/server/services/brainGraph.js b/server/services/brainGraph.js
index fe7eaaed67..60679298fa 100644
--- a/server/services/brainGraph.js
+++ b/server/services/brainGraph.js
@@ -5,6 +5,14 @@
* - Semantic similarity (via CoS memory embeddings through the bridge)
* - Shared tags (Jaccard similarity)
* - Explicit CoS memory links (through the bridge)
+ *
+ * Bounded by design: the full graph at scale (~1500 nodes, >1M shared-tag
+ * pairs) crashes the browser, so this service never returns the whole graph.
+ * Callers either fetch the lightweight search index (`getBrainGraphSearchIndex`),
+ * a bounded overview of the most-connected nodes (`getBrainGraphOverview`), or
+ * one node's neighborhood (`getBrainGraphNeighborhood`). Shared-tag edges are
+ * only ever computed *among a bounded node set* and capped per node, so the
+ * O(n²) tag explosion can't happen.
*/
import * as brainStorage from './brainStorage.js';
@@ -13,6 +21,14 @@ import { loadBridgeMap, bridgeKey } from './brainMemoryBridge.js';
const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];
+// Edges shown per node are capped so a densely-tagged hub can't reintroduce the
+// combinatorial blow-up inside a bounded view.
+const SHARED_TAG_CAP_PER_NODE = 8;
+const SHARED_TAG_MIN_JACCARD = 0.3;
+const OVERVIEW_DEFAULT_LIMIT = 100;
+const NEIGHBORHOOD_DEFAULT_LIMIT = 80;
+const MAX_LIMIT = 250;
+
function jaccardSimilarity(tagsA, tagsB) {
if (!tagsA?.length || !tagsB?.length) return 0;
const setA = new Set(tagsA);
@@ -25,8 +41,14 @@ function jaccardSimilarity(tagsA, tagsB) {
return union === 0 ? 0 : intersection / union;
}
-export async function getBrainGraphData() {
- // 1. Load all brain entities, filter archived
+const clampLimit = (limit, fallback) => {
+ const n = Number(limit);
+ if (!Number.isFinite(n) || n <= 0) return fallback;
+ return Math.min(Math.floor(n), MAX_LIMIT);
+};
+
+// Load all non-archived brain entities as graph nodes (no edges).
+async function loadNodes() {
const nodes = [];
for (const type of ENTITY_TYPES) {
const records = await brainStorage.getAll(type);
@@ -43,78 +65,227 @@ export async function getBrainGraphData() {
});
}
}
+ return nodes;
+}
+
+// Lightweight index for the client-side search box — every node, no edges.
+export async function getBrainGraphSearchIndex() {
+ const nodes = await loadNodes();
+ return { nodes: nodes.map(n => ({ id: n.id, label: n.label, brainType: n.brainType })) };
+}
- if (!nodes.length) return { nodes: [], edges: [], hasEmbeddings: false };
+// Build the shared graph context once: nodes + tag index + remapped
+// similar/linked edges (from CoS memory, capped per node already) + adjacency.
+// This deliberately omits shared-tag edges — those are computed per bounded set.
+async function loadGraphContext() {
+ const nodes = await loadNodes();
+ const nodeById = new Map(nodes.map(n => [n.id, n]));
+ const brainIdSet = new Set(nodeById.keys());
- // 2. Load bridge map and build reverse map (memoryId → brainId)
+ // tag → array of node ids
+ const tagIndex = new Map();
+ for (const n of nodes) {
+ for (const tag of n.tags || []) {
+ if (!tagIndex.has(tag)) tagIndex.set(tag, []);
+ tagIndex.get(tag).push(n.id);
+ }
+ }
+
+ // Reverse bridge: memoryId → brainId
const bridgeMap = await loadBridgeMap();
const reverseBridge = {};
for (const [bKey, memId] of Object.entries(bridgeMap)) {
- reverseBridge[memId] = bKey.split(':')[1]; // extract brainId from "type:id"
+ reverseBridge[memId] = bKey.split(':')[1];
}
- // Build brainId set for quick lookup
- const brainIdSet = new Set(nodes.map(n => n.id));
-
- // 3. Get CoS graph data and remap edges through bridge
- const edges = [];
- const seenEdges = new Set();
+ // Remap CoS similar/linked edges to brain ids. ~3 similar/node + links — not
+ // the explosion (that's shared_tag, computed per bounded set below).
+ const remappedEdges = [];
+ const seen = new Set();
let hasEmbeddings = false;
-
const cosGraph = await memoryBackend.getGraphData().catch(() => null);
if (cosGraph) {
for (const edge of cosGraph.edges) {
- const brainSourceId = reverseBridge[edge.source];
- const brainTargetId = reverseBridge[edge.target];
- if (!brainSourceId || !brainTargetId) continue;
- if (!brainIdSet.has(brainSourceId) || !brainIdSet.has(brainTargetId)) continue;
- if (brainSourceId === brainTargetId) continue;
-
- const edgeKey = [brainSourceId, brainTargetId].sort().join('-');
- if (seenEdges.has(edgeKey)) continue;
- seenEdges.add(edgeKey);
-
- const mappedType = edge.type === 'linked' ? 'linked' : 'similar';
- if (mappedType === 'similar') hasEmbeddings = true;
-
- edges.push({
- source: brainSourceId,
- target: brainTargetId,
- type: mappedType,
- weight: edge.weight
- });
+ const source = reverseBridge[edge.source];
+ const target = reverseBridge[edge.target];
+ if (!source || !target || source === target) continue;
+ if (!brainIdSet.has(source) || !brainIdSet.has(target)) continue;
+ const key = [source, target].sort().join('-');
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const type = edge.type === 'linked' ? 'linked' : 'similar';
+ if (type === 'similar') hasEmbeddings = true;
+ remappedEdges.push({ source, target, type, weight: edge.weight });
}
}
- // 4. Compute tag-based edges (Jaccard >= 0.3) using inverted index
- const tagIndex = new Map(); // tag → Set of node indices
- for (let i = 0; i < nodes.length; i++) {
- for (const tag of nodes[i].tags || []) {
- if (!tagIndex.has(tag)) tagIndex.set(tag, new Set());
- tagIndex.get(tag).add(i);
+ // adjacency: id → array of { otherId, type, weight }
+ const adjacency = new Map();
+ const addAdj = (a, b, type, weight) => {
+ if (!adjacency.has(a)) adjacency.set(a, []);
+ adjacency.get(a).push({ otherId: b, type, weight });
+ };
+ for (const e of remappedEdges) {
+ addAdj(e.source, e.target, e.type, e.weight);
+ addAdj(e.target, e.source, e.type, e.weight);
+ }
+
+ return { nodes, nodeById, tagIndex, remappedEdges, adjacency, hasEmbeddings };
+}
+
+// Shared-tag edges among a bounded set of node ids, Jaccard-gated and capped per
+// node (union of each endpoint's top-K) so a hub can't dominate the view.
+function sharedTagEdgesAmong(ids, nodeById) {
+ const idSet = new Set(ids);
+ // Collect candidate weighted pairs.
+ const perNode = new Map(); // id → array of { other, weight }
+ for (let i = 0; i < ids.length; i++) {
+ const a = nodeById.get(ids[i]);
+ if (!a?.tags?.length) continue;
+ for (let j = i + 1; j < ids.length; j++) {
+ const b = nodeById.get(ids[j]);
+ if (!b?.tags?.length) continue;
+ const w = jaccardSimilarity(a.tags, b.tags);
+ if (w < SHARED_TAG_MIN_JACCARD) continue;
+ if (!perNode.has(a.id)) perNode.set(a.id, []);
+ if (!perNode.has(b.id)) perNode.set(b.id, []);
+ perNode.get(a.id).push({ other: b.id, weight: w });
+ perNode.get(b.id).push({ other: a.id, weight: w });
}
}
- const candidatePairs = new Set();
- for (const indices of tagIndex.values()) {
- const arr = [...indices];
- for (let x = 0; x < arr.length; x++) {
- for (let y = x + 1; y < arr.length; y++) {
- const lo = Math.min(arr[x], arr[y]), hi = Math.max(arr[x], arr[y]);
- candidatePairs.add(`${lo}:${hi}`);
- }
+ // Keep an edge if it survives the top-K cap on *either* endpoint.
+ const kept = new Set();
+ for (const [, list] of perNode) {
+ list.sort((x, y) => y.weight - x.weight);
+ }
+ const edges = [];
+ for (const [id, list] of perNode) {
+ for (const { other, weight } of list.slice(0, SHARED_TAG_CAP_PER_NODE)) {
+ if (!idSet.has(other)) continue;
+ const key = [id, other].sort().join('-');
+ if (kept.has(key)) continue;
+ kept.add(key);
+ const [source, target] = [id, other].sort();
+ edges.push({ source, target, type: 'shared_tag', weight });
}
}
- for (const pair of candidatePairs) {
- const [i, j] = pair.split(':').map(Number);
- const a = nodes[i], b = nodes[j];
- const edgeKey = [a.id, b.id].sort().join('-');
- if (seenEdges.has(edgeKey)) continue;
- const similarity = jaccardSimilarity(a.tags, b.tags);
- if (similarity >= 0.3) {
- seenEdges.add(edgeKey);
- edges.push({ source: a.id, target: b.id, type: 'shared_tag', weight: similarity });
+ return edges;
+}
+
+// Edges induced among a bounded node set: explicit/semantic first, then capped
+// shared-tag for pairs not already connected.
+function inducedEdges(idSet, ctx) {
+ const ids = [...idSet];
+ const edges = [];
+ const seen = new Set();
+ for (const e of ctx.remappedEdges) {
+ if (!idSet.has(e.source) || !idSet.has(e.target)) continue;
+ const key = [e.source, e.target].sort().join('-');
+ if (seen.has(key)) continue;
+ seen.add(key);
+ edges.push(e);
+ }
+ for (const e of sharedTagEdgesAmong(ids, ctx.nodeById)) {
+ const key = [e.source, e.target].sort().join('-');
+ if (seen.has(key)) continue; // an explicit/semantic edge already connects them
+ seen.add(key);
+ edges.push(e);
+ }
+ return edges;
+}
+
+// Cheap connectivity proxy for ranking the overview: degree in the
+// similar/linked graph (weighted higher) plus a bounded co-tag participation
+// score derived from tag-bucket sizes — neither enumerates all pairs.
+function connectivityScores(ctx) {
+ const score = new Map();
+ for (const n of ctx.nodes) score.set(n.id, 0);
+ for (const [id, neighbors] of ctx.adjacency) {
+ score.set(id, (score.get(id) || 0) + neighbors.length * 2);
+ }
+ for (const [, ids] of ctx.tagIndex) {
+ const inc = Math.min(ids.length - 1, 5); // cap a giant bucket's contribution
+ if (inc <= 0) continue;
+ for (const id of ids) score.set(id, (score.get(id) || 0) + inc);
+ }
+ return score;
+}
+
+export async function getBrainGraphOverview({ limit } = {}) {
+ const cap = clampLimit(limit, OVERVIEW_DEFAULT_LIMIT);
+ const ctx = await loadGraphContext();
+ if (!ctx.nodes.length) {
+ return { nodes: [], edges: [], hasEmbeddings: false, mode: 'overview' };
+ }
+ const score = connectivityScores(ctx);
+ const topIds = [...ctx.nodes]
+ .sort((a, b) => (score.get(b.id) || 0) - (score.get(a.id) || 0))
+ .slice(0, cap)
+ .map(n => n.id);
+ const idSet = new Set(topIds);
+ const edges = inducedEdges(idSet, ctx);
+ const nodes = topIds.map(id => ctx.nodeById.get(id));
+ return { nodes, edges, hasEmbeddings: ctx.hasEmbeddings, mode: 'overview' };
+}
+
+export async function getBrainGraphNeighborhood({ focusId, limit } = {}) {
+ const cap = clampLimit(limit, NEIGHBORHOOD_DEFAULT_LIMIT);
+ const ctx = await loadGraphContext();
+ const focus = ctx.nodeById.get(focusId);
+ if (!focus) {
+ return { nodes: [], edges: [], hasEmbeddings: ctx.hasEmbeddings, mode: 'neighborhood', focusId, notFound: true };
+ }
+
+ // Gather neighbor candidates with a priority weight: linked > similar > tag.
+ const candidates = new Map(); // otherId → { type, weight, priority }
+ const consider = (otherId, type, weight) => {
+ if (otherId === focusId || !ctx.nodeById.has(otherId)) return;
+ const priority = type === 'linked' ? 2 : type === 'similar' ? 1 : 0;
+ const existing = candidates.get(otherId);
+ if (!existing || priority > existing.priority || (priority === existing.priority && weight > existing.weight)) {
+ candidates.set(otherId, { type, weight, priority });
}
+ };
+ for (const { otherId, type, weight } of ctx.adjacency.get(focusId) || []) {
+ consider(otherId, type, weight);
+ }
+ // Shared-tag neighbors of the focus (bounded by the focus's own tag buckets).
+ const tagCandidateIds = new Set();
+ for (const tag of focus.tags || []) {
+ for (const id of ctx.tagIndex.get(tag) || []) tagCandidateIds.add(id);
+ }
+ for (const id of tagCandidateIds) {
+ if (id === focusId) continue;
+ const w = jaccardSimilarity(focus.tags, ctx.nodeById.get(id)?.tags);
+ if (w >= SHARED_TAG_MIN_JACCARD) consider(id, 'shared_tag', w);
+ }
+
+ // Rank candidates and take the top `cap` neighbors.
+ const neighborIds = [...candidates.entries()]
+ .sort((a, b) => (b[1].priority - a[1].priority) || (b[1].weight - a[1].weight))
+ .slice(0, cap)
+ .map(([id]) => id);
+
+ const idSet = new Set([focusId, ...neighborIds]);
+
+ // Always include the focus↔neighbor edge for every selected neighbor (so none
+ // are orphaned by the shared-tag cap), then add neighbor↔neighbor context.
+ const edges = [];
+ const seen = new Set();
+ for (const id of neighborIds) {
+ const c = candidates.get(id);
+ const [source, target] = [focusId, id].sort();
+ const key = `${source}-${target}`;
+ seen.add(key);
+ edges.push({ source, target, type: c.type, weight: c.weight });
+ }
+ for (const e of inducedEdges(idSet, ctx)) {
+ const key = [e.source, e.target].sort().join('-');
+ if (seen.has(key)) continue;
+ seen.add(key);
+ edges.push(e);
}
- return { nodes, edges, hasEmbeddings };
+ const nodes = [...idSet].map(id => ctx.nodeById.get(id));
+ return { nodes, edges, hasEmbeddings: ctx.hasEmbeddings, mode: 'neighborhood', focusId };
}
diff --git a/server/services/brainGraph.test.js b/server/services/brainGraph.test.js
index 8528e7b46c..42b3b6b8bd 100644
--- a/server/services/brainGraph.test.js
+++ b/server/services/brainGraph.test.js
@@ -16,57 +16,78 @@ vi.mock('./brainMemoryBridge.js', () => ({
import * as brainStorage from './brainStorage.js';
import * as memoryBackend from './memoryBackend.js';
import { loadBridgeMap } from './brainMemoryBridge.js';
-import { getBrainGraphData } from './brainGraph.js';
+import {
+ getBrainGraphSearchIndex,
+ getBrainGraphOverview,
+ getBrainGraphNeighborhood
+} from './brainGraph.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ loadBridgeMap.mockResolvedValue({});
+ memoryBackend.getGraphData.mockResolvedValue(null);
+ brainStorage.getAll.mockResolvedValue([]);
+});
+
+// A small node set fits entirely inside one overview page, so getBrainGraphOverview
+// with a generous limit exercises the same edge-derivation the full graph used to.
+const onlyType = (wanted, records) =>
+ brainStorage.getAll.mockImplementation(async (type) => (type === wanted ? records : []));
+
+describe('getBrainGraphSearchIndex', () => {
+ it('returns every node as {id,label,brainType} with no edges or tags', async () => {
+ onlyType('memories', [
+ { id: 'a', name: 'Alice', tags: ['x'], archived: false },
+ { id: 'b', title: 'Bob', tags: [] }
+ ]);
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes).toHaveLength(2);
+ expect(nodes[0]).toEqual({ id: 'a', label: 'Alice', brainType: 'memories' });
+ expect(nodes[0]).not.toHaveProperty('tags');
+ });
-describe('getBrainGraphData', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- loadBridgeMap.mockResolvedValue({});
- memoryBackend.getGraphData.mockResolvedValue(null);
- brainStorage.getAll.mockResolvedValue([]);
+ it('skips archived records', async () => {
+ onlyType('people', [
+ { id: 'p1', name: 'A', archived: false },
+ { id: 'p2', name: 'B', archived: true }
+ ]);
+ const { nodes } = await getBrainGraphSearchIndex();
+ expect(nodes.map(n => n.id)).toEqual(['p1']);
});
+});
- it('returns empty graph when no entities exist', async () => {
- const result = await getBrainGraphData();
- expect(result).toEqual({ nodes: [], edges: [], hasEmbeddings: false });
+describe('getBrainGraphOverview', () => {
+ it('returns an empty graph when no entities exist', async () => {
+ const result = await getBrainGraphOverview();
+ expect(result).toEqual({ nodes: [], edges: [], hasEmbeddings: false, mode: 'overview' });
});
- it('skips archived records and aggregates the remaining entities into nodes', async () => {
+ it('skips archived records and aggregates the rest into nodes', async () => {
brainStorage.getAll.mockImplementation(async (type) => {
if (type === 'people') return [
{ id: 'p1', name: 'Alice', tags: ['friend'], archived: false },
{ id: 'p2', name: 'Bob', tags: [], archived: true }
];
- if (type === 'projects') return [
- { id: 'pr1', title: 'Phoenix', context: 'launch q4', tags: ['work'] }
- ];
+ if (type === 'projects') return [{ id: 'pr1', title: 'Phoenix', context: 'launch q4', tags: ['work'] }];
return [];
});
-
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.nodes).toHaveLength(2);
- const labels = result.nodes.map(n => n.label);
- expect(labels).toContain('Alice');
- expect(labels).toContain('Phoenix');
+ expect(result.nodes.map(n => n.label).sort()).toEqual(['Alice', 'Phoenix']);
});
it('falls back to "(untitled)" when an entity has no name/title', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'ideas' ? [{ id: 'i1', tags: [] }] : []
- );
- const result = await getBrainGraphData();
+ onlyType('ideas', [{ id: 'i1', tags: [] }]);
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.nodes[0].label).toBe('(untitled)');
});
- it('emits shared_tag edges when Jaccard similarity meets the 0.3 threshold', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [
- { id: 'a', name: 'A', tags: ['x', 'y'] },
- { id: 'b', name: 'B', tags: ['x', 'y', 'z'] }
- ] : []
- );
-
- const result = await getBrainGraphData();
+ it('emits a shared_tag edge when Jaccard >= 0.3', async () => {
+ onlyType('people', [
+ { id: 'a', name: 'A', tags: ['x', 'y'] },
+ { id: 'b', name: 'B', tags: ['x', 'y', 'z'] }
+ ]);
+ const result = await getBrainGraphOverview({ limit: 100 });
const tagEdges = result.edges.filter(e => e.type === 'shared_tag');
expect(tagEdges).toHaveLength(1);
expect(tagEdges[0].weight).toBeCloseTo(2 / 3, 5);
@@ -74,34 +95,21 @@ describe('getBrainGraphData', () => {
});
it('does not emit shared_tag edges below the 0.3 Jaccard threshold', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [
- { id: 'a', name: 'A', tags: ['x', 'p', 'q'] },
- { id: 'b', name: 'B', tags: ['x', 'r', 's'] }
- ] : []
- );
- const result = await getBrainGraphData();
+ onlyType('people', [
+ { id: 'a', name: 'A', tags: ['x', 'p', 'q'] },
+ { id: 'b', name: 'B', tags: ['x', 'r', 's'] }
+ ]);
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.edges).toEqual([]);
});
it('remaps CoS memory edges through the bridge to brain ids', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [
- { id: 'p1', name: 'Alice' },
- { id: 'p2', name: 'Bob' }
- ] : []
- );
- loadBridgeMap.mockResolvedValue({
- 'people:p1': 'mem-1',
- 'people:p2': 'mem-2'
- });
+ onlyType('people', [{ id: 'p1', name: 'Alice' }, { id: 'p2', name: 'Bob' }]);
+ loadBridgeMap.mockResolvedValue({ 'people:p1': 'mem-1', 'people:p2': 'mem-2' });
memoryBackend.getGraphData.mockResolvedValue({
- edges: [
- { source: 'mem-1', target: 'mem-2', type: 'similar', weight: 0.9 }
- ]
+ edges: [{ source: 'mem-1', target: 'mem-2', type: 'similar', weight: 0.9 }]
});
-
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.hasEmbeddings).toBe(true);
expect(result.edges).toHaveLength(1);
expect([result.edges[0].source, result.edges[0].target].sort()).toEqual(['p1', 'p2']);
@@ -110,65 +118,118 @@ describe('getBrainGraphData', () => {
});
it('preserves explicit "linked" type and does not flip hasEmbeddings on its own', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'projects' ? [
- { id: 'a', title: 'A' },
- { id: 'b', title: 'B' }
- ] : []
- );
- loadBridgeMap.mockResolvedValue({
- 'projects:a': 'm-a',
- 'projects:b': 'm-b'
- });
+ onlyType('projects', [{ id: 'a', title: 'A' }, { id: 'b', title: 'B' }]);
+ loadBridgeMap.mockResolvedValue({ 'projects:a': 'm-a', 'projects:b': 'm-b' });
memoryBackend.getGraphData.mockResolvedValue({
edges: [{ source: 'm-a', target: 'm-b', type: 'linked', weight: 1 }]
});
-
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.edges[0].type).toBe('linked');
expect(result.hasEmbeddings).toBe(false);
});
it('drops cos edges whose endpoints are not in the bridge', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [{ id: 'p1', name: 'A' }] : []
- );
- loadBridgeMap.mockResolvedValue({});
+ onlyType('people', [{ id: 'p1', name: 'A' }]);
memoryBackend.getGraphData.mockResolvedValue({
edges: [{ source: 'mem-X', target: 'mem-Y', type: 'similar', weight: 0.5 }]
});
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.edges).toEqual([]);
});
- it('handles a memoryBackend.getGraphData failure by treating it as no edges', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [{ id: 'p1', name: 'A' }] : []
- );
+ it('treats a getGraphData failure as no edges', async () => {
+ onlyType('people', [{ id: 'p1', name: 'A' }]);
memoryBackend.getGraphData.mockRejectedValue(new Error('embeddings unavailable'));
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.nodes).toHaveLength(1);
expect(result.edges).toEqual([]);
expect(result.hasEmbeddings).toBe(false);
});
- it('does not duplicate an edge that exists both as a memory link and a tag overlap', async () => {
- brainStorage.getAll.mockImplementation(async (type) =>
- type === 'people' ? [
- { id: 'a', name: 'A', tags: ['x', 'y'] },
- { id: 'b', name: 'B', tags: ['x', 'y'] }
- ] : []
- );
- loadBridgeMap.mockResolvedValue({
- 'people:a': 'm-a',
- 'people:b': 'm-b'
- });
+ it('does not duplicate an edge that is both a memory link and a tag overlap', async () => {
+ onlyType('people', [
+ { id: 'a', name: 'A', tags: ['x', 'y'] },
+ { id: 'b', name: 'B', tags: ['x', 'y'] }
+ ]);
+ loadBridgeMap.mockResolvedValue({ 'people:a': 'm-a', 'people:b': 'm-b' });
memoryBackend.getGraphData.mockResolvedValue({
edges: [{ source: 'm-a', target: 'm-b', type: 'similar', weight: 0.95 }]
});
-
- const result = await getBrainGraphData();
+ const result = await getBrainGraphOverview({ limit: 100 });
expect(result.edges).toHaveLength(1);
expect(result.edges[0].type).toBe('similar');
});
+
+ it('returns at most `limit` nodes', async () => {
+ onlyType('memories', Array.from({ length: 20 }, (_, i) => ({ id: `n${i}`, name: `N${i}`, tags: ['shared'] })));
+ const { nodes, edges } = await getBrainGraphOverview({ limit: 5 });
+ expect(nodes).toHaveLength(5);
+ const ids = new Set(nodes.map(n => n.id));
+ for (const e of edges) {
+ expect(ids.has(e.source) && ids.has(e.target)).toBe(true);
+ }
+ });
+
+ it('caps the shared_tag explosion — a fully co-tagged set stays bounded', async () => {
+ // 40 nodes all sharing the same tags = C(40,2)=780 pairs uncapped. The
+ // per-node cap (8) holds it to <= 40*8 — this is the fix for the 1M-edge crash.
+ const N = 40;
+ onlyType('memories', Array.from({ length: N }, (_, i) => ({ id: `n${i}`, name: `N${i}`, tags: ['x', 'y'] })));
+ const { nodes, edges } = await getBrainGraphOverview({ limit: N });
+ expect(nodes).toHaveLength(N);
+ expect(edges.every(e => e.type === 'shared_tag')).toBe(true);
+ expect(edges.length).toBeLessThan((N * (N - 1)) / 2);
+ expect(edges.length).toBeLessThanOrEqual(N * 8);
+ });
+});
+
+describe('getBrainGraphNeighborhood', () => {
+ it('returns the focus plus capped neighbors, each connected to the focus', async () => {
+ onlyType('memories', [
+ { id: 'focus', name: 'F', tags: ['t'] },
+ ...Array.from({ length: 6 }, (_, i) => ({ id: `nb${i}`, name: `NB${i}`, tags: ['t'] })),
+ ...Array.from({ length: 3 }, (_, i) => ({ id: `other${i}`, name: `O${i}`, tags: ['z'] }))
+ ]);
+ const { nodes, edges, focusId, mode } = await getBrainGraphNeighborhood({ focusId: 'focus', limit: 80 });
+ expect(mode).toBe('neighborhood');
+ expect(focusId).toBe('focus');
+ const ids = nodes.map(n => n.id);
+ expect(ids).toContain('focus');
+ expect(ids).not.toContain('other0');
+ const neighborIds = ids.filter(id => id !== 'focus');
+ expect(neighborIds).toHaveLength(6);
+ for (const nb of neighborIds) {
+ const connected = edges.some(e =>
+ (e.source === 'focus' && e.target === nb) || (e.target === 'focus' && e.source === nb));
+ expect(connected).toBe(true);
+ }
+ });
+
+ it('honors the neighbor limit', async () => {
+ onlyType('memories', [
+ { id: 'focus', name: 'F', tags: ['t'] },
+ ...Array.from({ length: 30 }, (_, i) => ({ id: `nb${i}`, name: `NB${i}`, tags: ['t'] }))
+ ]);
+ const { nodes } = await getBrainGraphNeighborhood({ focusId: 'focus', limit: 10 });
+ expect(nodes.length).toBeLessThanOrEqual(11);
+ expect(nodes.some(n => n.id === 'focus')).toBe(true);
+ });
+
+ it('flags an unknown focus as notFound', async () => {
+ onlyType('memories', [{ id: 'a', name: 'A' }]);
+ const res = await getBrainGraphNeighborhood({ focusId: 'missing' });
+ expect(res.notFound).toBe(true);
+ expect(res.nodes).toEqual([]);
+ });
+
+ it('includes neighbors reached via remapped linked/similar edges', async () => {
+ onlyType('memories', [{ id: 'focus', name: 'F', tags: [] }, { id: 'friend', name: 'Fr', tags: [] }]);
+ loadBridgeMap.mockResolvedValue({ 'memories:focus': 'mem-f', 'memories:friend': 'mem-r' });
+ memoryBackend.getGraphData.mockResolvedValue({
+ edges: [{ source: 'mem-f', target: 'mem-r', type: 'linked', weight: 1 }]
+ });
+ const { nodes, edges } = await getBrainGraphNeighborhood({ focusId: 'focus' });
+ expect(nodes.map(n => n.id).sort()).toEqual(['focus', 'friend']);
+ expect(edges.some(e => e.type === 'linked')).toBe(true);
+ });
});
diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.js
index ea59878aa0..ab009f33b2 100644
--- a/server/services/brainMemoryBridge.js
+++ b/server/services/brainMemoryBridge.js
@@ -232,10 +232,26 @@ export async function syncBrainRecord(brainType, record) {
* 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 } = {}) {
+// True when a record is already embedded: mapped AND its memory has a vector.
+// Shared by the onlyMissing sync path and the read-only coverage tally.
+const makeEmbeddedChecker = (map, missingMemIds) => (key) => {
+ const memId = map[key];
+ return !!memId && !missingMemIds.has(memId);
+};
+
+export async function syncAllBrainData({ dryRun = false, refresh = false, onlyMissing = false } = {}) {
const map = await loadBridgeMap();
const stats = { synced: 0, skipped: 0, errors: 0, archived: 0 };
+ // `onlyMissing` is the cheap, targeted backfill: embed only records that lack
+ // an embedding (unmapped, or mapped to a memory whose vector is NULL because
+ // generation failed) and skip everything already embedded. Unlike `refresh`
+ // it never re-embeds healthy records, so it's safe to run without a warning.
+ const missingMemIds = onlyMissing
+ ? await memory.getMemoryIdsMissingEmbedding().catch(() => new Set())
+ : null;
+ const isEmbedded = makeEmbeddedChecker(map, missingMemIds);
+
// Entity stores (JSON-based)
const entityTypes = ['people', 'projects', 'ideas', 'admin', 'memories'];
for (const type of entityTypes) {
@@ -247,7 +263,9 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})
continue;
}
const key = bridgeKey(type, record.id);
- if (map[key] && !dryRun && !refresh) {
+ if (onlyMissing) {
+ if (isEmbedded(key)) { stats.skipped++; continue; }
+ } else if (map[key] && !dryRun && !refresh) {
stats.skipped++;
continue;
}
@@ -277,7 +295,9 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})
// 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) — unless refresh is forcing a re-embed.
- if (map[key] && !refresh) {
+ if (onlyMissing) {
+ if (isEmbedded(key)) { stats.skipped += 1; continue; }
+ } else if (map[key] && !refresh) {
stats.skipped += 1;
continue;
}
@@ -302,7 +322,9 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})
const records = await getter(1000); // get all
for (const record of records) {
const key = bridgeKey(type, record.id);
- if (map[key] && !dryRun && !refresh) {
+ if (onlyMissing) {
+ if (isEmbedded(key)) { stats.skipped++; continue; }
+ } else if (map[key] && !dryRun && !refresh) {
stats.skipped++;
continue;
}
@@ -354,6 +376,41 @@ export async function syncAllBrainData({ dryRun = false, refresh = false } = {})
return stats;
}
+/**
+ * Count how many active brain records lack an embedding — the headline number
+ * for the "N memories missing embeddings · Embed missing" affordance on the
+ * graph. A record is "missing" when it's unmapped OR its mapped memory has a
+ * NULL embedding. Read-only; walks the same stores as the onlyMissing sync so
+ * the count matches what "Embed missing" would actually process.
+ */
+export async function getEmbeddingCoverage() {
+ const map = await loadBridgeMap();
+ const missingMemIds = await memory.getMemoryIdsMissingEmbedding().catch(() => new Set());
+ const isEmbedded = makeEmbeddedChecker(map, missingMemIds);
+
+ let total = 0;
+ let missing = 0;
+ const tally = (key) => { total += 1; if (!isEmbedded(key)) missing += 1; };
+
+ for (const type of ['people', 'projects', 'ideas', 'admin', 'memories']) {
+ const records = await brainStorage.getAll(type);
+ for (const record of records) {
+ if (record.archived) continue;
+ tally(bridgeKey(type, record.id));
+ }
+ }
+
+ const { records: journals } = await listJournals({ limit: 10000, includeContent: false });
+ for (const record of journals) tally(bridgeKey('journals', record.id));
+
+ for (const [type, getter] of [['digests', brainStorage.getDigests], ['reviews', brainStorage.getReviews]]) {
+ const records = await getter(1000);
+ for (const record of records) tally(bridgeKey(type, record.id));
+ }
+
+ return { total, missing };
+}
+
// ─── 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
diff --git a/server/services/memory.js b/server/services/memory.js
index bbb0741836..bb3264a6b5 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -673,6 +673,22 @@ export async function getGraphData() {
return { nodes, edges };
}
+/**
+ * Ids of active memories that have no embedding vector yet — the backfill
+ * target for "embed missing" (a record whose embedding generation failed or
+ * never ran). Mirrors the memoryDB.js implementation against the file store.
+ */
+export async function getMemoryIdsMissingEmbedding() {
+ const index = await loadIndex();
+ const embeddings = await loadEmbeddings();
+ const missing = new Set();
+ for (const m of index.memories) {
+ if (m.status !== 'active') continue;
+ if (!embeddings.vectors[m.id]) missing.add(m.id);
+ }
+ return missing;
+}
+
/**
* Link two memories
*/
diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.js
index 2f4c9db1fc..6e6231045d 100644
--- a/server/services/memoryBackend.js
+++ b/server/services/memoryBackend.js
@@ -199,6 +199,11 @@ export async function getGraphData() {
return b.getGraphData();
}
+export async function getMemoryIdsMissingEmbedding() {
+ const b = await getBackend();
+ return b.getMemoryIdsMissingEmbedding();
+}
+
export async function linkMemories(sourceId, targetId) {
const b = await getBackend();
return b.linkMemories(sourceId, targetId);
diff --git a/server/services/memoryDB.js b/server/services/memoryDB.js
index 42b77a90b6..5d815ffbfd 100644
--- a/server/services/memoryDB.js
+++ b/server/services/memoryDB.js
@@ -820,6 +820,18 @@ export async function getGraphData() {
return { nodes, edges };
}
+/**
+ * Ids of active memories with a NULL embedding — the backfill target for
+ * "embed missing" (a record whose embedding generation failed or never ran).
+ * Returned as a Set for O(1) membership tests by the bridge.
+ */
+export async function getMemoryIdsMissingEmbedding() {
+ const result = await query(`
+ SELECT id FROM memories WHERE embedding IS NULL AND status = 'active'
+ `);
+ return new Set(result.rows.map(r => r.id));
+}
+
/**
* Link two memories
*/