Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add Graph View — visualize wiki page relationships

nash_su76a47c01d28f
diff --git a/package-lock.json b/package-lock.json
index 548f7cd5..9fa61e5d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,18 +13,24 @@
"@milkdown/kit": "^7.20.0",
"@milkdown/react": "^7.20.0",
"@milkdown/theme-nord": "^7.20.0",
+ "@react-sigma/core": "^5.0.6",
"@tailwindcss/vite": "^4.2.2",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.7.0",
"@tauri-apps/plugin-store": "^2.4.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "graphology": "^0.26.0",
+ "graphology-layout-forceatlas2": "^0.10.1",
+ "i18next": "^26.0.3",
"lucide-react": "^1.7.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
+ "react-i18next": "^17.0.2",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^4.9.0",
"shadcn": "^4.1.2",
+ "sigma": "^3.0.2",
"tailwind-merge": "^3.5.0",
"tailwindcss": "^4.2.2",
"tw-animate-css": "^1.4.0",
@@ -2032,6 +2038,17 @@
"url": "https://github.com/sponsors/Boshen"
}
},
+ "node_modules/@react-sigma/core": {
+ "version": "5.0.6",
+ "resolved": "https://registry.npmjs.org/@react-sigma/core/-/core-5.0.6.tgz",
+ "integrity": "sha512-Xu2qXyvDZIhmvGC1n8d7Kcxm5Ntcz4HbPIM7CPDD2e4h3s/oxVpVPX7wtsNreJRRPj9mK+3oqB6SWXNI4mTqVg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "graphology": "^0.26.0",
+ "react": "^18.0.0 || ^19.0.0",
+ "sigma": "^3.0.2"
+ }
+ },
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.0-rc.12",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.12.tgz",
@@ -4134,6 +4151,15 @@
"node": ">= 0.6"
}
},
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
"node_modules/eventsource": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
@@ -4581,6 +4607,46 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
+ "node_modules/graphology": {
+ "version": "0.26.0",
+ "resolved": "https://registry.npmjs.org/graphology/-/graphology-0.26.0.tgz",
+ "integrity": "sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==",
+ "license": "MIT",
+ "dependencies": {
+ "events": "^3.3.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.24.0"
+ }
+ },
+ "node_modules/graphology-layout-forceatlas2": {
+ "version": "0.10.1",
+ "resolved": "https://registry.npmjs.org/graphology-layout-forceatlas2/-/graphology-layout-forceatlas2-0.10.1.tgz",
+ "integrity": "sha512-ogzBeF1FvWzjkikrIFwxhlZXvD2+wlY54lqhsrWprcdPjopM2J9HoMweUmIgwaTvY4bUYVimpSsOdvDv1gPRFQ==",
+ "license": "MIT",
+ "dependencies": {
+ "graphology-utils": "^2.1.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.19.0"
+ }
+ },
+ "node_modules/graphology-types": {
+ "version": "0.24.8",
+ "resolved": "https://registry.npmjs.org/graphology-types/-/graphology-types-0.24.8.tgz",
+ "integrity": "sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q==",
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/graphology-utils": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/graphology-utils/-/graphology-utils-2.5.2.tgz",
+ "integrity": "sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "graphology-types": ">=0.23.0"
+ }
+ },
"node_modules/graphql": {
"version": "16.13.2",
"resolved": "https://registry.npmjs.org/graphql/-/graphql-16.13.2.tgz",
@@ -4669,6 +4735,15 @@
"node": ">=16.9.0"
}
},
+ "node_modules/html-parse-stringify": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
+ "integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",
+ "license": "MIT",
+ "dependencies": {
+ "void-elements": "3.1.0"
+ }
+ },
"node_modules/html-url-attributes": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
@@ -4721,6 +4796,37 @@
"node": ">=18.18.0"
}
},
+ "node_modules/i18next": {
+ "version": "26.0.3",
+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.0.3.tgz",
+ "integrity": "sha512-1571kXINxHKY7LksWp8wP+zP0YqHSSpl/OW0Y0owFEf2H3s8gCAffWaZivcz14rMkOvn3R/psiQxVsR9t2Nafg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://www.locize.com/i18next"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.locize.com"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.29.2"
+ },
+ "peerDependencies": {
+ "typescript": "^5 || ^6"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
"node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
@@ -7321,6 +7427,33 @@
"react": "^19.2.4"
}
},
+ "node_modules/react-i18next": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.2.tgz",
+ "integrity": "sha512-shBftH2vaTWK2Bsp7FiL+cevx3xFJlvFxmsDFQSrJc+6twHkP0tv/bGa01VVWzpreUVVwU+3Hev5iFqRg65RwA==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.29.2",
+ "html-parse-stringify": "^3.0.1",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "peerDependencies": {
+ "i18next": ">= 26.0.1",
+ "react": ">= 16.8.0",
+ "typescript": "^5 || ^6"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ },
+ "react-native": {
+ "optional": true
+ },
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
"node_modules/react-markdown": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
@@ -7868,6 +8001,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/sigma": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/sigma/-/sigma-3.0.2.tgz",
+ "integrity": "sha512-/BUbeOwPGruiBOm0YQQ6ZMcLIZ6tf/W+Jcm7dxZyAX0tK3WP9/sq7/NAWBxPIxVahdGjCJoGwej0Gdrv0DxlQQ==",
+ "license": "MIT",
+ "dependencies": {
+ "events": "^3.3.0",
+ "graphology-utils": "^2.5.2"
+ }
+ },
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
@@ -8586,6 +8729,15 @@
}
}
},
+ "node_modules/void-elements": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
+ "integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/vue": {
"version": "3.5.32",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.32.tgz",
diff --git a/package.json b/package.json
index a8c9dc35..b44fa302 100644
--- a/package.json
+++ b/package.json
@@ -15,18 +15,24 @@
"@milkdown/kit": "^7.20.0",
"@milkdown/react": "^7.20.0",
"@milkdown/theme-nord": "^7.20.0",
+ "@react-sigma/core": "^5.0.6",
"@tailwindcss/vite": "^4.2.2",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.7.0",
"@tauri-apps/plugin-store": "^2.4.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "graphology": "^0.26.0",
+ "graphology-layout-forceatlas2": "^0.10.1",
+ "i18next": "^26.0.3",
"lucide-react": "^1.7.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
+ "react-i18next": "^17.0.2",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^4.9.0",
"shadcn": "^4.1.2",
+ "sigma": "^3.0.2",
"tailwind-merge": "^3.5.0",
"tailwindcss": "^4.2.2",
"tw-animate-css": "^1.4.0",
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsx
new file mode 100644
index 00000000..ff35f7c3
--- /dev/null
+++ b/src/components/graph/graph-view.tsx
@@ -0,0 +1,309 @@
+import { useEffect, useCallback, useState } from "react"
+import Graph from "graphology"
+import { SigmaContainer, useLoadGraph, useRegisterEvents, useSigma } from "@react-sigma/core"
+import "@react-sigma/core/lib/style.css"
+import forceAtlas2 from "graphology-layout-forceatlas2"
+import { Network, RefreshCw } from "lucide-react"
+import { useWikiStore } from "@/stores/wiki-store"
+import { readFile } from "@/commands/fs"
+import { buildWikiGraph, type GraphNode, type GraphEdge } from "@/lib/wiki-graph"
+
+const NODE_TYPE_COLORS: Record<string, string> = {
+ entity: "#3b82f6", // blue
+ concept: "#a855f7", // purple
+ source: "#f97316", // orange
+ query: "#22c55e", // green
+ synthesis: "#ef4444", // red
+ overview: "#eab308", // yellow
+ other: "#9ca3af", // gray
+}
+
+const NODE_TYPE_LABELS: Record<string, string> = {
+ entity: "Entity",
+ concept: "Concept",
+ source: "Source",
+ query: "Query",
+ synthesis: "Synthesis",
+ overview: "Overview",
+ other: "Other",
+}
+
+const BASE_NODE_SIZE = 6
+const MAX_NODE_SIZE = 24
+
+function nodeColor(type: string): string {
+ return NODE_TYPE_COLORS[type] ?? NODE_TYPE_COLORS.other
+}
+
+function nodeSize(linkCount: number, maxLinks: number): number {
+ if (maxLinks === 0) return BASE_NODE_SIZE
+ const ratio = linkCount / maxLinks
+ return BASE_NODE_SIZE + ratio * (MAX_NODE_SIZE - BASE_NODE_SIZE)
+}
+
+// --- Inner components that use sigma hooks (must be children of SigmaContainer) ---
+
+interface GraphLoaderProps {
+ nodes: GraphNode[]
+ edges: GraphEdge[]
+}
+
+function GraphLoader({ nodes, edges }: GraphLoaderProps) {
+ const loadGraph = useLoadGraph()
+
+ useEffect(() => {
+ const graph = new Graph()
+ const maxLinks = Math.max(...nodes.map((n) => n.linkCount), 0)
+
+ for (const node of nodes) {
+ graph.addNode(node.id, {
+ x: Math.random() * 100,
+ y: Math.random() * 100,
+ size: nodeSize(node.linkCount, maxLinks),
+ color: nodeColor(node.type),
+ label: node.label,
+ nodeType: node.type,
+ nodePath: node.path,
+ })
+ }
+
+ for (const edge of edges) {
+ if (graph.hasNode(edge.source) && graph.hasNode(edge.target)) {
+ graph.addEdge(edge.source, edge.target, {
+ color: "#e5e7eb",
+ size: 1,
+ })
+ }
+ }
+
+ // Run ForceAtlas2 layout for positioning
+ if (nodes.length > 1) {
+ forceAtlas2.assign(graph, {
+ iterations: 100,
+ settings: forceAtlas2.inferSettings(graph),
+ })
+ }
+
+ loadGraph(graph)
+ }, [loadGraph, nodes, edges])
+
+ return null
+}
+
+interface EventHandlerProps {
+ onNodeClick: (nodeId: string) => void
+}
+
+function EventHandler({ onNodeClick }: EventHandlerProps) {
+ const registerEvents = useRegisterEvents()
+ const sigma = useSigma()
+
+ useEffect(() => {
+ registerEvents({
+ clickNode: ({ node }) => {
+ onNodeClick(node)
+ },
+ enterNode: ({ node }) => {
+ const container = sigma.getContainer()
+ container.style.cursor = "pointer"
+ // Highlight node on hover
+ sigma.getGraph().setNodeAttribute(node, "highlighted", true)
+ sigma.refresh()
+ },
+ leaveNode: ({ node }) => {
+ const container = sigma.getContainer()
+ container.style.cursor = "default"
+ sigma.getGraph().setNodeAttribute(node, "highlighted", false)
+ sigma.refresh()
+ },
+ })
+ }, [registerEvents, sigma, onNodeClick])
+
+ return null
+}
+
+// --- Main GraphView component ---
+
+export function GraphView() {
+ const project = useWikiStore((s) => s.project)
+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+ const setFileContent = useWikiStore((s) => s.setFileContent)
+ const setActiveView = useWikiStore((s) => s.setActiveView)
+
+ const [nodes, setNodes] = useState<GraphNode[]>([])
+ const [edges, setEdges] = useState<GraphEdge[]>([])
+ const [loading, setLoading] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [loaded, setLoaded] = useState(false)
+
+ const loadGraph = useCallback(async () => {
+ if (!project) return
+ setLoading(true)
+ setError(null)
+ try {
+ const result = await buildWikiGraph(project.path)
+ setNodes(result.nodes)
+ setEdges(result.edges)
+ setLoaded(true)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "Failed to build graph"
+ setError(message)
+ } finally {
+ setLoading(false)
+ }
+ }, [project])
+
+ // Auto-load on mount when a project is open
+ useEffect(() => {
+ if (project && !loaded) {
+ loadGraph()
+ }
+ }, [project, loaded, loadGraph])
+
+ const handleNodeClick = useCallback(
+ async (nodeId: string) => {
+ const node = nodes.find((n) => n.id === nodeId)
+ if (!node) return
+ try {
+ const content = await readFile(node.path)
+ setSelectedFile(node.path)
+ setFileContent(content)
+ setActiveView("wiki")
+ } catch (err) {
+ console.error("Failed to open wiki page:", err)
+ }
+ },
+ [nodes, setSelectedFile, setFileContent, setActiveView],
+ )
+
+ if (!project) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <Network className="h-10 w-10 opacity-30" />
+ <p className="text-sm">Open a project to view the graph</p>
+ </div>
+ )
+ }
+
+ if (loading) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <RefreshCw className="h-8 w-8 animate-spin opacity-50" />
+ <p className="text-sm">Building graph...</p>
+ </div>
+ )
+ }
+
+ if (error) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <Network className="h-10 w-10 opacity-30" />
+ <p className="text-sm text-destructive">{error}</p>
+ <button
+ type="button"
+ onClick={loadGraph}
+ className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent transition-colors"
+ >
+ Retry
+ </button>
+ </div>
+ )
+ }
+
+ if (loaded && nodes.length === 0) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <Network className="h-10 w-10 opacity-30" />
+ <p className="text-sm">No pages yet</p>
+ <p className="text-xs">Create some wiki pages to see the graph</p>
+ </div>
+ )
+ }
+
+ if (!loaded) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
+ <Network className="h-10 w-10 opacity-30" />
+ <p className="text-sm">Graph not loaded</p>
+ <button
+ type="button"
+ onClick={loadGraph}
+ className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent transition-colors"
+ >
+ Load Graph
+ </button>
+ </div>
+ )
+ }
+
+ return (
+ <div className="relative flex h-full flex-col">
+ {/* Header */}
+ <div className="flex items-center justify-between border-b px-4 py-2 shrink-0">
+ <div className="flex items-center gap-2">
+ <Network className="h-4 w-4 text-muted-foreground" />
+ <span className="text-sm font-medium">Graph</span>
+ <span className="text-xs text-muted-foreground">
+ {nodes.length} node{nodes.length !== 1 ? "s" : ""},{" "}
+ {edges.length} edge{edges.length !== 1 ? "s" : ""}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={loadGraph}
+ title="Reload graph"
+ className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent transition-colors"
+ >
+ <RefreshCw className="h-3.5 w-3.5" />
+ Reload
+ </button>
+ </div>
+
+ {/* Graph canvas */}
+ <div className="relative flex-1 overflow-hidden">
+ <SigmaContainer
+ style={{ width: "100%", height: "100%", background: "transparent" }}
+ settings={{
+ renderEdgeLabels: false,
+ defaultEdgeColor: "#e5e7eb",
+ defaultNodeColor: "#9ca3af",
+ labelSize: 12,
+ labelWeight: "normal",
+ labelColor: { color: "var(--foreground, #111827)" },
+ nodeReducer: (_node, attrs) => ({
+ ...attrs,
+ highlighted: attrs.highlighted ?? false,
+ }),
+ }}
+ >
+ <GraphLoader nodes={nodes} edges={edges} />
+ <EventHandler onNodeClick={handleNodeClick} />
+ </SigmaContainer>
+
+ {/* Legend */}
+ <GraphLegend />
+ </div>
+ </div>
+ )
+}
+
+function GraphLegend() {
+ const usedTypes = Object.entries(NODE_TYPE_LABELS)
+
+ return (
+ <div className="absolute bottom-4 right-4 rounded-lg border bg-background/90 backdrop-blur-sm px-3 py-2 text-xs shadow-sm">
+ <div className="mb-1.5 font-medium text-muted-foreground">Node types</div>
+ <div className="flex flex-col gap-1">
+ {usedTypes.map(([type, label]) => (
+ <div key={type} className="flex items-center gap-2">
+ <span
+ className="inline-block h-2.5 w-2.5 rounded-full shrink-0"
+ style={{ backgroundColor: NODE_TYPE_COLORS[type] }}
+ />
+ <span className="text-muted-foreground">{label}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/layout/content-area.tsx b/src/components/layout/content-area.tsx
index d7fe9cc5..ac026369 100644
--- a/src/components/layout/content-area.tsx
+++ b/src/components/layout/content-area.tsx
@@ -5,6 +5,7 @@ import { SourcesView } from "@/components/sources/sources-view"
import { ReviewView } from "@/components/review/review-view"
import { LintView } from "@/components/lint/lint-view"
import { SearchView } from "@/components/search/search-view"
+import { GraphView } from "@/components/graph/graph-view"
export function ContentArea() {
const activeView = useWikiStore((s) => s.activeView)
@@ -20,6 +21,8 @@ export function ContentArea() {
return <LintView />
case "search":
return <SearchView />
+ case "graph":
+ return <GraphView />
default:
return <ChatPanel />
}
diff --git a/src/lib/wiki-graph.ts b/src/lib/wiki-graph.ts
new file mode 100644
index 00000000..d462146d
--- /dev/null
+++ b/src/lib/wiki-graph.ts
@@ -0,0 +1,163 @@
+import { readFile, listDirectory } from "@/commands/fs"
+import type { FileNode } from "@/types/wiki"
+
+export interface GraphNode {
+ id: string
+ label: string
+ type: string
+ path: string
+ linkCount: number // inbound + outbound
+}
+
+export interface GraphEdge {
+ source: string
+ target: string
+}
+
+const WIKILINK_REGEX = /\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g
+
+function flattenMdFiles(nodes: FileNode[]): FileNode[] {
+ const files: FileNode[] = []
+ for (const node of nodes) {
+ if (node.is_dir && node.children) {
+ files.push(...flattenMdFiles(node.children))
+ } else if (!node.is_dir && node.name.endsWith(".md")) {
+ files.push(node)
+ }
+ }
+ return files
+}
+
+function extractTitle(content: string, fileName: string): string {
+ const frontmatterTitleMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
+ if (frontmatterTitleMatch) return frontmatterTitleMatch[1].trim()
+
+ const headingMatch = content.match(/^#\s+(.+)$/m)
+ if (headingMatch) return headingMatch[1].trim()
+
+ return fileName.replace(/\.md$/, "").replace(/-/g, " ")
+}
+
+function extractType(content: string): string {
+ const frontmatterTypeMatch = content.match(/^---\n[\s\S]*?^type:\s*["']?(.+?)["']?\s*$/m)
+ if (frontmatterTypeMatch) return frontmatterTypeMatch[1].trim().toLowerCase()
+ return "other"
+}
+
+function extractWikilinks(content: string): string[] {
+ const links: string[] = []
+ const regex = new RegExp(WIKILINK_REGEX.source, "g")
+ let match: RegExpExecArray | null
+ while ((match = regex.exec(content)) !== null) {
+ links.push(match[1].trim())
+ }
+ return links
+}
+
+function fileNameToId(fileName: string): string {
+ return fileName.replace(/\.md$/, "")
+}
+
+export async function buildWikiGraph(
+ projectPath: string,
+): Promise<{ nodes: GraphNode[]; edges: GraphEdge[] }> {
+ const wikiRoot = `${projectPath}/wiki`
+
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(wikiRoot)
+ } catch {
+ return { nodes: [], edges: [] }
+ }
+
+ const mdFiles = flattenMdFiles(tree)
+ if (mdFiles.length === 0) {
+ return { nodes: [], edges: [] }
+ }
+
+ // Build a map of id -> node data
+ const nodeMap = new Map<
+ string,
+ { id: string; label: string; type: string; path: string; links: string[] }
+ >()
+
+ for (const file of mdFiles) {
+ const id = fileNameToId(file.name)
+ let content = ""
+ try {
+ content = await readFile(file.path)
+ } catch {
+ // Skip unreadable files
+ continue
+ }
+
+ nodeMap.set(id, {
+ id,
+ label: extractTitle(content, file.name),
+ type: extractType(content),
+ path: file.path,
+ links: extractWikilinks(content),
+ })
+ }
+
+ // Count link references
+ const linkCounts = new Map<string, number>()
+ for (const [id] of nodeMap) {
+ linkCounts.set(id, 0)
+ }
+
+ const rawEdges: GraphEdge[] = []
+
+ for (const [sourceId, nodeData] of nodeMap) {
+ for (const targetRaw of nodeData.links) {
+ // Normalize target: try matching by id (case-insensitive, hyphen/space)
+ const targetId = resolveTarget(targetRaw, nodeMap)
+ if (targetId === null) continue
+ if (targetId === sourceId) continue
+
+ rawEdges.push({ source: sourceId, target: targetId })
+
+ linkCounts.set(sourceId, (linkCounts.get(sourceId) ?? 0) + 1)
+ linkCounts.set(targetId, (linkCounts.get(targetId) ?? 0) + 1)
+ }
+ }
+
+ // Deduplicate edges (keep only unique source->target pairs)
+ const seenEdges = new Set<string>()
+ const edges: GraphEdge[] = []
+ for (const edge of rawEdges) {
+ const key = `${edge.source}:::${edge.target}`
+ if (!seenEdges.has(key)) {
+ seenEdges.add(key)
+ edges.push(edge)
+ }
+ }
+
+ const nodes: GraphNode[] = Array.from(nodeMap.values()).map((n) => ({
+ id: n.id,
+ label: n.label,
+ type: n.type,
+ path: n.path,
+ linkCount: linkCounts.get(n.id) ?? 0,
+ }))
+
+ return { nodes, edges }
+}
+
+function resolveTarget(
+ raw: string,
+ nodeMap: Map<string, { id: string }>,
+): string | null {
+ // Direct match
+ if (nodeMap.has(raw)) return raw
+
+ // Normalize: lowercase, replace spaces with hyphens and vice versa
+ const normalized = raw.toLowerCase().replace(/\s+/g, "-")
+ for (const id of nodeMap.keys()) {
+ if (id.toLowerCase() === normalized) return id
+ if (id.toLowerCase() === raw.toLowerCase()) return id
+ if (id.toLowerCase().replace(/\s+/g, "-") === normalized) return id
+ }
+
+ return null
+}