use crate::delta::Delta;
use crate::risk::RiskBand;
use crate::snapshot::{FunctionSnapshot, Snapshot};
use crate::views::agent::{to_agent_view, AgentFunctionView};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FileAggregates {
pub file: String,
pub sum_lrs: f64,
pub max_lrs: f64,
pub high_plus_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct DirectoryAggregates {
pub directory: String,
pub sum_lrs: f64,
pub max_lrs: f64,
pub high_plus_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FileRiskView {
pub file: String,
pub function_count: usize,
pub loc: usize,
pub max_cc: usize,
pub avg_cc: f64,
pub critical_count: usize,
pub file_risk_score: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct SnapshotAggregates {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub files: Vec<FileAggregates>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub directories: Vec<DirectoryAggregates>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub file_risk: Vec<FileRiskView>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub co_change: Vec<crate::git::CoChangePair>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FileDeltaAggregates {
pub file: String,
pub net_lrs_delta: f64,
pub regression_count: usize,
pub improvement_count: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub file_risk_score: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub file_risk_diff_percentile: Option<f64>,
pub file_risk_top_decile: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PrRiskSummary {
pub fn_changed_lines: usize,
pub band: RiskBand,
pub new_count: usize,
pub modified_count: usize,
pub deleted_count: usize,
pub regression_count: usize,
pub improvement_count: usize,
pub band_upgrades: usize,
pub policy_blocking: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct CoChangeDeltaEntry {
pub file_a: String,
pub file_b: String,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub prev_risk: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub curr_risk: Option<String>,
pub co_change_count: usize,
pub coupling_ratio: f64,
pub has_static_dep: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct DeltaAggregates {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub files: Vec<FileDeltaAggregates>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub co_change_delta: Vec<CoChangeDeltaEntry>,
pub pr_summary: PrRiskSummary,
}
const TRIAGE_TOP_N: usize = 5;
const HIDDEN_COUPLING_TOP_N: usize = 20;
const FILE_RISK_TOP_N: usize = 10;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct TriageTier {
pub count: usize,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub top: Vec<AgentFunctionView>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct TriageView {
pub active: TriageTier,
pub quiet: TriageTier,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct AgentCoChangeView {
pub hidden_coupling: Vec<crate::git::CoChangePair>,
pub hidden_count: usize,
pub total_pairs: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct AgentArchitectureView {
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub file_risk: Vec<FileRiskView>,
}
pub fn compute_agent_sections(
snapshot: &crate::snapshot::Snapshot,
aggregates: &SnapshotAggregates,
repo_root: &std::path::Path,
) -> (TriageView, Option<AgentArchitectureView>, AgentCoChangeView) {
let (mut active_fns, mut quiet_fns): (Vec<&FunctionSnapshot>, Vec<&FunctionSnapshot>) =
snapshot
.functions
.iter()
.partition(|f| f.tier.as_deref() == Some("active"));
let sort_by_risk = |fns: &mut Vec<&FunctionSnapshot>| {
fns.sort_by(|a, b| {
let a_score = a.activity_risk.unwrap_or(a.lrs);
let b_score = b.activity_risk.unwrap_or(b.lrs);
b_score
.partial_cmp(&a_score)
.unwrap_or(std::cmp::Ordering::Equal)
});
};
sort_by_risk(&mut active_fns);
sort_by_risk(&mut quiet_fns);
let triage = TriageView {
active: TriageTier {
count: active_fns.len(),
top: to_agent_view(&active_fns, repo_root, TRIAGE_TOP_N),
},
quiet: TriageTier {
count: quiet_fns.len(),
top: to_agent_view(&quiet_fns, repo_root, TRIAGE_TOP_N),
},
};
const SRC_EXTS: &[&str] = &[
".rs", ".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".c", ".cpp", ".h",
];
let is_src = |f: &str| SRC_EXTS.iter().any(|ext| f.ends_with(ext));
let total_pairs = aggregates.co_change.len();
let mut hidden_pairs: Vec<&crate::git::CoChangePair> = aggregates
.co_change
.iter()
.filter(|p| {
!p.has_static_dep
&& is_src(&p.file_a)
&& is_src(&p.file_b)
&& (p.risk == "high" || p.risk == "moderate")
})
.collect();
let hidden_count = hidden_pairs.len();
hidden_pairs.sort_by(|a, b| {
b.coupling_ratio
.partial_cmp(&a.coupling_ratio)
.unwrap_or(std::cmp::Ordering::Equal)
});
let hidden_coupling: Vec<crate::git::CoChangePair> = hidden_pairs
.into_iter()
.take(HIDDEN_COUPLING_TOP_N)
.cloned()
.collect();
let file_risk: Vec<FileRiskView> = aggregates
.file_risk
.iter()
.take(FILE_RISK_TOP_N)
.map(|fr| {
let rel_file = normalize_path_relative_to_repo(&fr.file, repo_root)
.unwrap_or_else(|| fr.file.clone());
FileRiskView {
file: rel_file,
..fr.clone()
}
})
.collect();
let architecture = if file_risk.is_empty() {
None
} else {
Some(AgentArchitectureView { file_risk })
};
(
triage,
architecture,
AgentCoChangeView {
hidden_coupling,
hidden_count,
total_pairs,
},
)
}
fn is_high_plus(band: RiskBand) -> bool {
matches!(band, RiskBand::High | RiskBand::Critical)
}
fn extract_directory(file_path: &str) -> String {
if let Some(last_slash) = file_path.rfind('/') {
file_path[..last_slash].to_string()
} else {
".".to_string()
}
}
pub(crate) fn normalize_path_relative_to_repo(
file_path: &str,
repo_root: &std::path::Path,
) -> Option<String> {
let file_path_buf = std::path::PathBuf::from(file_path);
if let Ok(relative) = file_path_buf.strip_prefix(repo_root) {
Some(relative.to_string_lossy().replace('\\', "/"))
} else {
if !file_path_buf.is_absolute() {
Some(file_path.to_string())
} else {
None
}
}
}
pub fn compute_file_aggregates(functions: &[FunctionSnapshot]) -> Vec<FileAggregates> {
let mut file_data: HashMap<String, (f64, f64, usize)> = HashMap::new();
for func in functions {
let entry = file_data.entry(func.file.clone()).or_insert((0.0, 0.0, 0));
entry.0 += func.lrs;
if func.lrs > entry.1 {
entry.1 = func.lrs;
}
if is_high_plus(func.band) {
entry.2 += 1;
}
}
let mut aggregates: Vec<FileAggregates> = file_data
.into_iter()
.map(
|(file, (sum_lrs, max_lrs, high_plus_count))| FileAggregates {
file,
sum_lrs,
max_lrs,
high_plus_count,
},
)
.collect();
aggregates.sort_by(|a, b| a.file.cmp(&b.file));
aggregates
}
pub fn compute_directory_aggregates(
file_aggregates: &[FileAggregates],
repo_root: &std::path::Path,
) -> Vec<DirectoryAggregates> {
let mut dir_data: HashMap<String, (f64, f64, usize)> = HashMap::new();
for file_agg in file_aggregates {
let normalized_file = match normalize_path_relative_to_repo(&file_agg.file, repo_root) {
Some(path) => path,
None => continue, };
let mut current_path = normalized_file.clone();
loop {
let dir = extract_directory(¤t_path);
if dir == current_path || dir.is_empty() {
break;
}
if dir.starts_with('/') && !dir.starts_with("./") {
break;
}
let entry = dir_data.entry(dir.clone()).or_insert((0.0, 0.0, 0));
entry.0 += file_agg.sum_lrs;
if file_agg.max_lrs > entry.1 {
entry.1 = file_agg.max_lrs;
}
entry.2 += file_agg.high_plus_count;
current_path = dir;
}
}
let mut aggregates: Vec<DirectoryAggregates> = dir_data
.into_iter()
.map(
|(directory, (sum_lrs, max_lrs, high_plus_count))| DirectoryAggregates {
directory,
sum_lrs,
max_lrs,
high_plus_count,
},
)
.collect();
aggregates.sort_by(|a, b| a.directory.cmp(&b.directory));
aggregates
}
pub fn compute_file_risk_views(functions: &[FunctionSnapshot]) -> Vec<FileRiskView> {
let mut file_data: HashMap<String, (usize, usize, usize, usize, usize)> = HashMap::new();
for func in functions {
let e = file_data
.entry(func.file.clone())
.or_insert((0, 0, 0, 0, 0));
e.0 += func.metrics.cc as usize;
e.1 = e.1.max(func.metrics.cc as usize);
e.2 += 1;
if func.band == RiskBand::Critical {
e.3 += 1;
}
e.4 += func.metrics.loc as usize;
}
let mut views: Vec<FileRiskView> = file_data
.into_iter()
.map(
|(file, (sum_cc, max_cc, function_count, critical_count, loc))| {
let avg_cc = if function_count > 0 {
sum_cc as f64 / function_count as f64
} else {
0.0
};
let score =
max_cc as f64 * 0.4 + avg_cc * 0.3 + (function_count as f64 + 1.0).log2() * 0.2;
FileRiskView {
file,
function_count,
loc,
max_cc,
avg_cc: (avg_cc * 100.0).round() / 100.0,
critical_count,
file_risk_score: (score * 100.0).round() / 100.0,
}
},
)
.collect();
views.sort_by(|a, b| {
b.file_risk_score
.partial_cmp(&a.file_risk_score)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.file.cmp(&b.file))
});
views
}
pub fn annotate_static_deps(
pairs: &mut [crate::git::CoChangePair],
edges: &[(String, String)],
repo_root: &std::path::Path,
) {
let mut edge_set: std::collections::HashSet<(String, String)> =
std::collections::HashSet::new();
for (a, b) in edges {
let a_rel = normalize_path_relative_to_repo(a, repo_root).unwrap_or_else(|| a.clone());
let b_rel = normalize_path_relative_to_repo(b, repo_root).unwrap_or_else(|| b.clone());
edge_set.insert((a_rel.clone(), b_rel.clone()));
edge_set.insert((b_rel, a_rel));
}
for pair in pairs.iter_mut() {
let has_dep = edge_set.contains(&(pair.file_a.clone(), pair.file_b.clone()));
pair.has_static_dep = has_dep;
if has_dep {
pair.risk = "expected".to_string();
}
}
}
pub fn compute_snapshot_aggregates(
snapshot: &Snapshot,
repo_root: &std::path::Path,
co_change_window_days: u64,
co_change_min_count: usize,
) -> SnapshotAggregates {
let files = compute_file_aggregates(&snapshot.functions);
let directories = compute_directory_aggregates(&files, repo_root);
let file_risk = compute_file_risk_views(&snapshot.functions);
let mut unique_files: Vec<String> = snapshot
.functions
.iter()
.map(|f| f.file.clone())
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();
unique_files.sort();
let files_as_str: Vec<&str> = unique_files.iter().map(|s| s.as_str()).collect();
let mut all_edges = crate::imports::resolve_file_deps(&files_as_str, repo_root);
all_edges.extend(crate::imports::resolve_cargo_workspace_edges(
repo_root,
&files_as_str,
));
let mut co_change =
crate::git::extract_co_change_pairs(repo_root, co_change_window_days, co_change_min_count)
.unwrap_or_default();
annotate_static_deps(&mut co_change, &all_edges, repo_root);
SnapshotAggregates {
files,
directories,
file_risk,
co_change,
}
}
fn risk_rank(risk: &str) -> u8 {
match risk {
"critical" => 4,
"high" => 3,
"moderate" => 2,
"low" => 1,
_ => 0,
}
}
pub fn diff_co_change_pairs(
prev: &[crate::git::CoChangePair],
curr: &[crate::git::CoChangePair],
) -> Vec<CoChangeDeltaEntry> {
let normalize = |a: &str, b: &str| -> (String, String) {
if a <= b {
(a.to_string(), b.to_string())
} else {
(b.to_string(), a.to_string())
}
};
let prev_map: HashMap<(String, String), &crate::git::CoChangePair> = prev
.iter()
.map(|p| (normalize(&p.file_a, &p.file_b), p))
.collect();
let curr_map: HashMap<(String, String), &crate::git::CoChangePair> = curr
.iter()
.map(|p| (normalize(&p.file_a, &p.file_b), p))
.collect();
let mut result: Vec<CoChangeDeltaEntry> = Vec::new();
for pair in curr {
let key = normalize(&pair.file_a, &pair.file_b);
let status = if let Some(prev_pair) = prev_map.get(&key) {
let pr = risk_rank(&prev_pair.risk);
let cr = risk_rank(&pair.risk);
if cr > pr {
"risk_increased"
} else if cr < pr {
"risk_decreased"
} else {
continue; }
} else {
"new"
};
let prev_risk = prev_map.get(&key).map(|p| p.risk.clone());
result.push(CoChangeDeltaEntry {
file_a: pair.file_a.clone(),
file_b: pair.file_b.clone(),
status: status.to_string(),
prev_risk,
curr_risk: Some(pair.risk.clone()),
co_change_count: pair.co_change_count,
coupling_ratio: pair.coupling_ratio,
has_static_dep: pair.has_static_dep,
});
}
for pair in prev {
let key = normalize(&pair.file_a, &pair.file_b);
if !curr_map.contains_key(&key) {
result.push(CoChangeDeltaEntry {
file_a: pair.file_a.clone(),
file_b: pair.file_b.clone(),
status: "dropped".to_string(),
prev_risk: Some(pair.risk.clone()),
curr_risk: None,
co_change_count: pair.co_change_count,
coupling_ratio: pair.coupling_ratio,
has_static_dep: pair.has_static_dep,
});
}
}
result.sort_by(|a, b| {
let a_dropped = a.status == "dropped";
let b_dropped = b.status == "dropped";
a_dropped
.cmp(&b_dropped)
.then_with(|| {
let ar = a.curr_risk.as_deref().map(risk_rank).unwrap_or(0);
let br = b.curr_risk.as_deref().map(risk_rank).unwrap_or(0);
br.cmp(&ar)
})
.then(a.file_a.cmp(&b.file_a))
.then(a.file_b.cmp(&b.file_b))
});
result
}
pub fn compute_diff_file_risk_ranks(
files: &[String],
current_file_risk: &[FileRiskView],
) -> HashMap<String, (f64, f64, bool)> {
let risk_by_file: HashMap<&str, f64> = current_file_risk
.iter()
.map(|v| (v.file.as_str(), v.file_risk_score))
.collect();
let mut scored: Vec<(&str, f64)> = files
.iter()
.filter_map(|f| {
risk_by_file
.get(f.as_str())
.map(|&score| (f.as_str(), score))
})
.collect();
let n = scored.len();
let mut result = HashMap::with_capacity(n);
if n < 2 {
for (file, score) in scored {
result.insert(file.to_string(), (score, 0.0, false));
}
return result;
}
scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
let mut i = 0;
while i < n {
let mut j = i + 1;
while j < n && scored[j].1 == scored[i].1 {
j += 1;
}
let avg_rank = ((i + 1) + j) as f64 / 2.0;
let percentile = 1.0 - (avg_rank - 1.0) / (n as f64 - 1.0);
let top_decile = percentile >= 0.90;
for (file, score) in &scored[i..j] {
result.insert(file.to_string(), (*score, percentile, top_decile));
}
i = j;
}
result
}
pub fn compute_delta_aggregates(
delta: &Delta,
current_co_change: &[crate::git::CoChangePair],
prev_co_change: &[crate::git::CoChangePair],
fn_changed_lines: usize,
current_file_risk: &[FileRiskView],
) -> DeltaAggregates {
let mut file_data: HashMap<String, (f64, usize, usize)> = HashMap::new();
let pure_renames = crate::delta::pure_rename_function_ids(&delta.deltas);
for entry in &delta.deltas {
if pure_renames.contains(&entry.function_id) {
continue;
}
let file = if let Some(file) = crate::function_id::file_of(&entry.function_id) {
file.to_string()
} else {
continue; };
let e = file_data.entry(file).or_insert((0.0, 0, 0));
if let Some(delta_val) = &entry.delta {
e.0 += delta_val.lrs;
if delta_val.lrs > 0.0 {
e.1 += 1; } else if delta_val.lrs < 0.0 {
e.2 += 1; }
} else {
match entry.status {
crate::delta::FunctionStatus::New => {
if let Some(after) = &entry.after {
e.0 += after.lrs;
}
}
crate::delta::FunctionStatus::Deleted => {
if let Some(before) = &entry.before {
e.0 -= before.lrs;
e.2 += 1; }
}
_ => {}
}
}
}
let changed_files: Vec<String> = file_data.keys().cloned().collect();
let risk_ranks = compute_diff_file_risk_ranks(&changed_files, current_file_risk);
let mut aggregates: Vec<FileDeltaAggregates> = file_data
.into_iter()
.map(
|(file, (net_lrs_delta, regression_count, improvement_count))| {
let (file_risk_score, file_risk_diff_percentile, file_risk_top_decile) =
match risk_ranks.get(&file) {
Some(&(score, percentile, top_decile)) => {
(Some(score), Some(percentile), top_decile)
}
None => (None, None, false),
};
FileDeltaAggregates {
file,
net_lrs_delta,
regression_count,
improvement_count,
file_risk_score,
file_risk_diff_percentile,
file_risk_top_decile,
}
},
)
.collect();
aggregates.sort_by(|a, b| {
b.net_lrs_delta
.partial_cmp(&a.net_lrs_delta)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.file.cmp(&b.file))
});
let co_change_delta = diff_co_change_pairs(prev_co_change, current_co_change);
DeltaAggregates {
files: aggregates,
co_change_delta,
pr_summary: compute_pr_risk_summary(delta, fn_changed_lines),
}
}
pub fn compute_pr_risk_summary(delta: &Delta, fn_changed_lines: usize) -> PrRiskSummary {
use crate::delta::FunctionStatus;
let mut new_count = 0;
let mut modified_count = 0;
let mut deleted_count = 0;
let mut regression_count = 0;
let mut improvement_count = 0;
let mut band_upgrades = 0;
let mut band = RiskBand::Low;
let pure_renames = crate::delta::pure_rename_function_ids(&delta.deltas);
for entry in &delta.deltas {
if pure_renames.contains(&entry.function_id) {
continue;
}
match entry.status {
FunctionStatus::New => {
new_count += 1;
if let Some(after) = &entry.after {
band = band.max(after.band);
}
}
FunctionStatus::Deleted => {
deleted_count += 1;
if entry.before.is_some() {
improvement_count += 1;
}
}
FunctionStatus::Modified => {
modified_count += 1;
if let Some(d) = &entry.delta {
if d.lrs > 0.0 {
regression_count += 1;
} else if d.lrs < 0.0 {
improvement_count += 1;
}
}
if let Some(after) = &entry.after {
band = band.max(after.band);
}
}
FunctionStatus::Unchanged => continue,
}
if let Some(t) = &entry.band_transition {
let from = RiskBand::parse(&t.from);
let to = RiskBand::parse(&t.to);
if let (Some(from), Some(to)) = (from, to) {
if to > from {
band_upgrades += 1;
}
}
}
}
let policy_blocking = delta
.policy
.as_ref()
.map(|p| p.has_blocking_failures())
.unwrap_or(false);
PrRiskSummary {
fn_changed_lines,
band,
new_count,
modified_count,
deleted_count,
regression_count,
improvement_count,
band_upgrades,
policy_blocking,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::report::MetricsReport;
use crate::snapshot::FunctionSnapshot;
fn create_test_function(file: &str, function: &str, lrs: f64, band: &str) -> FunctionSnapshot {
FunctionSnapshot {
function_id: format!("{}::{}", file, function),
file: file.to_string(),
line: 1,
language: crate::language::Language::TypeScript,
metrics: MetricsReport {
cc: 1,
nd: 0,
fo: 0,
ns: 0,
loc: 10,
missing_docstring: false,
},
lrs,
band: crate::risk::RiskBand::parse(band).unwrap_or(crate::risk::RiskBand::Low),
suppression_reason: None,
churn: None,
touch_count: None,
days_since_last_change: None,
callgraph: None,
activity_risk: None,
risk_factors: None,
tier: None,
subsystem: None,
authors_90d: None,
directed_coupling: None,
convention_bug_fix_count: None,
burst_score: None,
commit_count: None,
author_count: None,
author_entropy: None,
isolation_rate: None,
age_days: None,
last_touch_days: None,
newcomer_rate: None,
explanation: None,
}
}
#[test]
fn test_file_aggregates() {
let functions = vec![
create_test_function("src/foo.ts", "func1", 5.0, "moderate"),
create_test_function("src/foo.ts", "func2", 8.0, "high"),
create_test_function("src/bar.ts", "func3", 3.0, "low"),
];
let aggregates = compute_file_aggregates(&functions);
assert_eq!(aggregates.len(), 2);
let foo_agg = aggregates.iter().find(|a| a.file == "src/foo.ts").unwrap();
assert_eq!(foo_agg.sum_lrs, 13.0);
assert_eq!(foo_agg.max_lrs, 8.0);
assert_eq!(foo_agg.high_plus_count, 1);
let bar_agg = aggregates.iter().find(|a| a.file == "src/bar.ts").unwrap();
assert_eq!(bar_agg.sum_lrs, 3.0);
assert_eq!(bar_agg.max_lrs, 3.0);
assert_eq!(bar_agg.high_plus_count, 0);
}
#[test]
fn test_directory_aggregates() {
let file_aggregates = vec![
FileAggregates {
file: "src/api/handler.ts".to_string(),
sum_lrs: 10.0,
max_lrs: 8.0,
high_plus_count: 1,
},
FileAggregates {
file: "src/api/router.ts".to_string(),
sum_lrs: 5.0,
max_lrs: 5.0,
high_plus_count: 0,
},
FileAggregates {
file: "src/utils.ts".to_string(),
sum_lrs: 3.0,
max_lrs: 3.0,
high_plus_count: 0,
},
];
let repo_root = std::path::Path::new("/test/repo");
let dir_aggregates = compute_directory_aggregates(&file_aggregates, repo_root);
let api_dir = dir_aggregates
.iter()
.find(|a| a.directory == "src/api")
.unwrap();
assert_eq!(api_dir.sum_lrs, 15.0);
assert_eq!(api_dir.max_lrs, 8.0);
assert_eq!(api_dir.high_plus_count, 1);
let src_dir = dir_aggregates
.iter()
.find(|a| a.directory == "src")
.unwrap();
assert_eq!(src_dir.sum_lrs, 18.0); assert_eq!(src_dir.max_lrs, 8.0);
assert_eq!(src_dir.high_plus_count, 1);
}
#[test]
fn test_is_high_plus() {
assert!(is_high_plus(crate::risk::RiskBand::High));
assert!(is_high_plus(crate::risk::RiskBand::Critical));
assert!(!is_high_plus(crate::risk::RiskBand::Moderate));
assert!(!is_high_plus(crate::risk::RiskBand::Low));
}
fn file_risk_view(file: &str, score: f64) -> FileRiskView {
FileRiskView {
file: file.to_string(),
function_count: 1,
loc: 10,
max_cc: 1,
avg_cc: 1.0,
critical_count: 0,
file_risk_score: score,
}
}
#[test]
fn test_diff_file_risk_ranks_distinct_scores() {
let views = vec![
file_risk_view("a.ts", 1.0),
file_risk_view("b.ts", 5.0),
file_risk_view("c.ts", 3.0),
file_risk_view("d.ts", 9.0),
file_risk_view("e.ts", 7.0),
];
let files: Vec<String> = views.iter().map(|v| v.file.clone()).collect();
let ranks = compute_diff_file_risk_ranks(&files, &views);
let (score, pct, top) = ranks["d.ts"];
assert_eq!(score, 9.0);
assert_eq!(pct, 1.0);
assert!(
top,
"rank 1 of 5 must be top decile (percentile 1.0 >= 0.90)"
);
let (_, pct, top) = ranks["e.ts"];
assert_eq!(pct, 0.75);
assert!(!top);
let (_, pct, _) = ranks["a.ts"];
assert_eq!(pct, 0.0);
}
#[test]
fn test_diff_file_risk_ranks_tied_scores_use_average_rank() {
let views = vec![
file_risk_view("a.ts", 5.0),
file_risk_view("b.ts", 5.0),
file_risk_view("c.ts", 1.0),
file_risk_view("d.ts", 1.0),
];
let files: Vec<String> = views.iter().map(|v| v.file.clone()).collect();
let ranks = compute_diff_file_risk_ranks(&files, &views);
let (_, pct_a, _) = ranks["a.ts"];
let (_, pct_b, _) = ranks["b.ts"];
assert_eq!(pct_a, pct_b);
assert!((pct_a - (5.0 / 6.0)).abs() < 1e-9);
let (_, pct_c, _) = ranks["c.ts"];
let (_, pct_d, _) = ranks["d.ts"];
assert_eq!(pct_c, pct_d);
assert!((pct_c - (1.0 / 6.0)).abs() < 1e-9);
}
#[test]
fn test_diff_file_risk_ranks_single_file_has_no_relative_rank() {
let views = vec![file_risk_view("a.ts", 9.0)];
let files = vec!["a.ts".to_string()];
let ranks = compute_diff_file_risk_ranks(&files, &views);
let (score, pct, top) = ranks["a.ts"];
assert_eq!(score, 9.0);
assert_eq!(
pct, 0.0,
"a single-file diff has no meaningful relative rank"
);
assert!(!top);
}
#[test]
fn test_diff_file_risk_ranks_excludes_files_absent_from_current_file_risk() {
let views = vec![file_risk_view("a.ts", 5.0), file_risk_view("b.ts", 1.0)];
let files = vec![
"a.ts".to_string(),
"b.ts".to_string(),
"deleted.ts".to_string(),
];
let ranks = compute_diff_file_risk_ranks(&files, &views);
assert_eq!(
ranks.len(),
2,
"unscoreable file must not appear in the result"
);
assert!(!ranks.contains_key("deleted.ts"));
let (_, pct_a, top_a) = ranks["a.ts"];
assert_eq!(pct_a, 1.0);
assert!(top_a);
let (_, pct_b, _) = ranks["b.ts"];
assert_eq!(pct_b, 0.0);
}
}