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}
23
24fn serialize_renames<S>(renames: &[(String, String)], serializer: S) -> Result<S::Ok, S::Error>
25where
26 S: serde::Serializer,
27{
28 use serde::ser::SerializeSeq;
29 let mut seq = serializer.serialize_seq(Some(renames.len()))?;
30 for (from, to) in renames {
31 let mut m = std::collections::BTreeMap::new();
32 m.insert("from", from);
33 m.insert("to", to);
34 seq.serialize_element(&m)?;
35 }
36 seq.end()
37}
38
39#[derive(Serialize)]
40pub struct DiffContextOutput {
41 pub name: String,
42 #[serde(rename = "type")]
43 pub output_type: String,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub commit_message: Option<String>,
46 #[serde(skip_serializing_if = "Vec::is_empty")]
47 pub changed_files: Vec<String>,
48 #[serde(skip_serializing_if = "Vec::is_empty")]
49 pub deleted_files: Vec<String>,
50 #[serde(
51 skip_serializing_if = "Vec::is_empty",
52 serialize_with = "serialize_renames"
53 )]
54 pub renamed_files: Vec<(String, String)>,
55 #[serde(skip_serializing_if = "Vec::is_empty")]
58 pub lockfile_changes: Vec<String>,
59 pub fragment_count: usize,
60 pub fragments: Vec<FragmentEntry>,
61 #[serde(skip)]
62 pub latency: Option<LatencyBreakdown>,
63}
64
65pub struct LatencyBreakdown {
66 pub parse_changed_ms: f64,
67 pub universe_walk_ms: f64,
68 pub discovery_ms: f64,
69 pub parse_discovered_ms: f64,
70 pub tokenization_ms: f64,
71 pub graph_build_ms: f64,
76 pub scoring_selection_ms: f64,
80 pub total_ms: f64,
81 pub scoring_ms: f64,
85 pub selection_ms: f64,
87 pub candidate_count: usize,
94 pub edge_count: usize,
97 pub greedy_iters: usize,
101 pub edges_before_cap: usize,
103 pub edges_dropped_by_cap: usize,
105 pub nodes_capped: usize,
107 pub max_out_edges_per_node: usize,
109 pub ppr_truncated: bool,
114 pub ppr_forward_pushes: usize,
115 pub ppr_backward_pushes: usize,
116 pub stopping_certificate: f64,
121 pub peak_rss_bytes: u64,
124 pub edge_emissions_by_category: Vec<(&'static str, u64, u64)>,
129}
130
131#[derive(Serialize, Clone)]
132pub struct FragmentEntry {
133 pub path: String,
134 pub lines: String,
135 #[serde(skip_serializing_if = "Option::is_none")]
139 pub role: Option<String>,
140 pub kind: String,
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub symbol: Option<String>,
143 #[serde(skip_serializing_if = "Option::is_none")]
144 pub content: Option<Arc<str>>,
145}
146
147struct SymbolPatterns {
148 function: Vec<Regex>,
149 class: Vec<Regex>,
150 r#struct: Vec<Regex>,
151 interface: Vec<Regex>,
152 r#enum: Vec<Regex>,
153 r#impl: Vec<Regex>,
154 r#type: Vec<Regex>,
155 module: Vec<Regex>,
156 section: Vec<Regex>,
157}
158
159static SYMBOL_PATTERNS: Lazy<SymbolPatterns> = Lazy::new(|| {
160 SymbolPatterns {
161 function: vec![
162 Regex::new(r"(?m)^\s*(?:async\s+)?def\s+(\w+)\s*\(").unwrap(),
163 Regex::new(r"(?m)^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*[\(<]").unwrap(),
164 Regex::new(r"(?m)^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|\w)\s*=>").unwrap(),
165 Regex::new(r"(?m)^func\s+(?:\([^)]+\)\s+)?(\w+)\s*[\(\[]").unwrap(),
166 Regex::new(r"(?m)^\s*(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*[\(<]").unwrap(),
167 Regex::new(r"(?m)^\s*(?:(?:public|private|protected|static)\s+)*\w[\w<>\[\],]*\s+(\w+)\s*\(").unwrap(),
168 ],
169 class: vec![
170 Regex::new(r"(?m)^\s*class\s+(\w+)\s*[:\({\s]").unwrap(),
171 Regex::new(r"(?m)^\s*(?:export\s+)?(?:abstract\s+)?class\s+(\w+)").unwrap(),
172 ],
173 r#struct: vec![
174 Regex::new(r"(?m)^\s*(?:pub\s+)?struct\s+(\w+)").unwrap(),
175 Regex::new(r"(?m)^\s*type\s+(\w+)\s+struct\s*\{").unwrap(),
176 ],
177 interface: vec![
178 Regex::new(r"(?m)^\s*(?:export\s+)?interface\s+(\w+)").unwrap(),
179 Regex::new(r"(?m)^\s*type\s+(\w+)\s+interface\s*\{").unwrap(),
180 Regex::new(r"(?m)^\s*(?:pub\s+)?trait\s+(\w+)").unwrap(),
181 ],
182 r#enum: vec![
183 Regex::new(r"(?m)^\s*(?:pub\s+)?enum\s+(\w+)").unwrap(),
184 Regex::new(r"(?m)^\s*class\s+(\w+)\s*\(.*Enum\)").unwrap(),
185 ],
186 r#impl: vec![
187 Regex::new(r"(?m)^\s*impl(?:<[^>]+>)?\s+(\w+)").unwrap(),
188 ],
189 r#type: vec![
190 Regex::new(r"(?m)^\s*(?:export\s+)?type\s+(\w+)").unwrap(),
191 Regex::new(r"(?m)^\s*type\s+(\w+)\s").unwrap(),
192 ],
193 module: vec![
194 Regex::new(r"(?m)^\s*(?:pub\s+)?mod\s+(\w+)").unwrap(),
195 Regex::new(r"(?m)^\s*package\s+(\w+)").unwrap(),
196 ],
197 section: vec![
198 Regex::new(r"(?m)^#{1,6}\s+(\S[^\n]*)$").unwrap(),
199 ],
200}
201});
202
203fn extract_symbol(frag: &Fragment) -> Option<String> {
204 let patterns = match frag.kind {
205 FragmentKind::Function | FragmentKind::FunctionSignature => &SYMBOL_PATTERNS.function,
206 FragmentKind::Class | FragmentKind::ClassSignature => &SYMBOL_PATTERNS.class,
207 FragmentKind::Struct | FragmentKind::StructSignature => &SYMBOL_PATTERNS.r#struct,
208 FragmentKind::Interface | FragmentKind::InterfaceSignature => &SYMBOL_PATTERNS.interface,
209 FragmentKind::Enum | FragmentKind::EnumSignature => &SYMBOL_PATTERNS.r#enum,
210 FragmentKind::Impl => &SYMBOL_PATTERNS.r#impl,
211 FragmentKind::Type => &SYMBOL_PATTERNS.r#type,
212 FragmentKind::Module => &SYMBOL_PATTERNS.module,
213 FragmentKind::Section => &SYMBOL_PATTERNS.section,
214 _ => return None,
215 };
216
217 for pattern in patterns {
218 if let Some(caps) = pattern.captures(&frag.content) {
219 if let Some(m) = caps.get(1) {
220 let result = m.as_str().trim();
221 return Some(if frag.kind == FragmentKind::Section {
222 result
223 .chars()
224 .take(RENDER.section_symbol_max_chars)
225 .collect()
226 } else {
227 result.to_string()
228 });
229 }
230 }
231 }
232 None
233}
234
235fn get_relative_path(frag: &Fragment, repo_root: &Path) -> String {
236 let frag_path = Path::new(frag.path());
237 if !frag_path.is_absolute() {
238 return frag_path.to_string_lossy().replace('\\', "/");
239 }
240 frag_path
241 .strip_prefix(repo_root)
242 .unwrap_or(frag_path)
243 .to_string_lossy()
244 .replace('\\', "/")
245}
246
247fn create_fragment_entry(frag: &Fragment, path_str: &str) -> FragmentEntry {
248 let symbol = frag.symbol_name.clone().or_else(|| extract_symbol(frag));
249 let content = if frag.content.is_empty() {
250 None
251 } else {
252 Some(Arc::clone(&frag.content))
253 };
254
255 FragmentEntry {
256 path: path_str.to_string(),
257 lines: format!("{}-{}", frag.start_line(), frag.end_line()),
258 role: None,
259 kind: frag.kind.as_str().to_string(),
260 symbol,
261 content,
262 }
263}
264
265fn merge_file_fragments(
277 rel_path: &str,
278 frags: &[&Fragment],
279 core_ids: &FxHashSet<FragmentId>,
280) -> Vec<(bool, u32, FragmentEntry)> {
281 let mut out: Vec<(bool, u32, FragmentEntry)> = Vec::new();
282 let mut i = 0;
283 while i < frags.len() {
284 let first = frags[i];
285 let role_changed = core_ids.contains(&first.id);
286 let mut end = first.end_line();
287 let mut parts: Vec<&str> = vec![first.content.trim_end_matches('\n')];
288 let mut j = i + 1;
289 while j < frags.len() {
290 let next = frags[j];
291 if core_ids.contains(&next.id) != role_changed {
292 break;
293 }
294 if next.end_line() <= end {
295 j += 1;
297 } else if next.start_line() == end + 1 {
298 parts.push(next.content.trim_end_matches('\n'));
299 end = next.end_line();
300 j += 1;
301 } else {
302 break;
303 }
304 }
305
306 let mut entry = create_fragment_entry(first, rel_path);
307 if j > i + 1 {
308 entry.lines = format!("{}-{}", first.start_line(), end);
309 let merged = parts.join("\n");
310 entry.content = if merged.is_empty() {
311 None
312 } else {
313 Some(Arc::from(merged.as_str()))
314 };
315 }
316 entry.role = role_changed.then(|| "changed".to_string());
317 out.push((role_changed, first.start_line(), entry));
318 i = j;
319 }
320 out
321}
322
323pub fn build_diff_context_output(
324 repo_root: &Path,
325 selected: &[Fragment],
326 no_content: bool,
327 core_ids: &FxHashSet<FragmentId>,
328 rel_scores: &FxHashMap<FragmentId, f64>,
329 change: ChangeSummary,
330) -> DiffContextOutput {
331 let mut by_path: FxHashMap<String, Vec<&Fragment>> = FxHashMap::default();
332 for frag in selected {
333 by_path
334 .entry(get_relative_path(frag, repo_root))
335 .or_default()
336 .push(frag);
337 }
338
339 let mut changed: Vec<(String, u32, FragmentEntry)> = Vec::new();
343 let mut context: Vec<(f64, String, u32, FragmentEntry)> = Vec::new();
344 for (rel_path, frags) in &by_path {
345 let mut sorted: Vec<&Fragment> = frags.clone();
346 sorted.sort_by_key(|f| (f.start_line(), std::cmp::Reverse(f.end_line())));
351 let file_rel = sorted
352 .iter()
353 .map(|f| rel_scores.get(&f.id).copied().unwrap_or(0.0))
354 .fold(0.0_f64, f64::max);
355 for (role_changed, start, mut entry) in merge_file_fragments(rel_path, &sorted, core_ids) {
356 if no_content {
357 entry.content = None;
358 }
359 if role_changed {
360 changed.push((rel_path.clone(), start, entry));
361 } else {
362 context.push((file_rel, rel_path.clone(), start, entry));
363 }
364 }
365 }
366
367 changed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
368 context.sort_by(|a, b| {
369 b.0.partial_cmp(&a.0)
370 .unwrap_or(std::cmp::Ordering::Equal)
371 .then(a.1.cmp(&b.1))
372 .then(a.2.cmp(&b.2))
373 });
374
375 let mut fragments_out: Vec<FragmentEntry> = Vec::with_capacity(changed.len() + context.len());
376 fragments_out.extend(changed.into_iter().map(|(_, _, e)| e));
377 fragments_out.extend(context.into_iter().map(|(_, _, _, e)| e));
378
379 let resolved = repo_root
380 .canonicalize()
381 .unwrap_or_else(|_| repo_root.to_path_buf());
382 let name = resolved
383 .file_name()
384 .map(|n| n.to_string_lossy().to_string())
385 .unwrap_or_else(|| resolved.to_string_lossy().to_string());
386
387 DiffContextOutput {
388 name,
389 output_type: "diff_context".to_string(),
390 commit_message: change.commit_message,
391 changed_files: change.changed_files,
392 deleted_files: change.deleted_files,
393 renamed_files: change.renamed_files,
394 lockfile_changes: change.lockfile_changes,
395 fragment_count: fragments_out.len(),
396 fragments: fragments_out,
397 latency: None,
398 }
399}