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) = 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 seen_imports = HashSet::new();
49
50        for source in sources {
51            if remaining == 0 {
52                truncated = true;
53                break;
54            }
55
56            let import_policy = ImportPolicy {
57                workspace_root: &workspace_import_root,
58                allowed_roots: if source.scope == InstructionScope::User
59                    && !source.path.starts_with(&workspace_import_root)
60                {
61                    &allowed_import_roots
62                } else {
63                    std::slice::from_ref(&workspace_import_root)
64                },
65            };
66            let contents = match expand_instruction_contents(
67                &source.path,
68                &source.kind,
69                import_policy,
70                import_max_depth,
71                &mut seen_imports,
72                0,
73                &mut Vec::new(),
74            )? {
75                Some(contents) => contents,
76                None => continue,
77            };
78
79            if contents.len() > remaining {
80                truncated = true;
81            }
82
83            let slice_len = contents.len().min(remaining);
84            let visible = String::from_utf8_lossy(&contents.as_bytes()[..slice_len]).to_string();
85            if visible.trim().is_empty() {
86                remaining = remaining.saturating_sub(slice_len);
87                continue;
88            }
89
90            bytes_read += slice_len;
91            remaining = remaining.saturating_sub(slice_len);
92            segments.push(InstructionSegment { source, contents: visible });
93        }
94
95        Ok::<_, anyhow::Error>((segments, truncated, bytes_read))
96    })
97    .await
98    .context("Instruction expansion task panicked")??;
99
100    if segments.is_empty() {
101        Ok(None)
102    } else {
103        Ok(Some(InstructionBundle { segments, truncated, bytes_read }))
104    }
105}
106
107#[derive(Clone, Copy)]
108struct ImportPolicy<'a> {
109    workspace_root: &'a PathBuf,
110    allowed_roots: &'a [PathBuf],
111}
112
113fn expand_instruction_contents(
114    path: &Path,
115    kind: &InstructionSourceKind,
116    import_policy: ImportPolicy<'_>,
117    max_depth: usize,
118    seen_imports: &mut HashSet<PathBuf>,
119    depth: usize,
120    stack: &mut Vec<PathBuf>,
121) -> Result<Option<String>> {
122    let canonical = canonicalize_with_context(path, "instruction source")?;
123    if depth > 0 {
124        if stack.contains(&canonical) {
125            warn!("Skipping cyclic instruction import `{}` while expanding `{}`", canonical.display(), path.display());
126            return Ok(None);
127        }
128        if depth > max_depth {
129            warn!(
130                "Skipping instruction import `{}` because it exceeds the max depth of {}",
131                canonical.display(),
132                max_depth
133            );
134            return Ok(None);
135        }
136        if !seen_imports.insert(canonical.clone()) {
137            return Ok(None);
138        }
139    }
140
141    stack.push(canonical.clone());
142
143    let raw = match std::fs::read_to_string(&canonical) {
144        Ok(contents) => contents,
145        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
146            stack.pop();
147            return Ok(None);
148        }
149        Err(err) => {
150            stack.pop();
151            return Err(err).with_context(|| format!("Failed to open instruction file {}", canonical.display()));
152        }
153    };
154    let contents_without_frontmatter = match kind {
155        InstructionSourceKind::Rule => strip_rule_frontmatter(&raw),
156        InstructionSourceKind::Agents | InstructionSourceKind::Extra => raw,
157    };
158    let sanitized = strip_html_comments(&contents_without_frontmatter);
159    let output = expand_inline_imports(&sanitized, &canonical, import_policy, max_depth, seen_imports, depth, stack)?;
160
161    stack.pop();
162
163    if output.trim().is_empty() {
164        Ok(None)
165    } else {
166        Ok(Some(output))
167    }
168}
169
170fn expand_inline_imports(
171    contents: &str,
172    containing_file: &Path,
173    import_policy: ImportPolicy<'_>,
174    max_depth: usize,
175    seen_imports: &mut HashSet<PathBuf>,
176    depth: usize,
177    stack: &mut Vec<PathBuf>,
178) -> Result<String> {
179    let mut output = String::new();
180    let mut in_code_block = false;
181
182    for line in contents.lines() {
183        let trimmed = line.trim_start();
184        if is_fence_line(trimmed) {
185            in_code_block = !in_code_block;
186            output.push_str(line);
187            output.push('\n');
188            continue;
189        }
190
191        output.push_str(line);
192        output.push('\n');
193
194        if in_code_block {
195            continue;
196        }
197
198        let imports = collect_imports(line);
199        for import in imports {
200            let Some(import_path) = resolve_import_path(&import, containing_file, import_policy.allowed_roots)? else {
201                continue;
202            };
203
204            let import_kind = infer_instruction_kind(&import_path);
205            let child_policy = if import_path.starts_with(import_policy.workspace_root) {
206                ImportPolicy {
207                    allowed_roots: std::slice::from_ref(import_policy.workspace_root),
208                    ..import_policy
209                }
210            } else {
211                import_policy
212            };
213            let imported = expand_instruction_contents(
214                &import_path,
215                &import_kind,
216                child_policy,
217                max_depth,
218                seen_imports,
219                depth + 1,
220                stack,
221            )?;
222            let Some(imported) = imported else {
223                continue;
224            };
225
226            if imported.trim().is_empty() {
227                continue;
228            }
229
230            let _ = writeln!(output, "[Imported from {}]", import_path.display());
231            output.push_str(imported.trim());
232            output.push_str("\n\n");
233        }
234    }
235
236    Ok(output.trim().to_string())
237}
238
239fn infer_instruction_kind(path: &Path) -> InstructionSourceKind {
240    if path.components().any(|component| component.as_os_str() == "rules") {
241        InstructionSourceKind::Rule
242    } else if path.file_name().and_then(|value| value.to_str()) == Some(AGENTS_FILENAME)
243        || path.file_name().and_then(|value| value.to_str()) == Some(AGENTS_OVERRIDE_FILENAME)
244    {
245        InstructionSourceKind::Agents
246    } else {
247        InstructionSourceKind::Extra
248    }
249}