Skip to main content

merry_coding/
project_rules.rs

1use merry_runtime::{ContextError, ProjectRules};
2use std::{
3    fs,
4    io::{self, ErrorKind, Read},
5    path::{Path, PathBuf},
6};
7use thiserror::Error;
8
9#[cfg(unix)]
10use std::os::unix::fs::OpenOptionsExt;
11
12/// Root project-rule file loaded by the coding composition.
13pub const ROOT_PROJECT_RULES_FILE: &str = "AGENTS.md";
14/// Maximum accepted root project-rule file size.
15pub const MAX_ROOT_PROJECT_RULES_BYTES: usize = 1024 * 1024;
16
17/// Loads the root `AGENTS.md` file without following a file symlink.
18pub fn load_root_project_rules(root: &Path) -> Result<Option<ProjectRules>, ProjectRulesLoadError> {
19    let canonical_root = merry_core::host_paths::canonicalize_clean(root).map_err(|source| {
20        ProjectRulesLoadError::ProjectRulesRead {
21            path: root.to_path_buf(),
22            source,
23        }
24    })?;
25    let path = canonical_root.join(ROOT_PROJECT_RULES_FILE);
26    let metadata = match fs::symlink_metadata(&path) {
27        Ok(metadata) => metadata,
28        Err(source) if source.kind() == ErrorKind::NotFound => return Ok(None),
29        Err(source) => return Err(ProjectRulesLoadError::ProjectRulesRead { path, source }),
30    };
31    if metadata.file_type().is_symlink() {
32        return Err(ProjectRulesLoadError::ProjectRulesPathDenied {
33            path,
34            reason: "symbolic links are not allowed",
35        });
36    }
37    if !metadata.is_file() {
38        return Err(ProjectRulesLoadError::ProjectRulesNotRegularFile { path });
39    }
40
41    let file = match open_root_project_rules(&path) {
42        Ok(file) => file,
43        Err(source) if is_symlink_open_error(&source) => {
44            return Err(ProjectRulesLoadError::ProjectRulesPathDenied {
45                path,
46                reason: "symbolic links are not allowed",
47            });
48        }
49        Err(source) => return Err(ProjectRulesLoadError::ProjectRulesRead { path, source }),
50    };
51    let metadata = match file.metadata() {
52        Ok(metadata) => metadata,
53        Err(source) => return Err(ProjectRulesLoadError::ProjectRulesRead { path, source }),
54    };
55    if !metadata.is_file() {
56        return Err(ProjectRulesLoadError::ProjectRulesNotRegularFile { path });
57    }
58    if metadata.len() > MAX_ROOT_PROJECT_RULES_BYTES as u64 {
59        return Err(ProjectRulesLoadError::ProjectRulesTooLarge {
60            path,
61            max_bytes: MAX_ROOT_PROJECT_RULES_BYTES,
62        });
63    }
64
65    let mut bytes = Vec::new();
66    if let Err(source) = file
67        .take(MAX_ROOT_PROJECT_RULES_BYTES as u64 + 1)
68        .read_to_end(&mut bytes)
69    {
70        return Err(ProjectRulesLoadError::ProjectRulesRead { path, source });
71    }
72    if bytes.len() > MAX_ROOT_PROJECT_RULES_BYTES {
73        return Err(ProjectRulesLoadError::ProjectRulesTooLarge {
74            path,
75            max_bytes: MAX_ROOT_PROJECT_RULES_BYTES,
76        });
77    }
78    let text = match String::from_utf8(bytes) {
79        Ok(text) => text,
80        Err(source) => {
81            return Err(ProjectRulesLoadError::ProjectRulesRead {
82                path,
83                source: io::Error::new(ErrorKind::InvalidData, source),
84            });
85        }
86    };
87    let text = if text.contains("\r\n") {
88        text.replace("\r\n", "\n")
89    } else {
90        text
91    };
92
93    ProjectRules::new(ROOT_PROJECT_RULES_FILE, text)
94        .map(Some)
95        .map_err(|source| ProjectRulesLoadError::ProjectRulesInvalid {
96            path,
97            source: Box::new(source),
98        })
99}
100
101/// Errors raised while loading the root project rules.
102#[derive(Debug, Error)]
103pub enum ProjectRulesLoadError {
104    /// The root path or rules file could not be read.
105    #[error("failed to read project rules at {path}: {source}")]
106    ProjectRulesRead {
107        /// Path involved in the failed read.
108        path: PathBuf,
109        /// Underlying filesystem error.
110        #[source]
111        source: io::Error,
112    },
113    /// The rules path was intentionally rejected as unsafe.
114    #[error("project rules path is denied at {path}: {reason}")]
115    ProjectRulesPathDenied {
116        /// Path rejected by the loader.
117        path: PathBuf,
118        /// Stable rejection reason.
119        reason: &'static str,
120    },
121    /// The rules path exists but is not a regular file.
122    #[error("project rules path is not a regular file: {path}")]
123    ProjectRulesNotRegularFile {
124        /// Path that was not a regular file.
125        path: PathBuf,
126    },
127    /// The rules file exceeds the bounded loader limit.
128    #[error("project rules at {path} exceed the {max_bytes}-byte limit")]
129    ProjectRulesTooLarge {
130        /// Oversized rules path.
131        path: PathBuf,
132        /// Maximum accepted size.
133        max_bytes: usize,
134    },
135    /// The rules content failed typed runtime validation.
136    #[error("invalid project rules at {path}: {source}")]
137    ProjectRulesInvalid {
138        /// Invalid rules path.
139        path: PathBuf,
140        /// Runtime validation error.
141        #[source]
142        source: Box<ContextError>,
143    },
144}
145
146#[cfg(unix)]
147fn open_root_project_rules(path: &Path) -> io::Result<fs::File> {
148    let mut options = fs::OpenOptions::new();
149    options
150        .read(true)
151        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
152    options.open(path)
153}
154
155#[cfg(not(unix))]
156fn open_root_project_rules(path: &Path) -> io::Result<fs::File> {
157    fs::OpenOptions::new().read(true).open(path)
158}
159
160#[cfg(unix)]
161fn is_symlink_open_error(source: &io::Error) -> bool {
162    source.raw_os_error() == Some(libc::ELOOP)
163}
164
165#[cfg(not(unix))]
166fn is_symlink_open_error(_: &io::Error) -> bool {
167    false
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn loads_root_agents_as_project_rules() {
176        let temp = tempfile::tempdir().expect("tempdir");
177        std::fs::write(temp.path().join("AGENTS.md"), "Use fixture rule.\n").expect("write rules");
178
179        let rules = load_root_project_rules(temp.path())
180            .expect("rules load")
181            .expect("rules exist");
182
183        assert_eq!(rules.source_path(), "AGENTS.md");
184        assert_eq!(rules.text(), "Use fixture rule.\n");
185    }
186
187    #[test]
188    fn loads_crlf_root_agents_as_normalized_project_rules() {
189        let temp = tempfile::tempdir().expect("tempdir");
190        std::fs::write(
191            temp.path().join("AGENTS.md"),
192            "Use CRLF rule.\r\nSecond line.\r\n",
193        )
194        .expect("write CRLF rules");
195
196        let rules = load_root_project_rules(temp.path())
197            .expect("CRLF rules load")
198            .expect("rules exist");
199
200        assert_eq!(rules.text(), "Use CRLF rule.\nSecond line.\n");
201    }
202
203    fn expected_rules_path(root: &Path) -> PathBuf {
204        merry_core::host_paths::canonicalize_clean(root)
205            .expect("canonical root")
206            .join("AGENTS.md")
207    }
208
209    #[test]
210    fn lone_carriage_return_remains_invalid() {
211        let temp = tempfile::tempdir().expect("tempdir");
212        let path = expected_rules_path(temp.path());
213        std::fs::write(&path, "Use rule.\rNot a CRLF line.").expect("write lone CR rules");
214
215        let error = load_root_project_rules(temp.path()).expect_err("lone CR rules reject");
216
217        assert!(matches!(
218            error,
219            ProjectRulesLoadError::ProjectRulesInvalid { path: actual, .. } if actual == path
220        ));
221    }
222
223    #[test]
224    fn missing_root_agents_adds_no_project_rules() {
225        let temp = tempfile::tempdir().expect("tempdir");
226        assert_eq!(
227            load_root_project_rules(temp.path()).expect("missing rules are allowed"),
228            None
229        );
230    }
231
232    #[test]
233    fn blank_root_agents_is_a_path_aware_validation_error() {
234        let temp = tempfile::tempdir().expect("tempdir");
235        let path = expected_rules_path(temp.path());
236        std::fs::write(&path, " \n\t").expect("write blank rules");
237
238        let error = load_root_project_rules(temp.path()).expect_err("blank rules reject");
239
240        assert!(matches!(
241            error,
242            ProjectRulesLoadError::ProjectRulesInvalid { path: actual, .. } if actual == path
243        ));
244    }
245
246    #[test]
247    fn directory_root_agents_is_not_a_regular_file() {
248        let temp = tempfile::tempdir().expect("tempdir");
249        let path = expected_rules_path(temp.path());
250        std::fs::create_dir(&path).expect("create directory at rules path");
251
252        let error =
253            load_root_project_rules(temp.path()).expect_err("directory cannot be read as rules");
254
255        assert!(matches!(
256            error,
257            ProjectRulesLoadError::ProjectRulesNotRegularFile { path: actual } if actual == path
258        ));
259    }
260
261    #[cfg(unix)]
262    #[test]
263    fn symlinked_root_agents_is_path_denied() {
264        let temp = tempfile::tempdir().expect("tempdir");
265        let workspace = temp.path().join("workspace");
266        std::fs::create_dir(&workspace).expect("create workspace");
267        let secret_path = temp.path().join("secret.txt");
268        std::fs::write(&secret_path, "outside workspace secret\n").expect("write secret");
269        let path = workspace.join("AGENTS.md");
270        std::os::unix::fs::symlink(&secret_path, &path).expect("symlink rules to secret");
271
272        let error = load_root_project_rules(&workspace).expect_err("symlink must be denied");
273
274        assert!(matches!(
275            error,
276            ProjectRulesLoadError::ProjectRulesPathDenied { path: actual, .. } if actual == path
277        ));
278    }
279
280    #[test]
281    fn oversized_root_agents_is_rejected() {
282        let temp = tempfile::tempdir().expect("tempdir");
283        let path = expected_rules_path(temp.path());
284        std::fs::write(&path, vec![b'a'; MAX_ROOT_PROJECT_RULES_BYTES + 1])
285            .expect("write oversized rules");
286
287        let error = load_root_project_rules(temp.path()).expect_err("oversized rules reject");
288
289        assert!(matches!(
290            error,
291            ProjectRulesLoadError::ProjectRulesTooLarge {
292                path: actual,
293                max_bytes: MAX_ROOT_PROJECT_RULES_BYTES,
294            } if actual == path
295        ));
296    }
297
298    #[test]
299    fn exact_max_size_root_agents_loads() {
300        let temp = tempfile::tempdir().expect("tempdir");
301        let path = temp.path().join("AGENTS.md");
302        let expected = "a".repeat(MAX_ROOT_PROJECT_RULES_BYTES);
303        std::fs::write(&path, &expected).expect("write max-sized rules");
304
305        let rules = load_root_project_rules(temp.path())
306            .expect("max-sized rules load")
307            .expect("rules exist");
308
309        assert_eq!(rules.text(), expected);
310    }
311
312    #[test]
313    fn invalid_utf8_root_agents_preserves_invalid_data_source() {
314        let temp = tempfile::tempdir().expect("tempdir");
315        let path = expected_rules_path(temp.path());
316        std::fs::write(&path, [0xff]).expect("write invalid UTF-8 rules");
317
318        let error = load_root_project_rules(temp.path()).expect_err("invalid UTF-8 rejects");
319
320        match error {
321            ProjectRulesLoadError::ProjectRulesRead {
322                path: actual,
323                source,
324            } => {
325                assert_eq!(actual, path);
326                assert_eq!(source.kind(), ErrorKind::InvalidData);
327            }
328            other => panic!("expected path-aware read error, got {other:?}"),
329        }
330    }
331}