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    let paths = backend.list_entities()?;
1009    let mut entries: Vec<SourceEntry> = Vec::with_capacity(paths.len());
1010    let mut errors: Vec<SourceReadError> = Vec::new();
1011    for path in paths {
1012        match backend.read_entity(&path) {
1013            Ok(Some(bytes)) => match String::from_utf8(bytes) {
1014                Ok(content) => entries.push(SourceEntry {
1015                    relative_path: path.to_string_lossy().into_owned(),
1016                    source_path: path.clone(),
1017                    content,
1018                }),
1019                Err(e) => errors.push(SourceReadError {
1020                    source_path: path,
1021                    error: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
1022                }),
1023            },
1024            Ok(None) => {
1025                // Listed-but-absent: list/read race. Skip silently.
1026            }
1027            Err(e) => errors.push(SourceReadError {
1028                source_path: path,
1029                error: std::io::Error::other(e.to_string()),
1030            }),
1031        }
1032    }
1033    Ok((entries, errors))
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038
1039    use std::path::Path;
1040
1041    use memstead_schema::SchemaRef;
1042    use tempfile::TempDir;
1043
1044    use crate::backend::MemBackend;
1045    use crate::engine::test_helpers::*;
1046    use crate::engine::{Engine, EngineError};
1047    use crate::ops::WarningHint;
1048    use crate::storage::{ArchiveBackend, FilesystemMemWriter, MemWriter};
1049    use crate::vcs::CommitContext;
1050    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
1051
1052    /// The unbacked-mount probe on the folder backend: a path that does
1053    /// not exist is `missing_path`, an existing directory with no
1054    /// entity is `empty`, a directory holding one entity is silent, and
1055    /// a lazy mount (count unknown) is judged on storage presence only.
1056    #[test]
1057    fn unbacked_mount_probe_classes_missing_path_empty_and_present() {
1058        use crate::engine::boot::unbacked_mount_warning;
1059        use crate::ops::MountUnbackedReason;
1060        let tmp = TempDir::new().unwrap();
1061        let mount = |path: std::path::PathBuf| Mount {
1062            mem: "probe".into(),
1063            schema: None,
1064            storage: MountStorage::Folder { path },
1065            capability: MountCapability::Write,
1066            lifecycle: MountLifecycle::Eager,
1067            cross_linkable: true,
1068            migration_target: None,
1069        };
1070
1071        let gone = tmp.path().join("gone");
1072        let backend = FilesystemMemWriter::new(gone.clone());
1073        let w = unbacked_mount_warning(&mount(gone.clone()), &backend, Some(0))
1074            .expect("a missing folder is unbacked");
1075        match &w {
1076            WarningHint::MountUnbacked {
1077                mem,
1078                reason,
1079                location,
1080            } => {
1081                assert_eq!(mem, "probe");
1082                assert_eq!(*reason, MountUnbackedReason::MissingPath);
1083                assert_eq!(location, &gone.display().to_string());
1084            }
1085            other => panic!("unexpected variant: {other:?}"),
1086        }
1087        assert_eq!(w.code(), "MOUNT_UNBACKED");
1088        let json = serde_json::to_value(&w).unwrap();
1089        assert_eq!(json["details"]["reason"], "missing_path");
1090        // Lazy: storage presence alone decides, and the folder is gone.
1091        assert!(unbacked_mount_warning(&mount(gone), &backend, None).is_some());
1092
1093        let hollow = tmp.path().join("hollow");
1094        std::fs::create_dir_all(&hollow).unwrap();
1095        let backend = FilesystemMemWriter::new(hollow.clone());
1096        let w = unbacked_mount_warning(&mount(hollow.clone()), &backend, Some(0))
1097            .expect("an entity-less folder is unbacked");
1098        assert_eq!(
1099            serde_json::to_value(&w).unwrap()["details"]["reason"],
1100            "empty"
1101        );
1102        // Lazy with the folder present: nothing to say at boot.
1103        assert!(unbacked_mount_warning(&mount(hollow.clone()), &backend, None).is_none());
1104        // One entity: silent.
1105        assert!(unbacked_mount_warning(&mount(hollow), &backend, Some(1)).is_none());
1106    }
1107
1108    /// The `SchemaResolver` resolves a pin against the catalogue and, on
1109    /// a miss, yields the fixed-order (`local_storage` → `builtin` →
1110    /// `remote`) source diagnostics the `SCHEMA_NOT_FOUND` envelope carries.
1111    #[test]
1112    fn schema_resolver_resolves_builtin_and_yields_ordered_diagnostics_on_miss() {
1113        let catalogue = memstead_schema::builtins::load_builtin_schemas().unwrap();
1114        let resolver = super::SchemaResolver::new(&catalogue);
1115
1116        let ok: SchemaRef = "default@1.0.0".parse().unwrap();
1117        assert!(resolver.resolve(&ok).is_ok(), "shipped built-in resolves");
1118
1119        let miss: SchemaRef = "nope@9.9.9".parse().unwrap();
1120        let sources = resolver.resolve(&miss).unwrap_err();
1121        let labels: Vec<&str> = sources.iter().map(|s| s.source).collect();
1122        assert_eq!(labels, ["local_storage", "builtin", "remote"]);
1123        assert!(sources.iter().all(|s| !s.pinned_version_match));
1124    }
1125
1126    #[test]
1127    fn empty_mount_list_constructs_and_errors_unknown_mem_on_read() {
1128        let engine = Engine::from_mounts(Vec::new()).unwrap();
1129        assert!(engine.mem_names().is_empty());
1130        match engine.list_entities("missing") {
1131            Err(EngineError::UnknownMem(v)) => assert_eq!(v, "missing"),
1132            other => panic!("expected UnknownMem, got {other:?}"),
1133        }
1134    }
1135
1136    #[test]
1137    fn duplicate_mem_names_rejected_at_construction() {
1138        let tmp = TempDir::new().unwrap();
1139        let writer1: Box<dyn MemBackend> =
1140            Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf()));
1141        let writer2: Box<dyn MemBackend> =
1142            Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf()));
1143        let err = Engine::from_mounts(vec![
1144            (folder_mount("specs", tmp.path().to_path_buf()), writer1),
1145            (folder_mount("specs", tmp.path().to_path_buf()), writer2),
1146        ])
1147        .unwrap_err();
1148        assert!(matches!(err, EngineError::DuplicateMem(v) if v == "specs"));
1149    }
1150
1151    #[test]
1152    fn from_mounts_populates_load_warnings_from_duplicate_section_heading() {
1153        // A markdown file with the same `## Identity` heading twice
1154        // should cause the parser to emit a typed
1155        // `DuplicateSectionHeading` warning. With the
1156        // LoadCollector wiring, that warning lands on
1157        // `engine.load_warnings()`.
1158        let tmp = TempDir::new().unwrap();
1159        let mem_dir = tmp.path().to_path_buf();
1160        let body =
1161            "---\ntype: spec\n---\n# Dup\n\n## Identity\n\nfirst.\n\n## Identity\n\nsecond.\n";
1162        std::fs::write(mem_dir.join("dup.md"), body).unwrap();
1163
1164        let writer = FilesystemMemWriter::new(mem_dir.clone());
1165        let engine = Engine::from_mounts(vec![(
1166            folder_mount("specs", mem_dir),
1167            Box::new(writer) as Box<dyn MemBackend>,
1168        )])
1169        .unwrap();
1170
1171        let warnings = engine.load_warnings();
1172        assert!(
1173            warnings
1174                .iter()
1175                .any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
1176            "load_warnings must surface DuplicateSectionHeading: {warnings:?}",
1177        );
1178    }
1179
1180    /// Generation-behind hint: a mem pinning an OLD built-in
1181    /// generation (`default@1.0.0`; the catalogue retains up to
1182    /// 1.2.0) boots with the warn-tier `SCHEMA_GENERATIONS_BEHIND`
1183    /// naming the pinned ref and the newest version — and the hint
1184    /// never blocks: the boot serves and mutations succeed. A mem
1185    /// pinning the NEWEST generation stays silent, so its health
1186    /// output is unchanged.
1187    #[test]
1188    fn generation_behind_hint_fires_for_old_builtin_pin_only() {
1189        // Old pin → hint, non-blocking.
1190        let tmp = TempDir::new().unwrap();
1191        let mem_dir = tmp.path().to_path_buf();
1192        let writer = FilesystemMemWriter::new(mem_dir.clone());
1193        let mut engine = Engine::from_mounts(vec![(
1194            folder_mount("specs", mem_dir),
1195            Box::new(writer) as Box<dyn MemBackend>,
1196        )])
1197        .unwrap();
1198        let behind: Vec<_> = engine
1199            .load_warnings()
1200            .iter()
1201            .filter_map(|w| match w {
1202                WarningHint::SchemaGenerationsBehind {
1203                    mem,
1204                    pinned,
1205                    newest,
1206                } => Some((mem.clone(), pinned.clone(), newest.clone())),
1207                _ => None,
1208            })
1209            .collect();
1210        assert_eq!(
1211            behind,
1212            vec![(
1213                "specs".to_string(),
1214                "default@1.0.0".to_string(),
1215                "1.3.0".to_string()
1216            )],
1217            "old built-in pin must surface the generation-behind hint"
1218        );
1219        assert!(
1220            engine
1221                .health()
1222                .warnings
1223                .iter()
1224                .any(|w| w.code() == "SCHEMA_GENERATIONS_BEHIND"),
1225            "the hint rides health without an include gate"
1226        );
1227        // Never blocking: the warned mem still mutates.
1228        engine
1229            .create_entity_with_ctx(
1230                crate::engine::CreateEntityArgs {
1231                    anchors: Vec::new(),
1232                    mem: "specs".to_string(),
1233                    title: "Still writable".to_string(),
1234                    entity_type: "spec".to_string(),
1235                    sections: indexmap::IndexMap::from_iter([
1236                        ("identity".to_string(), "i".to_string()),
1237                        ("purpose".to_string(), "p".to_string()),
1238                    ]),
1239                    metadata: indexmap::IndexMap::new(),
1240                    relations: Vec::new(),
1241                    dry_run: false,
1242                },
1243                &crate::vcs::CommitContext::internal(),
1244            )
1245            .expect("generation-behind hint must never block mutations");
1246
1247        // Newest pin → silent (health output unchanged).
1248        let tmp = TempDir::new().unwrap();
1249        let mem_dir = tmp.path().to_path_buf();
1250        let writer = FilesystemMemWriter::new(mem_dir.clone());
1251        let mut mount = folder_mount("specs", mem_dir);
1252        mount.schema = Some("default@1.3.0".parse().unwrap());
1253        let engine =
1254            Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
1255        assert!(
1256            !engine
1257                .load_warnings()
1258                .iter()
1259                .any(|w| w.code() == "SCHEMA_GENERATIONS_BEHIND"),
1260            "newest built-in pin must stay silent: {:?}",
1261            engine.load_warnings()
1262        );
1263        let health_json = serde_json::to_string(&engine.health().warnings).unwrap();
1264        assert!(
1265            !health_json.contains("SCHEMA_GENERATIONS_BEHIND"),
1266            "newest pin: health output carries no generation hint"
1267        );
1268    }
1269
1270    /// The newest-generation lookup uses real semver ordering — a
1271    /// two-digit minor beats a one-digit one (string ordering would
1272    /// invert them).
1273    #[test]
1274    fn newest_builtin_version_orders_by_semver_not_string() {
1275        let manifest = |version: &str| {
1276            format!(
1277                r#"name: gen-test
1278version: {version}
1279description: test
1280when_to_use: test
1281types:
1282  - note
1283relationships:
1284  mode: strict
1285  definitions:
1286    - name: _default
1287      description: default
1288      default_weight: 1.0
1289    - name: PART_OF
1290      description: hier
1291      default_weight: 3.0
1292community:
1293  resolution: 1.0
1294  seed: 42
1295"#
1296            )
1297        };
1298        let type_yaml = r#"name: note
1299description: test
1300when_to_use: test
1301sections:
1302  - key: body
1303    heading: Body
1304    required: true
1305    search_weight: 10.0
1306    catch_all: true
1307metadata_fields: []
1308title_weight: 1.0
1309text_fields: [body]
1310hierarchy_relationship: PART_OF
1311no_self_loop_relationships: []
1312updatable_fields: [title, body]
1313health_required_fields: [body]
1314staleness_threshold_days: 30
1315write_rules: []
1316"#;
1317        let types = vec![("note".to_string(), type_yaml.to_string())];
1318        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = ["0.9.0", "0.10.0", "0.2.0"]
1319            .iter()
1320            .map(|v| {
1321                std::sync::Arc::new(
1322                    memstead_schema::load_schema_from_memory(&manifest(v), &types)
1323                        .expect("fixture schema loads"),
1324                )
1325            })
1326            .collect();
1327        let newest = super::newest_builtin_version("gen-test", &catalogue)
1328            .expect("name present in catalogue");
1329        assert_eq!(newest.to_string(), "0.10.0", "semver, not string, ordering");
1330        assert!(super::newest_builtin_version("absent", &catalogue).is_none());
1331    }
1332
1333    /// Parse-time relation validation drops relations whose `rel_type`
1334    /// is not declared in the source mem's strict-mode schema and
1335    /// emits `PARSED_RELATION_INVALID { reason: "unknown_rel_type" }`.
1336    /// The entity itself loads normally; only the bad relation goes
1337    /// missing from the in-memory store.
1338    #[test]
1339    fn from_mounts_drops_unknown_rel_type_from_hand_edit_with_warning() {
1340        let tmp = TempDir::new().unwrap();
1341        let mem_dir = tmp.path().to_path_buf();
1342        // Hand-authored markdown with a `## Relationships` entry whose
1343        // type isn't declared in the default schema (strict mode).
1344        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nThe target.\n";
1345        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
1346        std::fs::write(mem_dir.join("target.md"), target).unwrap();
1347        std::fs::write(mem_dir.join("source.md"), source).unwrap();
1348
1349        let writer = FilesystemMemWriter::new(mem_dir.clone());
1350        let engine = Engine::from_mounts(vec![(
1351            folder_mount("specs", mem_dir),
1352            Box::new(writer) as Box<dyn MemBackend>,
1353        )])
1354        .unwrap();
1355
1356        let source_id = crate::entity::EntityId::new("specs", "source");
1357        let target_id = crate::entity::EntityId::new("specs", "target");
1358        let source_entity = engine.get_entity(&source_id).expect("source loaded");
1359        // The offending relation does not survive into the entity's
1360        // in-memory relationships list.
1361        assert!(
1362            source_entity.relationships.is_empty(),
1363            "MADE_UP_TYPE relation must be dropped from entity.relationships, got: {:?}",
1364            source_entity.relationships,
1365        );
1366        // Nor into the store's edge index.
1367        let outgoing: Vec<_> = engine
1368            .store()
1369            .outgoing(&source_id)
1370            .iter()
1371            .filter(|e| e.rel_type == "MADE_UP_TYPE")
1372            .collect();
1373        assert!(
1374            outgoing.is_empty(),
1375            "MADE_UP_TYPE edge must be dropped from the store"
1376        );
1377        // The warning surfaces with the correct payload.
1378        let parsed_invalid: Vec<_> = engine
1379            .load_warnings()
1380            .iter()
1381            .filter_map(|w| match w {
1382                WarningHint::ParsedRelationInvalid {
1383                    entity_id,
1384                    rel_type,
1385                    target,
1386                    reason,
1387                    origin,
1388                    recovery,
1389                } => Some((
1390                    entity_id.clone(),
1391                    rel_type.clone(),
1392                    target.clone(),
1393                    reason.clone(),
1394                    origin.clone(),
1395                    recovery.clone(),
1396                )),
1397                _ => None,
1398            })
1399            .collect();
1400        assert_eq!(
1401            parsed_invalid.len(),
1402            1,
1403            "expected one warning, got {parsed_invalid:?}"
1404        );
1405        assert_eq!(parsed_invalid[0].0, source_id);
1406        assert_eq!(parsed_invalid[0].1, "MADE_UP_TYPE");
1407        assert_eq!(parsed_invalid[0].2, target_id);
1408        assert_eq!(parsed_invalid[0].3, "unknown_rel_type");
1409        assert_eq!(parsed_invalid[0].4, "writable");
1410        // Writable-origin warnings carry the abstract recovery action.
1411        let recovery = parsed_invalid[0]
1412            .5
1413            .as_ref()
1414            .expect("writable-origin warning must carry recovery");
1415        assert_eq!(
1416            recovery.kind,
1417            crate::ops::ParsedRelationRecovery::KIND_REMOVE_EXPLICIT_RELATION
1418        );
1419        assert_eq!(recovery.source_id, parsed_invalid[0].0);
1420        assert_eq!(recovery.target_id, parsed_invalid[0].2);
1421        assert_eq!(recovery.rel_type, parsed_invalid[0].1);
1422    }
1423
1424    /// Hand-edited markdown can inject a cycle in an `acyclic: true`
1425    /// rel-type's subgraph — the mutation surface's `would_cycle`
1426    /// guard never fires for that path. The boot validator's
1427    /// second pass finds the back-edge and drops it with
1428    /// `reason: "cycle"`. The entity itself loads normally; one of
1429    /// the two cycle-closing edges goes missing from the in-memory
1430    /// store; the other survives.
1431    #[test]
1432    fn from_mounts_drops_cycle_closing_edge_in_acyclic_subgraph() {
1433        let tmp = TempDir::new().unwrap();
1434        let mem_dir = tmp.path().to_path_buf();
1435        // Mutual PART_OF — acyclic in the default schema. The
1436        // wiki-link grammar admits both as well-formed cross-
1437        // references, so only the cycle pass can catch this.
1438        let alpha = "---\ntype: spec\n---\n# Alpha\n\n## Identity\n\nfirst.\n\n## Relationships\n\n- **PART_OF**: [[specs--beta]]\n";
1439        let beta = "---\ntype: spec\n---\n# Beta\n\n## Identity\n\nsecond.\n\n## Relationships\n\n- **PART_OF**: [[specs--alpha]]\n";
1440        std::fs::write(mem_dir.join("alpha.md"), alpha).unwrap();
1441        std::fs::write(mem_dir.join("beta.md"), beta).unwrap();
1442
1443        let writer = FilesystemMemWriter::new(mem_dir.clone());
1444        let engine = Engine::from_mounts(vec![(
1445            folder_mount("specs", mem_dir),
1446            Box::new(writer) as Box<dyn MemBackend>,
1447        )])
1448        .unwrap();
1449
1450        let alpha_id = crate::entity::EntityId::new("specs", "alpha");
1451        let beta_id = crate::entity::EntityId::new("specs", "beta");
1452
1453        // Both entities are real — only the relation in the cycle
1454        // gets dropped.
1455        assert!(engine.get_entity(&alpha_id).is_some_and(|e| !e.stub));
1456        assert!(engine.get_entity(&beta_id).is_some_and(|e| !e.stub));
1457
1458        // Exactly one of the two PART_OF edges survives — the cycle
1459        // is broken by dropping a single back-edge.
1460        let surviving: Vec<_> = engine
1461            .store()
1462            .all_entities()
1463            .flat_map(|e| {
1464                engine
1465                    .store()
1466                    .outgoing(&e.id)
1467                    .iter()
1468                    .filter(|edge| edge.rel_type == "PART_OF")
1469                    .map(|edge| (e.id.clone(), edge.target.clone()))
1470                    .collect::<Vec<_>>()
1471            })
1472            .collect();
1473        assert_eq!(
1474            surviving.len(),
1475            1,
1476            "exactly one PART_OF edge must survive the cycle break, got {surviving:?}",
1477        );
1478
1479        // The warning surfaces with `reason: "cycle"` and names the
1480        // dropped pair.
1481        let cycle_drops: Vec<_> = engine
1482            .load_warnings()
1483            .iter()
1484            .filter_map(|w| match w {
1485                WarningHint::ParsedRelationInvalid {
1486                    entity_id,
1487                    rel_type,
1488                    target,
1489                    reason,
1490                    ..
1491                } if reason == "cycle" => {
1492                    Some((entity_id.clone(), rel_type.clone(), target.clone()))
1493                }
1494                _ => None,
1495            })
1496            .collect();
1497        assert_eq!(
1498            cycle_drops.len(),
1499            1,
1500            "exactly one cycle warning must fire, got {cycle_drops:?}",
1501        );
1502        // The dropped edge is one of the two PART_OF entries.
1503        let (dropped_from, dropped_rel_type, dropped_to) = &cycle_drops[0];
1504        assert_eq!(dropped_rel_type, "PART_OF");
1505        let is_alpha_to_beta = dropped_from == &alpha_id && dropped_to == &beta_id;
1506        let is_beta_to_alpha = dropped_from == &beta_id && dropped_to == &alpha_id;
1507        assert!(
1508            is_alpha_to_beta || is_beta_to_alpha,
1509            "dropped edge must be one of the mutual PART_OF pair, got ({dropped_from} -> {dropped_to})",
1510        );
1511        // And the surviving edge isn't the same as the dropped one.
1512        assert_ne!(
1513            (&surviving[0].0, &surviving[0].1),
1514            (dropped_from, dropped_to),
1515            "surviving edge must differ from the dropped one",
1516        );
1517    }
1518
1519    /// The per-mount nested-prefix drift scan probes an incomplete
1520    /// store: a cross-mem link into a mem loaded LATER in the mount
1521    /// order can't see the real target yet and would false-positive on
1522    /// a perfectly valid id whose slug repeats its mem name (the
1523    /// `registry--registry-service` case). The post-load sweep must
1524    /// drop that hit — while a genuine drift link (target never
1525    /// materialises as a real entity) keeps its warning.
1526    #[test]
1527    fn nested_prefix_warning_exempts_real_cross_mem_target_loaded_later() {
1528        let tmp = TempDir::new().unwrap();
1529        let project_dir = tmp.path().join("project");
1530        let registry_dir = tmp.path().join("registry");
1531        std::fs::create_dir_all(&project_dir).unwrap();
1532        std::fs::create_dir_all(&registry_dir).unwrap();
1533
1534        // Mount 1 (loads first) links both a real later-loaded entity
1535        // and a genuinely missing one.
1536        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nReal: [[registry--registry-service]]. Drifted: [[registry--never-created]].\n";
1537        std::fs::write(project_dir.join("source.md"), source).unwrap();
1538
1539        // Mount 2 (loads second) carries the real target whose slug
1540        // repeats its mem name — the shape the heuristic suspects.
1541        let service = "---\ntype: spec\n---\n# Registry Service\n\n## Identity\n\nA real entity.\n";
1542        std::fs::write(registry_dir.join("registry-service.md"), service).unwrap();
1543
1544        let engine = Engine::from_mounts(vec![
1545            (
1546                folder_mount("project", project_dir.clone()),
1547                Box::new(FilesystemMemWriter::new(project_dir)) as Box<dyn MemBackend>,
1548            ),
1549            (
1550                folder_mount("registry", registry_dir.clone()),
1551                Box::new(FilesystemMemWriter::new(registry_dir)) as Box<dyn MemBackend>,
1552            ),
1553        ])
1554        .unwrap();
1555
1556        let nested: Vec<_> = engine
1557            .load_warnings()
1558            .iter()
1559            .filter_map(|w| match w {
1560                WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
1561                    Some(resolved_id.to_string())
1562                }
1563                _ => None,
1564            })
1565            .collect();
1566        assert!(
1567            !nested.contains(&"registry--registry-service".to_string()),
1568            "a valid cross-mem id resolving to a real entity must not warn, got {nested:?}",
1569        );
1570        assert!(
1571            nested.contains(&"registry--never-created".to_string()),
1572            "a genuinely unresolved nested-prefix link must keep its warning, got {nested:?}",
1573        );
1574    }
1575
1576    /// Shape-invalid relations on a writable-origin mount get dropped
1577    /// with `reason: "shape"`; the warning carries a
1578    /// `remove_explicit_relation` recovery hint whose ids and rel-type
1579    /// mirror the warning's top-level fields. Same envelope shape as
1580    /// the `unknown_rel_type` reason — `reason` discriminates the
1581    /// cause; `recovery.kind` discriminates the action. Uses a
1582    /// synthetic schema with `source_types` / `target_types`
1583    /// constraints because the default schema's rel-types are
1584    /// unconstrained.
1585    #[test]
1586    fn from_mounts_emits_recovery_hint_for_writable_shape_drop() {
1587        use crate::engine::test_helpers::write_schema_files_with_default_type;
1588
1589        let tmp = TempDir::new().unwrap();
1590        let schemas_dir = tmp.path().join("schemas");
1591        std::fs::create_dir_all(&schemas_dir).unwrap();
1592        // A schema declaring a single rel-type whose shape only
1593        // admits `actor -> doc`. The source markdown below uses
1594        // `doc -> doc`, which trips the shape validator.
1595        let manifest = r#"name: shape-test
1596version: 0.1.0
1597description: shape-constraint schema
1598when_to_use: tests
1599types:
1600  - doc
1601  - actor
1602relationships:
1603  mode: strict
1604  definitions:
1605    - name: OWNS
1606      description: actor owns doc
1607      default_weight: 1.0
1608      source_types: [actor]
1609      target_types: [doc]
1610    - name: _default
1611      description: fallback
1612      default_weight: 1.0
1613community:
1614  resolution: 1.0
1615  seed: 42
1616"#;
1617        write_schema_files_with_default_type(
1618            &schemas_dir,
1619            "shape-test",
1620            manifest,
1621            &["doc", "actor"],
1622        );
1623
1624        let mem_dir = tmp.path().join("mem");
1625        std::fs::create_dir_all(&mem_dir).unwrap();
1626        // Source is type `doc`; target is also type `doc`. The
1627        // declared `OWNS` rel-type expects `actor -> doc`, so the
1628        // shape check rejects this pair at load.
1629        let target = "---\ntype: doc\n---\n# Target\n\n## Body\n\nthe target\n";
1630        let source = "---\ntype: doc\n---\n# Source\n\n## Body\n\nthe source\n\n## Relationships\n\n- **OWNS**: [[specs--target]]\n";
1631        std::fs::write(mem_dir.join("target.md"), target).unwrap();
1632        std::fs::write(mem_dir.join("source.md"), source).unwrap();
1633
1634        let writer = FilesystemMemWriter::new(mem_dir.clone());
1635        let pin = SchemaRef::new("shape-test", semver::Version::new(0, 1, 0));
1636        let mount = Mount {
1637            mem: "specs".to_string(),
1638            schema: Some(pin),
1639            storage: MountStorage::Folder { path: mem_dir },
1640            capability: MountCapability::Write,
1641            lifecycle: MountLifecycle::Eager,
1642            cross_linkable: true,
1643            migration_target: None,
1644        };
1645        let engine = Engine::from_mounts_with_schemas_dir(
1646            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
1647            Some(&schemas_dir),
1648        )
1649        .unwrap();
1650
1651        let source_id = crate::entity::EntityId::new("specs", "source");
1652        let target_id = crate::entity::EntityId::new("specs", "target");
1653
1654        let shape_drops: Vec<_> = engine
1655            .load_warnings()
1656            .iter()
1657            .filter_map(|w| match w {
1658                WarningHint::ParsedRelationInvalid {
1659                    entity_id,
1660                    rel_type,
1661                    target,
1662                    reason,
1663                    origin,
1664                    recovery,
1665                } if reason == "shape" => Some((
1666                    entity_id.clone(),
1667                    rel_type.clone(),
1668                    target.clone(),
1669                    origin.clone(),
1670                    recovery.clone(),
1671                )),
1672                _ => None,
1673            })
1674            .collect();
1675        assert_eq!(
1676            shape_drops.len(),
1677            1,
1678            "expected one shape-reason warning, got {shape_drops:?}; all warnings = {:?}",
1679            engine.load_warnings(),
1680        );
1681        let (drop_from, drop_type, drop_to, drop_origin, drop_recovery) =
1682            shape_drops.into_iter().next().unwrap();
1683        assert_eq!(drop_from, source_id);
1684        assert_eq!(drop_type, "OWNS");
1685        assert_eq!(drop_to, target_id);
1686        assert_eq!(drop_origin, "writable");
1687        // Recovery mirrors the warning's top-level fields and names
1688        // the abstract `remove_explicit_relation` action.
1689        let recovery = drop_recovery.expect("writable origin must carry recovery");
1690        assert_eq!(
1691            recovery.kind,
1692            crate::ops::ParsedRelationRecovery::KIND_REMOVE_EXPLICIT_RELATION
1693        );
1694        assert_eq!(recovery.source_id, source_id);
1695        assert_eq!(recovery.target_id, target_id);
1696        assert_eq!(recovery.rel_type, "OWNS");
1697    }
1698
1699    /// Read-only-origin warnings omit the recovery hint — the engine
1700    /// cannot rewrite a read-only mount's markdown, so no abstract
1701    /// action is available. The message field still names the
1702    /// operator-level path (uninstall the archive or accept the
1703    /// drift); structured consumers branch on `recovery.is_none()`.
1704    #[test]
1705    fn from_mounts_emits_no_recovery_hint_for_readonly_origin() {
1706        let tmp = TempDir::new().unwrap();
1707        // Archive content with a `MADE_UP_TYPE` row that the schema
1708        // does not declare — parses to a `PARSED_RELATION_INVALID`
1709        // with `reason: "unknown_rel_type"` on a read-only mount.
1710        let target = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nThe target.\n";
1711        let source = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[external--target]]\n";
1712        let archive_path = build_archive(
1713            tmp.path(),
1714            "ext",
1715            &[
1716                ("target.md", target.as_bytes()),
1717                ("source.md", source.as_bytes()),
1718            ],
1719        );
1720
1721        let engine = Engine::from_mounts(vec![(
1722            archive_mount("external", archive_path.clone()),
1723            Box::new(ArchiveBackend::new(archive_path)),
1724        )])
1725        .unwrap();
1726
1727        let invalid: Vec<_> = engine
1728            .load_warnings()
1729            .iter()
1730            .filter_map(|w| match w {
1731                WarningHint::ParsedRelationInvalid {
1732                    rel_type,
1733                    reason,
1734                    origin,
1735                    recovery,
1736                    ..
1737                } => Some((
1738                    rel_type.clone(),
1739                    reason.clone(),
1740                    origin.clone(),
1741                    recovery.clone(),
1742                )),
1743                _ => None,
1744            })
1745            .collect();
1746        assert_eq!(
1747            invalid.len(),
1748            1,
1749            "expected one parse-time drop on the readonly mount, got {invalid:?}",
1750        );
1751        assert_eq!(invalid[0].0, "MADE_UP_TYPE");
1752        assert_eq!(invalid[0].1, "unknown_rel_type");
1753        assert_eq!(invalid[0].2, "readonly");
1754        assert!(
1755            invalid[0].3.is_none(),
1756            "readonly-origin warning must omit the recovery hint, got {:?}",
1757            invalid[0].3,
1758        );
1759    }
1760
1761    #[test]
1762    fn load_on_init_populates_store_from_folder_mount() {
1763        // Real markdown content: minimal but parses cleanly against
1764        // the builtin default schema.
1765        let body = "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA test entity.\n";
1766
1767        let tmp = TempDir::new().unwrap();
1768        let mem_dir = tmp.path().to_path_buf();
1769        let writer = FilesystemMemWriter::new(mem_dir.clone());
1770        <FilesystemMemWriter as MemWriter>::write_entity(
1771            &writer,
1772            Path::new("hello.md"),
1773            body.as_bytes(),
1774        )
1775        .unwrap();
1776        <FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
1777            .unwrap();
1778
1779        let engine = Engine::from_mounts(vec![(
1780            folder_mount("specs", mem_dir),
1781            Box::new(writer) as Box<dyn MemBackend>,
1782        )])
1783        .unwrap();
1784
1785        // Store is populated.
1786        assert_eq!(engine.store().len(), 1, "expected one entity in the store");
1787        let id = crate::EntityId::new("specs", "hello");
1788        let entity = engine.get_entity(&id).expect("entity must be present");
1789        assert_eq!(entity.title, "Hello");
1790        assert_eq!(entity.entity_type, "spec");
1791        assert!(engine.load_errors().is_empty());
1792        // Schema map carries one entry per mount.
1793        assert_eq!(engine.schemas().len(), 1);
1794        assert!(engine.schemas().contains_key("specs"));
1795    }
1796
1797    #[test]
1798    fn load_on_init_populates_store_from_archive_mount() {
1799        let body =
1800            "---\ntype: spec\n---\n# From Archive\n\n## Identity\n\nLives in a .memstead zip.\n";
1801
1802        let tmp = TempDir::new().unwrap();
1803        let archive_path =
1804            build_archive(tmp.path(), "ext", &[("from-archive.md", body.as_bytes())]);
1805
1806        let engine = Engine::from_mounts(vec![(
1807            archive_mount("external", archive_path.clone()),
1808            Box::new(ArchiveBackend::new(archive_path)),
1809        )])
1810        .unwrap();
1811
1812        let id = crate::EntityId::new("external", "from-archive");
1813        let entity = engine.get_entity(&id).expect("entity must be present");
1814        assert_eq!(entity.title, "From Archive");
1815        assert!(engine.load_errors().is_empty());
1816    }
1817
1818    #[test]
1819    fn load_on_init_populates_store_from_heterogeneous_mounts() {
1820        let folder_body = "---\ntype: spec\n---\n# Local\n\n## Identity\n\nLocal entity.\n";
1821        let archive_body = "---\ntype: spec\n---\n# External\n\n## Identity\n\nArchive entity.\n";
1822
1823        let tmp = TempDir::new().unwrap();
1824
1825        let folder_dir = tmp.path().join("folder-mem");
1826        std::fs::create_dir_all(&folder_dir).unwrap();
1827        let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
1828        <FilesystemMemWriter as MemWriter>::write_entity(
1829            &folder_writer,
1830            Path::new("local.md"),
1831            folder_body.as_bytes(),
1832        )
1833        .unwrap();
1834        <FilesystemMemWriter as MemWriter>::commit(
1835            &folder_writer,
1836            "seed",
1837            &CommitContext::internal(),
1838        )
1839        .unwrap();
1840
1841        let archive_path = build_archive(
1842            tmp.path(),
1843            "external",
1844            &[("external.md", archive_body.as_bytes())],
1845        );
1846
1847        let engine = Engine::from_mounts(vec![
1848            (
1849                folder_mount("local", folder_dir),
1850                Box::new(folder_writer) as Box<dyn MemBackend>,
1851            ),
1852            (
1853                archive_mount("external", archive_path.clone()),
1854                Box::new(ArchiveBackend::new(archive_path)),
1855            ),
1856        ])
1857        .unwrap();
1858
1859        // Both mems' entities live in one shared store.
1860        assert_eq!(engine.store().len(), 2);
1861        assert!(
1862            engine
1863                .get_entity(&crate::EntityId::new("local", "local"))
1864                .is_some()
1865        );
1866        assert!(
1867            engine
1868                .get_entity(&crate::EntityId::new("external", "external"))
1869                .is_some()
1870        );
1871    }
1872
1873    #[test]
1874    fn load_on_init_collects_per_file_parse_errors_without_failing() {
1875        // One good file + one with malformed frontmatter — the parser
1876        // produces an error for the malformed file but the good one
1877        // still loads.
1878        let good = "---\ntype: spec\n---\n# Good\n\n## Identity\n\nFine.\n";
1879        let bad = "---\nthis is not valid yaml: : :\n---\n# Bad\n";
1880
1881        let tmp = TempDir::new().unwrap();
1882        let mem_dir = tmp.path().to_path_buf();
1883        let writer = FilesystemMemWriter::new(mem_dir.clone());
1884        <FilesystemMemWriter as MemWriter>::write_entity(
1885            &writer,
1886            Path::new("good.md"),
1887            good.as_bytes(),
1888        )
1889        .unwrap();
1890        <FilesystemMemWriter as MemWriter>::write_entity(
1891            &writer,
1892            Path::new("bad.md"),
1893            bad.as_bytes(),
1894        )
1895        .unwrap();
1896        <FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
1897            .unwrap();
1898
1899        let engine = Engine::from_mounts(vec![(
1900            folder_mount("specs", mem_dir),
1901            Box::new(writer) as Box<dyn MemBackend>,
1902        )])
1903        .unwrap();
1904
1905        // The good entity is in the store; construction did not fail.
1906        assert!(
1907            engine
1908                .get_entity(&crate::EntityId::new("specs", "good"))
1909                .is_some(),
1910            "good.md must parse and reach the store"
1911        );
1912        // Either bad.md surfaces as a load error, or it parses
1913        // permissively — both are acceptable outcomes here. The
1914        // contract under test is "construction does not fail on a
1915        // single bad file".
1916        let bad_known_to_engine = engine
1917            .get_entity(&crate::EntityId::new("specs", "bad"))
1918            .is_some()
1919            || !engine.load_errors().is_empty();
1920        assert!(
1921            bad_known_to_engine,
1922            "bad.md must either parse or surface in load_errors"
1923        );
1924    }
1925
1926    #[test]
1927    fn empty_mount_list_yields_empty_store() {
1928        let engine = Engine::from_mounts(Vec::new()).unwrap();
1929        assert!(engine.store().is_empty());
1930        assert!(engine.schemas().is_empty());
1931        assert!(engine.load_errors().is_empty());
1932    }
1933
1934    // ---- Engine::create_entity --------------------------------------
1935
1936    #[test]
1937    fn from_workspace_root_errors_for_empty_layout() {
1938        let tmp = TempDir::new().unwrap();
1939        let err = Engine::from_workspace_root(tmp.path()).unwrap_err();
1940        match err {
1941            crate::BootError::NotInitialised(p) => {
1942                assert_eq!(p, tmp.path());
1943            }
1944            other => panic!("expected NotInitialised, got {other:?}"),
1945        }
1946    }
1947
1948    #[test]
1949    fn from_workspace_root_loads_new_two_layer_layout() {
1950        let tmp = TempDir::new().unwrap();
1951        let mem_dir = tmp.path().join("mem");
1952        std::fs::create_dir_all(&mem_dir).unwrap();
1953        std::fs::write(
1954            mem_dir.join("hello.md"),
1955            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
1956        )
1957        .unwrap();
1958
1959        let memstead = tmp.path().join(".memstead");
1960        std::fs::create_dir_all(&memstead).unwrap();
1961        std::fs::write(
1962            memstead.join("workspace.toml"),
1963            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
1964        )
1965        .unwrap();
1966        // Save the mount via the file adapter so the JSON shape matches
1967        // the wire format the loader expects.
1968        use crate::workspace_store::WorkspaceStoreAdapter;
1969        let store = crate::FileWorkspaceStore::new();
1970        store
1971            .save_state(
1972                tmp.path(),
1973                &crate::workspace::Workspace {
1974                    mounts: vec![folder_mount("specs", mem_dir)],
1975                    settings: crate::workspace::WorkspaceSettings::default(),
1976                },
1977            )
1978            .unwrap();
1979
1980        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
1981        assert_eq!(engine.mem_names(), vec!["specs"]);
1982        let entity = engine
1983            .get_entity(&crate::EntityId::new("specs", "hello"))
1984            .expect("seeded entity must load through from_workspace_root");
1985        assert_eq!(entity.title, "Hello");
1986    }
1987
1988    /// The engine-side pipeline loader: with a workspace store carrying one
1989    /// v2 binding, the engine on boot enumerates it through its read-only
1990    /// queryable surface; a retired-format file quarantines its binding
1991    /// with the typed reason (the loader never reads a prior generation).
1992    #[test]
1993    fn from_workspace_root_loads_pipeline_configs_into_queryable_surface() {
1994        use crate::pipeline::MediumType;
1995        let tmp = TempDir::new().unwrap();
1996        let mem_dir = tmp.path().join("mem");
1997        std::fs::create_dir_all(&mem_dir).unwrap();
1998
1999        let memstead = tmp.path().join(".memstead");
2000        std::fs::create_dir_all(&memstead).unwrap();
2001        std::fs::write(
2002            memstead.join("workspace.toml"),
2003            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2004        )
2005        .unwrap();
2006        use crate::workspace_store::WorkspaceStoreAdapter;
2007        crate::FileWorkspaceStore::new()
2008            .save_state(
2009                tmp.path(),
2010                &crate::workspace::Workspace {
2011                    mounts: vec![folder_mount("specs", mem_dir)],
2012                    settings: crate::workspace::WorkspaceSettings::default(),
2013                },
2014            )
2015            .unwrap();
2016
2017        // One v2 binding in the store.
2018        crate::pipeline_store::write_binding(
2019            tmp.path(),
2020            "specs",
2021            "graph",
2022            &sample_v2_binding("specs"),
2023        )
2024        .unwrap();
2025
2026        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
2027        let pc = engine.pipeline_configs();
2028        assert_eq!(pc.bindings.len(), 1, "one binding enumerated");
2029        assert_eq!(pc.bindings[0].mem, "specs");
2030        assert_eq!(pc.bindings[0].name, "graph");
2031        assert_eq!(pc.bindings[0].config.destination_mem, "specs");
2032        assert_eq!(
2033            pc.bindings[0].config.sources[0].medium_type,
2034            MediumType::Codebase
2035        );
2036
2037        // QUARANTINE: a pre-v2 (version-less gen-2) projection
2038        // file no longer fails the boot — the affected binding
2039        // quarantines with the retired-format reason, still never
2040        // read, still never tolerated; the workspace and the healthy
2041        // binding keep serving. Written raw: the engine has no type
2042        // for the retired shape.
2043        std::fs::write(
2044            tmp.path().join(".memstead/projections/specs/legacy.json"),
2045            br#"{"source_facets": ["view"], "reference_mems": [], "destination_mem": "specs"}"#,
2046        )
2047        .unwrap();
2048        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
2049        let pc = engine.pipeline_configs();
2050        assert_eq!(pc.bindings.len(), 1, "the healthy binding still serves");
2051        assert_eq!(pc.quarantined.len(), 1, "the legacy one quarantines");
2052        assert_eq!(pc.quarantined[0].name, "legacy");
2053        assert_eq!(pc.quarantined[0].reason_code, "PROJECTION_STORE_LEGACY");
2054        assert!(
2055            pc.quarantined[0]
2056                .reason_message
2057                .contains("retired binding format"),
2058            "quarantine reason names the retired format, got: {}",
2059            pc.quarantined[0].reason_message
2060        );
2061        assert!(
2062            pc.quarantined[0]
2063                .reason_message
2064                .contains("memstead projection init"),
2065            "quarantine reason names the way back, got: {}",
2066            pc.quarantined[0].reason_message
2067        );
2068    }
2069
2070    /// One v2 binding with a single codebase source under `pointer` — the
2071    /// shared fixture of the boot tests.
2072    fn sample_v2_binding(dest: &str) -> crate::binding::Binding {
2073        v2_binding_with_pointer(dest, "..")
2074    }
2075
2076    fn v2_binding_with_pointer(dest: &str, pointer: &str) -> crate::binding::Binding {
2077        use crate::binding::{BINDING_VERSION, Binding, BuildMode, BuildOperation, Operations};
2078        use crate::pipeline::{IngestTrigger, MediumType, Source};
2079        Binding {
2080            version: BINDING_VERSION,
2081            intent: None,
2082            sources: vec![Source {
2083                name: "src".to_string(),
2084                medium_type: MediumType::Codebase,
2085                pointer: pointer.to_string(),
2086                change_detection: None,
2087                scope: Vec::new(),
2088                engagement: None,
2089                preparation: None,
2090            }],
2091            reference_mems: Vec::new(),
2092            destination_mem: dest.to_string(),
2093            deny_paths: Vec::new(),
2094            coverage_semantics: None,
2095            rules: None,
2096            prune: None,
2097            operations: Operations {
2098                build: Some(BuildOperation {
2099                    mode: BuildMode::Discovery,
2100                    trigger: IngestTrigger::Loop,
2101                    batch_size: 10,
2102                    post_actions: None,
2103                }),
2104                sync: None,
2105                verify: None,
2106            },
2107        }
2108    }
2109
2110    /// Url anchors adjudicate from SUPPLIED observations through the one
2111    /// funnel (plan: url anchors observable): equal hash resolves, a
2112    /// differing hash drifts under `stable` and rechecks under `unstable`,
2113    /// `absent` rechecks; a url row without an observation stays unobserved,
2114    /// never scored. Recording the observations makes the states visible on
2115    /// the per-entity read and dates the rows so they age; the sidecar
2116    /// carries version 2 afterwards. A url anchor is legal beside a mem
2117    /// whose single binding source is path-shaped.
2118    #[test]
2119    fn url_anchors_adjudicate_from_supplied_observations_and_age() {
2120        use crate::anchor::{
2121            AnchorInput, AnchorState, SuppliedObservationInput, validate_supplied_observations,
2122        };
2123        use crate::vcs::Actor;
2124        use crate::workspace_store::WorkspaceStoreAdapter;
2125        use indexmap::IndexMap;
2126
2127        let tmp = TempDir::new().unwrap();
2128        let mem_dir = tmp.path().join("mem");
2129        std::fs::create_dir_all(&mem_dir).unwrap();
2130        std::fs::write(
2131            mem_dir.join("hello.md"),
2132            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
2133        )
2134        .unwrap();
2135
2136        let memstead = tmp.path().join(".memstead");
2137        std::fs::create_dir_all(&memstead).unwrap();
2138        std::fs::write(
2139            memstead.join("workspace.toml"),
2140            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2141        )
2142        .unwrap();
2143        crate::FileWorkspaceStore::new()
2144            .save_state(
2145                tmp.path(),
2146                &crate::workspace::Workspace {
2147                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2148                    settings: crate::workspace::WorkspaceSettings::default(),
2149                },
2150            )
2151            .unwrap();
2152        // Exactly one path-shaped binding source: the shape that used to
2153        // refuse url anchors with the namespace rule.
2154        crate::pipeline_store::write_binding(
2155            tmp.path(),
2156            "specs",
2157            "graph",
2158            &v2_binding_with_pointer("specs", "src"),
2159        )
2160        .unwrap();
2161        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
2162
2163        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2164        let clock_now = "2026-09-02T12:00:00Z";
2165        let pinned = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_788_350_400);
2166        engine.set_mutation_clock(std::sync::Arc::new(move || pinned));
2167        assert_eq!(
2168            engine.now_iso(),
2169            clock_now,
2170            "clock pin is the date the ages count from"
2171        );
2172
2173        let url = |artifact: &str, stability: &str, content: &str| AnchorInput {
2174            artifact: Some(artifact.to_string()),
2175            grain: Some("url".to_string()),
2176            class: Some("anchored".to_string()),
2177            content: Some(content.to_string()),
2178            hash_stability: Some(stability.to_string()),
2179            ..Default::default()
2180        };
2181        let mut sections = IndexMap::new();
2182        sections.insert("identity".to_string(), "Cites the web.".to_string());
2183        sections.insert("purpose".to_string(), "Four url anchors.".to_string());
2184        let created = engine
2185            .create_entity(
2186                crate::CreateEntityArgs {
2187                    mem: "specs".to_string(),
2188                    title: "Cites".to_string(),
2189                    entity_type: "spec".to_string(),
2190                    sections,
2191                    metadata: IndexMap::new(),
2192                    relations: Vec::new(),
2193                    anchors: vec![
2194                        url("https://w.test/stable", "stable", "immutable text"),
2195                        url("https://w.test/living", "unstable", "page v1"),
2196                        url("https://w.test/gone", "unstable", "was here"),
2197                        url("https://w.test/never", "unstable", "never observed again"),
2198                    ],
2199                    dry_run: false,
2200                },
2201                Actor::Agent,
2202                None,
2203                None,
2204            )
2205            .expect("url anchors beside a single path source are legal");
2206        let before = engine.entity_anchors_resolved(&created.id);
2207        assert_eq!(before.len(), 4);
2208        assert!(
2209            before
2210                .iter()
2211                .all(|r| r.state.is_none() && r.observed_at.is_none()),
2212            "no observation yet: every url row unobserved"
2213        );
2214        assert!(
2215            before
2216                .iter()
2217                .all(|r| r.anchor.hash_source == Some(crate::anchor::AnchorHashSource::Author)),
2218            "content supplied at write: author baseline"
2219        );
2220
2221        // Supplied observations: equal hash, changed content, absent; the
2222        // fourth row gets none.
2223        let rows = vec![
2224            SuppliedObservationInput {
2225                artifact: Some("https://w.test/stable".into()),
2226                hash: Some(crate::anchor::prepared_content_hash(b"immutable text")),
2227                ..Default::default()
2228            },
2229            SuppliedObservationInput {
2230                artifact: Some("https://w.test/living".into()),
2231                content: Some("page v2".into()),
2232                observed_at: Some("2026-08-03T09:00:00Z".into()),
2233                ..Default::default()
2234            },
2235            SuppliedObservationInput {
2236                artifact: Some("https://w.test/gone".into()),
2237                absent: Some(true),
2238                ..Default::default()
2239            },
2240            SuppliedObservationInput {
2241                artifact: Some("https://elsewhere.test/unrelated".into()),
2242                hash: Some("zz".into()),
2243                ..Default::default()
2244            },
2245        ];
2246        let supplied = validate_supplied_observations(&rows, clock_now).unwrap();
2247        let report = engine.verify_mem_anchors_with("specs", &supplied).unwrap();
2248        let state_of = |artifact: &str| {
2249            report
2250                .anchors
2251                .iter()
2252                .find(|a| a.artifact == artifact)
2253                .map(|a| {
2254                    (
2255                        a.state.clone(),
2256                        a.unobserved_for_days,
2257                        a.observation_supplied,
2258                    )
2259                })
2260                .unwrap()
2261        };
2262        assert_eq!(
2263            state_of("https://w.test/stable"),
2264            ("resolves".into(), Some(0), true)
2265        );
2266        assert_eq!(
2267            state_of("https://w.test/living"),
2268            ("recheck".into(), Some(30), true)
2269        );
2270        assert_eq!(
2271            state_of("https://w.test/gone"),
2272            ("recheck".into(), Some(0), true)
2273        );
2274        assert_eq!(
2275            state_of("https://w.test/never"),
2276            ("unobserved".into(), None, false)
2277        );
2278        assert_eq!(
2279            report.unmatched_observations,
2280            vec!["https://elsewhere.test/unrelated"]
2281        );
2282        assert_eq!(report.recordable_observations.len(), 3);
2283        assert_eq!(
2284            (
2285                report.figure.count_for_assertions(),
2286                report.recheck,
2287                report.unobserved
2288            ),
2289            (1, 2, 1)
2290        );
2291
2292        // Nothing was written by the verification itself.
2293        assert!(
2294            engine
2295                .entity_anchors_resolved(&created.id)
2296                .iter()
2297                .all(|r| r.state.is_none()),
2298            "verify writes nothing"
2299        );
2300
2301        // Record: the states land on the rows, the read shows them dated,
2302        // and the sidecar is version 2.
2303        let written = engine
2304            .record_anchor_observations("specs", &report.recordable_observations, None)
2305            .unwrap();
2306        assert_eq!(written, 3);
2307        let after = engine.entity_anchors_resolved(&created.id);
2308        let row = |artifact: &str| {
2309            after
2310                .iter()
2311                .find(|r| r.anchor.artifact == artifact)
2312                .unwrap()
2313        };
2314        assert_eq!(
2315            row("https://w.test/stable").state,
2316            Some(AnchorState::Resolves)
2317        );
2318        assert_eq!(
2319            row("https://w.test/living").state,
2320            Some(AnchorState::Recheck)
2321        );
2322        assert_eq!(
2323            row("https://w.test/living").observed_at.as_deref(),
2324            Some("2026-08-03T09:00:00Z")
2325        );
2326        assert_eq!(row("https://w.test/gone").state, Some(AnchorState::Recheck));
2327        assert_eq!(row("https://w.test/never").state, None, "still unobserved");
2328        let sidecar_bytes = std::fs::read(mem_dir.join(".memstead").join("anchors.json")).unwrap();
2329        let sidecar: serde_json::Value = serde_json::from_slice(&sidecar_bytes).unwrap();
2330        assert_eq!(sidecar["version"], 2);
2331        // A second identical recording stages nothing.
2332        assert_eq!(
2333            engine
2334                .record_anchor_observations("specs", &report.recordable_observations, None)
2335                .unwrap(),
2336            0
2337        );
2338
2339        // The next verify, with no observations supplied, rests on the
2340        // recorded ones and ages them: the living page's observation is
2341        // 30 days old; the stable row re-adjudicates DRIFTED when a later
2342        // observation brings a different hash.
2343        let report2 = engine.verify_mem_anchors("specs").unwrap();
2344        let aged = report2
2345            .anchors
2346            .iter()
2347            .find(|a| a.artifact == "https://w.test/living")
2348            .unwrap();
2349        assert_eq!(aged.unobserved_for_days, Some(30));
2350        assert!(!aged.observation_supplied);
2351        let axis = crate::ops::health::health_anchors_axis(&engine, None);
2352        let aging = axis["specs"]["aging"].as_array().unwrap();
2353        assert!(
2354            aging
2355                .iter()
2356                .any(|a| a["artifact"] == "https://w.test/living"
2357                    && a["note"] == "unobserved for 30 days"),
2358            "{axis}"
2359        );
2360        let open = crate::ops::health::health_open_questions_axis(&engine, Some("specs"));
2361        assert!(
2362            open["specs"]["anchors_aging"]["items"]
2363                .as_array()
2364                .is_some_and(|items| items.iter().any(|i| i["note"] == "unobserved for 30 days")),
2365            "{open}"
2366        );
2367
2368        let drift_rows = vec![SuppliedObservationInput {
2369            artifact: Some("https://w.test/stable".into()),
2370            content: Some("immutable text, edited after all".into()),
2371            ..Default::default()
2372        }];
2373        let supplied = validate_supplied_observations(&drift_rows, clock_now).unwrap();
2374        let report3 = engine.verify_mem_anchors_with("specs", &supplied).unwrap();
2375        assert_eq!(
2376            state_of_report(&report3, "https://w.test/stable"),
2377            "drifted"
2378        );
2379        assert_eq!(report3.drifted, 1);
2380    }
2381
2382    /// A version-1 anchors sidecar from a fixture loads unchanged (its rows
2383    /// have no `last_observed`, the file is not touched by reading) and is
2384    /// rewritten as version 2 by the next anchor write; a sidecar declaring a
2385    /// version this engine does not read refuses at the write seam with the
2386    /// existing typed parse error.
2387    #[test]
2388    fn sidecar_v1_fixture_loads_and_next_anchor_write_rewrites_v2_while_v3_refuses() {
2389        use crate::anchor::AnchorInput;
2390        use crate::vcs::Actor;
2391        use crate::workspace_store::WorkspaceStoreAdapter;
2392        use indexmap::IndexMap;
2393
2394        let tmp = TempDir::new().unwrap();
2395        let mem_dir = tmp.path().join("mem");
2396        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
2397        std::fs::write(
2398            mem_dir.join("hello.md"),
2399            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nA.\n",
2400        )
2401        .unwrap();
2402        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"}]}}"#;
2403        std::fs::write(mem_dir.join(".memstead").join("anchors.json"), v1).unwrap();
2404        let memstead = tmp.path().join(".memstead");
2405        std::fs::create_dir_all(&memstead).unwrap();
2406        std::fs::write(
2407            memstead.join("workspace.toml"),
2408            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2409        )
2410        .unwrap();
2411        crate::FileWorkspaceStore::new()
2412            .save_state(
2413                tmp.path(),
2414                &crate::workspace::Workspace {
2415                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2416                    settings: crate::workspace::WorkspaceSettings::default(),
2417                },
2418            )
2419            .unwrap();
2420        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2421
2422        let rows = engine.entity_anchors_resolved(&crate::EntityId::canonical("specs--hello"));
2423        assert_eq!(rows.len(), 1, "the version-1 row loads");
2424        assert_eq!(rows[0].anchor.hash.as_deref(), Some("author-pinned"));
2425        assert!(rows[0].anchor.last_observed.is_none());
2426        assert!(rows[0].state.is_none(), "never observed: unobserved");
2427        let on_disk =
2428            std::fs::read_to_string(mem_dir.join(".memstead").join("anchors.json")).unwrap();
2429        assert_eq!(on_disk, v1, "reading rewrites nothing");
2430
2431        // The next anchor write persists version 2 and keeps the v1 row's
2432        // author hash exactly as it was.
2433        let mut sections = IndexMap::new();
2434        sections.insert("identity".to_string(), "Second.".to_string());
2435        sections.insert("purpose".to_string(), "Second.".to_string());
2436        engine
2437            .create_entity(
2438                crate::CreateEntityArgs {
2439                    mem: "specs".to_string(),
2440                    title: "Second".to_string(),
2441                    entity_type: "spec".to_string(),
2442                    sections,
2443                    metadata: IndexMap::new(),
2444                    relations: Vec::new(),
2445                    anchors: vec![AnchorInput {
2446                        artifact: Some("https://fixture.test/other".to_string()),
2447                        grain: Some("url".to_string()),
2448                        class: Some("informed-by".to_string()),
2449                        ..Default::default()
2450                    }],
2451                    dry_run: false,
2452                },
2453                Actor::Agent,
2454                None,
2455                None,
2456            )
2457            .unwrap();
2458        let after: serde_json::Value = serde_json::from_slice(
2459            &std::fs::read(mem_dir.join(".memstead").join("anchors.json")).unwrap(),
2460        )
2461        .unwrap();
2462        assert_eq!(after["version"], 2);
2463        assert_eq!(
2464            after["entities"]["specs--hello"][0]["hash"],
2465            "author-pinned"
2466        );
2467        assert!(
2468            after["entities"]["specs--hello"][0]
2469                .get("last_observed")
2470                .is_none()
2471        );
2472
2473        // A version this engine does not read refuses at the write seam.
2474        std::fs::write(
2475            mem_dir.join(".memstead").join("anchors.json"),
2476            r#"{"version":3,"entities":{}}"#,
2477        )
2478        .unwrap();
2479        let mut sections = IndexMap::new();
2480        sections.insert("identity".to_string(), "Third.".to_string());
2481        sections.insert("purpose".to_string(), "Third.".to_string());
2482        let err = engine
2483            .create_entity(
2484                crate::CreateEntityArgs {
2485                    mem: "specs".to_string(),
2486                    title: "Third".to_string(),
2487                    entity_type: "spec".to_string(),
2488                    sections,
2489                    metadata: IndexMap::new(),
2490                    relations: Vec::new(),
2491                    anchors: vec![AnchorInput {
2492                        artifact: Some("https://fixture.test/third".to_string()),
2493                        grain: Some("url".to_string()),
2494                        class: Some("informed-by".to_string()),
2495                        ..Default::default()
2496                    }],
2497                    dry_run: false,
2498                },
2499                Actor::Agent,
2500                None,
2501                None,
2502            )
2503            .expect_err("a version-3 sidecar refuses");
2504        assert!(
2505            err.to_string()
2506                .contains("unsupported anchors sidecar version 3"),
2507            "{err}"
2508        );
2509    }
2510
2511    fn state_of_report(
2512        report: &crate::engine::query::MemAnchorVerification,
2513        artifact: &str,
2514    ) -> String {
2515        report
2516            .anchors
2517            .iter()
2518            .find(|a| a.artifact == artifact)
2519            .map(|a| a.state.clone())
2520            .unwrap()
2521    }
2522
2523    /// Live per-anchor state (criteria 1, 9 — path-medium subset): a
2524    /// single-medium `path` mem observes working-tree existence at the current
2525    /// HEAD. Absent artifact ⇒ `orphaned`; present + non-hash class ⇒
2526    /// `resolves`; present + hash-bearing class ⇒ the prepared-content hash
2527    /// comparison adjudicates deterministically — a recorded hash matching
2528    /// the observed prepared form `resolves`, a stable-medium mismatch is
2529    /// `drifted` (a real content drift, no longer deferred to `recheck`).
2530    #[test]
2531    fn entity_anchors_resolve_live_state_for_path_medium() {
2532        use crate::anchor::{AnchorInput, AnchorState};
2533        use crate::vcs::Actor;
2534        use crate::workspace_store::WorkspaceStoreAdapter;
2535        use indexmap::IndexMap;
2536
2537        let tmp = TempDir::new().unwrap();
2538        let mem_dir = tmp.path().join("mem");
2539        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
2540        std::fs::write(
2541            mem_dir.join(".memstead").join("config.json"),
2542            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
2543        )
2544        .unwrap();
2545
2546        let memstead = tmp.path().join(".memstead");
2547        std::fs::create_dir_all(&memstead).unwrap();
2548        std::fs::write(
2549            memstead.join("workspace.toml"),
2550            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2551        )
2552        .unwrap();
2553        crate::FileWorkspaceStore::new()
2554            .save_state(
2555                tmp.path(),
2556                &crate::workspace::Workspace {
2557                    mounts: vec![folder_mount("specs", mem_dir.clone())],
2558                    settings: crate::workspace::WorkspaceSettings::default(),
2559                },
2560            )
2561            .unwrap();
2562
2563        // A single `path` source rooted at `<workspace>/src` (medium context
2564        // now derives from the mem's binding sources). Anchor artifact ids
2565        // are workspace-relative (pointer-prefixed) — the dialect
2566        // enumeration / coverage / advance share — so `src/present.rs`
2567        // observes present and `src/gone.rs` observes absent.
2568        crate::pipeline_store::write_binding(
2569            tmp.path(),
2570            "specs",
2571            "graph",
2572            &v2_binding_with_pointer("specs", "src"),
2573        )
2574        .unwrap();
2575        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
2576        std::fs::write(tmp.path().join("src").join("present.rs"), "fn main() {}").unwrap();
2577        // Exists at write time (the write gate refuses dead references);
2578        // deleted after the write to produce the orphaned READ state.
2579        std::fs::write(tmp.path().join("src").join("gone.rs"), "fn gone() {}").unwrap();
2580
2581        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2582
2583        let anchor = |artifact: &str, class: &str, hash: Option<&str>| AnchorInput {
2584            artifact: Some(artifact.to_string()),
2585            grain: Some("file".to_string()),
2586            class: Some(class.to_string()),
2587            hash: hash.map(str::to_string),
2588            hash_stability: Some("stable".to_string()),
2589            ..Default::default()
2590        };
2591        let mut sections = IndexMap::new();
2592        sections.insert("identity".to_string(), "Covers src.".to_string());
2593        sections.insert("purpose".to_string(), "Track sources.".to_string());
2594        // The prepared-form hash of the present artifact, as the observation
2595        // computes it — an anchor recording it must resolve clean.
2596        let present_hash = crate::anchor::prepared_content_hash(
2597            &std::fs::read(tmp.path().join("src").join("present.rs")).unwrap(),
2598        );
2599        let created = engine
2600            .create_entity(
2601                crate::CreateEntityArgs {
2602                    mem: "specs".to_string(),
2603                    title: "Covers".to_string(),
2604                    entity_type: "spec".to_string(),
2605                    sections,
2606                    metadata: IndexMap::new(),
2607                    relations: Vec::new(),
2608                    anchors: vec![
2609                        anchor("src/present.rs", "anchored", Some(&present_hash)), // hash matches → resolves
2610                        anchor("src/present.rs", "informed-by", None), // present + non-hash → resolves
2611                        anchor("src/gone.rs", "anchored", Some("h2")), // absent → orphaned
2612                        anchor("src/present.rs", "derived", Some("stale")), // hash mismatch, stable → drifted
2613                    ],
2614                    dry_run: false,
2615                },
2616                Actor::Agent,
2617                None,
2618                None,
2619            )
2620            .unwrap();
2621
2622        std::fs::remove_file(tmp.path().join("src").join("gone.rs")).unwrap();
2623        let resolved = engine.entity_anchors_resolved(&created.id);
2624        assert_eq!(resolved.len(), 4);
2625        let state_of = |artifact: &str, class: crate::anchor::AnchorProvenanceClass| {
2626            resolved
2627                .iter()
2628                .find(|r| r.anchor.artifact == artifact && r.anchor.class == class)
2629                .and_then(|r| r.state)
2630        };
2631        assert_eq!(
2632            state_of(
2633                "src/present.rs",
2634                crate::anchor::AnchorProvenanceClass::Anchored
2635            ),
2636            Some(AnchorState::Resolves),
2637            "recorded hash matches the observed prepared form → resolves"
2638        );
2639        assert_eq!(
2640            state_of(
2641                "src/present.rs",
2642                crate::anchor::AnchorProvenanceClass::Derived
2643            ),
2644            Some(AnchorState::Drifted),
2645            "recorded hash mismatches the observed prepared form on a stable medium → drifted"
2646        );
2647        assert_eq!(
2648            state_of(
2649                "src/present.rs",
2650                crate::anchor::AnchorProvenanceClass::InformedBy
2651            ),
2652            Some(AnchorState::Resolves),
2653            "present non-hash anchor resolves on existence"
2654        );
2655        assert_eq!(
2656            state_of(
2657                "src/gone.rs",
2658                crate::anchor::AnchorProvenanceClass::Anchored
2659            ),
2660            Some(AnchorState::Orphaned),
2661            "absent artifact is orphaned"
2662        );
2663    }
2664
2665    /// The engine edit surface: a wrapper edit (`add_projection_json`)
2666    /// routes through the pipeline-edit layer, writes the store, and
2667    /// refreshes the in-memory snapshot in place (no `reload()`); the JSON
2668    /// read counterpart reflects the collapsed `{bindings}`-only shape.
2669    #[test]
2670    fn engine_pipeline_edit_methods_mutate_and_refresh_the_snapshot() {
2671        use crate::workspace_store::WorkspaceStoreAdapter;
2672
2673        let tmp = TempDir::new().unwrap();
2674        let mem_dir = tmp.path().join("mem");
2675        std::fs::create_dir_all(&mem_dir).unwrap();
2676        let memstead = tmp.path().join(".memstead");
2677        std::fs::create_dir_all(&memstead).unwrap();
2678        std::fs::write(
2679            memstead.join("workspace.toml"),
2680            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2681        )
2682        .unwrap();
2683        crate::FileWorkspaceStore::new()
2684            .save_state(
2685                tmp.path(),
2686                &crate::workspace::Workspace {
2687                    mounts: vec![folder_mount("specs", mem_dir)],
2688                    settings: crate::workspace::WorkspaceSettings::default(),
2689                },
2690            )
2691            .unwrap();
2692
2693        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
2694        assert!(engine.pipeline_configs().bindings.is_empty());
2695
2696        // The JSON entry point (the FFI-facing shape) deserializes and lands.
2697        engine
2698            .add_projection_json(
2699                "specs",
2700                "graph",
2701                r#"{
2702                    "sources": [{ "name": "src", "type": "codebase", "pointer": "..",
2703                                  "scope": [{ "path": "**/*.rs", "mode": "allow" }] }],
2704                    "destination_mem": "specs"
2705                }"#,
2706                None,
2707            )
2708            .unwrap();
2709        // Snapshot refreshed in place.
2710        assert_eq!(engine.pipeline_configs().bindings.len(), 1);
2711        assert_eq!(engine.pipeline_configs().bindings[0].name, "graph");
2712        assert_eq!(
2713            engine.pipeline_configs().bindings[0].config.sources[0].name,
2714            "src"
2715        );
2716
2717        // A malformed payload is refused without touching the store.
2718        let err = engine
2719            .add_projection_json("specs", "bad", "{ not json", None)
2720            .unwrap_err();
2721        assert!(
2722            matches!(
2723                err,
2724                crate::pipeline_edit::PipelineEditError::InvalidJson { .. }
2725            ),
2726            "got {err:?}"
2727        );
2728
2729        // Update patches over the stored record; delete removes and refreshes.
2730        engine
2731            .update_projection_json("specs", "graph", r#"{"intent":"i2"}"#, None)
2732            .unwrap();
2733        assert_eq!(
2734            engine.pipeline_configs().bindings[0]
2735                .config
2736                .intent
2737                .as_deref(),
2738            Some("i2")
2739        );
2740
2741        // Rename moves the record and refreshes the snapshot.
2742        engine
2743            .rename_projection("specs", "graph", "graph2", None)
2744            .unwrap();
2745        assert_eq!(engine.pipeline_configs().bindings[0].name, "graph2");
2746
2747        // The JSON read counterpart reflects the live store in the
2748        // `{bindings}`-only shape — no `mediums` / `facets` keys.
2749        let json = engine.pipeline_configs_json();
2750        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
2751        assert!(parsed.get("mediums").is_none(), "no mediums key: {json}");
2752        assert!(parsed.get("facets").is_none(), "no facets key: {json}");
2753        let bindings = parsed["bindings"].as_array().unwrap();
2754        assert_eq!(bindings.len(), 1);
2755        assert_eq!(bindings[0]["name"], "graph2");
2756        assert_eq!(bindings[0]["config"]["sources"][0]["type"], "codebase");
2757
2758        engine.delete_projection("specs", "graph2", None).unwrap();
2759        assert!(engine.pipeline_configs().bindings.is_empty());
2760    }
2761
2762    /// The folder authoring path: a schema package authored at the
2763    /// fixed `<workspace>/.memstead/schemas/<name>@<version>/` location
2764    /// is resolved at boot, so a folder mem can pin a non-built-in
2765    /// schema. Before this wiring `from_workspace_root` loaded only
2766    /// built-ins, so the pin would refuse with `SCHEMA_NOT_FOUND`.
2767    #[test]
2768    fn from_workspace_root_resolves_authored_schema_from_dot_memstead_schemas() {
2769        use crate::engine::test_helpers::write_schema_files_with_default_type;
2770
2771        let tmp = TempDir::new().unwrap();
2772        let mem_dir = tmp.path().join("mem");
2773        std::fs::create_dir_all(&mem_dir).unwrap();
2774
2775        // Author a schema package at the fixed folder location.
2776        let authored_dir = tmp.path().join(".memstead").join("schemas");
2777        let manifest = r#"name: authored
2778version: 0.1.0
2779description: an authored-in-workspace test schema
2780when_to_use: tests
2781types:
2782  - doc
2783relationships:
2784  mode: strict
2785  definitions:
2786    - name: _default
2787      description: fallback
2788      default_weight: 1.0
2789community:
2790  resolution: 1.0
2791  seed: 42
2792"#;
2793        write_schema_files_with_default_type(&authored_dir, "authored@0.1.0", manifest, &["doc"]);
2794
2795        // A folder mem pinning the authored (non-built-in) schema.
2796        let memstead = tmp.path().join(".memstead");
2797        std::fs::create_dir_all(&memstead).unwrap();
2798        std::fs::write(
2799            memstead.join("workspace.toml"),
2800            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2801        )
2802        .unwrap();
2803        let mount = Mount {
2804            mem: "specs".to_string(),
2805            schema: Some(SchemaRef::new("authored", semver::Version::new(0, 1, 0))),
2806            storage: MountStorage::Folder { path: mem_dir },
2807            capability: MountCapability::Write,
2808            lifecycle: MountLifecycle::Eager,
2809            cross_linkable: true,
2810            migration_target: None,
2811        };
2812        use crate::workspace_store::WorkspaceStoreAdapter;
2813        crate::FileWorkspaceStore::new()
2814            .save_state(
2815                tmp.path(),
2816                &crate::workspace::Workspace {
2817                    mounts: vec![mount],
2818                    settings: crate::workspace::WorkspaceSettings::default(),
2819                },
2820            )
2821            .unwrap();
2822
2823        // Boots cleanly — the authored pin resolved against the fixed
2824        // location rather than refusing as an unknown built-in.
2825        let engine = Engine::from_workspace_root(tmp.path())
2826            .expect("authored schema at .memstead/schemas/ must resolve at boot");
2827        assert_eq!(engine.mem_names(), vec!["specs"]);
2828    }
2829
2830    /// Authoring-drift health axis (plan 10): a STAMPED sealed schema
2831    /// reports a missing authoring package and (separately) a diverged
2832    /// one; an unmodified package, a cosmetic-only difference (editor
2833    /// header comment lines), and an unstamped seal produce NO
2834    /// finding; and the checks alter neither copy.
2835    #[test]
2836    fn health_reports_authoring_drift_for_stamped_schemas_only() {
2837        use crate::engine::test_helpers::write_schema_files_with_default_type;
2838
2839        let tmp = TempDir::new().unwrap();
2840        let mem_dir = tmp.path().join("mem");
2841        std::fs::create_dir_all(&mem_dir).unwrap();
2842        let manifest = r#"name: authored
2843version: 0.1.0
2844description: an authored-in-workspace test schema
2845when_to_use: tests
2846types:
2847  - doc
2848relationships:
2849  mode: strict
2850  definitions:
2851    - name: _default
2852      description: fallback
2853      default_weight: 1.0
2854community:
2855  resolution: 1.0
2856  seed: 42
2857"#;
2858        // Sealed copy at the fixed install location; authoring copy in
2859        // the working tree.
2860        let sealed_root = tmp.path().join(".memstead").join("schemas");
2861        write_schema_files_with_default_type(&sealed_root, "authored@0.1.0", manifest, &["doc"]);
2862        let author_root = tmp.path().join("author");
2863        write_schema_files_with_default_type(&author_root, "authored@0.1.0", manifest, &["doc"]);
2864        let authoring_dir = author_root.join("authored@0.1.0");
2865        let sealed_dir = sealed_root.join("authored@0.1.0");
2866        // The install-time stamp: the seal records where it came from.
2867        let stamp_path = sealed_dir.join(memstead_schema::INSTALL_PROVENANCE_FILE);
2868        std::fs::write(
2869            &stamp_path,
2870            serde_json::to_vec_pretty(&serde_json::json!({
2871                "authoring_path": authoring_dir.display().to_string(),
2872            }))
2873            .unwrap(),
2874        )
2875        .unwrap();
2876
2877        let memstead = tmp.path().join(".memstead");
2878        std::fs::write(
2879            memstead.join("workspace.toml"),
2880            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
2881        )
2882        .unwrap();
2883        let mount = Mount {
2884            mem: "specs".to_string(),
2885            schema: Some(SchemaRef::new("authored", semver::Version::new(0, 1, 0))),
2886            storage: MountStorage::Folder { path: mem_dir },
2887            capability: MountCapability::Write,
2888            lifecycle: MountLifecycle::Eager,
2889            cross_linkable: true,
2890            migration_target: None,
2891        };
2892        use crate::workspace_store::WorkspaceStoreAdapter;
2893        crate::FileWorkspaceStore::new()
2894            .save_state(
2895                tmp.path(),
2896                &crate::workspace::Workspace {
2897                    mounts: vec![mount],
2898                    settings: crate::workspace::WorkspaceSettings::default(),
2899                },
2900            )
2901            .unwrap();
2902        let engine = Engine::from_workspace_root(tmp.path()).expect("workspace boots");
2903        let drift_codes = |e: &Engine| -> Vec<String> {
2904            e.health()
2905                .warnings
2906                .iter()
2907                .filter(|w| w.code().starts_with("SCHEMA_AUTHORING_SOURCE_"))
2908                .map(|w| w.code().to_string())
2909                .collect()
2910        };
2911
2912        // Unmodified authoring package: no finding, and the check
2913        // touched neither copy.
2914        let sealed_before = std::fs::read(sealed_dir.join("schema.yaml")).unwrap();
2915        let author_before = std::fs::read(authoring_dir.join("schema.yaml")).unwrap();
2916        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2917        assert_eq!(
2918            std::fs::read(sealed_dir.join("schema.yaml")).unwrap(),
2919            sealed_before,
2920            "health must not touch the sealed copy"
2921        );
2922        assert_eq!(
2923            std::fs::read(authoring_dir.join("schema.yaml")).unwrap(),
2924            author_before,
2925            "health must not touch the authoring copy"
2926        );
2927
2928        // Cosmetic-only difference (the CLI-injected editor-header
2929        // line + a comment): still no finding — parsed equivalence,
2930        // never raw bytes.
2931        std::fs::write(
2932            authoring_dir.join("schema.yaml"),
2933            format!(
2934                "# yaml-language-server: $schema=../../.memstead/meta-schemas/schema-manifest.json\n# cosmetic comment\n{manifest}"
2935            ),
2936        )
2937        .unwrap();
2938        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2939
2940        // Semantic change: DIVERGED, naming schema, version, and the
2941        // pinning mems.
2942        std::fs::write(
2943            authoring_dir.join("schema.yaml"),
2944            manifest.replace(
2945                "an authored-in-workspace test schema",
2946                "a semantically different description",
2947            ),
2948        )
2949        .unwrap();
2950        let warnings = engine.health().warnings;
2951        let diverged = warnings
2952            .iter()
2953            .find(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_DIVERGED")
2954            .expect("semantic change must surface as DIVERGED");
2955        let d = serde_json::to_value(diverged).unwrap();
2956        assert_eq!(d["details"]["schema_ref"], "authored@0.1.0");
2957        assert_eq!(d["details"]["mems"], serde_json::json!(["specs"]));
2958
2959        // Authoring package gone: the DIFFERENT finding — MISSING.
2960        std::fs::remove_dir_all(&authoring_dir).unwrap();
2961        let warnings = engine.health().warnings;
2962        let missing = warnings
2963            .iter()
2964            .find(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_MISSING")
2965            .expect("vanished authoring package must surface as MISSING");
2966        let m = serde_json::to_value(missing).unwrap();
2967        assert_eq!(m["details"]["schema_ref"], "authored@0.1.0");
2968        assert_eq!(m["details"]["mems"], serde_json::json!(["specs"]));
2969        assert_eq!(
2970            m["details"]["stamped_path"],
2971            authoring_dir.display().to_string()
2972        );
2973        assert!(
2974            !warnings
2975                .iter()
2976                .any(|w| w.code() == "SCHEMA_AUTHORING_SOURCE_DIVERGED"),
2977            "missing and diverged are distinct findings"
2978        );
2979
2980        // No stamp → no finding, even with the package still gone.
2981        std::fs::remove_file(&stamp_path).unwrap();
2982        assert_eq!(drift_codes(&engine), Vec::<String>::new());
2983    }
2984
2985    /// `full_refresh` makes an out-of-band schema install and
2986    /// an out-of-band mem registration usable warm — additively.
2987    /// Removals are skipped and reported; a failed mount is reported
2988    /// per-item and does not abort the rest.
2989    #[test]
2990    fn full_refresh_is_additive_and_reports_skipped_removals() {
2991        use crate::engine::test_helpers::write_schema_files_with_default_type;
2992        use crate::workspace_store::WorkspaceStoreAdapter;
2993
2994        let tmp = TempDir::new().unwrap();
2995        let root = tmp.path();
2996        let mem_a = root.join("mem-a");
2997        std::fs::create_dir_all(&mem_a).unwrap();
2998        std::fs::create_dir_all(root.join(".memstead")).unwrap();
2999        std::fs::write(
3000            root.join(".memstead").join("workspace.toml"),
3001            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3002        )
3003        .unwrap();
3004        let mount = |mem: &str, dir: &Path, schema: &str, version: semver::Version| Mount {
3005            mem: mem.to_string(),
3006            schema: Some(SchemaRef::new(schema, version)),
3007            storage: MountStorage::Folder {
3008                path: dir.to_path_buf(),
3009            },
3010            capability: MountCapability::Write,
3011            lifecycle: MountLifecycle::Eager,
3012            cross_linkable: true,
3013            migration_target: None,
3014        };
3015        let save = |mounts: Vec<Mount>| {
3016            crate::FileWorkspaceStore::new()
3017                .save_state(
3018                    root,
3019                    &crate::workspace::Workspace {
3020                        mounts,
3021                        settings: crate::workspace::WorkspaceSettings::default(),
3022                    },
3023                )
3024                .unwrap();
3025        };
3026        save(vec![mount(
3027            "specs",
3028            &mem_a,
3029            "default",
3030            semver::Version::new(1, 0, 0),
3031        )]);
3032        let mut engine = Engine::from_workspace_root(root).expect("workspace boots");
3033        assert_eq!(engine.mem_names(), vec!["specs"]);
3034
3035        // --- Out of band, while the "server" runs: install a schema
3036        // and register a mem pinned to it. ---
3037        let manifest = r#"name: authored
3038version: 0.1.0
3039description: an out-of-band installed schema
3040when_to_use: tests
3041types:
3042  - doc
3043relationships:
3044  mode: strict
3045  definitions:
3046    - name: _default
3047      description: fallback
3048      default_weight: 1.0
3049community:
3050  resolution: 1.0
3051  seed: 42
3052"#;
3053        write_schema_files_with_default_type(
3054            &root.join(".memstead").join("schemas"),
3055            "authored@0.1.0",
3056            manifest,
3057            &["doc"],
3058        );
3059        let mem_b = root.join("mem-b");
3060        std::fs::create_dir_all(&mem_b).unwrap();
3061        save(vec![
3062            mount("specs", &mem_a, "default", semver::Version::new(1, 0, 0)),
3063            mount("notes", &mem_b, "authored", semver::Version::new(0, 1, 0)),
3064        ]);
3065
3066        // Since 2026-09-02 membership follows reload-before-operation: the
3067        // first operation would reconcile the roster on its own. The refresh
3068        // verb runs the same reconciliation, forced, and reports it.
3069        let (actor, client) = cli_actor();
3070        let mut pre = crate::engine::test_helpers::empty_create_args("notes", "Too Early");
3071        pre.entity_type = "doc".to_string();
3072        pre.sections = indexmap::IndexMap::from_iter([("body".to_string(), "body".to_string())]);
3073
3074        // --- Full refresh: both become usable, warm. ---
3075        let report = engine.full_refresh();
3076        assert_eq!(report.schemas_added, vec!["authored@0.1.0".to_string()]);
3077        assert_eq!(report.mems_mounted, vec!["notes".to_string()]);
3078        assert!(report.schema_removals_skipped.is_empty(), "{report:?}");
3079        assert!(report.mems_unmounted.is_empty(), "{report:?}");
3080        assert!(report.failures.is_empty(), "{report:?}");
3081        engine
3082            .create_entity(pre, actor, Some(&client), None)
3083            .expect("newly mounted mem accepts writes after the refresh");
3084
3085        // --- Removals do NOT take effect: drop `specs` from the
3086        // manifest and delete the schema package from its source. ---
3087        std::fs::remove_dir_all(
3088            root.join(".memstead")
3089                .join("schemas")
3090                .join("authored@0.1.0"),
3091        )
3092        .unwrap();
3093        save(vec![mount(
3094            "notes",
3095            &mem_b,
3096            "authored",
3097            semver::Version::new(0, 1, 0),
3098        )]);
3099        let report = engine.full_refresh();
3100        // Removals APPLY since 2026-09-02: the mem leaves the roster and is
3101        // no longer served; the schema removal stays skipped.
3102        assert_eq!(report.mems_unmounted, vec!["specs".to_string()]);
3103        assert_eq!(engine.mem_names(), vec!["notes"]);
3104        assert_eq!(
3105            report.schema_removals_skipped,
3106            vec!["authored@0.1.0".to_string()]
3107        );
3108        assert!(report.schemas_added.is_empty());
3109        assert!(report.mems_mounted.is_empty());
3110        // The unregistered mem is gone: a write naming it refuses with the
3111        // typed code; the removed schema version still resolves for its mem.
3112        let gone = engine
3113            .create_entity(
3114                crate::engine::test_helpers::empty_create_args("specs", "Still Here"),
3115                actor,
3116                Some(&client),
3117                None,
3118            )
3119            .expect_err("an unmounted mem refuses writes");
3120        assert_eq!(gone.code(), "MEM_UNMOUNTED", "{gone:?}");
3121        let mut into_notes =
3122            crate::engine::test_helpers::empty_create_args("notes", "Still Resolvable");
3123        into_notes.entity_type = "doc".to_string();
3124        into_notes.sections =
3125            indexmap::IndexMap::from_iter([("body".to_string(), "body".to_string())]);
3126        engine
3127            .create_entity(into_notes, actor, Some(&client), None)
3128            .expect("removed-from-source schema stays resolvable");
3129
3130        // --- Per-item failure: a manifest mount whose path is a FILE
3131        // fails alone; the rest of the refresh proceeds. ---
3132        let broken = root.join("broken-mem");
3133        std::fs::write(&broken, b"not a directory").unwrap();
3134        save(vec![
3135            mount("notes", &mem_b, "authored", semver::Version::new(0, 1, 0)),
3136            mount("broken", &broken, "default", semver::Version::new(1, 0, 0)),
3137        ]);
3138        let report = engine.full_refresh();
3139        assert!(
3140            report.mems_quarantined.contains(&"broken".to_string()),
3141            "a mount that cannot attach is quarantined per-item, as boot would: {report:?}"
3142        );
3143        assert!(engine.quarantine_reason("broken").is_some());
3144        assert!(
3145            !report.mems_mounted.contains(&"broken".to_string()),
3146            "a failed mount never surfaces as newly available"
3147        );
3148        assert!(
3149            engine
3150                .get_entity(&crate::EntityId::new("broken", "anything"))
3151                .is_none()
3152                && engine.mem_names().contains(&"notes"),
3153            "other mounts unaffected"
3154        );
3155    }
3156
3157    #[test]
3158    fn from_workspace_root_propagates_mem_management_settings() {
3159        // workspace.toml carries [mem_management] rules; the file
3160        // adapter parses them into Workspace.settings; from_workspace_root
3161        // calls Engine::set_settings so the engine surface reflects them.
3162        // End-to-end check that the carriers, parser, and plumbing connect.
3163        let tmp = TempDir::new().unwrap();
3164        let mem_dir = tmp.path().join("mem");
3165        std::fs::create_dir_all(&mem_dir).unwrap();
3166
3167        let memstead = tmp.path().join(".memstead");
3168        std::fs::create_dir_all(&memstead).unwrap();
3169        std::fs::write(
3170            memstead.join("workspace.toml"),
3171            r#"format = "memstead-git-branch-2"
3172
3173[persistence_adapter]
3174name = "file-two-layer"
3175
3176[[mem_management.create]]
3177pattern = "exec-*"
3178schemas = ["default@1.0.0"]
3179
3180[[mem_management.delete]]
3181pattern = "exec-*"
3182"#,
3183        )
3184        .unwrap();
3185        use crate::workspace_store::WorkspaceStoreAdapter;
3186        let store = crate::FileWorkspaceStore::new();
3187        store
3188            .save_state(
3189                tmp.path(),
3190                &crate::workspace::Workspace {
3191                    mounts: vec![folder_mount("specs", mem_dir)],
3192                    settings: crate::workspace::WorkspaceSettings::default(),
3193                },
3194            )
3195            .unwrap();
3196
3197        let engine = Engine::from_workspace_root(tmp.path()).unwrap();
3198        let s = engine.settings();
3199        assert_eq!(s.mem_create_rules.len(), 1);
3200        assert_eq!(s.mem_create_rules[0].pattern, "exec-*");
3201        assert_eq!(
3202            s.mem_create_rules[0].schemas,
3203            vec!["default@1.0.0".to_string()]
3204        );
3205        assert_eq!(s.mem_delete_rules.len(), 1);
3206        assert_eq!(s.mem_delete_rules[0].pattern, "exec-*");
3207    }
3208
3209    /// Deliberate replacement of the historical wholesale-abort test
3210    /// (`from_mounts_rejects_unknown_schema_pin_with_typed_error`):
3211    /// an unresolvable pin no longer fails the
3212    /// workspace — the mem is QUARANTINED with the same typed
3213    /// `SCHEMA_NOT_FOUND` reason (nothing is weakened, the blast
3214    /// radius shrinks), operations naming it refuse `MEM_QUARANTINED`,
3215    /// and the roster surfaces on health.
3216    #[test]
3217    fn from_mounts_quarantines_unknown_schema_pin() {
3218        let tmp = TempDir::new().unwrap();
3219        let writer = FilesystemMemWriter::new(tmp.path().to_path_buf());
3220        let mount = Mount {
3221            mem: "specs".to_string(),
3222            schema: Some(SchemaRef::new(
3223                "totally-not-a-schema",
3224                semver::Version::new(1, 0, 0),
3225            )),
3226            storage: MountStorage::Folder {
3227                path: tmp.path().to_path_buf(),
3228            },
3229            capability: MountCapability::Write,
3230            lifecycle: MountLifecycle::Eager,
3231            cross_linkable: true,
3232            migration_target: None,
3233        };
3234        let engine = Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)])
3235            .expect("a broken mem quarantines, never fails the workspace");
3236
3237        let roster = engine.quarantined_mems();
3238        assert_eq!(roster.len(), 1);
3239        assert_eq!(roster[0].mount.mem, "specs");
3240        assert_eq!(roster[0].reason_code, "SCHEMA_NOT_FOUND");
3241        assert!(
3242            roster[0].reason_message.contains("totally-not-a-schema"),
3243            "reason carries the failing pin: {}",
3244            roster[0].reason_message
3245        );
3246        // The mem serves nothing: it is not on the mount roster …
3247        assert!(engine.mounts().iter().all(|m| m.mem != "specs"));
3248        // … and lookups refuse with the typed quarantine code, not
3249        // UNKNOWN_MEM.
3250        let err = engine.unknown_mem_error("specs");
3251        assert_eq!(err.code(), "MEM_QUARANTINED");
3252        assert!(
3253            err.to_string().contains("SCHEMA_NOT_FOUND"),
3254            "quarantine refusal carries the underlying reason: {err}"
3255        );
3256        // Health carries the roster without an include gate.
3257        let health = engine.health();
3258        assert_eq!(health.quarantined.len(), 1);
3259        assert_eq!(health.quarantined[0].reason_code, "SCHEMA_NOT_FOUND");
3260    }
3261
3262    /// Criterion 5: quarantine → repair →
3263    /// reload returns the mem to service in the same engine instance;
3264    /// the roster entry disappears. The repair here is the same
3265    /// value-level config-pin rewrite `memstead mem set-schema`
3266    /// performs below boot (plan 03).
3267    #[test]
3268    fn reload_returns_repaired_mem_from_quarantine() {
3269        let tmp = TempDir::new().unwrap();
3270        let dir = tmp.path().to_path_buf();
3271        std::fs::create_dir_all(dir.join(".memstead")).unwrap();
3272        let config_path = dir.join(".memstead").join("config.json");
3273        std::fs::write(&config_path, r#"{ "schema": "ghost@1.0.0" }"#).unwrap();
3274        let writer = FilesystemMemWriter::new(dir.clone());
3275        let mount = Mount {
3276            mem: "specs".to_string(),
3277            schema: None,
3278            storage: MountStorage::Folder { path: dir },
3279            capability: MountCapability::Write,
3280            lifecycle: MountLifecycle::Eager,
3281            cross_linkable: true,
3282            migration_target: None,
3283        };
3284        let mut engine =
3285            Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
3286        assert_eq!(engine.quarantined_mems().len(), 1);
3287        // Un-repaired reload keeps the quarantine (refreshed reason,
3288        // typed refusal).
3289        let err = engine.reload_one_mem("specs").unwrap_err();
3290        assert_eq!(err.code(), "MEM_QUARANTINED");
3291        assert_eq!(engine.quarantined_mems().len(), 1);
3292
3293        // Repair: repin the config to a resolvable schema (what
3294        // `mem set-schema` does below boot), then reload.
3295        std::fs::write(&config_path, r#"{ "schema": "default@1.0.0" }"#).unwrap();
3296        engine
3297            .reload_one_mem("specs")
3298            .expect("repaired mem re-attaches on reload");
3299        assert!(
3300            engine.quarantined_mems().is_empty(),
3301            "roster entry disappears after re-attach"
3302        );
3303        // …and the mem serves again in the same process.
3304        let mut sections = indexmap::IndexMap::new();
3305        sections.insert("identity".to_string(), "back".to_string());
3306        sections.insert("purpose".to_string(), "post-repair service".to_string());
3307        engine
3308            .create_entity_with_ctx(
3309                crate::engine::CreateEntityArgs {
3310                    anchors: Vec::new(),
3311                    mem: "specs".to_string(),
3312                    title: "Back".to_string(),
3313                    entity_type: "spec".to_string(),
3314                    sections,
3315                    metadata: indexmap::IndexMap::new(),
3316                    relations: Vec::new(),
3317                    dry_run: false,
3318                },
3319                &crate::vcs::CommitContext::internal(),
3320            )
3321            .expect("reattached mem serves writes");
3322    }
3323
3324    /// Criterion 2 complement: a healthy mem
3325    /// whose entity body wiki-links INTO a quarantined mem loads
3326    /// normally — the link degrades like any dangling cross-mem link
3327    /// (stub target), no cascade failure.
3328    #[test]
3329    fn cross_mem_link_into_quarantined_mem_degrades_without_cascade() {
3330        let tmp = TempDir::new().unwrap();
3331        let healthy_dir = tmp.path().join("healthy");
3332        std::fs::create_dir_all(&healthy_dir).unwrap();
3333        std::fs::write(
3334            healthy_dir.join("linker.md"),
3335            "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\n---\n\
3336             # Linker\n\n## Identity\n\nsee [[badpin:target]] for detail.\n",
3337        )
3338        .unwrap();
3339        let badpin_dir = tmp.path().join("badpin");
3340        std::fs::create_dir_all(&badpin_dir).unwrap();
3341        let mount = |mem: &str, dir: std::path::PathBuf, pin: &str| {
3342            (
3343                Mount {
3344                    mem: mem.to_string(),
3345                    schema: Some(SchemaRef::new(pin, semver::Version::new(1, 0, 0))),
3346                    storage: MountStorage::Folder { path: dir.clone() },
3347                    capability: MountCapability::Write,
3348                    lifecycle: MountLifecycle::Eager,
3349                    cross_linkable: true,
3350                    migration_target: None,
3351                },
3352                Box::new(FilesystemMemWriter::new(dir)) as Box<dyn MemBackend>,
3353            )
3354        };
3355        let engine = Engine::from_mounts(vec![
3356            mount("healthy", healthy_dir, "default"),
3357            mount("badpin", badpin_dir, "ghost"),
3358        ])
3359        .expect("boot survives the cross-mem link into the quarantined mem");
3360        assert_eq!(engine.quarantined_mems().len(), 1);
3361        // The linking entity loaded; its target degrades to a stub /
3362        // dangling link — no cascade, no partial-truth serving of the
3363        // quarantined mem.
3364        let linker = engine
3365            .get_entity(&crate::EntityId::new("healthy", "linker"))
3366            .expect("linking entity loads");
3367        assert_eq!(linker.entity_type, "spec");
3368        assert!(
3369            engine
3370                .get_entity(&crate::EntityId::new("badpin", "target"))
3371                .is_none_or(|e| e.stub),
3372            "the quarantined-side target is at most a stub, never real data"
3373        );
3374    }
3375
3376    /// Complement: a workspace where
3377    /// one mem pins an authored schema still on the retired
3378    /// `propagating_relationships` key boots — that mem quarantines
3379    /// with the rename error as its reason (never workspace-fatal),
3380    /// while healthy mems load and serve.
3381    #[test]
3382    fn old_key_authored_schema_quarantines_pinning_mem_never_workspace() {
3383        let tmp = TempDir::new().unwrap();
3384        let root = tmp.path();
3385        // Workspace marker + two folder mems.
3386        std::fs::create_dir_all(root.join(".memstead").join("state")).unwrap();
3387        std::fs::write(
3388            root.join(".memstead").join("workspace.toml"),
3389            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3390        )
3391        .unwrap();
3392        for m in ["healthy", "oldkey"] {
3393            std::fs::create_dir_all(root.join(m)).unwrap();
3394        }
3395        std::fs::write(
3396            root.join(".memstead").join("state").join("mounts.json"),
3397            r#"{ "format": "memstead-mounts-3", "mounts": [
3398                { "mem": "healthy", "schema": "default@1.1.0", "storage": { "type": "folder", "path": "healthy" }, "capability": "write", "lifecycle": "eager", "cross_linkable": true },
3399                { "mem": "oldkey", "schema": "fieldschema@0.1.0", "storage": { "type": "folder", "path": "oldkey" }, "capability": "write", "lifecycle": "eager", "cross_linkable": true }
3400            ] }"#,
3401        )
3402        .unwrap();
3403        // The authored package, still on the retired key.
3404        let pkg = root
3405            .join(".memstead")
3406            .join("schemas")
3407            .join("fieldschema@0.1.0");
3408        std::fs::create_dir_all(pkg.join("types")).unwrap();
3409        std::fs::write(
3410            pkg.join("schema.yaml"),
3411            "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",
3412        )
3413        .unwrap();
3414        std::fs::write(
3415            pkg.join("types").join("thing.yaml"),
3416            "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",
3417        )
3418        .unwrap();
3419
3420        let engine = Engine::from_workspace_root(root)
3421            .expect("the old-key schema quarantines its mem, never the workspace");
3422        assert!(engine.mounts().iter().any(|m| m.mem == "healthy"));
3423        let q = engine
3424            .quarantine_reason("oldkey")
3425            .expect("oldkey mem is quarantined");
3426        assert_eq!(q.reason_code, "SCHEMA_LOAD_FAILED");
3427        assert!(
3428            q.reason_message.contains("no_self_loop_relationships"),
3429            "quarantine reason is the rename error naming the new key: {}",
3430            q.reason_message
3431        );
3432    }
3433
3434    /// A mem pinned to the new
3435    /// ingest@0.3.0 reports its edge-less entry entities as leaf
3436    /// population, zero false orphans; the prior version (0.2.0) is
3437    /// unchanged — the same entity still counts as an orphan there.
3438    #[test]
3439    fn ingest_0_3_entries_are_leaves_prior_version_unchanged() {
3440        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";
3441        let boot = |pin: &str| {
3442            let tmp = TempDir::new().unwrap();
3443            let dir = tmp.path().to_path_buf();
3444            std::fs::create_dir_all(dir.join(".memstead")).unwrap();
3445            std::fs::write(
3446                dir.join(".memstead").join("config.json"),
3447                format!("{{ \"schema\": \"{pin}\" }}"),
3448            )
3449            .unwrap();
3450            std::fs::write(dir.join("gap.md"), entry_md).unwrap();
3451            let writer = FilesystemMemWriter::new(dir.clone());
3452            let mount = Mount {
3453                mem: "proc".to_string(),
3454                schema: None,
3455                storage: MountStorage::Folder { path: dir },
3456                capability: MountCapability::Write,
3457                lifecycle: MountLifecycle::Eager,
3458                cross_linkable: true,
3459                migration_target: None,
3460            };
3461            let engine =
3462                Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)])
3463                    .unwrap();
3464            (engine.health(), tmp)
3465        };
3466
3467        let (health_new, _t1) = boot("ingest@0.3.0");
3468        assert_eq!(
3469            health_new.orphan_count, 0,
3470            "0.3.0 entry types are leaves — zero false orphans"
3471        );
3472        assert_eq!(
3473            health_new
3474                .leaf_entities_by_type
3475                .get("ingest@0.3.0:coverage_gap"),
3476            Some(&1),
3477            "the population stays visible: {:?}",
3478            health_new.leaf_entities_by_type
3479        );
3480
3481        let (health_old, _t2) = boot("ingest@0.2.0");
3482        assert_eq!(
3483            health_old.orphan_count, 1,
3484            "the prior version's behaviour is unchanged"
3485        );
3486        assert!(health_old.leaf_entities_by_type.is_empty());
3487    }
3488
3489    /// A workspace mixing one broken mem with healthy siblings boots,
3490    /// serves the healthy mems fully, and refuses typed on the
3491    /// quarantined one — the plenum shape (one bad pin, thirteen
3492    /// healthy hostages) can no longer occur. Drives the pin-failure
3493    /// and missing-pin variants in one fixture.
3494    #[test]
3495    fn broken_mem_quarantines_while_healthy_siblings_serve() {
3496        let tmp = TempDir::new().unwrap();
3497        let make_mount = |mem: &str, pin: Option<SchemaRef>| {
3498            let dir = tmp.path().join(mem);
3499            std::fs::create_dir_all(&dir).unwrap();
3500            let writer = FilesystemMemWriter::new(dir.clone());
3501            (
3502                Mount {
3503                    mem: mem.to_string(),
3504                    schema: pin,
3505                    storage: MountStorage::Folder { path: dir },
3506                    capability: MountCapability::Write,
3507                    lifecycle: MountLifecycle::Eager,
3508                    cross_linkable: true,
3509                    migration_target: None,
3510                },
3511                Box::new(writer) as Box<dyn MemBackend>,
3512            )
3513        };
3514        let healthy = make_mount(
3515            "healthy",
3516            Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
3517        );
3518        let bad_pin = make_mount(
3519            "badpin",
3520            Some(SchemaRef::new("ghost", semver::Version::new(1, 0, 0))),
3521        );
3522        let missing_pin = make_mount("nopin", None);
3523        // Backend-failure variant: the mount's storage path is a FILE,
3524        // so the backend's entity walk fails at read time.
3525        let bad_io_path = tmp.path().join("badio");
3526        std::fs::write(&bad_io_path, "not a directory").unwrap();
3527        let bad_io = (
3528            Mount {
3529                mem: "badio".to_string(),
3530                schema: Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
3531                storage: MountStorage::Folder {
3532                    path: bad_io_path.clone(),
3533                },
3534                capability: MountCapability::Write,
3535                lifecycle: MountLifecycle::Eager,
3536                cross_linkable: true,
3537                migration_target: None,
3538            },
3539            Box::new(FilesystemMemWriter::new(bad_io_path)) as Box<dyn MemBackend>,
3540        );
3541        let mut engine = Engine::from_mounts(vec![healthy, bad_pin, missing_pin, bad_io])
3542            .expect("mixed workspace boots");
3543
3544        // Roster: both broken mems, each with its own typed reason.
3545        let codes: std::collections::HashMap<String, String> = engine
3546            .quarantined_mems()
3547            .iter()
3548            .map(|q| (q.mount.mem.clone(), q.reason_code.clone()))
3549            .collect();
3550        assert_eq!(
3551            codes.get("badpin").map(String::as_str),
3552            Some("SCHEMA_NOT_FOUND")
3553        );
3554        assert_eq!(
3555            codes.get("nopin").map(String::as_str),
3556            Some("MEM_CONFIG_INCOMPLETE")
3557        );
3558        assert!(
3559            codes.contains_key("badio"),
3560            "backend read failure quarantines too: {codes:?}"
3561        );
3562
3563        // The healthy mem is fully writable.
3564        let mut sections = indexmap::IndexMap::new();
3565        sections.insert("identity".to_string(), "alive".to_string());
3566        sections.insert("purpose".to_string(), "proof of service".to_string());
3567        let created = engine
3568            .create_entity_with_ctx(
3569                crate::engine::CreateEntityArgs {
3570                    anchors: Vec::new(),
3571                    mem: "healthy".to_string(),
3572                    title: "Alive".to_string(),
3573                    entity_type: "spec".to_string(),
3574                    sections,
3575                    metadata: indexmap::IndexMap::new(),
3576                    relations: Vec::new(),
3577                    dry_run: false,
3578                },
3579                &crate::vcs::CommitContext::internal(),
3580            )
3581            .expect("healthy mem serves writes");
3582        assert_eq!(created.id.to_string(), "healthy--alive");
3583
3584        // Writes against a quarantined mem refuse with the typed code.
3585        let mut sections = indexmap::IndexMap::new();
3586        sections.insert("identity".to_string(), "x".to_string());
3587        let err = engine
3588            .create_entity_with_ctx(
3589                crate::engine::CreateEntityArgs {
3590                    anchors: Vec::new(),
3591                    mem: "badpin".to_string(),
3592                    title: "Nope".to_string(),
3593                    entity_type: "spec".to_string(),
3594                    sections,
3595                    metadata: indexmap::IndexMap::new(),
3596                    relations: Vec::new(),
3597                    dry_run: false,
3598                },
3599                &crate::vcs::CommitContext::internal(),
3600            )
3601            .unwrap_err();
3602        assert_eq!(err.code(), "MEM_QUARANTINED");
3603    }
3604
3605    /// Schema-pin authority: the mem's own per-mem config is the
3606    /// authoritative settled pin. Here the config pins a resolvable
3607    /// schema (`software@0.1.0`) while the workspace mount expects an
3608    /// unresolvable one — boot succeeds (proving the config pin won,
3609    /// not the mount's) and surfaces a `SchemaPinMismatch` warning
3610    /// naming both pins.
3611    #[test]
3612    fn mem_config_schema_is_authoritative_over_mount_pin() {
3613        let tmp = TempDir::new().unwrap();
3614        let mem_dir = tmp.path().to_path_buf();
3615        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
3616        std::fs::write(
3617            mem_dir.join(".memstead").join("config.json"),
3618            r#"{"schema":"software@0.1.0"}"#,
3619        )
3620        .unwrap();
3621        let writer = FilesystemMemWriter::new(mem_dir.clone());
3622        let mount = Mount {
3623            mem: "specs".to_string(),
3624            schema: Some(SchemaRef::new(
3625                "totally-not-a-schema",
3626                semver::Version::new(9, 9, 9),
3627            )),
3628            storage: MountStorage::Folder { path: mem_dir },
3629            capability: MountCapability::Write,
3630            lifecycle: MountLifecycle::Eager,
3631            cross_linkable: true,
3632            migration_target: None,
3633        };
3634        let engine = Engine::from_mounts(vec![(
3635            mount,
3636            Box::new(writer) as Box<dyn MemBackend>,
3637        )])
3638        .expect("config pin software@0.1.0 is authoritative — boot must resolve it despite the unresolvable mount pin");
3639
3640        let mismatch = engine
3641            .load_warnings()
3642            .iter()
3643            .find_map(|w| match w {
3644                WarningHint::SchemaPinMismatch {
3645                    mem,
3646                    config_pin,
3647                    mount_pin,
3648                } => Some((mem.clone(), config_pin.clone(), mount_pin.clone())),
3649                _ => None,
3650            })
3651            .expect("SchemaPinMismatch warning must surface naming both pins");
3652        assert_eq!(mismatch.0, "specs");
3653        assert_eq!(mismatch.1, "software@0.1.0");
3654        assert_eq!(mismatch.2, "totally-not-a-schema@9.9.9");
3655    }
3656
3657    #[test]
3658    fn from_workspace_root_quarantines_git_branch_mount_without_factory() {
3659        let tmp = TempDir::new().unwrap();
3660        let memstead = tmp.path().join(".memstead");
3661        std::fs::create_dir_all(&memstead).unwrap();
3662        std::fs::write(
3663            memstead.join("workspace.toml"),
3664            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
3665        )
3666        .unwrap();
3667        // Hand-craft a state/mounts.json carrying a git-branch mount —
3668        // the folder boot path can't instantiate that backend.
3669        let state_dir = memstead.join("state");
3670        std::fs::create_dir_all(&state_dir).unwrap();
3671        std::fs::write(
3672            state_dir.join("mounts.json"),
3673            r#"{
3674                "format": "memstead-mounts-3",
3675                "mounts": [
3676                    {
3677                        "mem": "specs",
3678                        "schema": "default@1.0.0",
3679                        "storage": { "type": "git-branch", "gitdir": "/tmp/x.git", "branch": "specs" },
3680                        "capability": "write",
3681                        "lifecycle": "eager",
3682                        "cross_linkable": true
3683                    }
3684                ]
3685            }"#,
3686        )
3687        .unwrap();
3688        // Deliberate replacement of the historical wholesale-abort
3689        // assertion: an engine without the git-branch factory meeting a
3690        // git-branch mount QUARANTINES that mem (typed
3691        // UNSUPPORTED_WORKSPACE_SHAPE reason) instead of refusing the
3692        // whole workspace — the judgment is unchanged, the blast
3693        // radius shrinks to the one mount the folder boot path cannot
3694        // serve.
3695        let engine = Engine::from_workspace_root(tmp.path())
3696            .expect("folder boot quarantines the git-branch mount, never fails the workspace");
3697        let roster = engine.quarantined_mems();
3698        assert_eq!(roster.len(), 1);
3699        assert_eq!(roster[0].mount.mem, "specs");
3700        assert_eq!(roster[0].reason_code, "UNSUPPORTED_WORKSPACE_SHAPE");
3701        assert_eq!(engine.unknown_mem_error("specs").code(), "MEM_QUARANTINED");
3702    }
3703
3704    #[test]
3705    fn from_workspace_root_roots_standalone_folder_mem() {
3706        // Standalone collapse: a bare folder mem — `.memstead/config.json`
3707        // pinning a schema, no `workspace.toml` — boots as a one-mount
3708        // workspace instead of refusing with NotInitialised.
3709        let tmp = TempDir::new().unwrap();
3710        let root = tmp.path();
3711        std::fs::create_dir_all(root.join(".memstead")).unwrap();
3712        std::fs::write(
3713            root.join(".memstead").join("config.json"),
3714            r#"{"schema":"default@1.0.0"}"#,
3715        )
3716        .unwrap();
3717        // A collapsed single-mem folder keeps its `.md` files at the root.
3718        std::fs::write(
3719            root.join("hello.md"),
3720            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nStandalone body.\n",
3721        )
3722        .unwrap();
3723
3724        let engine = Engine::from_workspace_root(root)
3725            .expect("a bare folder mem must root as a one-mount workspace");
3726        assert_eq!(engine.status().mem_count, 1, "exactly one mount");
3727        assert!(
3728            engine.status().entity_count >= 1,
3729            "the standalone mem's entity must load"
3730        );
3731    }
3732
3733    #[test]
3734    fn booting_a_workspace_writes_nothing_into_it() {
3735        // A read is a read. Booting an engine over a workspace must not
3736        // touch a single byte of it: not the config, not the mount state,
3737        // and not the authoring meta-schemas, which used to be republished
3738        // on every boot and so stamped a newer binary's copy over whatever
3739        // was on disk. That made a read-only mount, an installed
3740        // third-party mem, and a sealed corpus impossible to read without
3741        // modifying. The meta-schemas now publish from the schema-authoring
3742        // commands instead. This test fails if any boot-time write returns.
3743        let tmp = TempDir::new().unwrap();
3744        let root = tmp.path();
3745        std::fs::create_dir_all(root.join(".memstead").join("meta-schemas")).unwrap();
3746        std::fs::write(
3747            root.join(".memstead").join("config.json"),
3748            r#"{"schema":"default@1.0.0"}"#,
3749        )
3750        .unwrap();
3751        // A deliberately stale meta-schema: byte-different from the embedded
3752        // one, so a returning republish overwrites it and the test sees it.
3753        let stale = root
3754            .join(".memstead")
3755            .join("meta-schemas")
3756            .join("type-definition.schema.json");
3757        std::fs::write(&stale, "{\"title\":\"stale, from an older binary\"}").unwrap();
3758        std::fs::write(
3759            root.join("hello.md"),
3760            "---\ntype: spec\n---\n# Hello\n\n## Identity\n\nStandalone body.\n",
3761        )
3762        .unwrap();
3763
3764        fn snapshot(dir: &Path) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {
3765            let mut out = std::collections::BTreeMap::new();
3766            let mut stack = vec![dir.to_path_buf()];
3767            while let Some(d) = stack.pop() {
3768                for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() {
3769                    let p = entry.path();
3770                    if p.is_dir() {
3771                        stack.push(p);
3772                    } else if let Ok(bytes) = std::fs::read(&p) {
3773                        out.insert(p, bytes);
3774                    }
3775                }
3776            }
3777            out
3778        }
3779
3780        let before = snapshot(root);
3781        let engine = Engine::from_workspace_root(root).expect("the fixture must boot");
3782        assert_eq!(engine.status().mem_count, 1, "fixture sanity: one mount");
3783        let after = snapshot(root);
3784
3785        assert_eq!(
3786            before.keys().collect::<Vec<_>>(),
3787            after.keys().collect::<Vec<_>>(),
3788            "boot created or removed a file in the workspace it read"
3789        );
3790        for (path, bytes) in &before {
3791            assert_eq!(
3792                bytes,
3793                after.get(path).unwrap(),
3794                "boot rewrote {} in the workspace it read",
3795                path.display()
3796            );
3797        }
3798    }
3799
3800    #[test]
3801    fn from_workspace_root_still_rejects_truly_empty_dir() {
3802        // Refusal complement: a directory with neither `workspace.toml` nor a
3803        // `.memstead/config.json` is not a mem — it still refuses, so the
3804        // standalone path never masks a genuinely uninitialised directory.
3805        let tmp = TempDir::new().unwrap();
3806        let err = Engine::from_workspace_root(tmp.path()).unwrap_err();
3807        assert!(
3808            matches!(err, crate::BootError::NotInitialised(_)),
3809            "got {err:?}"
3810        );
3811    }
3812
3813    /// A workspace whose installed schema violates the heading
3814    /// round-trip rule still boots and serves reads; the violation
3815    /// surfaces as a `SCHEMA_HEADING_ROUNDTRIP_VIOLATION` load warning
3816    /// (merged into health), never as a boot failure — refusing at
3817    /// boot would brick every workspace that installed such a schema
3818    /// before the install gate existed.
3819    #[test]
3820    fn boot_keeps_loading_violating_schema_and_surfaces_health_finding() {
3821        let tmp = TempDir::new().unwrap();
3822        let schemas_dir = tmp.path().join("schemas");
3823        let pkg = schemas_dir.join("debate");
3824        std::fs::create_dir_all(pkg.join("types")).unwrap();
3825        std::fs::write(
3826            pkg.join("schema.yaml"),
3827            r#"name: debate
3828version: 0.1.0
3829description: sealed-violator fixture
3830when_to_use: tests
3831types:
3832  - question
3833relationships:
3834  mode: strict
3835  definitions:
3836    - name: PART_OF
3837      description: hier
3838      default_weight: 3.0
3839    - name: _default
3840      description: fallback
3841      default_weight: 1.0
3842community:
3843  resolution: 1.0
3844  seed: 42
3845"#,
3846        )
3847        .unwrap();
3848        std::fs::write(
3849            pkg.join("types").join("question.yaml"),
3850            r#"name: question
3851description: t
3852when_to_use: tests
3853sections:
3854  - key: answers
3855    heading: Answers argued
3856    required: true
3857    search_weight: 10.0
3858    write_rules: []
3859  - key: notes
3860    heading: Notes
3861    required: false
3862    search_weight: 3.0
3863    catch_all: true
3864    write_rules: []
3865metadata_fields: []
3866title_weight: 100.0
3867text_fields:
3868  - answers
3869  - notes
3870hierarchy_relationship: PART_OF
3871no_self_loop_relationships: []
3872updatable_fields:
3873  - title
3874  - answers
3875  - notes
3876health_required_fields:
3877  - answers
3878staleness_threshold_days: 90
3879write_rules: []
3880"#,
3881        )
3882        .unwrap();
3883
3884        let mem_dir = tmp.path().join("mem");
3885        std::fs::create_dir_all(&mem_dir).unwrap();
3886        std::fs::write(
3887            mem_dir.join("q.md"),
3888            "---\ntype: question\n---\n# Q\n\n## Answers argued\n\nTwo answers.\n",
3889        )
3890        .unwrap();
3891
3892        let writer = FilesystemMemWriter::new(mem_dir.clone());
3893        let mount = Mount {
3894            mem: "debate-mem".to_string(),
3895            schema: Some(SchemaRef::new("debate", semver::Version::new(0, 1, 0))),
3896            storage: MountStorage::Folder { path: mem_dir },
3897            capability: MountCapability::Write,
3898            lifecycle: MountLifecycle::Eager,
3899            cross_linkable: true,
3900            migration_target: None,
3901        };
3902        let engine = Engine::from_mounts_with_schemas_dir(
3903            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
3904            Some(&schemas_dir),
3905        )
3906        .expect("a violating sealed schema must keep loading, never refuse boot");
3907
3908        // Reads still serve.
3909        assert!(
3910            engine.status().entity_count >= 1,
3911            "entities load despite the schema violation"
3912        );
3913
3914        // The violation is a health finding with the full tuple.
3915        let hits: Vec<_> = engine
3916            .load_warnings()
3917            .iter()
3918            .filter_map(|w| match w {
3919                WarningHint::SchemaHeadingRoundtripViolation {
3920                    mem,
3921                    schema_ref,
3922                    violations,
3923                } => Some((mem.clone(), schema_ref.clone(), violations.clone())),
3924                _ => None,
3925            })
3926            .collect();
3927        assert_eq!(
3928            hits.len(),
3929            1,
3930            "exactly one schema-level finding; all warnings = {:?}",
3931            engine.load_warnings()
3932        );
3933        let (mem, schema_ref, violations) = &hits[0];
3934        assert_eq!(mem, "debate-mem");
3935        assert_eq!(schema_ref, "debate@0.1.0");
3936        assert_eq!(violations.len(), 1);
3937        assert_eq!(violations[0].type_name, "question");
3938        assert_eq!(violations[0].key, "answers");
3939        assert_eq!(violations[0].heading, "Answers argued");
3940        assert_eq!(violations[0].derived_key, "answers_argued");
3941    }
3942
3943    /// The other half of "still serves reads AND writes": a mem pinned
3944    /// to a sealed heading-round-trip-violating schema accepts writes.
3945    /// The update commits (refusal complement: it is NOT refused), the
3946    /// schema-level health finding persists after the write, and the
3947    /// write-path `SECTION_HEADING_DIVERGENCE` warning fires where its
3948    /// condition holds (the file carries a heading that derives to the
3949    /// written key while the schema declares a different heading text).
3950    #[test]
3951    fn sealed_violator_mem_still_serves_writes() {
3952        // Same fixture as the read test above.
3953        let tmp = TempDir::new().unwrap();
3954        let schemas_dir = tmp.path().join("schemas");
3955        let pkg = schemas_dir.join("debate");
3956        std::fs::create_dir_all(pkg.join("types")).unwrap();
3957        std::fs::write(
3958            pkg.join("schema.yaml"),
3959            r#"name: debate
3960version: 0.1.0
3961description: sealed-violator fixture
3962when_to_use: tests
3963types:
3964  - question
3965relationships:
3966  mode: strict
3967  definitions:
3968    - name: PART_OF
3969      description: hier
3970      default_weight: 3.0
3971    - name: _default
3972      description: fallback
3973      default_weight: 1.0
3974community:
3975  resolution: 1.0
3976  seed: 42
3977"#,
3978        )
3979        .unwrap();
3980        std::fs::write(
3981            pkg.join("types").join("question.yaml"),
3982            r#"name: question
3983description: t
3984when_to_use: tests
3985sections:
3986  - key: answers
3987    heading: Answers argued
3988    required: true
3989    search_weight: 10.0
3990    write_rules: []
3991  - key: notes
3992    heading: Notes
3993    required: false
3994    search_weight: 3.0
3995    catch_all: true
3996    write_rules: []
3997metadata_fields: []
3998title_weight: 100.0
3999text_fields:
4000  - answers
4001  - notes
4002hierarchy_relationship: PART_OF
4003no_self_loop_relationships: []
4004updatable_fields:
4005  - title
4006  - answers
4007  - notes
4008health_required_fields:
4009  - answers
4010staleness_threshold_days: 90
4011write_rules: []
4012"#,
4013        )
4014        .unwrap();
4015
4016        let mem_dir = tmp.path().join("mem");
4017        std::fs::create_dir_all(&mem_dir).unwrap();
4018        // The file's own heading "Answers" derives to the key
4019        // `answers`, differing from the schema's declared
4020        // "Answers argued" — the divergence-warning condition.
4021        std::fs::write(
4022            mem_dir.join("q.md"),
4023            "---\ntype: question\n---\n# Q\n\n## Answers\n\nTwo answers.\n",
4024        )
4025        .unwrap();
4026
4027        let writer = FilesystemMemWriter::new(mem_dir.clone());
4028        let mount = Mount {
4029            mem: "debate-mem".to_string(),
4030            schema: Some(SchemaRef::new("debate", semver::Version::new(0, 1, 0))),
4031            storage: MountStorage::Folder { path: mem_dir },
4032            capability: MountCapability::Write,
4033            lifecycle: MountLifecycle::Eager,
4034            cross_linkable: true,
4035            migration_target: None,
4036        };
4037        let mut engine = Engine::from_mounts_with_schemas_dir(
4038            vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
4039            Some(&schemas_dir),
4040        )
4041        .expect("a violating sealed schema must keep loading");
4042
4043        let id = crate::EntityId::new("debate-mem", "q");
4044        let hash = engine.get_entity(&id).unwrap().content_hash.clone();
4045        let mut sections = indexmap::IndexMap::new();
4046        sections.insert("answers".to_string(), "Updated answers body.".to_string());
4047        let outcome = engine
4048            .update_entity(
4049                crate::engine::UpdateEntityArgs {
4050                    anchors: Vec::new(),
4051                    anchors_unset: Vec::new(),
4052                    id: id.clone(),
4053                    expected_hash: Some(hash),
4054                    sections,
4055                    append_sections: indexmap::IndexMap::new(),
4056                    patch_sections: indexmap::IndexMap::new(),
4057                    sections_unset: Vec::new(),
4058                    metadata: indexmap::IndexMap::new(),
4059                    metadata_unset: Vec::new(),
4060                    declare_relations: Vec::new(),
4061                    dry_run: false,
4062                    relations_unset: Vec::new(),
4063                },
4064                crate::vcs::Actor::Cli,
4065                None,
4066                None,
4067            )
4068            .expect("a write against a sealed-violator mem must NOT be refused");
4069        assert!(!outcome.write_id.is_empty(), "the write commits");
4070        assert!(
4071            outcome
4072                .warnings
4073                .iter()
4074                .any(|w| w.code() == "SECTION_HEADING_DIVERGENCE"),
4075            "the write-path divergence warning fires where its condition holds: {:?}",
4076            outcome.warnings
4077        );
4078
4079        // The schema-level finding persists after the write.
4080        assert!(
4081            engine.load_warnings().iter().any(|w| matches!(
4082                w,
4083                WarningHint::SchemaHeadingRoundtripViolation { mem, .. } if mem == "debate-mem"
4084            )),
4085            "the health finding persists across writes"
4086        );
4087        // The written content is durably on disk and survives the
4088        // reparse — under the catch-all, because the violating schema's
4089        // declared heading cannot round-trip to the written key. That
4090        // fork is exactly what the divergence warning announced (and
4091        // what the persisting health finding tells the operator to fix
4092        // at the schema); the "serves writes" guarantee is that the
4093        // write lands and nothing refuses, not that a broken schema
4094        // routes content correctly.
4095        let entity = engine.get_entity(&id).unwrap();
4096        assert!(
4097            entity
4098                .sections
4099                .values()
4100                .any(|s| s.contains("Updated answers body.")),
4101            "written content survives the round-trip (in the catch-all): {:?}",
4102            entity.sections
4103        );
4104    }
4105
4106    /// A search `mem` filter naming no visible mem refuses typed
4107    /// `UNKNOWN_MEM` — matching every other mem-naming surface — while a
4108    /// quarantined mem keeps its established typed refusal and a VALID
4109    /// mem with no matches still returns success with 0 hits. Absence of
4110    /// mem and absence of matches are never the same answer
4111    /// (an earlier plan, decision 4).
4112    #[test]
4113    fn search_mem_filter_gates_against_visible_roster() {
4114        use crate::vcs::Actor;
4115        use crate::workspace_store::WorkspaceStoreAdapter;
4116        use indexmap::IndexMap;
4117
4118        let tmp = TempDir::new().unwrap();
4119        let mem_dir = tmp.path().join("mem");
4120        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
4121        std::fs::write(
4122            mem_dir.join(".memstead").join("config.json"),
4123            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
4124        )
4125        .unwrap();
4126        let memstead = tmp.path().join(".memstead");
4127        std::fs::create_dir_all(&memstead).unwrap();
4128        std::fs::write(
4129            memstead.join("workspace.toml"),
4130            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
4131        )
4132        .unwrap();
4133        crate::FileWorkspaceStore::new()
4134            .save_state(
4135                tmp.path(),
4136                &crate::workspace::Workspace {
4137                    mounts: vec![folder_mount("specs", mem_dir.clone())],
4138                    settings: crate::workspace::WorkspaceSettings::default(),
4139                },
4140            )
4141            .unwrap();
4142        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
4143        let mut sections = IndexMap::new();
4144        sections.insert(
4145            "identity".to_string(),
4146            "Zebra searching fixture.".to_string(),
4147        );
4148        sections.insert("purpose".to_string(), "Search gate test.".to_string());
4149        engine
4150            .create_entity(
4151                crate::CreateEntityArgs {
4152                    mem: "specs".to_string(),
4153                    title: "Zebra".to_string(),
4154                    entity_type: "spec".to_string(),
4155                    sections,
4156                    metadata: IndexMap::new(),
4157                    relations: Vec::new(),
4158                    anchors: Vec::new(),
4159                    dry_run: false,
4160                },
4161                Actor::Agent,
4162                None,
4163                None,
4164            )
4165            .unwrap();
4166
4167        let scope = |mem: Option<&str>, term: &str| crate::ops::SearchScope {
4168            query: Some(crate::ops::Query {
4169                any: vec![term.to_string()],
4170                ..Default::default()
4171            }),
4172            mem: mem.map(str::to_string),
4173            ..Default::default()
4174        };
4175
4176        // Nonexistent mem → typed UNKNOWN_MEM, never success-with-0-hits.
4177        let err = engine
4178            .search(&scope(Some("no-such-mem"), "zebra"))
4179            .expect_err("a nonexistent mem filter must refuse");
4180        assert_eq!(err.code(), "UNKNOWN_MEM", "got {err:?}");
4181
4182        // Valid mem, matching query → hits.
4183        let hit = engine.search(&scope(Some("specs"), "zebra")).unwrap();
4184        assert!(hit.total >= 1, "the fixture entity matches: {hit:?}");
4185
4186        // Valid mem, no matches → success with 0 hits (the gate
4187        // distinguishes absence of mem from absence of matches).
4188        let none = engine
4189            .search(&scope(Some("specs"), "quixotic-nonword"))
4190            .unwrap();
4191        assert_eq!(none.total, 0, "{none:?}");
4192    }
4193
4194    // ---- Engine::reload_one_mem -----------------------------------
4195
4196    // ---- lazy mounts (flywheel W7/01) -----------------------------
4197
4198    fn lazy_folder_mount(mem: &str, path: std::path::PathBuf) -> Mount {
4199        Mount {
4200            lifecycle: MountLifecycle::Lazy,
4201            ..folder_mount(mem, path)
4202        }
4203    }
4204
4205    fn write_spec(dir: &Path, slug: &str, title: &str, extra: &str) {
4206        std::fs::write(
4207            dir.join(format!("{slug}.md")),
4208            format!("---\ntype: spec\n---\n# {title}\n\n## Identity\n\nBody.\n{extra}"),
4209        )
4210        .unwrap();
4211    }
4212
4213    fn two_mem_dirs(tmp: &TempDir) -> (std::path::PathBuf, std::path::PathBuf) {
4214        let eager_dir = tmp.path().join("eag");
4215        let lazy_dir = tmp.path().join("laz");
4216        std::fs::create_dir_all(&eager_dir).unwrap();
4217        std::fs::create_dir_all(&lazy_dir).unwrap();
4218        write_spec(&eager_dir, "alpha", "Alpha", "");
4219        write_spec(&lazy_dir, "omega", "Omega", "");
4220        (eager_dir, lazy_dir)
4221    }
4222
4223    fn mixed_engine(eager_dir: &Path, lazy_dir: &Path) -> Engine {
4224        Engine::from_mounts(vec![
4225            (
4226                folder_mount("eag", eager_dir.to_path_buf()),
4227                Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf())) as Box<dyn MemBackend>,
4228            ),
4229            (
4230                lazy_folder_mount("laz", lazy_dir.to_path_buf()),
4231                Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf())) as Box<dyn MemBackend>,
4232            ),
4233        ])
4234        .unwrap()
4235    }
4236
4237    /// The lazy lifecycle defers exactly the entity load: boot carries
4238    /// the mem on the roster with its schema resolved but no entities;
4239    /// the first operation touching it (the `reload_if_stale` funnel)
4240    /// triggers the load; afterwards the mem behaves identically to an
4241    /// eager mount and the deferred state is gone for good.
4242    #[test]
4243    fn lazy_mount_defers_and_first_read_loads() {
4244        let tmp = TempDir::new().unwrap();
4245        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4246        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4247
4248        // Boot: eager loaded, lazy on the roster but deferred.
4249        assert!(
4250            engine
4251                .get_entity(&crate::EntityId::new("eag", "alpha"))
4252                .is_some()
4253        );
4254        assert_eq!(engine.deferred_mems(), vec!["laz"]);
4255        assert!(engine.mem_is_deferred("laz"));
4256        assert!(
4257            engine
4258                .get_entity(&crate::EntityId::new("laz", "omega"))
4259                .is_none(),
4260            "deferred mem's entities are not in the store yet"
4261        );
4262        // Never absent: the mount roster and schema map both carry it.
4263        assert!(engine.schema_for("laz").is_some());
4264
4265        // First read triggers the load through the operation funnel.
4266        engine.reload_if_stale(Some("laz"));
4267        assert!(engine.deferred_mems().is_empty());
4268        let omega = engine
4269            .get_entity(&crate::EntityId::new("laz", "omega"))
4270            .expect("first read loads the mem");
4271        assert_eq!(omega.title, "Omega");
4272
4273        // Identical to eager from here on: a write round-trips.
4274        let (actor, client) = cli_actor();
4275        engine
4276            .create_entity(
4277                empty_create_args("laz", "Later"),
4278                actor,
4279                Some(&client),
4280                None,
4281            )
4282            .unwrap();
4283        assert!(
4284            engine
4285                .get_entity(&crate::EntityId::new("laz", "later"))
4286                .is_some()
4287        );
4288    }
4289
4290    /// An operation scoped to an eager mem never loads a lazy sibling
4291    /// as a side effect; a workspace-scoped funnel pass loads every
4292    /// deferred mem so no answer computes over a partial store.
4293    #[test]
4294    fn scoped_operation_never_loads_lazy_sibling() {
4295        let tmp = TempDir::new().unwrap();
4296        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4297        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4298
4299        engine.reload_if_stale(Some("eag"));
4300        assert_eq!(
4301            engine.deferred_mems(),
4302            vec!["laz"],
4303            "an eager-scoped operation must not load the lazy sibling"
4304        );
4305
4306        engine.reload_if_stale(None);
4307        assert!(
4308            engine.deferred_mems().is_empty(),
4309            "a workspace-scoped pass loads every deferred mem"
4310        );
4311    }
4312
4313    /// A deferred load that fails quarantines the mem at the moment of
4314    /// first read, with the same typed reporting an eager boot failure
4315    /// produces — never an empty-mem impression.
4316    #[test]
4317    fn lazy_load_failure_quarantines_typed() {
4318        let tmp = TempDir::new().unwrap();
4319        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4320        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4321
4322        // The backend's tree is destroyed between boot and first read —
4323        // a plain file now sits where the mem directory was, so the
4324        // entity walk errors rather than reading an empty directory.
4325        std::fs::remove_dir_all(&lazy_dir).unwrap();
4326        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4327        engine.reload_if_stale(Some("laz"));
4328
4329        let q = engine
4330            .quarantine_reason("laz")
4331            .expect("failed deferred load quarantines, never serves empty");
4332        assert!(!q.reason_code.is_empty());
4333        assert!(
4334            !engine.mem_names().contains(&"laz"),
4335            "a quarantined mem leaves the serving roster"
4336        );
4337        assert!(engine.deferred_mems().is_empty());
4338    }
4339
4340    /// Quarantine-ENTRY invalidation pin (flywheel W8/01, first
4341    /// grade's refutation): entering quarantine from a failed deferred
4342    /// load removes the mem's schema (epoch bump) — a search memo
4343    /// filled beforehand is then stale-keyed and MUST clear, or the
4344    /// next search trips the memo-key debug_assert (the grade's live
4345    /// repro). Same rule pinned for the reattach-failure branch by
4346    /// re-failing the reattach.
4347    #[test]
4348    fn quarantine_entry_invalidates_both_memos() {
4349        let tmp = TempDir::new().unwrap();
4350        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4351        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4352
4353        // Fill both memos while the lazy mem is still deferred.
4354        let _ = engine.communities();
4355        let _ = engine.search_indexes();
4356        assert!(engine.search_indexes_memo.get().is_some());
4357
4358        // Destroy the backend; the first read quarantines the mem.
4359        std::fs::remove_dir_all(&lazy_dir).unwrap();
4360        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4361        engine.reload_if_stale(Some("laz"));
4362        assert!(engine.quarantine_reason("laz").is_some());
4363        assert!(
4364            engine.search_indexes_memo.get().is_none(),
4365            "quarantine entry bumps the schemas epoch — the search memo must clear"
4366        );
4367        assert!(
4368            engine.community_memo.get().is_none(),
4369            "quarantine entry must clear the community memo too"
4370        );
4371        // The next search must not trip the memo-key assert.
4372        let _ = engine.search_indexes();
4373
4374        // Reattach FAILURE (backend still broken): same rule.
4375        let _ = engine.communities();
4376        let _ = engine.search_indexes();
4377        let _ = engine.reload_one_mem("laz");
4378        assert!(engine.quarantine_reason("laz").is_some());
4379        assert!(
4380            engine.search_indexes_memo.get().is_none(),
4381            "a failed reattach bumps the epoch — the search memo must clear"
4382        );
4383        let _ = engine.search_indexes();
4384    }
4385
4386    /// Quarantine-reattach regression pin (flywheel W8/01, criterion
4387    /// 2's complement): the reattach path routes through the one-mem
4388    /// reload, which invalidates BOTH derived memos — pinned so
4389    /// incremental maintenance can never silently degrade it.
4390    #[test]
4391    fn quarantine_reattach_invalidates_both_memos() {
4392        let tmp = TempDir::new().unwrap();
4393        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4394        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4395
4396        // Quarantine the lazy mem: destroy its backend, trigger load.
4397        std::fs::remove_dir_all(&lazy_dir).unwrap();
4398        std::fs::write(&lazy_dir, b"not a directory").unwrap();
4399        engine.reload_if_stale(Some("laz"));
4400        assert!(engine.quarantine_reason("laz").is_some());
4401
4402        // Fill both memos while the mem sits quarantined.
4403        let _ = engine.communities();
4404        let _ = engine.search_indexes();
4405        assert!(engine.community_memo.get().is_some());
4406        assert!(engine.search_indexes_memo.get().is_some());
4407
4408        // Restore the backend and reattach via the reload path.
4409        std::fs::remove_file(&lazy_dir).unwrap();
4410        std::fs::create_dir_all(&lazy_dir).unwrap();
4411        write_spec(&lazy_dir, "omega", "Omega", "");
4412        engine
4413            .reload_one_mem("laz")
4414            .expect("reattach succeeds once the backend is back");
4415        assert!(engine.quarantine_reason("laz").is_none());
4416
4417        // Both memos cleared — the reattached mem's entities must be
4418        // visible to the next partition and the next search.
4419        assert!(
4420            engine.community_memo.get().is_none(),
4421            "reattach must invalidate the community memo"
4422        );
4423        assert!(
4424            engine.search_indexes_memo.get().is_none(),
4425            "reattach must invalidate the search memo"
4426        );
4427    }
4428
4429    /// The lazy load runs the same validation gauntlet an eager boot
4430    /// runs: content an eager boot warns about produces the SAME
4431    /// warning when its mem loads lazily — deferral changes when, not
4432    /// whether.
4433    #[test]
4434    fn lazy_load_runs_the_same_validation_gauntlet() {
4435        let tmp = TempDir::new().unwrap();
4436        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4437        // Hand-authored invalid relation in the LAZY mem.
4438        std::fs::write(
4439            lazy_dir.join("bad.md"),
4440            "---\ntype: spec\n---\n# Bad\n\n## Identity\n\nx.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[laz--omega]]\n",
4441        )
4442        .unwrap();
4443
4444        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4445        let warned_before = engine
4446            .load_warnings()
4447            .iter()
4448            .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }));
4449        engine.reload_if_stale(Some("laz"));
4450        let warned_after = engine
4451            .load_warnings()
4452            .iter()
4453            .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. }));
4454        assert!(
4455            !warned_before && warned_after,
4456            "the gauntlet fires at load time: before={warned_before} after={warned_after}, \
4457             warnings: {:?}",
4458            engine.load_warnings()
4459        );
4460        // And the offending relation was dropped, as an eager boot drops it.
4461        let bad = engine
4462            .get_entity(&crate::EntityId::new("laz", "bad"))
4463            .unwrap();
4464        assert!(bad.relationships.is_empty());
4465    }
4466
4467    /// The destructive guard sees referrers living in DEFERRED mems:
4468    /// deleting an entity whose incoming references originate in a lazy,
4469    /// not-yet-loaded mem refuses `HAS_INCOMING_REFS` exactly as an
4470    /// eager boot refuses it. The third final grade demonstrated the
4471    /// counterexample live — the scoped reload left the referrer's mem
4472    /// unloaded and the delete destroyed the entity an eager boot
4473    /// protects. The guard now takes the full load first.
4474    #[test]
4475    fn delete_guard_sees_referrers_in_deferred_mems() {
4476        use crate::engine::{DeleteEntityArgs, RelateEntityArgs};
4477
4478        let tmp = TempDir::new().unwrap();
4479        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4480        let (actor, client) = cli_actor();
4481
4482        // Author the cross-mem referrer through the mutation surface
4483        // while both mems are eager (with the cross-link grant), so the
4484        // persisted relation is exactly what a real workspace carries.
4485        {
4486            let mut authoring = Engine::from_mounts(vec![
4487                (
4488                    folder_mount("eag", eager_dir.to_path_buf()),
4489                    Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf()))
4490                        as Box<dyn MemBackend>,
4491                ),
4492                (
4493                    folder_mount("laz", lazy_dir.to_path_buf()),
4494                    Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf()))
4495                        as Box<dyn MemBackend>,
4496                ),
4497            ])
4498            .unwrap();
4499            let mut settings = crate::workspace::WorkspaceSettings::default();
4500            settings.cross_mem_links.insert(
4501                "laz".to_string(),
4502                memstead_schema::workspace_config::CrossLinkValue::List(vec!["eag".to_string()]),
4503            );
4504            authoring.set_settings(settings);
4505            authoring
4506                .relate_entity(
4507                    RelateEntityArgs {
4508                        source: crate::EntityId::new("laz", "omega"),
4509                        expected_hash: None,
4510                        rel_type: "USES".to_string(),
4511                        target: crate::EntityId::new("eag", "alpha"),
4512                        remove: false,
4513                        description: None,
4514                        dry_run: false,
4515                    },
4516                    actor,
4517                    Some(&client),
4518                    None,
4519                )
4520                .expect("cross-mem relate lands under the grant");
4521        }
4522
4523        // Fresh boot with the REFERRER's mem lazy: the incoming edge
4524        // into `eag--alpha` lives in an unloaded mem. The guard must
4525        // still see it — full load before destructive adjudication.
4526        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4527        assert!(engine.mem_is_deferred("laz"));
4528        let err = engine
4529            .delete_entity(
4530                DeleteEntityArgs {
4531                    id: crate::EntityId::new("eag", "alpha"),
4532                    expected_hash: None,
4533                },
4534                actor,
4535                Some(&client),
4536                None,
4537            )
4538            .expect_err("a referenced entity must refuse deletion, lazy referrer or not");
4539        assert!(
4540            matches!(err, EngineError::HasIncomingRefs { .. }),
4541            "expected HAS_INCOMING_REFS, got {err:?}"
4542        );
4543        assert!(
4544            engine
4545                .get_entity(&crate::EntityId::new("eag", "alpha"))
4546                .is_some(),
4547            "the entity survives"
4548        );
4549    }
4550
4551    /// The write-time acyclicity guard sees edges living in DEFERRED
4552    /// mems: an add that closes a cycle THROUGH a lazy, not-yet-loaded
4553    /// mem refuses `RELATIONSHIP_CYCLE` exactly as an eager boot
4554    /// refuses it. The fourth final grade demonstrated the
4555    /// counterexample on a three-mem chain — the mid-path edge lived on
4556    /// the lazy mem's entity, the walk over the endpoint mems missed
4557    /// it, the cycle landed, and the next eager boot dropped an
4558    /// INNOCENT pre-existing edge to break it. A two-mem fixture would
4559    /// pass vacuously (relate loads both endpoint mems); three mems
4560    /// with the middle one lazy is the discriminating shape.
4561    #[test]
4562    fn acyclicity_guard_sees_edges_in_deferred_mems() {
4563        use crate::engine::RelateEntityArgs;
4564        use memstead_schema::workspace_config::CrossLinkValue;
4565
4566        let tmp = TempDir::new().unwrap();
4567        let dirs: Vec<std::path::PathBuf> = ["ma", "mb", "mc"]
4568            .iter()
4569            .map(|m| {
4570                let d = tmp.path().join(m);
4571                std::fs::create_dir_all(&d).unwrap();
4572                d
4573            })
4574            .collect();
4575        write_spec(&dirs[0], "node", "Node A", "");
4576        write_spec(&dirs[1], "node", "Node B", "");
4577        write_spec(&dirs[2], "node", "Node C", "");
4578
4579        let mounts = |lazy_mid: bool| -> Vec<(Mount, Box<dyn MemBackend>)> {
4580            ["ma", "mb", "mc"]
4581                .iter()
4582                .zip(dirs.iter())
4583                .map(|(m, d)| {
4584                    let mut mount = folder_mount(m, d.clone());
4585                    if lazy_mid && *m == "ma" {
4586                        mount.lifecycle = MountLifecycle::Lazy;
4587                    }
4588                    (
4589                        mount,
4590                        Box::new(FilesystemMemWriter::new(d.clone())) as Box<dyn MemBackend>,
4591                    )
4592                })
4593                .collect()
4594        };
4595        let grants = || {
4596            let mut settings = crate::workspace::WorkspaceSettings::default();
4597            for (from, to) in [("mb", "ma"), ("ma", "mc"), ("mc", "mb")] {
4598                settings
4599                    .cross_mem_links
4600                    .insert(from.to_string(), CrossLinkValue::List(vec![to.to_string()]));
4601            }
4602            settings
4603        };
4604        let relate = |engine: &mut Engine, from: &str, to: &str| {
4605            let (actor, client) = cli_actor();
4606            engine.relate_entity(
4607                RelateEntityArgs {
4608                    source: crate::EntityId::new(from, "node"),
4609                    expected_hash: None,
4610                    rel_type: "DEPENDS_ON".to_string(),
4611                    target: crate::EntityId::new(to, "node"),
4612                    remove: false,
4613                    description: None,
4614                    dry_run: false,
4615                },
4616                actor,
4617                Some(&client),
4618                None,
4619            )
4620        };
4621
4622        // Author the chain mb→ma→mc while everything is eager.
4623        {
4624            let mut authoring = Engine::from_mounts(mounts(false)).unwrap();
4625            authoring.set_settings(grants());
4626            relate(&mut authoring, "mb", "ma").expect("mb→ma lands");
4627            relate(&mut authoring, "ma", "mc").expect("ma→mc lands");
4628        }
4629
4630        // Fresh boot with the MID-PATH mem lazy: closing mc→mb would
4631        // complete the cycle mb→ma→mc→mb through the unloaded mem.
4632        let mut engine = Engine::from_mounts(mounts(true)).unwrap();
4633        engine.set_settings(grants());
4634        assert!(engine.mem_is_deferred("ma"), "the mid-path mem is deferred");
4635        let err = relate(&mut engine, "mc", "mb")
4636            .expect_err("a cycle through a deferred mem must refuse, as eager refuses");
4637        assert!(
4638            matches!(err, EngineError::RelationshipCycle { .. }),
4639            "expected RELATIONSHIP_CYCLE, got {err:?}"
4640        );
4641    }
4642
4643    /// The BATCH relate path runs the same acyclicity guard over the
4644    /// same full store: a two-entry batch (the shape MCP routes to
4645    /// `batch_relate`) whose first entry closes a cycle through a
4646    /// deferred mid-path mem is refused whole, exactly as an eager
4647    /// boot refuses it. The fifth lazy-mount grade demonstrated the
4648    /// complement live: without the batch-path full load the cycle
4649    /// committed silently.
4650    #[test]
4651    fn batch_acyclicity_guard_sees_edges_in_deferred_mems() {
4652        use crate::engine::RelateEntityArgs;
4653        use memstead_schema::workspace_config::CrossLinkValue;
4654
4655        let tmp = TempDir::new().unwrap();
4656        let dirs: Vec<std::path::PathBuf> = ["ma", "mb", "mc"]
4657            .iter()
4658            .map(|m| {
4659                let d = tmp.path().join(m);
4660                std::fs::create_dir_all(&d).unwrap();
4661                d
4662            })
4663            .collect();
4664        write_spec(&dirs[0], "node", "Node A", "");
4665        write_spec(&dirs[1], "node", "Node B", "");
4666        write_spec(&dirs[2], "node", "Node C", "");
4667        // A second entity in mc so the batch's second entry can be an
4668        // intra-mem edge that touches ONLY mc — a target in any other
4669        // mem would put that mem on the batch's touched-mems reload
4670        // list and load it by that route, masking the guard under test.
4671        write_spec(&dirs[2], "node2", "Node C2", "");
4672
4673        let mounts = |lazy_mid: bool| -> Vec<(Mount, Box<dyn MemBackend>)> {
4674            ["ma", "mb", "mc"]
4675                .iter()
4676                .zip(dirs.iter())
4677                .map(|(m, d)| {
4678                    let mut mount = folder_mount(m, d.clone());
4679                    if lazy_mid && *m == "ma" {
4680                        mount.lifecycle = MountLifecycle::Lazy;
4681                    }
4682                    (
4683                        mount,
4684                        Box::new(FilesystemMemWriter::new(d.clone())) as Box<dyn MemBackend>,
4685                    )
4686                })
4687                .collect()
4688        };
4689        let grants = || {
4690            let mut settings = crate::workspace::WorkspaceSettings::default();
4691            for (from, to) in [("mb", "ma"), ("ma", "mc"), ("mc", "mb")] {
4692                settings
4693                    .cross_mem_links
4694                    .insert(from.to_string(), CrossLinkValue::List(vec![to.to_string()]));
4695            }
4696            settings
4697        };
4698        let relate_args = |from: &str, to: &str| RelateEntityArgs {
4699            source: crate::EntityId::new(from, "node"),
4700            expected_hash: None,
4701            rel_type: "DEPENDS_ON".to_string(),
4702            target: crate::EntityId::new(to, "node"),
4703            remove: false,
4704            description: None,
4705            dry_run: false,
4706        };
4707
4708        // Author the chain mb→ma→mc while everything is eager.
4709        {
4710            let (actor, client) = cli_actor();
4711            let mut authoring = Engine::from_mounts(mounts(false)).unwrap();
4712            authoring.set_settings(grants());
4713            authoring
4714                .relate_entity(relate_args("mb", "ma"), actor, Some(&client), None)
4715                .expect("mb→ma lands");
4716            let (actor2, client2) = cli_actor();
4717            authoring
4718                .relate_entity(relate_args("ma", "mc"), actor2, Some(&client2), None)
4719                .expect("ma→mc lands");
4720        }
4721
4722        // Fresh boot with the MID-PATH mem lazy; a two-entry batch
4723        // whose first edge mc→mb completes the cycle mb→ma→mc→mb
4724        // through the unloaded mem must refuse whole.
4725        let mut engine = Engine::from_mounts(mounts(true)).unwrap();
4726        engine.set_settings(grants());
4727        assert!(engine.mem_is_deferred("ma"), "the mid-path mem is deferred");
4728        let (actor, client) = cli_actor();
4729        let result = engine
4730            .batch_relate(
4731                vec![
4732                    (relate_args("mc", "mb"), None),
4733                    // The second entry makes the batch two entries —
4734                    // the shape MCP routes to `batch_relate` — and is
4735                    // an intra-mem edge inside mc: it touches no other
4736                    // mem (so it cannot load ma via the touched-mems
4737                    // reload) and closes no cycle of its own.
4738                    (
4739                        RelateEntityArgs {
4740                            source: crate::EntityId::new("mc", "node2"),
4741                            expected_hash: None,
4742                            rel_type: "DEPENDS_ON".to_string(),
4743                            target: crate::EntityId::new("mc", "node"),
4744                            remove: false,
4745                            description: None,
4746                            dry_run: false,
4747                        },
4748                        None,
4749                    ),
4750                ],
4751                actor,
4752                Some(&client),
4753                false,
4754            )
4755            .expect("the batch call itself returns a report-all envelope");
4756        assert!(
4757            !result.applied,
4758            "a batch closing a cycle through a deferred mem must refuse, as eager refuses; got applied with {} succeeded",
4759            result.succeeded
4760        );
4761    }
4762
4763    /// Write-time cross-mem target verification (flywheel W7/02): a
4764    /// relate into a DEFERRED Write mem verifies the target against
4765    /// storage without loading the mem. A storage-verified target is
4766    /// admitted with a LoadTime stub and NO auto-stub warning (the
4767    /// entity exists — it resolves when the mem loads); a genuinely
4768    /// absent target keeps today's forward-reference mechanic, warning
4769    /// included. Either way the target mem stays deferred.
4770    #[test]
4771    fn relate_into_deferred_mem_verifies_against_storage_without_load() {
4772        use crate::engine::RelateEntityArgs;
4773        use memstead_schema::workspace_config::CrossLinkValue;
4774
4775        let tmp = TempDir::new().unwrap();
4776        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4777        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4778        let mut settings = crate::workspace::WorkspaceSettings::default();
4779        settings.cross_mem_links.insert(
4780            "eag".to_string(),
4781            CrossLinkValue::List(vec!["laz".to_string()]),
4782        );
4783        engine.set_settings(settings);
4784
4785        let relate = |engine: &mut Engine, to: &str| {
4786            let (actor, client) = cli_actor();
4787            engine.relate_entity(
4788                RelateEntityArgs {
4789                    source: crate::EntityId::new("eag", "alpha"),
4790                    expected_hash: None,
4791                    rel_type: "SUPPORTS".to_string(),
4792                    target: crate::EntityId::new("laz", to),
4793                    remove: false,
4794                    description: None,
4795                    dry_run: false,
4796                },
4797                actor,
4798                Some(&client),
4799                None,
4800            )
4801        };
4802
4803        // Storage-verified target: laz--omega exists on disk.
4804        let outcome = relate(&mut engine, "omega").expect("verified target admits");
4805        assert!(
4806            engine.mem_is_deferred("laz"),
4807            "verification never loads the mem"
4808        );
4809        assert!(
4810            !outcome
4811                .warnings
4812                .iter()
4813                .any(|w| matches!(w, WarningHint::AutoStubCreated { .. })),
4814            "a storage-verified target is not an auto-stub case: {:?}",
4815            outcome.warnings
4816        );
4817        let stub = engine
4818            .store()
4819            .get(&crate::EntityId::new("laz", "omega"))
4820            .expect("until-load stub present");
4821        assert!(stub.stub);
4822        assert_eq!(
4823            stub.stub_kind,
4824            Some(crate::entity::StubKind::LoadTime),
4825            "verified-in-storage stub carries the load-time kind"
4826        );
4827
4828        // Genuinely absent target: forward-reference mechanic intact.
4829        let outcome = relate(&mut engine, "missing").expect("absent Write-mem target auto-stubs");
4830        assert!(engine.mem_is_deferred("laz"), "still no load");
4831        assert!(
4832            outcome
4833                .warnings
4834                .iter()
4835                .any(|w| matches!(w, WarningHint::AutoStubCreated { .. })),
4836            "absent target keeps the auto-stub warning: {:?}",
4837            outcome.warnings
4838        );
4839        let stub = engine
4840            .store()
4841            .get(&crate::EntityId::new("laz", "missing"))
4842            .expect("forward-reference stub present");
4843        assert_eq!(
4844            stub.stub_kind,
4845            Some(crate::entity::StubKind::ForwardReference)
4846        );
4847    }
4848
4849    /// The read-only contract, now answerable without load (flywheel
4850    /// W7/02): an entity PRESENT in a deferred read-only mem's storage
4851    /// is admitted — the refusal never fires merely because the mem is
4852    /// unloaded — and an ABSENT one refuses with the existing typed
4853    /// error. The mem stays deferred through both.
4854    #[test]
4855    fn readonly_deferred_target_answers_from_storage() {
4856        use crate::engine::RelateEntityArgs;
4857        use memstead_schema::workspace_config::CrossLinkValue;
4858
4859        let tmp = TempDir::new().unwrap();
4860        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4861        let mut ro_mount = lazy_folder_mount("laz", lazy_dir.to_path_buf());
4862        ro_mount.capability = crate::workspace::MountCapability::ReadOnly;
4863        let mut engine = Engine::from_mounts(vec![
4864            (
4865                folder_mount("eag", eager_dir.to_path_buf()),
4866                Box::new(FilesystemMemWriter::new(eager_dir.to_path_buf())) as Box<dyn MemBackend>,
4867            ),
4868            (
4869                ro_mount,
4870                Box::new(FilesystemMemWriter::new(lazy_dir.to_path_buf())) as Box<dyn MemBackend>,
4871            ),
4872        ])
4873        .unwrap();
4874        let mut settings = crate::workspace::WorkspaceSettings::default();
4875        settings.cross_mem_links.insert(
4876            "eag".to_string(),
4877            CrossLinkValue::List(vec!["laz".to_string()]),
4878        );
4879        engine.set_settings(settings);
4880
4881        let relate = |engine: &mut Engine, to: &str| {
4882            let (actor, client) = cli_actor();
4883            engine.relate_entity(
4884                RelateEntityArgs {
4885                    source: crate::EntityId::new("eag", "alpha"),
4886                    expected_hash: None,
4887                    rel_type: "SUPPORTS".to_string(),
4888                    target: crate::EntityId::new("laz", to),
4889                    remove: false,
4890                    description: None,
4891                    dry_run: false,
4892                },
4893                actor,
4894                Some(&client),
4895                None,
4896            )
4897        };
4898
4899        relate(&mut engine, "omega").expect("present-in-storage RO target admits");
4900        assert!(
4901            engine.mem_is_deferred("laz"),
4902            "the admit never loads the mem"
4903        );
4904
4905        let err =
4906            relate(&mut engine, "missing").expect_err("absent RO target keeps the typed refusal");
4907        assert!(
4908            matches!(err, EngineError::CrossMemTargetNotFound { .. }),
4909            "expected CROSS_MEM_TARGET_NOT_FOUND, got {err:?}"
4910        );
4911        assert!(
4912            engine.mem_is_deferred("laz"),
4913            "the refusal never loads the mem either"
4914        );
4915    }
4916
4917    /// A cross-mem body link from an eager mem into a lazy one is a
4918    /// stub until the target mem loads, and resolves to the real entity
4919    /// afterwards — never silently dropped, never a spurious permanent
4920    /// warning.
4921    #[test]
4922    fn cross_mem_link_into_lazy_mem_resolves_on_load() {
4923        let tmp = TempDir::new().unwrap();
4924        let (eager_dir, lazy_dir) = two_mem_dirs(&tmp);
4925        write_spec(
4926            &eager_dir,
4927            "linker",
4928            "Linker",
4929            "\nSee [[laz--omega]] for detail.\n",
4930        );
4931
4932        let mut engine = mixed_engine(&eager_dir, &lazy_dir);
4933        let target = crate::EntityId::new("laz", "omega");
4934        assert!(
4935            engine.get_entity(&target).is_none_or(|e| e.stub),
4936            "before the lazy load the cross-mem target is at most a stub, never real"
4937        );
4938
4939        engine.reload_if_stale(Some("laz"));
4940        let resolved = engine.get_entity(&target).expect("target loaded");
4941        assert!(!resolved.stub, "after the load the target is real");
4942        assert!(
4943            !engine.load_warnings().iter().any(
4944                |w| matches!(w, WarningHint::SuspiciousNestedPrefix { resolved_id, .. } if resolved_id.as_ref() == target.as_ref())
4945            ),
4946            "no lingering nested-prefix warning for a resolved cross-mem link: {:?}",
4947            engine.load_warnings()
4948        );
4949    }
4950
4951    /// Shared fixture for the roster tests: a workspace with folder mems
4952    /// `alpha` (one entity) and `beta` (one entity linking into alpha), the
4953    /// roster saved through the workspace store, the engine booted.
4954    fn roster_change(warnings: &[WarningHint]) -> Option<(Vec<String>, Vec<String>)> {
4955        warnings.iter().find_map(|w| match w {
4956            WarningHint::MemRosterChanged { added, removed, .. } => {
4957                Some((added.clone(), removed.clone()))
4958            }
4959            _ => None,
4960        })
4961    }
4962
4963    fn search_scope(mem: Option<&str>, term: &str) -> crate::ops::SearchScope {
4964        crate::ops::SearchScope {
4965            query: Some(crate::ops::Query {
4966                any: vec![term.to_string()],
4967                ..Default::default()
4968            }),
4969            mem: mem.map(str::to_string),
4970            ..Default::default()
4971        }
4972    }
4973
4974    fn roster_fixture() -> (TempDir, Engine) {
4975        use crate::workspace_store::WorkspaceStoreAdapter;
4976        let tmp = TempDir::new().unwrap();
4977        let root = tmp.path();
4978        std::fs::create_dir_all(root.join(".memstead")).unwrap();
4979        std::fs::write(
4980            root.join(".memstead").join("workspace.toml"),
4981            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
4982        )
4983        .unwrap();
4984        for mem in ["alpha", "beta"] {
4985            let dir = root.join(mem);
4986            std::fs::create_dir_all(dir.join(".memstead")).unwrap();
4987            std::fs::write(
4988                dir.join(".memstead").join("config.json"),
4989                br#"{"format":1,"schema":"default@1.0.0"}"#,
4990            )
4991            .unwrap();
4992        }
4993        std::fs::write(
4994            root.join("alpha").join("one.md"),
4995            "---\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",
4996        )
4997        .unwrap();
4998        std::fs::write(
4999            root.join("beta").join("two.md"),
5000            "---\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",
5001        )
5002        .unwrap();
5003        let mount = |mem: &str| Mount {
5004            mem: mem.to_string(),
5005            schema: Some(SchemaRef::new("default", semver::Version::new(1, 0, 0))),
5006            storage: MountStorage::Folder {
5007                path: root.join(mem),
5008            },
5009            capability: MountCapability::Write,
5010            lifecycle: MountLifecycle::Eager,
5011            cross_linkable: true,
5012            migration_target: None,
5013        };
5014        crate::FileWorkspaceStore::new()
5015            .save_state(
5016                root,
5017                &crate::workspace::Workspace {
5018                    mounts: vec![mount("alpha"), mount("beta")],
5019                    settings: crate::workspace::WorkspaceSettings::default(),
5020                },
5021            )
5022            .unwrap();
5023        let engine = Engine::from_workspace_root(root).expect("workspace boots");
5024        (tmp, engine)
5025    }
5026
5027    fn save_roster(root: &Path, mems: &[(&str, &Path)]) {
5028        let with_schema: Vec<(&str, &Path, &str)> =
5029            mems.iter().map(|(m, d)| (*m, *d, "default")).collect();
5030        save_roster_pinned(root, &with_schema);
5031    }
5032
5033    fn save_roster_pinned(root: &Path, mems: &[(&str, &Path, &str)]) {
5034        use crate::workspace_store::WorkspaceStoreAdapter;
5035        let mounts = mems
5036            .iter()
5037            .map(|(mem, dir, schema)| Mount {
5038                mem: mem.to_string(),
5039                schema: Some(SchemaRef::new(*schema, semver::Version::new(1, 0, 0))),
5040                storage: MountStorage::Folder {
5041                    path: dir.to_path_buf(),
5042                },
5043                capability: MountCapability::Write,
5044                lifecycle: MountLifecycle::Eager,
5045                cross_linkable: true,
5046                migration_target: None,
5047            })
5048            .collect();
5049        // A roster write inside the same mtime tick as the previous one is
5050        // told apart by its hash, so no sleep is needed here.
5051        crate::FileWorkspaceStore::new()
5052            .save_state(
5053                root,
5054                &crate::workspace::Workspace {
5055                    mounts,
5056                    settings: crate::workspace::WorkspaceSettings::default(),
5057                },
5058            )
5059            .unwrap();
5060    }
5061
5062    /// A workspace whose roster file does not exist at boot (the first mem
5063    /// is created by another process after this engine started) mounts
5064    /// that mem on the next operation, with `MEM_ROSTER_CHANGED` naming it,
5065    /// and never needs a restart; the same file unchanged afterwards is
5066    /// quiet.
5067    #[test]
5068    fn roster_file_that_appears_after_boot_mounts_its_mems() {
5069        let tmp = TempDir::new().unwrap();
5070        let root = tmp.path();
5071        std::fs::create_dir_all(root.join(".memstead")).unwrap();
5072        std::fs::write(
5073            root.join(".memstead").join("workspace.toml"),
5074            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
5075        )
5076        .unwrap();
5077        let mut engine = Engine::from_workspace_root(root).expect("an empty workspace boots");
5078        assert!(engine.mem_names().is_empty(), "nothing is mounted at boot");
5079        assert!(
5080            !root
5081                .join(".memstead")
5082                .join("state")
5083                .join("mounts.json")
5084                .exists(),
5085            "the fixture has no roster file yet"
5086        );
5087        assert!(
5088            engine.reload_if_stale(None).is_empty(),
5089            "no roster, no warning"
5090        );
5091
5092        // Another process creates the first mem: folder plus roster entry.
5093        let dir = root.join("alpha");
5094        std::fs::create_dir_all(dir.join(".memstead")).unwrap();
5095        std::fs::write(
5096            dir.join(".memstead").join("config.json"),
5097            br#"{"format":1,"schema":"default@1.0.0"}"#,
5098        )
5099        .unwrap();
5100        std::fs::write(
5101            dir.join("one.md"),
5102            "---\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",
5103        )
5104        .unwrap();
5105        save_roster(root, &[("alpha", &dir)]);
5106
5107        let warnings = engine.reload_if_stale(None);
5108        let (added, removed) = roster_change(&warnings).expect("the first roster is a change");
5109        assert_eq!(added, vec!["alpha".to_string()]);
5110        assert!(removed.is_empty());
5111        assert_eq!(engine.mem_names(), vec!["alpha"]);
5112        assert!(
5113            engine
5114                .get_entity(&crate::EntityId("alpha--one".into()))
5115                .is_some(),
5116            "the mem's entity is served without a restart"
5117        );
5118        assert!(
5119            engine.reload_if_stale(None).is_empty(),
5120            "the unchanged roster is quiet"
5121        );
5122    }
5123
5124    /// A4 AC1 (engine half): a mem that leaves the roster is gone on the
5125    /// next operation with `MEM_ROSTER_CHANGED` naming it, its entities are
5126    /// not searchable, an operation naming it refuses `MEM_UNMOUNTED`; a mem
5127    /// that returns is served again with its entities.
5128    #[test]
5129    fn roster_membership_follows_reload_before_operation() {
5130        let (tmp, mut engine) = roster_fixture();
5131        let root = tmp.path();
5132        assert_eq!(engine.mem_names(), vec!["alpha", "beta"]);
5133        assert!(
5134            engine.reload_if_stale(None).is_empty(),
5135            "no change, no warning"
5136        );
5137
5138        // beta leaves the roster.
5139        save_roster(root, &[("alpha", &root.join("alpha"))]);
5140        let warnings = engine.reload_if_stale(None);
5141        let (added, removed) = roster_change(&warnings).expect("the roster change is reported");
5142        assert_eq!(removed, vec!["beta".to_string()]);
5143        assert!(added.is_empty());
5144        assert_eq!(engine.mem_names(), vec!["alpha"]);
5145        assert!(
5146            engine
5147                .get_entity(&crate::EntityId("beta--two".into()))
5148                .is_none()
5149        );
5150        let unscoped = engine.search(&search_scope(None, "beta two")).unwrap();
5151        assert_eq!(
5152            unscoped.total, 0,
5153            "no hit from the removed mem: {unscoped:?}"
5154        );
5155        let scoped = engine
5156            .search(&search_scope(Some("beta"), "beta two"))
5157            .expect_err("a search scoped to the removed mem refuses");
5158        assert_eq!(scoped.code(), "MEM_UNMOUNTED", "{scoped}");
5159        let err = engine.unknown_mem_error("beta");
5160        assert_eq!(err.code(), "MEM_UNMOUNTED", "{err}");
5161        assert!(
5162            engine.reload_if_stale(None).is_empty(),
5163            "reconciled once, quiet after"
5164        );
5165
5166        // beta returns: mounted cold with its entity.
5167        save_roster(
5168            root,
5169            &[("alpha", &root.join("alpha")), ("beta", &root.join("beta"))],
5170        );
5171        let warnings = engine.reload_if_stale(None);
5172        let (added, _) = roster_change(&warnings).expect("the return is reported");
5173        assert_eq!(added, vec!["beta".to_string()]);
5174        assert_eq!(engine.mem_names(), vec!["alpha", "beta"]);
5175        assert!(
5176            engine
5177                .get_entity(&crate::EntityId("beta--two".into()))
5178                .is_some()
5179        );
5180        assert_eq!(
5181            engine.unknown_mem_error("beta").code(),
5182            "UNKNOWN_MEM",
5183            "the memory clears"
5184        );
5185    }
5186
5187    /// A4 AC1, refusal complement: a roster entry whose storage does not
5188    /// exist quarantines on reconciliation exactly as boot would, with the
5189    /// boot's reason code, and the other mems keep serving.
5190    #[test]
5191    fn roster_entry_with_missing_storage_quarantines_like_boot() {
5192        let (tmp, mut engine) = roster_fixture();
5193        let root = tmp.path();
5194        // `ghost` pins a schema no source holds (boot's SCHEMA_NOT_FOUND
5195        // quarantine); `hollow` names a folder that does not exist (boot's
5196        // MOUNT_UNBACKED quarantine). The reconcile must do exactly the same
5197        // for both, and the other mems keep serving.
5198        std::fs::create_dir_all(root.join("ghost").join(".memstead")).unwrap();
5199        std::fs::write(
5200            root.join("ghost").join(".memstead").join("config.json"),
5201            br#"{"format":1,"schema":"nope@1.0.0"}"#,
5202        )
5203        .unwrap();
5204        save_roster_pinned(
5205            root,
5206            &[
5207                ("alpha", &root.join("alpha"), "default"),
5208                ("beta", &root.join("beta"), "default"),
5209                ("ghost", &root.join("ghost"), "nope"),
5210                ("hollow", &root.join("does-not-exist"), "default"),
5211            ],
5212        );
5213        let warnings = engine.reload_if_stale(None);
5214        let quarantined = warnings
5215            .iter()
5216            .find_map(|w| match w {
5217                WarningHint::MemRosterChanged { quarantined, .. } => Some(quarantined.clone()),
5218                _ => None,
5219            })
5220            .expect("reported");
5221        assert_eq!(quarantined, vec!["ghost".to_string(), "hollow".to_string()]);
5222        let q = engine
5223            .quarantine_reason("ghost")
5224            .expect("on the quarantine roster");
5225        // Boot quarantines the same entry under the same code.
5226        let booted = Engine::from_workspace_root(root).unwrap();
5227        let at_boot = booted
5228            .quarantine_reason("ghost")
5229            .expect("boot quarantines it too");
5230        assert_eq!(q.reason_code, at_boot.reason_code);
5231        assert_eq!(q.reason_code, "SCHEMA_NOT_FOUND");
5232        // The hollow mount: whatever boot does with it (quarantine or an
5233        // empty mount), the reconcile does the same.
5234        for name in ["ghost", "hollow"] {
5235            assert_eq!(
5236                engine
5237                    .quarantine_reason(name)
5238                    .map(|q| q.reason_code.clone()),
5239                booted
5240                    .quarantine_reason(name)
5241                    .map(|q| q.reason_code.clone()),
5242                "{name}: quarantine parity with boot"
5243            );
5244            assert_eq!(
5245                engine.mem_names().contains(&name),
5246                booted.mem_names().contains(&name),
5247                "{name}: membership parity with boot (reconciled {:?}, boot {:?})",
5248                engine.mem_names(),
5249                booted.mem_names()
5250            );
5251        }
5252        assert!(engine.mem_names().contains(&"alpha") && engine.mem_names().contains(&"beta"));
5253        assert!(
5254            engine
5255                .get_entity(&crate::EntityId("alpha--one".into()))
5256                .is_some()
5257        );
5258        assert_eq!(engine.unknown_mem_error("ghost").code(), "MEM_QUARANTINED");
5259    }
5260
5261    /// A4 AC2: after the unmount, the cross-mem edge from beta into alpha
5262    /// reads dangling on the integrity axis, search has no hit from the
5263    /// removed mem, and the community partition and search indexes carry no
5264    /// reference to it; the probe cost over one hundred operations stays in
5265    /// the branch-tip probe's band (printed as a benchmark line).
5266    #[test]
5267    fn unmount_is_atomic_and_cross_mem_edges_go_dangling() {
5268        let (tmp, mut engine) = roster_fixture();
5269        let root = tmp.path();
5270        // beta depends on alpha; alpha leaves.
5271        save_roster(root, &[("beta", &root.join("beta"))]);
5272        let _ = engine.reload_if_stale(None);
5273        assert_eq!(engine.mem_names(), vec!["beta"]);
5274        let findings = engine.consistency_findings("beta").unwrap();
5275        assert!(
5276            findings
5277                .iter()
5278                .any(|f| f.code == "DANGLING_RELATION_TARGET_MISSING" && f.id == "beta--two"),
5279            "the edge into the unmounted mem is dangling: {findings:?}"
5280        );
5281        let hits = engine.search(&search_scope(None, "alpha one")).unwrap();
5282        assert_eq!(hits.total, 0, "{hits:?}");
5283        // Derived structures: no community member and no index for alpha.
5284        let communities = engine.communities();
5285        assert!(
5286            communities
5287                .entity_cluster_map
5288                .keys()
5289                .all(|id| !id.starts_with("alpha--")),
5290            "the community partition carries no entity of the removed mem"
5291        );
5292        assert!(
5293            communities
5294                .clusters
5295                .values()
5296                .all(|c| c.entities.iter().all(|e| !e.starts_with("alpha--")))
5297        );
5298        assert!(engine.store().all_entities().all(|e| e.mem != "alpha"));
5299
5300        // Benchmark: one hundred reload probes with no change, roster
5301        // probe included, against one hundred branch-tip-only probes.
5302        let start = std::time::Instant::now();
5303        for _ in 0..100 {
5304            let _ = engine.reload_if_stale(None);
5305        }
5306        let with_roster = start.elapsed();
5307        let start = std::time::Instant::now();
5308        for _ in 0..100 {
5309            let _ = engine.reload_if_stale_content_only(None);
5310        }
5311        let content_only = start.elapsed();
5312        eprintln!(
5313            "BENCH roster probe: 100 ops with roster {with_roster:?}, content-only {content_only:?}"
5314        );
5315        assert!(
5316            with_roster < content_only * 4 + std::time::Duration::from_millis(50),
5317            "roster probe left the branch-tip band: {with_roster:?} vs {content_only:?}"
5318        );
5319    }
5320
5321    /// A4 AC2, refusal complement: an unmount that fails mid-way leaves the
5322    /// roster unapplied and the mem fully served, and the response names
5323    /// the failure.
5324    #[test]
5325    fn failed_unmount_leaves_the_roster_unapplied_and_the_mem_served() {
5326        let (tmp, mut engine) = roster_fixture();
5327        let root = tmp.path();
5328        engine.inject_unmount_failure = Some("beta".to_string());
5329        save_roster(root, &[("alpha", &root.join("alpha"))]);
5330        let warnings = engine.reload_if_stale(None);
5331        let (removed, failures) = warnings
5332            .iter()
5333            .find_map(|w| match w {
5334                WarningHint::MemRosterChanged {
5335                    removed, failures, ..
5336                } => Some((removed.clone(), failures.clone())),
5337                _ => None,
5338            })
5339            .expect("reported");
5340        assert!(removed.is_empty());
5341        assert!(
5342            failures
5343                .iter()
5344                .any(|f| f.contains("unmount:beta") && f.contains("injected")),
5345            "{failures:?}"
5346        );
5347        assert_eq!(
5348            engine.mem_names(),
5349            vec!["alpha", "beta"],
5350            "beta still served"
5351        );
5352        assert!(
5353            engine
5354                .get_entity(&crate::EntityId("beta--two".into()))
5355                .is_some()
5356        );
5357        assert_eq!(
5358            engine.unknown_mem_error("beta").code(),
5359            "UNKNOWN_MEM",
5360            "not remembered as unmounted"
5361        );
5362        // The baseline was kept: lifting the injection, the next operation
5363        // applies the pending change.
5364        engine.inject_unmount_failure = None;
5365        let warnings = engine.reload_if_stale(None);
5366        let (_, removed) = roster_change(&warnings).expect("retried");
5367        assert_eq!(removed, vec!["beta".to_string()]);
5368        assert_eq!(engine.mem_names(), vec!["alpha"]);
5369    }
5370}