Skip to main content

base/
rules.rs

1//! The rule index: its entries and the merge of several rule sources.
2//!
3//! Rules stay lazy: the model sees each document's name and first line and
4//! reads the rest on demand. Where the documents come from is the
5//! [`RuleProvider`](crate::interface::instruction_provider::RuleProvider)
6//! contract; the directory-backed sources are in `prompt_files`.
7
8use crate::interface::instruction_provider::RuleProvider;
9use std::path::PathBuf;
10use std::sync::Arc;
11
12/// One discovered rule document.
13#[derive(Debug, Clone, PartialEq)]
14pub struct RuleEntry {
15    /// Filename stem (e.g. "security" for `security.md`).
16    pub name: String,
17    /// First non-empty line of the file, `#`/whitespace-stripped — same
18    /// "fallback to first body line" convention as skills. Capped at
19    /// `prompt_files::MAX_RULE_DESCRIPTION_CHARS` regardless of how verbose the line is.
20    pub description: String,
21    /// Absolute path — always resolvable by the Read tool regardless of
22    /// which tier (project/scene/global) the file came from.
23    pub path: PathBuf,
24}
25
26/// Rule sources merged into one index: a later source's entry replaces an
27/// earlier one of the same name, and the result is sorted by name.
28#[derive(Clone)]
29pub struct RuleTiers {
30    sources: Vec<Arc<dyn RuleProvider>>,
31}
32
33impl RuleTiers {
34    pub fn new(sources: Vec<Arc<dyn RuleProvider>>) -> Self {
35        Self { sources }
36    }
37}
38
39impl RuleProvider for RuleTiers {
40    fn id(&self) -> &str {
41        "tiers"
42    }
43
44    fn rules(&self) -> Vec<RuleEntry> {
45        let mut by_name: std::collections::HashMap<String, RuleEntry> =
46            std::collections::HashMap::new();
47        for source in &self.sources {
48            for entry in source.rules() {
49                by_name.insert(entry.name.clone(), entry);
50            }
51        }
52        let mut entries: Vec<RuleEntry> = by_name.into_values().collect();
53        entries.sort_by(|a, b| a.name.cmp(&b.name));
54        entries
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::interface::instruction_provider::StaticRules;
62
63    fn entry(name: &str, description: &str, path: &str) -> RuleEntry {
64        RuleEntry {
65            name: name.into(),
66            description: description.into(),
67            path: PathBuf::from(path),
68        }
69    }
70
71    #[test]
72    fn the_merge_is_sorted_by_name() {
73        let tiers = RuleTiers::new(vec![Arc::new(StaticRules::new(
74            "s",
75            vec![entry("b", "", "/b.md"), entry("a", "", "/a.md")],
76        ))]);
77        let names: Vec<String> = tiers.rules().into_iter().map(|e| e.name).collect();
78        assert_eq!(names, ["a", "b"]);
79    }
80
81    /// The tier list is a composition of sources, not three paths written
82    /// into the discovery function — so a fourth source merges by the same
83    /// last-wins rule the tiers use.
84    #[test]
85    fn a_source_the_engine_does_not_own_takes_part_in_the_merge() {
86        let sources: Vec<Arc<dyn RuleProvider>> = vec![
87            Arc::new(StaticRules::new(
88                "service",
89                vec![RuleEntry {
90                    name: "testing".into(),
91                    description: "from the service".into(),
92                    path: PathBuf::from("/srv/testing.md"),
93                }],
94            )),
95            Arc::new(StaticRules::new(
96                "override",
97                vec![RuleEntry {
98                    name: "testing".into(),
99                    description: "from the later source".into(),
100                    path: PathBuf::from("/late/testing.md"),
101                }],
102            )),
103        ];
104        let entries = RuleTiers::new(sources).rules();
105        assert_eq!(entries.len(), 1);
106        assert_eq!(entries[0].description, "from the later source");
107    }
108}