Skip to main content

rust_anything/
rules.rs

1//! Port rules: behavior the port must keep exactly, learned from the user's corrections.
2//!
3//! They live in `<repo>/rust/RULES.md`, one `- rule` bullet each, next to the port's decisions
4//! and map, and every agent prompt rust-anything writes includes them, so a correction made once
5//! reaches every later unit and every agent.
6
7use std::path::{Path, PathBuf};
8
9use anyhow::{Context, Result};
10use serde::Serialize;
11
12use crate::bridge::{MANIFEST, Manifest};
13
14pub const FILE: &str = "rust/RULES.md";
15
16const HEADER: &str = "# Port rules\n\n\
17Behavior the port must keep exactly, learned from corrections. Every agent prompt rust-anything \
18writes includes these rules. Edit them by hand, or add one with `rust-anything rules --add`.\n\n";
19
20#[derive(Debug, Serialize)]
21pub struct RulesOutcome {
22    pub file: PathBuf,
23    pub rules: Vec<String>,
24    pub added: Vec<String>,
25    /// Rules given to add that the file already had.
26    #[serde(skip_serializing_if = "Vec::is_empty")]
27    pub skipped: Vec<String>,
28}
29
30/// The repository a path stands for: a crate folder made by `bridge` stands for its original's
31/// repository, any other folder for itself.
32pub fn repo_of(path: &Path) -> PathBuf {
33    if path.join(MANIFEST).is_file()
34        && let Ok(m) = Manifest::load(path)
35    {
36        return m.root;
37    }
38    path.to_path_buf()
39}
40
41/// The rules in the repository's rules file, in order; none when it does not exist.
42pub fn load(root: &Path) -> Vec<String> {
43    let text = std::fs::read_to_string(repo_of(root).join(FILE)).unwrap_or_default();
44    text.lines()
45        .filter_map(|l| l.trim_start().strip_prefix("- "))
46        .map(|r| r.trim().to_string())
47        .filter(|r| !r.is_empty())
48        .collect()
49}
50
51/// Appends each rule that is not in the file yet, creating the file when needed. With no rules
52/// to add it only reads.
53pub fn add(root: &Path, rules: &[String]) -> Result<RulesOutcome> {
54    let file = repo_of(root).join(FILE);
55    let mut have = load(root);
56    let mut added = Vec::new();
57    let mut skipped = Vec::new();
58    for rule in rules {
59        let rule = rule.split_whitespace().collect::<Vec<_>>().join(" ");
60        anyhow::ensure!(!rule.is_empty(), "a rule needs text");
61        if have.contains(&rule) {
62            skipped.push(rule);
63        } else {
64            have.push(rule.clone());
65            added.push(rule);
66        }
67    }
68    if !added.is_empty() {
69        let mut text = std::fs::read_to_string(&file).unwrap_or_else(|_| HEADER.to_string());
70        if !text.is_empty() && !text.ends_with('\n') {
71            text.push('\n');
72        }
73        for rule in &added {
74            text.push_str(&format!("- {rule}\n"));
75        }
76        if let Some(dir) = file.parent() {
77            std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
78        }
79        std::fs::write(&file, text).with_context(|| format!("writing {}", file.display()))?;
80    }
81    Ok(RulesOutcome {
82        file,
83        rules: have,
84        added,
85        skipped,
86    })
87}
88
89/// The `## Project rules` section of an agent prompt; empty when the repository has none.
90pub fn section(root: &Path) -> String {
91    let rules = load(root);
92    if rules.is_empty() {
93        return String::new();
94    }
95    let mut out = format!(
96        "## Project rules\n\nFrom `{FILE}`: behavior the port must keep exactly, learned from \
97         corrections. Follow every one.\n\n"
98    );
99    for rule in rules {
100        out.push_str(&format!("- {rule}\n"));
101    }
102    out
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn rules_are_bullets_and_anything_else_is_kept_as_written() {
111        let dir = crate::app::temp_dir("rules-load").unwrap();
112        std::fs::create_dir_all(dir.join("rust")).unwrap();
113        std::fs::write(
114            dir.join(FILE),
115            "# Port rules\n\nSome text.\n\n- keep trailing spaces\n  - nested still counts\n-\n",
116        )
117        .unwrap();
118        assert_eq!(load(&dir), ["keep trailing spaces", "nested still counts"]);
119        let out = add(&dir, &["one  more\nrule".into()]).unwrap();
120        let text = std::fs::read_to_string(dir.join(FILE)).unwrap();
121        std::fs::remove_dir_all(&dir).unwrap();
122        assert_eq!(out.added, ["one more rule"]);
123        assert!(text.starts_with("# Port rules\n\nSome text."), "{text}");
124        assert!(text.ends_with("-\n- one more rule\n"), "{text}");
125    }
126
127    #[test]
128    fn no_rules_no_section() {
129        let dir = crate::app::temp_dir("rules-none").unwrap();
130        assert_eq!(section(&dir), "");
131        let out = add(&dir, &[]).unwrap();
132        assert!(out.rules.is_empty());
133        assert!(!dir.join(FILE).exists(), "reading writes nothing");
134        assert!(add(&dir, &["  ".into()]).is_err());
135        std::fs::remove_dir_all(&dir).unwrap();
136    }
137}