Skip to main content

kiss_coding/
context_files.rs

1//! Project context file discovery: AGENTS.md / CLAUDE.md, with
2//! AGENTS.override.md taking precedence per directory. Load order: global
3//! file, then ancestor directories root->cwd, then cwd.
4
5use std::path::{Path, PathBuf};
6
7#[derive(Debug, Clone, PartialEq)]
8pub struct ContextFile {
9    pub path: PathBuf,
10    pub content: String,
11}
12
13fn pick_context_file(dir: &Path) -> Option<PathBuf> {
14    for name in ["AGENTS.override.md", "AGENTS.md", "CLAUDE.md"] {
15        let candidate = dir.join(name);
16        if candidate.is_file() {
17            return Some(candidate);
18        }
19    }
20    None
21}
22
23pub fn discover(cwd: &Path) -> Vec<ContextFile> {
24    let mut paths: Vec<PathBuf> = Vec::new();
25
26    if let Some(home) = dirs::home_dir() {
27        let global = home.join(".kiss/agent/AGENTS.md");
28        if global.is_file() {
29            paths.push(global);
30        }
31    }
32
33    // Ancestors from root down to cwd (cwd last so it wins by proximity).
34    let mut chain: Vec<&Path> = cwd.ancestors().collect();
35    chain.reverse();
36    for dir in chain {
37        if let Some(file) = pick_context_file(dir) {
38            paths.push(file);
39        }
40    }
41
42    // A symlinked AGENTS.md, such as one in a git worktree nested inside its
43    // main repository, can name a file that an ancestor already loaded.
44    let mut seen = std::collections::HashSet::new();
45    paths.retain(|path| seen.insert(std::fs::canonicalize(path).unwrap_or_else(|_| path.clone())));
46    paths
47        .into_iter()
48        .filter_map(|path| {
49            let content = std::fs::read_to_string(&path).ok()?;
50            Some(ContextFile { path, content })
51        })
52        .collect()
53}
54
55/// System-prompt replacement/append files (project wins over global).
56pub struct SystemPromptFiles {
57    pub replace: Option<String>,
58    pub append: Option<String>,
59}
60
61pub fn system_prompt_files(cwd: &Path) -> SystemPromptFiles {
62    let read = |p: PathBuf| std::fs::read_to_string(p).ok();
63    let global = dirs::home_dir().map(|h| h.join(".kiss/agent"));
64    let project = cwd.join(".kiss");
65
66    let replace = read(project.join("SYSTEM.md"))
67        .or_else(|| global.as_ref().and_then(|g| read(g.join("SYSTEM.md"))));
68    let append = read(project.join("APPEND_SYSTEM.md")).or_else(|| {
69        global
70            .as_ref()
71            .and_then(|g| read(g.join("APPEND_SYSTEM.md")))
72    });
73    SystemPromptFiles { replace, append }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[cfg(unix)]
81    #[test]
82    fn symlinked_context_file_loads_once() {
83        let repo = tempfile::tempdir().unwrap();
84        std::fs::write(repo.path().join("AGENTS.md"), "rules").unwrap();
85        let worktree = repo.path().join("worktrees/feature");
86        std::fs::create_dir_all(&worktree).unwrap();
87        std::os::unix::fs::symlink(repo.path().join("AGENTS.md"), worktree.join("AGENTS.md"))
88            .unwrap();
89        let files: Vec<ContextFile> = discover(&worktree)
90            .into_iter()
91            .filter(|file| file.path.starts_with(repo.path()))
92            .collect();
93        assert_eq!(files.len(), 1);
94        assert_eq!(files[0].content, "rules");
95    }
96
97    #[test]
98    fn override_beats_agents_beats_claude() {
99        let dir = tempfile::tempdir().unwrap();
100        std::fs::write(dir.path().join("CLAUDE.md"), "claude").unwrap();
101        assert!(
102            pick_context_file(dir.path())
103                .unwrap()
104                .ends_with("CLAUDE.md")
105        );
106        std::fs::write(dir.path().join("AGENTS.md"), "agents").unwrap();
107        assert!(
108            pick_context_file(dir.path())
109                .unwrap()
110                .ends_with("AGENTS.md")
111        );
112        std::fs::write(dir.path().join("AGENTS.override.md"), "override").unwrap();
113        assert!(
114            pick_context_file(dir.path())
115                .unwrap()
116                .ends_with("AGENTS.override.md")
117        );
118    }
119
120    #[test]
121    fn ancestors_ordered_root_to_cwd() {
122        let dir = tempfile::tempdir().unwrap();
123        let nested = dir.path().join("a/b");
124        std::fs::create_dir_all(&nested).unwrap();
125        std::fs::write(dir.path().join("AGENTS.md"), "root rules").unwrap();
126        std::fs::write(nested.join("AGENTS.md"), "leaf rules").unwrap();
127        let files = discover(&nested);
128        let contents: Vec<&str> = files.iter().map(|f| f.content.as_str()).collect();
129        let root_pos = contents.iter().position(|c| *c == "root rules").unwrap();
130        let leaf_pos = contents.iter().position(|c| *c == "leaf rules").unwrap();
131        assert!(root_pos < leaf_pos);
132    }
133}