Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add Brain Graph visualization, fix memory tag input
Adam Eivyf274235da786
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b4ecefa4df..7026e4c202 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,8 @@- Source filter toggle (All/CoS/Brain) and source badges on Memory tab- `appId` filtering on memory list and search APIs- Migration script for existing brain data (`server/scripts/migrateBrainToMemories.js`)+- Brain Graph tab (`/brain/graph`): 3D force-directed visualization of brain entities with semantic similarity, shared-tag, and linked edges; type filter checkboxes, text search, detail panel+- Shared graph simulation library (`client/src/lib/graphSimulation.js`) extracted from CoS MemoryGraph## Changed@@ -17,4 +19,6 @@## Fixed+- Brain Memory tag input now allows typing commas (stores raw string, splits to array on save)+## Removeddiff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.jsindex 6d6deb6130..65ea215385 100644--- a/client/src/components/brain/constants.js+++ b/client/src/components/brain/constants.js@@ -1,10 +1,11 @@-import { MessageSquare, Database, Calendar, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen } from 'lucide-react';+import { MessageSquare, Database, Calendar, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network } from 'lucide-react';// Main navigation tabsexport const TABS = [{ id: 'inbox', label: 'Inbox', icon: MessageSquare },{ id: 'links', label: 'Links', icon: Link2 },{ id: 'memory', label: 'Memory', icon: Database },+ { id: 'graph', label: 'Graph', icon: Network },{ id: 'digest', label: 'Digest', icon: Calendar },{ id: 'trust', label: 'Trust', icon: Shield },{ id: 'config', label: 'Config', icon: Settings }@@ -98,6 +99,15 @@ export function getConfidenceColor(confidence) {return CONFIDENCE_COLORS.low;}+// Brain entity type hex colors for graph visualization+export const BRAIN_TYPE_HEX = {+ people: '#a855f7',+ projects: '#3b82f6',+ ideas: '#eab308',+ admin: '#22c55e',+ memories: '#ec4899'+};+// Format relative timeexport function formatRelativeTime(dateString) {if (!dateString) return 'Never';diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsxnew file mode 100644index 0000000000..d12bdd2e9b--- /dev/null+++ b/client/src/components/brain/tabs/BrainGraph.jsx@@ -0,0 +1,441 @@+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 { RefreshCw, Search, AlertTriangle } from 'lucide-react';+import * as api from '../../../services/api';+import { BRAIN_TYPE_HEX, DESTINATIONS } from '../constants';+import { buildGraph } from '../../../lib/graphSimulation';++const EDGE_COLORS = {+ similar: '#3b82f6',+ shared_tag: '#f59e0b',+ linked: '#ffffff'+};++const BRAIN_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];++// Per-type API getters for detail panel+const TYPE_GETTERS = {+ people: api.getBrainPerson,+ projects: api.getBrainProject,+ ideas: api.getBrainIdea,+ admin: api.getBrainAdminItem,+ memories: api.getBrainMemory+};++function GraphEdges({ simEdges, selectedId }) {+ const geoRef = useRef();++ useEffect(() => {+ const geo = geoRef.current;+ if (!geo || !simEdges.length) return;++ const count = simEdges.length;+ const positions = new Float32Array(count * 6);+ const colors = new Float32Array(count * 6);+ const tmpColor = new THREE.Color();++ simEdges.forEach((e, i) => {+ const a = e.sourceNode, b = e.targetNode;+ const off = i * 6;+ positions[off] = a.x; positions[off + 1] = a.y; positions[off + 2] = a.z;+ positions[off + 3] = b.x; positions[off + 4] = b.y; positions[off + 5] = b.z;++ const dimmed = selectedId && e.source !== selectedId && e.target !== selectedId;+ tmpColor.set(EDGE_COLORS[e.type] || '#6b7280');+ const intensity = dimmed ? 0.06 : (e.type === 'linked' ? 0.6 : 0.3 * (e.weight || 0.5));+ const r = tmpColor.r * intensity, g = tmpColor.g * intensity, bl = tmpColor.b * intensity;+ colors[off] = r; colors[off + 1] = g; colors[off + 2] = bl;+ colors[off + 3] = r; colors[off + 4] = g; colors[off + 5] = bl;+ });++ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));+ geo.computeBoundingSphere();+ }, [simEdges, selectedId]);++ return (+ <lineSegments>+ <bufferGeometry ref={geoRef} />+ <lineBasicMaterial vertexColors />+ </lineSegments>+ );+}++function GraphScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {+ const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);++ const selNode = selectedId ? graph.idMap.get(selectedId) : null;+ const selRadius = selNode ? 0.4 + (selNode.importance ?? 0.5) * 0.8 : 0;++ return (+ <>+ <ambientLight intensity={0.4} />+ <pointLight position={[50, 50, 50]} intensity={0.8} />+ <pointLight position={[-30, -30, -30]} intensity={0.3} />++ <GraphEdges simEdges={graph.simEdges} selectedId={selectedId} />++ {graph.simNodes.map(node => {+ const radius = 0.4 + (node.importance ?? 0.5) * 0.8;+ const color = BRAIN_TYPE_HEX[node.brainType] || '#6b7280';+ const isSelected = node.id === selectedId;+ const isConnected = adjacentIds?.has(node.id);+ const dimmed = selectedId && !isSelected && !isConnected;++ return (+ <mesh+ key={node.id}+ geometry={sphereGeo}+ scale={radius}+ position={[node.x, node.y, node.z]}+ onClick={(e) => { e.stopPropagation(); onSelect(node); }}+ onPointerOver={(e) => { e.stopPropagation(); onHover(node); }}+ onPointerOut={() => onHover(null)}+ >+ <meshStandardMaterial+ color={dimmed ? '#1a1a1a' : color}+ emissive={color}+ emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.2)}+ />+ </mesh>+ );+ })}++ {selNode && (+ <mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}>+ <meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe />+ </mesh>+ )}++ <OrbitControls enableDamping dampingFactor={0.05} minDistance={10} maxDistance={200} />+ </>+ );+}++export default function BrainGraph() {+ const [graphData, setGraphData] = useState(null);+ const [loading, setLoading] = useState(true);+ 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 [typeFilters, setTypeFilters] = useState(() =>+ Object.fromEntries(BRAIN_TYPES.map(t => [t, true]))+ );++ const graphRef = useRef(null);+ const dragStartRef = useRef(null);++ useEffect(() => {+ api.getBrainGraph().then(setGraphData).catch(() => setGraphData(null)).finally(() => setLoading(false));+ }, []);++ // Filter nodes based on type toggles and search+ 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 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]);++ const graph = useMemo(() => {+ if (!filteredData?.nodes?.length) return null;+ const g = buildGraph(filteredData.nodes, filteredData.edges);+ graphRef.current = g;+ return g;+ }, [filteredData, layoutKey]);++ const adjacentIds = useMemo(() => {+ if (!selectedNode || !graph) return null;+ const set = new Set();+ for (const e of graph.simEdges) {+ if (e.source === selectedNode.id) set.add(e.target);+ if (e.target === selectedNode.id) set.add(e.source);+ }+ return set;+ }, [selectedNode, graph]);++ const connectedEdges = selectedNode && graph+ ? graph.simEdges.filter(e => e.source === selectedNode.id || e.target === selectedNode.id)+ : [];+ const connectedNodes = selectedNode && graph+ ? connectedEdges.map(e => {+ const otherId = e.source === selectedNode.id ? e.target : e.source;+ const n = graph.idMap.get(otherId);+ return n ? { ...n, edgeType: e.type, weight: e.weight } : null;+ }).filter(Boolean)+ : [];++ // Fetch full brain record when a node is selected+ useEffect(() => {+ if (!selectedNode) { setFullRecord(null); return; }+ let cancelled = false;+ const getter = TYPE_GETTERS[selectedNode.brainType];+ if (!getter) return;+ getter(selectedNode.id).then(record => {+ if (!cancelled) setFullRecord(record);+ }).catch(() => {+ if (!cancelled) setFullRecord(null);+ });+ return () => { cancelled = true; };+ }, [selectedNode?.id, selectedNode?.brainType]);++ const handleSelect = useCallback((node) => {+ setSelectedNode(prev => prev?.id === node.id ? null : node);+ }, []);++ const handleHover = useCallback((node) => {+ setHoveredNode(node);+ }, []);++ const handlePointerMissed = useCallback((e) => {+ const start = dragStartRef.current;+ if (!start) return;+ if (Math.abs(e.clientX - start.x) < 5 && Math.abs(e.clientY - start.y) < 5) {+ setSelectedNode(null);+ }+ }, []);++ const toggleType = (type) => {+ setTypeFilters(prev => ({ ...prev, [type]: !prev[type] }));+ setSelectedNode(null);+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="animate-spin text-port-accent" size={24} />+ </div>+ );+ }++ if (!graphData || !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.+ </div>+ );+ }++ return (+ <div className="space-y-3">+ {/* No-embeddings banner */}+ {graphData && !graphData.hasEmbeddings && (+ <div className="flex items-center gap-2 bg-port-warning/10 border border-port-warning/30 rounded-lg px-4 py-2 text-sm text-port-warning">+ <AlertTriangle size={16} />+ No embeddings found. Run a brain→memory sync to enable semantic similarity edges.+ </div>+ )}++ {/* Controls bar */}+ <div className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg px-4 py-2 flex-wrap">+ {/* Type filter checkboxes */}+ <div className="flex items-center gap-3">+ {BRAIN_TYPES.map(type => {+ const dest = DESTINATIONS[type];+ return (+ <label key={type} className="flex items-center gap-1.5 cursor-pointer text-sm">+ <input+ type="checkbox"+ checked={typeFilters[type]}+ onChange={() => toggleType(type)}+ className="sr-only"+ />+ <span+ className={`inline-block w-3 h-3 rounded-sm border-2 transition-colors ${+ typeFilters[type] ? 'border-transparent' : 'border-gray-600 bg-transparent'+ }`}+ style={typeFilters[type] ? { backgroundColor: BRAIN_TYPE_HEX[type] } : undefined}+ />+ <span className={typeFilters[type] ? 'text-gray-300' : 'text-gray-600'}>{dest?.label || type}</span>+ </label>+ );+ })}+ </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">+ {filteredData?.nodes?.length || 0} nodes · {filteredData?.edges?.length || 0} edges+ </span>+ <button+ onClick={() => { setSelectedNode(null); setLayoutKey(k => k + 1); }}+ className="px-3 py-1.5 min-h-[36px] text-xs bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"+ >+ Re-layout+ </button>+ </div>++ {/* 3D Canvas */}+ <div+ className="relative bg-port-card border border-port-border rounded-lg overflow-hidden"+ style={{ height: '500px' }}+ onPointerDown={(e) => { dragStartRef.current = { x: e.clientX, y: e.clientY }; }}+ onPointerMove={(e) => setTooltipPos({ x: e.clientX, y: e.clientY })}+ >+ {graph && (+ <Canvas+ camera={{ position: [0, 0, 80], fov: 50 }}+ dpr={[1, 1.5]}+ style={{ background: '#0f0f0f' }}+ gl={{ antialias: true }}+ onPointerMissed={handlePointerMissed}+ >+ <GraphScene+ graph={graph}+ selectedId={selectedNode?.id}+ adjacentIds={adjacentIds}+ onSelect={handleSelect}+ onHover={handleHover}+ />+ </Canvas>+ )}++ {!graph && filteredData?.nodes?.length === 0 && (+ <div className="flex items-center justify-center h-full text-gray-500 text-sm">+ No nodes match the current filters.+ </div>+ )}++ {/* 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 => (+ <div key={t} className="flex items-center gap-2">+ <span className="inline-block w-2.5 h-2.5 rounded-full" style={{ backgroundColor: BRAIN_TYPE_HEX[t] }} />+ <span className="text-gray-400">{DESTINATIONS[t]?.label || t}</span>+ </div>+ ))}+ <div className="border-t border-port-border pt-1.5 mt-1.5 space-y-1">+ <div className="flex items-center gap-2">+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.similar }} />+ <span className="text-gray-500">similar</span>+ </div>+ <div className="flex items-center gap-2">+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.shared_tag }} />+ <span className="text-gray-500">shared tag</span>+ </div>+ <div className="flex items-center gap-2">+ <span className="inline-block w-4 h-0 border-t" style={{ borderColor: EDGE_COLORS.linked }} />+ <span className="text-gray-500">linked</span>+ </div>+ </div>+ </div>++ {/* Tooltip */}+ {hoveredNode && (+ <div+ className="fixed z-50 pointer-events-none bg-port-bg border border-port-border rounded-lg px-3 py-2 shadow-lg max-w-xs"+ style={{ left: tooltipPos.x + 12, top: tooltipPos.y - 12 }}+ >+ <div className="flex items-center gap-2 mb-1">+ <span+ className="px-1.5 py-0.5 text-[10px] rounded-full border"+ style={{ borderColor: BRAIN_TYPE_HEX[hoveredNode.brainType], color: BRAIN_TYPE_HEX[hoveredNode.brainType] }}+ >+ {DESTINATIONS[hoveredNode.brainType]?.label || hoveredNode.brainType}+ </span>+ </div>+ <p className="text-xs text-white leading-snug font-medium">{hoveredNode.label}</p>+ {hoveredNode.summary && (+ <p className="text-[10px] text-gray-400 mt-0.5 line-clamp-2">{hoveredNode.summary}</p>+ )}+ </div>+ )}+ </div>++ {/* Detail panel */}+ {selectedNode && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-start justify-between gap-3 mb-3">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-2">+ <span+ className="px-2 py-1 text-xs rounded-full border"+ style={{ borderColor: BRAIN_TYPE_HEX[selectedNode.brainType], color: BRAIN_TYPE_HEX[selectedNode.brainType] }}+ >+ {DESTINATIONS[selectedNode.brainType]?.label || selectedNode.brainType}+ </span>+ {selectedNode.status && (+ <span className="text-xs text-gray-500">{selectedNode.status}</span>+ )}+ </div>+ <h3 className="text-sm font-medium text-white mb-1">{selectedNode.label}</h3>+ {fullRecord ? (+ <div className="space-y-3">+ {(fullRecord.context || fullRecord.oneLiner || fullRecord.notes || fullRecord.content) && (+ <p className="text-sm text-gray-300 whitespace-pre-wrap">+ {fullRecord.context || fullRecord.oneLiner || fullRecord.notes || fullRecord.content}+ </p>+ )}+ {fullRecord.tags?.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {fullRecord.tags.map(tag => (+ <span key={tag} className="px-2 py-1 text-xs bg-port-border rounded text-gray-400">{tag}</span>+ ))}+ </div>+ )}+ <div className="text-xs text-gray-500 flex flex-wrap gap-3">+ {fullRecord.createdAt && <span>Created: {new Date(fullRecord.createdAt).toLocaleDateString()}</span>}+ {fullRecord.nextAction && <span>Next: {fullRecord.nextAction}</span>}+ </div>+ </div>+ ) : (+ <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"+ >+ ×+ </button>+ </div>+ {connectedNodes.length > 0 && (+ <div>+ <p className="text-xs text-gray-500 mb-2">{connectedNodes.length} connections</p>+ <div className="space-y-1.5 max-h-48 overflow-y-auto">+ {connectedNodes.map(cn => (+ <button+ key={cn.id}+ onClick={() => {+ const node = graphRef.current?.idMap.get(cn.id);+ if (node) setSelectedNode(node);+ }}+ 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] }} />+ <span className="text-xs text-gray-300 truncate flex-1">{cn.label}</span>+ <span className="text-[10px] text-gray-600 shrink-0">+ {cn.edgeType === 'linked' ? 'linked' : cn.edgeType === 'shared_tag' ? 'tag' : `${((cn.weight || 0) * 100).toFixed(0)}%`}+ </span>+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsxindex 87b2e5f8ae..d19ab89b15 100644--- a/client/src/components/brain/tabs/MemoryTab.jsx+++ b/client/src/components/brain/tabs/MemoryTab.jsx@@ -105,12 +105,15 @@ export default function MemoryTab({ onRefresh }) {return null;});break;- case 'memories':- result = await api.updateBrainMemory(editingId, editForm).catch(err => {+ case 'memories': {+ const { tagInput, ...memData } = editForm;+ if (tagInput != null) memData.tags = tagInput.split(',').map(s => s.trim()).filter(Boolean);+ result = await api.updateBrainMemory(editingId, memData).catch(err => {toast.error(err.message);return null;});break;+ }}if (result) {@@ -149,12 +152,15 @@ export default function MemoryTab({ onRefresh }) {return null;});break;- case 'memories':- result = await api.createBrainMemory(addForm).catch(err => {+ case 'memories': {+ const { tagInput, ...memData } = addForm;+ if (tagInput != null) memData.tags = tagInput.split(',').map(s => s.trim()).filter(Boolean);+ result = await api.createBrainMemory(memData).catch(err => {toast.error(err.message);return null;});break;+ }}if (result) {@@ -240,7 +246,7 @@ export default function MemoryTab({ onRefresh }) {const startEdit = (record) => {setEditingId(record.id);- setEditForm({ ...record });+ setEditForm({ ...record, tagInput: (record.tags || []).join(', ') });};const renderForm = (form, setForm, isEdit = false) => {@@ -408,8 +414,8 @@ export default function MemoryTab({ onRefresh }) {<inputtype="text"placeholder="Tags (comma separated)"- value={(form.tags || []).join(', ')}- onChange={(e) => setForm({ ...form, tags: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })}+ value={form.tagInput ?? (form.tags || []).join(', ')}+ onChange={(e) => setForm({ ...form, tagInput: e.target.value })}className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"/></div>diff --git a/client/src/components/cos/tabs/MemoryGraph.jsx b/client/src/components/cos/tabs/MemoryGraph.jsxindex b6e4940080..708cd25874 100644--- a/client/src/components/cos/tabs/MemoryGraph.jsx+++ b/client/src/components/cos/tabs/MemoryGraph.jsx@@ -5,6 +5,7 @@ import * as THREE from 'three';import { RefreshCw } from 'lucide-react';import * as api from '../../../services/api';import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';+import { buildGraph } from '../../../lib/graphSimulation';const TYPE_HEX = {fact: '#3b82f6',@@ -15,73 +16,6 @@ const TYPE_HEX = {context: '#6b7280'};-// 3D force simulation parameters-const REPULSION = 500;-const SPRING_K = 0.008;-const SPRING_REST = 12;-const CENTER_GRAVITY = 0.02;-const DAMPING = 0.9;-const ALPHA_DECAY = 0.995;-const ALPHA_MIN = 0.001;--function tickSim(nodes, edges, alpha) {- for (let i = 0; i < nodes.length; i++) {- for (let j = i + 1; j < nodes.length; j++) {- const a = nodes[i], b = nodes[j];- const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z;- const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;- const force = REPULSION / (dist * dist);- const fx = (dx / dist) * force * alpha;- const fy = (dy / dist) * force * alpha;- const fz = (dz / dist) * force * alpha;- a.vx -= fx; a.vy -= fy; a.vz -= fz;- b.vx += fx; b.vy += fy; b.vz += fz;- }- }- for (const e of edges) {- const a = e.sourceNode, b = e.targetNode;- const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z;- const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;- const disp = dist - SPRING_REST;- const force = SPRING_K * disp * alpha;- const fx = (dx / dist) * force, fy = (dy / dist) * force, fz = (dz / dist) * force;- a.vx += fx; a.vy += fy; a.vz += fz;- b.vx -= fx; b.vy -= fy; b.vz -= fz;- }- for (const n of nodes) {- n.vx -= n.x * CENTER_GRAVITY * alpha;- n.vy -= n.y * CENTER_GRAVITY * alpha;- n.vz -= n.z * CENTER_GRAVITY * alpha;- n.vx *= DAMPING; n.vy *= DAMPING; n.vz *= DAMPING;- n.x += n.vx; n.y += n.vy; n.z += n.vz;- }-}--function settleSimulation(nodes, edges) {- let alpha = 1;- while (alpha > ALPHA_MIN) {- tickSim(nodes, edges, alpha);- alpha *= ALPHA_DECAY;- }-}--function buildGraph(rawNodes, rawEdges) {- const simNodes = rawNodes.map((n, i) => ({- ...n,- x: (Math.random() - 0.5) * 60,- y: (Math.random() - 0.5) * 60,- z: (Math.random() - 0.5) * 60,- vx: 0, vy: 0, vz: 0,- index: i- }));- const idMap = new Map(simNodes.map(n => [n.id, n]));- const simEdges = rawEdges- .map(e => ({ ...e, sourceNode: idMap.get(e.source), targetNode: idMap.get(e.target) }))- .filter(e => e.sourceNode && e.targetNode);- settleSimulation(simNodes, simEdges);- return { simNodes, simEdges, idMap };-}-// --- Three.js scene components ---function GraphEdges({ simEdges, selectedId }) {diff --git a/client/src/lib/graphSimulation.js b/client/src/lib/graphSimulation.jsnew file mode 100644index 0000000000..de9daac20d--- /dev/null+++ b/client/src/lib/graphSimulation.js@@ -0,0 +1,66 @@+// 3D force simulation parameters+const REPULSION = 500;+const SPRING_K = 0.008;+const SPRING_REST = 12;+const CENTER_GRAVITY = 0.02;+const DAMPING = 0.9;+const ALPHA_DECAY = 0.995;+const ALPHA_MIN = 0.001;++function tickSim(nodes, edges, alpha) {+ for (let i = 0; i < nodes.length; i++) {+ for (let j = i + 1; j < nodes.length; j++) {+ const a = nodes[i], b = nodes[j];+ const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z;+ const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;+ const force = REPULSION / (dist * dist);+ const fx = (dx / dist) * force * alpha;+ const fy = (dy / dist) * force * alpha;+ const fz = (dz / dist) * force * alpha;+ a.vx -= fx; a.vy -= fy; a.vz -= fz;+ b.vx += fx; b.vy += fy; b.vz += fz;+ }+ }+ for (const e of edges) {+ const a = e.sourceNode, b = e.targetNode;+ const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z;+ const dist = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;+ const disp = dist - SPRING_REST;+ const force = SPRING_K * disp * alpha;+ const fx = (dx / dist) * force, fy = (dy / dist) * force, fz = (dz / dist) * force;+ a.vx += fx; a.vy += fy; a.vz += fz;+ b.vx -= fx; b.vy -= fy; b.vz -= fz;+ }+ for (const n of nodes) {+ n.vx -= n.x * CENTER_GRAVITY * alpha;+ n.vy -= n.y * CENTER_GRAVITY * alpha;+ n.vz -= n.z * CENTER_GRAVITY * alpha;+ n.vx *= DAMPING; n.vy *= DAMPING; n.vz *= DAMPING;+ n.x += n.vx; n.y += n.vy; n.z += n.vz;+ }+}++function settleSimulation(nodes, edges) {+ let alpha = 1;+ while (alpha > ALPHA_MIN) {+ tickSim(nodes, edges, alpha);+ alpha *= ALPHA_DECAY;+ }+}++export function buildGraph(rawNodes, rawEdges) {+ const simNodes = rawNodes.map((n, i) => ({+ ...n,+ x: (Math.random() - 0.5) * 60,+ y: (Math.random() - 0.5) * 60,+ z: (Math.random() - 0.5) * 60,+ vx: 0, vy: 0, vz: 0,+ index: i+ }));+ const idMap = new Map(simNodes.map(n => [n.id, n]));+ const simEdges = rawEdges+ .map(e => ({ ...e, sourceNode: idMap.get(e.source), targetNode: idMap.get(e.target) }))+ .filter(e => e.sourceNode && e.targetNode);+ settleSimulation(simNodes, simEdges);+ return { simNodes, simEdges, idMap };+}diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 790ffcc66d..fff23de5d5 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -11,6 +11,7 @@ import {import InboxTab from '../components/brain/tabs/InboxTab';import LinksTab from '../components/brain/tabs/LinksTab';import MemoryTab from '../components/brain/tabs/MemoryTab';+import BrainGraph from '../components/brain/tabs/BrainGraph';import DigestTab from '../components/brain/tabs/DigestTab';import TrustTab from '../components/brain/tabs/TrustTab';import ConfigTab from '../components/brain/tabs/ConfigTab';@@ -52,6 +53,8 @@ export default function Brain() {return <LinksTab onRefresh={fetchData} />;case 'memory':return <MemoryTab onRefresh={fetchData} />;+ case 'graph':+ return <BrainGraph />;case 'digest':return <DigestTab onRefresh={fetchData} />;case 'trust':diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 66f9179515..ce1d788cb6 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1042,6 +1042,9 @@ export const cloneBrainLink = (id) => request(`/brain/links/${id}/clone`, { methexport const pullBrainLink = (id) => request(`/brain/links/${id}/pull`, { method: 'POST' });export const openBrainLinkFolder = (id) => request(`/brain/links/${id}/open-folder`, { method: 'POST' });+// Brain - Graph+export const getBrainGraph = () => request('/brain/graph');+// Media - Server media devicesexport const getMediaDevices = () => request('/media/devices');export const getMediaStatus = () => request('/media/status');diff --git a/server/routes/brain.js b/server/routes/brain.jsindex f0c793dbc0..cbc32c8782 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -32,6 +32,7 @@ import {linksQuerySchema} from '../lib/brainValidation.js';import * as githubCloner from '../services/githubCloner.js';+import { getBrainGraphData } from '../services/brainGraph.js';const router = Router();@@ -713,4 +714,17 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {res.json({ message: 'Folder opened', path: link.localPath });}));+// =============================================================================+// GRAPH+// =============================================================================++/**+ * GET /api/brain/graph+ * Get brain entity graph data for visualization+ */+router.get('/graph', asyncHandler(async (req, res) => {+ const data = await getBrainGraphData();+ res.json(data);+}));+export default router;diff --git a/server/services/brainGraph.js b/server/services/brainGraph.jsnew file mode 100644index 0000000000..8bbe4ecb40--- /dev/null+++ b/server/services/brainGraph.js@@ -0,0 +1,108 @@+/**+ * Brain Graph Data Service+ *+ * Computes a graph of brain entities with edges derived from:+ * - Semantic similarity (via CoS memory embeddings through the bridge)+ * - Shared tags (Jaccard similarity)+ * - Explicit CoS memory links (through the bridge)+ */++import * as brainStorage from './brainStorage.js';+import * as memoryBackend from './memoryBackend.js';+import { loadBridgeMap, bridgeKey } from './brainMemoryBridge.js';++const ENTITY_TYPES = ['people', 'projects', 'ideas', 'admin', 'memories'];++function jaccardSimilarity(tagsA, tagsB) {+ if (!tagsA?.length || !tagsB?.length) return 0;+ const setA = new Set(tagsA);+ const setB = new Set(tagsB);+ let intersection = 0;+ for (const t of setA) {+ if (setB.has(t)) intersection++;+ }+ const union = setA.size + setB.size - intersection;+ return union === 0 ? 0 : intersection / union;+}++export async function getBrainGraphData() {+ // 1. Load all brain entities, filter archived+ const nodes = [];+ for (const type of ENTITY_TYPES) {+ const records = await brainStorage.getAll(type);+ for (const record of records) {+ if (record.archived) continue;+ nodes.push({+ id: record.id,+ brainType: type,+ label: record.name || record.title || '(untitled)',+ summary: record.context || record.oneLiner || record.notes || record.content || '',+ tags: record.tags || [],+ importance: 0.6,+ status: record.status+ });+ }+ }++ if (!nodes.length) return { nodes: [], edges: [], hasEmbeddings: false };++ // 2. Load bridge map and build reverse map (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"+ }++ // 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();+ 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);+ hasEmbeddings = true;++ edges.push({+ source: brainSourceId,+ target: brainTargetId,+ type: edge.type === 'linked' ? 'linked' : 'similar',+ weight: edge.weight+ });+ }+ }++ // 4. Compute tag-based edges (Jaccard >= 0.3)+ for (let i = 0; i < nodes.length; i++) {+ for (let j = i + 1; j < nodes.length; j++) {+ 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 { nodes, edges, hasEmbeddings };+}diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 392a33f1e6..021773da41 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -38,7 +38,7 @@ const TYPE_MAP = {let bridgeMap = null;-async function loadBridgeMap() {+export async function loadBridgeMap() {if (bridgeMap) return bridgeMap;if (!existsSync(BRIDGE_MAP_PATH)) {bridgeMap = {};@@ -55,7 +55,7 @@ async function saveBridgeMap() {await writeFile(BRIDGE_MAP_PATH, JSON.stringify(bridgeMap, null, 2));}-function bridgeKey(brainType, brainId) {+export function bridgeKey(brainType, brainId) {return `${brainType}:${brainId}`;}@@ -118,7 +118,7 @@ function composeReviewContent(r) {return parts.join('\n');}-const CONTENT_COMPOSERS = {+export const CONTENT_COMPOSERS = {people: composePeopleContent,projects: composeProjectContent,ideas: composeIdeaContent,