Skip to main content

memstead_base/engine/
boot.rs

1//! Engine construction — `from_mounts*` and `from_workspace_root`.
2//!
3//! `from_mounts` is the in-process constructor every test, in-process
4//! embedder, and the MCP filesystem server reach through.
5//! `from_workspace_root` is the folder boot path that produces the
6//! same engine from a workspace root; the git-branch counterpart lives in
7//! `memstead_git_branch::engine_from_workspace_root` and follows the same
8//! shape with the git-branch backend added to the factory.
9//!
10//! Free helpers in this module materialise the workspace schemas
11//! catalogue, walk each mount's backend at load-time, and synthesise
12//! the [`MemRouterSnapshot`] from the resolved mount list — pieces
13//! the two entry points share.
14
15use std::cell::OnceCell;
16use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use memstead_schema::Schema;
21
22use crate::backend::MemBackend;
23use crate::engine_fallback_type;
24use crate::entity::loader::parse_entries;
25use crate::entity::source::{SourceEntry, SourceReadError};
26use crate::entity::store_builder::push_entities_into_store;
27use crate::mem::{MemOrigin, MemRouterSnapshot};
28use crate::ops::WarningHint;
29use crate::store::Store;
30use crate::workspace::{Mount, MountCapability, MountStorage, WorkspaceSettings};
31
32use super::{BootError, Engine, EngineError, MountedBackend};
33
34impl Engine {
35    /// Build an engine from `(mount, backend)` pairs. The backend
36    /// is the implementor that will serve reads / writes for that
37    /// mount's mem.
38    ///
39    /// Returns [`EngineError::DuplicateMem`] when two mounts name
40    /// the same mem; that's a configuration error the caller must
41    /// fix before the engine can route deterministically. An empty
42    /// mount list is allowed (returns an engine that errors
43    /// `UnknownMem` on every read) — useful for tests; production
44    /// callers will reject empty inputs at the persistence-adapter
45    /// layer.
46    pub fn from_mounts(mounts: Vec<(Mount, Box<dyn MemBackend>)>) -> Result<Self, EngineError> {
47        Self::from_mounts_inner(mounts, Vec::new(), Vec::new())
48    }
49
50    /// Construct an engine from mounts plus an optional workspace
51    /// schemas directory. Loads every subdirectory of `schemas_dir`
52    /// as a workspace-authored schema and combines with the builtin
53    /// catalogue for per-mem schema-pin resolution. Workspace
54    /// schemas take precedence on (name, version) collision —
55    /// matches full's behaviour.
56    ///
57    /// `schemas_dir = None` is equivalent to [`Self::from_mounts`].
58    /// Used by `engine_from_workspace_root` to thread the
59    /// `[schemas_dir]` workspace-toml entry into schema resolution.
60    pub fn from_mounts_with_schemas_dir(
61        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
62        schemas_dir: Option<&Path>,
63    ) -> Result<Self, EngineError> {
64        let (extra_schemas, failed) = load_workspace_schemas_with_failures(schemas_dir);
65        Self::from_mounts_inner(mounts, extra_schemas, failed)
66    }
67
68    /// Like [`Self::from_mounts_with_schemas_dir`] but layers additional,
69    /// pre-loaded local-storage schemas (e.g. those a git-branch backend
70    /// reads from its `__MEMSTEAD:schemas/` ref via `SchemaSource`) on
71    /// top of the folder `schemas_dir` set. Both are local-storage
72    /// schemas — they override built-ins on `(name, version)` collision.
73    /// The git-branch boot path uses this to make ref-installed schemas
74    /// resolvable, which `from_mounts_with_schemas_dir` (folder only)
75    /// does not.
76    pub fn from_mounts_with_schemas_dir_and_extra(
77        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
78        schemas_dir: Option<&Path>,
79        mut extra: Vec<Arc<memstead_schema::Schema>>,
80    ) -> Result<Self, EngineError> {
81        let (mut local, failed) = load_workspace_schemas_with_failures(schemas_dir);
82        local.append(&mut extra);
83        Self::from_mounts_inner(mounts, local, failed)
84    }
85
86    pub(crate) fn from_mounts_inner(
87        mounts: Vec<(Mount, Box<dyn MemBackend>)>,
88        extra_schemas: Vec<Arc<memstead_schema::Schema>>,
89        failed_schema_packages: Vec<FailedSchemaPackage>,
90    ) -> Result<Self, EngineError> {
91        let mut seen: std::collections::HashSet<String> =
92            std::collections::HashSet::with_capacity(mounts.len());
93        let mut mounted: Vec<MountedBackend> = Vec::with_capacity(mounts.len());
94        for (mount, backend) in mounts {
95            if !seen.insert(mount.mem.clone()) {
96                return Err(EngineError::DuplicateMem(mount.mem));
97            }
98            // Seed the per-mount drift baseline. A backend that
99            // doesn't track HEAD (folder, archive) returns Ok(None)
100            // — drift detection is then a no-op for the mount. A
101            // probe failure during init falls back to None so a
102            // later successful probe can establish the baseline.
103            let last_known_head = backend.current_head().ok().flatten();
104            // Load the per-mem `.memstead/config.json` via the
105            // backend trait. Each backend resolves its own
106            // canonical location (folder: `<root>/.memstead/config.json`;
107            // archive: inside the zip; git-branch:
108            // `__MEMSTEAD:mems/<leaf>/config.json`). Read failures
109            // or missing files surface as
110            // `None` — `memstead_health` accommodates the missing-config
111            // case (handler emits empty `writeGuidance` + `extra`).
112            let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
113                let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
114                memstead_schema::config::parse_mem_config(&value).ok()
115            });
116            // Read the optional authoring-provenance payload the archive
117            // carries (`.memstead/provenance.json`). A malformed payload is
118            // downgraded to `None` (the member is additive — a parse
119            // failure means "provenance absent", not "mount failed").
120            let archive_provenance =
121                backend
122                    .read_archive_provenance()
123                    .ok()
124                    .flatten()
125                    .and_then(|bytes| {
126                        memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok()
127                    });
128            mounted.push(MountedBackend {
129                mount,
130                backend,
131                last_known_head,
132                mem_config,
133                archive_provenance,
134                // Set below, after the schema pin resolves: a lazy mount
135                // whose METADATA half fails still quarantines at boot;
136                // only the entity load defers.
137                deferred: false,
138            });
139        }
140
141        // Walk each backend, parse entries, populate one shared Store.
142        // Resolve each mount's schema pin against the built-in schema
143        // catalogue. The schema-registry resolver (which would also
144        // honor workspace-authored schemas living inside the storage
145        // backend) lands as a separate plan; this resolution closes
146        // the gap for the built-in catalogue so a workspace pinning
147        // a non-default built-in (e.g. `software`, `memory`) surfaces
148        // the right schema rather than silently downgrading to
149        // `default`.
150        let builtin_schemas_only = memstead_schema::builtins::load_builtin_schemas()
151            .map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?;
152        // Workspace-authored schemas resolve first (override builtins
153        // on (name, version) collision); builtins fill the rest.
154        let workspace_schemas = extra_schemas.clone();
155        let mut catalogue: Vec<Arc<memstead_schema::Schema>> =
156            Vec::with_capacity(extra_schemas.len() + builtin_schemas_only.len());
157        catalogue.extend(extra_schemas);
158        catalogue.extend(builtin_schemas_only.clone());
159        let builtin_schemas = catalogue;
160        let mut store = Store::new();
161        let mut load_errors: Vec<(PathBuf, String)> = Vec::new();
162        let mut schemas: HashMap<String, Arc<Schema>> = HashMap::with_capacity(mounted.len());
163        let fallback = engine_fallback_type();
164
165        // Derive the mem roster + last-segment suffixes ONCE so the
166        // per-mount load loop hands the same view to every
167        // `LoadCollector`. `known_suffixes` is the input the
168        // nested-prefix detector compares against; the full
169        // `mem_names` list feeds the two-pass cross-mem resolver
170        // in `push_entities_into_store`.
171        let mem_names: Vec<String> = mounted.iter().map(|m| m.mount.mem.clone()).collect();
172        let known_suffixes: Vec<String> = mem_names
173            .iter()
174            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
175            .collect();
176        let mut load_warnings: Vec<WarningHint> = Vec::new();
177
178        // Mem-level failures quarantine the mem instead of failing the
179        // workspace (degrade, never disappear — plenum/expertise
180        // 2026-08-06/07, where one broken mem took every healthy
181        // sibling offline). Nothing is weakened: everything that
182        // failed the boot still fails it, the blast radius shrinks to
183        // the one mem, which serves nothing until repaired + reloaded.
184        let mut quarantined: Vec<crate::engine::QuarantinedMem> = Vec::new();
185        let mut quarantined_idx: std::collections::HashSet<usize> =
186            std::collections::HashSet::new();
187        // Mounts whose entity load is DEFERRED (`lifecycle: lazy`): the
188        // metadata half above and the schema resolution below still run
189        // at boot — the roster must know the mem exists, with its pin —
190        // but the entity walk is skipped until the first operation that
191        // needs the mem triggers [`Engine::ensure_mems_loaded`].
192        let mut deferred_idx: std::collections::HashSet<usize> = std::collections::HashSet::new();
193
194        for (m_idx, m) in mounted.iter().enumerate() {
195            // Schema-pin authority: the mem's own per-mem config is
196            // the authoritative settled pin, so a copied or cloned mem
197            // resolves its schema from its own backend without consulting
198            // this workspace's `mounts.json`. `Mount.schema` (the mount
199            // record's pin) is the fallback when the config carries no
200            // schema, and an expectation assertion when it does — a
201            // disagreement surfaces a `SchemaPinMismatch` warning rather
202            // than silently preferring either.
203            let config_pin = m.mem_config.as_ref().and_then(|c| c.schema.as_ref());
204            let mount_pin = m.mount.schema.as_ref();
205            // `Mount.schema` is an optional expectation assertion: warn
206            // only when it is set *and* disagrees with the authoritative
207            // config pin.
208            if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
209                && cfg != mp
210            {
211                load_warnings.push(WarningHint::SchemaPinMismatch {
212                    mem: m.mount.mem.clone(),
213                    config_pin: cfg.as_display(),
214                    mount_pin: mp.as_display(),
215                });
216            }
217            // Boot-honesty skew check: a mem whose engine-owned
218            // mutation stamp names a different engine version than
219            // this binary gets a warn-tier hint — informative, never
220            // fatal, and a stamp-less (pre-stamp) mem is silent by
221            // construction. Read-only: the stamp is only ever
222            // rewritten by the next mutation.
223            //
224            // Compared as SEMVER, not as full strings.
225            // The old rule fired on any difference including the `+g<sha>`
226            // build metadata, so every rebuild between releases read as
227            // skew — noise on any workspace whose binary is built from
228            // source, which is every one of this project's own workspaces. Semver ordering
229            // ignores build metadata, so what survives is a real version
230            // difference, and it now carries its direction.
231            if let Some(stamp) = m
232                .mem_config
233                .as_ref()
234                .and_then(|c| c.mutation_stamp.as_ref())
235                && let Some(direction) = crate::build_info::skew_direction(
236                    &stamp.engine_version,
237                    crate::build_info::full_version(),
238                )
239            {
240                load_warnings.push(WarningHint::EngineVersionSkew {
241                    mem: m.mount.mem.clone(),
242                    stamped_engine: stamp.engine_version.clone(),
243                    running_engine: crate::build_info::full_version().to_string(),
244                    stamped_schema: stamp.schema.clone(),
245                    direction,
246                });
247            }
248            // Authoritative pin first (the backend config), then the
249            // mount assertion as fallback when the config carries none.
250            let settled_pin = config_pin.or(mount_pin);
251            // Dual-pin: a mem mid-migration validates against the
252            // migration target, not the settled pin.
253            let Some(effective_pin) = m.mount.migration_target.as_ref().or(settled_pin) else {
254                // Missing pin: quarantine, don't abort the workspace.
255                let e = EngineError::MemConfigIncomplete {
256                    mem: m.mount.mem.clone(),
257                    missing_fields: vec!["schema".to_string()],
258                };
259                quarantined.push(crate::engine::QuarantinedMem {
260                    mount: m.mount.clone(),
261                    reason_code: e.code().to_string(),
262                    reason_message: e.to_string(),
263                });
264                quarantined_idx.insert(m_idx);
265                continue;
266            };
267            // An archive-backed mount carries its own sealed vocabulary
268            // and resolves against it on every workspace shape: a
269            // folder workspace has no sealed-package storage to stage a
270            // third party's schema into, and a mem published under such
271            // a schema would otherwise quarantine there. The embedded
272            // package is layered per mount, between the workspace tier
273            // and the built-ins, and never into the shared catalogue —
274            // a sealed vocabulary is this mount's, not something a
275            // writable mem may pin.
276            let embedded = embedded_archive_schemas(&m.mount);
277            let resolved = if embedded.is_empty() {
278                SchemaResolver::new(&builtin_schemas).resolve(effective_pin)
279            } else {
280                let mut per_mount: Vec<Arc<Schema>> = Vec::with_capacity(
281                    workspace_schemas.len() + embedded.len() + builtin_schemas_only.len(),
282                );
283                per_mount.extend(workspace_schemas.iter().cloned());
284                per_mount.extend(embedded);
285                per_mount.extend(builtin_schemas_only.iter().cloned());
286                SchemaResolver::new(&per_mount).resolve(effective_pin)
287            };
288            let schema = match resolved {
289                Ok(schema) => schema,
290                Err(sources) => {
291                    // Unresolvable pin: the plenum failure class —
292                    // quarantine this mem, serve the rest. When the
293                    // pin names a workspace-authored package that
294                    // FAILED to load (e.g. one still on the retired
295                    // `propagating_relationships` key), that load
296                    // failure is the honest reason — not a generic
297                    // not-found.
298                    let failed = failed_schema_packages.iter().find(|f| {
299                        f.name.as_deref() == Some(effective_pin.name.as_str())
300                            && f.version
301                                .as_deref()
302                                .is_none_or(|v| v == effective_pin.version.to_string())
303                    });
304                    let (reason_code, reason_message) = match failed {
305                        Some(f) => (
306                            "SCHEMA_LOAD_FAILED".to_string(),
307                            format!(
308                                "schema package at {} failed to load: {}",
309                                f.path.display(),
310                                f.error
311                            ),
312                        ),
313                        None => {
314                            let e = EngineError::SchemaNotFound {
315                                mem: m.mount.mem.clone(),
316                                pin: effective_pin.as_display(),
317                                sources,
318                                install_hint: None,
319                            };
320                            (e.code().to_string(), e.to_string())
321                        }
322                    };
323                    quarantined.push(crate::engine::QuarantinedMem {
324                        mount: m.mount.clone(),
325                        reason_code,
326                        reason_message,
327                    });
328                    quarantined_idx.insert(m_idx);
329                    continue;
330                }
331            };
332            schemas.insert(m.mount.mem.clone(), schema.clone());
333
334            // Generation-behind hint (warn-tier, ungated, never
335            // blocking): the pin resolved from the BUILT-IN catalogue
336            // and the catalogue registers at least one strictly-higher
337            // version of the same name. Locally-installed
338            // (workspace-storage) pins are silent — the engine only
339            // knows generations for built-ins, and a local install
340            // shadowing a built-in (name, version) counts as local
341            // (that is also the resolver's precedence). Real semver
342            // ordering via `semver::Version`, never string ordering.
343            let locally_installed = workspace_schemas.iter().any(|s| {
344                s.manifest.name == effective_pin.name && s.version == effective_pin.version
345            });
346            let is_builtin = builtin_schemas_only.iter().any(|s| {
347                s.manifest.name == effective_pin.name && s.version == effective_pin.version
348            });
349            if !locally_installed
350                && is_builtin
351                && let Some(newest) =
352                    newest_builtin_version(&effective_pin.name, &builtin_schemas_only)
353                && *newest > effective_pin.version
354            {
355                load_warnings.push(WarningHint::SchemaGenerationsBehind {
356                    mem: m.mount.mem.clone(),
357                    pinned: effective_pin.as_display(),
358                    newest: newest.to_string(),
359                });
360            }
361
362            // Sealed schemas keep loading even when they violate the
363            // heading round-trip rule new installs are refused for —
364            // the violation surfaces as a health finding here, never
365            // as a boot failure (refusing would brick the workspace).
366            if let Err(memstead_schema::SchemaLoadError::SectionHeadingMismatch { violations }) =
367                memstead_schema::check_section_heading_roundtrip(&schema)
368            {
369                let (name, version) = schema.id();
370                load_warnings.push(WarningHint::SchemaHeadingRoundtripViolation {
371                    mem: m.mount.mem.clone(),
372                    schema_ref: format!("{name}@{version}"),
373                    violations: violations.iter().map(Into::into).collect(),
374                });
375            }
376
377            // Lazy lifecycle: everything above (config, provenance, pin
378            // resolution, schema warnings — the metadata half) ran; the
379            // entity walk is the expensive leg and defers to first read.
380            // A lazy mount with a broken pin still quarantined above —
381            // deferral never converts a metadata failure into silence.
382            if m.mount.lifecycle == crate::workspace::MountLifecycle::Lazy {
383                if let Some(w) = unbacked_mount_warning(&m.mount, m.backend.as_ref(), None) {
384                    load_warnings.push(w);
385                }
386                deferred_idx.insert(m_idx);
387                continue;
388            }
389
390            let (entries, read_errors) = match collect_source_entries(m.backend.as_ref()) {
391                Ok(pair) => pair,
392                Err(e) => {
393                    // Backend read failure: quarantine this mem, serve
394                    // the rest.
395                    quarantined.push(crate::engine::QuarantinedMem {
396                        mount: m.mount.clone(),
397                        reason_code: e.code().to_string(),
398                        reason_message: e.to_string(),
399                    });
400                    quarantined_idx.insert(m_idx);
401                    schemas.remove(&m.mount.mem);
402                    continue;
403                }
404            };
405            // Storage that is GONE quarantines rather than serving an empty
406            // graph (04/05). "Configured but cannot serve" is exactly what
407            // quarantine already means, its three sibling causes already
408            // quarantine, and this ends an incoherence: the same broken mount
409            // used to quarantine or serve empty depending on whether the
410            // mounts file happened to carry a schema assertion, which is
411            // unrelated to the breakage. A mem that answers reads with an
412            // empty graph is a worse default than one that refuses by name
413            // with a reason.
414            //
415            // The quarantine roster is rendered on every roster surface, which
416            // is what keeps this from trading a mount that looks healthy for a
417            // mount that is simply gone.
418            //
419            // SCOPED TO PATH-BACKED STORAGE, and the exception is a deliberate
420            // departure from backend parity rather than an oversight. For a
421            // git-branch mount, "the ref does not exist" is ALSO the normal
422            // state of a mem never pushed or never cloned, and quarantine
423            // removes the mount from the serving set. Parity was attempted
424            // twice. Each attempt cleared one blocker and uncovered the next:
425            // the mount lookup (a line), the pre-push gate's schema-before-ref
426            // ordering (fixed here, and worth fixing on its own), and finally
427            // `pull`'s pre-fast-forward validation, which needs a resolved
428            // schema a quarantined mem does not have. That last one is a
429            // semantic decision about what validation means for a mem being
430            // cloned, not plumbing. Recorded in the session log.
431            let path_backed = matches!(
432                m.mount.storage,
433                crate::workspace::MountStorage::Folder { .. }
434                    | crate::workspace::MountStorage::Archive { .. }
435            );
436            if path_backed && !m.backend.storage_present().unwrap_or(true) {
437                let location = match &m.mount.storage {
438                    crate::workspace::MountStorage::GitBranch { branch, .. } => branch.clone(),
439                    crate::workspace::MountStorage::Folder { path }
440                    | crate::workspace::MountStorage::Archive { path } => {
441                        path.display().to_string()
442                    }
443                    crate::workspace::MountStorage::InMemory => String::new(),
444                };
445                quarantined.push(crate::engine::QuarantinedMem {
446                    mount: m.mount.clone(),
447                    reason_code: "MOUNT_UNBACKED".to_string(),
448                    reason_message: format!(
449                        "the mount's storage is gone ({location}); it is configured but cannot \
450                         serve, so it is held out of the roster rather than answering reads \
451                         with an empty graph"
452                    ),
453                });
454                quarantined_idx.insert(m_idx);
455                schemas.remove(&m.mount.mem);
456                continue;
457            }
458            // A mount that is PRESENT but holds nothing still only warns: an
459            // empty mem is a legitimate state and must never be reported as
460            // unbacked or quarantined.
461            if let Some(w) =
462                unbacked_mount_warning(&m.mount, m.backend.as_ref(), Some(entries.len()))
463            {
464                load_warnings.push(w);
465            }
466            let load_result = parse_entries(entries, read_errors, &m.mount.mem, schema.as_ref());
467            // Wire the LoadCollector so the parser/store-builder
468            // pipeline forwards typed drift warnings
469            // (`SuspiciousNestedPrefix`, `DuplicateSectionHeading`,
470            // `InlineWikiLinkAutoStubbed`) into `load_warnings`.
471            // Mutation paths still pass `None` to stay silent.
472            push_entities_into_store(
473                &mut store,
474                load_result.entities,
475                fallback.as_ref(),
476                Some(crate::entity::store_builder::LoadCollector {
477                    warnings: &mut load_warnings,
478                    known_suffixes: &known_suffixes,
479                    mem_names: &mem_names,
480                }),
481            );
482            // Normalize folder-mount error paths to absolute (the
483            // backend walk yields mem-relative ones) so the per-mem
484            // reload can later replace exactly this mem's entries —
485            // a repaired file must stop reporting its old refusal.
486            if let crate::workspace::MountStorage::Folder { path } = &m.mount.storage {
487                let root = path.clone();
488                load_errors.extend(load_result.errors.into_iter().map(|(p, msg)| {
489                    let abs = if p.is_relative() { root.join(&p) } else { p };
490                    (abs, msg)
491                }));
492            } else {
493                load_errors.extend(load_result.errors);
494            }
495        }
496
497        // Stamp the deferred flags before the quarantine retain below
498        // renumbers the vector.
499        for idx in &deferred_idx {
500            mounted[*idx].deferred = true;
501        }
502
503        // Drop quarantined mounts from the serving roster: a
504        // quarantined mem has no backend in service, no entities in
505        // the store, no schema in the per-mem map — it exists only on
506        // the quarantine roster until repair + reload re-attach it.
507        if !quarantined_idx.is_empty() {
508            let mut keep_idx = 0usize;
509            mounted.retain(|_| {
510                let keep = !quarantined_idx.contains(&keep_idx);
511                keep_idx += 1;
512                keep
513            });
514        }
515
516        // Parse-time relation validation runs after every mount's
517        // entities are loaded so cross-mem target types are
518        // resolvable. Hand-edits, external tooling, and embedder
519        // editor surfaces can inject relations that bypass
520        // `memstead_relate`; this is the only place those get caught.
521        // Mutation paths pre-validate before writing, so they
522        // never trip the warning post-load.
523        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> =
524            mounted
525                .iter()
526                .map(|m| (m.mount.mem.clone(), m.mount.capability))
527                .collect();
528        crate::entity::store_builder::validate_loaded_relations(
529            &mut store,
530            &schemas,
531            &mount_caps,
532            &mut load_warnings,
533        );
534
535        // Stamp `EdgeSource::BodyLink` on edges whose rel-type matches
536        // the source mem's `alias_target_rel_type` pointer. Runs
537        // after `validate_loaded_relations` so the surviving relation
538        // set is schema-clean before the labeling pass.
539        crate::entity::store_builder::remap_alias_target_edge_sources(&mut store, &schemas);
540
541        // The nested-prefix drift scan runs per mount, so a cross-mem
542        // link into a mem loaded LATER in the mount order probes an
543        // incomplete store and false-positives on a perfectly valid id
544        // (e.g. `registry--registry-service` referenced from a mem that
545        // mounts before `registry`). Now that every mount is loaded,
546        // drop any hit whose resolved target exists as a real entity —
547        // the same legitimate-cross-mem-reference exemption the
548        // in-batch scan already applies when load order permits.
549        load_warnings.retain(|w| match w {
550            WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
551                store.get(resolved_id).is_none_or(|e| e.stub)
552            }
553            _ => true,
554        });
555
556        // Derive the runtime mem router from the mount list.
557        // Mirrors full's `Engine::from_init` step that registers every
558        // mount with `MemRouterSnapshot` so handlers reach a
559        // consistent writable/visible roster regardless of which
560        // backend serves the mem.
561        let mem_router = build_mem_router_from_mounts(&mounted);
562
563        // The baseline a later `persist_state` diffs against: the roster
564        // as handed to this constructor. A mount quarantined before this
565        // point is deliberately absent from it, so the merge treats its
566        // on-disk record as "not ours to remove" and leaves it standing —
567        // degrade, never disappear.
568        let mounts_baseline =
569            std::cell::RefCell::new(mounted.iter().map(|m| m.mount.clone()).collect::<Vec<_>>());
570
571        Ok(Self {
572            mounts: mounted,
573            mounts_baseline,
574            store,
575            schemas,
576            workspace_schemas,
577            builtin_schemas: builtin_schemas_only,
578            load_errors,
579            community_memo: OnceCell::new(),
580            labelling_memo: OnceCell::new(),
581            #[cfg(not(target_arch = "wasm32"))]
582            search_indexes_memo: OnceCell::new(),
583            settings: WorkspaceSettings::default(),
584            create_rule_set_memo: OnceCell::new(),
585            declared_origins: HashMap::new(),
586            workspace_root: None,
587            load_warnings,
588            quarantined,
589            boot_diagnosis: None,
590            pipeline_configs: crate::pipeline_store::BindingConfigs::default(),
591            mem_router: Arc::new(mem_router),
592            backend_factory: crate::workspace_store::instantiate_local_backend,
593            unmounted_storage_prober: None,
594            schemas_epoch: 0,
595            git_branch_ops: None,
596            event_subscribers: Arc::new(std::sync::Mutex::new(
597                crate::engine::events::SubscriberRegistry::new(),
598            )),
599            pending_mem_changed: Vec::new(),
600            roster_fingerprint: None,
601            roster_subscribers: Arc::new(std::sync::Mutex::new((0, Vec::new()))),
602            recently_unmounted: std::collections::HashSet::new(),
603            #[cfg(test)]
604            inject_unmount_failure: None,
605            mutation_clock: Arc::new(crate::engine::mutation::wall_clock_now),
606            current_role: crate::vcs::Role::Unspecified,
607            current_identity: None,
608        })
609    }
610
611    /// Boot an engine from a workspace root using only the local
612    /// backends (folder + archive): the folder boot path. The CLI's
613    /// folder-workspace path reaches the engine through this entry
614    /// point; git-branch mounts quarantine unless a backend factory is set.
615    ///
616    /// Loads the workspace through [`crate::FileWorkspaceStore`],
617    /// instantiates each mount's backend via
618    /// [`crate::instantiate_local_backend`], and constructs the
619    /// engine via [`Engine::from_mounts`].
620    ///
621    /// Errors:
622    /// - [`Layout::Empty`](crate::Layout) → [`BootError::NotInitialised`]
623    /// - any mount declaring [`crate::workspace::MountStorage::GitBranch`]
624    ///   → [`BootError::Instantiate`] wrapping
625    ///   [`crate::InstantiateError::GitBranchBackendUnavailable`]
626    /// - underlying store / engine failures lift through the
627    ///   `#[from]` conversions
628    pub fn from_workspace_root(workspace_root: &Path) -> Result<Self, BootError> {
629        use crate::workspace_store::{
630            FileWorkspaceStore, Layout, WorkspaceStoreAdapter, detect_layout,
631            instantiate_local_backend,
632        };
633
634        let workspace = match detect_layout(workspace_root) {
635            // Standalone collapse: a bare folder mem (`.memstead/config.json`,
636            // no `workspace.toml`) roots as a one-mount workspace rather than
637            // refusing — the lone-mem boot path is the unified one.
638            Layout::Empty => match crate::workspace_store::standalone_workspace(workspace_root) {
639                Some(ws) => ws,
640                None => {
641                    return Err(BootError::NotInitialised(workspace_root.to_path_buf()));
642                }
643            },
644            Layout::New => FileWorkspaceStore::new().load(workspace_root)?,
645        };
646
647        let settings = workspace.settings.clone();
648        let mut mounts: Vec<(Mount, Box<dyn MemBackend>)> =
649            Vec::with_capacity(workspace.mounts.len());
650        // Backend-instantiation failures quarantine the mem instead of
651        // failing the workspace (degrade, never disappear); the roster
652        // entry lands on the engine after construction.
653        let mut instantiate_quarantine: Vec<crate::engine::QuarantinedMem> = Vec::new();
654        for mount in workspace.mounts {
655            match instantiate_local_backend(&mount) {
656                Ok(backend) => mounts.push((mount, backend)),
657                Err(e) => instantiate_quarantine.push(crate::engine::QuarantinedMem {
658                    reason_code: e.code().to_string(),
659                    reason_message: e.to_string(),
660                    mount,
661                }),
662            }
663        }
664        // Folder-backend authoring path: authored schema packages live
665        // at the fixed `<workspace>/.memstead/schemas/<name>@<version>/`
666        // location — the folder analogue of the git-branch backend's
667        // `__MEMSTEAD:schemas/` ref. Read them through the folder
668        // `SchemaSource` (which no-ops when the directory is absent, so a
669        // workspace that authored no schemas resolves exactly as before —
670        // built-ins only). This is the folder boot path's schema-authoring
671        // path, which it lacked.
672        let fixed_dir = workspace_root.join(".memstead").join("schemas");
673        let (local, failed) = load_workspace_schemas_with_failures(Some(fixed_dir.as_path()));
674        // Root is known here, so an unresolved pin can be enriched with
675        // the never-installed-package hint before it surfaces.
676        let mut engine = Engine::from_mounts_inner(mounts, local, failed)
677            .map_err(|e| e.with_schema_install_probe(Some(workspace_root)))?;
678        engine.quarantined.extend(instantiate_quarantine);
679        engine.set_settings(settings);
680        engine.workspace_root = Some(workspace_root.to_path_buf());
681        engine.capture_roster_fingerprint();
682        // Load the workspace store's pipeline configs — the v2 single-record
683        // binding store — and expose them read-only. A malformed config
684        // surfaces a typed `StoreError::Parse` naming the file (early
685        // validation of operator-edited configs); an absent `projections/`
686        // directory resolves to empty. A file in a retired binding format
687        // quarantines its binding with `StoreError::LegacyProjectionStore`
688        // (the engine never reads a prior generation and no longer converts
689        // one; the binding is re-authored with `memstead projection init`).
690        engine.set_pipeline_configs(crate::pipeline_store::load_pipeline_configs(
691            workspace_root,
692        )?);
693        // The authoring meta-schemas are NOT published here. They are an
694        // editor convenience for hand-authored schema YAML, and publishing
695        // them at boot made every read of a mem write to the directory it
696        // read: pointing the binary at a workspace stamped a newer binary's
697        // meta-schemas over the ones on disk. That broke read-only mounts,
698        // installed third-party mems, and sealed corpora, which cannot be
699        // verified without being modified. Publishing now happens in the
700        // schema-authoring commands (`memstead schema new` / `validate` /
701        // `install`), the only paths that produce YAML an editor validates.
702        // Boot is a read; a read does not write.
703        Ok(engine)
704    }
705}
706
707/// Derive a [`MemRouterSnapshot`] from the engine's resolved mount
708/// list. Mirrors full's `Engine::from_init` mount-register loop so the
709/// runtime router carries the same writable/visible roster regardless
710/// of which backend serves each mem.
711///
712/// One pass over the mounts:
713/// - Writable mounts ([`MountCapability::Write`]) register via
714///   `add_writable` with the storage's worktree path. Folder mounts
715///   surface `MountStorage::Folder.path`; git-branch mounts surface
716///   `None` (the mem content lives only inside the gitdir).
717///   Archive mounts should never be writable; if one slips through,
718///   it registers with `dir: None`.
719/// - Read-only folder / git-branch mounts also register via
720///   `add_writable` with `dir: None`, then are *visible-only* —
721///   `is_writable` returns `false` because we follow up with a
722///   `remove_writable` (no-op for archives because archives are
723///   registered as `add_read_only`).
724///
725/// Actually we keep it simple: writable mounts go through
726/// `add_writable`; read-only mounts go through `add_read_only` with
727/// a synthesized archive-style path. For folder/git-branch read-only
728/// mounts we use the path the storage offers as the archive_path
729/// argument — semantically wrong but the router treats
730/// `add_read_only` data as opaque for visibility tracking. The two
731/// callers that care (`archive_path_for_mem`, `dir_for_mem`)
732/// branch on backend type at the handler level rather than reading
733/// these synthesized paths.
734///
735/// Origin is `MemOrigin::ExplicitToml` for every mount built from
736/// `Workspace.mounts` — the file-adapter case. `RuntimeCreated`
737/// origins land when `memstead_mem_create` migrates onto the unified
738/// engine and produces fresh runtime registrations.
739pub(crate) fn build_mem_router_from_mounts(mounts: &[MountedBackend]) -> MemRouterSnapshot {
740    let mut router = MemRouterSnapshot::new();
741    for m in mounts {
742        match m.mount.capability {
743            MountCapability::Write => {
744                let dir: Option<PathBuf> = match &m.mount.storage {
745                    MountStorage::Folder { path } => Some(path.clone()),
746                    MountStorage::GitBranch { .. } => None,
747                    MountStorage::Archive { .. } => None,
748                    // In-memory mounts have no on-disk working dir —
749                    // they register writable with `dir: None`, the same
750                    // shape mem-repo-backed mounts use.
751                    MountStorage::InMemory => None,
752                };
753                router.add_writable(m.mount.mem.clone(), dir, MemOrigin::ExplicitToml);
754            }
755            MountCapability::ReadOnly => match &m.mount.storage {
756                MountStorage::Archive { path } => {
757                    router.add_read_only(m.mount.mem.clone(), path.clone());
758                }
759                MountStorage::Folder { path } => {
760                    router.add_read_only(m.mount.mem.clone(), path.clone());
761                }
762                MountStorage::GitBranch { gitdir, .. } => {
763                    router.add_read_only(m.mount.mem.clone(), gitdir.clone());
764                }
765                // A read-only in-memory mount has no on-disk read
766                // source to register. The engine never produces this
767                // configuration (in-memory mounts are created writable
768                // for ephemeral sessions); handled here only to keep
769                // the match total.
770                MountStorage::InMemory => {}
771            },
772        }
773    }
774    router
775}
776
777/// Public re-export of [`resolve_builtin_schema_pin`] for the lifecycle
778/// orchestrators in `crate::mem_management`. Mirrors the orchestrators'
779/// `resolve_mem_schema` against the built-in catalogue;
780/// workspace-schema-registry resolution lifts later.
781pub fn resolve_builtin_schema_pin_pub(
782    pin: &memstead_schema::SchemaRef,
783    catalogue: &[Arc<memstead_schema::Schema>],
784) -> Option<Arc<memstead_schema::Schema>> {
785    resolve_builtin_schema_pin(pin, catalogue)
786}
787
788/// The newest version registered in the built-in catalogue under
789/// `name` — real `semver::Version` ordering (0.10.0 beats 0.9.0),
790/// never string ordering. `None` when no built-in carries the name.
791/// Feeds the `SCHEMA_GENERATIONS_BEHIND` boot hint.
792fn newest_builtin_version<'a>(
793    name: &str,
794    builtins: &'a [Arc<memstead_schema::Schema>],
795) -> Option<&'a semver::Version> {
796    builtins
797        .iter()
798        .filter(|s| s.manifest.name == name)
799        .map(|s| &s.version)
800        .max()
801}
802
803/// The engine's schema-pin resolver — the single named entry point a
804/// load path resolves a `name@version` pin through. Consults schema
805/// sources in a fixed order: **local storage** (the mem's own storage
806/// backend — folder `.memstead/schemas/` or the git-branch
807/// `__MEMSTEAD:schemas/` ref, layered first into the catalogue so it
808/// wins on `(name, version)` collision), **built-in** (compiled into the
809/// binary), **remote** (memstead.io, reserved, not implemented). The
810/// order is fixed in code — local-over-built-in by the catalogue's
811/// insertion precedence, remote always last. On a miss it yields the
812/// per-source [`SchemaSourceDiagnostic`] trail the `SCHEMA_NOT_FOUND`
813/// envelope carries.
814///
815/// Holds a borrowed view of the merged catalogue (`local ⧺ built-in`)
816/// the boot / register paths assemble, so resolution allocates nothing.
817pub struct SchemaResolver<'a> {
818    catalogue: &'a [Arc<memstead_schema::Schema>],
819}
820
821impl<'a> SchemaResolver<'a> {
822    /// Wrap the merged resolution catalogue (workspace-authored schemas
823    /// layered over the built-in set, local winning on collision).
824    pub fn new(catalogue: &'a [Arc<memstead_schema::Schema>]) -> Self {
825        Self { catalogue }
826    }
827
828    /// Resolve a pin to its schema, or the fixed-order source
829    /// diagnostics on a miss (fed straight into
830    /// `EngineError::SchemaNotFound`'s `sources`).
831    pub fn resolve(
832        &self,
833        pin: &memstead_schema::SchemaRef,
834    ) -> Result<Arc<memstead_schema::Schema>, Vec<crate::engine::error::SchemaSourceDiagnostic>>
835    {
836        resolve_builtin_schema_pin(pin, self.catalogue).ok_or_else(|| {
837            crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
838                &pin.name,
839                &pin.version,
840                self.catalogue,
841            )
842        })
843    }
844}
845
846/// Walk `schemas_dir` and load every immediate subdirectory as a
847/// workspace-authored schema. Each subdirectory must contain a
848/// `schema.yaml` manifest (and optional `types/*.yaml`) — silently
849/// skips entries that don't carry the manifest. `pub` so the folder
850/// `SchemaSource` and the below-boot repair path (memstead-git-branch)
851/// read through the same walker the boot path uses — one loader, no
852/// resolution fork between the booted and below-boot surfaces.
853pub fn load_workspace_schemas(
854    schemas_dir: Option<&Path>,
855) -> Result<Vec<Arc<memstead_schema::Schema>>, EngineError> {
856    Ok(load_workspace_schemas_with_failures(schemas_dir).0)
857}
858
859/// One workspace-authored schema package that failed to load — the
860/// package is SKIPPED (never fails the boot; degrade, never
861/// disappear), and a mem pinning it quarantines with this failure as
862/// its typed reason. `name`/`version` are best-effort peeks at the
863/// package's `schema.yaml` header so the pin match works even though
864/// the full load refused.
865#[derive(Debug, Clone)]
866pub struct FailedSchemaPackage {
867    pub path: PathBuf,
868    pub name: Option<String>,
869    pub version: Option<String>,
870    /// The loader's typed failure, rendered.
871    pub error: String,
872}
873
874/// The sealed schema package an archive-backed mount carries inside its
875/// `.mem` (`.memstead/schema/`), read through the same sealed reader
876/// the install validator uses, so the mount can resolve its pin from
877/// the archive itself. Empty for every other storage kind, for an
878/// archive mount with no on-disk path (the from-bytes boot already
879/// threads its embedded schemas through `extra_schemas`), and for an
880/// archive that cannot be read: the pin then fails to resolve and the
881/// mem quarantines with the ordinary not-found reason, which names the
882/// sources consulted.
883pub(crate) fn embedded_archive_schemas(mount: &Mount) -> Vec<Arc<Schema>> {
884    let crate::workspace::MountStorage::Archive { path } = &mount.storage else {
885        return Vec::new();
886    };
887    if path.as_os_str().is_empty() || !path.is_file() {
888        return Vec::new();
889    }
890    use crate::schema_source::SchemaSource as _;
891    crate::schema_source::ArchiveSchemaSource::from_path(path)
892        .ok()
893        .and_then(|source| source.read_schemas().ok())
894        .unwrap_or_default()
895}
896
897/// Tolerant form of [`load_workspace_schemas`]: broken packages are
898/// skipped and recorded instead of failing the whole walk (the
899/// historical `?` made one refusing package — e.g. a schema still on
900/// the retired `propagating_relationships` key after a binary
901/// upgrade — take every mem in the workspace down).
902pub fn load_workspace_schemas_with_failures(
903    schemas_dir: Option<&Path>,
904) -> (Vec<Arc<memstead_schema::Schema>>, Vec<FailedSchemaPackage>) {
905    let Some(dir) = schemas_dir else {
906        return (Vec::new(), Vec::new());
907    };
908    if !dir.is_dir() {
909        return (Vec::new(), Vec::new());
910    }
911    let entries = match std::fs::read_dir(dir) {
912        Ok(e) => e,
913        Err(_) => return (Vec::new(), Vec::new()),
914    };
915    let mut schemas: Vec<Arc<memstead_schema::Schema>> = Vec::new();
916    let mut failures: Vec<FailedSchemaPackage> = Vec::new();
917    for entry in entries.flatten() {
918        let path = entry.path();
919        if !path.is_dir() {
920            continue;
921        }
922        if !path.join("schema.yaml").is_file() {
923            continue;
924        }
925        match memstead_schema::load_schema_from_dir(&path) {
926            Ok(schema) => schemas.push(Arc::new(schema)),
927            Err(e) => {
928                // Best-effort header peek without a YAML dependency:
929                // top-level `name:` / `version:` are single-line
930                // scalars in every real package.
931                let header = std::fs::read_to_string(path.join("schema.yaml")).unwrap_or_default();
932                let peek = |k: &str| {
933                    header
934                        .lines()
935                        .find_map(|l| l.strip_prefix(&format!("{k}:")))
936                        .map(|v| v.trim().trim_matches('"').to_string())
937                        .filter(|v| !v.is_empty())
938                };
939                failures.push(FailedSchemaPackage {
940                    path: path.clone(),
941                    name: peek("name"),
942                    version: peek("version"),
943                    error: e.to_string(),
944                });
945            }
946        }
947    }
948    (schemas, failures)
949}
950
951pub(super) fn resolve_builtin_schema_pin(
952    pin: &memstead_schema::SchemaRef,
953    catalogue: &[Arc<memstead_schema::Schema>],
954) -> Option<Arc<memstead_schema::Schema>> {
955    catalogue
956        .iter()
957        .find(|s| {
958            let id = s.id();
959            id.0 == pin.name && id.1 == pin.version
960        })
961        .cloned()
962}
963
964/// The `MOUNT_UNBACKED` probe for one mount: `Some(warning)` when the
965/// storage the mount names does not exist (`missing_ref` /
966/// `missing_path`, from [`MemBackend::storage_present`]) or, when
967/// `entity_count` is known and zero, holds no entity (`empty`). A
968/// probe failure reads as present — best-effort, never a boot failure.
969/// Lazy mounts pass `None` for the count: their walk is deferred, so
970/// only the storage half is judged at boot.
971pub(super) fn unbacked_mount_warning(
972    mount: &crate::workspace::Mount,
973    backend: &dyn MemBackend,
974    entity_count: Option<usize>,
975) -> Option<WarningHint> {
976    use crate::ops::MountUnbackedReason;
977    use crate::workspace::MountStorage;
978    let (location, missing_reason) = match &mount.storage {
979        MountStorage::GitBranch { branch, .. } => (branch.clone(), MountUnbackedReason::MissingRef),
980        MountStorage::Folder { path } => {
981            (path.display().to_string(), MountUnbackedReason::MissingPath)
982        }
983        MountStorage::Archive { path } => {
984            (path.display().to_string(), MountUnbackedReason::MissingPath)
985        }
986        MountStorage::InMemory => return None,
987    };
988    if !backend.storage_present().unwrap_or(true) {
989        return Some(WarningHint::MountUnbacked {
990            mem: mount.mem.clone(),
991            reason: missing_reason,
992            location,
993        });
994    }
995    if entity_count == Some(0) {
996        return Some(WarningHint::MountUnbacked {
997            mem: mount.mem.clone(),
998            reason: MountUnbackedReason::Empty,
999            location,
1000        });
1001    }
1002    None
1003}
1004
1005pub(super) fn collect_source_entries(
1006    backend: &dyn MemBackend,
1007) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), EngineError> {
1008    // One backend pass for the whole mem: the git-branch backend
1009    // answers with a single tree walk, where the per-path route
1010    // re-inflated the root tree once per entity (quadratic in the
1011    // mem size — the boot cost the sizing curve reported as
1012    // super-linear).
1013    let reads = backend.read_all_entities()?;
1014    let mut entries: Vec<SourceEntry> = Vec::with_capacity(reads.len());
1015    let mut errors: Vec<SourceReadError> = Vec::new();
1016    for (path, read) in reads {
1017        match read {
1018            Ok(bytes) => match String::from_utf8(bytes) {
1019                Ok(content) => entries.push(SourceEntry {
1020                    relative_path: path.to_string_lossy().into_owned(),
1021                    source_path: path.clone(),
1022                    content,
1023                }),
1024                Err(e) => errors.push(SourceReadError {
1025                    source_path: path,
1026                    error: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
1027                }),
1028            },
1029            Err(e) => errors.push(SourceReadError {
1030                source_path: path,
1031                error: std::io::Error::other(e.to_string()),
1032            }),
1033        }
1034    }
1035    Ok((entries, errors))
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040
1041    use std::path::Path;
1042
1043    use memstead_schema::SchemaRef;
1044    use tempfile::TempDir;
1045
1046    use crate::backend::MemBackend;
1047    use crate::engine::test_helpers::*;
1048    use crate::engine::{Engine, EngineError};
1049    use crate::ops::WarningHint;
1050    use crate::storage::{ArchiveBackend, FilesystemMemWriter, MemWriter};
1051    use crate::vcs::CommitContext;
1052    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
1053
1054    /// The unbacked-mount probe on the folder backend: a path that does
1055    /// not exist is `missing_path`, an existing directory with no
1056    /// entity is `empty`, a directory holding one entity is silent, and
1057    /// a lazy mount (count unknown) is judged on storage presence only.
1058    #[test]
1059    fn unbacked_mount_probe_classes_missing_path_empty_and_present() {
1060        use crate::engine::boot::unbacked_mount_warning;
1061        use crate::ops::MountUnbackedReason;
1062        let tmp = TempDir::new().unwrap();
1063        let mount = |path: std::path::PathBuf| Mount {
1064            mem: "probe".into(),
1065            schema: None,
1066            storage: MountStorage::Folder { path },
1067            capability: MountCapability::Write,
1068            lifecycle: MountLifecycle::Eager,
1069            cross_linkable: true,
1070            migration_target: None,
1071        };
1072
1073        let gone = tmp.path().join("gone");
1074        let backend = FilesystemMemWriter::new(gone.clone());
1075        let w = unbacked_mount_warning(&mount(gone.clone()), &backend, Some(0))
1076            .expect("a missing folder is unbacked");
1077        match &w {
1078            WarningHint::MountUnbacked {
1079                mem,
1080                reason,
1081                location,
1082            } => {
1083                assert_eq!(mem, "probe");
1084                assert_eq!(*reason, MountUnbackedReason::MissingPath);
1085                assert_eq!(location, &gone.display().to_string());
1086            }
1087            other => panic!("unexpected variant: {other:?}"),
1088        }
1089        assert_eq!(w.code(), "MOUNT_UNBACKED");
1090        let json = serde_json::to_value(&w).unwrap();
1091        assert_eq!(json["details"]["reason"], "missing_path");
1092        // Lazy: storage presence alone decides, and the folder is gone.
1093        assert!(unbacked_mount_warning(&mount(gone), &backend, None).is_some());
1094
1095        let hollow = tmp.path().join("hollow");
1096        std::fs::create_dir_all(&hollow).unwrap();
1097        let backend = FilesystemMemWriter::new(hollow.clone());
1098        let w = unbacked_mount_warning(&mount(hollow.clone()), &backend, Some(0))
1099            .expect("an entity-less folder is unbacked");
1100        assert_eq!(
1101            serde_json::to_value(&w).unwrap()["details"]["reason"],
1102            "empty"
1103        );
1104        // Lazy with the folder present: nothing to say at boot.
1105        assert!(unbacked_mount_warning(&mount(hollow.clone()), &backend, None).is_none());
1106        // One entity: silent.
1107        assert!(unbacked_mount_warning(&mount(hollow), &backend, Some(1)).is_none());
1108    }
1109
1110    /// The `SchemaResolver` resolves a pin against the catalogue and, on
1111    /// a miss, yields the fixed-order (`local_storage` → `builtin` →
1112    /// `remote`) source diagnostics the `SCHEMA_NOT_FOUND` envelope carries.
1113    #[test]
1114    fn schema_resolver_resolves_builtin_and_yields_ordered_diagnostics_on_miss() {
1115        let catalogue = memstead_schema::builtins::load_builtin_schemas().unwrap();
1116        let resolver = super::SchemaResolver::new(&catalogue);
1117
1118        let ok: SchemaRef = "default@1.0.0".parse().unwrap();
1119        assert!(resolver.resolve(&ok).is_ok(), "shipped built-in resolves");
1120
1121        let miss: SchemaRef = "nope@9.9.9".parse().unwrap();
1122        let sources = resolver.resolve(&miss).unwrap_err();
1123        let labels: Vec<&str> = sources.iter().map(|s| s.source).collect();
1124        assert_eq!(labels, ["local_storage", "builtin", "remote"]);
1125        assert!(sources.iter().all(|s| !s.pinned_version_match));
1126    }
1127
1128    #[test]
1129    fn empty_mount_list_constructs_and_errors_unknown_mem_on_read() {
1130        let engine = Engine::from_mounts(Vec::new()).unwrap();
1131        assert!(engine.mem_names().is_empty());
1132        match engine.list_entities("missing") {
1133            Err(EngineError::UnknownMem(v)) => assert_eq!(v, "missing"),
1134            other => panic!("expected UnknownMem, got {other:?}"),
1135        }
1136    }
1137
1138    #[test]
1139    fn duplicate_mem_names_rejected_at_construction() {
1140        let tmp = TempDir::new().unwrap();
1141        let writer1: Box<dyn MemBackend> =
1142            Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf()));
1143        let writer2: Box<dyn MemBackend> =
1144            Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf()));
1145        let err = Engine::from_mounts(vec![
1146            (folder_mount("specs", tmp.path().to_path_buf()), writer1),
1147            (folder_mount("specs", tmp.path().to_path_buf()), writer2),
1148        ])
1149        .unwrap_err();
1150        assert!(matches!(err, EngineError::DuplicateMem(v) if v == "specs"));
1151    }
1152
1153    #[test]
1154    fn from_mounts_populates_load_warnings_from_duplicate_section_heading() {
1155        // A markdown file with the same `## Identity` heading twice
1156        // should cause the parser to emit a typed
1157        // `DuplicateSectionHeading` warning. With the
1158        // LoadCollector wiring, that warning lands on
1159        // `engine.load_warnings()`.
1160        let tmp = TempDir::new().unwrap();
1161        let mem_dir = tmp.path().to_path_buf();
1162        let body =
1163            "---\ntype: spec\n---\n# Dup\n\n## Identity\n\nfirst.\n\n## Identity\n\nsecond.\n";
1164        std::fs::write(mem_dir.join("dup.md"), body).unwrap();
1165
1166        let writer = FilesystemMemWriter::new(mem_dir.clone());
1167        let engine = Engine::from_mounts(vec![(
1168            folder_mount("specs", mem_dir),
1169            Box::new(writer) as Box<dyn MemBackend>,
1170        )])
1171        .unwrap();
1172
1173        let warnings = engine.load_warnings();
1174        assert!(
1175            warnings
1176                .iter()
1177                .any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
1178            "load_warnings must surface DuplicateSectionHeading: {warnings:?}",
1179        );
1180    }
1181
1182    /// Generation-behind hint: a mem pinning an OLD built-in
1183    /// generation (`default@1.0.0`; the catalogue retains up to
1184    /// 1.2.0) boots with the warn-tier `SCHEMA_GENERATIONS_BEHIND`
1185    /// naming the pinned ref and the newest version — and the hint
1186    /// never blocks: the boot serves and mutations succeed. A mem
1187    /// pinning the NEWEST generation stays silent, so its health
1188    /// output is unchanged.
1189    #[test]
1190    fn generation_behind_hint_fires_for_old_builtin_pin_only() {
1191        // Old pin → hint, non-blocking.
1192        let tmp = TempDir::new().unwrap();
1193        let mem_dir = tmp.path().to_path_buf();
1194        let writer = FilesystemMemWriter::new(mem_dir.clone());
1195        let mut engine = Engine::from_mounts(vec![(
1196            folder_mount("specs", mem_dir),
1197            Box::new(writer) as Box<dyn MemBackend>,
1198        )])
1199        .unwrap();
1200        let behind: Vec<_> = engine
1201            .load_warnings()
1202            .iter()
1203            .filter_map(|w| match w {
1204                WarningHint::SchemaGenerationsBehind {
1205                    mem,
1206                    pinned,
1207                    newest,
1208                } => Some((mem.clone(), pinned.clone(), newest.clone())),
1209                _ => None,
1210            })
1211            .collect();
1212        assert_eq!(
1213            behind,
1214            vec![(
1215                "specs".to_string(),
1216                "default@1.0.0".to_string(),
1217                "1.3.0".to_string()
1218            )],
1219            "old built-in pin must surface the generation-behind hint"
1220        );
1221        assert!(
1222            engine
1223                .health()
1224                .warnings
1225                .iter()
1226                .any(|w| w.code() == "SCHEMA_GENERATIONS_BEHIND"),
1227            "the hint rides health without an include gate"
1228        );
1229        // Never blocking: the warned mem still mutates.
1230        engine
1231            .create_entity_with_ctx(
1232                crate::engine::CreateEntityArgs {
1233                    anchors: Vec::new(),
1234                    mem: "specs".to_string(),
1235                    title: "Still writable".to_string(),
1236                    entity_type: "spec".to_string(),
1237                    sections: indexmap::IndexMap::from_iter([
1238                        ("identity".to_string(), "i".to_string()),
1239                        ("purpose".to_string(), "p".to_string()),
1240                    ]),
1241                    metadata: indexmap::IndexMap::new(),
1242                    relations: Vec::new(),
1243                    dry_run: false,
1244                },
1245                &crate::vcs::CommitContext::internal(),
1246            )
1247            .expect("generation-behind hint must never block mutations");
1248
1249        // Newest pin → silent (health output unchanged).
1250        let tmp = TempDir::new().unwrap();
1251        let mem_dir = tmp.path().to_path_buf();
1252        let writer = FilesystemMemWriter::new(mem_dir.clone());
1253        let mut mount = folder_mount("specs", mem_dir);
1254        mount.schema = Some("default@1.3.0".parse().unwrap());
1255        let engine =
1256            Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
1257        assert!(
1258            !engine
1259                .load_warnings()
1260                .iter()
1261                .any(|w| w.code() == "SCHEMA_GENERATIONS_BEHIND"),
1262            "newest built-in pin must stay silent: {:?}",
1263            engine.load_warnings()
1264        );
1265        let health_json = serde_json::to_string(&engine.health().warnings).unwrap();
1266        assert!(
1267            !health_json.contains("SCHEMA_GENERATIONS_BEHIND"),
1268            "newest pin: health output carries no generation hint"
1269        );
1270    }
1271
1272    /// The newest-generation lookup uses real semver ordering — a
1273    /// two-digit minor beats a one-digit one (string ordering would
1274    /// invert them).
1275    #[test]
1276    fn newest_builtin_version_orders_by_semver_not_string() {
1277        let manifest = |version: &str| {
1278            format!(
1279                r#"name: gen-test
1280version: {version}
1281description: test
1282when_to_use: test
1283types:
1284  - note
1285relationships:
1286  mode: strict
1287  definitions:
1288    - name: _default
1289      description: default
1290      default_weight: 1.0
1291    - name: PART_OF
1292      description: hier
1293      default_weight: 3.0
1294community:
1295  resolution: 1.0
1296  seed: 42
1297"#
1298            )
1299        };
1300        let type_yaml = r#"name: note
1301description: test
1302when_to_use: test
1303sections:
1304  - key: body
1305    heading: Body
1306    required: true
1307    search_weight: 10.0
1308    catch_all: true
1309metadata_fields: []
1310title_weight: 1.0
1311text_fields: [body]
1312hierarchy_relationship: PART_OF
1313no_self_loop_relationships: []
1314updatable_fields: [title, body]
1315health_required_fields: [body]
1316staleness_threshold_days: 30
1317write_rules: []
1318"#;
1319        let types = vec![("note".to_string(), type_yaml.to_string())];
1320        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = ["0.9.0", "0.10.0", "0.2.0"]
1321            .iter()
1322            .map(|v| {
1323                std::sync::Arc::new(
1324                    memstead_schema::load_schema_from_memory(&manifest(v), &types)
1325                        .expect("fixture schema loads"),
1326                )
1327            })
1328            .collect();
1329        let newest = super::newest_builtin_version("gen-test", &catalogue)
1330            .expect("name present in catalogue");
1331        assert_eq!(newest.to_string(), "0.10.0", "semver, not string, ordering");
1332        assert!(super::newest_builtin_version("absent", &catalogue).is_none());
1333    }
1334
1335    /// Parse-time relation validation drops relations whose `rel_type`
1336    /// is not declared in the source mem's strict-mode schema and
1337    /// emits `PARSED_RELATION_INVALID { reason: "unknown_rel_type" }`.
1338    /// The entity itself loads normally; only the bad relation goes
1339    /// missing from the in-memory store.
1340    #[test]
1341    fn from_mounts_drops_unknown_rel_type_from_hand_edit_with_warning() {
1342        let tmp = TempDir::new().unwrap();
1343        let mem_dir = tmp.path().to_path_buf();
1344        // Hand-authored markdown with a `## Relationships` entry whose
1345        // type isn't declared in the default schema (strict mode).
1346        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nThe target.\n";
1347        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
1348        std::fs::write(mem_dir.join("target.md"), target).unwrap();
1349        std::fs::write(mem_dir.join("source.md"), source).unwrap();
1350
1351        let writer = FilesystemMemWriter::new(mem_dir.clone());
1352        let engine = Engine::from_mounts(vec![(
1353            folder_mount("specs", mem_dir),
1354            Box::new(writer) as Box<dyn MemBackend>,
1355        )])
1356        .unwrap();
1357
1358        let source_id = crate::entity::EntityId::new("specs", "source");
1359        let target_id = crate::entity::EntityId::new("specs", "target");
1360        let source_entity = engine.get_entity(&source_id).expect("source loaded");
1361        // The offending relation does not survive into the entity's
1362        // in-memory relationships list.
1363        assert!(
1364            source_entity.relationships.is_empty(),
1365            "MADE_UP_TYPE relation must be dropped from entity.relationships, got: {:?}",
1366            source_entity.relationships,
1367        );
1368        // Nor into the store's edge index.
1369        let outgoing: Vec<_> = engine
1370            .store()
1371            .outgoing(&source_id)
1372            .iter()
1373            .filter(|e| e.rel_type == "MADE_UP_TYPE")
1374            .collect();
1375        assert!(
1376            outgoing.is_empty(),
1377            "MADE_UP_TYPE edge must be dropped from the store"
1378        );
1379        // The warning surfaces with the correct payload.
1380        let parsed_invalid: Vec<_> = engine
1381            .load_warnings()
1382            .iter()
1383            .filter_map(|w| match w {
1384                WarningHint::ParsedRelationInvalid {
1385                    entity_id,
1386                    rel_type,
1387                    target,
1388                    reason,
1389                    origin,
1390                    recovery,
1391                } => Some((
1392                    entity_id.clone(),
1393                    rel_type.clone(),
1394                    target.clone(),
1395                    reason.clone(),
1396                    origin.clone(),
1397                    recovery.clone(),
1398                )),
1399                _ => None,
1400            })
1401            .collect();
1402        assert_eq!(
1403            parsed_invalid.len(),
1404            1,
1405            "expected one warning, got {parsed_invalid:?}"
1406        );
1407        assert_eq!(parsed_invalid[0].0, source_id);
1408        assert_eq!(parsed_invalid[0].1, "MADE_UP_TYPE");
1409        assert_eq!(parsed_invalid[0].2, target_id);
1410        assert_eq!(parsed_invalid[0].3, "unknown_rel_type");
1411        assert_eq!(parsed_invalid[0].4, "writable");
1412        // Writable-origin warnings carry the abstract recovery action.
1413        let recovery = parsed_invalid[0]
1414            .5
1415            .as_ref()
1416            .expect("writable-origin warning must carry recovery");
1417        assert_eq!(
1418            recovery.kind,
1419            crate::ops::ParsedRelationRecovery::KIND_REMOVE_EXPLICIT_RELATION
1420        );
1421        assert_eq!(recovery.source_id, parsed_invalid[0].0);
1422        assert_eq!(recovery.target_id, parsed_invalid[0].2);
1423        assert_eq!(recovery.rel_type, parsed_invalid[0].1);
1424    }
1425
1426    /// Hand-edited markdown can inject a cycle in an `acyclic: true`
1427    /// rel-type's subgraph — the mutation surface's `would_cycle`
1428    /// guard never fires for that path. The boot validator's
1429    /// second pass finds the back-edge and drops it with
1430    /// `reason: "cycle"`. The entity itself loads normally; one of
1431    /// the two cycle-closing edges goes missing from the in-memory
1432    /// store; the other survives.
1433    #[test]
1434    fn from_mounts_drops_cycle_closing_edge_in_acyclic_subgraph() {
1435        let tmp = TempDir::new().unwrap();
1436        let mem_dir = tmp.path().to_path_buf();
1437        // Mutual PART_OF — acyclic in the default schema. The
1438        // wiki-link grammar admits both as well-formed cross-
1439        // references, so only the cycle pass can catch this.
1440        let alpha = "---\ntype: spec\n---\n# Alpha\n\n## Identity\n\nfirst.\n\n## Relationships\n\n- **PART_OF**: [[specs--beta]]\n";
1441        let beta = "---\ntype: spec\n---\n# Beta\n\n## Identity\n\nsecond.\n\n## Relationships\n\n- **PART_OF**: [[specs--alpha]]\n";
1442        std::fs::write(mem_dir.join("alpha.md"), alpha).unwrap();
1443        std::fs::write(mem_dir.join("beta.md"), beta).unwrap();
1444
1445        let writer = FilesystemMemWriter::new(mem_dir.clone());
1446        let engine = Engine::from_mounts(vec![(
1447            folder_mount("specs", mem_dir),
1448            Box::new(writer) as Box<dyn MemBackend>,
1449        )])
1450        .unwrap();
1451
1452        let alpha_id = crate::entity::EntityId::new("specs", "alpha");
1453        let beta_id = crate::entity::EntityId::new("specs", "beta");
1454
1455        // Both entities are real — only the relation in the cycle
1456        // gets dropped.
1457        assert!(engine.get_entity(&alpha_id).is_some_and(|e| !e.stub));
1458        assert!(engine.get_entity(&beta_id).is_some_and(|e| !e.stub));
1459
1460        // Exactly one of the two PART_OF edges survives — the cycle
1461        // is broken by dropping a single back-edge.
1462        let surviving: Vec<_> = engine
1463            .store()
1464            .all_entities()
1465            .flat_map(|e| {
1466                engine
1467                    .store()
1468                    .outgoing(&e.id)
1469                    .iter()
1470                    .filter(|edge| edge.rel_type == "PART_OF")
1471                    .map(|edge| (e.id.clone(), edge.target.clone()))
1472                    .collect::<Vec<_>>()
1473            })
1474            .collect();
1475        assert_eq!(
1476            surviving.len(),
1477            1,
1478            "exactly one PART_OF edge must survive the cycle break, got {surviving:?}",
1479        );
1480
1481        // The warning surfaces with `reason: "cycle"` and names the
1482        // dropped pair.
1483        let cycle_drops: Vec<_> = engine
1484            .load_warnings()
1485            .iter()
1486            .filter_map(|w| match w {
1487                WarningHint::ParsedRelationInvalid {
1488                    entity_id,
1489                    rel_type,
1490                    target,
1491                    reason,
1492                    ..
1493                } if reason == "cycle" => {
1494                    Some((entity_id.clone(), rel_type.clone(), target.clone()))
1495                }
1496                _ => None,
1497            })
1498            .collect();
1499        assert_eq!(
1500            cycle_drops.len(),
1501            1,
1502            "exactly one cycle warning must fire, got {cycle_drops:?}",
1503        );
1504        // The dropped edge is one of the two PART_OF entries.
1505        let (dropped_from, dropped_rel_type, dropped_to) = &cycle_drops[0];
1506        assert_eq!(dropped_rel_type, "PART_OF");
1507        let is_alpha_to_beta = dropped_from == &alpha_id && dropped_to == &beta_id;
1508        let is_beta_to_alpha = dropped_from == &beta_id && dropped_to == &alpha_id;
1509        assert!(
1510            is_alpha_to_beta || is_beta_to_alpha,
1511            "dropped edge must be one of the mutual PART_OF pair, got ({dropped_from} -> {dropped_to})",
1512        );
1513        // And the surviving edge isn't the same as the dropped one.
1514        assert_ne!(
1515            (&surviving[0].0, &surviving[0].1),
1516            (dropped_from, dropped_to),
1517            "surviving edge must differ from the dropped one",
1518        );
1519    }
1520
1521    /// The per-mount nested-prefix drift scan probes an incomplete
1522    /// store: a cross-mem link into a mem loaded LATER in the mount
1523    /// order can't see the real target yet and would false-positive on
1524    /// a perfectly valid id whose slug repeats its mem name (the
1525    /// `registry--registry-service` case). The post-load sweep must
1526    /// drop that hit — while a genuine drift link (target never
1527    /// materialises as a real entity) keeps its warning.
1528    #[test]
1529    fn nested_prefix_warning_exempts_real_cross_mem_target_loaded_later() {
1530        let tmp = TempDir::new().unwrap();
1531        let project_dir = tmp.path().join("project");
1532        let registry_dir = tmp.path().join("registry");
1533        std::fs::create_dir_all(&project_dir).unwrap();
1534        std::fs::create_dir_all(&registry_dir).unwrap();
1535
1536        // Mount 1 (loads first) links both a real later-loaded entity
1537        // and a genuinely missing one.
1538        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nReal: [[registry--registry-service]]. Drifted: [[registry--never-created]].\n";
1539        std::fs::write(project_dir.join("source.md"), source).unwrap();
1540
1541        // Mount 2 (loads second) carries the real target whose slug
1542        // repeats its mem name — the shape the heuristic suspects.
1543        let service = "---\ntype: spec\n---\n# Registry Service\n\n## Identity\n\nA real entity.\n";
1544        std::fs::write(registry_dir.join("registry-service.md"), service).unwrap();
1545
1546        let engine = Engine::from_mounts(vec![
1547            (
1548                folder_mount("project", project_dir.clone()),
1549                Box::new(FilesystemMemWriter::new(project_dir)) as Box<dyn MemBackend>,
1550            ),
1551            (
1552                folder_mount("registry", registry_dir.clone()),
1553                Box::new(FilesystemMemWriter::new(registry_dir)) as Box<dyn MemBackend>,
1554            ),
1555        ])
1556        .unwrap();
1557
1558        let nested: Vec<_> = engine
1559            .load_warnings()
1560            .iter()
1561            .filter_map(|w| match w {
1562                WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
1563                    Some(resolved_id.to_string())
1564                }
1565                _ => None,
1566            })
1567            .collect();
1568        assert!(
1569            !nested.contains(&"registry--registry-service".to_string()),
1570            "a valid cross-mem id resolving to a real entity must not warn, got {nested:?}",
1571        );
1572        assert!(
1573            nested.contains(&"registry--never-created".to_string()),
1574            "a genuinely unresolved nested-prefix link must keep its warning, got {nested:?}",
1575        );
1576    }
1577
1578    /// Shape-invalid relations on a writable-origin mount get dropped
1579    /// with `reason: "shape"`; the warning carries a
1580    /// `remove_explicit_relation` recovery hint whose ids and rel-type
1581    /// mirror the warning's top-level fields. Same envelope shape as
1582    /// the `unknown_rel_type` reason — `reason` discriminates the
1583    /// cause; `recovery.kind` discriminates the action. Uses a
1584    /// synthetic schema with `source_types` / `target_types`
1585    /// constraints because the default schema's rel-types are
1586    /// unconstrained.
1587    #[test]
1588    fn from_mounts_emits_recovery_hint_for_writable_shape_drop() {
1589        use crate::engine::test_helpers::write_schema_files_with_default_type;
1590
1591        let tmp = TempDir::new().unwrap();
1592        let schemas_dir = tmp.path().join("schemas");
1593        std::fs::create_dir_all(&schemas_dir).unwrap();
1594        // A schema declaring a single rel-type whose shape only
1595        // admits `actor -> doc`. The source markdown below uses
1596        // `doc -> doc`, which trips the shape validator.
1597        let manifest = r#"name: shape-test
1598version: 0.1.0
1599description: shape-constraint schema
1600when_to_use: tests
1601types:
1602  - doc
1603  - actor
1604relationships:
1605  mode: strict
1606  definitions:
1607    - name: OWNS
1608      description: actor owns doc
1609      default_weight: 1.0
1610      source_types: [actor]
1611      target_types: [doc]
1612    - name: _default
1613      description: fallback
1614      default_weight: 1.0
1615community:
1616  resolution: 1.0
1617  seed: 42
1618"#;
1619        write_schema_files_with_default_type(
1620            &schemas_dir,
1621            "shape-test",
1622            manifest,
1623            &["doc", "actor"],
1624        );
1625
1626        let mem_dir = tmp.path().join("mem");
1627        std::fs::create_dir_all(&mem_dir).unwrap();
1628        // Source is type `doc`; target is also type `doc`. The
1629        // declared `OWNS` rel-type expects `actor -> doc`, so the
1630        // shape check rejects this pair at load.
1631        let target = "---\ntype: doc\n---\n# Target\n\n## Body\n\nthe target\n";
1632        let source = "---\ntype: doc\n---\n# Source\n\n## Body\n\nthe source\n\n## Relationships\n\n- **OWNS**: [[specs--target]]\n";
1633        std::fs::write(mem_dir.join("target.md"), target).unwrap();
1634        std::fs::write(mem_dir.join("source.md"), source).unwrap();
1635
1636        let writer = FilesystemMemWriter::new(mem_dir.clone());
1637        let pin = SchemaRef::new("shape-test", semver::Version::new(0, 1, 0));
1638        let mount = Mount {
1639            mem: "specs".to_string(),
1640            schema: Some(pin),
1641            storage: MountStorage::Folder { path: mem_dir },
1642            capability: MountCapability::Write,
1643            lifecycle: MountLifecycle::Eager,
1644            cross_linkable: true,
1645            migration_target: None,
1646        };
1647        let engine = Engine::from_mounts_with_schemas_dir(
1648            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
1649            Some(&schemas_dir),
1650        )
1651        .unwrap();
1652
1653        let source_id = crate::entity::EntityId::new("specs", "source");
1654        let target_id = crate::entity::EntityId::new("specs", "target");
1655
1656        let shape_drops: Vec<_> = engine
1657            .load_warnings()
1658            .iter()
1659            .filter_map(|w| match w {
1660                WarningHint::ParsedRelationInvalid {
1661                    entity_id,
1662                    rel_type,
1663                    target,
1664                    reason,
1665                    origin,
1666                    recovery,
1667                } if reason == "shape" => Some((
1668                    entity_id.clone(),
1669                    rel_type.clone(),
1670                    target.clone(),
1671                    origin.clone(),
1672                    recovery.clone(),
1673                )),
1674                _ => None,
1675            })
1676            .collect();
1677        assert_eq!(
1678            shape_drops.len(),
1679            1,
1680            "expected one shape-reason warning, got {shape_drops:?}; all warnings = {:?}",
1681            engine.load_warnings(),
1682        );
1683        let (drop_from, drop_type, drop_to, drop_origin, drop_recovery) =
1684            shape_drops.into_iter().next().unwrap();
1685        assert_eq!(drop_from, source_id);
1686        assert_eq!(drop_type, "OWNS");
1687        assert_eq!(drop_to, target_id);
1688        assert_eq!(drop_origin, "writable");
1689        // Recovery mirrors the warning's top-level fields and names
1690        // the abstract `remove_explicit_relation` action.
1691        let recovery = drop_recovery.expect("writable origin must carry recovery");
1692        assert_eq!(
1693            recovery.kind,
1694            crate::ops::ParsedRelationRecovery::KIND_REMOVE_EXPLICIT_RELATION
1695        );
1696        assert_eq!(recovery.source_id, source_id);
1697        assert_eq!(recovery.target_id, target_id);
1698        assert_eq!(recovery.rel_type, "OWNS");
1699    }
1700
1701    /// Read-only-origin warnings omit the recovery hint — the engine
1702    /// cannot rewrite a read-only mount's markdown, so no abstract
1703    /// action is available. The message field still names the
1704    /// operator-level path (uninstall the archive or accept the
1705    /// drift); structured consumers branch on `recovery.is_none()`.
1706    #[test]
1707    fn from_mounts_emits_no_recovery_hint_for_readonly_origin() {
1708        let tmp = TempDir::new().unwrap();
1709        // Archive content with a `MADE_UP_TYPE` row that the schema
1710        // does not declare — parses to a `PARSED_RELATION_INVALID`
1711        // with `reason: "unknown_rel_type"` on a read-only mount.
1712        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nThe target.\n";
1713        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[external--target]]\n";
1714        let archive_path = build_archive(
1715            tmp.path(),
1716            "ext",
1717            &[
1718                ("target.md", target.as_bytes()),
1719                ("source.md", source.as_bytes()),
1720            ],
1721        );
1722
1723        let engine = Engine::from_mounts(vec![(
1724            archive_mount("external", archive_path.clone()),
1725            Box::new(ArchiveBackend::new(archive_path)),
1726        )])
1727        .unwrap();
1728
1729        let invalid: Vec<_> = engine
1730            .load_warnings()
1731            .iter()
1732            .filter_map(|w| match w {
1733                WarningHint::ParsedRelationInvalid {
1734                    rel_type,
1735                    reason,
1736                    origin,
1737                    recovery,
1738                    ..
1739                } => Some((
1740                    rel_type.clone(),
1741                    reason.clone(),
1742                    origin.clone(),
1743                    recovery.clone(),
1744                )),
1745                _ => None,
1746            })
1747            .collect();
1748        assert_eq!(
1749            invalid.len(),
1750            1,
1751            "expected one parse-time drop on the readonly mount, got {invalid:?}",
1752        );
1753        assert_eq!(invalid[0].0, "MADE_UP_TYPE");
1754        assert_eq!(invalid[0].1, "unknown_rel_type");
1755        assert_eq!(invalid[0].2, "readonly");
1756        assert!(
1757            invalid[0].3.is_none(),
1758            "readonly-origin warning must omit the recovery hint, got {:?}",
1759            invalid[0].3,
1760        );
1761    }
1762
1763    #[test]
1764    fn load_on_init_populates_store_from_folder_mount() {
1765        // Real markdown content: minimal but parses cleanly against
1766        // the builtin default schema.
1767        let body = "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA test entity.\n";
1768
1769        let tmp = TempDir::new().unwrap();
1770        let mem_dir = tmp.path().to_path_buf();
1771        let writer = FilesystemMemWriter::new(mem_dir.clone());
1772        <FilesystemMemWriter as MemWriter>::write_entity(
1773            &writer,
1774            Path::new("hello.md"),
1775            body.as_bytes(),
1776        )
1777        .unwrap();
1778        <FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
1779            .unwrap();
1780
1781        let engine = Engine::from_mounts(vec![(
1782            folder_mount("specs", mem_dir),
1783            Box::new(writer) as Box<dyn MemBackend>,
1784        )])
1785        .unwrap();
1786
1787        // Store is populated.
1788        assert_eq!(engine.store().len(), 1, "expected one entity in the store");
1789        let id = crate::EntityId::new("specs", "hello");
1790        let entity = engine.get_entity(&id).expect("entity must be present");
1791        assert_eq!(entity.title, "Hello");
1792        assert_eq!(entity.entity_type, "spec");
1793        assert!(engine.load_errors().is_empty());
1794        // Schema map carries one entry per mount.
1795        assert_eq!(engine.schemas().len(), 1);
1796        assert!(engine.schemas().contains_key("specs"));
1797    }
1798
1799    #[test]
1800    fn load_on_init_populates_store_from_archive_mount() {
1801        let body =
1802            "---\ntype: spec\n---\n# From Archive\n\n## Identity\n\nLives in a .memstead zip.\n";
1803
1804        let tmp = TempDir::new().unwrap();
1805        let archive_path =
1806            build_archive(tmp.path(), "ext", &[("from-archive.md", body.as_bytes())]);
1807
1808        let engine = Engine::from_mounts(vec![(
1809            archive_mount("external", archive_path.clone()),
1810            Box::new(ArchiveBackend::new(archive_path)),
1811        )])
1812        .unwrap();
1813
1814        let id = crate::EntityId::new("external", "from-archive");
1815        let entity = engine.get_entity(&id).expect("entity must be present");
1816        assert_eq!(entity.title, "From Archive");
1817        assert!(engine.load_errors().is_empty());
1818    }
1819
1820    #[test]
1821    fn load_on_init_populates_store_from_heterogeneous_mounts() {
1822        let folder_body = "---\ntype: spec\n---\n# Local\n\n## Identity\n\nLocal entity.\n";
1823        let archive_body = "---\ntype: spec\n---\n# External\n\n## Identity\n\nArchive entity.\n";
1824
1825        let tmp = TempDir::new().unwrap();
1826
1827        let folder_dir = tmp.path().join("folder-mem");
1828        std::fs::create_dir_all(&folder_dir).unwrap();
1829        let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
1830        <FilesystemMemWriter as MemWriter>::write_entity(
1831            &folder_writer,
1832            Path::new("local.md"),
1833            folder_body.as_bytes(),
1834        )
1835        .unwrap();
1836        <FilesystemMemWriter as MemWriter>::commit(
1837            &folder_writer,
1838            "seed",
1839            &CommitContext::internal(),
1840        )
1841        .unwrap();
1842
1843        let archive_path = build_archive(
1844            tmp.path(),
1845            "external",
1846            &[("external.md", archive_body.as_bytes())],
1847        );
1848
1849        let engine = Engine::from_mounts(vec![
1850            (
1851                folder_mount("local", folder_dir),
1852                Box::new(folder_writer) as Box<dyn MemBackend>,
1853            ),
1854            (
1855                archive_mount("external", archive_path.clone()),
1856                Box::new(ArchiveBackend::new(archive_path)),
1857            ),
1858        ])
1859        .unwrap();
1860
1861        // Both mems' entities live in one shared store.
1862        assert_eq!(engine.store().len(), 2);
1863        assert!(
1864            engine
1865                .get_entity(&crate::EntityId::new("local", "local"))
1866                .is_some()
1867        );
1868        assert!(
1869            engine
1870                .get_entity(&crate::EntityId::new("external", "external"))
1871                .is_some()
1872        );
1873    }
1874
1875    #[test]
1876    fn load_on_init_collects_per_file_parse_errors_without_failing() {
1877        // One good file + one with malformed frontmatter — the parser
1878        // produces an error for the malformed file but the good one
1879        // still loads.
1880        let good = "---\ntype: spec\n---\n# Good\n\n## Identity\n\nFine.\n";
1881        let bad = "---\nthis is not valid yaml: : :\n---\n# Bad\n";
1882
1883        let tmp = TempDir::new().unwrap();
1884        let mem_dir = tmp.path().to_path_buf();
1885        let writer = FilesystemMemWriter::new(mem_dir.clone());
1886        <FilesystemMemWriter as MemWriter>::write_entity(
1887            &writer,
1888            Path::new("good.md"),
1889            good.as_bytes(),
1890        )
1891        .unwrap();
1892        <FilesystemMemWriter as MemWriter>::write_entity(
1893            &writer,
1894            Path::new("bad.md"),
1895            bad.as_bytes(),
1896        )
1897        .unwrap();
1898        <FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
1899            .unwrap();
1900
1901        let engine = Engine::from_mounts(vec![(
1902            folder_mount("specs", mem_dir),
1903            Box::new(writer) as Box<dyn MemBackend>,
1904        )])
1905        .unwrap();
1906
1907        // The good entity is in the store; construction did not fail.
1908        assert!(
1909            engine
1910                .get_entity(&crate::EntityId::new("specs", "good"))
1911                .is_some(),
1912            "good.md must parse and reach the store"
1913        );
1914        // Either bad.md surfaces as a load error, or it parses
1915        // permissively — both are acceptable outcomes here. The
1916        // contract under test is "construction does not fail on a
1917        // single bad file".
1918        let bad_known_to_engine = engine
1919            .get_entity(&crate::EntityId::new("specs", "bad"))
1920            .is_some()
1921            || !engine.load_errors().is_empty();
1922        assert!(
1923            bad_known_to_engine,
1924            "bad.md must either parse or surface in load_errors"
1925        );
1926    }
1927
1928    #[test]
1929    fn empty_mount_list_yields_empty_store() {
1930        let engine = Engine::from_mounts(Vec::new()).unwrap();
1931        assert!(engine.store().is_empty());
1932        assert!(engine.schemas().is_empty());
1933        assert!(engine.load_errors().is_empty());
1934    }
1935
1936    // ---- Engine::create_entity --------------------------------------
1937
1938    #[test]
1939    fn from_workspace_root_errors_for_empty_layout() {
1940        let tmp = TempDir::new().unwrap();
1941        let err = Engine::from_workspace_root(tmp.path()).unwrap_err();
1942        match err {
1943            crate::BootError::NotInitialised(p) => {
1944                assert_eq!(p, tmp.path());
1945            }
1946            other => panic!("expected NotInitialised, got {other:?}"),
1947        }
1948    }
1949
1950    #[test]
1951    fn from_workspace_root_loads_new_two_layer_layout() {
1952        let tmp = TempDir::new().unwrap();
1953        let mem_dir = tmp.path().join("mem");
1954        std::fs::create_dir_all(&mem_dir).unwrap();
1955        std::fs::write(
1956            mem_dir.join("hello.md"),
1957            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
1958        )
1959        .unwrap();
1960
1961        let memstead = tmp.path().join(".memstead");
1962        std::fs::create_dir_all(&memstead).unwrap();
1963        std::fs::write(
1964            memstead.join("workspace.toml"),
1965            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
1966        )
1967        .unwrap();
1968        // Save the mount via the file adapter so the JSON shape matches
1969        // the wire format the loader expects.
1970        use crate::workspace_store::WorkspaceStoreAdapter;
1971        let store = crate::FileWorkspaceStore::new();
1972        store
1973            .save_state(
1974                tmp.path(),
1975                &crate::workspace::Workspace {
1976                    mounts: vec![folder_mount("specs", mem_dir)],
1977                    settings: crate::workspace::WorkspaceSettings::default(),
1978                },
1979            )
1980            .unwrap();
1981
1982        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
1983        assert_eq!(engine.mem_names(), vec!["specs"]);
1984        let entity = engine
1985            .get_entity(&crate::EntityId::new("specs", "hello"))
1986            .expect("seeded entity must load through from_workspace_root");
1987        assert_eq!(entity.title, "Hello");
1988    }
1989
1990    /// The engine-side pipeline loader: with a workspace store carrying one
1991    /// v2 binding, the engine on boot enumerates it through its read-only
1992    /// queryable surface; a retired-format file quarantines its binding
1993    /// with the typed reason (the loader never reads a prior generation).
1994    #[test]
1995    fn from_workspace_root_loads_pipeline_configs_into_queryable_surface() {
1996        use crate::pipeline::MediumType;
1997        let tmp = TempDir::new().unwrap();
1998        let mem_dir = tmp.path().join("mem");
1999        std::fs::create_dir_all(&mem_dir).unwrap();
2000
2001        let memstead = tmp.path().join(".memstead");
2002        std::fs::create_dir_all(&memstead).unwrap();
2003        std::fs::write(
2004            memstead.join("workspace.toml"),
2005            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2006        )
2007        .unwrap();
2008        use crate::workspace_store::WorkspaceStoreAdapter;
2009        crate::FileWorkspaceStore::new()
2010            .save_state(
2011                tmp.path(),
2012                &crate::workspace::Workspace {
2013                    mounts: vec![folder_mount("specs", mem_dir)],
2014                    settings: crate::workspace::WorkspaceSettings::default(),
2015                },
2016            )
2017            .unwrap();
2018
2019        // One v2 binding in the store.
2020        crate::pipeline_store::write_binding(
2021            tmp.path(),
2022            "specs",
2023            "graph",
2024            &sample_v2_binding("specs"),
2025        )
2026        .unwrap();
2027
2028        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
2029        let pc = engine.pipeline_configs();
2030        assert_eq!(pc.bindings.len(), 1, "one binding enumerated");
2031        assert_eq!(pc.bindings[0].mem, "specs");
2032        assert_eq!(pc.bindings[0].name, "graph");
2033        assert_eq!(pc.bindings[0].config.destination_mem, "specs");
2034        assert_eq!(
2035            pc.bindings[0].config.sources[0].medium_type,
2036            MediumType::Codebase
2037        );
2038
2039        // QUARANTINE: a pre-v2 (version-less gen-2) projection
2040        // file no longer fails the boot — the affected binding
2041        // quarantines with the retired-format reason, still never
2042        // read, still never tolerated; the workspace and the healthy
2043        // binding keep serving. Written raw: the engine has no type
2044        // for the retired shape.
2045        std::fs::write(
2046            tmp.path().join(".memstead/projections/specs/legacy.json"),
2047            br#"{"source_facets": ["view"], "reference_mems": [], "destination_mem": "specs"}"#,
2048        )
2049        .unwrap();
2050        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
2051        let pc = engine.pipeline_configs();
2052        assert_eq!(pc.bindings.len(), 1, "the healthy binding still serves");
2053        assert_eq!(pc.quarantined.len(), 1, "the legacy one quarantines");
2054        assert_eq!(pc.quarantined[0].name, "legacy");
2055        assert_eq!(pc.quarantined[0].reason_code, "PROJECTION_STORE_LEGACY");
2056        assert!(
2057            pc.quarantined[0]
2058                .reason_message
2059                .contains("retired binding format"),
2060            "quarantine reason names the retired format, got: {}",
2061            pc.quarantined[0].reason_message
2062        );
2063        assert!(
2064            pc.quarantined[0]
2065                .reason_message
2066                .contains("memstead projection init"),
2067            "quarantine reason names the way back, got: {}",
2068            pc.quarantined[0].reason_message
2069        );
2070    }
2071
2072    /// One v2 binding with a single codebase source under `pointer` — the
2073    /// shared fixture of the boot tests.
2074    fn sample_v2_binding(dest: &str) -> crate::binding::Binding {
2075        v2_binding_with_pointer(dest, "..")
2076    }
2077
2078    fn v2_binding_with_pointer(dest: &str, pointer: &str) -> crate::binding::Binding {
2079        use crate::binding::{BINDING_VERSION, Binding, BuildMode, BuildOperation, Operations};
2080        use crate::pipeline::{IngestTrigger, MediumType, Source};
2081        Binding {
2082            version: BINDING_VERSION,
2083            intent: None,
2084            sources: vec![Source {
2085                name: "src".to_string(),
2086                medium_type: MediumType::Codebase,
2087                pointer: pointer.to_string(),
2088                change_detection: None,
2089                scope: Vec::new(),
2090                engagement: None,
2091                preparation: None,
2092            }],
2093            reference_mems: Vec::new(),
2094            destination_mem: dest.to_string(),
2095            deny_paths: Vec::new(),
2096            coverage_semantics: None,
2097            rules: None,
2098            prune: None,
2099            operations: Operations {
2100                build: Some(BuildOperation {
2101                    mode: BuildMode::Discovery,
2102                    trigger: IngestTrigger::Loop,
2103                    batch_size: 10,
2104                    post_actions: None,
2105                }),
2106                sync: None,
2107                verify: None,
2108            },
2109        }
2110    }
2111
2112    /// Url anchors adjudicate from SUPPLIED observations through the one
2113    /// funnel (plan: url anchors observable): equal hash resolves, a
2114    /// differing hash drifts under `stable` and rechecks under `unstable`,
2115    /// `absent` rechecks; a url row without an observation stays unobserved,
2116    /// never scored. Recording the observations makes the states visible on
2117    /// the per-entity read and dates the rows so they age; the sidecar
2118    /// carries version 2 afterwards. A url anchor is legal beside a mem
2119    /// whose single binding source is path-shaped.
2120    #[test]
2121    fn url_anchors_adjudicate_from_supplied_observations_and_age() {
2122        use crate::anchor::{
2123            AnchorInput, AnchorState, SuppliedObservationInput, validate_supplied_observations,
2124        };
2125        use crate::vcs::Actor;
2126        use crate::workspace_store::WorkspaceStoreAdapter;
2127        use indexmap::IndexMap;
2128
2129        let tmp = TempDir::new().unwrap();
2130        let mem_dir = tmp.path().join("mem");
2131        std::fs::create_dir_all(&mem_dir).unwrap();
2132        std::fs::write(
2133            mem_dir.join("hello.md"),
2134            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
2135        )
2136        .unwrap();
2137
2138        let memstead = tmp.path().join(".memstead");
2139        std::fs::create_dir_all(&memstead).unwrap();
2140        std::fs::write(
2141            memstead.join("workspace.toml"),
2142            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2143        )
2144        .unwrap();
2145        crate::FileWorkspaceStore::new()
2146            .save_state(
2147                tmp.path(),
2148                &crate::workspace::Workspace {
2149                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2150                    settings: crate::workspace::WorkspaceSettings::default(),
2151                },
2152            )
2153            .unwrap();
2154        // Exactly one path-shaped binding source: the shape that used to
2155        // refuse url anchors with the namespace rule.
2156        crate::pipeline_store::write_binding(
2157            tmp.path(),
2158            "specs",
2159            "graph",
2160            &v2_binding_with_pointer("specs", "src"),
2161        )
2162        .unwrap();
2163        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
2164
2165        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2166        let clock_now = "2026-09-02T12:00:00Z";
2167        let pinned = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_788_350_400);
2168        engine.set_mutation_clock(std::sync::Arc::new(move || pinned));
2169        assert_eq!(
2170            engine.now_iso(),
2171            clock_now,
2172            "clock pin is the date the ages count from"
2173        );
2174
2175        let url = |artifact: &str, stability: &str, content: &str| AnchorInput {
2176            artifact: Some(artifact.to_string()),
2177            grain: Some("url".to_string()),
2178            class: Some("anchored".to_string()),
2179            content: Some(content.to_string()),
2180            hash_stability: Some(stability.to_string()),
2181            ..Default::default()
2182        };
2183        let mut sections = IndexMap::new();
2184        sections.insert("identity".to_string(), "Cites the web.".to_string());
2185        sections.insert("purpose".to_string(), "Four url anchors.".to_string());
2186        let created = engine
2187            .create_entity(
2188                crate::CreateEntityArgs {
2189                    mem: "specs".to_string(),
2190                    title: "Cites".to_string(),
2191                    entity_type: "spec".to_string(),
2192                    sections,
2193                    metadata: IndexMap::new(),
2194                    relations: Vec::new(),
2195                    anchors: vec![
2196                        url("https://w.test/stable", "stable", "immutable text"),
2197                        url("https://w.test/living", "unstable", "page v1"),
2198                        url("https://w.test/gone", "unstable", "was here"),
2199                        url("https://w.test/never", "unstable", "never observed again"),
2200                    ],
2201                    dry_run: false,
2202                },
2203                Actor::Agent,
2204                None,
2205                None,
2206            )
2207            .expect("url anchors beside a single path source are legal");
2208        let before = engine.entity_anchors_resolved(&created.id);
2209        assert_eq!(before.len(), 4);
2210        assert!(
2211            before
2212                .iter()
2213                .all(|r| r.state.is_none() && r.observed_at.is_none()),
2214            "no observation yet: every url row unobserved"
2215        );
2216        assert!(
2217            before
2218                .iter()
2219                .all(|r| r.anchor.hash_source == Some(crate::anchor::AnchorHashSource::Author)),
2220            "content supplied at write: author baseline"
2221        );
2222
2223        // Supplied observations: equal hash, changed content, absent; the
2224        // fourth row gets none.
2225        let rows = vec![
2226            SuppliedObservationInput {
2227                artifact: Some("https://w.test/stable".into()),
2228                hash: Some(crate::anchor::prepared_content_hash(b"immutable text")),
2229                ..Default::default()
2230            },
2231            SuppliedObservationInput {
2232                artifact: Some("https://w.test/living".into()),
2233                content: Some("page v2".into()),
2234                observed_at: Some("2026-08-03T09:00:00Z".into()),
2235                ..Default::default()
2236            },
2237            SuppliedObservationInput {
2238                artifact: Some("https://w.test/gone".into()),
2239                absent: Some(true),
2240                ..Default::default()
2241            },
2242            SuppliedObservationInput {
2243                artifact: Some("https://elsewhere.test/unrelated".into()),
2244                hash: Some("zz".into()),
2245                ..Default::default()
2246            },
2247        ];
2248        let supplied = validate_supplied_observations(&rows, clock_now).unwrap();
2249        let report = engine.verify_mem_anchors_with("specs", &supplied).unwrap();
2250        let state_of = |artifact: &str| {
2251            report
2252                .anchors
2253                .iter()
2254                .find(|a| a.artifact == artifact)
2255                .map(|a| {
2256                    (
2257                        a.state.clone(),
2258                        a.unobserved_for_days,
2259                        a.observation_supplied,
2260                    )
2261                })
2262                .unwrap()
2263        };
2264        assert_eq!(
2265            state_of("https://w.test/stable"),
2266            ("resolves".into(), Some(0), true)
2267        );
2268        assert_eq!(
2269            state_of("https://w.test/living"),
2270            ("recheck".into(), Some(30), true)
2271        );
2272        assert_eq!(
2273            state_of("https://w.test/gone"),
2274            ("recheck".into(), Some(0), true)
2275        );
2276        assert_eq!(
2277            state_of("https://w.test/never"),
2278            ("unobserved".into(), None, false)
2279        );
2280        assert_eq!(
2281            report.unmatched_observations,
2282            vec!["https://elsewhere.test/unrelated"]
2283        );
2284        assert_eq!(report.recordable_observations.len(), 3);
2285        assert_eq!(
2286            (
2287                report.figure.count_for_assertions(),
2288                report.recheck,
2289                report.unobserved
2290            ),
2291            (1, 2, 1)
2292        );
2293
2294        // Nothing was written by the verification itself.
2295        assert!(
2296            engine
2297                .entity_anchors_resolved(&created.id)
2298                .iter()
2299                .all(|r| r.state.is_none()),
2300            "verify writes nothing"
2301        );
2302
2303        // Record: the states land on the rows, the read shows them dated,
2304        // and the sidecar is version 2.
2305        let written = engine
2306            .record_anchor_observations("specs", &report.recordable_observations, None)
2307            .unwrap();
2308        assert_eq!(written, 3);
2309        let after = engine.entity_anchors_resolved(&created.id);
2310        let row = |artifact: &str| {
2311            after
2312                .iter()
2313                .find(|r| r.anchor.artifact == artifact)
2314                .unwrap()
2315        };
2316        assert_eq!(
2317            row("https://w.test/stable").state,
2318            Some(AnchorState::Resolves)
2319        );
2320        assert_eq!(
2321            row("https://w.test/living").state,
2322            Some(AnchorState::Recheck)
2323        );
2324        assert_eq!(
2325            row("https://w.test/living").observed_at.as_deref(),
2326            Some("2026-08-03T09:00:00Z")
2327        );
2328        assert_eq!(row("https://w.test/gone").state, Some(AnchorState::Recheck));
2329        assert_eq!(row("https://w.test/never").state, None, "still unobserved");
2330        let sidecar_bytes = std::fs::read(mem_dir.join(".memstead").join("anchors.json")).unwrap();
2331        let sidecar: serde_json::Value = serde_json::from_slice(&sidecar_bytes).unwrap();
2332        assert_eq!(sidecar["version"], 2);
2333        // A second identical recording stages nothing.
2334        assert_eq!(
2335            engine
2336                .record_anchor_observations("specs", &report.recordable_observations, None)
2337                .unwrap(),
2338            0
2339        );
2340
2341        // The next verify, with no observations supplied, rests on the
2342        // recorded ones and ages them: the living page's observation is
2343        // 30 days old; the stable row re-adjudicates DRIFTED when a later
2344        // observation brings a different hash.
2345        let report2 = engine.verify_mem_anchors("specs").unwrap();
2346        let aged = report2
2347            .anchors
2348            .iter()
2349            .find(|a| a.artifact == "https://w.test/living")
2350            .unwrap();
2351        assert_eq!(aged.unobserved_for_days, Some(30));
2352        assert!(!aged.observation_supplied);
2353        let axis = crate::ops::health::health_anchors_axis(&engine, None);
2354        let aging = axis["specs"]["aging"].as_array().unwrap();
2355        assert!(
2356            aging
2357                .iter()
2358                .any(|a| a["artifact"] == "https://w.test/living"
2359                    && a["note"] == "unobserved for 30 days"),
2360            "{axis}"
2361        );
2362        let open = crate::ops::health::health_open_questions_axis(&engine, Some("specs"));
2363        assert!(
2364            open["specs"]["anchors_aging"]["items"]
2365                .as_array()
2366                .is_some_and(|items| items.iter().any(|i| i["note"] == "unobserved for 30 days")),
2367            "{open}"
2368        );
2369
2370        let drift_rows = vec![SuppliedObservationInput {
2371            artifact: Some("https://w.test/stable".into()),
2372            content: Some("immutable text, edited after all".into()),
2373            ..Default::default()
2374        }];
2375        let supplied = validate_supplied_observations(&drift_rows, clock_now).unwrap();
2376        let report3 = engine.verify_mem_anchors_with("specs", &supplied).unwrap();
2377        assert_eq!(
2378            state_of_report(&report3, "https://w.test/stable"),
2379            "drifted"
2380        );
2381        assert_eq!(report3.drifted, 1);
2382    }
2383
2384    /// A version-1 anchors sidecar from a fixture loads unchanged (its rows
2385    /// have no `last_observed`, the file is not touched by reading) and is
2386    /// rewritten as version 2 by the next anchor write; a sidecar declaring a
2387    /// version this engine does not read refuses at the write seam with the
2388    /// existing typed parse error.
2389    #[test]
2390    fn sidecar_v1_fixture_loads_and_next_anchor_write_rewrites_v2_while_v3_refuses() {
2391        use crate::anchor::AnchorInput;
2392        use crate::vcs::Actor;
2393        use crate::workspace_store::WorkspaceStoreAdapter;
2394        use indexmap::IndexMap;
2395
2396        let tmp = TempDir::new().unwrap();
2397        let mem_dir = tmp.path().join("mem");
2398        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
2399        std::fs::write(
2400            mem_dir.join("hello.md"),
2401            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
2402        )
2403        .unwrap();
2404        let v1 = r#"{"version":1,"entities":{"specs--hello":[{"artifact":"https://fixture.test/doc","grain":"url","class":"anchored","hash":"author-pinned","hash_stability":"stable","hash_source":"author"}]}}"#;
2405        std::fs::write(mem_dir.join(".memstead").join("anchors.json"), v1).unwrap();
2406        let memstead = tmp.path().join(".memstead");
2407        std::fs::create_dir_all(&memstead).unwrap();
2408        std::fs::write(
2409            memstead.join("workspace.toml"),
2410            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2411        )
2412        .unwrap();
2413        crate::FileWorkspaceStore::new()
2414            .save_state(
2415                tmp.path(),
2416                &crate::workspace::Workspace {
2417                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2418                    settings: crate::workspace::WorkspaceSettings::default(),
2419                },
2420            )
2421            .unwrap();
2422        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2423
2424        let rows = engine.entity_anchors_resolved(&crate::EntityId::canonical("specs--hello"));
2425        assert_eq!(rows.len(), 1, "the version-1 row loads");
2426        assert_eq!(rows[0].anchor.hash.as_deref(), Some("author-pinned"));
2427        assert!(rows[0].anchor.last_observed.is_none());
2428        assert!(rows[0].state.is_none(), "never observed: unobserved");
2429        let on_disk =
2430            std::fs::read_to_string(mem_dir.join(".memstead").join("anchors.json")).unwrap();
2431        assert_eq!(on_disk, v1, "reading rewrites nothing");
2432
2433        // The next anchor write persists version 2 and keeps the v1 row's
2434        // author hash exactly as it was.
2435        let mut sections = IndexMap::new();
2436        sections.insert("identity".to_string(), "Second.".to_string());
2437        sections.insert("purpose".to_string(), "Second.".to_string());
2438        engine
2439            .create_entity(
2440                crate::CreateEntityArgs {
2441                    mem: "specs".to_string(),
2442                    title: "Second".to_string(),
2443                    entity_type: "spec".to_string(),
2444                    sections,
2445                    metadata: IndexMap::new(),
2446                    relations: Vec::new(),
2447                    anchors: vec![AnchorInput {
2448                        artifact: Some("https://fixture.test/other".to_string()),
2449                        grain: Some("url".to_string()),
2450                        class: Some("informed-by".to_string()),
2451                        ..Default::default()
2452                    }],
2453                    dry_run: false,
2454                },
2455                Actor::Agent,
2456                None,
2457                None,
2458            )
2459            .unwrap();
2460        let after: serde_json::Value = serde_json::from_slice(
2461            &std::fs::read(mem_dir.join(".memstead").join("anchors.json")).unwrap(),
2462        )
2463        .unwrap();
2464        assert_eq!(after["version"], 2);
2465        assert_eq!(
2466            after["entities"]["specs--hello"][0]["hash"],
2467            "author-pinned"
2468        );
2469        assert!(
2470            after["entities"]["specs--hello"][0]
2471                .get("last_observed")
2472                .is_none()
2473        );
2474
2475        // A version this engine does not read refuses at the write seam.
2476        std::fs::write(
2477            mem_dir.join(".memstead").join("anchors.json"),
2478            r#"{"version":3,"entities":{}}"#,
2479        )
2480        .unwrap();
2481        let mut sections = IndexMap::new();
2482        sections.insert("identity".to_string(), "Third.".to_string());
2483        sections.insert("purpose".to_string(), "Third.".to_string());
2484        let err = engine
2485            .create_entity(
2486                crate::CreateEntityArgs {
2487                    mem: "specs".to_string(),
2488                    title: "Third".to_string(),
2489                    entity_type: "spec".to_string(),
2490                    sections,
2491                    metadata: IndexMap::new(),
2492                    relations: Vec::new(),
2493                    anchors: vec![AnchorInput {
2494                        artifact: Some("https://fixture.test/third".to_string()),
2495                        grain: Some("url".to_string()),
2496                        class: Some("informed-by".to_string()),
2497                        ..Default::default()
2498                    }],
2499                    dry_run: false,
2500                },
2501                Actor::Agent,
2502                None,
2503                None,
2504            )
2505            .expect_err("a version-3 sidecar refuses");
2506        assert!(
2507            err.to_string()
2508                .contains("unsupported anchors sidecar version 3"),
2509            "{err}"
2510        );
2511    }
2512
2513    fn state_of_report(
2514        report: &crate::engine::query::MemAnchorVerification,
2515        artifact: &str,
2516    ) -> String {
2517        report
2518            .anchors
2519            .iter()
2520            .find(|a| a.artifact == artifact)
2521            .map(|a| a.state.clone())
2522            .unwrap()
2523    }
2524
2525    /// Live per-anchor state (criteria 1, 9 — path-medium subset): a
2526    /// single-medium `path` mem observes working-tree existence at the current
2527    /// HEAD. Absent artifact ⇒ `orphaned`; present + non-hash class ⇒
2528    /// `resolves`; present + hash-bearing class ⇒ the prepared-content hash
2529    /// comparison adjudicates deterministically — a recorded hash matching
2530    /// the observed prepared form `resolves`, a stable-medium mismatch is
2531    /// `drifted` (a real content drift, no longer deferred to `recheck`).
2532    #[test]
2533    fn entity_anchors_resolve_live_state_for_path_medium() {
2534        use crate::anchor::{AnchorInput, AnchorState};
2535        use crate::vcs::Actor;
2536        use crate::workspace_store::WorkspaceStoreAdapter;
2537        use indexmap::IndexMap;
2538
2539        let tmp = TempDir::new().unwrap();
2540        let mem_dir = tmp.path().join("mem");
2541        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
2542        std::fs::write(
2543            mem_dir.join(".memstead").join("config.json"),
2544            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
2545        )
2546        .unwrap();
2547
2548        let memstead = tmp.path().join(".memstead");
2549        std::fs::create_dir_all(&memstead).unwrap();
2550        std::fs::write(
2551            memstead.join("workspace.toml"),
2552            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2553        )
2554        .unwrap();
2555        crate::FileWorkspaceStore::new()
2556            .save_state(
2557                tmp.path(),
2558                &crate::workspace::Workspace {
2559                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2560                    settings: crate::workspace::WorkspaceSettings::default(),
2561                },
2562            )
2563            .unwrap();
2564
2565        // A single `path` source rooted at `<workspace>/src` (medium context
2566        // now derives from the mem's binding sources). Anchor artifact ids
2567        // are workspace-relative (pointer-prefixed) — the dialect
2568        // enumeration / coverage / advance share — so `src/present.rs`
2569        // observes present and `src/gone.rs` observes absent.
2570        crate::pipeline_store::write_binding(
2571            tmp.path(),
2572            "specs",
2573            "graph",
2574            &v2_binding_with_pointer("specs", "src"),
2575        )
2576        .unwrap();
2577        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
2578        std::fs::write(tmp.path().join("src").join("present.rs"), "fn main() {}").unwrap();
2579        // Exists at write time (the write gate refuses dead references);
2580        // deleted after the write to produce the orphaned READ state.
2581        std::fs::write(tmp.path().join("src").join("gone.rs"), "fn gone() {}").unwrap();
2582
2583        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2584
2585        let anchor = |artifact: &str, class: &str, hash: Option<&str>| AnchorInput {
2586            artifact: Some(artifact.to_string()),
2587            grain: Some("file".to_string()),
2588            class: Some(class.to_string()),
2589            hash: hash.map(str::to_string),
2590            hash_stability: Some("stable".to_string()),
2591            ..Default::default()
2592        };
2593        let mut sections = IndexMap::new();
2594        sections.insert("identity".to_string(), "Covers src.".to_string());
2595        sections.insert("purpose".to_string(), "Track sources.".to_string());
2596        // The prepared-form hash of the present artifact, as the observation
2597        // computes it — an anchor recording it must resolve clean.
2598        let present_hash = crate::anchor::prepared_content_hash(
2599            &std::fs::read(tmp.path().join("src").join("present.rs")).unwrap(),
2600        );
2601        let created = engine
2602            .create_entity(
2603                crate::CreateEntityArgs {
2604                    mem: "specs".to_string(),
2605                    title: "Covers".to_string(),
2606                    entity_type: "spec".to_string(),
2607                    sections,
2608                    metadata: IndexMap::new(),
2609                    relations: Vec::new(),
2610                    anchors: vec![
2611                        anchor("src/present.rs", "anchored", Some(&present_hash)), // hash matches → resolves
2612                        anchor("src/present.rs", "informed-by", None), // present + non-hash → resolves
2613                        anchor("src/gone.rs", "anchored", Some("h2")), // absent → orphaned
2614                        anchor("src/present.rs", "derived", Some("stale")), // hash mismatch, stable → drifted
2615                    ],
2616                    dry_run: false,
2617                },
2618                Actor::Agent,
2619                None,
2620                None,
2621            )
2622            .unwrap();
2623
2624        std::fs::remove_file(tmp.path().join("src").join("gone.rs")).unwrap();
2625        let resolved = engine.entity_anchors_resolved(&created.id);
2626        assert_eq!(resolved.len(), 4);
2627        let state_of = |artifact: &str, class: crate::anchor::AnchorProvenanceClass| {
2628            resolved
2629                .iter()
2630                .find(|r| r.anchor.artifact == artifact && r.anchor.class == class)
2631                .and_then(|r| r.state)
2632        };
2633        assert_eq!(
2634            state_of(
2635                "src/present.rs",
2636                crate::anchor::AnchorProvenanceClass::Anchored
2637            ),
2638            Some(AnchorState::Resolves),
2639            "recorded hash matches the observed prepared form → resolves"
2640        );
2641        assert_eq!(
2642            state_of(
2643                "src/present.rs",
2644                crate::anchor::AnchorProvenanceClass::Derived
2645            ),
2646            Some(AnchorState::Drifted),
2647            "recorded hash mismatches the observed prepared form on a stable medium → drifted"
2648        );
2649        assert_eq!(
2650            state_of(
2651                "src/present.rs",
2652                crate::anchor::AnchorProvenanceClass::InformedBy
2653            ),
2654            Some(AnchorState::Resolves),
2655            "present non-hash anchor resolves on existence"
2656        );
2657        assert_eq!(
2658            state_of(
2659                "src/gone.rs",
2660                crate::anchor::AnchorProvenanceClass::Anchored
2661            ),
2662            Some(AnchorState::Orphaned),
2663            "absent artifact is orphaned"
2664        );
2665    }
2666
2667    /// The engine edit surface: a wrapper edit (`add_projection_json`)
2668    /// routes through the pipeline-edit layer, writes the store, and
2669    /// refreshes the in-memory snapshot in place (no `reload()`); the JSON
2670    /// read counterpart reflects the collapsed `{bindings}`-only shape.
2671    #[test]
2672    fn engine_pipeline_edit_methods_mutate_and_refresh_the_snapshot() {
2673        use crate::workspace_store::WorkspaceStoreAdapter;
2674
2675        let tmp = TempDir::new().unwrap();
2676        let mem_dir = tmp.path().join("mem");
2677        std::fs::create_dir_all(&mem_dir).unwrap();
2678        let memstead = tmp.path().join(".memstead");
2679        std::fs::create_dir_all(&memstead).unwrap();
2680        std::fs::write(
2681            memstead.join("workspace.toml"),
2682            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2683        )
2684        .unwrap();
2685        crate::FileWorkspaceStore::new()
2686            .save_state(
2687                tmp.path(),
2688                &crate::workspace::Workspace {
2689                    mounts: vec![folder_mount("specs", mem_dir)],
2690                    settings: crate::workspace::WorkspaceSettings::default(),
2691                },
2692            )
2693            .unwrap();
2694
2695        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2696        assert!(engine.pipeline_configs().bindings.is_empty());
2697
2698        // The JSON entry point (the FFI-facing shape) deserializes and lands.
2699        engine
2700            .add_projection_json(
2701                "specs",
2702                "graph",
2703                r#"{
2704                    "sources": [{ "name": "src", "type": "codebase", "pointer": "..",
2705                                  "scope": [{ "path": "**/*.rs", "mode": "allow" }] }],
2706                    "destination_mem": "specs"
2707                }"#,
2708                None,
2709            )
2710            .unwrap();
2711        // Snapshot refreshed in place.
2712        assert_eq!(engine.pipeline_configs().bindings.len(), 1);
2713        assert_eq!(engine.pipeline_configs().bindings[0].name, "graph");
2714        assert_eq!(
2715            engine.pipeline_configs().bindings[0].config.sources[0].name,
2716            "src"
2717        );
2718
2719        // A malformed payload is refused without touching the store.
2720        let err = engine
2721            .add_projection_json("specs", "bad", "{ not json", None)
2722            .unwrap_err();
2723        assert!(
2724            matches!(
2725                err,
2726                crate::pipeline_edit::PipelineEditError::InvalidJson { .. }
2727            ),
2728            "got {err:?}"
2729        );
2730
2731        // Update patches over the stored record; delete removes and refreshes.
2732        engine
2733            .update_projection_json("specs", "graph", r#"{"intent":"i2"}"#, None)
2734            .unwrap();
2735        assert_eq!(
2736            engine.pipeline_configs().bindings[0]
2737                .config
2738                .intent
2739                .as_deref(),
2740            Some("i2")
2741        );
2742
2743        // Rename moves the record and refreshes the snapshot.
2744        engine
2745            .rename_projection("specs", "graph", "graph2", None)
2746            .unwrap();
2747        assert_eq!(engine.pipeline_configs().bindings[0].name, "graph2");
2748
2749        // The JSON read counterpart reflects the live store in the
2750        // `{bindings}`-only shape — no `mediums` / `facets` keys.
2751        let json = engine.pipeline_configs_json();
2752        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
2753        assert!(parsed.get("mediums").is_none(), "no mediums key: {json}");
2754        assert!(parsed.get("facets").is_none(), "no facets key: {json}");
2755        let bindings = parsed["bindings"].as_array().unwrap();
2756        assert_eq!(bindings.len(), 1);
2757        assert_eq!(bindings[0]["name"], "graph2");
2758        assert_eq!(bindings[0]["config"]["sources"][0]["type"], "codebase");
2759
2760        engine.delete_projection("specs", "graph2", None).unwrap();
2761        assert!(engine.pipeline_configs().bindings.is_empty());
2762    }
2763
2764    /// The folder authoring path: a schema package authored at the
2765    /// fixed `<workspace>/.memstead/schemas/<name>@<version>/` location
2766    /// is resolved at boot, so a folder mem can pin a non-built-in
2767    /// schema. Before this wiring `from_workspace_root` loaded only
2768    /// built-ins, so the pin would refuse with `SCHEMA_NOT_FOUND`.
2769    #[test]
2770    fn from_workspace_root_resolves_authored_schema_from_dot_memstead_schemas() {
2771        use crate::engine::test_helpers::write_schema_files_with_default_type;
2772
2773        let tmp = TempDir::new().unwrap();
2774        let mem_dir = tmp.path().join("mem");
2775        std::fs::create_dir_all(&mem_dir).unwrap();
2776
2777        // Author a schema package at the fixed folder location.
2778        let authored_dir = tmp.path().join(".memstead").join("schemas");
2779        let manifest = r#"name: authored
2780version: 0.1.0
2781description: an authored-in-workspace test schema
2782when_to_use: tests
2783types:
2784  - doc
2785relationships:
2786  mode: strict
2787  definitions:
2788    - name: _default
2789      description: fallback
2790      default_weight: 1.0
2791community:
2792  resolution: 1.0
2793  seed: 42
2794"#;
2795        write_schema_files_with_default_type(&authored_dir, "authored@0.1.0", manifest, &["doc"]);
2796
2797        // A folder mem pinning the authored (non-built-in) schema.
2798        let memstead = tmp.path().join(".memstead");
2799        std::fs::create_dir_all(&memstead).unwrap();
2800        std::fs::write(
2801            memstead.join("workspace.toml"),
2802            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2803        )
2804        .unwrap();
2805        let mount = Mount {
2806            mem: "specs".to_string(),
2807            schema: Some(SchemaRef::new("authored", semver::Version::new(0, 1, 0))),
2808            storage: MountStorage::Folder { path: mem_dir },
2809            capability: MountCapability::Write,
2810            lifecycle: MountLifecycle::Eager,
2811            cross_linkable: true,
2812            migration_target: None,
2813        };
2814        use crate::workspace_store::WorkspaceStoreAdapter;
2815        crate::FileWorkspaceStore::new()
2816            .save_state(
2817                tmp.path(),
2818                &crate::workspace::Workspace {
2819                    mounts: vec![mount],
2820                    settings: crate::workspace::WorkspaceSettings::default(),
2821                },
2822            )
2823            .unwrap();
2824
2825        // Boots cleanly — the authored pin resolved against the fixed
2826        // location rather than refusing as an unknown built-in.
2827        let engine = Engine::from_workspace_root(tmp.path())
2828            .expect("authored schema at .memstead/schemas/ must resolve at boot");
2829        assert_eq!(engine.mem_names(), vec!["specs"]);
2830    }
2831
2832    /// Authoring-drift health axis (plan 10): a STAMPED sealed schema
2833    /// reports a missing authoring package and (separately) a diverged
2834    /// one; an unmodified package, a cosmetic-only difference (editor
2835    /// header comment lines), and an unstamped seal produce NO
2836    /// finding; and the checks alter neither copy.
2837    #[test]
2838    fn health_reports_authoring_drift_for_stamped_schemas_only() {
2839        use crate::engine::test_helpers::write_schema_files_with_default_type;
2840
2841        let tmp = TempDir::new().unwrap();
2842        let mem_dir = tmp.path().join("mem");
2843        std::fs::create_dir_all(&mem_dir).unwrap();
2844        let manifest = r#"name: authored
2845version: 0.1.0
2846description: an authored-in-workspace test schema
2847when_to_use: tests
2848types:
2849  - doc
2850relationships:
2851  mode: strict
2852  definitions:
2853    - name: _default
2854      description: fallback
2855      default_weight: 1.0
2856community:
2857  resolution: 1.0
2858  seed: 42
2859"#;
2860        // Sealed copy at the fixed install location; authoring copy in
2861        // the working tree.
2862        let sealed_root = tmp.path().join(".memstead").join("schemas");
2863        write_schema_files_with_default_type(&sealed_root, "authored@0.1.0", manifest, &["doc"]);
2864        let author_root = tmp.path().join("author");
2865        write_schema_files_with_default_type(&author_root, "authored@0.1.0", manifest, &["doc"]);
2866        let authoring_dir = author_root.join("authored@0.1.0");
2867        let sealed_dir = sealed_root.join("authored@0.1.0");
2868        // The install-time stamp: the seal records where it came from.
2869        let stamp_path = sealed_dir.join(memstead_schema::INSTALL_PROVENANCE_FILE);
2870        std::fs::write(
2871            &stamp_path,
2872            serde_json::to_vec_pretty(&serde_json::json!({
2873                "authoring_path": authoring_dir.display().to_string(),
2874            }))
2875            .unwrap(),
2876        )
2877        .unwrap();
2878
2879        let memstead = tmp.path().join(".memstead");
2880        std::fs::write(
2881            memstead.join("workspace.toml"),
2882            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2883        )
2884        .unwrap();
2885        let mount = Mount {
2886            mem: "specs".to_string(),
2887            schema: Some(SchemaRef::new("authored", semver::Version::new(0, 1, 0))),
2888            storage: MountStorage::Folder { path: mem_dir },
2889            capability: MountCapability::Write,
2890            lifecycle: MountLifecycle::Eager,
2891            cross_linkable: true,
2892            migration_target: None,
2893        };
2894        use crate::workspace_store::WorkspaceStoreAdapter;
2895        crate::FileWorkspaceStore::new()
2896            .save_state(
2897                tmp.path(),
2898                &crate::workspace::Workspace {
2899                    mounts: vec![mount],
2900                    settings: crate::workspace::WorkspaceSettings::default(),
2901                },
2902            )
2903            .unwrap();
2904        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
2905        let drift_codes = |e: &Engine| -> Vec<String> {
2906            e.health()
2907                .warnings
2908                .iter()
2909                .filter(|w| w.code().starts_with("SCHEMA_AUTHORING_SOURCE_"))
2910                .map(|w| w.code().to_string())
2911                .collect()
2912        };
2913
2914        // Unmodified authoring package: no finding, and the check
2915        // touched neither copy.
2916        let sealed_before = std::fs::read(sealed_dir.join("schema.yaml")).unwrap();
2917        let author_before = std::fs::read(authoring_dir.join("schema.yaml")).unwrap();
2918        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2919        assert_eq!(
2920            std::fs::read(sealed_dir.join("schema.yaml")).unwrap(),
2921            sealed_before,
2922            "health must not touch the sealed copy"
2923        );
2924        assert_eq!(
2925            std::fs::read(authoring_dir.join("schema.yaml")).unwrap(),
2926            author_before,
2927            "health must not touch the authoring copy"
2928        );
2929
2930        // Cosmetic-only difference (the CLI-injected editor-header
2931        // line + a comment): still no finding — parsed equivalence,
2932        // never raw bytes.
2933        std::fs::write(
2934            authoring_dir.join("schema.yaml"),
2935            format!(
2936                "# yaml-language-server: $schema=../../.memstead/meta-schemas/schema-manifest.json\n# cosmetic comment\n{manifest}"
2937            ),
2938        )
2939        .unwrap();
2940        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2941
2942        // Semantic change: DIVERGED, naming schema, version, and the
2943        // pinning mems.
2944        std::fs::write(
2945            authoring_dir.join("schema.yaml"),
2946            manifest.replace(
2947                "an authored-in-workspace test schema",
2948                "a semantically different description",
2949            ),
2950        )
2951        .unwrap();
2952        let warnings = engine.health().warnings;
2953        let diverged = warnings
2954            .iter()
2955            .find(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_DIVERGED")
2956            .expect("semantic change must surface as DIVERGED");
2957        let d = serde_json::to_value(diverged).unwrap();
2958        assert_eq!(d["details"]["schema_ref"], "authored@0.1.0");
2959        assert_eq!(d["details"]["mems"], serde_json::json!(["specs"]));
2960
2961        // Authoring package gone: the DIFFERENT finding — MISSING.
2962        std::fs::remove_dir_all(&authoring_dir).unwrap();
2963        let warnings = engine.health().warnings;
2964        let missing = warnings
2965            .iter()
2966            .find(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_MISSING")
2967            .expect("vanished authoring package must surface as MISSING");
2968        let m = serde_json::to_value(missing).unwrap();
2969        assert_eq!(m["details"]["schema_ref"], "authored@0.1.0");
2970        assert_eq!(m["details"]["mems"], serde_json::json!(["specs"]));
2971        assert_eq!(
2972            m["details"]["stamped_path"],
2973            authoring_dir.display().to_string()
2974        );
2975        assert!(
2976            !warnings
2977                .iter()
2978                .any(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_DIVERGED"),
2979            "missing and diverged are distinct findings"
2980        );
2981
2982        // No stamp → no finding, even with the package still gone.
2983        std::fs::remove_file(&stamp_path).unwrap();
2984        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2985    }
2986
2987    /// `full_refresh` makes an out-of-band schema install and
2988    /// an out-of-band mem registration usable warm — additively.
2989    /// Removals are skipped and reported; a failed mount is reported
2990    /// per-item and does not abort the rest.
2991    #[test]
2992    fn full_refresh_is_additive_and_reports_skipped_removals() {
2993        use crate::engine::test_helpers::write_schema_files_with_default_type;
2994        use crate::workspace_store::WorkspaceStoreAdapter;
2995
2996        let tmp = TempDir::new().unwrap();
2997        let root = tmp.path();
2998        let mem_a = root.join("mem-a");
2999        std::fs::create_dir_all(&mem_a).unwrap();
3000        std::fs::create_dir_all(root.join(".memstead")).unwrap();
3001        std::fs::write(
3002            root.join(".memstead").join("workspace.toml"),
3003            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3004        )
3005        .unwrap();
3006        let mount = |mem: &str, dir: &Path, schema: &str, version: semver::Version| Mount {
3007            mem: mem.to_string(),
3008            schema: Some(SchemaRef::new(schema, version)),
3009            storage: MountStorage::Folder {
3010                path: dir.to_path_buf(),
3011            },
3012            capability: MountCapability::Write,
3013            lifecycle: MountLifecycle::Eager,
3014            cross_linkable: true,
3015            migration_target: None,
3016        };
3017        let save = |mounts: Vec<Mount>| {
3018            crate::FileWorkspaceStore::new()
3019                .save_state(
3020                    root,
3021                    &crate::workspace::Workspace {
3022                        mounts,
3023                        settings: crate::workspace::WorkspaceSettings::default(),
3024                    },
3025                )
3026                .unwrap();
3027        };
3028        save(vec![mount(
3029            "specs",
3030            &mem_a,
3031            "default",
3032            semver::Version::new(1, 0, 0),
3033        )]);
3034        let mut engine = Engine::from_workspace_root(root).expect("workspace boots");
3035        assert_eq!(engine.mem_names(), vec!["specs"]);
3036
3037        // --- Out of band, while the "server" runs: install a schema
3038        // and register a mem pinned to it. ---
3039        let manifest = r#"name: authored
3040version: 0.1.0
3041description: an out-of-band installed schema
3042when_to_use: tests
3043types:
3044  - doc
3045relationships:
3046  mode: strict
3047  definitions:
3048    - name: _default
3049      description: fallback
3050      default_weight: 1.0
3051community:
3052  resolution: 1.0
3053  seed: 42
3054"#;
3055        write_schema_files_with_default_type(
3056            &root.join(".memstead").join("schemas"),
3057            "authored@0.1.0",
3058            manifest,
3059            &["doc"],
3060        );
3061        let mem_b = root.join("mem-b");
3062        std::fs::create_dir_all(&mem_b).unwrap();
3063        save(vec![
3064            mount("specs", &mem_a, "default", semver::Version::new(1, 0, 0)),
3065            mount("notes", &mem_b, "authored", semver::Version::new(0, 1, 0)),
3066        ]);
3067
3068        // Since 2026-09-02 membership follows reload-before-operation: the
3069        // first operation would reconcile the roster on its own. The refresh
3070        // verb runs the same reconciliation, forced, and reports it.
3071        let (actor, client) = cli_actor();
3072        let mut pre = crate::engine::test_helpers::empty_create_args("notes", "Too Early");
3073        pre.entity_type = "doc".to_string();
3074        pre.sections = indexmap::IndexMap::from_iter([("body".to_string(), "body".to_string())]);
3075
3076        // --- Full refresh: both become usable, warm. ---
3077        let report = engine.full_refresh();
3078        assert_eq!(report.schemas_added, vec!["authored@0.1.0".to_string()]);
3079        assert_eq!(report.mems_mounted, vec!["notes".to_string()]);
3080        assert!(report.schema_removals_skipped.is_empty(), "{report:?}");
3081        assert!(report.mems_unmounted.is_empty(), "{report:?}");
3082        assert!(report.failures.is_empty(), "{report:?}");
3083        engine
3084            .create_entity(pre, actor, Some(&client), None)
3085            .expect("newly mounted mem accepts writes after the refresh");
3086
3087        // --- Removals do NOT take effect: drop `specs` from the
3088        // manifest and delete the schema package from its source. ---
3089        std::fs::remove_dir_all(
3090            root.join(".memstead")
3091                .join("schemas")
3092                .join("authored@0.1.0"),
3093        )
3094        .unwrap();
3095        save(vec![mount(
3096            "notes",
3097            &mem_b,
3098            "authored",
3099            semver::Version::new(0, 1, 0),
3100        )]);
3101        let report = engine.full_refresh();
3102        // Removals APPLY since 2026-09-02: the mem leaves the roster and is
3103        // no longer served; the schema removal stays skipped.
3104        assert_eq!(report.mems_unmounted, vec!["specs".to_string()]);
3105        assert_eq!(engine.mem_names(), vec!["notes"]);
3106        assert_eq!(
3107            report.schema_removals_skipped,
3108            vec!["authored@0.1.0".to_string()]
3109        );
3110        assert!(report.schemas_added.is_empty());
3111        assert!(report.mems_mounted.is_empty());
3112        // The unregistered mem is gone: a write naming it refuses with the
3113        // typed code; the removed schema version still resolves for its mem.
3114        let gone = engine
3115            .create_entity(
3116                crate::engine::test_helpers::empty_create_args("specs", "Still Here"),
3117                actor,
3118                Some(&client),
3119                None,
3120            )
3121            .expect_err("an unmounted mem refuses writes");
3122        assert_eq!(gone.code(), "MEM_UNMOUNTED", "{gone:?}");
3123        let mut into_notes =
3124            crate::engine::test_helpers::empty_create_args("notes", "Still Resolvable");
3125        into_notes.entity_type = "doc".to_string();
3126        into_notes.sections =
3127            indexmap::IndexMap::from_iter([("body".to_string(), "body".to_string())]);
3128        engine
3129            .create_entity(into_notes, actor, Some(&client), None)
3130            .expect("removed-from-source schema stays resolvable");
3131
3132        // --- Per-item failure: a manifest mount whose path is a FILE
3133        // fails alone; the rest of the refresh proceeds. ---
3134        let broken = root.join("broken-mem");
3135        std::fs::write(&broken, b"not a directory").unwrap();
3136        save(vec![
3137            mount("notes", &mem_b, "authored", semver::Version::new(0, 1, 0)),
3138            mount("broken", &broken, "default", semver::Version::new(1, 0, 0)),
3139        ]);
3140        let report = engine.full_refresh();
3141        assert!(
3142            report.mems_quarantined.contains(&"broken".to_string()),
3143            "a mount that cannot attach is quarantined per-item, as boot would: {report:?}"
3144        );
3145        assert!(engine.quarantine_reason("broken").is_some());
3146        assert!(
3147            !report.mems_mounted.contains(&"broken".to_string()),
3148            "a failed mount never surfaces as newly available"
3149        );
3150        assert!(
3151            engine
3152                .get_entity(&crate::EntityId::new("broken", "anything"))
3153                .is_none()
3154                && engine.mem_names().contains(&"notes"),
3155            "other mounts unaffected"
3156        );
3157    }
3158
3159    #[test]
3160    fn from_workspace_root_propagates_mem_management_settings() {
3161        // workspace.toml carries [mem_management] rules; the file
3162        // adapter parses them into Workspace.settings; from_workspace_root
3163        // calls Engine::set_settings so the engine surface reflects them.
3164        // End-to-end check that the carriers, parser, and plumbing connect.
3165        let tmp = TempDir::new().unwrap();
3166        let mem_dir = tmp.path().join("mem");
3167        std::fs::create_dir_all(&mem_dir).unwrap();
3168
3169        let memstead = tmp.path().join(".memstead");
3170        std::fs::create_dir_all(&memstead).unwrap();
3171        std::fs::write(
3172            memstead.join("workspace.toml"),
3173            r#"format = "memstead-git-branch-2"
3174
3175[persistence_adapter]
3176name = "file-two-layer"
3177
3178[[mem_management.create]]
3179pattern = "exec-*"
3180schemas = ["default@1.0.0"]
3181
3182[[mem_management.delete]]
3183pattern = "exec-*"
3184"#,
3185        )
3186        .unwrap();
3187        use crate::workspace_store::WorkspaceStoreAdapter;
3188        let store = crate::FileWorkspaceStore::new();
3189        store
3190            .save_state(
3191                tmp.path(),
3192                &crate::workspace::Workspace {
3193                    mounts: vec![folder_mount("specs", mem_dir)],
3194                    settings: crate::workspace::WorkspaceSettings::default(),
3195                },
3196            )
3197            .unwrap();
3198
3199        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
3200        let s = engine.settings();
3201        assert_eq!(s.mem_create_rules.len(), 1);
3202        assert_eq!(s.mem_create_rules[0].pattern, "exec-*");
3203        assert_eq!(
3204            s.mem_create_rules[0].schemas,
3205            vec!["default@1.0.0".to_string()]
3206        );
3207        assert_eq!(s.mem_delete_rules.len(), 1);
3208        assert_eq!(s.mem_delete_rules[0].pattern, "exec-*");
3209    }
3210
3211    /// Deliberate replacement of the historical wholesale-abort test
3212    /// (`from_mounts_rejects_unknown_schema_pin_with_typed_error`):
3213    /// an unresolvable pin no longer fails the
3214    /// workspace — the mem is QUARANTINED with the same typed
3215    /// `SCHEMA_NOT_FOUND` reason (nothing is weakened, the blast
3216    /// radius shrinks), operations naming it refuse `MEM_QUARANTINED`,
3217    /// and the roster surfaces on health.
3218    #[test]
3219    fn from_mounts_quarantines_unknown_schema_pin() {
3220        let tmp = TempDir::new().unwrap();
3221        let writer = FilesystemMemWriter::new(tmp.path().to_path_buf());
3222        let mount = Mount {
3223            mem: "specs".to_string(),
3224            schema: Some(SchemaRef::new(
3225                "totally-not-a-schema",
3226                semver::Version::new(1, 0, 0),
3227            )),
3228            storage: MountStorage::Folder {
3229                path: tmp.path().to_path_buf(),
3230            },
3231            capability: MountCapability::Write,
3232            lifecycle: MountLifecycle::Eager,
3233            cross_linkable: true,
3234            migration_target: None,
3235        };
3236        let engine = Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)])
3237            .expect("a broken mem quarantines, never fails the workspace");
3238
3239        let roster = engine.quarantined_mems();
3240        assert_eq!(roster.len(), 1);
3241        assert_eq!(roster[0].mount.mem, "specs");
3242        assert_eq!(roster[0].reason_code, "SCHEMA_NOT_FOUND");
3243        assert!(
3244            roster[0].reason_message.contains("totally-not-a-schema"),
3245            "reason carries the failing pin: {}",
3246            roster[0].reason_message
3247        );
3248        // The mem serves nothing: it is not on the mount roster …
3249        assert!(engine.mounts().iter().all(|m| m.mem != "specs"));
3250        // … and lookups refuse with the typed quarantine code, not
3251        // UNKNOWN_MEM.
3252        let err = engine.unknown_mem_error("specs");
3253        assert_eq!(err.code(), "MEM_QUARANTINED");
3254        assert!(
3255            err.to_string().contains("SCHEMA_NOT_FOUND"),
3256            "quarantine refusal carries the underlying reason: {err}"
3257        );
3258        // Health carries the roster without an include gate.
3259        let health = engine.health();
3260        assert_eq!(health.quarantined.len(), 1);
3261        assert_eq!(health.quarantined[0].reason_code, "SCHEMA_NOT_FOUND");
3262    }
3263
3264    /// Criterion 5: quarantine → repair →
3265    /// reload returns the mem to service in the same engine instance;
3266    /// the roster entry disappears. The repair here is the same
3267    /// value-level config-pin rewrite `memstead mem set-schema`
3268    /// performs below boot (plan 03).
3269    #[test]
3270    fn reload_returns_repaired_mem_from_quarantine() {
3271        let tmp = TempDir::new().unwrap();
3272        let dir = tmp.path().to_path_buf();
3273        std::fs::create_dir_all(dir.join(".memstead")).unwrap();
3274        let config_path = dir.join(".memstead").join("config.json");
3275        std::fs::write(&config_path, r#"{ "schema": "ghost@1.0.0" }"#).unwrap();
3276        let writer = FilesystemMemWriter::new(dir.clone());
3277        let mount = Mount {
3278            mem: "specs".to_string(),
3279            schema: None,
3280            storage: MountStorage::Folder { path: dir },
3281            capability: MountCapability::Write,
3282            lifecycle: MountLifecycle::Eager,
3283            cross_linkable: true,
3284            migration_target: None,
3285        };
3286        let mut engine =
3287            Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
3288        assert_eq!(engine.quarantined_mems().len(), 1);
3289        // Un-repaired reload keeps the quarantine (refreshed reason,
3290        // typed refusal).
3291        let err = engine.reload_one_mem("specs").unwrap_err();
3292        assert_eq!(err.code(), "MEM_QUARANTINED");
3293        assert_eq!(engine.quarantined_mems().len(), 1);
3294
3295        // Repair: repin the config to a resolvable schema (what
3296        // `mem set-schema` does below boot), then reload.
3297        std::fs::write(&config_path, r#"{ "schema": "default@1.0.0" }"#).unwrap();
3298        engine
3299            .reload_one_mem("specs")
3300            .expect("repaired mem re-attaches on reload");
3301        assert!(
3302            engine.quarantined_mems().is_empty(),
3303            "roster entry disappears after re-attach"
3304        );
3305        // …and the mem serves again in the same process.
3306        let mut sections = indexmap::IndexMap::new();
3307        sections.insert("identity".to_string(), "back".to_string());
3308        sections.insert("purpose".to_string(), "post-repair service".to_string());
3309        engine
3310            .create_entity_with_ctx(
3311                crate::engine::CreateEntityArgs {
3312                    anchors: Vec::new(),
3313                    mem: "specs".to_string(),
3314                    title: "Back".to_string(),
3315                    entity_type: "spec".to_string(),
3316                    sections,
3317                    metadata: indexmap::IndexMap::new(),
3318                    relations: Vec::new(),
3319                    dry_run: false,
3320                },
3321                &crate::vcs::CommitContext::internal(),
3322            )
3323            .expect("reattached mem serves writes");
3324    }
3325
3326    /// Criterion 2 complement: a healthy mem
3327    /// whose entity body wiki-links INTO a quarantined mem loads
3328    /// normally — the link degrades like any dangling cross-mem link
3329    /// (stub target), no cascade failure.
3330    #[test]
3331    fn cross_mem_link_into_quarantined_mem_degrades_without_cascade() {
3332        let tmp = TempDir::new().unwrap();
3333        let healthy_dir = tmp.path().join("healthy");
3334        std::fs::create_dir_all(&healthy_dir).unwrap();
3335        std::fs::write(
3336            healthy_dir.join("linker.md"),
3337            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\n---\n\
3338             # Linker\n\n## Identity\n\nsee [[badpin:target]] for detail.\n",
3339        )
3340        .unwrap();
3341        let badpin_dir = tmp.path().join("badpin");
3342        std::fs::create_dir_all(&badpin_dir).unwrap();
3343        let mount = |mem: &str, dir: std::path::PathBuf, pin: &str| {
3344            (
3345                Mount {
3346                    mem: mem.to_string(),
3347                    schema: Some(SchemaRef::new(pin, semver::Version::new(1, 0, 0))),
3348                    storage: MountStorage::Folder { path: dir.clone() },
3349                    capability: MountCapability::Write,
3350                    lifecycle: MountLifecycle::Eager,
3351                    cross_linkable: true,
3352                    migration_target: None,
3353                },
3354                Box::new(FilesystemMemWriter::new(dir)) as Box<dyn MemBackend>,
3355            )
3356        };
3357        let engine = Engine::from_mounts(vec![
3358            mount("healthy", healthy_dir, "default"),
3359            mount("badpin", badpin_dir, "ghost"),
3360        ])
3361        .expect("boot survives the cross-mem link into the quarantined mem");
3362        assert_eq!(engine.quarantined_mems().len(), 1);
3363        // The linking entity loaded; its target degrades to a stub /
3364        // dangling link — no cascade, no partial-truth serving of the
3365        // quarantined mem.
3366        let linker = engine
3367            .get_entity(&crate::EntityId::new("healthy", "linker"))
3368            .expect("linking entity loads");
3369        assert_eq!(linker.entity_type, "spec");
3370        assert!(
3371            engine
3372                .get_entity(&crate::EntityId::new("badpin", "target"))
3373                .is_none_or(|e| e.stub),
3374            "the quarantined-side target is at most a stub, never real data"
3375        );
3376    }
3377
3378    /// Complement: a workspace where
3379    /// one mem pins an authored schema still on the retired
3380    /// `propagating_relationships` key boots — that mem quarantines
3381    /// with the rename error as its reason (never workspace-fatal),
3382    /// while healthy mems load and serve.
3383    #[test]
3384    fn old_key_authored_schema_quarantines_pinning_mem_never_workspace() {
3385        let tmp = TempDir::new().unwrap();
3386        let root = tmp.path();
3387        // Workspace marker + two folder mems.
3388        std::fs::create_dir_all(root.join(".memstead").join("state")).unwrap();
3389        std::fs::write(
3390            root.join(".memstead").join("workspace.toml"),
3391            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3392        )
3393        .unwrap();
3394        for m in ["healthy", "oldkey"] {
3395            std::fs::create_dir_all(root.join(m)).unwrap();
3396        }
3397        std::fs::write(
3398            root.join(".memstead").join("state").join("mounts.json"),
3399            r#"{ "format": "memstead-mounts-3", "mounts": [
3400                { "mem": "healthy", "schema": "default@1.1.0", "storage": { "type": "folder", "path": "healthy" }, "capability": "write", "lifecycle": "eager", "cross_linkable": true },
3401                { "mem": "oldkey", "schema": "fieldschema@0.1.0", "storage": { "type": "folder", "path": "oldkey" }, "capability": "write", "lifecycle": "eager", "cross_linkable": true }
3402            ] }"#,
3403        )
3404        .unwrap();
3405        // The authored package, still on the retired key.
3406        let pkg = root
3407            .join(".memstead")
3408            .join("schemas")
3409            .join("fieldschema@0.1.0");
3410        std::fs::create_dir_all(pkg.join("types")).unwrap();
3411        std::fs::write(
3412            pkg.join("schema.yaml"),
3413            "name: fieldschema\nversion: 0.1.0\ndescription: field schema\nwhen_to_use: tests\ntypes:\n  - thing\nrelationships:\n  mode: strict\n  definitions:\n    - name: PART_OF\n      description: h\n      default_weight: 1.0\n      acyclic: true\n    - name: _default\n      description: f\n      default_weight: 1.0\ncommunity:\n  resolution: 1.0\n  seed: 42\n",
3414        )
3415        .unwrap();
3416        std::fs::write(
3417            pkg.join("types").join("thing.yaml"),
3418            "name: thing\ndescription: t\nwhen_to_use: h\nsections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\npropagating_relationships: []\nupdatable_fields:\n  - title\nhealth_required_fields: []\nstaleness_threshold_days: 90\nwrite_rules: []\n",
3419        )
3420        .unwrap();
3421
3422        let engine = Engine::from_workspace_root(root)
3423            .expect("the old-key schema quarantines its mem, never the workspace");
3424        assert!(engine.mounts().iter().any(|m| m.mem == "healthy"));
3425        let q = engine
3426            .quarantine_reason("oldkey")
3427            .expect("oldkey mem is quarantined");
3428        assert_eq!(q.reason_code, "SCHEMA_LOAD_FAILED");
3429        assert!(
3430            q.reason_message.contains("no_self_loop_relationships"),
3431            "quarantine reason is the rename error naming the new key: {}",
3432            q.reason_message
3433        );
3434    }
3435
3436    /// A mem pinned to the new
3437    /// ingest@0.3.0 reports its edge-less entry entities as leaf
3438    /// population, zero false orphans; the prior version (0.2.0) is
3439    /// unchanged — the same entity still counts as an orphan there.
3440    #[test]
3441    fn ingest_0_3_entries_are_leaves_prior_version_unchanged() {
3442        let entry_md = "---\ntype: coverage_gap\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nstatus: open\n---\n# Gap\n\n## Area\n\nan uncovered area.\n";
3443        let boot = |pin: &str| {
3444            let tmp = TempDir::new().unwrap();
3445            let dir = tmp.path().to_path_buf();
3446            std::fs::create_dir_all(dir.join(".memstead")).unwrap();
3447            std::fs::write(
3448                dir.join(".memstead").join("config.json"),
3449                format!("{{ \"schema\": \"{pin}\" }}"),
3450            )
3451            .unwrap();
3452            std::fs::write(dir.join("gap.md"), entry_md).unwrap();
3453            let writer = FilesystemMemWriter::new(dir.clone());
3454            let mount = Mount {
3455                mem: "proc".to_string(),
3456                schema: None,
3457                storage: MountStorage::Folder { path: dir },
3458                capability: MountCapability::Write,
3459                lifecycle: MountLifecycle::Eager,
3460                cross_linkable: true,
3461                migration_target: None,
3462            };
3463            let engine =
3464                Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)])
3465                    .unwrap();
3466            (engine.health(), tmp)
3467        };
3468
3469        let (health_new, _t1) = boot("ingest@0.3.0");
3470        assert_eq!(
3471            health_new.orphan_count, 0,
3472            "0.3.0 entry types are leaves — zero false orphans"
3473        );
3474        assert_eq!(
3475            health_new
3476                .leaf_entities_by_type
3477                .get("ingest@0.3.0:coverage_gap"),
3478            Some(&1),
3479            "the population stays visible: {:?}",
3480            health_new.leaf_entities_by_type
3481        );
3482
3483        let (health_old, _t2) = boot("ingest@0.2.0");
3484        assert_eq!(
3485            health_old.orphan_count, 1,
3486            "the prior version's behaviour is unchanged"
3487        );
3488        assert!(health_old.leaf_entities_by_type.is_empty());
3489    }
3490
3491    /// A workspace mixing one broken mem with healthy siblings boots,
3492    /// serves the healthy mems fully, and refuses typed on the
3493    /// quarantined one — the plenum shape (one bad pin, thirteen
3494    /// healthy hostages) can no longer occur. Drives the pin-failure
3495    /// and missing-pin variants in one fixture.
3496    #[test]
3497    fn broken_mem_quarantines_while_healthy_siblings_serve() {
3498        let tmp = TempDir::new().unwrap();
3499        let make_mount = |mem: &str, pin: Option<SchemaRef>| {
3500            let dir = tmp.path().join(mem);
3501            std::fs::create_dir_all(&dir).unwrap();
3502            let writer = FilesystemMemWriter::new(dir.clone());
3503            (
3504                Mount {
3505                    mem: mem.to_string(),
3506                    schema: pin,
3507                    storage: MountStorage::Folder { path: dir },
3508                    capability: MountCapability::Write,
3509                    lifecycle: MountLifecycle::Eager,
3510                    cross_linkable: true,
3511                    migration_target: None,
3512                },
3513                Box::new(writer) as Box<dyn MemBackend>,
3514            )
3515        };
3516        let healthy = make_mount(
3517            "healthy",
3518            Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
3519        );
3520        let bad_pin = make_mount(
3521            "badpin",
3522            Some(SchemaRef::new("ghost", semver::Version::new(1, 0, 0))),
3523        );
3524        let missing_pin = make_mount("nopin", None);
3525        // Backend-failure variant: the mount's storage path is a FILE,
3526        // so the backend's entity walk fails at read time.
3527        let bad_io_path = tmp.path().join("badio");
3528        std::fs::write(&bad_io_path, "not a directory").unwrap();
3529        let bad_io = (
3530            Mount {
3531                mem: "badio".to_string(),
3532                schema: Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
3533                storage: MountStorage::Folder {
3534                    path: bad_io_path.clone(),
3535                },
3536                capability: MountCapability::Write,
3537                lifecycle: MountLifecycle::Eager,
3538                cross_linkable: true,
3539                migration_target: None,
3540            },
3541            Box::new(FilesystemMemWriter::new(bad_io_path)) as Box<dyn MemBackend>,
3542        );
3543        let mut engine = Engine::from_mounts(vec![healthy, bad_pin, missing_pin, bad_io])
3544            .expect("mixed workspace boots");
3545
3546        // Roster: both broken mems, each with its own typed reason.
3547        let codes: std::collections::HashMap<String, String> = engine
3548            .quarantined_mems()
3549            .iter()
3550            .map(|q| (q.mount.mem.clone(), q.reason_code.clone()))
3551            .collect();
3552        assert_eq!(
3553            codes.get("badpin").map(String::as_str),
3554            Some("SCHEMA_NOT_FOUND")
3555        );
3556        assert_eq!(
3557            codes.get("nopin").map(String::as_str),
3558            Some("MEM_CONFIG_INCOMPLETE")
3559        );
3560        assert!(
3561            codes.contains_key("badio"),
3562            "backend read failure quarantines too: {codes:?}"
3563        );
3564
3565        // The healthy mem is fully writable.
3566        let mut sections = indexmap::IndexMap::new();
3567        sections.insert("identity".to_string(), "alive".to_string());
3568        sections.insert("purpose".to_string(), "proof of service".to_string());
3569        let created = engine
3570            .create_entity_with_ctx(
3571                crate::engine::CreateEntityArgs {
3572                    anchors: Vec::new(),
3573                    mem: "healthy".to_string(),
3574                    title: "Alive".to_string(),
3575                    entity_type: "spec".to_string(),
3576                    sections,
3577                    metadata: indexmap::IndexMap::new(),
3578                    relations: Vec::new(),
3579                    dry_run: false,
3580                },
3581                &crate::vcs::CommitContext::internal(),
3582            )
3583            .expect("healthy mem serves writes");
3584        assert_eq!(created.id.to_string(), "healthy--alive");
3585
3586        // Writes against a quarantined mem refuse with the typed code.
3587        let mut sections = indexmap::IndexMap::new();
3588        sections.insert("identity".to_string(), "x".to_string());
3589        let err = engine
3590            .create_entity_with_ctx(
3591                crate::engine::CreateEntityArgs {
3592                    anchors: Vec::new(),
3593                    mem: "badpin".to_string(),
3594                    title: "Nope".to_string(),
3595                    entity_type: "spec".to_string(),
3596                    sections,
3597                    metadata: indexmap::IndexMap::new(),
3598                    relations: Vec::new(),
3599                    dry_run: false,
3600                },
3601                &crate::vcs::CommitContext::internal(),
3602            )
3603            .unwrap_err();
3604        assert_eq!(err.code(), "MEM_QUARANTINED");
3605    }
3606
3607    /// Schema-pin authority: the mem's own per-mem config is the
3608    /// authoritative settled pin. Here the config pins a resolvable
3609    /// schema (`software@0.1.0`) while the workspace mount expects an
3610    /// unresolvable one — boot succeeds (proving the config pin won,
3611    /// not the mount's) and surfaces a `SchemaPinMismatch` warning
3612    /// naming both pins.
3613    #[test]
3614    fn mem_config_schema_is_authoritative_over_mount_pin() {
3615        let tmp = TempDir::new().unwrap();
3616        let mem_dir = tmp.path().to_path_buf();
3617        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
3618        std::fs::write(
3619            mem_dir.join(".memstead").join("config.json"),
3620            r#"{"schema":"software@0.1.0"}"#,
3621        )
3622        .unwrap();
3623        let writer = FilesystemMemWriter::new(mem_dir.clone());
3624        let mount = Mount {
3625            mem: "specs".to_string(),
3626            schema: Some(SchemaRef::new(
3627                "totally-not-a-schema",
3628                semver::Version::new(9, 9, 9),
3629            )),
3630            storage: MountStorage::Folder { path: mem_dir },
3631            capability: MountCapability::Write,
3632            lifecycle: MountLifecycle::Eager,
3633            cross_linkable: true,
3634            migration_target: None,
3635        };
3636        let engine = Engine::from_mounts(vec![(
3637            mount,
3638            Box::new(writer) as Box<dyn MemBackend>,
3639        )])
3640        .expect("config pin software@0.1.0 is authoritative — boot must resolve it despite the unresolvable mount pin");
3641
3642        let mismatch = engine
3643            .load_warnings()
3644            .iter()
3645            .find_map(|w| match w {
3646                WarningHint::SchemaPinMismatch {
3647                    mem,
3648                    config_pin,
3649                    mount_pin,
3650                } => Some((mem.clone(), config_pin.clone(), mount_pin.clone())),
3651                _ => None,
3652            })
3653            .expect("SchemaPinMismatch warning must surface naming both pins");
3654        assert_eq!(mismatch.0, "specs");
3655        assert_eq!(mismatch.1, "software@0.1.0");
3656        assert_eq!(mismatch.2, "totally-not-a-schema@9.9.9");
3657    }
3658
3659    #[test]
3660    fn from_workspace_root_quarantines_git_branch_mount_without_factory() {
3661        let tmp = TempDir::new().unwrap();
3662        let memstead = tmp.path().join(".memstead");
3663        std::fs::create_dir_all(&memstead).unwrap();
3664        std::fs::write(
3665            memstead.join("workspace.toml"),
3666            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3667        )
3668        .unwrap();
3669        // Hand-craft a state/mounts.json carrying a git-branch mount —
3670        // the folder boot path can't instantiate that backend.
3671        let state_dir = memstead.join("state");
3672        std::fs::create_dir_all(&state_dir).unwrap();
3673        std::fs::write(
3674            state_dir.join("mounts.json"),
3675            r#"{
3676                "format": "memstead-mounts-3",
3677                "mounts": [
3678                    {
3679                        "mem": "specs",
3680                        "schema": "default@1.0.0",
3681                        "storage": { "type": "git-branch", "gitdir": "/tmp/x.git", "branch": "specs" },
3682                        "capability": "write",
3683                        "lifecycle": "eager",
3684                        "cross_linkable": true
3685                    }
3686                ]
3687            }"#,
3688        )
3689        .unwrap();
3690        // Deliberate replacement of the historical wholesale-abort
3691        // assertion: an engine without the git-branch factory meeting a
3692        // git-branch mount QUARANTINES that mem (typed
3693        // UNSUPPORTED_WORKSPACE_SHAPE reason) instead of refusing the
3694        // whole workspace — the judgment is unchanged, the blast
3695        // radius shrinks to the one mount the folder boot path cannot
3696        // serve.
3697        let engine = Engine::from_workspace_root(tmp.path())
3698            .expect("folder boot quarantines the git-branch mount, never fails the workspace");
3699        let roster = engine.quarantined_mems();
3700        assert_eq!(roster.len(), 1);
3701        assert_eq!(roster[0].mount.mem, "specs");
3702        assert_eq!(roster[0].reason_code, "UNSUPPORTED_WORKSPACE_SHAPE");
3703        assert_eq!(engine.unknown_mem_error("specs").code(), "MEM_QUARANTINED");
3704    }
3705
3706    #[test]
3707    fn from_workspace_root_roots_standalone_folder_mem() {
3708        // Standalone collapse: a bare folder mem — `.memstead/config.json`
3709        // pinning a schema, no `workspace.toml` — boots as a one-mount
3710        // workspace instead of refusing with NotInitialised.
3711        let tmp = TempDir::new().unwrap();
3712        let root = tmp.path();
3713        std::fs::create_dir_all(root.join(".memstead")).unwrap();
3714        std::fs::write(
3715            root.join(".memstead").join("config.json"),
3716            r#"{"schema":"default@1.0.0"}"#,
3717        )
3718        .unwrap();
3719        // A collapsed single-mem folder keeps its `.md` files at the root.
3720        std::fs::write(
3721            root.join("hello.md"),
3722            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nStandalone body.\n",
3723        )
3724        .unwrap();
3725
3726        let engine = Engine::from_workspace_root(root)
3727            .expect("a bare folder mem must root as a one-mount workspace");
3728        assert_eq!(engine.status().mem_count, 1, "exactly one mount");
3729        assert!(
3730            engine.status().entity_count >= 1,
3731            "the standalone mem's entity must load"
3732        );
3733    }
3734
3735    #[test]
3736    fn booting_a_workspace_writes_nothing_into_it() {
3737        // A read is a read. Booting an engine over a workspace must not
3738        // touch a single byte of it: not the config, not the mount state,
3739        // and not the authoring meta-schemas, which used to be republished
3740        // on every boot and so stamped a newer binary's copy over whatever
3741        // was on disk. That made a read-only mount, an installed
3742        // third-party mem, and a sealed corpus impossible to read without
3743        // modifying. The meta-schemas now publish from the schema-authoring
3744        // commands instead. This test fails if any boot-time write returns.
3745        let tmp = TempDir::new().unwrap();
3746        let root = tmp.path();
3747        std::fs::create_dir_all(root.join(".memstead").join("meta-schemas")).unwrap();
3748        std::fs::write(
3749            root.join(".memstead").join("config.json"),
3750            r#"{"schema":"default@1.0.0"}"#,
3751        )
3752        .unwrap();
3753        // A deliberately stale meta-schema: byte-different from the embedded
3754        // one, so a returning republish overwrites it and the test sees it.
3755        let stale = root
3756            .join(".memstead")
3757            .join("meta-schemas")
3758            .join("type-definition.schema.json");
3759        std::fs::write(&stale, "{\"title\":\"stale, from an older binary\"}").unwrap();
3760        std::fs::write(
3761            root.join("hello.md"),
3762            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nStandalone body.\n",
3763        )
3764        .unwrap();
3765
3766        fn snapshot(dir: &Path) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {
3767            let mut out = std::collections::BTreeMap::new();
3768            let mut stack = vec![dir.to_path_buf()];
3769            while let Some(d) = stack.pop() {
3770                for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() {
3771                    let p = entry.path();
3772                    if p.is_dir() {
3773                        stack.push(p);
3774                    } else if let Ok(bytes) = std::fs::read(&p) {
3775                        out.insert(p, bytes);
3776                    }
3777                }
3778            }
3779            out
3780        }
3781
3782        let before = snapshot(root);
3783        let engine = Engine::from_workspace_root(root).expect("the fixture must boot");
3784        assert_eq!(engine.status().mem_count, 1, "fixture sanity: one mount");
3785        let after = snapshot(root);
3786
3787        assert_eq!(
3788            before.keys().collect::<Vec<_>>(),
3789            after.keys().collect::<Vec<_>>(),
3790            "boot created or removed a file in the workspace it read"
3791        );
3792        for (path, bytes) in &before {
3793            assert_eq!(
3794                bytes,
3795                after.get(path).unwrap(),
3796                "boot rewrote {} in the workspace it read",
3797                path.display()
3798            );
3799        }
3800    }
3801
3802    #[test]
3803    fn from_workspace_root_still_rejects_truly_empty_dir() {
3804        // Refusal complement: a directory with neither `workspace.toml` nor a
3805        // `.memstead/config.json` is not a mem — it still refuses, so the
3806        // standalone path never masks a genuinely uninitialised directory.
3807        let tmp = TempDir::new().unwrap();
3808        let err = Engine::from_workspace_root(tmp.path()).unwrap_err();
3809        assert!(
3810            matches!(err, crate::BootError::NotInitialised(_)),
3811            "got {err:?}"
3812        );
3813    }
3814
3815    /// A workspace whose installed schema violates the heading
3816    /// round-trip rule still boots and serves reads; the violation
3817    /// surfaces as a `SCHEMA_HEADING_ROUNDTRIP_VIOLATION` load warning
3818    /// (merged into health), never as a boot failure — refusing at
3819    /// boot would brick every workspace that installed such a schema
3820    /// before the install gate existed.
3821    #[test]
3822    fn boot_keeps_loading_violating_schema_and_surfaces_health_finding() {
3823        let tmp = TempDir::new().unwrap();
3824        let schemas_dir = tmp.path().join("schemas");
3825        let pkg = schemas_dir.join("debate");
3826        std::fs::create_dir_all(pkg.join("types")).unwrap();
3827        std::fs::write(
3828            pkg.join("schema.yaml"),
3829            r#"name: debate
3830version: 0.1.0
3831description: sealed-violator fixture
3832when_to_use: tests
3833types:
3834  - question
3835relationships:
3836  mode: strict
3837  definitions:
3838    - name: PART_OF
3839      description: hier
3840      default_weight: 3.0
3841    - name: _default
3842      description: fallback
3843      default_weight: 1.0
3844community:
3845  resolution: 1.0
3846  seed: 42
3847"#,
3848        )
3849        .unwrap();
3850        std::fs::write(
3851            pkg.join("types").join("question.yaml"),
3852            r#"name: question
3853description: t
3854when_to_use: tests
3855sections:
3856  - key: answers
3857    heading: Answers argued
3858    required: true
3859    search_weight: 10.0
3860    write_rules: []
3861  - key: notes
3862    heading: Notes
3863    required: false
3864    search_weight: 3.0
3865    catch_all: true
3866    write_rules: []
3867metadata_fields: []
3868title_weight: 100.0
3869text_fields:
3870  - answers
3871  - notes
3872hierarchy_relationship: PART_OF
3873no_self_loop_relationships: []
3874updatable_fields:
3875  - title
3876  - answers
3877  - notes
3878health_required_fields:
3879  - answers
3880staleness_threshold_days: 90
3881write_rules: []
3882"#,
3883        )
3884        .unwrap();
3885
3886        let mem_dir = tmp.path().join("mem");
3887        std::fs::create_dir_all(&mem_dir).unwrap();
3888        std::fs::write(
3889            mem_dir.join("q.md"),
3890            "---\ntype: question\n---\n# Q\n\n## Answers argued\n\nTwo answers.\n",
3891        )
3892        .unwrap();
3893
3894        let writer = FilesystemMemWriter::new(mem_dir.clone());
3895        let mount = Mount {
3896            mem: "debate-mem".to_string(),
3897            schema: Some(SchemaRef::new("debate", semver::Version::new(0, 1, 0))),
3898            storage: MountStorage::Folder { path: mem_dir },
3899            capability: MountCapability::Write,
3900            lifecycle: MountLifecycle::Eager,
3901            cross_linkable: true,
3902            migration_target: None,
3903        };
3904        let engine = Engine::from_mounts_with_schemas_dir(
3905            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
3906            Some(&schemas_dir),
3907        )
3908        .expect("a violating sealed schema must keep loading, never refuse boot");
3909
3910        // Reads still serve.
3911        assert!(
3912            engine.status().entity_count >= 1,
3913            "entities load despite the schema violation"
3914        );
3915
3916        // The violation is a health finding with the full tuple.
3917        let hits: Vec<_> = engine
3918            .load_warnings()
3919            .iter()
3920            .filter_map(|w| match w {
3921                WarningHint::SchemaHeadingRoundtripViolation {
3922                    mem,
3923                    schema_ref,
3924                    violations,
3925                } => Some((mem.clone(), schema_ref.clone(), violations.clone())),
3926                _ => None,
3927            })
3928            .collect();
3929        assert_eq!(
3930            hits.len(),
3931            1,
3932            "exactly one schema-level finding; all warnings = {:?}",
3933            engine.load_warnings()
3934        );
3935        let (mem, schema_ref, violations) = &hits[0];
3936        assert_eq!(mem, "debate-mem");
3937        assert_eq!(schema_ref, "debate@0.1.0");
3938        assert_eq!(violations.len(), 1);
3939        assert_eq!(violations[0].type_name, "question");
3940        assert_eq!(violations[0].key, "answers");
3941        assert_eq!(violations[0].heading, "Answers argued");
3942        assert_eq!(violations[0].derived_key, "answers_argued");
3943    }
3944
3945    /// The other half of "still serves reads AND writes": a mem pinned
3946    /// to a sealed heading-round-trip-violating schema accepts writes.
3947    /// The update commits (refusal complement: it is NOT refused), the
3948    /// schema-level health finding persists after the write, and the
3949    /// write-path `SECTION_HEADING_DIVERGENCE` warning fires where its
3950    /// condition holds (the file carries a heading that derives to the
3951    /// written key while the schema declares a different heading text).
3952    #[test]
3953    fn sealed_violator_mem_still_serves_writes() {
3954        // Same fixture as the read test above.
3955        let tmp = TempDir::new().unwrap();
3956        let schemas_dir = tmp.path().join("schemas");
3957        let pkg = schemas_dir.join("debate");
3958        std::fs::create_dir_all(pkg.join("types")).unwrap();
3959        std::fs::write(
3960            pkg.join("schema.yaml"),
3961            r#"name: debate
3962version: 0.1.0
3963description: sealed-violator fixture
3964when_to_use: tests
3965types:
3966  - question
3967relationships:
3968  mode: strict
3969  definitions:
3970    - name: PART_OF
3971      description: hier
3972      default_weight: 3.0
3973    - name: _default
3974      description: fallback
3975      default_weight: 1.0
3976community:
3977  resolution: 1.0
3978  seed: 42
3979"#,
3980        )
3981        .unwrap();
3982        std::fs::write(
3983            pkg.join("types").join("question.yaml"),
3984            r#"name: question
3985description: t
3986when_to_use: tests
3987sections:
3988  - key: answers
3989    heading: Answers argued
3990    required: true
3991    search_weight: 10.0
3992    write_rules: []
3993  - key: notes
3994    heading: Notes
3995    required: false
3996    search_weight: 3.0
3997    catch_all: true
3998    write_rules: []
3999metadata_fields: []
4000title_weight: 100.0
4001text_fields:
4002  - answers
4003  - notes
4004hierarchy_relationship: PART_OF
4005no_self_loop_relationships: []
4006updatable_fields:
4007  - title
4008  - answers
4009  - notes
4010health_required_fields:
4011  - answers
4012staleness_threshold_days: 90
4013write_rules: []
4014"#,
4015        )
4016        .unwrap();
4017
4018        let mem_dir = tmp.path().join("mem");
4019        std::fs::create_dir_all(&mem_dir).unwrap();
4020        // The file's own heading "Answers" derives to the key
4021        // `answers`, differing from the schema's declared
4022        // "Answers argued" — the divergence-warning condition.
4023        std::fs::write(
4024            mem_dir.join("q.md"),
4025            "---\ntype: question\n---\n# Q\n\n## Answers\n\nTwo answers.\n",
4026        )
4027        .unwrap();
4028
4029        let writer = FilesystemMemWriter::new(mem_dir.clone());
4030        let mount = Mount {
4031            mem: "debate-mem".to_string(),
4032            schema: Some(SchemaRef::new("debate", semver::Version::new(0, 1, 0))),
4033            storage: MountStorage::Folder { path: mem_dir },
4034            capability: MountCapability::Write,
4035            lifecycle: MountLifecycle::Eager,
4036            cross_linkable: true,
4037            migration_target: None,
4038        };
4039        let mut engine = Engine::from_mounts_with_schemas_dir(
4040            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
4041            Some(&schemas_dir),
4042        )
4043        .expect("a violating sealed schema must keep loading");
4044
4045        let id = crate::EntityId::new("debate-mem", "q");
4046        let hash = engine.get_entity(&id).unwrap().content_hash.clone();
4047        let mut sections = indexmap::IndexMap::new();
4048        sections.insert("answers".to_string(), "Updated answers body.".to_string());
4049        let outcome = engine
4050            .update_entity(
4051                crate::engine::UpdateEntityArgs {
4052                    anchors: Vec::new(),
4053                    anchors_unset: Vec::new(),
4054                    id: id.clone(),
4055                    expected_hash: Some(hash),
4056                    sections,
4057                    append_sections: indexmap::IndexMap::new(),
4058                    patch_sections: indexmap::IndexMap::new(),
4059                    sections_unset: Vec::new(),
4060                    metadata: indexmap::IndexMap::new(),
4061                    metadata_unset: Vec::new(),
4062                    declare_relations: Vec::new(),
4063                    dry_run: false,
4064                    relations_unset: Vec::new(),
4065                },
4066                crate::vcs::Actor::Cli,
4067                None,
4068                None,
4069            )
4070            .expect("a write against a sealed-violator mem must NOT be refused");
4071        assert!(!outcome.write_id.is_empty(), "the write commits");
4072        assert!(
4073            outcome
4074                .warnings
4075                .iter()
4076                .any(|w| w.code() == "SECTION_HEADING_DIVERGENCE"),
4077            "the write-path divergence warning fires where its condition holds: {:?}",
4078            outcome.warnings
4079        );
4080
4081        // The schema-level finding persists after the write.
4082        assert!(
4083            engine.load_warnings().iter().any(|w| matches!(
4084                w,
4085                WarningHint::SchemaHeadingRoundtripViolation { mem, .. } if mem == "debate-mem"
4086            )),
4087            "the health finding persists across writes"
4088        );
4089        // The written content is durably on disk and survives the
4090        // reparse — under the catch-all, because the violating schema's
4091        // declared heading cannot round-trip to the written key. That
4092        // fork is exactly what the divergence warning announced (and
4093        // what the persisting health finding tells the operator to fix
4094        // at the schema); the "serves writes" guarantee is that the
4095        // write lands and nothing refuses, not that a broken schema
4096        // routes content correctly.
4097        let entity = engine.get_entity(&id).unwrap();
4098        assert!(
4099            entity
4100                .sections
4101                .values()
4102                .any(|s| s.contains("Updated answers body.")),
4103            "written content survives the round-trip (in the catch-all): {:?}",
4104            entity.sections
4105        );
4106    }
4107
4108    /// A search `mem` filter naming no visible mem refuses typed
4109    /// `UNKNOWN_MEM` — matching every other mem-naming surface — while a
4110    /// quarantined mem keeps its established typed refusal and a VALID
4111    /// mem with no matches still returns success with 0 hits. Absence of
4112    /// mem and absence of matches are never the same answer
4113    /// (an earlier plan, decision 4).
4114    #[test]
4115    fn search_mem_filter_gates_against_visible_roster() {
4116        use crate::vcs::Actor;
4117        use crate::workspace_store::WorkspaceStoreAdapter;
4118        use indexmap::IndexMap;
4119
4120        let tmp = TempDir::new().unwrap();
4121        let mem_dir = tmp.path().join("mem");
4122        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
4123        std::fs::write(
4124            mem_dir.join(".memstead").join("config.json"),
4125            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
4126        )
4127        .unwrap();
4128        let memstead = tmp.path().join(".memstead");
4129        std::fs::create_dir_all(&memstead).unwrap();
4130        std::fs::write(
4131            memstead.join("workspace.toml"),
4132            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
4133        )
4134        .unwrap();
4135        crate::FileWorkspaceStore::new()
4136            .save_state(
4137                tmp.path(),
4138                &crate::workspace::Workspace {
4139                    mounts: vec![folder_mount("specs", mem_dir.clone())],
4140                    settings: crate::workspace::WorkspaceSettings::default(),
4141                },
4142            )
4143            .unwrap();
4144        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
4145        let mut sections = IndexMap::new();
4146        sections.insert(
4147            "identity".to_string(),
4148            "Zebra searching fixture.".to_string(),
4149        );
4150        sections.insert("purpose".to_string(), "Search gate test.".to_string());
4151        engine
4152            .create_entity(
4153                crate::CreateEntityArgs {
4154                    mem: "specs".to_string(),
4155                    title: "Zebra".to_string(),
4156                    entity_type: "spec".to_string(),
4157                    sections,
4158                    metadata: IndexMap::new(),
4159                    relations: Vec::new(),
4160                    anchors: Vec::new(),
4161                    dry_run: false,
4162                },
4163                Actor::Agent,
4164                None,
4165                None,
4166            )
4167            .unwrap();
4168
4169        let scope = |mem: Option<&str>, term: &str| crate::ops::SearchScope {
4170            query: Some(crate::ops::Query {
4171                any: vec![term.to_string()],
4172                ..Default::default()
4173            }),
4174            mem: mem.map(str::to_string),
4175            ..Default::default()
4176        };
4177
4178        // Nonexistent mem → typed UNKNOWN_MEM, never success-with-0-hits.
4179        let err = engine
4180            .search(&scope(Some("no-such-mem"), "zebra"))
4181            .expect_err("a nonexistent mem filter must refuse");
4182        assert_eq!(err.code(), "UNKNOWN_MEM", "got {err:?}");
4183
4184        // Valid mem, matching query → hits.
4185        let hit = engine.search(&scope(Some("specs"), "zebra")).unwrap();
4186        assert!(hit.total >= 1, "the fixture entity matches: {hit:?}");
4187
4188        // Valid mem, no matches → success with 0 hits (the gate
4189        // distinguishes absence of mem from absence of matches).
4190        let none = engine
4191            .search(&scope(Some("specs"), "quixotic-nonword"))
4192            .unwrap();
4193        assert_eq!(none.total, 0, "{none:?}");
4194    }
4195
4196    // ---- Engine::reload_one_mem -----------------------------------
4197
4198    // ---- lazy mounts (flywheel W7/01) -----------------------------
4199
4200    fn lazy_folder_mount(mem: &str, path: std::path::PathBuf) -> Mount {
4201        Mount {
4202            lifecycle: MountLifecycle::Lazy,
4203            ..folder_mount(mem, path)
4204        }
4205    }
4206
4207    fn write_spec(dir: &Path, slug: &str, title: &str, extra: &str) {
4208        std::fs::write(
4209            dir.join(format!("{slug}.md")),
4210            format!("---\ntype: spec\n---\n# {title}\n\n## Identity\n\nBody.\n{extra}"),
4211        )
4212        .unwrap();
4213    }
4214
4215    fn two_mem_dirs(tmp: &TempDir) -> (std::path::PathBuf, std::path::PathBuf) {
4216        let eager_dir = tmp.path().join("eag");
4217        let lazy_dir = tmp.path().join("laz");
4218        std::fs::create_dir_all(&eager_dir).unwrap();
4219        std::fs::create_dir_all(&lazy_dir).unwrap();
4220        write_spec(&eager_dir, "alpha", "Alpha", "");
4221        write_spec(&lazy_dir, "omega", "Omega", "");
4222        (eager_dir, lazy_dir)
4223    }
4224
4225    fn mixed_engine(eager_dir: &Path, lazy_dir: &Path) -> Engine {
4226        Engine::from_mounts(vec![
4227            (
4228                folder_mount("eag", eager_dir.to_path_buf()),
4229                Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf())) as Box<dyn MemBackend>,
4230            ),
4231            (
4232                lazy_folder_mount("laz", lazy_dir.to_path_buf()),
4233                Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf())) as Box<dyn MemBackend>,
4234            ),
4235        ])
4236        .unwrap()
4237    }
4238
4239    /// The lazy lifecycle defers exactly the entity load: boot carries
4240    /// the mem on the roster with its schema resolved but no entities;
4241    /// the first operation touching it (the `reload_if_stale` funnel)
4242    /// triggers the load; afterwards the mem behaves identically to an
4243    /// eager mount and the deferred state is gone for good.
4244    #[test]
4245    fn lazy_mount_defers_and_first_read_loads() {
4246        let tmp = TempDir::new().unwrap();
4247        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4248        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4249
4250        // Boot: eager loaded, lazy on the roster but deferred.
4251        assert!(
4252            engine
4253                .get_entity(&crate::EntityId::new("eag", "alpha"))
4254                .is_some()
4255        );
4256        assert_eq!(engine.deferred_mems(), vec!["laz"]);
4257        assert!(engine.mem_is_deferred("laz"));
4258        assert!(
4259            engine
4260                .get_entity(&crate::EntityId::new("laz", "omega"))
4261                .is_none(),
4262            "deferred mem's entities are not in the store yet"
4263        );
4264        // Never absent: the mount roster and schema map both carry it.
4265        assert!(engine.schema_for("laz").is_some());
4266
4267        // First read triggers the load through the operation funnel.
4268        engine.reload_if_stale(Some("laz"));
4269        assert!(engine.deferred_mems().is_empty());
4270        let omega = engine
4271            .get_entity(&crate::EntityId::new("laz", "omega"))
4272            .expect("first read loads the mem");
4273        assert_eq!(omega.title, "Omega");
4274
4275        // Identical to eager from here on: a write round-trips.
4276        let (actor, client) = cli_actor();
4277        engine
4278            .create_entity(
4279                empty_create_args("laz", "Later"),
4280                actor,
4281                Some(&client),
4282                None,
4283            )
4284            .unwrap();
4285        assert!(
4286            engine
4287                .get_entity(&crate::EntityId::new("laz", "later"))
4288                .is_some()
4289        );
4290    }
4291
4292    /// An operation scoped to an eager mem never loads a lazy sibling
4293    /// as a side effect; a workspace-scoped funnel pass loads every
4294    /// deferred mem so no answer computes over a partial store.
4295    #[test]
4296    fn scoped_operation_never_loads_lazy_sibling() {
4297        let tmp = TempDir::new().unwrap();
4298        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4299        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4300
4301        engine.reload_if_stale(Some("eag"));
4302        assert_eq!(
4303            engine.deferred_mems(),
4304            vec!["laz"],
4305            "an eager-scoped operation must not load the lazy sibling"
4306        );
4307
4308        engine.reload_if_stale(None);
4309        assert!(
4310            engine.deferred_mems().is_empty(),
4311            "a workspace-scoped pass loads every deferred mem"
4312        );
4313    }
4314
4315    /// A deferred load that fails quarantines the mem at the moment of
4316    /// first read, with the same typed reporting an eager boot failure
4317    /// produces — never an empty-mem impression.
4318    #[test]
4319    fn lazy_load_failure_quarantines_typed() {
4320        let tmp = TempDir::new().unwrap();
4321        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4322        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4323
4324        // The backend's tree is destroyed between boot and first read —
4325        // a plain file now sits where the mem directory was, so the
4326        // entity walk errors rather than reading an empty directory.
4327        std::fs::remove_dir_all(&lazy_dir).unwrap();
4328        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4329        engine.reload_if_stale(Some("laz"));
4330
4331        let q = engine
4332            .quarantine_reason("laz")
4333            .expect("failed deferred load quarantines, never serves empty");
4334        assert!(!q.reason_code.is_empty());
4335        assert!(
4336            !engine.mem_names().contains(&"laz"),
4337            "a quarantined mem leaves the serving roster"
4338        );
4339        assert!(engine.deferred_mems().is_empty());
4340    }
4341
4342    /// Quarantine-ENTRY invalidation pin (flywheel W8/01, first
4343    /// grade's refutation): entering quarantine from a failed deferred
4344    /// load removes the mem's schema (epoch bump) — a search memo
4345    /// filled beforehand is then stale-keyed and MUST clear, or the
4346    /// next search trips the memo-key debug_assert (the grade's live
4347    /// repro). Same rule pinned for the reattach-failure branch by
4348    /// re-failing the reattach.
4349    #[test]
4350    fn quarantine_entry_invalidates_both_memos() {
4351        let tmp = TempDir::new().unwrap();
4352        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4353        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4354
4355        // Fill both memos while the lazy mem is still deferred.
4356        let _ = engine.communities();
4357        let _ = engine.search_indexes();
4358        assert!(engine.search_indexes_memo.get().is_some());
4359
4360        // Destroy the backend; the first read quarantines the mem.
4361        std::fs::remove_dir_all(&lazy_dir).unwrap();
4362        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4363        engine.reload_if_stale(Some("laz"));
4364        assert!(engine.quarantine_reason("laz").is_some());
4365        assert!(
4366            engine.search_indexes_memo.get().is_none(),
4367            "quarantine entry bumps the schemas epoch — the search memo must clear"
4368        );
4369        assert!(
4370            engine.community_memo.get().is_none(),
4371            "quarantine entry must clear the community memo too"
4372        );
4373        // The next search must not trip the memo-key assert.
4374        let _ = engine.search_indexes();
4375
4376        // Reattach FAILURE (backend still broken): same rule.
4377        let _ = engine.communities();
4378        let _ = engine.search_indexes();
4379        let _ = engine.reload_one_mem("laz");
4380        assert!(engine.quarantine_reason("laz").is_some());
4381        assert!(
4382            engine.search_indexes_memo.get().is_none(),
4383            "a failed reattach bumps the epoch — the search memo must clear"
4384        );
4385        let _ = engine.search_indexes();
4386    }
4387
4388    /// Quarantine-reattach regression pin (flywheel W8/01, criterion
4389    /// 2's complement): the reattach path routes through the one-mem
4390    /// reload, which invalidates BOTH derived memos — pinned so
4391    /// incremental maintenance can never silently degrade it.
4392    #[test]
4393    fn quarantine_reattach_invalidates_both_memos() {
4394        let tmp = TempDir::new().unwrap();
4395        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4396        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4397
4398        // Quarantine the lazy mem: destroy its backend, trigger load.
4399        std::fs::remove_dir_all(&lazy_dir).unwrap();
4400        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4401        engine.reload_if_stale(Some("laz"));
4402        assert!(engine.quarantine_reason("laz").is_some());
4403
4404        // Fill both memos while the mem sits quarantined.
4405        let _ = engine.communities();
4406        let _ = engine.search_indexes();
4407        assert!(engine.community_memo.get().is_some());
4408        assert!(engine.search_indexes_memo.get().is_some());
4409
4410        // Restore the backend and reattach via the reload path.
4411        std::fs::remove_file(&lazy_dir).unwrap();
4412        std::fs::create_dir_all(&lazy_dir).unwrap();
4413        write_spec(&lazy_dir, "omega", "Omega", "");
4414        engine
4415            .reload_one_mem("laz")
4416            .expect("reattach succeeds once the backend is back");
4417        assert!(engine.quarantine_reason("laz").is_none());
4418
4419        // Both memos cleared — the reattached mem's entities must be
4420        // visible to the next partition and the next search.
4421        assert!(
4422            engine.community_memo.get().is_none(),
4423            "reattach must invalidate the community memo"
4424        );
4425        assert!(
4426            engine.search_indexes_memo.get().is_none(),
4427            "reattach must invalidate the search memo"
4428        );
4429    }
4430
4431    /// The lazy load runs the same validation gauntlet an eager boot
4432    /// runs: content an eager boot warns about produces the SAME
4433    /// warning when its mem loads lazily — deferral changes when, not
4434    /// whether.
4435    #[test]
4436    fn lazy_load_runs_the_same_validation_gauntlet() {
4437        let tmp = TempDir::new().unwrap();
4438        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4439        // Hand-authored invalid relation in the LAZY mem.
4440        std::fs::write(
4441            lazy_dir.join("bad.md"),
4442            "---\ntype: spec\n---\n# Bad\n\n## Identity\n\nx.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[laz--omega]]\n",
4443        )
4444        .unwrap();
4445
4446        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4447        let warned_before = engine
4448            .load_warnings()
4449            .iter()
4450            .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }));
4451        engine.reload_if_stale(Some("laz"));
4452        let warned_after = engine
4453            .load_warnings()
4454            .iter()
4455            .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }));
4456        assert!(
4457            !warned_before && warned_after,
4458            "the gauntlet fires at load time: before={warned_before} after={warned_after}, \
4459             warnings: {:?}",
4460            engine.load_warnings()
4461        );
4462        // And the offending relation was dropped, as an eager boot drops it.
4463        let bad = engine
4464            .get_entity(&crate::EntityId::new("laz", "bad"))
4465            .unwrap();
4466        assert!(bad.relationships.is_empty());
4467    }
4468
4469    /// The destructive guard sees referrers living in DEFERRED mems:
4470    /// deleting an entity whose incoming references originate in a lazy,
4471    /// not-yet-loaded mem refuses `HAS_INCOMING_REFS` exactly as an
4472    /// eager boot refuses it. The third final grade demonstrated the
4473    /// counterexample live — the scoped reload left the referrer's mem
4474    /// unloaded and the delete destroyed the entity an eager boot
4475    /// protects. The guard now takes the full load first.
4476    #[test]
4477    fn delete_guard_sees_referrers_in_deferred_mems() {
4478        use crate::engine::{DeleteEntityArgs, RelateEntityArgs};
4479
4480        let tmp = TempDir::new().unwrap();
4481        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4482        let (actor, client) = cli_actor();
4483
4484        // Author the cross-mem referrer through the mutation surface
4485        // while both mems are eager (with the cross-link grant), so the
4486        // persisted relation is exactly what a real workspace carries.
4487        {
4488            let mut authoring = Engine::from_mounts(vec![
4489                (
4490                    folder_mount("eag", eager_dir.to_path_buf()),
4491                    Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf()))
4492                        as Box<dyn MemBackend>,
4493                ),
4494                (
4495                    folder_mount("laz", lazy_dir.to_path_buf()),
4496                    Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf()))
4497                        as Box<dyn MemBackend>,
4498                ),
4499            ])
4500            .unwrap();
4501            let mut settings = crate::workspace::WorkspaceSettings::default();
4502            settings.cross_mem_links.insert(
4503                "laz".to_string(),
4504                memstead_schema::workspace_config::CrossLinkValue::List(vec!["eag".to_string()]),
4505            );
4506            authoring.set_settings(settings);
4507            authoring
4508                .relate_entity(
4509                    RelateEntityArgs {
4510                        source: crate::EntityId::new("laz", "omega"),
4511                        expected_hash: None,
4512                        rel_type: "USES".to_string(),
4513                        target: crate::EntityId::new("eag", "alpha"),
4514                        remove: false,
4515                        description: None,
4516                        dry_run: false,
4517                    },
4518                    actor,
4519                    Some(&client),
4520                    None,
4521                )
4522                .expect("cross-mem relate lands under the grant");
4523        }
4524
4525        // Fresh boot with the REFERRER's mem lazy: the incoming edge
4526        // into `eag--alpha` lives in an unloaded mem. The guard must
4527        // still see it — full load before destructive adjudication.
4528        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4529        assert!(engine.mem_is_deferred("laz"));
4530        let err = engine
4531            .delete_entity(
4532                DeleteEntityArgs {
4533                    id: crate::EntityId::new("eag", "alpha"),
4534                    expected_hash: None,
4535                },
4536                actor,
4537                Some(&client),
4538                None,
4539            )
4540            .expect_err("a referenced entity must refuse deletion, lazy referrer or not");
4541        assert!(
4542            matches!(err, EngineError::HasIncomingRefs { .. }),
4543            "expected HAS_INCOMING_REFS, got {err:?}"
4544        );
4545        assert!(
4546            engine
4547                .get_entity(&crate::EntityId::new("eag", "alpha"))
4548                .is_some(),
4549            "the entity survives"
4550        );
4551    }
4552
4553    /// The write-time acyclicity guard sees edges living in DEFERRED
4554    /// mems: an add that closes a cycle THROUGH a lazy, not-yet-loaded
4555    /// mem refuses `RELATIONSHIP_CYCLE` exactly as an eager boot
4556    /// refuses it. The fourth final grade demonstrated the
4557    /// counterexample on a three-mem chain — the mid-path edge lived on
4558    /// the lazy mem's entity, the walk over the endpoint mems missed
4559    /// it, the cycle landed, and the next eager boot dropped an
4560    /// INNOCENT pre-existing edge to break it. A two-mem fixture would
4561    /// pass vacuously (relate loads both endpoint mems); three mems
4562    /// with the middle one lazy is the discriminating shape.
4563    #[test]
4564    fn acyclicity_guard_sees_edges_in_deferred_mems() {
4565        use crate::engine::RelateEntityArgs;
4566        use memstead_schema::workspace_config::CrossLinkValue;
4567
4568        let tmp = TempDir::new().unwrap();
4569        let dirs: Vec<std::path::PathBuf> = ["ma", "mb", "mc"]
4570            .iter()
4571            .map(|m| {
4572                let d = tmp.path().join(m);
4573                std::fs::create_dir_all(&d).unwrap();
4574                d
4575            })
4576            .collect();
4577        write_spec(&dirs[0], "node", "Node A", "");
4578        write_spec(&dirs[1], "node", "Node B", "");
4579        write_spec(&dirs[2], "node", "Node C", "");
4580
4581        let mounts = |lazy_mid: bool| -> Vec<(Mount, Box<dyn MemBackend>)> {
4582            ["ma", "mb", "mc"]
4583                .iter()
4584                .zip(dirs.iter())
4585                .map(|(m, d)| {
4586                    let mut mount = folder_mount(m, d.clone());
4587                    if lazy_mid && *m == "ma" {
4588                        mount.lifecycle = MountLifecycle::Lazy;
4589                    }
4590                    (
4591                        mount,
4592                        Box::new(FilesystemMemWriter::new(d.clone())) as Box<dyn MemBackend>,
4593                    )
4594                })
4595                .collect()
4596        };
4597        let grants = || {
4598            let mut settings = crate::workspace::WorkspaceSettings::default();
4599            for (from, to) in [("mb", "ma"), ("ma", "mc"), ("mc", "mb")] {
4600                settings
4601                    .cross_mem_links
4602                    .insert(from.to_string(), CrossLinkValue::List(vec![to.to_string()]));
4603            }
4604            settings
4605        };
4606        let relate = |engine: &mut Engine, from: &str, to: &str| {
4607            let (actor, client) = cli_actor();
4608            engine.relate_entity(
4609                RelateEntityArgs {
4610                    source: crate::EntityId::new(from, "node"),
4611                    expected_hash: None,
4612                    rel_type: "DEPENDS_ON".to_string(),
4613                    target: crate::EntityId::new(to, "node"),
4614                    remove: false,
4615                    description: None,
4616                    dry_run: false,
4617                },
4618                actor,
4619                Some(&client),
4620                None,
4621            )
4622        };
4623
4624        // Author the chain mb→ma→mc while everything is eager.
4625        {
4626            let mut authoring = Engine::from_mounts(mounts(false)).unwrap();
4627            authoring.set_settings(grants());
4628            relate(&mut authoring, "mb", "ma").expect("mb→ma lands");
4629            relate(&mut authoring, "ma", "mc").expect("ma→mc lands");
4630        }
4631
4632        // Fresh boot with the MID-PATH mem lazy: closing mc→mb would
4633        // complete the cycle mb→ma→mc→mb through the unloaded mem.
4634        let mut engine = Engine::from_mounts(mounts(true)).unwrap();
4635        engine.set_settings(grants());
4636        assert!(engine.mem_is_deferred("ma"), "the mid-path mem is deferred");
4637        let err = relate(&mut engine, "mc", "mb")
4638            .expect_err("a cycle through a deferred mem must refuse, as eager refuses");
4639        assert!(
4640            matches!(err, EngineError::RelationshipCycle { .. }),
4641            "expected RELATIONSHIP_CYCLE, got {err:?}"
4642        );
4643    }
4644
4645    /// The BATCH relate path runs the same acyclicity guard over the
4646    /// same full store: a two-entry batch (the shape MCP routes to
4647    /// `batch_relate`) whose first entry closes a cycle through a
4648    /// deferred mid-path mem is refused whole, exactly as an eager
4649    /// boot refuses it. The fifth lazy-mount grade demonstrated the
4650    /// complement live: without the batch-path full load the cycle
4651    /// committed silently.
4652    #[test]
4653    fn batch_acyclicity_guard_sees_edges_in_deferred_mems() {
4654        use crate::engine::RelateEntityArgs;
4655        use memstead_schema::workspace_config::CrossLinkValue;
4656
4657        let tmp = TempDir::new().unwrap();
4658        let dirs: Vec<std::path::PathBuf> = ["ma", "mb", "mc"]
4659            .iter()
4660            .map(|m| {
4661                let d = tmp.path().join(m);
4662                std::fs::create_dir_all(&d).unwrap();
4663                d
4664            })
4665            .collect();
4666        write_spec(&dirs[0], "node", "Node A", "");
4667        write_spec(&dirs[1], "node", "Node B", "");
4668        write_spec(&dirs[2], "node", "Node C", "");
4669        // A second entity in mc so the batch's second entry can be an
4670        // intra-mem edge that touches ONLY mc — a target in any other
4671        // mem would put that mem on the batch's touched-mems reload
4672        // list and load it by that route, masking the guard under test.
4673        write_spec(&dirs[2], "node2", "Node C2", "");
4674
4675        let mounts = |lazy_mid: bool| -> Vec<(Mount, Box<dyn MemBackend>)> {
4676            ["ma", "mb", "mc"]
4677                .iter()
4678                .zip(dirs.iter())
4679                .map(|(m, d)| {
4680                    let mut mount = folder_mount(m, d.clone());
4681                    if lazy_mid && *m == "ma" {
4682                        mount.lifecycle = MountLifecycle::Lazy;
4683                    }
4684                    (
4685                        mount,
4686                        Box::new(FilesystemMemWriter::new(d.clone())) as Box<dyn MemBackend>,
4687                    )
4688                })
4689                .collect()
4690        };
4691        let grants = || {
4692            let mut settings = crate::workspace::WorkspaceSettings::default();
4693            for (from, to) in [("mb", "ma"), ("ma", "mc"), ("mc", "mb")] {
4694                settings
4695                    .cross_mem_links
4696                    .insert(from.to_string(), CrossLinkValue::List(vec![to.to_string()]));
4697            }
4698            settings
4699        };
4700        let relate_args = |from: &str, to: &str| RelateEntityArgs {
4701            source: crate::EntityId::new(from, "node"),
4702            expected_hash: None,
4703            rel_type: "DEPENDS_ON".to_string(),
4704            target: crate::EntityId::new(to, "node"),
4705            remove: false,
4706            description: None,
4707            dry_run: false,
4708        };
4709
4710        // Author the chain mb→ma→mc while everything is eager.
4711        {
4712            let (actor, client) = cli_actor();
4713            let mut authoring = Engine::from_mounts(mounts(false)).unwrap();
4714            authoring.set_settings(grants());
4715            authoring
4716                .relate_entity(relate_args("mb", "ma"), actor, Some(&client), None)
4717                .expect("mb→ma lands");
4718            let (actor2, client2) = cli_actor();
4719            authoring
4720                .relate_entity(relate_args("ma", "mc"), actor2, Some(&client2), None)
4721                .expect("ma→mc lands");
4722        }
4723
4724        // Fresh boot with the MID-PATH mem lazy; a two-entry batch
4725        // whose first edge mc→mb completes the cycle mb→ma→mc→mb
4726        // through the unloaded mem must refuse whole.
4727        let mut engine = Engine::from_mounts(mounts(true)).unwrap();
4728        engine.set_settings(grants());
4729        assert!(engine.mem_is_deferred("ma"), "the mid-path mem is deferred");
4730        let (actor, client) = cli_actor();
4731        let result = engine
4732            .batch_relate(
4733                vec![
4734                    (relate_args("mc", "mb"), None),
4735                    // The second entry makes the batch two entries —
4736                    // the shape MCP routes to `batch_relate` — and is
4737                    // an intra-mem edge inside mc: it touches no other
4738                    // mem (so it cannot load ma via the touched-mems
4739                    // reload) and closes no cycle of its own.
4740                    (
4741                        RelateEntityArgs {
4742                            source: crate::EntityId::new("mc", "node2"),
4743                            expected_hash: None,
4744                            rel_type: "DEPENDS_ON".to_string(),
4745                            target: crate::EntityId::new("mc", "node"),
4746                            remove: false,
4747                            description: None,
4748                            dry_run: false,
4749                        },
4750                        None,
4751                    ),
4752                ],
4753                actor,
4754                Some(&client),
4755                false,
4756            )
4757            .expect("the batch call itself returns a report-all envelope");
4758        assert!(
4759            !result.applied,
4760            "a batch closing a cycle through a deferred mem must refuse, as eager refuses; got applied with {} succeeded",
4761            result.succeeded
4762        );
4763    }
4764
4765    /// Write-time cross-mem target verification (flywheel W7/02): a
4766    /// relate into a DEFERRED Write mem verifies the target against
4767    /// storage without loading the mem. A storage-verified target is
4768    /// admitted with a LoadTime stub and NO auto-stub warning (the
4769    /// entity exists — it resolves when the mem loads); a genuinely
4770    /// absent target keeps today's forward-reference mechanic, warning
4771    /// included. Either way the target mem stays deferred.
4772    #[test]
4773    fn relate_into_deferred_mem_verifies_against_storage_without_load() {
4774        use crate::engine::RelateEntityArgs;
4775        use memstead_schema::workspace_config::CrossLinkValue;
4776
4777        let tmp = TempDir::new().unwrap();
4778        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4779        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4780        let mut settings = crate::workspace::WorkspaceSettings::default();
4781        settings.cross_mem_links.insert(
4782            "eag".to_string(),
4783            CrossLinkValue::List(vec!["laz".to_string()]),
4784        );
4785        engine.set_settings(settings);
4786
4787        let relate = |engine: &mut Engine, to: &str| {
4788            let (actor, client) = cli_actor();
4789            engine.relate_entity(
4790                RelateEntityArgs {
4791                    source: crate::EntityId::new("eag", "alpha"),
4792                    expected_hash: None,
4793                    rel_type: "SUPPORTS".to_string(),
4794                    target: crate::EntityId::new("laz", to),
4795                    remove: false,
4796                    description: None,
4797                    dry_run: false,
4798                },
4799                actor,
4800                Some(&client),
4801                None,
4802            )
4803        };
4804
4805        // Storage-verified target: laz--omega exists on disk.
4806        let outcome = relate(&mut engine, "omega").expect("verified target admits");
4807        assert!(
4808            engine.mem_is_deferred("laz"),
4809            "verification never loads the mem"
4810        );
4811        assert!(
4812            !outcome
4813                .warnings
4814                .iter()
4815                .any(|w| matches!(w, WarningHint::AutoStubCreated { .. })),
4816            "a storage-verified target is not an auto-stub case: {:?}",
4817            outcome.warnings
4818        );
4819        let stub = engine
4820            .store()
4821            .get(&crate::EntityId::new("laz", "omega"))
4822            .expect("until-load stub present");
4823        assert!(stub.stub);
4824        assert_eq!(
4825            stub.stub_kind,
4826            Some(crate::entity::StubKind::LoadTime),
4827            "verified-in-storage stub carries the load-time kind"
4828        );
4829
4830        // Genuinely absent target: forward-reference mechanic intact.
4831        let outcome = relate(&mut engine, "missing").expect("absent Write-mem target auto-stubs");
4832        assert!(engine.mem_is_deferred("laz"), "still no load");
4833        assert!(
4834            outcome
4835                .warnings
4836                .iter()
4837                .any(|w| matches!(w, WarningHint::AutoStubCreated { .. })),
4838            "absent target keeps the auto-stub warning: {:?}",
4839            outcome.warnings
4840        );
4841        let stub = engine
4842            .store()
4843            .get(&crate::EntityId::new("laz", "missing"))
4844            .expect("forward-reference stub present");
4845        assert_eq!(
4846            stub.stub_kind,
4847            Some(crate::entity::StubKind::ForwardReference)
4848        );
4849    }
4850
4851    /// The read-only contract, now answerable without load (flywheel
4852    /// W7/02): an entity PRESENT in a deferred read-only mem's storage
4853    /// is admitted — the refusal never fires merely because the mem is
4854    /// unloaded — and an ABSENT one refuses with the existing typed
4855    /// error. The mem stays deferred through both.
4856    #[test]
4857    fn readonly_deferred_target_answers_from_storage() {
4858        use crate::engine::RelateEntityArgs;
4859        use memstead_schema::workspace_config::CrossLinkValue;
4860
4861        let tmp = TempDir::new().unwrap();
4862        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4863        let mut ro_mount = lazy_folder_mount("laz", lazy_dir.to_path_buf());
4864        ro_mount.capability = crate::workspace::MountCapability::ReadOnly;
4865        let mut engine = Engine::from_mounts(vec![
4866            (
4867                folder_mount("eag", eager_dir.to_path_buf()),
4868                Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf())) as Box<dyn MemBackend>,
4869            ),
4870            (
4871                ro_mount,
4872                Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf())) as Box<dyn MemBackend>,
4873            ),
4874        ])
4875        .unwrap();
4876        let mut settings = crate::workspace::WorkspaceSettings::default();
4877        settings.cross_mem_links.insert(
4878            "eag".to_string(),
4879            CrossLinkValue::List(vec!["laz".to_string()]),
4880        );
4881        engine.set_settings(settings);
4882
4883        let relate = |engine: &mut Engine, to: &str| {
4884            let (actor, client) = cli_actor();
4885            engine.relate_entity(
4886                RelateEntityArgs {
4887                    source: crate::EntityId::new("eag", "alpha"),
4888                    expected_hash: None,
4889                    rel_type: "SUPPORTS".to_string(),
4890                    target: crate::EntityId::new("laz", to),
4891                    remove: false,
4892                    description: None,
4893                    dry_run: false,
4894                },
4895                actor,
4896                Some(&client),
4897                None,
4898            )
4899        };
4900
4901        relate(&mut engine, "omega").expect("present-in-storage RO target admits");
4902        assert!(
4903            engine.mem_is_deferred("laz"),
4904            "the admit never loads the mem"
4905        );
4906
4907        let err =
4908            relate(&mut engine, "missing").expect_err("absent RO target keeps the typed refusal");
4909        assert!(
4910            matches!(err, EngineError::CrossMemTargetNotFound { .. }),
4911            "expected CROSS_MEM_TARGET_NOT_FOUND, got {err:?}"
4912        );
4913        assert!(
4914            engine.mem_is_deferred("laz"),
4915            "the refusal never loads the mem either"
4916        );
4917    }
4918
4919    /// A cross-mem body link from an eager mem into a lazy one is a
4920    /// stub until the target mem loads, and resolves to the real entity
4921    /// afterwards — never silently dropped, never a spurious permanent
4922    /// warning.
4923    #[test]
4924    fn cross_mem_link_into_lazy_mem_resolves_on_load() {
4925        let tmp = TempDir::new().unwrap();
4926        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4927        write_spec(
4928            &eager_dir,
4929            "linker",
4930            "Linker",
4931            "\nSee [[laz--omega]] for detail.\n",
4932        );
4933
4934        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4935        let target = crate::EntityId::new("laz", "omega");
4936        assert!(
4937            engine.get_entity(&target).is_none_or(|e| e.stub),
4938            "before the lazy load the cross-mem target is at most a stub, never real"
4939        );
4940
4941        engine.reload_if_stale(Some("laz"));
4942        let resolved = engine.get_entity(&target).expect("target loaded");
4943        assert!(!resolved.stub, "after the load the target is real");
4944        assert!(
4945            !engine.load_warnings().iter().any(
4946                |w| matches!(w, WarningHint::SuspiciousNestedPrefix { resolved_id, .. } if resolved_id.as_ref() == target.as_ref())
4947            ),
4948            "no lingering nested-prefix warning for a resolved cross-mem link: {:?}",
4949            engine.load_warnings()
4950        );
4951    }
4952
4953    /// Shared fixture for the roster tests: a workspace with folder mems
4954    /// `alpha` (one entity) and `beta` (one entity linking into alpha), the
4955    /// roster saved through the workspace store, the engine booted.
4956    fn roster_change(warnings: &[WarningHint]) -> Option<(Vec<String>, Vec<String>)> {
4957        warnings.iter().find_map(|w| match w {
4958            WarningHint::MemRosterChanged { added, removed, .. } => {
4959                Some((added.clone(), removed.clone()))
4960            }
4961            _ => None,
4962        })
4963    }
4964
4965    fn search_scope(mem: Option<&str>, term: &str) -> crate::ops::SearchScope {
4966        crate::ops::SearchScope {
4967            query: Some(crate::ops::Query {
4968                any: vec![term.to_string()],
4969                ..Default::default()
4970            }),
4971            mem: mem.map(str::to_string),
4972            ..Default::default()
4973        }
4974    }
4975
4976    fn roster_fixture() -> (TempDir, Engine) {
4977        use crate::workspace_store::WorkspaceStoreAdapter;
4978        let tmp = TempDir::new().unwrap();
4979        let root = tmp.path();
4980        std::fs::create_dir_all(root.join(".memstead")).unwrap();
4981        std::fs::write(
4982            root.join(".memstead").join("workspace.toml"),
4983            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
4984        )
4985        .unwrap();
4986        for mem in ["alpha", "beta"] {
4987            let dir = root.join(mem);
4988            std::fs::create_dir_all(dir.join(".memstead")).unwrap();
4989            std::fs::write(
4990                dir.join(".memstead").join("config.json"),
4991                br#"{"format":1,"schema":"default@1.0.0"}"#,
4992            )
4993            .unwrap();
4994        }
4995        std::fs::write(
4996            root.join("alpha").join("one.md"),
4997            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# One\n\n## Identity\n\nalpha one\n\n## Purpose\n\nseed\n",
4998        )
4999        .unwrap();
5000        std::fs::write(
5001            root.join("beta").join("two.md"),
5002            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Two\n\n## Identity\n\nbeta two\n\n## Purpose\n\nseed\n\n## Relationships\n\n- **DEPENDS_ON**: [[alpha--one]]\n",
5003        )
5004        .unwrap();
5005        let mount = |mem: &str| Mount {
5006            mem: mem.to_string(),
5007            schema: Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
5008            storage: MountStorage::Folder {
5009                path: root.join(mem),
5010            },
5011            capability: MountCapability::Write,
5012            lifecycle: MountLifecycle::Eager,
5013            cross_linkable: true,
5014            migration_target: None,
5015        };
5016        crate::FileWorkspaceStore::new()
5017            .save_state(
5018                root,
5019                &crate::workspace::Workspace {
5020                    mounts: vec![mount("alpha"), mount("beta")],
5021                    settings: crate::workspace::WorkspaceSettings::default(),
5022                },
5023            )
5024            .unwrap();
5025        let engine = Engine::from_workspace_root(root).expect("workspace boots");
5026        (tmp, engine)
5027    }
5028
5029    fn save_roster(root: &Path, mems: &[(&str, &Path)]) {
5030        let with_schema: Vec<(&str, &Path, &str)> =
5031            mems.iter().map(|(m, d)| (*m, *d, "default")).collect();
5032        save_roster_pinned(root, &with_schema);
5033    }
5034
5035    fn save_roster_pinned(root: &Path, mems: &[(&str, &Path, &str)]) {
5036        use crate::workspace_store::WorkspaceStoreAdapter;
5037        let mounts = mems
5038            .iter()
5039            .map(|(mem, dir, schema)| Mount {
5040                mem: mem.to_string(),
5041                schema: Some(SchemaRef::new(*schema, semver::Version::new(1, 0, 0))),
5042                storage: MountStorage::Folder {
5043                    path: dir.to_path_buf(),
5044                },
5045                capability: MountCapability::Write,
5046                lifecycle: MountLifecycle::Eager,
5047                cross_linkable: true,
5048                migration_target: None,
5049            })
5050            .collect();
5051        // A roster write inside the same mtime tick as the previous one is
5052        // told apart by its hash, so no sleep is needed here.
5053        crate::FileWorkspaceStore::new()
5054            .save_state(
5055                root,
5056                &crate::workspace::Workspace {
5057                    mounts,
5058                    settings: crate::workspace::WorkspaceSettings::default(),
5059                },
5060            )
5061            .unwrap();
5062    }
5063
5064    /// A workspace whose roster file does not exist at boot (the first mem
5065    /// is created by another process after this engine started) mounts
5066    /// that mem on the next operation, with `MEM_ROSTER_CHANGED` naming it,
5067    /// and never needs a restart; the same file unchanged afterwards is
5068    /// quiet.
5069    #[test]
5070    fn roster_file_that_appears_after_boot_mounts_its_mems() {
5071        let tmp = TempDir::new().unwrap();
5072        let root = tmp.path();
5073        std::fs::create_dir_all(root.join(".memstead")).unwrap();
5074        std::fs::write(
5075            root.join(".memstead").join("workspace.toml"),
5076            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
5077        )
5078        .unwrap();
5079        let mut engine = Engine::from_workspace_root(root).expect("an empty workspace boots");
5080        assert!(engine.mem_names().is_empty(), "nothing is mounted at boot");
5081        assert!(
5082            !root
5083                .join(".memstead")
5084                .join("state")
5085                .join("mounts.json")
5086                .exists(),
5087            "the fixture has no roster file yet"
5088        );
5089        assert!(
5090            engine.reload_if_stale(None).is_empty(),
5091            "no roster, no warning"
5092        );
5093
5094        // Another process creates the first mem: folder plus roster entry.
5095        let dir = root.join("alpha");
5096        std::fs::create_dir_all(dir.join(".memstead")).unwrap();
5097        std::fs::write(
5098            dir.join(".memstead").join("config.json"),
5099            br#"{"format":1,"schema":"default@1.0.0"}"#,
5100        )
5101        .unwrap();
5102        std::fs::write(
5103            dir.join("one.md"),
5104            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# One\n\n## Identity\n\nalpha one\n\n## Purpose\n\nseed\n",
5105        )
5106        .unwrap();
5107        save_roster(root, &[("alpha", &dir)]);
5108
5109        let warnings = engine.reload_if_stale(None);
5110        let (added, removed) = roster_change(&warnings).expect("the first roster is a change");
5111        assert_eq!(added, vec!["alpha".to_string()]);
5112        assert!(removed.is_empty());
5113        assert_eq!(engine.mem_names(), vec!["alpha"]);
5114        assert!(
5115            engine
5116                .get_entity(&crate::EntityId("alpha--one".into()))
5117                .is_some(),
5118            "the mem's entity is served without a restart"
5119        );
5120        assert!(
5121            engine.reload_if_stale(None).is_empty(),
5122            "the unchanged roster is quiet"
5123        );
5124    }
5125
5126    /// A4 AC1 (engine half): a mem that leaves the roster is gone on the
5127    /// next operation with `MEM_ROSTER_CHANGED` naming it, its entities are
5128    /// not searchable, an operation naming it refuses `MEM_UNMOUNTED`; a mem
5129    /// that returns is served again with its entities.
5130    #[test]
5131    fn roster_membership_follows_reload_before_operation() {
5132        let (tmp, mut engine) = roster_fixture();
5133        let root = tmp.path();
5134        assert_eq!(engine.mem_names(), vec!["alpha", "beta"]);
5135        assert!(
5136            engine.reload_if_stale(None).is_empty(),
5137            "no change, no warning"
5138        );
5139
5140        // beta leaves the roster.
5141        save_roster(root, &[("alpha", &root.join("alpha"))]);
5142        let warnings = engine.reload_if_stale(None);
5143        let (added, removed) = roster_change(&warnings).expect("the roster change is reported");
5144        assert_eq!(removed, vec!["beta".to_string()]);
5145        assert!(added.is_empty());
5146        assert_eq!(engine.mem_names(), vec!["alpha"]);
5147        assert!(
5148            engine
5149                .get_entity(&crate::EntityId("beta--two".into()))
5150                .is_none()
5151        );
5152        let unscoped = engine.search(&search_scope(None, "beta two")).unwrap();
5153        assert_eq!(
5154            unscoped.total, 0,
5155            "no hit from the removed mem: {unscoped:?}"
5156        );
5157        let scoped = engine
5158            .search(&search_scope(Some("beta"), "beta two"))
5159            .expect_err("a search scoped to the removed mem refuses");
5160        assert_eq!(scoped.code(), "MEM_UNMOUNTED", "{scoped}");
5161        let err = engine.unknown_mem_error("beta");
5162        assert_eq!(err.code(), "MEM_UNMOUNTED", "{err}");
5163        assert!(
5164            engine.reload_if_stale(None).is_empty(),
5165            "reconciled once, quiet after"
5166        );
5167
5168        // beta returns: mounted cold with its entity.
5169        save_roster(
5170            root,
5171            &[("alpha", &root.join("alpha")), ("beta", &root.join("beta"))],
5172        );
5173        let warnings = engine.reload_if_stale(None);
5174        let (added, _) = roster_change(&warnings).expect("the return is reported");
5175        assert_eq!(added, vec!["beta".to_string()]);
5176        assert_eq!(engine.mem_names(), vec!["alpha", "beta"]);
5177        assert!(
5178            engine
5179                .get_entity(&crate::EntityId("beta--two".into()))
5180                .is_some()
5181        );
5182        assert_eq!(
5183            engine.unknown_mem_error("beta").code(),
5184            "UNKNOWN_MEM",
5185            "the memory clears"
5186        );
5187    }
5188
5189    /// A4 AC1, refusal complement: a roster entry whose storage does not
5190    /// exist quarantines on reconciliation exactly as boot would, with the
5191    /// boot's reason code, and the other mems keep serving.
5192    #[test]
5193    fn roster_entry_with_missing_storage_quarantines_like_boot() {
5194        let (tmp, mut engine) = roster_fixture();
5195        let root = tmp.path();
5196        // `ghost` pins a schema no source holds (boot's SCHEMA_NOT_FOUND
5197        // quarantine); `hollow` names a folder that does not exist (boot's
5198        // MOUNT_UNBACKED quarantine). The reconcile must do exactly the same
5199        // for both, and the other mems keep serving.
5200        std::fs::create_dir_all(root.join("ghost").join(".memstead")).unwrap();
5201        std::fs::write(
5202            root.join("ghost").join(".memstead").join("config.json"),
5203            br#"{"format":1,"schema":"nope@1.0.0"}"#,
5204        )
5205        .unwrap();
5206        save_roster_pinned(
5207            root,
5208            &[
5209                ("alpha", &root.join("alpha"), "default"),
5210                ("beta", &root.join("beta"), "default"),
5211                ("ghost", &root.join("ghost"), "nope"),
5212                ("hollow", &root.join("does-not-exist"), "default"),
5213            ],
5214        );
5215        let warnings = engine.reload_if_stale(None);
5216        let quarantined = warnings
5217            .iter()
5218            .find_map(|w| match w {
5219                WarningHint::MemRosterChanged { quarantined, .. } => Some(quarantined.clone()),
5220                _ => None,
5221            })
5222            .expect("reported");
5223        assert_eq!(quarantined, vec!["ghost".to_string(), "hollow".to_string()]);
5224        let q = engine
5225            .quarantine_reason("ghost")
5226            .expect("on the quarantine roster");
5227        // Boot quarantines the same entry under the same code.
5228        let booted = Engine::from_workspace_root(root).unwrap();
5229        let at_boot = booted
5230            .quarantine_reason("ghost")
5231            .expect("boot quarantines it too");
5232        assert_eq!(q.reason_code, at_boot.reason_code);
5233        assert_eq!(q.reason_code, "SCHEMA_NOT_FOUND");
5234        // The hollow mount: whatever boot does with it (quarantine or an
5235        // empty mount), the reconcile does the same.
5236        for name in ["ghost", "hollow"] {
5237            assert_eq!(
5238                engine
5239                    .quarantine_reason(name)
5240                    .map(|q| q.reason_code.clone()),
5241                booted
5242                    .quarantine_reason(name)
5243                    .map(|q| q.reason_code.clone()),
5244                "{name}: quarantine parity with boot"
5245            );
5246            assert_eq!(
5247                engine.mem_names().contains(&name),
5248                booted.mem_names().contains(&name),
5249                "{name}: membership parity with boot (reconciled {:?}, boot {:?})",
5250                engine.mem_names(),
5251                booted.mem_names()
5252            );
5253        }
5254        assert!(engine.mem_names().contains(&"alpha") && engine.mem_names().contains(&"beta"));
5255        assert!(
5256            engine
5257                .get_entity(&crate::EntityId("alpha--one".into()))
5258                .is_some()
5259        );
5260        assert_eq!(engine.unknown_mem_error("ghost").code(), "MEM_QUARANTINED");
5261    }
5262
5263    /// A4 AC2: after the unmount, the cross-mem edge from beta into alpha
5264    /// reads dangling on the integrity axis, search has no hit from the
5265    /// removed mem, and the community partition and search indexes carry no
5266    /// reference to it; the probe cost over one hundred operations stays in
5267    /// the branch-tip probe's band (printed as a benchmark line).
5268    #[test]
5269    fn unmount_is_atomic_and_cross_mem_edges_go_dangling() {
5270        let (tmp, mut engine) = roster_fixture();
5271        let root = tmp.path();
5272        // beta depends on alpha; alpha leaves.
5273        save_roster(root, &[("beta", &root.join("beta"))]);
5274        let _ = engine.reload_if_stale(None);
5275        assert_eq!(engine.mem_names(), vec!["beta"]);
5276        let findings = engine.consistency_findings("beta").unwrap();
5277        assert!(
5278            findings
5279                .iter()
5280                .any(|f| f.code == "DANGLING_RELATION_TARGET_MISSING" && f.id == "beta--two"),
5281            "the edge into the unmounted mem is dangling: {findings:?}"
5282        );
5283        let hits = engine.search(&search_scope(None, "alpha one")).unwrap();
5284        assert_eq!(hits.total, 0, "{hits:?}");
5285        // Derived structures: no community member and no index for alpha.
5286        let communities = engine.communities();
5287        assert!(
5288            communities
5289                .entity_cluster_map
5290                .keys()
5291                .all(|id| !id.starts_with("alpha--")),
5292            "the community partition carries no entity of the removed mem"
5293        );
5294        assert!(
5295            communities
5296                .clusters
5297                .values()
5298                .all(|c| c.entities.iter().all(|e| !e.starts_with("alpha--")))
5299        );
5300        assert!(engine.store().all_entities().all(|e| e.mem != "alpha"));
5301
5302        // Benchmark: one hundred reload probes with no change, roster
5303        // probe included, against one hundred branch-tip-only probes.
5304        let start = std::time::Instant::now();
5305        for _ in 0..100 {
5306            let _ = engine.reload_if_stale(None);
5307        }
5308        let with_roster = start.elapsed();
5309        let start = std::time::Instant::now();
5310        for _ in 0..100 {
5311            let _ = engine.reload_if_stale_content_only(None);
5312        }
5313        let content_only = start.elapsed();
5314        eprintln!(
5315            "BENCH roster probe: 100 ops with roster {with_roster:?}, content-only {content_only:?}"
5316        );
5317        assert!(
5318            with_roster < content_only * 4 + std::time::Duration::from_millis(50),
5319            "roster probe left the branch-tip band: {with_roster:?} vs {content_only:?}"
5320        );
5321    }
5322
5323    /// A4 AC2, refusal complement: an unmount that fails mid-way leaves the
5324    /// roster unapplied and the mem fully served, and the response names
5325    /// the failure.
5326    #[test]
5327    fn failed_unmount_leaves_the_roster_unapplied_and_the_mem_served() {
5328        let (tmp, mut engine) = roster_fixture();
5329        let root = tmp.path();
5330        engine.inject_unmount_failure = Some("beta".to_string());
5331        save_roster(root, &[("alpha", &root.join("alpha"))]);
5332        let warnings = engine.reload_if_stale(None);
5333        let (removed, failures) = warnings
5334            .iter()
5335            .find_map(|w| match w {
5336                WarningHint::MemRosterChanged {
5337                    removed, failures, ..
5338                } => Some((removed.clone(), failures.clone())),
5339                _ => None,
5340            })
5341            .expect("reported");
5342        assert!(removed.is_empty());
5343        assert!(
5344            failures
5345                .iter()
5346                .any(|f| f.contains("unmount:beta") && f.contains("injected")),
5347            "{failures:?}"
5348        );
5349        assert_eq!(
5350            engine.mem_names(),
5351            vec!["alpha", "beta"],
5352            "beta still served"
5353        );
5354        assert!(
5355            engine
5356                .get_entity(&crate::EntityId("beta--two".into()))
5357                .is_some()
5358        );
5359        assert_eq!(
5360            engine.unknown_mem_error("beta").code(),
5361            "UNKNOWN_MEM",
5362            "not remembered as unmounted"
5363        );
5364        // The baseline was kept: lifting the injection, the next operation
5365        // applies the pending change.
5366        engine.inject_unmount_failure = None;
5367        let warnings = engine.reload_if_stale(None);
5368        let (_, removed) = roster_change(&warnings).expect("retried");
5369        assert_eq!(removed, vec!["beta".to_string()]);
5370        assert_eq!(engine.mem_names(), vec!["alpha"]);
5371    }
5372}