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 /// Remove a read-only mem from the router. Returns `true` when the
232 /// entry was present. Mirror of [`Self::remove_writable`] for the
233 /// uninstall path: writable entries are not affected, and `visible`
234 /// only drops the name when no writable entry still carries it.
235 pub fn remove_read_only(&mut self, name: &str) -> bool {
236 if self.read_only_archives.remove(name).is_some() {
237 if !self.writable_entries.contains_key(name) {
238 self.visible.remove(name);
239 }
240 true
241 } else {
242 false
243 }
244 }
245
246 /// Check if a mem is writable.
247 pub fn is_writable(&self, mem: &str) -> bool {
248 self.writable.contains(mem)
249 }
250
251 /// Check if a mem is visible (writable or read-only).
252 pub fn is_visible(&self, mem: &str) -> bool {
253 self.visible.contains(mem)
254 }
255
256 /// Check if an entity is visible from the given context.
257 pub fn is_entity_visible(&self, entity_id: &EntityId) -> bool {
258 let mem = entity_id.mem();
259 mem.is_empty() || self.visible.contains(mem)
260 }
261
262 /// Get the directory path for a writable mem.
263 ///
264 /// Returns `None` when the mem is unknown OR when the mem is
265 /// mem-repo-backed (no on-disk directory). Callers that need to
266 /// distinguish "mem not found" from "mem has no dir" use
267 /// `is_writable` first.
268 pub fn dir_for_mem(&self, mem: &str) -> Option<&Path> {
269 self.writable_entries
270 .get(mem)
271 .and_then(|e| e.dir.as_deref())
272 }
273
274 /// Get the `MemOrigin` for a writable mem. Used by the
275 /// `MEM_NAME_COLLISION` envelope renderer and the
276 /// `memstead_health { include_config: true }` per-mem `origin` field.
277 pub fn origin_for_mem(&self, mem: &str) -> Option<&MemOrigin> {
278 self.writable_entries.get(mem).map(|e| &e.origin)
279 }
280
281 /// Get the sealed-archive path for a read-only mem.
282 ///
283 /// Returns `None` for writable mems and unknown names. Keep this
284 /// distinct from `dir_for_mem` — a directory and a zip archive are
285 /// different backing stores, and callers usually care which they get.
286 pub fn archive_path_for_mem(&self, mem: &str) -> Option<&Path> {
287 self.read_only_archives.get(mem).map(|p| p.as_path())
288 }
289
290 /// Get all writable mem names.
291 pub fn writable_mems(&self) -> &HashSet<String> {
292 &self.writable
293 }
294
295 /// Get all visible mem names.
296 pub fn visible_mems(&self) -> &HashSet<String> {
297 &self.visible
298 }
299
300 /// Validate that a mem is writable, returning an error message if not.
301 pub fn validate_writable(&self, mem: &str) -> Result<(), String> {
302 if self.writable.contains(mem) {
303 Ok(())
304 } else {
305 let writable: Vec<_> = self.writable.iter().cloned().collect();
306 Err(format!(
307 "Mem '{}' is read-only. Writable mems: {}",
308 mem,
309 writable.join(", ")
310 ))
311 }
312 }
313}
314
315impl Default for MemRouterSnapshot {
316 fn default() -> Self {
317 Self::new()
318 }
319}
320
321/// Convenience: check if an entity is visible. Returns true if router is None (no filtering).
322pub fn is_visible(entity_id: &EntityId, router: Option<&MemRouterSnapshot>) -> bool {
323 match router {
324 Some(r) => r.is_entity_visible(entity_id),
325 None => true,
326 }
327}
328
329/// Convenience: check if a mem is writable. Returns true if router is None.
330pub fn is_writable(mem: &str, router: Option<&MemRouterSnapshot>) -> bool {
331 match router {
332 Some(r) => r.is_writable(mem),
333 None => true,
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 #[test]
342 fn empty_router_allows_nothing() {
343 let router = MemRouterSnapshot::new();
344 assert!(!router.is_writable("specs"));
345 assert!(!router.is_visible("specs"));
346 }
347
348 #[test]
349 fn writable_mem_is_visible() {
350 let mut router = MemRouterSnapshot::new();
351 router.add_writable(
352 "specs".to_string(),
353 Some(PathBuf::from("/path/to/specs")),
354 MemOrigin::ExplicitToml,
355 );
356 assert!(router.is_writable("specs"));
357 assert!(router.is_visible("specs"));
358 assert!(!router.is_writable("other"));
359 }
360
361 #[test]
362 fn read_only_mem() {
363 let mut router = MemRouterSnapshot::new();
364 router.add_read_only(
365 "external".to_string(),
366 PathBuf::from("/path/to/external.mem"),
367 );
368 assert!(!router.is_writable("external"));
369 assert!(router.is_visible("external"));
370 }
371
372 #[test]
373 fn entity_visibility() {
374 let mut router = MemRouterSnapshot::new();
375 router.add_writable(
376 "specs".to_string(),
377 Some(PathBuf::from("/specs")),
378 MemOrigin::ExplicitToml,
379 );
380 router.add_read_only(
381 "external".to_string(),
382 PathBuf::from("/path/to/external.mem"),
383 );
384
385 assert!(router.is_entity_visible(&EntityId::new("specs", "entity")));
386 assert!(router.is_entity_visible(&EntityId::new("external", "entity")));
387 assert!(!router.is_entity_visible(&EntityId::new("hidden", "entity")));
388 }
389
390 #[test]
391 fn dir_for_mem() {
392 let mut router = MemRouterSnapshot::new();
393 router.add_writable(
394 "specs".to_string(),
395 Some(PathBuf::from("/path/to/specs")),
396 MemOrigin::ExplicitToml,
397 );
398 assert_eq!(
399 router.dir_for_mem("specs"),
400 Some(Path::new("/path/to/specs"))
401 );
402 assert_eq!(router.dir_for_mem("unknown"), None);
403 }
404
405 #[test]
406 fn validate_writable_ok() {
407 let mut router = MemRouterSnapshot::new();
408 router.add_writable(
409 "specs".to_string(),
410 Some(PathBuf::from("/specs")),
411 MemOrigin::ExplicitToml,
412 );
413 assert!(router.validate_writable("specs").is_ok());
414 }
415
416 #[test]
417 fn validate_writable_err() {
418 let mut router = MemRouterSnapshot::new();
419 router.add_read_only(
420 "external".to_string(),
421 PathBuf::from("/path/to/external.mem"),
422 );
423 assert!(router.validate_writable("external").is_err());
424 }
425
426 #[test]
427 fn convenience_functions_with_none() {
428 let id = EntityId::new("any", "entity");
429 assert!(is_visible(&id, None));
430 assert!(is_writable("any", None));
431 }
432
433 #[test]
434 fn archive_path_for_read_only_mem() {
435 let mut router = MemRouterSnapshot::new();
436 router.add_read_only("external".to_string(), PathBuf::from("/deps/external.mem"));
437 assert_eq!(
438 router.archive_path_for_mem("external"),
439 Some(Path::new("/deps/external.mem"))
440 );
441 // Writable mems do not carry an archive path.
442 router.add_writable(
443 "specs".to_string(),
444 Some(PathBuf::from("/specs")),
445 MemOrigin::ExplicitToml,
446 );
447 assert_eq!(router.archive_path_for_mem("specs"), None);
448 // Unknown mems return None cleanly.
449 assert_eq!(router.archive_path_for_mem("unknown"), None);
450 }
451
452 #[test]
453 fn dir_and_archive_paths_stay_separate() {
454 // Deliberate check that `dir_for_mem` and `archive_path_for_mem`
455 // don't leak into each other's keyspace — a writable mem must
456 // never surface via the archive accessor, and vice versa.
457 let mut router = MemRouterSnapshot::new();
458 router.add_writable(
459 "specs".to_string(),
460 Some(PathBuf::from("/specs")),
461 MemOrigin::ExplicitToml,
462 );
463 router.add_read_only("external".to_string(), PathBuf::from("/deps/external.mem"));
464 assert!(router.dir_for_mem("specs").is_some());
465 assert!(router.dir_for_mem("external").is_none());
466 assert!(router.archive_path_for_mem("specs").is_none());
467 assert!(router.archive_path_for_mem("external").is_some());
468 }
469
470 #[test]
471 fn remove_writable_returns_true_when_present() {
472 let mut router = MemRouterSnapshot::new();
473 router.add_writable(
474 "specs".to_string(),
475 Some(PathBuf::from("/specs")),
476 MemOrigin::ExplicitToml,
477 );
478 assert!(router.remove_writable("specs"));
479 assert!(!router.is_writable("specs"));
480 assert!(!router.is_visible("specs"));
481 assert!(router.dir_for_mem("specs").is_none());
482 }
483
484 #[test]
485 fn remove_writable_returns_false_when_absent() {
486 let mut router = MemRouterSnapshot::new();
487 assert!(!router.remove_writable("nonexistent"));
488 }
489
490 #[test]
491 fn remove_writable_leaves_read_only_visibility_when_same_name_read_only_exists() {
492 // Contrived: a name carried by both a writable entry and a
493 // read-only archive. Not a current product state, but the
494 // router's invariant ("visibility reflects union of registry
495 // kinds") is worth locking in.
496 let mut router = MemRouterSnapshot::new();
497 router.add_writable(
498 "shared".to_string(),
499 Some(PathBuf::from("/specs")),
500 MemOrigin::ExplicitToml,
501 );
502 router.add_read_only("shared".to_string(), PathBuf::from("/deps/shared.mem"));
503 assert!(router.remove_writable("shared"));
504 assert!(!router.is_writable("shared"));
505 assert!(router.is_visible("shared"));
506 }
507
508 #[test]
509 fn mem_origin_render_source_explicit() {
510 let o = MemOrigin::ExplicitToml;
511 // The config file lives at `.memstead/workspace.toml`.
512 assert_eq!(o.render_source(), "explicit from .memstead/workspace.toml");
513 assert_eq!(o.kind(), "explicit");
514 }
515
516 #[test]
517 fn mem_origin_render_source_runtime_created() {
518 // Anchor at a deterministic epoch offset so the rendered form
519 // is stable: 1_700_000_000 = 2023-11-14T22:13:20Z.
520 let ts = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
521 let o = MemOrigin::RuntimeCreated {
522 at: ts,
523 by_tool: "memstead_mem_create",
524 };
525 let rendered = o.render_source();
526 assert!(
527 rendered.contains("memstead_mem_create"),
528 "rendered source should name the tool: {rendered}"
529 );
530 assert!(
531 rendered.contains("2023-11-14T22:13:20Z"),
532 "rendered source should carry the RFC-3339 timestamp: {rendered}"
533 );
534 assert_eq!(o.kind(), "runtime_created");
535 }
536
537 #[test]
538 fn snapshot_clone_is_independent() {
539 // Locks the COW-snapshot discipline: a clone taken before a
540 // mutation does not observe the mutation. This is the
541 // invariant `Arc<MemRouterSnapshot>` relies on — readers
542 // holding the pre-swap `Arc` see the pre-swap state.
543 let mut original = MemRouterSnapshot::new();
544 original.add_writable(
545 "a".to_string(),
546 Some(PathBuf::from("/a")),
547 MemOrigin::ExplicitToml,
548 );
549 let pre_clone = original.clone();
550
551 original.add_writable(
552 "b".to_string(),
553 Some(PathBuf::from("/b")),
554 MemOrigin::ExplicitToml,
555 );
556
557 assert!(pre_clone.is_writable("a"));
558 assert!(!pre_clone.is_writable("b"));
559 assert!(original.is_writable("a"));
560 assert!(original.is_writable("b"));
561 }
562
563 /// Hierarchical mem identity lives directly in the router HashMap
564 /// key — `add_writable("team/sub-mem", …)` registers under the full
565 /// path, lookups against `"sub-mem"` (the leaf alone) miss
566 /// cleanly. Locks the "path is the only identifier" invariant.
567 #[test]
568 fn hierarchical_name_is_the_router_key() {
569 let mut router = MemRouterSnapshot::new();
570 router.add_writable("team/sub-mem".to_string(), None, MemOrigin::ExplicitToml);
571 assert!(router.is_writable("team/sub-mem"));
572 // Leaf-only lookup misses — there's no fallback path-lookup.
573 assert!(!router.is_writable("sub-mem"));
574 }
575}