1use std::fmt::Write;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4
5use rayon::prelude::*;
6use rustc_hash::{FxHashMap, FxHashSet};
7use similar::{ChangeTag, TextDiff};
8
9use crate::config::budget::BUDGET;
10use crate::config::limits::LIMITS;
11use crate::config::tokenization::TOKENIZATION;
12use crate::core::{compute_seed_weights, identify_core_fragments};
13use crate::edges;
14use crate::mode::{PipelineConfig, ScoringMode};
15use crate::parsers::fragment_file;
16use crate::render::{DiffContextOutput, build_diff_context_output};
17use crate::scoring::create_scoring_strategy;
18use crate::signatures::generate_signature_variants;
19use crate::tokenizer::count_tokens;
20use crate::types::{DiffHunk, Fragment, FragmentId};
21
22pub struct MemoryRepo {
23 pub name: String,
24 pub initial_files: FxHashMap<String, String>,
25 pub changed_files: FxHashMap<String, String>,
26}
27
28pub fn build_diff_context_in_memory(
29 repo: &MemoryRepo,
30 budget_tokens: Option<u32>,
31 _alpha: f64,
32 tau: f64,
33 no_content: bool,
34 scoring_mode: ScoringMode,
35) -> DiffContextOutput {
36 let hunks = compute_memory_hunks(&repo.initial_files, &repo.changed_files);
37 if hunks.is_empty() {
38 return empty_output(&repo.name);
39 }
40
41 let diff_text = compute_memory_diff_text(&repo.initial_files, &repo.changed_files);
42 let all_files = merge_file_contents(&repo.initial_files, &repo.changed_files);
43
44 let changed_paths: FxHashSet<String> =
45 hunks.iter().map(|h| h.path.as_ref().to_string()).collect();
46
47 let changed_file_paths: Vec<PathBuf> = changed_paths.iter().map(PathBuf::from).collect();
48 let all_file_paths: Vec<PathBuf> = all_files.keys().map(PathBuf::from).collect();
49 let file_cache: FxHashMap<PathBuf, String> = all_files
50 .iter()
51 .map(|(k, v)| (PathBuf::from(k), v.clone()))
52 .collect();
53
54 let discovered = edges::discover_all_related_files(
55 &changed_file_paths,
56 &all_file_paths,
57 None,
58 Some(&file_cache),
59 );
60 let discovered_paths: FxHashSet<String> = discovered
61 .iter()
62 .map(|p| p.to_string_lossy().to_string())
63 .collect();
64
65 let allowed_paths: FxHashSet<&str> = changed_paths
66 .iter()
67 .chain(discovered_paths.iter())
68 .map(|s| s.as_str())
69 .collect();
70
71 let mut all_fragments: Vec<Fragment> = Vec::new();
72 let mut seen: FxHashSet<FragmentId> = FxHashSet::default();
73 for (path, content) in &all_files {
74 if !allowed_paths.contains(path.as_str()) {
75 continue;
76 }
77 let path_arc: Arc<str> = Arc::from(path.as_str());
78 let frags = fragment_file(path_arc, content);
79 for f in frags {
80 if seen.insert(f.id.clone()) {
81 all_fragments.push(f);
82 }
83 }
84 }
85
86 all_fragments.par_iter_mut().for_each(|f| {
87 f.token_count = count_tokens(&f.content) + LIMITS.overhead_per_fragment;
88 });
89
90 let core_ids = identify_core_fragments(&hunks, &all_fragments);
91
92 let mut core_excerpts =
99 crate::excerpt::generate_core_excerpts(&all_fragments, &core_ids, &hunks);
100 core_excerpts.par_iter_mut().for_each(|(_, f)| {
101 f.token_count = count_tokens(&f.content) + LIMITS.overhead_per_fragment;
102 });
103
104 let mut sig_frags = generate_signature_variants(&all_fragments);
105 sig_frags.par_iter_mut().for_each(|f| {
106 f.token_count = count_tokens(&f.content) + LIMITS.overhead_per_fragment;
107 });
108 all_fragments.extend(sig_frags);
109
110 let effective_budget = budget_tokens.unwrap_or(BUDGET.unlimited);
111 let config = PipelineConfig::from_mode(scoring_mode);
112 let seed_weights = compute_seed_weights(&hunks, &core_ids, &all_fragments);
113
114 let discovered_arc: FxHashSet<Arc<str>> = discovered_paths
115 .iter()
116 .map(|s| Arc::from(s.as_str()))
117 .collect();
118
119 let strategy = create_scoring_strategy(&config);
120
121 let scoring_result = strategy.score_and_filter(
122 &all_fragments,
123 &core_ids,
124 &hunks,
125 None,
126 Some(&seed_weights),
127 Some(&discovered_arc),
128 );
129
130 let needs = crate::utility::needs::needs_from_diff(&all_fragments, &core_ids, &diff_text);
131
132 let file_importance =
133 crate::utility::compute_file_importance(&scoring_result.filtered_fragments);
134 let selection = crate::select::lazy_greedy_select(
135 scoring_result.filtered_fragments.clone(),
136 &core_ids,
137 &scoring_result.rel_scores,
138 &needs,
139 effective_budget,
140 tau,
141 Some(&file_importance),
142 Some(&core_excerpts),
143 );
144
145 let mut selected = selection.selected;
146
147 crate::postpass::coherence_post_pass(
148 &mut selected,
149 &scoring_result.filtered_fragments,
150 &scoring_result.graph,
151 effective_budget,
152 );
153
154 crate::postpass::rescue_nontrivial_context(
155 &mut selected,
156 &all_fragments,
157 &scoring_result.rel_scores,
158 &core_ids,
159 effective_budget,
160 );
161
162 let used: u32 = selected.iter().map(|f| f.token_count).sum();
163 let remaining = effective_budget.saturating_sub(used);
164 let changed_files: Vec<PathBuf> = changed_paths.iter().map(PathBuf::from).collect();
165 crate::postpass::ensure_changed_files_represented(
166 &mut selected,
167 &all_fragments,
168 &changed_files,
169 remaining,
170 Path::new("."),
171 &[],
172 None,
173 &core_ids,
174 &FxHashMap::default(),
175 );
176
177 let dummy_root = Path::new(".");
178 let mut changed_list: Vec<String> = changed_paths.iter().cloned().collect();
179 changed_list.sort();
180 let change = crate::render::ChangeSummary {
181 lockfile_changes: Vec::new(),
182 ignored_changes: Vec::new(),
183 policy_excluded_count: 0,
184 commit_message: None,
185 changed_files: changed_list,
186 deleted_files: Vec::new(),
187 renamed_files: Vec::new(),
188 };
189 build_diff_context_output(
190 dummy_root,
191 &selected,
192 no_content,
193 &core_ids,
194 &scoring_result.rel_scores,
195 change,
196 )
197}
198
199fn compute_memory_hunks(
200 initial: &FxHashMap<String, String>,
201 changed: &FxHashMap<String, String>,
202) -> Vec<DiffHunk> {
203 let mut hunks = Vec::new();
204
205 for (path, new_content) in changed {
206 let old_content = initial.get(path).map(|s| s.as_str()).unwrap_or("");
207 if old_content == new_content {
208 continue;
209 }
210 let path_arc: Arc<str> = Arc::from(path.as_str());
211 let file_hunks = diff_to_hunks(&path_arc, old_content, new_content);
212 hunks.extend(file_hunks);
213 }
214
215 for (path, _old_content) in initial {
216 if !changed.contains_key(path) {
217 let path_arc: Arc<str> = Arc::from(path.as_str());
218 let old_line_count = initial[path].lines().count() as u32;
219 if old_line_count > 0 {
220 hunks.push(DiffHunk {
221 path: path_arc,
222 new_start: 1,
223 new_len: 0,
224 old_start: 1,
225 old_len: old_line_count,
226 });
227 }
228 }
229 }
230
231 hunks
232}
233
234fn diff_to_hunks(path: &Arc<str>, old: &str, new: &str) -> Vec<DiffHunk> {
235 let diff = TextDiff::from_lines(old, new);
236 let mut hunks = Vec::new();
237
238 let mut new_line: u32 = 0;
239 let mut old_line: u32 = 0;
240
241 let mut hunk_new_start: Option<u32> = None;
242 let mut hunk_new_len: u32 = 0;
243 let mut hunk_old_start: u32 = 0;
244 let mut hunk_old_len: u32 = 0;
245
246 for change in diff.iter_all_changes() {
247 match change.tag() {
248 ChangeTag::Equal => {
249 if let Some(start) = hunk_new_start.take() {
250 hunks.push(DiffHunk {
251 path: Arc::clone(path),
252 new_start: start,
253 new_len: hunk_new_len,
254 old_start: hunk_old_start,
255 old_len: hunk_old_len,
256 });
257 hunk_new_len = 0;
258 hunk_old_len = 0;
259 }
260 new_line += 1;
261 old_line += 1;
262 }
263 ChangeTag::Delete => {
264 if hunk_new_start.is_none() {
265 hunk_new_start = Some(new_line + 1);
266 hunk_old_start = old_line + 1;
267 }
268 hunk_old_len += 1;
269 old_line += 1;
270 }
271 ChangeTag::Insert => {
272 if hunk_new_start.is_none() {
273 hunk_new_start = Some(new_line + 1);
274 hunk_old_start = old_line + 1;
275 }
276 hunk_new_len += 1;
277 new_line += 1;
278 }
279 }
280 }
281
282 if let Some(start) = hunk_new_start {
283 hunks.push(DiffHunk {
284 path: Arc::clone(path),
285 new_start: start,
286 new_len: hunk_new_len,
287 old_start: hunk_old_start,
288 old_len: hunk_old_len,
289 });
290 }
291
292 hunks
293}
294
295fn compute_memory_diff_text(
296 initial: &FxHashMap<String, String>,
297 changed: &FxHashMap<String, String>,
298) -> String {
299 let mut result = String::new();
300
301 let mut paths: Vec<&String> = changed.keys().collect();
302 paths.sort();
303
304 for path in paths {
305 let new_content = &changed[path];
306 let old_content = initial.get(path).map(|s| s.as_str()).unwrap_or("");
307 if old_content == new_content {
308 continue;
309 }
310
311 let diff = TextDiff::from_lines(old_content, new_content);
312 let mut udiff = diff.unified_diff();
313 let formatted = udiff
314 .context_radius(TOKENIZATION.diff_context_radius)
315 .header(&format!("a/{path}"), &format!("b/{path}"));
316 let _ = write!(result, "{formatted}");
317 }
318
319 let mut deleted_paths: Vec<&String> = initial
320 .keys()
321 .filter(|p| !changed.contains_key(*p))
322 .collect();
323 deleted_paths.sort();
324
325 for path in deleted_paths {
326 let old_content = &initial[path];
327 let empty = String::new();
328 let diff = TextDiff::from_lines(old_content, &empty);
329 let mut udiff = diff.unified_diff();
330 let formatted = udiff
331 .context_radius(TOKENIZATION.diff_context_radius)
332 .header(&format!("a/{path}"), "/dev/null");
333 let _ = write!(result, "{formatted}");
334 }
335
336 result
337}
338
339fn merge_file_contents(
340 initial: &FxHashMap<String, String>,
341 changed: &FxHashMap<String, String>,
342) -> FxHashMap<String, String> {
343 let mut merged = initial.clone();
344 for (path, content) in changed {
345 merged.insert(path.clone(), content.clone());
346 }
347 merged
348}
349
350fn empty_output(name: &str) -> DiffContextOutput {
351 DiffContextOutput {
352 lockfile_changes: Vec::new(),
353 ignored_changes: Vec::new(),
354 policy_excluded_count: 0,
355 name: name.to_string(),
356 output_type: "diff_context".to_string(),
357 commit_message: None,
358 changed_files: Vec::new(),
359 deleted_files: Vec::new(),
360 renamed_files: Vec::new(),
361 fragment_count: 0,
362 fragments: Vec::new(),
363 latency: None,
364 }
365}