diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 482f1017..d993a36c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,6 +213,7 @@ jobs: - name: Run benchmarks run: | + git branch ${{ github.head_ref }} || true git fetch origin ${{ github.base_ref }} git checkout ${{ github.base_ref }} cargo bench --bench serialization --no-run @@ -261,6 +262,7 @@ jobs: - name: Fetch and check out base branch if: github.event_name == 'pull_request' run: | + git branch ${{ github.head_ref }} || true git fetch origin ${{ github.base_ref }} git checkout ${{ github.base_ref }} diff --git a/src/config.rs b/src/config.rs index 1287b813..a270131e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -86,6 +86,18 @@ pub struct YekConfig { #[config_arg(accept_from = "config_only")] pub git_boost_max: Option, + /// Enable dependency centrality ranking (fixes #255) + #[config_arg(accept_from = "config_only")] + pub centrality: Option, + + /// Weight for dependency centrality ranking (0.0..1.0, default 0.6) + #[config_arg(accept_from = "config_only")] + pub centrality_weight: Option, + + /// Weight for Git recency ranking (0.0..1.0, default 0.4) + #[config_arg(accept_from = "config_only")] + pub recency_weight: Option, + /// Category-based priority weights #[config_arg(accept_from = "config_only")] pub category_weights: Option, @@ -135,6 +147,9 @@ impl Default for YekConfig { .map(|s| s.to_string()) .collect(), git_boost_max: Some(100), + centrality: Some(true), + centrality_weight: Some(0.6), + recency_weight: Some(0.4), category_weights: None, // computed fields @@ -324,6 +339,10 @@ impl YekConfig { self.line_numbers |= config_bool(&settings, "line_numbers", "line-numbers"); self.tree_header |= config_bool(&settings, "tree_header", "tree-header"); self.tree_only |= config_bool(&settings, "tree_only", "tree-only"); + + if let Ok(val) = settings.get_bool("centrality") { + self.centrality = Some(val); + } } /// Compute a quick checksum for the input paths (files and directories). @@ -455,6 +474,18 @@ impl YekConfig { })?; } + // Validate centrality weights + if let Some(w) = self.centrality_weight { + if !(0.0..=1.0).contains(&w) { + return Err(anyhow!("centrality_weight: must be between 0.0 and 1.0")); + } + } + if let Some(w) = self.recency_weight { + if !(0.0..=1.0).contains(&w) { + return Err(anyhow!("recency_weight: must be between 0.0 and 1.0")); + } + } + // Validate tree options are mutually exclusive if self.tree_header && self.tree_only { return Err(anyhow!("tree_header and tree_only cannot both be enabled")); diff --git a/src/lib.rs b/src/lib.rs index 7ac58885..06e9fc5c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -116,6 +116,41 @@ pub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec) let mut files = merged_files; + // Apply hybrid priority boost (combining Git recency + Dependency Centrality, fixes #255) + let enable_centrality = config.centrality.unwrap_or(true); + let max_boost = config.git_boost_max.unwrap_or(100); + let r_weight = config.recency_weight.unwrap_or(0.4); + let c_weight = config.centrality_weight.unwrap_or(0.6); + + let file_inputs: Vec<(String, String)> = files + .iter() + .map(|f| (f.rel_path.clone(), f.content.clone())) + .collect(); + + let centrality_scores = if enable_centrality { + Some(priority::compute_dependency_centrality(&file_inputs)) + } else { + None + }; + + let hybrid_boosts = priority::compute_hybrid_priority_boost( + if combined_commit_times.is_empty() { + None + } else { + Some(&combined_commit_times) + }, + centrality_scores.as_ref(), + max_boost, + r_weight, + c_weight, + ); + + for file in &mut files { + if let Some(boost) = hybrid_boosts.get(&file.rel_path) { + file.priority += *boost; + } + } + // Sort final (priority asc, then file_index asc) files.par_sort_by(|a, b| { a.priority diff --git a/src/models.rs b/src/models.rs index 2079c6c5..3c2ff239 100644 --- a/src/models.rs +++ b/src/models.rs @@ -300,6 +300,12 @@ pub struct ProcessingConfig { pub memory_limit_mb: Option, /// Batch size for processing pub batch_size: usize, + /// Whether to enable dependency centrality ranking + pub centrality: Option, + /// Weight for dependency centrality ranking (0.0..1.0) + pub centrality_weight: Option, + /// Weight for Git recency ranking (0.0..1.0) + pub recency_weight: Option, } impl Default for ProcessingConfig { @@ -312,6 +318,9 @@ impl Default for ProcessingConfig { max_threads: None, memory_limit_mb: None, batch_size: 1000, + centrality: Some(true), + centrality_weight: Some(0.6), + recency_weight: Some(0.4), } } } diff --git a/src/parallel.rs b/src/parallel.rs index d3c84fcc..104bc63c 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -494,6 +494,9 @@ pub fn process_files_parallel( max_threads: None, memory_limit_mb: None, batch_size: 1000, + centrality: config.centrality, + centrality_weight: config.centrality_weight, + recency_weight: config.recency_weight, }, crate::models::RepositoryInfo::new(base_path.to_path_buf(), false), // TODO: Proper repo info Arc::new(crate::repository::RealFileSystem), diff --git a/src/pipeline.rs b/src/pipeline.rs index 1459d6b2..01c98f52 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -532,11 +532,14 @@ impl FileDiscoveryStage { } } - // Apply git boost if available - if let Some(commit_time) = repo_info.commit_times.get(rel_path) { - let max_boost = context.input_config.git_boost_max.unwrap_or(100); - let boost = self.calculate_git_boost(*commit_time, &repo_info.commit_times, max_boost); - priority += boost; + // Apply git boost if available and centrality is disabled (otherwise hybrid boost is applied at pipeline completion) + if !context.processing_config.centrality.unwrap_or(true) { + if let Some(commit_time) = repo_info.commit_times.get(rel_path) { + let max_boost = context.input_config.git_boost_max.unwrap_or(100); + let boost = + self.calculate_git_boost(*commit_time, &repo_info.commit_times, max_boost); + priority += boost; + } } priority @@ -760,6 +763,41 @@ impl ProcessingPipeline { files = stage.process(files, &self.context)?; } + // Apply hybrid boost (dependency centrality + Git recency, fixes #255) + let enable_centrality = self.context.processing_config.centrality.unwrap_or(true); + if enable_centrality { + let file_inputs: Vec<(String, String)> = files + .iter() + .map(|f| (f.rel_path.clone(), f.content.clone())) + .collect(); + let centralities = crate::priority::compute_dependency_centrality(&file_inputs); + let max_boost = self.context.input_config.git_boost_max.unwrap_or(100); + let c_weight = self + .context + .processing_config + .centrality_weight + .unwrap_or(0.6); + let r_weight = self.context.processing_config.recency_weight.unwrap_or(0.4); + + let commit_times = &self.context.repository_info.commit_times; + let hybrid_boosts = crate::priority::compute_hybrid_priority_boost( + if commit_times.is_empty() { + None + } else { + Some(commit_times) + }, + Some(¢ralities), + max_boost, + r_weight, + c_weight, + ); + for f in &mut files { + if let Some(boost) = hybrid_boosts.get(&f.rel_path) { + f.priority += *boost; + } + } + } + // Final sorting by priority and file_index files.sort_by(|a, b| { a.priority diff --git a/src/priority.rs b/src/priority.rs index 3a90904c..10771f62 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -175,3 +175,497 @@ pub fn get_recent_commit_times_git2( Some(commit_times) } + +// --------------------------------------------------------------------------- +// Dependency Centrality Analysis & Ranking (Issue #255) +// --------------------------------------------------------------------------- + +/// Normalizes path string by replacing backslashes with slashes and trimming leading `./`. +pub fn normalize_priority_path(p: &str) -> String { + p.replace('\\', "/").trim_start_matches("./").to_string() +} + +/// Extracts dependency / import / require / include specifiers from a file's content. +/// +/// Supports: +/// - JavaScript / TypeScript: `import ... from '...'`, `require('...')`, `export ... from '...'` +/// - Rust: `mod foo;`, `use foo::...;`, `use crate::foo::...;`, `use super::foo;` +/// - Python: `from foo import bar`, `from .foo import bar`, `import foo` +/// - C / C++: `#include "foo.h"` +/// - Go: `import "pkg/foo"`, `import "./foo"` +pub fn extract_import_specifiers(content: &str) -> Vec { + use std::sync::OnceLock; + static QUOTED_IMPORT_RE: OnceLock = OnceLock::new(); + static RUST_MOD_RE: OnceLock = OnceLock::new(); + static RUST_USE_RE: OnceLock = OnceLock::new(); + static PYTHON_IMPORT_RE: OnceLock = OnceLock::new(); + + let quoted_re = QUOTED_IMPORT_RE.get_or_init(|| { + regex::Regex::new( + r#"(?m)(?:import\s+(?:\{[^}]*\}|\*|\w+)?\s*(?:from\s+)?|require\s*\(\s*|export\s+(?:\{[^}]*\}|\*)\s+from\s+|#include\s*)["'<]([^"'>]+)[">']"# + ).expect("valid quoted import regex") + }); + + let rust_mod_re = RUST_MOD_RE.get_or_init(|| { + regex::Regex::new(r#"(?m)^\s*(?:pub(?:\([^)]+\))?\s+)?mod\s+([a-zA-Z0-9_]+)\s*;"#) + .expect("valid rust mod regex") + }); + + let rust_use_re = RUST_USE_RE.get_or_init(|| { + regex::Regex::new( + r#"(?m)^\s*(?:pub(?:\([^)]+\))?\s+)?use\s+(?:crate::|super::)?([a-zA-Z0-9_]+)"#, + ) + .expect("valid rust use regex") + }); + + let python_import_re = PYTHON_IMPORT_RE.get_or_init(|| { + regex::Regex::new( + r#"(?m)^\s*(?:from\s+([a-zA-Z0-9_.]+)\s+import|import\s+([a-zA-Z0-9_.]+))"#, + ) + .expect("valid python import regex") + }); + + let mut specifiers = Vec::new(); + + // 1. Quoted imports (JS, TS, C, C++, Go, CSS, etc.) + for cap in quoted_re.captures_iter(content) { + if let Some(spec) = cap.get(1) { + specifiers.push(spec.as_str().to_string()); + } + } + + // 2. Rust mod statements + for cap in rust_mod_re.captures_iter(content) { + if let Some(spec) = cap.get(1) { + specifiers.push(spec.as_str().to_string()); + } + } + + // 3. Rust use statements + for cap in rust_use_re.captures_iter(content) { + if let Some(spec) = cap.get(1) { + let spec_str = spec.as_str(); + if spec_str != "std" && spec_str != "core" && spec_str != "alloc" { + specifiers.push(spec_str.to_string()); + } + } + } + + // 4. Python imports + for cap in python_import_re.captures_iter(content) { + if let Some(spec) = cap.get(1).or_else(|| cap.get(2)) { + specifiers.push(spec.as_str().to_string()); + } + } + + specifiers +} + +/// Catalog of project files used to resolve import specifiers to project files. +pub struct ProjectFileCatalog { + exact_paths: HashMap, + no_ext_paths: HashMap>, + stems: HashMap>, + filenames: HashMap>, +} + +impl ProjectFileCatalog { + pub fn new(files: &[String]) -> Self { + let mut exact_paths = HashMap::new(); + let mut no_ext_paths: HashMap> = HashMap::new(); + let mut stems: HashMap> = HashMap::new(); + let mut filenames: HashMap> = HashMap::new(); + + for (idx, file_path) in files.iter().enumerate() { + let normalized = normalize_priority_path(file_path); + exact_paths.insert(normalized.clone(), idx); + + let path = Path::new(&normalized); + + if let Some(parent) = path.parent() { + let parent_str = parent.to_string_lossy().replace('\\', "/"); + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + let no_ext = if parent_str.is_empty() || parent_str == "." { + stem.to_string() + } else { + format!("{}/{}", parent_str, stem) + }; + no_ext_paths.entry(no_ext).or_default().push(idx); + } + } + + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + stems.entry(stem.to_string()).or_default().push(idx); + } + + if let Some(name) = path.file_name().and_then(|s| s.to_str()) { + filenames.entry(name.to_string()).or_default().push(idx); + } + } + + Self { + exact_paths, + no_ext_paths, + stems, + filenames, + } + } + + pub fn resolve(&self, from_file: &str, specifier: &str) -> Option { + let norm_from = normalize_priority_path(from_file); + let from_path = Path::new(&norm_from); + let parent_dir = from_path + .parent() + .map(|p| p.to_string_lossy().replace('\\', "/")) + .unwrap_or_default(); + + let clean_spec = specifier.trim().replace('\\', "/"); + if clean_spec.is_empty() { + return None; + } + + // 1. If relative path (e.g. "./models", "../models") + if clean_spec.starts_with("./") || clean_spec.starts_with("../") { + let resolved_relative = resolve_relative_path(&parent_dir, &clean_spec); + if let Some(target) = self.match_path_or_mod(&resolved_relative) { + return Some(target); + } + } + + // 2. Direct exact or clean path + let stripped = clean_spec + .trim_start_matches("@/") + .trim_start_matches("~/") + .trim_start_matches("./"); + + if let Some(target) = self.match_path_or_mod(stripped) { + return Some(target); + } + + // 3. Same directory resolution + if !parent_dir.is_empty() && parent_dir != "." { + let in_same_dir = format!("{}/{}", parent_dir, stripped); + if let Some(target) = self.match_path_or_mod(&in_same_dir) { + return Some(target); + } + } + + // 4. Dot-separated or double-colon module path + let slash_converted = stripped.replace("::", "/").replace('.', "/"); + if slash_converted != stripped { + if let Some(target) = self.match_path_or_mod(&slash_converted) { + return Some(target); + } + if !parent_dir.is_empty() && parent_dir != "." { + let in_same_dir = format!("{}/{}", parent_dir, slash_converted); + if let Some(target) = self.match_path_or_mod(&in_same_dir) { + return Some(target); + } + } + if let Some(first_seg) = slash_converted.split('/').next() { + if !first_seg.is_empty() + && first_seg != "crate" + && first_seg != "super" + && first_seg != "self" + { + if let Some(target) = self.match_path_or_mod(first_seg) { + return Some(target); + } + if !parent_dir.is_empty() && parent_dir != "." { + let in_same_dir = format!("{}/{}", parent_dir, first_seg); + if let Some(target) = self.match_path_or_mod(&in_same_dir) { + return Some(target); + } + } + } + } + } + + // 5. Direct filename match + if let Some(targets) = self.filenames.get(stripped) { + if targets.len() == 1 { + return Some(targets[0]); + } + for &idx in targets { + if self.is_in_dir(idx, &parent_dir) { + return Some(idx); + } + } + return targets.first().copied(); + } + + // 6. Direct unique stem match + let stem = Path::new(stripped) + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(stripped); + if let Some(targets) = self.stems.get(stem) { + if targets.len() == 1 { + return Some(targets[0]); + } + for &idx in targets { + if self.is_in_dir(idx, &parent_dir) { + return Some(idx); + } + } + } + + None + } + + fn match_path_or_mod(&self, path_str: &str) -> Option { + let p = path_str.trim_end_matches('/'); + if let Some(&idx) = self.exact_paths.get(p) { + return Some(idx); + } + if let Some(targets) = self.no_ext_paths.get(p) { + if let Some(&first) = targets.first() { + return Some(first); + } + } + for entry in &[ + "mod.rs", + "index.ts", + "index.js", + "index.tsx", + "index.jsx", + "__init__.py", + ] { + let entry_path = format!("{}/{}", p, entry); + if let Some(&idx) = self.exact_paths.get(&entry_path) { + return Some(idx); + } + } + None + } + + fn is_in_dir(&self, idx: usize, parent_dir: &str) -> bool { + if parent_dir.is_empty() || parent_dir == "." { + return true; + } + for (path, &i) in &self.exact_paths { + if i == idx && path.starts_with(parent_dir) { + return true; + } + } + false + } +} + +fn resolve_relative_path(base_dir: &str, relative: &str) -> String { + let mut parts = Vec::new(); + if !base_dir.is_empty() && base_dir != "." { + for seg in base_dir.split('/') { + if !seg.is_empty() && seg != "." { + parts.push(seg); + } + } + } + for seg in relative.split('/') { + if seg.is_empty() || seg == "." { + continue; + } else if seg == ".." { + parts.pop(); + } else { + parts.push(seg); + } + } + parts.join("/") +} + +/// Compute in-degree dependency centrality for each file in the project. +/// +/// Returns a map of relative file path -> in-degree count (how many other project files reference it). +pub fn compute_dependency_centrality(files: &[(String, String)]) -> HashMap { + if files.is_empty() { + return HashMap::new(); + } + + let file_paths: Vec = files + .iter() + .map(|(p, _)| normalize_priority_path(p)) + .collect(); + let catalog = ProjectFileCatalog::new(&file_paths); + + let mut in_degrees: Vec> = + vec![std::collections::HashSet::new(); files.len()]; + + for (from_idx, (from_path, content)) in files.iter().enumerate() { + let specifiers = extract_import_specifiers(content); + for spec in specifiers { + if let Some(target_idx) = catalog.resolve(from_path, &spec) { + // Do not count self-references + if target_idx != from_idx { + in_degrees[target_idx].insert(from_idx); + } + } + } + } + + let mut result = HashMap::new(); + for (idx, (orig_path, _)) in files.iter().enumerate() { + result.insert(orig_path.clone(), in_degrees[idx].len()); + } + + result +} + +/// Compute centrality boost scaled to max_boost (0..=max_boost). +/// Higher in-degree = higher boost. +pub fn compute_centrality_boost( + centrality_scores: &HashMap, + max_boost: i32, +) -> HashMap { + if centrality_scores.is_empty() { + return HashMap::new(); + } + + let max_degree = centrality_scores.values().copied().max().unwrap_or(0); + let mut result = HashMap::new(); + + if max_degree == 0 { + for path in centrality_scores.keys() { + result.insert(path.clone(), 0); + } + return result; + } + + for (path, °) in centrality_scores { + let rank = deg as f64 / max_degree as f64; + let boost = (rank * max_boost as f64).round() as i32; + result.insert(path.clone(), boost); + } + + result +} + +/// Combine recency score and dependency centrality score using a normalized hybrid formula: +/// `score = (recency_weight * recency_score) + (centrality_weight * centrality_score)`. +/// +/// If `commit_times` is empty/None, centrality takes 100% of the boost. +/// If `centrality_scores` is empty/None, recency takes 100% of the boost. +/// If both are available, weights are normalized: +/// `combined_rank = (recency_weight * r_rank + centrality_weight * c_rank) / (recency_weight + centrality_weight)`. +/// The combined rank (0.0..=1.0) is scaled by `max_boost`. +pub fn compute_hybrid_priority_boost( + commit_times: Option<&HashMap>, + centrality_scores: Option<&HashMap>, + max_boost: i32, + recency_weight: f64, + centrality_weight: f64, +) -> HashMap { + let has_recency = commit_times.map(|m| !m.is_empty()).unwrap_or(false); + let has_centrality = centrality_scores.map(|m| !m.is_empty()).unwrap_or(false); + + if !has_recency && !has_centrality { + return HashMap::new(); + } + + // 1. Calculate normalized recency ranks (0.0..=1.0) + let recency_ranks: HashMap = if let Some(times) = commit_times { + if times.len() <= 1 { + times.keys().map(|k| (k.clone(), 0.0)).collect() + } else { + let min_time = *times.values().min().unwrap(); + let max_time = *times.values().max().unwrap(); + let range = (max_time.saturating_sub(min_time)) as f64; + if range == 0.0 { + times.keys().map(|k| (k.clone(), 0.0)).collect() + } else { + times + .iter() + .map(|(k, &t)| { + let rank = (t.saturating_sub(min_time)) as f64 / range; + (k.clone(), rank) + }) + .collect() + } + } + } else { + HashMap::new() + }; + + // 2. Calculate normalized centrality ranks (0.0..=1.0) + let centrality_ranks: HashMap = if let Some(centralities) = centrality_scores { + let max_degree = centralities.values().copied().max().unwrap_or(0); + if max_degree == 0 { + centralities.keys().map(|k| (k.clone(), 0.0)).collect() + } else { + centralities + .iter() + .map(|(k, °)| { + let rank = deg as f64 / max_degree as f64; + (k.clone(), rank) + }) + .collect() + } + } else { + HashMap::new() + }; + + // 3. Collect all paths from both maps + let mut all_paths: std::collections::HashSet = std::collections::HashSet::new(); + if let Some(times) = commit_times { + all_paths.extend(times.keys().cloned()); + } + if let Some(centralities) = centrality_scores { + all_paths.extend(centralities.keys().cloned()); + } + + // 4. Combine ranks using normalized weights + let rw = recency_weight.max(0.0); + let cw = centrality_weight.max(0.0); + let total_weight = rw + cw; + + if total_weight == 0.0 { + let mut result = HashMap::new(); + for path in all_paths { + result.insert(path, 0); + } + return result; + } + + // Pure recency fallback when centrality is not available across the project + if has_recency && !has_centrality { + let mut result = HashMap::new(); + for path in all_paths { + let r = recency_ranks.get(&path).copied().unwrap_or(0.0); + let boost = if rw > 0.0 { + (r * max_boost as f64).round() as i32 + } else { + 0 + }; + result.insert(path, boost); + } + return result; + } + + // Pure centrality fallback when git recency is not available across the project + if !has_recency && has_centrality { + let mut result = HashMap::new(); + for path in all_paths { + let c = centrality_ranks.get(&path).copied().unwrap_or(0.0); + let boost = if cw > 0.0 { + (c * max_boost as f64).round() as i32 + } else { + 0 + }; + result.insert(path, boost); + } + return result; + } + + // Both signals are present: combine with normalized weights. + // If a file is absent from one signal, its rank for that signal defaults to 0.0. + let mut result = HashMap::new(); + for path in all_paths { + let r = recency_ranks.get(&path).copied().unwrap_or(0.0); + let c = centrality_ranks.get(&path).copied().unwrap_or(0.0); + + let combined_rank = (rw * r + cw * c) / total_weight; + let boost = (combined_rank * max_boost as f64).round() as i32; + result.insert(path, boost); + } + + result +} diff --git a/tests/lib_test.rs b/tests/lib_test.rs index 87bb2814..8a02465d 100644 --- a/tests/lib_test.rs +++ b/tests/lib_test.rs @@ -512,6 +512,120 @@ mod lib_tests { assert_eq!(files[1].priority, 520); } + #[test] + fn test_dependency_centrality_ranks_hub_above_peripheral_file() { + init_tracing(); + let temp_dir = tempdir().unwrap(); + let repo_path = temp_dir.path(); + + // 1. Initialize git repository + std::process::Command::new("git") + .args(["init"]) + .current_dir(repo_path) + .output() + .unwrap(); + + std::process::Command::new("git") + .args(["config", "user.name", "Test User"]) + .current_dir(repo_path) + .output() + .unwrap(); + std::process::Command::new("git") + .args(["config", "user.email", "test@example.com"]) + .current_dir(repo_path) + .output() + .unwrap(); + + // 2. Commit foundational architectural hub file FIRST (oldest commit) + std::fs::create_dir_all(repo_path.join("src")).unwrap(); + let lib_path = repo_path.join("src/lib.rs"); + std::fs::write(&lib_path, "pub struct CoreArchitecture;\npub fn init() {}").unwrap(); + + std::process::Command::new("git") + .args(["add", "src/lib.rs"]) + .current_dir(repo_path) + .output() + .unwrap(); + std::process::Command::new("git") + .args(["commit", "-m", "Initial architectural commit (oldest)"]) + .current_dir(repo_path) + .output() + .unwrap(); + + // 3. Create 10 files that import src/lib.rs + for i in 1..=10 { + let worker_file = format!("src/worker_{}.rs", i); + let worker_path = repo_path.join(&worker_file); + std::fs::write( + &worker_path, + format!("use crate::lib::CoreArchitecture;\npub fn run_{}() {{}}", i), + ) + .unwrap(); + + std::process::Command::new("git") + .args(["add", &worker_file]) + .current_dir(repo_path) + .output() + .unwrap(); + std::process::Command::new("git") + .args(["commit", "-m", &format!("Add worker {}", i)]) + .current_dir(repo_path) + .output() + .unwrap(); + } + + // 4. Create peripheral leaf file with ZERO imports, committed LAST (newest commit) + let peripheral_path = repo_path.join("src/peripheral_leaf.rs"); + std::fs::write( + &peripheral_path, + "// Peripheral leaf file with no dependencies\npub fn unused_helper() {}", + ) + .unwrap(); + + std::process::Command::new("git") + .args(["add", "src/peripheral_leaf.rs"]) + .current_dir(repo_path) + .output() + .unwrap(); + std::process::Command::new("git") + .args(["commit", "-m", "Peripheral recent edit (newest)"]) + .current_dir(repo_path) + .output() + .unwrap(); + + // 5. Serialize repository with Dependency Centrality enabled + let mut config = create_test_config(vec![repo_path.to_string_lossy().to_string()]); + config.priority_rules = Vec::new(); // Zero manual priority rules to isolate algorithmic ranking + config.centrality = Some(true); + config.centrality_weight = Some(0.6); + config.recency_weight = Some(0.4); + config.git_boost_max = Some(100); + + let (_output, files) = serialize_repo(&config).unwrap(); + + let lib_file = files + .iter() + .find(|f| f.rel_path.ends_with("lib.rs")) + .expect("lib.rs must be present"); + let peripheral_file = files + .iter() + .find(|f| f.rel_path.ends_with("peripheral_leaf.rs")) + .expect("peripheral_leaf.rs must be present"); + + println!( + "lib.rs priority: {}, peripheral_leaf.rs priority: {}", + lib_file.priority, peripheral_file.priority + ); + + // Foundational hub file MUST rank higher than peripheral leaf + assert!( + lib_file.priority > peripheral_file.priority, + "Foundational hub lib.rs (priority {}) must rank strictly above peripheral leaf (priority {})", + lib_file.priority, + peripheral_file.priority + ); + } + #[test] fn test_serialize_repo_with_ignore_patterns_config() { init_tracing(); diff --git a/tests/priority_test.rs b/tests/priority_test.rs index 175f48e8..3d412189 100644 --- a/tests/priority_test.rs +++ b/tests/priority_test.rs @@ -729,3 +729,329 @@ fn test_get_recent_commit_times_git_with_submodules() { // Should handle repos with submodules configuration assert!(times.is_none() || times.unwrap().is_empty()); } + +// --------------------------------------------------------------------------- +// Tests for Dependency Centrality Ranking (Issue #255) +// --------------------------------------------------------------------------- + +#[test] +fn test_extract_import_specifiers() { + use yek::priority::extract_import_specifiers; + + let rust_content = r#" + pub mod models; + mod priority; + use crate::config::YekConfig; + use super::category::CategoryWeights; + use std::collections::HashMap; + "#; + let specs = extract_import_specifiers(rust_content); + assert!(specs.contains(&"models".to_string())); + assert!(specs.contains(&"priority".to_string())); + assert!(specs.contains(&"config".to_string())); + assert!(specs.contains(&"category".to_string())); + // std should be filtered out + assert!(!specs.contains(&"std".to_string())); + + let ts_content = r#" + import { User } from './models'; + import { db } from "../db/client"; + const auth = require('@/auth/middleware'); + export { helper } from './utils'; + export * from './constants'; + "#; + let ts_specs = extract_import_specifiers(ts_content); + assert!(ts_specs.contains(&"./models".to_string())); + assert!(ts_specs.contains(&"../db/client".to_string())); + assert!(ts_specs.contains(&"@/auth/middleware".to_string())); + assert!(ts_specs.contains(&"./utils".to_string())); + assert!(ts_specs.contains(&"./constants".to_string())); + + let py_content = r#" + from .models import User + from app.services import payment + import helpers + "#; + let py_specs = extract_import_specifiers(py_content); + assert!(py_specs.contains(&".models".to_string())); + assert!(py_specs.contains(&"app.services".to_string())); + assert!(py_specs.contains(&"helpers".to_string())); + + let c_content = r#" + #include "models.h" + #include + "#; + let c_specs = extract_import_specifiers(c_content); + assert!(c_specs.contains(&"models.h".to_string())); +} + +#[test] +fn test_compute_dependency_centrality_basic() { + use yek::priority::compute_dependency_centrality; + + let files = vec![ + ( + "src/lib.rs".to_string(), + "pub mod models;\npub mod priority;".to_string(), + ), + ("src/models.rs".to_string(), "pub struct Model;".to_string()), + ( + "src/priority.rs".to_string(), + "use crate::models;\npub fn score() {}".to_string(), + ), + ( + "src/pipeline.rs".to_string(), + "use crate::models;\nuse crate::priority;".to_string(), + ), + ]; + + let scores = compute_dependency_centrality(&files); + + // models is imported by lib.rs, priority.rs, and pipeline.rs => in-degree = 3 + assert_eq!(scores.get("src/models.rs"), Some(&3)); + // priority is imported by lib.rs and pipeline.rs => in-degree = 2 + assert_eq!(scores.get("src/priority.rs"), Some(&2)); + // lib.rs is imported by 0 files => in-degree = 0 + assert_eq!(scores.get("src/lib.rs"), Some(&0)); + // pipeline.rs is imported by 0 files => in-degree = 0 + assert_eq!(scores.get("src/pipeline.rs"), Some(&0)); +} + +#[test] +fn test_compute_dependency_centrality_circular_imports() { + use yek::priority::compute_dependency_centrality; + + // File A imports B, File B imports A + let files = vec![ + ( + "src/a.ts".to_string(), + "import { b } from './b';".to_string(), + ), + ( + "src/b.ts".to_string(), + "import { a } from './a';".to_string(), + ), + ]; + + let scores = compute_dependency_centrality(&files); + assert_eq!(scores.get("src/a.ts"), Some(&1)); + assert_eq!(scores.get("src/b.ts"), Some(&1)); +} + +#[test] +fn test_compute_dependency_centrality_self_and_duplicate_imports() { + use yek::priority::compute_dependency_centrality; + + // A file importing itself or importing another file multiple times + let files = vec![ + ( + "src/models.ts".to_string(), + "export interface User {};".to_string(), + ), + ( + "src/service.ts".to_string(), + "import { User } from './models';\nimport { Account } from './models';\nimport { self } from './service';".to_string(), + ), + ]; + + let scores = compute_dependency_centrality(&files); + // models imported twice in same file => in-degree = 1 (unique referencing files) + assert_eq!(scores.get("src/models.ts"), Some(&1)); + // service imports itself => in-degree = 0 (self-references ignored) + assert_eq!(scores.get("src/service.ts"), Some(&0)); +} + +#[test] +fn test_compute_dependency_centrality_non_code_and_isolated_files() { + use yek::priority::compute_dependency_centrality; + + let files = vec![ + ("README.md".to_string(), "# Project docs".to_string()), + ("config.json".to_string(), r#"{"key": "val"}"#.to_string()), + ( + "src/isolated.rs".to_string(), + "// isolated file with no imports".to_string(), + ), + ]; + + let scores = compute_dependency_centrality(&files); + assert_eq!(scores.get("README.md"), Some(&0)); + assert_eq!(scores.get("config.json"), Some(&0)); + assert_eq!(scores.get("src/isolated.rs"), Some(&0)); +} + +#[test] +fn test_compute_centrality_boost() { + use yek::priority::compute_centrality_boost; + + let mut scores = std::collections::HashMap::new(); + scores.insert("src/hub.rs".to_string(), 10); + scores.insert("src/mid.rs".to_string(), 5); + scores.insert("src/leaf.rs".to_string(), 0); + + let boosts = compute_centrality_boost(&scores, 100); + assert_eq!(boosts.get("src/hub.rs"), Some(&100)); + assert_eq!(boosts.get("src/mid.rs"), Some(&50)); + assert_eq!(boosts.get("src/leaf.rs"), Some(&0)); +} + +#[test] +fn test_compute_centrality_boost_all_zero() { + use yek::priority::compute_centrality_boost; + + let mut scores = std::collections::HashMap::new(); + scores.insert("a.rs".to_string(), 0); + scores.insert("b.rs".to_string(), 0); + + let boosts = compute_centrality_boost(&scores, 100); + assert_eq!(boosts.get("a.rs"), Some(&0)); + assert_eq!(boosts.get("b.rs"), Some(&0)); +} + +/// Issue #255 Core Verification: +/// Test a synthetic project where a foundational `lib.rs` has zero recent commits (oldest timestamp) +/// but is imported by 10 other files, verifying it ranks ABOVE a peripheral file with a recent commit. +#[test] +fn test_hybrid_priority_foundational_hub_beats_recent_peripheral_file() { + use yek::priority::compute_hybrid_priority_boost; + + let mut commit_times = std::collections::HashMap::new(); + let oldest_time = 1_000_000; + let newest_time = 2_000_000; + + // Foundational lib.rs: oldest commit (zero recent commits) + commit_times.insert("src/lib.rs".to_string(), oldest_time); + + // Peripheral file: newest commit + commit_times.insert("src/peripheral_leaf.rs".to_string(), newest_time); + + // 10 other files with intermediate timestamps + for i in 1..=10 { + commit_times.insert(format!("src/worker_{}.rs", i), oldest_time + (i * 50_000)); + } + + // Centrality: lib.rs is imported by 10 files + let mut centrality_scores = std::collections::HashMap::new(); + centrality_scores.insert("src/lib.rs".to_string(), 10); + centrality_scores.insert("src/peripheral_leaf.rs".to_string(), 0); + for i in 1..=10 { + centrality_scores.insert(format!("src/worker_{}.rs", i), 1); + } + + // Default weights: centrality_weight = 0.6, recency_weight = 0.4, max_boost = 100 + let max_boost = 100; + let hybrid_boosts = compute_hybrid_priority_boost( + Some(&commit_times), + Some(¢rality_scores), + max_boost, + 0.4, // recency_weight + 0.6, // centrality_weight + ); + + let lib_boost = *hybrid_boosts.get("src/lib.rs").expect("lib.rs boost"); + let leaf_boost = *hybrid_boosts + .get("src/peripheral_leaf.rs") + .expect("leaf boost"); + + // lib.rs: recency_rank = 0.0, centrality_rank = 1.0 => (0.4*0 + 0.6*1.0) = 0.60 => 60 + // peripheral: recency_rank = 1.0, centrality_rank = 0.0 => (0.4*1.0 + 0.6*0) = 0.40 => 40 + assert!( + lib_boost > leaf_boost, + "Foundational hub lib.rs ({}) must rank strictly above peripheral leaf ({})", + lib_boost, + leaf_boost + ); + assert_eq!(lib_boost, 60); + assert_eq!(leaf_boost, 40); +} + +#[test] +fn test_hybrid_priority_pure_centrality_fallback_when_no_git() { + use yek::priority::compute_hybrid_priority_boost; + + let mut centrality_scores = std::collections::HashMap::new(); + centrality_scores.insert("src/core.rs".to_string(), 8); + centrality_scores.insert("src/leaf.rs".to_string(), 2); + + // Git commit times unavailable (None) + let hybrid_boosts = + compute_hybrid_priority_boost(None, Some(¢rality_scores), 100, 0.4, 0.6); + + // Core should scale to 100%, leaf to 25% + assert_eq!(hybrid_boosts.get("src/core.rs"), Some(&100)); + assert_eq!(hybrid_boosts.get("src/leaf.rs"), Some(&25)); +} + +#[test] +fn test_hybrid_priority_pure_recency_fallback_when_centrality_empty() { + use yek::priority::compute_hybrid_priority_boost; + + let mut commit_times = std::collections::HashMap::new(); + commit_times.insert("old.rs".to_string(), 1000); + commit_times.insert("new.rs".to_string(), 2000); + + let hybrid_boosts = compute_hybrid_priority_boost(Some(&commit_times), None, 100, 0.4, 0.6); + + assert_eq!(hybrid_boosts.get("old.rs"), Some(&0)); + assert_eq!(hybrid_boosts.get("new.rs"), Some(&100)); +} + +#[test] +fn test_hybrid_priority_when_centrality_disabled_by_weight_zero() { + use yek::priority::compute_hybrid_priority_boost; + + let mut commit_times = std::collections::HashMap::new(); + commit_times.insert("old.rs".to_string(), 1000); + commit_times.insert("new.rs".to_string(), 2000); + + let mut centrality_scores = std::collections::HashMap::new(); + centrality_scores.insert("old.rs".to_string(), 10); + centrality_scores.insert("new.rs".to_string(), 0); + centrality_scores.insert("no_git.rs".to_string(), 20); + + // Centrality disabled: centrality_weight = 0.0, recency_weight = 0.4 + let hybrid_boosts = + compute_hybrid_priority_boost(Some(&commit_times), Some(¢rality_scores), 100, 0.4, 0.0); + + // Because centrality is disabled, rankings depend 100% on recency + assert_eq!(hybrid_boosts.get("old.rs"), Some(&0)); + assert_eq!(hybrid_boosts.get("new.rs"), Some(&100)); + // File without git history gets 0 boost when centrality is disabled + assert_eq!(hybrid_boosts.get("no_git.rs"), Some(&0)); +} + +#[test] +fn test_hybrid_priority_when_recency_disabled_by_weight_zero() { + use yek::priority::compute_hybrid_priority_boost; + + let mut commit_times = std::collections::HashMap::new(); + commit_times.insert("hub.rs".to_string(), 1000); + commit_times.insert("leaf.rs".to_string(), 2000); + + let mut centrality_scores = std::collections::HashMap::new(); + centrality_scores.insert("hub.rs".to_string(), 10); + centrality_scores.insert("leaf.rs".to_string(), 0); + + // Recency disabled: recency_weight = 0.0, centrality_weight = 0.6 + let hybrid_boosts = + compute_hybrid_priority_boost(Some(&commit_times), Some(¢rality_scores), 100, 0.0, 0.6); + + // Because recency is disabled, hub gets 100 and leaf gets 0 + assert_eq!(hybrid_boosts.get("hub.rs"), Some(&100)); + assert_eq!(hybrid_boosts.get("leaf.rs"), Some(&0)); +} + +#[test] +fn test_hybrid_priority_when_both_weights_zero() { + use yek::priority::compute_hybrid_priority_boost; + + let mut commit_times = std::collections::HashMap::new(); + commit_times.insert("a.rs".to_string(), 1000); + let mut centrality_scores = std::collections::HashMap::new(); + centrality_scores.insert("a.rs".to_string(), 10); + + let hybrid_boosts = + compute_hybrid_priority_boost(Some(&commit_times), Some(¢rality_scores), 100, 0.0, 0.0); + + assert_eq!(hybrid_boosts.get("a.rs"), Some(&0)); +}