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    ProjectRules::new(ROOT_PROJECT_RULES_FILE, text)
88        .map(Some)
89        .map_err(|source| ProjectRulesLoadError::ProjectRulesInvalid {
90            path,
91            source: Box::new(source),
92        })
93}
94
95/// Errors raised while loading the root project rules.
96#[derive(Debug, Error)]
97pub enum ProjectRulesLoadError {
98    /// The root path or rules file could not be read.
99    #[error("failed to read project rules at {path}: {source}")]
100    ProjectRulesRead {
101        /// Path involved in the failed read.
102        path: PathBuf,
103        /// Underlying filesystem error.
104        #[source]
105        source: io::Error,
106    },
107    /// The rules path was intentionally rejected as unsafe.
108    #[error("project rules path is denied at {path}: {reason}")]
109    ProjectRulesPathDenied {
110        /// Path rejected by the loader.
111        path: PathBuf,
112        /// Stable rejection reason.
113        reason: &'static str,
114    },
115    /// The rules path exists but is not a regular file.
116    #[error("project rules path is not a regular file: {path}")]
117    ProjectRulesNotRegularFile {
118        /// Path that was not a regular file.
119        path: PathBuf,
120    },
121    /// The rules file exceeds the bounded loader limit.
122    #[error("project rules at {path} exceed the {max_bytes}-byte limit")]
123    ProjectRulesTooLarge {
124        /// Oversized rules path.
125        path: PathBuf,
126        /// Maximum accepted size.
127        max_bytes: usize,
128    },
129    /// The rules content failed typed runtime validation.
130    #[error("invalid project rules at {path}: {source}")]
131    ProjectRulesInvalid {
132        /// Invalid rules path.
133        path: PathBuf,
134        /// Runtime validation error.
135        #[source]
136        source: Box<ContextError>,
137    },
138}
139
140#[cfg(unix)]
141fn open_root_project_rules(path: &Path) -> io::Result<fs::File> {
142    let mut options = fs::OpenOptions::new();
143    options
144        .read(true)
145        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
146    options.open(path)
147}
148
149#[cfg(not(unix))]
150fn open_root_project_rules(path: &Path) -> io::Result<fs::File> {
151    fs::OpenOptions::new().read(true).open(path)
152}
153
154#[cfg(unix)]
155fn is_symlink_open_error(source: &io::Error) -> bool {
156    source.raw_os_error() == Some(libc::ELOOP)
157}
158
159#[cfg(not(unix))]
160fn is_symlink_open_error(_: &io::Error) -> bool {
161    false
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn loads_root_agents_as_project_rules() {
170        let temp = tempfile::tempdir().expect("tempdir");
171        std::fs::write(temp.path().join("AGENTS.md"), "Use fixture rule.\n").expect("write rules");
172
173        let rules = load_root_project_rules(temp.path())
174            .expect("rules load")
175            .expect("rules exist");
176
177        assert_eq!(rules.source_path(), "AGENTS.md");
178        assert_eq!(rules.text(), "Use fixture rule.\n");
179    }
180
181    #[test]
182    fn loads_crlf_root_agents_as_normalized_project_rules() {
183        let temp = tempfile::tempdir().expect("tempdir");
184        std::fs::write(
185            temp.path().join("AGENTS.md"),
186            "Use CRLF rule.\r\nSecond line.\r\n",
187        )
188        .expect("write CRLF rules");
189
190        let rules = load_root_project_rules(temp.path())
191            .expect("CRLF rules load")
192            .expect("rules exist");
193
194        assert_eq!(rules.text(), "Use CRLF rule.\nSecond line.\n");
195    }
196
197    fn expected_rules_path(root: &Path) -> PathBuf {
198        merry_core::host_paths::canonicalize_clean(root)
199            .expect("canonical root")
200            .join("AGENTS.md")
201    }
202
203    #[test]
204    fn bare_carriage_return_and_controls_are_sanitized_and_control_only_rejects() {
205        let temp = tempfile::tempdir().expect("tempdir");
206        let path = expected_rules_path(temp.path());
207        std::fs::write(&path, "Use rule.\rSecond line.\x07\0").expect("write dirty rules");
208
209        let rules = load_root_project_rules(temp.path())
210            .expect("dirty rules sanitize")
211            .expect("rules exist");
212        assert_eq!(rules.text(), "Use rule.\nSecond line.");
213
214        std::fs::write(&path, "\x07\0").expect("write control-only rules");
215        let error = load_root_project_rules(temp.path()).expect_err("control-only rules reject");
216        assert!(matches!(
217            error,
218            ProjectRulesLoadError::ProjectRulesInvalid { path: actual, .. } if actual == path
219        ));
220    }
221
222    #[test]
223    fn missing_root_agents_adds_no_project_rules() {
224        let temp = tempfile::tempdir().expect("tempdir");
225        assert_eq!(
226            load_root_project_rules(temp.path()).expect("missing rules are allowed"),
227            None
228        );
229    }
230
231    #[test]
232    fn blank_root_agents_is_a_path_aware_validation_error() {
233        let temp = tempfile::tempdir().expect("tempdir");
234        let path = expected_rules_path(temp.path());
235        std::fs::write(&path, " \n\t").expect("write blank rules");
236
237        let error = load_root_project_rules(temp.path()).expect_err("blank rules reject");
238
239        assert!(matches!(
240            error,
241            ProjectRulesLoadError::ProjectRulesInvalid { path: actual, .. } if actual == path
242        ));
243    }
244
245    #[test]
246    fn directory_root_agents_is_not_a_regular_file() {
247        let temp = tempfile::tempdir().expect("tempdir");
248        let path = expected_rules_path(temp.path());
249        std::fs::create_dir(&path).expect("create directory at rules path");
250
251        let error =
252            load_root_project_rules(temp.path()).expect_err("directory cannot be read as rules");
253
254        assert!(matches!(
255            error,
256            ProjectRulesLoadError::ProjectRulesNotRegularFile { path: actual } if actual == path
257        ));
258    }
259
260    #[cfg(unix)]
261    #[test]
262    fn symlinked_root_agents_is_path_denied() {
263        let temp = tempfile::tempdir().expect("tempdir");
264        let workspace = temp.path().join("workspace");
265        std::fs::create_dir(&workspace).expect("create workspace");
266        let secret_path = temp.path().join("secret.txt");
267        std::fs::write(&secret_path, "outside workspace secret\n").expect("write secret");
268        let path = workspace.join("AGENTS.md");
269        std::os::unix::fs::symlink(&secret_path, &path).expect("symlink rules to secret");
270
271        let error = load_root_project_rules(&workspace).expect_err("symlink must be denied");
272
273        assert!(matches!(
274            error,
275            ProjectRulesLoadError::ProjectRulesPathDenied { path: actual, .. } if actual == path
276        ));
277    }
278
279    #[test]
280    fn oversized_root_agents_is_rejected() {
281        let temp = tempfile::tempdir().expect("tempdir");
282        let path = expected_rules_path(temp.path());
283        std::fs::write(&path, vec![b'a'; MAX_ROOT_PROJECT_RULES_BYTES + 1])
284            .expect("write oversized rules");
285
286        let error = load_root_project_rules(temp.path()).expect_err("oversized rules reject");
287
288        assert!(matches!(
289            error,
290            ProjectRulesLoadError::ProjectRulesTooLarge {
291                path: actual,
292                max_bytes: MAX_ROOT_PROJECT_RULES_BYTES,
293            } if actual == path
294        ));
295    }
296
297    #[test]
298    fn exact_max_size_root_agents_loads() {
299        let temp = tempfile::tempdir().expect("tempdir");
300        let path = temp.path().join("AGENTS.md");
301        let expected = "a".repeat(MAX_ROOT_PROJECT_RULES_BYTES);
302        std::fs::write(&path, &expected).expect("write max-sized rules");
303
304        let rules = load_root_project_rules(temp.path())
305            .expect("max-sized rules load")
306            .expect("rules exist");
307
308        assert_eq!(rules.text(), expected);
309    }
310
311    #[test]
312    fn invalid_utf8_root_agents_preserves_invalid_data_source() {
313        let temp = tempfile::tempdir().expect("tempdir");
314        let path = expected_rules_path(temp.path());
315        std::fs::write(&path, [0xff]).expect("write invalid UTF-8 rules");
316
317        let error = load_root_project_rules(temp.path()).expect_err("invalid UTF-8 rejects");
318
319        match error {
320            ProjectRulesLoadError::ProjectRulesRead {
321                path: actual,
322                source,
323            } => {
324                assert_eq!(actual, path);
325                assert_eq!(source.kind(), ErrorKind::InvalidData);
326            }
327            other => panic!("expected path-aware read error, got {other:?}"),
328        }
329    }
330}