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