Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/veles-cli/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/veles-cli/src/tui/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ fn worker_loop(index: Arc<VelesIndex>, cmd_rx: Receiver<WorkerCmd>, 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,
Expand Down
30 changes: 23 additions & 7 deletions crates/veles-core/src/veles_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,20 +441,36 @@ impl VelesIndex {
}

/// Return chunks semantically similar to the given chunk.
pub fn find_related(&self, source: &Chunk, top_k: usize) -> Vec<SearchResult> {
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<SearchResult> {
let selector: Option<Vec<usize>> = 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,
&self.model,
&self.dense_index,
&self.chunks,
top_k + 1,
selector,
selector.as_deref(),
);

results
Expand Down
2 changes: 1 addition & 1 deletion crates/veles-grpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
52 changes: 49 additions & 3 deletions crates/veles-mcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ fn tools() -> Vec<Tool> {
},
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": {
Expand All @@ -282,6 +282,21 @@ fn tools() -> Vec<Tool> {
"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"],
Expand Down Expand Up @@ -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<veles_core::types::SearchResult> = 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!({
Expand Down Expand Up @@ -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 {
Expand All @@ -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!({
Expand Down