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

perf: scale weighted knowledge graphs

nash_su66b0e8372326
diff --git a/src/lib/__tests__/wiki-graph.test.ts b/src/lib/__tests__/wiki-graph.test.ts
index 9f4dd1d4..dec6ab55 100644
--- a/src/lib/__tests__/wiki-graph.test.ts
+++ b/src/lib/__tests__/wiki-graph.test.ts
@@ -129,7 +129,9 @@ describe("buildWikiGraph frontmatter extraction", () => {
const second = await buildWikiGraph("/cached-project", 42)
expect(second).toBe(first)
- expect(mockListDirectory).toHaveBeenCalledTimes(1)
- expect(mockReadFile).toHaveBeenCalledTimes(1)
+ // The first graph build reads once for graph topology and once for
+ // relevance metadata; the second call is fully served by the cache.
+ expect(mockListDirectory).toHaveBeenCalledTimes(2)
+ expect(mockReadFile).toHaveBeenCalledTimes(2)
})
})
diff --git a/src/lib/graph-relevance.test.ts b/src/lib/graph-relevance.test.ts
new file mode 100644
index 00000000..f0e69b46
--- /dev/null
+++ b/src/lib/graph-relevance.test.ts
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { FileNode } from "@/types/wiki"
+
+const { listDirectory, readFile } = vi.hoisted(() => ({
+ listDirectory: vi.fn(),
+ readFile: vi.fn(),
+}))
+
+vi.mock("@/commands/fs", () => ({ listDirectory, readFile }))
+
+import { buildRetrievalGraph, clearGraphCache } from "./graph-relevance"
+
+function files(root: string, count: number): FileNode[] {
+ return Array.from({ length: count }, (_, index) => ({
+ name: `page-${index}.md`,
+ path: `${root}/wiki/page-${index}.md`,
+ is_dir: false,
+ }))
+}
+
+beforeEach(() => {
+ clearGraphCache()
+ listDirectory.mockReset()
+ readFile.mockReset()
+})
+
+describe("buildRetrievalGraph", () => {
+ it("reads wiki pages concurrently without exceeding the worker limit", async () => {
+ listDirectory.mockResolvedValue(files("/project", 40))
+ let active = 0
+ let peak = 0
+ readFile.mockImplementation(async () => {
+ active += 1
+ peak = Math.max(peak, active)
+ await new Promise((resolve) => setTimeout(resolve, 1))
+ active -= 1
+ return "---\ntype: concept\n---\n# Page"
+ })
+
+ const graph = await buildRetrievalGraph("/project", 1)
+
+ expect(graph.nodes.size).toBe(40)
+ expect(peak).toBeGreaterThan(1)
+ expect(peak).toBeLessThanOrEqual(16)
+ })
+
+ it("does not reuse a same-version cache entry across projects", async () => {
+ listDirectory.mockImplementation(async (root: string) => files(root.replace(/\/wiki$/, ""), 1))
+ readFile.mockImplementation(async (path: string) => `# ${path.includes("project-a") ? "A" : "B"}`)
+
+ const a = await buildRetrievalGraph("/project-a", 7)
+ const b = await buildRetrievalGraph("/project-b", 7)
+
+ expect(a.nodes.values().next().value?.title).toBe("A")
+ expect(b.nodes.values().next().value?.title).toBe("B")
+ expect(readFile).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/lib/graph-relevance.ts b/src/lib/graph-relevance.ts
index c7a578d9..f007c4fd 100644
--- a/src/lib/graph-relevance.ts
+++ b/src/lib/graph-relevance.ts
@@ -26,6 +26,8 @@ export interface RetrievalGraph {
// ---------------------------------------------------------------------------
const WIKILINK_REGEX = /\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g
+const GRAPH_FILE_READ_CONCURRENCY = 16
+const MAX_CACHED_RETRIEVAL_GRAPHS = 2
const WEIGHTS = {
directLink: 3.0,
@@ -46,7 +48,7 @@ const TYPE_AFFINITY: Record<string, Record<string, number>> = {
// Module-level cache
// ---------------------------------------------------------------------------
-let cachedGraph: RetrievalGraph | null = null
+const cachedGraphs = new Map<string, RetrievalGraph>()
// ---------------------------------------------------------------------------
// Helpers (pure)
@@ -64,6 +66,23 @@ function flattenMdFiles(nodes: readonly FileNode[]): FileNode[] {
return files
}
+async function mapWithConcurrency<T, R>(
+ values: readonly T[],
+ limit: number,
+ mapper: (value: T) => Promise<R>,
+): Promise<R[]> {
+ const results = new Array<R>(values.length)
+ let cursor = 0
+ const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
+ while (cursor < values.length) {
+ const index = cursor++
+ results[index] = await mapper(values[index])
+ }
+ })
+ await Promise.all(workers)
+ return results
+}
+
function fileNameToId(fileName: string): string {
return fileName.replace(/\.md$/, "")
}
@@ -156,25 +175,27 @@ export async function buildRetrievalGraph(
projectPath: string,
dataVersion: number = 0,
): Promise<RetrievalGraph> {
+ const normalizedProjectPath = normalizePath(projectPath)
// Return cached if version matches
- if (cachedGraph !== null && cachedGraph.dataVersion === dataVersion) {
+ const cachedGraph = cachedGraphs.get(normalizedProjectPath)
+ if (cachedGraph?.dataVersion === dataVersion) {
return cachedGraph
}
- const wikiRoot = `${normalizePath(projectPath)}/wiki`
+ const wikiRoot = `${normalizedProjectPath}/wiki`
let tree: FileNode[]
try {
tree = await listDirectory(wikiRoot)
} catch {
const emptyGraph: RetrievalGraph = { nodes: new Map(), dataVersion }
- cachedGraph = emptyGraph
+ cacheRetrievalGraph(normalizedProjectPath, emptyGraph)
return emptyGraph
}
const mdFiles = flattenMdFiles(tree)
// First pass: read all files and build raw node data
- const rawNodes: Array<{
+ type RawNode = {
id: string
title: string
type: string
@@ -182,29 +203,31 @@ export async function buildRetrievalGraph(
sources: string[]
rawLinks: string[]
fileName: string
- }> = []
-
- for (const file of mdFiles) {
- const id = fileNameToId(file.name)
- let content = ""
- try {
- content = await readFile(file.path)
- } catch {
- continue
- }
-
- const fm = extractFrontmatter(content)
- rawNodes.push({
- id,
- title: fm.title || file.name.replace(/\.md$/, "").replace(/-/g, " "),
- type: fm.type,
- path: file.path,
- sources: fm.sources,
- rawLinks: extractWikilinks(content),
- fileName: file.name,
- })
}
+ const parsedFiles = await mapWithConcurrency<FileNode, RawNode | null>(
+ mdFiles,
+ GRAPH_FILE_READ_CONCURRENCY,
+ async (file) => {
+ try {
+ const content = await readFile(file.path)
+ const fm = extractFrontmatter(content)
+ return {
+ id: fileNameToId(file.name),
+ title: fm.title || file.name.replace(/\.md$/, "").replace(/-/g, " "),
+ type: fm.type,
+ path: file.path,
+ sources: fm.sources,
+ rawLinks: extractWikilinks(content),
+ fileName: file.name,
+ }
+ } catch {
+ return null
+ }
+ },
+ )
+ const rawNodes = parsedFiles.filter((node): node is RawNode => node !== null)
+
const nodeIds = new Set(rawNodes.map((n) => n.id))
// Second pass: resolve links and build graph nodes
@@ -240,10 +263,19 @@ export async function buildRetrievalGraph(
}
const graph: RetrievalGraph = { nodes, dataVersion }
- cachedGraph = graph
+ cacheRetrievalGraph(normalizedProjectPath, graph)
return graph
}
+function cacheRetrievalGraph(projectPath: string, graph: RetrievalGraph): void {
+ cachedGraphs.delete(projectPath)
+ if (cachedGraphs.size >= MAX_CACHED_RETRIEVAL_GRAPHS) {
+ const oldest = cachedGraphs.keys().next().value
+ if (oldest) cachedGraphs.delete(oldest)
+ }
+ cachedGraphs.set(projectPath, graph)
+}
+
export function calculateRelevance(
nodeA: RetrievalNode,
nodeB: RetrievalNode,
@@ -308,5 +340,5 @@ export function getRelatedNodes(
}
export function clearGraphCache(): void {
- cachedGraph = null
+ cachedGraphs.clear()
}
diff --git a/src/lib/wiki-graph.ts b/src/lib/wiki-graph.ts
index 7a4dd165..ffdf77a2 100644
--- a/src/lib/wiki-graph.ts
+++ b/src/lib/wiki-graph.ts
@@ -34,8 +34,7 @@ export interface WikiGraphResult {
}
const GRAPH_FILE_READ_CONCURRENCY = 16
-const MAX_WEIGHTED_GRAPH_NODES = 3_000
-const COMMUNITY_WORKER_THRESHOLD = 3_000
+const COMMUNITY_WORKER_THRESHOLD = 500
const MAX_CACHED_PROJECT_GRAPHS = 2
const graphCache = new Map<string, { dataVersion: number; result: WikiGraphResult }>()
const graphBuilds = new Map<string, Promise<WikiGraphResult>>()
@@ -283,14 +282,12 @@ async function buildWikiGraphUncached(projectPath: string): Promise<WikiGraphRes
// Calculate relevance weights using the retrieval graph
let retrievalGraph: Awaited<ReturnType<typeof buildRetrievalGraph>> | null = null
- if (nodeMap.size <= MAX_WEIGHTED_GRAPH_NODES) {
- try {
- const { useWikiStore } = await import("@/stores/wiki-store")
- const dv = useWikiStore.getState().dataVersion
- retrievalGraph = await buildRetrievalGraph(normalizePath(projectPath), dv)
- } catch {
- // ignore — weights will default to 1
- }
+ try {
+ const { useWikiStore } = await import("@/stores/wiki-store")
+ const dv = useWikiStore.getState().dataVersion
+ retrievalGraph = await buildRetrievalGraph(normalizePath(projectPath), dv)
+ } catch {
+ // Keep the graph available with neutral weights if relevance enrichment fails.
}
const edges: GraphEdge[] = dedupedEdges.map((e) => {