Skip to main content

memstead_base/engine/
lifecycle.rs

1//! Engine lifecycle — settings/workspace-root setters, runtime
2//! mem add/remove, reload, and export.
3//!
4//! `register_writable_mem` / `unregister_writable_mem` are the
5//! engine-level primitives the `memstead_mem_create` / `memstead_mem_delete`
6//! handlers build on. `reload_one_mem*` re-reads a mount's backend
7//! and refreshes the in-memory store; `reload_each_writable_mem*`
8//! sweeps every writable mount. `export_markdown` regenerates entity
9//! markdown for folder mounts; `export_mem` produces a portable
10//! `.mem` archive via the backend-aware dispatch in
11//! [`crate::ops::export`].
12
13use std::cell::OnceCell;
14use std::collections::HashMap;
15use std::path::PathBuf;
16use std::sync::Arc;
17
18use crate::backend::{BackendError, MemBackend};
19use crate::engine_fallback_type;
20use crate::entity::EntityId;
21use crate::entity::generator::generate_markdown;
22use crate::entity::loader::parse_entries;
23use crate::entity::store_builder::push_entities_into_store;
24use crate::mem::MemOrigin;
25use crate::ops::WarningHint;
26use crate::workspace::{Mount, MountStorage, WorkspaceSettings};
27
28use super::boot::collect_source_entries;
29use super::{BackendFactory, Engine, EngineError, GitBranchOps, MountedBackend};
30
31/// What [`Engine::stage_sealed_schema`] did.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum SchemaStaging {
34    /// The pin already resolves in this workspace — nothing written.
35    /// Re-installing a mem, and installing a second mem that pins the
36    /// same schema, both land here.
37    AlreadyResolvable,
38    /// The package was written into the workspace's local schema
39    /// storage and is resolvable in this process from now on.
40    Staged,
41    /// The archive carries no embedded schema tree. Nothing to stage;
42    /// the pin must resolve on its own or the mount refuses.
43    NoEmbeddedSchema,
44    /// The workspace has no sealed-package storage (a folder-shaped
45    /// workspace: its `.memstead/schemas/` is the authoring tier and
46    /// never holds a third party's sealed bytes). The package was read
47    /// and checked against the pin, nothing was written, and the mount
48    /// resolves its vocabulary from the archive itself — on this shape
49    /// the archive IS the schema storage.
50    CarriedByArchive,
51}
52
53impl Engine {
54    /// Replace the workspace-level settings. Called by
55    /// [`Self::from_workspace_root`] (and the full counterpart) after
56    /// reading `.memstead/workspace.toml`. Tests / direct callers leave
57    /// the default empty value in place. Cheap clone — settings
58    /// carry only data shapes (raw rule lists, link policy map),
59    /// no compiled matchers. Invalidates the lazy
60    /// `create_rule_set_memo` so the next synthesis call rebuilds
61    /// from the new policy.
62    pub fn set_settings(&mut self, settings: WorkspaceSettings) {
63        self.settings = settings;
64        self.create_rule_set_memo = OnceCell::new();
65    }
66
67    /// Replace the backend factory. Full consumers call this once at boot
68    /// (`engine_from_workspace_root`) to install
69    /// `memstead_git_branch::storage::instantiate_full_backend` so the engine
70    /// can materialise git-branch backends on top of folder + archive.
71    /// Consumers without the git-branch crate leave the default in place.
72    pub fn set_backend_factory(&mut self, factory: BackendFactory) {
73        self.backend_factory = factory;
74    }
75
76    /// Insert into the engine's schema map, bumping the schemas epoch
77    /// (the second half of the derived-memo key — flywheel W8/01):
78    /// derived structures depend on schemas, so any change here must
79    /// be visible to the memo-invalidation hooks even when the store
80    /// generation did not move.
81    pub(crate) fn schemas_insert(
82        &mut self,
83        mem: String,
84        schema: std::sync::Arc<memstead_schema::Schema>,
85    ) {
86        self.schemas_epoch += 1;
87        self.schemas.insert(mem, schema);
88    }
89
90    /// Remove from the engine's schema map, bumping the schemas epoch
91    /// — see [`Self::schemas_insert`].
92    pub(crate) fn schemas_remove(&mut self, mem: &str) {
93        self.schemas_epoch += 1;
94        self.schemas.remove(mem);
95    }
96
97    /// Install the unmounted-mem storage discovery hook (flywheel
98    /// W7/02). Full boot sets it; without one, writes referencing
99    /// unmounted mems keep the forward-reference mechanic unchanged.
100    pub fn set_unmounted_storage_prober(&mut self, prober: super::UnmountedStorageProber) {
101        self.unmounted_storage_prober = Some(prober);
102    }
103
104    /// Replace the mutation-timestamp clock — the source every
105    /// engine-stamped metadata field (`init_timestamp` /
106    /// `auto_timestamp` schema flags: `created_date`, `last_modified`)
107    /// reads. A testing affordance for suites that assert over
108    /// canonical entity bytes (e.g. cross-surface hash parity):
109    /// pin both engines to the same constant and byte-level
110    /// nondeterminism from wall-clock seconds disappears. Production
111    /// code never calls this — the default installed at construction
112    /// is the system clock, and the stamped format is unchanged
113    /// either way.
114    pub fn set_mutation_clock(&mut self, clock: crate::engine::MutationClock) {
115        self.mutation_clock = clock;
116    }
117
118    /// Set the caller-declared role for subsequent mutations
119    ///. The surface calls this before every
120    /// mutation with the per-call parameter resolved against its
121    /// session default (per-call wins); `Role::Unspecified` records
122    /// as absence.
123    pub fn set_role(&mut self, role: crate::vcs::Role) {
124        self.current_role = role;
125    }
126
127    /// The currently declared role — what the next mutation records.
128    pub fn current_role(&self) -> crate::vcs::Role {
129        self.current_role
130    }
131
132    /// Set the caller-declared identity for subsequent mutations and
133    /// checks. The surface calls this before
134    /// every operation with the per-call parameter resolved against
135    /// its session default (per-call wins); `None` records as
136    /// absence. Callers pass an already-normalised value
137    /// ([`crate::vcs::normalise_identity`]).
138    pub fn set_identity(&mut self, identity: Option<String>) {
139        self.current_identity = identity;
140    }
141
142    /// The currently declared identity — what the next mutation or
143    /// check records.
144    pub fn current_identity(&self) -> Option<&str> {
145        self.current_identity.as_deref()
146    }
147
148    /// Current mutation timestamp as the second-granularity ISO form
149    /// the stamping paths write. Reads [`Self::mutation_clock`] — the
150    /// system clock unless a test pinned it.
151    pub(crate) fn now_iso(&self) -> String {
152        crate::engine::mutation::iso_from_system_time((self.mutation_clock)())
153    }
154
155    /// Install the git-branch ops bundle. Full boot
156    /// (`memstead_git_branch::engine_from_workspace_root`) calls this once
157    /// at construction. Consumers without the git-branch crate leave it unset
158    /// and the git-branch dispatch branches collapse to typed errors / empty
159    /// reports; such an engine serves no git-branch mounts.
160    pub fn set_git_branch_ops(&mut self, ops: GitBranchOps) {
161        self.git_branch_ops = Some(ops);
162    }
163
164    /// Install a schema package onto the workspace's git-branch backend —
165    /// the unified `__MEMSTEAD:schemas/<name>@<version>/` ref. `files`
166    /// are `(relative-path, bytes)` pairs (`schema.yaml`,
167    /// `types/<t>.yaml`, optional `mem-template.json`). Returns the
168    /// resulting commit sha; idempotent at the storage layer (an
169    /// identical re-install produces no new commit).
170    ///
171    /// Folder workspaces install schemas by writing under
172    /// `<workspace>/.memstead/schemas/` directly; this is the git-branch
173    /// path, where the engine owns the mem-repo and the write must
174    /// route through it. Errors when no git-branch ops are wired
175    /// or no git-branch mount exists to resolve the shared
176    /// mem-repo gitdir from. The caller reloads (or restarts) to pick
177    /// the new schema into the resolution catalogue.
178    pub fn install_schema(
179        &self,
180        name: &str,
181        version: &str,
182        files: &[(String, Vec<u8>)],
183    ) -> Result<String, EngineError> {
184        // Validation gate: the engine refuses to seal a package that the
185        // loader would reject or whose section headings cannot round-trip
186        // to their keys. Install time is the last moment the author can
187        // act — sealed schemas keep loading even when a later rule would
188        // refuse them, so nothing invalid may pass this point.
189        Self::validate_schema_package(name, version, files)?;
190        // Resolve the shared mem-repo gitdir: prefer a live git-branch
191        // mount's gitdir (authoritative — that is where the engine reads
192        // schemas from), falling back to the workspace's `mem-repo/.git`
193        // so a schema can be installed into an empty mem-repo *before*
194        // any mem pins it.
195        let gitdir = self
196            .mounts
197            .iter()
198            .find_map(|m| match &m.mount.storage {
199                crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
200                _ => None,
201            })
202            .or_else(|| {
203                self.workspace_root()
204                    .map(|r| r.join("mem-repo").join(".git"))
205            })
206            .ok_or_else(|| {
207                EngineError::Mem(
208                    "schema install requires a mem-repo workspace (no git-branch mount and \
209                     no workspace root to resolve the mem-repo gitdir)"
210                        .to_string(),
211                )
212            })?;
213        let ops = self.git_branch_ops.as_ref().ok_or_else(|| {
214            EngineError::Mem("git-branch ops are not wired on this engine".to_string())
215        })?;
216        // Seal the package AS-GIVEN: the format marker is a generation
217        // claim only the resolver can make (an authored directory source
218        // arrives already stamped; a legacy builtin or sealed source
219        // arrives unmarked, and absence IS its legacy claim). Stamping
220        // here mis-labelled legacy content as current and flipped every
221        // bare field's meaning in the sealed copy — the manufacturing
222        // defect an earlier plan removed.
223        (ops.write_schema)(&gitdir, name, version, files).map_err(EngineError::Backend)
224    }
225
226    /// Make a **sealed third-party** schema package resolvable in this
227    /// workspace — the install-time half of "a published mem installs
228    /// on the strength of the schema it carries".
229    ///
230    /// The package (package-relative files: `schema.yaml`,
231    /// `types/<t>.yaml`, `schema-format.json`) is written into the
232    /// workspace's local schema storage, the same storage
233    /// [`Self::install_schema`] writes to and the pin resolver reads —
234    /// so the mount that follows resolves without a fourth mechanism
235    /// and a second mem pinning the same schema finds it already
236    /// there. The loaded schema also lands in this engine's live
237    /// catalogue, so the caller mounts in the same process without a
238    /// reload.
239    ///
240    /// Two things it deliberately does NOT do. It does not run the
241    /// authoring gate ([`Self::validate_schema_package`]): these are a
242    /// third party's sealed bytes, the installing user cannot fix
243    /// them, and the archive validator has already admitted them under
244    /// the sealed reading — applying the authoring gate here would
245    /// make an archive that is valid to publish invalid to install.
246    /// And it does not append the format marker: presence of the
247    /// marker IS the package's metadata-polarity generation, so
248    /// injecting one would rewrite the meaning of bytes the publisher
249    /// sealed.
250    ///
251    /// Idempotent: a pin the engine can already resolve returns
252    /// [`SchemaStaging::AlreadyResolvable`] with nothing written.
253    ///
254    /// Shape-agnostic: on a workspace with no sealed-package storage (the
255    /// folder shape) the package is still read and checked against the
256    /// pin, so a broken embedded schema refuses before any mount side
257    /// effect, but nothing is written — the archive-backed mount that
258    /// follows resolves the vocabulary from the archive itself
259    /// ([`SchemaStaging::CarriedByArchive`]). What that shape forgoes is
260    /// the staged copy's extras: `memstead schema <pin>` rendering the
261    /// installed package, and a second, writable mem pinning it.
262    pub fn stage_sealed_schema(
263        &mut self,
264        mem: &str,
265        pin: &memstead_schema::SchemaRef,
266        files: &[(String, Vec<u8>)],
267    ) -> Result<SchemaStaging, EngineError> {
268        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
269            .workspace_schemas
270            .iter()
271            .chain(self.builtin_schemas.iter())
272            .cloned()
273            .collect();
274        if crate::engine::SchemaResolver::new(&catalogue)
275            .resolve(pin)
276            .is_ok()
277        {
278            return Ok(SchemaStaging::AlreadyResolvable);
279        }
280        if files.is_empty() {
281            // Nothing embedded to stage. The caller's mount attempt
282            // reports the unresolved pin with its own source trail —
283            // that IS the actionable error here.
284            return Ok(SchemaStaging::NoEmbeddedSchema);
285        }
286
287        let unloadable = |reason: String| EngineError::EmbeddedSchemaInvalid {
288            mem: mem.to_string(),
289            pin: pin.as_display(),
290            reason,
291        };
292        // Read it exactly as the local schema source will read it back
293        // — one sealed reader, so admission and re-read cannot diverge.
294        let schema =
295            memstead_schema::load_sealed_package(files).map_err(|e| unloadable(e.to_string()))?;
296        let (name, version) = schema.id();
297        if name != pin.name || version != pin.version {
298            return Err(unloadable(format!(
299                "the package declares '{name}@{version}' but the mem pins {}",
300                pin.as_display()
301            )));
302        }
303
304        if self.sealed_schema_gitdir().is_none() {
305            return Ok(SchemaStaging::CarriedByArchive);
306        }
307        self.write_to_local_schema_source(&name, &version.to_string(), files)?;
308        self.workspace_schemas.push(std::sync::Arc::new(schema));
309        Ok(SchemaStaging::Staged)
310    }
311
312    /// The gitdir that holds sealed third-party packages (the
313    /// `__MEMSTEAD:schemas/` ref): the first git-branch mount's, else the
314    /// workspace's `mem-repo/.git`. `None` on a folder-shaped workspace,
315    /// whose `.memstead/schemas/` is the authoring tier and never holds
316    /// sealed bytes.
317    fn sealed_schema_gitdir(&self) -> Option<PathBuf> {
318        self.mounts
319            .iter()
320            .find_map(|m| match &m.mount.storage {
321                crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
322                _ => None,
323            })
324            .or_else(|| {
325                self.workspace_root()
326                    .map(|r| r.join("mem-repo").join(".git"))
327            })
328            .filter(|g| g.is_dir())
329    }
330
331    /// Write a schema package into the workspace's local schema
332    /// storage — the git-branch `__MEMSTEAD:schemas/` ref when the
333    /// workspace is mem-repo-shaped. Shares
334    /// [`Self::install_schema`]'s gitdir resolution so authored and
335    /// staged packages land in one place.
336    fn write_to_local_schema_source(
337        &self,
338        name: &str,
339        version: &str,
340        files: &[(String, Vec<u8>)],
341    ) -> Result<(), EngineError> {
342        let gitdir = self.sealed_schema_gitdir().ok_or_else(|| {
343            EngineError::Mem(
344                "staging a schema requires a mem-repo workspace — the folder workspace's \
345                     `.memstead/schemas/` is the authoring tier and never holds sealed \
346                     third-party packages"
347                    .to_string(),
348            )
349        })?;
350        let ops = self.git_branch_ops.as_ref().ok_or_else(|| {
351            EngineError::Mem("git-branch ops are not wired on this engine".to_string())
352        })?;
353        (ops.write_schema)(&gitdir, name, version, files).map_err(EngineError::Backend)?;
354        Ok(())
355    }
356
357    /// Validate a schema package's files before they are sealed. Runs
358    /// the full loader (structural + semantic) plus the section-heading
359    /// round-trip gate, and checks the manifest's declared identity
360    /// matches the `(name, version)` the package is being installed
361    /// under — a mismatch would seal the schema under a ref its own
362    /// manifest contradicts.
363    ///
364    /// `pub` so the below-boot install path (memstead-git-branch's
365    /// repair surface) runs the SAME gate as this booted path — the
366    /// two must never fork into separate validation regimes.
367    pub fn validate_schema_package(
368        name: &str,
369        version: &str,
370        files: &[(String, Vec<u8>)],
371    ) -> Result<(), EngineError> {
372        let invalid = |message: String| EngineError::SchemaPackageInvalid {
373            name: name.to_string(),
374            version: version.to_string(),
375            message,
376        };
377        let manifest_yaml = files
378            .iter()
379            .find(|(rel, _)| rel == "schema.yaml")
380            .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())
381            .ok_or_else(|| invalid("package has no schema.yaml".to_string()))?;
382        let types: Vec<(String, String)> = files
383            .iter()
384            .filter_map(|(rel, bytes)| {
385                rel.strip_prefix("types/")
386                    .and_then(|f| f.strip_suffix(".yaml"))
387                    .map(|stem| {
388                        (
389                            stem.to_string(),
390                            String::from_utf8_lossy(bytes).into_owned(),
391                        )
392                    })
393            })
394            .collect();
395        // Install validates the CURRENT language (the author acts
396        // now) — the retired `optional:` key refuses here, and absent
397        // required keys mean optional.
398        let schema = memstead_schema::load_schema_from_memory_with_format(
399            &manifest_yaml,
400            &types,
401            memstead_schema::loader::MetadataPolarityFormat::RequiredOptIn,
402        )
403        .map_err(|e| invalid(e.to_string()))?;
404        memstead_schema::check_section_heading_roundtrip(&schema)
405            .map_err(|e| invalid(e.to_string()))?;
406        memstead_schema::check_reserved_metadata_keys(&schema)
407            .map_err(|e| invalid(e.to_string()))?;
408        memstead_schema::check_section_formats(&schema).map_err(|e| invalid(e.to_string()))?;
409        let (declared_name, declared_version) =
410            (schema.manifest.name.as_str(), schema.version.to_string());
411        if declared_name != name || declared_version != version {
412            return Err(invalid(format!(
413                "manifest declares '{declared_name}@{declared_version}' but the package is \
414                 being installed as '{name}@{version}'"
415            )));
416        }
417        Self::validate_schema_exemplars(&std::sync::Arc::new(schema)).map_err(invalid)?;
418        Ok(())
419    }
420
421    /// Validate every type exemplar a schema carries by running it
422    /// through the REAL create validation stage:
423    /// an in-memory engine is booted with the candidate schema pinned
424    /// on a virtual mem, and each exemplar is submitted as a
425    /// `dry_run` create — the same gates a real write runs (sections,
426    /// metadata + enums, rel-type vocabulary, edge shape, description
427    /// posture), commit-free by construction. Placeholder relation
428    /// targets are bare slugs scoped to the virtual mem, so target
429    /// existence is never checked (an absent target is the legal
430    /// would-be-stub path).
431    ///
432    /// Returns the defect as a message naming the type — the caller
433    /// wraps it in its own typed envelope (`SchemaPackageInvalid` on
434    /// the install path). There is deliberately no warn-and-carry
435    /// mode: a non-conformant exemplar refuses, because the whole
436    /// value of an exemplar is the impossibility of drift.
437    ///
438    /// `pub` so the built-in suite gates every shipped exemplar
439    /// through the SAME validator (a broken built-in exemplar fails
440    /// CI), and the below-boot install path shares the gate via
441    /// [`Self::validate_schema_package`].
442    pub fn validate_schema_exemplars(
443        schema: &std::sync::Arc<memstead_schema::Schema>,
444    ) -> Result<(), String> {
445        let with_exemplars: Vec<&str> = schema
446            .manifest
447            .types
448            .iter()
449            .filter(|t| {
450                schema
451                    .types
452                    .get(t.as_str())
453                    .is_some_and(|td| td.exemplar.is_some())
454            })
455            .map(String::as_str)
456            .collect();
457        if with_exemplars.is_empty() {
458            return Ok(());
459        }
460
461        let (name, version) = schema.id();
462        let mem = "exemplar";
463        let mount = crate::workspace::Mount {
464            mem: mem.to_string(),
465            schema: Some(memstead_schema::SchemaRef::new(name, version)),
466            storage: crate::workspace::MountStorage::InMemory,
467            capability: crate::workspace::MountCapability::Write,
468            lifecycle: crate::workspace::MountLifecycle::Eager,
469            cross_linkable: true,
470            migration_target: None,
471        };
472        let backend = Box::new(crate::storage::InMemoryBackend::new()) as Box<dyn MemBackend>;
473        let mut engine = Engine::from_mounts_with_schemas_dir_and_extra(
474            vec![(mount, backend)],
475            None,
476            vec![schema.clone()],
477        )
478        .map_err(|e| format!("exemplar validation could not boot: {e}"))?;
479
480        for type_name in with_exemplars {
481            let td = schema
482                .types
483                .get(type_name)
484                .expect("filtered on presence above");
485            let ex = td.exemplar.as_ref().expect("filtered on presence above");
486            let mut relations = Vec::with_capacity(ex.relations.len());
487            for r in &ex.relations {
488                let target = r.target_slug();
489                if target.contains("--") || target.trim().is_empty() {
490                    return Err(format!(
491                        "type '{type_name}' exemplar relation target '{target}' must be a bare \
492                         placeholder slug (no `--`, non-empty) — exemplars live outside \
493                         any mem",
494                    ));
495                }
496                relations.push(crate::ops::RelateArg {
497                    target: crate::entity::EntityId::new(mem, target),
498                    rel_type: r.rel_type_name().to_string(),
499                    description: r.description.clone(),
500                });
501            }
502            let args = crate::engine::CreateEntityArgs {
503                anchors: Vec::new(),
504                mem: mem.to_string(),
505                title: ex.title.clone(),
506                entity_type: type_name.to_string(),
507                sections: ex.sections.clone(),
508                metadata: ex.metadata.clone(),
509                relations,
510                dry_run: true,
511            };
512            if let Err(e) = engine.create_entity(args, crate::vcs::Actor::Cli, None, None) {
513                return Err(format!(
514                    "type '{type_name}' exemplar does not conform: [{}] {e}",
515                    e.code()
516                ));
517            }
518        }
519        Ok(())
520    }
521    /// Unregister a writable mem at runtime. Engine-level
522    /// primitive that `memstead_mem_delete` builds on.
523    ///
524    /// Removes the named mount from [`Self::mounts`], drops the
525    /// mem's entities from the store, refreshes the
526    /// [`MemRouterSnapshot`] via `Arc::make_mut` (COW swap so
527    /// readers holding a pre-swap snapshot see the pre-state for
528    /// their lifetime), and invalidates the community + search
529    /// memos. Does NOT touch the backend's on-disk state — the
530    /// caller (`delete_mem` orchestrator) decides whether to
531    /// remove the directory / gitdir after this returns.
532    ///
533    /// Returns `Ok(Some(backend))` when the mem was present and
534    /// unregistered — the caller can drive any backend-specific
535    /// follow-up cleanup (`backend.delete_artifacts()` for the
536    /// mem-repo branch + `__MEMSTEAD` config when `delete_files=true`).
537    /// Returns `Ok(None)` when no mount named the mem (idempotent —
538    /// repeated calls are safe).
539    pub fn unregister_writable_mem(
540        &mut self,
541        mem_name: &str,
542    ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
543        let pos = self.mounts.iter().position(|m| m.mount.mem == mem_name);
544        let Some(idx) = pos else {
545            return Ok(None);
546        };
547
548        // Drop the mount first — releases all engine-side state that
549        // referenced the backend. The `Box<dyn MemBackend>` itself
550        // travels back to the caller so backend-side cleanup
551        // (`delete_artifacts`) can run after the engine snapshot
552        // settled.
553        let mount = self.mounts.remove(idx);
554
555        // Drop the schema entry for this mem (kept in lockstep
556        // with `self.mounts`).
557        self.schemas_remove(&mount.mount.mem);
558
559        // Drop entities. The store's mem index is the
560        // authoritative count; the return value (number of
561        // entities removed) is informational only — the caller
562        // already knows the mem and doesn't need the count.
563        let _removed = self.store.remove_entities_by_mem(mem_name);
564
565        // Purge load-time warnings attributed to the removed mem.
566        // `health()` merges `self.load_warnings` unconditionally, so
567        // a skipped purge leaves phantom warnings citing entities the
568        // store no longer holds — for the whole engine lifetime, since
569        // nothing else clears the accumulator on the MCP path.
570        // Attribution is by SOURCE mem only (`WarningHint::source_mem`):
571        // a warning whose source entity lives in a surviving mem stays
572        // even when its target pointed into the deleted mem — the
573        // invalid row still exists in that survivor's markdown and
574        // remains visible drift (recover-worthy), not stale state.
575        self.load_warnings
576            .retain(|w| w.source_mem() != Some(mem_name));
577
578        // COW snapshot swap on the mem_router. `Arc::make_mut`
579        // clones the inner snapshot when other Arcs exist; if this
580        // is the only handle (typical for the engine's lifetime),
581        // it returns the existing inner directly without cloning.
582        // Readers that captured an `Arc` before this call observe
583        // the pre-swap state — the in-flight handler's
584        // `mem_router()` borrow is unaffected by this mutation.
585        Arc::make_mut(&mut self.mem_router).remove_writable(mem_name);
586
587        // Invalidate dependent memos — community detection + search
588        // indexes were computed over the pre-removal store and are
589        // now stale. Mutation paths already invalidate; this
590        // matches the contract.
591        self.invalidate_communities();
592        self.invalidate_search_indexes();
593
594        Ok(Some(mount.backend))
595    }
596
597    /// Register a read-only mount at runtime — the install path's
598    /// engine primitive. Same registration pipeline as
599    /// [`Self::register_writable_mem`] (collision probe, config read,
600    /// schema resolution, entity load, router swap); the router branch
601    /// lands the mount in the read-only slot for
602    /// `capability: ReadOnly` + `Archive` storage, so `is_writable`
603    /// stays false and `archive_path_for_mem` resolves.
604    pub fn register_read_mount(
605        &mut self,
606        mount: Mount,
607        backend: Box<dyn MemBackend>,
608        origin: MemOrigin,
609    ) -> Result<(), EngineError> {
610        self.register_writable_mem_inner(mount, backend, origin, true)
611    }
612
613    /// Unregister a read-only mount at runtime — the uninstall path's
614    /// engine primitive, mirroring [`Self::unregister_writable_mem`]
615    /// for the read-only slot. Returns `Ok(None)` when the name is
616    /// not a registered read-only mount (writable mems are the
617    /// delete/unregister verbs' business, deliberately not this
618    /// one's). Registration removal only — the backing archive file
619    /// (global cache) is never touched.
620    pub fn unregister_read_mount(
621        &mut self,
622        mem_name: &str,
623    ) -> Result<Option<Box<dyn MemBackend>>, EngineError> {
624        let pos = self.mounts.iter().position(|m| {
625            m.mount.mem == mem_name
626                && m.mount.capability == crate::workspace::MountCapability::ReadOnly
627        });
628        let Some(idx) = pos else {
629            return Ok(None);
630        };
631        let mount = self.mounts.remove(idx);
632        self.schemas_remove(&mount.mount.mem);
633        let _removed = self.store.remove_entities_by_mem(mem_name);
634        self.load_warnings
635            .retain(|w| w.source_mem() != Some(mem_name));
636        Arc::make_mut(&mut self.mem_router).remove_read_only(mem_name);
637        self.invalidate_communities();
638        self.invalidate_search_indexes();
639        Ok(Some(mount.backend))
640    }
641
642    /// Append a typed load-time warning from outside the engine's own
643    /// load pipeline — the boot orchestrators (which live in the full
644    /// crate) use this to surface one-time migrations they perform
645    /// around engine construction.
646    pub fn push_load_warning(&mut self, warning: crate::ops::WarningHint) {
647        self.load_warnings.push(warning);
648    }
649
650    /// Register a writable mem at runtime. Engine-level primitive
651    /// that `memstead_mem_create` builds on.
652    ///
653    /// Steps:
654    /// 1. Name collision probe against the current `mem_router`
655    ///    snapshot. Writable AND read-only entries collide; the
656    ///    error surfaces the colliding source so the orchestrator
657    ///    can render a recovery hint.
658    /// 2. Schema resolution via the built-in catalogue (mirrors
659    ///    [`Self::from_mounts`]; workspace-authored schema
660    ///    resolution lifts later).
661    /// 3. Per-mem config load (folder backends only; git-branch /
662    ///    archive return None — same contract as
663    ///    [`Self::from_mounts`]).
664    /// 4. Entity load via the backend, parse, push into the engine's
665    ///    store with a `LoadCollector` so drift warnings forward to
666    ///    `self.load_warnings`.
667    /// 5. Insert schema into [`Self::schemas`].
668    /// 6. Push the [`MountedBackend`] into [`Self::mounts`].
669    /// 7. COW snapshot swap on [`Self::mem_router`] via
670    ///    `Arc::make_mut` + `add_writable(name, dir, origin, mem_path)`.
671    ///    Folder mounts surface their on-disk path; other backends
672    ///    register with `dir: None` (matches full's contract).
673    ///    `mem_path` carries the create-time organisational `path`
674    ///    component (mirrors `MemCreateParams.path`) — the
675    ///    delete-side lifecycle composer reads it back to rebuild the
676    ///    `<mem_path>/<name>` candidate the create-side composer
677    ///    matched against. Caller threads `None` for flat-layout
678    ///    registrations and `Some(p)` for hierarchical ones.
679    /// 8. Invalidate community + search memos.
680    ///
681    /// Returns `Err(EngineError::MemNameCollision)` when the name
682    /// is already registered. Other failures (schema-not-found,
683    /// backend read errors) propagate as their typed variants. On
684    /// failure no engine mutation happens: every potentially-
685    /// mutating step runs only after the collision probe succeeds,
686    /// and intermediate failures propagate before the mount /
687    /// router are touched.
688    pub fn register_writable_mem(
689        &mut self,
690        mount: Mount,
691        backend: Box<dyn MemBackend>,
692        origin: MemOrigin,
693    ) -> Result<(), EngineError> {
694        self.register_writable_mem_inner(mount, backend, origin, true)
695    }
696
697    /// [`Self::register_writable_mem`] with the workspace-global
698    /// passes (relation validation, alias remap, memo invalidation)
699    /// made optional: `run_global_passes: false` lets a batch caller
700    /// ([`Self::full_refresh`]) attach N mounts and run the global
701    /// passes ONCE afterwards instead of N times under the engine
702    /// lock. A `false` caller MUST run
703    /// [`Self::finish_batched_registrations`] after its loop, or
704    /// loaded relations skip validation and alias edges stay
705    /// unmapped.
706    fn register_writable_mem_inner(
707        &mut self,
708        mount: Mount,
709        backend: Box<dyn MemBackend>,
710        origin: MemOrigin,
711        run_global_passes: bool,
712    ) -> Result<(), EngineError> {
713        // Step 1: name collision probe.
714        if let Some(existing) = self.mem_router.origin_for_mem(&mount.mem) {
715            return Err(EngineError::MemNameCollision {
716                name: mount.mem.clone(),
717                source_origin: existing.render_source(),
718            });
719        }
720        if self.mem_router.archive_path_for_mem(&mount.mem).is_some() {
721            return Err(EngineError::MemNameCollision {
722                name: mount.mem.clone(),
723                source_origin: "attached read mem".to_string(),
724            });
725        }
726
727        // Step 2: per-mem config load via the backend trait. Read
728        // before resolving the schema — the mem's own config carries
729        // the authoritative pin (mirrors the boot path), so a mem
730        // re-registered or mounted from another machine resolves from
731        // its own backend, not this workspace's mount expectation.
732        let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
733            let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
734            memstead_schema::config::parse_mem_config(&value).ok()
735        });
736
737        // Step 3: schema resolution. `MemConfig.schema` is the
738        // authoritative settled pin; `Mount.schema` is the fallback when
739        // the config carries none, and an expectation assertion when it
740        // does — a disagreement surfaces `SchemaPinMismatch` (config
741        // wins, neither silently dropped). Mirrors `from_mounts_inner`.
742        // Resolve against the engine's full loaded catalogue (already-
743        // loaded workspace/local-storage schemas layered over built-ins)
744        // so a mem registered against a backend-installed (e.g.
745        // git-branch `__MEMSTEAD:schemas/` ref) schema resolves.
746        let mut builtin_schemas: Vec<std::sync::Arc<memstead_schema::Schema>> =
747            self.workspace_schemas().to_vec();
748        // An archive-backed mount's own sealed vocabulary sits between
749        // the workspace tier and the built-ins, for this resolution
750        // only — see `from_mounts_inner` for why it never joins the
751        // shared catalogue.
752        builtin_schemas.extend(super::boot::embedded_archive_schemas(&mount));
753        builtin_schemas.extend(
754            memstead_schema::builtins::load_builtin_schemas()
755                .map_err(|e| EngineError::SchemaResolverInit(e.to_string()))?,
756        );
757        let config_pin = mem_config.as_ref().and_then(|c| c.schema.as_ref());
758        let mount_pin = mount.schema.as_ref();
759        if let (Some(cfg), Some(mp)) = (config_pin, mount_pin)
760            && cfg != mp
761        {
762            self.load_warnings
763                .push(crate::ops::WarningHint::SchemaPinMismatch {
764                    mem: mount.mem.clone(),
765                    config_pin: cfg.as_display(),
766                    mount_pin: mp.as_display(),
767                });
768        }
769        let settled_pin = config_pin.or(mount_pin);
770        let effective_pin = mount
771            .migration_target
772            .as_ref()
773            .or(settled_pin)
774            .ok_or_else(|| EngineError::MemConfigIncomplete {
775                mem: mount.mem.clone(),
776                missing_fields: vec!["schema".to_string()],
777            })?
778            .clone();
779        let schema = crate::engine::SchemaResolver::new(&builtin_schemas)
780            .resolve(&effective_pin)
781            .map_err(|sources| {
782                EngineError::SchemaNotFound {
783                    mem: mount.mem.clone(),
784                    pin: effective_pin.as_display(),
785                    sources,
786                    install_hint: None,
787                }
788                .with_schema_install_probe(self.workspace_root())
789            })?;
790
791        // Step 4: load entities via the backend, push into the
792        // engine's store with a LoadCollector so drift warnings
793        // forward into `self.load_warnings`. Derive the mem
794        // roster + last-segment suffixes from the POST-registration
795        // view (new mem included) so cross-mem references
796        // targeting the new mem resolve correctly during this
797        // load.
798        let (entries, read_errors) = collect_source_entries(backend.as_ref())?;
799        if let Some(w) =
800            super::boot::unbacked_mount_warning(&mount, backend.as_ref(), Some(entries.len()))
801        {
802            self.load_warnings.push(w);
803        }
804        let load_result = parse_entries(entries, read_errors, &mount.mem, schema.as_ref());
805
806        let mut mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
807        mem_names.push(mount.mem.clone());
808        let known_suffixes: Vec<String> = mem_names
809            .iter()
810            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
811            .collect();
812        let fallback = engine_fallback_type();
813        push_entities_into_store(
814            &mut self.store,
815            load_result.entities,
816            fallback.as_ref(),
817            Some(crate::entity::store_builder::LoadCollector {
818                warnings: &mut self.load_warnings,
819                known_suffixes: &known_suffixes,
820                mem_names: &mem_names,
821            }),
822        );
823        self.load_errors.extend(load_result.errors);
824
825        // Step 5: insert schema (kept in lockstep with `self.mounts`).
826        self.schemas_insert(mount.mem.clone(), schema);
827
828        // Re-run the parse-time relation validator now that the new
829        // mem's schema is in `self.schemas`. Mirrors the boot path
830        // (`Engine::from_mounts_inner`) — hand-edited or externally-
831        // generated markdown in the newly-attached mount goes through
832        // the same gauntlet (grammar / unknown_rel_type / shape /
833        // cycle) and offending relations are dropped with typed
834        // `PARSED_RELATION_INVALID` warnings on `self.load_warnings`.
835        // The newly-pushed mount isn't in `self.mounts` yet (that's
836        // Step 6 below), so build the map from `self.mounts` plus the
837        // about-to-be-attached mount we're still holding.
838        if run_global_passes {
839            let mut mount_caps: std::collections::HashMap<
840                String,
841                crate::workspace::MountCapability,
842            > = self
843                .mounts
844                .iter()
845                .map(|m| (m.mount.mem.clone(), m.mount.capability))
846                .collect();
847            mount_caps.insert(mount.mem.clone(), mount.capability);
848            crate::entity::store_builder::validate_loaded_relations(
849                &mut self.store,
850                &self.schemas,
851                &mount_caps,
852                &mut self.load_warnings,
853            );
854            crate::entity::store_builder::remap_alias_target_edge_sources(
855                &mut self.store,
856                &self.schemas,
857            );
858        }
859
860        // Step 6: push the MountedBackend.
861        let last_known_head = backend.current_head().ok().flatten();
862        let mem_name_for_router = mount.mem.clone();
863        let storage_for_router = mount.storage.clone();
864        let mount_capability_for_router = mount.capability;
865        self.mounts.push(MountedBackend {
866            mount,
867            backend,
868            last_known_head,
869            mem_config,
870            // A runtime-created mem is authored live, not installed from
871            // an archive — it carries no archive-borne provenance payload.
872            archive_provenance: None,
873            // Registered live and loaded in this call — never deferred.
874            deferred: false,
875        });
876
877        // Step 7: COW snapshot swap on mem_router, branched on the
878        // mount's capability — a read-only archive mount registers in
879        // the router's read-only slot (so `is_writable` stays false
880        // and `archive_path_for_mem` resolves), everything else in the
881        // writable slot. Folder mounts surface their on-disk path;
882        // other backends register with `dir: None` (mem-repo-backed
883        // mounts have no working tree).
884        match (&mount_capability_for_router, &storage_for_router) {
885            (crate::workspace::MountCapability::ReadOnly, MountStorage::Archive { path }) => {
886                Arc::make_mut(&mut self.mem_router)
887                    .add_read_only(mem_name_for_router, path.clone());
888            }
889            _ => {
890                let dir: Option<PathBuf> = match &storage_for_router {
891                    MountStorage::Folder { path } => Some(path.clone()),
892                    MountStorage::GitBranch { .. }
893                    | MountStorage::Archive { .. }
894                    | MountStorage::InMemory => None,
895                };
896                Arc::make_mut(&mut self.mem_router).add_writable(mem_name_for_router, dir, origin);
897            }
898        }
899
900        // Step 8: invalidate dependent memos.
901        if run_global_passes {
902            self.invalidate_communities();
903            self.invalidate_search_indexes();
904        }
905
906        Ok(())
907    }
908
909    /// The batched tail of `register_writable_mem_inner(...,
910    /// run_global_passes: false)`: one workspace-global relation
911    /// validation, one alias remap, one memo invalidation for the
912    /// whole batch of registrations.
913    /// [`Self::register_writable_mem`] without the workspace-global
914    /// passes — the batch form the roster reconciliation uses; the
915    /// caller runs [`Self::finish_batched_registrations`] once after.
916    pub(crate) fn register_writable_mem_batched(
917        &mut self,
918        mount: Mount,
919        backend: Box<dyn MemBackend>,
920        origin: MemOrigin,
921    ) -> Result<(), EngineError> {
922        self.register_writable_mem_inner(mount, backend, origin, false)
923    }
924
925    pub(crate) fn finish_batched_registrations(&mut self) {
926        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
927            .mounts
928            .iter()
929            .map(|m| (m.mount.mem.clone(), m.mount.capability))
930            .collect();
931        crate::entity::store_builder::validate_loaded_relations(
932            &mut self.store,
933            &self.schemas,
934            &mount_caps,
935            &mut self.load_warnings,
936        );
937        crate::entity::store_builder::remap_alias_target_edge_sources(
938            &mut self.store,
939            &self.schemas,
940        );
941        self.invalidate_communities();
942        self.invalidate_search_indexes();
943    }
944
945    /// Additive full refresh — the warm-server half of "restart the
946    /// process": re-scan the schema sources and the mount manifest,
947    /// making newly installed schema versions resolvable and newly
948    /// registered mems usable, WITHOUT applying removals. The
949    /// asymmetry is deliberate and is the whole safety argument:
950    /// adding extends what the in-memory store can answer, while
951    /// removing can strand entities, in-flight handles, and cached
952    /// hashes the process is still serving. Removals are skipped and
953    /// reported; a restart applies them.
954    ///
955    /// Failure model is per-item: a schema source or a mount that
956    /// fails to refresh lands in `failures` and never surfaces as
957    /// newly available; the others proceed. Each mount registration
958    /// is all-or-nothing (every fallible step runs before the store
959    /// is touched), so a failed item leaves no half-updated state.
960    /// The workspace-global passes (relation validation, alias remap,
961    /// memo invalidation) run ONCE per refresh regardless of how many
962    /// mounts attached.
963    ///
964    /// A newly mounted mem starts cold and loads like any other
965    /// mount. Content reload of pre-existing mems is NOT part of this
966    /// method — callers that want both (the `memstead_reload
967    /// full=true` surface) run the existing content-reload sweep
968    /// alongside.
969    pub fn full_refresh(&mut self) -> crate::ops::FullRefreshReport {
970        let started = std::time::Instant::now();
971        let mut report = crate::ops::FullRefreshReport::default();
972
973        let Some(_root) = self.workspace_root.clone() else {
974            report.failures.push(crate::ops::RefreshFailure {
975                item: "workspace".to_string(),
976                error: "engine has no workspace root (ad-hoc mount-list construction) — \
977                        nothing to re-scan"
978                    .to_string(),
979            });
980            report.elapsed_ms = started.elapsed().as_millis() as u64;
981            return report;
982        };
983
984        // Workspace policy — same best-effort refresh the
985        // workspace-wide content reload performs.
986        self.refresh_workspace_settings_if_possible();
987
988        // --- Schema sources, additively. ---
989        self.refresh_schema_sources(&mut report);
990
991        // --- Mount roster: the same reconciliation every operation runs
992        // (roster.rs), forced here even when the fingerprint says
993        // unchanged so the report is authoritative. Removals APPLY. ---
994        match self.reconcile_roster_forced() {
995            Ok(change) => {
996                report.mems_mounted = change.added;
997                report.mems_unmounted = change.removed;
998                report.mems_quarantined = change.quarantined;
999                report.failures.extend(change.failures);
1000            }
1001            Err(e) => report.failures.push(crate::ops::RefreshFailure {
1002                item: "mount-manifest".to_string(),
1003                error: e.to_string(),
1004            }),
1005        }
1006        report.mems_mounted.sort();
1007        report.mems_unmounted.sort();
1008        report.mems_quarantined.sort();
1009
1010        report.elapsed_ms = started.elapsed().as_millis() as u64;
1011        report
1012    }
1013
1014    /// Re-scan the schema sources additively into `report`
1015    /// (`schemas_added`, `schema_removals_skipped`, per-source failures).
1016    pub(crate) fn refresh_schema_sources(&mut self, report: &mut crate::ops::FullRefreshReport) {
1017        let Some(root) = self.workspace_root.clone() else {
1018            return;
1019        };
1020        use crate::schema_source::SchemaSource as _;
1021        let mut fresh: Vec<std::sync::Arc<memstead_schema::Schema>> = Vec::new();
1022        let mut sources_complete = true;
1023        match crate::schema_source::FolderSchemaSource::for_workspace(&root).read_schemas() {
1024            Ok(mut s) => fresh.append(&mut s),
1025            Err(e) => {
1026                sources_complete = false;
1027                report.failures.push(crate::ops::RefreshFailure {
1028                    item: "schema-source:folder".to_string(),
1029                    error: e.to_string(),
1030                });
1031            }
1032        }
1033        if let Some(ops) = self.git_branch_ops() {
1034            match (ops.read_ref_schemas)(&root) {
1035                Ok(mut s) => fresh.append(&mut s),
1036                Err(e) => {
1037                    sources_complete = false;
1038                    report.failures.push(crate::ops::RefreshFailure {
1039                        item: "schema-source:memstead-ref".to_string(),
1040                        error: e.to_string(),
1041                    });
1042                }
1043            }
1044        }
1045        let key = |s: &memstead_schema::Schema| {
1046            let (name, version) = s.id();
1047            format!("{name}@{version}")
1048        };
1049        let existing: std::collections::HashSet<String> =
1050            self.workspace_schemas.iter().map(|s| key(s)).collect();
1051        let fresh_keys: std::collections::HashSet<String> = fresh.iter().map(|s| key(s)).collect();
1052        for schema in fresh {
1053            let k = key(&schema);
1054            if !existing.contains(&k) && !report.schemas_added.contains(&k) {
1055                report.schemas_added.push(k);
1056                self.workspace_schemas.push(schema);
1057            }
1058        }
1059        report.schemas_added.sort();
1060        // Removal detection is only meaningful when every source was
1061        // actually readable — otherwise an unreadable source would
1062        // masquerade as a mass removal.
1063        if sources_complete {
1064            report.schema_removals_skipped = existing
1065                .difference(&fresh_keys)
1066                .cloned()
1067                .collect::<Vec<_>>();
1068            report.schema_removals_skipped.sort();
1069        }
1070    }
1071
1072    /// Override the workspace root after construction. The full
1073    /// boot helper `memstead_git_branch::engine_from_workspace_root`
1074    /// calls this so the engine knows the path even when the boot
1075    /// route runs through the full adapter rather than
1076    /// [`Self::from_workspace_root`].
1077    pub fn set_workspace_root(&mut self, root: PathBuf) {
1078        self.workspace_root = Some(root);
1079        self.capture_roster_fingerprint();
1080    }
1081
1082    /// Persist the engine's current mount list to the workspace
1083    /// store so a freshly-booted sibling process observes the same
1084    /// mem membership. Called by
1085    /// [`crate::mem_management::create_mem`] /
1086    /// [`crate::mem_management::delete_mem`] after the in-memory
1087    /// router mutation lands — without this, the per-mem content
1088    /// (branch + `__MEMSTEAD` config blob, or folder + `.memstead/config.json`)
1089    /// is already on disk, but the next process boot reads an empty
1090    /// `.memstead/state/mounts.json` and the engine starts with zero
1091    /// writable mems.
1092    ///
1093    /// No-op when `workspace_root` is unset (tests / ad-hoc
1094    /// consumers that build the engine directly from a mount list).
1095    /// Production boot paths (`Engine::from_workspace_root` and the
1096    /// full counterpart) always set the root, so the engine-side
1097    /// fix covers every caller — in-process embedders included
1098    /// — by construction.
1099    ///
1100    /// Hardcoded against [`crate::FileWorkspaceStore`] because that
1101    /// is the only V1 adapter; a future SQLite or remote adapter
1102    /// would install through a setter mirroring
1103    /// [`Self::set_backend_factory`].
1104    pub fn persist_state(&self) -> Result<(), EngineError> {
1105        let Some(root) = self.workspace_root.as_ref() else {
1106            return Ok(());
1107        };
1108        use crate::workspace_store::WorkspaceStoreAdapter as _;
1109        let store = crate::FileWorkspaceStore::new();
1110        let map = |e: crate::workspace_store::StoreError| {
1111            EngineError::Mem(format!("persist workspace state: {e}"))
1112        };
1113
1114        // Publish THIS engine's changes, not its whole cached view. An
1115        // earlier version serialized `self.mounts` wholesale, so a
1116        // long-lived process silently dropped every mount a sibling
1117        // process had registered since the cache was taken — the same
1118        // condition the mem-config writers close by re-reading, reaching
1119        // the workspace roster through the one writer they did not cover.
1120        // The delta is computed against `mounts_baseline` (what this
1121        // engine last read or wrote) rather than against a clock: a
1122        // single-writer workspace has an identical on-disk roster, so
1123        // the merge is a no-op there.
1124        // The roster this engine speaks for is the attached mounts PLUS
1125        // the quarantined ones: a quarantined mem's retained Mount is
1126        // what lets `reload` re-attempt the attach after a repair, and
1127        // dropping it from the file is how "degrade, never disappear"
1128        // turns into "disappear". It is also the record the
1129        // quarantine-repair path repins before asking for a state write.
1130        let ours: Vec<crate::workspace::Mount> = self
1131            .mounts
1132            .iter()
1133            .map(|m| m.mount.clone())
1134            .chain(self.quarantined.iter().map(|q| q.mount.clone()))
1135            .collect();
1136
1137        for attempt in 0..8 {
1138            let expected = store.read_state_bytes(root).map_err(map)?;
1139            let on_disk: Vec<crate::workspace::Mount> = match expected.as_deref() {
1140                Some(bytes) => store.parse_state_bytes(root, bytes).map_err(map)?,
1141                None => Vec::new(),
1142            };
1143
1144            let merged = {
1145                let baseline = self.mounts_baseline.borrow();
1146                merge_mount_rosters(&baseline, &ours, on_disk)
1147            };
1148            let workspace = crate::workspace::Workspace {
1149                mounts: merged,
1150                settings: self.settings.clone(),
1151            };
1152
1153            if store
1154                .save_state_cas(root, &workspace, expected.as_deref())
1155                .map_err(map)?
1156            {
1157                *self.mounts_baseline.borrow_mut() = ours;
1158                return Ok(());
1159            }
1160            if attempt == 7 {
1161                return Err(EngineError::Mem(
1162                    "workspace state is being written concurrently: eight compare-and-set \
1163                     attempts all lost the race. Retry, or find the writer that is not \
1164                     backing off."
1165                        .to_string(),
1166                ));
1167            }
1168        }
1169        unreachable!("the loop returns on success and on exhaustion")
1170    }
1171    /// Set a mem's schema pin — the conformance-gated schema-migration
1172    /// trigger. Behaviour per the pinned contract:
1173    ///
1174    /// - requested == current pin → `Noop`, no state change.
1175    /// - requested != pin, mem integral against the target →
1176    ///   atomic switch (`schema_pin = target`, migration state
1177    ///   cleared) in one workspace-store write → `Switched`.
1178    /// - requested != pin, mem NOT integral → enter (or stay in)
1179    ///   dual-pin: `migration_target = target`, writes validate
1180    ///   against the target from this call on, `findings` carries
1181    ///   the non-integral entities → `MigrationStarted`
1182    ///   (first call) / `MigrationPending` (same target re-issued).
1183    /// - re-issued with the in-flight target once every entity is
1184    ///   integral → atomic switch → `Switched`.
1185    ///
1186    /// The trigger is a label change gated by the conformance check —
1187    /// no content hashing. The response hands the agent findings and
1188    /// nothing else (no migration scripts, no hints); each repair
1189    /// write is validated strictly against the target.
1190    pub fn set_mem_schema(
1191        &mut self,
1192        mem: &str,
1193        target: &memstead_schema::SchemaRef,
1194    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
1195        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
1196        // A quarantined mem's set-schema IS the repair path (an
1197        // unresolvable pin is the commonest quarantine cause): repin
1198        // the retained mount, then re-attempt the attach — the same
1199        // in-process recovery `reload` performs after an external
1200        // repair. Ordinary mounts proceed below unchanged.
1201        if self.quarantine_reason(mem).is_some() {
1202            return self.set_schema_on_quarantined(mem, target);
1203        }
1204        let mount_idx = self
1205            .mounts
1206            .iter()
1207            .position(|m| m.mount.mem == mem)
1208            .ok_or_else(|| self.unknown_mem_error(mem))?;
1209        // Capability gate, identical in shape and position to the six
1210        // sibling setters (`set_mem_version` … `set_mem_sync_state`):
1211        // a schema-pin change starts a migration — the one lifecycle
1212        // mutation a read-only mount must be able to refuse like any
1213        // other.
1214        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
1215            return Err(EngineError::ReadOnlyMount(mem.to_string()));
1216        }
1217
1218        // The requested target must resolve before anything else —
1219        // an unknown ref is an error, not a migration into nowhere.
1220        let target_schema = self.resolve_schema_by_ref(target).ok_or_else(|| {
1221            // The migration resolver consulted workspace-authored
1222            // schemas layered over the built-ins (`resolve_schema_by_ref`).
1223            let consulted: Vec<_> = self
1224                .workspace_schemas
1225                .iter()
1226                .chain(self.builtin_schemas.iter())
1227                .cloned()
1228                .collect();
1229            EngineError::SchemaNotFound {
1230                mem: mem.to_string(),
1231                pin: target.as_display(),
1232                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
1233                    &target.name,
1234                    &target.version,
1235                    &consulted,
1236                ),
1237                install_hint: None,
1238            }
1239            .with_schema_install_probe(self.workspace_root())
1240        })?;
1241
1242        // `Mount.schema` is now the optional assertion; for a mem the
1243        // operator is actively re-pinning it is normally `Some` (and kept
1244        // in sync with the config by the switch below). `<unset>` covers a
1245        // mount that carried no assertion.
1246        let current_pin = self.mounts[mount_idx].mount.schema.clone();
1247        let current_pin_display = current_pin
1248            .as_ref()
1249            .map(|p| p.as_display())
1250            .unwrap_or_else(|| "<unset>".to_string());
1251        let in_flight = self.mounts[mount_idx].mount.migration_target.clone();
1252
1253        // The noop question is asked of the pin the engine actually
1254        // serves (the loaded schema, resolved from the authoritative
1255        // backend config at boot), never of the mount's expectation
1256        // alone. With a `SCHEMA_PIN_MISMATCH` (mount says 0.4.0, config
1257        // says 0.1.0) the old comparison against the mount answered
1258        // "noop" for a target of 0.4.0 and the config stayed at 0.1.0
1259        // forever: the one command meant to repair the mismatch could
1260        // not. When the served pin already equals the target and only
1261        // the mount expectation lags, the expectation is aligned in
1262        // place and reported as switched.
1263        let served_pin: Option<memstead_schema::SchemaRef> = self.schemas.get(mem).map(|s| {
1264            let (name, version) = s.id();
1265            memstead_schema::SchemaRef::new(name, version)
1266        });
1267        // During a dual-pin migration the served schema IS the target
1268        // (writes validate against it) while the config still pins the
1269        // old generation, so the shortcut applies only with no migration
1270        // in flight; an in-flight target falls through to the
1271        // conformance gate that completes it.
1272        if served_pin.as_ref() == Some(target) && in_flight.is_none() {
1273            if current_pin.as_ref() == Some(target) {
1274                return Ok(SetSchemaOutcome {
1275                    mem: mem.to_string(),
1276                    schema_pin: current_pin_display,
1277                    migration_target: in_flight.map(|t| t.as_display()),
1278                    outcome: SetSchemaResult::Noop,
1279                    findings: Vec::new(),
1280                    stamped_schema: self.stamped_schema_of(mount_idx),
1281                });
1282            }
1283            self.mounts[mount_idx].mount.schema = Some(target.clone());
1284            self.mounts[mount_idx].mount.migration_target = None;
1285            self.persist_state()?;
1286            return Ok(SetSchemaOutcome {
1287                mem: mem.to_string(),
1288                schema_pin: target.as_display(),
1289                migration_target: None,
1290                outcome: SetSchemaResult::Switched,
1291                findings: Vec::new(),
1292                stamped_schema: self.stamped_schema_of(mount_idx),
1293            });
1294        }
1295
1296        // Conformance gate against the requested target. The full
1297        // integrity definition includes the consistency axis, but the
1298        // schema-switch gate is conformance: consistency breaks are
1299        // schema-independent (they neither block nor are caused by a
1300        // pin change) and keep their always-available repair paths.
1301        let findings = crate::ops::integrity::conformance_findings(
1302            &self.store,
1303            mem,
1304            target_schema.as_ref(),
1305            &self.schemas,
1306        );
1307
1308        if findings.is_empty() {
1309            // Atomic switch. The pin's authoritative home is the backend
1310            // config (boot resolution prefers it over `Mount.schema`), so
1311            // persist there FIRST — if that write fails, every other piece
1312            // of state stays untouched and the switch is a clean no-op.
1313            // Without this the new pin landed only in `mounts.json` and was
1314            // silently reverted on the next process boot for any
1315            // config-present mem.
1316            self.persist_mem_schema_pin(mount_idx, target)?;
1317            self.mounts[mount_idx].mount.schema = Some(target.clone());
1318            self.mounts[mount_idx].mount.migration_target = None;
1319            self.schemas_insert(mem.to_string(), target_schema);
1320            self.invalidate_communities();
1321            // The index field set derives from the pinned schema — the
1322            // schema-switch staleness the whole-map drop used to mask:
1323            // this mem's index must be
1324            // rebuilt against the new field set.
1325            self.invalidate_search_indexes();
1326            self.persist_state()?;
1327            // The completed migration re-stamps the mutation stamp (the
1328            // marker `ENGINE_VERSION_SKEW` reads) with the generation
1329            // the mem now sits on. Without this the marker kept naming
1330            // the old pin until the next entity write, and an agent
1331            // reading it after the migration re-derived from a stale
1332            // generation (B5 grader finding, 2026-09-02). The stamp
1333            // writer's equality guard keeps a no-move write from
1334            // happening; its warnings ride entity mutations and have no
1335            // channel on this outcome, the same standing as the sweep.
1336            let _stamp_warnings_have_no_channel_here = self.stamp_mutation_versions(mount_idx);
1337            return Ok(SetSchemaOutcome {
1338                mem: mem.to_string(),
1339                schema_pin: target.as_display(),
1340                migration_target: None,
1341                outcome: SetSchemaResult::Switched,
1342                findings: Vec::new(),
1343                stamped_schema: self.stamped_schema_of(mount_idx),
1344            });
1345        }
1346
1347        let outcome = if in_flight.as_ref() == Some(target) {
1348            SetSchemaResult::MigrationPending
1349        } else {
1350            SetSchemaResult::MigrationStarted
1351        };
1352        self.mounts[mount_idx].mount.migration_target = Some(target.clone());
1353        // Writes validate against the target from this point on —
1354        // the load-bearing dual-pin semantic.
1355        self.schemas_insert(mem.to_string(), target_schema);
1356        self.invalidate_communities();
1357        // Same field-set dependency as the atomic-switch branch above.
1358        self.invalidate_search_indexes();
1359        self.persist_state()?;
1360        // A dual-pin entry never moves the marker: the mem still sits
1361        // on the old generation until every entity is integral, and
1362        // the outcome says which generation the marker carries.
1363        Ok(SetSchemaOutcome {
1364            mem: mem.to_string(),
1365            schema_pin: current_pin_display,
1366            migration_target: Some(target.as_display()),
1367            outcome,
1368            findings,
1369            stamped_schema: self.stamped_schema_of(mount_idx),
1370        })
1371    }
1372
1373    /// The resolved schema the mem's mutation stamp names, from the
1374    /// engine's cached config (kept current by the shared config
1375    /// writer), or `None` when the mem carries no stamp.
1376    fn stamped_schema_of(&self, mount_idx: usize) -> Option<String> {
1377        self.mounts
1378            .get(mount_idx)
1379            .and_then(|m| m.mem_config.as_ref())
1380            .and_then(|c| c.mutation_stamp.as_ref())
1381            .map(|st| st.schema.clone())
1382    }
1383
1384    /// Persist a mem's new schema pin into the authoritative backend
1385    /// config (`.memstead/config.json` for folder, the `__MEMSTEAD`
1386    /// mem-config blob for git-branch).
1387    ///
1388    /// Boot resolution treats the backend config as the authoritative
1389    /// settled pin and `Mount.schema` (the `mounts.json` copy) as a
1390    /// cross-checked assertion. A schema switch that updated only
1391    /// `mounts.json` would therefore be silently reverted on the next
1392    /// process boot — the config still names the old pin. This keeps the
1393    /// authoritative home in sync at switch time.
1394    ///
1395    /// Value-level field bump: only the `"schema"` string is rewritten;
1396    /// every other config field (`readMems`, write guidance, …) is
1397    /// preserved verbatim. Config-absent mems (no `config.json`) keep
1398    /// `Mount.schema` as their settled pin, so there is nothing to update
1399    /// — a clean no-op.
1400    /// **The one way this engine writes a mem config.** Every config-writing
1401    /// operation goes through it; none serializes its cached struct
1402    /// (consistency-sweep 04/03, criteria 1 and 2).
1403    ///
1404    /// The defect it removes: a long-lived MCP server reads each mem's config
1405    /// once at boot and holds it for days. Eight operations used to clone that
1406    /// cached struct, set one field, and write the whole thing back, so
1407    /// anything a sibling process changed in between was gone. The
1408    /// reload-before-operation invariant did not save them, because the
1409    /// staleness probe watches the entity branch (git-branch) or the change
1410    /// log (folder) and a config-only write advances neither.
1411    ///
1412    /// What this does instead is what the schema-pin writer next door already
1413    /// did: read the config the backend HAS, mutate the one field on that
1414    /// JSON, write it back. A field this call did not set cannot be reverted,
1415    /// because this call never had an opinion about it.
1416    ///
1417    /// `apply` receives the freshly-read config, PARSED. It deliberately does
1418    /// not receive raw JSON: an earlier draft handed out the `Value` and each
1419    /// closure wrote its own key name, which put `review_mark` in the file
1420    /// where the struct reads `reviewMark` and lost the field on the next
1421    /// read. Serde owns the wire names; the closures must not restate them.
1422    /// Unknown fields survive because `MemConfig` flattens them into `extra`.
1423    ///
1424    /// `apply` runs again on a re-read if the file moved between the read and
1425    /// the write, so it must be a pure function of the config it is handed,
1426    /// never of the engine's cache.
1427    ///
1428    /// Returns the parsed new config plus, when the stored config had moved on
1429    /// from what this engine last observed, the fields the intervening writer
1430    /// had changed. The caller rides that on its own response as
1431    /// `CONFIG_WRITE_INTERVENED`.
1432    pub(crate) fn write_mem_config_merged(
1433        &mut self,
1434        mount_idx: usize,
1435        mem_name: &str,
1436        note: Option<&str>,
1437        apply: &dyn Fn(&mut memstead_schema::config::MemConfig),
1438    ) -> Result<(memstead_schema::config::MemConfig, Vec<String>), EngineError> {
1439        let backend = self.mounts[mount_idx].backend.as_ref();
1440        let read = |b: &dyn crate::backend::MemBackend| -> Result<Vec<u8>, EngineError> {
1441            b.read_mem_config()
1442                .map_err(|e| EngineError::Mem(format!("read mem config for update: {e}")))?
1443                .ok_or_else(|| {
1444                    EngineError::InvalidInput(format!(
1445                        "mem '{mem_name}' has no stored MemConfig (initialize the mem via \
1446                         `memstead init` or `memstead mem create` first)"
1447                    ))
1448                })
1449        };
1450
1451        let stored = read(backend)?;
1452        // What the intervening writer changed, if anyone did. Compared against
1453        // the engine's cached copy, never against a clock: the rule forbids
1454        // reacting to cache age, and a single-writer workspace has an
1455        // identical cache, so this is empty there.
1456        let intervened = match self.mounts[mount_idx].mem_config.as_ref() {
1457            Some(cached) => changed_config_fields(cached, &stored),
1458            None => Vec::new(),
1459        };
1460
1461        let render =
1462            |raw: &[u8]| -> Result<(memstead_schema::config::MemConfig, Vec<u8>), EngineError> {
1463                let value: serde_json::Value = serde_json::from_slice(raw)
1464                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
1465                let mut cfg = memstead_schema::config::parse_mem_config(&value)
1466                    .map_err(|e| EngineError::Mem(format!("parse mem config for update: {e}")))?;
1467                apply(&mut cfg);
1468                let mut bytes = serde_json::to_vec_pretty(&cfg)
1469                    .map_err(|e| EngineError::Mem(format!("serialize mem config: {e}")))?;
1470                bytes.push(b'\n');
1471                Ok((cfg, bytes))
1472            };
1473        let (mut parsed, mut bytes) = render(&stored)?;
1474
1475        // Compare-and-set, done by the backend so the check and the write are
1476        // one step. An earlier draft re-read here and then wrote, which is
1477        // check-then-write and leaves exactly the lost-update window
1478        // open. On a mismatch the loop re-reads, re-applies onto what is
1479        // there, and retries: the intervening writer's change is merged, never
1480        // overwritten. Bounded, because an unbounded retry against a hot
1481        // writer is a hang, and reaching the bound is a real contention
1482        // problem the caller should hear about rather than a state to spin in.
1483        let mut expected = stored;
1484        for attempt in 0..8 {
1485            let wrote = self.mounts[mount_idx].backend.write_mem_config_cas(
1486                Some(&expected),
1487                &bytes,
1488                note,
1489            )?;
1490            if wrote {
1491                break;
1492            }
1493            if attempt == 7 {
1494                return Err(EngineError::Mem(format!(
1495                    "mem '{mem_name}' config is being written concurrently: eight \
1496                     compare-and-set attempts all lost the race. Retry, or find the \
1497                     writer that is not backing off."
1498                )));
1499            }
1500            expected = read(self.mounts[mount_idx].backend.as_ref())?;
1501            let rendered = render(&expected)?;
1502            parsed = rendered.0;
1503            bytes = rendered.1;
1504        }
1505
1506        let mounted = &mut self.mounts[mount_idx];
1507        mounted.mem_config = Some(parsed.clone());
1508        // Refresh the head cursor so the next drift probe does not surface
1509        // MEM_RELOADED for the commit this call just produced.
1510        if let Some(sha) = mounted.backend.current_head().ok().flatten() {
1511            mounted.last_known_head = Some(sha);
1512        }
1513        Ok((parsed, intervened))
1514    }
1515
1516    fn persist_mem_schema_pin(
1517        &mut self,
1518        mount_idx: usize,
1519        target: &memstead_schema::SchemaRef,
1520    ) -> Result<(), EngineError> {
1521        let value = bump_backend_schema_pin(self.mounts[mount_idx].backend.as_ref(), target)?;
1522        // Refresh the cached parsed config so in-session reads observe the
1523        // new pin without a reload.
1524        if let Some(value) = value
1525            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
1526        {
1527            self.mounts[mount_idx].mem_config = Some(cfg);
1528        }
1529        Ok(())
1530    }
1531
1532    /// Regenerate entity markdown files from the in-memory store.
1533    ///
1534    /// Dispatch:
1535    /// - When `mem_filter` is `Some(name)`, only that mem's mount
1536    ///   is considered. If its active backend doesn't support markdown
1537    ///   regeneration in place (today: anything other than
1538    ///   `MountStorage::Folder`), the call refuses with
1539    ///   [`EngineError::MarkdownExportUnsupportedBackend`] carrying
1540    ///   the active backend's id and the supported-backend list.
1541    /// - When `mem_filter` is `None`, every mount is iterated.
1542    ///   Folder mounts regenerate as today; non-folder mounts are
1543    ///   recorded in [`crate::ops::ExportResult::skipped_mounts`] so
1544    ///   the caller can surface the partial-success shape.
1545    ///
1546    /// Per-folder-mount behaviour: iterate the store, regenerate each
1547    /// non-stub entity belonging to the mount's mem, compare to the
1548    /// on-disk file, write if changed.
1549    ///
1550    /// `schema_filter` narrows the per-entity-type subset: when
1551    /// `Some(name)`, only entities whose `entity_type` matches are
1552    /// regenerated. `None` exports every type.
1553    ///
1554    /// Pre-fix this returned
1555    /// `ExportResult { written: 0, unchanged: 0 }` for git-branch /
1556    /// archive mounts — a successful-looking no-op that masked the
1557    /// backend-incompatibility. The typed refusal (per-mem) and the
1558    /// `skipped_mounts` channel (workspace-wide) give the caller an
1559    /// agent-actionable signal in one round-trip.
1560    pub fn export_markdown(
1561        &self,
1562        mem_filter: Option<&str>,
1563        schema_filter: Option<&str>,
1564    ) -> Result<crate::ops::ExportResult, EngineError> {
1565        use crate::workspace::MountStorage;
1566        let fallback = engine_fallback_type();
1567        let supported_backends = vec!["folder".to_string()];
1568
1569        if let Some(name) = mem_filter {
1570            let mount = self
1571                .mounts
1572                .iter()
1573                .find(|m| m.mount.mem == name)
1574                .ok_or_else(|| self.unknown_mem_error(name))?;
1575            if !matches!(mount.mount.storage, MountStorage::Folder { .. }) {
1576                return Err(EngineError::MarkdownExportUnsupportedBackend {
1577                    mem: name.to_string(),
1578                    active_backend: mount.mount.storage.backend_id().to_string(),
1579                    supported_backends,
1580                });
1581            }
1582        }
1583
1584        let mut total_written = 0;
1585        let mut refused: Vec<crate::ops::RefusedEntity> = Vec::new();
1586        let mut total_unchanged = 0;
1587        let mut skipped_mounts: Vec<crate::ops::SkippedMount> = Vec::new();
1588
1589        for mount in &self.mounts {
1590            let mem_name = mount.mount.mem.as_str();
1591            if let Some(filter) = mem_filter
1592                && mem_name != filter
1593            {
1594                continue;
1595            }
1596            let MountStorage::Folder { path: mem_dir } = &mount.mount.storage else {
1597                skipped_mounts.push(crate::ops::SkippedMount {
1598                    mem: mem_name.to_string(),
1599                    active_backend: mount.mount.storage.backend_id().to_string(),
1600                    reason: "backend_does_not_support_markdown_export".to_string(),
1601                });
1602                continue;
1603            };
1604            let schema = match self.schemas.get(mem_name) {
1605                Some(s) => s,
1606                None => continue,
1607            };
1608
1609            for entity in self.store.all_entities() {
1610                if entity.stub || entity.file_path.is_empty() {
1611                    continue;
1612                }
1613                if entity.id.mem() != mem_name {
1614                    continue;
1615                }
1616                if let Some(filter) = schema_filter
1617                    && entity.entity_type != filter
1618                {
1619                    continue;
1620                }
1621                let type_def = schema
1622                    .get_type(&entity.entity_type)
1623                    .unwrap_or_else(|| fallback.clone());
1624                let generated = generate_markdown(entity, type_def.as_ref());
1625
1626                let full_path = mem_dir.join(&entity.file_path);
1627                let needs_write = match std::fs::read_to_string(&full_path) {
1628                    Ok(existing) => existing != generated,
1629                    Err(_) => true,
1630                };
1631                if needs_write {
1632                    match crate::entity::writer::write_entity(entity, mem_dir, type_def.as_ref()) {
1633                        Ok(_) => total_written += 1,
1634                        // The one refusal the export must not swallow: writing
1635                        // this entity would bury the sections its open fence
1636                        // absorbed. Name it and carry on — an export that
1637                        // aborted here would strand every other entity.
1638                        Err(e @ crate::entity::writer::WriteError::UnterminatedFence { .. }) => {
1639                            refused.push(crate::ops::RefusedEntity {
1640                                id: entity.id.to_string(),
1641                                reason: "UNTERMINATED_FENCE_IN_STORED_BODY".to_string(),
1642                                detail: e.to_string(),
1643                            });
1644                        }
1645                        Err(_) => {}
1646                    }
1647                } else {
1648                    total_unchanged += 1;
1649                }
1650            }
1651        }
1652
1653        Ok(crate::ops::ExportResult {
1654            refused_entities: refused,
1655            written: total_written,
1656            unchanged: total_unchanged,
1657            skipped_mounts,
1658        })
1659    }
1660
1661    /// Export a mem as a portable `.mem` archive.
1662    ///
1663    /// Dispatch is internal: the engine looks up the mount whose mem
1664    /// name matches and branches on its `MountStorage`. Folder mounts
1665    /// produce a snapshot archive (current `.md` files + config);
1666    /// git-branch mounts invoke the registered [`GitBranchOps::export`]
1667    /// hook to produce a history archive (the per-mem branch tip's
1668    /// tree); archive mounts reject with `BackendError::Sealed`
1669    /// (already-an-archive — no meaningful re-export).
1670    ///
1671    /// The mem's `MemConfig` is looked up via
1672    /// [`Self::mem_config_for`]; unloaded configs (folder mounts
1673    /// without a `.memstead/config.json`, git-branch mounts without a
1674    /// `__MEMSTEAD:mems/<mem>/config.json`) surface as
1675    /// `EngineError::InvalidInput`. Workspace-level schema dir is
1676    /// threaded from `self.settings.schemas_dir` for the
1677    /// schema-source resolution chain.
1678    /// Resolve the mem's pinned schema from the workspace's
1679    /// `__MEMSTEAD:schemas/` ref (git-branch schema store) for the
1680    /// export paths of NON-git-branch mounts. `None` when the git-branch
1681    /// ops are not wired, the workspace has no mem-repo, or the
1682    /// package is not on the ref — callers then fall through to the
1683    /// disk/builtin chain unchanged. Without this, a folder mem whose
1684    /// schema `memstead schema install` sealed on the ref LOADS but
1685    /// cannot EXPORT: the loader and the archive assembler must read
1686    /// the same store.
1687    pub(crate) fn ref_schema_source_for(
1688        &self,
1689        config: &memstead_schema::MemConfig,
1690    ) -> Option<Vec<memstead_schema::SchemaSourceFile>> {
1691        let ops = self.git_branch_ops.as_ref()?;
1692        let root = self.workspace_root.as_deref()?;
1693        let pin = config.schema.as_ref()?;
1694        (ops.collect_ref_schema_source)(root, pin).ok().flatten()
1695    }
1696
1697    pub fn export_mem(
1698        &self,
1699        mem_name: &str,
1700        output_path: &std::path::Path,
1701    ) -> Result<crate::ops::MemExportResult, EngineError> {
1702        let mount = self
1703            .mounts
1704            .iter()
1705            .find(|m| m.mount.mem == mem_name)
1706            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1707        let config = self.mem_config_for(mem_name).ok_or_else(|| {
1708            EngineError::InvalidInput(format!(
1709                "mem '{mem_name}' has no loaded MemConfig — cannot export"
1710            ))
1711        })?;
1712        // F1: surface the missing-version case as a typed
1713        // `MEM_CONFIG_INCOMPLETE` envelope with structured recovery
1714        // details, rather than letting it bubble through as the
1715        // backend's `INTERNAL` collapse pointing at the wrong path
1716        // (`.memstead/config.json` is the folder-backend layout — the
1717        // mem-repo backend keeps the blob under `__MEMSTEAD:mems/`).
1718        // The check fires for both backends symmetrically.
1719        if config.version.is_none() {
1720            return Err(EngineError::MemConfigIncomplete {
1721                mem: mem_name.to_string(),
1722                missing_fields: vec!["version".to_string()],
1723            });
1724        }
1725        // Collected before the backend split so both storage kinds report
1726        // it. `install` refuses the archive for each of these; naming them at
1727        // export time is the same courtesy the dangling cross-mem edges get,
1728        // and for the same reason: an operator who learns at install time has
1729        // already shared the archive.
1730        let fenced: Vec<String> = self
1731            .store
1732            .all_entities()
1733            .filter(|e| e.mem == mem_name && !e.stub)
1734            .filter(|e| {
1735                e.sections
1736                    .values()
1737                    .any(|v| crate::markdown::closing_fence_if_unterminated(v.trim()).is_some())
1738            })
1739            .map(|e| e.id.to_string())
1740            .collect();
1741        let workspace_root = self.workspace_root.as_deref();
1742        // Authored schemas live at the fixed `<workspace>/.memstead/schemas/`
1743        // location (the `schemas_dir` key is retired). Absent dir → the
1744        // schema-source chain falls through to cache/built-in, as before.
1745        let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
1746        let workspace_schemas_dir = fixed_schemas_dir.as_deref();
1747        let exported = match &mount.mount.storage {
1748            MountStorage::Folder { path } => crate::ops::export::export_mem(
1749                path,
1750                config,
1751                output_path,
1752                workspace_root,
1753                workspace_schemas_dir,
1754                self.ref_schema_source_for(config),
1755            )
1756            .map_err(|e| EngineError::Backend(BackendError::Other(format!("export_mem: {e}")))),
1757            MountStorage::GitBranch { gitdir, branch } => {
1758                let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
1759                    EngineError::Backend(BackendError::Other(
1760                        "git-branch export hook not installed (git-branch ops not wired)"
1761                            .to_string(),
1762                    ))
1763                })?;
1764                // Source per-entity provenance from the git-branch mutation
1765                // log (commit trailers) and hand the serialised payload to
1766                // the export hook to embed — symmetric with the bytes path.
1767                let entity_paths = crate::ops::export::entity_paths_of(
1768                    &mount
1769                        .backend
1770                        .list_entities()
1771                        .map_err(EngineError::Backend)?,
1772                );
1773                let records = mount.backend.read_provenance(None).unwrap_or_default();
1774                let (provenance, redactions) =
1775                    crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
1776                let provenance_bytes = provenance.to_archive_bytes().ok();
1777                // Source the anchors sidecar from the branch tip — symmetric
1778                // with the bytes-export path so the disk `.mem` carries anchors.
1779                let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
1780                (hook.export)(
1781                    gitdir,
1782                    branch,
1783                    mem_name,
1784                    config,
1785                    output_path,
1786                    workspace_root,
1787                    workspace_schemas_dir,
1788                    provenance_bytes.as_deref(),
1789                    anchors_bytes.as_deref(),
1790                )
1791                .map(|mut r| {
1792                    r.redactions = redactions;
1793                    r
1794                })
1795                .map_err(EngineError::Backend)
1796            }
1797            MountStorage::Archive { .. } => Err(EngineError::Backend(BackendError::Sealed)),
1798            // `.mem` export from an in-memory mem lands with the
1799            // writable-session-server plan (it needs a backend-level
1800            // archive builder); this plan adds the backend, not the
1801            // export path, so refuse explicitly rather than silently.
1802            MountStorage::InMemory => Err(EngineError::Backend(BackendError::Other(
1803                "export not yet supported for in-memory backend".to_string(),
1804            ))),
1805        };
1806        exported.map(|mut r| {
1807            r.unterminated_fence_entities = fenced;
1808            r
1809        })
1810    }
1811
1812    /// Update a mem's `version` field in its per-mem config and
1813    /// persist it through the backend. Backend-symmetric: folder
1814    /// backends rewrite `.memstead/config.json`; git-branch backends
1815    /// commit `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts
1816    /// reject with `BackendError::Sealed`.
1817    ///
1818    /// Returns the (mem, old_version, new_version) triple so
1819    /// callers can surface the change without an extra read. Reads
1820    /// the current value from the in-memory `MemConfig` and
1821    /// updates it on success, keeping the next call free of a
1822    /// stale-version read.
1823    ///
1824    /// `EngineError::UnknownMem` when the name resolves to no
1825    /// mount; `EngineError::ReadOnlyMount` when the mount is sealed
1826    /// for writes; `EngineError::InvalidInput` when the mount has no
1827    /// loaded `MemConfig` (folder mount with no
1828    /// `.memstead/config.json`; the residual missing-config path is
1829    /// distinct from the missing-version path). F1.
1830    /// Record pipeline-edit provenance through `mem`'s backend — the
1831    /// bridge the pipeline-edit block (outside the engine module) uses
1832    /// to reach a mount's backend. A mem that isn't currently mounted
1833    /// is a successful no-op: pipeline configs may reference unmounted
1834    /// mems, and provenance is recorded against the mounted set.
1835    pub fn record_pipeline_edit_provenance(
1836        &self,
1837        mem: &str,
1838        kind: &str,
1839        edits: &[(String, Option<Vec<u8>>)],
1840        note: Option<&str>,
1841        verb: &str,
1842    ) -> Result<(), crate::backend::BackendError> {
1843        match self.mounts.iter().find(|m| m.mount.mem == mem) {
1844            Some(m) => m.backend.record_pipeline_edit(kind, edits, note, verb),
1845            None => Ok(()),
1846        }
1847    }
1848
1849    pub fn set_mem_version(
1850        &mut self,
1851        mem_name: &str,
1852        new_version: semver::Version,
1853        note: Option<&str>,
1854    ) -> Result<crate::ops::SetMemVersionOutcome, EngineError> {
1855        // Resolve the mount up-front so an unknown-mem name refuses
1856        // before any drift-probe side effect lands.
1857        let mount_idx = self
1858            .mounts
1859            .iter()
1860            .position(|m| m.mount.mem == mem_name)
1861            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1862        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
1863            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
1864        }
1865
1866        // Probe for concurrent-drift before the write — a sibling
1867        // engine that committed between our last snapshot and now
1868        // surfaces `MEM_RELOADED` on the response so callers see
1869        // the drift without a separate read round-trip. Drift
1870        // warnings ride alongside the success outcome; an
1871        // unreachable-backend probe collapses to no warnings (the
1872        // existing accessor warn-logs internally and skips).
1873        let mut warnings = self.reload_if_stale(Some(mem_name));
1874        // Provenance nudge — same posture as every other commit-
1875        // producing mutation: when `require_notes` is set and no note
1876        // was supplied, ride a non-blocking `NOTE_MISSING` warning.
1877        // The version bump still commits.
1878        if let Some(w) = self.note_missing_warning("set_mem_version", note) {
1879            warnings.push(w);
1880        }
1881
1882        // The old value is read from the STORED config, not the cache: the
1883        // cache may be days stale, and reporting a version the file has not
1884        // held since boot would be its own small lie.
1885        let old_version = self.mounts[mount_idx]
1886            .mem_config
1887            .as_ref()
1888            .and_then(|c| c.version.clone());
1889        let target = new_version.clone();
1890        let (_, intervened) = self.write_mem_config_merged(
1891            mount_idx,
1892            mem_name,
1893            note,
1894            &move |c: &mut memstead_schema::config::MemConfig| {
1895                c.version = Some(target.clone());
1896            },
1897        )?;
1898        if !intervened.is_empty() {
1899            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
1900                mem: mem_name.to_string(),
1901                fields: intervened,
1902            });
1903        }
1904
1905        Ok(crate::ops::SetMemVersionOutcome {
1906            mem: mem_name.to_string(),
1907            old_version,
1908            new_version,
1909            warnings,
1910        })
1911    }
1912
1913    /// Update a mem's `description` field in its per-mem config and
1914    /// persist it through the backend — the one-line text mem-archive
1915    /// export embeds and the registry card surfaces. `None` clears the
1916    /// field. Same backend symmetry, drift probe, and provenance-note
1917    /// posture as [`Self::set_mem_version`]; archive mounts reject with
1918    /// `BackendError::Sealed`.
1919    pub fn set_mem_description(
1920        &mut self,
1921        mem_name: &str,
1922        new_description: Option<String>,
1923        note: Option<&str>,
1924    ) -> Result<crate::ops::SetMemDescriptionOutcome, EngineError> {
1925        let mount_idx = self
1926            .mounts
1927            .iter()
1928            .position(|m| m.mount.mem == mem_name)
1929            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1930        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
1931            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
1932        }
1933
1934        let mut warnings = self.reload_if_stale(Some(mem_name));
1935        if let Some(w) = self.note_missing_warning("set_mem_description", note) {
1936            warnings.push(w);
1937        }
1938
1939        let old_description = self.mounts[mount_idx]
1940            .mem_config
1941            .as_ref()
1942            .and_then(|c| c.description.clone());
1943        let target = new_description.clone();
1944        let (_, intervened) = self.write_mem_config_merged(
1945            mount_idx,
1946            mem_name,
1947            note,
1948            &move |c: &mut memstead_schema::config::MemConfig| {
1949                c.description = target.clone();
1950            },
1951        )?;
1952        if !intervened.is_empty() {
1953            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
1954                mem: mem_name.to_string(),
1955                fields: intervened,
1956            });
1957        }
1958
1959        Ok(crate::ops::SetMemDescriptionOutcome {
1960            mem: mem_name.to_string(),
1961            old_description,
1962            new_description,
1963            warnings,
1964        })
1965    }
1966
1967    /// Update a mem's display `title` — free text, NOT identity: the
1968    /// mem name stays the sole handle everywhere. `None` clears it.
1969    /// Mirrors [`Self::set_mem_description`] in backend symmetry,
1970    /// drift probe, and provenance-note posture.
1971    pub fn set_mem_title(
1972        &mut self,
1973        mem_name: &str,
1974        new_title: Option<String>,
1975        note: Option<&str>,
1976    ) -> Result<crate::ops::SetMemTitleOutcome, EngineError> {
1977        let mount_idx = self
1978            .mounts
1979            .iter()
1980            .position(|m| m.mount.mem == mem_name)
1981            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1982        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
1983            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
1984        }
1985
1986        let mut warnings = self.reload_if_stale(Some(mem_name));
1987        if let Some(w) = self.note_missing_warning("set_mem_title", note) {
1988            warnings.push(w);
1989        }
1990
1991        let old_title = self.mounts[mount_idx]
1992            .mem_config
1993            .as_ref()
1994            .and_then(|c| c.title.clone());
1995        let target = new_title.clone();
1996        let (_, intervened) = self.write_mem_config_merged(
1997            mount_idx,
1998            mem_name,
1999            note,
2000            &move |c: &mut memstead_schema::config::MemConfig| {
2001                c.title = target.clone();
2002            },
2003        )?;
2004        if !intervened.is_empty() {
2005            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
2006                mem: mem_name.to_string(),
2007                fields: intervened,
2008            });
2009        }
2010
2011        Ok(crate::ops::SetMemTitleOutcome {
2012            mem: mem_name.to_string(),
2013            old_title,
2014            new_title,
2015            warnings,
2016        })
2017    }
2018
2019    /// Update a mem's `subject` block — scope, method, deliberate
2020    /// exclusions, published verbatim. `None` clears the block AS A
2021    /// UNIT. Mirrors [`Self::set_mem_description`].
2022    pub fn set_mem_subject(
2023        &mut self,
2024        mem_name: &str,
2025        new_subject: Option<memstead_schema::MemSubject>,
2026        note: Option<&str>,
2027    ) -> Result<crate::ops::SetMemSubjectOutcome, EngineError> {
2028        let mount_idx = self
2029            .mounts
2030            .iter()
2031            .position(|m| m.mount.mem == mem_name)
2032            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
2033        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
2034            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
2035        }
2036
2037        let mut warnings = self.reload_if_stale(Some(mem_name));
2038        if let Some(w) = self.note_missing_warning("set_mem_subject", note) {
2039            warnings.push(w);
2040        }
2041
2042        let old_subject = self.mounts[mount_idx]
2043            .mem_config
2044            .as_ref()
2045            .and_then(|c| c.subject.clone());
2046        let target = new_subject.clone();
2047        let (_, intervened) = self.write_mem_config_merged(
2048            mount_idx,
2049            mem_name,
2050            note,
2051            &move |c: &mut memstead_schema::config::MemConfig| {
2052                c.subject = target.clone();
2053            },
2054        )?;
2055        if !intervened.is_empty() {
2056            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
2057                mem: mem_name.to_string(),
2058                fields: intervened,
2059            });
2060        }
2061
2062        Ok(crate::ops::SetMemSubjectOutcome {
2063            mem: mem_name.to_string(),
2064            old_subject,
2065            new_subject,
2066            warnings,
2067        })
2068    }
2069
2070    /// Mark (or unmark) a mem as **internal** — hidden from the default
2071    /// `memstead_overview` roster and public projections, while remaining a
2072    /// real, schema-validated, diffable mem (inspectable when explicitly
2073    /// scoped by name, and deletable). The ingest process-state redesign
2074    /// (candidate (b)) flags each `ingest/<name>` process mem this way so it
2075    /// does not clutter the roster alongside real content.
2076    ///
2077    /// Stored as the top-level `internal` config field (captured by the
2078    /// flattened `extra` map). Backend-symmetric like
2079    /// [`Self::set_mem_description`]; `EngineError::UnknownMem` /
2080    /// `ReadOnlyMount` / `InvalidInput` on the usual failures.
2081    pub fn set_mem_internal(
2082        &mut self,
2083        mem_name: &str,
2084        internal: bool,
2085        note: Option<&str>,
2086    ) -> Result<crate::ops::SetMemInternalOutcome, EngineError> {
2087        let mount_idx = self
2088            .mounts
2089            .iter()
2090            .position(|m| m.mount.mem == mem_name)
2091            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
2092        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
2093            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
2094        }
2095
2096        let _ = self.reload_if_stale(Some(mem_name));
2097
2098        let (_, intervened) = self.write_mem_config_merged(
2099            mount_idx,
2100            mem_name,
2101            note,
2102            &move |c: &mut memstead_schema::config::MemConfig| {
2103                if internal {
2104                    c.extra
2105                        .insert("internal".to_string(), serde_json::Value::Bool(true));
2106                } else {
2107                    c.extra.remove("internal");
2108                }
2109            },
2110        )?;
2111        // This one used to return a bare `bool` and so had nowhere to put the
2112        // intervention report: it was dropped, not even logged.
2113        // A writer whose signature
2114        // cannot carry a warning is a writer that silently will not.
2115        let mut warnings = Vec::new();
2116        if !intervened.is_empty() {
2117            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
2118                mem: mem_name.to_string(),
2119                fields: intervened,
2120            });
2121        }
2122
2123        Ok(crate::ops::SetMemInternalOutcome {
2124            mem: mem_name.to_string(),
2125            internal,
2126            warnings,
2127        })
2128    }
2129
2130    /// Set (or clear) one opaque sync-state token in a mem's per-mem
2131    /// config and persist it through the backend. The ingest layer calls
2132    /// this after a successful pass over a source's changed slice to
2133    /// record "the source state the graph was last synced against".
2134    ///
2135    /// `key` and `token` are both opaque to the engine: the key is
2136    /// conventionally `"<ingest>/<facet>"` but the engine treats it as an
2137    /// arbitrary string; the token's meaning belongs to the medium-type
2138    /// layer (git → commit id, graph → snapshot token, filesystem → a
2139    /// JSON-stringified stat digest). The engine never parses either.
2140    /// An **empty** `token` removes the key — the surface for clearing a
2141    /// baseline (which the next ingest pass re-seeds at the current
2142    /// source state).
2143    ///
2144    /// Backend-symmetric like [`Self::set_mem_version`]: folder backends
2145    /// rewrite `.memstead/config.json`; git-branch backends commit
2146    /// `__MEMSTEAD:mems/<mem>/config.json`. Archive mounts reject with
2147    /// `BackendError::Sealed`.
2148    ///
2149    /// Returns the (mem, key, previous-token) triple so callers can
2150    /// surface the change without an extra read. `EngineError::UnknownMem`
2151    /// when the name resolves to no mount; `EngineError::ReadOnlyMount`
2152    /// when the mount is sealed for writes; `EngineError::InvalidInput`
2153    /// when the mount has no loaded `MemConfig`.
2154    pub fn set_mem_sync_state(
2155        &mut self,
2156        mem_name: &str,
2157        key: &str,
2158        token: &str,
2159        note: Option<&str>,
2160    ) -> Result<crate::ops::SetMemSyncStateOutcome, EngineError> {
2161        // Resolve the mount up-front so an unknown-mem name refuses
2162        // before any drift-probe side effect lands.
2163        let mount_idx = self
2164            .mounts
2165            .iter()
2166            .position(|m| m.mount.mem == mem_name)
2167            .ok_or_else(|| self.unknown_mem_error(mem_name))?;
2168        if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
2169            return Err(EngineError::ReadOnlyMount(mem_name.to_string()));
2170        }
2171
2172        // Probe for concurrent-drift before the write — same posture as
2173        // every other commit-producing mutation; a sibling engine that
2174        // committed since our last snapshot surfaces `MEM_RELOADED`.
2175        let mut warnings = self.reload_if_stale(Some(mem_name));
2176        if let Some(w) = self.note_missing_warning("set_mem_sync_state", note) {
2177            warnings.push(w);
2178        }
2179
2180        // `previous` has to come from the config this write actually lands
2181        // on, not from the cache: a sibling ingest pass may have moved the
2182        // very token this call is replacing, and reporting the cached value
2183        // would name a baseline that has not been current since boot. The
2184        // cell is written by each `apply` pass, so after a compare-and-set
2185        // retry it holds what was really overwritten.
2186        let seen: std::cell::RefCell<Option<String>> = std::cell::RefCell::new(None);
2187        let key_owned = key.to_string();
2188        let token_owned = token.to_string();
2189        let (_, intervened) = self.write_mem_config_merged(
2190            mount_idx,
2191            mem_name,
2192            note,
2193            &|c: &mut memstead_schema::config::MemConfig| {
2194                *seen.borrow_mut() = if token_owned.is_empty() {
2195                    c.sync_state.remove(&key_owned)
2196                } else {
2197                    c.sync_state.insert(key_owned.clone(), token_owned.clone())
2198                };
2199            },
2200        )?;
2201        let previous = seen.into_inner();
2202        // `removed` distinguishes a no-op clear (key absent) from a real one
2203        // so the outcome is honest.
2204        let removed = token.is_empty() && previous.is_some();
2205        if !intervened.is_empty() {
2206            warnings.push(crate::ops::WarningHint::ConfigWriteIntervened {
2207                mem: mem_name.to_string(),
2208                fields: intervened,
2209            });
2210        }
2211
2212        Ok(crate::ops::SetMemSyncStateOutcome {
2213            mem: mem_name.to_string(),
2214            key: key.to_string(),
2215            previous,
2216            removed,
2217            warnings,
2218        })
2219    }
2220
2221    /// Re-read the named mount's backend entities and refresh the
2222    /// in-memory store for that mem. Returns the diff against the
2223    /// pre-reload snapshot — `added` (ids newly present), `removed`
2224    /// (ids no longer present), `changed` (same id, different
2225    /// `content_hash`).
2226    ///
2227    /// Operator-triggered: useful when an external writer modified
2228    /// disk while this engine instance was alive (the folder backend
2229    /// assumes single-writer; this primitive is the escape hatch when
2230    /// that assumption breaks). On the happy path the diff is empty.
2231    ///
2232    /// Drift detection (whether disk *did* change) is not part of this
2233    /// surface — callers that want to short-circuit on "nothing
2234    /// changed" must compare `added.is_empty() && changed.is_empty()
2235    /// && removed.is_empty()` against the result. Backend-specific
2236    /// drift signals (git HEAD comparison, mtime check) live in the
2237    /// backends where they have meaning.
2238    ///
2239    /// Invalidates community + search-index memos on success.
2240    /// Load every DEFERRED (lazy, not-yet-loaded) mem matching `mem`
2241    /// (`None` = all) into the store — the first-read trigger of the
2242    /// lazy-mount lifecycle. Runs before the staleness probes on every
2243    /// operation ([`Self::reload_if_stale`] calls it first), so an
2244    /// operation scoped to one mem loads exactly that mem, and a
2245    /// workspace-scoped operation (search, overview, health) loads
2246    /// whatever it needs to answer over a complete store — a count
2247    /// computed over a partial store is never presented as truth.
2248    ///
2249    /// Loading rides the ordinary per-mem reload (entity walk, store
2250    /// push, the workspace-global validation passes, memo
2251    /// invalidation), so a lazily-loaded mem gets the same refusals and
2252    /// warnings an eager boot produces for the same content — deferral
2253    /// changes WHEN the gauntlet runs, never whether. After each load,
2254    /// pending `SuspiciousNestedPrefix` warnings whose target arrived
2255    /// with this mem are dropped — the same legitimate-cross-mem
2256    /// exemption the eager boot applies once every mount is loaded.
2257    ///
2258    /// A deferred load that FAILS quarantines the mem with the same
2259    /// typed reporting an eager boot failure produces, at this first
2260    /// read: the mount leaves the serving roster, the quarantine roster
2261    /// gains the typed reason, and the existing reattach contract
2262    /// applies. Deferral never converts a load failure into an
2263    /// empty-mem impression.
2264    ///
2265    /// No-op for workspaces without lazy mounts, for already-loaded
2266    /// mems, and for a filter naming no deferred mem.
2267    pub fn ensure_mems_loaded(&mut self, mem: Option<&str>) {
2268        let pending: Vec<String> = self
2269            .mounts
2270            .iter()
2271            .filter(|m| m.deferred && mem.is_none_or(|v| m.mount.mem == v))
2272            .map(|m| m.mount.mem.clone())
2273            .collect();
2274        for name in pending {
2275            match self.reload_one_mem(&name) {
2276                Ok(_) => {
2277                    if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
2278                        state.deferred = false;
2279                    }
2280                    // Cross-mem links INTO this mem were scanned by the
2281                    // nested-prefix detector against a store that did
2282                    // not yet carry it; now that its entities exist,
2283                    // drop any hit the arrival resolves (mirrors the
2284                    // boot-time retain over the complete store).
2285                    let store = &self.store;
2286                    self.load_warnings.retain(|w| match w {
2287                        crate::ops::WarningHint::SuspiciousNestedPrefix { resolved_id, .. } => {
2288                            store.get(resolved_id).is_none_or(|e| e.stub)
2289                        }
2290                        _ => true,
2291                    });
2292                }
2293                Err(e) => {
2294                    // Quarantine at the moment of first read — mirror
2295                    // the eager boot failure path byte-for-byte in
2296                    // consequence: out of the serving roster, onto the
2297                    // quarantine roster with the typed reason.
2298                    let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == name) else {
2299                        continue;
2300                    };
2301                    let removed = self.mounts.remove(idx);
2302                    self.schemas_remove(&name);
2303                    self.quarantined.push(crate::engine::QuarantinedMem {
2304                        mount: removed.mount,
2305                        reason_code: e.code().to_string(),
2306                        reason_message: e.to_string(),
2307                    });
2308                    self.mem_router = std::sync::Arc::new(
2309                        crate::engine::boot::build_mem_router_from_mounts(&self.mounts),
2310                    );
2311                    self.invalidate_communities();
2312                    // The schemas epoch just moved (`schemas_remove`),
2313                    // so a filled search memo is stale-keyed — clear it
2314                    // here or the next search trips the memo-key
2315                    // assert (the first W8/01 grade demonstrated
2316                    // exactly that on this branch).
2317                    self.invalidate_search_indexes();
2318                }
2319            }
2320        }
2321    }
2322
2323    pub fn reload_one_mem(&mut self, mem: &str) -> Result<crate::ops::ReloadResult, EngineError> {
2324        // Per-mem reload refreshes THIS mem's slice of the engine-wide
2325        // `load_warnings` accumulator: stale boot-time warnings for the
2326        // mem drop, fresh re-parse warnings take their place, other
2327        // mems' entries stay untouched. (The earlier "intentionally
2328        // silent" contract let a reload heal drift on disk while
2329        // `health()` kept reporting the healed warning forever — the
2330        // same class of stale-state lie the mem-delete purge closes.)
2331        //
2332        // The sink is filtered by source-mem attribution before it
2333        // merges: `validate_loaded_relations` scans the whole store, so
2334        // in principle the sink can carry other mems' warnings. In the
2335        // common case those mems' invalid rows were already dropped
2336        // from the in-memory store at their own load, so the filter is
2337        // a no-op guard against cross-mem duplicates, not a routine
2338        // trim. Failure leaves the accumulator untouched (`?` fires
2339        // before the merge), matching the inner fn's no-mutation-on-
2340        // failed-read fence. Drift events still surface as
2341        // `MemReloaded` warnings via `reload_if_stale`.
2342        // A quarantined mem's reload is the way back into service:
2343        // re-attempt the whole attach (backend, schema resolution,
2344        // entity load). On success the roster entry disappears; on
2345        // failure the mem stays quarantined with a refreshed reason.
2346        if self.quarantine_reason(mem).is_some() {
2347            return self.reattach_quarantined_mem(mem);
2348        }
2349        let mut sink: Vec<WarningHint> = Vec::new();
2350        let result = self.reload_one_mem_inner(mem, &mut sink)?;
2351        self.load_warnings.retain(|w| w.source_mem() != Some(mem));
2352        self.load_warnings
2353            .extend(sink.into_iter().filter(|w| w.source_mem() == Some(mem)));
2354        Ok(result)
2355    }
2356
2357    /// The quarantine branch of [`Self::set_mem_schema`]: repin the
2358    /// retained mount (target must resolve — the same booted resolver;
2359    /// repair never force-writes a pin that resolves nowhere), bump
2360    /// the backend config through the shared value-level writer,
2361    /// persist the mount state, then re-attempt the attach. A reattach
2362    /// that still fails (some second cause) leaves the mem quarantined
2363    /// with its refreshed reason — the pin switch itself is durable
2364    /// either way. The booted path's conformance gate cannot run over
2365    /// an unloaded mem; findings surface on the post-reattach health.
2366    fn set_schema_on_quarantined(
2367        &mut self,
2368        mem: &str,
2369        target: &memstead_schema::SchemaRef,
2370    ) -> Result<crate::engine::SetSchemaOutcome, EngineError> {
2371        use crate::engine::{SetSchemaOutcome, SetSchemaResult};
2372        // Same target-ref validation as the ordinary branch.
2373        if self.resolve_schema_by_ref(target).is_none() {
2374            let consulted: Vec<_> = self
2375                .workspace_schemas
2376                .iter()
2377                .chain(self.builtin_schemas.iter())
2378                .cloned()
2379                .collect();
2380            return Err(EngineError::SchemaNotFound {
2381                mem: mem.to_string(),
2382                pin: target.as_display(),
2383                sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
2384                    &target.name,
2385                    &target.version,
2386                    &consulted,
2387                ),
2388                install_hint: None,
2389            }
2390            .with_schema_install_probe(self.workspace_root()));
2391        }
2392        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
2393            return Err(self.unknown_mem_error(mem));
2394        };
2395        // Repin the retained mount and, where a backend can be
2396        // instantiated, the authoritative backend config (shared
2397        // value-level bump — same writer as the ordinary branch).
2398        self.quarantined[q_idx].mount.schema = Some(target.clone());
2399        self.quarantined[q_idx].mount.migration_target = None;
2400        if let Ok(backend) = (self.backend_factory)(&self.quarantined[q_idx].mount) {
2401            let _ = bump_backend_schema_pin(backend.as_ref(), target);
2402        }
2403        self.persist_state()?;
2404        // Re-attempt the attach. Failure keeps the quarantine (fresh
2405        // reason on the roster) but the pin switch stands — the
2406        // outcome reports the switch, the roster reports any
2407        // remaining cause.
2408        let _ = self.reattach_quarantined_mem(mem);
2409        // The below-gate repair path validated nothing, so it stamps
2410        // nothing: the marker reports what the last validated mutation
2411        // stamped (read from the re-attached mount when the repair
2412        // succeeded), and the next entity write re-stamps it.
2413        let stamped_schema = self
2414            .mounts
2415            .iter()
2416            .position(|m| m.mount.mem == mem)
2417            .and_then(|idx| self.stamped_schema_of(idx));
2418        Ok(SetSchemaOutcome {
2419            mem: mem.to_string(),
2420            schema_pin: target.as_display(),
2421            migration_target: None,
2422            outcome: SetSchemaResult::Switched,
2423            findings: Vec::new(),
2424            stamped_schema,
2425        })
2426    }
2427
2428    /// Re-attempt the boot-time attach of a quarantined mem —
2429    /// backend instantiation, schema resolution (same resolver and
2430    /// catalogue layering as boot: workspace-authored schemas over
2431    /// built-ins), then a per-mem entity load. Success removes the
2432    /// roster entry and the mem serves again in the same process;
2433    /// any failure keeps (re-)quarantining with the fresh typed
2434    /// reason, so the roster never goes stale against the live state.
2435    fn reattach_quarantined_mem(
2436        &mut self,
2437        mem: &str,
2438    ) -> Result<crate::ops::ReloadResult, EngineError> {
2439        let Some(q_idx) = self.quarantined.iter().position(|q| q.mount.mem == mem) else {
2440            return Err(self.unknown_mem_error(mem));
2441        };
2442        let mount = self.quarantined[q_idx].mount.clone();
2443
2444        let requarantine = |this: &mut Self, e: &EngineError| {
2445            this.quarantined[q_idx].reason_code = e.code().to_string();
2446            this.quarantined[q_idx].reason_message = e.to_string();
2447        };
2448
2449        let backend = match (self.backend_factory)(&mount) {
2450            Ok(b) => b,
2451            Err(e) => {
2452                let err = EngineError::Mem(e.to_string());
2453                requarantine(self, &err);
2454                return Err(self.unknown_mem_error(mem));
2455            }
2456        };
2457
2458        // Same config / pin-authority reads as the boot loop.
2459        let last_known_head = backend.current_head().ok().flatten();
2460        let mem_config = backend.read_mem_config().ok().flatten().and_then(|bytes| {
2461            let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
2462            memstead_schema::config::parse_mem_config(&value).ok()
2463        });
2464        let archive_provenance = backend
2465            .read_archive_provenance()
2466            .ok()
2467            .flatten()
2468            .and_then(|bytes| memstead_schema::ArchiveProvenance::from_archive_bytes(&bytes).ok());
2469        let config_pin = mem_config.as_ref().and_then(|c| c.schema.clone());
2470        let effective_pin = mount
2471            .migration_target
2472            .clone()
2473            .or(config_pin)
2474            .or(mount.schema.clone());
2475        let Some(effective_pin) = effective_pin else {
2476            let err = EngineError::MemConfigIncomplete {
2477                mem: mem.to_string(),
2478                missing_fields: vec!["schema".to_string()],
2479            };
2480            requarantine(self, &err);
2481            return Err(self.unknown_mem_error(mem));
2482        };
2483        // Same catalogue order as boot: workspace tier, then the mount's
2484        // own embedded vocabulary when it is archive-backed, then the
2485        // built-ins.
2486        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
2487            .workspace_schemas
2488            .iter()
2489            .cloned()
2490            .chain(super::boot::embedded_archive_schemas(&mount))
2491            .chain(self.builtin_schemas.iter().cloned())
2492            .collect();
2493        let schema = match crate::engine::SchemaResolver::new(&catalogue).resolve(&effective_pin) {
2494            Ok(s) => s,
2495            Err(sources) => {
2496                let err = EngineError::SchemaNotFound {
2497                    mem: mem.to_string(),
2498                    pin: effective_pin.as_display(),
2499                    sources,
2500                    install_hint: None,
2501                }
2502                .with_schema_install_probe(self.workspace_root());
2503                requarantine(self, &err);
2504                return Err(self.unknown_mem_error(mem));
2505            }
2506        };
2507
2508        // Attach, then load entities through the ordinary per-mem
2509        // reload. An entity-load failure re-quarantines (the mount is
2510        // detached again) — quarantine is not tolerance.
2511        self.quarantined.remove(q_idx);
2512        self.schemas_insert(mem.to_string(), schema);
2513        self.mounts.push(crate::engine::MountedBackend {
2514            mount,
2515            backend,
2516            last_known_head,
2517            mem_config,
2518            archive_provenance,
2519            // The reattach loads entities immediately below — a
2520            // quarantine return-to-service is never deferred.
2521            deferred: false,
2522        });
2523        self.mem_router = std::sync::Arc::new(crate::engine::boot::build_mem_router_from_mounts(
2524            &self.mounts,
2525        ));
2526        let mut sink: Vec<WarningHint> = Vec::new();
2527        match self.reload_one_mem_inner(mem, &mut sink) {
2528            Ok(result) => {
2529                self.load_warnings.retain(|w| w.source_mem() != Some(mem));
2530                self.load_warnings
2531                    .extend(sink.into_iter().filter(|w| w.source_mem() == Some(mem)));
2532                self.invalidate_communities();
2533                Ok(result)
2534            }
2535            Err(e) => {
2536                let mount_idx = self.mounts.len() - 1;
2537                let mounted = self.mounts.remove(mount_idx);
2538                self.schemas_remove(mem);
2539                self.mem_router = std::sync::Arc::new(
2540                    crate::engine::boot::build_mem_router_from_mounts(&self.mounts),
2541                );
2542                self.quarantined.push(crate::engine::QuarantinedMem {
2543                    mount: mounted.mount,
2544                    reason_code: e.code().to_string(),
2545                    reason_message: e.to_string(),
2546                });
2547                // Same epoch-moved staleness as the deferred-load
2548                // quarantine branch: `schemas_remove` bumped the
2549                // epoch, so both memos must clear.
2550                self.invalidate_communities();
2551                self.invalidate_search_indexes();
2552                Err(e)
2553            }
2554        }
2555    }
2556
2557    /// Inner per-mem body shared by [`Self::reload_one_mem`]
2558    /// and [`Self::reload_each_writable_mem`]. The caller passes
2559    /// a warning sink so the workspace-wide reload can forward
2560    /// warnings into `self.load_warnings` while the single-mem
2561    /// path keeps the accumulator pristine.
2562    fn reload_one_mem_inner(
2563        &mut self,
2564        mem: &str,
2565        warnings_sink: &mut Vec<WarningHint>,
2566    ) -> Result<crate::ops::ReloadResult, EngineError> {
2567        // Locate the target mount + schema. Unknown mem short-
2568        // circuits before any store mutation.
2569        let mount_idx = self
2570            .mounts
2571            .iter()
2572            .position(|m| m.mount.mem == mem)
2573            .ok_or_else(|| self.unknown_mem_error(mem))?;
2574        let schema = self
2575            .schemas
2576            .get(mem)
2577            .cloned()
2578            .ok_or_else(|| self.unknown_mem_error(mem))?;
2579
2580        // Snapshot pre-reload (id, content_hash) for this mem.
2581        let pre: HashMap<EntityId, String> = self
2582            .store
2583            .all_entities()
2584            .filter(|e| !e.stub && e.mem == mem)
2585            .map(|e| (e.id.clone(), e.content_hash.clone()))
2586            .collect();
2587        let pre_ids: std::collections::HashSet<EntityId> = pre.keys().cloned().collect();
2588
2589        // Walk the backend; surface read-time errors instead of
2590        // mutating the store on a failed reload.
2591        let backend = self.mounts[mount_idx].backend.as_ref();
2592        let (entries, read_errors) = collect_source_entries(backend)?;
2593        // The unbacked-mount probe rides the reload like the other
2594        // load-time warnings: a branch that appeared (or vanished) since
2595        // boot changes the answer, and the sink's per-mem replace below
2596        // drops the boot-time one.
2597        let unbacked = super::boot::unbacked_mount_warning(
2598            &self.mounts[mount_idx].mount,
2599            backend,
2600            Some(entries.len()),
2601        );
2602        let load_result = parse_entries(entries, read_errors, mem, schema.as_ref());
2603
2604        // Build the LoadCollector inputs — mem roster + last-
2605        // segment suffixes — so the parser pipeline can emit
2606        // typed drift warnings into the caller's sink.
2607        let mem_names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
2608        let known_suffixes: Vec<String> = mem_names
2609            .iter()
2610            .map(|n| crate::entity::store_builder::last_segment_suffix(n).to_string())
2611            .collect();
2612
2613        // Failure fence above; below this point the store is mutated.
2614        self.store.remove_entities_by_mem(mem);
2615        if let Some(w) = unbacked {
2616            warnings_sink.push(w);
2617        }
2618        let fallback = engine_fallback_type();
2619        push_entities_into_store(
2620            &mut self.store,
2621            load_result.entities,
2622            fallback.as_ref(),
2623            Some(crate::entity::store_builder::LoadCollector {
2624                warnings: warnings_sink,
2625                known_suffixes: &known_suffixes,
2626                mem_names: &mem_names,
2627            }),
2628        );
2629        // Re-run parse-time relation validation across the workspace.
2630        // A reload re-parses one mem but the validator's cycle pass
2631        // is global (acyclic-rel-type subgraphs span mems), so the
2632        // scan runs against the whole store. Hand-edits arriving via
2633        // sibling-writer commits get the same gauntlet boot enforces
2634        // (grammar / unknown_rel_type / shape / cycle).
2635        let mount_caps: std::collections::HashMap<String, crate::workspace::MountCapability> = self
2636            .mounts
2637            .iter()
2638            .map(|m| (m.mount.mem.clone(), m.mount.capability))
2639            .collect();
2640        // Restore cross-mem edges that point INTO this mem. The
2641        // removal cascade above dropped their incoming mirrors and the
2642        // re-push only rebuilt edges authored by this mem's own
2643        // entities, so a cross-mem `A→B` would silently vanish from the
2644        // index until a workspace-wide reload. Reconstruct from the
2645        // authoritative source records (in-memory only — no other mem is
2646        // re-read), then let the remap pass below reclassify alias sources.
2647        crate::entity::store_builder::reconstruct_incoming_cross_mem_edges(&mut self.store, mem);
2648        crate::entity::store_builder::validate_loaded_relations(
2649            &mut self.store,
2650            &self.schemas,
2651            &mount_caps,
2652            warnings_sink,
2653        );
2654        crate::entity::store_builder::remap_alias_target_edge_sources(
2655            &mut self.store,
2656            &self.schemas,
2657        );
2658        // Surface load errors back through the engine's accumulator
2659        // so subsequent `load_errors()` calls reflect the latest read.
2660        // THIS mem's stale entries are replaced, not accumulated — a
2661        // repaired file (e.g. a resolved merge conflict) must stop
2662        // reporting its old refusal, and a re-read of a still-broken
2663        // file must not duplicate its entry. Other mems' entries are
2664        // untouched (their reloads own them). Folder mounts key their
2665        // entries by absolute source path under the mem root; other
2666        // backends have no path-attributable entries to replace.
2667        if let crate::workspace::MountStorage::Folder { path } =
2668            &self.mounts[mount_idx].mount.storage
2669        {
2670            let root = path.clone();
2671            self.load_errors.retain(|(p, _)| !p.starts_with(&root));
2672            // The backend walk yields mem-relative paths while the boot
2673            // loader yields absolute ones — normalize to absolute so the
2674            // replace-on-reload key stays uniform across both origins.
2675            self.load_errors
2676                .extend(load_result.errors.into_iter().map(|(p, m)| {
2677                    let abs = if p.is_relative() { root.join(&p) } else { p };
2678                    (abs, m)
2679                }));
2680        } else {
2681            self.load_errors.extend(load_result.errors);
2682        }
2683
2684        // Refresh the mem's config from the backend too (D13). `sync_state`
2685        // (the projection baselines) and the schema pin / write guidance are
2686        // mem-scoped state that rides the mem branch, so an out-of-band write
2687        // — a sibling `projection advance` / `mem set-sync-state` — must become
2688        // visible after a per-mem reload, not only entity changes. A missing or
2689        // unparseable config leaves the cached value untouched (best-effort:
2690        // the reload never fails on a config read hiccup).
2691        if let Ok(Some(bytes)) = self.mounts[mount_idx].backend.read_mem_config()
2692            && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
2693            && let Ok(cfg) = memstead_schema::config::parse_mem_config(&value)
2694        {
2695            self.mounts[mount_idx].mem_config = Some(cfg);
2696        }
2697
2698        // Diff post-reload against the snapshot.
2699        let mut added: Vec<EntityId> = Vec::new();
2700        let mut changed: Vec<EntityId> = Vec::new();
2701        for entity in self.store.all_entities() {
2702            if entity.stub || entity.mem != mem {
2703                continue;
2704            }
2705            match pre.get(&entity.id) {
2706                None => added.push(entity.id.clone()),
2707                Some(prev_hash) if prev_hash != &entity.content_hash => {
2708                    changed.push(entity.id.clone());
2709                }
2710                Some(_) => {}
2711            }
2712        }
2713        let post_ids: std::collections::HashSet<EntityId> = self
2714            .store
2715            .all_entities()
2716            .filter(|e| !e.stub && e.mem == mem)
2717            .map(|e| e.id.clone())
2718            .collect();
2719        let mut removed: Vec<EntityId> = pre_ids.difference(&post_ids).cloned().collect();
2720        added.sort_by(|a, b| a.0.cmp(&b.0));
2721        changed.sort_by(|a, b| a.0.cmp(&b.0));
2722        removed.sort_by(|a, b| a.0.cmp(&b.0));
2723
2724        self.invalidate_communities();
2725        self.invalidate_search_indexes();
2726
2727        Ok(crate::ops::ReloadResult {
2728            added,
2729            changed,
2730            removed,
2731        })
2732    }
2733
2734    /// Rich-shape variant of [`Self::reload_one_mem`] that returns a
2735    /// [`crate::ops::ReloadReport`] (mem + head_before + head_after +
2736    /// entities_loaded + changed_entity_ids) instead of the slim
2737    /// [`crate::ops::ReloadResult`]. Handler-facing wrapper consumed
2738    /// by the `memstead_reload` MCP tool — the rich shape is the wire
2739    /// contract MCP callers depend on; the slim form stays for
2740    /// programmatic consumers that just want the diff lists.
2741    ///
2742    /// `head_before` is the engine's **prior cursor** for this mem
2743    /// (its cached `last_known_head`), *not* the current on-disk tip:
2744    /// when a sibling has committed since, the tip has already advanced,
2745    /// so reporting it would make the advertised
2746    /// `changes_since(since=head_before)` recipe span an empty range.
2747    /// `head_after` is the freshly-peeled tip from
2748    /// [`crate::backend::MemBackend::current_head`]; the reload also
2749    /// advances the cursor to it, so a follow-up staleness probe does
2750    /// not re-reload the same window. Backends without history (folder,
2751    /// archive) carry no cursor and return `Ok(None)`; both fields fall
2752    /// back to [`crate::ops::EMPTY_TREE_SHA`] for wire-shape stability.
2753    ///
2754    /// `entities_loaded` is the post-reload non-stub count for the
2755    /// mem — same semantic as full's report.
2756    ///
2757    /// `changed_entity_ids` is the union of `added ∪ changed ∪
2758    /// removed` from the underlying [`crate::ops::ReloadResult`]
2759    /// so callers don't have to merge three lists themselves —
2760    /// matches full's bundled wire shape.
2761    pub fn reload_one_mem_report(
2762        &mut self,
2763        mem: &str,
2764    ) -> Result<crate::ops::ReloadReport, EngineError> {
2765        // `head_before` is the engine's PRIOR cursor — the SHA it last
2766        // knew for this mem — not the current (possibly already
2767        // drifted) on-disk tip. Reporting the tip would collapse the
2768        // `changes_since(since=head_before)` range to empty in exactly
2769        // the sibling-drift case the recipe targets. `current_head` is
2770        // backend-defined: git-branch serves a git cursor, the folder
2771        // backend serves its change-ledger watermark, and a backend
2772        // without a head signal returns None — for those, `head_before`
2773        // stays the empty-tree sentinel that pairs with the
2774        // equally-empty `head_after` below.
2775        let tracks_head = self
2776            .mounts
2777            .iter()
2778            .find(|m| m.mount.mem == mem)
2779            .and_then(|m| m.backend.current_head().ok().flatten())
2780            .is_some();
2781        let head_before = if tracks_head {
2782            self.mounts
2783                .iter()
2784                .find(|m| m.mount.mem == mem)
2785                .and_then(|m| m.last_known_head.clone())
2786                .unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string())
2787        } else {
2788            crate::ops::EMPTY_TREE_SHA.to_string()
2789        };
2790
2791        let result = self.reload_one_mem(mem)?;
2792
2793        // Capture head_after = the freshly-peeled tip, and advance the
2794        // engine's cursor to it. Without this advance the next
2795        // operation's `reload_if_stale` would compare the stale cursor
2796        // against the same tip and re-reload the identical window,
2797        // re-emitting a spurious `MEM_RELOADED`. Only history-backed
2798        // mounts (current_head → Some) carry a cursor to advance.
2799        let head_after_raw = self
2800            .mounts
2801            .iter()
2802            .find(|m| m.mount.mem == mem)
2803            .and_then(|m| m.backend.current_head().ok().flatten());
2804        if let Some(new_head) = head_after_raw.clone()
2805            && let Some(m) = self.mounts.iter_mut().find(|m| m.mount.mem == mem)
2806        {
2807            m.last_known_head = Some(new_head);
2808        }
2809        let head_after = head_after_raw.unwrap_or_else(|| crate::ops::EMPTY_TREE_SHA.to_string());
2810
2811        let entities_loaded = self
2812            .store
2813            .all_entities()
2814            .filter(|e| !e.stub && e.mem == mem)
2815            .count();
2816
2817        // Union of added + changed + removed, sorted lexicographically
2818        // for deterministic wire output. Matches full's "single
2819        // changed_entity_ids list" contract — saves callers from
2820        // merging three slices themselves.
2821        let mut changed_entity_ids: Vec<EntityId> = result
2822            .added
2823            .into_iter()
2824            .chain(result.changed)
2825            .chain(result.removed)
2826            .collect();
2827        changed_entity_ids.sort_by(|a, b| a.0.cmp(&b.0));
2828
2829        Ok(crate::ops::ReloadReport {
2830            mem: mem.to_string(),
2831            head_before,
2832            head_after,
2833            entities_loaded,
2834            changed_entity_ids,
2835        })
2836    }
2837
2838    /// Batched rich-shape variant — returns one
2839    /// [`crate::ops::ReloadReport`] per mounted mem in declaration
2840    /// order. Counterpart to [`Self::reload_each_writable_mem`]
2841    /// (slim) that the `memstead_reload` MCP tool's no-mem path
2842    /// consumes.
2843    ///
2844    /// `load_warnings` semantics ride on the per-mem contract: each
2845    /// [`Self::reload_one_mem`] in the sweep refreshes its own mem's
2846    /// slice of the engine-wide accumulator, so a full sweep leaves
2847    /// the accumulator equivalent to a fresh boot. (Earlier this
2848    /// variant discarded every reload warning while its slim
2849    /// counterpart repopulated — the MCP workspace-wide reload could
2850    /// never clear a stale warning.) On first-error-abort, mems
2851    /// reloaded before the failure carry refreshed slices and the
2852    /// rest keep their boot-time entries — no slice is lost.
2853    ///
2854    /// Also re-reads `.memstead/workspace.toml` and refreshes
2855    /// [`crate::workspace::WorkspaceSettings`] before sweeping the
2856    /// mems — this is the pairing with the CLI's
2857    /// `memstead workspace allow-create / grant-cross-link / set-mutations`
2858    /// family. Without this re-read, a CLI write would land on disk but
2859    /// the running MCP would still serve the engine's boot-time policy
2860    /// snapshot; every subsequent `memstead_mem_create` against the new
2861    /// allowlist would fail with `MEM_PATH_NOT_ALLOWED` until process
2862    /// restart. The workspace-wide form runs the heavier path; the
2863    /// per-mem form (`reload_one_mem_report`) intentionally skips
2864    /// the workspace re-read — content drift doesn't imply policy
2865    /// drift.
2866    ///
2867    /// Reload of `workspace.toml` is best-effort: a missing or
2868    /// unparseable file leaves the existing settings untouched. The
2869    /// per-mem sweep is the primary contract — settings refresh is
2870    /// the additive bonus.
2871    ///
2872    /// First-error-aborts: if any mem's reload fails, the loop
2873    /// stops and the error propagates. Mems reloaded before the
2874    /// failing one are already mutated in the store; the returned
2875    /// error has no rollback. Operators run the per-mem form to
2876    /// retry the failing mem explicitly.
2877    pub fn reload_each_writable_mem_reports(
2878        &mut self,
2879    ) -> Result<Vec<crate::ops::ReloadReport>, EngineError> {
2880        self.refresh_workspace_settings_if_possible();
2881        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
2882        let mut out = Vec::with_capacity(names.len());
2883        for name in names {
2884            let report = self.reload_one_mem_report(&name)?;
2885            out.push(report);
2886        }
2887        Ok(out)
2888    }
2889
2890    /// Best-effort refresh of [`crate::workspace::WorkspaceSettings`]
2891    /// from the workspace's `.memstead/workspace.toml`. Called by the
2892    /// workspace-wide reload sweep so CLI-driven policy edits become
2893    /// visible to a live engine without process restart.
2894    ///
2895    /// Silent no-op when the engine has no `workspace_root` (legacy
2896    /// in-memory constructions) or when the on-disk file is missing /
2897    /// unparseable. The per-mem reload contract stays the canonical
2898    /// failure surface; settings refresh failures are intentionally
2899    /// non-fatal so a malformed workspace.toml doesn't break content
2900    /// drift detection.
2901    fn refresh_workspace_settings_if_possible(&mut self) {
2902        let Some(root) = self.workspace_root.clone() else {
2903            return;
2904        };
2905        let store = crate::workspace_store::FileWorkspaceStore::new();
2906        let workspace = match crate::workspace_store::WorkspaceStoreAdapter::load(&store, &root) {
2907            Ok(w) => w,
2908            Err(_) => return,
2909        };
2910        self.set_settings(workspace.settings);
2911    }
2912
2913    /// Reload every mounted mem in declaration order; returns one
2914    /// `(mem, ReloadResult)` per mount.
2915    ///
2916    /// Failure model is **first-error-aborts**: if any mem's reload
2917    /// fails, the loop stops and the error propagates. Mems reloaded
2918    /// before the failing one are already mutated in the store; the
2919    /// returned error has no rollback. Operators run the per-mem
2920    /// form to retry the failing mem explicitly.
2921    ///
2922    /// Caller-friendly batching wrapper around [`Self::reload_one_mem`];
2923    /// internal cache invalidation happens once per mem (the inner
2924    /// call invalidates) so an N-mem batch invalidates the memos
2925    /// N times. That's wasteful for large workspaces; once the
2926    /// `memstead_reload` MCP handler migrates we can tighten this to one
2927    /// invalidation at the end.
2928    pub fn reload_each_writable_mem(
2929        &mut self,
2930    ) -> Result<Vec<(String, crate::ops::ReloadResult)>, EngineError> {
2931        let names: Vec<String> = self.mounts.iter().map(|m| m.mount.mem.clone()).collect();
2932        // Workspace-wide reload semantics: take the engine-wide
2933        // sink, clear it, route per-mem inner reloads through it,
2934        // put it back. The result is `self.load_warnings` carries
2935        // every typed drift warning the reload sweep produced (so
2936        // the next `engine.health()` call surfaces them).
2937        let mut sink = std::mem::take(&mut self.load_warnings);
2938        sink.clear();
2939        let mut out = Vec::with_capacity(names.len());
2940        let mut loop_err = None;
2941        for name in names {
2942            match self.reload_one_mem_inner(&name, &mut sink) {
2943                Ok(result) => out.push((name, result)),
2944                Err(e) => {
2945                    loop_err = Some(e);
2946                    break;
2947                }
2948            }
2949        }
2950        self.load_warnings = sink;
2951        if let Some(e) = loop_err {
2952            return Err(e);
2953        }
2954        Ok(out)
2955    }
2956}
2957
2958/// Value-level schema-pin bump on a backend's mem config: read the
2959/// config blob, rewrite ONLY the `"schema"` string, write it back —
2960/// every other field (`readMems`, write guidance, sync state, …) is
2961/// preserved verbatim. Config-absent backends (no `config.json`) are a
2962/// clean no-op returning `None`; the caller's `Mount.schema` then
2963/// stays the settled pin. Returns the updated JSON value on a write so
2964/// callers can refresh caches.
2965///
2966/// One shared implementation for the booted path
2967/// (`Engine::persist_mem_schema_pin`) and the below-boot repair path
2968/// (memstead-git-branch) — the two must never fork: a pin written by
2969/// repair must be byte-shaped exactly as one written by the engine.
2970/// Field names on which the stored config differs from `cached`.
2971///
2972/// Compared as JSON so the comparison covers every field the struct models
2973/// without a hand-written field list that a new field would silently escape.
2974/// A parse failure yields no fields rather than a false report: the write
2975/// itself will surface the malformed config.
2976fn changed_config_fields(
2977    cached: &memstead_schema::config::MemConfig,
2978    stored_bytes: &[u8],
2979) -> Vec<String> {
2980    let (Ok(a), Ok(b)) = (
2981        serde_json::to_value(cached),
2982        serde_json::from_slice::<serde_json::Value>(stored_bytes),
2983    ) else {
2984        return Vec::new();
2985    };
2986    let (Some(a), Some(b)) = (a.as_object(), b.as_object()) else {
2987        return Vec::new();
2988    };
2989    let mut keys: std::collections::BTreeSet<&String> = a.keys().collect();
2990    keys.extend(b.keys());
2991    keys.into_iter()
2992        .filter(|k| a.get(*k) != b.get(*k))
2993        .map(|k| k.to_string())
2994        .collect()
2995}
2996
2997pub fn bump_backend_schema_pin(
2998    backend: &dyn crate::backend::MemBackend,
2999    target: &memstead_schema::SchemaRef,
3000) -> Result<Option<serde_json::Value>, EngineError> {
3001    let Some(bytes) = backend
3002        .read_mem_config()
3003        .map_err(|e| EngineError::Mem(format!("read mem config for pin update: {e}")))?
3004    else {
3005        return Ok(None);
3006    };
3007    let mut value: serde_json::Value = serde_json::from_slice(&bytes)
3008        .map_err(|e| EngineError::Mem(format!("parse mem config for pin update: {e}")))?;
3009    value["schema"] = serde_json::Value::String(target.as_display());
3010    let new_bytes = serde_json::to_vec_pretty(&value)
3011        .map_err(|e| EngineError::Mem(format!("serialize mem config for pin update: {e}")))?;
3012    backend
3013        .write_mem_config(&new_bytes)
3014        .map_err(|e| EngineError::Mem(format!("write mem config for pin update: {e}")))?;
3015    Ok(Some(value))
3016}
3017
3018/// Three-way merge of a mount roster for a state write.
3019///
3020/// `baseline` is what the writing engine last read or wrote, `ours` is
3021/// its roster now, `on_disk` is what the file holds at this instant.
3022/// The result keeps every on-disk mount the writer did not touch (so a
3023/// sibling's registration survives), drops the ones the writer removed
3024/// since its baseline, and applies the ones it added or changed.
3025///
3026/// A mount present in `ours` unchanged since the baseline does NOT
3027/// overwrite the on-disk record of the same name: if a sibling edited
3028/// it and we did not, the sibling's edit is the newer statement about
3029/// it, and republishing our stale copy is exactly the loss this merge
3030/// exists to prevent.
3031fn merge_mount_rosters(
3032    baseline: &[crate::workspace::Mount],
3033    ours: &[crate::workspace::Mount],
3034    on_disk: Vec<crate::workspace::Mount>,
3035) -> Vec<crate::workspace::Mount> {
3036    use std::collections::{HashMap, HashSet};
3037
3038    let ours_names: HashSet<&str> = ours.iter().map(|m| m.mem.as_str()).collect();
3039    let removed_by_us: HashSet<&str> = baseline
3040        .iter()
3041        .map(|m| m.mem.as_str())
3042        .filter(|n| !ours_names.contains(n))
3043        .collect();
3044    let baseline_by_name: HashMap<&str, &crate::workspace::Mount> =
3045        baseline.iter().map(|m| (m.mem.as_str(), m)).collect();
3046
3047    let mut merged: Vec<crate::workspace::Mount> = on_disk
3048        .into_iter()
3049        .filter(|m| !removed_by_us.contains(m.mem.as_str()))
3050        .collect();
3051
3052    for mount in ours {
3053        let untouched_by_us = baseline_by_name
3054            .get(mount.mem.as_str())
3055            .is_some_and(|b| *b == mount);
3056        match merged.iter_mut().find(|d| d.mem == mount.mem) {
3057            Some(slot) => {
3058                if !untouched_by_us {
3059                    *slot = mount.clone();
3060                }
3061            }
3062            None => merged.push(mount.clone()),
3063        }
3064    }
3065    merged
3066}
3067
3068#[cfg(test)]
3069mod tests {
3070
3071    use tempfile::TempDir;
3072
3073    use crate::backend::{BackendError, MemBackend};
3074    use crate::engine::test_helpers::*;
3075    use crate::engine::{Engine, EngineError};
3076    use crate::mem::MemOrigin;
3077    use crate::ops::WarningHint;
3078    use crate::storage::{ArchiveBackend, FilesystemMemWriter};
3079
3080    fn schema_package_files(heading: &str, manifest_name: &str) -> Vec<(String, Vec<u8>)> {
3081        let manifest = format!(
3082            r#"name: {manifest_name}
3083version: 1.0.0
3084description: Install-gate test schema
3085when_to_use: Tests
3086types:
3087  - sample
3088relationships:
3089  mode: strict
3090  definitions:
3091    - name: PART_OF
3092      description: hier
3093      default_weight: 3.0
3094    - name: _default
3095      description: fallback
3096      default_weight: 1.0
3097community:
3098  resolution: 1.0
3099  seed: 42
3100"#
3101        );
3102        let type_yaml = format!(
3103            r#"name: sample
3104description: t
3105when_to_use: tests
3106sections:
3107  - key: body
3108    heading: {heading}
3109    required: true
3110    search_weight: 10.0
3111    catch_all: true
3112    write_rules: []
3113metadata_fields: []
3114title_weight: 100.0
3115text_fields:
3116  - body
3117hierarchy_relationship: PART_OF
3118no_self_loop_relationships: []
3119updatable_fields:
3120  - title
3121  - body
3122health_required_fields:
3123  - body
3124staleness_threshold_days: 90
3125write_rules: []
3126"#
3127        );
3128        vec![
3129            ("schema.yaml".to_string(), manifest.into_bytes()),
3130            ("types/sample.yaml".to_string(), type_yaml.into_bytes()),
3131        ]
3132    }
3133
3134    /// The install gate accepts a conforming package and refuses one
3135    /// whose section heading cannot round-trip to its key — the last
3136    /// moment the author can act, since sealed schemas keep loading.
3137    #[test]
3138    fn install_gate_refuses_non_roundtrip_heading() {
3139        let ok =
3140            Engine::validate_schema_package("gate", "1.0.0", &schema_package_files("Body", "gate"));
3141        assert!(ok.is_ok(), "conforming package passes: {ok:?}");
3142
3143        let err = Engine::validate_schema_package(
3144            "gate",
3145            "1.0.0",
3146            &schema_package_files("Body Text", "gate"),
3147        )
3148        .expect_err("non-deriving heading must refuse install");
3149        match &err {
3150            EngineError::SchemaPackageInvalid { name, message, .. } => {
3151                assert_eq!(name, "gate");
3152                assert!(
3153                    message.contains("'body'") && message.contains("'Body Text'"),
3154                    "message names the offending tuple: {message}"
3155                );
3156            }
3157            other => panic!("expected SchemaPackageInvalid, got {other:?}"),
3158        }
3159    }
3160
3161    /// Build a package whose single type carries an exemplar assembled
3162    /// from the given pieces — the fixture for the exemplar-gate
3163    /// tests. The type declares a required `body` section, a `status`
3164    /// enum field, PART_OF (unpinned), and REFINES pinned to
3165    /// `source_types: [other]` so a REFINES exemplar edge from
3166    /// `sample` violates shape.
3167    fn exemplar_package_files(
3168        section_key: &str,
3169        status_value: &str,
3170        rel_type: &str,
3171    ) -> Vec<(String, Vec<u8>)> {
3172        let manifest = r#"name: gate
3173version: 1.0.0
3174description: exemplar gate fixture
3175when_to_use: tests
3176types:
3177  - sample
3178  - other
3179relationships:
3180  mode: strict
3181  definitions:
3182    - name: PART_OF
3183      description: hier
3184      default_weight: 3.0
3185    - name: REFINES
3186      description: pinned
3187      default_weight: 1.0
3188      source_types: [other]
3189    - name: _default
3190      description: fallback
3191      default_weight: 1.0
3192community:
3193  resolution: 1.0
3194  seed: 42
3195"#
3196        .to_string();
3197        let type_yaml = format!(
3198            r#"name: sample
3199description: t
3200when_to_use: tests
3201sections:
3202  - key: body
3203    heading: Body
3204    required: true
3205    search_weight: 10.0
3206    catch_all: true
3207    write_rules: []
3208metadata_fields:
3209  - key: status
3210    description: workflow state
3211    field_type: string
3212    enum_values: [draft, final]
3213title_weight: 100.0
3214text_fields:
3215  - body
3216hierarchy_relationship: PART_OF
3217no_self_loop_relationships: []
3218updatable_fields:
3219  - title
3220  - body
3221health_required_fields:
3222  - body
3223staleness_threshold_days: 90
3224write_rules: []
3225exemplar:
3226  title: A Conforming Sample
3227  metadata:
3228    status: "{status_value}"
3229  sections:
3230    {section_key}: "One canonical body paragraph."
3231  relations:
3232    - to: parent-placeholder
3233      type: {rel_type}
3234"#
3235        );
3236        let other_yaml = r#"name: other
3237description: shape-pin partner
3238when_to_use: tests
3239sections:
3240  - key: body
3241    heading: Body
3242    required: true
3243    search_weight: 10.0
3244    catch_all: true
3245    write_rules: []
3246metadata_fields: []
3247title_weight: 100.0
3248text_fields:
3249  - body
3250hierarchy_relationship: PART_OF
3251no_self_loop_relationships: []
3252updatable_fields:
3253  - title
3254  - body
3255health_required_fields:
3256  - body
3257staleness_threshold_days: 90
3258write_rules: []
3259"#
3260        .to_string();
3261        vec![
3262            ("schema.yaml".to_string(), manifest.into_bytes()),
3263            ("types/sample.yaml".to_string(), type_yaml.into_bytes()),
3264            ("types/other.yaml".to_string(), other_yaml.into_bytes()),
3265        ]
3266    }
3267
3268    /// The exemplar gate: a package whose type
3269    /// carries a CONFORMANT exemplar installs; the same package broken
3270    /// three ways — wrong section key, illegal enum value, relationship
3271    /// shape violation — refuses with a typed error naming the type
3272    /// and the defect. No warn-and-carry path exists: the refusal is
3273    /// `SchemaPackageInvalid`, same as every other install-gate class.
3274    #[test]
3275    fn install_gate_validates_exemplars_through_the_real_create_path() {
3276        // Conformant exemplar → the package installs.
3277        let ok = Engine::validate_schema_package(
3278            "gate",
3279            "1.0.0",
3280            &exemplar_package_files("body", "draft", "PART_OF"),
3281        );
3282        assert!(ok.is_ok(), "conformant exemplar passes: {ok:?}");
3283
3284        // Variant 1 — wrong section key.
3285        let err = Engine::validate_schema_package(
3286            "gate",
3287            "1.0.0",
3288            &exemplar_package_files("bogus_section", "draft", "PART_OF"),
3289        )
3290        .expect_err("wrong section key must refuse");
3291        match &err {
3292            EngineError::SchemaPackageInvalid { message, .. } => {
3293                assert!(
3294                    message.contains("'sample'") && message.contains("exemplar"),
3295                    "names type and calls out the exemplar: {message}"
3296                );
3297                assert!(
3298                    message.contains("UNKNOWN_SECTION")
3299                        || message.contains("MISSING_REQUIRED_SECTION"),
3300                    "carries the typed defect code: {message}"
3301                );
3302            }
3303            other => panic!("expected SchemaPackageInvalid, got {other:?}"),
3304        }
3305
3306        // Variant 2 — illegal enum value.
3307        let err = Engine::validate_schema_package(
3308            "gate",
3309            "1.0.0",
3310            &exemplar_package_files("body", "not-a-legal-status", "PART_OF"),
3311        )
3312        .expect_err("illegal enum value must refuse");
3313        assert!(
3314            matches!(&err, EngineError::SchemaPackageInvalid { message, .. }
3315                if message.contains("'sample'") && message.contains("INVALID_ENUM_VALUE")),
3316            "got {err:?}"
3317        );
3318
3319        // Variant 3 — relationship shape violation (REFINES is pinned
3320        // to source_types [other]; the exemplar's type is `sample`).
3321        let err = Engine::validate_schema_package(
3322            "gate",
3323            "1.0.0",
3324            &exemplar_package_files("body", "draft", "REFINES"),
3325        )
3326        .expect_err("relationship shape violation must refuse");
3327        assert!(
3328            matches!(&err, EngineError::SchemaPackageInvalid { message, .. }
3329                if message.contains("'sample'") && message.contains("INVALID_REL_SHAPE")),
3330            "got {err:?}"
3331        );
3332    }
3333
3334    /// The worked-example teaching package (`memstead-schema/examples/
3335    /// minimal`) models the exemplar practice — its exemplars validate
3336    /// through the same gate, so the material that teaches schema
3337    /// authoring can never itself teach a non-conformant shape.
3338    #[test]
3339    fn worked_example_package_exemplars_validate() {
3340        let pkg = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3341            .join("../memstead-schema/examples/minimal");
3342        let schema = std::sync::Arc::new(
3343            memstead_schema::load_schema_from_dir(&pkg).expect("worked example loads"),
3344        );
3345        assert!(
3346            schema.types.values().all(|td| td.exemplar.is_some()),
3347            "every worked-example type models the exemplar practice"
3348        );
3349        Engine::validate_schema_exemplars(&schema).expect("worked-example exemplars conform");
3350    }
3351
3352    /// Every built-in schema's exemplars validate through the SAME
3353    /// gate the install path runs — a built-in exemplar broken by a
3354    /// future edit fails CI here. Completeness rides the same walk:
3355    /// the NEWEST version of every built-in name carries an exemplar
3356    /// on every type (older versions are sealed as shipped and may
3357    /// predate the field).
3358    #[test]
3359    fn builtin_exemplars_validate_through_the_install_gate() {
3360        let schemas = memstead_schema::builtins::load_builtin_schemas()
3361            .expect("built-in schemas always load");
3362        // Validity: every exemplar anywhere in the catalogue conforms.
3363        for schema in &schemas {
3364            if let Err(defect) = Engine::validate_schema_exemplars(schema) {
3365                let (name, version) = schema.id();
3366                panic!("built-in {name}@{version}: {defect}");
3367            }
3368        }
3369        // Completeness: the newest version per name is exemplar-complete.
3370        let mut newest: std::collections::HashMap<
3371            String,
3372            &std::sync::Arc<memstead_schema::Schema>,
3373        > = std::collections::HashMap::new();
3374        for schema in &schemas {
3375            let name = schema.manifest.name.clone();
3376            match newest.get(&name) {
3377                Some(cur) if cur.version >= schema.version => {}
3378                _ => {
3379                    newest.insert(name, schema);
3380                }
3381            }
3382        }
3383        for (name, schema) in &newest {
3384            for (type_name, td) in &schema.types {
3385                assert!(
3386                    td.exemplar.is_some(),
3387                    "built-in {name}@{} type '{type_name}' has no exemplar — the \
3388                     reference schemas model the practice completely",
3389                    schema.version
3390                );
3391            }
3392        }
3393    }
3394
3395    /// Exemplar relation targets are PLACEHOLDERS: a bare slug is
3396    /// legal (target existence is never checked — the absent target
3397    /// is the would-be-stub path), while a mem-prefixed target
3398    /// refuses with the placeholder rule named.
3399    #[test]
3400    fn exemplar_relation_targets_are_bare_placeholder_slugs() {
3401        let mut files = exemplar_package_files("body", "draft", "PART_OF");
3402        let patched = String::from_utf8(files[1].1.clone())
3403            .unwrap()
3404            .replace("to: parent-placeholder", "to: other--real-entity");
3405        files[1].1 = patched.into_bytes();
3406        let err = Engine::validate_schema_package("gate", "1.0.0", &files)
3407            .expect_err("mem-prefixed exemplar target must refuse");
3408        assert!(
3409            matches!(&err, EngineError::SchemaPackageInvalid { message, .. }
3410                if message.contains("bare") && message.contains("'sample'")),
3411            "got {err:?}"
3412        );
3413    }
3414
3415    /// A manifest whose declared identity contradicts the install ref
3416    /// is refused — the schema would otherwise seal under a ref its
3417    /// own manifest disagrees with.
3418    #[test]
3419    fn install_gate_refuses_manifest_identity_mismatch() {
3420        let err = Engine::validate_schema_package(
3421            "gate",
3422            "1.0.0",
3423            &schema_package_files("Body", "other"),
3424        )
3425        .expect_err("identity mismatch must refuse install");
3426        assert!(
3427            matches!(&err, EngineError::SchemaPackageInvalid { message, .. }
3428                if message.contains("other@1.0.0")),
3429            "got {err:?}"
3430        );
3431    }
3432
3433    #[test]
3434    fn reload_each_writable_mem_repopulates_load_warnings() {
3435        // Boot with a clean mem, then mid-flight write a file
3436        // with a duplicate heading, then call reload_each_writable_mem.
3437        // The accumulator should pick up the new typed warning.
3438        let tmp = TempDir::new().unwrap();
3439        let mem_dir = tmp.path().to_path_buf();
3440        let writer = FilesystemMemWriter::new(mem_dir.clone());
3441        // Newest default generation so the clean-boot baseline isn't
3442        // tripped by the SCHEMA_GENERATIONS_BEHIND hint.
3443        let mut mount = folder_mount("specs", mem_dir.clone());
3444        mount.schema = Some("default@1.3.0".parse().unwrap());
3445        let mut engine =
3446            Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
3447        // The only thing a clean, entity-less mount says about itself
3448        // is that it is empty (`MOUNT_UNBACKED` / `empty`).
3449        assert!(
3450            engine
3451                .load_warnings()
3452                .iter()
3453                .all(|w| w.code() == "MOUNT_UNBACKED"),
3454            "clean boot has no warnings beyond the empty-mount one: {:?}",
3455            engine.load_warnings()
3456        );
3457
3458        // Drop a markdown file with two `## Identity` headings.
3459        let body =
3460            "---\ntype: spec\n---\n# Dup\n\n## Identity\n\nfirst.\n\n## Identity\n\nsecond.\n";
3461        std::fs::write(mem_dir.join("dup.md"), body).unwrap();
3462
3463        engine.reload_each_writable_mem().unwrap();
3464        let warnings = engine.load_warnings();
3465        assert!(
3466            warnings
3467                .iter()
3468                .any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
3469            "workspace-wide reload must repopulate load_warnings: {warnings:?}",
3470        );
3471    }
3472
3473    /// `validate_loaded_relations` runs on the reload path too — a
3474    /// sibling-writer commit that injects a markdown file carrying a
3475    /// schema-undeclared rel-type must surface as a typed
3476    /// `PARSED_RELATION_INVALID` warning after `reload_each_writable_mem`.
3477    /// Without the reload-path wiring this drift would slip past the
3478    /// validator (boot only catches what existed at startup).
3479    #[test]
3480    fn reload_picks_up_parse_time_relation_drift_from_sibling_writer() {
3481        let tmp = TempDir::new().unwrap();
3482        let mem_dir = tmp.path().to_path_buf();
3483        // Seed a clean target entity at boot.
3484        let target_body = "---\ntype: spec\n---\n# Target\n\n## Identity\n\nThe target.\n";
3485        std::fs::write(mem_dir.join("target.md"), target_body).unwrap();
3486        let writer = FilesystemMemWriter::new(mem_dir.clone());
3487        let mut engine = Engine::from_mounts(vec![(
3488            folder_mount("specs", mem_dir.clone()),
3489            Box::new(writer) as Box<dyn MemBackend>,
3490        )])
3491        .unwrap();
3492        // Clean boot — no parse-time relation warnings yet.
3493        assert!(
3494            !engine
3495                .load_warnings()
3496                .iter()
3497                .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { .. })),
3498            "clean boot must not emit ParsedRelationInvalid; got: {:?}",
3499            engine.load_warnings()
3500        );
3501
3502        // Sibling-writer drops a new file with an unknown rel-type.
3503        let drift_body = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[specs--target]]\n";
3504        std::fs::write(mem_dir.join("source.md"), drift_body).unwrap();
3505
3506        engine.reload_each_writable_mem().unwrap();
3507
3508        let invalid: Vec<_> = engine
3509            .load_warnings()
3510            .iter()
3511            .filter_map(|w| match w {
3512                WarningHint::ParsedRelationInvalid {
3513                    rel_type,
3514                    reason,
3515                    origin,
3516                    ..
3517                } => Some((rel_type.clone(), reason.clone(), origin.clone())),
3518                _ => None,
3519            })
3520            .collect();
3521        assert_eq!(
3522            invalid.len(),
3523            1,
3524            "reload must surface the parse-time drift, got: {invalid:?}",
3525        );
3526        assert_eq!(invalid[0].0, "MADE_UP_TYPE");
3527        assert_eq!(invalid[0].1, "unknown_rel_type");
3528        assert_eq!(invalid[0].2, "writable");
3529    }
3530
3531    #[test]
3532    fn reload_one_mem_refreshes_own_slice_and_keeps_other_mems() {
3533        // Boot two mems, each with a duplicate-heading file, so the
3534        // accumulator carries one warning per mem. Fix alpha's file on
3535        // disk, reload ONLY alpha: alpha's stale warning must drop
3536        // (reload heals drift — health() must stop reporting it) while
3537        // beta's untouched warning survives (per-mem reload never
3538        // clears other mems' slices).
3539        let tmp = TempDir::new().unwrap();
3540        let dup_body = "---\ntype: spec\n---\n# Dup\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
3541        let a_dir = tmp.path().join("a");
3542        std::fs::create_dir_all(&a_dir).unwrap();
3543        std::fs::write(a_dir.join("dup.md"), dup_body).unwrap();
3544        let b_dir = tmp.path().join("b");
3545        std::fs::create_dir_all(&b_dir).unwrap();
3546        std::fs::write(b_dir.join("dup.md"), dup_body).unwrap();
3547        let mut engine = Engine::from_mounts(vec![
3548            (
3549                folder_mount("alpha", a_dir.clone()),
3550                Box::new(FilesystemMemWriter::new(a_dir.clone())) as Box<dyn MemBackend>,
3551            ),
3552            (
3553                folder_mount("beta", b_dir.clone()),
3554                Box::new(FilesystemMemWriter::new(b_dir.clone())) as Box<dyn MemBackend>,
3555            ),
3556        ])
3557        .unwrap();
3558        let mem_of = |w: &WarningHint| w.source_mem().map(str::to_string);
3559        let pre: Vec<_> = engine.load_warnings().iter().filter_map(mem_of).collect();
3560        assert!(
3561            pre.contains(&"alpha".to_string()) && pre.contains(&"beta".to_string()),
3562            "boot must populate one warning per mem: {pre:?}"
3563        );
3564
3565        // Heal alpha's file on disk, then reload only alpha.
3566        let clean_body = "---\ntype: spec\n---\n# Dup\n\n## Identity\n\na.\n";
3567        std::fs::write(a_dir.join("dup.md"), clean_body).unwrap();
3568        engine.reload_one_mem("alpha").unwrap();
3569
3570        let post: Vec<_> = engine.load_warnings().iter().filter_map(mem_of).collect();
3571        assert!(
3572            !post.contains(&"alpha".to_string()),
3573            "reload must drop the healed mem's stale warning: {post:?}"
3574        );
3575        assert!(
3576            post.contains(&"beta".to_string()),
3577            "reload of alpha must not clear beta's slice: {post:?}"
3578        );
3579    }
3580
3581    #[test]
3582    fn unregister_writable_mem_purges_load_warnings_for_that_mem_only() {
3583        // Two mems, each contributing a boot-time warning. Deleting
3584        // alpha must purge alpha's warnings from the accumulator
3585        // (health() merges it unconditionally — leftovers would cite
3586        // entities the store no longer holds) while beta's survive.
3587        let tmp = TempDir::new().unwrap();
3588        let dup_body = "---\ntype: spec\n---\n# Dup\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
3589        let a_dir = tmp.path().join("a");
3590        std::fs::create_dir_all(&a_dir).unwrap();
3591        std::fs::write(a_dir.join("dup.md"), dup_body).unwrap();
3592        let b_dir = tmp.path().join("b");
3593        std::fs::create_dir_all(&b_dir).unwrap();
3594        std::fs::write(b_dir.join("dup.md"), dup_body).unwrap();
3595        let mut engine = Engine::from_mounts(vec![
3596            (
3597                folder_mount("alpha", a_dir.clone()),
3598                Box::new(FilesystemMemWriter::new(a_dir)) as Box<dyn MemBackend>,
3599            ),
3600            (
3601                folder_mount("beta", b_dir.clone()),
3602                Box::new(FilesystemMemWriter::new(b_dir)) as Box<dyn MemBackend>,
3603            ),
3604        ])
3605        .unwrap();
3606        assert!(
3607            engine
3608                .load_warnings()
3609                .iter()
3610                .any(|w| w.source_mem() == Some("alpha")),
3611            "boot must carry alpha-sourced warnings"
3612        );
3613
3614        engine.unregister_writable_mem("alpha").unwrap();
3615
3616        let post = engine.load_warnings();
3617        assert!(
3618            !post.iter().any(|w| w.source_mem() == Some("alpha")),
3619            "delete must purge the removed mem's warnings: {post:?}"
3620        );
3621        assert!(
3622            post.iter().any(|w| w.source_mem() == Some("beta")),
3623            "delete of alpha must keep beta's warnings: {post:?}"
3624        );
3625    }
3626
3627    #[test]
3628    fn unregister_writable_mem_keeps_warnings_sourced_in_surviving_mems() {
3629        // Complement to the purge: a warning SOURCED in a surviving
3630        // mem whose TARGET pointed into the deleted mem must survive.
3631        // The invalid row still exists in the survivor's markdown —
3632        // it is live drift (recover-worthy), not stale state, so
3633        // purging by target would hide a real finding.
3634        let tmp = TempDir::new().unwrap();
3635        let a_dir = tmp.path().join("a");
3636        std::fs::create_dir_all(&a_dir).unwrap();
3637        let source_body = "---\ntype: spec\n---\n# Source\n\n## Identity\n\nThe source.\n\n## Relationships\n\n- **MADE_UP_TYPE**: [[beta--b1]]\n";
3638        std::fs::write(a_dir.join("source.md"), source_body).unwrap();
3639        let b_dir = tmp.path().join("b");
3640        std::fs::create_dir_all(&b_dir).unwrap();
3641        let target_body = "---\ntype: spec\n---\n# B1\n\n## Identity\n\nThe target.\n";
3642        std::fs::write(b_dir.join("b1.md"), target_body).unwrap();
3643        let mut engine = Engine::from_mounts(vec![
3644            (
3645                folder_mount("alpha", a_dir.clone()),
3646                Box::new(FilesystemMemWriter::new(a_dir)) as Box<dyn MemBackend>,
3647            ),
3648            (
3649                folder_mount("beta", b_dir.clone()),
3650                Box::new(FilesystemMemWriter::new(b_dir)) as Box<dyn MemBackend>,
3651            ),
3652        ])
3653        .unwrap();
3654        let alpha_sourced = |engine: &Engine| {
3655            engine
3656                .load_warnings()
3657                .iter()
3658                .any(|w| matches!(w, WarningHint::ParsedRelationInvalid { entity_id, .. } if entity_id.mem() == "alpha"))
3659        };
3660        assert!(
3661            alpha_sourced(&engine),
3662            "boot must flag alpha's invalid row: {:?}",
3663            engine.load_warnings()
3664        );
3665
3666        engine.unregister_writable_mem("beta").unwrap();
3667
3668        assert!(
3669            alpha_sourced(&engine),
3670            "deleting the TARGET mem must not purge the survivor-sourced warning: {:?}",
3671            engine.load_warnings()
3672        );
3673    }
3674
3675    /// The `memstead_reload` MCP tool's no-mem path consumes the
3676    /// reports variant — it must refresh `load_warnings` like its slim
3677    /// counterpart, not discard the sweep's warnings. Regression for
3678    /// the split-brain where the slim variant repopulated and the
3679    /// reports variant silently kept the boot-time snapshot forever
3680    /// (observed live 2026-07-11: warnings for deleted mems survived a
3681    /// workspace-wide MCP reload).
3682    #[test]
3683    fn reload_each_writable_mem_reports_refreshes_load_warnings() {
3684        let tmp = TempDir::new().unwrap();
3685        let mem_dir = tmp.path().to_path_buf();
3686        let dup_body = "---\ntype: spec\n---\n# Dup\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
3687        std::fs::write(mem_dir.join("dup.md"), dup_body).unwrap();
3688        let writer = FilesystemMemWriter::new(mem_dir.clone());
3689        let mut engine = Engine::from_mounts(vec![(
3690            folder_mount("specs", mem_dir.clone()),
3691            Box::new(writer) as Box<dyn MemBackend>,
3692        )])
3693        .unwrap();
3694        assert!(
3695            !engine.load_warnings().is_empty(),
3696            "boot must populate load_warnings"
3697        );
3698
3699        // Heal the file on disk; the reports sweep must clear the
3700        // stale warning.
3701        let clean_body = "---\ntype: spec\n---\n# Dup\n\n## Identity\n\na.\n";
3702        std::fs::write(mem_dir.join("dup.md"), clean_body).unwrap();
3703        engine.reload_each_writable_mem_reports().unwrap();
3704        assert!(
3705            engine.load_warnings().is_empty(),
3706            "reports sweep must drop healed warnings: {:?}",
3707            engine.load_warnings()
3708        );
3709
3710        // And the inverse: fresh drift surfaces through the same sweep.
3711        std::fs::write(mem_dir.join("dup.md"), dup_body).unwrap();
3712        engine.reload_each_writable_mem_reports().unwrap();
3713        assert!(
3714            engine
3715                .load_warnings()
3716                .iter()
3717                .any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
3718            "reports sweep must surface fresh drift: {:?}",
3719            engine.load_warnings()
3720        );
3721    }
3722
3723    /// A cross-mem edge `A→B` must survive a
3724    /// per-mem reload of the TARGET mem B. The removal cascade drops
3725    /// B's incoming mirrors (including the cross-mem one sourced from A)
3726    /// and the re-push only rebuilds edges authored by B, so without the
3727    /// reconstruction pass the edge silently vanishes from the in-memory
3728    /// index while staying intact in A's record and on disk — under-
3729    /// reporting topology until a workspace-wide reload heals it.
3730    #[test]
3731    fn per_mem_reload_of_target_preserves_incoming_cross_mem_edge() {
3732        let tmp = TempDir::new().unwrap();
3733        let a_dir = tmp.path().join("a");
3734        let b_dir = tmp.path().join("b");
3735        std::fs::create_dir_all(&a_dir).unwrap();
3736        std::fs::create_dir_all(&b_dir).unwrap();
3737        let a_writer = FilesystemMemWriter::new(a_dir.clone());
3738        let b_writer = FilesystemMemWriter::new(b_dir.clone());
3739        let mut engine = Engine::from_mounts(vec![
3740            (
3741                folder_mount("specs", a_dir),
3742                Box::new(a_writer) as Box<dyn MemBackend>,
3743            ),
3744            (
3745                folder_mount("memos", b_dir),
3746                Box::new(b_writer) as Box<dyn MemBackend>,
3747            ),
3748        ])
3749        .unwrap();
3750
3751        // Grant the cross-mem link specs → memos so the relate lands.
3752        let mut settings = crate::workspace::WorkspaceSettings::default();
3753        settings.cross_mem_links.insert(
3754            "specs".to_string(),
3755            memstead_schema::workspace_config::CrossLinkValue::Wildcard,
3756        );
3757        engine.set_settings(settings);
3758
3759        let (actor, client) = cli_actor();
3760        let source = engine
3761            .create_entity(
3762                empty_create_args("specs", "Source"),
3763                actor,
3764                Some(&client),
3765                None,
3766            )
3767            .unwrap();
3768        let target = engine
3769            .create_entity(
3770                empty_create_args("memos", "Target"),
3771                actor,
3772                Some(&client),
3773                None,
3774            )
3775            .unwrap();
3776        engine
3777            .relate_entity(
3778                crate::engine::RelateEntityArgs {
3779                    source: source.id.clone(),
3780                    expected_hash: Some(source.content_hash.clone()),
3781                    rel_type: "USES".to_string(),
3782                    target: target.id.clone(),
3783                    remove: false,
3784                    description: None,
3785                    dry_run: false,
3786                },
3787                actor,
3788                Some(&client),
3789                None,
3790            )
3791            .unwrap();
3792
3793        // (outgoing-present, incoming-present) for the A→B edge.
3794        let has_edge = |e: &Engine| {
3795            let out = e
3796                .store()
3797                .outgoing(&source.id)
3798                .iter()
3799                .any(|edge| edge.target == target.id);
3800            let inc = e
3801                .store()
3802                .incoming(&target.id)
3803                .iter()
3804                .any(|edge| edge.from == source.id);
3805            (out, inc)
3806        };
3807
3808        assert_eq!(
3809            has_edge(&engine),
3810            (true, true),
3811            "edge must be indexed in both directions after relate",
3812        );
3813
3814        // Per-mem reload of the TARGET mem — the bug trigger.
3815        engine.reload_one_mem("memos").unwrap();
3816        assert_eq!(
3817            has_edge(&engine),
3818            (true, true),
3819            "cross-mem edge into B must survive a per-mem reload of B",
3820        );
3821
3822        // Convergence: a workspace-wide reload yields the same incoming
3823        // adjacency for the target — no path-dependent difference.
3824        engine.reload_each_writable_mem().unwrap();
3825        assert_eq!(
3826            has_edge(&engine),
3827            (true, true),
3828            "per-mem and workspace reload converge on the same edge",
3829        );
3830
3831        // Complement: the edge stayed in the source record throughout —
3832        // the bug and the fix are about the index, not the records.
3833        assert!(
3834            engine
3835                .store()
3836                .get(&source.id)
3837                .unwrap()
3838                .relationships
3839                .iter()
3840                .any(|r| r.target == target.id),
3841            "source record must retain the relationship throughout",
3842        );
3843    }
3844
3845    /// A per-mem reload of the SOURCE
3846    /// mem leaves the cross-mem edge intact too — the source's own
3847    /// outgoing edges are rebuilt by the re-push, and the reconstruction
3848    /// pass for the OTHER mem is not needed here. Guards against a fix
3849    /// that fixates on the target case and perturbs the source case.
3850    #[test]
3851    fn per_mem_reload_of_source_preserves_outgoing_cross_mem_edge() {
3852        let tmp = TempDir::new().unwrap();
3853        let a_dir = tmp.path().join("a");
3854        let b_dir = tmp.path().join("b");
3855        std::fs::create_dir_all(&a_dir).unwrap();
3856        std::fs::create_dir_all(&b_dir).unwrap();
3857        let a_writer = FilesystemMemWriter::new(a_dir.clone());
3858        let b_writer = FilesystemMemWriter::new(b_dir.clone());
3859        let mut engine = Engine::from_mounts(vec![
3860            (
3861                folder_mount("specs", a_dir),
3862                Box::new(a_writer) as Box<dyn MemBackend>,
3863            ),
3864            (
3865                folder_mount("memos", b_dir),
3866                Box::new(b_writer) as Box<dyn MemBackend>,
3867            ),
3868        ])
3869        .unwrap();
3870        let mut settings = crate::workspace::WorkspaceSettings::default();
3871        settings.cross_mem_links.insert(
3872            "specs".to_string(),
3873            memstead_schema::workspace_config::CrossLinkValue::Wildcard,
3874        );
3875        engine.set_settings(settings);
3876
3877        let (actor, client) = cli_actor();
3878        let source = engine
3879            .create_entity(
3880                empty_create_args("specs", "Source"),
3881                actor,
3882                Some(&client),
3883                None,
3884            )
3885            .unwrap();
3886        let target = engine
3887            .create_entity(
3888                empty_create_args("memos", "Target"),
3889                actor,
3890                Some(&client),
3891                None,
3892            )
3893            .unwrap();
3894        engine
3895            .relate_entity(
3896                crate::engine::RelateEntityArgs {
3897                    source: source.id.clone(),
3898                    expected_hash: Some(source.content_hash.clone()),
3899                    rel_type: "USES".to_string(),
3900                    target: target.id.clone(),
3901                    remove: false,
3902                    description: None,
3903                    dry_run: false,
3904                },
3905                actor,
3906                Some(&client),
3907                None,
3908            )
3909            .unwrap();
3910
3911        engine.reload_one_mem("specs").unwrap();
3912
3913        let out = engine
3914            .store()
3915            .outgoing(&source.id)
3916            .iter()
3917            .any(|edge| edge.target == target.id);
3918        let inc = engine
3919            .store()
3920            .incoming(&target.id)
3921            .iter()
3922            .any(|edge| edge.from == source.id);
3923        assert!(
3924            out && inc,
3925            "outgoing cross-mem edge must survive a source-mem reload"
3926        );
3927    }
3928
3929    #[test]
3930    fn workspace_root_setter_round_trips() {
3931        let tmp = TempDir::new().unwrap();
3932        let mem_dir = tmp.path().to_path_buf();
3933        let writer = FilesystemMemWriter::new(mem_dir.clone());
3934        let mut engine = Engine::from_mounts(vec![(
3935            folder_mount("specs", mem_dir),
3936            Box::new(writer) as Box<dyn MemBackend>,
3937        )])
3938        .unwrap();
3939        let root = tmp.path().to_path_buf();
3940        engine.set_workspace_root(root.clone());
3941        assert_eq!(engine.workspace_root(), Some(root.as_path()));
3942    }
3943
3944    #[test]
3945    fn export_mem_folder_backend_produces_archive() {
3946        // Folder-backed mem with config + one entity. The
3947        // export_mem dispatcher routes to the folder backend's
3948        // override which produces a deterministic .memstead archive.
3949        let tmp = TempDir::new().unwrap();
3950        let mem_dir = tmp.path().join("specs");
3951        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
3952        let config_body = r#"{
3953            "format": 1,
3954            "schema": "default@1.0.0",
3955            "version": "1.0.0"
3956        }"#;
3957        std::fs::write(mem_dir.join(".memstead").join("config.json"), config_body).unwrap();
3958
3959        let writer = FilesystemMemWriter::new(mem_dir.clone());
3960        let engine = Engine::from_mounts(vec![(
3961            folder_mount("specs", mem_dir.clone()),
3962            Box::new(writer) as Box<dyn MemBackend>,
3963        )])
3964        .unwrap();
3965
3966        let archive_path = tmp.path().join("specs.mem");
3967        let result = engine.export_mem("specs", &archive_path).unwrap();
3968        assert!(archive_path.exists(), "archive must exist on disk");
3969        assert!(result.size_bytes > 0);
3970        // entity_count is 0 here (no .md files seeded); the function
3971        // still produces an archive carrying the config + schema.
3972        assert_eq!(result.entity_count, 0);
3973    }
3974
3975    #[test]
3976    fn export_mem_unknown_mem_returns_unknown_mem() {
3977        let tmp = TempDir::new().unwrap();
3978        let mem_dir = tmp.path().to_path_buf();
3979        let writer = FilesystemMemWriter::new(mem_dir.clone());
3980        let engine = Engine::from_mounts(vec![(
3981            folder_mount("specs", mem_dir),
3982            Box::new(writer) as Box<dyn MemBackend>,
3983        )])
3984        .unwrap();
3985        let output = tmp.path().join("out.mem");
3986        let err = engine.export_mem("missing", &output).unwrap_err();
3987        assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
3988    }
3989
3990    #[test]
3991    fn export_mem_missing_config_returns_invalid_input() {
3992        // Folder mount with no .memstead/config.json — `mem_config_for`
3993        // returns None and `export_mem` surfaces InvalidInput
3994        // rather than reaching the backend.
3995        let tmp = TempDir::new().unwrap();
3996        let mem_dir = tmp.path().to_path_buf();
3997        let writer = FilesystemMemWriter::new(mem_dir.clone());
3998        let engine = Engine::from_mounts(vec![(
3999            folder_mount("specs", mem_dir),
4000            Box::new(writer) as Box<dyn MemBackend>,
4001        )])
4002        .unwrap();
4003        let output = tmp.path().join("out.mem");
4004        let err = engine.export_mem("specs", &output).unwrap_err();
4005        assert!(matches!(err, EngineError::InvalidInput(_)));
4006    }
4007
4008    #[test]
4009    fn export_mem_archive_backend_returns_sealed() {
4010        // Archive backends are already-an-archive — re-export is
4011        // intentionally rejected via BackendError::Sealed.
4012        let tmp = TempDir::new().unwrap();
4013        let archive_path = build_archive(
4014            tmp.path(),
4015            "ext",
4016            &[(
4017                ".memstead/config.json",
4018                b"{\"format\":1,\"schema\":\"default@1.0.0\",\"version\":\"1.0.0\"}",
4019            )],
4020        );
4021        let engine = Engine::from_mounts(vec![(
4022            archive_mount("ext", archive_path.clone()),
4023            Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
4024        )])
4025        .unwrap();
4026        let output = tmp.path().join("out.mem");
4027        let err = engine.export_mem("ext", &output).unwrap_err();
4028        assert!(matches!(err, EngineError::Backend(BackendError::Sealed)));
4029    }
4030
4031    #[test]
4032    fn export_markdown_writes_unchanged_files_zero_writes() {
4033        // Seed a folder-backed mem with one entity, then call
4034        // export_markdown. The entity's file already matches the
4035        // generated content (engine wrote it via create_entity), so
4036        // export reports `unchanged: 1, written: 0`.
4037        let tmp = TempDir::new().unwrap();
4038        let (engine, _seeded) = engine_with_seed(&tmp, "Sample");
4039        let result = engine.export_markdown(None, None).unwrap();
4040        assert_eq!(
4041            result.written, 0,
4042            "freshly-created entity's file already matches generated markdown"
4043        );
4044        assert_eq!(
4045            result.unchanged, 1,
4046            "the one seeded entity counts as unchanged"
4047        );
4048        assert!(
4049            result.skipped_mounts.is_empty(),
4050            "folder-only workspace has no skipped mounts"
4051        );
4052    }
4053
4054    #[test]
4055    fn export_markdown_skips_non_folder_mounts() {
4056        // Archive-mounted mem has no working tree — workspace-wide
4057        // export records it under skipped_mounts and reports zero
4058        // writes / zero unchanged for the rest.
4059        let tmp = TempDir::new().unwrap();
4060        let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"# Title: Foo\n")]);
4061        let engine = Engine::from_mounts(vec![(
4062            archive_mount("ext", archive_path.clone()),
4063            Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
4064        )])
4065        .unwrap();
4066        let result = engine.export_markdown(None, None).unwrap();
4067        assert_eq!(result.written, 0);
4068        assert_eq!(result.unchanged, 0);
4069        assert_eq!(
4070            result.skipped_mounts.len(),
4071            1,
4072            "archive mount is in the skipped list"
4073        );
4074        let entry = &result.skipped_mounts[0];
4075        assert_eq!(entry.mem, "ext");
4076        assert_eq!(entry.active_backend, "archive");
4077        assert_eq!(entry.reason, "backend_does_not_support_markdown_export");
4078    }
4079
4080    #[test]
4081    fn export_markdown_per_mem_refuses_on_incompatible_backend() {
4082        // Per-mem export against an archive-backed mem returns
4083        // the typed `MARKDOWN_EXPORT_UNSUPPORTED_BACKEND` refusal
4084        // naming the active backend and the supported-backend list.
4085        let tmp = TempDir::new().unwrap();
4086        let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"# Title: Foo\n")]);
4087        let engine = Engine::from_mounts(vec![(
4088            archive_mount("ext", archive_path.clone()),
4089            Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
4090        )])
4091        .unwrap();
4092        let err = engine.export_markdown(Some("ext"), None).unwrap_err();
4093        assert_eq!(err.code(), "MARKDOWN_EXPORT_UNSUPPORTED_BACKEND");
4094        let details = err.details();
4095        assert_eq!(details["mem"], "ext");
4096        assert_eq!(details["active_backend"], "archive");
4097        assert_eq!(details["supported_backends"], serde_json::json!(["folder"]));
4098    }
4099
4100    #[test]
4101    fn register_writable_mem_adds_mount_and_router_entry() {
4102        // Start with one mem; register a second at runtime. Both
4103        // should be visible afterwards.
4104        let tmp = TempDir::new().unwrap();
4105        let mem_a = tmp.path().join("a");
4106        std::fs::create_dir_all(&mem_a).unwrap();
4107        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4108
4109        let mut engine = Engine::from_mounts(vec![(
4110            folder_mount("alpha", mem_a),
4111            Box::new(writer_a) as Box<dyn MemBackend>,
4112        )])
4113        .unwrap();
4114        assert!(engine.mem_router().is_writable("alpha"));
4115
4116        let mem_b = tmp.path().join("b");
4117        std::fs::create_dir_all(&mem_b).unwrap();
4118        let writer_b = FilesystemMemWriter::new(mem_b.clone());
4119
4120        engine
4121            .register_writable_mem(
4122                folder_mount("beta", mem_b.clone()),
4123                Box::new(writer_b) as Box<dyn MemBackend>,
4124                MemOrigin::ExplicitToml,
4125            )
4126            .unwrap();
4127
4128        // Both mems are now writable + visible.
4129        assert!(engine.mem_router().is_writable("alpha"));
4130        assert!(engine.mem_router().is_writable("beta"));
4131        assert!(engine.mem_router().is_visible("beta"));
4132
4133        // Mount + schema lookups resolve.
4134        assert!(engine.mount("beta").is_some());
4135        assert!(engine.schemas().contains_key("beta"));
4136
4137        // Folder path surfaces via mem_router.
4138        assert_eq!(
4139            engine.mem_router().dir_for_mem("beta"),
4140            Some(mem_b.as_path()),
4141        );
4142    }
4143
4144    /// Schema-pin authority on the runtime-register path (symmetric with
4145    /// the boot path): a mem registered at runtime resolves its schema
4146    /// from its own config (`software@0.1.0`) even though the mount
4147    /// expects an unresolvable pin — register succeeds, and the
4148    /// disagreement surfaces a `SchemaPinMismatch` warning.
4149    #[test]
4150    fn register_writable_mem_resolves_schema_from_mem_config() {
4151        let tmp = TempDir::new().unwrap();
4152        let mem_a = tmp.path().join("a");
4153        std::fs::create_dir_all(&mem_a).unwrap();
4154        let mut engine = Engine::from_mounts(vec![(
4155            folder_mount("alpha", mem_a.clone()),
4156            Box::new(FilesystemMemWriter::new(mem_a)) as Box<dyn MemBackend>,
4157        )])
4158        .unwrap();
4159
4160        let mem_b = tmp.path().join("b");
4161        std::fs::create_dir_all(mem_b.join(".memstead")).unwrap();
4162        std::fs::write(
4163            mem_b.join(".memstead").join("config.json"),
4164            r#"{"schema":"software@0.1.0"}"#,
4165        )
4166        .unwrap();
4167        let mount_b = crate::workspace::Mount {
4168            mem: "beta".to_string(),
4169            schema: Some(memstead_schema::SchemaRef::new(
4170                "totally-not-a-schema",
4171                semver::Version::new(9, 9, 9),
4172            )),
4173            storage: crate::workspace::MountStorage::Folder {
4174                path: mem_b.clone(),
4175            },
4176            capability: crate::workspace::MountCapability::Write,
4177            lifecycle: crate::workspace::MountLifecycle::Eager,
4178            cross_linkable: true,
4179            migration_target: None,
4180        };
4181        engine
4182            .register_writable_mem(
4183                mount_b,
4184                Box::new(FilesystemMemWriter::new(mem_b)) as Box<dyn MemBackend>,
4185                MemOrigin::ExplicitToml,
4186            )
4187            .expect("config pin software@0.1.0 is authoritative — register must succeed despite the unresolvable mount pin");
4188
4189        assert!(engine.schemas().contains_key("beta"));
4190        let surfaced = engine.load_warnings().iter().any(|w| {
4191            matches!(
4192                w,
4193                WarningHint::SchemaPinMismatch { mem, config_pin, mount_pin }
4194                    if mem == "beta"
4195                        && config_pin == "software@0.1.0"
4196                        && mount_pin == "totally-not-a-schema@9.9.9"
4197            )
4198        });
4199        assert!(
4200            surfaced,
4201            "SchemaPinMismatch must surface for beta: {:?}",
4202            engine.load_warnings(),
4203        );
4204    }
4205
4206    #[test]
4207    fn register_writable_mem_rejects_existing_name() {
4208        // Re-registering an already-writable mem must fail with
4209        // MemNameCollision and not mutate the engine.
4210        let tmp = TempDir::new().unwrap();
4211        let mem_a = tmp.path().join("a");
4212        std::fs::create_dir_all(&mem_a).unwrap();
4213        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4214
4215        let mut engine = Engine::from_mounts(vec![(
4216            folder_mount("alpha", mem_a),
4217            Box::new(writer_a) as Box<dyn MemBackend>,
4218        )])
4219        .unwrap();
4220        let mount_count_pre = engine.mounts().len();
4221
4222        let mem_collide = tmp.path().join("alpha-2");
4223        std::fs::create_dir_all(&mem_collide).unwrap();
4224        let writer_collide = FilesystemMemWriter::new(mem_collide.clone());
4225
4226        let err = engine
4227            .register_writable_mem(
4228                folder_mount("alpha", mem_collide),
4229                Box::new(writer_collide) as Box<dyn MemBackend>,
4230                MemOrigin::ExplicitToml,
4231            )
4232            .unwrap_err();
4233        match err {
4234            EngineError::MemNameCollision {
4235                name,
4236                source_origin,
4237            } => {
4238                assert_eq!(name, "alpha");
4239                // post-restructure source_origin references
4240                // `.memstead/workspace.toml`; the assertion stays
4241                // permissive (substring OR non-empty) so the test
4242                // doesn't lock the exact wording.
4243                assert!(
4244                    source_origin.contains(".memstead/workspace.toml") || !source_origin.is_empty()
4245                );
4246            }
4247            other => panic!("expected MemNameCollision, got {other:?}"),
4248        }
4249
4250        // Engine state unchanged.
4251        assert_eq!(engine.mounts().len(), mount_count_pre);
4252    }
4253
4254    #[test]
4255    fn register_writable_mem_loads_entities_into_store() {
4256        // The newly-registered mem's entities should surface in
4257        // the engine's store after registration.
4258        let tmp = TempDir::new().unwrap();
4259        let mem_a = tmp.path().join("a");
4260        std::fs::create_dir_all(&mem_a).unwrap();
4261        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4262
4263        let mut engine = Engine::from_mounts(vec![(
4264            folder_mount("alpha", mem_a),
4265            Box::new(writer_a) as Box<dyn MemBackend>,
4266        )])
4267        .unwrap();
4268        let pre_count = engine.store().all_entities().count();
4269
4270        // Build mem_b with a markdown entity on disk.
4271        let mem_b = tmp.path().join("b");
4272        std::fs::create_dir_all(&mem_b).unwrap();
4273        std::fs::write(
4274            mem_b.join("b1.md"),
4275            "---\ntype: spec\n---\n# B1\n\n## Identity\n\nseed.\n",
4276        )
4277        .unwrap();
4278        let writer_b = FilesystemMemWriter::new(mem_b.clone());
4279
4280        engine
4281            .register_writable_mem(
4282                folder_mount("beta", mem_b),
4283                Box::new(writer_b) as Box<dyn MemBackend>,
4284                MemOrigin::ExplicitToml,
4285            )
4286            .unwrap();
4287
4288        let post_count = engine.store().all_entities().count();
4289        assert!(post_count > pre_count, "register must load entities");
4290        let beta_count = engine
4291            .store()
4292            .all_entities()
4293            .filter(|e| e.mem == "beta")
4294            .count();
4295        assert_eq!(beta_count, 1);
4296    }
4297
4298    #[test]
4299    fn register_then_unregister_round_trips() {
4300        // End-to-end check: register a mem, then unregister it,
4301        // and confirm the engine returns to the pre-registration
4302        // state.
4303        let tmp = TempDir::new().unwrap();
4304        let mem_a = tmp.path().join("a");
4305        std::fs::create_dir_all(&mem_a).unwrap();
4306        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4307
4308        let mut engine = Engine::from_mounts(vec![(
4309            folder_mount("alpha", mem_a),
4310            Box::new(writer_a) as Box<dyn MemBackend>,
4311        )])
4312        .unwrap();
4313        let pre_mounts = engine.mounts().len();
4314
4315        let mem_b = tmp.path().join("b");
4316        std::fs::create_dir_all(&mem_b).unwrap();
4317        let writer_b = FilesystemMemWriter::new(mem_b);
4318
4319        engine
4320            .register_writable_mem(
4321                folder_mount("beta", tmp.path().join("b")),
4322                Box::new(writer_b) as Box<dyn MemBackend>,
4323                MemOrigin::ExplicitToml,
4324            )
4325            .unwrap();
4326        assert_eq!(engine.mounts().len(), pre_mounts + 1);
4327
4328        let removed = engine.unregister_writable_mem("beta").unwrap();
4329        assert!(removed.is_some());
4330        assert_eq!(engine.mounts().len(), pre_mounts);
4331        assert!(!engine.mem_router().is_writable("beta"));
4332    }
4333
4334    #[test]
4335    fn unregister_writable_mem_returns_false_for_unknown_name() {
4336        // Idempotent contract: repeated calls / unknown names are
4337        // not errors — return false so callers can branch without
4338        // a typed error envelope for the common "already gone" case.
4339        let tmp = TempDir::new().unwrap();
4340        let mem_dir = tmp.path().to_path_buf();
4341        let writer = FilesystemMemWriter::new(mem_dir.clone());
4342        let mut engine = Engine::from_mounts(vec![(
4343            folder_mount("specs", mem_dir),
4344            Box::new(writer) as Box<dyn MemBackend>,
4345        )])
4346        .unwrap();
4347        let removed = engine.unregister_writable_mem("missing").unwrap();
4348        assert!(removed.is_none(), "unknown mem returns Ok(None)");
4349        // The original mem is still present and readable.
4350        assert!(engine.mem_router().is_writable("specs"));
4351    }
4352
4353    #[test]
4354    fn unregister_writable_mem_drops_mount_and_router_entry() {
4355        // Heterogeneous engine: two mounts. Unregister one and
4356        // assert (a) it's gone from the mount list, (b) gone from
4357        // the mem_router's writable set, (c) the OTHER mount is
4358        // untouched.
4359        let tmp = TempDir::new().unwrap();
4360        let mem_a = tmp.path().join("a");
4361        std::fs::create_dir_all(&mem_a).unwrap();
4362        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4363        let mem_b = tmp.path().join("b");
4364        std::fs::create_dir_all(&mem_b).unwrap();
4365        let writer_b = FilesystemMemWriter::new(mem_b.clone());
4366
4367        let mut engine = Engine::from_mounts(vec![
4368            (
4369                folder_mount("alpha", mem_a),
4370                Box::new(writer_a) as Box<dyn MemBackend>,
4371            ),
4372            (
4373                folder_mount("beta", mem_b),
4374                Box::new(writer_b) as Box<dyn MemBackend>,
4375            ),
4376        ])
4377        .unwrap();
4378
4379        let removed = engine.unregister_writable_mem("alpha").unwrap();
4380        assert!(removed.is_some());
4381
4382        // alpha is gone from every surface.
4383        assert!(!engine.mem_router().is_writable("alpha"));
4384        assert!(!engine.mem_router().is_visible("alpha"));
4385        assert!(engine.mount("alpha").is_none());
4386
4387        // beta survives unchanged.
4388        assert!(engine.mem_router().is_writable("beta"));
4389        assert!(engine.mount("beta").is_some());
4390    }
4391
4392    #[test]
4393    fn unregister_writable_mem_drops_entities_for_that_mem_only() {
4394        // Build an engine with two mems, write one entity to each
4395        // backend, build the engine (loads both), unregister one,
4396        // assert the store still has the other mem's entity.
4397        let tmp = TempDir::new().unwrap();
4398        let mem_a = tmp.path().join("a");
4399        std::fs::create_dir_all(&mem_a).unwrap();
4400        std::fs::write(
4401            mem_a.join("a1.md"),
4402            "---\ntype: spec\n---\n# A1\n\n## Identity\n\nseed.\n",
4403        )
4404        .unwrap();
4405        let writer_a = FilesystemMemWriter::new(mem_a.clone());
4406
4407        let mem_b = tmp.path().join("b");
4408        std::fs::create_dir_all(&mem_b).unwrap();
4409        std::fs::write(
4410            mem_b.join("b1.md"),
4411            "---\ntype: spec\n---\n# B1\n\n## Identity\n\nseed.\n",
4412        )
4413        .unwrap();
4414        let writer_b = FilesystemMemWriter::new(mem_b.clone());
4415
4416        let mut engine = Engine::from_mounts(vec![
4417            (
4418                folder_mount("alpha", mem_a),
4419                Box::new(writer_a) as Box<dyn MemBackend>,
4420            ),
4421            (
4422                folder_mount("beta", mem_b),
4423                Box::new(writer_b) as Box<dyn MemBackend>,
4424            ),
4425        ])
4426        .unwrap();
4427
4428        let pre_total = engine.store().all_entities().count();
4429        assert!(pre_total >= 2, "both mems must load entities");
4430
4431        engine.unregister_writable_mem("alpha").unwrap();
4432
4433        // alpha's entities are gone.
4434        let alpha_remaining = engine
4435            .store()
4436            .all_entities()
4437            .filter(|e| e.mem == "alpha")
4438            .count();
4439        assert_eq!(alpha_remaining, 0);
4440
4441        // beta's entities survive.
4442        let beta_remaining = engine
4443            .store()
4444            .all_entities()
4445            .filter(|e| e.mem == "beta")
4446            .count();
4447        assert!(beta_remaining > 0, "beta entities must survive");
4448    }
4449    #[test]
4450    fn reload_one_mem_returns_empty_diff_when_disk_is_unchanged() {
4451        let tmp = TempDir::new().unwrap();
4452        let mut engine = build_demo_engine(&tmp);
4453        let result = engine
4454            .reload_one_mem("specs")
4455            .expect("reload on stable disk must succeed");
4456        assert!(result.added.is_empty(), "added: {:?}", result.added);
4457        assert!(result.changed.is_empty(), "changed: {:?}", result.changed);
4458        assert!(result.removed.is_empty(), "removed: {:?}", result.removed);
4459    }
4460
4461    #[test]
4462    fn reload_one_mem_picks_up_external_addition() {
4463        let tmp = TempDir::new().unwrap();
4464        let mut engine = build_demo_engine(&tmp);
4465        // Simulate an external writer dropping a new entity on disk
4466        // without going through the engine.
4467        std::fs::write(
4468            tmp.path().join("external.md"),
4469            "---\ntype: spec\n---\n# External\n\n## Identity\n\nE.\n",
4470        )
4471        .unwrap();
4472        let result = engine.reload_one_mem("specs").unwrap();
4473        assert_eq!(
4474            result.added.iter().map(|i| i.as_ref()).collect::<Vec<_>>(),
4475            vec!["specs--external"]
4476        );
4477        assert!(result.changed.is_empty());
4478        assert!(result.removed.is_empty());
4479        // The new entity is now reachable through the engine.
4480        assert!(
4481            engine
4482                .get_entity(&crate::EntityId::new("specs", "external"))
4483                .is_some()
4484        );
4485    }
4486
4487    #[test]
4488    fn reload_one_mem_picks_up_external_removal() {
4489        let tmp = TempDir::new().unwrap();
4490        let mut engine = build_demo_engine(&tmp);
4491        // Lonely Three exists from the demo fixture; remove it
4492        // off-engine and reload.
4493        std::fs::remove_file(tmp.path().join("lonely-three.md")).unwrap();
4494        let result = engine.reload_one_mem("specs").unwrap();
4495        assert!(result.added.is_empty());
4496        assert!(result.changed.is_empty());
4497        assert_eq!(
4498            result
4499                .removed
4500                .iter()
4501                .map(|i| i.as_ref())
4502                .collect::<Vec<_>>(),
4503            vec!["specs--lonely-three"]
4504        );
4505    }
4506
4507    #[test]
4508    fn reload_one_mem_picks_up_external_change() {
4509        let tmp = TempDir::new().unwrap();
4510        let mut engine = build_demo_engine(&tmp);
4511        // Overwrite an existing entity's content; the new
4512        // `content_hash` must surface in the `changed` diff.
4513        std::fs::write(
4514            tmp.path().join("source-one.md"),
4515            "---\ntype: spec\n---\n# Source One Edited\n\n## Identity\n\nNew body.\n",
4516        )
4517        .unwrap();
4518        let result = engine.reload_one_mem("specs").unwrap();
4519        assert!(result.added.is_empty());
4520        assert_eq!(
4521            result
4522                .changed
4523                .iter()
4524                .map(|i| i.as_ref())
4525                .collect::<Vec<_>>(),
4526            vec!["specs--source-one"]
4527        );
4528        assert!(result.removed.is_empty());
4529    }
4530
4531    #[test]
4532    fn reload_one_mem_rejects_unknown_mem() {
4533        let tmp = TempDir::new().unwrap();
4534        let mut engine = build_demo_engine(&tmp);
4535        let err = engine.reload_one_mem("nope").unwrap_err();
4536        match err {
4537            EngineError::UnknownMem(name) => assert_eq!(name, "nope"),
4538            other => panic!("expected UnknownMem, got {other:?}"),
4539        }
4540    }
4541
4542    #[test]
4543    fn reload_each_writable_mem_returns_one_entry_per_mount() {
4544        let tmp = TempDir::new().unwrap();
4545        let mut engine = build_demo_engine(&tmp);
4546        let reports = engine
4547            .reload_each_writable_mem()
4548            .expect("batch reload on stable disk must succeed");
4549        assert_eq!(reports.len(), 1);
4550        assert_eq!(reports[0].0, "specs");
4551        assert!(reports[0].1.added.is_empty());
4552        assert!(reports[0].1.changed.is_empty());
4553        assert!(reports[0].1.removed.is_empty());
4554    }
4555
4556    // ---- Engine::settings -------------------------------------------
4557
4558    #[test]
4559    fn settings_default_to_empty_on_fresh_engine() {
4560        let tmp = TempDir::new().unwrap();
4561        let engine = build_demo_engine(&tmp);
4562        let s = engine.settings();
4563        assert!(s.mem_create_rules.is_empty());
4564        assert!(s.mem_delete_rules.is_empty());
4565        assert!(s.cross_mem_links.is_empty());
4566    }
4567
4568    #[test]
4569    fn set_settings_replaces_workspace_policy() {
4570        use crate::workspace::{CreateRuleSetting, DeleteRuleSetting, WorkspaceSettings};
4571        let tmp = TempDir::new().unwrap();
4572        let mut engine = build_demo_engine(&tmp);
4573        let mut settings = WorkspaceSettings::default();
4574        settings.mem_create_rules.push(CreateRuleSetting {
4575            pattern: "exec-*".to_string(),
4576            schemas: vec!["default@1.0.0".to_string()],
4577            default_cross_links: None,
4578        });
4579        settings.mem_delete_rules.push(DeleteRuleSetting {
4580            pattern: "exec-*".to_string(),
4581        });
4582        engine.set_settings(settings);
4583        assert_eq!(engine.settings().mem_create_rules.len(), 1);
4584        assert_eq!(engine.settings().mem_create_rules[0].pattern, "exec-*");
4585        assert_eq!(engine.settings().mem_delete_rules.len(), 1);
4586        assert_eq!(engine.settings().mem_delete_rules[0].pattern, "exec-*");
4587    }
4588
4589    // ---- Engine::reload_each_writable_mem (continued) -------------
4590
4591    #[test]
4592    fn reload_each_writable_mem_picks_up_external_changes_per_mem() {
4593        let tmp = TempDir::new().unwrap();
4594        let mut engine = build_demo_engine(&tmp);
4595        // Mutate disk: add one entity, remove another, change a third.
4596        std::fs::write(
4597            tmp.path().join("new-via-disk.md"),
4598            "---\ntype: spec\n---\n# New Via Disk\n\n## Identity\n\nN.\n",
4599        )
4600        .unwrap();
4601        std::fs::remove_file(tmp.path().join("lonely-three.md")).unwrap();
4602        std::fs::write(
4603            tmp.path().join("source-one.md"),
4604            "---\ntype: spec\n---\n# Source One\n\n## Identity\n\nDifferent body.\n",
4605        )
4606        .unwrap();
4607
4608        let reports = engine.reload_each_writable_mem().unwrap();
4609        assert_eq!(reports.len(), 1);
4610        let (mem, result) = &reports[0];
4611        assert_eq!(mem, "specs");
4612        assert_eq!(
4613            result.added.iter().map(|i| i.as_ref()).collect::<Vec<_>>(),
4614            vec!["specs--new-via-disk"]
4615        );
4616        assert_eq!(
4617            result
4618                .removed
4619                .iter()
4620                .map(|i| i.as_ref())
4621                .collect::<Vec<_>>(),
4622            vec!["specs--lonely-three"]
4623        );
4624        assert_eq!(
4625            result
4626                .changed
4627                .iter()
4628                .map(|i| i.as_ref())
4629                .collect::<Vec<_>>(),
4630            vec!["specs--source-one"]
4631        );
4632    }
4633
4634    // ---- Engine::reload_one_mem_report (rich-shape wrapper) -------
4635
4636    #[test]
4637    fn reload_one_mem_report_returns_rich_shape_for_folder_default() {
4638        // The folder backend's drift cursor is the changelog's
4639        // last-line timestamp (RFC3339-millis) — the same dialect
4640        // `folder_changes_since` accepts. With the demo engine's
4641        // creates already logged, both heads carry that cursor and,
4642        // with the disk unchanged between init and reload, they are
4643        // equal. entities_loaded reflects the post-reload count;
4644        // changed_entity_ids is empty when the disk is unchanged.
4645        let tmp = TempDir::new().unwrap();
4646        let mut engine = build_demo_engine(&tmp);
4647        let report = engine.reload_one_mem_report("specs").unwrap();
4648        assert_eq!(report.mem, "specs");
4649        assert_eq!(
4650            report.head_before, report.head_after,
4651            "unchanged disk → stable cursor"
4652        );
4653        assert!(
4654            crate::filesystem::changelog::parse_rfc3339_utc(&report.head_after).is_some(),
4655            "folder heads carry the changelog-ts cursor, got {}",
4656            report.head_after
4657        );
4658        // build_demo_engine seeds 3 entities (Source One, Target Two,
4659        // Lonely Three) — all real, no stubs from those creates.
4660        assert_eq!(report.entities_loaded, 3);
4661        // No external disk changes between init and reload → empty diff.
4662        assert!(report.changed_entity_ids.is_empty());
4663    }
4664
4665    #[test]
4666    fn reload_one_mem_report_unions_added_changed_removed_into_one_list() {
4667        // Mutate disk: add one, remove one, change one. The report's
4668        // changed_entity_ids unions the slim ReloadResult's three
4669        // diff lists into a single sorted vec — matches full's
4670        // wire contract.
4671        let tmp = TempDir::new().unwrap();
4672        let mut engine = build_demo_engine(&tmp);
4673        std::fs::write(
4674            tmp.path().join("new-via-disk.md"),
4675            "---\ntype: spec\n---\n# New Via Disk\n\n## Identity\n\nN.\n",
4676        )
4677        .unwrap();
4678        std::fs::remove_file(tmp.path().join("lonely-three.md")).unwrap();
4679        std::fs::write(
4680            tmp.path().join("source-one.md"),
4681            "---\ntype: spec\n---\n# Source One\n\n## Identity\n\nDifferent body.\n",
4682        )
4683        .unwrap();
4684
4685        let report = engine.reload_one_mem_report("specs").unwrap();
4686        assert_eq!(report.mem, "specs");
4687        let ids: Vec<&str> = report
4688            .changed_entity_ids
4689            .iter()
4690            .map(|id| id.as_ref())
4691            .collect();
4692        // Sorted lexicographically: lonely-three < new-via-disk < source-one
4693        assert_eq!(
4694            ids,
4695            vec![
4696                "specs--lonely-three",
4697                "specs--new-via-disk",
4698                "specs--source-one",
4699            ]
4700        );
4701    }
4702
4703    #[test]
4704    fn reload_one_mem_report_rejects_unknown_mem() {
4705        let tmp = TempDir::new().unwrap();
4706        let mut engine = build_demo_engine(&tmp);
4707        let err = engine.reload_one_mem_report("missing").unwrap_err();
4708        assert!(matches!(err, EngineError::UnknownMem(_)));
4709    }
4710
4711    #[test]
4712    fn reload_each_writable_mem_reports_returns_one_entry_per_mount() {
4713        let tmp = TempDir::new().unwrap();
4714        let mut engine = build_demo_engine(&tmp);
4715        let reports = engine.reload_each_writable_mem_reports().unwrap();
4716        assert_eq!(reports.len(), 1);
4717        assert_eq!(reports[0].mem, "specs");
4718        assert_eq!(reports[0].entities_loaded, 3);
4719    }
4720
4721    /// Workspace-wide reload re-reads `.memstead/workspace.toml` and
4722    /// refreshes [`WorkspaceSettings`]. This is the pairing with the
4723    /// CLI's `memstead workspace allow-create / grant-cross-link /
4724    /// set-mutations` family — without it, a CLI write lands on disk
4725    /// but the running engine keeps serving the boot-time policy
4726    /// snapshot until process restart.
4727    #[test]
4728    fn reload_each_writable_mem_reports_refreshes_workspace_settings() {
4729        let tmp = TempDir::new().unwrap();
4730
4731        // Minimum-viable workspace.toml (no rules) + one writable
4732        // folder-backed mem.
4733        let memstead_dir = tmp.path().join(".memstead");
4734        std::fs::create_dir_all(&memstead_dir).unwrap();
4735        let workspace_toml = memstead_dir.join("workspace.toml");
4736        std::fs::write(
4737            &workspace_toml,
4738            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
4739        )
4740        .unwrap();
4741        let mounts_json = memstead_dir.join("state").join("mounts.json");
4742        std::fs::create_dir_all(mounts_json.parent().unwrap()).unwrap();
4743        let mem_dir = tmp.path().join("specs");
4744        std::fs::create_dir_all(&mem_dir).unwrap();
4745        let mounts_body = format!(
4746            r#"{{ "format": "memstead-mounts-3", "mounts": [{{ "mem": "specs", "schema": "default@1.0.0", "storage": {{ "type": "folder", "path": "{}" }}, "capability": "write", "lifecycle": "eager", "cross_linkable": true }}] }}"#,
4747            mem_dir.display(),
4748        );
4749        std::fs::write(&mounts_json, mounts_body).unwrap();
4750
4751        let mut engine = Engine::from_workspace_root(tmp.path()).unwrap();
4752        assert!(
4753            engine.settings().mem_create_rules.is_empty(),
4754            "boot-time settings carry no create rules"
4755        );
4756
4757        // Simulate an out-of-band CLI write to workspace.toml.
4758        std::fs::write(
4759            &workspace_toml,
4760            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n\n[[mem_management.create]]\npattern = \"exec-*\"\nschemas = [\"default@1.0.0\"]\n",
4761        )
4762        .unwrap();
4763
4764        engine.reload_each_writable_mem_reports().unwrap();
4765
4766        let rules = &engine.settings().mem_create_rules;
4767        assert_eq!(
4768            rules.len(),
4769            1,
4770            "workspace-wide reload must refresh the policy"
4771        );
4772        assert_eq!(rules[0].pattern, "exec-*");
4773    }
4774
4775    // ---- Engine::reload_if_stale ------------------------------
4776
4777    // ---- set_mem_schema / dual-pin migration ----
4778
4779    const MIG_TYPE_TAIL: &str = r#"sections:
4780  - key: body
4781    heading: Body
4782    required: true
4783    search_weight: 10.0
4784    catch_all: true
4785    write_rules: []
4786title_weight: 100.0
4787text_fields:
4788  - body
4789hierarchy_relationship: _default
4790no_self_loop_relationships: []
4791updatable_fields: []
4792health_required_fields: []
4793staleness_threshold_days: 90
4794write_rules: []
4795"#;
4796
4797    /// Schema manifest for the migration tests: `name@version` with a
4798    /// `doc` type. `with_status = true` adds a required, no-default
4799    /// enum field `status` — entities created without it are
4800    /// non-conformant against that schema.
4801    fn mig_manifest(name: &str, version: &str) -> String {
4802        format!(
4803            r#"name: {name}
4804version: {version}
4805description: migration test schema
4806when_to_use: tests
4807types:
4808  - doc
4809relationships:
4810  mode: strict
4811  definitions:
4812    - name: USES
4813      description: link
4814      default_weight: 1.0
4815    - name: _default
4816      description: fallback
4817      default_weight: 1.0
4818community:
4819  resolution: 1.0
4820  seed: 42
4821"#
4822        )
4823    }
4824
4825    fn mig_type_yaml(with_status: bool) -> String {
4826        let metadata = if with_status {
4827            "metadata_fields:\n  - key: status\n    description: Lifecycle state\n    field_type: string\n    required: true\n    enum_values:\n      - open\n      - closed\n"
4828        } else {
4829            "metadata_fields: []\n"
4830        };
4831        format!("name: doc\ndescription: t\nwhen_to_use: tests\n{metadata}{MIG_TYPE_TAIL}")
4832    }
4833
4834    fn write_mig_schema(
4835        root: &std::path::Path,
4836        dir: &str,
4837        name: &str,
4838        version: &str,
4839        with_status: bool,
4840    ) {
4841        let d = root.join(dir);
4842        std::fs::create_dir_all(d.join("types")).unwrap();
4843        std::fs::write(d.join("schema.yaml"), mig_manifest(name, version)).unwrap();
4844        std::fs::write(d.join("types").join("doc.yaml"), mig_type_yaml(with_status)).unwrap();
4845    }
4846
4847    /// Engine with one mem pinned `mig-a@0.1.0` (no required
4848    /// metadata) plus loadable `mig-a@0.2.0` (identical shape) and
4849    /// `mig-b@0.1.0` (required enum `status`) in the workspace
4850    /// schemas dir. Two conformant-under-A entities are created.
4851    /// The criterion-4 property test (flywheel W8/01): a
4852    /// deterministic, seeded, hand-rolled generator (xorshift64 — the
4853    /// house discipline, no dependency) drives mutation sequences
4854    /// across EVERY kind — create, update, relate, delete, rename,
4855    /// batch update (applied AND refused/rolled-back), reload, and a
4856    /// schema switch — asserting at checkpoints and at sequence end
4857    /// that the maintained derived structures are identical to a
4858    /// from-scratch rebuild over the current store. Coverage is
4859    /// guaranteed by construction (the first pass cycles every kind
4860    /// once before the random tail), and asserted, so a silently
4861    /// narrowed generator fails the suite. A failing sequence
4862    /// reproduces from the seed printed in the panic message alone.
4863    #[test]
4864    fn derived_structures_match_rebuild_across_random_mutation_sequences() {
4865        for seed in [0x5eed_0001_u64, 0x5eed_0002, 0x5eed_0003] {
4866            run_mutation_sequence(seed);
4867        }
4868    }
4869
4870    struct Xorshift(u64);
4871    impl Xorshift {
4872        fn next(&mut self) -> u64 {
4873            let mut x = self.0;
4874            x ^= x << 13;
4875            x ^= x >> 7;
4876            x ^= x << 17;
4877            self.0 = x;
4878            x
4879        }
4880        fn pick(&mut self, n: usize) -> usize {
4881            (self.next() % n as u64) as usize
4882        }
4883    }
4884
4885    fn assert_derived_oracles(engine: &Engine, seed: u64, label: &str) {
4886        // Search oracle: the maintained per-mem index holds exactly
4887        // the ids a from-scratch build over the current store holds.
4888        let fresh = crate::search_index::build_all(engine.store(), &engine.schemas);
4889        let live = engine.search_indexes();
4890        let mut live_mems: Vec<&String> = live.keys().collect();
4891        let mut fresh_mems: Vec<&String> = fresh.keys().collect();
4892        live_mems.sort();
4893        fresh_mems.sort();
4894        assert_eq!(
4895            live_mems, fresh_mems,
4896            "seed {seed:#x} @ {label}: index mem set diverged from rebuild"
4897        );
4898        for (mem, idx) in live {
4899            let mut got = idx.stored_ids().unwrap();
4900            let mut want = fresh[mem].stored_ids().unwrap();
4901            got.sort();
4902            want.sort();
4903            assert_eq!(
4904                got, want,
4905                "seed {seed:#x} @ {label}: mem `{mem}` index contents diverged from rebuild"
4906            );
4907        }
4908        // Community oracle: the memoised partition equals a fresh
4909        // detection with the same parameter source (smallest mem name).
4910        let schema = engine
4911            .schemas
4912            .iter()
4913            .min_by(|a, b| a.0.cmp(b.0))
4914            .map(|(_, s)| s.clone())
4915            .expect("schema present");
4916        let weights_schema = schema.clone();
4917        let fresh_partition = crate::graph::community::detect_communities(
4918            engine.store(),
4919            schema.manifest.community.resolution,
4920            schema.manifest.community.seed,
4921            move |rel_type| {
4922                weights_schema
4923                    .manifest
4924                    .relationships
4925                    .definitions
4926                    .iter()
4927                    .find(|d| d.name == rel_type)
4928                    .map(|d| d.default_weight as f64)
4929                    .unwrap_or(1.0)
4930            },
4931        );
4932        assert_eq!(
4933            engine.communities().entity_cluster_map,
4934            fresh_partition.entity_cluster_map,
4935            "seed {seed:#x} @ {label}: partition diverged from a fresh detection"
4936        );
4937    }
4938
4939    fn run_mutation_sequence(seed: u64) {
4940        use indexmap::IndexMap;
4941
4942        let (_tmp, mut engine) = migration_engine();
4943        let mut rng = Xorshift(seed);
4944        let mut live: Vec<crate::EntityId> = vec![
4945            crate::EntityId::new("specs", "one"),
4946            crate::EntityId::new("specs", "two"),
4947        ];
4948        let mut counter = 0usize;
4949        let mut kinds_hit: std::collections::HashSet<&'static str> =
4950            std::collections::HashSet::new();
4951
4952        const KINDS: [&str; 7] = [
4953            "create",
4954            "update",
4955            "relate",
4956            "delete",
4957            "rename",
4958            "batch_applied",
4959            "batch_refused",
4960        ];
4961
4962        let bare_update = |id: crate::EntityId| crate::engine::UpdateEntityArgs {
4963            anchors: Vec::new(),
4964            anchors_unset: Vec::new(),
4965            id,
4966            expected_hash: None,
4967            sections: IndexMap::new(),
4968            append_sections: IndexMap::new(),
4969            patch_sections: IndexMap::new(),
4970            sections_unset: Vec::new(),
4971            metadata: IndexMap::new(),
4972            metadata_unset: Vec::new(),
4973            declare_relations: Vec::new(),
4974            dry_run: false,
4975            relations_unset: Vec::new(),
4976        };
4977
4978        for op_i in 0..30usize {
4979            // First pass cycles every kind once (coverage by
4980            // construction); the tail is seed-driven.
4981            let kind = *KINDS
4982                .get(op_i)
4983                .unwrap_or_else(|| &KINDS[rng.pick(KINDS.len())]);
4984            match kind {
4985                "create" => {
4986                    counter += 1;
4987                    let mut args = empty_create_args("specs", &format!("Gen {counter}"));
4988                    args.entity_type = "doc".to_string();
4989                    args.sections = IndexMap::from_iter([(
4990                        "body".to_string(),
4991                        format!("generated body {counter}"),
4992                    )]);
4993                    let out = engine
4994                        .create_entity(args, crate::vcs::Actor::Cli, None, None)
4995                        .expect("generated create is conformant");
4996                    live.push(out.id);
4997                    kinds_hit.insert("create");
4998                }
4999                "update" => {
5000                    let id = live[rng.pick(live.len())].clone();
5001                    let mut args = bare_update(id);
5002                    args.append_sections
5003                        .insert("body".to_string(), format!("appended at op {op_i}"));
5004                    engine
5005                        .update_entity(args, crate::vcs::Actor::Cli, None, None)
5006                        .expect("append update is conformant");
5007                    kinds_hit.insert("update");
5008                }
5009                "relate" => {
5010                    if live.len() >= 2 {
5011                        let a = rng.pick(live.len());
5012                        let mut b = rng.pick(live.len());
5013                        if a == b {
5014                            b = (b + 1) % live.len();
5015                        }
5016                        engine
5017                            .relate_entity(
5018                                crate::engine::RelateEntityArgs {
5019                                    source: live[a].clone(),
5020                                    expected_hash: None,
5021                                    rel_type: "USES".to_string(),
5022                                    target: live[b].clone(),
5023                                    remove: false,
5024                                    description: None,
5025                                    dry_run: false,
5026                                },
5027                                crate::vcs::Actor::Cli,
5028                                None,
5029                                None,
5030                            )
5031                            .expect("USES relate is legal under mig-a");
5032                        kinds_hit.insert("relate");
5033                    }
5034                }
5035                "delete" => {
5036                    // Only reference-free entities delete cleanly; keep
5037                    // at least two so relate stays possible.
5038                    if live.len() > 2
5039                        && let Some(pos) = (0..live.len()).find(|&i| {
5040                            engine.store().incoming(&live[i]).is_empty()
5041                                && engine
5042                                    .store()
5043                                    .get(&live[i])
5044                                    .is_some_and(|e| e.relationships.is_empty())
5045                        })
5046                    {
5047                        let id = live.remove(pos);
5048                        engine
5049                            .delete_entity(
5050                                crate::engine::DeleteEntityArgs {
5051                                    id: id.clone(),
5052                                    expected_hash: None,
5053                                },
5054                                crate::vcs::Actor::Cli,
5055                                None,
5056                                None,
5057                            )
5058                            .expect("reference-free delete lands");
5059                        kinds_hit.insert("delete");
5060                    }
5061                }
5062                "rename" => {
5063                    counter += 1;
5064                    let pos = rng.pick(live.len());
5065                    let old = live[pos].clone();
5066                    let out = engine
5067                        .rename_entity(
5068                            crate::engine::RenameEntityArgs {
5069                                id: old,
5070                                new_title: format!("Renamed {counter}"),
5071                                expected_hash: None,
5072                            },
5073                            crate::vcs::Actor::Cli,
5074                            None,
5075                            None,
5076                        )
5077                        .expect("fresh-slug rename lands");
5078                    live[pos] = out.new_id;
5079                    kinds_hit.insert("rename");
5080                }
5081                "batch_applied" => {
5082                    let id_a = live[rng.pick(live.len())].clone();
5083                    let mut a = bare_update(id_a);
5084                    a.append_sections
5085                        .insert("body".to_string(), format!("batch line {op_i}"));
5086                    let result = engine
5087                        .batch_update(vec![(a, None)], crate::vcs::Actor::Cli, None, false)
5088                        .expect("batch envelope");
5089                    assert!(result.applied, "single-entry append batch applies");
5090                    kinds_hit.insert("batch_applied");
5091                }
5092                "batch_refused" => {
5093                    let id_a = live[rng.pick(live.len())].clone();
5094                    let mut a = bare_update(id_a);
5095                    a.append_sections
5096                        .insert("body".to_string(), "doomed".to_string());
5097                    let missing = bare_update(crate::EntityId::new("specs", "no-such-entity"));
5098                    let result = engine
5099                        .batch_update(
5100                            vec![(a, None), (missing, None)],
5101                            crate::vcs::Actor::Cli,
5102                            None,
5103                            false,
5104                        )
5105                        .expect("refused batch returns a report-all envelope");
5106                    assert!(!result.applied, "the missing target refuses the batch");
5107                    kinds_hit.insert("batch_refused");
5108                }
5109                _ => unreachable!(),
5110            }
5111
5112            if op_i == 14 {
5113                // The at-least-one schema switch the criterion demands
5114                // (identical field shape, so the index rebuild is
5115                // exercised through the epoch path).
5116                engine
5117                    .set_mem_schema("specs", &sref("mig-a@0.2.0"))
5118                    .expect("integral switch");
5119                kinds_hit.insert("schema_switch");
5120            }
5121            if op_i == 19 {
5122                engine.reload_one_mem("specs").expect("reload lands");
5123                kinds_hit.insert("reload");
5124            }
5125
5126            if op_i % 10 == 9 {
5127                assert_derived_oracles(&engine, seed, &format!("checkpoint op {op_i}"));
5128            }
5129        }
5130
5131        assert_derived_oracles(&engine, seed, "sequence end");
5132
5133        for kind in KINDS.iter().copied().chain(["schema_switch", "reload"]) {
5134            assert!(
5135                kinds_hit.contains(kind),
5136                "seed {seed:#x}: generator coverage narrowed — kind `{kind}` never executed"
5137            );
5138        }
5139    }
5140
5141    fn migration_engine() -> (tempfile::TempDir, Engine) {
5142        let tmp = tempfile::TempDir::new().unwrap();
5143        let schemas_dir = tmp.path().join("schemas");
5144        write_mig_schema(&schemas_dir, "mig-a-1", "mig-a", "0.1.0", false);
5145        write_mig_schema(&schemas_dir, "mig-a-2", "mig-a", "0.2.0", false);
5146        write_mig_schema(&schemas_dir, "mig-b-1", "mig-b", "0.1.0", true);
5147        let mem_dir = tmp.path().join("mem");
5148        std::fs::create_dir_all(&mem_dir).unwrap();
5149        let writer = crate::storage::FilesystemMemWriter::new(mem_dir.clone());
5150        let mut mount = folder_mount("specs", mem_dir);
5151        mount.schema = Some("mig-a@0.1.0".parse().unwrap());
5152        let mut engine = Engine::from_mounts_with_schemas_dir(
5153            vec![(
5154                mount,
5155                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
5156            )],
5157            Some(&schemas_dir),
5158        )
5159        .unwrap();
5160        for title in ["One", "Two"] {
5161            let mut args = empty_create_args("specs", title);
5162            args.entity_type = "doc".to_string();
5163            args.sections =
5164                indexmap::IndexMap::from_iter([("body".to_string(), "content".to_string())]);
5165            engine
5166                .create_entity(args, crate::vcs::Actor::Cli, None, None)
5167                .expect("conformant create under mig-a");
5168        }
5169        (tmp, engine)
5170    }
5171
5172    fn sref(s: &str) -> memstead_schema::SchemaRef {
5173        s.parse().unwrap()
5174    }
5175
5176    /// A `SCHEMA_PIN_MISMATCH` state (the mount expects the target, the
5177    /// served config pins an older generation) is exactly what
5178    /// `set-schema` must repair: the switch persists the config pin and
5179    /// reports `switched`, never `noop`. Complement: with both in
5180    /// agreement the same call is a noop.
5181    #[test]
5182    fn set_schema_repairs_a_mount_expectation_ahead_of_the_served_pin() {
5183        let (_tmp, mut engine) = migration_engine();
5184        // Fabricate the mismatch: the mount expectation says mig-b while
5185        // the engine still serves mig-a from the config.
5186        let idx = engine
5187            .mounts
5188            .iter()
5189            .position(|m| m.mount.mem == "specs")
5190            .unwrap();
5191        engine.mounts[idx].mount.schema = Some(sref("mig-b@0.1.0"));
5192        assert_eq!(engine.schemas.get("specs").unwrap().id().0, "mig-a");
5193
5194        let out = engine
5195            .set_mem_schema("specs", &sref("mig-b@0.1.0"))
5196            .unwrap();
5197        // The fixture's entities are not integral against mig-b, so the
5198        // honest answer is a started migration; the point is that it is
5199        // NOT the noop the stale mount expectation used to produce.
5200        assert_eq!(
5201            out.outcome,
5202            crate::engine::SetSchemaResult::MigrationStarted,
5203            "a served pin behind the target enters the switch path, never a noop: {out:?}"
5204        );
5205        assert!(!out.findings.is_empty());
5206        assert_eq!(
5207            engine.schemas.get("specs").unwrap().id().0,
5208            "mig-b",
5209            "writes now validate against the target"
5210        );
5211
5212        // Complement: served pin and expectation both at the target (no
5213        // migration in flight) is a noop.
5214        let (_tmp2, mut clean) = migration_engine();
5215        let again = clean.set_mem_schema("specs", &sref("mig-a@0.1.0")).unwrap();
5216        assert_eq!(again.outcome, crate::engine::SetSchemaResult::Noop);
5217    }
5218
5219    #[test]
5220    fn set_schema_noop_on_current_pin() {
5221        let (_tmp, mut engine) = migration_engine();
5222        let out = engine
5223            .set_mem_schema("specs", &sref("mig-a@0.1.0"))
5224            .unwrap();
5225        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Noop);
5226        assert_eq!(out.schema_pin, "mig-a@0.1.0");
5227        assert_eq!(out.migration_target, None);
5228        assert!(out.findings.is_empty());
5229    }
5230
5231    /// Schema-switch invalidation: a
5232    /// schema switch changes NO store content — the store generation
5233    /// stays put — yet both derived memos depend on the schema
5234    /// (community weights, the index field set), so the switch must
5235    /// clear them. The schemas EPOCH is what carries that dependency
5236    /// into the memo key; without it the generation-checked hooks
5237    /// would keep both memos and serve results computed against the
5238    /// old schema (the staleness the whole-map drop used to mask).
5239    #[test]
5240    fn schema_switch_invalidates_both_memos_despite_unchanged_store() {
5241        let (_tmp, mut engine) = migration_engine();
5242
5243        let _ = engine.communities();
5244        let _ = engine.search_indexes();
5245        assert!(engine.community_memo.get().is_some());
5246        assert!(engine.search_indexes_memo.get().is_some());
5247        let store_gen_before = engine.store().generation();
5248
5249        engine
5250            .set_mem_schema("specs", &sref("mig-a@0.2.0"))
5251            .unwrap();
5252
5253        assert_eq!(
5254            engine.store().generation(),
5255            store_gen_before,
5256            "a schema switch mutates no store content"
5257        );
5258        assert!(
5259            engine.community_memo.get().is_none(),
5260            "the community memo must clear on a schema switch (weights derive from the schema)"
5261        );
5262        assert!(
5263            engine.search_indexes_memo.get().is_none(),
5264            "the search memo must clear on a schema switch (the field set derives from the schema)"
5265        );
5266    }
5267
5268    #[test]
5269    fn set_schema_switches_immediately_when_integral() {
5270        // Version bump within the same domain; entities conform to
5271        // the identical-shape 0.2.0, so the switch is immediate.
5272        let (_tmp, mut engine) = migration_engine();
5273        let out = engine
5274            .set_mem_schema("specs", &sref("mig-a@0.2.0"))
5275            .unwrap();
5276        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Switched);
5277        assert_eq!(out.schema_pin, "mig-a@0.2.0");
5278        assert_eq!(out.migration_target, None);
5279        assert!(out.findings.is_empty());
5280        assert_eq!(
5281            engine.schema_pin("specs").unwrap().as_display(),
5282            "mig-a@0.2.0"
5283        );
5284        assert!(engine.migration_target("specs").is_none());
5285    }
5286
5287    /// Regression: an atomic switch must persist the new pin into the
5288    /// **authoritative** backend config, not just `mounts.json`. Boot
5289    /// resolution prefers the backend config's pin over `Mount.schema`,
5290    /// so before this fix the switch evaporated on the next process boot
5291    /// for any config-present mem (every `create_mem`-made mem).
5292    #[test]
5293    fn set_schema_switch_persists_pin_into_backend_config() {
5294        let tmp = tempfile::TempDir::new().unwrap();
5295        let schemas_dir = tmp.path().join("schemas");
5296        write_mig_schema(&schemas_dir, "mig-a-1", "mig-a", "0.1.0", false);
5297        write_mig_schema(&schemas_dir, "mig-a-2", "mig-a", "0.2.0", false);
5298        let mem_dir = tmp.path().join("mem");
5299        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
5300        // Config-present mem: the authoritative pin lives here.
5301        std::fs::write(
5302            mem_dir.join(".memstead").join("config.json"),
5303            br#"{"schema":"mig-a@0.1.0"}"#,
5304        )
5305        .unwrap();
5306        let writer = crate::storage::FilesystemMemWriter::new(mem_dir.clone());
5307        let mut mount = folder_mount("specs", mem_dir.clone());
5308        mount.schema = Some("mig-a@0.1.0".parse().unwrap());
5309        let mut engine = Engine::from_mounts_with_schemas_dir(
5310            vec![(
5311                mount,
5312                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
5313            )],
5314            Some(&schemas_dir),
5315        )
5316        .unwrap();
5317
5318        let out = engine
5319            .set_mem_schema("specs", &sref("mig-a@0.2.0"))
5320            .unwrap();
5321        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Switched);
5322
5323        // The authoritative backend config now carries the new pin —
5324        // otherwise the switch would evaporate on reboot.
5325        let cfg_bytes = std::fs::read(mem_dir.join(".memstead").join("config.json")).unwrap();
5326        let cfg: serde_json::Value = serde_json::from_slice(&cfg_bytes).unwrap();
5327        assert_eq!(
5328            cfg["schema"], "mig-a@0.2.0",
5329            "atomic switch must update the authoritative backend config"
5330        );
5331    }
5332
5333    /// A completed migration re-stamps the mutation stamp (the marker
5334    /// `ENGINE_VERSION_SKEW` reads) with the target; a dual-pin entry
5335    /// leaves it on the old generation and says so; a set-schema to
5336    /// the pin the mem already carries changes no byte of the config.
5337    #[test]
5338    fn set_schema_completed_switch_restamps_marker_and_dual_pin_leaves_it() {
5339        let tmp = tempfile::TempDir::new().unwrap();
5340        let schemas_dir = tmp.path().join("schemas");
5341        write_mig_schema(&schemas_dir, "mig-a-1", "mig-a", "0.1.0", false);
5342        write_mig_schema(&schemas_dir, "mig-a-2", "mig-a", "0.2.0", false);
5343        write_mig_schema(&schemas_dir, "mig-b-1", "mig-b", "0.1.0", true);
5344        let mem_dir = tmp.path().join("mem");
5345        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
5346        let config_path = mem_dir.join(".memstead").join("config.json");
5347        // A stamp from an earlier mutation on the old generation.
5348        std::fs::write(
5349            &config_path,
5350            br#"{"schema":"mig-a@0.1.0","mutationStamp":{"engineVersion":"0.0.1","schema":"mig-a@0.1.0"}}"#,
5351        )
5352        .unwrap();
5353        let writer = crate::storage::FilesystemMemWriter::new(mem_dir.clone());
5354        let mut mount = folder_mount("specs", mem_dir.clone());
5355        mount.schema = Some("mig-a@0.1.0".parse().unwrap());
5356        let mut engine = Engine::from_mounts_with_schemas_dir(
5357            vec![(
5358                mount,
5359                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
5360            )],
5361            Some(&schemas_dir),
5362        )
5363        .unwrap();
5364        let stamp_of = |path: &std::path::Path| -> serde_json::Value {
5365            let cfg: serde_json::Value =
5366                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
5367            cfg["mutationStamp"].clone()
5368        };
5369
5370        // Refusal complement: the same pin moves no byte.
5371        let before = std::fs::read(&config_path).unwrap();
5372        let out = engine
5373            .set_mem_schema("specs", &sref("mig-a@0.1.0"))
5374            .unwrap();
5375        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Noop);
5376        assert_eq!(out.stamped_schema.as_deref(), Some("mig-a@0.1.0"));
5377        assert_eq!(
5378            std::fs::read(&config_path).unwrap(),
5379            before,
5380            "a noop set-schema changes no byte of the mem config"
5381        );
5382
5383        // Dual-pin entry (mig-b requires a section the entities lack):
5384        // the marker stays on the old generation and the outcome says so.
5385        for title in ["One", "Two"] {
5386            let mut args = empty_create_args("specs", title);
5387            args.entity_type = "doc".to_string();
5388            args.sections =
5389                indexmap::IndexMap::from_iter([("body".to_string(), "content".to_string())]);
5390            engine
5391                .create_entity(args, crate::vcs::Actor::Cli, None, None)
5392                .expect("conformant create under mig-a");
5393        }
5394        let out = engine
5395            .set_mem_schema("specs", &sref("mig-b@0.1.0"))
5396            .unwrap();
5397        assert_eq!(
5398            out.outcome,
5399            crate::engine::SetSchemaResult::MigrationStarted
5400        );
5401        assert!(!out.findings.is_empty());
5402        assert_eq!(out.stamped_schema.as_deref(), Some("mig-a@0.1.0"));
5403        assert_eq!(stamp_of(&config_path)["schema"], "mig-a@0.1.0");
5404
5405        // Completed switch (mig-a@0.2.0 is shape-identical, so the
5406        // in-flight mig-b target is replaced by an integral switch): the
5407        // marker names the new generation, stamped by this engine.
5408        let out = engine
5409            .set_mem_schema("specs", &sref("mig-a@0.2.0"))
5410            .unwrap();
5411        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Switched);
5412        assert_eq!(out.stamped_schema.as_deref(), Some("mig-a@0.2.0"));
5413        let stamp = stamp_of(&config_path);
5414        assert_eq!(stamp["schema"], "mig-a@0.2.0");
5415        assert_eq!(stamp["engineVersion"], crate::build_info::full_version());
5416    }
5417
5418    #[test]
5419    fn set_schema_unknown_target_refuses_schema_not_found() {
5420        let (_tmp, mut engine) = migration_engine();
5421        let err = engine
5422            .set_mem_schema("specs", &sref("nope@9.9.9"))
5423            .unwrap_err();
5424        assert_eq!(err.code(), "SCHEMA_NOT_FOUND");
5425        // No state change.
5426        assert!(engine.migration_target("specs").is_none());
5427    }
5428
5429    #[test]
5430    fn set_schema_migration_lifecycle_end_to_end() {
5431        let (_tmp, mut engine) = migration_engine();
5432        let target = sref("mig-b@0.1.0");
5433
5434        // 1. Non-integral target → migration starts; pin unchanged.
5435        let out = engine.set_mem_schema("specs", &target).unwrap();
5436        assert_eq!(
5437            out.outcome,
5438            crate::engine::SetSchemaResult::MigrationStarted
5439        );
5440        assert_eq!(out.schema_pin, "mig-a@0.1.0");
5441        assert_eq!(out.migration_target.as_deref(), Some("mig-b@0.1.0"));
5442        assert_eq!(out.findings.len(), 2, "both entities lack `status`");
5443        assert!(
5444            out.findings
5445                .iter()
5446                .all(|f| f.code == "REQUIRED_FIELD_UNSET")
5447        );
5448
5449        // 2. Reads of not-yet-repaired entities stay permissive.
5450        let one = crate::entity::EntityId::new("specs", "one");
5451        assert!(engine.store().get(&one).is_some());
5452
5453        // 3. Re-issue while unrepaired → pending, full remaining set.
5454        let out = engine.set_mem_schema("specs", &target).unwrap();
5455        assert_eq!(
5456            out.outcome,
5457            crate::engine::SetSchemaResult::MigrationPending
5458        );
5459        assert_eq!(out.findings.len(), 2);
5460
5461        // 4. Writes validate against the TARGET: `status` is unknown
5462        //    to the pinned mig-a but declared by mig-b — setting it
5463        //    must commit; an invalid enum value must refuse.
5464        let mut bad = crate::engine::UpdateEntityArgs {
5465            anchors: Vec::new(),
5466            id: one.clone(),
5467            expected_hash: None,
5468            sections: indexmap::IndexMap::new(),
5469            append_sections: indexmap::IndexMap::new(),
5470            patch_sections: indexmap::IndexMap::new(),
5471            sections_unset: Vec::new(),
5472            metadata: indexmap::IndexMap::from_iter([("status".to_string(), "banana".to_string())]),
5473            metadata_unset: Vec::new(),
5474            declare_relations: Vec::new(),
5475            dry_run: false,
5476            relations_unset: Vec::new(),
5477            anchors_unset: Vec::new(),
5478        };
5479        let err = engine
5480            .update_entity(bad.clone(), crate::vcs::Actor::Cli, None, None)
5481            .unwrap_err();
5482        assert_eq!(err.code(), "INVALID_ENUM_VALUE", "strict against target");
5483        bad.metadata = indexmap::IndexMap::from_iter([("status".to_string(), "open".to_string())]);
5484        engine
5485            .update_entity(bad, crate::vcs::Actor::Cli, None, None)
5486            .expect("repair write validated against the migration target");
5487
5488        // 5. One entity repaired → still pending, findings shrink.
5489        let out = engine.set_mem_schema("specs", &target).unwrap();
5490        assert_eq!(
5491            out.outcome,
5492            crate::engine::SetSchemaResult::MigrationPending
5493        );
5494        assert_eq!(out.findings.len(), 1, "only `two` remains non-integral");
5495
5496        // 6. Repair the second entity, re-issue → atomic switch.
5497        let two = crate::entity::EntityId::new("specs", "two");
5498        let repair = crate::engine::UpdateEntityArgs {
5499            anchors: Vec::new(),
5500            id: two.clone(),
5501            expected_hash: None,
5502            sections: indexmap::IndexMap::new(),
5503            append_sections: indexmap::IndexMap::new(),
5504            patch_sections: indexmap::IndexMap::new(),
5505            sections_unset: Vec::new(),
5506            metadata: indexmap::IndexMap::from_iter([("status".to_string(), "closed".to_string())]),
5507            metadata_unset: Vec::new(),
5508            declare_relations: Vec::new(),
5509            dry_run: false,
5510            relations_unset: Vec::new(),
5511            anchors_unset: Vec::new(),
5512        };
5513        engine
5514            .update_entity(repair, crate::vcs::Actor::Cli, None, None)
5515            .unwrap();
5516        let out = engine.set_mem_schema("specs", &target).unwrap();
5517        assert_eq!(out.outcome, crate::engine::SetSchemaResult::Switched);
5518        assert_eq!(out.schema_pin, "mig-b@0.1.0");
5519        assert_eq!(out.migration_target, None);
5520        assert!(out.findings.is_empty());
5521        assert_eq!(
5522            engine.schema_pin("specs").unwrap().as_display(),
5523            "mig-b@0.1.0"
5524        );
5525        assert!(engine.migration_target("specs").is_none());
5526    }
5527
5528    /// During migration every not-yet-repaired entity is
5529    /// non-conformant against the target, so `relations_unset` works
5530    /// on exactly those entities with no mode flag — and the same
5531    /// update can complete the entity's repair.
5532    #[test]
5533    fn relations_unset_works_during_migration_without_mode_flag() {
5534        let (_tmp, mut engine) = migration_engine();
5535        let one = crate::entity::EntityId::new("specs", "one");
5536        let two = crate::entity::EntityId::new("specs", "two");
5537        engine
5538            .relate_entity(
5539                crate::engine::RelateEntityArgs {
5540                    source: one.clone(),
5541                    expected_hash: None,
5542                    rel_type: "USES".to_string(),
5543                    target: two.clone(),
5544                    remove: false,
5545                    description: None,
5546                    dry_run: false,
5547                },
5548                crate::vcs::Actor::Cli,
5549                None,
5550                None,
5551            )
5552            .unwrap();
5553        // Conformant under the pin → the repair gate is shut.
5554        let shut = engine
5555            .update_entity(
5556                crate::engine::UpdateEntityArgs {
5557                    anchors: Vec::new(),
5558                    id: one.clone(),
5559                    expected_hash: None,
5560                    sections: indexmap::IndexMap::new(),
5561                    append_sections: indexmap::IndexMap::new(),
5562                    patch_sections: indexmap::IndexMap::new(),
5563                    sections_unset: Vec::new(),
5564                    metadata: indexmap::IndexMap::new(),
5565                    metadata_unset: Vec::new(),
5566                    declare_relations: Vec::new(),
5567                    dry_run: false,
5568                    relations_unset: vec![crate::ops::RelationUnsetArg {
5569                        rel_type: "USES".to_string(),
5570                        target: two.clone(),
5571                    }],
5572                    anchors_unset: Vec::new(),
5573                },
5574                crate::vcs::Actor::Cli,
5575                None,
5576                None,
5577            )
5578            .unwrap_err();
5579        assert_eq!(shut.code(), "REPAIR_NOT_NEEDED");
5580
5581        // Enter migration → `one` is now non-conformant against the
5582        // target; the same call opens, removes the relation, and the
5583        // bundled `status` set makes the entity integral-against-target.
5584        engine
5585            .set_mem_schema("specs", &sref("mig-b@0.1.0"))
5586            .unwrap();
5587        engine
5588            .update_entity(
5589                crate::engine::UpdateEntityArgs {
5590                    anchors: Vec::new(),
5591                    id: one.clone(),
5592                    expected_hash: None,
5593                    sections: indexmap::IndexMap::new(),
5594                    append_sections: indexmap::IndexMap::new(),
5595                    patch_sections: indexmap::IndexMap::new(),
5596                    sections_unset: Vec::new(),
5597                    metadata: indexmap::IndexMap::from_iter([(
5598                        "status".to_string(),
5599                        "open".to_string(),
5600                    )]),
5601                    metadata_unset: Vec::new(),
5602                    declare_relations: Vec::new(),
5603                    dry_run: false,
5604                    relations_unset: vec![crate::ops::RelationUnsetArg {
5605                        rel_type: "USES".to_string(),
5606                        target: two.clone(),
5607                    }],
5608                    anchors_unset: Vec::new(),
5609                },
5610                crate::vcs::Actor::Cli,
5611                None,
5612                None,
5613            )
5614            .expect("repair-shaped update lands during migration without a flag");
5615        let entity = engine.store().get(&one).unwrap();
5616        assert!(entity.relationships.is_empty());
5617    }
5618
5619    /// Boot honors a persisted in-flight migration: a mount carrying
5620    /// `migration_target` validates writes against the target from
5621    /// the first call of the new process — the resumability half of
5622    /// the dual-pin contract.
5623    #[test]
5624    fn boot_resumes_dual_pin_validation_against_target() {
5625        let (tmp, engine) = migration_engine();
5626        drop(engine);
5627        let schemas_dir = tmp.path().join("schemas");
5628        let mem_dir = tmp.path().join("mem");
5629        let writer = crate::storage::FilesystemMemWriter::new(mem_dir.clone());
5630        let mut mount = folder_mount("specs", mem_dir);
5631        mount.schema = Some("mig-a@0.1.0".parse().unwrap());
5632        mount.migration_target = Some("mig-b@0.1.0".parse().unwrap());
5633        let engine = Engine::from_mounts_with_schemas_dir(
5634            vec![(
5635                mount,
5636                Box::new(writer) as Box<dyn crate::backend::MemBackend>,
5637            )],
5638            Some(&schemas_dir),
5639        )
5640        .unwrap();
5641        // Effective validation schema is the target...
5642        let (name, version) = {
5643            let s = engine.schema_for("specs").unwrap();
5644            let (n, v) = s.id();
5645            (n.to_string(), v.to_string())
5646        };
5647        assert_eq!((name.as_str(), version.as_str()), ("mig-b", "0.1.0"));
5648        // ...while the settled pin and the in-flight target read back
5649        // distinctly.
5650        assert_eq!(
5651            engine.schema_pin("specs").unwrap().as_display(),
5652            "mig-a@0.1.0"
5653        );
5654        assert_eq!(
5655            engine.migration_target("specs").unwrap().as_display(),
5656            "mig-b@0.1.0"
5657        );
5658    }
5659
5660    /// Every lifecycle setter refuses `READ_ONLY_MOUNT` on a read-only
5661    /// mount — the family, not an instance. `set_mem_schema` was the
5662    /// one ungated sibling (a schema-pin change starts a migration —
5663    /// the last mutation a sealed mount should accept); this test
5664    /// enumerates all seven current setters — extend it when adding an
5665    /// eighth (the enumeration is manual, not reflective). Refusal complement: the same calls succeed (or fail
5666    /// for their own non-capability reasons) against a writable mount —
5667    /// covered by the existing per-setter tests; `set_mem_schema`'s
5668    /// writable-mount behaviour is pinned by the migration tests above.
5669    #[test]
5670    fn every_lifecycle_setter_refuses_on_read_only_mount() {
5671        let tmp = TempDir::new().unwrap();
5672        let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"# Title: Foo\n")]);
5673        let mut engine = Engine::from_mounts(vec![(
5674            archive_mount("ext", archive_path.clone()),
5675            Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
5676        )])
5677        .unwrap();
5678
5679        let default_pin: memstead_schema::SchemaRef = "default@1.0.0".parse().unwrap();
5680        let attempts: Vec<(&str, EngineError)> = vec![
5681            (
5682                "set_mem_schema",
5683                engine.set_mem_schema("ext", &default_pin).unwrap_err(),
5684            ),
5685            (
5686                "set_mem_version",
5687                engine
5688                    .set_mem_version("ext", semver::Version::new(9, 9, 9), None)
5689                    .unwrap_err(),
5690            ),
5691            (
5692                "set_mem_description",
5693                engine
5694                    .set_mem_description("ext", Some("x".into()), None)
5695                    .unwrap_err(),
5696            ),
5697            (
5698                "set_mem_title",
5699                engine
5700                    .set_mem_title("ext", Some("x".into()), None)
5701                    .unwrap_err(),
5702            ),
5703            (
5704                "set_mem_subject",
5705                engine.set_mem_subject("ext", None, None).unwrap_err(),
5706            ),
5707            (
5708                "set_mem_internal",
5709                engine.set_mem_internal("ext", true, None).unwrap_err(),
5710            ),
5711            (
5712                "set_mem_sync_state",
5713                engine
5714                    .set_mem_sync_state("ext", "k", "t", None)
5715                    .unwrap_err(),
5716            ),
5717        ];
5718        for (setter, err) in attempts {
5719            match err {
5720                EngineError::ReadOnlyMount(v) => {
5721                    assert_eq!(v, "ext", "{setter} must name the refused mem")
5722                }
5723                other => panic!("{setter} must refuse ReadOnlyMount, got {other:?}"),
5724            }
5725        }
5726    }
5727
5728    /// 04/03, criteria 1 and 2, on the folder backend. Every one of the
5729    /// lifecycle setters, each against a config a sibling moved after boot.
5730    /// The loop is the point: the criterion is the whole set behind one
5731    /// implementation, so a test that exercised one setter would pass while
5732    /// the other six stayed broken.
5733    #[test]
5734    fn no_config_setter_reverts_a_siblings_write() {
5735        type Setter = fn(&mut Engine) -> Result<(), EngineError>;
5736        let setters: Vec<(&str, Setter)> = vec![
5737            ("version", |e| {
5738                e.set_mem_version("specs", semver::Version::new(9, 0, 0), None)
5739                    .map(|_| ())
5740            }),
5741            ("description", |e| {
5742                e.set_mem_description("specs", Some("mine".into()), None)
5743                    .map(|_| ())
5744            }),
5745            ("title", |e| {
5746                e.set_mem_title("specs", Some("Mine".into()), None)
5747                    .map(|_| ())
5748            }),
5749            ("internal", |e| {
5750                e.set_mem_internal("specs", true, None).map(|_| ())
5751            }),
5752            ("sync_state", |e| {
5753                e.set_mem_sync_state("specs", "src/facet", "tok", None)
5754                    .map(|_| ())
5755            }),
5756            // Cleared rather than set: the mark validates against a real
5757            // commit cursor, and the clear path writes config just the same,
5758            // which is what this test is about.
5759            ("review_mark", |e| {
5760                e.set_review_mark("specs", None, None).map(|_| ())
5761            }),
5762        ];
5763
5764        for (name, set) in setters {
5765            let tmp = TempDir::new().unwrap();
5766            let mem_dir = tmp.path().to_path_buf();
5767            let meta = mem_dir.join(memstead_schema::MEM_META_DIR);
5768            std::fs::create_dir_all(&meta).unwrap();
5769            let path = meta.join("config.json");
5770            std::fs::write(
5771                &path,
5772                br#"{"schema": "default@1.0.0", "version": "0.1.0"}"#.as_slice(),
5773            )
5774            .unwrap();
5775
5776            let writer = FilesystemMemWriter::new(mem_dir.clone());
5777            let mut engine = Engine::from_mounts(vec![(
5778                folder_mount("specs", mem_dir.clone()),
5779                Box::new(writer) as Box<dyn MemBackend>,
5780            )])
5781            .unwrap();
5782            // The review-mark setter validates its cursor against a real
5783            // entity, so seed one before the sibling write.
5784            engine
5785                .create_entity(
5786                    crate::engine::test_helpers::empty_create_args("specs", "Seed"),
5787                    crate::vcs::Actor::Cli,
5788                    None,
5789                    None,
5790                )
5791                .unwrap();
5792
5793            // A sibling writes a field this engine has never seen.
5794            let mut sibling: memstead_schema::MemConfig =
5795                serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
5796            sibling
5797                .extra
5798                .insert("siblingMark".into(), serde_json::json!("kept"));
5799            std::fs::write(&path, serde_json::to_vec_pretty(&sibling).unwrap()).unwrap();
5800
5801            set(&mut engine).unwrap_or_else(|e| panic!("{name} setter failed: {e}"));
5802
5803            let after: memstead_schema::MemConfig =
5804                serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
5805            assert_eq!(
5806                after.extra.get("siblingMark"),
5807                Some(&serde_json::json!("kept")),
5808                "the {name} setter reverted a field it never set"
5809            );
5810        }
5811    }
5812
5813    /// Criterion 3, and its complement 4: the intervention is reported on the
5814    /// operation's own response, and only when there was one.
5815    #[test]
5816    fn intervention_is_reported_on_the_response_and_only_when_real() {
5817        let tmp = TempDir::new().unwrap();
5818        let mem_dir = tmp.path().to_path_buf();
5819        let meta = mem_dir.join(memstead_schema::MEM_META_DIR);
5820        std::fs::create_dir_all(&meta).unwrap();
5821        let path = meta.join("config.json");
5822        std::fs::write(&path, br#"{"schema": "default@1.0.0"}"#.as_slice()).unwrap();
5823        let writer = FilesystemMemWriter::new(mem_dir.clone());
5824        let mut engine = Engine::from_mounts(vec![(
5825            folder_mount("specs", mem_dir.clone()),
5826            Box::new(writer) as Box<dyn MemBackend>,
5827        )])
5828        .unwrap();
5829
5830        // Single writer: no report. This is the ordinary path, and a fix that
5831        // cried intervention here would be worse than the bug.
5832        let quiet = engine
5833            .set_mem_description("specs", Some("first".into()), None)
5834            .unwrap();
5835        assert!(
5836            !quiet
5837                .warnings
5838                .iter()
5839                .any(|w| w.code() == "CONFIG_WRITE_INTERVENED"),
5840            "single-writer workspace must stay silent: {:?}",
5841            quiet.warnings
5842        );
5843
5844        // A sibling intervenes; the next write says so, naming the field.
5845        let mut sibling: memstead_schema::MemConfig =
5846            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
5847        sibling.title = Some("theirs".into());
5848        std::fs::write(&path, serde_json::to_vec_pretty(&sibling).unwrap()).unwrap();
5849
5850        let loud = engine
5851            .set_mem_description("specs", Some("second".into()), None)
5852            .unwrap();
5853        let hint = loud
5854            .warnings
5855            .iter()
5856            .find(|w| w.code() == "CONFIG_WRITE_INTERVENED")
5857            .expect("intervention must be reported on the response");
5858        assert!(
5859            format!("{hint}").contains("title"),
5860            "the report names what they changed: {hint}"
5861        );
5862        // And theirs survived, which is the point of reporting rather than refusing.
5863        let after: memstead_schema::MemConfig =
5864            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
5865        assert_eq!(after.title.as_deref(), Some("theirs"));
5866        assert_eq!(after.description.as_deref(), Some("second"));
5867    }
5868}