Skip to main content

memstead_base/mem_management/
mod.rs

1//! Compiled lifecycle-policy rule sets — first-match-wins glob lookup
2//! over the `[[mem_management.create]]` /
3//! `[[mem_management.delete]]` arrays surfaced in `workspace.toml`.
4//!
5//! The data carriers ([`crate::workspace::CreateRuleSetting`],
6//! [`crate::workspace::DeleteRuleSetting`]) live with the workspace
7//! types in [`crate::workspace`]; this module owns the *compiled*
8//! matcher view that handlers call to decide whether a candidate
9//! mem path matches an operator-allowed rule.
10//!
11//! Each rule's pattern is a gitignore-style glob: `*` does not cross
12//! `/`; `**` matches zero-or-more path segments. Matching is
13//! case-sensitive, no normalization. The matcher targets the composed
14//! candidate `<path>/<name>` (the mem's full hierarchical branch
15//! path on the mem-repo) so rules can scope to a directory under
16//! the registry tree without separate path-glob plumbing. Flat-layout
17//! mems pass their leaf name as the candidate.
18//!
19//! The lifecycle orchestrators (`create_mem`, `delete_mem`, their
20//! params/responses, the shared `NOTE_MAX_LEN` cap, the
21//! `validate_mem_path` helper) live in the [`lifecycle`] submodule and
22//! are re-exported here; the matcher primitives below are what
23//! [`crate::Engine::cross_mem_link_allowed`] synthesises a
24//! [`CreateRuleSet`] from on multi-folder workspaces.
25
26pub mod lifecycle;
27pub use lifecycle::*;
28
29use std::path::Path;
30
31use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
32use thiserror::Error;
33
34use crate::workspace::{CreateRuleSetting, DeleteRuleSetting};
35
36/// Construction-time error for the matcher constructors. The
37/// `ParseEntry` variant names the offending entry string so callers
38/// can surface an actionable `INVALID_INPUT` envelope without
39/// re-deriving which entry blew up.
40#[derive(Debug, Error)]
41pub enum MatcherSetError {
42    #[error("invalid glob pattern {entry:?}: {source}")]
43    ParseEntry {
44        entry: String,
45        #[source]
46        source: globset::Error,
47    },
48    #[error("glob set build failed: {0}")]
49    Build(#[source] globset::Error),
50}
51
52/// Compiled set of allowlist globs with gitignore semantics.
53///
54/// The `patterns` vector preserves the original strings (used by
55/// `memstead_health` and error envelopes). The `set` is the compiled form
56/// used for `matches`. Empty-input construction is valid and produces
57/// a matcher that rejects every candidate — the natural default when
58/// `[mem_management]` is absent.
59#[derive(Debug, Clone)]
60pub struct MatcherSet {
61    patterns: Vec<String>,
62    set: GlobSet,
63}
64
65impl MatcherSet {
66    /// Compile a list of glob strings. Empty input is valid. A
67    /// malformed entry returns `ParseEntry` naming the entry; `Build`
68    /// covers residual post-assembly failures.
69    pub fn new<I, S>(entries: I) -> Result<Self, MatcherSetError>
70    where
71        I: IntoIterator<Item = S>,
72        S: AsRef<str>,
73    {
74        let mut builder = GlobSetBuilder::new();
75        let mut patterns: Vec<String> = Vec::new();
76        for entry in entries {
77            let entry_str = entry.as_ref();
78            let glob: Glob = GlobBuilder::new(entry_str)
79                .literal_separator(true)
80                .build()
81                .map_err(|source| MatcherSetError::ParseEntry {
82                    entry: entry_str.to_string(),
83                    source,
84                })?;
85            builder.add(glob);
86            patterns.push(entry_str.to_string());
87        }
88        let set = builder.build().map_err(MatcherSetError::Build)?;
89        Ok(Self { patterns, set })
90    }
91
92    /// Test whether `candidate` matches any compiled glob. The
93    /// caller passes a path-like string; the matcher compares as-is —
94    /// no normalization, no canonicalization, no cross-boundary
95    /// widening.
96    pub fn matches(&self, candidate: &Path) -> bool {
97        self.set.is_match(candidate)
98    }
99
100    /// Original glob strings in input order. Consumed by health
101    /// surfaces and `MEM_PATH_NOT_ALLOWED` envelopes.
102    pub fn patterns(&self) -> &[String] {
103        &self.patterns
104    }
105
106    /// `true` when no globs were compiled. Lifecycle handlers
107    /// short-circuit with a `reason: "no_allowlist_configured"` detail
108    /// instead of the generic "no match" message.
109    pub fn is_empty(&self) -> bool {
110        self.patterns.is_empty()
111    }
112}
113
114impl Default for MatcherSet {
115    fn default() -> Self {
116        Self::new::<_, &str>(std::iter::empty::<&str>()).expect("empty MatcherSet is always valid")
117    }
118}
119
120/// Compiled `[[mem_management.create]]` rule set. Each rule is a
121/// pre-built `globset::Glob` plus the raw [`CreateRuleSetting`]. The
122/// underlying `GlobSet` carries the same globs in declaration order
123/// so [`Self::first_match`] resolves to the first-listed rule whose
124/// glob matches.
125#[derive(Debug, Clone)]
126pub struct CreateRuleSet {
127    rules: Vec<CreateRuleSetting>,
128    set: GlobSet,
129}
130
131/// Compiled `[[mem_management.delete]]` rule set. Same first-match
132/// semantics as [`CreateRuleSet`], minus the schema dimension.
133#[derive(Debug, Clone)]
134pub struct DeleteRuleSet {
135    rules: Vec<DeleteRuleSetting>,
136    set: GlobSet,
137}
138
139impl CreateRuleSet {
140    /// Compile each rule's glob with `literal_separator(true)`. A
141    /// malformed pattern surfaces as
142    /// [`MatcherSetError::ParseEntry`] naming the offending entry so
143    /// `Engine::init` can produce an `INVALID_INPUT` envelope without
144    /// half-constructing.
145    pub fn new(rules: Vec<CreateRuleSetting>) -> Result<Self, MatcherSetError> {
146        let mut builder = GlobSetBuilder::new();
147        for r in &rules {
148            let glob = GlobBuilder::new(&r.pattern)
149                .literal_separator(true)
150                .build()
151                .map_err(|source| MatcherSetError::ParseEntry {
152                    entry: r.pattern.clone(),
153                    source,
154                })?;
155            builder.add(glob);
156        }
157        let set = builder.build().map_err(MatcherSetError::Build)?;
158        Ok(Self { rules, set })
159    }
160
161    /// First rule whose glob matches `candidate`, in declaration
162    /// order. `None` when no rule matches; callers check
163    /// [`Self::is_empty`] separately to distinguish "no rules
164    /// configured" from "rules configured but none match".
165    pub fn first_match(&self, candidate: &Path) -> Option<&CreateRuleSetting> {
166        let matched = self.set.matches(candidate);
167        matched.into_iter().next().map(|i| &self.rules[i])
168    }
169
170    /// Raw rule list in declaration order. Consumed by `memstead_overview`
171    /// when surfacing the lifecycle-namespaces section.
172    pub fn rules(&self) -> &[CreateRuleSetting] {
173        &self.rules
174    }
175
176    pub fn is_empty(&self) -> bool {
177        self.rules.is_empty()
178    }
179
180    /// Convenience: pattern strings in declaration order. Useful for
181    /// tests and diagnostic surfaces.
182    pub fn patterns(&self) -> Vec<String> {
183        self.rules.iter().map(|r| r.pattern.clone()).collect()
184    }
185
186    /// Convenience: any-rule match against `candidate`.
187    pub fn matches(&self, candidate: &Path) -> bool {
188        self.first_match(candidate).is_some()
189    }
190}
191
192impl DeleteRuleSet {
193    pub fn new(rules: Vec<DeleteRuleSetting>) -> Result<Self, MatcherSetError> {
194        let mut builder = GlobSetBuilder::new();
195        for r in &rules {
196            let glob = GlobBuilder::new(&r.pattern)
197                .literal_separator(true)
198                .build()
199                .map_err(|source| MatcherSetError::ParseEntry {
200                    entry: r.pattern.clone(),
201                    source,
202                })?;
203            builder.add(glob);
204        }
205        let set = builder.build().map_err(MatcherSetError::Build)?;
206        Ok(Self { rules, set })
207    }
208
209    pub fn first_match(&self, candidate: &Path) -> Option<&DeleteRuleSetting> {
210        let matched = self.set.matches(candidate);
211        matched.into_iter().next().map(|i| &self.rules[i])
212    }
213
214    pub fn rules(&self) -> &[DeleteRuleSetting] {
215        &self.rules
216    }
217
218    pub fn is_empty(&self) -> bool {
219        self.rules.is_empty()
220    }
221
222    pub fn patterns(&self) -> Vec<String> {
223        self.rules.iter().map(|r| r.pattern.clone()).collect()
224    }
225
226    pub fn matches(&self, candidate: &Path) -> bool {
227        self.first_match(candidate).is_some()
228    }
229}
230
231impl Default for CreateRuleSet {
232    fn default() -> Self {
233        Self::new(Vec::new()).expect("empty rule set always compiles")
234    }
235}
236
237impl Default for DeleteRuleSet {
238    fn default() -> Self {
239        Self::new(Vec::new()).expect("empty rule set always compiles")
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use std::path::Path;
247
248    fn cr(pattern: &str, schemas: &[&str]) -> CreateRuleSetting {
249        CreateRuleSetting {
250            pattern: pattern.to_string(),
251            schemas: schemas.iter().map(|s| s.to_string()).collect(),
252            default_cross_links: None,
253        }
254    }
255
256    fn dr(pattern: &str) -> DeleteRuleSetting {
257        DeleteRuleSetting {
258            pattern: pattern.to_string(),
259        }
260    }
261
262    // ---- MatcherSet primitives -------------------------------------
263
264    #[test]
265    fn empty_matcher_rejects_everything() {
266        let m = MatcherSet::new::<_, &str>(std::iter::empty::<&str>()).unwrap();
267        assert!(m.is_empty());
268        assert_eq!(m.patterns().len(), 0);
269        assert!(!m.matches(Path::new("anything")));
270    }
271
272    #[test]
273    fn single_segment_star_does_not_cross_slash() {
274        let m = MatcherSet::new(["memstead/*"]).unwrap();
275        assert!(m.matches(Path::new("memstead/engine")));
276        assert!(!m.matches(Path::new("memstead/engine/nested")));
277        assert!(!m.matches(Path::new("other/engine")));
278    }
279
280    #[test]
281    fn double_star_matches_any_segments() {
282        let m = MatcherSet::new(["memstead/**"]).unwrap();
283        assert!(m.matches(Path::new("memstead/engine")));
284        assert!(m.matches(Path::new("memstead/engine/nested")));
285        assert!(!m.matches(Path::new("other/engine")));
286    }
287
288    #[test]
289    fn malformed_entry_returns_parse_entry_error() {
290        let err = MatcherSet::new(["[unclosed"]).unwrap_err();
291        match err {
292            MatcherSetError::ParseEntry { entry, .. } => assert_eq!(entry, "[unclosed"),
293            MatcherSetError::Build(_) => panic!("expected ParseEntry, got Build"),
294        }
295    }
296
297    #[test]
298    fn case_sensitive_by_default() {
299        let m = MatcherSet::new(["MEMSTEAD/*"]).unwrap();
300        assert!(m.matches(Path::new("MEMSTEAD/foo")));
301        assert!(!m.matches(Path::new("memstead/foo")));
302    }
303
304    // ---- CreateRuleSet ---------------------------------------------
305
306    #[test]
307    fn empty_rule_set_matches_nothing() {
308        let cs = CreateRuleSet::new(vec![]).unwrap();
309        assert!(cs.is_empty());
310        assert!(cs.first_match(Path::new("anything")).is_none());
311    }
312
313    #[test]
314    fn first_match_resolves_in_declaration_order() {
315        // `planning/plan-*` is more specific than `planning/**` and
316        // appears first; both globs match `planning/plan-foo` but the
317        // resolver returns the first-listed.
318        let cs = CreateRuleSet::new(vec![
319            cr("planning/plan-*", &["default@1.0.0"]),
320            cr("planning/**", &["*"]),
321        ])
322        .unwrap();
323        let m = cs.first_match(Path::new("planning/plan-foo")).unwrap();
324        assert_eq!(m.pattern, "planning/plan-*");
325    }
326
327    #[test]
328    fn second_rule_picked_when_first_does_not_match() {
329        let cs = CreateRuleSet::new(vec![
330            cr("planning/plan-*", &["default@1.0.0"]),
331            cr("exec-*", &["default@1.0.0"]),
332        ])
333        .unwrap();
334        let m = cs.first_match(Path::new("exec-foo")).unwrap();
335        assert_eq!(m.pattern, "exec-*");
336    }
337
338    #[test]
339    fn flat_candidate_matches_flat_pattern() {
340        let cs = CreateRuleSet::new(vec![cr("exec-*", &["default@1.0.0"])]).unwrap();
341        assert!(cs.first_match(Path::new("exec-foo")).is_some());
342        // `exec-*` does not match `nested/exec-foo` (literal_separator).
343        assert!(cs.first_match(Path::new("nested/exec-foo")).is_none());
344    }
345
346    #[test]
347    fn hierarchical_candidate_requires_path_prefix() {
348        let cs = CreateRuleSet::new(vec![cr("planning/plan-*", &["default@1.0.0"])]).unwrap();
349        assert!(cs.first_match(Path::new("planning/plan-q4")).is_some());
350        // Same leaf without the path prefix does not match.
351        assert!(cs.first_match(Path::new("plan-q4")).is_none());
352        // Same leaf under a different path does not match.
353        assert!(cs.first_match(Path::new("other/plan-q4")).is_none());
354    }
355
356    #[test]
357    fn create_rule_set_malformed_pattern_returns_parse_entry_error() {
358        let err = CreateRuleSet::new(vec![cr("[unclosed", &["*"])]).unwrap_err();
359        match err {
360            MatcherSetError::ParseEntry { entry, .. } => {
361                assert_eq!(entry, "[unclosed")
362            }
363            _ => panic!("expected ParseEntry, got {err:?}"),
364        }
365    }
366
367    #[test]
368    fn create_rule_set_carries_default_cross_links_in_matched_rule() {
369        // Regression: lifting must keep default_cross_links accessible
370        // through first_match.
371        use memstead_schema::workspace_config::CrossLinkValue;
372        let rule = CreateRuleSetting {
373            pattern: "exec-*".to_string(),
374            schemas: vec!["default".to_string()],
375            default_cross_links: Some(CrossLinkValue::Wildcard),
376        };
377        let cs = CreateRuleSet::new(vec![rule]).unwrap();
378        let m = cs.first_match(Path::new("exec-foo")).unwrap();
379        assert_eq!(m.default_cross_links, Some(CrossLinkValue::Wildcard));
380    }
381
382    // ---- DeleteRuleSet ---------------------------------------------
383
384    #[test]
385    fn delete_rule_set_resolves_by_pattern_only() {
386        let ds = DeleteRuleSet::new(vec![dr("planning/plan-*"), dr("exec-*")]).unwrap();
387        assert!(ds.first_match(Path::new("planning/plan-foo")).is_some());
388        assert!(ds.first_match(Path::new("exec-bar")).is_some());
389        assert!(ds.first_match(Path::new("engine")).is_none());
390    }
391
392    #[test]
393    fn delete_rule_set_default_is_empty() {
394        let ds = DeleteRuleSet::default();
395        assert!(ds.is_empty());
396        assert!(!ds.matches(Path::new("anything")));
397    }
398
399    #[test]
400    fn create_rule_set_default_is_empty() {
401        let cs = CreateRuleSet::default();
402        assert!(cs.is_empty());
403        assert!(!cs.matches(Path::new("anything")));
404    }
405}