diff --git a/crates/veles-cli/src/handlers.rs b/crates/veles-cli/src/handlers.rs index 7b8f444..68849fd 100644 --- a/crates/veles-cli/src/handlers.rs +++ b/crates/veles-cli/src/handlers.rs @@ -83,7 +83,7 @@ pub fn handle_find_related( } }; - let mut results = index.find_related(&chunk, top_k); + let mut results = index.find_related(&chunk, top_k, None, None); if let Some(threshold) = min_score { results.retain(|r| r.score >= threshold); } diff --git a/crates/veles-cli/src/tui/search.rs b/crates/veles-cli/src/tui/search.rs index 487b743..ea5ea47 100644 --- a/crates/veles-cli/src/tui/search.rs +++ b/crates/veles-cli/src/tui/search.rs @@ -95,7 +95,7 @@ fn worker_loop(index: Arc, cmd_rx: Receiver, msg_tx: Send WorkerCmd::Related { seq, source, top_k } => { let started = Instant::now(); let anchor = format!("{}:{}", source.file_path, source.start_line); - let results = index.find_related(&source, top_k); + let results = index.find_related(&source, top_k, None, None); let elapsed_ms = started.elapsed().as_millis() as u64; let _ = msg_tx.send(WorkerMsg::SearchDone(SearchDone { seq, diff --git a/crates/veles-core/src/veles_index.rs b/crates/veles-core/src/veles_index.rs index 8ed1425..55d046c 100644 --- a/crates/veles-core/src/veles_index.rs +++ b/crates/veles-core/src/veles_index.rs @@ -441,12 +441,28 @@ impl VelesIndex { } /// Return chunks semantically similar to the given chunk. - pub fn find_related(&self, source: &Chunk, top_k: usize) -> Vec { - let selector = source - .language - .as_ref() - .and_then(|lang| self.language_mapping.get(lang)) - .map(|v| v.as_slice()); + /// + /// When neither `filter_languages` nor `filter_paths` is supplied, the + /// search is restricted to chunks in the same language as `source` — + /// the historical default ("show me semantically similar Rust code + /// given a Rust starting point"). Pass an explicit empty slice + /// (`Some(&[])`) on either filter to opt out of that default. + pub fn find_related( + &self, + source: &Chunk, + top_k: usize, + filter_languages: Option<&[String]>, + filter_paths: Option<&[String]>, + ) -> Vec { + let selector: Option> = if filter_languages.is_none() && filter_paths.is_none() { + source + .language + .as_ref() + .and_then(|lang| self.language_mapping.get(lang)) + .cloned() + } else { + self.get_selector_vector(filter_languages, filter_paths) + }; let results = search_semantic( &source.content, @@ -454,7 +470,7 @@ impl VelesIndex { &self.dense_index, &self.chunks, top_k + 1, - selector, + selector.as_deref(), ); results diff --git a/crates/veles-grpc/src/lib.rs b/crates/veles-grpc/src/lib.rs index 8d001e8..5bb3a66 100644 --- a/crates/veles-grpc/src/lib.rs +++ b/crates/veles-grpc/src/lib.rs @@ -226,7 +226,7 @@ impl VelesService for VelesServiceImpl { })? .clone(); - let results = index.find_related(&chunk, top_k); + let results = index.find_related(&chunk, top_k, None, None); Ok(Response::new(FindRelatedResponse { results: results.into_iter().map(convert_result).collect(), diff --git a/crates/veles-mcp/src/lib.rs b/crates/veles-mcp/src/lib.rs index eb51ac7..baeee01 100644 --- a/crates/veles-mcp/src/lib.rs +++ b/crates/veles-mcp/src/lib.rs @@ -261,7 +261,7 @@ fn tools() -> Vec { }, Tool { name: "find_related".into(), - description: "Find code chunks semantically similar to a specific location in a file. Use after `search` to explore related implementations or callers.".into(), + description: "Find code chunks semantically similar to a specific location in a file. Use after `search` to explore related implementations or callers. Defaults to the source chunk's language; pass `lang` / `path` / `exclude` to override.".into(), input_schema: json!({ "type": "object", "properties": { @@ -282,6 +282,21 @@ fn tools() -> Vec { "description": "Number of similar chunks to return.", "default": 5 }, + "lang": { + "type": "array", + "items": {"type": "string"}, + "description": "Restrict results to these languages. Overrides the default (same language as the source chunk)." + }, + "path": { + "type": "array", + "items": {"type": "string"}, + "description": "Glob patterns of paths to include (e.g. ['src/**/*.rs'])." + }, + "exclude": { + "type": "array", + "items": {"type": "string"}, + "description": "Glob patterns of paths to exclude (e.g. ['tests/**'])." + }, "format": { "type": "string", "enum": ["default", "paths"], @@ -648,7 +663,25 @@ impl McpServer { .then(a.start_line.cmp(&b.start_line)) }); - let bm25_hits = index.search(name, top_k, SearchMode::Bm25, None, None, None); + // Pull a few extra BM25 hits so that dropping chunks that overlap a + // definition site still leaves the caller with roughly the requested + // count. Two-thirds extra is enough for most realistic queries + // without ballooning the round-trip. + let bm25_overshoot = top_k + (top_k / 2).max(1); + let bm25_hits: Vec = index + .search(name, bm25_overshoot, SearchMode::Bm25, None, None, None) + .into_iter() + .filter(|hit| { + // Drop hits whose chunk *contains* a definition's start line — + // those are the same code the def section already pointed at. + !defs.iter().any(|d| { + d.file_path == hit.chunk.file_path + && d.start_line >= hit.chunk.start_line + && d.start_line <= hit.chunk.end_line + }) + }) + .take(top_k) + .collect(); if defs.is_empty() && bm25_hits.is_empty() { return Ok(json!({ @@ -815,6 +848,9 @@ impl McpServer { let repo = args["repo"].as_str().unwrap_or("."); let top_k = args["top_k"].as_u64().unwrap_or(5) as usize; let format = args["format"].as_str().unwrap_or("default"); + let lang = string_array(&args, "lang"); + let path_globs = string_array(&args, "path"); + let exclude_globs = string_array(&args, "exclude"); let mut cache = self.cache.lock().await; let index = cache.get_or_index(repo, false).map_err(|e| JsonRpcError { @@ -830,7 +866,17 @@ impl McpServer { })? .clone(); - let results = index.find_related(&chunk, top_k); + let glob_paths = + filter::resolve_path_filter(index, &path_globs, &exclude_globs).map_err(|e| { + JsonRpcError { + code: -32000, + message: e.to_string(), + } + })?; + let lang_slice: Option<&[String]> = if lang.is_empty() { None } else { Some(&lang) }; + let path_slice: Option<&[String]> = glob_paths.as_deref(); + + let results = index.find_related(&chunk, top_k, lang_slice, path_slice); if results.is_empty() { return Ok(json!({