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([issue-705]): CyberCity memory district — crystal clusters, light bridges, inbox well
[._.]/ Adam Eivy6bf08229b3ef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f6a3a17633..4c6e5a2fde 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -45,6 +45,7 @@- **[issue-824] CyberCity seasonal decorations** — the city now dresses itself for the time of year: a glowing ring of accent props and a banner that follow the current season, switching to a special palette during holiday windows like New Year, the winter holidays, spring bloom, midsummer, and Halloween. Pure atmosphere that turns over with the calendar.- **[issue-824] CyberCity easter eggs** — rare hidden emblems now appear in a quiet corner of the city when you hit a special condition — a developer's date, reaching a "leet" or famously-answered level, a palindrome best-streak, or a clean sweep with every goal completed. They're meant to be discovered, not announced, and disappear again when the condition passes.- **[issue-705] CyberCity earned artifacts** — a "Hall of Achievements" now appears east of downtown as a cluster of trophies on glowing pedestals — but only for milestones you've actually earned: leveling up your adventurer, completing life goals (your 1st, 5th, 10th), and building your best task-completion streak (3, 7, 30 days). Each trophy reads bronze, silver, or gold for how big the milestone is, and the whole cluster shimmers; nothing shows until you've earned your first, so the hall fills in as you make progress.+- **[issue-705] CyberCity memory district** — your long-term memory now crystallizes into a quiet quarter northwest of downtown: each memory category becomes a cluster of glowing crystals, taller and brighter the more (and more important) the memories it holds, and categories that link to each other arc together with light bridges — so the shape of how your knowledge connects is legible at a glance. A glowing well at the district's heart pulses with your Brain inbox backlog, brightening and beating faster the more captures are waiting to be sorted, and calming once the inbox is clear. The district stays hidden until you've recorded your first memory.## Changeddiff --git a/client/src/components/city/CityMemoryDistrict.jsx b/client/src/components/city/CityMemoryDistrict.jsxnew file mode 100644index 0000000000..e89c05342c--- /dev/null+++ b/client/src/components/city/CityMemoryDistrict.jsx@@ -0,0 +1,160 @@+import { useMemo, useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { Text, Line } from '@react-three/drei';+import { PIXEL_FONT_URL } from './cityConstants';+import { computeMemoryDistrict, MEMORY_DISTRICT } from '../../utils/cityMemoryDistrict';++// CyberCity's memory / knowledge district (roadmap 3.2): the user's long-term memory graph+// crystallizes into a quiet northwest quarter. Each memory *category* is a cluster of glowing+// octahedral crystals — taller and brighter the more (and more important) the memories — and+// edges that connect different categories arc between clusters as light bridges. A central+// "well" glows with the brain-inbox backlog: brighter and pulsing when captures are waiting to+// be classified, calm when the inbox is clear. Mirrors CityGoalMonuments / CityBackupVault:+// pure helper does all topology, this component only renders + animates.++// One category's crystal cluster: a small ring of octahedra of varying height around the+// cluster center, plus a category label. The tallest crystal carries the cluster's breathing+// glow (one per-frame ref mutation per cluster).+function CrystalCluster({ cluster, glowRef, isGlow }) {+ const { position, color, height, crystals, label, count, isOverflow } = cluster;+ // Arrange the crystals in a tight ring; the count is already capped in the helper.+ const ring = useMemo(() => {+ const out = [];+ for (let i = 0; i < crystals; i++) {+ const a = (i / crystals) * Math.PI * 2;+ const r = crystals === 1 ? 0 : MEMORY_DISTRICT.crystalSpacing;+ // Deterministic per-crystal height falloff so the cluster reads as a faceted shard pile.+ const h = height * (0.55 + 0.45 * Math.abs(Math.cos(a * 1.7 + i)));+ out.push({ x: Math.cos(a) * r, z: Math.sin(a) * r, h, tallest: false });+ }+ if (out.length) {+ // Tag the tallest so the breathing glow lands on a stable crystal.+ let max = 0;+ out.forEach((c, i) => { if (c.h > out[max].h) max = i; });+ out[max].tallest = true;+ }+ return out;+ }, [crystals, height]);++ return (+ <group position={position}>+ {ring.map((c, i) => (+ <mesh+ key={i}+ ref={isGlow && c.tallest ? glowRef : undefined}+ position={[c.x, c.h / 2 + 0.3, c.z]}+ >+ {/* Octahedron reads as a crystal shard */}+ <octahedronGeometry args={[0.5 + c.h * 0.12, 0]} />+ <meshStandardMaterial+ color={color}+ emissive={color}+ emissiveIntensity={isOverflow ? 0.4 : 0.7}+ metalness={0.3}+ roughness={0.15}+ transparent+ opacity={isOverflow ? 0.55 : 0.9}+ toneMapped={false}+ />+ </mesh>+ ))}+ <Text position={[0, height + 1.3, 0]} fontSize={0.6} color={color} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>+ {label}+ </Text>+ <Text position={[0, height + 0.7, 0]} fontSize={0.42} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>+ {count}+ </Text>+ </group>+ );+}++export default function CityMemoryDistrict({ memoryGraph, inboxDepth = 0, settings }) {+ const district = useMemo(() => computeMemoryDistrict(memoryGraph), [memoryGraph]);+ const glowRef = useRef();+ const wellRef = useRef();++ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ // The brightest (most important) cluster carries the breathing glow.+ const glowCategory = useMemo(() => {+ let best = null;+ for (const c of district.clusters) {+ if (!c.isOverflow && (!best || c.importance > best.importance)) best = c;+ }+ return best?.category ?? null;+ }, [district.clusters]);++ // Inbox well: glows brighter and pulses faster the deeper the unclassified backlog.+ const inboxActive = inboxDepth > 0;+ const wellColor = inboxActive ? '#06b6d4' : '#1e3a5f';++ useFrame(({ clock }) => {+ const t = clock.getElapsedTime();+ if (animate && glowRef.current) {+ const pulse = (Math.sin(t * 1.4) + 1) / 2;+ glowRef.current.material.emissiveIntensity = 0.7 + pulse * 0.6;+ }+ if (wellRef.current) {+ const base = inboxActive ? 0.6 + Math.min(inboxDepth, 10) * 0.06 : 0.25;+ const speed = inboxActive ? 2.5 + Math.min(inboxDepth, 10) * 0.2 : 0.7;+ const pulse = animate ? (Math.sin(t * speed) + 1) / 2 : 0.5;+ wellRef.current.material.emissiveIntensity = base + pulse * (inboxActive ? 0.7 : 0.15);+ }+ });++ if (district.empty) return null;++ const { base, clusters, bridges, totalMemories } = district;++ return (+ <group>+ {clusters.map((cluster) => (+ <CrystalCluster+ key={cluster.category}+ cluster={cluster}+ glowRef={glowRef}+ isGlow={cluster.category === glowCategory}+ />+ ))}++ {/* Light bridges between connected categories — thicker/brighter the stronger the link */}+ {bridges.map((bridge, i) => {+ const from = [bridge.fromPos[0], MEMORY_DISTRICT.bridgeY, bridge.fromPos[2]];+ const to = [bridge.toPos[0], MEMORY_DISTRICT.bridgeY, bridge.toPos[2]];+ // Arc the midpoint up so bridges read as light arcs, not flat lines.+ const mid = [(from[0] + to[0]) / 2, MEMORY_DISTRICT.bridgeY + 2 + Math.min(bridge.weight, 6) * 0.3, (from[2] + to[2]) / 2];+ return (+ <Line+ key={i}+ points={[from, mid, to]}+ color="#67e8f9"+ lineWidth={Math.min(1 + bridge.weight * 0.5, 4)}+ transparent+ opacity={Math.min(0.25 + bridge.weight * 0.12, 0.8)}+ />+ );+ })}++ {/* Brain-inbox well at the district center: a glowing ring whose intensity tracks backlog */}+ <group position={base}>+ <mesh ref={wellRef} position={[0, 0.1, 0]} rotation={[Math.PI / 2, 0, 0]}>+ <ringGeometry args={[1.4, 2.4, 32]} />+ <meshStandardMaterial color={wellColor} emissive={wellColor} emissiveIntensity={0.4} side={2} toneMapped={false} transparent opacity={0.85} />+ </mesh>+ {inboxActive && (+ <Text position={[0, 1.2, 0]} fontSize={0.5} color="#06b6d4" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>+ {`${inboxDepth} TO SORT`}+ </Text>+ )}+ </group>++ {/* District title */}+ <Text position={[base[0], 14, base[2] - 3]} fontSize={1.3} color="#8b5cf6" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>+ MEMORY+ </Text>+ <Text position={[base[0], 13, base[2] - 3]} fontSize={0.75} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={30}>+ {`${totalMemories} MEMORIES`}+ </Text>+ </group>+ );+}diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex 5122ec51f8..ee5a1ab9b9 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -26,6 +26,7 @@ import CityArtifacts from './CityArtifacts';import CitySeasonalDecor from './CitySeasonalDecor';import CityEasterEggs from './CityEasterEggs';import CityVoiceMarker from './CityVoiceMarker';+import CityMemoryDistrict from './CityMemoryDistrict';import CityAiCore from './CityAiCore';import CityDataRain from './CityDataRain';import CityNeonSigns from './CityNeonSigns';@@ -38,7 +39,7 @@ import CityEnergyOverlay from './CityEnergyOverlay';import PlayerController from './PlayerController';import CameraTransition from './CameraTransition';-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, settings, playSfx, keysRef, dimmedAppIds }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, memoryGraph, inboxDepth, settings, playSfx, keysRef, dimmedAppIds }) {const [positions, setPositions] = useState(null);const [proximityApp, setProximityApp] = useState(null);const [transitioning, setTransitioning] = useState(false);@@ -99,6 +100,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,<CitySeasonalDecor settings={settings} /><CityEasterEggs character={character} goals={goals} productivityData={productivityData} settings={settings} /><CityVoiceMarker voiceState={voiceState} settings={settings} />+ <CityMemoryDistrict memoryGraph={memoryGraph} inboxDepth={inboxDepth} settings={settings} /><CityAiCore aiActivity={aiActivity} positions={positions} apps={apps} settings={settings} /><CityGround settings={settings} />diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 52897bb89d..ded1112d0e 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -91,6 +91,21 @@ function CyberCityInner() {600_000,);+ // Long-term memory graph drives the knowledge district (crystal clusters + light bridges).+ // The graph changes slowly (new memories trickle in), so a 2-minute poll is plenty. Same+ // last-good-snapshot semantics as the fetches above.+ const { data: memoryGraph } = useAutoRefetch(+ () => api.getMemoryGraph({ silent: true }),+ 120_000,+ );++ // Brain-inbox backlog feeds the memory district's glowing well — `needs_review` is the count+ // of captures waiting for the user to sort. Lightweight; the well pulses harder as it grows.+ const { data: inboxData } = useAutoRefetch(+ () => api.getBrainInbox({ status: 'needs_review', limit: 1, silent: true }),+ 60_000,+ );+const handleBuildingClick = useCallback((app) => {if (app?.id) {navigate(`/apps/${app.id}`);@@ -139,6 +154,8 @@ function CyberCityInner() {goals={goalsData}character={character}chronotype={chronotypeData}+ memoryGraph={memoryGraph}+ inboxDepth={inboxData?.counts?.needs_review ?? 0}settings={settings}playSfx={playSfx}keysRef={keysRef}diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 2ba0b5bf4b..ddc5b0e67f 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -18,7 +18,10 @@ export const getBrainInbox = (options = {}) => {if (options.status) params.set('status', options.status);if (options.limit) params.set('limit', options.limit);if (options.offset) params.set('offset', options.offset);- return request(`/brain/inbox?${params}`);+ // Forward request-level options (e.g. { silent: true }) so background pollers can opt out+ // of the default error toast. `silent` is the only request-level flag the helper reads;+ // the rest of `options` is query params handled above.+ return request(`/brain/inbox?${params}`, { silent: options.silent });};export const getBrainInboxEntry = (id) => request(`/brain/inbox/${id}`);export const resolveBrainReview = (inboxLogId, destination, editedExtracted) => request('/brain/review/resolve', {diff --git a/client/src/services/apiMemory.js b/client/src/services/apiMemory.jsindex 7e77124ce3..0b78912ef7 100644--- a/client/src/services/apiMemory.js+++ b/client/src/services/apiMemory.js@@ -38,7 +38,7 @@ export const getMemoryTimeline = (options = {}) => {if (options.limit) params.set('limit', options.limit);return request(`/memory/timeline?${params}`);};-export const getMemoryGraph = () => request('/memory/graph');+export const getMemoryGraph = (options = {}) => request('/memory/graph', options);export const getMemoryStats = () => request('/memory/stats');export const getRelatedMemories = (id, limit = 10) => request(`/memory/${id}/related?limit=${limit}`);export const linkMemories = (sourceId, targetId) => request('/memory/link', {diff --git a/client/src/utils/cityMemoryDistrict.js b/client/src/utils/cityMemoryDistrict.jsnew file mode 100644index 0000000000..91c5ee3cab--- /dev/null+++ b/client/src/utils/cityMemoryDistrict.js@@ -0,0 +1,173 @@+// Pure, deterministic helpers for CyberCity's memory / knowledge district (roadmap 3.2):+// a quiet quarter in the northwest where the user's long-term memory graph crystallizes+// into the city. Each memory *category* becomes a cluster of glowing crystals — taller and+// brighter the more (and more important) the memories it holds — and edges that cross+// category boundaries arc between clusters as light bridges, so the shape of how knowledge+// connects is legible at a glance. No three.js / React imports so the topology is+// unit-testable (mirrors cityFederation.js / cityBackupVault.js).++import { hashString } from './hashString';++export const MEMORY_DISTRICT = {+ // Northwest quadrant — mirrors the artifact cluster at NE (+44,-28), clear of the+ // productivity district (SW, -48,+28), the backup vault (W, -34,-10), and downtown.+ base: [-44, 0, -30],+ radius: 9, // clusters arrange on a ring of this radius around the district center+ maxCrystalsPerCluster: 7, // visual cap; overflow is summarized in the cluster label+ crystalSpacing: 1.4, // horizontal spread of crystals within a cluster+ minCrystalHeight: 1.2,+ maxCrystalHeight: 4.5,+ bridgeY: 2.2, // height the light bridges arc at+ maxClusters: 8, // most-populous categories rendered; the rest fold into "OTHER"+};++// Per-category crystal color. Reuses the PortOS neon palette feel; unknown/uncategorized+// memories fall back to slate so an unclassified cluster still reads as present-but-quiet.+const CATEGORY_COLORS = {+ personal: '#ec4899', // pink+ work: '#3b82f6', // port-accent blue+ technical: '#06b6d4', // cyan+ health: '#22c55e', // port-success green+ finance: '#f59e0b', // port-warning amber+ relationships: '#f43f5e', // rose+ preferences: '#a855f7', // violet+ ideas: '#8b5cf6', // purple+ other: '#64748b', // slate — fallback+};++// Deterministic color for any category string: known categories map to their token, unknown+// ones hash into the neon palette so two distinct unknown categories still look distinct.+const PALETTE = ['#ec4899', '#3b82f6', '#06b6d4', '#22c55e', '#f59e0b', '#f43f5e', '#a855f7', '#8b5cf6'];+export function categoryColor(category) {+ const key = String(category || 'other').toLowerCase();+ if (CATEGORY_COLORS[key]) return CATEGORY_COLORS[key];+ return PALETTE[hashString(key) % PALETTE.length];+}++// Normalize a raw graph node's category to a stable, lowercase bucket key. Missing/blank →+// 'other' so uncategorized memories collect into one cluster instead of vanishing.+export function categoryKey(node) {+ const raw = node?.category;+ if (typeof raw !== 'string' || raw.trim() === '') return 'other';+ return raw.trim().toLowerCase();+}++// Group graph nodes into per-category buckets, each carrying a node count and a summed+// importance (importance defaults to 1 when absent so every memory contributes some mass).+// Returns buckets sorted by count desc, then category asc for a stable order.+export function groupByCategory(nodes) {+ const buckets = new Map();+ for (const node of Array.isArray(nodes) ? nodes : []) {+ const key = categoryKey(node);+ const entry = buckets.get(key) || { category: key, count: 0, importance: 0 };+ entry.count += 1;+ entry.importance += Number.isFinite(node?.importance) ? node.importance : 1;+ buckets.set(key, entry);+ }+ return [...buckets.values()].sort((a, b) => b.count - a.count || a.category.localeCompare(b.category));+}++// Place a cluster on the district ring. Angle is seeded by the category name (not the index)+// so a category keeps its spot as the graph grows, and index is a stable tiebreaker fan-out+// so two categories hashing near the same angle still separate.+export function placeCluster(category, index, total, opts = {}) {+ const base = opts.base || MEMORY_DISTRICT.base;+ const radius = opts.radius ?? MEMORY_DISTRICT.radius;+ const hashAngle = (hashString(category) % 360) * (Math.PI / 180);+ const fan = total > 0 ? (index / total) * Math.PI * 2 : 0;+ // Blend the hash angle with an even fan so clusters neither overlap nor drift on regrouping.+ const angle = hashAngle * 0.5 + fan * 0.5;+ return [+ base[0] + Math.cos(angle) * radius,+ base[1],+ base[2] + Math.sin(angle) * radius,+ ];+}++// Crystal height scales with the cluster's total importance, clamped to the configured band so+// a huge category doesn't dwarf the skyline and a tiny one is still visible.+export function clusterHeight(importance) {+ const { minCrystalHeight, maxCrystalHeight } = MEMORY_DISTRICT;+ const scaled = minCrystalHeight + Math.log2(1 + Math.max(0, importance)) * 0.7;+ return Math.min(maxCrystalHeight, Math.max(minCrystalHeight, scaled));+}++// Build the bridges between category clusters from the graph's cross-category edges. Each edge+// whose endpoints live in different categories increments that category-pair's weight; the+// result is a deduped, sorted list of { from, to, weight, count } the renderer arcs as light.+// `linked` edges count double vs `similar` so explicit links read as stronger connective tissue.+export function computeBridges(nodes, edges) {+ const catOf = new Map();+ for (const node of Array.isArray(nodes) ? nodes : []) {+ catOf.set(node?.id, categoryKey(node));+ }+ const pairs = new Map();+ for (const edge of Array.isArray(edges) ? edges : []) {+ const a = catOf.get(edge?.source);+ const b = catOf.get(edge?.target);+ if (!a || !b || a === b) continue; // intra-cluster edges don't bridge+ const [from, to] = a < b ? [a, b] : [b, a];+ const key = `${from}|${to}`;+ const w = edge?.type === 'linked' ? 2 : 1;+ const entry = pairs.get(key) || { from, to, weight: 0, count: 0 };+ entry.weight += w;+ entry.count += 1;+ pairs.set(key, entry);+ }+ return [...pairs.values()].sort((a, b) => b.weight - a.weight || a.from.localeCompare(b.from));+}++// Full derived view-model for the component: positioned clusters (capped at maxClusters with the+// overflow folded into a single 'other'-style summary) plus the light bridges between them. Pure+// and deterministic — same graph in, same scene out — so the whole thing is testable headless.+export function computeMemoryDistrict(graph, opts = {}) {+ const nodes = Array.isArray(graph?.nodes) ? graph.nodes : [];+ const edges = Array.isArray(graph?.edges) ? graph.edges : [];+ const maxClusters = opts.maxClusters ?? MEMORY_DISTRICT.maxClusters;++ const grouped = groupByCategory(nodes);++ // Fold the long tail of small categories into one "+N more" overflow cluster so the district+ // stays readable; its mass is the sum of what it absorbs.+ let clustersData = grouped;+ let overflow = null;+ if (grouped.length > maxClusters) {+ clustersData = grouped.slice(0, maxClusters - 1);+ const rest = grouped.slice(maxClusters - 1);+ overflow = {+ category: 'other',+ count: rest.reduce((s, c) => s + c.count, 0),+ importance: rest.reduce((s, c) => s + c.importance, 0),+ overflowOf: rest.length,+ };+ clustersData = [...clustersData, overflow];+ }++ const total = clustersData.length;+ const clusters = clustersData.map((c, i) => ({+ category: c.category,+ label: c.overflowOf ? `+${c.overflowOf} MORE` : c.category.toUpperCase(),+ count: c.count,+ importance: c.importance,+ color: categoryColor(c.category),+ position: placeCluster(c.category, i, total, opts),+ height: clusterHeight(c.importance),+ crystals: Math.min(MEMORY_DISTRICT.maxCrystalsPerCluster, Math.max(1, c.count)),+ isOverflow: !!c.overflowOf,+ }));++ // Bridges reference category keys; resolve them to cluster positions, dropping any whose+ // endpoint folded into overflow (those edges are summarized away rather than mis-drawn).+ const posByCategory = new Map(clusters.map(c => [c.category, c.position]));+ const bridges = computeBridges(nodes, edges)+ .map(b => ({ ...b, fromPos: posByCategory.get(b.from), toPos: posByCategory.get(b.to) }))+ .filter(b => b.fromPos && b.toPos);++ return {+ base: opts.base || MEMORY_DISTRICT.base,+ clusters,+ bridges,+ totalMemories: nodes.length,+ empty: nodes.length === 0,+ };+}diff --git a/client/src/utils/cityMemoryDistrict.test.js b/client/src/utils/cityMemoryDistrict.test.jsnew file mode 100644index 0000000000..ef7a1c9d9f--- /dev/null+++ b/client/src/utils/cityMemoryDistrict.test.js@@ -0,0 +1,171 @@+import { describe, it, expect } from 'vitest';+import {+ MEMORY_DISTRICT,+ categoryColor,+ categoryKey,+ groupByCategory,+ placeCluster,+ clusterHeight,+ computeBridges,+ computeMemoryDistrict,+} from './cityMemoryDistrict';++describe('categoryKey', () => {+ it('lowercases and trims a category', () => {+ expect(categoryKey({ category: ' Work ' })).toBe('work');+ });+ it('falls back to "other" for missing/blank categories', () => {+ expect(categoryKey({})).toBe('other');+ expect(categoryKey({ category: ' ' })).toBe('other');+ expect(categoryKey(null)).toBe('other');+ });+});++describe('categoryColor', () => {+ it('maps known categories to their token color', () => {+ expect(categoryColor('work')).toBe('#3b82f6');+ expect(categoryColor('Health')).toBe('#22c55e'); // case-insensitive+ });+ it('is deterministic for unknown categories', () => {+ expect(categoryColor('quokkas')).toBe(categoryColor('quokkas'));+ });+});++describe('groupByCategory', () => {+ it('counts nodes and sums importance per category', () => {+ const nodes = [+ { id: 'a', category: 'work', importance: 3 },+ { id: 'b', category: 'work', importance: 2 },+ { id: 'c', category: 'health', importance: 5 },+ ];+ const grouped = groupByCategory(nodes);+ expect(grouped[0]).toMatchObject({ category: 'work', count: 2, importance: 5 });+ expect(grouped[1]).toMatchObject({ category: 'health', count: 1, importance: 5 });+ });+ it('defaults importance to 1 when absent', () => {+ const grouped = groupByCategory([{ id: 'a', category: 'x' }, { id: 'b', category: 'x' }]);+ expect(grouped[0].importance).toBe(2);+ });+ it('sorts by count desc then category asc', () => {+ const nodes = [+ { id: '1', category: 'zeta' },+ { id: '2', category: 'alpha' },+ { id: '3', category: 'alpha' },+ { id: '4', category: 'beta' },+ ];+ expect(groupByCategory(nodes).map(g => g.category)).toEqual(['alpha', 'beta', 'zeta']);+ });+ it('handles non-array input', () => {+ expect(groupByCategory(undefined)).toEqual([]);+ });+});++describe('placeCluster', () => {+ it('is deterministic for the same category regardless of fan index span', () => {+ const a = placeCluster('work', 1, 4);+ const b = placeCluster('work', 1, 4);+ expect(a).toEqual(b);+ });+ it('places the cluster near the district ring radius from the base', () => {+ const base = MEMORY_DISTRICT.base;+ const [x, , z] = placeCluster('work', 0, 3);+ const r = Math.hypot(x - base[0], z - base[2]);+ expect(r).toBeCloseTo(MEMORY_DISTRICT.radius, 5);+ });+ it('gives different categories different positions', () => {+ expect(placeCluster('aaa', 0, 3)).not.toEqual(placeCluster('zzz', 1, 3));+ });+});++describe('clusterHeight', () => {+ it('clamps to the configured band', () => {+ expect(clusterHeight(0)).toBeGreaterThanOrEqual(MEMORY_DISTRICT.minCrystalHeight);+ expect(clusterHeight(1e9)).toBeLessThanOrEqual(MEMORY_DISTRICT.maxCrystalHeight);+ });+ it('grows monotonically with importance', () => {+ expect(clusterHeight(10)).toBeGreaterThan(clusterHeight(2));+ });+});++describe('computeBridges', () => {+ const nodes = [+ { id: 'a', category: 'work' },+ { id: 'b', category: 'health' },+ { id: 'c', category: 'work' },+ ];+ it('only bridges cross-category edges', () => {+ const edges = [+ { source: 'a', target: 'c', type: 'similar' }, // intra-category → skipped+ { source: 'a', target: 'b', type: 'similar' }, // cross → bridge+ ];+ const bridges = computeBridges(nodes, edges);+ expect(bridges).toHaveLength(1);+ expect(bridges[0]).toMatchObject({ from: 'health', to: 'work', count: 1 });+ });+ it('weights linked edges double vs similar', () => {+ const linked = computeBridges(nodes, [{ source: 'a', target: 'b', type: 'linked' }]);+ const similar = computeBridges(nodes, [{ source: 'a', target: 'b', type: 'similar' }]);+ expect(linked[0].weight).toBe(2 * similar[0].weight);+ });+ it('aggregates multiple edges between the same category pair', () => {+ const edges = [+ { source: 'a', target: 'b', type: 'similar' },+ { source: 'c', target: 'b', type: 'similar' },+ ];+ const bridges = computeBridges(nodes, edges);+ expect(bridges).toHaveLength(1);+ expect(bridges[0].count).toBe(2);+ });+ it('handles missing edges/nodes gracefully', () => {+ expect(computeBridges(undefined, undefined)).toEqual([]);+ expect(computeBridges(nodes, [{ source: 'a', target: 'missing' }])).toEqual([]);+ });+});++describe('computeMemoryDistrict', () => {+ it('marks empty when there are no nodes', () => {+ const d = computeMemoryDistrict({ nodes: [], edges: [] });+ expect(d.empty).toBe(true);+ expect(d.clusters).toEqual([]);+ expect(d.totalMemories).toBe(0);+ });+ it('handles undefined graph', () => {+ expect(computeMemoryDistrict(undefined).empty).toBe(true);+ });+ it('builds one cluster per category with positions and labels', () => {+ const graph = {+ nodes: [+ { id: 'a', category: 'work', importance: 3 },+ { id: 'b', category: 'health', importance: 1 },+ ],+ edges: [{ source: 'a', target: 'b', type: 'linked' }],+ };+ const d = computeMemoryDistrict(graph);+ expect(d.clusters).toHaveLength(2);+ expect(d.clusters.map(c => c.label)).toContain('WORK');+ expect(d.totalMemories).toBe(2);+ expect(d.bridges).toHaveLength(1);+ expect(d.bridges[0].fromPos).toBeDefined();+ expect(d.bridges[0].toPos).toBeDefined();+ });+ it('folds the long tail into a single overflow cluster', () => {+ const nodes = [];+ for (let i = 0; i < 12; i++) nodes.push({ id: `n${i}`, category: `cat${i}` });+ const d = computeMemoryDistrict({ nodes, edges: [] }, { maxClusters: 5 });+ expect(d.clusters).toHaveLength(5);+ const overflow = d.clusters.find(c => c.isOverflow);+ expect(overflow).toBeDefined();+ expect(overflow.label).toMatch(/MORE/);+ });+ it('drops bridges whose endpoint folded into overflow', () => {+ const nodes = [];+ for (let i = 0; i < 12; i++) nodes.push({ id: `n${i}`, category: `cat${i}` });+ // edge between two rare categories that both fold away+ const d = computeMemoryDistrict(+ { nodes, edges: [{ source: 'n10', target: 'n11', type: 'linked' }] },+ { maxClusters: 5 },+ );+ // n10/n11's categories aren't rendered as their own clusters → bridge dropped+ expect(d.bridges.every(b => b.fromPos && b.toPos)).toBe(true);+ });+});