microclaw_engine/
subdirectory_hints.rs1use std::collections::HashSet;
19use std::path::{Path, PathBuf};
20
21const HINT_FILENAMES: &[&str] = &[
22 "AGENTS.md",
23 "agents.md",
24 "CLAUDE.md",
25 "claude.md",
26 ".cursorrules",
27];
28
29const PATH_ARG_KEYS: &[&str] = &["path", "file_path", "workdir", "cwd"];
31
32const COMMAND_TOOLS: &[&str] = &["bash"];
35
36const MAX_HINT_CHARS: usize = 8_000;
37const MAX_ANCESTOR_WALK: usize = 5;
38
39pub struct SubdirectoryHintTracker {
40 working_dir: PathBuf,
41 loaded_dirs: HashSet<PathBuf>,
42}
43
44impl SubdirectoryHintTracker {
45 pub fn new(working_dir: PathBuf) -> Self {
46 let working_dir = working_dir.canonicalize().unwrap_or(working_dir);
47 let mut loaded_dirs = HashSet::new();
48 loaded_dirs.insert(working_dir.clone());
50 Self {
51 working_dir,
52 loaded_dirs,
53 }
54 }
55
56 pub fn check_tool_call(&mut self, tool_name: &str, args: &serde_json::Value) -> Option<String> {
59 let dirs = self.extract_directories(tool_name, args);
60 if dirs.is_empty() {
61 return None;
62 }
63 let mut found = Vec::new();
64 for d in dirs {
65 if let Some(hint) = self.load_hints_for_directory(&d) {
66 found.push(hint);
67 }
68 }
69 if found.is_empty() {
70 None
71 } else {
72 Some(format!("\n\n{}", found.join("\n\n")))
73 }
74 }
75
76 fn extract_directories(&self, tool_name: &str, args: &serde_json::Value) -> Vec<PathBuf> {
77 let mut candidates: HashSet<PathBuf> = HashSet::new();
78 let obj = match args.as_object() {
79 Some(o) => o,
80 None => return Vec::new(),
81 };
82 for key in PATH_ARG_KEYS {
83 if let Some(s) = obj.get(*key).and_then(|v| v.as_str()) {
84 self.add_path_candidate(s, &mut candidates);
85 }
86 }
87 if tool_name == "apply_patch" {
89 if let Some(patch) = args.get("patch").and_then(|v| v.as_str()) {
90 for line in patch.lines() {
91 for prefix in [
92 "*** Add File: ",
93 "*** Update File: ",
94 "*** Delete File: ",
95 "*** Move to: ",
96 ] {
97 if let Some(path) = line.strip_prefix(prefix) {
98 self.add_path_candidate(path.trim(), &mut candidates);
99 }
100 }
101 }
102 }
103 }
104 if COMMAND_TOOLS.contains(&tool_name) {
105 if let Some(cmd) = obj.get("command").and_then(|v| v.as_str()) {
106 self.extract_paths_from_command(cmd, &mut candidates);
107 }
108 }
109 candidates.into_iter().collect()
110 }
111
112 fn add_path_candidate(&self, raw: &str, candidates: &mut HashSet<PathBuf>) {
113 if raw.trim().is_empty() {
114 return;
115 }
116 let raw = raw.trim();
117 if raw.starts_with("http://") || raw.starts_with("https://") || raw.starts_with("git@") {
119 return;
120 }
121 let mut p = PathBuf::from(raw);
122 if !p.is_absolute() {
123 p = self.working_dir.join(p);
124 }
125 let resolved = p.canonicalize().unwrap_or(p);
126 let mut current = if resolved.is_file() || resolved.extension().is_some() {
128 resolved
129 .parent()
130 .map(|p| p.to_path_buf())
131 .unwrap_or(resolved)
132 } else {
133 resolved
134 };
135 for _ in 0..MAX_ANCESTOR_WALK {
136 if self.loaded_dirs.contains(¤t) {
137 break;
138 }
139 if current.is_dir() {
140 candidates.insert(current.clone());
141 }
142 let parent = current.parent().map(|p| p.to_path_buf());
143 match parent {
144 Some(p) if p != current => current = p,
145 _ => break,
146 }
147 }
148 }
149
150 fn extract_paths_from_command(&self, cmd: &str, candidates: &mut HashSet<PathBuf>) {
151 for token in cmd.split_whitespace() {
152 if token.starts_with('-') {
153 continue;
154 }
155 if !token.contains('/') && !token.contains('.') {
156 continue;
157 }
158 self.add_path_candidate(token, candidates);
159 }
160 }
161
162 fn load_hints_for_directory(&mut self, directory: &Path) -> Option<String> {
163 self.loaded_dirs.insert(directory.to_path_buf());
166 for filename in HINT_FILENAMES {
167 let hint_path = directory.join(filename);
168 if !hint_path.is_file() {
169 continue;
170 }
171 let content = match std::fs::read_to_string(&hint_path) {
172 Ok(s) => s.trim().to_string(),
173 Err(_) => continue,
174 };
175 if content.is_empty() {
176 continue;
177 }
178 let total_chars = content.chars().count();
179 let truncated = if total_chars > MAX_HINT_CHARS {
180 let prefix: String = content.chars().take(MAX_HINT_CHARS).collect();
181 format!(
182 "{}\n\n[...truncated {}: {} chars total]",
183 prefix, filename, total_chars
184 )
185 } else {
186 content
187 };
188 let display = hint_path
189 .strip_prefix(&self.working_dir)
190 .map(|p| p.to_string_lossy().into_owned())
191 .unwrap_or_else(|_| hint_path.to_string_lossy().into_owned());
192 return Some(format!(
193 "[Subdirectory context discovered: {display}]\n{truncated}"
194 ));
195 }
196 None
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use serde_json::json;
204
205 fn tmp_root() -> PathBuf {
206 let dir = std::env::temp_dir().join(format!("microclaw_subhint_{}", uuid::Uuid::new_v4()));
207 std::fs::create_dir_all(&dir).unwrap();
208 dir.canonicalize().unwrap()
209 }
210
211 #[test]
212 fn loads_subdir_agents_md_on_first_touch() {
213 let root = tmp_root();
214 let sub = root.join("backend");
215 std::fs::create_dir_all(&sub).unwrap();
216 std::fs::write(sub.join("AGENTS.md"), "# Backend conventions\nUse async.").unwrap();
217 std::fs::write(sub.join("main.py"), "print('hi')").unwrap();
218
219 let mut tracker = SubdirectoryHintTracker::new(root.clone());
220 let hint = tracker
221 .check_tool_call("read_file", &json!({"path": "backend/main.py"}))
222 .expect("should emit a hint");
223 assert!(hint.contains("Backend conventions"));
224 assert!(hint.contains("AGENTS.md") || hint.contains("backend"));
225
226 let again = tracker.check_tool_call("read_file", &json!({"path": "backend/main.py"}));
228 assert!(again.is_none());
229
230 let _ = std::fs::remove_dir_all(&root);
231 }
232
233 #[test]
234 fn ignores_root_directory() {
235 let root = tmp_root();
236 std::fs::write(root.join("AGENTS.md"), "root context").unwrap();
237 std::fs::write(root.join("a.txt"), "data").unwrap();
238 let mut tracker = SubdirectoryHintTracker::new(root.clone());
239 let hint = tracker.check_tool_call("read_file", &json!({"path": "a.txt"}));
240 assert!(
241 hint.is_none(),
242 "root context should be loaded by system prompt, not hint"
243 );
244 let _ = std::fs::remove_dir_all(&root);
245 }
246
247 #[test]
248 fn walks_ancestors_until_hint_found() {
249 let root = tmp_root();
250 let deep = root.join("a/b/c");
251 std::fs::create_dir_all(&deep).unwrap();
252 std::fs::write(root.join("a/AGENTS.md"), "ancestor hint").unwrap();
253 std::fs::write(deep.join("file.txt"), "hi").unwrap();
254
255 let mut tracker = SubdirectoryHintTracker::new(root.clone());
256 let hint = tracker
257 .check_tool_call("read_file", &json!({"path": "a/b/c/file.txt"}))
258 .expect("should walk up to a/AGENTS.md");
259 assert!(hint.contains("ancestor hint"));
260 let _ = std::fs::remove_dir_all(&root);
261 }
262
263 #[test]
264 fn extracts_paths_from_apply_patch_headers() {
265 let root = tmp_root();
266 let sub = root.join("crates").join("engine");
267 std::fs::create_dir_all(&sub).unwrap();
268 std::fs::write(sub.join("AGENTS.md"), "engine rules").unwrap();
269 let mut tracker = SubdirectoryHintTracker::new(root.clone());
270 let hint = tracker.check_tool_call(
271 "apply_patch",
272 &serde_json::json!({"patch": "*** Begin Patch\n*** Update File: crates/engine/lib.rs\n-a\n+b\n*** End Patch"}),
273 );
274 assert!(hint.unwrap_or_default().contains("engine rules"));
275 let _ = std::fs::remove_dir_all(&root);
276 }
277
278 #[test]
279 fn extracts_paths_from_bash_command() {
280 let root = tmp_root();
281 let sub = root.join("frontend");
282 std::fs::create_dir_all(&sub).unwrap();
283 std::fs::write(sub.join("CLAUDE.md"), "frontend rules").unwrap();
284 std::fs::write(sub.join("page.tsx"), "x").unwrap();
285
286 let mut tracker = SubdirectoryHintTracker::new(root.clone());
287 let hint = tracker
288 .check_tool_call("bash", &json!({"command": "cat frontend/page.tsx"}))
289 .expect("should pull frontend hint from bash command");
290 assert!(hint.contains("frontend rules"));
291 let _ = std::fs::remove_dir_all(&root);
292 }
293
294 #[test]
295 fn truncates_oversized_hint() {
296 let root = tmp_root();
297 let sub = root.join("big");
298 std::fs::create_dir_all(&sub).unwrap();
299 let huge = "x".repeat(MAX_HINT_CHARS + 5_000);
300 std::fs::write(sub.join("AGENTS.md"), &huge).unwrap();
301 std::fs::write(sub.join("file"), "y").unwrap();
302
303 let mut tracker = SubdirectoryHintTracker::new(root.clone());
304 let hint = tracker
305 .check_tool_call("read_file", &json!({"path": "big/file"}))
306 .unwrap();
307 assert!(hint.contains("[...truncated"));
308 let _ = std::fs::remove_dir_all(&root);
309 }
310
311 #[test]
312 fn no_path_arg_returns_none() {
313 let root = tmp_root();
314 let mut tracker = SubdirectoryHintTracker::new(root.clone());
315 let hint = tracker.check_tool_call("web_search", &json!({"query": "rust"}));
316 assert!(hint.is_none());
317 let _ = std::fs::remove_dir_all(&root);
318 }
319
320 #[test]
321 fn url_paths_are_skipped() {
322 let root = tmp_root();
323 let mut tracker = SubdirectoryHintTracker::new(root.clone());
324 let hint = tracker.check_tool_call(
325 "web_fetch",
326 &json!({"url": "https://example.com/some/path"}),
327 );
328 assert!(hint.is_none());
329 let _ = std::fs::remove_dir_all(&root);
330 }
331}