1use std::path::Path;
2use std::sync::Arc;
3
4use once_cell::sync::Lazy;
5use regex::Regex;
6use rustc_hash::{FxHashMap, FxHashSet};
7use serde::Serialize;
8
9use crate::config::render::RENDER;
10use crate::types::{Fragment, FragmentId, FragmentKind};
11
12#[derive(Default)]
16pub struct ChangeSummary {
17 pub commit_message: Option<String>,
18 pub changed_files: Vec<String>,
19 pub deleted_files: Vec<String>,
20 pub renamed_files: Vec<(String, String)>,
21 pub lockfile_changes: Vec<String>,
22 pub ignored_changes: Vec<String>,
23 pub policy_excluded_count: usize,
24}
25
26pub fn is_zero(n: &usize) -> bool {
27 *n == 0
28}
29
30fn serialize_renames<S>(renames: &[(String, String)], serializer: S) -> Result<S::Ok, S::Error>
31where
32 S: serde::Serializer,
33{
34 use serde::ser::SerializeSeq;
35 let mut seq = serializer.serialize_seq(Some(renames.len()))?;
36 for (from, to) in renames {
37 let mut m = std::collections::BTreeMap::new();
38 m.insert("from", from);
39 m.insert("to", to);
40 seq.serialize_element(&m)?;
41 }
42 seq.end()
43}
44
45#[derive(Serialize)]
46pub struct DiffContextOutput {
47 pub name: String,
48 #[serde(rename = "type")]
49 pub output_type: String,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub commit_message: Option<String>,
52 #[serde(skip_serializing_if = "Vec::is_empty")]
53 pub changed_files: Vec<String>,
54 #[serde(skip_serializing_if = "Vec::is_empty")]
55 pub deleted_files: Vec<String>,
56 #[serde(
57 skip_serializing_if = "Vec::is_empty",
58 serialize_with = "serialize_renames"
59 )]
60 pub renamed_files: Vec<(String, String)>,
61 #[serde(skip_serializing_if = "Vec::is_empty")]
64 pub lockfile_changes: Vec<String>,
65 #[serde(skip_serializing_if = "Vec::is_empty")]
69 pub ignored_changes: Vec<String>,
70 #[serde(skip_serializing_if = "is_zero")]
73 pub policy_excluded_count: usize,
74 pub fragment_count: usize,
75 pub fragments: Vec<FragmentEntry>,
76 #[serde(skip)]
77 pub latency: Option<LatencyBreakdown>,
78}
79
80pub struct LatencyBreakdown {
81 pub pre_phase_ms: f64,
85 pub parse_changed_ms: f64,
86 pub universe_walk_ms: f64,
87 pub discovery_ms: f64,
88 pub parse_discovered_ms: f64,
89 pub tokenization_ms: f64,
90 pub graph_build_ms: f64,
95 pub scoring_selection_ms: f64,
99 pub total_ms: f64,
100 pub scoring_ms: f64,
104 pub selection_ms: f64,
106 pub candidate_count: usize,
113 pub edge_count: usize,
116 pub greedy_iters: usize,
120 pub edges_before_cap: usize,
122 pub edges_dropped_by_cap: usize,
124 pub nodes_capped: usize,
126 pub max_out_edges_per_node: usize,
128 pub ppr_truncated: bool,
133 pub ppr_forward_pushes: usize,
134 pub ppr_backward_pushes: usize,
135 pub stopping_certificate: f64,
140 pub peak_rss_bytes: u64,
143 pub edge_emissions_by_category: Vec<(&'static str, u64, u64)>,
148}
149
150#[derive(Serialize, Clone)]
151pub struct FragmentEntry {
152 pub path: String,
153 pub lines: String,
154 #[serde(skip_serializing_if = "Option::is_none")]
158 pub role: Option<String>,
159 pub kind: String,
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub symbol: Option<String>,
162 #[serde(skip_serializing_if = "Option::is_none")]
163 pub content: Option<Arc<str>>,
164}
165
166struct SymbolPatterns {
167 function: Vec<Regex>,
168 class: Vec<Regex>,
169 r#struct: Vec<Regex>,
170 interface: Vec<Regex>,
171 r#enum: Vec<Regex>,
172 r#impl: Vec<Regex>,
173 r#type: Vec<Regex>,
174 module: Vec<Regex>,
175 section: Vec<Regex>,
176}
177
178static SYMBOL_PATTERNS: Lazy<SymbolPatterns> = Lazy::new(|| {
179 SymbolPatterns {
180 function: vec![
181 Regex::new(r"(?m)^\s*(?:async\s+)?def\s+(\w+)\s*\(").unwrap(),
182 Regex::new(r"(?m)^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*[\(<]").unwrap(),
183 Regex::new(r"(?m)^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|\w)\s*=>").unwrap(),
184 Regex::new(r"(?m)^func\s+(?:\([^)]+\)\s+)?(\w+)\s*[\(\[]").unwrap(),
185 Regex::new(r"(?m)^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*[\(<]").unwrap(),
186 Regex::new(r"(?m)^\s*(?:(?:public|private|protected|static)\s+)*\w[\w<>\[\],]*\s+(\w+)\s*\(").unwrap(),
187 ],
188 class: vec![
189 Regex::new(r"(?m)^\s*class\s+(\w+)\s*[:\({\s]").unwrap(),
190 Regex::new(r"(?m)^\s*(?:export\s+)?(?:abstract\s+)?class\s+(\w+)").unwrap(),
191 ],
192 r#struct: vec![
193 Regex::new(r"(?m)^\s*(?:pub\s+)?struct\s+(\w+)").unwrap(),
194 Regex::new(r"(?m)^\s*type\s+(\w+)\s+struct\s*\{").unwrap(),
195 ],
196 interface: vec![
197 Regex::new(r"(?m)^\s*(?:export\s+)?interface\s+(\w+)").unwrap(),
198 Regex::new(r"(?m)^\s*type\s+(\w+)\s+interface\s*\{").unwrap(),
199 Regex::new(r"(?m)^\s*(?:pub\s+)?trait\s+(\w+)").unwrap(),
200 ],
201 r#enum: vec![
202 Regex::new(r"(?m)^\s*(?:pub\s+)?enum\s+(\w+)").unwrap(),
203 Regex::new(r"(?m)^\s*class\s+(\w+)\s*\(.*Enum\)").unwrap(),
204 ],
205 r#impl: vec![
206 Regex::new(r"(?m)^\s*impl(?:<[^>]+>)?\s+(\w+)").unwrap(),
207 ],
208 r#type: vec![
209 Regex::new(r"(?m)^\s*(?:export\s+)?type\s+(\w+)").unwrap(),
210 Regex::new(r"(?m)^\s*type\s+(\w+)\s").unwrap(),
211 ],
212 module: vec![
213 Regex::new(r"(?m)^\s*(?:pub\s+)?mod\s+(\w+)").unwrap(),
214 Regex::new(r"(?m)^\s*package\s+(\w+)").unwrap(),
215 ],
216 section: vec![
217 Regex::new(r"(?m)^#{1,6}\s+(\S[^\n]*)$").unwrap(),
218 ],
219}
220});
221
222fn extract_symbol(frag: &Fragment) -> Option<String> {
223 let patterns = match frag.kind {
224 FragmentKind::Function | FragmentKind::FunctionSignature => &SYMBOL_PATTERNS.function,
225 FragmentKind::Class | FragmentKind::ClassSignature => &SYMBOL_PATTERNS.class,
226 FragmentKind::Struct | FragmentKind::StructSignature => &SYMBOL_PATTERNS.r#struct,
227 FragmentKind::Interface | FragmentKind::InterfaceSignature => &SYMBOL_PATTERNS.interface,
228 FragmentKind::Enum | FragmentKind::EnumSignature => &SYMBOL_PATTERNS.r#enum,
229 FragmentKind::Impl => &SYMBOL_PATTERNS.r#impl,
230 FragmentKind::Type => &SYMBOL_PATTERNS.r#type,
231 FragmentKind::Module => &SYMBOL_PATTERNS.module,
232 FragmentKind::Section => &SYMBOL_PATTERNS.section,
233 _ => return None,
234 };
235
236 for pattern in patterns {
237 if let Some(caps) = pattern.captures(&frag.content) {
238 if let Some(m) = caps.get(1) {
239 let result = m.as_str().trim();
240 return Some(if frag.kind == FragmentKind::Section {
241 result
242 .chars()
243 .take(RENDER.section_symbol_max_chars)
244 .collect()
245 } else {
246 result.to_string()
247 });
248 }
249 }
250 }
251 None
252}
253
254use crate::paths::to_posix_display as normalize_path_separators;
255
256pub(crate) fn get_relative_path(frag: &Fragment, repo_root: &Path) -> String {
257 let frag_path = Path::new(frag.path());
258 if !frag_path.is_absolute() {
259 return normalize_path_separators(frag_path.to_string_lossy());
260 }
261 normalize_path_separators(
262 frag_path
263 .strip_prefix(repo_root)
264 .unwrap_or(frag_path)
265 .to_string_lossy(),
266 )
267}
268
269fn create_fragment_entry(frag: &Fragment, path_str: &str) -> FragmentEntry {
270 let symbol = frag.symbol_name.clone().or_else(|| extract_symbol(frag));
271 let content = if frag.content.is_empty() {
272 None
273 } else {
274 Some(Arc::clone(&frag.content))
275 };
276
277 FragmentEntry {
278 path: path_str.to_string(),
279 lines: format!("{}-{}", frag.start_line(), frag.end_line()),
280 role: None,
281 kind: frag.kind.as_str().to_string(),
282 symbol,
283 content,
284 }
285}
286
287fn carries_changed_role(frag: &Fragment, core_ids: &FxHashSet<FragmentId>) -> bool {
294 core_ids.contains(&frag.id) || frag.kind == FragmentKind::Excerpt
295}
296
297fn merge_file_fragments(
309 rel_path: &str,
310 frags: &[&Fragment],
311 core_ids: &FxHashSet<FragmentId>,
312) -> Vec<(bool, u32, FragmentEntry)> {
313 let mut out: Vec<(bool, u32, FragmentEntry)> = Vec::new();
314 let mut i = 0;
315 while i < frags.len() {
316 let first = frags[i];
317 let role_changed = carries_changed_role(first, core_ids);
318 let mut end = first.end_line();
319 let mut parts: Vec<&str> = vec![first.content.trim_end_matches('\n')];
320 let mut uniform_kind = true;
321 let mut j = i + 1;
322 while j < frags.len() {
323 let next = frags[j];
324 if carries_changed_role(next, core_ids) != role_changed {
325 break;
326 }
327 if next.end_line() <= end {
328 j += 1;
330 } else if next.start_line() == end + 1 {
331 parts.push(next.content.trim_end_matches('\n'));
332 uniform_kind &= next.kind == first.kind;
333 end = next.end_line();
334 j += 1;
335 } else {
336 break;
337 }
338 }
339
340 let mut entry = create_fragment_entry(first, rel_path);
341 if j > i + 1 {
342 entry.lines = format!("{}-{}", first.start_line(), end);
343 let merged = parts.join("\n");
344 entry.content = if merged.is_empty() {
345 None
346 } else {
347 Some(Arc::from(merged.as_str()))
348 };
349 if !uniform_kind {
358 entry.kind = crate::types::FragmentKind::Chunk.as_str().to_string();
359 }
360 }
361 entry.role = role_changed.then(|| "changed".to_string());
362 out.push((role_changed, first.start_line(), entry));
363 i = j;
364 }
365 out
366}
367
368pub fn build_diff_context_output(
369 repo_root: &Path,
370 selected: &[Fragment],
371 no_content: bool,
372 core_ids: &FxHashSet<FragmentId>,
373 rel_scores: &FxHashMap<FragmentId, f64>,
374 change: ChangeSummary,
375) -> DiffContextOutput {
376 let mut by_path: FxHashMap<String, Vec<&Fragment>> = FxHashMap::default();
377 for frag in selected {
378 by_path
379 .entry(get_relative_path(frag, repo_root))
380 .or_default()
381 .push(frag);
382 }
383
384 let mut changed: Vec<(String, u32, FragmentEntry)> = Vec::new();
388 let mut context: Vec<(f64, String, u32, FragmentEntry)> = Vec::new();
389 for (rel_path, frags) in &by_path {
390 let mut sorted: Vec<&Fragment> = frags.clone();
391 sorted.sort_by_key(|f| (f.start_line(), std::cmp::Reverse(f.end_line())));
396 let file_rel = sorted
397 .iter()
398 .map(|f| rel_scores.get(&f.id).copied().unwrap_or(0.0))
399 .fold(0.0_f64, f64::max);
400 for (role_changed, start, mut entry) in merge_file_fragments(rel_path, &sorted, core_ids) {
401 if no_content {
402 entry.content = None;
403 }
404 if role_changed {
405 changed.push((rel_path.clone(), start, entry));
406 } else {
407 context.push((file_rel, rel_path.clone(), start, entry));
408 }
409 }
410 }
411
412 changed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
413 context.sort_by(|a, b| {
414 b.0.partial_cmp(&a.0)
415 .unwrap_or(std::cmp::Ordering::Equal)
416 .then(a.1.cmp(&b.1))
417 .then(a.2.cmp(&b.2))
418 });
419
420 let mut fragments_out: Vec<FragmentEntry> = Vec::with_capacity(changed.len() + context.len());
421 fragments_out.extend(changed.into_iter().map(|(_, _, e)| e));
422 fragments_out.extend(context.into_iter().map(|(_, _, _, e)| e));
423
424 let resolved = repo_root
425 .canonicalize()
426 .unwrap_or_else(|_| repo_root.to_path_buf());
427 let name = resolved
428 .file_name()
429 .map(|n| n.to_string_lossy().to_string())
430 .unwrap_or_else(|| resolved.to_string_lossy().to_string());
431
432 DiffContextOutput {
433 name,
434 output_type: "diff_context".to_string(),
435 commit_message: change.commit_message,
436 changed_files: change.changed_files,
437 deleted_files: change.deleted_files,
438 renamed_files: change.renamed_files,
439 lockfile_changes: change.lockfile_changes,
440 ignored_changes: change.ignored_changes,
441 policy_excluded_count: change.policy_excluded_count,
442 fragment_count: fragments_out.len(),
443 fragments: fragments_out,
444 latency: None,
445 }
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 fn empty_output(renamed_files: Vec<(String, String)>) -> DiffContextOutput {
453 DiffContextOutput {
454 name: "repo".to_string(),
455 output_type: "diff_context".to_string(),
456 commit_message: None,
457 changed_files: Vec::new(),
458 deleted_files: Vec::new(),
459 renamed_files,
460 lockfile_changes: Vec::new(),
461 ignored_changes: Vec::new(),
462 policy_excluded_count: 0,
463 fragment_count: 0,
464 fragments: Vec::new(),
465 latency: None,
466 }
467 }
468
469 #[test]
470 fn renamed_files_serialize_as_labelled_from_to_in_yaml() {
471 let out = empty_output(vec![("old.py".to_string(), "new.py".to_string())]);
472 let yaml = serde_yaml::to_string(&out).unwrap();
473 assert!(
474 yaml.contains("from: old.py"),
475 "expected labelled `from:` entry, got:\n{yaml}"
476 );
477 assert!(
478 yaml.contains("to: new.py"),
479 "expected labelled `to:` entry, got:\n{yaml}"
480 );
481 assert!(!yaml.contains("- - old.py"));
484 }
485
486 #[test]
487 fn renamed_files_serialize_as_labelled_from_to_in_json() {
488 let out = empty_output(vec![("old.py".to_string(), "new.py".to_string())]);
489 let json = serde_json::to_value(&out).unwrap();
490 let renamed = json["renamed_files"]
491 .as_array()
492 .expect("renamed_files must serialize as an array");
493 assert_eq!(renamed.len(), 1);
494 assert_eq!(renamed[0]["from"], "old.py");
495 assert_eq!(renamed[0]["to"], "new.py");
496 assert!(
497 renamed[0].is_object(),
498 "must not serialize as a positional [old, new] tuple: {renamed:?}"
499 );
500 }
501
502 #[test]
503 fn renamed_files_empty_is_omitted_from_output() {
504 let out = empty_output(Vec::new());
505 let json = serde_json::to_value(&out).unwrap();
506 assert!(json.get("renamed_files").is_none());
507 }
508
509 fn frag_at(path: &str) -> Fragment {
510 Fragment {
511 id: FragmentId::new(Arc::from(path), 1, 5),
512 kind: FragmentKind::Function,
513 content: Arc::from(""),
514 identifiers: FxHashSet::default(),
515 token_count: 1,
516 symbol_name: None,
517 }
518 }
519
520 #[cfg(unix)]
521 #[test]
522 fn get_relative_path_posix_backslash_in_filename_round_trips_unchanged() {
523 let frag = frag_at("src\\utils.py");
527 let root = Path::new("/repo");
528 let rel = get_relative_path(&frag, root);
529 assert_eq!(rel, "src\\utils.py");
530 }
531
532 #[cfg(unix)]
533 #[test]
534 fn get_relative_path_strips_repo_root_on_posix() {
535 let frag = frag_at("/repo/src/lib.rs");
536 let root = Path::new("/repo");
537 let rel = get_relative_path(&frag, root);
538 assert_eq!(rel, "src/lib.rs");
539 }
540}
541
542#[cfg(test)]
543mod merge_kind_tests {
544 use super::*;
545 use crate::types::{FragmentId, FragmentKind};
546
547 fn frag(start: u32, end: u32, kind: FragmentKind, body: &str) -> Fragment {
548 Fragment {
549 id: FragmentId::new(Arc::from("a.py"), start, end),
550 kind,
551 content: Arc::from(body),
552 identifiers: FxHashSet::default(),
553 token_count: 10,
554 symbol_name: None,
555 }
556 }
557
558 #[test]
565 fn a_merged_run_of_mixed_kinds_does_not_claim_the_first_kind() {
566 let frags = vec![
567 frag(1, 1, FragmentKind::FunctionSignature, "def big(a):"),
568 frag(2, 3, FragmentKind::Chunk, " x = 1\n y = 2"),
569 ];
570 let refs: Vec<&Fragment> = frags.iter().collect();
571 let out = merge_file_fragments("a.py", &refs, &FxHashSet::default());
572
573 assert_eq!(out.len(), 1, "contiguous fragments should merge into one");
574 assert_eq!(out[0].2.kind, "chunk");
575 assert_eq!(out[0].2.lines, "1-3");
576 }
577
578 #[test]
581 fn a_merged_run_of_one_kind_keeps_it() {
582 let frags = vec![
583 frag(1, 2, FragmentKind::Chunk, "a\nb"),
584 frag(3, 4, FragmentKind::Chunk, "c\nd"),
585 ];
586 let refs: Vec<&Fragment> = frags.iter().collect();
587 let out = merge_file_fragments("a.py", &refs, &FxHashSet::default());
588
589 assert_eq!(out.len(), 1);
590 assert_eq!(out[0].2.kind, "chunk");
591 }
592
593 #[test]
595 fn a_lone_fragment_keeps_its_kind() {
596 let frags = vec![frag(1, 1, FragmentKind::FunctionSignature, "def big(a):")];
597 let refs: Vec<&Fragment> = frags.iter().collect();
598 let out = merge_file_fragments("a.py", &refs, &FxHashSet::default());
599
600 assert_eq!(out[0].2.kind, "function_signature");
601 }
602}