-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext.rs
More file actions
376 lines (329 loc) · 12.6 KB
/
context.rs
File metadata and controls
376 lines (329 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use anyhow::Result;
use glob::glob;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use crate::core::function_chunker::find_enclosing_boundary_line;
use crate::core::SymbolIndex;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLMContextChunk {
pub file_path: PathBuf,
pub content: String,
pub context_type: ContextType,
pub line_range: Option<(usize, usize)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ContextType {
FileContent,
Definition,
Reference,
Documentation,
}
pub struct ContextFetcher {
repo_path: PathBuf,
}
impl ContextFetcher {
pub fn new(repo_path: PathBuf) -> Self {
Self { repo_path }
}
pub async fn fetch_context_for_file(
&self,
file_path: &PathBuf,
lines: &[(usize, usize)],
) -> Result<Vec<LLMContextChunk>> {
let mut chunks = Vec::new();
let full_path = self.repo_path.join(file_path);
if full_path.exists() {
let content = read_file_lossy(&full_path).await?;
let file_lines: Vec<&str> = content.lines().collect();
let merged_ranges = merge_ranges(lines);
for (start, end) in merged_ranges {
if file_lines.is_empty() {
break;
}
let start = start.max(1);
let end = end.max(start);
// Dynamic context: expand start to enclosing function boundary
let expanded_start = find_enclosing_boundary_line(&content, file_path, start, 10)
.filter(|&boundary| boundary >= start.saturating_sub(10))
.unwrap_or_else(|| start.saturating_sub(5)); // fallback: 5 lines before
let expanded_start = expanded_start.max(1);
// Asymmetric: less context after (1 extra line)
let expanded_end = (end + 1).min(file_lines.len());
let start_idx = expanded_start.saturating_sub(1);
let end_idx = expanded_end.min(file_lines.len());
if start_idx < file_lines.len() {
let chunk_content = truncate_with_notice(
file_lines[start_idx..end_idx].join("\n"),
MAX_CONTEXT_CHARS,
);
chunks.push(LLMContextChunk {
file_path: file_path.clone(),
content: chunk_content,
context_type: ContextType::FileContent,
line_range: Some((expanded_start, expanded_end)),
});
}
}
}
Ok(chunks)
}
pub async fn fetch_additional_context(
&self,
patterns: &[String],
) -> Result<Vec<LLMContextChunk>> {
self.fetch_additional_context_from_base(&self.repo_path, patterns, 10, 200)
.await
}
pub async fn fetch_additional_context_from_base(
&self,
base_path: &Path,
patterns: &[String],
max_files: usize,
max_lines: usize,
) -> Result<Vec<LLMContextChunk>> {
let mut chunks = Vec::new();
if patterns.is_empty() {
return Ok(chunks);
}
let mut matched_paths = HashSet::new();
for pattern in patterns {
let pattern_path = if Path::new(pattern).is_absolute() {
pattern.clone()
} else {
base_path.join(pattern).to_string_lossy().to_string()
};
if let Ok(entries) = glob(&pattern_path) {
for path in entries.flatten() {
if path.is_file() {
matched_paths.insert(path);
}
}
}
}
for path in matched_paths.into_iter().take(max_files) {
let relative_path = path.strip_prefix(base_path).unwrap_or(&path);
let content = read_file_lossy(&path).await?;
let snippet = content
.lines()
.take(max_lines)
.collect::<Vec<_>>()
.join("\n");
let snippet = truncate_with_notice(snippet, MAX_CONTEXT_CHARS);
if snippet.trim().is_empty() {
continue;
}
chunks.push(LLMContextChunk {
file_path: relative_path.to_path_buf(),
content: snippet,
context_type: ContextType::Reference,
line_range: None,
});
}
Ok(chunks)
}
pub async fn fetch_related_definitions(
&self,
file_path: &PathBuf,
symbols: &[String],
) -> Result<Vec<LLMContextChunk>> {
let mut chunks = Vec::new();
if symbols.is_empty() {
return Ok(chunks);
}
// Search for symbol definitions in the same file first
let full_path = self.repo_path.join(file_path);
if full_path.exists() {
if let Ok(content) = read_file_lossy(&full_path).await {
let lines: Vec<&str> = content.lines().collect();
for symbol in symbols {
// Look for function/class/interface definitions
for (line_num, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if trimmed.contains(&format!("function {}", symbol))
|| trimmed.contains(&format!("class {}", symbol))
|| trimmed.contains(&format!("interface {}", symbol))
|| trimmed.contains(&format!("fn {}", symbol))
|| trimmed.contains(&format!("struct {}", symbol))
|| trimmed.contains(&format!("enum {}", symbol))
|| trimmed.contains(&format!("impl {}", symbol))
{
// Extract a few lines around the definition for context
let start_line = line_num.saturating_sub(2);
let end_line = (line_num + 5).min(lines.len());
let definition_content = truncate_with_notice(
lines[start_line..end_line].join("\n"),
MAX_CONTEXT_CHARS,
);
chunks.push(LLMContextChunk {
file_path: file_path.clone(),
content: definition_content,
context_type: ContextType::Definition,
line_range: Some((start_line + 1, end_line)),
});
}
}
}
}
}
Ok(chunks)
}
pub async fn fetch_related_definitions_with_index(
&self,
file_path: &PathBuf,
symbols: &[String],
index: &SymbolIndex,
max_locations: usize,
graph_hops: usize,
graph_max_files: usize,
) -> Result<Vec<LLMContextChunk>> {
let mut chunks = Vec::new();
if symbols.is_empty() {
return Ok(chunks);
}
for symbol in symbols {
if let Some(locations) = index.lookup(symbol) {
for location in locations.iter().take(max_locations) {
if &location.file_path == file_path {
continue;
}
let snippet = truncate_with_notice(location.snippet.clone(), MAX_CONTEXT_CHARS);
chunks.push(LLMContextChunk {
file_path: location.file_path.clone(),
content: snippet,
context_type: ContextType::Definition,
line_range: Some(location.line_range),
});
}
}
}
for location in index.multi_hop_locations(
file_path,
symbols,
max_locations,
graph_hops,
graph_max_files,
) {
if &location.file_path == file_path {
continue;
}
let snippet = truncate_with_notice(location.snippet, MAX_CONTEXT_CHARS);
chunks.push(LLMContextChunk {
file_path: location.file_path,
content: snippet,
context_type: ContextType::Reference,
line_range: Some(location.line_range),
});
}
Ok(chunks)
}
}
fn merge_ranges(lines: &[(usize, usize)]) -> Vec<(usize, usize)> {
if lines.is_empty() {
return Vec::new();
}
let mut ranges = lines.to_vec();
ranges.sort_by_key(|(start, _)| *start);
let mut merged: Vec<(usize, usize)> = Vec::new();
for (start, end) in ranges {
let end = end.max(start);
if let Some(last) = merged.last_mut() {
if start <= last.1.saturating_add(1) {
last.1 = last.1.max(end);
continue;
}
}
merged.push((start, end));
}
merged
}
const MAX_CONTEXT_CHARS: usize = 8000;
fn truncate_with_notice(mut content: String, max_chars: usize) -> String {
if max_chars == 0 || content.len() <= max_chars {
return content;
}
let mut end = max_chars.saturating_sub(20);
while end > 0 && !content.is_char_boundary(end) {
end -= 1;
}
content.truncate(end);
content.push_str("\n[Truncated]\n");
content
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_truncate_with_notice_utf8_safety() {
// '€' is 3 bytes in UTF-8. With 5 euros = 15 bytes,
// max_chars=10 means truncate at 10 - 20 = 0 (saturating), but
// let's use a value where the truncation point lands mid-character.
let content = "€€€€€€€€€€".to_string(); // 10 euros = 30 bytes
// max_chars=25: truncate at 25-20=5, but byte 5 is mid-char (€ boundaries: 0,3,6,9,...)
// This should NOT panic
let result = truncate_with_notice(content, 25);
assert!(result.contains("[Truncated]"));
// Verify the result is valid UTF-8 (it is since it's a String, but
// the point is truncate() would have panicked)
assert!(result.len() > 0);
}
#[test]
fn test_truncate_with_notice_ascii() {
let content = "hello world, this is a long string".to_string();
let result = truncate_with_notice(content, 30);
assert!(result.contains("[Truncated]"));
}
#[test]
fn test_truncate_with_notice_no_truncation() {
let content = "short".to_string();
let result = truncate_with_notice(content, 100);
assert_eq!(result, "short");
assert!(!result.contains("[Truncated]"));
}
#[test]
fn test_merge_ranges_basic() {
let ranges = vec![(1, 5), (3, 8), (10, 15)];
let merged = merge_ranges(&ranges);
assert_eq!(merged, vec![(1, 8), (10, 15)]);
}
#[test]
fn test_merge_ranges_empty() {
let merged = merge_ranges(&[]);
assert!(merged.is_empty());
}
#[test]
fn test_merge_ranges_adjacent() {
let ranges = vec![(1, 5), (6, 10)];
let merged = merge_ranges(&ranges);
assert_eq!(merged, vec![(1, 10)]);
}
#[tokio::test]
async fn test_fetch_context_expands_to_function_boundary() {
// Create a temp file with a function
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.rs");
let content = "use std::io;\n\npub fn process(x: i32) -> bool {\n let y = x + 1;\n y > 0\n}\n\npub fn other() {\n println!(\"hi\");\n}\n";
std::fs::write(&file_path, content).unwrap();
let fetcher = ContextFetcher::new(dir.path().to_path_buf());
let relative = PathBuf::from("test.rs");
// Request context for line 4-5 (inside process function)
let chunks = fetcher
.fetch_context_for_file(&relative, &[(4, 5)])
.await
.unwrap();
assert!(!chunks.is_empty());
// Should expand to include the function signature (line 3)
let chunk = &chunks[0];
assert!(chunk.content.contains("pub fn process"));
}
}
async fn read_file_lossy(path: &Path) -> Result<String> {
match tokio::fs::read_to_string(path).await {
Ok(content) => Ok(content),
Err(_) => {
let bytes = tokio::fs::read(path).await?;
Ok(String::from_utf8_lossy(&bytes).to_string())
}
}
}