Skip to main content

vtcode_core/instructions/
expansion.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use hashbrown::HashSet;
6use tracing::warn;
7use vtcode_commons::canonicalize_async;
8
9use crate::utils::file_utils::canonicalize_with_context;
10
11use super::discovery::discover_instruction_sources;
12use super::matching::{
13    allowed_import_roots, collect_imports, is_fence_line, resolve_import_path, strip_html_comments,
14    strip_rule_frontmatter,
15};
16use super::types::{
17    InstructionBundle, InstructionDiscoveryOptions, InstructionScope, InstructionSegment, InstructionSourceKind,
18};
19use super::{AGENTS_FILENAME, AGENTS_OVERRIDE_FILENAME};
20
21pub async fn read_instruction_bundle(
22    options: &InstructionDiscoveryOptions<'_>,
23    max_bytes: usize,
24) -> Result<Option<InstructionBundle>> {
25    if max_bytes == 0 {
26        return Ok(None);
27    }
28
29    let sources = discover_instruction_sources(options).await?;
30    if sources.is_empty() {
31        return Ok(None);
32    }
33
34    let allowed_import_roots = allowed_import_roots(options.project_root, options.home_dir).await?;
35    let workspace_import_root = canonicalize_async(options.project_root)
36        .await
37        .with_context(|| format!("Failed to canonicalize project root {}", options.project_root.display()))?;
38    let import_max_depth = options.import_max_depth.max(1);
39
40    // expand_instruction_contents performs blocking filesystem I/O (read_to_string,
41    // canonicalize) for each instruction file and its recursive imports. Offload
42    // the entire expansion loop to the blocking thread pool.
43    let (segments, truncated, bytes_read, omitted) = tokio::task::spawn_blocking(move || {
44        let mut remaining = max_bytes;
45        let mut segments = Vec::with_capacity(sources.len());
46        let mut truncated = false;
47        let mut bytes_read = 0usize;
48        let mut omitted = Vec::new();
49        let mut seen_imports = HashSet::new();
50
51        let mut sources = sources.into_iter();
52        while let Some(source) = sources.next() {
53            if remaining == 0 {
54                truncated = true;
55                omitted.push(source.path);
56                omitted.extend(sources.map(|source| source.path));
57                break;
58            }
59
60            let import_policy = ImportPolicy {
61                workspace_root: &workspace_import_root,
62                allowed_roots: if source.scope == InstructionScope::User
63                    && !source.path.starts_with(&workspace_import_root)
64                {
65                    &allowed_import_roots
66                } else {
67                    std::slice::from_ref(&workspace_import_root)
68                },
69            };
70            let contents = match expand_instruction_contents(
71                &source.path,
72                &source.kind,
73                import_policy,
74                import_max_depth,
75                &mut seen_imports,
76                0,
77                &mut Vec::new(),
78            )? {
79                Some(contents) => contents,
80                None => continue,
81            };
82
83            if contents.len() > remaining {
84                truncated = true;
85                omitted.push(source.path.clone());
86            }
87
88            // Cut on a char boundary so truncation never injects U+FFFD into the prompt.
89            let slice_len = contents.floor_char_boundary(contents.len().min(remaining));
90            let visible = contents.get(..slice_len).unwrap_or_default().to_string();
91            if visible.trim().is_empty() {
92                remaining = remaining.saturating_sub(slice_len);
93                continue;
94            }
95
96            bytes_read += slice_len;
97            remaining = remaining.saturating_sub(slice_len);
98            segments.push(InstructionSegment { source, contents: visible });
99        }
100
101        Ok::<_, anyhow::Error>((segments, truncated, bytes_read, omitted))
102    })
103    .await
104    .context("Instruction expansion task panicked")??;
105
106    if !omitted.is_empty() {
107        let paths: Vec<_> = omitted.iter().map(|path| path.display().to_string()).collect();
108        warn!(
109            max_bytes,
110            omitted = ?paths,
111            "instruction files exceeded the shared instruction budget (agent.instruction_max_bytes) and were cut or skipped"
112        );
113    }
114
115    if segments.is_empty() {
116        Ok(None)
117    } else {
118        Ok(Some(InstructionBundle { segments, truncated, bytes_read, omitted }))
119    }
120}
121
122#[derive(Clone, Copy)]
123struct ImportPolicy<'a> {
124    workspace_root: &'a PathBuf,
125    allowed_roots: &'a [PathBuf],
126}
127
128fn expand_instruction_contents(
129    path: &Path,
130    kind: &InstructionSourceKind,
131    import_policy: ImportPolicy<'_>,
132    max_depth: usize,
133    seen_imports: &mut HashSet<PathBuf>,
134    depth: usize,
135    stack: &mut Vec<PathBuf>,
136) -> Result<Option<String>> {
137    let canonical = canonicalize_with_context(path, "instruction source")?;
138    if depth > 0 {
139        if stack.contains(&canonical) {
140            warn!("Skipping cyclic instruction import `{}` while expanding `{}`", canonical.display(), path.display());
141            return Ok(None);
142        }
143        if depth > max_depth {
144            warn!(
145                "Skipping instruction import `{}` because it exceeds the max depth of {}",
146                canonical.display(),
147                max_depth
148            );
149            return Ok(None);
150        }
151        if !seen_imports.insert(canonical.clone()) {
152            return Ok(None);
153        }
154    }
155
156    stack.push(canonical.clone());
157
158    let raw = match std::fs::read_to_string(&canonical) {
159        Ok(contents) => contents,
160        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
161            stack.pop();
162            return Ok(None);
163        }
164        Err(err) => {
165            stack.pop();
166            return Err(err).with_context(|| format!("Failed to open instruction file {}", canonical.display()));
167        }
168    };
169    let contents_without_frontmatter = match kind {
170        InstructionSourceKind::Rule => strip_rule_frontmatter(&raw),
171        InstructionSourceKind::Agents | InstructionSourceKind::Extra => raw,
172    };
173    let sanitized = strip_html_comments(&contents_without_frontmatter);
174    let output = expand_inline_imports(&sanitized, &canonical, import_policy, max_depth, seen_imports, depth, stack)?;
175
176    stack.pop();
177
178    if output.trim().is_empty() {
179        Ok(None)
180    } else {
181        Ok(Some(output))
182    }
183}
184
185fn expand_inline_imports(
186    contents: &str,
187    containing_file: &Path,
188    import_policy: ImportPolicy<'_>,
189    max_depth: usize,
190    seen_imports: &mut HashSet<PathBuf>,
191    depth: usize,
192    stack: &mut Vec<PathBuf>,
193) -> Result<String> {
194    let mut output = String::new();
195    let mut in_code_block = false;
196
197    for line in contents.lines() {
198        let trimmed = line.trim_start();
199        if is_fence_line(trimmed) {
200            in_code_block = !in_code_block;
201            output.push_str(line);
202            output.push('\n');
203            continue;
204        }
205
206        output.push_str(line);
207        output.push('\n');
208
209        if in_code_block {
210            continue;
211        }
212
213        let imports = collect_imports(line);
214        for import in imports {
215            let Some(import_path) = resolve_import_path(&import, containing_file, import_policy.allowed_roots)? else {
216                continue;
217            };
218
219            let import_kind = infer_instruction_kind(&import_path);
220            let child_policy = if import_path.starts_with(import_policy.workspace_root) {
221                ImportPolicy {
222                    allowed_roots: std::slice::from_ref(import_policy.workspace_root),
223                    ..import_policy
224                }
225            } else {
226                import_policy
227            };
228            let imported = expand_instruction_contents(
229                &import_path,
230                &import_kind,
231                child_policy,
232                max_depth,
233                seen_imports,
234                depth + 1,
235                stack,
236            )?;
237            let Some(imported) = imported else {
238                continue;
239            };
240
241            if imported.trim().is_empty() {
242                continue;
243            }
244
245            let _ = writeln!(output, "[Imported from {}]", import_path.display());
246            output.push_str(imported.trim());
247            output.push_str("\n\n");
248        }
249    }
250
251    Ok(output.trim().to_string())
252}
253
254fn infer_instruction_kind(path: &Path) -> InstructionSourceKind {
255    if path.components().any(|component| component.as_os_str() == "rules") {
256        InstructionSourceKind::Rule
257    } else if path.file_name().and_then(|value| value.to_str()) == Some(AGENTS_FILENAME)
258        || path.file_name().and_then(|value| value.to_str()) == Some(AGENTS_OVERRIDE_FILENAME)
259    {
260        InstructionSourceKind::Agents
261    } else {
262        InstructionSourceKind::Extra
263    }
264}