Skip to main content

vtcode_core/instructions/
discovery.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result, anyhow};
4use glob::{Pattern, glob};
5use hashbrown::HashSet;
6use tokio::io;
7use tracing::warn;
8use vtcode_commons::VtCodePaths;
9use vtcode_commons::canonicalize;
10use vtcode_commons::canonicalize_async;
11use vtcode_commons::walk::build_walker_single_threaded;
12
13use crate::utils::file_utils::canonicalize_with_context;
14
15use super::matching::{
16    RulePattern, contains_glob_meta, parse_rule_frontmatter, pattern_matches_candidate, rule_specificity,
17};
18use super::types::{
19    InstructionDiscoveryOptions, InstructionScope, InstructionSource, InstructionSourceKind, MatchCandidate,
20};
21use super::{AGENTS_FILENAME, AGENTS_OVERRIDE_FILENAME, CLAUDE_FILENAME, GLOBAL_CONFIG_DIRECTORY, RULES_DIRECTORY};
22
23#[derive(Debug, Clone)]
24struct RuleDescriptor {
25    patterns: Vec<String>,
26    specificity: usize,
27}
28
29#[derive(Debug, Clone)]
30struct MatchContext {
31    candidates: Vec<MatchCandidate>,
32}
33
34impl MatchContext {
35    async fn new(project_root: &Path, match_paths: &[PathBuf]) -> Self {
36        let mut seen = HashSet::new();
37        let mut candidates = Vec::with_capacity(match_paths.len());
38        let canonical_root = canonicalize_async(project_root).await.ok();
39
40        for raw_path in match_paths {
41            let candidate = if raw_path.is_absolute() {
42                raw_path.to_path_buf()
43            } else {
44                project_root.join(raw_path)
45            };
46
47            let normalized = canonicalize_async(&candidate).await.unwrap_or_else(|_| candidate.clone());
48            let relative = normalized
49                .strip_prefix(project_root)
50                .ok()
51                .or_else(|| canonical_root.as_ref().and_then(|root| normalized.strip_prefix(root).ok()))
52                .or_else(|| candidate.strip_prefix(project_root).ok())
53                .or_else(|| canonical_root.as_ref().and_then(|root| candidate.strip_prefix(root).ok()));
54            let Some(relative) = relative else {
55                continue;
56            };
57
58            let relative = relative.display().to_string();
59            if relative.is_empty() {
60                continue;
61            }
62
63            let is_dir = tokio::fs::metadata(&normalized).await.is_ok_and(|metadata| metadata.is_dir());
64            let key = format!("{relative}:{is_dir}");
65            if seen.insert(key) {
66                candidates.push(MatchCandidate { relative_path: relative, is_dir });
67            }
68        }
69
70        candidates.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
71        Self { candidates }
72    }
73
74    fn matches_any(&self, patterns: &[String]) -> Result<bool> {
75        const MAX_RULE_PATTERN_BYTES: usize = 4096;
76        for raw_pattern in patterns {
77            let trimmed = raw_pattern.trim();
78            if trimmed.is_empty() {
79                continue;
80            }
81            if trimmed.len() > MAX_RULE_PATTERN_BYTES {
82                anyhow::bail!("instruction rule path pattern exceeds {MAX_RULE_PATTERN_BYTES} bytes");
83            }
84
85            let Ok(pattern) = RulePattern::new(trimmed) else {
86                warn!("Ignoring invalid instruction rule path pattern `{trimmed}`");
87                continue;
88            };
89
90            if self
91                .candidates
92                .iter()
93                .any(|candidate| pattern_matches_candidate(&pattern, candidate))
94            {
95                return Ok(true);
96            }
97        }
98        Ok(false)
99    }
100}
101
102#[derive(Debug, Clone)]
103struct ExclusionMatcher {
104    patterns: Vec<Pattern>,
105}
106
107impl ExclusionMatcher {
108    async fn compile(project_root: &Path, home_dir: Option<&Path>, raw_patterns: &[String]) -> Result<Self> {
109        let mut patterns = Vec::with_capacity(raw_patterns.len());
110        for raw in raw_patterns {
111            let trimmed = raw.trim();
112            if trimmed.is_empty() {
113                continue;
114            }
115            let resolved = resolve_pattern(trimmed, project_root, home_dir).await?;
116            let pattern = Pattern::new(&resolved)
117                .with_context(|| format!("Failed to compile instruction exclude pattern `{trimmed}`"))?;
118            patterns.push(pattern);
119        }
120
121        Ok(Self { patterns })
122    }
123
124    fn matches(&self, path: &Path) -> bool {
125        self.patterns.iter().any(|pattern| {
126            pattern.matches_path(path)
127                || pattern.matches_path_with(
128                    path,
129                    glob::MatchOptions {
130                        case_sensitive: true,
131                        require_literal_separator: false,
132                        require_literal_leading_dot: false,
133                    },
134                )
135        })
136    }
137}
138
139pub async fn discover_instruction_sources(options: &InstructionDiscoveryOptions<'_>) -> Result<Vec<InstructionSource>> {
140    let mut sources = Vec::with_capacity(16);
141    let mut seen_paths = HashSet::new();
142    let excludes = ExclusionMatcher::compile(options.project_root, options.home_dir, options.exclude_patterns).await?;
143    let match_context = MatchContext::new(options.project_root, options.match_paths).await;
144
145    if let Some(home) = options.home_dir {
146        for candidate in user_instruction_candidates(home, options.fallback_filenames) {
147            if let Some(path) = normalize_instruction_candidate(&candidate, &excludes).await?
148                && seen_paths.insert(path.clone())
149            {
150                sources.push(InstructionSource {
151                    path,
152                    scope: InstructionScope::User,
153                    kind: InstructionSourceKind::Agents,
154                    matched: false,
155                });
156            }
157        }
158
159        let (user_unconditional_rules, user_matched_rules) =
160            discover_rule_sources(user_rules_roots(home), InstructionScope::User, &match_context, &excludes, None)
161                .await?;
162        for source in user_unconditional_rules.into_iter().chain(user_matched_rules) {
163            if seen_paths.insert(source.path.clone()) {
164                sources.push(source);
165            }
166        }
167    }
168
169    let extra_paths =
170        expand_instruction_patterns(options.project_root, options.home_dir, options.extra_patterns, &excludes).await?;
171    for path in extra_paths {
172        if seen_paths.insert(path.clone()) {
173            sources.push(InstructionSource {
174                path,
175                scope: InstructionScope::Custom,
176                kind: InstructionSourceKind::Extra,
177                matched: false,
178            });
179        }
180    }
181
182    let root = canonicalize_async(options.project_root)
183        .await
184        .with_context(|| format!("Failed to canonicalize project root {}", options.project_root.display()))?;
185    let mut cursor = canonicalize_async(options.current_dir)
186        .await
187        .with_context(|| format!("Failed to canonicalize working directory {}", options.current_dir.display()))?;
188    if !cursor.starts_with(&root) {
189        cursor = root.clone();
190    }
191
192    let mut workspace_levels = Vec::with_capacity(4);
193    loop {
194        let chosen_paths =
195            select_workspace_instruction_candidates(&cursor, &root, options.fallback_filenames, &excludes).await?;
196
197        let mut level_sources = Vec::with_capacity(chosen_paths.len());
198        for path in chosen_paths {
199            if seen_paths.insert(path.clone()) {
200                level_sources.push(InstructionSource {
201                    path,
202                    scope: InstructionScope::Workspace,
203                    kind: InstructionSourceKind::Agents,
204                    matched: false,
205                });
206            }
207        }
208        if !level_sources.is_empty() {
209            workspace_levels.push(level_sources);
210        }
211
212        if cursor == root {
213            break;
214        }
215
216        cursor = cursor
217            .parent()
218            .map(Path::to_path_buf)
219            .ok_or_else(|| anyhow!("Reached filesystem root before encountering project root"))?;
220    }
221
222    workspace_levels.reverse();
223    sources.extend(workspace_levels.into_iter().flatten());
224
225    let (workspace_unconditional_rules, workspace_matched_rules) = discover_rule_sources(
226        vec![root.join(RULES_DIRECTORY)],
227        InstructionScope::Workspace,
228        &match_context,
229        &excludes,
230        Some(&root),
231    )
232    .await?;
233    for source in workspace_unconditional_rules.into_iter().chain(workspace_matched_rules) {
234        if seen_paths.insert(source.path.clone()) {
235            sources.push(source);
236        }
237    }
238
239    Ok(sources)
240}
241
242fn user_instruction_candidates(home: &Path, fallback_filenames: &[String]) -> Vec<PathBuf> {
243    let mut candidates = Vec::new();
244    for root in user_global_instruction_roots(home) {
245        candidates.extend(instruction_candidates_for_dir(&root, fallback_filenames));
246    }
247    candidates
248}
249
250fn user_rules_roots(home: &Path) -> Vec<PathBuf> {
251    user_global_instruction_roots(home)
252        .into_iter()
253        .map(|root| root.join("rules"))
254        .collect()
255}
256
257pub(super) fn user_global_instruction_roots(home: &Path) -> Vec<PathBuf> {
258    let canonical_config = VtCodePaths::resolve()
259        .ok()
260        .filter(|_paths| dirs::home_dir().as_deref() == Some(home))
261        .map(|paths| paths.config_dir().to_path_buf())
262        .unwrap_or_else(|| home.join(GLOBAL_CONFIG_DIRECTORY));
263    let legacy = VtCodePaths::resolve()
264        .ok()
265        .filter(|_paths| dirs::home_dir().as_deref() == Some(home))
266        .map(|paths| paths.legacy_dir().to_path_buf())
267        .unwrap_or_else(|| home.join(".vtcode"));
268
269    let mut roots = vec![
270        home.to_path_buf(),
271        legacy,
272        home.join(GLOBAL_CONFIG_DIRECTORY),
273        canonical_config,
274    ];
275    roots.dedup();
276    roots
277}
278
279fn instruction_candidates_for_dir(dir: &Path, fallback_filenames: &[String]) -> Vec<PathBuf> {
280    let mut candidates = Vec::with_capacity(2 + fallback_filenames.len());
281    candidates.push(dir.join(AGENTS_OVERRIDE_FILENAME));
282    candidates.push(dir.join(AGENTS_FILENAME));
283    for name in fallback_filenames {
284        let trimmed = name.trim();
285        if trimmed.is_empty()
286            || trimmed.eq_ignore_ascii_case(AGENTS_FILENAME)
287            || trimmed.eq_ignore_ascii_case(AGENTS_OVERRIDE_FILENAME)
288        {
289            continue;
290        }
291        candidates.push(dir.join(trimmed));
292    }
293    candidates
294}
295
296async fn select_workspace_instruction_candidate(
297    dir: &Path,
298    workspace_root: &Path,
299    fallback_filenames: &[String],
300    excludes: &ExclusionMatcher,
301) -> Result<Option<PathBuf>> {
302    for candidate in instruction_candidates_for_dir(dir, fallback_filenames) {
303        if let Some(path) = normalize_instruction_candidate(&candidate, excludes).await?
304            && path.starts_with(workspace_root)
305        {
306            return Ok(Some(path));
307        }
308    }
309    Ok(None)
310}
311
312async fn select_workspace_instruction_candidates(
313    dir: &Path,
314    workspace_root: &Path,
315    fallback_filenames: &[String],
316    excludes: &ExclusionMatcher,
317) -> Result<Vec<PathBuf>> {
318    let mut selected = Vec::with_capacity(2);
319    if let Some(path) =
320        select_workspace_instruction_candidate(dir, workspace_root, fallback_filenames, excludes).await?
321    {
322        selected.push(path);
323    }
324
325    if let Some(path) = normalize_instruction_candidate(&dir.join(CLAUDE_FILENAME), excludes).await?
326        && path.starts_with(workspace_root)
327        && !selected.iter().any(|existing_path| existing_path == &path)
328    {
329        selected.push(path);
330    }
331
332    Ok(selected)
333}
334
335async fn normalize_instruction_candidate(candidate: &Path, excludes: &ExclusionMatcher) -> Result<Option<PathBuf>> {
336    if !instruction_exists(candidate).await? {
337        return Ok(None);
338    }
339
340    let canonical = canonicalize_async(candidate)
341        .await
342        .with_context(|| format!("Failed to canonicalize instruction candidate {}", candidate.display()))?;
343    if excludes.matches(&canonical) {
344        return Ok(None);
345    }
346
347    Ok(Some(canonical))
348}
349
350async fn discover_rule_sources(
351    rule_roots: Vec<PathBuf>,
352    scope: InstructionScope,
353    match_context: &MatchContext,
354    excludes: &ExclusionMatcher,
355    workspace_root: Option<&Path>,
356) -> Result<(Vec<InstructionSource>, Vec<InstructionSource>)> {
357    // Directory walking performs blocking filesystem I/O (readdir, stat, canonicalize).
358    // Offload the traversal to the blocking thread pool so the async runtime
359    // stays responsive while we discover rule files on disk.
360    let discovered = {
361        let excludes = excludes.clone();
362        let workspace_root = workspace_root.map(Path::to_path_buf);
363        tokio::task::spawn_blocking(move || {
364            let mut paths = Vec::new();
365            let mut seen = HashSet::new();
366
367            for root in &rule_roots {
368                if !root.exists() {
369                    continue;
370                }
371                if workspace_root.as_ref().is_some_and(|workspace_root| {
372                    canonicalize(root).map_or(true, |path| !path.starts_with(workspace_root))
373                }) {
374                    continue;
375                }
376
377                let mut builder = build_walker_single_threaded(root);
378                builder.follow_links(true).sort_by_file_name(|a, b| a.cmp(b));
379                if let Some(workspace_root) = &workspace_root {
380                    let workspace_root = workspace_root.clone();
381                    builder.filter_entry(move |entry| {
382                        canonicalize(entry.path()).is_ok_and(|path| path.starts_with(&workspace_root))
383                    });
384                }
385                for entry in builder.build().filter_map(std::result::Result::ok) {
386                    if !entry.file_type().is_some_and(|ft| ft.is_file()) {
387                        continue;
388                    }
389
390                    if entry.path().extension().and_then(|value| value.to_str()) != Some("md") {
391                        continue;
392                    }
393
394                    if entry
395                        .file_name()
396                        .to_str()
397                        .is_some_and(|name| name.eq_ignore_ascii_case("README.md"))
398                    {
399                        continue;
400                    }
401
402                    let path = canonicalize_with_context(entry.path(), "instruction rule")?;
403                    if workspace_root.as_ref().is_some_and(|root| !path.starts_with(root))
404                        || excludes.matches(&path)
405                        || !seen.insert(path.clone())
406                    {
407                        continue;
408                    }
409
410                    paths.push(path);
411                }
412            }
413
414            Ok::<_, anyhow::Error>(paths)
415        })
416        .await
417        .context("Rule discovery task panicked")??
418    };
419
420    // Process discovered paths asynchronously: read frontmatter and match patterns.
421    let mut unconditional = Vec::new();
422    let mut matched = Vec::new();
423
424    for path in discovered {
425        let descriptor = read_rule_descriptor(&path).await?;
426        let is_matched = if descriptor.patterns.is_empty() {
427            false
428        } else {
429            match_context
430                .matches_any(&descriptor.patterns)
431                .with_context(|| format!("Failed to match instruction rule {}", path.display()))?
432        };
433        let source = InstructionSource {
434            path,
435            scope: scope.clone(),
436            kind: InstructionSourceKind::Rule,
437            matched: is_matched,
438        };
439
440        if descriptor.patterns.is_empty() {
441            unconditional.push(source);
442        } else if is_matched {
443            matched.push((descriptor.specificity, source));
444        }
445    }
446
447    unconditional.sort_by(|left, right| left.path.cmp(&right.path));
448    matched.sort_by(|(left_specificity, left), (right_specificity, right)| {
449        left_specificity.cmp(right_specificity).then(left.path.cmp(&right.path))
450    });
451
452    Ok((unconditional, matched.into_iter().map(|(_, source)| source).collect()))
453}
454
455async fn read_rule_descriptor(path: &Path) -> Result<RuleDescriptor> {
456    let contents = tokio::fs::read_to_string(path)
457        .await
458        .with_context(|| format!("Failed to read instruction rule {}", path.display()))?;
459    let frontmatter = parse_rule_frontmatter(&contents, path)?;
460    let specificity = frontmatter
461        .paths
462        .iter()
463        .map(|pattern| rule_specificity(pattern))
464        .max()
465        .unwrap_or(0);
466
467    Ok(RuleDescriptor { patterns: frontmatter.paths, specificity })
468}
469
470async fn expand_instruction_patterns(
471    project_root: &Path,
472    home_dir: Option<&Path>,
473    patterns: &[String],
474    excludes: &ExclusionMatcher,
475) -> Result<Vec<PathBuf>> {
476    let mut paths = Vec::with_capacity(patterns.len());
477    let mut seen = HashSet::new();
478
479    for pattern in patterns {
480        let resolved = resolve_pattern(pattern, project_root, home_dir).await?;
481        let glob_matches: Vec<PathBuf> = glob(&resolved)
482            .with_context(|| format!("Failed to expand instruction pattern `{pattern}`"))?
483            .filter_map(|entry| match entry {
484                Ok(path) => Some(path),
485                Err(err) => {
486                    warn!("Ignoring malformed instruction path for pattern `{pattern}`: {err}");
487                    None
488                }
489            })
490            .collect();
491
492        let mut matches = Vec::with_capacity(glob_matches.len());
493        for path in glob_matches {
494            match normalize_instruction_candidate(&path, excludes).await {
495                Ok(Some(canonical)) if seen.insert(canonical.clone()) => matches.push(canonical),
496                Ok(Some(_)) | Ok(None) => {}
497                Err(err) => {
498                    warn!("Failed to inspect potential instruction `{}`: {err:#}", path.display());
499                }
500            }
501        }
502
503        if matches.is_empty() {
504            warn!("Instruction pattern `{pattern}` did not match any files");
505        } else {
506            matches.sort();
507            paths.extend(matches);
508        }
509    }
510
511    Ok(paths)
512}
513
514async fn resolve_pattern(pattern: &str, project_root: &Path, home_dir: Option<&Path>) -> Result<String> {
515    if let Some(stripped) = pattern.strip_prefix("~/") {
516        let home = home_dir
517            .ok_or_else(|| anyhow!("Cannot expand `~` in instruction pattern `{pattern}` without a home directory"))?;
518        let resolved = home.join(stripped);
519        if !contains_glob_meta(stripped) && tokio::fs::try_exists(&resolved).await.unwrap_or(false) {
520            return Ok(canonicalize_async(&resolved)
521                .await
522                .with_context(|| format!("Failed to canonicalize instruction pattern {}", resolved.display()))?
523                .to_string_lossy()
524                .into_owned());
525        }
526        return Ok(resolved.to_string_lossy().into_owned());
527    }
528
529    let candidate = Path::new(pattern);
530    let full_path = if candidate.is_absolute() {
531        candidate.to_path_buf()
532    } else {
533        project_root.join(candidate)
534    };
535
536    if !contains_glob_meta(pattern) && tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
537        return Ok(canonicalize_async(&full_path)
538            .await
539            .with_context(|| format!("Failed to canonicalize instruction pattern {}", full_path.display()))?
540            .to_string_lossy()
541            .into_owned());
542    }
543
544    Ok(full_path.to_string_lossy().into_owned())
545}
546
547async fn instruction_exists(path: &Path) -> Result<bool> {
548    match tokio::fs::symlink_metadata(path).await {
549        Ok(metadata) => Ok(metadata.file_type().is_file() || metadata.file_type().is_symlink()),
550        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
551        Err(err) => Err(err).with_context(|| format!("Failed to inspect instruction candidate {}", path.display())),
552    }
553}