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: scale graph API for large wikis
nash_suff089881255a
diff --git a/README.md b/README.mdindex 47020c0a..1dd00a53 100644--- a/README.md+++ b/README.md@@ -449,7 +449,7 @@ LLM Wiki ships a built-in local HTTP API at `http://127.0.0.1:19828` (token-prot- `POST /api/v1/projects/{id}/reviews/resolve` — bulk-resolve Review items (JSON body `{ "ids": [...], "action": "label" }`), returns `{ resolved, notFound, count }`; the Review tab's Refresh button re-reads the result from disk- `POST /api/v1/projects/{id}/search` — **hybrid** retrieval (keyword + vector) returning `mode`, `tokenHits`, `vectorHits`, per-result `vectorScore`- `POST /api/v1/projects/{id}/chat` — backend Agent chat endpoint for wiki/source/web/AnyTXT retrieval. JSON requests remain non-streaming by default; send `"stream": true` or `Accept: text/event-stream` for SSE events (`meta`, incremental `agent`, then `done`, `cancelled`, or `error`). The terminal `done` frame contains the complete aggregate response, so clients should not render both message deltas and the final message as separate answers. `mode: "deep"` broadens evidence collection, while the full Deep Research workspace remains available in the desktop UI-- `GET /api/v1/projects/{id}/graph` — wikilinks graph+- `GET /api/v1/projects/{id}/graph` — wikilinks graph; supports `q`, `nodeType`, `limit` (max 1000), `offset`, and `edgeScope=page|filtered`, and returns `totalCount` / `hasMore` for large projects- `POST /api/v1/projects/{id}/sources/rescan` — trigger a backend rescan- `POST /api/v1/projects/{id}/pages/embed` — index one externally created or updated `wiki/*.md` page without rebuilding the whole vector databasediff --git a/mcp-server/src/api-client.ts b/mcp-server/src/api-client.tsindex 652297a7..42f2c699 100644--- a/mcp-server/src/api-client.ts+++ b/mcp-server/src/api-client.ts@@ -101,6 +101,15 @@ export interface ApiGraphEdge {weight?: number}+export interface ApiGraphResponse {+ nodes: ApiGraphNode[]+ edges: ApiGraphEdge[]+ offset: number+ limit: number+ totalCount: number+ hasMore: boolean+}+export type ApiReviewStatus = "unresolved" | "resolved" | "all"export interface ApiReviewOption {@@ -300,16 +309,24 @@ export class LlmWikiApiClient {}}- async graph(projectId = "current", options: { q?: string; nodeType?: string; limit?: number } = {}): Promise<{ nodes: ApiGraphNode[]; edges: ApiGraphEdge[] }> {+ async graph(projectId = "current", options: { q?: string; nodeType?: string; limit?: number; offset?: number; edgeScope?: "page" | "filtered" } = {}): Promise<ApiGraphResponse> {const params = new URLSearchParams()if (options.q) params.set("q", options.q)if (options.nodeType) params.set("nodeType", options.nodeType)if (options.limit !== undefined) params.set("limit", String(options.limit))+ if (options.offset !== undefined) params.set("offset", String(options.offset))+ if (options.edgeScope) params.set("edgeScope", options.edgeScope)const suffix = params.toString() ? `?${params.toString()}` : ""const json = await this.request(`/projects/${encodeURIComponent(projectId)}/graph${suffix}`)return {nodes: Array.isArray(json.nodes) ? json.nodes.map(parseGraphNode) : [],edges: Array.isArray(json.edges) ? json.edges.map(parseGraphEdge) : [],+ offset: typeof json.offset === "number" ? json.offset : 0,+ limit: typeof json.limit === "number" ? json.limit : 200,+ totalCount: typeof json.totalCount === "number"+ ? json.totalCount+ : (Array.isArray(json.nodes) ? json.nodes.length : 0),+ hasMore: json.hasMore === true,}}diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.tsindex a6bad289..7726ffb3 100644--- a/mcp-server/src/index.ts+++ b/mcp-server/src/index.ts@@ -154,6 +154,8 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({q: { type: "string", description: "Optional text filter." },node_type: { type: "string", description: "Optional node type filter." },limit: { type: "number", description: "Maximum nodes. The local API clamps to its configured maximum." },+ offset: { type: "number", minimum: 0, description: "Zero-based node offset." },+ edge_scope: { type: "string", enum: ["page", "filtered"], description: "Use 'page' for self-contained edges or 'filtered' when merging all pages." },},additionalProperties: false,},@@ -274,8 +276,12 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {q: optionalStringArg(args.q),nodeType: optionalStringArg(args.node_type),limit: numberArg(args.limit),+ offset: numberArg(args.offset),+ edgeScope: optionalStringArg(args.edge_scope)+ ? enumArg(args.edge_scope, ["page", "filtered"] as const, "page")+ : (args.offset !== undefined ? "filtered" : "page"),})- return textResult(withActiveProject(formatGraph(graph.nodes, graph.edges), scope.project, scope.id))+ return textResult(withActiveProject(formatGraph(graph), scope.project, scope.id))}case "llm_wiki_rescan_sources": {await assertMcpEnabled()@@ -500,7 +506,8 @@ function formatReviewOptions(review: ApiReviewItem): string {.join(", ")}-function formatGraph(nodes: ApiGraphNode[], edges: Array<{ source: string; target: string; weight?: number }>): string {+function formatGraph(graph: { nodes: ApiGraphNode[]; edges: Array<{ source: string; target: string; weight?: number }>; offset: number; totalCount: number; hasMore: boolean }): string {+ const { nodes, edges } = graphconst typeCounts = new Map<string, number>()for (const node of nodes) typeCounts.set(node.type, (typeCounts.get(node.type) ?? 0) + 1)const lines = [@@ -508,6 +515,7 @@ function formatGraph(nodes: ApiGraphNode[], edges: Array<{ source: string; targe"",`Nodes: ${nodes.length}`,`Edges: ${edges.length}`,+ `Page: offset ${graph.offset}, ${nodes.length} of ${graph.totalCount}${graph.hasMore ? " (more available)" : ""}`,"","## Node types",...[...typeCounts.entries()]diff --git a/mcp-server/test/api-client.test.ts b/mcp-server/test/api-client.test.tsindex b2275c73..4ad1eb0d 100644--- a/mcp-server/test/api-client.test.ts+++ b/mcp-server/test/api-client.test.ts@@ -202,6 +202,31 @@ test("graph parses nodeType from API graph nodes", async () => {assert.equal(graph.edges[0]?.weight, 0.75)})+test("graph forwards pagination and exposes page metadata", async () => {+ let requestedUrl = ""+ const fetchImpl = async (input: string | URL | Request): Promise<Response> => {+ requestedUrl = String(input)+ return new Response(JSON.stringify({+ ok: true,+ nodes: [],+ edges: [],+ offset: 200,+ limit: 200,+ totalCount: 450,+ hasMore: true,+ }), { status: 200 })+ }+ const client = new LlmWikiApiClient({ fetchImpl })+ const graph = await client.graph("current", { limit: 200, offset: 200, edgeScope: "filtered" })+ assert.match(requestedUrl, /limit=200/)+ assert.match(requestedUrl, /offset=200/)+ assert.match(requestedUrl, /edgeScope=filtered/)+ assert.equal(graph.totalCount, 450)+ assert.equal(graph.offset, 200)+ assert.equal(graph.limit, 200)+ assert.equal(graph.hasMore, true)+})+test("files exposes truncated flag", async () => {const fetchImpl = async (): Promise<Response> => (new Response(JSON.stringify({diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 00b7b3cb..d842621d 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -1,10 +1,11 @@-use std::collections::{BTreeMap, BTreeSet, VecDeque};+use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};use std::fs;+use std::hash::{DefaultHasher, Hash, Hasher};use std::io::{Cursor, Read};use std::path::{Component, Path, PathBuf};use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};use std::sync::mpsc::{self, Receiver, SyncSender};-use std::sync::{Mutex, OnceLock};+use std::sync::{Arc, Mutex, OnceLock};use std::thread;use std::time::{Duration, Instant};@@ -39,6 +40,8 @@ const MAX_IN_FLIGHT_CHAT_STREAMS: usize = 8;const MAX_IN_FLIGHT_PAGE_EMBEDS: usize = 4;const SSE_QUEUE_CAPACITY: usize = 64;const SSE_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);+const GRAPH_CACHE_TTL: Duration = Duration::from_secs(5);+const GRAPH_CACHE_MAX_PROJECTS: usize = 8;/// API status: 0=starting, 1=running, 2=port_conflict, 3=errorstatic API_STATUS: AtomicU8 = AtomicU8::new(0);@@ -47,6 +50,7 @@ static IN_FLIGHT_CHAT_STREAMS: AtomicUsize = AtomicUsize::new(0);static IN_FLIGHT_PAGE_EMBEDS: AtomicUsize = AtomicUsize::new(0);static APP_STATE_CACHE: OnceLock<Mutex<Option<CachedAppState>>> = OnceLock::new();static RATE_LIMIT: OnceLock<Mutex<VecDeque<Instant>>> = OnceLock::new();+static GRAPH_CACHE: OnceLock<Mutex<HashMap<String, Arc<CachedGraph>>>> = OnceLock::new();#[derive(Clone)]struct CachedAppState {@@ -54,6 +58,14 @@ struct CachedAppState {value: Option<Value>,}+#[derive(Clone)]+struct CachedGraph {+ loaded_at: Instant,+ fingerprint: u64,+ nodes: Vec<ApiGraphNode>,+ edges: Vec<ApiGraphEdge>,+}+pub fn get_api_status() -> &'static str {match API_STATUS.load(Ordering::Relaxed) {0 => "starting",@@ -2372,6 +2384,13 @@ struct ApiGraphEdge {weight: f64,}+struct GraphPage {+ nodes: Vec<ApiGraphNode>,+ edges: Vec<ApiGraphEdge>,+ total_count: usize,+ has_more: bool,+}+fn handle_graph(app: &AppHandle, project_id: &str, query: &str) -> ApiResponse {let project = match resolve_project(app, project_id) {Ok(project) => project,@@ -2380,70 +2399,231 @@ fn handle_graph(app: &AppHandle, project_id: &str, query: &str) -> ApiResponse {let params = parse_query(query);let q = params.get("q").map(|s| s.to_lowercase());let node_type = params.get("nodeType").map(|s| s.to_lowercase());- let limit = params- .get("limit")- .and_then(|s| s.parse::<usize>().ok())- .unwrap_or(200)- .clamp(1, 1000);-- match build_graph(&project.path) {- Ok((mut nodes, edges)) => {- if let Some(ref q) = q {- nodes.retain(|n| {- n.id.to_lowercase().contains(q) || n.label.to_lowercase().contains(q)- });+ let paged_edges = match params.get("edgeScope").map(String::as_str) {+ Some("filtered") => true,+ Some("page") | None => false,+ Some(_) => return err(400, "edgeScope must be 'page' or 'filtered'"),+ };+ let offset = match params.get("offset") {+ Some(value) => match value.parse::<usize>() {+ Ok(value) => value,+ Err(_) => return err(400, "offset must be a non-negative integer"),+ },+ None => 0,+ };+ let limit = match params.get("limit") {+ Some(value) => match value.parse::<usize>() {+ Ok(value) if value > 0 => value.clamp(1, 1000),+ _ => return err(400, "limit must be a positive integer"),+ },+ None => 200,+ };++ match load_graph(&project.path) {+ Ok(graph) => {+ let page = select_graph_page(+ &graph.nodes,+ &graph.edges,+ q.as_deref(),+ node_type.as_deref(),+ offset,+ limit,+ paged_edges,+ );+ ok(json!({+ "ok": true,+ "projectId": project.id,+ "nodes": page.nodes,+ "edges": page.edges,+ "offset": offset,+ "limit": limit,+ "totalCount": page.total_count,+ "hasMore": page.has_more,+ }))+ }+ Err(e) => err(500, e),+ }+}++fn select_graph_page(+ nodes: &[ApiGraphNode],+ edges: &[ApiGraphEdge],+ q: Option<&str>,+ node_type: Option<&str>,+ offset: usize,+ limit: usize,+ paged_edges: bool,+) -> GraphPage {+ let matches = |node: &&ApiGraphNode| {+ q.is_none_or(|q| {+ node.id.to_lowercase().contains(q) || node.label.to_lowercase().contains(q)+ }) && node_type.is_none_or(|node_type| node.node_type == node_type)+ };+ let total_count = nodes.iter().filter(matches).count();+ let filtered_ids = paged_edges.then(|| {+ nodes+ .iter()+ .filter(matches)+ .map(|node| node.id.clone())+ .collect::<BTreeSet<_>>()+ });+ let nodes: Vec<ApiGraphNode> = nodes+ .iter()+ .filter(matches)+ .skip(offset)+ .take(limit)+ .cloned()+ .collect();+ let page_ids: BTreeSet<String> = nodes.iter().map(|node| node.id.clone()).collect();+ let edges = edges+ .iter()+ .filter(|edge| {+ if paged_edges {+ page_ids.contains(&edge.source)+ && filtered_ids+ .as_ref()+ .is_some_and(|ids| ids.contains(&edge.target))+ } else {+ page_ids.contains(&edge.source) && page_ids.contains(&edge.target)}- if let Some(ref node_type) = node_type {- nodes.retain(|n| n.node_type == *node_type);+ })+ .cloned()+ .collect();+ let has_more = offset.saturating_add(nodes.len()) < total_count;+ GraphPage {+ nodes,+ edges,+ total_count,+ has_more,+ }+}++fn load_graph(project_path: &str) -> Result<Arc<CachedGraph>, String> {+ let cache = GRAPH_CACHE.get_or_init(|| Mutex::new(HashMap::new()));+ let cached = cache.lock().ok().and_then(|cache| {+ cache+ .get(project_path)+ .filter(|entry| entry.loaded_at.elapsed() < GRAPH_CACHE_TTL)+ .cloned()+ });+ if let Some(entry) = cached {+ return Ok(entry);+ }++ let (fingerprint, files) = graph_files(project_path)?;+ let cached = cache.lock().ok().and_then(|cache| {+ cache+ .get(project_path)+ .filter(|entry| entry.fingerprint == fingerprint)+ .cloned()+ });+ if let Some(entry) = cached {+ return Ok(entry);+ }++ let (nodes, edges) = build_graph_from_files(project_path, &files)?;+ let graph = Arc::new(CachedGraph {+ loaded_at: Instant::now(),+ fingerprint,+ nodes,+ edges,+ });+ if let Ok(mut cache) = cache.lock() {+ cache.retain(|_, entry| entry.loaded_at.elapsed() < GRAPH_CACHE_TTL);+ if cache.len() >= GRAPH_CACHE_MAX_PROJECTS && !cache.contains_key(project_path) {+ if let Some(oldest) = cache+ .iter()+ .min_by_key(|(_, entry)| entry.loaded_at)+ .map(|(path, _)| path.clone())+ {+ cache.remove(&oldest);}- nodes.truncate(limit);- let ids: BTreeSet<String> = nodes.iter().map(|n| n.id.clone()).collect();- let edges: Vec<ApiGraphEdge> = edges- .into_iter()- .filter(|e| ids.contains(&e.source) && ids.contains(&e.target))- .collect();- ok(json!({ "ok": true, "projectId": project.id, "nodes": nodes, "edges": edges }))}- Err(e) => err(500, e),+ cache.insert(project_path.to_string(), Arc::clone(&graph));}+ Ok(graph)}-fn build_graph(project_path: &str) -> Result<(Vec<ApiGraphNode>, Vec<ApiGraphEdge>), String> {+fn graph_files(project_path: &str) -> Result<(u64, Vec<PathBuf>), String> {let wiki_root = Path::new(project_path).join("wiki");- let mut raw: BTreeMap<String, (String, String, String, Vec<String>)> = BTreeMap::new();+ let mut files = Vec::new();for entry in WalkDir::new(&wiki_root).into_iter().filter_map(Result::ok) {- if !entry.file_type().is_file()- || entry.path().extension().and_then(|s| s.to_str()) != Some("md")+ if entry.file_type().is_file()+ && entry+ .path()+ .extension()+ .and_then(|value| value.to_str())+ .is_some_and(|value| value.eq_ignore_ascii_case("md")){- continue;+ files.push(entry.into_path());+ }+ }+ files.sort();++ let mut hasher = DefaultHasher::new();+ for path in &files {+ path.hash(&mut hasher);+ if let Ok(metadata) = fs::metadata(path) {+ metadata.len().hash(&mut hasher);+ metadata.modified().ok().hash(&mut hasher);}- let content = match fs::read_to_string(entry.path()) {+ }+ Ok((hasher.finish(), files))+}++#[cfg(test)]+fn build_graph(project_path: &str) -> Result<(Vec<ApiGraphNode>, Vec<ApiGraphEdge>), String> {+ let (_, files) = graph_files(project_path)?;+ build_graph_from_files(project_path, &files)+}++fn build_graph_from_files(+ project_path: &str,+ files: &[PathBuf],+) -> Result<(Vec<ApiGraphNode>, Vec<ApiGraphEdge>), String> {+ let wiki_root = Path::new(project_path).join("wiki");+ let mut stem_counts = HashMap::new();+ for path in files {+ if let Some(stem) = path.file_stem().and_then(|value| value.to_str()) {+ *stem_counts.entry(stem.to_string()).or_insert(0usize) += 1;+ }+ }+ let mut raw: BTreeMap<String, (String, String, String, Vec<String>)> = BTreeMap::new();+ for path in files {+ let content = match fs::read_to_string(path) {Ok(content) => content,Err(_) => continue,};- let id = entry- .path()+ let relative_id = wiki_page_id(&wiki_root, path);+ let stem = path.file_stem()- .and_then(|s| s.to_str())- .unwrap_or("")- .to_string();+ .and_then(|value| value.to_str())+ .unwrap_or("");+ let id = if stem_counts.get(stem) == Some(&1) {+ stem.to_string()+ } else {+ relative_id+ };if id.is_empty() {continue;}- let title =- commands::search::extract_title(&content, entry.file_name().to_string_lossy().as_ref());+ let fallback_name = path+ .file_name()+ .and_then(|value| value.to_str())+ .unwrap_or("");+ let title = commands::search::extract_title(&content, fallback_name);let node_type = extract_type(&content);- let path = relative_to_project(project_path, entry.path());+ let relative_path = relative_to_project(project_path, path);let links = extract_wikilinks(&content);- raw.insert(id, (title, node_type, path, links));+ raw.insert(id, (title, node_type, relative_path, links));}- let ids: BTreeSet<String> = raw.keys().cloned().collect();+ let aliases = graph_aliases(&raw);let mut link_count: BTreeMap<String, usize> = raw.keys().map(|id| (id.clone(), 0)).collect();let mut seen = BTreeSet::new();let mut edges = Vec::new();for (source, (_, _, _, links)) in &raw {for link in links {- let Some(target) = resolve_link(link, &ids) else {+ let Some(target) = resolve_link(link, &aliases) else {continue;};if &target == source {@@ -2479,6 +2659,91 @@ fn build_graph(project_path: &str) -> Result<(Vec<ApiGraphNode>, Vec<ApiGraphEdgOk((nodes, edges))}+fn wiki_page_id(wiki_root: &Path, path: &Path) -> String {+ path.strip_prefix(wiki_root)+ .unwrap_or(path)+ .with_extension("")+ .to_string_lossy()+ .replace('\\', "/")+}++struct GraphAliases {+ exact_ids: HashMap<String, String>,+ ids: HashMap<String, Option<String>>,+ stems: HashMap<String, Option<String>>,+ titles: HashMap<String, Option<String>>,+}++fn graph_aliases(raw: &BTreeMap<String, (String, String, String, Vec<String>)>) -> GraphAliases {+ let mut aliases = GraphAliases {+ exact_ids: HashMap::new(),+ ids: HashMap::new(),+ stems: HashMap::new(),+ titles: HashMap::new(),+ };+ for (id, (title, _, path, _)) in raw {+ aliases.exact_ids.insert(id.clone(), id.clone());+ insert_graph_alias(&mut aliases.ids, name_alias_keys(id), id);+ let canonical_path = path+ .strip_prefix("wiki/")+ .unwrap_or(path)+ .trim_end_matches(".md");+ insert_graph_alias(&mut aliases.ids, name_alias_keys(canonical_path), id);+ if let Some(stem) = id.rsplit('/').next() {+ insert_graph_alias(&mut aliases.stems, name_alias_keys(stem), id);+ }+ insert_graph_alias(&mut aliases.titles, name_alias_keys(title), id);+ }+ aliases+}++fn insert_graph_alias(aliases: &mut HashMap<String, Option<String>>, keys: Vec<String>, id: &str) {+ for key in keys {+ match aliases.get(&key) {+ None => {+ aliases.insert(key, Some(id.to_string()));+ }+ Some(Some(existing)) if existing != id => {+ aliases.insert(key, None);+ }+ _ => {}+ }+ }+}++fn link_alias_keys(raw: &str) -> Vec<String> {+ let target = raw+ .split('|')+ .next()+ .unwrap_or("")+ .split('#')+ .next()+ .unwrap_or("")+ .trim();+ name_alias_keys(target)+}++fn name_alias_keys(raw: &str) -> Vec<String> {+ let normalized = raw.trim().replace('\\', "/").to_lowercase();+ let normalized = normalized.trim_matches('/');+ let normalized = normalized.strip_prefix("./").unwrap_or(normalized);+ let normalized = normalized.strip_prefix("wiki/").unwrap_or(normalized);+ let normalized = if normalized.ends_with(".md") {+ &normalized[..normalized.len() - 3]+ } else {+ normalized+ };+ if normalized.is_empty() {+ return Vec::new();+ }+ let slugged = normalized.replace(' ', "-");+ if slugged == normalized {+ vec![normalized.to_string()]+ } else {+ vec![normalized.to_string(), slugged]+ }+}+fn extract_type(content: &str) -> String {for line in content.lines() {if let Some(value) = line.trim().strip_prefix("type:") {@@ -2510,14 +2775,35 @@ fn extract_wikilinks(content: &str) -> Vec<String> {out}-fn resolve_link(raw: &str, ids: &BTreeSet<String>) -> Option<String> {- if ids.contains(raw) {- return Some(raw.to_string());+fn resolve_link(raw: &str, aliases: &GraphAliases) -> Option<String> {+ let exact = raw+ .split('|')+ .next()+ .unwrap_or("")+ .split('#')+ .next()+ .unwrap_or("")+ .trim();+ if let Some(id) = aliases.exact_ids.get(exact) {+ return Some(id.clone());+ }+ let keys = link_alias_keys(raw);+ for tier in [&aliases.ids, &aliases.stems, &aliases.titles] {+ for key in &keys {+ if let Some(resolved) = tier.get(key) {+ return resolved.clone();+ }+ }+ }+ None+}++fn invalidate_graph_cache(project_path: &str) {+ if let Some(cache) = GRAPH_CACHE.get() {+ if let Ok(mut cache) = cache.lock() {+ cache.remove(project_path);+ }}- let normalized = raw.to_lowercase().replace(' ', "-");- ids.iter()- .find(|id| id.to_lowercase() == normalized || id.to_lowercase() == raw.to_lowercase())- .cloned()}fn handle_rescan(app: &AppHandle, project_id: &str) -> ApiResponse {@@ -2525,6 +2811,7 @@ fn handle_rescan(app: &AppHandle, project_id: &str) -> ApiResponse {Ok(project) => project,Err(e) => return err(404, e),};+ invalidate_graph_cache(&project.path);let source_watch_config = load_source_watch_config(app, &project.id);match commands::file_sync::rescan_project_files(app.clone(),@@ -2610,6 +2897,185 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[test]+ fn graph_uses_relative_slugs_and_resolves_path_links() {+ let root = test_project_dir();+ fs::create_dir_all(root.join("wiki/topic")).unwrap();+ fs::write(+ root.join("wiki/index.md"),+ "---\ntype: overview\n---\n# Index\n[[topic/Detail Page.md#section|Detail]]",+ )+ .unwrap();+ fs::write(+ root.join("wiki/topic/Detail Page.md"),+ "---\ntype: entity\n---\n# Detail Page",+ )+ .unwrap();++ let (nodes, edges) = build_graph(root.to_string_lossy().as_ref()).unwrap();+ assert!(nodes.iter().any(|node| node.id == "Detail Page"));+ assert!(edges+ .iter()+ .any(|edge| { edge.source == "index" && edge.target == "Detail Page" }));+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn graph_does_not_resolve_ambiguous_bare_stems() {+ let root = test_project_dir();+ fs::create_dir_all(root.join("wiki/a")).unwrap();+ fs::create_dir_all(root.join("wiki/b")).unwrap();+ fs::write(root.join("wiki/index.md"), "# Index\n[[same]]").unwrap();+ fs::write(root.join("wiki/a/same.md"), "# A").unwrap();+ fs::write(root.join("wiki/b/same.md"), "# B").unwrap();++ let (nodes, edges) = build_graph(root.to_string_lossy().as_ref()).unwrap();+ assert_eq!(nodes.len(), 3);+ assert!(nodes.iter().any(|node| node.id == "a/same"));+ assert!(nodes.iter().any(|node| node.id == "b/same"));+ assert!(edges.is_empty());+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn graph_exact_id_wins_over_a_colliding_title() {+ let root = test_project_dir();+ fs::write(root.join("wiki/index.md"), "# Home").unwrap();+ fs::write(root.join("wiki/glossary.md"), "# Index\n[[index]]").unwrap();++ let (_, edges) = build_graph(root.to_string_lossy().as_ref()).unwrap();+ assert_eq!(edges.len(), 1);+ assert_eq!(edges[0].target, "index");+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn graph_exact_id_wins_over_a_normalized_id_collision() {+ let mut raw = BTreeMap::new();+ for id in ["Machine Learning", "machine-learning"] {+ raw.insert(+ id.to_string(),+ (+ id.to_string(),+ "entity".to_string(),+ format!("wiki/{id}.md"),+ vec![],+ ),+ );+ }+ let aliases = graph_aliases(&raw);+ assert_eq!(+ resolve_link("Machine Learning", &aliases).as_deref(),+ Some("Machine Learning")+ );+ assert_eq!(+ resolve_link("machine-learning", &aliases).as_deref(),+ Some("machine-learning")+ );+ }++ #[test]+ fn graph_link_normalization_accepts_common_path_forms() {+ let mut raw = BTreeMap::new();+ raw.insert(+ "Page".to_string(),+ (+ "Display Title".to_string(),+ "entity".to_string(),+ "wiki/Page.md".to_string(),+ vec![],+ ),+ );+ let aliases = graph_aliases(&raw);+ for link in [+ "./Page",+ "wiki/Page",+ "/wiki/Page",+ "Page.MD",+ "Display Title",+ ] {+ assert_eq!(+ resolve_link(link, &aliases).as_deref(),+ Some("Page"),+ "{link}"+ );+ }+ }++ #[test]+ fn graph_pagination_can_be_merged_without_losing_edges() {+ let nodes = ["a", "b", "c"]+ .into_iter()+ .map(|id| ApiGraphNode {+ id: id.to_string(),+ label: id.to_string(),+ node_type: "entity".to_string(),+ path: format!("wiki/{id}.md"),+ link_count: 1,+ })+ .collect::<Vec<_>>();+ let edges = vec![+ ApiGraphEdge {+ source: "a".to_string(),+ target: "c".to_string(),+ weight: 1.0,+ },+ ApiGraphEdge {+ source: "b".to_string(),+ target: "c".to_string(),+ weight: 1.0,+ },+ ];++ let first = select_graph_page(&nodes, &edges, None, None, 0, 2, true);+ let second = select_graph_page(&nodes, &edges, None, None, 2, 2, true);+ assert_eq!(first.nodes.len(), 2);+ assert_eq!(first.total_count, 3);+ assert!(first.has_more);+ assert_eq!(second.nodes.len(), 1);+ assert!(!second.has_more);+ assert_eq!(first.edges.len() + second.edges.len(), 2);+ }++ #[test]+ fn graph_legacy_response_keeps_edge_endpoints_in_the_node_page() {+ let nodes = ["a", "b", "c"]+ .into_iter()+ .map(|id| ApiGraphNode {+ id: id.to_string(),+ label: id.to_string(),+ node_type: "entity".to_string(),+ path: format!("wiki/{id}.md"),+ link_count: 1,+ })+ .collect::<Vec<_>>();+ let edges = vec![ApiGraphEdge {+ source: "a".to_string(),+ target: "c".to_string(),+ weight: 1.0,+ }];+ let page = select_graph_page(&nodes, &edges, None, None, 0, 2, false);+ assert!(page.edges.is_empty());+ }++ #[test]+ fn graph_cache_invalidates_when_a_page_changes() {+ let root = test_project_dir();+ let page = root.join("wiki/page.md");+ fs::write(&page, "# Before").unwrap();+ let before = load_graph(root.to_string_lossy().as_ref()).unwrap();+ assert_eq!(before.nodes[0].label, "Before");+ let cached = load_graph(root.to_string_lossy().as_ref()).unwrap();+ assert!(Arc::ptr_eq(&before, &cached));++ fs::write(&page, "# After with a different length").unwrap();+ invalidate_graph_cache(root.to_string_lossy().as_ref());+ let after = load_graph(root.to_string_lossy().as_ref()).unwrap();+ assert_eq!(after.nodes[0].label, "After with a different length");+ assert!(!Arc::ptr_eq(&before, &after));+ let _ = fs::remove_dir_all(root);+ }+#[test]fn query_parser_decodes_percent_and_plus() {let parsed = parse_query("path=wiki%2Fhello+world.md&token=a%2Bb");