Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / rules.rs

rules.rs256 lines · 9.1 KiBRaw
1//! `AGENTS.md` auto-load: per-directory rules fetched through the runner.
2//!
3//! Rules live in `tasks.rules_json` (path → content, or null for "no file" so
4//! missing files are never re-read) and appear in the system prompt sorted by
5//! path, after root/module rules and before plan/todos. They survive
6//! park/resume (DB) and are never re-read.
7//!
8//! Entry points:
9//! * [`load_session_rules`] — at session start: root `AGENTS.md`,
10//! `<scope>/AGENTS.md`, and `.llms/repo-map.md` when present.
11//! * [`ensure_rules_for_path`] — on any tool touching a path: walk ancestor
12//! dirs root → target dir and `runner.read` each `<dir>/AGENTS.md` not yet
13//! in `rules_json`. Returns the newly loaded paths for the tool-result note.
14//! The parallel worker's git/find tools call this too.
15//!
16//! Caps: 16 KiB per file, 48 KiB total (each truncated with a note).
17
18use std::collections::BTreeMap;
19
20use crate::agent::DriverCtx;
21
22/// Max bytes kept per rules file.
23pub const RULES_PER_FILE_BYTES: usize = 16 * 1024;
24/// Max total bytes across all stored rules.
25pub const RULES_TOTAL_BYTES: usize = 48 * 1024;
26
27/// Sorted `(path, content)` pairs of loaded (non-null) rules for the system
28/// prompt. `rules_json` may be absent (no rules yet).
29pub fn sorted_loaded_rules(rules_json: Option<&str>) -> Vec<(String, String)> {
30 let Some(raw) = rules_json else {
31 return Vec::new();
32 };
33 let map: BTreeMap<String, Option<String>> = match serde_json::from_str(raw) {
34 Ok(m) => m,
35 Err(_) => return Vec::new(),
36 };
37 map.into_iter()
38 .filter_map(|(p, c)| c.map(|content| (p, content)))
39 .collect()
40}
41
42/// Current total bytes of stored (non-null) rule contents.
43#[allow(dead_code)]
44fn stored_bytes(rules_json: Option<&str>) -> usize {
45 sorted_loaded_rules(rules_json)
46 .iter()
47 .map(|(_, c)| c.len())
48 .sum()
49}
50
51/// Truncate one rules file to the per-file cap with a note.
52fn cap_file(content: &str, path: &str) -> String {
53 if content.len() <= RULES_PER_FILE_BYTES {
54 return content.to_string();
55 }
56 let mut end = RULES_PER_FILE_BYTES;
57 while end > 0 && !content.is_char_boundary(end) {
58 end -= 1;
59 }
60 format!(
61 "{}\n… [rules file {path} capped at {RULES_PER_FILE_BYTES} bytes] …",
62 &content[..end]
63 )
64}
65
66/// Ancestor directories from the repo root down to (and including) the target
67/// file's parent dir. `"notes/sub/file.txt"` → `["notes", "notes/sub"]`.
68/// Root-level files (`"AGENTS.md"`) → `[]`. Pure; unit-tested.
69pub fn ancestor_dirs(path: &str) -> Vec<String> {
70 let p = path.trim_start_matches('/');
71 let Some(slash) = p.rfind('/') else {
72 return Vec::new();
73 };
74 let dir = &p[..slash];
75 if dir.is_empty() {
76 return Vec::new();
77 }
78 let mut out = Vec::new();
79 let mut cur = String::new();
80 for seg in dir.split('/') {
81 if seg.is_empty() || seg == "." {
82 continue;
83 }
84 if seg == ".." {
85 continue; // paths are validated repo-relative elsewhere; skip
86 }
87 if !cur.is_empty() {
88 cur.push('/');
89 }
90 cur.push_str(seg);
91 out.push(cur.clone());
92 }
93 out
94}
95
96/// Read `rules_json` paths already known (loaded or known-missing).
97fn known_paths(store: &crate::store::Store, task_id: i64) -> BTreeMap<String, Option<String>> {
98 let task = store.get_task(task_id).ok().flatten();
99 let raw = task.as_ref().and_then(|t| t.rules_json.as_deref());
100 match raw {
101 Some(s) => serde_json::from_str(s).unwrap_or_default(),
102 None => BTreeMap::new(),
103 }
104}
105
106/// At session start: load root `AGENTS.md`, `<scope>/AGENTS.md`, and
107/// `.llms/repo-map.md` when present. Returns `(root_rules, module_rules)`.
108/// (The driver still needs these two separately for the prompt's fixed root /
109/// module sections; the same contents are also merged into `rules_json` for
110/// the sorted `extra_rules` section — dedupe is by path there.)
111///
112/// Missing files map to `None` and are stored as null so they are not re-read.
113pub async fn load_session_rules(
114 ctx: &DriverCtx,
115 task_id: i64,
116 slot: u32,
117 module_scope: &str,
118) -> (Option<String>, Option<String>) {
119 let dir = module_scope.replace(':', "/");
120 let dir = dir.trim_matches('/');
121 let module_path = if dir.is_empty() {
122 "AGENTS.md".to_string()
123 } else {
124 format!("{dir}/AGENTS.md")
125 };
126 let known = known_paths(&ctx.store, task_id);
127 let mut fresh: BTreeMap<String, Option<String>> = BTreeMap::new();
128 let mut root_rules: Option<String> = None;
129 let mut module_rules: Option<String> = None;
130 for path in ["AGENTS.md", module_path.as_str(), ".llms/repo-map.md"] {
131 if known.contains_key(path) {
132 let v = known.get(path).cloned().flatten();
133 if path == "AGENTS.md" {
134 root_rules = v.clone();
135 }
136 if path == module_path.as_str() {
137 module_rules = v.clone();
138 }
139 continue;
140 }
141 let content = ctx
142 .runner
143 .read(slot, path, None, Some(400))
144 .await
145 .ok()
146 .map(|r| cap_file(&r.content, path));
147 if path == "AGENTS.md" {
148 root_rules = content.clone();
149 }
150 if path == module_path.as_str() {
151 module_rules = content.clone();
152 }
153 fresh.insert(path.to_string(), content);
154 }
155 // Merge with the total cap enforced (session files count too).
156 let mut merged = known;
157 let mut total_bytes: usize = merged.values().flatten().map(|c| c.len()).sum();
158 for (path, content) in fresh {
159 if merged.contains_key(&path) {
160 continue;
161 }
162 match content {
163 None => {
164 merged.insert(path, None);
165 }
166 Some(c) => {
167 if total_bytes >= RULES_TOTAL_BYTES {
168 merged.insert(
169 path.clone(),
170 Some(format!(
171 "… [rules total cap {RULES_TOTAL_BYTES} bytes reached; {path} skipped] …"
172 )),
173 );
174 continue;
175 }
176 let mut c = c;
177 let room = RULES_TOTAL_BYTES.saturating_sub(total_bytes);
178 if c.len() > room {
179 let mut end = room;
180 while end > 0 && !c.is_char_boundary(end) {
181 end -= 1;
182 }
183 c.truncate(end);
184 c.push_str("\n… [rules total cap reached; truncated] …");
185 }
186 total_bytes += c.len();
187 merged.insert(path, Some(c));
188 }
189 }
190 }
191 // Persist (merge_rules keeps existing entries on conflict).
192 let _ = ctx.store.merge_rules(task_id, &merged);
193 (root_rules, module_rules)
194}
195
196/// On any tool touching `path`: walk ancestor dirs root → target dir and
197/// `runner.read` each `<dir>/AGENTS.md` not yet in `rules_json` (store null
198/// when missing so it is not re-read). Returns the newly loaded paths for the
199/// tool-result `[loaded rules: …]` note.
200///
201/// `slot` is the runner slot id (same as the worker index). Exposed `pub` for
202/// the parallel worker's git/find tools.
203pub async fn ensure_rules_for_path(
204 ctx: &DriverCtx,
205 task_id: i64,
206 slot: u32,
207 path: &str,
208) -> Vec<String> {
209 let known = known_paths(&ctx.store, task_id);
210 let mut total_bytes: usize = known.values().flatten().map(|c| c.len()).sum();
211 let mut fresh: BTreeMap<String, Option<String>> = BTreeMap::new();
212 let mut newly: Vec<String> = Vec::new();
213 for dir in ancestor_dirs(path) {
214 let rules_path = format!("{dir}/AGENTS.md");
215 if known.contains_key(&rules_path) || fresh.contains_key(&rules_path) {
216 continue;
217 }
218 let content = ctx
219 .runner
220 .read(slot, &rules_path, None, Some(400))
221 .await
222 .ok()
223 .map(|r| cap_file(&r.content, &rules_path));
224 match content {
225 None => {
226 fresh.insert(rules_path.clone(), None);
227 }
228 Some(c) => {
229 if total_bytes >= RULES_TOTAL_BYTES {
230 fresh.insert(
231 rules_path.clone(),
232 Some("… [rules total cap reached; skipped] …".to_string()),
233 );
234 } else {
235 let mut c = c;
236 let room = RULES_TOTAL_BYTES.saturating_sub(total_bytes);
237 if c.len() > room {
238 let mut end = room;
239 while end > 0 && !c.is_char_boundary(end) {
240 end -= 1;
241 }
242 c.truncate(end);
243 c.push_str("\n… [rules total cap reached; truncated] …");
244 }
245 total_bytes += c.len();
246 fresh.insert(rules_path.clone(), Some(c));
247 }
248 newly.push(rules_path.clone());
249 }
250 }
251 }
252 if !fresh.is_empty() {
253 let _ = ctx.store.merge_rules(task_id, &fresh);
254 }
255 newly
256}