resources/
context_files.rs1use crate::paths::{canonicalize, resolve_path, strip_bom};
4use jsrt::path::{basename, dirname};
5use std::fs;
6use std::path::Path;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct ContextFile {
10 pub path: String,
11 pub content: String,
12}
13
14const CANDIDATES: [&str; 5] = ["AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"];
15
16fn load_from_dir(dir: &str) -> Option<ContextFile> {
17 CANDIDATES.iter().find_map(|name| {
18 let path = jsrt::path::join(&[dir, name]);
19 if !fs::metadata(&path).ok()?.is_file() {
20 return None;
21 }
22 let content = fs::read_to_string(&path).ok()?;
23 Some(ContextFile {
24 content: strip_bom(&content).to_string(),
25 path,
26 })
27 })
28}
29
30fn find_shadowed(cwd: &str) -> Option<String> {
32 let git = config::git::find_git_paths(Path::new(cwd))?;
33 let common = canonicalize(&git.common_git_dir.to_string_lossy());
34 let worktree_root = canonicalize(&git.repo_dir.to_string_lossy());
35 let main_root = dirname(&common);
36 if !worktree_root.starts_with(&format!("{main_root}/")) {
37 return None;
38 }
39 if canonicalize(&jsrt::path::join(&[&main_root, ".git"])) != common {
40 return None;
41 }
42 let own = load_from_dir(&worktree_root)?;
43 Some(jsrt::path::join(&[&main_root, basename(&own.path)]))
44}
45
46pub fn load_project_context_files(cwd: &str, agent_dir: &str, home: &str) -> Vec<ContextFile> {
48 let cwd = resolve_path(cwd, "/", home, false);
49 let agent_dir = resolve_path(agent_dir, &cwd, home, false);
50 let mut files = Vec::new();
51 let mut seen: Vec<String> = Vec::new();
52 if let Some(global) = load_from_dir(&agent_dir) {
53 seen.push(global.path.clone());
54 files.push(global);
55 }
56 let shadowed = find_shadowed(&cwd);
57 let mut ancestors = Vec::new();
58 let mut dir = cwd;
59 loop {
60 if let Some(file) = load_from_dir(&dir) {
61 let is_shadowed = shadowed.as_ref().is_some_and(|s| &canonicalize(&file.path) == s);
62 if !is_shadowed && !seen.contains(&file.path) {
63 seen.push(file.path.clone());
64 ancestors.insert(0, file);
65 }
66 }
67 let parent = dirname(&dir);
68 if parent == dir {
69 break;
70 }
71 dir = parent;
72 }
73 files.extend(ancestors);
74 files
75}