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
fix: include related metadata in graph links
nash_sub726bd16eaa2
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 266862e5..ccc00bd7 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -2674,7 +2674,7 @@ fn build_graph_from_files(let title = commands::search::extract_title(&content, fallback_name);let node_type = extract_type(&content);let relative_path = relative_to_project(project_path, path);- let links = extract_wikilinks(&content);+ let links = commands::search::extract_graph_links(&content);raw.insert(id, (title, node_type, relative_path, links));}let aliases = graph_aliases(&raw);@@ -2817,24 +2817,6 @@ fn extract_type(content: &str) -> String {"other".to_string()}-fn extract_wikilinks(content: &str) -> Vec<String> {- let mut out = Vec::new();- let mut rest = content;- while let Some(start) = rest.find("[[") {- rest = &rest[start + 2..];- let Some(end) = rest.find("]]") else {- break;- };- let inner = &rest[..end];- let target = inner.split('|').next().unwrap_or("").trim();- if !target.is_empty() {- out.push(target.to_string());- }- rest = &rest[end + 2..];- }- out-}-fn resolve_link(raw: &str, aliases: &GraphAliases) -> Option<String> {let exact = raw.split('|')@@ -2980,6 +2962,23 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[test]+ fn graph_includes_frontmatter_related_links() {+ let root = test_project_dir();+ fs::write(+ root.join("wiki/source.md"),+ "---\nrelated: [target]\n---\n# Source",+ )+ .unwrap();+ fs::write(root.join("wiki/target.md"), "# Target").unwrap();++ let (_, edges) = build_graph(root.to_string_lossy().as_ref()).unwrap();+ assert!(edges+ .iter()+ .any(|edge| edge.source == "source" && edge.target == "target"));+ let _ = fs::remove_dir_all(root);+ }+#[test]fn graph_does_not_resolve_ambiguous_bare_stems() {let root = test_project_dir();diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex f3604499..c1f29761 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -204,7 +204,7 @@ fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinksGraphPage {path,title,- links: extract_wikilinks(&content),+ links: extract_graph_links(&content),content,},);@@ -401,7 +401,7 @@ pub async fn search_project_inner(GraphPage {path: relative_path,title,- links: extract_wikilinks(&content),+ links: extract_graph_links(&content),content,},);@@ -670,7 +670,7 @@ fn normalize_graph_alias(value: &str) -> String {.to_lowercase()}-fn extract_wikilinks(content: &str) -> Vec<String> {+pub(crate) fn extract_graph_links(content: &str) -> Vec<String> {let mut links = Vec::new();let mut rest = content;while let Some(start) = rest.find("[[") {@@ -684,9 +684,67 @@ fn extract_wikilinks(content: &str) -> Vec<String> {}rest = &rest[end + 2..];}+ for related in extract_related_frontmatter(content) {+ if !links.contains(&related) {+ links.push(related);+ }+ }links}+fn extract_related_frontmatter(content: &str) -> Vec<String> {+ let normalized = content.replace("\r\n", "\n");+ let Some(rest) = normalized.strip_prefix("---\n") else {+ return Vec::new();+ };+ let Some(end) = rest.find("\n---") else {+ return Vec::new();+ };+ let lines: Vec<&str> = rest[..end].lines().collect();+ let mut out = Vec::new();+ let mut index = 0;+ while index < lines.len() {+ let line = lines[index];+ let Some(value) = line.trim().strip_prefix("related:") else {+ index += 1;+ continue;+ };+ let value = value.trim();+ if value.starts_with('[') && value.ends_with(']') {+ for item in value[1..value.len() - 1].split(',') {+ if let Some(item) = normalize_related_value(item) {+ out.push(item);+ }+ }+ } else if value.is_empty() {+ index += 1;+ while index < lines.len() {+ let trimmed = lines[index].trim();+ let Some(item) = trimmed.strip_prefix('-') else {+ break;+ };+ if let Some(item) = normalize_related_value(item) {+ out.push(item);+ }+ index += 1;+ }+ continue;+ }+ index += 1;+ }+ out+}++fn normalize_related_value(value: &str) -> Option<String> {+ let value = value.trim().trim_matches('"').trim_matches('\'').trim();+ let value = value+ .strip_prefix("[[")+ .and_then(|value| value.strip_suffix("]]"))+ .unwrap_or(value)+ .trim();+ (!value.is_empty()).then(|| value.to_string())+}+fn search_mode(token_rank_empty: bool, vector_hits: usize, graph_hits: usize) -> &'static str {if graph_hits > 0 {"hybrid"@@ -1705,6 +1763,17 @@ mod tests {assert_eq!(refs[0].alt, "a");}+ #[test]+ fn graph_links_include_frontmatter_related_and_dedupe_body_links() {+ let links = extract_graph_links("---\nrelated: [foo, \"[[bar]]\"]\n---\n# Page\n[[foo]]");+ assert_eq!(links, vec!["bar", "foo"]);++ let block_links = extract_graph_links(+ "---\r\nrelated:\r\n - wiki/entities/alpha.md\r\n - beta\r\n---\r\n# Page",+ );+ assert_eq!(block_links, vec!["wiki/entities/alpha.md", "beta"]);+ }+#[test]fn extract_title_uses_frontmatter_or_heading_not_body_title_lines() {let with_frontmatter = "---\ntitle: Real Title\n---\n\ntitle: Body Label\n# Heading";diff --git a/src/lib/__tests__/wiki-graph.test.ts b/src/lib/__tests__/wiki-graph.test.tsindex dec6ab55..45f8744e 100644--- a/src/lib/__tests__/wiki-graph.test.ts+++ b/src/lib/__tests__/wiki-graph.test.ts@@ -100,6 +100,25 @@ describe("buildWikiGraph frontmatter extraction", () => {])})+ it("includes frontmatter related entries as graph edges", async () => {+ const buildWikiGraph = await loadBuildWikiGraph()+ mockListDirectory.mockResolvedValue([+ mdFile("source.md"),+ mdFile("target.md"),+ ])+ mockReadFile.mockImplementation(async (path: string) =>+ path.endsWith("source.md")+ ? "---\nrelated: [wiki/concepts/target.md]\n---\n# Source"+ : "# Target",+ )++ const graph = await buildWikiGraph("/related-project")++ expect(graph.edges).toEqual([+ expect.objectContaining({ source: "source", target: "target" }),+ ])+ })+it("prefers an exact page id when case-folded aliases collide", async () => {const buildWikiGraph = await loadBuildWikiGraph()mockListDirectory.mockResolvedValue([diff --git a/src/lib/graph-relevance.test.ts b/src/lib/graph-relevance.test.tsindex f0e69b46..389fcb9e 100644--- a/src/lib/graph-relevance.test.ts+++ b/src/lib/graph-relevance.test.ts@@ -55,4 +55,20 @@ describe("buildRetrievalGraph", () => {expect(b.nodes.values().next().value?.title).toBe("B")expect(readFile).toHaveBeenCalledTimes(2)})++ it("includes frontmatter related entries in retrieval links", async () => {+ listDirectory.mockResolvedValue([+ ...files("/project", 2),+ ])+ readFile.mockImplementation(async (path: string) =>+ path.endsWith("page-0.md")+ ? "---\nrelated: [page-1]\n---\n# Source"+ : "# Target",+ )++ const graph = await buildRetrievalGraph("/project", 2)++ expect(graph.nodes.get("page-0")?.outLinks).toContain("page-1")+ expect(graph.nodes.get("page-1")?.inLinks).toContain("page-0")+ })})diff --git a/src/lib/graph-relevance.ts b/src/lib/graph-relevance.tsindex f007c4fd..9bf6c5e1 100644--- a/src/lib/graph-relevance.ts+++ b/src/lib/graph-relevance.ts@@ -1,6 +1,7 @@import { readFile, listDirectory } from "@/commands/fs"import type { FileNode } from "@/types/wiki"import { normalizePath } from "@/lib/path-utils"+import { parseFrontmatter } from "@/lib/frontmatter"// ---------------------------------------------------------------------------// Types@@ -87,7 +88,7 @@ function fileNameToId(fileName: string): string {return fileName.replace(/\.md$/, "")}-function extractFrontmatter(content: string): { title: string; type: string; sources: string[] } {+function extractFrontmatter(content: string): { title: string; type: string; sources: string[]; related: string[] } {const fmMatch = content.match(/^---\n([\s\S]*?)\n---/)const fm = fmMatch ? fmMatch[1] : ""@@ -96,6 +97,7 @@ function extractFrontmatter(content: string): { title: string; type: string; sou// Parse sources array from YAML frontmatterconst sources: string[] = []+ const related: string[] = []const sourcesBlockMatch = fm.match(/^sources:\s*\n((?:\s+-\s+.+\n?)*)/m)if (sourcesBlockMatch) {const lines = sourcesBlockMatch[1].split("\n")@@ -117,6 +119,23 @@ function extractFrontmatter(content: string): { title: string; type: string; sou}}+ const parsedRelated = parseFrontmatter(content).frontmatter?.related+ if (Array.isArray(parsedRelated)) {+ for (const item of parsedRelated) {+ if (typeof item !== "string") continue+ const normalized = item+ .trim()+ .replace(/^\[\[|\]\]$/g, "")+ .split("|")[0]+ .split("#")[0]+ .replace(/\\/g, "/")+ .split("/")+ .pop()+ ?.replace(/\.md$/i, "") ?? ""+ if (normalized) related.push(normalized)+ }+ }+let title = titleMatch ? titleMatch[1].trim() : ""if (!title) {const headingMatch = content.match(/^#\s+(.+)$/m)@@ -127,6 +146,7 @@ function extractFrontmatter(content: string): { title: string; type: string; soutitle,type: typeMatch ? typeMatch[1].trim().toLowerCase() : "other",sources,+ related,}}@@ -218,7 +238,7 @@ export async function buildRetrievalGraph(type: fm.type,path: file.path,sources: fm.sources,- rawLinks: extractWikilinks(content),+ rawLinks: Array.from(new Set([...extractWikilinks(content), ...fm.related])),fileName: file.name,}} catch {diff --git a/src/lib/wiki-graph.ts b/src/lib/wiki-graph.tsindex 5241cbff..f47ebd09 100644--- a/src/lib/wiki-graph.ts+++ b/src/lib/wiki-graph.ts@@ -111,6 +111,17 @@ function extractWikilinks(content: string): string[] {return links}+function extractRelated(content: string): string[] {+ const related = parseFrontmatter(content).frontmatter?.related+ if (!Array.isArray(related)) return []+ return related+ .filter((value): value is string => typeof value === "string")+ .map((value) => value.trim().replace(/^\[\[|\]\]$/g, ""))+ .map((value) => value.split("|")[0].split("#")[0].replace(/\\/g, "/"))+ .map((value) => value.split("/").pop()?.replace(/\.md$/i, "") ?? "")+ .filter(Boolean)+}+function fileNameToId(fileName: string): string {return fileName.replace(/\.md$/, "")}@@ -225,7 +236,7 @@ async function buildWikiGraphUncached(projectPath: string): Promise<WikiGraphReslabel: extractTitle(content, file.name),type: extractType(content),path: file.path,- links: extractWikilinks(content),+ links: Array.from(new Set([...extractWikilinks(content), ...extractRelated(content)])),}} catch {return null