kiss_coding/
context_files.rs1use 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(agent_dir) = kiss_ai::paths::agent_dir() {
27 let global = agent_dir.join("AGENTS.md");
28 if global.is_file() {
29 paths.push(global);
30 }
31 }
32
33 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 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
55pub struct SystemPromptFiles {
57 pub replace: Option<String>,
58 pub append: Option<String>,
59}
60
61impl SystemPromptFiles {
62 pub fn append_after(&self, extra: Option<&str>) -> Option<String> {
65 match (extra, self.append.as_deref()) {
66 (Some(first), Some(second)) => Some(format!("{first}\n\n{second}")),
67 (Some(value), None) | (None, Some(value)) => Some(value.to_string()),
68 (None, None) => None,
69 }
70 }
71}
72
73pub fn system_prompt_files(cwd: &Path, project_trusted: bool) -> SystemPromptFiles {
76 let dirs: Vec<PathBuf> = project_trusted
77 .then(|| cwd.join(".kiss"))
78 .into_iter()
79 .chain(kiss_ai::paths::agent_dir())
80 .collect();
81 let read = |name: &str| {
82 dirs.iter()
83 .find_map(|dir| std::fs::read_to_string(dir.join(name)).ok())
84 };
85 SystemPromptFiles {
86 replace: read("SYSTEM.md"),
87 append: read("APPEND_SYSTEM.md"),
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94
95 #[test]
96 fn an_untrusted_project_cannot_replace_the_system_prompt() {
97 let project = tempfile::tempdir().unwrap();
98 std::fs::create_dir(project.path().join(".kiss")).unwrap();
99 std::fs::write(project.path().join(".kiss/SYSTEM.md"), "project prompt").unwrap();
100 assert_eq!(
101 system_prompt_files(project.path(), true).replace.as_deref(),
102 Some("project prompt")
103 );
104 assert_ne!(
105 system_prompt_files(project.path(), false)
106 .replace
107 .as_deref(),
108 Some("project prompt")
109 );
110 }
111
112 #[cfg(unix)]
113 #[test]
114 fn symlinked_context_file_loads_once() {
115 let repo = tempfile::tempdir().unwrap();
116 std::fs::write(repo.path().join("AGENTS.md"), "rules").unwrap();
117 let worktree = repo.path().join("worktrees/feature");
118 std::fs::create_dir_all(&worktree).unwrap();
119 std::os::unix::fs::symlink(repo.path().join("AGENTS.md"), worktree.join("AGENTS.md"))
120 .unwrap();
121 let files: Vec<ContextFile> = discover(&worktree)
122 .into_iter()
123 .filter(|file| file.path.starts_with(repo.path()))
124 .collect();
125 assert_eq!(files.len(), 1);
126 assert_eq!(files[0].content, "rules");
127 }
128
129 #[test]
130 fn override_beats_agents_beats_claude() {
131 let dir = tempfile::tempdir().unwrap();
132 std::fs::write(dir.path().join("CLAUDE.md"), "claude").unwrap();
133 assert!(
134 pick_context_file(dir.path())
135 .unwrap()
136 .ends_with("CLAUDE.md")
137 );
138 std::fs::write(dir.path().join("AGENTS.md"), "agents").unwrap();
139 assert!(
140 pick_context_file(dir.path())
141 .unwrap()
142 .ends_with("AGENTS.md")
143 );
144 std::fs::write(dir.path().join("AGENTS.override.md"), "override").unwrap();
145 assert!(
146 pick_context_file(dir.path())
147 .unwrap()
148 .ends_with("AGENTS.override.md")
149 );
150 }
151
152 #[test]
153 fn ancestors_ordered_root_to_cwd() {
154 let dir = tempfile::tempdir().unwrap();
155 let nested = dir.path().join("a/b");
156 std::fs::create_dir_all(&nested).unwrap();
157 std::fs::write(dir.path().join("AGENTS.md"), "root rules").unwrap();
158 std::fs::write(nested.join("AGENTS.md"), "leaf rules").unwrap();
159 let files = discover(&nested);
160 let contents: Vec<&str> = files.iter().map(|f| f.content.as_str()).collect();
161 let root_pos = contents.iter().position(|c| *c == "root rules").unwrap();
162 let leaf_pos = contents.iter().position(|c| *c == "leaf rules").unwrap();
163 assert!(root_pos < leaf_pos);
164 }
165}