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