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: enrich agent retrieval and activity references
nash_su1c478ea4a307
diff --git a/src-tauri/src/agent/context.rs b/src-tauri/src/agent/context.rsindex 1ff2f17a..7f371ec1 100644--- a/src-tauri/src/agent/context.rs+++ b/src-tauri/src/agent/context.rs@@ -77,7 +77,8 @@ fn build_system_context(.join("\n");out.push_str("\n\nTool policy:\n");- out.push_str("- wiki.search can search generated wiki pages.\n");+ out.push_str("- wiki.search retrieves pages for factual or topical questions.\n");+ out.push_str("- graph.search retrieves relationships, neighbors, backlinks, dependencies, and connections between project entities. Prefer it when the requested answer is about how concepts or entities relate, and use concise entity names rather than the full natural-language question.\n");if router.should_hint_web {out.push_str("- web.search is available when current or external information is useful.\n");}@@ -230,6 +231,33 @@ fn build_user_context(input: AgentContextInput<'_>) -> String {if let Some(snippet) = reference.snippet.as_deref() {rendered.push_str(&format!("Snippet: {}\n", collapse_whitespace(snippet)));}+ if let Some(context) = reference.knowledge_context.as_ref() {+ if !context.related_to.is_empty() {+ rendered.push_str(&format!(+ "Graph neighbors of: {}\n",+ context.related_to.join(", ")+ ));+ }+ if !context.tags.is_empty() {+ rendered.push_str(&format!("Tags: {}\n", context.tags.join(", ")));+ }+ if !context.outgoing_links.is_empty() {+ rendered.push_str(&format!(+ "Links to: {}\n",+ context.outgoing_links.join(", ")+ ));+ }+ if !context.backlinks.is_empty() {+ rendered.push_str(&format!("Backlinks: {}\n", context.backlinks.join(", ")));+ }+ rendered.push_str(&format!("Related links: {}\n", context.link_count));+ if let Some(version) = context.latest_version.as_ref() {+ rendered.push_str(&format!(+ "Latest version: {} via {} at {}\n",+ version.author, version.tool, version.timestamp+ ));+ }+ }}out.push_str(&trim_chars(&rendered, MAX_REFERENCE_CHARS));out.push('\n');@@ -349,7 +377,53 @@ pub fn intent_label(intent: QueryIntent) -> &'static str {mod tests {use super::*;use crate::agent::router::route_query;- use crate::agent::types::{AgentMode, AgentToolOptions};+ use crate::agent::types::{+ AgentKnowledgeContext, AgentMode, AgentReference, AgentToolOptions, AgentVersionSummary,+ };++ #[test]+ fn retrieved_context_renders_graph_and_version_briefing() {+ let project = ProjectContext {+ overview: None,+ schema: None,+ agent_workspace: "/tmp/project/agent-workspace".to_string(),+ };+ let router = route_query("alpha", AgentMode::Standard, &AgentToolOptions::default());+ let references = vec![AgentReference {+ title: "Alpha".to_string(),+ path: "wiki/alpha.md".to_string(),+ kind: "wiki".to_string(),+ snippet: Some("alpha summary".to_string()),+ score: Some(1.0),+ knowledge_context: Some(AgentKnowledgeContext {+ related_to: Vec::new(),+ tags: vec!["core".to_string()],+ outgoing_links: vec!["Beta".to_string()],+ backlinks: vec!["wiki/gamma.md".to_string()],+ link_count: 2,+ latest_version: Some(AgentVersionSummary {+ timestamp: 123,+ author: "agent".to_string(),+ tool: "wiki.write_page".to_string(),+ }),+ }),+ }];+ let rendered = build_user_context(AgentContextInput {+ query: "alpha",+ project: &project,+ router: &router,+ history: &[],+ skills: &[],+ skill_mode: AgentSkillMode::Auto,+ references: &references,+ retrieval_summary: "",+ explicit_files: &[],+ });+ assert!(rendered.contains("Tags: core"));+ assert!(rendered.contains("Links to: Beta"));+ assert!(rendered.contains("Backlinks: wiki/gamma.md"));+ assert!(rendered.contains("Latest version: agent via wiki.write_page at 123"));+ }#[tokio::test]async fn explicit_context_files_are_project_scoped() {diff --git a/src-tauri/src/agent/runtime.rs b/src-tauri/src/agent/runtime.rsindex ee4b49d0..4d784e7a 100644--- a/src-tauri/src/agent/runtime.rs+++ b/src-tauri/src/agent/runtime.rs@@ -674,8 +674,12 @@ impl AgentRuntime {tool: "wiki.search".to_string(),status: "completed".to_string(),detail: Some(format!(- "{} result(s), mode={}, tokenHits={}, vectorHits={}",- search_count, search.mode, search.token_hits, search.vector_hits+ "{} result(s), mode={}, tokenHits={}, vectorHits={}, graphHits={}",+ search_count,+ search.mode,+ search.token_hits,+ search.vector_hits,+ search.graph_hits)),},);@@ -1335,8 +1339,14 @@ impl AgentRuntime {);}let mut observations = Vec::<AgentObservation>::new();+ let mut executed_retrievals = BTreeSet::<String>::new();+ let mut retrieval_steps = 0usize;+ let mut force_final_next = false;let mut last_prompt_chars = 0usize;- let max_iterations = agent_loop_iteration_budget(request.mode, !skills.is_empty());+ let has_explicit_skills =+ request.skill_mode == AgentSkillMode::Explicit && !skills.is_empty();+ let max_iterations = agent_loop_iteration_budget(request.mode, has_explicit_skills);+ let retrieval_budget = agent_loop_retrieval_budget(request.mode, has_explicit_skills);if let Some(command) = request.shell_command@@ -1376,6 +1386,7 @@ impl AgentRuntime {for iteration in 0..max_iterations {check_cancel(cancellation)?;+ let must_finalize = force_final_next || retrieval_steps >= retrieval_budget;let built_context = fit_context_to_model(build_agent_context(AgentContextInput {query: message,@@ -1394,18 +1405,27 @@ impl AgentRuntime {}),self.llm_config.as_ref(),);- let system = build_agent_loop_system(&built_context.system);- let user = build_agent_loop_user(- &built_context.user,- request,- &skills,- &observations,- iteration,- max_iterations,- references- .iter()- .any(|reference| reference.kind == "workspace"),- );+ let (system, user) = if must_finalize {+ (+ build_agent_final_system(&built_context.system),+ build_agent_final_user(&built_context.user, &observations),+ )+ } else {+ (+ build_agent_loop_system(&built_context.system),+ build_agent_loop_user(+ &built_context.user,+ request,+ &skills,+ &observations,+ iteration,+ max_iterations,+ references+ .iter()+ .any(|reference| reference.kind == "workspace"),+ ),+ )+ };last_prompt_chars = system.chars().count() + user.chars().count();tool_emit_event(&mut tool_events,@@ -1469,6 +1489,45 @@ impl AgentRuntime {};let action = parse_agent_loop_action(&raw);+ if must_finalize {+ let answer = forced_final_answer(&raw, &action, &references);+ if event_sink.is_some() {+ emit_event(+ &mut events,+ &event_sink,+ AgentEvent::MessageDelta {+ text: answer.clone(),+ },+ );+ }+ emit_event(+ &mut events,+ &event_sink,+ AgentEvent::Done {+ session_id: session_id.clone(),+ },+ );+ let reference_count = references.len();+ let tool_event_count = tool_events.len();+ return Ok(AgentChatResponse {+ ok: true,+ project_id: self.project_id.clone(),+ session_id,+ mode: request.mode,+ message: answer.clone(),+ references,+ tool_events,+ events,+ user_input_request: None,+ usage: Some(AgentUsage {+ prompt_chars: last_prompt_chars,+ completion_chars: answer.len(),+ reference_count,+ tool_event_count,+ }),+ });+ }+if action.action.eq_ignore_ascii_case("invalid_tool_json") {observations.push(record_loop_tool_rejection("agent.action",@@ -1623,6 +1682,26 @@ impl AgentRuntime {});}+ if action.tool.as_deref().is_some_and(is_agent_retrieval_tool) {+ let tool = action.tool.as_deref().unwrap_or_default();+ if let Ok(input) = self.agent_loop_tool_input(request, tool, &action) {+ let signature = format!("{tool}:{}", canonical_json(&input));+ if !executed_retrievals.insert(signature) {+ observations.push(record_loop_tool_rejection(+ tool,+ "duplicate retrieval skipped; use the existing observation and answer the user"+ .to_string(),+ &mut tool_events,+ &mut events,+ &event_sink,+ ));+ force_final_next = true;+ continue;+ }+ }+ retrieval_steps += 1;+ }+let observation = self.execute_agent_loop_tool(request,@@ -2118,8 +2197,8 @@ impl AgentRuntime {}).count();Ok(format!(- "{count} result(s), {added} new, mode={}, tokenHits={}, vectorHits={}",- search.mode, search.token_hits, search.vector_hits+ "{count} result(s), {added} new, mode={}, tokenHits={}, vectorHits={}, graphHits={}",+ search.mode, search.token_hits, search.vector_hits, search.graph_hits))}"source.search" | "graph.search" | "web.search" | "anytxt.search" => {@@ -2140,10 +2219,18 @@ impl AgentRuntime {.and_then(Value::as_str).unwrap_or("wiki page");let content = value.get("content").and_then(Value::as_str).unwrap_or("");- Ok(format!(+ let mut summary = format!("read {path}\n{}",trim_chars(&collapse_whitespace(content), 4_000)- ))+ );+ if let Some(context) = value+ .get("knowledgeContext")+ .filter(|value| !value.is_null())+ {+ summary.push_str("\nKnowledge context: ");+ summary.push_str(&trim_chars(&context.to_string(), 2_000));+ }+ Ok(summary)}"skill.read_file" => {let skill = value@@ -2205,6 +2292,7 @@ impl AgentRuntime {kind: "workspace".to_string(),snippet: Some(format!("Generated file {action} by Agent ({bytes} bytes).")),score: None,+ knowledge_context: None,};push_unique_reference(references, events, event_sink, reference);Ok(format!(@@ -2233,6 +2321,7 @@ impl AgentRuntime {generated.bytes)),score: None,+ knowledge_context: None,};push_unique_reference(references, events, event_sink, reference);}@@ -2313,7 +2402,7 @@ impl AgentRuntime {let skill_context = render_skill_planner_context(skills, skill_mode);let workspace = agent_workspace_display(&self.project_path);let user = format!(- "User request:\n{message}\n\nSkill context:\n{skill_context}\n\nAvailable tools: {}\n\nAgent workspace for generated files: {workspace}\n\nReturn JSON exactly like {{\"toolCalls\":[{{\"tool\":\"wiki.search\",\"query\":\"short query\"}}]}}. Use an empty array when no tool is needed. The skill context and tool list above are already available to the assistant; do not call wiki.search, source.search, graph.search, web.search, anytxt.search, skill.read_file, workspace.write_file, or shell.exec merely to list, explain, or summarize the currently available skills, tools, modes, or agent capabilities. Prefer web.search only for current/external information. Prefer anytxt.search only for user files outside the wiki. Prefer wiki.search only when the user asks about project/wiki knowledge that is not already present in the runtime context. Use wiki.write_page only when the user explicitly asks to create a wiki page; include path under wiki/ ending in .md and full Markdown content. Existing pages are create-only by default; include allowOverwrite:true only when the user explicitly asks to overwrite or update an existing wiki page. Use skill.read_file for Markdown/reference files inside an active skill directory. Use workspace.write_file for generated artifacts under agent-workspace; do not inline large heredocs or generated file bodies inside shell.exec. Use shell.exec only when a relevant active skill requires a command-line operation after any large files have been written. shell.exec runs from the Agent workspace; commands that generate files must write them under that workspace and must not write to home, Desktop, Downloads, system temp folders, hidden app metadata folders, or skill installation folders.",+ "User request:\n{message}\n\nSkill context:\n{skill_context}\n\nAvailable tools: {}\n\nAgent workspace for generated files: {workspace}\n\nReturn JSON exactly like {{\"toolCalls\":[{{\"tool\":\"wiki.search\",\"query\":\"short query\"}}]}}. Use an empty array when no tool is needed. The skill context and tool list above are already available to the assistant; do not call wiki.search, source.search, graph.search, web.search, anytxt.search, skill.read_file, workspace.write_file, or shell.exec merely to list, explain, or summarize the currently available skills, tools, modes, or agent capabilities. Use wiki.search for factual or topical retrieval. Prefer graph.search for relationships, dependencies, neighborhoods, backlinks, or connections between entities; pass concise entity or concept names instead of the full question. The planner may select both when the answer needs page content and graph structure. Prefer web.search only for current/external information. Prefer anytxt.search only for user files outside the wiki. Use wiki.write_page only when the user explicitly asks to create a wiki page; include path under wiki/ ending in .md and full Markdown content. Existing pages are create-only by default; include allowOverwrite:true only when the user explicitly asks to overwrite or update an existing wiki page. Use skill.read_file for Markdown/reference files inside an active skill directory. Use workspace.write_file for generated artifacts under agent-workspace; do not inline large heredocs or generated file bodies inside shell.exec. Use shell.exec only when a relevant active skill requires a command-line operation after any large files have been written. shell.exec runs from the Agent workspace; commands that generate files must write them under that workspace and must not write to home, Desktop, Downloads, system temp folders, hidden app metadata folders, or skill installation folders.",available.join(", "),);let client = LlmClient::new(config.clone())?@@ -2648,6 +2737,35 @@ fn agent_loop_iteration_budget(mode: AgentMode, has_skills: bool) -> usize {}}+fn agent_loop_retrieval_budget(mode: AgentMode, has_explicit_skills: bool) -> usize {+ let base = match mode {+ AgentMode::Fast => 2,+ AgentMode::Standard | AgentMode::LocalFirst => 4,+ AgentMode::Deep => 8,+ };+ if has_explicit_skills {+ base + 4+ } else {+ base+ }+}++fn is_agent_retrieval_tool(tool: &str) -> bool {+ matches!(+ tool,+ "wiki.search"+ | "wiki.read_page"+ | "source.search"+ | "graph.search"+ | "web.search"+ | "anytxt.search"+ )+}++fn canonical_json(value: &Value) -> String {+ serde_json::to_string(value).unwrap_or_else(|_| value.to_string())+}+fn should_fallback_wiki_search(planner_unavailable_or_failed: bool,tools: &super::types::AgentToolOptions,@@ -2679,6 +2797,62 @@ Use wiki.write_page only when the user explicitly asks to create or update a wik)}+fn build_agent_final_system(base_system: &str) -> String {+ format!(+ "{base_system}\n\nThe retrieval phase is complete. No tools are available now. Answer the user's latest request directly using the project context and tool observations already provided. Return only compact JSON in the form {{\"action\":\"final\",\"answer\":\"...\"}}. Do not request, announce, or simulate another search or file read."+ )+}++fn build_agent_final_user(base_user: &str, observations: &[AgentObservation]) -> String {+ let mut out = String::new();+ out.push_str(base_user);+ if !observations.is_empty() {+ out.push_str("\n\nCompleted tool observations:\n");+ out.push_str(&render_observations(observations));+ }+ out.push_str("\n\nProvide the final answer now. No further tool action is permitted.");+ out+}++fn forced_final_answer(+ raw: &str,+ action: &AgentLoopAction,+ references: &[AgentReference],+) -> String {+ if action.action.eq_ignore_ascii_case("final") {+ if let Some(answer) = action+ .answer+ .as_deref()+ .map(str::trim)+ .filter(|v| !v.is_empty())+ {+ return answer.to_string();+ }+ }+ let trimmed = raw.trim();+ if !trimmed.is_empty() && !looks_like_agent_tool_json(trimmed) {+ return trimmed.to_string();+ }+ if references.is_empty() {+ return "I could not find enough project context to answer this request reliably."+ .to_string();+ }+ let mut answer = String::from("I found the following relevant project context:\n");+ for reference in references.iter().take(8) {+ answer.push_str("- ");+ answer.push_str(&reference.title);+ answer.push_str(" (");+ answer.push_str(&reference.path);+ answer.push(')');+ if let Some(snippet) = reference.snippet.as_deref() {+ answer.push_str(": ");+ answer.push_str(&trim_chars(&collapse_whitespace(snippet), 320));+ }+ answer.push('\n');+ }+ answer+}+fn build_agent_loop_user(base_user: &str,request: &AgentChatRequest,@@ -2692,10 +2866,10 @@ fn build_agent_loop_user(out.push_str(base_user);out.push_str("\n\nAvailable Agent tools for this turn:\n");if request.tools.wiki {- out.push_str("- wiki.search: search generated wiki pages.\n");+ out.push_str("- wiki.search: retrieve wiki pages for factual or topical questions.\n");out.push_str("- wiki.read_page: read a specific wiki markdown page by path.\n");out.push_str("- source.search: search raw source snippets.\n");- out.push_str("- graph.search: search graph/page relationships.\n");+ out.push_str("- graph.search: retrieve relationships, neighbors, backlinks, dependencies, and connections between entities. Prefer it for relational questions and query with concise entity or concept names.\n");out.push_str("- wiki.write_page: create a wiki markdown page when explicitly requested.\n");}if request.tools.web {@@ -4284,6 +4458,39 @@ mod tests {assert_eq!(agent_loop_iteration_budget(AgentMode::Deep, true), 20);}+ #[test]+ fn retrieval_budget_expands_only_for_explicit_skill_turns() {+ assert_eq!(agent_loop_retrieval_budget(AgentMode::Fast, false), 2);+ assert_eq!(agent_loop_retrieval_budget(AgentMode::Standard, false), 4);+ assert_eq!(agent_loop_retrieval_budget(AgentMode::LocalFirst, false), 4);+ assert_eq!(agent_loop_retrieval_budget(AgentMode::Deep, false), 8);+ assert_eq!(agent_loop_retrieval_budget(AgentMode::Standard, true), 8);+ assert_eq!(agent_loop_retrieval_budget(AgentMode::Deep, true), 12);+ }++ #[test]+ fn forced_final_answer_prefers_model_final_content() {+ let raw = r#"{"action":"final","answer":"grounded answer"}"#;+ let action = parse_agent_loop_action(raw);+ assert_eq!(forced_final_answer(raw, &action, &[]), "grounded answer");+ }++ #[test]+ fn finalization_prompt_removes_tool_choice() {+ let system = build_agent_final_system("base");+ let user = build_agent_final_user(+ "question",+ &[AgentObservation {+ tool: "wiki.search".to_string(),+ summary: "2 results".to_string(),+ }],+ );+ assert!(system.contains("No tools are available"));+ assert!(system.contains(r#"{"action":"final""#));+ assert!(user.contains("No further tool action is permitted"));+ assert!(user.contains("wiki.search"));+ }+#[test]fn agent_loop_user_prompt_warns_before_iteration_budget_is_exhausted() {let prompt = build_agent_loop_user(@@ -4903,6 +5110,7 @@ mod tests {kind: "wiki".to_string(),snippet: None,score: None,+ knowledge_context: None,};assert!(push_unique_reference(@@ -5016,6 +5224,7 @@ mod tests {kind: "workspace".to_string(),snippet: None,score: None,+ knowledge_context: None,},AgentReference {title: "index.html duplicate".to_string(),@@ -5023,6 +5232,7 @@ mod tests {kind: "workspace".to_string(),snippet: None,score: None,+ knowledge_context: None,},AgentReference {title: "Wiki".to_string(),@@ -5030,6 +5240,7 @@ mod tests {kind: "wiki".to_string(),snippet: None,score: None,+ knowledge_context: None,},];@@ -5055,6 +5266,7 @@ mod tests {kind: "wiki".to_string(),snippet: None,score: None,+ knowledge_context: None,}];let answer = agent_iteration_limit_answer(8, 9, &references);diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rsindex 26158d0e..24b61c98 100644--- a/src-tauri/src/agent/tools.rs+++ b/src-tauri/src/agent/tools.rs@@ -1,5 +1,5 @@use std::collections::hash_map::DefaultHasher;-use std::collections::BTreeMap;+use std::collections::{BTreeMap, BTreeSet};use std::fs;use std::fs::OpenOptions;use std::future::Future;@@ -21,7 +21,7 @@ use walkdir::WalkDir;use crate::commands::external_search::file_url_for_path;use crate::commands::search::{self, SearchEmbeddingConfig};-use super::types::AgentReference;+use super::types::{AgentKnowledgeContext, AgentReference, AgentVersionSummary};use super::workspace::{agent_workspace_path, AGENT_WORKSPACE_DIR};// Tool I/O limits are backend security boundaries. Do not relax them only in@@ -37,6 +37,7 @@ const MAX_WORKSPACE_ROLLBACK_BYTES: u64 = 512 * 1024;const MAX_SOURCE_SEARCH_FILES: usize = 10_000;const MAX_SOURCE_SNIPPET_CHARS: usize = 500;const MAX_GRAPH_SEARCH_FILES: usize = 10_000;+const MAX_KNOWLEDGE_CONTEXT_ITEMS: usize = 20;const WEB_SEARCH_TIMEOUT_SECS: u64 = 30;const SHELL_EXEC_TIMEOUT_SECS: u64 = 30;const MAX_SHELL_COMMAND_CHARS: usize = 4_000;@@ -158,9 +159,19 @@ impl ToolRegistry for BuiltinToolRegistry {.map(str::trim).filter(|path| !path.is_empty()).ok_or_else(|| "wiki.read_page requires path".to_string())?;+ let content = read_wiki_page(context.project_path, path)?;+ let normalized_path = normalize_rel_path(path);+ let mut knowledge_context = build_knowledge_context_index(context.project_path)+ .remove(&normalized_path);+ attach_latest_version(+ context.project_path,+ &normalized_path,+ &mut knowledge_context,+ );serde_json::to_value(json!({"path": path,- "content": read_wiki_page(context.project_path, path)?,+ "content": content,+ "knowledgeContext": knowledge_context,})).map_err(|err| format!("Failed to serialize wiki.read_page result: {err}"))}@@ -278,6 +289,7 @@ pub struct WikiSearchToolOutput {pub mode: String,pub token_hits: usize,pub vector_hits: usize,+ pub graph_hits: usize,pub references: Vec<AgentReference>,}@@ -461,7 +473,8 @@ pub fn builtin_tool_specs() -> Vec<ToolSpec> {},ToolSpec {name: "graph.search".to_string(),- description: "Search wiki graph nodes and relationship-heavy pages.".to_string(),+ description: "Retrieve graph relationships, neighbors, backlinks, dependencies, and connections between project entities. Use concise entity or concept names rather than a full question."+ .to_string(),effects: vec![ToolEffect::Read],parameters: Some(serde_json::json!({"type": "object",@@ -682,11 +695,12 @@ fn write_wiki_page_with_activity(.unwrap_or("Wiki page").replace('-', " ")}),- path: rel,+ path: rel.clone(),kind: "wiki".to_string(),snippet: Some(trim_text(&collapse_markdown_preview(content), 500)).filter(|value| !value.trim().is_empty()),score: None,+ knowledge_context: None,},existed_before,previous_content,@@ -814,28 +828,50 @@ pub async fn run_wiki_search() -> Result<WikiSearchToolOutput, String> {let query_embedding = search::resolve_query_embedding(query, None, embedding_config).await?;let search = search::search_project_inner(- project_path,+ project_path.clone(),query.to_string(),top_k,include_content,query_embedding,).await?;+ let project_for_context = project_path.clone();+ let context_index =+ tokio::task::spawn_blocking(move || build_knowledge_context_index(&project_for_context))+ .await+ .map_err(|err| format!("wiki.search graph context worker failed: {err}"));+ // Retrieval must remain useful if optional graph enrichment fails. The+ // search result is the source of truth; context is a bounded enhancement.+ let mut context_index = context_index.unwrap_or_default();let references = search.results.iter()- .map(|result| AgentReference {- title: result.title.clone(),- path: result.path.clone(),- kind: "wiki".to_string(),- snippet: Some(result.snippet.clone()).filter(|s| !s.trim().is_empty()),- score: Some(result.score),+ .map(|result| {+ let normalized_path = normalize_rel_path(&result.path);+ let mut knowledge_context = context_index.remove(&normalized_path);+ if let Some(context) = knowledge_context.as_mut() {+ context.related_to = result.graph_related_to.clone();+ }+ attach_latest_version(&project_path, &normalized_path, &mut knowledge_context);+ AgentReference {+ title: result.title.clone(),+ path: result.path.clone(),+ kind: if result.graph_related_to.is_empty() {+ "wiki".to_string()+ } else {+ "graph".to_string()+ },+ snippet: Some(result.snippet.clone()).filter(|s| !s.trim().is_empty()),+ score: Some(result.score),+ knowledge_context,+ }}).collect();Ok(WikiSearchToolOutput {mode: search.mode,token_hits: search.token_hits,vector_hits: search.vector_hits,+ graph_hits: search.graph_hits,references,})}@@ -1264,6 +1300,7 @@ pub async fn run_anytxt_search()).filter(|s| !s.trim().is_empty()),score: None,+ knowledge_context: None,});}Ok(references)@@ -1834,6 +1871,7 @@ fn web_items_to_references(raw: Vec<WebSearchItem>, max_results: usize) -> Vec<Akind: "web".to_string(),snippet: Some(item.snippet).filter(|s| !s.trim().is_empty()),score: None,+ knowledge_context: None,}).collect()}@@ -1936,6 +1974,246 @@ fn friendly_firecrawl_error(error: &str) -> String {}}+#[derive(Debug)]+struct KnowledgePage {+ path: String,+ title: String,+ stem: String,+ tags: Vec<String>,+ links: Vec<String>,+ matches_query: bool,+ neighbors: Vec<String>,+}++/// Build one bounded graph/provenance index for a complete retrieval tool+/// invocation. Never call this once per result: large projects would otherwise+/// turn top-k retrieval into top-k full filesystem scans.+fn build_knowledge_context_index(project_path: &str) -> BTreeMap<String, AgentKnowledgeContext> {+ build_knowledge_graph_snapshot(project_path, None).1+}++fn build_knowledge_graph_snapshot(+ project_path: &str,+ query: Option<&str>,+) -> (Vec<KnowledgePage>, BTreeMap<String, AgentKnowledgeContext>) {+ let wiki_root = Path::new(project_path).join("wiki");+ if !wiki_root.is_dir() {+ return (Vec::new(), BTreeMap::new());+ }++ let mut pages = Vec::new();+ for entry in WalkDir::new(&wiki_root).into_iter().filter_map(Result::ok) {+ if pages.len() >= MAX_GRAPH_SEARCH_FILES+ || !entry.file_type().is_file()+ || entry.path().extension().and_then(|value| value.to_str()) != Some("md")+ {+ continue;+ }+ let Ok(content) = fs::read_to_string(entry.path()) else {+ continue;+ };+ let path = relative_to_project(project_path, entry.path());+ if is_hidden_rel(&path) {+ continue;+ }+ let title = search::extract_title(&content, entry.file_name().to_string_lossy().as_ref());+ let matches_query = query.is_some_and(|query| {+ let haystack = format!("{title} {path} {content}").to_lowercase();+ haystack.contains(query)+ || graph_query_terms(query)+ .iter()+ .any(|term| haystack.contains(term))+ });+ pages.push(KnowledgePage {+ path,+ title,+ stem: entry+ .path()+ .file_stem()+ .and_then(|value| value.to_str())+ .unwrap_or_default()+ .to_string(),+ tags: extract_frontmatter_list(&content, "tags"),+ links: extract_wikilinks(&content),+ matches_query,+ neighbors: Vec::new(),+ });+ }++ let mut aliases: BTreeMap<String, String> = BTreeMap::new();+ for page in &pages {+ let wiki_relative_path = page.path.strip_prefix("wiki/").unwrap_or(&page.path);+ for alias in [&page.stem, &page.title, &page.path, wiki_relative_path] {+ aliases.insert(normalize_wiki_link(alias), page.path.clone());+ }+ }++ let mut backlinks: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ let mut neighbors: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for page in &pages {+ for link in &page.links {+ if let Some(target) = aliases.get(&normalize_wiki_link(link)) {+ if target != &page.path {+ backlinks+ .entry(target.clone())+ .or_default()+ .insert(page.path.clone());+ neighbors+ .entry(page.path.clone())+ .or_default()+ .insert(target.clone());+ neighbors+ .entry(target.clone())+ .or_default()+ .insert(page.path.clone());+ }+ }+ }+ }++ for page in &mut pages {+ page.neighbors = neighbors+ .remove(&page.path)+ .unwrap_or_default()+ .into_iter()+ .take(MAX_KNOWLEDGE_CONTEXT_ITEMS)+ .collect();+ }++ let contexts = pages+ .iter()+ .map(|page| {+ let mut outgoing_links = page.links.clone();+ outgoing_links.sort();+ outgoing_links.dedup();+ let total_outgoing = outgoing_links.len();+ outgoing_links.truncate(MAX_KNOWLEDGE_CONTEXT_ITEMS);+ let mut page_backlinks: Vec<String> = backlinks+ .remove(&page.path)+ .unwrap_or_default()+ .into_iter()+ .collect();+ let total_backlinks = page_backlinks.len();+ page_backlinks.truncate(MAX_KNOWLEDGE_CONTEXT_ITEMS);+ let link_count = total_outgoing + total_backlinks;+ (+ page.path.clone(),+ AgentKnowledgeContext {+ related_to: Vec::new(),+ tags: page+ .tags+ .iter()+ .cloned()+ .take(MAX_KNOWLEDGE_CONTEXT_ITEMS)+ .collect(),+ outgoing_links,+ backlinks: page_backlinks,+ link_count,+ latest_version: None,+ },+ )+ })+ .collect();+ (pages, contexts)+}++fn attach_latest_version(+ project_path: &str,+ relative_path: &str,+ context: &mut Option<AgentKnowledgeContext>,+) {+ let Some(context) = context else {+ return;+ };+ context.latest_version = crate::commands::file_history::latest_file_version(+ &Path::new(project_path).join(relative_path),+ )+ .map(|(timestamp, author, tool)| AgentVersionSummary {+ timestamp,+ author,+ tool,+ });+}++fn normalize_wiki_link(value: &str) -> String {+ value+ .split('#')+ .next()+ .unwrap_or_default()+ .trim()+ .trim_end_matches(".md")+ .replace('\\', "/")+ .to_lowercase()+ .replace(' ', "-")+}++fn graph_query_terms(query: &str) -> Vec<String> {+ query+ .split(|character: char| {+ character.is_whitespace()+ || matches!(character, ',' | ',' | ';' | ';' | ':' | ':' | '/' | '|')+ })+ .map(str::trim)+ .filter(|term| !term.is_empty())+ .map(str::to_string)+ .collect()+}++fn extract_wikilinks(content: &str) -> Vec<String> {+ let mut links = Vec::new();+ let mut rest = content;+ while let Some(start) = rest.find("[[") {+ rest = &rest[start + 2..];+ let Some(end) = rest.find("]]") else {+ break;+ };+ let target = rest[..end].split('|').next().unwrap_or_default().trim();+ if !target.is_empty() {+ links.push(target.to_string());+ }+ rest = &rest[end + 2..];+ }+ links+}++fn extract_frontmatter_list(content: &str, key: &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 prefix = format!("{key}:");+ let lines: Vec<&str> = rest[..end].lines().collect();+ for (index, line) in lines.iter().enumerate() {+ let Some(value) = line.trim().strip_prefix(&prefix) else {+ continue;+ };+ let inline = value.trim();+ if inline.starts_with('[') && inline.ends_with(']') {+ return inline[1..inline.len() - 1]+ .split(',')+ .map(|item| item.trim().trim_matches(['\'', '"']).to_string())+ .filter(|item| !item.is_empty())+ .collect();+ }+ let mut values = Vec::new();+ for next in lines.iter().skip(index + 1) {+ let trimmed = next.trim();+ let Some(item) = trimmed.strip_prefix('-') else {+ break;+ };+ let item = item.trim().trim_matches(['\'', '"']);+ if !item.is_empty() {+ values.push(item.to_string());+ }+ }+ return values;+ }+ Vec::new()+}+pub fn read_wiki_page(project_path: &str, rel_path: &str) -> Result<String, String> {let rel = normalize_rel_path(rel_path);if !is_public_read_rel(&rel) || !rel.to_ascii_lowercase().starts_with("wiki/") {@@ -1961,60 +2239,60 @@ pub fn search_graph(if query.is_empty() {return Ok(Vec::new());}- let wiki_root = Path::new(project_path).join("wiki");- if !wiki_root.exists() {+ let (pages, mut context_index) = build_knowledge_graph_snapshot(project_path, Some(&query));+ let seed_paths: BTreeSet<String> = pages+ .iter()+ .filter(|page| page.matches_query)+ .map(|page| page.path.clone())+ .collect();+ if seed_paths.is_empty() {return Ok(Vec::new());}let mut refs = Vec::new();- let mut seen_files = 0usize;- 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")- {- continue;- }- seen_files += 1;- if seen_files > MAX_GRAPH_SEARCH_FILES {- eprintln!(- "[Agent] graph.search stopped after {MAX_GRAPH_SEARCH_FILES} markdown files in {project_path}"- );- break;- }- let Ok(content) = fs::read_to_string(entry.path()) else {+ for page in pages {+ let Some(page_context) = context_index.get(&page.path) else {continue;};- let rel = relative_to_project(project_path, entry.path());- if is_hidden_rel(&rel) {- continue;- }- let title = search::extract_title(- &content,- entry- .path()- .file_stem()- .and_then(|s| s.to_str())- .unwrap_or(&rel),- );- let link_count = count_wikilinks(&content);- let haystack = format!("{} {} {}", title, rel, content).to_lowercase();- if !haystack.contains(&query) && link_count == 0 {+ let link_count = page_context.link_count;+ let connected_to_seed = page+ .neighbors+ .iter()+ .any(|neighbor| seed_paths.contains(neighbor));+ if !page.matches_query && !connected_to_seed {continue;}+ let rel = page.path;+ let relation = if page.matches_query {+ "matched entity"+ } else {+ "direct neighbor"+ };refs.push(AgentReference {- title,- path: rel,+ title: page.title,+ path: rel.clone(),kind: "graph".to_string(),- snippet: Some(format!("{link_count} wikilink(s)")),- score: Some(link_count as f64),- });- refs.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.path.cmp(&b.path))+ snippet: Some(format!("{relation}; {link_count} related link(s)")),+ score: Some(+ if page.matches_query {+ 10_000.0+ } else {+ 5_000.0+ } + link_count as f64,+ ),+ knowledge_context: {+ let mut context = context_index.remove(&rel);+ attach_latest_version(project_path, &rel, &mut context);+ context+ },});- refs.truncate(top_k.clamp(1, 10));}+ refs.sort_by(|a, b| {+ b.score+ .partial_cmp(&a.score)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| a.path.cmp(&b.path))+ });+ refs.truncate(top_k.clamp(1, 10));Ok(refs)}@@ -2089,6 +2367,7 @@ pub fn search_sources(MAX_SOURCE_SNIPPET_CHARS,)),score: None,+ knowledge_context: None,});if refs.len() >= top_k.clamp(1, 10) {break;@@ -2119,10 +2398,6 @@ fn source_query_terms(query: &str) -> Vec<String> {.collect()}-fn count_wikilinks(content: &str) -> usize {- content.match_indices("[[").count()-}-fn safe_project_join(project_path: &str, rel: &str) -> Result<PathBuf, String> {let root = Path::new(project_path);let rel_path = Path::new(rel);@@ -2415,6 +2690,49 @@ mod tests {assert!(err.contains("wiki.read_page"));}+ #[test]+ fn knowledge_context_indexes_tags_links_backlinks_and_latest_version() {+ let root = std::env::temp_dir().join(format!("llm-wiki-context-{}", Uuid::new_v4()));+ fs::create_dir_all(root.join(".llm-wiki")).unwrap();+ fs::create_dir_all(root.join("wiki/entities")).unwrap();+ let alpha = root.join("wiki/entities/alpha.md");+ let beta = root.join("wiki/entities/beta.md");+ fs::write(+ &alpha,+ "---\r\ntitle: Alpha\r\ntags: [core, test]\r\n---\r\n# Alpha\r\n\r\n[[Beta]]",+ )+ .unwrap();+ fs::write(+ &beta,+ "---\ntitle: Beta\ntags:\n - linked\n---\n# Beta\n\n[[entities/alpha]]",+ )+ .unwrap();+ crate::commands::file_history::record_file_version(&alpha, "agent", "test.write");++ let mut contexts = build_knowledge_context_index(root.to_str().unwrap());+ let mut alpha_context = contexts.remove("wiki/entities/alpha.md");+ attach_latest_version(+ root.to_str().unwrap(),+ "wiki/entities/alpha.md",+ &mut alpha_context,+ );+ let alpha_context = alpha_context.as_ref().unwrap();+ let beta_context = contexts.get("wiki/entities/beta.md").unwrap();++ assert_eq!(alpha_context.tags, vec!["core", "test"]);+ assert_eq!(alpha_context.outgoing_links, vec!["Beta"]);+ assert_eq!(alpha_context.backlinks, vec!["wiki/entities/beta.md"]);+ assert_eq!(alpha_context.link_count, 2);+ assert_eq!(+ alpha_context.latest_version.as_ref().unwrap().tool,+ "test.write"+ );+ assert_eq!(beta_context.tags, vec!["linked"]);+ assert_eq!(beta_context.backlinks, vec!["wiki/entities/alpha.md"]);++ let _ = fs::remove_dir_all(root);+ }+#[tokio::test]async fn registry_executes_declared_read_page_and_deep_tools() {let root = std::env::temp_dir().join(format!("llm-wiki-tool-registry-{}", Uuid::new_v4()));@@ -2941,11 +3259,48 @@ mod tests {"---\ntitle: Agent Graph\n---\n# Agent Graph\n\nLinks to [[Tool Registry]] and [[Context Builder]].",).unwrap();+ fs::write(+ wiki_dir.join("tool-registry.md"),+ "---\ntitle: Tool Registry\n---\n# Tool Registry\n\nTool definitions.",+ )+ .unwrap();+ fs::write(+ wiki_dir.join("context-builder.md"),+ "---\ntitle: Context Builder\n---\n# Context Builder\n\nContext assembly.",+ )+ .unwrap();+ fs::write(+ wiki_dir.join("unrelated.md"),+ "---\ntitle: Unrelated Hub\n---\n# Unrelated Hub\n\n[[Missing A]] [[Missing B]] [[Missing C]].",+ )+ .unwrap();- let refs = search_graph(root.to_str().unwrap(), "agent", 5).unwrap();- assert_eq!(refs.len(), 1);- assert_eq!(refs[0].kind, "graph");- assert_eq!(refs[0].score, Some(2.0));+ let refs = search_graph(root.to_str().unwrap(), "Agent Graph", 5).unwrap();+ assert_eq!(refs.len(), 3);+ assert_eq!(refs[0].title, "Agent Graph");+ assert!(refs[0]+ .snippet+ .as_deref()+ .unwrap()+ .contains("matched entity"));+ assert!(refs+ .iter()+ .skip(1)+ .all(|reference| reference.kind == "graph"+ && reference+ .snippet+ .as_deref()+ .unwrap()+ .contains("direct neighbor")));+ assert!(refs+ .iter()+ .any(|reference| reference.title == "Tool Registry"));+ assert!(refs+ .iter()+ .any(|reference| reference.title == "Context Builder"));+ assert!(!refs+ .iter()+ .any(|reference| reference.title == "Unrelated Hub"));let _ = fs::remove_dir_all(root);}diff --git a/src-tauri/src/agent/types.rs b/src-tauri/src/agent/types.rsindex caa2eb1b..75bb64f4 100644--- a/src-tauri/src/agent/types.rs+++ b/src-tauri/src/agent/types.rs@@ -159,6 +159,35 @@ pub struct AgentReference {pub snippet: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub score: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub knowledge_context: Option<AgentKnowledgeContext>,+}++/// Lightweight graph and provenance briefing attached to wiki retrievals.+/// Keep this bounded: the complete page body is already available through the+/// read/search result and duplicating an unbounded graph would waste context.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct AgentKnowledgeContext {+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub related_to: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub tags: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub outgoing_links: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub backlinks: Vec<String>,+ pub link_count: usize,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub latest_version: Option<AgentVersionSummary>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct AgentVersionSummary {+ pub timestamp: i64,+ pub author: String,+ pub tool: String,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex f837daf3..661d492e 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -1665,9 +1665,10 @@ fn handle_search(app: &AppHandle, project_id: &str, body: &str) -> ApiResponse {"ok": true,"projectId": project.id,"mode": search.mode,- "note": "Search uses the shared backend retrieval service. When embeddingConfig is enabled, the API automatically includes LanceDB vector results; clients may also pass queryEmbedding explicitly.",+ "note": "Search uses the shared backend hybrid retrieval service, combining keyword, vector, and one-hop knowledge-graph candidates. When embeddingConfig is enabled, the API automatically includes LanceDB vector results; clients may also pass queryEmbedding explicitly.","tokenHits": search.token_hits,"vectorHits": search.vector_hits,+ "graphHits": search.graph_hits,"results": search.results,})),Err(e) => err(500, e),diff --git a/src-tauri/src/commands/file_history.rs b/src-tauri/src/commands/file_history.rsindex 39a23966..12e61b6c 100644--- a/src-tauri/src/commands/file_history.rs+++ b/src-tauri/src/commands/file_history.rs@@ -21,6 +21,19 @@ pub struct FileHistoryEntry {pub content: String,}+/// Return provenance only, never historical content, for Agent retrieval+/// briefings. Reading the same bounded store as the timeline keeps attribution+/// consistent without expanding prompt size or exposing rollback snapshots.+pub fn latest_file_version(path: &Path) -> Option<(i64, String, String)> {+ let root = project_root_for(path)?;+ let _guard = HISTORY_LOCK.lock().ok()?;+ let raw = fs::read_to_string(history_path(&root, path)).ok()?;+ let entries: Vec<FileHistoryEntry> = serde_json::from_str(&raw).ok()?;+ entries+ .last()+ .map(|entry| (entry.timestamp, entry.author.clone(), entry.tool.clone()))+}+fn project_root_for(path: &Path) -> Option<PathBuf> {let mut cursor = path.parent();while let Some(dir) = cursor {diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex eb49c7fc..1e401b0f 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -21,6 +21,9 @@ const CONTENT_TOKEN_WEIGHT: f64 = 1.0;const SNIPPET_CONTEXT: usize = 80;const SEARCH_EMBEDDING_TIMEOUT_SECS: u64 = 8;const MAX_SEARCH_FILES: usize = 10_000;+const MIN_GRAPH_RESULT_RATIO: f64 = 0.15;+const MAX_GRAPH_RESULT_RATIO: f64 = 0.30;+const MAX_GRAPH_SEEDS: usize = 20;#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -42,6 +45,8 @@ pub struct ProjectSearchResult {pub images: Vec<SearchImageRef>,#[serde(skip_serializing_if = "Option::is_none")]pub content: Option<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub graph_related_to: Vec<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -51,6 +56,15 @@ pub struct ProjectSearchResponse {pub results: Vec<ProjectSearchResult>,pub token_hits: usize,pub vector_hits: usize,+ pub graph_hits: usize,+}++#[derive(Debug, Clone)]+struct GraphPage {+ path: String,+ title: String,+ content: String,+ links: Vec<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -159,6 +173,7 @@ pub async fn search_project_inner(let query_phrase = trim_query_punctuation(&query.to_lowercase());let mut results = Vec::new();let mut page_paths_by_stem = BTreeMap::new();+ let mut graph_pages = BTreeMap::new();let wiki_root = Path::new(&project_path).join("wiki");if wiki_root.exists() {@@ -192,7 +207,16 @@ pub async fn search_project_inner();}}- if let Some(hit) = score_file(+ let relative_path = relative_to_project(&project_path, entry.path());+ let title = extract_title(+ &content,+ entry+ .path()+ .file_name()+ .and_then(|value| value.to_str())+ .unwrap_or_default(),+ );+ let hit = score_file(&project_path,entry.path(),&content,@@ -200,7 +224,17 @@ pub async fn search_project_inner(&query_phrase,&query,include_content,- ) {+ );+ graph_pages.insert(+ normalize_path(&relative_path),+ GraphPage {+ path: relative_path,+ title,+ links: extract_wikilinks(&content),+ content,+ },+ );+ if let Some(hit) = hit {results.push(hit);}}@@ -249,36 +283,29 @@ pub async fn search_project_inner(}}- if vector_hits == 0 {- results.sort_by(|a, b| {- b.score- .partial_cmp(&a.score)- .unwrap_or(std::cmp::Ordering::Equal)- .then_with(|| a.path.cmp(&b.path))- });- results.truncate(limit);- return Ok(ProjectSearchResponse {- mode: "keyword".to_string(),- token_hits: token_rank.len(),- vector_hits,- results,- });+ if vector_hits > 0 {+ apply_rrf_scores(&mut results, &token_rank, &vector_rank, &vector_score);}- apply_rrf_scores(&mut results, &token_rank, &vector_rank, &vector_score);-results.sort_by(|a, b| {b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.path.cmp(&b.path))});- results.truncate(limit);+ let graph_hits = blend_graph_results(+ &mut results,+ &graph_pages,+ limit,+ vector_hits,+ include_content,+ );Ok(ProjectSearchResponse {- mode: search_mode(token_rank.is_empty(), vector_hits).to_string(),+ mode: search_mode(token_rank.is_empty(), vector_hits, graph_hits).to_string(),token_hits: token_rank.len(),vector_hits,+ graph_hits,results,})}@@ -306,8 +333,193 @@ fn apply_rrf_scores(}}-fn search_mode(token_rank_empty: bool, vector_hits: usize) -> &'static str {- if vector_hits == 0 {+/// Reserve 15-30% of the final window for one-hop graph expansion. A full+/// vector window leaves the minimum graph share; sparse vector retrieval moves+/// progressively toward the maximum. Missing graph candidates automatically+/// return their slots to keyword/vector results.+fn graph_result_quota(limit: usize, vector_hits: usize) -> usize {+ if limit < 2 {+ return 0;+ }+ let vector_coverage = vector_hits.min(limit) as f64 / limit as f64;+ let ratio = MAX_GRAPH_RESULT_RATIO+ - (MAX_GRAPH_RESULT_RATIO - MIN_GRAPH_RESULT_RATIO) * vector_coverage;+ ((limit as f64 * ratio).ceil() as usize).clamp(1, limit - 1)+}++fn blend_graph_results(+ ranked_results: &mut Vec<ProjectSearchResult>,+ pages: &BTreeMap<String, GraphPage>,+ limit: usize,+ vector_hits: usize,+ include_content: bool,+) -> usize {+ if ranked_results.is_empty() || pages.is_empty() {+ ranked_results.truncate(limit);+ return 0;+ }++ let mut aliases = BTreeMap::<String, String>::new();+ for (normalized_path, page) in pages {+ let wiki_relative = page.path.strip_prefix("wiki/").unwrap_or(&page.path);+ let stem = file_stem(&page.path);+ for alias in [+ page.path.as_str(),+ wiki_relative,+ stem.as_str(),+ page.title.as_str(),+ ] {+ aliases.insert(normalize_graph_alias(alias), normalized_path.clone());+ }+ }++ let mut adjacency = BTreeMap::<String, BTreeSet<String>>::new();+ for (source, page) in pages {+ for link in &page.links {+ let Some(target) = aliases.get(&normalize_graph_alias(link)) else {+ continue;+ };+ if source == target {+ continue;+ }+ adjacency+ .entry(source.clone())+ .or_default()+ .insert(target.clone());+ adjacency+ .entry(target.clone())+ .or_default()+ .insert(source.clone());+ }+ }++ let seed_paths: Vec<String> = ranked_results+ .iter()+ .take(limit.min(MAX_GRAPH_SEEDS))+ .map(|result| normalize_path(&result.path))+ .collect();+ let seed_set: BTreeSet<String> = seed_paths.iter().cloned().collect();+ let mut candidate_scores = BTreeMap::<String, f64>::new();+ let mut candidate_seeds = BTreeMap::<String, BTreeSet<String>>::new();+ for (rank, seed) in seed_paths.iter().enumerate() {+ let Some(neighbors) = adjacency.get(seed) else {+ continue;+ };+ for neighbor in neighbors {+ if seed_set.contains(neighbor) {+ continue;+ }+ *candidate_scores.entry(neighbor.clone()).or_default() += 1.0 / (rank + 1) as f64;+ if let Some(seed_page) = pages.get(seed) {+ candidate_seeds+ .entry(neighbor.clone())+ .or_default()+ .insert(seed_page.title.clone());+ }+ }+ }++ let mut candidates: Vec<(String, f64)> = candidate_scores.into_iter().collect();+ candidates.sort_by(|(path_a, score_a), (path_b, score_b)| {+ score_b+ .partial_cmp(score_a)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| path_a.cmp(path_b))+ });+ candidates.truncate(graph_result_quota(limit, vector_hits));+ if candidates.is_empty() {+ ranked_results.truncate(limit);+ return 0;+ }++ let selected_paths: BTreeSet<String> =+ candidates.iter().map(|(path, _)| path.clone()).collect();+ let mut existing = BTreeMap::<String, ProjectSearchResult>::new();+ let mut ranked_paths = Vec::new();+ for result in ranked_results.drain(..) {+ let path = normalize_path(&result.path);+ ranked_paths.push(path.clone());+ existing.insert(path, result);+ }++ let graph_count = candidates.len();+ let base_limit = limit.saturating_sub(graph_count);+ let mut base_results: Vec<ProjectSearchResult> = ranked_paths+ .iter()+ .filter(|path| !selected_paths.contains(*path))+ .filter_map(|path| existing.get(path).cloned())+ .take(base_limit)+ .collect();++ for (path, graph_score) in candidates {+ if let Some(result) = existing.remove(&path) {+ let mut result = result;+ result.graph_related_to = candidate_seeds+ .remove(&path)+ .unwrap_or_default()+ .into_iter()+ .collect();+ base_results.push(result);+ continue;+ }+ let Some(page) = pages.get(&path) else {+ continue;+ };+ let related_titles = candidate_seeds+ .remove(&path)+ .unwrap_or_default()+ .into_iter()+ .collect::<Vec<_>>();+ let related = related_titles.join(", ");+ base_results.push(ProjectSearchResult {+ path: page.path.clone(),+ title: page.title.clone(),+ snippet: format!("Graph neighbor of {related}"),+ title_match: false,+ score: graph_score / (RRF_K + 1.0),+ vector_score: None,+ images: extract_image_refs(&page.content),+ content: include_content.then(|| page.content.clone()),+ graph_related_to: related_titles,+ });+ }+ *ranked_results = base_results;+ graph_count+}++fn normalize_graph_alias(value: &str) -> String {+ value+ .split('#')+ .next()+ .unwrap_or_default()+ .trim()+ .trim_end_matches(".md")+ .replace('\\', "/")+ .replace(' ', "-")+ .to_lowercase()+}++fn extract_wikilinks(content: &str) -> Vec<String> {+ let mut links = Vec::new();+ let mut rest = content;+ while let Some(start) = rest.find("[[") {+ rest = &rest[start + 2..];+ let Some(end) = rest.find("]]") else {+ break;+ };+ let target = rest[..end].split('|').next().unwrap_or_default().trim();+ if !target.is_empty() {+ links.push(target.to_string());+ }+ rest = &rest[end + 2..];+ }+ links+}++fn search_mode(token_rank_empty: bool, vector_hits: usize, graph_hits: usize) -> &'static str {+ if graph_hits > 0 {+ "hybrid"+ } else if vector_hits == 0 {"keyword"} else if token_rank_empty {"vector"@@ -408,6 +620,7 @@ fn materialize_vector_only_results(vector_score: Some(vr.score),images: extract_image_refs(&content),content: include_content.then_some(content),+ graph_related_to: Vec::new(),});known.insert(vr.id.clone());}@@ -494,6 +707,7 @@ fn score_file(vector_score: None,images: extract_image_refs(content),content: include_content.then_some(content.to_string()),+ graph_related_to: Vec::new(),})}@@ -1180,6 +1394,7 @@ mod tests {vector_score: None,images: vec![],content: None,+ graph_related_to: Vec::new(),}}@@ -1444,9 +1659,19 @@ mod tests {#[test]fn search_mode_distinguishes_keyword_vector_and_hybrid() {- assert_eq!(search_mode(false, 0), "keyword");- assert_eq!(search_mode(true, 3), "vector");- assert_eq!(search_mode(false, 3), "hybrid");+ assert_eq!(search_mode(false, 0, 0), "keyword");+ assert_eq!(search_mode(true, 3, 0), "vector");+ assert_eq!(search_mode(false, 3, 0), "hybrid");+ assert_eq!(search_mode(false, 0, 1), "hybrid");+ }++ #[test]+ fn graph_quota_scales_from_thirty_to_fifteen_percent() {+ assert_eq!(graph_result_quota(1, 0), 0);+ assert_eq!(graph_result_quota(20, 0), 6);+ assert_eq!(graph_result_quota(20, 10), 5);+ assert_eq!(graph_result_quota(20, 20), 3);+ assert_eq!(graph_result_quota(10, 100), 2);}#[test]@@ -1529,6 +1754,50 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[tokio::test]+ async fn keyword_search_always_blends_available_graph_neighbors() {+ let root = tmp_project();+ write_page(+ &root,+ "wiki/concepts/agent.md",+ "---\ntitle: Agent Runtime\n---\n\n# Agent Runtime\n\nagent runtime details. [[Tool Registry]]",+ );+ write_page(+ &root,+ "wiki/concepts/tool-registry.md",+ "---\ntitle: Tool Registry\n---\n\n# Tool Registry\n\nDefines callable tools.",+ );+ write_page(+ &root,+ "wiki/concepts/unrelated.md",+ "---\ntitle: Unrelated\n---\n\n# Unrelated\n\nNo graph connection.",+ );++ let out = search_project_inner(+ root.to_string_lossy().to_string(),+ "agent runtime".into(),+ 10,+ false,+ None,+ )+ .await+ .unwrap();++ assert_eq!(out.mode, "hybrid");+ assert_eq!(out.graph_hits, 1);+ assert!(out+ .results+ .iter()+ .any(|result| result.title == "Agent Runtime"));+ assert!(out.results.iter().any(|result| {+ result.title == "Tool Registry"+ && result.snippet.contains("Graph neighbor")+ && result.graph_related_to == vec!["Agent Runtime"]+ }));+ assert!(!out.results.iter().any(|result| result.title == "Unrelated"));+ let _ = fs::remove_dir_all(root);+ }+#[tokio::test]async fn keyword_search_handles_cjk_bigram_queries() {let root = tmp_project();diff --git a/src/components/chat/agent-file-activity.tsx b/src/components/chat/agent-file-activity.tsxindex a11161de..a36a9287 100644--- a/src/components/chat/agent-file-activity.tsx+++ b/src/components/chat/agent-file-activity.tsx@@ -1,4 +1,4 @@-import { useState } from "react"+import { useMemo, useState } from "react"import { ChevronDown, ChevronRight, FilePlus2, FileText, RotateCcw } from "lucide-react"import { useTranslation } from "react-i18next"import { deleteFile, readFile, writeFile } from "@/commands/fs"@@ -6,16 +6,26 @@ import type { ChatAgentFileChange } from "@/lib/chat-agent-types"import { getFileName } from "@/lib/path-utils"import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"import { useWikiStore } from "@/stores/wiki-store"+import { groupAgentFileChanges } from "@/lib/agent-file-activity"-export function AgentFileActivity({ changes }: { changes: ChatAgentFileChange[] }) {+export function AgentFileActivity({+ changes,+ embedded = false,+}: {+ changes: ChatAgentFileChange[]+ embedded?: boolean+}) {const { t } = useTranslation()const project = useWikiStore((state) => state.project)const openFileInPreview = useWikiStore((state) => state.openFileInPreview)- const [expanded, setExpanded] = useState<Record<string, boolean>>({})+ const [expandedFiles, setExpandedFiles] = useState<Record<string, boolean>>({})+ const [expandedEdits, setExpandedEdits] = useState<Record<string, boolean>>({})const [undoing, setUndoing] = useState<string | null>(null)const [undone, setUndone] = useState<Set<string>>(() => new Set())const [error, setError] = useState<string | null>(null)+ const groups = useMemo(() => groupAgentFileChanges(changes), [changes])+if (changes.length === 0) return nullconst undo = async (change: ChatAgentFileChange) => {@@ -42,64 +52,91 @@ export function AgentFileActivity({ changes }: { changes: ChatAgentFileChange[]}return (- <section className="rounded-md border border-border/60 bg-background/60" aria-label={t("chat.agentChanges.title") }>- <div className="flex items-center justify-between gap-2 border-b border-border/50 px-2.5 py-1.5">- <span className="text-xs font-medium">{t("chat.agentChanges.title")}</span>- <span className="text-[10px] tabular-nums text-muted-foreground">- {t("chat.agentChanges.fileCount", { count: changes.length })}- </span>- </div>+ <section className={embedded ? "" : "rounded-md border border-border/60 bg-background/60"} aria-label={t("chat.agentChanges.title") }>+ {!embedded && (+ <div className="flex items-center justify-between gap-2 border-b border-border/50 px-2.5 py-1.5">+ <span className="text-xs font-medium">{t("chat.agentChanges.title")}</span>+ <span className="text-[10px] tabular-nums text-muted-foreground">+ {t("chat.agentChanges.fileCount", { count: groups.length })}+ </span>+ </div>+ )}<div>- {changes.map((change) => {- const isExpanded = Boolean(expanded[change.id])- const canUndo = change.beforeContent !== undefined- && change.afterContent !== undefined- && !undone.has(change.id)- const Icon = change.operation === "created" ? FilePlus2 : FileText+ {groups.map((group) => {+ const fileExpanded = expandedFiles[group.path] ?? true+ const FileIcon = group.edits[0]?.operation === "created" ? FilePlus2 : FileTextreturn (- <div key={change.id} className="border-b border-border/40 last:border-b-0">- <div className="flex min-w-0 items-center gap-1.5 px-2 py-1.5 text-xs">+ <div key={group.path} className="border-b border-border/40 last:border-b-0">+ <div className="flex min-w-0 items-center gap-1.5 bg-muted/15 px-2 py-1.5 text-xs"><buttontype="button"- onClick={() => setExpanded((current) => ({ ...current, [change.id]: !isExpanded }))}+ onClick={() => setExpandedFiles((current) => ({ ...current, [group.path]: !fileExpanded }))}className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"- aria-expanded={isExpanded}- aria-label={isExpanded ? t("chat.agentChanges.collapseDiff") : t("chat.agentChanges.expandDiff")}+ aria-expanded={fileExpanded}+ aria-label={fileExpanded ? t("chat.agentChanges.collapseDiff") : t("chat.agentChanges.expandDiff")}>- {isExpanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}+ {fileExpanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}</button>- <Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <FileIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /><buttontype="button"onClick={() => {- void readFile(change.path)+ void readFile(group.path).catch(() => "")- .then((content) => openFileInPreview(change.path, content))+ .then((content) => openFileInPreview(group.path, content))}}className="min-w-0 flex-1 truncate text-left hover:underline"- title={change.path}- >- {getFileName(change.path)}- </button>- <span className="shrink-0 font-mono text-[10px] text-emerald-600 dark:text-emerald-400">+{change.additions}</span>- <span className="shrink-0 font-mono text-[10px] text-red-600 dark:text-red-400">-{change.deletions}</span>- <span className="shrink-0 text-[10px] text-muted-foreground">{new Date(change.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}</span>- <button- type="button"- disabled={!canUndo || undoing === change.id}- onClick={() => void undo(change)}- className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30"- title={canUndo ? t("chat.agentChanges.undo") : t("chat.agentChanges.undoUnavailable")}- aria-label={canUndo ? t("chat.agentChanges.undo") : t("chat.agentChanges.undoUnavailable")}+ title={group.path}>- <RotateCcw className={`h-3.5 w-3.5 ${undoing === change.id ? "animate-spin" : ""}`} />+ {getFileName(group.path)}</button>+ <span className="shrink-0 text-[10px] text-muted-foreground">+ {t("chat.agentChanges.editCount", { count: group.edits.length })}+ </span>+ <span className="shrink-0 font-mono text-[10px] text-emerald-600 dark:text-emerald-400">+{group.additions}</span>+ <span className="shrink-0 font-mono text-[10px] text-red-600 dark:text-red-400">-{group.deletions}</span></div>- {isExpanded && (- <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words border-t border-border/40 bg-muted/30 px-3 py-2 font-mono text-[10px] leading-4">- {change.diff}- </pre>- )}+ {fileExpanded && group.edits.map((change, editIndex) => {+ const editExpanded = Boolean(expandedEdits[change.id])+ const canUndo = change.beforeContent !== undefined+ && change.afterContent !== undefined+ && !undone.has(change.id)+ return (+ <div key={change.id} className="border-t border-border/30 pl-5">+ <div className="flex min-w-0 items-center gap-1.5 px-2 py-1 text-[11px]">+ <button+ type="button"+ onClick={() => setExpandedEdits((current) => ({ ...current, [change.id]: !editExpanded }))}+ className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-expanded={editExpanded}+ >+ {editExpanded ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}+ </button>+ <span className="min-w-0 flex-1 truncate text-muted-foreground">+ {change.tool} · {t("chat.agentChanges.editNumber", { number: editIndex + 1 })}+ </span>+ <span className="shrink-0 font-mono text-[10px] text-emerald-600 dark:text-emerald-400">+{change.additions}</span>+ <span className="shrink-0 font-mono text-[10px] text-red-600 dark:text-red-400">-{change.deletions}</span>+ <span className="shrink-0 text-[10px] text-muted-foreground">{new Date(change.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}</span>+ <button+ type="button"+ disabled={!canUndo || undoing === change.id}+ onClick={() => void undo(change)}+ className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30"+ title={canUndo ? t("chat.agentChanges.undo") : t("chat.agentChanges.undoUnavailable")}+ aria-label={canUndo ? t("chat.agentChanges.undo") : t("chat.agentChanges.undoUnavailable")}+ >+ <RotateCcw className={`h-3.5 w-3.5 ${undoing === change.id ? "animate-spin" : ""}`} />+ </button>+ </div>+ {editExpanded && (+ <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words border-t border-border/30 bg-muted/30 px-3 py-2 font-mono text-[10px] leading-4">+ {change.diff}+ </pre>+ )}+ </div>+ )+ })}</div>)})}diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsxindex 65abb0f2..9d0af23b 100644--- a/src/components/chat/chat-message.tsx+++ b/src/components/chat/chat-message.tsx@@ -36,6 +36,7 @@ import { filterRawSourceTree } from "@/lib/source-filter"import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"import { getFileCategory, getFileExtension, isTextReadable } from "@/lib/file-types"import { AgentFileActivity } from "@/components/chat/agent-file-activity"+import { ReferenceKnowledgeGraph } from "@/components/chat/reference-knowledge-graph"// Module-level cache of source file nameslet cachedSourceFiles: string[] = []@@ -148,15 +149,16 @@ function ChatMessageImpl({</div>)}{isAssistant && (- <SavedAgentActivity+ (message.agentSteps?.some((step) => step.type !== "final") ?? false)+ || (message.agentFileChanges?.length ?? 0) > 0+ ) && (+ <AgentTurnActivitysteps={message.agentSteps ?? []}+ changes={message.agentFileChanges ?? []}canApproveShellCommand={Boolean(isLastAssistant && onApproveShellCommand)}onApproveShellCommand={(command) => onApproveShellCommand?.(command, message.id)}/>)}- {isAssistant && message.agentFileChanges && message.agentFileChanges.length > 0 && (- <AgentFileActivity changes={message.agentFileChanges} />- )}{(!isUser || message.content) && (<divclassName={`rounded-lg px-3 py-2 text-sm ${@@ -206,14 +208,49 @@ function ChatMessageImpl({)}+function AgentTurnActivity({+ steps,+ changes,+ canApproveShellCommand,+ onApproveShellCommand,+}: {+ steps: ChatAgentStep[]+ changes: NonNullable<DisplayMessage["agentFileChanges"]>+ canApproveShellCommand?: boolean+ onApproveShellCommand?: (command: string) => void+}) {+ const { t } = useTranslation()+ return (+ <section className="rounded-md border border-border/50 bg-background/50" aria-label={t("chat.agentChanges.taskTitle")}>+ <div className="flex items-center justify-between border-b border-border/50 px-2.5 py-1.5">+ <span className="text-xs font-medium">{t("chat.agentChanges.taskTitle")}</span>+ {changes.length > 0 && (+ <span className="text-[10px] text-muted-foreground">+ {t("chat.agentChanges.fileCount", { count: new Set(changes.map((change) => change.path)).size })}+ </span>+ )}+ </div>+ <SavedAgentActivity+ steps={steps}+ canApproveShellCommand={canApproveShellCommand}+ onApproveShellCommand={onApproveShellCommand}+ embedded+ />+ {changes.length > 0 && <AgentFileActivity changes={changes} embedded />}+ </section>+ )+}+function SavedAgentActivity({steps,canApproveShellCommand,onApproveShellCommand,+ embedded = false,}: {steps: ChatAgentStep[]canApproveShellCommand?: booleanonApproveShellCommand?: (command: string) => void+ embedded?: boolean}) {const { t } = useTranslation()const events = useMemo<ChatAgentEvent[]>(() => steps@@ -231,11 +268,12 @@ function SavedAgentActivity({message: step.message,count: step.count,status: step.status,+ timestamp: step.timestamp,})), [steps])const shellCommand = useMemo(() => extractShellApprovalCommand(steps), [steps])if (events.length === 0 && !shellCommand) return nullreturn (- <div className="space-y-1 rounded-md border border-border/50 bg-background/50 px-2 py-1">+ <div className={embedded ? "space-y-1 border-b border-border/40 px-2 py-1.5" : "space-y-1 rounded-md border border-border/50 bg-background/50 px-2 py-1"}>{events.length > 0 && <AgentActivity events={events} compact />}{shellCommand && canApproveShellCommand && (<button@@ -1082,6 +1120,7 @@ function CitedReferencesPanel({)}</button><div className="px-2 pb-1.5">+ <ReferenceKnowledgeGraph references={citedPages} onOpenReference={openCitedPage} />{visiblePages.map((page, i) => {const refType = getRefType(page.path, page)const config = REF_TYPE_CONFIG[refType] ?? REF_TYPE_CONFIG.source@@ -1311,6 +1350,15 @@ function AgentActivity({ events, compact = false }: { events: ChatAgentEvent[];<span className="text-muted-foreground"> · {t("chat.agent.resultCount", { count: event.count })}</span>) : null}</span>+ {event.timestamp && (+ <time className="ml-auto shrink-0 text-[10px] tabular-nums text-muted-foreground/70">+ {new Date(event.timestamp).toLocaleTimeString([], {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ })}+ </time>+ )}</div>)})}diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex 73a1c3e0..c5ca0c02 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -35,12 +35,18 @@ interface BackendAgentReference {kind: stringsnippet?: stringscore?: number+ knowledgeContext?: {+ relatedTo?: string[]+ outgoingLinks?: string[]+ backlinks?: string[]+ }}interface BackendAgentToolEvent {tool: stringstatus: stringdetail?: string+ timestamp?: number}interface BackendAgentEventPayload {@@ -264,6 +270,7 @@ function backendReferenceToMessageReference(ref: BackendAgentReference): Messagesource,url: isWeb ? ref.path : undefined,snippet: ref.snippet,+ graphRelations: ref.knowledgeContext?.relatedTo,}}@@ -291,6 +298,7 @@ function backendToolToAgentStep(event: BackendAgentToolEvent, index: number) {type: "routing" as const,message: event.detail ?? event.tool,status: event.status === "failed" ? "error" as const : "success" as const,+ timestamp: event.timestamp,}}if (event.tool === "llm.generate") {@@ -301,6 +309,7 @@ function backendToolToAgentStep(event: BackendAgentToolEvent, index: number) {status: event.status === "failed" ? "error" as const: event.status === "started" ? "running" as const: "success" as const,+ timestamp: event.timestamp,}}const tool = normalizeBackendToolName(event.tool)@@ -313,6 +322,7 @@ function backendToolToAgentStep(event: BackendAgentToolEvent, index: number) {: event.status === "available" ? "skipped" as const: event.status === "started" ? "running" as const: "success" as const,+ timestamp: event.timestamp,}}@@ -341,6 +351,7 @@ function backendToolToAgentEvent(event: BackendAgentToolEvent): ChatAgentEvent {stage: "routing",message: event.detail ?? event.tool,status: event.status === "failed" ? "error" : "success",+ timestamp: event.timestamp,}}if (event.tool === "llm.generate") {@@ -350,6 +361,7 @@ function backendToolToAgentEvent(event: BackendAgentToolEvent): ChatAgentEvent {status: event.status === "failed" ? "error": event.status === "started" ? "running": "success",+ timestamp: event.timestamp,}}const tool = normalizeBackendToolName(event.tool)@@ -369,6 +381,7 @@ function backendToolToAgentEvent(event: BackendAgentToolEvent): ChatAgentEvent {: event.status === "started" ? "running": event.status === "available" ? "skipped": "success",+ timestamp: event.timestamp,}}@@ -738,6 +751,7 @@ export function ChatPanel() {const fileChanges = new Map<string, ChatAgentFileChange>()const fileEditChanges: ChatAgentFileChange[] = []let fileEditSequence = 0+ const fileEditOrder = new Map<string, number>()const trackedFilePaths = new Set<string>()const fileActivityTasks: Promise<void>[] = []const fileActivityChains = new Map<string, Promise<void>>()@@ -811,10 +825,14 @@ export function ChatPanel() {return [...prev, preview]})if (!trackedFilePaths.has(outputPath) && !fileChanges.has(outputPath)) {+ const editSequence = ++fileEditSequence+ const editId = `${backendRunId}:${outputPath}:${editSequence}`+ const editTimestamp = Date.now()+ fileEditOrder.set(editId, editSequence)const task = readAgentActivitySnapshot(outputPath).then((afterContent) => {if (afterContent === null) returnconst change = summarizeAgentFileChange({- id: `${backendRunId}:${outputPath}:${++fileEditSequence}`,+ id: editId,path: outputPath,tool: "shell.exec",// Shell can create or replace multiple files, but it cannot@@ -822,6 +840,7 @@ export function ChatPanel() {// observed file is new because Undo could delete user data.beforeContent: "",afterContent,+ timestamp: editTimestamp,})change.operation = "modified"change.additions = 0@@ -839,7 +858,10 @@ export function ChatPanel() {}if (agentEvent.type === "fileChanged" && project && agentEvent.path && agentEvent.tool) {const filePath = projectAbsolutePath(project.path, agentEvent.path)- const editId = `${backendRunId}:${filePath}:${++fileEditSequence}`+ const editSequence = ++fileEditSequence+ const editId = `${backendRunId}:${filePath}:${editSequence}`+ const editTimestamp = Date.now()+ fileEditOrder.set(editId, editSequence)trackedFilePaths.add(filePath)const previousTask = fileActivityChains.get(filePath) ?? Promise.resolve()const task = previousTask.then(async () => {@@ -853,6 +875,7 @@ export function ChatPanel() {tool: agentEvent.tool!,beforeContent: beforeKnown ? (originalBefore ?? null) : "",afterContent,+ timestamp: editTimestamp,})if (!beforeKnown) {change.operation = "modified"@@ -884,6 +907,7 @@ export function ChatPanel() {tool: agentEvent.tool,status: "started",detail: agentEvent.input,+ timestamp: Date.now(),}backendEvents.push(toolEvent)setAgentEvents((prev) => [...prev, backendToolToAgentEvent(toolEvent)].slice(-6))@@ -896,6 +920,7 @@ export function ChatPanel() {tool: agentEvent.tool,status: failed ? "failed" : skipped ? "available" : "completed",detail: agentEvent.output,+ timestamp: Date.now(),}backendEvents.push(toolEvent)setAgentEvents((prev) => [...prev, backendToolToAgentEvent(toolEvent)].slice(-6))@@ -906,6 +931,7 @@ export function ChatPanel() {tool: "agent",status: "failed",detail: agentEvent.message,+ timestamp: Date.now(),}backendEvents.push(toolEvent)setAgentEvents((prev) => [...prev, backendToolToAgentEvent(toolEvent)].slice(-6))@@ -947,6 +973,9 @@ export function ChatPanel() {})await streamDoneawait Promise.allSettled(fileActivityTasks)+ fileEditChanges.sort(+ (left, right) => (fileEditOrder.get(left.id) ?? 0) - (fileEditOrder.get(right.id) ?? 0),+ )} finally {clearStreamTimeout()streamUnlisten?.()diff --git a/src/components/chat/reference-knowledge-graph.tsx b/src/components/chat/reference-knowledge-graph.tsxnew file mode 100644index 00000000..74388888--- /dev/null+++ b/src/components/chat/reference-knowledge-graph.tsx@@ -0,0 +1,140 @@+import { useEffect, useMemo, useState } from "react"+import Graph from "graphology"+import { SigmaContainer, useLoadGraph, useRegisterEvents, useSigma } from "@react-sigma/core"+import "@react-sigma/core/lib/style.css"+import type { MessageReference } from "@/stores/chat-store"++interface ReferenceKnowledgeGraphProps {+ references: MessageReference[]+ onOpenReference: (reference: MessageReference) => void+}++interface ReferenceGraphData {+ nodes: Array<{ id: string; label: string; reference?: MessageReference; graphResult: boolean }>+ edges: Array<{ source: string; target: string }>+}++function buildReferenceGraph(references: MessageReference[]): ReferenceGraphData {+ const byTitle = new Map(references.map((reference) => [reference.title, reference]))+ const nodes = new Map<string, ReferenceGraphData["nodes"][number]>()+ const edges = new Map<string, ReferenceGraphData["edges"][number]>()++ for (const target of references) {+ if (target.source !== "Graph") continue+ const targetId = `reference:${target.path}`+ nodes.set(targetId, { id: targetId, label: target.title, reference: target, graphResult: true })+ for (const relatedTitle of target.graphRelations ?? []) {+ const source = byTitle.get(relatedTitle)+ const sourceId = source ? `reference:${source.path}` : `relation:${relatedTitle}`+ nodes.set(sourceId, {+ id: sourceId,+ label: relatedTitle,+ reference: source,+ graphResult: false,+ })+ const key = [sourceId, targetId].sort().join("\u0000")+ edges.set(key, { source: sourceId, target: targetId })+ }+ }++ return { nodes: [...nodes.values()], edges: [...edges.values()] }+}++function ReferenceGraphLoader({ data }: { data: ReferenceGraphData }) {+ const loadGraph = useLoadGraph()++ useEffect(() => {+ const graph = new Graph({ type: "undirected" })+ const count = Math.max(data.nodes.length, 1)+ data.nodes.forEach((node, index) => {+ const angle = (index / count) * Math.PI * 2 - Math.PI / 2+ graph.addNode(node.id, {+ x: Math.cos(angle),+ y: Math.sin(angle),+ size: node.graphResult ? 11 : 8,+ color: node.graphResult ? "#2dd4bf" : "#60a5fa",+ label: node.label,+ forceLabel: true,+ })+ })+ data.edges.forEach((edge, index) => {+ if (!graph.hasNode(edge.source) || !graph.hasNode(edge.target)) return+ graph.addEdgeWithKey(`reference-edge-${index}`, edge.source, edge.target, {+ color: "rgba(100,116,139,0.55)",+ size: 1.5,+ })+ })+ loadGraph(graph)+ }, [data, loadGraph])++ return null+}++function ReferenceGraphEvents({ data, onOpenReference }: ReferenceKnowledgeGraphProps & { data: ReferenceGraphData }) {+ const registerEvents = useRegisterEvents()+ const sigma = useSigma()+ const referencesByNode = useMemo(+ () => new Map(data.nodes.map((node) => [node.id, node.reference])),+ [data.nodes],+ )++ useEffect(() => {+ return registerEvents({+ enterNode: ({ event }) => {+ event.original.preventDefault()+ sigma.getContainer().style.cursor = "pointer"+ },+ leaveNode: () => {+ sigma.getContainer().style.cursor = "default"+ },+ clickNode: ({ node }) => {+ const reference = referencesByNode.get(node)+ if (reference) onOpenReference(reference)+ },+ })+ }, [onOpenReference, referencesByNode, registerEvents, sigma])++ useEffect(() => () => {+ sigma.getContainer().style.cursor = "default"+ }, [sigma])++ return null+}++export function ReferenceKnowledgeGraph({ references, onOpenReference }: ReferenceKnowledgeGraphProps) {+ const data = useMemo(() => buildReferenceGraph(references), [references])+ const [dark, setDark] = useState(() => document.documentElement.classList.contains("dark"))+ useEffect(() => {+ const root = document.documentElement+ const observer = new MutationObserver(() => setDark(root.classList.contains("dark")))+ observer.observe(root, { attributes: true, attributeFilter: ["class"] })+ return () => observer.disconnect()+ }, [])+ if (data.nodes.length < 2 || data.edges.length === 0) return null++ return (+ <div className="mb-1.5 h-44 overflow-hidden border-b border-border/50 pb-1.5">+ <SigmaContainer+ key={dark ? "dark" : "light"}+ style={{ width: "100%", height: "100%", background: "transparent" }}+ settings={{+ defaultNodeType: "circle",+ renderEdgeLabels: false,+ hideEdgesOnMove: true,+ // Reference graphs are deliberately small. Keep labels visible while+ // dragging and zooming; the large-graph performance optimization used+ // by GraphView makes this compact graph appear to flicker.+ hideLabelsOnMove: false,+ labelColor: { color: dark ? "#f8fafc" : "#1e293b" },+ labelSize: 11,+ labelWeight: "600",+ stagePadding: 24,+ allowInvalidContainer: true,+ }}+ >+ <ReferenceGraphLoader data={data} />+ <ReferenceGraphEvents data={data} references={references} onOpenReference={onOpenReference} />+ </SigmaContainer>+ </div>+ )+}diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex c840017e..446f35e4 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -125,8 +125,12 @@"chat": {"agentChanges": {"title": "Agent file changes",+ "taskTitle": "Agent activity","fileCount": "{{count}} file","fileCount_other": "{{count}} files",+ "editCount": "{{count}} edit",+ "editCount_other": "{{count}} edits",+ "editNumber": "edit {{number}}","expandDiff": "Expand file diff","collapseDiff": "Collapse file diff","undo": "Undo this Agent change",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 0af70196..1a3f7614 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -125,8 +125,12 @@"chat": {"agentChanges": {"title": "Agent 文件修改",+ "taskTitle": "Agent 活动","fileCount": "{{count}} 个文件","fileCount_other": "{{count}} 个文件",+ "editCount": "{{count}} 次修改",+ "editCount_other": "{{count}} 次修改",+ "editNumber": "第 {{number}} 次修改","expandDiff": "展开文件差异","collapseDiff": "收起文件差异","undo": "撤销本次 Agent 修改",diff --git a/src/lib/agent-file-activity.test.ts b/src/lib/agent-file-activity.test.tsindex 08cfcd90..77ec89ba 100644--- a/src/lib/agent-file-activity.test.ts+++ b/src/lib/agent-file-activity.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vitest"-import { mergeAgentFileChange, summarizeAgentFileChange } from "@/lib/agent-file-activity"+import {+ groupAgentFileChanges,+ mergeAgentFileChange,+ summarizeAgentFileChange,+} from "@/lib/agent-file-activity"describe("agent file activity", () => {it("summarizes a created file", () => {@@ -51,4 +55,41 @@ describe("agent file activity", () => {expect(merged.beforeContent).toBe("original")expect(merged.afterContent).toBe("middle\nend")})++ it("groups repeated edits by file while preserving execution order", () => {+ const first = summarizeAgentFileChange({+ id: "1",+ path: "/project/wiki/a.md",+ tool: "wiki.write_page",+ beforeContent: "old",+ afterContent: "new",+ timestamp: 1,+ })+ const second = summarizeAgentFileChange({+ id: "2",+ path: "/project/wiki/b.md",+ tool: "workspace.write_file",+ beforeContent: null,+ afterContent: "b",+ timestamp: 2,+ })+ const third = summarizeAgentFileChange({+ id: "3",+ path: "/project/wiki/a.md",+ tool: "wiki.write_page",+ beforeContent: "new",+ afterContent: "newer\nline",+ timestamp: 3,+ })++ const groups = groupAgentFileChanges([first, second, third])++ expect(groups.map((group) => group.path)).toEqual([+ "/project/wiki/a.md",+ "/project/wiki/b.md",+ ])+ expect(groups[0].edits.map((edit) => edit.id)).toEqual(["1", "3"])+ expect(groups[0].additions).toBe(first.additions + third.additions)+ expect(groups[0].deletions).toBe(first.deletions + third.deletions)+ })})diff --git a/src/lib/agent-file-activity.ts b/src/lib/agent-file-activity.tsindex 252a2358..3d8b98bd 100644--- a/src/lib/agent-file-activity.ts+++ b/src/lib/agent-file-activity.ts@@ -77,3 +77,29 @@ export function mergeAgentFileChange(afterContent: next.afterContent,}}++export interface AgentFileChangeGroup {+ path: string+ edits: ChatAgentFileChange[]+ additions: number+ deletions: number+}++/** Preserve first-seen file and edit order so the activity timeline matches+ * execution order while aggregating per-file totals for quick review. */+export function groupAgentFileChanges(+ changes: readonly ChatAgentFileChange[],+): AgentFileChangeGroup[] {+ const byPath = new Map<string, ChatAgentFileChange[]>()+ for (const change of changes) {+ const edits = byPath.get(change.path) ?? []+ edits.push(change)+ byPath.set(change.path, edits)+ }+ return [...byPath.entries()].map(([path, edits]) => ({+ path,+ edits,+ additions: edits.reduce((sum, edit) => sum + edit.additions, 0),+ deletions: edits.reduce((sum, edit) => sum + edit.deletions, 0),+ }))+}diff --git a/src/lib/chat-agent-types.ts b/src/lib/chat-agent-types.tsindex ab17cf81..e747d1fe 100644--- a/src/lib/chat-agent-types.ts+++ b/src/lib/chat-agent-types.ts@@ -27,6 +27,7 @@ export interface ChatAgentEvent {message?: stringcount?: numberstatus?: "running" | "success" | "error" | "skipped"+ timestamp?: number}export type ChatAgentMode = "fast" | "standard" | "deep" | "local_first"@@ -75,6 +76,7 @@ export interface ChatAgentStep {message?: stringcount?: numberstatus?: "running" | "success" | "error" | "skipped"+ timestamp?: number}export interface ChatAgentFileChange {diff --git a/src/lib/search.ts b/src/lib/search.tsindex a73f81c4..e83056e3 100644--- a/src/lib/search.ts+++ b/src/lib/search.ts@@ -24,6 +24,7 @@ interface BackendSearchResponse {results: SearchResult[]tokenHits: numbervectorHits: number+ graphHits?: number}const STOP_WORDS = new Set([diff --git a/src/stores/chat-store.ts b/src/stores/chat-store.tsindex 4886fc94..63a8f671 100644--- a/src/stores/chat-store.ts+++ b/src/stores/chat-store.ts@@ -31,6 +31,7 @@ export interface MessageReference {source?: stringurl?: stringsnippet?: string+ graphRelations?: string[]}export interface DisplayMessage {