Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(brain): knowledge mind map of everything Mercury knows
Salman Qureshi2d04d3de7743
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.jsonindex baa4022e..d8d86cac 100644--- a/apps/desktop/package-lock.json+++ b/apps/desktop/package-lock.json@@ -28,6 +28,7 @@"@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1","d3-force": "^3.0.0",+ "d3-hierarchy": "^3.1.2","force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1",@@ -40,6 +41,7 @@"devDependencies": {"@tauri-apps/cli": "^2.12.4","@types/d3-force": "^3.0.10",+ "@types/d3-hierarchy": "^3.1.7","@types/react": "^18.3.28","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.5.2",@@ -2410,6 +2412,13 @@"dev": true,"license": "MIT"},+ "node_modules/@types/d3-hierarchy": {+ "version": "3.1.7",+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/debug": {"version": "4.1.13","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",@@ -3148,6 +3157,15 @@"node": ">=12"}},+ "node_modules/d3-hierarchy": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-interpolate": {"version": "3.0.1","resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 51e86e9e..eaa3363f 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -35,6 +35,7 @@"@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1","d3-force": "^3.0.0",+ "d3-hierarchy": "^3.1.2","force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1",@@ -47,6 +48,7 @@"devDependencies": {"@tauri-apps/cli": "^2.12.4","@types/d3-force": "^3.0.10",+ "@types/d3-hierarchy": "^3.1.7","@types/react": "^18.3.28","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.5.2",diff --git a/apps/desktop/src/api/brain.ts b/apps/desktop/src/api/brain.tsindex b87376dc..980c6981 100644--- a/apps/desktop/src/api/brain.ts+++ b/apps/desktop/src/api/brain.ts@@ -67,6 +67,17 @@ export interface BrainGraphData {available: boolean;}+/** The knowledge map (GET /api/brain/map): themes → sub-themes → notes, with sparse "related" links. */+export interface BrainMap {+ themes: Array<{ id: string; label: string; terms: string[]; parent: string | null; size: number }>;+ /** note id → the theme (or sub-theme) it sits in. */+ placement: Record<string, string>;+ links: Array<{ a: string; b: string; w: number }>;+ notes: Array<{ id: string; text: string; kind: string; at: number; confidence: number; archived: boolean }>;+ stats: { notes: number; links: number; themes: number; ms: number };+ available: boolean;+}+export interface CheckStatus {enabled: boolean;pending: number;@@ -118,6 +129,7 @@ export const brain = {runCheck: () => http.post<{ checked: number; status: CheckStatus }>("/api/brain/persons/checks/run"),queueExisting: () => http.post<{ queued: number; status: CheckStatus | null }>("/api/brain/persons/checks/queue-existing"),+ map: (archive = false) => http.get<BrainMap>(`/api/brain/map${archive ? "?archive=1" : ""}`),graph: (memories = 300, shadows = false) => http.get<BrainGraphData>(`/api/brain/graph/v2?memories=${memories}${shadows ? "&shadows=1" : ""}`),relations: () => http.get<{ relations: Array<{ label: string; cardinality: "one" | "many" }> }>("/api/brain/relations"),};diff --git a/apps/desktop/src/views/brain/BrainGraph.tsx b/apps/desktop/src/views/brain/BrainGraph.tsxindex ffdddb01..7a6f0cee 100644--- a/apps/desktop/src/views/brain/BrainGraph.tsx+++ b/apps/desktop/src/views/brain/BrainGraph.tsx@@ -1,4 +1,4 @@-import { Maximize2, Minus, Plus, RefreshCw, RotateCcw, Search } from "lucide-react";+import { RefreshCw, Search } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type ForceGraph from "force-graph";import type { LinkObject, NodeObject } from "force-graph";@@ -10,6 +10,7 @@ import { Switch } from "~/components/ui/Switch";import { Tooltip } from "~/components/ui/Tooltip";import { useTheme } from "~/app/theme";import { cx } from "~/lib/cx";+import { ZoomPanel, zoomKeys } from "./ZoomPanel";/*** The brain as a living graph, Obsidian-style.@@ -226,20 +227,12 @@ export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean// Keyboard: + / - / 0 zoom while the graph is on screen.useEffect(() => {if (!visible) return;- const onKey = (e: KeyboardEvent) => {- const t = e.target as HTMLElement | null;- if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;- if (e.metaKey || e.ctrlKey || e.altKey) return;- if (e.key === "+" || e.key === "=") zoomBy(1.4);- else if (e.key === "-") zoomBy(1 / 1.4);- else if (e.key === "0") graph.current?.zoomToFit(500, 80);- };+ const onKey = zoomKeys(zoomBy, () => graph.current?.zoomToFit(500, 80));window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, [visible]);const counts = data ? { people: data.persons.length, memories: data.memories.length, links: data.memoryPersons.length + data.relationships.length } : null;- const ctl = "flex h-8 w-8 items-center justify-center rounded-lg text-ink2 hover:bg-ink/[0.07] hover:text-ink";return (<div className="relative h-full w-full overflow-hidden">@@ -266,15 +259,7 @@ export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean</Tooltip></div>- {/* Zoom controls, bottom right like a map. */}- <div className="absolute bottom-3 right-4 flex flex-col items-center gap-1 rounded-xl border border-line bg-surface/90 p-1 shadow-sm backdrop-blur">- <Tooltip label="Zoom in" shortcut="+" side="left"><button onClick={() => zoomBy(1.4)} className={ctl} aria-label="Zoom in"><Plus size={15} /></button></Tooltip>- <span className="font-mono text-2xs text-ink4">{zoomPct}%</span>- <Tooltip label="Zoom out" shortcut="−" side="left"><button onClick={() => zoomBy(1 / 1.4)} className={ctl} aria-label="Zoom out"><Minus size={15} /></button></Tooltip>- <div className="my-0.5 h-px w-6 bg-line" />- <Tooltip label="Fit to screen" shortcut="0" side="left"><button onClick={() => graph.current?.zoomToFit(500, 80)} className={ctl} aria-label="Fit to screen"><Maximize2 size={14} /></button></Tooltip>- <Tooltip label="Reset layout (unpin everything)" side="left"><button onClick={resetLayout} className={ctl} aria-label="Reset layout"><RotateCcw size={14} /></button></Tooltip>- </div>+ <ZoomPanel zoomPct={zoomPct} onZoom={zoomBy} onFit={() => graph.current?.zoomToFit(500, 80)} onReset={resetLayout} />{!data && !error && <div className="absolute inset-0 flex items-center justify-center text-ink3"><Spinner size={20} /></div>}{error && <div className="absolute inset-0 flex items-center justify-center p-8 text-center text-sm text-ink3">Couldn't load the brain: {error}</div>}diff --git a/apps/desktop/src/views/brain/BrainView.tsx b/apps/desktop/src/views/brain/BrainView.tsxindex 96a858d2..dff09eb7 100644--- a/apps/desktop/src/views/brain/BrainView.tsx+++ b/apps/desktop/src/views/brain/BrainView.tsx@@ -6,21 +6,23 @@ import { Badge, Segmented, Spinner } from "~/components/ui/bits";import { PageHeader } from "~/components/ui/kit";import { BrainGraph, type SelectableKind } from "./BrainGraph";import { Memories } from "./Memories";+import { MindMap } from "./MindMap";import { People } from "./People";import { PersonCard } from "./PersonCard";-type Tab = "graph" | "memories" | "people";+type Tab = "map" | "graph" | "memories" | "people";const TAB_KEY = "mercury.brain.tab";/**- * The second brain: a living graph, the memories, and the people. Each tab- * loads its data only when first opened; the graph pauses while hidden;- * each part is behind its own crash boundary.+ * The second brain: a mind map of everything known, a living graph of+ * people, the memories, and the people. Each tab loads its data only when+ * first opened; canvases pause while hidden; each part is behind its own+ * crash boundary.*/export function BrainView() {const view = useUi((s) => s.view);- const [tab, setTab] = useState<Tab>(() => { try { return (sessionStorage.getItem(TAB_KEY) as Tab) || "graph"; } catch { return "graph"; } });- const [opened, setOpened] = useState<Record<Tab, boolean>>({ graph: false, memories: false, people: false });+ const [tab, setTab] = useState<Tab>(() => { try { return (sessionStorage.getItem(TAB_KEY) as Tab) || "map"; } catch { return "map"; } });+ const [opened, setOpened] = useState<Record<Tab, boolean>>({ map: false, graph: false, memories: false, people: false });const [selected, setSelected] = useState<{ id: string; kind: SelectableKind } | null>(null);const [people, setPeople] = useState<BrainPerson[]>([]);const visible = view === "brain";@@ -33,16 +35,25 @@ export function BrainView() {return (<div className="flex h-full min-h-0 flex-col"><PageHeader title="Brain">- <Segmented size="md" value={tab} onChange={setTab} options={[{ value: "graph", label: "Graph" }, { value: "memories", label: "Memories" }, { value: "people", label: "People" }]} />+ <Segmented size="md" value={tab} onChange={setTab} options={[{ value: "map", label: "Map" }, { value: "graph", label: "Graph" }, { value: "memories", label: "Memories" }, { value: "people", label: "People" }]} /></PageHeader><div className="relative min-h-0 flex-1">- <div className={tab === "graph" ? "absolute inset-0 flex" : "hidden"}>+ <div className={tab === "map" || tab === "graph" ? "absolute inset-0 flex" : "hidden"}><div className="relative min-w-0 flex-1">- {opened.graph && (- <ErrorBoundary label="The graph" resetKey={tab}>- <BrainGraph visible={visible && tab === "graph"} selectedId={selected?.id ?? null} onSelect={setSelected} />- </ErrorBoundary>- )}+ <div className={tab === "map" ? "absolute inset-0" : "hidden"}>+ {opened.map && (+ <ErrorBoundary label="The map" resetKey={tab}>+ <MindMap visible={visible && tab === "map"} selectedId={selected?.id ?? null} onSelect={setSelected} />+ </ErrorBoundary>+ )}+ </div>+ <div className={tab === "graph" ? "absolute inset-0" : "hidden"}>+ {opened.graph && (+ <ErrorBoundary label="The graph" resetKey={tab}>+ <BrainGraph visible={visible && tab === "graph"} selectedId={selected?.id ?? null} onSelect={setSelected} />+ </ErrorBoundary>+ )}+ </div></div>{selected && selected.kind !== "you" && (<aside className="w-[380px] shrink-0 overflow-y-auto border-l border-line bg-soft">diff --git a/apps/desktop/src/views/brain/MindMap.test.ts b/apps/desktop/src/views/brain/MindMap.test.tsnew file mode 100644index 00000000..a1773ad6--- /dev/null+++ b/apps/desktop/src/views/brain/MindMap.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import type { BrainMap } from "~/api/brain";+import { toMindMap } from "./MindMap";++const map: BrainMap = {+ themes: [+ { id: "t1", label: "Garden · Tomatoes", terms: [], parent: null, size: 3 },+ { id: "t2", label: "Rust · CLI", terms: [], parent: null, size: 4 },+ { id: "t2.a", label: "Cargo", terms: [], parent: "t2", size: 2 },+ { id: "t2.b", label: "Ownership", terms: [], parent: "t2", size: 2 },+ { id: "loose", label: "Loose notes", terms: [], parent: null, size: 1 },+ ],+ placement: { g1: "t1", g2: "t1", g3: "t1", r1: "t2.a", r2: "t2.a", r3: "t2.b", r4: "t2.b", x: "loose" },+ links: [{ a: "g1", b: "g2", w: 0.5 }, { a: "r1", b: "r2", w: 0.4 }],+ notes: ["g1", "g2", "g3", "r1", "r2", "r3", "r4", "x"].map((id, i) => ({ id, text: `note ${id}`, kind: "fact", at: i, confidence: 0.8, archived: false })),+ stats: { notes: 8, links: 2, themes: 2, ms: 1 },+ available: true,+};++describe("toMindMap", () => {+ it("builds you → themes → sub-themes → notes", () => {+ const { nodes, links } = toMindMap(map);+ const kind = (id: string) => nodes.find((n) => n.id === id)?.kind;+ expect(kind("you")).toBe("you");+ expect(kind("t1")).toBe("theme");+ expect(kind("t2.a")).toBe("sub");+ expect(kind("r1")).toBe("note");+ expect(nodes.find((n) => n.id === "r1")?.parent).toBe("t2.a");+ expect(nodes.find((n) => n.id === "g1")?.parent).toBe("t1");+ expect(links.length).toBe(nodes.length - 1);+ });++ it("puts notes on the outer ring and themes inside it", () => {+ const { nodes } = toMindMap(map);+ const r = (id: string) => { const n = nodes.find((x) => x.id === id)!; return Math.hypot(n.tx, n.ty); };+ expect(r("you")).toBe(0);+ expect(r("t1")).toBeLessThan(r("t2.a"));+ expect(r("t2.a")).toBeLessThan(r("r1"));+ expect(Math.abs(r("g1") - r("r4"))).toBeLessThan(1e-6);+ });++ it("colours a branch with its theme and keeps loose notes grey, last", () => {+ const { nodes } = toMindMap(map);+ const c = (id: string) => nodes.find((n) => n.id === id)!.color;+ expect(c("r1")).toBe(c("t2"));+ expect(c("t1")).not.toBe(c("t2"));+ expect(c("x")).toBe("#8A97A3");+ expect(nodes.filter((n) => n.kind === "theme").at(-1)?.id).toBe("loose");+ });++ it("indexes related notes both ways, strongest first", () => {+ const { related } = toMindMap(map);+ expect(related.get("g2")?.[0][0]).toBe("g1");+ expect(related.get("r1")?.[0]).toEqual(["r2", 0.4]);+ });+});diff --git a/apps/desktop/src/views/brain/MindMap.tsx b/apps/desktop/src/views/brain/MindMap.tsxnew file mode 100644index 00000000..f2fd39c9--- /dev/null+++ b/apps/desktop/src/views/brain/MindMap.tsx@@ -0,0 +1,703 @@+import { ChevronRight, RefreshCw, Search } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type ForceGraph from "force-graph";+import type { LinkObject, NodeObject } from "force-graph";+import { forceCollide, forceX, forceY } from "d3-force";+import { cluster, hierarchy } from "d3-hierarchy";+import { brain, type BrainMap } from "~/api/brain";+import { Button } from "~/components/ui/Button";+import { Segmented, Spinner } from "~/components/ui/bits";+import { Switch } from "~/components/ui/Switch";+import { Tooltip } from "~/components/ui/Tooltip";+import { useTheme } from "~/app/theme";+import { cx } from "~/lib/cx";+import { ZoomPanel, zoomKeys } from "./ZoomPanel";++/**+ * Everything Mercury knows, as a mind map: You → themes → sub-themes →+ * notes, laid out radially (d3-hierarchy cluster) and kept alive by+ * force-graph, so it flows from a random start into place and stays fluid+ * under the pointer. Themes and links come from the runtime+ * (knowledge-map.ts: BM25 + mutual-kNN + Louvain + c-TF-IDF, no model).+ *+ * Only the tree is physics. "Related" links (notes saying similar things)+ * are drawn on top, for the note under the pointer, or all of them, faint,+ * with "Links" on, so the map never turns into a hairball. Click a theme to+ * focus its branch; drag anything to pin it until "Reset layout". Outline+ * shows the same tree as a list.+ */++type Kind = "you" | "theme" | "sub" | "note";++export interface MapNode extends NodeObject {+ id: string;+ kind: Kind;+ label: string;+ /** Top-level theme this node belongs to ("" for you). */+ theme: string;+ /** Parent node id in the tree. */+ parent: string | null;+ color: string;+ size: number;+ /** Where the mind map wants it (radial target). */+ tx: number;+ ty: number;+ noteKind?: string;+ loose?: boolean;+}++interface MapLink extends LinkObject<MapNode> {+ kind: "tree";+ length: number;+}++const PINS_KEY = "mercury.brain.map.pins.v1";+const LOOSE = "loose";+/** Twelve hues that read on light and dark; a theme keeps its hue while its id lives. */+const HUES = ["#5B8DEF", "#E0739B", "#3FB37F", "#D4A72C", "#9B7BD8", "#E8894A", "#2BB5C9", "#C9644F", "#7AA33B", "#B565C9", "#4F9AA8", "#D08A2E"];+const KIND_LABEL: Record<string, string> = {+ fact: "Fact", preference: "Preference", trait: "Trait", situation: "Situation", relationship: "Relationship", goal: "Goal", project: "Project",+ episode: "Moment", identity: "Identity", habit: "Habit", decision: "Decision", constraint: "Constraint", reflection: "Reflection",+};++function hash(s: string): number {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }+ return h >>> 0;+}++/** Stable colours: each theme hashes to a hue; clashes step to the next free one. */+function themeColors(ids: string[]): Map<string, string> {+ const out = new Map<string, string>();+ const used = new Set<number>();+ for (const id of ids) {+ if (id === LOOSE) { out.set(id, "#8A97A3"); continue; }+ let i = hash(id) % HUES.length;+ for (let k = 0; k < HUES.length && used.has(i); k++) i = (i + 1) % HUES.length;+ used.add(i);+ if (used.size === HUES.length) used.clear();+ out.set(id, HUES[i]);+ }+ return out;+}++/** The map as a tree with radial targets. Pure, for tests. */+export function toMindMap(m: BrainMap): { nodes: MapNode[]; links: MapLink[]; related: Map<string, Array<[string, number]>> } {+ const tops = m.themes.filter((t) => !t.parent).sort((a, b) => (a.id === LOOSE ? 1 : b.id === LOOSE ? -1 : b.size - a.size));+ const subsOf = new Map<string, typeof m.themes>();+ for (const t of m.themes) if (t.parent) subsOf.set(t.parent, [...(subsOf.get(t.parent) ?? []), t]);+ const notesIn = new Map<string, BrainMap["notes"]>();+ for (const n of m.notes) {+ const at = m.placement[n.id];+ if (!at) continue;+ notesIn.set(at, [...(notesIn.get(at) ?? []), n]);+ }+ const colors = themeColors(tops.map((t) => t.id));++ type T = { id: string; children?: T[] };+ const tree: T = {+ id: "you",+ children: tops.map((t) => {+ const subs = (subsOf.get(t.id) ?? []).sort((a, b) => b.size - a.size);+ const leaves = (id: string) => (notesIn.get(id) ?? []).sort((a, b) => a.kind.localeCompare(b.kind) || b.at - a.at).map((n) => ({ id: n.id }));+ return { id: t.id, children: subs.length ? subs.map((s) => ({ id: s.id, children: leaves(s.id) })) : leaves(t.id) };+ }),+ };+ const noteCount = m.notes.length;+ // Ring big enough for every note to have a few pixels of arc.+ const R = Math.max(240, (noteCount * 9) / (2 * Math.PI));+ const root = hierarchy(tree);+ cluster<T>().size([2 * Math.PI, R]).separation((a, b) => (a.parent === b.parent ? 1 : 2.4))(root);++ const byId = new Map(m.themes.map((t) => [t.id, t]));+ const noteById = new Map(m.notes.map((n) => [n.id, n]));+ const nodes: MapNode[] = [];+ const links: MapLink[] = [];+ for (const d of root.descendants()) {+ const angle = d.x ?? 0;+ const kind: Kind = d.depth === 0 ? "you" : d.depth === 1 ? "theme" : d.children ? "sub" : "note";+ const r = kind === "you" ? 0 : kind === "theme" ? R * 0.34 : kind === "sub" ? R * 0.64 : R;+ const tx = r * Math.cos(angle - Math.PI / 2);+ const ty = r * Math.sin(angle - Math.PI / 2);+ const top = d.ancestors().find((a) => a.depth === 1)?.data.id ?? "";+ const color = colors.get(top) ?? "#8A97A3";+ const id = d.data.id;+ if (kind === "note") {+ const n = noteById.get(id)!;+ nodes.push({ id, kind, label: n.text, theme: top, parent: d.parent?.data.id ?? null, color, size: n.confidence, tx, ty, noteKind: n.kind, loose: top === LOOSE });+ } else if (kind === "you") {+ nodes.push({ id, kind, label: "You", theme: "", parent: null, color, size: noteCount, tx: 0, ty: 0 });+ } else {+ const t = byId.get(id)!;+ nodes.push({ id, kind, label: t.label, theme: top, parent: d.parent?.data.id ?? null, color, size: t.size, tx, ty, loose: top === LOOSE });+ }+ if (d.parent) links.push({ source: d.parent.data.id, target: id, kind: "tree", length: Math.max(20, r - (d.parent.depth === 0 ? 0 : d.parent.depth === 1 ? R * 0.34 : R * 0.64)) });+ }+ // Draw order is label priority: you, themes, sub-themes, notes.+ const order: Record<Kind, number> = { you: 0, theme: 1, sub: 2, note: 3 };+ nodes.sort((a, b) => order[a.kind] - order[b.kind]);++ const related = new Map<string, Array<[string, number]>>();+ const add = (a: string, b: string, w: number) => related.set(a, [...(related.get(a) ?? []), [b, w]]);+ for (const l of m.links) { add(l.a, l.b, l.w); add(l.b, l.a, l.w); }+ for (const list of related.values()) list.sort((x, y) => y[1] - x[1]);+ return { nodes, links, related };+}++type Mode = "map" | "outline";++export function MindMap({ visible, onSelect, selectedId }: { visible: boolean; onSelect: (node: { id: string; kind: "memory" } | null) => void; selectedId: string | null }) {+ const host = useRef<HTMLDivElement>(null);+ const graph = useRef<ForceGraph<MapNode, MapLink> | null>(null);+ const [data, setData] = useState<BrainMap | null>(null);+ const [archive, setArchive] = useState(false);+ const [showLinks, setShowLinks] = useState(false);+ const [mode, setMode] = useState<Mode>("map");+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const [zoomPct, setZoomPct] = useState(100);+ const [find, setFind] = useState("");+ const [matchCount, setMatchCount] = useState(0);+ const [focus, setFocus] = useState<string | null>(null);+ const hover = useRef<MapNode | null>(null);+ const focusRef = useRef<string | null>(null);+ focusRef.current = focus;+ const linksRef = useRef(showLinks);+ linksRef.current = showLinks;+ const related = useRef<Map<string, Array<[string, number]>>>(new Map());+ const byId = useRef<Map<string, MapNode>>(new Map());+ const labelsDrawn = useRef<Array<[number, number, number, number]>>([]);+ const matches = useRef<Set<string>>(new Set());+ const resolved = useTheme((s) => s.resolved);+ const dark = useRef(resolved === "dark");+ dark.current = resolved === "dark";+ const selectedRef = useRef<string | null>(selectedId);+ selectedRef.current = selectedId;+ const onSelectRef = useRef(onSelect);+ onSelectRef.current = onSelect;++ const load = useCallback(async (withArchive: boolean) => {+ setLoading(true);+ setError(null);+ try { setData(await brain.map(withArchive)); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ setLoading(false);+ }, []);++ const requested = useRef(false);+ useEffect(() => {+ if (visible && !requested.current) { requested.current = true; void load(archive); }+ }, [visible, archive, load]);++ const mapData = useMemo(() => (data ? toMindMap(data) : null), [data]);+ const lastData = useRef<typeof mapData>(null);++ function setGraph(g: ForceGraph<MapNode, MapLink>, next: NonNullable<typeof mapData>) {+ lastData.current = next;+ related.current = next.related;+ const placed = place(next, g.graphData().nodes);+ byId.current = new Map(placed.nodes.map((n) => [n.id, n]));+ g.graphData(placed);+ }++ useEffect(() => {+ if (!visible || mode !== "map" || !mapData || graph.current || !host.current) return;+ let disposed = false;+ void import("force-graph").then(({ default: ForceGraphCtor }) => {+ if (disposed || !host.current || graph.current) return;+ const el = host.current;+ const g = new ForceGraphCtor<MapNode, MapLink>(el)+ .width(el.clientWidth)+ .height(el.clientHeight)+ .backgroundColor("rgba(0,0,0,0)")+ .nodeId("id")+ .minZoom(0.08)+ .maxZoom(12)+ .d3VelocityDecay(0.35)+ .d3AlphaDecay(0.02)+ .warmupTicks(0)+ .cooldownTicks(800)+ .linkCanvasObjectMode(() => "replace")+ .linkCanvasObject((l, ctx, scale) => drawBranch(l, ctx, scale))+ .nodeCanvasObject((n, ctx, scale) => drawNode(n, ctx, scale))+ .nodePointerAreaPaint((n, color, ctx, scale) => {+ ctx.fillStyle = color;+ ctx.beginPath();+ ctx.arc(n.x ?? 0, n.y ?? 0, radius(n) + 3 / Math.min(1, scale), 0, 2 * Math.PI);+ ctx.fill();+ const hit = (n as MapNode & { __hit?: [number, number, number, number] }).__hit;+ if (hit && n.kind !== "note") ctx.fillRect(hit[0], hit[1], hit[2], hit[3]);+ })+ .onRenderFramePre(() => { labelsDrawn.current = []; })+ .onRenderFramePost((ctx, scale) => drawRelated(ctx, scale))+ .onZoom(({ k }) => setZoomPct(Math.round(k * 100)))+ .onNodeHover((n) => { hover.current = n ?? null; el.style.cursor = n ? "pointer" : "grab"; })+ .onNodeClick((n) => {+ if (n.kind === "note") { onSelectRef.current({ id: n.id, kind: "memory" }); return; }+ if (n.kind === "you") { setFocus(null); g.zoomToFit(600, 60); return; }+ focusOn(n.kind === "theme" ? n.id : n.id);+ })+ .onBackgroundClick(() => { setFocus(null); onSelectRef.current(null); })+ .onNodeDragEnd((n) => { n.fx = n.x; n.fy = n.y; savePin(n); });++ g.d3Force("charge")?.strength?.((n: MapNode) => CHARGE[n.kind]).distanceMax?.(260);+ g.d3Force("link")?.distance?.((l: MapLink) => l.length).strength?.(0.06);+ g.d3Force("collide", forceCollide<MapNode>((n) => radius(n) + (n.kind === "note" ? 1.2 : 6)).strength(0.7).iterations(1));+ g.d3Force("x", forceX<MapNode>((n) => n.tx).strength((n: MapNode) => PULL[n.kind]));+ g.d3Force("y", forceY<MapNode>((n) => n.ty).strength((n: MapNode) => PULL[n.kind]));++ graph.current = g;+ setGraph(g, mapData);+ setTimeout(() => { if (graph.current === g) g.zoomToFit(800, 50); }, 1800);+ }).catch((e) => setError(e instanceof Error ? e.message : String(e)));+ return () => { disposed = true; };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [visible, mapData, mode]);++ useEffect(() => {+ const g = graph.current;+ if (!g || !mapData || lastData.current === mapData) return;+ setGraph(g, mapData);+ }, [mapData]);++ useEffect(() => {+ const g = graph.current;+ if (!g) return;+ if (visible && mode === "map") g.resumeAnimation();+ else g.pauseAnimation();+ }, [visible, mode]);++ useEffect(() => {+ const el = host.current;+ if (!el) return;+ const ro = new ResizeObserver(() => { if (el.clientWidth && el.clientHeight) graph.current?.width(el.clientWidth).height(el.clientHeight); });+ ro.observe(el);+ return () => ro.disconnect();+ }, []);++ useEffect(() => () => { graph.current?._destructor(); graph.current = null; }, []);++ useEffect(() => { const g = graph.current; if (g) g.nodeCanvasObject(g.nodeCanvasObject()); }, [resolved, selectedId, focus, showLinks]);++ useEffect(() => {+ const q = find.trim().toLowerCase();+ matches.current = new Set(q.length < 2 ? [] : [...byId.current.values()].filter((n) => n.label.toLowerCase().includes(q)).map((n) => n.id));+ setMatchCount(matches.current.size);+ const g = graph.current;+ if (g) g.nodeCanvasObject(g.nodeCanvasObject());+ }, [find, mapData]);++ function inBranch(n: MapNode, id: string): boolean {+ if (n.id === id) return true;+ let p = n.parent;+ while (p) { if (p === id) return true; p = byId.current.get(p)?.parent ?? null; }+ return false;+ }++ function focusOn(id: string) {+ const g = graph.current;+ setFocus(id);+ if (g) g.zoomToFit(700, 70, (n: MapNode) => inBranch(n, id));+ }++ function flyToMatch() {+ const g = graph.current;+ const n = [...byId.current.values()].find((x) => matches.current.has(x.id));+ if (!g || !n) return;+ g.centerAt(n.x, n.y, 600);+ g.zoom(Math.max(2.4, g.zoom()), 600);+ if (n.kind === "note") onSelectRef.current({ id: n.id, kind: "memory" });+ }++ function zoomBy(f: number) {+ const g = graph.current;+ if (g) g.zoom(Math.min(12, Math.max(0.08, g.zoom() * f)), 250);+ }++ function resetLayout() {+ const g = graph.current;+ if (!g) return;+ clearPins();+ setFocus(null);+ scatter(g.graphData().nodes, true);+ g.d3ReheatSimulation();+ setTimeout(() => g.zoomToFit(800, 50), 1800);+ }++ useEffect(() => {+ if (!visible || mode !== "map") return;+ const onKey = zoomKeys(zoomBy, () => graph.current?.zoomToFit(500, 50));+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [visible, mode]);++ const empty = data && data.notes.length === 0;++ return (+ <div className="relative h-full w-full overflow-hidden">+ <div ref={host} className={cx("absolute inset-0", mode !== "map" && "invisible")} style={{ cursor: "grab" }} />+ {mode === "outline" && data && <Outline data={data} selectedId={selectedId} onSelect={(id) => onSelect({ id, kind: "memory" })} find={find} />}++ <div className="pointer-events-none absolute left-4 right-4 top-3 flex flex-wrap items-center gap-2">+ <div className="pointer-events-auto"><Segmented value={mode} onChange={setMode} options={[{ value: "map", label: "Map" }, { value: "outline", label: "Outline" }]} /></div>+ <div className="pointer-events-auto flex h-8 items-center gap-3 rounded-md bg-surface/85 px-2.5 text-xs text-ink2 backdrop-blur">+ <Tooltip label="Draw every related link, not only for the note under the pointer" side="bottom">+ <span><Switch checked={showLinks} onCheckedChange={setShowLinks} label="Links" /></span>+ </Tooltip>+ <Tooltip label="Include older memories from before the Owner Model" side="bottom">+ <span><Switch checked={archive} onCheckedChange={(v) => { setArchive(v); void load(v); }} label="Archive" /></span>+ </Tooltip>+ </div>+ <div className="pointer-events-auto flex h-8 items-center gap-1.5 rounded-md border border-line bg-surface/85 px-2 backdrop-blur">+ <Search size={13} className="text-ink4" />+ <input value={find} onChange={(e) => setFind(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") flyToMatch(); if (e.key === "Escape") setFind(""); }}+ placeholder="Find in your brain" className="w-[160px] bg-transparent text-xs text-ink placeholder:text-ink4" aria-label="Find in your brain" />+ {find.trim().length > 1 && <span className="text-2xs text-ink4">{matchCount}</span>}+ </div>+ {data && <span className="rounded-md bg-surface/80 px-2 py-1 text-xs text-ink3 backdrop-blur">{data.stats.themes} themes · {data.stats.notes} notes · {data.stats.links} links</span>}+ {focus && mode === "map" && (+ <Button className="pointer-events-auto" size="sm" variant="outline" onClick={() => { setFocus(null); graph.current?.zoomToFit(600, 50); }}>Show everything</Button>+ )}+ <span className="flex-1" />+ <Tooltip label="Reload" side="bottom">+ <Button className="pointer-events-auto" size="sm" variant="ghost" icon onClick={() => void load(archive)} loading={loading} aria-label="Reload"><RefreshCw size={14} /></Button>+ </Tooltip>+ </div>++ {mode === "map" && <ZoomPanel zoomPct={zoomPct} onZoom={zoomBy} onFit={() => graph.current?.zoomToFit(500, 50)} onReset={resetLayout} />}++ {!data && !error && <div className="absolute inset-0 flex items-center justify-center text-ink3"><Spinner size={20} /></div>}+ {error && <div className="absolute inset-0 flex items-center justify-center p-8 text-center text-sm text-ink3">Couldn't load the map: {error}</div>}+ {empty && <div className="absolute inset-0 flex items-center justify-center text-sm text-ink3">Nothing to map yet. Mercury builds this as it learns about you.</div>}+ {mode === "map" && data && !empty && (+ <div className="pointer-events-none absolute bottom-3 left-4 rounded-md bg-surface/85 px-2.5 py-1.5 text-xs text-ink4 backdrop-blur">+ click a theme to focus · hover a note for related ones · drag to pin · scroll or +/− to zoom+ </div>+ )}+ </div>+ );++ // ── drawing ──────────────────────────────────────────────────────────────++ function dimmed(n: MapNode): boolean {+ const f = focusRef.current;+ if (f && !inBranch(n, f) && n.kind !== "you") return true;+ if (matches.current.size > 0 && !matches.current.has(n.id) && n.kind === "note") return true;+ const h = hover.current;+ if (h?.kind === "note" && n.kind === "note" && h.id !== n.id && !related.current.get(h.id)?.some(([id]) => id === n.id)) return true;+ return false;+ }++ function drawBranch(l: MapLink, ctx: CanvasRenderingContext2D, scale: number) {+ const s = l.source as MapNode;+ const t = l.target as MapNode;+ if (s.x === undefined || t.x === undefined) return;+ const sx = s.x, sy = s.y ?? 0, tx = t.x, ty = t.y ?? 0;+ // Radial curve: leave the parent outward, arrive at the child along its own ray.+ const rs = Math.hypot(sx, sy);+ const rt = Math.hypot(tx, ty) || 1;+ const rm = (rs + rt) / 2;+ const c1x = rs > 1 ? (sx / rs) * rm : 0;+ const c1y = rs > 1 ? (sy / rs) * rm : 0;+ const c2x = (tx / rt) * rm;+ const c2y = (ty / rt) * rm;+ const dim = dimmed(t);+ const lit = hover.current && (hover.current.id === t.id || hover.current.parent === t.id);+ ctx.globalAlpha = dim ? 0.07 : lit ? 0.9 : t.kind === "note" ? 0.28 : 0.55;+ ctx.strokeStyle = t.color;+ ctx.lineWidth = (t.kind === "note" ? 0.7 : t.kind === "sub" ? 1.4 : 2.2) / Math.sqrt(scale);+ ctx.beginPath();+ ctx.moveTo(sx, sy);+ ctx.bezierCurveTo(c1x, c1y, c2x, c2y, tx, ty);+ ctx.stroke();+ ctx.globalAlpha = 1;+ }++ /** Related links: the hovered (or selected) note's, bright; everything, faint, when "Links" is on. */+ function drawRelated(ctx: CanvasRenderingContext2D, scale: number) {+ const lines: Array<[MapNode, MapNode, number, boolean]> = [];+ const focusNote = hover.current?.kind === "note" ? hover.current : selectedRef.current ? byId.current.get(selectedRef.current) : undefined;+ if (linksRef.current) {+ for (const [a, list] of related.current) {+ const na = byId.current.get(a);+ if (!na) continue;+ for (const [b, w] of list) if (a < b) { const nb = byId.current.get(b); if (nb) lines.push([na, nb, w, false]); }+ }+ }+ if (focusNote) for (const [b, w] of related.current.get(focusNote.id) ?? []) { const nb = byId.current.get(b); if (nb) lines.push([focusNote, nb, w, true]); }+ if (!lines.length) return;+ const d = dark.current;+ for (const [a, b, w, lit] of lines) {+ const ax = a.x ?? 0, ay = a.y ?? 0, bx = b.x ?? 0, by = b.y ?? 0;+ // Bow toward the centre, like a chord diagram, so links read as arcs across the map.+ const mx = ((ax + bx) / 2) * 0.55;+ const my = ((ay + by) / 2) * 0.55;+ ctx.globalAlpha = lit ? Math.min(1, 0.45 + w) : Math.min(0.35, 0.06 + w * 0.4);+ ctx.strokeStyle = lit ? (d ? "#34E1A1" : "#1A9E6E") : (d ? "#C8D0D6" : "#4A535B");+ ctx.lineWidth = (lit ? 1.6 : 0.6) / Math.sqrt(scale);+ ctx.beginPath();+ ctx.moveTo(ax, ay);+ ctx.quadraticCurveTo(mx, my, bx, by);+ ctx.stroke();+ }+ ctx.globalAlpha = 1;+ // Name the related notes of the one under the pointer.+ if (focusNote) for (const [b] of (related.current.get(focusNote.id) ?? []).slice(0, 6)) { const nb = byId.current.get(b); if (nb) noteLabel(nb, ctx, scale, true); }+ }++ function claim(x: number, y: number, w: number, h: number): boolean {+ for (const [ax, ay, aw, ah] of labelsDrawn.current) if (x < ax + aw && x + w > ax && y < ay + ah && y + h > ay) return false;+ labelsDrawn.current.push([x, y, w, h]);+ return true;+ }++ function noteLabel(n: MapNode, ctx: CanvasRenderingContext2D, scale: number, force: boolean) {+ const x = n.x ?? 0;+ const y = n.y ?? 0;+ const size = 10.5 / scale;+ const text = truncate(n.label, 64);+ ctx.font = `400 ${size}px "Geist Variable", system-ui, sans-serif`;+ const w = ctx.measureText(text).width;+ // Outward along the node's ray, flipped on the left so it never reads upside down.+ const a = Math.atan2(y, x);+ const left = Math.cos(a) < 0;+ const gap = radius(n) + 3 / scale;+ const lx = x + Math.cos(a) * gap;+ const ly = y + Math.sin(a) * gap;+ const box: [number, number, number, number] = [Math.min(lx, lx + Math.cos(a) * w) - 1, Math.min(ly, ly + Math.sin(a) * w) - size / 2, Math.abs(Math.cos(a) * w) + size, Math.abs(Math.sin(a) * w) + size];+ if (!force && !claim(...box)) return;+ if (force) labelsDrawn.current.push(box);+ ctx.save();+ ctx.translate(lx, ly);+ ctx.rotate(left ? a + Math.PI : a);+ ctx.textAlign = left ? "right" : "left";+ ctx.textBaseline = "middle";+ ctx.lineWidth = 3 / scale;+ ctx.strokeStyle = dark.current ? "rgba(17,19,21,0.85)" : "rgba(255,255,255,0.9)";+ ctx.strokeText(text, 0, 0);+ ctx.fillStyle = dark.current ? "rgba(236,239,241,0.95)" : "rgba(22,24,26,0.92)";+ ctx.fillText(text, 0, 0);+ ctx.restore();+ }++ function drawNode(n: MapNode, ctx: CanvasRenderingContext2D, scale: number) {+ const d = dark.current;+ const x = n.x ?? 0;+ const y = n.y ?? 0;+ const r = radius(n);+ const dim = dimmed(n);+ ctx.globalAlpha = dim ? 0.14 : n.loose ? 0.7 : 1;++ if (n.kind === "you") {+ ctx.beginPath();+ ctx.arc(x, y, r, 0, 2 * Math.PI);+ ctx.fillStyle = d ? "#34E1A1" : "#1A9E6E";+ ctx.fill();+ pill(n, ctx, scale, "You", 13, 650, x, y + r + 4 / scale, null);+ ctx.globalAlpha = 1;+ return;+ }++ ctx.beginPath();+ ctx.arc(x, y, r, 0, 2 * Math.PI);+ if (n.kind === "note") {+ ctx.fillStyle = n.color;+ ctx.fill();+ } else {+ ctx.fillStyle = d ? "rgba(17,19,21,0.95)" : "rgba(255,255,255,0.97)";+ ctx.fill();+ ctx.lineWidth = (n.kind === "theme" ? 2.6 : 1.8) / scale;+ ctx.strokeStyle = n.color;+ ctx.stroke();+ }+ if (selectedRef.current === n.id || matches.current.has(n.id)) {+ ctx.beginPath();+ ctx.arc(x, y, r + 3 / scale, 0, 2 * Math.PI);+ ctx.lineWidth = 2 / scale;+ ctx.strokeStyle = d ? "#fff" : "#111";+ ctx.stroke();+ }+ if (n.fx !== undefined) {+ ctx.beginPath();+ ctx.arc(x + r * 0.75, y - r * 0.75, 2 / scale, 0, 2 * Math.PI);+ ctx.fillStyle = d ? "#F5C451" : "#A0620A";+ ctx.fill();+ }++ if (!dim) {+ if (n.kind === "theme") pill(n, ctx, scale, `${n.label} ${n.size}`, 13, 650, x, y + r + 4 / scale, n.color);+ else if (n.kind === "sub" && (scale > 0.5 || focusRef.current === n.theme)) pill(n, ctx, scale, n.label, 11.5, 550, x, y + r + 3 / scale, n.color);+ else if (n.kind === "note") {+ const lit = hover.current?.id === n.id || selectedRef.current === n.id || matches.current.has(n.id);+ if (lit || scale > 1.7 || (focusRef.current && scale > 1.1)) noteLabel(n, ctx, scale, lit);+ }+ }+ ctx.globalAlpha = 1;+ }++ /** A label on a soft pill, kept in screen pixels; remembers its box as part of the click target. */+ function pill(n: MapNode, ctx: CanvasRenderingContext2D, scale: number, text: string, px: number, weight: number, cx0: number, top: number, accent: string | null) {+ const size = px / scale;+ ctx.font = `${weight} ${size}px "Geist Variable", system-ui, sans-serif`;+ const w = ctx.measureText(text).width;+ const padX = 6 / scale;+ const padY = 3 / scale;+ const bx = cx0 - w / 2 - padX;+ const bw = w + padX * 2;+ const bh = size + padY * 2;+ const force = n.kind !== "sub";+ if (!force && !claim(bx, top, bw, bh)) return;+ if (force) labelsDrawn.current.push([bx, top, bw, bh]);+ (n as MapNode & { __hit?: [number, number, number, number] }).__hit = [bx, top, bw, bh];+ const d = dark.current;+ ctx.beginPath();+ ctx.roundRect(bx, top, bw, bh, bh / 2);+ ctx.fillStyle = d ? "rgba(23,26,29,0.92)" : "rgba(255,255,255,0.94)";+ ctx.fill();+ if (accent) {+ ctx.lineWidth = 1 / scale;+ ctx.strokeStyle = accent;+ ctx.stroke();+ }+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillStyle = d ? "rgba(236,239,241,0.96)" : "rgba(22,24,26,0.94)";+ ctx.fillText(text, cx0, top + bh / 2);+ }+}++// ── outline: the same tree as a list ─────────────────────────────────────────++function Outline({ data, selectedId, onSelect, find }: { data: BrainMap; selectedId: string | null; onSelect: (id: string) => void; find: string }) {+ const q = find.trim().toLowerCase();+ const tree = useMemo(() => {+ const tops = data.themes.filter((t) => !t.parent).sort((a, b) => (a.id === LOOSE ? 1 : b.id === LOOSE ? -1 : b.size - a.size));+ const colors = themeColors(tops.map((t) => t.id));+ const notesIn = new Map<string, BrainMap["notes"]>();+ for (const n of data.notes) { const at = data.placement[n.id]; if (at) notesIn.set(at, [...(notesIn.get(at) ?? []), n]); }+ return tops.map((t) => ({+ theme: t,+ color: colors.get(t.id)!,+ subs: data.themes.filter((s) => s.parent === t.id).sort((a, b) => b.size - a.size).map((s) => ({ theme: s, notes: notesIn.get(s.id) ?? [] })),+ notes: notesIn.get(t.id) ?? [],+ }));+ }, [data]);+ const [open, setOpen] = useState<Set<string>>(() => new Set(tree.slice(0, 1).map((t) => t.theme.id)));+ const toggle = (id: string) => setOpen((o) => { const n = new Set(o); if (n.has(id)) n.delete(id); else n.add(id); return n; });+ const hit = (text: string) => !q || text.toLowerCase().includes(q);++ const NoteRow = ({ n }: { n: BrainMap["notes"][number] }) => (+ <button onClick={() => onSelect(n.id)} className={cx("flex w-full items-baseline gap-2 rounded-md px-2 py-1 text-left text-sm text-ink2 hover:bg-ink/[0.05]", selectedId === n.id && "bg-ink/[0.07] text-ink")}>+ <span className="w-[74px] shrink-0 font-mono text-2xs uppercase text-ink4">{KIND_LABEL[n.kind] ?? n.kind}</span>+ <span className="min-w-0 flex-1">{n.text}</span>+ </button>+ );++ return (+ <div className="absolute inset-0 overflow-y-auto px-4 pb-8 pt-14">+ <div className="mx-auto flex max-w-3xl flex-col gap-1">+ {tree.map(({ theme, color, subs, notes }) => {+ const all = [...notes, ...subs.flatMap((s) => s.notes)];+ const shown = all.filter((n) => hit(n.text));+ if (q && shown.length === 0 && !hit(theme.label)) return null;+ const isOpen = open.has(theme.id) || (q.length > 1 && shown.length > 0);+ return (+ <div key={theme.id} className="rounded-xl border border-line bg-surface">+ <button onClick={() => toggle(theme.id)} className="flex w-full items-center gap-2.5 px-3 py-2.5 text-left">+ <ChevronRight size={14} className={cx("text-ink4 transition-transform", isOpen && "rotate-90")} />+ <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: color }} />+ <span className="flex-1 text-base font-medium text-ink">{theme.label}</span>+ <span className="font-mono text-xs text-ink4">{q ? `${shown.length}/` : ""}{all.length}</span>+ </button>+ {isOpen && (+ <div className="flex flex-col gap-2 border-t border-line px-3 py-2">+ {subs.map((s) => {+ const ns = s.notes.filter((n) => hit(n.text));+ if (q && ns.length === 0) return null;+ return (+ <div key={s.theme.id}>+ <div className="mb-0.5 flex items-center gap-2 px-2 pt-1 text-xs font-medium text-ink3">+ <span className="h-1.5 w-1.5 rounded-full" style={{ background: color }} />{s.theme.label}<span className="text-ink4">· {s.notes.length}</span>+ </div>+ {ns.map((n) => <NoteRow key={n.id} n={n} />)}+ </div>+ );+ })}+ {notes.filter((n) => hit(n.text)).map((n) => <NoteRow key={n.id} n={n} />)}+ </div>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}++// ── physics constants, placement ─────────────────────────────────────────────++const CHARGE: Record<Kind, number> = { you: -260, theme: -160, sub: -60, note: -6 };+/** Pull toward the mind-map position: firm for the skeleton, softer for notes so they stay fluid. */+const PULL: Record<Kind, number> = { you: 1, theme: 0.22, sub: 0.18, note: 0.1 };++function radius(n: MapNode): number {+ if (n.kind === "you") return 10;+ if (n.kind === "theme") return 6 + Math.min(9, Math.sqrt(n.size) * 0.9);+ if (n.kind === "sub") return 3.5 + Math.min(5, Math.sqrt(n.size) * 0.7);+ return 2.2 + Math.min(1.6, n.size * 1.6);+}++function truncate(s: string, n: number): string {+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;+}++function readPins(): Record<string, [number, number]> {+ try { return JSON.parse(sessionStorage.getItem(PINS_KEY) ?? "{}") as Record<string, [number, number]>; } catch { return {}; }+}++function savePin(n: MapNode) {+ try {+ const pins = readPins();+ pins[n.id] = [Math.round(n.x ?? 0), Math.round(n.y ?? 0)];+ sessionStorage.setItem(PINS_KEY, JSON.stringify(pins));+ } catch { /* storage blocked: the pin holds until reload */ }+}++function clearPins() {+ try { sessionStorage.removeItem(PINS_KEY); } catch { /* ignore */ }+}++/** A random start near the middle; the mind map then flows out into its shape. */+function scatter(nodes: MapNode[], unpin: boolean) {+ for (const n of nodes) {+ if (n.kind === "you") { n.x = 0; n.y = 0; n.fx = 0; n.fy = 0; continue; }+ if (unpin) { n.fx = undefined; n.fy = undefined; }+ const a = Math.random() * Math.PI * 2;+ const r = 40 + Math.random() * 260;+ n.x = Math.cos(a) * r;+ n.y = Math.sin(a) * r;+ n.vx = 0;+ n.vy = 0;+ }+}++function endId(e: string | number | MapNode | undefined): string {+ return typeof e === "object" && e ? String(e.id) : String(e ?? "");+}++function place(g: { nodes: MapNode[]; links: MapLink[] }, live: MapNode[]): { nodes: MapNode[]; links: MapLink[] } {+ const pins = readPins();+ const current = new Map(live.map((n) => [n.id, n]));+ const fresh: MapNode[] = [];+ const nodes = g.nodes.map((n) => {+ if (n.kind === "you") return { ...n, x: 0, y: 0, fx: 0, fy: 0 };+ const pin = pins[n.id];+ if (pin) return { ...n, x: pin[0], y: pin[1], fx: pin[0], fy: pin[1] };+ const c = current.get(n.id);+ if (c?.x !== undefined) return { ...n, x: c.x, y: c.y, vx: c.vx, vy: c.vy, fx: c.fx, fy: c.fy };+ const copy = { ...n };+ fresh.push(copy);+ return copy;+ });+ scatter(fresh, false);+ return { nodes, links: g.links.map((l) => ({ ...l, source: endId(l.source), target: endId(l.target) })) };+}diff --git a/apps/desktop/src/views/brain/ZoomPanel.tsx b/apps/desktop/src/views/brain/ZoomPanel.tsxnew file mode 100644index 00000000..44479e63--- /dev/null+++ b/apps/desktop/src/views/brain/ZoomPanel.tsx@@ -0,0 +1,29 @@+import { Maximize2, Minus, Plus, RotateCcw } from "lucide-react";+import { Tooltip } from "~/components/ui/Tooltip";++/** Map-style zoom controls, bottom right: in, level, out, fit, reset layout. */+export function ZoomPanel({ zoomPct, onZoom, onFit, onReset }: { zoomPct: number; onZoom: (factor: number) => void; onFit: () => void; onReset: () => void }) {+ const ctl = "flex h-8 w-8 items-center justify-center rounded-lg text-ink2 hover:bg-ink/[0.07] hover:text-ink";+ return (+ <div className="absolute bottom-3 right-4 flex flex-col items-center gap-1 rounded-xl border border-line bg-surface/90 p-1 shadow-sm backdrop-blur">+ <Tooltip label="Zoom in" shortcut="+" side="left"><button onClick={() => onZoom(1.4)} className={ctl} aria-label="Zoom in"><Plus size={15} /></button></Tooltip>+ <span className="font-mono text-2xs text-ink4">{zoomPct}%</span>+ <Tooltip label="Zoom out" shortcut="−" side="left"><button onClick={() => onZoom(1 / 1.4)} className={ctl} aria-label="Zoom out"><Minus size={15} /></button></Tooltip>+ <div className="my-0.5 h-px w-6 bg-line" />+ <Tooltip label="Fit to screen" shortcut="0" side="left"><button onClick={onFit} className={ctl} aria-label="Fit to screen"><Maximize2 size={14} /></button></Tooltip>+ <Tooltip label="Reset layout (unpin everything)" side="left"><button onClick={onReset} className={ctl} aria-label="Reset layout"><RotateCcw size={14} /></button></Tooltip>+ </div>+ );+}++/** + / - / 0 zoom while a canvas view is on screen (ignored while typing). */+export function zoomKeys(onZoom: (factor: number) => void, onFit: () => void): (e: KeyboardEvent) => void {+ return (e) => {+ const t = e.target as HTMLElement | null;+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.key === "+" || e.key === "=") onZoom(1.4);+ else if (e.key === "-") onZoom(1 / 1.4);+ else if (e.key === "0") onFit();+ };+}diff --git a/src/memory/knowledge-map.test.ts b/src/memory/knowledge-map.test.tsnew file mode 100644index 00000000..a9f11a27--- /dev/null+++ b/src/memory/knowledge-map.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';+import { buildKnowledgeMap, LOOSE_THEME, louvain, termsOf, themeMemory, type MapNote } from './knowledge-map.js';++const note = (id: string, text: string, kind = 'fact'): MapNote => ({ id, text, kind, at: 0 });++/** Three clear subjects, phrased the way beliefs are. */+function brain(): MapNote[] {+ const garden = ['grows tomatoes in the garden', 'waters the garden tomatoes every morning', 'wants raised beds for the garden tomatoes',+ 'composts kitchen scraps for the garden', 'planted basil beside the garden tomatoes', 'bought a hose for the garden'];+ const guitar = ['practises guitar chords nightly', 'wants a Fender guitar for chords practice', 'learning guitar scales and chords',+ 'records guitar covers on weekends', 'restrings the guitar every month', 'takes guitar lessons for chords'];+ const rust = ['is learning Rust ownership and borrowing', 'writes a Rust CLI with Cargo', 'prefers Rust over Go for the CLI',+ 'reads the Rust book on ownership', 'publishes Rust crates with Cargo', 'debugs Rust borrowing errors in the CLI'];+ return [+ ...garden.map((t, i) => note(`g${i}`, `User ${t}`, 'preference')),+ ...guitar.map((t, i) => note(`m${i}`, `User ${t}`, 'goal')),+ ...rust.map((t, i) => note(`r${i}`, `User ${t}`, 'project')),+ ];+}++const themeOf = (map: ReturnType<typeof buildKnowledgeMap>, id: string) => {+ const t = map.placement[id];+ return map.themes.find((x) => x.id === t)?.parent ?? t;+};++describe('knowledge map', () => {+ it('groups notes by subject and names each theme from its own words', () => {+ const map = buildKnowledgeMap(brain(), {}, { ownerNames: ['Test Owner'] });+ const groups = ['g', 'm', 'r'].map((p) => new Set(Array.from({ length: 6 }, (_, i) => themeOf(map, `${p}${i}`))));+ for (const g of groups) expect(g.size).toBe(1);+ expect(new Set(groups.map((g) => [...g][0])).size).toBe(3);+ const labels = map.themes.map((t) => t.label.toLowerCase()).join(' | ');+ expect(labels).toMatch(/garden|tomato/);+ expect(labels).toMatch(/guitar|chord/);+ expect(labels).toMatch(/rust|cli|cargo/);+ });++ it('keeps links sparse: a handful per note, never all pairs', () => {+ const map = buildKnowledgeMap(brain());+ expect(map.links.length).toBeGreaterThan(9);+ expect(map.links.length).toBeLessThan((18 * 17) / 2 / 3);+ const same = map.links.filter((l) => themeOf(map, l.a) === themeOf(map, l.b)).length;+ expect(same / map.links.length).toBeGreaterThan(0.9);+ });++ it('a note that shares nothing goes to Loose notes, not into a theme', () => {+ const map = buildKnowledgeMap([...brain(), note('x', 'Zebra quokka marmalade')]);+ expect(map.placement.x).toBe(LOOSE_THEME);+ expect(map.stats.notes).toBe(19);+ });++ it('theme ids survive a rebuild with new notes', () => {+ const first = buildKnowledgeMap(brain());+ const ids = (m: typeof first) => ['g0', 'm0', 'r0'].map((id) => themeOf(m, id));+ const more = [...brain(), note('g9', 'User harvests garden tomatoes in August'), note('r9', 'User refactors the Rust CLI with Cargo')];+ const second = buildKnowledgeMap(more, themeMemory(first));+ expect(ids(second)).toEqual(ids(first));+ expect(themeOf(second, 'g9')).toBe(themeOf(second, 'g0'));+ });++ it('never names a theme after the owner', () => {+ const notes = brain().map((n) => ({ ...n, text: n.text.replace('User', 'Salman Qureshi') }));+ const map = buildKnowledgeMap(notes, {}, { ownerNames: ['Salman Qureshi'] });+ expect(map.themes.map((t) => t.label).join(' ')).not.toMatch(/salman|qureshi/i);+ });++ it('keeps named things whole and drops the opening word', () => {+ const t = termsOf('Prefers VS Code over Cosmic Stack tools');+ expect(t.counts.has('e:vs code')).toBe(true);+ expect(t.counts.has('e:cosmic stack')).toBe(true);+ expect([...t.counts.keys()].some((k) => k.includes('prefers'))).toBe(false);+ });++ it('louvain splits two cliques joined by one edge', () => {+ const edges: Array<[number, number, number]> = [];+ for (const base of [0, 5]) for (let i = 0; i < 5; i++) for (let j = i + 1; j < 5; j++) edges.push([base + i, base + j, 1]);+ edges.push([4, 5, 0.1]);+ const c = louvain(10, edges);+ expect(new Set(c.slice(0, 5)).size).toBe(1);+ expect(new Set(c.slice(5)).size).toBe(1);+ expect(c[0]).not.toBe(c[9]);+ });++ it('an empty brain is an empty map', () => {+ expect(buildKnowledgeMap([]).themes).toEqual([]);+ });+});diff --git a/src/memory/knowledge-map.ts b/src/memory/knowledge-map.tsnew file mode 100644index 00000000..009ff28a--- /dev/null+++ b/src/memory/knowledge-map.ts@@ -0,0 +1,475 @@+/**+ * The knowledge map: everything Mercury knows about you, as a mind map.+ *+ * You → themes → sub-themes → notes, plus a sparse web of "related" links.+ *+ * Built locally from the text alone. No model calls, no embeddings, so it+ * costs nothing to rebuild and works offline. The pipeline (chosen after+ * comparing Obsidian/Logseq "hairball" graphs with TheBrain/Capacities-style+ * focused maps, see docs in the PR):+ *+ * 1. Terms. Words (lower-cased, stop-words dropped, lightly stemmed) plus+ * named things ("Cosmic Stack", "VS Code") kept whole and weighted ×2,+ * because in one-sentence notes names carry most of the meaning.+ * 2. Weights. BM25 (k1 1.2, b 0.3 for short texts) → unit vectors.+ * 3. Links. Cosine kNN with k = clamp(⌈ln n⌉, 5, 10); keep mutual pairs,+ * one-way pairs only when strong (≥ 0.25), and every note's best match so+ * nothing floats alone. Sparse by construction: no hairball.+ * 4. Themes. Louvain on that graph (deterministic order), resolution searched+ * for 6–12 themes; each community split into connected pieces (Leiden's+ * fix); crumbs merged into their strongest neighbour. Big themes get+ * sub-themes the same way.+ * 5. Names. c-TF-IDF (BERTopic): a theme is named by the terms that are+ * frequent in it and rare elsewhere, names preferred.+ * 6. Stability. Themes are matched to the previous map by member overlap+ * (Jaccard ≥ 0.3) and keep their id, so colours and places stay put.+ *+ * Pure: give it notes, get a map. The store caches it and keeps the ids.+ */++export interface MapNote {+ id: string;+ text: string;+ kind: string;+ at: number;+ /** 0-1; scales the note's links (archive memories count half). */+ weight?: number;+}++export interface MapTheme {+ id: string;+ label: string;+ terms: string[];+ /** null for a top-level theme, else the theme it belongs to. */+ parent: string | null;+ size: number;+}++export interface MapLink { a: string; b: string; w: number }++export interface KnowledgeMap {+ themes: MapTheme[];+ /** note id → the theme it sits in (a sub-theme when its theme has them). */+ placement: Record<string, string>;+ links: MapLink[];+ stats: { notes: number; links: number; themes: number; ms: number };+}++/** Previous membership, for stable ids: theme id → note ids. */+export type ThemeMemory = Record<string, { parent: string | null; members: string[] }>;++// ── 1. Terms ─────────────────────────────────────────────────────────────────++const STOP = new Set(`a about above after again against all also am an and any are aren as at be because been before being below between both but by can+cannot could did do does doing don down during each few for from further had has have having he her here hers herself him himself his how i if in into is+isn it its itself just let me more most my myself no nor not now of off on once only or other ought our ours ourselves out over own same she should so some+such than that the their theirs them themselves then there these they this those through to too under until up very was we were what when where which while+who whom why will with would you your yours yourself yourselves via per etc using used use uses one two new get got make made like want wants wanted wanting+prefer prefers preferred user user's users owner salman mercury's s t re ve ll d m within without across around rather instead currently recently always+never often usually still yet already may might must need needs needed shall should would able unable thing things something someone anything way ways+lot lots much many very really just also even ever every each both either neither however therefore thus hence via based including include includes`.split(/\s+/));++/** Opening words that are capitalised only because they start the note. */+const OPENERS = new Set(['User', 'Users', 'Wants', 'Prefers', 'Uses', 'Is', 'Has', 'The', 'A', 'An', 'Likes', 'Loves', 'Dislikes', 'Works', 'Working',+ 'Building', 'Created', 'Completed', 'Developing', 'Managing', 'Considering', 'Values', 'Cannot', 'Can', 'Used', 'Only', 'Prefer', 'Want', 'He', 'She',+ 'They', 'His', 'Her', 'Their', 'This', 'That', 'When', 'If', 'For', 'In', 'On', 'At', 'To', 'Of', 'And', 'But', 'Or', 'As', 'With', 'Wanted', 'Decided',+ 'Asked', 'Plans', 'Planning', 'Started', 'Finished', 'Owner', 'Mercury']);++/** Fine for linking, poor as a theme name: codes, dates, filler. */+const MONTHS = /^(january|february|march|april|may|june|july|august|september|october|november|december|monday|tuesday|wednesday|thursday|friday|saturday|sunday|today|yesterday|tomorrow)$/;+const WEAK_LABEL = new Set(['account', 'feature', 'access', 'expect', 'agent', 'work', 'code', 'data', 'file', 'system', 'app', 'tool', 'thing', 'part', 'time',+ 'request', 'requested', 'task', 'version', 'step', 'mode', 'option', 'issue', 'help', 'support', 'interact', 'creat', 'build', 'implement', 'test', 'check', 'add']);+function labelable(t: string): boolean {+ const w = t.replace(/^e:/, '');+ if (/\d/.test(w) && !/^[a-z]+[\s-]?\d+(?:\.\d+)?\s*[a-z ]*$/i.test(w)) return false; // C25-G6, 2026-10-01+ if (/^[a-z]?\d+[a-z]?$/i.test(w) || /^[a-z]\d+/i.test(w)) return false; // C62, 7006804336+ if (MONTHS.test(w)) return false;+ if (!t.startsWith('e:') && WEAK_LABEL.has(w)) return false;+ return w.length >= 3;+}++function stem(w: string): string {+ if (w.length > 5 && w.endsWith('ies')) return `${w.slice(0, -3)}y`;+ if (w.length > 6 && w.endsWith('ing')) return w.slice(0, -3);+ if (w.length > 5 && w.endsWith('ed')) return w.slice(0, -2);+ if (w.length > 4 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us') && !w.endsWith('is')) return w.slice(0, -1);+ return w;+}++export interface Terms { counts: Map<string, number>; display: Map<string, string>; length: number }++/** Terms of one note: stemmed words, plus named things kept whole ("e:cosmic stack"). */+export function termsOf(text: string, stop: Set<string> = new Set()): Terms {+ const counts = new Map<string, number>();+ const display = new Map<string, string>();+ const add = (t: string, shown: string, n = 1) => { counts.set(t, (counts.get(t) ?? 0) + n); if (!display.has(t)) display.set(t, shown); };+ // Named things: runs of capitalised words (and acronyms / CamelCase), not the opener.+ const named = text.match(/\b(?:[A-Z][\w.+#-]*[A-Za-z0-9+#])(?:\s+(?:[A-Z][\w.+#-]*[A-Za-z0-9+#]|\d+(?:\.\d+)*))*/g) ?? [];+ for (let raw of named) {+ const words = raw.split(/\s+/);+ while (words.length && OPENERS.has(words[0])) words.shift();+ raw = words.join(' ').replace(/['’]s$/, '');+ if (raw.length < 2 || STOP.has(raw.toLowerCase()) || raw.toLowerCase().split(' ').some((w) => stop.has(w))) continue;+ add(`e:${raw.toLowerCase()}`, raw, 2);+ }+ let length = 0;+ for (const w of text.toLowerCase().replace(/['’]s\b/g, '').split(/[^a-z0-9+#]+/)) {+ if (w.length < 3 || STOP.has(w) || stop.has(w) || /^\d+$/.test(w)) continue;+ const s = stem(w);+ if (STOP.has(s)) continue;+ add(s, w);+ length += 1;+ }+ return { counts, display, length: Math.max(1, length) };+}++// ── 2-3. Weights and links ───────────────────────────────────────────────────++type Vec = Map<string, number>;++function vectors(terms: Terms[]): { vecs: Vec[]; df: Map<string, number> } {+ const n = terms.length;+ const df = new Map<string, number>();+ for (const t of terms) for (const k of t.counts.keys()) df.set(k, (df.get(k) ?? 0) + 1);+ const avg = terms.reduce((s, t) => s + t.length, 0) / Math.max(1, n);+ const k1 = 1.2;+ const b = 0.3;+ const vecs = terms.map((t) => {+ const v: Vec = new Map();+ let norm = 0;+ for (const [k, tf] of t.counts) {+ const d = df.get(k) ?? 1;+ if (d < 2) continue; // a term only this note has can't link it to anything+ const idf = Math.log(1 + (n - d + 0.5) / (d + 0.5));+ const w = idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + (b * t.length) / avg)));+ v.set(k, w);+ norm += w * w;+ }+ norm = Math.sqrt(norm) || 1;+ for (const [k, w] of v) v.set(k, w / norm);+ return v;+ });+ return { vecs, df };+}++/** Link rules. Below `min` two notes only share filler; one-way picks need `oneWay`; a note's best match needs `best`. */+export const LINK_RULES = { min: 0.1, oneWay: 0.25, best: 0.15 };++/** Sparse kNN links: mutual pairs, strong one-way pairs, and each note's best match. */+export function linkNotes(vecs: Vec[], weights: number[] = []): Array<[number, number, number]> {+ const n = vecs.length;+ if (n < 2) return [];+ const k = Math.max(5, Math.min(10, Math.ceil(Math.log(n))));+ // Inverted index; very common terms are skipped for finding candidates (they still score).+ const postings = new Map<string, number[]>();+ vecs.forEach((v, i) => { for (const t of v.keys()) { let p = postings.get(t); if (!p) postings.set(t, (p = [])); p.push(i); } });+ const busy = Math.max(40, Math.floor(n * 0.15));+ const top: Array<Array<[number, number]>> = [];+ const score = new Float64Array(n);+ const touched: number[] = [];+ for (let i = 0; i < n; i++) {+ for (const [t, w] of vecs[i]) {+ const p = postings.get(t)!;+ if (p.length > busy) continue;+ for (const j of p) {+ if (j === i) continue;+ if (score[j] === 0) touched.push(j);+ score[j] += w * (vecs[j].get(t) ?? 0);+ }+ }+ // Busy terms add to pairs already found.+ for (const [t, w] of vecs[i]) {+ const p = postings.get(t)!;+ if (p.length <= busy) continue;+ for (const j of touched) score[j] += w * (vecs[j].get(t) ?? 0);+ }+ const best = touched.map((j) => [j, score[j]] as [number, number]).sort((a, b) => b[1] - a[1] || a[0] - b[0]).slice(0, k);+ top.push(best.filter(([, s]) => s >= LINK_RULES.min));+ for (const j of touched) score[j] = 0;+ touched.length = 0;+ }+ const inTop = top.map((list) => new Map(list));+ const edges = new Map<string, [number, number, number]>();+ const keep = (i: number, j: number, s: number) => {+ const a = Math.min(i, j);+ const b = Math.max(i, j);+ const key = `${a}:${b}`;+ if (!edges.has(key)) edges.set(key, [a, b, s * Math.min(weights[a] ?? 1, weights[b] ?? 1)]);+ };+ for (let i = 0; i < n; i++) {+ top[i].forEach(([j, s], rank) => {+ if (inTop[j].has(i) || s >= LINK_RULES.oneWay || (rank === 0 && s >= LINK_RULES.best)) keep(i, j, s);+ });+ }+ return [...edges.values()];+}++// ── 4. Communities (Louvain) ─────────────────────────────────────────────────++interface WGraph { n: number; adj: Array<Map<number, number>>; strength: Float64Array; total: number }++function wgraph(n: number, edges: Array<[number, number, number]>): WGraph {+ const adj = Array.from({ length: n }, () => new Map<number, number>());+ for (const [a, b, w] of edges) {+ if (a === b) { adj[a].set(a, (adj[a].get(a) ?? 0) + 2 * w); continue; }+ adj[a].set(b, (adj[a].get(b) ?? 0) + w);+ adj[b].set(a, (adj[b].get(a) ?? 0) + w);+ }+ const strength = new Float64Array(n);+ let total = 0;+ for (let i = 0; i < n; i++) { let s = 0; for (const w of adj[i].values()) s += w; strength[i] = s; total += s; }+ return { n, adj, strength, total: total / 2 };+}++/** Louvain with a resolution γ. Deterministic: nodes are visited in index order. Returns a community per node. */+export function louvain(n: number, edges: Array<[number, number, number]>, resolution = 1): number[] {+ let g = wgraph(n, edges);+ let membership = Array.from({ length: n }, (_, i) => i);+ if (g.total === 0) return membership;+ const m2 = 2 * g.total;+ for (let level = 0; level < 12; level++) {+ const comm = Array.from({ length: g.n }, (_, i) => i);+ const tot = Float64Array.from(g.strength);+ let moved = false;+ for (let pass = 0; pass < 20; pass++) {+ let changed = 0;+ for (let i = 0; i < g.n; i++) {+ const ci = comm[i];+ const ki = g.strength[i];+ const links = new Map<number, number>();+ for (const [j, w] of g.adj[i]) if (j !== i) links.set(comm[j], (links.get(comm[j]) ?? 0) + w);+ tot[ci] -= ki;+ let best = ci;+ let gain = (links.get(ci) ?? 0) - (resolution * tot[ci] * ki) / m2;+ for (const [c, w] of links) {+ const dq = w - (resolution * tot[c] * ki) / m2;+ if (dq > gain + 1e-12 || (Math.abs(dq - gain) <= 1e-12 && c < best && dq > 0)) { gain = dq; best = c; }+ }+ tot[best] += ki;+ if (best !== ci) { comm[i] = best; changed++; }+ }+ if (changed === 0) break;+ moved = true;+ }+ if (!moved) break;+ // Renumber and aggregate.+ const ids = new Map<number, number>();+ for (const c of comm) if (!ids.has(c)) ids.set(c, ids.size);+ membership = membership.map((c) => ids.get(comm[c])!);+ const agg: Array<[number, number, number]> = [];+ for (let i = 0; i < g.n; i++) for (const [j, w] of g.adj[i]) if (i <= j) agg.push([ids.get(comm[i])!, ids.get(comm[j])!, i === j ? w / 2 : w]);+ const merged = new Map<string, [number, number, number]>();+ for (const [a, b, w] of agg) {+ const x = Math.min(a, b);+ const y = Math.max(a, b);+ const key = `${x}:${y}`;+ const e = merged.get(key);+ if (e) e[2] += w; else merged.set(key, [x, y, w]);+ }+ if (ids.size === g.n) break;+ g = wgraph(ids.size, [...merged.values()]);+ }+ return membership;+}++/** Split each community into its connected pieces (Leiden's guarantee, cheaply). */+function splitDisconnected(members: number[], adj: Array<Map<number, number>>): number[] {+ const out = new Array<number>(members.length).fill(-1);+ let next = 0;+ for (let s = 0; s < members.length; s++) {+ if (out[s] !== -1) continue;+ const id = next++;+ const stack = [s];+ out[s] = id;+ while (stack.length) {+ const i = stack.pop()!;+ for (const j of adj[i].keys()) if (out[j] === -1 && members[j] === members[s]) { out[j] = id; stack.push(j); }+ }+ }+ return out;+}++/** Fold groups smaller than `min` into the neighbour group they link to most; unlinked crumbs gather as one group. */+function absorbCrumbs(groups: number[], adj: Array<Map<number, number>>, min: number): number[] {+ const out = groups.slice();+ for (let round = 0; round < 4; round++) {+ const size = new Map<number, number>();+ for (const c of out) size.set(c, (size.get(c) ?? 0) + 1);+ const small = [...size].filter(([, s]) => s < min).map(([c]) => c);+ if (!small.length) break;+ let changed = false;+ for (const c of small) {+ const pull = new Map<number, number>();+ out.forEach((ci, i) => { if (ci !== c) return; for (const [j, w] of adj[i]) if (out[j] !== c) pull.set(out[j], (pull.get(out[j]) ?? 0) + w); });+ const target = [...pull].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];+ if (target) { out.forEach((ci, i) => { if (ci === c) out[i] = target[0]; }); changed = true; }+ }+ if (!changed) break;+ }+ return out;+}++/** Communities with a resolution searched so the count lands in [lo, hi] when possible. */+function themesFor(n: number, edges: Array<[number, number, number]>, lo: number, hi: number, minSize: number): number[] {+ const adj = wgraph(n, edges).adj;+ const run = (r: number) => absorbCrumbs(splitDisconnected(louvain(n, edges, r), adj), adj, minSize);+ const count = (g: number[]) => new Set(g).size;+ let best = run(1);+ let bestCount = count(best);+ if (bestCount >= lo && bestCount <= hi) return best;+ let a = 0.2;+ let b = 4;+ for (let i = 0; i < 9; i++) {+ const r = (a + b) / 2;+ const g = run(r);+ const c = count(g);+ const dist = (x: number) => (x < lo ? lo - x : x > hi ? x - hi : 0);+ if (dist(c) < dist(bestCount)) { best = g; bestCount = c; }+ if (c >= lo && c <= hi) return g;+ if (c < lo) a = r; else b = r;+ }+ return best;+}++// ── 5. Names (c-TF-IDF) ──────────────────────────────────────────────────────++function nameGroups(groups: number[][], terms: Terms[], avoid: Set<string> = new Set()): Array<{ label: string; terms: string[] }> {+ const tfc = groups.map((g) => { const m = new Map<string, number>(); for (const i of g) for (const [t, c] of terms[i].counts) m.set(t, (m.get(t) ?? 0) + c); return m; });+ const tf = new Map<string, number>();+ for (const m of tfc) for (const [t, c] of m) tf.set(t, (tf.get(t) ?? 0) + c);+ const words = tfc.map((m) => [...m.values()].reduce((s, c) => s + c, 0));+ const A = words.reduce((s, c) => s + c, 0) / Math.max(1, groups.length);+ const shown = (t: string) => { for (const i of groups.flat()) { const d = terms[i].display.get(t); if (d) return d; } return t.replace(/^e:/, ''); };+ return groups.map((g, gi) => {+ const scored = [...tfc[gi]]+ .filter(([t, c]) => c >= Math.min(2, g.length) && !avoid.has(t) && labelable(t))+ .map(([t, c]) => [t, c * Math.log(1 + A / (tf.get(t) ?? 1)) * (t.startsWith('e:') ? 1.5 : 1)] as [string, number])+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1));+ const picked: string[] = [];+ const seenWords = new Set<string>([...avoid].filter((t) => !t.startsWith('e:')));+ for (const [t] of scored) {+ const words = t.replace(/^e:/, '').split(' ').map(stem);+ // "Cosmic Stack" and "stack", "DUNS" and "Dun" say the same thing.+ if (words.some((w) => [...seenWords].some((x) => x === w || (Math.min(x.length, w.length) >= 3 && (x.startsWith(w) || w.startsWith(x)))))) continue;+ words.forEach((w) => seenWords.add(w));+ picked.push(t);+ if (picked.length === 3) break;+ }+ const label = picked.slice(0, 2).map((t) => { const s = shown(t); return t.startsWith('e:') ? s : s[0].toUpperCase() + s.slice(1); }).join(' · ');+ return { label: label || 'Other notes', terms: picked };+ });+}++// ── 6. Stable ids ────────────────────────────────────────────────────────────++function jaccard(a: Set<string>, b: string[]): number {+ let inter = 0;+ for (const x of b) if (a.has(x)) inter++;+ return inter / (a.size + b.length - inter || 1);+}++function matchIds(groups: string[][], previous: Array<[string, string[]]>, prefix: string, taken: Set<string>): string[] {+ const pairs: Array<[number, number, number]> = [];+ groups.forEach((g, gi) => { const s = new Set(g); previous.forEach(([, members], pi) => { const j = jaccard(s, members); if (j >= 0.3) pairs.push([gi, pi, j]); }); });+ pairs.sort((a, b) => b[2] - a[2]);+ const ids = new Array<string | null>(groups.length).fill(null);+ const usedPrev = new Set<number>();+ for (const [gi, pi] of pairs) {+ if (ids[gi] || usedPrev.has(pi) || taken.has(previous[pi][0])) continue;+ ids[gi] = previous[pi][0];+ usedPrev.add(pi);+ taken.add(previous[pi][0]);+ }+ return ids.map((id, gi) => {+ if (id) return id;+ // New theme: an id from its first member, so it is stable for the same content.+ let h = 2166136261;+ for (const ch of [...groups[gi]].sort()[0] ?? `${gi}`) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); }+ let nid = `${prefix}${(h >>> 0).toString(36)}`;+ while (taken.has(nid)) nid += 'x';+ taken.add(nid);+ return nid;+ });+}++// ── The map ──────────────────────────────────────────────────────────────────++export const LOOSE_THEME = 'loose';++export function buildKnowledgeMap(notes: MapNote[], previous: ThemeMemory = {}, opts: { now?: () => number; ownerNames?: string[] } = {}): KnowledgeMap {+ const clock = opts.now ?? (() => Date.now());+ const started = clock();+ const n = notes.length;+ if (n === 0) return { themes: [], placement: {}, links: [], stats: { notes: 0, links: 0, themes: 0, ms: 0 } };+ const stop = new Set((opts.ownerNames ?? []).flatMap((o) => { const f = o.trim().toLowerCase(); return f ? [f, ...f.split(/\s+/)] : []; }));+ const terms = notes.map((x) => termsOf(x.text, stop));+ const { vecs } = vectors(terms);+ const edges = linkNotes(vecs, notes.map((x) => x.weight ?? 1));++ // Top level: aim for 6-12 themes (fewer for a small brain).+ const lo = n < 40 ? 2 : n < 150 ? 4 : 6;+ const hi = n < 40 ? 5 : n < 150 ? 9 : 12;+ const top = themesFor(n, edges, lo, hi, Math.max(4, Math.round(n * 0.01)));+ const linked = new Set<number>();+ for (const [a, b] of edges) { linked.add(a); linked.add(b); }+ const groupsIdx = new Map<number, number[]>();+ const loose: number[] = [];+ top.forEach((c, i) => {+ if (!linked.has(i)) { loose.push(i); return; }+ let g = groupsIdx.get(c); if (!g) groupsIdx.set(c, (g = [])); g.push(i);+ });+ // Largest first, so themes read from most to least. Tiny leftovers join the loose notes.+ const groups = [...groupsIdx.values()].filter((g) => (g.length >= 3 ? true : (loose.push(...g), false))).sort((a, b) => b.length - a.length);+ const names = nameGroups(groups, terms);++ const prevTop = Object.entries(previous).filter(([, v]) => v.parent === null).map(([id, v]) => [id, v.members] as [string, string[]]);+ const taken = new Set<string>();+ const topIds = matchIds(groups.map((g) => g.map((i) => notes[i].id)), prevTop, 't', taken);++ const themes: MapTheme[] = [];+ const placement: Record<string, string> = {};+ groups.forEach((g, gi) => {+ const id = topIds[gi];+ themes.push({ id, label: names[gi].label, terms: names[gi].terms, parent: null, size: g.length });+ for (const i of g) placement[notes[i].id] = id;+ if (g.length <= 25) return;+ // Sub-themes inside a big theme, from the links within it.+ const local = new Map(g.map((i, li) => [i, li]));+ const sub = edges.filter(([a, b]) => local.has(a) && local.has(b)).map(([a, b, w]) => [local.get(a)!, local.get(b)!, w] as [number, number, number]);+ const parts = themesFor(g.length, sub, 2, Math.min(7, Math.ceil(g.length / 8)), 3);+ const partIdx = new Map<number, number[]>();+ parts.forEach((c, li) => { let p = partIdx.get(c); if (!p) partIdx.set(c, (p = [])); p.push(g[li]); });+ const subGroups = [...partIdx.values()].sort((a, b) => b.length - a.length);+ if (subGroups.length < 2) return;+ // Sub-themes say something their theme's name doesn't.+ const parentWords = names[gi].terms.flatMap((t) => [t, ...t.replace(/^e:/, '').split(' ').map(stem)]);+ const subNames = nameGroups(subGroups, terms, new Set(parentWords));+ const prevSub = Object.entries(previous).filter(([, v]) => v.parent === id).map(([sid, v]) => [sid, v.members] as [string, string[]]);+ const subIds = matchIds(subGroups.map((sg) => sg.map((i) => notes[i].id)), prevSub, `${id}.`, taken);+ subGroups.forEach((sg, si) => {+ themes.push({ id: subIds[si], label: subNames[si].label, terms: subNames[si].terms, parent: id, size: sg.length });+ for (const i of sg) placement[notes[i].id] = subIds[si];+ });+ });++ // Notes that share nothing worth a link with anything else: kept, under one quiet theme.+ if (loose.length) {+ themes.push({ id: LOOSE_THEME, label: 'Loose notes', terms: [], parent: null, size: loose.length });+ for (const i of loose) placement[notes[i].id] = LOOSE_THEME;+ }++ const links = edges.map(([a, b, w]) => ({ a: notes[a].id, b: notes[b].id, w: Number(w.toFixed(3)) }));+ return { themes, placement, links, stats: { notes: n, links: links.length, themes: themes.filter((t) => !t.parent && t.id !== LOOSE_THEME).length, ms: clock() - started } };+}++/** What to remember for next time: each theme's members, for stable ids. */+export function themeMemory(map: KnowledgeMap): ThemeMemory {+ const out: ThemeMemory = {};+ for (const t of map.themes) out[t.id] = { parent: t.parent, members: [] };+ for (const [note, theme] of Object.entries(map.placement)) {+ out[theme]?.members.push(note);+ const parent = map.themes.find((t) => t.id === theme)?.parent;+ if (parent) out[parent]?.members.push(note);+ }+ return out;+}diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex c687de21..65ae164f 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -1119,6 +1119,20 @@ export class SecondBrainDB {.trim();}+ /** The legacy archive as map notes (live rows only). */+ archiveNotes(userKey: string, limit = 50000): Array<{ id: string; text: string; kind: string; at: number; confidence: number }> {+ return this.db.prepare(`SELECT id, summary AS text, type AS kind, updated_at AS at, confidence FROM memories+ WHERE user_key = ? AND dismissed = 0 AND superseded_by IS NULL ORDER BY updated_at DESC LIMIT ?`).all(userKey, limit) as Array<{ id: string; text: string; kind: string; at: number; confidence: number }>;+ }++ /** Changes when any live belief or archive row changes: count + newest update. */+ knowledgeSignature(userKey: string, ownerKey: string, archive: boolean): string {+ const b = this.db.prepare(`SELECT COUNT(*) AS n, COALESCE(MAX(updated_at), 0) AS t FROM beliefs WHERE owner_key = ? AND status IN ('candidate','held','confirmed','contested')`).get(ownerKey) as { n: number; t: number };+ if (!archive) return `${b.n}:${b.t}`;+ const m = this.db.prepare(`SELECT COUNT(*) AS n, COALESCE(MAX(updated_at), 0) AS t FROM memories WHERE user_key = ? AND dismissed = 0 AND superseded_by IS NULL`).get(userKey) as { n: number; t: number };+ return `${b.n}:${b.t}|${m.n}:${m.t}`;+ }+setMeta(key: string, value: string): void {const stmt = this.db.prepare('INSERT OR REPLACE INTO second_brain_meta (key, value) VALUES (@key, @value)');stmt.run({ key, value });diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex 7de1ae92..a9614380 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -6,6 +6,7 @@ import { looksLikeSecret } from '../learning/text.js';import { join } from 'node:path';import { copyFileSync, existsSync } from 'node:fs';import { logger } from '../utils/logger.js';+import { buildKnowledgeMap, themeMemory, type KnowledgeMap, type ThemeMemory } from './knowledge-map.js';import { capKnown, standingOf, type PersonStanding, type PersonTier } from './person-standing.js';import { extractAliases, extractOwnerRelations, extractPersonLinks, isOwnerName, ownerNameSet } from './person-extract.js';@@ -98,6 +99,10 @@ export interface UserPersonRecord {// 10: owner is never a person, real relationship phrasing, aliases merged, person-to-person links, standing.const PERSON_INDEX_VERSION = '10';+export type KnowledgeMapResult = KnowledgeMap & {+ notes: Array<{ id: string; text: string; kind: string; at: number; confidence: number; archived: boolean }>;+};+export class UserMemoryStore {private db: SecondBrainDB;private userKey: string;@@ -110,6 +115,8 @@ export class UserMemoryStore {/** The owner's own names: never a person, always "you". */private ownerNames: Set<string>;+ /** Last knowledge map per mode, rebuilt only when the brain changed. */+ private mapCache = new Map<string, { key: string; value: KnowledgeMapResult }>();constructor(config: MercuryConfig, userKey: string = 'user:owner', dbPath?: string) {this.userKey = userKey;@@ -486,6 +493,34 @@ export class UserMemoryStore {return this.beliefs.list({ statuses: ['retired'], limit }).map((b) => this.toBeliefRecord(b));}+ /**+ * Everything known, as a mind map (knowledge-map.ts): themes, sub-themes,+ * notes and sparse "related" links. Local and free (no model calls);+ * cached until a belief or archive row changes; theme ids carry over from+ * the last build so colours and places stay put.+ */+ knowledgeMap(opts: { archive?: boolean } = {}): KnowledgeMapResult {+ const archive = !!opts.archive;+ const mode = archive ? 'archive' : 'live';+ const key = this.db.knowledgeSignature(this.userKey, this.userKey, archive);+ const hit = this.mapCache.get(mode);+ if (hit && hit.key === key) return hit.value;+ const now = Date.now();+ const notes: KnowledgeMapResult['notes'] = this.beliefs.list({ limit: 100_000 }).map((b) => ({+ id: b.id, text: b.statement, kind: b.kind, at: b.updatedAt, confidence: Number(this.beliefs.confidence(b, now).toFixed(3)), archived: false,+ }));+ if (archive) for (const r of this.db.archiveNotes(this.userKey)) notes.push({ ...r, archived: true });+ const metaKey = `knowledge_map_themes_v1_${mode}`;+ let previous: ThemeMemory = {};+ try { previous = JSON.parse(this.db.getMeta(metaKey) ?? '{}') as ThemeMemory; } catch { /* rebuild fresh */ }+ const owner = [...this.ownerNames].filter((n) => n !== 'user' && n !== 'the user');+ const map = buildKnowledgeMap(notes.map((n) => ({ id: n.id, text: n.text, kind: n.kind, at: n.at, weight: n.archived ? 0.5 : 1 })), previous, { ownerNames: owner });+ try { this.db.setMeta(metaKey, JSON.stringify(themeMemory(map))); } catch { /* ids just won't carry over */ }+ const value = { ...map, notes };+ this.mapCache.set(mode, { key, value });+ return value;+ }+getById(id: string): UserMemoryRecord | null {const belief = this.beliefs.get(id);if (belief) return this.toBeliefRecord(belief);diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex cb9231b4..60efc304 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -38,6 +38,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['usage.history', // GET /api/usage/history?days= — tokens per local day'brain.people', // PATCH/merge persons, person checks, GET /api/brain/graph/v2'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)+ 'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links]);export interface ApiContractInfo {diff --git a/src/web/api/brain.ts b/src/web/api/brain.tsindex 3820a503..30e4ed94 100644--- a/src/web/api/brain.ts+++ b/src/web/api/brain.ts@@ -315,6 +315,14 @@ brain.post('/api/brain/persons/:id/merge', async (c) => {return c.json({ person: into ? personToJson(into) : null });});+/** Everything known as a mind map: themes → sub-themes → notes, with sparse "related" links. Local, no model calls. */+brain.get('/api/brain/map', (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ available: false, error: SQLITE_DEPENDENCY_ERROR }, 503);+ const map = mem.knowledgeMap({ archive: c.req.query('archive') === '1' });+ return c.json({ ...map, available: true });+});+/** The brain as a graph of real links: memories, people, who appears where, who relates to whom. */brain.get('/api/brain/graph/v2', (c) => {const mem = ensureMemory();