Skip to main content

memstead_base/
mem.rs

1//! Multi-mem routing, visibility filtering, mem config.
2//!
3//! Writable/visible mem tracking. The engine loads multiple mems;
4//! some may be read-only (from --read-mem paths or JSON imports).
5//!
6//! The router is structured as a **snapshot** (`MemRouterSnapshot`) —
7//! a `Clone`-able value that the engine holds behind an `Arc`. Lifecycle
8//! operations mutate by cloning the snapshot, editing the clone, and
9//! swapping the `Arc` pointer on `Engine`. Readers that hold an `Arc`
10//! before the swap observe the pre-swap snapshot for their lifetime; no
11//! torn reads are possible. The MCP-level `memstead_mem_create` /
12//! `memstead_mem_delete` tools flip state at runtime.
13
14use std::collections::HashMap;
15use std::collections::HashSet;
16use std::path::{Path, PathBuf};
17use std::time::SystemTime;
18
19use crate::entity::EntityId;
20
21/// The per-mem engine-internal directory under a folder mem's
22/// root (`<mem_root>/.memstead/` — `config.json`, `changes.jsonl`).
23/// Defined in `memstead-schema` (mem-config loading lives there);
24/// re-exported here as the mem-level home for the concept.
25pub use memstead_schema::MEM_META_DIR;
26
27/// Whether `dir` is the root of a mem of its own: it holds
28/// `.memstead/config.json`. A folder walker of an enclosing mem stops
29/// there, so the nested mem's entities never load a second time under
30/// the enclosing mem's id.
31pub fn is_nested_mem_root(dir: &std::path::Path) -> bool {
32    dir.join(MEM_META_DIR).join("config.json").is_file()
33}
34
35/// Provenance record attached to every writable-mem registration.
36///
37/// `MEM_NAME_COLLISION` reads the colliding registration's
38/// `MemOrigin` and renders it into `details.source` so agents can
39/// distinguish "collision with an explicit workspace mem" from
40/// "collision with a previously-runtime-created mem" without a
41/// follow-up round trip. The enum is kept internal to `memstead-git-branch` with a
42/// `render_source` rendering helper that produces the agent-facing
43/// string — no public `serde` derivation yet; the render path is the
44/// only supported serialization surface until a caller needs structured
45/// consumption.
46#[derive(Debug, Clone)]
47pub enum MemOrigin {
48    /// Loaded from the workspace's `.memstead/workspace.toml` `mems = [...]`
49    /// entry.
50    ExplicitToml,
51    /// Registered after `Engine::init` via
52    /// `Engine::register_mem_runtime` — the path lifecycle tools
53    /// take. `at` captures when the runtime registration
54    /// happened (rendered as an RFC-3339 timestamp on the error
55    /// surface); `by_tool` names the MCP tool that produced the
56    /// registration (today always `"memstead_mem_create"`, but kept
57    /// extensible).
58    RuntimeCreated {
59        at: SystemTime,
60        by_tool: &'static str,
61    },
62}
63
64impl MemOrigin {
65    /// Agent-facing string rendering consumed by
66    /// `MEM_NAME_COLLISION.details.source`. The string is short,
67    /// declarative, and identifies the registration site so agents can
68    /// correlate the collision with something they can observe
69    /// (`.memstead/workspace.toml` entry, timestamp).
70    ///
71    /// The workspace config file lives at `.memstead/workspace.toml`.
72    /// The error message points at the current path so an agent
73    /// following the hint finds it.
74    pub fn render_source(&self) -> String {
75        match self {
76            MemOrigin::ExplicitToml => "explicit from .memstead/workspace.toml".to_string(),
77            MemOrigin::RuntimeCreated { at, by_tool } => {
78                format!("runtime-created at {} by {}", render_rfc3339(*at), by_tool)
79            }
80        }
81    }
82
83    /// Short discriminator consumed by `memstead_health { include_config:
84    /// true }` to tag each writable-mem entry with an agent-readable
85    /// origin string. Variants map to stable kebab-case tokens so
86    /// downstream filters key on them.
87    pub fn kind(&self) -> &'static str {
88        match self {
89            MemOrigin::ExplicitToml => "explicit",
90            MemOrigin::RuntimeCreated { .. } => "runtime_created",
91        }
92    }
93}
94
95/// Render a `SystemTime` as an RFC-3339 UTC timestamp with second
96/// precision. Kept deliberately local to this module because the only
97/// consumer is `MemOrigin::render_source` — lifting it into a shared
98/// utility is premature until a second caller appears.
99///
100/// Pre-epoch times fall back to the epoch itself; the error surface is
101/// an agent-facing string and "crashing on a nonsensical timestamp" is
102/// worse than the (vanishingly unlikely) pre-1970 fallback.
103fn render_rfc3339(ts: SystemTime) -> String {
104    let secs = ts
105        .duration_since(std::time::UNIX_EPOCH)
106        .map(|d| d.as_secs())
107        .unwrap_or(0);
108    let days = secs / 86400;
109    let remainder = secs % 86400;
110    let hour = remainder / 3600;
111    let minute = (remainder % 3600) / 60;
112    let second = remainder % 60;
113    let (year, month, day) = days_to_ymd(days);
114    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
115}
116
117/// Convert days since epoch (1970-01-01) to (year, month, day).
118/// Algorithm from http://howardhinnant.github.io/date_algorithms.html —
119/// duplicated from `entity::generator::days_to_ymd` deliberately: this
120/// module's rendering semantics (UTC-anchored, time-inclusive) are a
121/// different shape than the generator's pure-date helper, and a shared
122/// utility would couple two independent code paths.
123fn days_to_ymd(days: u64) -> (u64, u64, u64) {
124    let z = days + 719468;
125    let era = z / 146097;
126    let doe = z - era * 146097;
127    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
128    let y = yoe + era * 400;
129    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
130    let mp = (5 * doy + 2) / 153;
131    let d = doy - (153 * mp + 2) / 5 + 1;
132    let m = if mp < 10 { mp + 3 } else { mp - 9 };
133    let y = if m <= 2 { y + 1 } else { y };
134    (y, m, d)
135}
136
137/// Per-writable-mem origin + directory payload held inside
138/// `MemRouterSnapshot`. Cloned along with the snapshot on every
139/// lifecycle mutation; clone cost is O(1).
140///
141/// Hierarchical mem identity lives directly on the router HashMap
142/// key (and on `Mount::mem`) — there's exactly one identifier (the
143/// full path, e.g. `team/sub-mem`). The delete-side lifecycle
144/// composer reads the mem name as-is, no path-composition step
145/// needed.
146#[derive(Debug, Clone)]
147pub struct WritableEntry {
148    pub dir: Option<PathBuf>,
149    pub origin: MemOrigin,
150}
151
152/// Mem configuration for the engine runtime — cloneable snapshot.
153///
154/// Tracks which mems are writable, which are visible, and their
155/// directories. Held on `Engine` behind an `Arc<MemRouterSnapshot>`;
156/// lifecycle mutations clone the snapshot, edit the clone, and swap the
157/// `Arc` pointer atomically inside the engine mutex.
158#[derive(Debug, Clone)]
159pub struct MemRouterSnapshot {
160    /// Writable mem names.
161    writable: HashSet<String>,
162    /// All visible mem names (writable + read-only).
163    visible: HashSet<String>,
164    /// Mem name → (directory path, registration origin). Writable
165    /// mems only — read-only entries live in `read_only_archives`.
166    /// `dir` is `Some(path)` for disk-backed mems and `None` for
167    /// mem-repo-backed mems whose content lives only as a branch in
168    /// `mem-repo-git` (no working tree).
169    writable_entries: HashMap<String, WritableEntry>,
170    /// Mem name → sealed-archive path (read-only mems only).
171    /// Stored so reload can re-open the same archive when its mtime
172    /// changes without needing to re-parse the project config.
173    read_only_archives: HashMap<String, PathBuf>,
174}
175
176impl MemRouterSnapshot {
177    pub fn new() -> Self {
178        Self {
179            writable: HashSet::new(),
180            visible: HashSet::new(),
181            writable_entries: HashMap::new(),
182            read_only_archives: HashMap::new(),
183        }
184    }
185
186    /// Register a writable mem with its directory path and origin.
187    ///
188    /// The mem's hierarchical organisational path is part of `name`
189    /// itself (e.g. `"team/sub-mem"`). The router HashMap key, the
190    /// `Mount::mem` field, and the lifecycle-allowlist candidate
191    /// all converge on the same string — no separate composition
192    /// step.
193    pub fn add_writable(&mut self, name: String, dir: Option<PathBuf>, origin: MemOrigin) {
194        self.visible.insert(name.clone());
195        self.writable.insert(name.clone());
196        self.writable_entries
197            .insert(name, WritableEntry { dir, origin });
198    }
199
200    /// Remove a writable mem from the router. Returns `true` when
201    /// the entry was present.
202    ///
203    /// Internal — called by `Engine::unregister_mem_runtime`.
204    /// Read-only entries are not affected; unregistering a name that
205    /// names a read-only mem is a caller-level misuse and returns
206    /// `false`.
207    pub fn remove_writable(&mut self, name: &str) -> bool {
208        if self.writable_entries.remove(name).is_some() {
209            self.writable.remove(name);
210            // `visible` tracks both writable + read-only; only drop
211            // from `visible` when no read-only entry still carries it.
212            if !self.read_only_archives.contains_key(name) {
213                self.visible.remove(name);
214            }
215            true
216        } else {
217            false
218        }
219    }
220
221    /// Register a read-only mem backed by a sealed `.mem` archive.
222    ///
223    /// `archive_path` is the on-disk location of the archive. The
224    /// router retains it so reload can re-open the same archive without
225    /// re-parsing the project config.
226    pub fn add_read_only(&mut self, name: String, archive_path: PathBuf) {
227        self.visible.insert(name.clone());
228        self.read_only_archives.insert(name, archive_path);
229    }
230
231    /// Register one mount under the rule every registration path
232    /// shares, boot and runtime alike. A writable mount takes the
233    /// writable slot, with its working directory when it is a folder. A
234    /// read-only mount takes the read-only slot whatever its storage:
235    /// an archive with its file, a folder with its path, a git-branch
236    /// mount with its git directory (the slot's path is opaque for
237    /// visibility; the callers that need a real archive path branch on
238    /// the backend). A read-only in-memory mount has no read source and
239    /// is not registered; the engine never produces one.
240    pub(crate) fn add_mount(&mut self, mount: &crate::workspace::Mount, origin: MemOrigin) {
241        use crate::workspace::{MountCapability, MountStorage};
242        match mount.capability {
243            MountCapability::Write => {
244                let dir = match &mount.storage {
245                    MountStorage::Folder { path } => Some(path.clone()),
246                    MountStorage::GitBranch { .. }
247                    | MountStorage::Archive { .. }
248                    | MountStorage::InMemory => None,
249                };
250                self.add_writable(mount.mem.clone(), dir, origin);
251            }
252            MountCapability::ReadOnly => match &mount.storage {
253                MountStorage::Archive { path } | MountStorage::Folder { path } => {
254                    self.add_read_only(mount.mem.clone(), path.clone());
255                }
256                MountStorage::GitBranch { gitdir, .. } => {
257                    self.add_read_only(mount.mem.clone(), gitdir.clone());
258                }
259                MountStorage::InMemory => {}
260            },
261        }
262    }
263
264    /// Remove a read-only mem from the router. Returns `true` when the
265    /// entry was present. Mirror of [`Self::remove_writable`] for the
266    /// uninstall path: writable entries are not affected, and `visible`
267    /// only drops the name when no writable entry still carries it.
268    pub fn remove_read_only(&mut self, name: &str) -> bool {
269        if self.read_only_archives.remove(name).is_some() {
270            if !self.writable_entries.contains_key(name) {
271                self.visible.remove(name);
272            }
273            true
274        } else {
275            false
276        }
277    }
278
279    /// Check if a mem is writable.
280    pub fn is_writable(&self, mem: &str) -> bool {
281        self.writable.contains(mem)
282    }
283
284    /// Check if a mem is visible (writable or read-only).
285    pub fn is_visible(&self, mem: &str) -> bool {
286        self.visible.contains(mem)
287    }
288
289    /// Check if an entity is visible from the given context.
290    pub fn is_entity_visible(&self, entity_id: &EntityId) -> bool {
291        let mem = entity_id.mem();
292        mem.is_empty() || self.visible.contains(mem)
293    }
294
295    /// Get the directory path for a writable mem.
296    ///
297    /// Returns `None` when the mem is unknown OR when the mem is
298    /// mem-repo-backed (no on-disk directory). Callers that need to
299    /// distinguish "mem not found" from "mem has no dir" use
300    /// `is_writable` first.
301    pub fn dir_for_mem(&self, mem: &str) -> Option<&Path> {
302        self.writable_entries
303            .get(mem)
304            .and_then(|e| e.dir.as_deref())
305    }
306
307    /// Get the `MemOrigin` for a writable mem. Used by the
308    /// `MEM_NAME_COLLISION` envelope renderer and the
309    /// `memstead_health { include_config: true }` per-mem `origin` field.
310    pub fn origin_for_mem(&self, mem: &str) -> Option<&MemOrigin> {
311        self.writable_entries.get(mem).map(|e| &e.origin)
312    }
313
314    /// Get the sealed-archive path for a read-only mem.
315    ///
316    /// Returns `None` for writable mems and unknown names. Keep this
317    /// distinct from `dir_for_mem` — a directory and a zip archive are
318    /// different backing stores, and callers usually care which they get.
319    pub fn archive_path_for_mem(&self, mem: &str) -> Option<&Path> {
320        self.read_only_archives.get(mem).map(|p| p.as_path())
321    }
322
323    /// Get all writable mem names.
324    pub fn writable_mems(&self) -> &HashSet<String> {
325        &self.writable
326    }
327
328    /// Get all visible mem names.
329    pub fn visible_mems(&self) -> &HashSet<String> {
330        &self.visible
331    }
332
333    /// Validate that a mem is writable, returning an error message if not.
334    pub fn validate_writable(&self, mem: &str) -> Result<(), String> {
335        if self.writable.contains(mem) {
336            Ok(())
337        } else {
338            let writable: Vec<_> = self.writable.iter().cloned().collect();
339            Err(format!(
340                "Mem '{}' is read-only. Writable mems: {}",
341                mem,
342                writable.join(", ")
343            ))
344        }
345    }
346}
347
348impl Default for MemRouterSnapshot {
349    fn default() -> Self {
350        Self::new()
351    }
352}
353
354/// Convenience: check if an entity is visible. Returns true if router is None (no filtering).
355pub fn is_visible(entity_id: &EntityId, router: Option<&MemRouterSnapshot>) -> bool {
356    match router {
357        Some(r) => r.is_entity_visible(entity_id),
358        None => true,
359    }
360}
361
362/// Convenience: check if a mem is writable. Returns true if router is None.
363pub fn is_writable(mem: &str, router: Option<&MemRouterSnapshot>) -> bool {
364    match router {
365        Some(r) => r.is_writable(mem),
366        None => true,
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    /// The one registration rule: a read-only mount is visible and
375    /// never writable, whatever its storage; a writable mount is both.
376    #[test]
377    fn add_mount_keeps_a_read_only_mount_out_of_the_writable_slot() {
378        use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
379        let mount = |mem: &str, storage: MountStorage, capability: MountCapability| Mount {
380            mem: mem.to_string(),
381            schema: None,
382            storage,
383            capability,
384            lifecycle: MountLifecycle::Eager,
385            cross_linkable: true,
386            migration_target: None,
387        };
388        let branch = || MountStorage::GitBranch {
389            gitdir: PathBuf::from("/elsewhere/mem-repo/.git"),
390            branch: "notes".to_string(),
391        };
392        let folder = || MountStorage::Folder {
393            path: PathBuf::from("/work/notes"),
394        };
395        let archive = || MountStorage::Archive {
396            path: PathBuf::from("/cache/notes.mem"),
397        };
398
399        for (name, storage) in [
400            ("branch", branch()),
401            ("folder", folder()),
402            ("archive", archive()),
403        ] {
404            let mut router = MemRouterSnapshot::new();
405            router.add_mount(
406                &mount(name, storage, MountCapability::ReadOnly),
407                MemOrigin::ExplicitToml,
408            );
409            assert!(router.is_visible(name), "{name} must be visible");
410            assert!(!router.is_writable(name), "{name} must not be writable");
411            assert!(
412                router.remove_read_only(name),
413                "{name} sits in the read-only slot"
414            );
415            assert!(!router.is_visible(name));
416        }
417
418        let mut router = MemRouterSnapshot::new();
419        router.add_mount(
420            &mount("branch", branch(), MountCapability::Write),
421            MemOrigin::ExplicitToml,
422        );
423        router.add_mount(
424            &mount("folder", folder(), MountCapability::Write),
425            MemOrigin::ExplicitToml,
426        );
427        assert!(router.is_writable("branch") && router.is_writable("folder"));
428    }
429
430    #[test]
431    fn empty_router_allows_nothing() {
432        let router = MemRouterSnapshot::new();
433        assert!(!router.is_writable("specs"));
434        assert!(!router.is_visible("specs"));
435    }
436
437    #[test]
438    fn writable_mem_is_visible() {
439        let mut router = MemRouterSnapshot::new();
440        router.add_writable(
441            "specs".to_string(),
442            Some(PathBuf::from("/path/to/specs")),
443            MemOrigin::ExplicitToml,
444        );
445        assert!(router.is_writable("specs"));
446        assert!(router.is_visible("specs"));
447        assert!(!router.is_writable("other"));
448    }
449
450    #[test]
451    fn read_only_mem() {
452        let mut router = MemRouterSnapshot::new();
453        router.add_read_only(
454            "external".to_string(),
455            PathBuf::from("/path/to/external.mem"),
456        );
457        assert!(!router.is_writable("external"));
458        assert!(router.is_visible("external"));
459    }
460
461    #[test]
462    fn entity_visibility() {
463        let mut router = MemRouterSnapshot::new();
464        router.add_writable(
465            "specs".to_string(),
466            Some(PathBuf::from("/specs")),
467            MemOrigin::ExplicitToml,
468        );
469        router.add_read_only(
470            "external".to_string(),
471            PathBuf::from("/path/to/external.mem"),
472        );
473
474        assert!(router.is_entity_visible(&EntityId::new("specs", "entity")));
475        assert!(router.is_entity_visible(&EntityId::new("external", "entity")));
476        assert!(!router.is_entity_visible(&EntityId::new("hidden", "entity")));
477    }
478
479    #[test]
480    fn dir_for_mem() {
481        let mut router = MemRouterSnapshot::new();
482        router.add_writable(
483            "specs".to_string(),
484            Some(PathBuf::from("/path/to/specs")),
485            MemOrigin::ExplicitToml,
486        );
487        assert_eq!(
488            router.dir_for_mem("specs"),
489            Some(Path::new("/path/to/specs"))
490        );
491        assert_eq!(router.dir_for_mem("unknown"), None);
492    }
493
494    #[test]
495    fn validate_writable_ok() {
496        let mut router = MemRouterSnapshot::new();
497        router.add_writable(
498            "specs".to_string(),
499            Some(PathBuf::from("/specs")),
500            MemOrigin::ExplicitToml,
501        );
502        assert!(router.validate_writable("specs").is_ok());
503    }
504
505    #[test]
506    fn validate_writable_err() {
507        let mut router = MemRouterSnapshot::new();
508        router.add_read_only(
509            "external".to_string(),
510            PathBuf::from("/path/to/external.mem"),
511        );
512        assert!(router.validate_writable("external").is_err());
513    }
514
515    #[test]
516    fn convenience_functions_with_none() {
517        let id = EntityId::new("any", "entity");
518        assert!(is_visible(&id, None));
519        assert!(is_writable("any", None));
520    }
521
522    #[test]
523    fn archive_path_for_read_only_mem() {
524        let mut router = MemRouterSnapshot::new();
525        router.add_read_only("external".to_string(), PathBuf::from("/deps/external.mem"));
526        assert_eq!(
527            router.archive_path_for_mem("external"),
528            Some(Path::new("/deps/external.mem"))
529        );
530        // Writable mems do not carry an archive path.
531        router.add_writable(
532            "specs".to_string(),
533            Some(PathBuf::from("/specs")),
534            MemOrigin::ExplicitToml,
535        );
536        assert_eq!(router.archive_path_for_mem("specs"), None);
537        // Unknown mems return None cleanly.
538        assert_eq!(router.archive_path_for_mem("unknown"), None);
539    }
540
541    #[test]
542    fn dir_and_archive_paths_stay_separate() {
543        // Deliberate check that `dir_for_mem` and `archive_path_for_mem`
544        // don't leak into each other's keyspace — a writable mem must
545        // never surface via the archive accessor, and vice versa.
546        let mut router = MemRouterSnapshot::new();
547        router.add_writable(
548            "specs".to_string(),
549            Some(PathBuf::from("/specs")),
550            MemOrigin::ExplicitToml,
551        );
552        router.add_read_only("external".to_string(), PathBuf::from("/deps/external.mem"));
553        assert!(router.dir_for_mem("specs").is_some());
554        assert!(router.dir_for_mem("external").is_none());
555        assert!(router.archive_path_for_mem("specs").is_none());
556        assert!(router.archive_path_for_mem("external").is_some());
557    }
558
559    #[test]
560    fn remove_writable_returns_true_when_present() {
561        let mut router = MemRouterSnapshot::new();
562        router.add_writable(
563            "specs".to_string(),
564            Some(PathBuf::from("/specs")),
565            MemOrigin::ExplicitToml,
566        );
567        assert!(router.remove_writable("specs"));
568        assert!(!router.is_writable("specs"));
569        assert!(!router.is_visible("specs"));
570        assert!(router.dir_for_mem("specs").is_none());
571    }
572
573    #[test]
574    fn remove_writable_returns_false_when_absent() {
575        let mut router = MemRouterSnapshot::new();
576        assert!(!router.remove_writable("nonexistent"));
577    }
578
579    #[test]
580    fn remove_writable_leaves_read_only_visibility_when_same_name_read_only_exists() {
581        // Contrived: a name carried by both a writable entry and a
582        // read-only archive. Not a current product state, but the
583        // router's invariant ("visibility reflects union of registry
584        // kinds") is worth locking in.
585        let mut router = MemRouterSnapshot::new();
586        router.add_writable(
587            "shared".to_string(),
588            Some(PathBuf::from("/specs")),
589            MemOrigin::ExplicitToml,
590        );
591        router.add_read_only("shared".to_string(), PathBuf::from("/deps/shared.mem"));
592        assert!(router.remove_writable("shared"));
593        assert!(!router.is_writable("shared"));
594        assert!(router.is_visible("shared"));
595    }
596
597    #[test]
598    fn mem_origin_render_source_explicit() {
599        let o = MemOrigin::ExplicitToml;
600        // The config file lives at `.memstead/workspace.toml`.
601        assert_eq!(o.render_source(), "explicit from .memstead/workspace.toml");
602        assert_eq!(o.kind(), "explicit");
603    }
604
605    #[test]
606    fn mem_origin_render_source_runtime_created() {
607        // Anchor at a deterministic epoch offset so the rendered form
608        // is stable: 1_700_000_000 = 2023-11-14T22:13:20Z.
609        let ts = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
610        let o = MemOrigin::RuntimeCreated {
611            at: ts,
612            by_tool: "memstead_mem_create",
613        };
614        let rendered = o.render_source();
615        assert!(
616            rendered.contains("memstead_mem_create"),
617            "rendered source should name the tool: {rendered}"
618        );
619        assert!(
620            rendered.contains("2023-11-14T22:13:20Z"),
621            "rendered source should carry the RFC-3339 timestamp: {rendered}"
622        );
623        assert_eq!(o.kind(), "runtime_created");
624    }
625
626    #[test]
627    fn snapshot_clone_is_independent() {
628        // Locks the COW-snapshot discipline: a clone taken before a
629        // mutation does not observe the mutation. This is the
630        // invariant `Arc<MemRouterSnapshot>` relies on — readers
631        // holding the pre-swap `Arc` see the pre-swap state.
632        let mut original = MemRouterSnapshot::new();
633        original.add_writable(
634            "a".to_string(),
635            Some(PathBuf::from("/a")),
636            MemOrigin::ExplicitToml,
637        );
638        let pre_clone = original.clone();
639
640        original.add_writable(
641            "b".to_string(),
642            Some(PathBuf::from("/b")),
643            MemOrigin::ExplicitToml,
644        );
645
646        assert!(pre_clone.is_writable("a"));
647        assert!(!pre_clone.is_writable("b"));
648        assert!(original.is_writable("a"));
649        assert!(original.is_writable("b"));
650    }
651
652    /// Hierarchical mem identity lives directly in the router HashMap
653    /// key — `add_writable("team/sub-mem", …)` registers under the full
654    /// path, lookups against `"sub-mem"` (the leaf alone) miss
655    /// cleanly. Locks the "path is the only identifier" invariant.
656    #[test]
657    fn hierarchical_name_is_the_router_key() {
658        let mut router = MemRouterSnapshot::new();
659        router.add_writable("team/sub-mem".to_string(), None, MemOrigin::ExplicitToml);
660        assert!(router.is_writable("team/sub-mem"));
661        // Leaf-only lookup misses — there's no fallback path-lookup.
662        assert!(!router.is_writable("sub-mem"));
663    }
664}