use std::path::Path;
use std::sync::{OnceLock, RwLock};
use super::query::path_has_component;
pub const STRONG_PATH_SCORE: f32 = 1000.0;
pub const BASENAME_SCORE: f32 = 100.0;
pub const PREFIX_SCORE: f32 = 50.0;
pub const LOOSE_PATH_SCORE: f32 = 10.0;
#[derive(Debug, Clone, Copy)]
pub struct RankCtx<'a> {
pub query: &'a str,
pub tokens: &'a [String],
pub current_file: Option<&'a str>,
pub target_path: Option<&'a str>,
}
impl<'a> RankCtx<'a> {
pub const fn empty() -> Self {
Self {
query: "",
tokens: &[],
current_file: None,
target_path: None,
}
}
}
impl Default for RankCtx<'_> {
fn default() -> Self {
Self::empty()
}
}
pub trait RankSignal: Send + Sync {
fn name(&self) -> &'static str;
fn weight(&self) -> f32;
fn score(&self, path: &Path, ctx: &RankCtx<'_>) -> f32;
}
pub struct PathMatchSignal;
impl RankSignal for PathMatchSignal {
fn name(&self) -> &'static str {
"path_match"
}
fn weight(&self) -> f32 {
1.0
}
fn score(&self, path: &Path, ctx: &RankCtx<'_>) -> f32 {
if ctx.tokens.is_empty() {
return 0.0;
}
let path_str = path.to_string_lossy();
let path_lower = path_str.to_ascii_lowercase();
let query_lower = ctx.query.to_ascii_lowercase();
let has_path_context = ctx.query.contains('/');
let is_exact = !query_lower.is_empty() && path_lower == query_lower;
let is_suffix = has_path_context
&& !query_lower.is_empty()
&& path_lower.ends_with(&query_lower);
let basename_token = ctx.tokens.last().map(String::as_str).unwrap_or("");
let component_tokens: &[String] = if ctx.tokens.len() > 1 {
&ctx.tokens[..ctx.tokens.len() - 1]
} else {
&[]
};
let file_basename = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let file_stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_ascii_lowercase();
let has_basename_match =
!basename_token.is_empty() && file_basename == basename_token;
let has_all_components = !component_tokens.is_empty()
&& component_tokens
.iter()
.all(|component| path_has_component(&path_str, component));
if is_exact || is_suffix || (has_basename_match && has_all_components) {
return STRONG_PATH_SCORE;
}
if has_basename_match {
return BASENAME_SCORE;
}
if basename_token.len() >= 3 && file_stem.starts_with(basename_token) {
return PREFIX_SCORE;
}
if ctx.tokens.iter().all(|token| path_lower.contains(token)) {
return LOOSE_PATH_SCORE;
}
0.0
}
}
pub struct CoChangeSignal;
impl RankSignal for CoChangeSignal {
fn name(&self) -> &'static str {
"co_change"
}
fn weight(&self) -> f32 {
1.0
}
fn score(&self, _path: &Path, _ctx: &RankCtx<'_>) -> f32 {
0.0
}
}
fn registry() -> &'static RwLock<Vec<Box<dyn RankSignal>>> {
static REGISTRY: OnceLock<RwLock<Vec<Box<dyn RankSignal>>>> = OnceLock::new();
REGISTRY.get_or_init(|| {
let defaults: Vec<Box<dyn RankSignal>> =
vec![Box::new(PathMatchSignal), Box::new(CoChangeSignal)];
RwLock::new(defaults)
})
}
pub fn register(signal: Box<dyn RankSignal>) {
let mut guard = registry().write().expect("rank_signals registry poisoned");
guard.push(signal);
}
pub fn combine(path: &Path, ctx: &RankCtx<'_>) -> f32 {
let guard = registry().read().expect("rank_signals registry poisoned");
guard
.iter()
.map(|signal| signal.weight() * signal.score(path, ctx))
.sum()
}
#[cfg(test)]
fn registered_count() -> usize {
registry()
.read()
.expect("rank_signals registry poisoned")
.len()
}
#[cfg(test)]
fn reset_for_tests() {
let mut guard = registry().write().expect("rank_signals registry poisoned");
guard.clear();
guard.push(Box::new(PathMatchSignal));
guard.push(Box::new(CoChangeSignal));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_register_two_signals() {
reset_for_tests();
assert_eq!(registered_count(), 2);
}
#[test]
fn default_signals_expose_stable_names() {
assert_eq!(PathMatchSignal.name(), "path_match");
assert_eq!(CoChangeSignal.name(), "co_change");
}
#[test]
fn default_signals_score_zero_on_any_input() {
let ctx = RankCtx::empty();
assert_eq!(PathMatchSignal.score(Path::new("foo.rs"), &ctx), 0.0);
assert_eq!(CoChangeSignal.score(Path::new("foo.rs"), &ctx), 0.0);
}
#[test]
fn rank_signal_is_object_safe() {
let _boxed: Box<dyn RankSignal> = Box::new(PathMatchSignal);
let _erased: &dyn RankSignal = &CoChangeSignal;
}
#[test]
fn combine_with_defaults_returns_zero() {
reset_for_tests();
let ctx = RankCtx::empty();
assert_eq!(combine(Path::new("src/live_index/rank_signals.rs"), &ctx), 0.0);
}
#[test]
fn combine_sums_weighted_scores_from_registered_signals() {
struct FixedTwoTimesThree;
impl RankSignal for FixedTwoTimesThree {
fn name(&self) -> &'static str {
"__test_two_times_three"
}
fn weight(&self) -> f32 {
2.0
}
fn score(&self, _path: &Path, _ctx: &RankCtx<'_>) -> f32 {
3.0
}
}
struct FixedHalfTimesFour;
impl RankSignal for FixedHalfTimesFour {
fn name(&self) -> &'static str {
"__test_half_times_four"
}
fn weight(&self) -> f32 {
0.5
}
fn score(&self, _path: &Path, _ctx: &RankCtx<'_>) -> f32 {
4.0
}
}
reset_for_tests();
register(Box::new(FixedTwoTimesThree));
register(Box::new(FixedHalfTimesFour));
let ctx = RankCtx::empty();
let total = combine(Path::new("anything"), &ctx);
assert!((total - 8.0).abs() < f32::EPSILON);
reset_for_tests();
}
#[test]
fn rank_ctx_default_matches_empty() {
let default = RankCtx::default();
let empty = RankCtx::empty();
assert_eq!(default.query, empty.query);
assert_eq!(default.tokens.len(), empty.tokens.len());
assert_eq!(default.current_file, empty.current_file);
assert_eq!(default.target_path, empty.target_path);
}
fn ctx_with<'a>(query: &'a str, tokens: &'a [String]) -> RankCtx<'a> {
RankCtx {
query,
tokens,
current_file: None,
target_path: None,
}
}
#[test]
fn path_match_strong_on_exact_path() {
let tokens = vec![
"src".to_string(),
"protocol".to_string(),
"tools.rs".to_string(),
];
let ctx = ctx_with("src/protocol/tools.rs", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/protocol/tools.rs"), &ctx),
STRONG_PATH_SCORE
);
}
#[test]
fn path_match_strong_on_suffix_with_path_context() {
let tokens = vec!["live_index".to_string(), "search.rs".to_string()];
let ctx = ctx_with("live_index/search.rs", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/live_index/search.rs"), &ctx),
STRONG_PATH_SCORE
);
}
#[test]
fn path_match_strong_on_basename_plus_component_tokens() {
let tokens = vec!["protocol".to_string(), "tools.rs".to_string()];
let ctx = ctx_with("protocol/tools.rs", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/protocol/tools.rs"), &ctx),
STRONG_PATH_SCORE
);
assert_eq!(
PathMatchSignal.score(Path::new("src/sidecar/tools.rs"), &ctx),
BASENAME_SCORE
);
}
#[test]
fn path_match_basename_only_without_component_tokens() {
let tokens = vec!["tools.rs".to_string()];
let ctx = ctx_with("tools.rs", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/protocol/tools.rs"), &ctx),
BASENAME_SCORE
);
}
#[test]
fn path_match_prefix_on_basename_stem() {
let tokens = vec!["orchestrat".to_string()];
let ctx = ctx_with("orchestrat", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/orchestrator.rs"), &ctx),
PREFIX_SCORE
);
assert_eq!(
PathMatchSignal.score(Path::new("src/orchestration.rs"), &ctx),
PREFIX_SCORE
);
}
#[test]
fn path_match_prefix_requires_minimum_token_length() {
let tokens = vec!["or".to_string()];
let ctx = ctx_with("or", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/orchestrator.rs"), &ctx),
LOOSE_PATH_SCORE
);
}
#[test]
fn path_match_loose_when_all_tokens_contained() {
let tokens = vec!["protocol".to_string()];
let ctx = ctx_with("protocol", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/protocol/tools.rs"), &ctx),
LOOSE_PATH_SCORE
);
}
#[test]
fn path_match_zero_when_no_token_matches() {
let tokens = vec!["definitely_not_in_fixture".to_string()];
let ctx = ctx_with("definitely_not_in_fixture", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("src/protocol/tools.rs"), &ctx),
0.0
);
}
#[test]
#[allow(clippy::assertions_on_constants)] fn path_match_tier_ordering_preserved_by_score() {
assert!(STRONG_PATH_SCORE > BASENAME_SCORE);
assert!(BASENAME_SCORE > PREFIX_SCORE);
assert!(PREFIX_SCORE > LOOSE_PATH_SCORE);
assert!(LOOSE_PATH_SCORE > 0.0);
}
#[test]
fn path_match_case_insensitive() {
let tokens = vec!["tools.rs".to_string()];
let ctx = ctx_with("tools.rs", &tokens);
assert_eq!(
PathMatchSignal.score(Path::new("SRC/Protocol/Tools.RS"), &ctx),
BASENAME_SCORE
);
}
}