1use super::{ChildWorkspaceScope, SubagentError, spec::validate_scope_path};
4use std::{
5 fs,
6 path::{Path, PathBuf},
7};
8
9pub const MAX_CONTEXT_FILES_TOTAL_BYTES: usize = 32 * 1024;
11
12pub const MAX_CONTEXT_FILE_REFS: usize = 32;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ContextFileRef {
18 path: PathBuf,
19 line_range: Option<(usize, usize)>,
20}
21
22impl ContextFileRef {
23 pub fn parse(raw: &str) -> Result<Self, SubagentError> {
25 let trimmed = raw.trim();
26 if trimmed.is_empty() {
27 return Err(SubagentError::InvalidContextFileRef {
28 value: raw.to_owned(),
29 });
30 }
31 let (path_str, line_range) = match trimmed.rsplit_once(':') {
32 Some((prefix, range_part)) if looks_like_line_range(range_part) => {
33 let parsed = parse_line_range(range_part).ok_or_else(|| {
34 SubagentError::InvalidContextFileRef {
35 value: raw.to_owned(),
36 }
37 })?;
38 (prefix, Some(parsed))
39 }
40 _ => (trimmed, None),
41 };
42 if path_str == "." {
43 return Err(SubagentError::InvalidContextFileRef {
44 value: raw.to_owned(),
45 });
46 }
47 let path = validate_scope_path(PathBuf::from(path_str)).map_err(|_| {
48 SubagentError::InvalidContextFileRef {
49 value: raw.to_owned(),
50 }
51 })?;
52 Ok(Self { path, line_range })
53 }
54
55 #[must_use]
57 pub fn path(&self) -> &Path {
58 &self.path
59 }
60
61 #[must_use]
63 pub const fn line_range(&self) -> Option<(usize, usize)> {
64 self.line_range
65 }
66
67 #[must_use]
69 pub fn display_label(&self) -> String {
70 match self.line_range {
71 Some((start, end)) => format!("{}:{start}-{end}", self.path.display()),
72 None => self.path.display().to_string(),
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct PreloadedContextFile {
80 pub label: String,
82 pub content: String,
84}
85
86#[must_use]
88pub fn preload_context_files(
89 workspace_root: &Path,
90 scope: &ChildWorkspaceScope,
91 refs: &[ContextFileRef],
92) -> Vec<PreloadedContextFile> {
93 if refs.is_empty() {
94 return Vec::new();
95 }
96 let canonical_root = fs::canonicalize(workspace_root).ok();
97 let mut remaining_bytes = MAX_CONTEXT_FILES_TOTAL_BYTES;
98 let mut loaded = Vec::with_capacity(refs.len());
99
100 for file_ref in refs {
101 let label = file_ref.display_label();
102 if !path_allowed_by_scope(file_ref.path(), scope) {
103 loaded.push(PreloadedContextFile {
104 label,
105 content: "[skipped: path is outside read_scope or inside forbidden_paths]"
106 .to_owned(),
107 });
108 continue;
109 }
110 if remaining_bytes == 0 {
111 loaded.push(PreloadedContextFile {
112 label,
113 content: "[skipped: context_files byte budget exhausted; inspect directly with read_file]".to_owned(),
114 });
115 continue;
116 }
117 let full_path = workspace_root.join(file_ref.path());
118 if let Some(root) = canonical_root.as_deref() {
119 match fs::canonicalize(&full_path) {
120 Ok(canonical_file) if canonical_file.starts_with(root) => {}
121 Ok(_) => {
122 loaded.push(PreloadedContextFile {
123 label,
124 content: "[skipped: symlink escapes workspace root]".to_owned(),
125 });
126 continue;
127 }
128 Err(_) => {
129 loaded.push(PreloadedContextFile {
130 label,
131 content: "[unavailable: file does not exist or cannot be read]".to_owned(),
132 });
133 continue;
134 }
135 }
136 }
137 let raw_bytes = match fs::read(&full_path) {
138 Ok(bytes) => bytes,
139 Err(_) => {
140 loaded.push(PreloadedContextFile {
141 label,
142 content: "[unavailable: file could not be read]".to_owned(),
143 });
144 continue;
145 }
146 };
147 let Ok(text) = String::from_utf8(raw_bytes) else {
148 loaded.push(PreloadedContextFile {
149 label,
150 content: "[skipped: binary or non-UTF-8 file]".to_owned(),
151 });
152 continue;
153 };
154 let sliced = slice_lines(&text, file_ref.line_range());
155 let content = truncate_utf8(&sliced, remaining_bytes);
156 remaining_bytes = remaining_bytes.saturating_sub(content.len());
157 loaded.push(PreloadedContextFile { label, content });
158 }
159
160 loaded
161}
162
163#[must_use]
165pub fn render_subagent_handoff(
166 expected_output: Option<&str>,
167 files: &[PreloadedContextFile],
168) -> Option<String> {
169 let expected_output = expected_output
170 .map(str::trim)
171 .filter(|value| !value.is_empty());
172 if expected_output.is_none() && files.is_empty() {
173 return None;
174 }
175
176 let mut sections = Vec::new();
177 if let Some(expected) = expected_output {
178 sections.push(format!("<expected_output>\n{expected}\n</expected_output>"));
179 }
180 for file in files {
181 let mut block = format!("<context_file path=\"{}\">\n", file.label);
182 block.push_str(&file.content);
183 if !file.content.ends_with('\n') {
184 block.push('\n');
185 }
186 block.push_str("</context_file>");
187 sections.push(block);
188 }
189
190 Some(crate::prompt::render_prompt_block(
191 "merry_subagent_handoff",
192 §ions.join("\n\n"),
193 ))
194}
195
196fn path_allowed_by_scope(path: &Path, scope: &ChildWorkspaceScope) -> bool {
197 let in_read_scope = scope
198 .read_scope()
199 .iter()
200 .any(|root| root == Path::new(".") || path == root || path.starts_with(root));
201 if !in_read_scope {
202 return false;
203 }
204 let in_forbidden = scope
205 .forbidden_paths()
206 .iter()
207 .any(|denied| denied == Path::new(".") || path == denied || path.starts_with(denied));
208 !in_forbidden
209}
210
211fn looks_like_line_range(part: &str) -> bool {
212 !part.is_empty()
213 && part
214 .bytes()
215 .all(|byte| byte.is_ascii_digit() || byte == b'-')
216}
217
218fn parse_line_range(part: &str) -> Option<(usize, usize)> {
219 let (start_str, end_str) = match part.split_once('-') {
220 Some((start, end)) => (start, end),
221 None => (part, part),
222 };
223 let start: usize = start_str.parse().ok()?;
224 let end: usize = end_str.parse().ok()?;
225 if start == 0 || end < start {
226 return None;
227 }
228 Some((start, end))
229}
230
231fn slice_lines(text: &str, line_range: Option<(usize, usize)>) -> String {
232 let Some((start, end)) = line_range else {
233 return text.to_owned();
234 };
235 let mut out = String::new();
236 for (index, line) in text.lines().enumerate() {
237 let line_no = index + 1;
238 if line_no < start {
239 continue;
240 }
241 if line_no > end {
242 break;
243 }
244 out.push_str(&format!("{line_no}: {line}\n"));
245 }
246 out
247}
248
249fn truncate_utf8(text: &str, max_bytes: usize) -> String {
250 if text.len() <= max_bytes {
251 return text.to_owned();
252 }
253 let suffix = "\n...[truncated; inspect remaining lines with read_file]";
254 let limit = max_bytes.saturating_sub(suffix.len());
255 let mut end = limit.min(text.len());
256 while end > 0 && !text.is_char_boundary(end) {
257 end -= 1;
258 }
259 let mut truncated = text[..end].to_owned();
260 truncated.push_str(suffix);
261 truncated
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn parses_plain_and_line_ranged_context_file_refs() {
270 let plain = ContextFileRef::parse("crates/merry-runtime/src/lib.rs").expect("valid ref");
271 assert_eq!(plain.path(), Path::new("crates/merry-runtime/src/lib.rs"));
272 assert_eq!(plain.line_range(), None);
273 assert_eq!(plain.display_label(), "crates/merry-runtime/src/lib.rs");
274
275 let ranged =
276 ContextFileRef::parse("crates/merry-runtime/src/lib.rs:10-40").expect("valid range");
277 assert_eq!(ranged.path(), Path::new("crates/merry-runtime/src/lib.rs"));
278 assert_eq!(ranged.line_range(), Some((10, 40)));
279 assert_eq!(
280 ranged.display_label(),
281 "crates/merry-runtime/src/lib.rs:10-40"
282 );
283
284 let single = ContextFileRef::parse("src/main.rs:5").expect("valid single line");
285 assert_eq!(single.line_range(), Some((5, 5)));
286
287 for invalid in [
288 "",
289 ".",
290 "../secret.rs",
291 "/etc/passwd",
292 "src/lib.rs:0-5",
293 "src/lib.rs:10-5",
294 ] {
295 assert!(
296 ContextFileRef::parse(invalid).is_err(),
297 "{invalid:?} must be rejected"
298 );
299 }
300 }
301
302 #[test]
303 fn preloads_line_ranges_enforces_scope_and_renders_handoff() {
304 let dir = tempfile::tempdir().expect("tempdir");
305 fs::create_dir_all(dir.path().join("src")).expect("src dir");
306 fs::create_dir_all(dir.path().join("secret")).expect("secret dir");
307 fs::write(dir.path().join("src/a.rs"), "line1\nline2\nline3\nline4\n").expect("write a");
308 fs::write(dir.path().join("secret/key.txt"), "top-secret\n").expect("write secret");
309
310 let scope = ChildWorkspaceScope {
311 read_scope: vec![PathBuf::from("src")],
312 write_scope: Vec::new(),
313 forbidden_paths: vec![PathBuf::from("secret")],
314 workspace_mode: crate::SubagentWorkspaceMode::Shared,
315 };
316 let refs = vec![
317 ContextFileRef::parse("src/a.rs:2-3").expect("valid"),
318 ContextFileRef::parse("secret/key.txt").expect("valid"),
319 ];
320 let files = preload_context_files(dir.path(), &scope, &refs);
321 assert_eq!(files.len(), 2);
322 assert_eq!(files[0].content, "2: line2\n3: line3\n");
323 assert!(files[1].content.contains("skipped"));
324
325 let handoff = render_subagent_handoff(Some("Return JSON findings."), &files)
326 .expect("handoff should render");
327 assert!(handoff.starts_with("<merry_subagent_handoff>\n"));
328 assert!(handoff.contains("<expected_output>\nReturn JSON findings.\n</expected_output>"));
329 assert!(handoff.contains("<context_file path=\"src/a.rs:2-3\">"));
330 assert!(handoff.contains("2: line2"));
331 }
332}