memstead_base/engine/query.rs
1//! Engine read paths — accessors and queries.
2//!
3//! Read-only methods on `Engine`: store / schema / mount accessors,
4//! per-mem path helpers (`gitdir_for` / `worktree_for`), aggregated
5//! views (`communities`, `orphans`, `stubs`, `most_connected`,
6//! `missing_required_outgoing`), per-mem summaries (`health`,
7//! `status`, `context`), search (`list`, `search`,
8//! `search_indexes`), and the bytes-level read wrappers
9//! (`list_entities`, `read_entity`, `read_provenance`). Capability and
10//! cross-mem link gating live here too — they're consulted by
11//! handlers before any mutation reaches the backend.
12
13use std::cell::OnceCell;
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use memstead_schema::Schema;
19
20use crate::engine_fallback_type;
21use crate::entity::{Entity, EntityId};
22use crate::graph::{LouvainOutput, community::detect_communities};
23use crate::mem::MemRouterSnapshot;
24use crate::ops::{ContextResult, Direction, NeighborInfo, SearchResult, SearchScope, WarningHint};
25use crate::provenance::Provenance;
26#[cfg(not(target_arch = "wasm32"))]
27use crate::search_index::{MemIndex, build_all};
28use crate::store::Store;
29use crate::workspace::{MountCapability, MountStorage, WorkspaceSettings};
30
31use super::{BackendFactory, Engine, EngineError, MountedBackend};
32
33impl Engine {
34 /// In-memory store populated at construction time from every
35 /// mount's backend. Read-only at this point in the rebuild —
36 /// mutation paths land in a later session.
37 pub fn store(&self) -> &Store {
38 &self.store
39 }
40
41 /// Per-mem schema, keyed by mount's mem name. Each entry is the
42 /// schema resolved from that mount's pin at boot, so the map holds
43 /// genuinely heterogeneous schemas in a multi-schema workspace.
44 pub fn schemas(&self) -> &HashMap<String, Arc<Schema>> {
45 &self.schemas
46 }
47
48 /// Workspace-authored schemas loaded from
49 /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
50 /// [`Self::schemas`] (per-mem, only schemas pinned by a mount):
51 /// this slice carries every workspace-loaded schema regardless of
52 /// whether a mem pins it. Used by `memstead_overview` to enumerate
53 /// schemas referenced by `mem_create_rules.schemas[]` but not
54 /// pinned by any mem — agents see what could be pinned without
55 /// looking up the workspace.toml directly.
56 pub fn workspace_schemas(&self) -> &[Arc<Schema>] {
57 &self.workspace_schemas
58 }
59
60 /// Embedded built-in schemas loaded once at boot. Handlers
61 /// resolving a schema pin by `<name>@<version>` (MCP's `memstead_schema`,
62 /// `memstead_overview` rendering) walk mem-pinned, workspace, and
63 /// built-in catalogues in order — built-ins are the catch-all when
64 /// no mem or workspace dir pins the schema. Workspace schemas
65 /// shadow built-ins on `(name, version)` collision; resolve from
66 /// `workspace_schemas()` first.
67 pub fn builtin_schemas(&self) -> &[Arc<Schema>] {
68 &self.builtin_schemas
69 }
70
71 /// Classify a schema's trust origin — the single authority every read
72 /// surface consults before serving a schema's instruction-prose.
73 ///
74 /// A schema is [`OriginClass::FirstParty`] iff it is an engine built-in
75 /// **or** pinned by a writable mount in this workspace. Built-ins are
76 /// compiled into the binary — unforgeable. A non-built-in schema earns
77 /// first-party status only once the operator *adopts* it by writably
78 /// mounting a mem that pins it: writing into a mem is the act that
79 /// legitimately needs a schema's authoring prose (`system_message`,
80 /// `write_rules`, …), and the mount's writable posture is set by the
81 /// consumer's own config — a publisher cannot forge it.
82 ///
83 /// Everything else is [`OriginClass::ThirdParty`]: a schema present in
84 /// the catalogue but pinned only by read-only mounts (a registry-
85 /// installed read-mem or an adopted foreign folder/clone), or one the
86 /// engine cannot vouch for at all. Its prose is served structural-only
87 /// so a stranger's free-text never reaches a consuming agent as
88 /// instructions. This classifies by the mount graph — never by scanning
89 /// the schema's content, which a publisher controls — and `ThirdParty`
90 /// is the safe default for any ambiguous origin.
91 ///
92 /// Note a read-only mount pinning a *built-in* schema (e.g. a registry
93 /// mem on `default@1.0.0`) resolves to the consumer's own clean copy
94 /// and stays first-party — the de-framing targets only foreign,
95 /// non-built-in schemas that no writable mem has adopted.
96 pub fn schema_origin(&self, schema: &Arc<Schema>) -> crate::render::OriginClass {
97 use crate::render::OriginClass;
98 let (name, version) = schema.id();
99 // Built-in schemas are compiled in — first-party, unforgeable.
100 let is_builtin = self.builtin_schemas.iter().any(|s| {
101 let id = s.id();
102 id.0 == name && id.1 == version
103 });
104 if is_builtin {
105 return OriginClass::FirstParty;
106 }
107 // Adoption signal: some writable mount pins this exact schema, so
108 // the operator authors against it here.
109 let canon = format!("{name}@{version}");
110 let pinned_by_writable = self.mounts().iter().any(|m| {
111 m.schema.as_ref().map(|s| s.to_string()).as_deref() == Some(canon.as_str())
112 && self.mem_router().is_writable(&m.mem)
113 });
114 if pinned_by_writable {
115 OriginClass::FirstParty
116 } else {
117 OriginClass::ThirdParty
118 }
119 }
120
121 /// Classify a mem's *data* trust origin — the authority every read
122 /// surface consults before serving an entity's content (bodies,
123 /// snippets, titles). A writable mount is [`OriginClass::FirstParty`]:
124 /// its content is authored in this workspace. Anything else — a
125 /// read-only mount (a registry-installed read-mem or an adopted
126 /// foreign folder/clone) or an unknown mem — is
127 /// [`OriginClass::ThirdParty`], so the consuming agent/host treats the
128 /// content as quoted, untrusted data.
129 ///
130 /// This reads the deployment's declaration when one exists (see
131 /// [`Self::declare_mem_origin`]), else the mount's already-decided
132 /// writable/read-only posture (fixed at adopt/mount time) — it never
133 /// scans content, and both levers are consumer-side config, so a
134 /// publisher cannot forge first-party. Distinct from
135 /// [`Self::schema_origin`], which governs a schema's
136 /// instruction-prose: the data channel and the instruction channel
137 /// are separate vectors with separate authorities.
138 pub fn mem_origin_class(&self, mem: &str) -> crate::render::OriginClass {
139 if let Some(declared) = self.declared_origins.get(mem) {
140 return *declared;
141 }
142 if self.mem_router().is_writable(mem) {
143 crate::render::OriginClass::FirstParty
144 } else {
145 crate::render::OriginClass::ThirdParty
146 }
147 }
148
149 /// Declare a mem's data-trust origin as a deployment fact — the
150 /// embedding process (a curated hosted read tier, an app that vouches
151 /// for a bundled mem) overrides the writability inference for one mem.
152 /// Composition-layer-only by design: not persisted, not reachable over
153 /// MCP, never derived from mem content — the operator running the
154 /// process is the only authority that can set it, so a served mem the
155 /// deployment does *not* vouch for keeps reporting third-party on
156 /// every surface. (Deliberately absent from the CLI: that surface
157 /// operates a workspace, not a deployment; the CLI counterpart would be
158 /// a workspace-config knob no use case demands yet.)
159 pub fn declare_mem_origin(
160 &mut self,
161 mem: impl Into<String>,
162 origin: crate::render::OriginClass,
163 ) {
164 self.declared_origins.insert(mem.into(), origin);
165 }
166
167 /// Per-file errors collected during load. Non-fatal: the engine
168 /// continues with whatever did parse. Empty when every backend's
169 /// content parses cleanly.
170 pub fn load_errors(&self) -> &[(PathBuf, String)] {
171 &self.load_errors
172 }
173
174 /// Resolve a VISIBLE mem to its folder-storage root on disk.
175 ///
176 /// Unknown or quarantined names refuse `UNKNOWN_MEM` (the same
177 /// visibility gate `search` and the conflicts door apply); a
178 /// visible mount whose storage is not folder-backed returns
179 /// `Ok(None)` so callers branch on backend applicability without
180 /// inventing a typed error. Read-only mounts resolve too — this is
181 /// a read accessor, not a write gate. Generic by design: any
182 /// consumer that needs a folder mem's disk root (per-mem changelog
183 /// readers, export tooling, future doors) gets the same answer.
184 pub fn folder_mem_root(&self, mem: &str) -> Result<Option<PathBuf>, EngineError> {
185 let mount = self
186 .mounts
187 .iter()
188 .find(|m| m.mount.mem == mem)
189 .ok_or_else(|| self.unknown_mem_error(mem))?;
190 if self.quarantine_reason(mem).is_some() {
191 return Err(self.unknown_mem_error(mem));
192 }
193 match &mount.mount.storage {
194 crate::workspace::MountStorage::Folder { path } => Ok(Some(path.clone())),
195 _ => Ok(None),
196 }
197 }
198
199 /// Workspace-level operator policy (mem create/delete rules,
200 /// cross-mem links). Defaults to empty; populated via
201 /// [`Engine::set_settings`] after construction. Surfaced for MCP
202 /// handlers (`memstead_health { include_config: true }`,
203 /// `memstead_overview`'s lifecycle-namespaces section) and other
204 /// consumers that need to read workspace policy.
205 pub fn settings(&self) -> &WorkspaceSettings {
206 &self.settings
207 }
208
209 /// The pipeline configs — the v2 single-record binding store — loaded
210 /// from the workspace at boot: the read-only queryable surface the
211 /// loader exposes. Empty for engines not booted from a workspace root,
212 /// or for a workspace that declares no pipelines. The ingest skill
213 /// and future MCP tools consume this structured form
214 /// rather than re-reading the JSON folders.
215 pub fn pipeline_configs(&self) -> &crate::pipeline_store::BindingConfigs {
216 &self.pipeline_configs
217 }
218
219 /// The pipeline configs serialized as a JSON string — the read
220 /// counterpart of the `add_projection_json` edit entry point.
221 /// Serialization-boundary callers (where serde does not live)
222 /// get the store in one call and deserialize on their side.
223 ///
224 /// Shape: `{ "bindings": [{ mem, name, config }] }` — the v2
225 /// single-record store (`config` carries the whole binding: inline
226 /// `sources`, `operations`, everything). The `mediums` / `facets` /
227 /// `ingests` keys are **gone** with their record kinds. This reads the
228 /// live binding store fresh (like the brief path) rather than the
229 /// in-memory snapshot, so an edit shows back immediately. A missing
230 /// root or a legacy/unreadable store yields the fallback empty object.
231 pub fn pipeline_configs_json(&self) -> String {
232 let empty = || "{\"bindings\":[]}".to_string();
233 let Some(root) = self.workspace_root() else {
234 return empty();
235 };
236 match crate::pipeline_store::load_pipeline_configs(root) {
237 Ok(configs) => serde_json::to_string(&configs).unwrap_or_else(|_| empty()),
238 Err(_) => empty(),
239 }
240 }
241
242 /// Overwrite the in-memory pipeline configs. The workspace-root boot
243 /// paths call this after [`crate::pipeline_store::load_pipeline_configs`];
244 /// exposed so the full boot helper (a separate crate) can populate the
245 /// same surface.
246 pub fn set_pipeline_configs(&mut self, configs: crate::pipeline_store::BindingConfigs) {
247 self.pipeline_configs = configs;
248 }
249
250 /// Build a [`WarningHint::NoteMissing`] when the workspace has
251 /// `[mutations].require_notes = true` and the caller omitted (or
252 /// passed a blank/whitespace-only) `note`; `None` otherwise.
253 ///
254 /// This is the single enforcement point for the `require_notes`
255 /// provenance nudge. Every mutation that accepts a `note` calls it
256 /// on its commit-landing path and pushes the result onto the
257 /// outcome's `warnings`, so both the CLI and the MCP transports
258 /// inherit identical behaviour from the engine response rather than
259 /// each re-deriving the policy at its own boundary (the drift that
260 /// left the policy decorative on the CLI). `tool` becomes the
261 /// warning's `details.tool` — callers pass the engine-level verb
262 /// (`create_entity`, `update_entity`, `relate_entity`,
263 /// `delete_entity`, `rename_entity`, `create_mem`,
264 /// `delete_mem`), matching the commit `Tool:` provenance trailer.
265 /// The mutation still commits — the policy nudges, it never blocks.
266 pub fn note_missing_warning(&self, tool: &str, note: Option<&str>) -> Option<WarningHint> {
267 if !self.settings.mutations.require_notes.unwrap_or(false) {
268 return None;
269 }
270 let has_note = note.map(|n| !n.trim().is_empty()).unwrap_or(false);
271 if has_note {
272 return None;
273 }
274 Some(WarningHint::NoteMissing {
275 tool: tool.to_string(),
276 })
277 }
278
279 /// Backend factory currently installed on this engine. Returned by
280 /// value because [`BackendFactory`] is a function pointer (`Copy`).
281 /// Used by [`crate::mem_management::create_mem`] to materialise
282 /// the backend for a freshly-registered mount; consumers that need
283 /// to instantiate a backend ad-hoc can call this directly.
284 pub fn backend_factory(&self) -> BackendFactory {
285 self.backend_factory
286 }
287
288 /// Git-branch ops bundle currently installed on this engine.
289 /// `None` on engines without the git-branch crate, which see no mem-repo
290 /// mounts. Returned by value because [`super::GitBranchOps`] is
291 /// `Copy`. `create_mem` reaches for
292 /// the bundle to drive `prune_residue` against an unmounted
293 /// gitdir when the `ForceOverwrite` recovery action is selected.
294 pub fn git_branch_ops(&self) -> Option<super::GitBranchOps> {
295 self.git_branch_ops
296 }
297
298 /// Convenience: look up a parsed entity by id. Returns `None` for
299 /// unknown ids, including stub entries created for unresolved
300 /// inline-link targets — callers that want to distinguish real
301 /// from stub branch on `Entity::stub`.
302 pub fn get_entity(&self, id: &EntityId) -> Option<&Entity> {
303 self.store.get(id)
304 }
305
306 /// The stored provenance anchors for `id`, read from its mem's
307 /// anchors sidecar. Empty for an entity with none, an unknown mem, or
308 /// a backend that does not persist anchors (a pre-anchor archive / any
309 /// sealed read-only mount). Additive read surface: the
310 /// resolution *model* lives in [`crate::anchor`]
311 /// ([`crate::anchor::resolve_anchor`] / [`crate::anchor::compose_entity_anchors`]);
312 /// the live per-anchor *state* (which requires observing the source
313 /// artifacts through the medium/preparation pipeline) is the anchor
314 /// observation pass's concern.
315 /// The anchors sidecar's parse error for `mem`, if it has one.
316 ///
317 /// The anchor readers below degrade a malformed sidecar to "no anchors",
318 /// which keeps a read path alive but makes a corrupt file
319 /// indistinguishable from an empty one. For a *reader* that is the right
320 /// trade; for anything that draws a conclusion from the absence of
321 /// anchors it is not — a fidelity pass would report every artifact
322 /// uncovered and call it a finding, when the truth is that it could not
323 /// read the file. Callers that need that distinction ask here first and
324 /// refuse. `None` means the sidecar is absent (legitimately no anchors
325 /// yet) or parses cleanly; the binding store draws the same distinction
326 /// with its quarantine path.
327 /// The entities of `mem` that hold at least one anchor row — the
328 /// sidecar's key set, no observation performed. What a coverage reading
329 /// subtracts from the mem's entity roster to name the entities no
330 /// artifact stands behind. Empty for a mem with no sidecar, an unmounted
331 /// mem, or an unreadable sidecar (the latter is reported by
332 /// [`Self::anchors_sidecar_error`], never inferred from an empty set).
333 pub fn mem_anchor_holders(&self, mem: &str) -> std::collections::BTreeSet<String> {
334 let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
335 return Default::default();
336 };
337 let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
338 return Default::default();
339 };
340 let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
341 return Default::default();
342 };
343 sc.entities
344 .iter()
345 .filter(|(_, rows)| !rows.is_empty())
346 .map(|(eid, _)| eid.clone())
347 .collect()
348 }
349
350 pub fn anchors_sidecar_error(&self, mem: &str) -> Option<String> {
351 let mount = self.mounts.iter().find(|m| m.mount.mem == mem)?;
352 // Three distinct ways to be unreadable, and only one of them is a
353 // parse error. `.ok().flatten()` would collapse the first into
354 // "absent", which is the very confusion this exists to prevent.
355 let bytes = match mount.backend.read_anchors_sidecar() {
356 // A backend error — permission denied, an IO fault. The file may
357 // be perfectly well-formed; we simply could not look at it.
358 Err(e) => return Some(format!("could not read the sidecar: {e}")),
359 // Genuinely absent: a mem with no anchors yet. Not an error.
360 Ok(None) => return None,
361 Ok(Some(b)) => b,
362 };
363 // An empty or whitespace-only file parses as "no anchors" by a
364 // deliberate tolerance in `from_bytes`. That tolerance is right for a
365 // reader and wrong here: a sidecar truncated to zero by an
366 // interrupted write is not a mem that never had anchors.
367 if bytes.iter().all(|b| b.is_ascii_whitespace()) {
368 return Some(
369 "the sidecar file is empty — an interrupted write leaves this state, and it is not the same as having no anchors; remove the file if the mem genuinely has none"
370 .to_string(),
371 );
372 }
373 match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
374 Ok(_) => None,
375 Err(e) => Some(e.to_string()),
376 }
377 }
378
379 pub fn entity_anchors(&self, id: &EntityId) -> Vec<crate::anchor::Anchor> {
380 let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == id.mem()) else {
381 return Vec::new();
382 };
383 let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
384 return Vec::new();
385 };
386 match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
387 Ok(sc) => sc.get(id.as_ref()).to_vec(),
388 // Deliberate degrade-to-empty for the read path; a caller that
389 // must not confuse "unreadable" with "none" checks
390 // [`Self::anchors_sidecar_error`] first.
391 Err(_) => Vec::new(),
392 }
393 }
394
395 /// The stored anchors for `id`, each paired with its **live** resolution
396 /// state when the engine could observe the source artifact this pass.
397 ///
398 /// Additive over [`Self::entity_anchors`]: the durable data is unchanged;
399 /// `state` is the [`crate::anchor::resolve_anchor`] outcome against an
400 /// observation the engine produces here. A `path`-namespace anchor
401 /// (codebase / filesystem / git) is observed against the working tree at
402 /// the current HEAD; an `entity`-namespace anchor is observed against the
403 /// live graph by [`Self::observe_entity_anchor`]:
404 ///
405 /// - artifact absent ⇒ [`AnchorState::Orphaned`](crate::anchor::AnchorState::Orphaned);
406 /// - artifact present, non-hash class (`authored` / `informed-by`) ⇒
407 /// [`Resolves`](crate::anchor::AnchorState::Resolves);
408 /// - artifact present, hash-bearing class (`anchored` / `derived`) ⇒ the
409 /// prepared-content hash comparison decides:
410 /// [`Resolves`](crate::anchor::AnchorState::Resolves) on a match,
411 /// [`Drifted`](crate::anchor::AnchorState::Drifted) on a stable-medium
412 /// mismatch, [`Recheck`](crate::anchor::AnchorState::Recheck) on an
413 /// unstable medium or when a hash is unavailable on either side (a
414 /// hash-less anchor, a `tree` grain, an unreadable artifact).
415 ///
416 /// For an `entity` grain the same table applies, read off the store
417 /// rather than the filesystem: the entity missing (or present only as a
418 /// stub) is `Orphaned`, and a hash-bearing class compares the canonical
419 /// rendered markdown.
420 ///
421 /// `state` is `None` (unobserved — never a fabricated state) when there is
422 /// no workspace root, when the grain is `url` (the engine never fetches;
423 /// a url anchor's hash is the registry's prepared form of the content
424 /// its observer supplied at write time), when an `entity` anchor's
425 /// source declares a preparation the registry does not know (the form
426 /// cannot be computed), or when an `entity` anchor's mem is **not
427 /// mounted** — an unmounted mem is not a mem of deleted entities, and
428 /// saying so would route a deletion proposal to prune.
429 pub fn entity_anchors_resolved(&self, id: &EntityId) -> Vec<ResolvedAnchor> {
430 let anchors = self.entity_anchors(id);
431 let source_roots = self.anchor_source_roots(id.mem());
432 let none = SuppliedObservations::new();
433 anchors
434 .into_iter()
435 .map(|anchor| self.resolve_one(anchor, &source_roots, &none))
436 .collect()
437 }
438
439 /// Observe one stored anchor and pair it with its resolution — the
440 /// shared step behind every anchor read.
441 fn resolve_one(
442 &self,
443 anchor: crate::anchor::Anchor,
444 source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
445 supplied: &SuppliedObservations,
446 ) -> ResolvedAnchor {
447 let observed = self.observe_anchor(&anchor, source_roots, supplied);
448 let (state, observed_hash, observed_at) = match observed {
449 Some(o) => (Some(o.state), o.hash, o.at),
450 None => (None, None, None),
451 };
452 ResolvedAnchor {
453 anchor,
454 state,
455 observed_hash,
456 observed_at,
457 }
458 }
459
460 /// Per-anchor observation — THE one resolution mechanism, shared by
461 /// binding-backed verify (`mem_anchors_resolved`, which the ingest
462 /// render/report/prune/findings paths consume), the per-entity read
463 /// (`entity_anchors_resolved`), and the standalone
464 /// `verify_mem_anchors` operation. Path-shaped grains
465 /// (`span`/`file`/`tree`) observe under the **decision-29 candidate
466 /// priority** (an earlier plana): the anchor's artifact path is
467 /// SOURCE-relative first — when its `source` name resolves through
468 /// `source_roots` to a declared pointer, the pointer-joined path is
469 /// authoritative — and workspace-relative only as the fallback, tried
470 /// when the source-join does not resolve. A path resolving under both
471 /// joins is decided by that priority, deterministically. An anchor
472 /// without a `source` (a hand-authored mem, a binding-less write)
473 /// observes workspace-relative exactly as before. A `url`
474 /// grain has no engine-side observation and returns `None` (the report
475 /// vocabulary's `unresolvable`) — the engine never fetches; its hash is
476 /// recorded from observation-supplied content at write time — as does a
477 /// workspace-root-less engine. An `entity`
478 /// grain is not a filesystem path but is not unobservable either — it
479 /// resolves against the live graph via
480 /// [`Self::observe_entity_anchor`], under the preparation its source
481 /// declares (touchpoint A of [`crate::preparation`]: the registry
482 /// decides the prepared form the artifact hashes as). This replaces the retired `single_path_medium_root` gate,
483 /// whose single-source assumption nulled every anchor of a mem with
484 /// zero or several bindings — the honest per-anchor answer supersedes
485 /// the all-or-nothing mem-level one.
486 ///
487 /// A `url` grain is the one grain the engine cannot observe itself: it
488 /// resolves from a SUPPLIED observation when the caller passed one for
489 /// its artifact (`memstead verify-anchors --observations`), else from
490 /// the row's recorded `last_observed` (sidecar version 2) — an
491 /// observation that was made, carrying its own date so the row ages
492 /// visibly — else it is unobserved (`None`), never fabricated. A
493 /// supplied `absent` resolves `recheck`, not `orphaned`: an observer
494 /// failing to retrieve a web resource is not the medium saying the
495 /// artifact is gone, and prune must never act on it.
496 fn observe_anchor(
497 &self,
498 anchor: &crate::anchor::Anchor,
499 source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
500 supplied: &SuppliedObservations,
501 ) -> Option<Observed> {
502 if anchor.grain == crate::anchor::AnchorGrain::Url {
503 if let Some(obs) = supplied.get(&anchor.artifact) {
504 return Some(match &obs.outcome {
505 crate::anchor::SuppliedOutcome::Absent => Observed {
506 state: crate::anchor::AnchorState::Recheck,
507 hash: None,
508 at: Some(obs.at.clone()),
509 },
510 crate::anchor::SuppliedOutcome::Present { hash, content } => {
511 // Touchpoint A for a url row: supplied CONTENT is
512 // re-prepared under the anchor's source preparation,
513 // the rule the write path applied to the anchor's
514 // own `content`, so a `quoted-phrase` row is
515 // adjudicated on its phrase. A phrase the retrieved
516 // page no longer carries is the medium saying the
517 // unit is gone — `orphaned` — unlike a failed
518 // retrieval, which stays `recheck`. A supplied hash,
519 // or a source with no preparation, compares as is.
520 let preparation = anchor
521 .source
522 .as_deref()
523 .and_then(|name| source_roots.get(name))
524 .and_then(|j| j.preparation.as_deref());
525 let current = match (preparation, content) {
526 (Some(_), Some(text)) => crate::preparation::path_prepared_hash(
527 preparation,
528 &anchor.artifact,
529 anchor.grain,
530 text.as_bytes(),
531 ),
532 _ => crate::preparation::PathPrepared::NoHash,
533 };
534 match current {
535 crate::preparation::PathPrepared::UnitAbsent => Observed {
536 state: crate::anchor::resolve_anchor(
537 anchor,
538 &crate::anchor::ArtifactObservation::Absent,
539 ),
540 hash: None,
541 at: Some(obs.at.clone()),
542 },
543 crate::preparation::PathPrepared::Hash(h) => Observed {
544 state: crate::anchor::resolve_anchor(
545 anchor,
546 &crate::anchor::ArtifactObservation::Present {
547 current_hash: Some(h.clone()),
548 },
549 ),
550 hash: Some(h),
551 at: Some(obs.at.clone()),
552 },
553 crate::preparation::PathPrepared::NoHash => Observed {
554 state: crate::anchor::resolve_anchor(
555 anchor,
556 &crate::anchor::ArtifactObservation::Present {
557 current_hash: Some(hash.clone()),
558 },
559 ),
560 hash: Some(hash.clone()),
561 at: Some(obs.at.clone()),
562 },
563 }
564 }
565 });
566 }
567 return anchor.last_observed.as_ref().map(|rec| Observed {
568 state: rec.state,
569 hash: rec.hash.clone(),
570 at: Some(rec.at.clone()),
571 });
572 }
573 let join = anchor
574 .source
575 .as_deref()
576 .and_then(|name| source_roots.get(name));
577 // An `entity`-grain anchor points into a mem's graph, not a file
578 // tree. It has always returned `None` here — "unobserved this pass" —
579 // which meant it could never be drifted, never be orphaned, and always
580 // blocked prune. That is the bail the S1b pilot demonstrated: a
581 // deliberately stale anchor over a changed source entity went unflagged
582 // while the capability matrix claimed full parity.
583 if anchor.grain == crate::anchor::AnchorGrain::Entity {
584 return self
585 .observe_entity_anchor(anchor, join.and_then(|j| j.preparation.as_deref()))
586 .map(Observed::live);
587 }
588 let root = self.workspace_root.as_deref()?;
589 observe_path_anchor(root, anchor, join).map(Observed::live)
590 }
591
592 /// Observe an `entity`-grain anchor against the live graph — the entity-
593 /// namespace counterpart of [`observe_path_anchor`], and the mechanism
594 /// that makes a graph-medium binding's drift real.
595 ///
596 /// The artifact is an entity id. Present/absent comes from the store, so
597 /// this works uniformly across backends — a git-branch mem has no
598 /// working-tree file to stat, which is exactly why observation cannot go
599 /// through the filesystem here. The compared form is the preparation
600 /// registry's **prepared form** for `preparation` (the anchor's source's
601 /// declared preparation, [`crate::preparation::entity_prepared_hash`]):
602 /// the **canonical rendered markdown** when the source declares none —
603 /// byte-for-byte today's form — or the load-bearing serialization under
604 /// `entity-load-bearing`; hashed with the same `prepared_content_hash`
605 /// the path arm uses, so an anchor's recorded hash means the same thing
606 /// in both namespaces. An identifier the registry does not know cannot
607 /// be prepared: the anchor is reported unobserved (`None`), never hashed
608 /// under a fabricated form.
609 ///
610 /// A stub is treated as absent: a stub is the engine's placeholder for an
611 /// unresolved reference, not the entity the anchor claims to pin. Scoring
612 /// it as present would let a dangling anchor resolve clean.
613 fn observe_entity_anchor(
614 &self,
615 anchor: &crate::anchor::Anchor,
616 preparation: Option<&str>,
617 ) -> Option<(crate::anchor::AnchorState, Option<String>)> {
618 // A `#<locator>` on an entity artifact is the preparation's business
619 // (`quoted-phrase`: the phrase the entity must still carry); the id
620 // is what stands before it.
621 let (id_part, locator) = crate::preparation::split_unit_id(&anchor.artifact);
622 let id = EntityId::canonical(id_part);
623
624 // The mem the anchor points into must be MOUNTED before a store miss
625 // can mean anything. If it is not, every entity in it is missing from
626 // the store, and reporting `Orphaned` would say "the source deleted
627 // these" about entities sitting untouched on disk. `None` — genuinely
628 // unobserved — is the honest answer.
629 //
630 // This guard lives here, at the one observation site, and not at the
631 // callers. An earlier fix put it in `run_verify` alone; `prune` reaches
632 // anchor resolution by its own path (`mem_anchors_resolved`), so the
633 // sync brief went on proposing the deletion of every destination
634 // entity — a data-loss suggestion routed to the graph's only
635 // maintenance writer, from a mem merely being unmounted. A guard that
636 // protects one caller is not a guard on the behaviour.
637 if !self.mounts.iter().any(|m| m.mount.mem == id.mem()) {
638 return None;
639 }
640
641 let entity = self.store.get(&id).filter(|e| !e.stub);
642 let Some(entity) = entity else {
643 return Some((
644 crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
645 None,
646 ));
647 };
648 let current_hash = if anchor.class.is_hash_bearing() {
649 let type_def = self
650 .schema_for(id.mem())
651 .and_then(|schema| schema.get_type(&entity.entity_type));
652 match crate::preparation::entity_prepared(
653 entity,
654 type_def.as_deref(),
655 preparation,
656 locator,
657 ) {
658 crate::preparation::PathPrepared::Hash(h) => Some(h),
659 // The entity stands but no longer carries the addressed
660 // unit (a `quoted-phrase` the markdown lost): an absent
661 // artifact, adjudicated like a file's vanished unit.
662 crate::preparation::PathPrepared::UnitAbsent => {
663 return Some((
664 crate::anchor::resolve_anchor(
665 anchor,
666 &crate::anchor::ArtifactObservation::Absent,
667 ),
668 None,
669 ));
670 }
671 crate::preparation::PathPrepared::NoHash => return None,
672 }
673 } else {
674 None
675 };
676 let observation = crate::anchor::ArtifactObservation::Present {
677 current_hash: current_hash.clone(),
678 };
679 Some((
680 crate::anchor::resolve_anchor(anchor, &observation),
681 current_hash,
682 ))
683 }
684
685 /// The `source name → join` map for `mem`'s bindings: the filesystem
686 /// roots that anchors written in the source dialect join onto (decision
687 /// 26: anchor artifact paths are source-relative first) and the
688 /// preparation each source declares (touchpoint A: what the registry
689 /// prepares the artifact as before hashing). Empty when the workspace
690 /// has no root, the pipeline store does not load, or `mem` has no
691 /// bindings — resolution then degrades to the workspace-relative dialect
692 /// alone with no preparation, which is exactly the hand-authored-mem
693 /// posture.
694 pub(crate) fn anchor_source_roots(
695 &self,
696 mem: &str,
697 ) -> std::collections::BTreeMap<String, AnchorSourceJoin> {
698 let mut roots = std::collections::BTreeMap::new();
699 let Some(root) = self.workspace_root.as_deref() else {
700 return roots;
701 };
702 let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root) else {
703 return roots;
704 };
705 for record in configs.bindings.iter().filter(|r| r.mem == mem) {
706 for source in &record.config.sources {
707 roots
708 .entry(source.name.clone())
709 .or_insert_with(|| AnchorSourceJoin {
710 pointer: source.pointer.clone(),
711 preparation: source.preparation.clone(),
712 source: source.clone(),
713 deny_paths: record.config.deny_paths.clone(),
714 });
715 }
716 }
717 roots
718 }
719
720 /// Reverse anchor lookup: every `(entity_id, anchor)` across all mems
721 /// whose anchor references `artifact_path`. This is the query the
722 /// rebuilt check-realization hook consumes — given the file an agent
723 /// just edited, which entities anchored to it. A `span`/`file`/`tree`
724 /// anchor references the path when its base path (locator suffix
725 /// `@commit` / `#span` stripped) equals the path, or — for a `tree`
726 /// grain — when the path lies under the tree. Path-shaped grains only;
727 /// `url` / `entity` anchors are matched by exact base equality.
728 pub fn anchors_referencing_artifact(
729 &self,
730 artifact_path: &str,
731 ) -> Vec<(EntityId, crate::anchor::Anchor)> {
732 let mut out = Vec::new();
733 for mount in &self.mounts {
734 let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
735 continue;
736 };
737 let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
738 continue;
739 };
740 // Source-dialect anchors (decision 26) reference the same
741 // artifact under its pointer-joined workspace form — match both.
742 let source_roots = self.anchor_source_roots(&mount.mount.mem);
743 for (eid, anchors) in &sc.entities {
744 for a in anchors {
745 // The shared decision-29 candidate rule: the join
746 // candidate exists only where the rule produces one (a
747 // climbing `../…` artifact never joins); the
748 // workspace-relative form is the `anchor_references_path`
749 // arm below.
750 let joined = a
751 .source
752 .as_deref()
753 .and_then(|name| source_roots.get(name))
754 .map(|join| {
755 artifact_candidates(&join.pointer, anchor_base_path(&a.artifact))
756 })
757 .and_then(|mut c| (c.len() > 1).then(|| c.remove(0)));
758 if anchor_references_path(a, artifact_path)
759 || joined.is_some_and(|j| {
760 path_references(
761 &j,
762 a.grain == crate::anchor::AnchorGrain::Tree,
763 artifact_path,
764 )
765 })
766 {
767 out.push((EntityId(eid.clone()), a.clone()));
768 }
769 }
770 }
771 }
772 out
773 }
774
775 /// Every `(entity_id, resolved anchor)` in `mem`, read from its anchors
776 /// sidecar once and each paired with its **live** resolution state (the
777 /// same observation [`Self::entity_anchors_resolved`] produces per entity,
778 /// computed here mem-wide in a single sidecar read). Empty for an unknown
779 /// mem, a backend that persists no anchors, or a mem with none.
780 ///
781 /// Additive read surface: the durable data is unchanged; `state` is the
782 /// [`crate::anchor::resolve_anchor`] outcome against an observation the
783 /// engine produces — the working tree for a `path`-namespace anchor, the
784 /// live graph for an `entity` one — or `None` when unobserved (never
785 /// fabricated). The verify pipeline consumes it to adjudicate a mem's
786 /// anchors against the source; audit/health can reuse it.
787 /// Whether `mem`'s anchor sidecar records ANY anchor row — the cheap
788 /// existence check [`Self::mem_anchors_resolved`] cannot serve: that
789 /// walk OBSERVES every anchor (hashing live source artifacts, and for
790 /// path anchors enumerating the facet's file scope) when a caller only
791 /// needs to know the sidecar is non-empty. Parses the sidecar and stops
792 /// there; false for an unknown mem, a backend without anchors, or an
793 /// empty sidecar — the same population `mem_anchors_resolved` would
794 /// report empty for, minus the observation cost.
795 pub fn mem_has_anchors(&self, mem: &str) -> bool {
796 let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
797 return false;
798 };
799 let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
800 return false;
801 };
802 let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
803 return false;
804 };
805 sc.entities.values().any(|anchors| !anchors.is_empty())
806 }
807
808 pub fn mem_anchors_resolved(&self, mem: &str) -> Vec<(EntityId, ResolvedAnchor)> {
809 self.mem_anchors_resolved_with(mem, &SuppliedObservations::new())
810 }
811
812 /// [`Self::mem_anchors_resolved`] with observer-supplied observations
813 /// for the grains the engine cannot observe itself (`url`), keyed by
814 /// artifact. Rows without a supplied observation resolve as they would
815 /// without the map.
816 pub fn mem_anchors_resolved_with(
817 &self,
818 mem: &str,
819 supplied: &SuppliedObservations,
820 ) -> Vec<(EntityId, ResolvedAnchor)> {
821 let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
822 return Vec::new();
823 };
824 let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
825 return Vec::new();
826 };
827 let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
828 return Vec::new();
829 };
830 let mut out = Vec::new();
831 let source_roots = self.anchor_source_roots(mem);
832 for (eid, anchors) in &sc.entities {
833 for anchor in anchors {
834 out.push((
835 EntityId(eid.clone()),
836 self.resolve_one(anchor.clone(), &source_roots, supplied),
837 ));
838 }
839 }
840 out
841 }
842
843 /// Standalone anchor verification — "do my sources still say what I
844 /// recorded?" for one mem, regardless of how it was built. Walks the
845 /// mem's anchor sidecar through the shared per-anchor mechanism
846 /// ([`Self::observe_anchor`] via [`Self::mem_anchors_resolved`]) and
847 /// classifies every anchor into the report vocabulary: `resolved`
848 /// (source present, hash matches or non-hash class), `drifted`
849 /// (present, hash differs, stability `stable`), `recheck` (hash
850 /// differs under `unstable`, or a hash is missing on either side),
851 /// `unresolvable` (source absent, or a grain/medium the mechanism
852 /// does not reach — never fabricated into drift). Read-only on mem
853 /// content: pure sidecar read + filesystem observation, no commit on
854 /// any backend. A mem with no anchors returns an empty report.
855 pub fn verify_mem_anchors(&self, mem: &str) -> Result<MemAnchorVerification, EngineError> {
856 self.verify_mem_anchors_with(mem, &SuppliedObservations::new())
857 }
858
859 /// The stale axis defers to anchor state: an entity carrying at least
860 /// one adjudicated hash-bearing anchor (`resolves`, `drifted` or
861 /// `recheck`) reads by its anchors, not by the day threshold. `drifted`
862 /// and `recheck` list the entity as their own condition whatever its
863 /// age; `resolves` keeps it off the list, and when the threshold would
864 /// have listed it the row moves to `anchor_fresh` so the reading names
865 /// the clock that overruled the threshold. Entities with no adjudicated
866 /// anchor (none at all, or only `unresolvable` / `unobserved` rows)
867 /// keep the day-threshold reading, byte for byte. Derived at read time
868 /// from the same verification the anchors axis runs; nothing stored.
869 fn apply_anchor_clock(&self, summary: &mut crate::ops::HealthSummary, mem: Option<&str>) {
870 use std::collections::HashMap;
871 // Dominant adjudicated state per entity: drifted > recheck > resolves.
872 fn rank(state: &str) -> Option<u8> {
873 match state {
874 "drifted" => Some(3),
875 "recheck" => Some(2),
876 "resolves" => Some(1),
877 _ => None,
878 }
879 }
880 let mut by_entity: HashMap<String, (u8, String)> = HashMap::new();
881 let mut mems: Vec<String> = self.mem_names().iter().map(|s| s.to_string()).collect();
882 mems.retain(|m| mem.is_none_or(|scope| scope == m));
883 for m in mems {
884 let Ok(report) = self.verify_mem_anchors(&m) else {
885 continue;
886 };
887 for row in &report.anchors {
888 let Some(r) = rank(&row.state) else { continue };
889 let entry = by_entity
890 .entry(row.entity_id.clone())
891 .or_insert((0, String::new()));
892 if r > entry.0 {
893 *entry = (r, row.state.clone());
894 }
895 }
896 }
897 if by_entity.is_empty() {
898 return;
899 }
900 let today = crate::ops::health::days_since_epoch();
901 let mut stale = std::mem::take(&mut summary.stale_entities);
902 // Day-threshold rows on anchored entities leave the list: a
903 // resolving anchor makes them fresh, a drifted or recheck one is
904 // re-listed below under its own condition.
905 let mut fresh = Vec::new();
906 stale.retain(|row| match by_entity.get(row.id.0.as_str()) {
907 None => true,
908 Some((_, state)) => {
909 if state == "resolves" {
910 fresh.push(crate::ops::StaleEntity {
911 id: row.id.clone(),
912 title: row.title.clone(),
913 days_since_modified: row.days_since_modified,
914 anchor_state: Some(state.clone()),
915 });
916 }
917 false
918 }
919 });
920 let mut by_anchor: Vec<crate::ops::StaleEntity> = by_entity
921 .iter()
922 .filter(|(_, (_, state))| state != "resolves")
923 .filter_map(|(id, (_, state))| {
924 let entity = self.store.get(&crate::EntityId(id.clone()))?;
925 if entity.stub || mem.is_some_and(|scope| entity.mem != scope) {
926 return None;
927 }
928 let days = entity
929 .metadata
930 .get("last_modified")
931 .and_then(|v| crate::ops::health::parse_iso_to_days(&v.to_frontmatter_string()))
932 .map(|d| today.saturating_sub(d))
933 .unwrap_or(0);
934 Some(crate::ops::StaleEntity {
935 id: entity.id.clone(),
936 title: entity.title.clone(),
937 days_since_modified: days,
938 anchor_state: Some(state.clone()),
939 })
940 })
941 .collect();
942 stale.append(&mut by_anchor);
943 stale.sort_by(|a, b| a.id.0.cmp(&b.id.0));
944 fresh.sort_by(|a, b| a.id.0.cmp(&b.id.0));
945 summary.stale_entities = stale;
946 summary.anchor_fresh = fresh;
947 }
948
949 /// [`Self::verify_mem_anchors`] with observer-supplied observations
950 /// (the `--observations` file of `memstead verify-anchors`). A `url`
951 /// row whose artifact has a supplied observation adjudicates through
952 /// the shared funnel exactly like a file row; a supplied row matching
953 /// no `url` anchor of the mem is reported in `unmatched_observations`
954 /// and changes nothing. The report's `recordable_observations` are the
955 /// `last_observed` records the caller commits with
956 /// [`Self::record_anchor_observations`] — the verification itself
957 /// writes nothing.
958 pub fn verify_mem_anchors_with(
959 &self,
960 mem: &str,
961 supplied: &SuppliedObservations,
962 ) -> Result<MemAnchorVerification, EngineError> {
963 if !self.mem_router.is_visible(mem) {
964 return Err(self.unknown_mem_error(mem));
965 }
966 let now = self.now_iso();
967 // An unreadable sidecar is a condition, never zero rows: the readers
968 // below would degrade it to "no anchors" and the report would then
969 // describe a clean mem it never measured.
970 if let Some(why) = self.anchors_sidecar_error(mem) {
971 let mut report = MemAnchorVerification {
972 mem: mem.to_string(),
973 sidecar_error: Some(why),
974 ..Default::default()
975 };
976 report.figure = report.figure_over(0);
977 return Ok(report);
978 }
979 let mut report = MemAnchorVerification {
980 mem: mem.to_string(),
981 unreconciled: self
982 .entity_set_is_reconcilable(mem)
983 .err()
984 .map(str::to_string),
985 ..Default::default()
986 };
987 let reconciled = report.unreconciled.is_none();
988 let mut resolves = 0usize;
989 let mut matched: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
990 for (eid, resolved) in self.mem_anchors_resolved_with(mem, supplied) {
991 let is_url = resolved.anchor.grain == crate::anchor::AnchorGrain::Url;
992 let supplied_here = is_url && supplied.contains_key(&resolved.anchor.artifact);
993 if supplied_here {
994 matched.insert(resolved.anchor.artifact.clone());
995 }
996 let observed_at = resolved.observed_at.clone();
997 let unobserved_for_days = observed_at
998 .as_deref()
999 .and_then(|at| crate::anchor::days_between(at, &now));
1000 if let (true, Some(state), Some(at)) = (supplied_here, resolved.state, &observed_at) {
1001 report.recordable_observations.push(RecordedObservation {
1002 entity: eid.to_string(),
1003 artifact: resolved.anchor.artifact.clone(),
1004 observation: crate::anchor::AnchorObservation {
1005 at: at.clone(),
1006 hash: resolved.observed_hash.clone(),
1007 state,
1008 },
1009 });
1010 }
1011 // The entity end first: a row whose holder is gone is adjudicated
1012 // against its artifact alone otherwise, and a matching hash then
1013 // reports it as `resolved` for an entity that does not exist.
1014 if reconciled && self.entity_is_absent(&eid) {
1015 report.dangling += 1;
1016 report.anchors.push(VerifiedAnchor {
1017 entity_id: eid.to_string(),
1018 artifact: resolved.anchor.artifact.clone(),
1019 grain: resolved.anchor.grain.as_wire().to_string(),
1020 class: resolved.anchor.class.as_wire().to_string(),
1021 state: "dangling".to_string(),
1022 observed_hash: resolved.observed_hash,
1023 observed_at,
1024 unobserved_for_days,
1025 observation_supplied: supplied_here,
1026 });
1027 continue;
1028 }
1029 let state = match resolved.state {
1030 Some(crate::anchor::AnchorState::Resolves) => {
1031 resolves += 1;
1032 crate::anchor::AnchorState::Resolves.as_wire()
1033 }
1034 Some(crate::anchor::AnchorState::Drifted) => {
1035 report.drifted += 1;
1036 crate::anchor::AnchorState::Drifted.as_wire()
1037 }
1038 Some(crate::anchor::AnchorState::Recheck) => {
1039 report.recheck += 1;
1040 crate::anchor::AnchorState::Recheck.as_wire()
1041 }
1042 // The row spells the enum's wire name (`orphaned`); the
1043 // summary count beside it keeps its surface name,
1044 // `unresolvable` (the artifact is gone: a measured failure).
1045 Some(crate::anchor::AnchorState::Orphaned) => {
1046 report.unresolvable += 1;
1047 crate::anchor::AnchorState::Orphaned.as_wire()
1048 }
1049 // Split from `unresolvable`: the artifact
1050 // being GONE is a measurement; the pass not reaching the
1051 // artifact at all is the absence of one, and the repairs
1052 // differ.
1053 None => {
1054 report.unobserved += 1;
1055 "unobserved"
1056 }
1057 };
1058 report.anchors.push(VerifiedAnchor {
1059 entity_id: eid.to_string(),
1060 artifact: resolved.anchor.artifact.clone(),
1061 grain: resolved.anchor.grain.as_wire().to_string(),
1062 class: resolved.anchor.class.as_wire().to_string(),
1063 state: state.to_string(),
1064 observed_hash: resolved.observed_hash,
1065 observed_at,
1066 unobserved_for_days,
1067 observation_supplied: supplied_here,
1068 });
1069 }
1070 report.unmatched_observations = supplied
1071 .keys()
1072 .filter(|artifact| !matched.contains(*artifact))
1073 .cloned()
1074 .collect();
1075 report.figure = report.figure_over(resolves);
1076 Ok(report)
1077 }
1078
1079 /// Mem names the engine knows about, in declaration order.
1080 /// Cheap; useful for callers that need to enumerate before
1081 /// dispatching by mem.
1082 pub fn mem_names(&self) -> Vec<&str> {
1083 self.mounts.iter().map(|m| m.mount.mem.as_str()).collect()
1084 }
1085
1086 /// Derivation-staleness report for one mem:
1087 /// every EXPLICIT edge whose rel-type the mem's schema declares
1088 /// `derivation: true`, compared against its recorded baseline.
1089 /// Baseline differs from the target's current hash → `stale`;
1090 /// no baseline recorded (edge predates the declaration, or was
1091 /// load-derived) → `unbaselined`, distinctly — never fabricated
1092 /// as fresh or stale. Fresh edges are not reported. A mem whose
1093 /// schema declares no derivation rel-types returns the empty
1094 /// report; an unreadable sidecar reads as empty (every edge
1095 /// unbaselined) rather than an error.
1096 pub fn derivation_report(
1097 &self,
1098 mem: &str,
1099 ) -> Result<Vec<crate::ops::health::DerivationFinding>, EngineError> {
1100 if !self.mem_router.is_visible(mem) {
1101 return Err(self.unknown_mem_error(mem));
1102 }
1103 let Some(schema) = self.schemas.get(mem) else {
1104 return Ok(Vec::new());
1105 };
1106 let declared: std::collections::HashSet<&str> = schema
1107 .manifest
1108 .relationships
1109 .definitions
1110 .iter()
1111 .filter(|d| d.derivation)
1112 .map(|d| d.name.as_str())
1113 .collect();
1114 if declared.is_empty() {
1115 return Ok(Vec::new());
1116 }
1117 let sidecar = self
1118 .mounts
1119 .iter()
1120 .find(|m| m.mount.mem == mem)
1121 .and_then(|m| {
1122 m.backend
1123 .read_entity(Path::new(crate::derivation::DERIVATION_SIDECAR_PATH))
1124 .ok()
1125 .flatten()
1126 })
1127 .and_then(|bytes| crate::derivation::DerivationSidecar::from_bytes(&bytes).ok())
1128 .unwrap_or_default();
1129
1130 let mut out = Vec::new();
1131 let mut sources: Vec<&crate::entity::Entity> = self
1132 .store
1133 .all_entities()
1134 .filter(|e| !e.stub && e.id.mem() == mem)
1135 .collect();
1136 sources.sort_by(|a, b| a.id.as_ref().cmp(b.id.as_ref()));
1137 for entity in sources {
1138 for edge in self.store.outgoing(&entity.id) {
1139 if !declared.contains(edge.rel_type.as_str())
1140 || edge.source != crate::store::EdgeSource::Explicit
1141 {
1142 continue;
1143 }
1144 let current = self
1145 .store
1146 .get(&edge.target)
1147 .map(|t| t.content_hash.clone())
1148 .unwrap_or_default();
1149 match sidecar.get(entity.id.as_ref(), &edge.rel_type, edge.target.as_ref()) {
1150 None => out.push(crate::ops::health::DerivationFinding {
1151 source: entity.id.clone(),
1152 rel_type: edge.rel_type.clone(),
1153 target: edge.target.clone(),
1154 state: "unbaselined".to_string(),
1155 baseline: None,
1156 current,
1157 }),
1158 Some(baseline) if baseline != current => {
1159 out.push(crate::ops::health::DerivationFinding {
1160 source: entity.id.clone(),
1161 rel_type: edge.rel_type.clone(),
1162 target: edge.target.clone(),
1163 state: "stale".to_string(),
1164 baseline: Some(baseline.to_string()),
1165 current,
1166 })
1167 }
1168 Some(_) => {}
1169 }
1170 }
1171 }
1172 Ok(out)
1173 }
1174
1175 /// Public-shape mount record for `mem`, or `None` for an unknown
1176 /// mem.
1177 ///
1178 /// Surfaces the operator-facing
1179 /// [`crate::workspace::Mount`] (mem name, schema pin, storage
1180 /// reference, capability, lifecycle, cross_linkable) so MCP / CLI
1181 /// handlers can branch on backend-specific shapes via
1182 /// [`crate::workspace::MountStorage`] when they need accessors
1183 /// that don't make sense on every backend (e.g. gitdir / branch
1184 /// for `memstead_health { include_config: true }`'s git-class
1185 /// payload). Backends that want the equivalent of full's
1186 /// `engine.gitdir_for(mem)` match
1187 /// `engine.mount(mem).map(|m| &m.storage)` against
1188 /// `MountStorage::GitBranch { gitdir, branch }` and walk
1189 /// directly — keeps the engine surface backend-neutral.
1190 ///
1191 /// Counterpart to [`Self::mem_names`] which lists every mount.
1192 pub fn mount(&self, mem: &str) -> Option<&crate::workspace::Mount> {
1193 self.mounts
1194 .iter()
1195 .find(|m| m.mount.mem == mem)
1196 .map(|m| &m.mount)
1197 }
1198
1199 /// Orphan count attributed to each mem's pinned schema, over the
1200 /// given `orphan_ids` (the caller pre-filters them by any mem scope).
1201 /// Lets a health surface show that ingest-mem isolates (orphans by
1202 /// design) and code-mem debt land in different schema buckets rather
1203 /// than one blended, misleading total. Mems with no settled pin
1204 /// bucket under the empty string.
1205 pub fn orphans_by_schema(
1206 &self,
1207 orphan_ids: &[EntityId],
1208 ) -> std::collections::BTreeMap<String, usize> {
1209 let mut by_schema = std::collections::BTreeMap::new();
1210 for id in orphan_ids {
1211 let schema = self
1212 .store()
1213 .get(id)
1214 .and_then(|e| self.mount(&e.mem))
1215 .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
1216 .unwrap_or_default();
1217 *by_schema.entry(schema).or_insert(0) += 1;
1218 }
1219 by_schema
1220 }
1221
1222 /// Community count attributed to each schema across `mems`: a cluster
1223 /// counts toward every schema whose mems it touches, so these figures
1224 /// can sum above the global community count — the same "touches"
1225 /// semantic as the mem-scoped count. Per-schema dedup keeps a cluster
1226 /// touching two mems of one schema from being counted twice.
1227 pub fn communities_by_schema(
1228 &self,
1229 mems: &[String],
1230 ) -> std::collections::BTreeMap<String, usize> {
1231 let louvain = self.communities();
1232 let mut buckets: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
1233 std::collections::BTreeMap::new();
1234 for name in mems {
1235 let schema = self
1236 .mount(name)
1237 .and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
1238 .unwrap_or_default();
1239 let clusters = crate::graph::community::clusters_in_mem(self.store(), louvain, name);
1240 buckets.entry(schema).or_default().extend(clusters);
1241 }
1242 buckets
1243 .into_iter()
1244 .map(|(schema, set)| (schema, set.len()))
1245 .collect()
1246 }
1247
1248 /// All mounts the engine knows about, in declaration order.
1249 /// Counterpart to [`Self::mem_names`] when the caller needs
1250 /// the full mount shape (e.g. to enumerate by storage variant).
1251 pub fn mounts(&self) -> Vec<&crate::workspace::Mount> {
1252 self.mounts.iter().map(|m| &m.mount).collect()
1253 }
1254
1255 /// Names of mems whose mount declares
1256 /// [`crate::workspace::MountCapability::Write`], in declaration
1257 /// order. Convenience over `mounts().iter().filter(...).map(...)`
1258 /// for handlers that gate by writable status (`memstead_health`,
1259 /// `memstead_overview`'s mem roster, the lifecycle tools'
1260 /// candidate list). Read-only mounts (archive backends) are
1261 /// excluded.
1262 pub fn writable_mem_names(&self) -> Vec<&str> {
1263 self.mounts
1264 .iter()
1265 .filter(|m| m.mount.capability == MountCapability::Write)
1266 .map(|m| m.mount.mem.as_str())
1267 .collect()
1268 }
1269
1270 /// The default writable mem — the target a mutation lands in when
1271 /// it omits `mem`. `None` when no writable mem is mounted.
1272 ///
1273 /// Defined as the **first writable mount in declaration order**, i.e.
1274 /// the seed / earliest-created writable mem. This is a *stable*
1275 /// designation, not a function of the current name set: new mems
1276 /// register via `register_writable_mem`, which pushes onto the end
1277 /// of the mount list (and `mounts.json` preserves that order across
1278 /// reboots), so creating an additional mem never moves the default
1279 /// — even one whose name sorts ahead alphabetically. Deleting the
1280 /// current default promotes the next-earliest writable mem; that is
1281 /// the only thing that shifts it. Both the MCP `resolve_mem` and the
1282 /// CLI's omitted-`--mem` path resolve through here so the two
1283 /// surfaces always agree (the
1284 /// pre-fix MCP path read `writable_mems().iter().next()` off an
1285 /// unordered `HashSet`, which silently retargeted writes when a second
1286 /// mem appeared).
1287 pub fn default_writable_mem(&self) -> Option<&str> {
1288 self.mounts
1289 .iter()
1290 .find(|m| m.mount.capability == MountCapability::Write)
1291 .map(|m| m.mount.mem.as_str())
1292 }
1293
1294 /// On-disk folder path for a folder-backed mount, or `None` for
1295 /// any other backend (git-branch, archive) or unknown mem.
1296 /// Convenience over `engine.mount(mem).map(|m| &m.storage)` +
1297 /// matching on `MountStorage::Folder { path }`. Used by
1298 /// handlers that need a filesystem path for a folder mem
1299 /// (e.g. `memstead_health { include_config: true }`'s
1300 /// `mems[].vcs.worktree` field for folder mounts).
1301 pub fn folder_path_for_mem(&self, mem: &str) -> Option<&Path> {
1302 match self.mount(mem).map(|m| &m.storage) {
1303 Some(crate::workspace::MountStorage::Folder { path }) => Some(path.as_path()),
1304 _ => None,
1305 }
1306 }
1307
1308 /// Runtime snapshot of writable / visible mems. Handlers that
1309 /// need the writable roster (`memstead_health`'s `writable_mems` /
1310 /// `read_mems`), per-mem origin tag (`include_config:
1311 /// true`'s `mems[].origin`), or visibility check
1312 /// (`memstead_overview`'s mem list, the lifecycle tools' collision
1313 /// guard) consume the router here. Returned by reference — the
1314 /// `Arc` is held on the engine; callers that need a clonable
1315 /// handle can `Arc::clone` the engine's field directly when that
1316 /// surface arrives.
1317 pub fn mem_router(&self) -> &MemRouterSnapshot {
1318 &self.mem_router
1319 }
1320
1321 /// Resolve the gitdir for a writable mem. Used by `memstead_health
1322 /// { include_config: true }` to surface per-mem `vcs.gitdir`
1323 /// so outer-repo bookkeeping clients can `git -C <gitdir>` per
1324 /// mem without hardcoding the layout.
1325 ///
1326 /// - `EngineError::UnknownMem` when the name does not resolve.
1327 /// - `EngineError::Mem` when the mount's storage is not
1328 /// git-branch-backed (folder, archive — they have no gitdir).
1329 pub fn gitdir_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
1330 let m = self
1331 .mount(mem_name)
1332 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1333 match &m.storage {
1334 MountStorage::GitBranch { gitdir, .. } => Ok(gitdir.clone()),
1335 MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
1336 Err(EngineError::Mem(format!(
1337 "mem '{mem_name}' has no resolved gitdir"
1338 )))
1339 }
1340 }
1341 }
1342
1343 /// Resolve the worktree for a writable mem. Used by
1344 /// `memstead_health { include_config: true }` to surface per-mem
1345 /// `vcs.worktree`.
1346 ///
1347 /// - `EngineError::UnknownMem` when the name does not resolve.
1348 /// - `EngineError::Mem` when the mount's backend has no
1349 /// worktree concept (git-branch with no working tree, archive).
1350 ///
1351 /// Folder mounts surface their on-disk path. Git-branch mounts
1352 /// follow the `dir: Some(...)` composition pattern: when the
1353 /// workspace root contains a folder named after the mem with a
1354 /// `.memstead/config.json` marker, that folder is the worktree
1355 /// (disk-shape composition). Otherwise — pure mem-repo-backed
1356 /// — return Err.
1357 pub fn worktree_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
1358 let m = self
1359 .mount(mem_name)
1360 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1361 match &m.storage {
1362 MountStorage::Folder { path } => Ok(path.clone()),
1363 MountStorage::GitBranch { .. } => {
1364 if let Some(root) = self.workspace_root.as_deref() {
1365 let candidate = root.join(mem_name);
1366 if candidate
1367 .join(crate::mem::MEM_META_DIR)
1368 .join("config.json")
1369 .is_file()
1370 {
1371 return Ok(candidate.canonicalize().unwrap_or(candidate));
1372 }
1373 }
1374 Err(EngineError::Mem(format!(
1375 "mem '{mem_name}' has no working tree (mem-repo-backed)"
1376 )))
1377 }
1378 MountStorage::Archive { .. } => Err(EngineError::Mem(format!(
1379 "mem '{mem_name}' is archive-backed and has no worktree"
1380 ))),
1381 MountStorage::InMemory => Err(EngineError::Mem(format!(
1382 "mem '{mem_name}' is in-memory and has no worktree"
1383 ))),
1384 }
1385 }
1386
1387 /// Per-mem `.memstead/config.json` payload, when available. Used
1388 /// by `memstead_health { include_config: true }` to surface the
1389 /// opaque `write_guidance` map and the catch-all `extra` fields
1390 /// per mem.
1391 ///
1392 /// Folder-backed mounts return `Some(&MemConfig)` when
1393 /// `<path>/.memstead/config.json` parsed cleanly at construction.
1394 /// Git-branch and archive backends return `None` until the
1395 /// read-from-storage-backend path lifts (the V1 unified engine
1396 /// loads configs only from folder layouts; the file lives
1397 /// inside the gitdir / archive for the other backends and
1398 /// needs a backend-level read primitive).
1399 ///
1400 /// Unknown mem names return `None` (no error variant — the
1401 /// accessor is intentionally lenient because memstead_health emits
1402 /// an empty detail block per missing config rather than
1403 /// aborting the call).
1404 pub fn mem_config_for(&self, mem: &str) -> Option<&memstead_schema::config::MemConfig> {
1405 self.mounts
1406 .iter()
1407 .find(|m| m.mount.mem == mem)
1408 .and_then(|m| m.mem_config.as_ref())
1409 }
1410
1411 /// The authoring-provenance payload an installed mem carries, read
1412 /// from the archive's `.memstead/provenance.json` at construction.
1413 /// `None` when the mem carries none (a pre-provenance archive, a
1414 /// runtime-created mem, or a backend that does not surface one) —
1415 /// the read path reports provenance as absent. Unknown mem names
1416 /// return `None`.
1417 pub fn archive_provenance_for(&self, mem: &str) -> Option<&memstead_schema::ArchiveProvenance> {
1418 self.mounts
1419 .iter()
1420 .find(|m| m.mount.mem == mem)
1421 .and_then(|m| m.archive_provenance.as_ref())
1422 }
1423
1424 /// Iterate `(mem_name, &MemConfig)` for every mount whose
1425 /// mem-config payload loaded at construction. Used by callers
1426 /// that walk every writable mount's config (`memstead health`'s
1427 /// per-mem dump, the workspace-dump CLI). The yielded `&str` is
1428 /// the authoritative mem leaf from the mount record.
1429 ///
1430 /// Folder-backed mounts yield when their `.memstead/config.json`
1431 /// parsed cleanly. Git-branch and archive backends are silent in
1432 /// V1 (the same deferred-read-from-storage gap that
1433 /// [`Self::mem_config_for`] documents).
1434 pub fn mem_configs_named(
1435 &self,
1436 ) -> impl Iterator<Item = (&str, &memstead_schema::config::MemConfig)> {
1437 self.mounts
1438 .iter()
1439 .filter_map(|m| m.mem_config.as_ref().map(|c| (m.mount.mem.as_str(), c)))
1440 }
1441
1442 /// Every configured mount, with its config when one was readable.
1443 ///
1444 /// The counterpart to [`Self::mem_configs_named`], whose contract is "mems
1445 /// WITH config" and which is therefore right to omit the rest. The trouble
1446 /// was that callers wanting to enumerate mounts reached for it anyway: a
1447 /// folder mount whose directory is gone returns no config rather than an
1448 /// error, boot stores none, and the mount became invisible to every one of
1449 /// them. Nine call sites shared that blind spot, and the omission was a
1450 /// side effect of config readability rather than anything about the mount
1451 /// (04/05, criteria 1 and 8).
1452 ///
1453 /// Callers that genuinely want only configured mems keep using the other
1454 /// one; drivers that want every mount ask for every mount.
1455 pub fn mounts_with_optional_config(
1456 &self,
1457 ) -> impl Iterator<Item = (&str, Option<&memstead_schema::config::MemConfig>)> {
1458 self.mounts
1459 .iter()
1460 .map(|m| (m.mount.mem.as_str(), m.mem_config.as_ref()))
1461 }
1462
1463 /// Resolved `Arc<Schema>` for a writable mem by name. `None`
1464 /// when the name is not a registered mount.
1465 ///
1466 /// Cheap — `Arc::clone` over the per-mem schema map. Resolved
1467 /// schemas are stored in `HashMap<String, Arc<Schema>>` so the
1468 /// lookup is a single hash hit + clone.
1469 pub fn schema_for(&self, mem: &str) -> Option<std::sync::Arc<memstead_schema::Schema>> {
1470 self.schemas.get(mem).cloned()
1471 }
1472
1473 /// Cached current branch-tip cursor (typically a 40-char hex
1474 /// SHA for git-branch backends; `None` for fresh mems or
1475 /// backends that don't track a head — folder / archive).
1476 ///
1477 /// The value is the per-mount `last_known_head`, seeded at
1478 /// construction by `backend.current_head()` and refreshed by
1479 /// [`Self::reload_if_stale`] / mutation paths after a
1480 /// successful commit.
1481 ///
1482 /// - `EngineError::UnknownMem` when the name does not resolve.
1483 pub fn mem_head_sha(&self, mem_name: &str) -> Result<Option<String>, EngineError> {
1484 let m = self
1485 .mounts
1486 .iter()
1487 .find(|m| m.mount.mem == mem_name)
1488 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1489 Ok(m.last_known_head.clone())
1490 }
1491
1492 /// Whether a sibling writer has advanced this mem's backend past
1493 /// the engine's cached `last_known_head` — a read-only drift probe
1494 /// that does **not** reload (unlike [`Self::reload_if_stale`]). One
1495 /// `backend.current_head()` read compared against the cached cursor;
1496 /// the comparison clears once the engine re-reads (a `reload` /
1497 /// `reload_if_stale` refreshes `last_known_head` to the live tip).
1498 ///
1499 /// Only git-branch backends track a head, so folder / archive /
1500 /// in-memory mounts always report `false`. A backend that errors on
1501 /// the probe (transient refdb hiccup) reports `false` rather than
1502 /// surfacing the error — drift is advisory, and the next real
1503 /// operation's reload path is the authoritative sync.
1504 ///
1505 /// - `EngineError::UnknownMem` when the name does not resolve.
1506 pub fn mem_drifted(&self, mem_name: &str) -> Result<bool, EngineError> {
1507 let m = self
1508 .mounts
1509 .iter()
1510 .find(|m| m.mount.mem == mem_name)
1511 .ok_or_else(|| self.unknown_mem_error(mem_name))?;
1512 let live = m.backend.current_head().ok().flatten();
1513 Ok(live != m.last_known_head)
1514 }
1515
1516 /// Workspace root the engine booted from, when one is known.
1517 /// `None` for engines built directly from a mount list (tests,
1518 /// ad-hoc consumers). Set by [`Self::from_workspace_root`] and
1519 /// the full counterpart.
1520 pub fn workspace_root(&self) -> Option<&Path> {
1521 self.workspace_root.as_deref()
1522 }
1523
1524 /// Typed warnings surfaced during mem load — drift findings
1525 /// the loader pipeline collects per entity. Empty for V1; the
1526 /// accessor surfaces them so handlers can merge into health
1527 /// summaries uniformly.
1528 pub fn load_warnings(&self) -> &[WarningHint] {
1529 &self.load_warnings
1530 }
1531
1532 /// The quarantine roster: mems that failed their mem-level boot
1533 /// step and serve nothing until repaired + reloaded. Empty on a
1534 /// fully healthy workspace. Surfaced on overview and health.
1535 pub fn quarantined_mems(&self) -> &[crate::engine::QuarantinedMem] {
1536 &self.quarantined
1537 }
1538
1539 /// The quarantine entry for `mem`, when it is quarantined.
1540 pub fn quarantine_reason(&self, mem: &str) -> Option<&crate::engine::QuarantinedMem> {
1541 self.quarantined.iter().find(|q| q.mount.mem == mem)
1542 }
1543
1544 /// Whether the store's entity set for `mem` can be trusted to answer the
1545 /// question "does this entity still exist?".
1546 ///
1547 /// WHY this is a question and not an assumption: an anchor sidecar is
1548 /// keyed by entity id, and a key with no entity behind it is a dangling
1549 /// row (consistency-sweep 03/02). Detecting one means reading a NEGATIVE
1550 /// from the store, and a negative is only evidence when the store is known
1551 /// to hold everything the mem has. Four states break that, and each of
1552 /// them would otherwise turn every anchor in the mem into a false dangling
1553 /// report: the mem is not mounted at all, it is quarantined (serving
1554 /// nothing), its lazy load has not run yet (mounted, entities absent), or
1555 /// a file in it failed to parse, in which case an id missing from the
1556 /// store may be a load failure rather than a deleted entity.
1557 ///
1558 /// The last case is deliberately COARSE for non-folder mounts: load-error
1559 /// paths are normalized to absolute only for folder mounts, so a
1560 /// git-branch mem's errors carry mem-relative paths that two mems can
1561 /// spell identically. Attributing them by name would be a guess, and a
1562 /// wrong guess here fabricates dangling rows. Any load error at all
1563 /// therefore blocks reconciliation for a non-folder mem. The caller states
1564 /// the block rather than skipping silently, which is the honest direction.
1565 pub fn entity_set_is_reconcilable(&self, mem: &str) -> Result<(), &'static str> {
1566 if self.quarantine_reason(mem).is_some() {
1567 return Err("the mem is quarantined and serves no entities");
1568 }
1569 let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
1570 return Err("the mem is not mounted here");
1571 };
1572 if mount.deferred {
1573 return Err("the mem's lazy entity load has not run this session");
1574 }
1575 if self.load_errors.is_empty() {
1576 return Ok(());
1577 }
1578 match &mount.mount.storage {
1579 crate::workspace::MountStorage::Folder { path } => {
1580 if self.load_errors.iter().any(|(p, _)| p.starts_with(path)) {
1581 Err(
1582 "a file in this mem failed to parse, so an id missing from the store may be a load failure rather than a deleted entity",
1583 )
1584 } else {
1585 Ok(())
1586 }
1587 }
1588 _ => Err(
1589 "this workspace has files that failed to parse, and their paths cannot be attributed to one mem",
1590 ),
1591 }
1592 }
1593
1594 /// Whether `id` names an entity this mem no longer holds. A STUB counts
1595 /// as missing: a stub is the placeholder an unresolved wiki-link target
1596 /// leaves behind, not an entity anyone wrote, so an anchor keyed to one
1597 /// is dangling exactly as if nothing were there.
1598 ///
1599 /// Only meaningful once [`Self::entity_set_is_reconcilable`] says yes.
1600 pub fn entity_is_absent(&self, id: &EntityId) -> bool {
1601 self.store.get(id).is_none_or(|e| e.stub)
1602 }
1603
1604 /// Mems whose lazy entity load is still DEFERRED — on the mount
1605 /// roster with a resolved schema pin, but with no entities in the
1606 /// store yet. Read surfaces that render per-mem counts or
1607 /// distributions consult this: a count over a deferred mem's slice
1608 /// of the store is a count over nothing, and rendering it as a
1609 /// bare zero is the silent absence the lazy-mount contract forbids.
1610 /// Either trigger the load ([`Self::ensure_mems_loaded`]) or render
1611 /// the load state explicitly.
1612 pub fn deferred_mems(&self) -> Vec<&str> {
1613 self.mounts
1614 .iter()
1615 .filter(|m| m.deferred)
1616 .map(|m| m.mount.mem.as_str())
1617 .collect()
1618 }
1619
1620 /// Whether `mem` is a lazy mount whose entity load has not run yet.
1621 pub fn mem_is_deferred(&self, mem: &str) -> bool {
1622 self.mounts.iter().any(|m| m.deferred && m.mount.mem == mem)
1623 }
1624
1625 /// The typed error for a mem name that did not resolve to a
1626 /// serving mount: `MEM_QUARANTINED` (carrying the underlying boot
1627 /// failure and its repair command) when the mem is on the
1628 /// quarantine roster, `UNKNOWN_MEM` otherwise. Every lookup site
1629 /// that fails to find a mem routes here so a quarantined mem is
1630 /// never misreported as unknown — honest absence, with the reason.
1631 /// Resolve an entity id that may lack its mem prefix — the one
1632 /// rule every id-taking mutation verb applies before it reads the
1633 /// id's mem. A full id (`mem--slug`) returns unchanged with no
1634 /// hint, byte for byte the path it always took. A bare slug is
1635 /// looked up across every mounted mem (loading deferred mems
1636 /// first, so a lazily mounted carrier is not invisible): exactly
1637 /// one carrier resolves the id and returns the
1638 /// [`crate::ops::WarningHint::ShortIdResolved`] announcement the
1639 /// verb rides on its outcome; zero or several carriers refuse
1640 /// [`EngineError::EntityIdMissingMem`] naming every candidate.
1641 /// Before this rule a bare slug reached the verbs as an id whose
1642 /// mem was the empty string, and the caller was told a mem called
1643 /// "" did not exist (B7 grader finding, 2026-09-02).
1644 pub fn resolve_entity_id(
1645 &mut self,
1646 id: &EntityId,
1647 ) -> Result<(EntityId, Option<crate::ops::WarningHint>), EngineError> {
1648 if !id.mem().is_empty() {
1649 return Ok((id.clone(), None));
1650 }
1651 // Grammar before resolution: a malformed bare string is an
1652 // invalid id, not a slug nobody carries.
1653 let slug = id.0.as_str();
1654 if let Err(reason) = crate::entity::id::validate_id_path_grammar(slug) {
1655 return Err(EngineError::InvalidEntityId {
1656 id: id.0.clone(),
1657 reason,
1658 });
1659 }
1660 self.ensure_mems_loaded(None);
1661 let mut candidates: Vec<EntityId> = self
1662 .store
1663 .all_entities()
1664 .filter(|e| !e.stub && e.id.path() == slug)
1665 .map(|e| e.id.clone())
1666 .collect();
1667 candidates.sort_by(|a, b| a.0.cmp(&b.0));
1668 candidates.dedup();
1669 if candidates.len() == 1 {
1670 let resolved = candidates.remove(0);
1671 let hint = crate::ops::WarningHint::ShortIdResolved {
1672 given: id.0.clone(),
1673 resolved: resolved.clone(),
1674 };
1675 return Ok((resolved, Some(hint)));
1676 }
1677 Err(EngineError::EntityIdMissingMem {
1678 id: id.0.clone(),
1679 candidates: candidates.into_iter().map(|c| c.0).collect(),
1680 })
1681 }
1682
1683 pub fn unknown_mem_error(&self, mem: &str) -> EngineError {
1684 match self.quarantine_reason(mem) {
1685 Some(q) => EngineError::MemQuarantined {
1686 mem: mem.to_string(),
1687 reason_code: q.reason_code.clone(),
1688 reason_message: q.reason_message.clone(),
1689 },
1690 None if self.recently_unmounted(mem) => EngineError::MemUnmounted {
1691 mem: mem.to_string(),
1692 },
1693 None => EngineError::UnknownMem(mem.to_string()),
1694 }
1695 }
1696
1697 /// The workspace-level boot diagnosis a diagnostic-shell engine
1698 /// carries (`None` on ordinarily booted engines).
1699 pub fn boot_diagnosis(&self) -> Option<(&str, &str)> {
1700 self.boot_diagnosis
1701 .as_ref()
1702 .map(|(c, m)| (c.as_str(), m.as_str()))
1703 }
1704
1705 /// Build a mem-less diagnostic-shell engine for a workspace whose
1706 /// boot failed at the WORKSPACE level (nothing loadable — e.g. an
1707 /// unparseable store). It serves no mems and no entities; its one
1708 /// job is answering overview/health with the typed boot diagnosis
1709 /// so a session can always ask WHY the graph is gone — the MCP
1710 /// server serves this instead of exiting into `-32000 Connection
1711 /// closed` (degrade, never disappear).
1712 pub fn diagnostic_shell(reason_code: String, reason_message: String) -> Engine {
1713 let mut engine =
1714 Engine::from_mounts(Vec::new()).expect("an empty mount list always constructs");
1715 engine.boot_diagnosis = Some((reason_code, reason_message));
1716 engine
1717 }
1718
1719 /// Append boot-path quarantine entries recorded outside
1720 /// `from_mounts_inner` (backend-instantiation failures happen
1721 /// before the mount list reaches the engine constructor). Boot
1722 /// paths only — quarantine is a boot judgment, never a runtime
1723 /// mutation.
1724 pub fn extend_quarantine(&mut self, entries: Vec<crate::engine::QuarantinedMem>) {
1725 self.quarantined.extend(entries);
1726 }
1727
1728 // ---------------------------------------------------------------
1729 // Read-side delegates onto the kernel ops/graph functions.
1730 //
1731 // The mem-router engine exposed each of these directly so the
1732 // MCP layer could call them without reaching into the store. The
1733 // unified engine mirrors that surface so the MCP migration is a
1734 // straight rename rather than a re-architecture.
1735 //
1736 // Multi-mem cache strategy: per-mem community detection and
1737 // per-mem search indexes are unnecessary at this layer — the
1738 // engine-wide store already carries every mount's edges; Louvain
1739 // and tantivy run once across the union. `mem_schemas` for
1740 // health/search is the engine's existing `schemas` field as-is.
1741 // ---------------------------------------------------------------
1742
1743 /// Lazy community-detection cache. First call runs Louvain
1744 /// against the current store using one pinned schema for
1745 /// `community.{resolution, seed}` and the per-rel weights.
1746 /// Subsequent calls return the cached result. Mutations invalidate
1747 /// the cache via [`Self::invalidate_communities`].
1748 ///
1749 /// One detection run per engine. The partition is workspace-global,
1750 /// so it needs a single source for the Louvain parameters; that
1751 /// source is the schema of the lexicographically-first mem name —
1752 /// a stable key, so the partition is deterministic across processes
1753 /// even when mounts pin heterogeneous schemas. For a single-schema
1754 /// workspace every mem's schema is identical, so the choice of
1755 /// key is immaterial there.
1756 pub fn communities(&self) -> &LouvainOutput {
1757 // Generation sanity: a stored memo must match the live store
1758 // generation — the mutation hooks clear stale memos before any
1759 // read can arrive here. A mismatch would mean a mutation path
1760 // skipped its invalidation call (the exact silent-staleness
1761 // bug the generation exists to catch).
1762 if let Some((memo_key, _)) = self.community_memo.get() {
1763 debug_assert_eq!(
1764 *memo_key,
1765 self.derived_key(),
1766 "community memo key lags the engine — a mutation path missed invalidate_communities"
1767 );
1768 }
1769 &self
1770 .community_memo
1771 .get_or_init(|| (self.derived_key(), self.compute_communities()))
1772 .1
1773 }
1774
1775 /// The current validity key for derived-structure memos: store
1776 /// generation plus schemas epoch (see [`super::DerivedKey`]).
1777 pub fn derived_key(&self) -> super::DerivedKey {
1778 super::DerivedKey {
1779 store_generation: self.store.generation(),
1780 schemas_epoch: self.schemas_epoch,
1781 }
1782 }
1783
1784 fn compute_communities(&self) -> LouvainOutput {
1785 {
1786 // Select the parameter schema by a stable key (smallest
1787 // mem name) rather than unordered-map iteration, so the
1788 // partition does not vary between processes. Fall back to
1789 // the builtin default for the empty-mounts case (caller
1790 // still gets a valid empty Louvain result against an empty
1791 // store).
1792 let schema = self
1793 .schemas
1794 .iter()
1795 .min_by(|a, b| a.0.cmp(b.0))
1796 .map(|(_, s)| s.clone())
1797 .unwrap_or_else(Schema::builtin_default);
1798 let manifest = &schema.manifest;
1799 let resolution = manifest.community.resolution;
1800 let seed = manifest.community.seed;
1801 let schema_for_weights = schema.clone();
1802 detect_communities(&self.store, resolution, seed, move |rel_type| {
1803 schema_for_weights
1804 .manifest
1805 .relationships
1806 .definitions
1807 .iter()
1808 .find(|d| d.name == rel_type)
1809 .map(|d| d.default_weight as f64)
1810 .unwrap_or(1.0)
1811 })
1812 }
1813 }
1814
1815 /// Drop the cached community detection result and the grounded
1816 /// labelling memo — unless the store still sits at the generation
1817 /// each memo was computed from (flywheel W8/01). The keep case is
1818 /// exactly the batch-rollback path: the restored snapshot restored
1819 /// the generation with it, so the memo describes the live state
1820 /// and recomputing it would be pure waste. Every real mutation
1821 /// bumps the generation first, so those clears behave as before.
1822 /// Coupling the labelling reset here means every site that already
1823 /// invalidates communities (all mutation paths, drift reload,
1824 /// quarantine attach/detach, apply-commit) invalidates the
1825 /// labelling too, so a stale label can never outlive the state
1826 /// change that moved it.
1827 pub fn invalidate_communities(&mut self) {
1828 let key = self.derived_key();
1829 if !matches!(self.community_memo.get(), Some((k, _)) if *k == key) {
1830 self.community_memo = OnceCell::new();
1831 }
1832 if !matches!(self.labelling_memo.get(), Some((k, _)) if *k == key) {
1833 self.labelling_memo = OnceCell::new();
1834 }
1835 }
1836
1837 /// The grounded labelling of one mem — `None` when its pinned
1838 /// schema declares no `relationships.labelling`. Computed on
1839 /// first access for every declaring mem, memoised until the next
1840 /// invalidation; generation-keyed like `community_memo`.
1841 pub fn mem_labelling(&self, mem: &str) -> Option<&crate::ops::labelling::MemLabelling> {
1842 // Generation sanity, same contract as `communities()`: a
1843 // stored memo must match the live derived key — a mismatch
1844 // means a mutation path missed invalidate_communities.
1845 if let Some((memo_key, _)) = self.labelling_memo.get() {
1846 debug_assert_eq!(
1847 *memo_key,
1848 self.derived_key(),
1849 "labelling memo key lags the engine — a mutation path missed invalidate_communities"
1850 );
1851 }
1852 let (_, map) = self.labelling_memo.get_or_init(|| {
1853 let mut out = std::collections::HashMap::new();
1854 for (mem_name, schema) in &self.schemas {
1855 if let Some(lab) = crate::ops::labelling::labelling_of(schema) {
1856 out.insert(
1857 mem_name.clone(),
1858 crate::ops::labelling::compute_mem_labelling(
1859 &self.store,
1860 mem_name,
1861 &lab.attack,
1862 ),
1863 );
1864 }
1865 }
1866 (self.derived_key(), out)
1867 });
1868 map.get(mem)
1869 }
1870
1871 /// One entity's served labelling view — `None` when the entity is
1872 /// a stub or its mem's schema declares no labelling; serving
1873 /// surfaces then keep their byte-identical payloads. The shape
1874 /// block is present exactly when the declaration carries a
1875 /// `support` walk.
1876 pub fn computed_labelling(
1877 &self,
1878 entity: &Entity,
1879 ) -> Option<crate::ops::labelling::LabellingView> {
1880 use crate::ops::labelling::{Label, compute_shape, labelling_of};
1881 if entity.stub {
1882 return None;
1883 }
1884 let schema = self.schemas.get(entity.mem.as_str())?;
1885 let lab = labelling_of(schema)?;
1886 let mem_lab = self.mem_labelling(entity.mem.as_str())?;
1887 let label = *mem_lab.labels.get(entity.id.0.as_str())?;
1888 let defeated_by = if label == Label::Defeated {
1889 mem_lab.accepted_attackers_of(entity.id.0.as_str())
1890 } else {
1891 Vec::new()
1892 };
1893 let undecided_by = if label == Label::Undecided {
1894 mem_lab.undecided_attackers_of(entity.id.0.as_str())
1895 } else {
1896 Vec::new()
1897 };
1898 let shape = lab.support.as_ref().map(|walk| {
1899 let label_of = |id: &EntityId| -> Option<Label> {
1900 self.mem_labelling(id.mem())
1901 .and_then(|ml| ml.labels.get(id.0.as_str()).copied())
1902 };
1903 compute_shape(&self.store, &entity.id, walk, &label_of)
1904 });
1905 Some(crate::ops::labelling::LabellingView {
1906 label,
1907 defeated_by,
1908 undecided_by,
1909 shape,
1910 })
1911 }
1912
1913 /// The `labelling` health axis payload — per declaring mem:
1914 /// counts per label, the defeated list with its accepted
1915 /// attackers, the undecided list with its open attacker set, and
1916 /// the excluded cross-mem attack-edge count. One composer shared
1917 /// by the CLI health command and the MCP server.
1918 pub fn health_labelling_axis(&self, mem_filter: Option<&str>) -> serde_json::Value {
1919 use crate::ops::labelling::Label;
1920 let mut mems = serde_json::Map::new();
1921 let mut mem_names: Vec<&String> = self.schemas.keys().collect();
1922 mem_names.sort();
1923 for mem in mem_names {
1924 if let Some(v) = mem_filter
1925 && mem != v
1926 {
1927 continue;
1928 }
1929 let Some(ml) = self.mem_labelling(mem) else {
1930 continue;
1931 };
1932 let mut accepted = 0usize;
1933 let mut defeated: Vec<serde_json::Value> = Vec::new();
1934 let mut undecided: Vec<serde_json::Value> = Vec::new();
1935 for (id, label) in &ml.labels {
1936 match label {
1937 Label::Accepted => accepted += 1,
1938 Label::Defeated => defeated.push(serde_json::json!({
1939 "id": id,
1940 "defeated_by": ml.accepted_attackers_of(id),
1941 })),
1942 Label::Undecided => undecided.push(serde_json::json!({
1943 "id": id,
1944 "undecided_by": ml.undecided_attackers_of(id),
1945 })),
1946 }
1947 }
1948 mems.insert(
1949 mem.clone(),
1950 serde_json::json!({
1951 "counts": {
1952 "accepted": accepted,
1953 "defeated": defeated.len(),
1954 "undecided": undecided.len(),
1955 },
1956 "defeated": defeated,
1957 "undecided": undecided,
1958 "cross_mem_edges_excluded": ml.cross_mem_edges_excluded,
1959 }),
1960 );
1961 }
1962 serde_json::Value::Object(mems)
1963 }
1964
1965 /// Real entities with no incoming or outgoing edges — leaf-declared
1966 /// types exempt (their edge-less entities are terminal by
1967 /// construction; see [`Self::leaf_population`]).
1968 pub fn orphans(&self) -> Vec<EntityId> {
1969 crate::graph::query::find_orphans_with_schemas(&self.store, &self.schemas)
1970 }
1971
1972 /// Count of real entities per leaf-declared type, keyed
1973 /// `<schema_ref>:<type>` — the visible population the orphan
1974 /// exemption covers.
1975 pub fn leaf_population(&self) -> std::collections::BTreeMap<String, usize> {
1976 crate::graph::query::leaf_population(&self.store, &self.schemas)
1977 }
1978
1979 /// Stub entities with their referencer ids.
1980 pub fn stubs(&self) -> Vec<(EntityId, Vec<EntityId>)> {
1981 crate::graph::query::find_stubs(&self.store)
1982 }
1983
1984 /// Top `limit` entities by total degree.
1985 pub fn most_connected(&self, limit: usize) -> Vec<crate::graph::query::Connectivity> {
1986 crate::graph::query::most_connected(&self.store, limit)
1987 }
1988
1989 /// Entities whose type's `required_outgoing` blocks are not yet
1990 /// satisfied. `mem_filter = None` scans every mem; `Some(v)`
1991 /// scans only that mem.
1992 pub fn missing_required_outgoing(
1993 &self,
1994 mem_filter: Option<&str>,
1995 ) -> Vec<crate::ops::health::MissingRequiredOutgoingReport> {
1996 crate::ops::health::collect_missing_required_outgoing(
1997 &self.store,
1998 mem_filter,
1999 &self.schemas,
2000 )
2001 }
2002
2003 /// Standing violations of declared `constraints` (the health
2004 /// `constraints` include) — every non-stub entity whose type
2005 /// declares constraints its current state violates, in
2006 /// deterministic `(mem, id)` order.
2007 pub fn constraint_findings(
2008 &self,
2009 mem_filter: Option<&str>,
2010 ) -> Vec<crate::ops::health::ConstraintFindingReport> {
2011 let check_provider = self.check_standing_provider();
2012 crate::ops::health::collect_constraint_findings(
2013 &self.store,
2014 mem_filter,
2015 &self.schemas,
2016 Some(&check_provider),
2017 )
2018 }
2019
2020 /// The evaluated aggregate signals for one entity — `None` when
2021 /// the mem has no schema, the type is unknown or a stub, or the
2022 /// type declares no signals; serving surfaces then keep their
2023 /// byte-identical payloads.
2024 pub fn computed_signals(
2025 &self,
2026 entity: &Entity,
2027 ) -> Option<Vec<crate::ops::signals::ComputedSignal>> {
2028 if entity.stub {
2029 return None;
2030 }
2031 let schema = self.schemas.get(entity.mem.as_str())?;
2032 let td = schema.types.get(entity.entity_type.as_str())?;
2033 if td.signals.is_empty() {
2034 return None;
2035 }
2036 Some(crate::ops::signals::compute_signals(
2037 &self.store,
2038 td,
2039 &entity.id,
2040 ))
2041 }
2042
2043 /// Every entity carrying at least one signal above `none` — the
2044 /// include-gated `signals` health axis.
2045 pub fn signal_reports(
2046 &self,
2047 mem_filter: Option<&str>,
2048 ) -> Vec<crate::ops::health::SignalReport> {
2049 crate::ops::health::collect_signal_reports(&self.store, mem_filter, &self.schemas)
2050 }
2051
2052 /// The `signals` health axis payload — the entity roster plus
2053 /// per-level counts. One composer shared by the CLI health
2054 /// command and the MCP server so the axis cannot drift
2055 /// between surfaces.
2056 pub fn health_signals_axis(&self, mem_filter: Option<&str>) -> serde_json::Value {
2057 use memstead_schema::SignalLevel;
2058 let reports = self.signal_reports(mem_filter);
2059 let mut notice = 0usize;
2060 let mut warn = 0usize;
2061 for r in &reports {
2062 for s in &r.signals {
2063 match s.level {
2064 Some(SignalLevel::Notice) => notice += 1,
2065 Some(SignalLevel::Warn) => warn += 1,
2066 None => {}
2067 }
2068 }
2069 }
2070 serde_json::json!({
2071 "entities": reports,
2072 "counts": { "notice": notice, "warn": warn },
2073 })
2074 }
2075
2076 /// Defective section-format declarations the loaded schemas carry
2077 /// (lenient boot recorded them; install would have refused).
2078 pub fn schema_format_defects(&self) -> Vec<crate::ops::health::SchemaFormatDefect> {
2079 crate::ops::health::collect_schema_format_defects(&self.schemas)
2080 }
2081
2082 /// Conformance-axis integrity findings for one mem — which
2083 /// entities a write would refuse under the effective schema, and
2084 /// why. `target_schema = None` lints against the mem's current
2085 /// pin; `Some(ref)` lints against that schema instead (resolved
2086 /// among mem-pinned, workspace, and built-in schemas).
2087 pub fn conformance_findings(
2088 &self,
2089 mem: &str,
2090 target_schema: Option<&memstead_schema::SchemaRef>,
2091 ) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
2092 let pinned = self
2093 .schemas
2094 .get(mem)
2095 .ok_or_else(|| self.unknown_mem_error(mem))?;
2096 let effective: Arc<Schema> = match target_schema {
2097 None => pinned.clone(),
2098 Some(target) => self.resolve_schema_by_ref(target).ok_or_else(|| {
2099 let consulted: Vec<_> = self
2100 .workspace_schemas
2101 .iter()
2102 .chain(self.builtin_schemas.iter())
2103 .cloned()
2104 .collect();
2105 EngineError::SchemaNotFound {
2106 mem: mem.to_string(),
2107 pin: target.as_display(),
2108 sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
2109 &target.name,
2110 &target.version,
2111 &consulted,
2112 ),
2113 install_hint: None,
2114 }
2115 .with_schema_install_probe(self.workspace_root())
2116 })?,
2117 };
2118 Ok(crate::ops::integrity::conformance_findings(
2119 &self.store,
2120 mem,
2121 &effective,
2122 &self.schemas,
2123 ))
2124 }
2125
2126 /// What `mem`'s entity BODIES carry that their types do not declare
2127 /// (consistency-sweep 04/01): headings absorbed into the catch-all,
2128 /// headings repeated so that later bodies were not kept, and frontmatter
2129 /// keys the next write will drop.
2130 ///
2131 /// A folder mem's ledger set against its file set, per mem.
2132 ///
2133 /// **Folder mems only, and that is the point.** On a
2134 /// git-branch mem the change set is a real two-tree diff against the
2135 /// committed tree, so ledger-versus-files divergence is structurally
2136 /// impossible; emitting an always-clean version of this check there would
2137 /// be a surface asserting something it never had to establish, which is
2138 /// the failure class this bundle exists to remove. Such a mem is absent
2139 /// from the map rather than present and empty.
2140 pub fn ledger_reconciliation(
2141 &self,
2142 ) -> std::collections::BTreeMap<String, crate::filesystem::changelog::LedgerReconciliation>
2143 {
2144 let mut out = std::collections::BTreeMap::new();
2145 for m in &self.mounts {
2146 let crate::workspace::MountStorage::Folder { path } = &m.mount.storage else {
2147 continue;
2148 };
2149 if let Ok(r) = crate::filesystem::changelog::reconcile_ledger(path) {
2150 out.insert(m.mount.mem.clone(), r);
2151 }
2152 }
2153 out
2154 }
2155
2156 /// Separate from [`Self::conformance_findings`] on purpose. These are
2157 /// observations, not violations: absorbing an undeclared heading is the
2158 /// catch-all working as designed, and reporting it as a finding would fail
2159 /// every mem that uses the feature. What a reader needs here is whether the
2160 /// content SURVIVES, which each observation states.
2161 pub fn body_observations(
2162 &self,
2163 mem: &str,
2164 target_schema: Option<&memstead_schema::SchemaRef>,
2165 ) -> Result<Vec<crate::ops::integrity::BodyObservation>, EngineError> {
2166 let pinned = self
2167 .schemas
2168 .get(mem)
2169 .ok_or_else(|| self.unknown_mem_error(mem))?;
2170 let effective: Arc<Schema> = match target_schema {
2171 None => pinned.clone(),
2172 Some(target) => {
2173 self.resolve_schema_by_ref(target)
2174 .ok_or_else(|| EngineError::SchemaNotFound {
2175 mem: mem.to_string(),
2176 pin: target.as_display(),
2177 sources: Vec::new(),
2178 install_hint: None,
2179 })?
2180 }
2181 };
2182 Ok(crate::ops::integrity::body_observations(
2183 &self.store,
2184 mem,
2185 &effective,
2186 ))
2187 }
2188
2189 /// Resolve an exact `name@version` ref against every schema this
2190 /// engine can see: mem-pinned, workspace-authored, built-in.
2191 /// `None` when no loaded schema matches.
2192 pub(crate) fn resolve_schema_by_ref(
2193 &self,
2194 target: &memstead_schema::SchemaRef,
2195 ) -> Option<Arc<Schema>> {
2196 self.schemas
2197 .values()
2198 .chain(self.workspace_schemas.iter())
2199 .chain(self.builtin_schemas.iter())
2200 .find(|s| {
2201 let (name, version) = s.id();
2202 name == target.name && version == target.version
2203 })
2204 .cloned()
2205 }
2206
2207 /// The mem's `Mount.schema` expectation assertion, when set.
2208 /// `None` for unknown mems *and* for mems whose mount carries no
2209 /// assertion (the authoritative pin then lives in the backend
2210 /// config; the resolved active schema, not this, is the effective pin).
2211 pub fn schema_pin(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
2212 self.mounts
2213 .iter()
2214 .find(|m| m.mount.mem == mem)
2215 .and_then(|m| m.mount.schema.clone())
2216 }
2217
2218 /// The mem's in-flight migration target, when dual-pin state is
2219 /// active. `None` for settled or unknown mems.
2220 pub fn migration_target(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
2221 self.mounts
2222 .iter()
2223 .find(|m| m.mount.mem == mem)
2224 .and_then(|m| m.mount.migration_target.clone())
2225 }
2226
2227 /// Consistency-axis integrity findings for one mem — the
2228 /// pre-existing graph-coherence categories (dangling links, stubs)
2229 /// plus cross-mem edges the workspace grant table no longer permits,
2230 /// projected into the `{ id, axis, code, detail }` finding shape.
2231 pub fn consistency_findings(
2232 &self,
2233 mem: &str,
2234 ) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
2235 if !self.schemas.contains_key(mem) {
2236 return Err(self.unknown_mem_error(mem));
2237 }
2238 let mut findings = crate::ops::integrity::consistency_findings(
2239 &self.store,
2240 mem,
2241 // The one grant resolver, the same one the write gate calls. Every
2242 // consumer of the axis reaches it through this funnel, so there is
2243 // no site where a second answer could be written (04/07).
2244 &|from, to| self.cross_mem_link_allowed(from, to),
2245 // The mount set, so an edge into a mem that is not mounted is
2246 // reported as the dangling finding it is and never as a grant
2247 // the table still names.
2248 &|target| self.mount(target).is_some(),
2249 );
2250 // The provenance layer's own consistency: a sidecar the engine cannot
2251 // read is a finding on the mem, beside the entity-level ones. Without
2252 // it every anchor surface reads zero rows over this mem and calls
2253 // that clean (backlog, found by the evidence-engine grader 2026-09-02).
2254 if let Some(why) = self.anchors_sidecar_error(mem) {
2255 findings.push(crate::ops::integrity::IntegrityFinding {
2256 id: mem.to_string(),
2257 axis: crate::ops::integrity::IntegrityAxis::Consistency,
2258 code: "ANCHORS_SIDECAR_UNREADABLE".to_string(),
2259 detail: serde_json::json!({
2260 "mem": mem,
2261 "reason": why,
2262 "repair": "the anchors sidecar is unreadable, so every anchor surface for this mem reports a condition instead of rows; fix or remove the sidecar file, then re-record anchors",
2263 }),
2264 });
2265 }
2266 Ok(findings)
2267 }
2268
2269 /// Every cross-mem edge the workspace's current grant resolution does
2270 /// not permit, across every visible mem.
2271 ///
2272 /// A projection of [`Self::consistency_findings`] filtered to the one
2273 /// code, not a second scan: the revoke path and the health axis must
2274 /// never be able to answer differently about the same edge, and the
2275 /// surest way to guarantee that is for one of them to BE the other.
2276 ///
2277 /// Call it after the grant edit has landed and the settings have been
2278 /// reloaded — the answer is "what does the CURRENT policy leave
2279 /// unbacked", which is what an operator revoking a grant wants to know.
2280 ///
2281 /// Takes `&mut self` because it must load lazily-deferred mems first. A
2282 /// deferred mem's entities are not in the store, so scanning without the
2283 /// load would report zero ungranted edges for it and call that clean —
2284 /// which is precisely the silent all-clear this whole axis exists to
2285 /// prevent. The long-lived server engines carry lazy mounts; the CLI's
2286 /// fresh boot does not, so this only bites on the surface where it is
2287 /// hardest to notice.
2288 pub fn ungranted_cross_mem_edges(&mut self) -> Vec<crate::ops::integrity::IntegrityFinding> {
2289 self.ensure_mems_loaded(None);
2290 let mut mems: Vec<&String> = self.schemas.keys().collect();
2291 mems.sort();
2292 mems.into_iter()
2293 .filter_map(|mem| self.consistency_findings(mem).ok())
2294 .flatten()
2295 .filter(|f| f.code == "CROSS_MEM_EDGE_UNGRANTED")
2296 .collect()
2297 }
2298
2299 /// The edges that went from permitted to unpermitted between two
2300 /// readings of [`Self::ungranted_cross_mem_edges`] — what a policy edit
2301 /// just orphaned, as opposed to what was already orphaned before it.
2302 ///
2303 /// A revocation that reported the whole standing set would blame this
2304 /// edit for every edge some earlier unrelated revocation left behind,
2305 /// which is a different and less useful claim.
2306 pub fn newly_ungranted(
2307 before: &[crate::ops::integrity::IntegrityFinding],
2308 after: Vec<crate::ops::integrity::IntegrityFinding>,
2309 ) -> Vec<crate::ops::integrity::IntegrityFinding> {
2310 let seen: std::collections::BTreeSet<(String, String)> = before
2311 .iter()
2312 .map(|f| (f.id.clone(), f.detail["target_id"].to_string()))
2313 .collect();
2314 after
2315 .into_iter()
2316 .filter(|f| !seen.contains(&(f.id.clone(), f.detail["target_id"].to_string())))
2317 .collect()
2318 }
2319
2320 /// Engine-wide health summary across every mount.
2321 pub fn health(&self) -> crate::ops::HealthSummary {
2322 self.health_inner(None)
2323 }
2324
2325 /// Health summary scoped to one visible mem. The scans and
2326 /// structural counts narrow to that mem; workspace-level facts
2327 /// (quarantine roster, boot diagnosis, workspace-scoped warnings)
2328 /// stay global — an agent scoping to one mem must still see them.
2329 /// A name that is quarantined or not on the visible roster refuses
2330 /// `UNKNOWN_MEM` — the same gate `search` applies to its `mem`
2331 /// filter, so "no such mem" and "healthy mem, nothing to report"
2332 /// can never be confused. `None` is the engine-wide sweep.
2333 pub fn health_scoped(
2334 &self,
2335 mem: Option<&str>,
2336 ) -> Result<crate::ops::HealthSummary, crate::EngineError> {
2337 if let Some(name) = mem
2338 && (self.quarantine_reason(name).is_some() || !self.mem_router.is_visible(name))
2339 {
2340 return Err(self.unknown_mem_error(name));
2341 }
2342 Ok(self.health_inner(mem))
2343 }
2344
2345 fn health_inner(&self, mem: Option<&str>) -> crate::ops::HealthSummary {
2346 let fallback = engine_fallback_type();
2347 let mut summary =
2348 crate::ops::health::compute_health(&self.store, fallback.as_ref(), &self.schemas, mem);
2349 self.apply_anchor_clock(&mut summary, mem);
2350 // Merge in load-time drift warnings so every caller of
2351 // Engine::health — MCP handler, Swift FFI, direct CLI —
2352 // sees the SuspiciousNestedPrefix / DuplicateSectionHeading
2353 // findings without reaching into private engine state. The
2354 // MCP handler further appends request-scoped warnings on
2355 // top. Mirrors full's merge.
2356 if !self.load_warnings.is_empty() {
2357 let mut merged = self.load_warnings.clone();
2358 merged.append(&mut summary.warnings);
2359 summary.warnings = merged;
2360 }
2361 // A standing property, reported here rather than on every boot: a
2362 // folder mem's drift cursor is its own ledger, which only the engine
2363 // writes, so an edit made to its files by anything else is invisible
2364 // and reads keep serving the pre-edit content. Silence about that is
2365 // the one outcome this forbids. Git-branch mems are
2366 // absent: their change set is a real two-tree diff, so the condition
2367 // cannot arise.
2368 for m in &self.mounts {
2369 if matches!(
2370 m.mount.storage,
2371 crate::workspace::MountStorage::Folder { .. }
2372 ) && mem.is_none_or(|scope| scope == m.mount.mem)
2373 {
2374 summary
2375 .warnings
2376 .push(crate::ops::WarningHint::OutOfBandEditsUndetected {
2377 mem: m.mount.mem.clone(),
2378 });
2379 }
2380 }
2381 // Quarantine roster — a boot-honesty fact, present whenever
2382 // non-empty, never behind an include gate. Empty (and omitted
2383 // from the wire) on a healthy workspace.
2384 summary.quarantined = self
2385 .quarantined
2386 .iter()
2387 .map(|q| crate::ops::QuarantinedMemReport {
2388 mem: q.mount.mem.clone(),
2389 reason_code: q.reason_code.clone(),
2390 reason_message: q.reason_message.clone(),
2391 })
2392 .collect();
2393 // Per-file load failures ride the report unconditionally, like
2394 // the quarantine roster — each entry's message names the remedy
2395 // (the merge-conflict refusal names `memstead conflicts
2396 // resolve`), and a remedy only a library accessor carries is a
2397 // capability nobody finds at the moment it is needed.
2398 summary.load_errors = self
2399 .load_errors
2400 .iter()
2401 .map(|(path, msg)| crate::ops::LoadErrorReport {
2402 file: path.display().to_string(),
2403 error: msg.clone(),
2404 })
2405 .collect();
2406 summary.boot_diagnosis = self
2407 .boot_diagnosis
2408 .as_ref()
2409 .map(|(code, message)| serde_json::json!({ "code": code, "message": message }));
2410 // Surface OUTER_REPO_NOT_IGNORING_MEM_REPO when the
2411 // workspace is embedded inside a git repository whose
2412 // .gitignore does not list `mem-repo/`. Skipped when
2413 // workspace_root is unset (engine built ad-hoc from a mount
2414 // list).
2415 if let Some(root) = self.workspace_root.as_deref()
2416 && let Some(outer) = crate::workspace_root::find_enclosing_git_repo(root)
2417 && !crate::workspace_root::outer_repo_ignores_mem_repo(&outer, root)
2418 {
2419 summary
2420 .warnings
2421 .push(WarningHint::OuterRepoNotIgnoringMemRepo {
2422 outer_repo_root: outer.display().to_string(),
2423 workspace_root: root.display().to_string(),
2424 });
2425 }
2426 // Authoring-drift axis: for every pinned schema whose sealed
2427 // copy carries an install-provenance stamp, report a MISSING
2428 // authoring package (stamped path gone) or a DIVERGED one
2429 // (present but no longer parsed-equivalent to the seal).
2430 // Unstamped schemas — sealed pre-stamp, built-ins, archive
2431 // installs — produce no finding. Read-only on both copies.
2432 summary.warnings.extend(self.authoring_drift_findings());
2433 // Rot axis for the pins the drift axis skips: an UNSTAMPED
2434 // sealed package whose content no longer passes current-
2435 // language authoring validation gets its own low-tier hint —
2436 // the holding runs fine on the tolerant seal, but the package
2437 // (and the unlocatable authoring source it came from) is no
2438 // longer installable, and nothing else would say so before the
2439 // next install attempt. A parsing unstamped package stays
2440 // silent; stamped pins are the drift axis's business.
2441 summary.warnings.extend(self.unstamped_rot_findings());
2442 // Claims no verify watches: every `unanchored-mention` finding the
2443 // bindings' verify passes recorded, read off the durable findings
2444 // stores (no source is observed here — health reports the standing,
2445 // verify establishes it). Warn-level, one line per (entity,
2446 // artifact), the same unit the store holds.
2447 summary.warnings.extend(self.unanchored_mention_findings());
2448 // Under a mem scope, mem-attributable warnings narrow to the
2449 // scoped mem; workspace- and request-scoped warnings return
2450 // `None` from `source_mem()` and stay visible regardless.
2451 // Mirrors the health composer's filter.
2452 if let Some(v) = mem {
2453 summary
2454 .warnings
2455 .retain(|w| w.source_mem().is_none_or(|wv| wv == v));
2456 }
2457 summary
2458 }
2459
2460 /// The `unanchored-mention` findings of every binding's current batch,
2461 /// as health warnings. Empty without a workspace root (no binding store
2462 /// to read) and for a binding whose store or resolution is unreadable —
2463 /// health never fabricates a projection reading it did not find.
2464 fn unanchored_mention_findings(&self) -> Vec<WarningHint> {
2465 let Some(root) = self.workspace_root.as_deref() else {
2466 return Vec::new();
2467 };
2468 let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root) else {
2469 return Vec::new();
2470 };
2471 let mut out = Vec::new();
2472 for record in &configs.bindings {
2473 let binding_id = format!("{}/{}", record.mem, record.name);
2474 let Ok(resolved) =
2475 crate::ingest::resolve::resolve_binding_run(&binding_id, &record.config)
2476 else {
2477 continue;
2478 };
2479 let Ok((_, findings)) =
2480 crate::ingest::findings::current_findings(self, root, &record.config, &resolved)
2481 else {
2482 continue;
2483 };
2484 for f in findings {
2485 if let crate::ingest::findings::FindingTarget::Mention {
2486 entity,
2487 artifact,
2488 section,
2489 } = f.target
2490 {
2491 out.push(WarningHint::UnanchoredMention {
2492 mem: record.config.destination_mem.clone(),
2493 binding: binding_id.clone(),
2494 entity: EntityId(entity),
2495 artifact,
2496 section,
2497 });
2498 }
2499 }
2500 }
2501 out
2502 }
2503
2504 /// Compute the authoring-drift findings for every stamped pinned
2505 /// schema. See the call site in [`Self::health`] for the axis
2506 /// contract; returns an empty list when no workspace root is set
2507 /// (ad-hoc mount-list engines have no authoring tree to check).
2508 fn authoring_drift_findings(&self) -> Vec<WarningHint> {
2509 let Some(root) = self.workspace_root.as_deref() else {
2510 return Vec::new();
2511 };
2512 // Group pinning mems by (name, version) — BTreeMap for a
2513 // deterministic finding order.
2514 let mut pins: std::collections::BTreeMap<(String, String), Vec<String>> =
2515 std::collections::BTreeMap::new();
2516 for (mem, schema) in &self.schemas {
2517 let (name, version) = schema.id();
2518 pins.entry((name.to_string(), version.to_string()))
2519 .or_default()
2520 .push(mem.clone());
2521 }
2522 let mut out = Vec::new();
2523 for ((name, version), mut mems) in pins {
2524 mems.sort();
2525 let Some(stamped_path) = self.read_install_provenance(root, &name, &version) else {
2526 continue;
2527 };
2528 let schema_ref = format!("{name}@{version}");
2529 // A workspace-relative stamp (the portable form the installer
2530 // writes for in-workspace authoring dirs) resolves against
2531 // THIS workspace root, so the axis checks real drift on every
2532 // clone instead of reporting another machine's absolute path
2533 // as missing. Absolute stamps stay machine-pinned as-is.
2534 let stamped = std::path::Path::new(&stamped_path);
2535 let resolved: std::path::PathBuf = if stamped.is_absolute() {
2536 stamped.to_path_buf()
2537 } else {
2538 root.join(stamped)
2539 };
2540 let authoring = resolved.as_path();
2541 if !authoring.is_dir() {
2542 out.push(WarningHint::SchemaAuthoringSourceMissing {
2543 schema_ref,
2544 stamped_path,
2545 mems,
2546 });
2547 continue;
2548 }
2549 let sealed = self
2550 .schemas
2551 .get(&mems[0])
2552 .expect("mems collected from self.schemas keys")
2553 .clone();
2554 match memstead_schema::load_schema_from_dir(authoring) {
2555 Err(e) => out.push(WarningHint::SchemaAuthoringSourceDiverged {
2556 schema_ref,
2557 stamped_path,
2558 mems,
2559 detail: format!("the authoring package no longer loads: {e}"),
2560 }),
2561 Ok(authored) => {
2562 if schema_parsed_fingerprint(&authored) != schema_parsed_fingerprint(&sealed) {
2563 out.push(WarningHint::SchemaAuthoringSourceDiverged {
2564 schema_ref,
2565 stamped_path,
2566 mems,
2567 detail: "the parsed authoring package differs from the sealed copy \
2568 the engine runs on"
2569 .to_string(),
2570 });
2571 }
2572 }
2573 }
2574 }
2575 out
2576 }
2577
2578 /// Compute the rot findings for every UNSTAMPED pinned schema: read
2579 /// the sealed package's content back (folder seal directory, or the
2580 /// `__MEMSTEAD:schemas/` ref via the ops bundle) and run the
2581 /// authoring-tier check over it. A pin with a stamp is skipped (the
2582 /// divergence axis owns it); a pin with no readable sealed package
2583 /// — built-ins resolving from the embedded catalogue — is skipped
2584 /// too (nothing on disk can rot). See the call site in
2585 /// [`Self::health`] for the axis contract.
2586 fn unstamped_rot_findings(&self) -> Vec<WarningHint> {
2587 let Some(root) = self.workspace_root.as_deref() else {
2588 return Vec::new();
2589 };
2590 let mut pins: std::collections::BTreeMap<(String, String), Vec<String>> =
2591 std::collections::BTreeMap::new();
2592 for (mem, schema) in &self.schemas {
2593 let (name, version) = schema.id();
2594 pins.entry((name.to_string(), version.to_string()))
2595 .or_default()
2596 .push(mem.clone());
2597 }
2598 let mut out = Vec::new();
2599 for ((name, version), mut mems) in pins {
2600 mems.sort();
2601 if self
2602 .read_install_provenance(root, &name, &version)
2603 .is_some()
2604 {
2605 continue; // stamped — the divergence axis checks it
2606 }
2607 let schema_ref = format!("{name}@{version}");
2608 // Folder seal: the sealed package is a real directory the
2609 // authoring loader can probe directly.
2610 let sealed_dir = root.join(".memstead").join("schemas").join(&schema_ref);
2611 let detail: Option<String> = if sealed_dir.join("schema.yaml").is_file() {
2612 memstead_schema::load_schema_from_dir(&sealed_dir)
2613 .err()
2614 .map(|e| e.to_string())
2615 } else if let Some((manifest, types)) = self.read_sealed_package_yamls(&name, &version)
2616 {
2617 memstead_schema::loader::check_package_reauthorable(&manifest, &types)
2618 .err()
2619 .map(|e| e.to_string())
2620 } else {
2621 None // no sealed copy anywhere — embedded builtin
2622 };
2623 if let Some(detail) = detail {
2624 out.push(WarningHint::SchemaUnstampedSourceRot {
2625 schema_ref,
2626 mems,
2627 detail,
2628 });
2629 }
2630 }
2631 out
2632 }
2633
2634 /// Read a sealed package's `schema.yaml` + `types/*.yaml` back from
2635 /// the `__MEMSTEAD:schemas/` ref, reconstructing the type-file names
2636 /// from the pinned parsed schema's type roster (seal-time authoring
2637 /// enforces stem == declared type name). `None` when the ops bundle
2638 /// or the package is absent — the embedded-builtin state.
2639 fn read_sealed_package_yamls(
2640 &self,
2641 name: &str,
2642 version: &str,
2643 ) -> Option<(String, Vec<(String, String)>)> {
2644 let ops = self.git_branch_ops()?;
2645 let root = self.workspace_root.as_deref()?;
2646 let gitdir = self
2647 .mounts
2648 .iter()
2649 .find_map(|m| match &m.mount.storage {
2650 crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
2651 _ => None,
2652 })
2653 .or_else(|| {
2654 let g = root.join("mem-repo").join(".git");
2655 g.is_dir().then_some(g)
2656 })?;
2657 let read = |rel: &str| -> Option<String> {
2658 (ops.read_schema_file)(&gitdir, name, version, rel)
2659 .ok()
2660 .flatten()
2661 .and_then(|bytes| String::from_utf8(bytes).ok())
2662 };
2663 let manifest = read("schema.yaml")?;
2664 let schema = self
2665 .schemas
2666 .values()
2667 .find(|s| {
2668 let (n, v) = s.id();
2669 n == name && v.to_string() == version
2670 })?
2671 .clone();
2672 let mut type_names: Vec<String> = schema.types.keys().cloned().collect();
2673 type_names.sort();
2674 let mut types = Vec::new();
2675 for t in type_names {
2676 if let Some(body) = read(&format!("types/{t}.yaml")) {
2677 types.push((t, body));
2678 }
2679 }
2680 Some((manifest, types))
2681 }
2682
2683 /// Read the install-provenance stamp for a sealed schema package,
2684 /// checking the folder location first
2685 /// (`.memstead/schemas/<name>@<version>/`) and falling back to the
2686 /// `__MEMSTEAD:schemas/` ref via the git-branch ops bundle when
2687 /// wired. `None` when no stamp exists anywhere — the normal state
2688 /// for pre-stamp seals, built-ins, and archive installs.
2689 fn read_install_provenance(&self, root: &Path, name: &str, version: &str) -> Option<String> {
2690 let folder_stamp = root
2691 .join(".memstead")
2692 .join("schemas")
2693 .join(format!("{name}@{version}"))
2694 .join(memstead_schema::INSTALL_PROVENANCE_FILE);
2695 let bytes = if folder_stamp.is_file() {
2696 std::fs::read(&folder_stamp).ok()
2697 } else {
2698 let ops = self.git_branch_ops()?;
2699 let gitdir = self
2700 .mounts
2701 .iter()
2702 .find_map(|m| match &m.mount.storage {
2703 crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
2704 Some(gitdir.clone())
2705 }
2706 _ => None,
2707 })
2708 .or_else(|| {
2709 let g = root.join("mem-repo").join(".git");
2710 g.is_dir().then_some(g)
2711 })?;
2712 (ops.read_schema_file)(
2713 &gitdir,
2714 name,
2715 version,
2716 memstead_schema::INSTALL_PROVENANCE_FILE,
2717 )
2718 .ok()
2719 .flatten()
2720 }?;
2721 let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
2722 v.get("authoring_path")?.as_str().map(String::from)
2723 }
2724
2725 /// Engine-wide [`crate::ops::Status`] across every mount — the graph
2726 /// counts behind `memstead status` (renamed from `stats` with the
2727 /// command, D11; fields unchanged).
2728 pub fn status(&self) -> crate::ops::Status {
2729 let mut types_in_use: Vec<String> = self
2730 .store
2731 .all_entities()
2732 .filter(|e| !e.stub && !e.entity_type.is_empty())
2733 .map(|e| e.entity_type.clone())
2734 .collect();
2735 types_in_use.sort();
2736 types_in_use.dedup();
2737
2738 let mut edge_types: std::collections::BTreeMap<String, usize> =
2739 std::collections::BTreeMap::new();
2740 for id in self.store.all_ids() {
2741 for edge in self.store.outgoing(id) {
2742 *edge_types.entry(edge.rel_type.clone()).or_insert(0) += 1;
2743 }
2744 }
2745
2746 crate::ops::Status {
2747 entity_count: self.store.all_entities().filter(|e| !e.stub).count(),
2748 edge_count: self.store.edge_count(),
2749 edge_types,
2750 community_count: self.communities().count,
2751 mem_count: self.mounts.len(),
2752 types_in_use,
2753 }
2754 }
2755
2756 /// Build a [`ContextResult`] for `id`: the community cluster id
2757 /// (or `None` when the entity is a stub or not present), plus the
2758 /// outgoing + incoming neighbour lists.
2759 pub fn context(&self, id: &EntityId) -> Option<ContextResult> {
2760 let entity = self.store.get(id)?;
2761 let community = self
2762 .communities()
2763 .entity_cluster_map
2764 .get(id.as_ref())
2765 .cloned();
2766 let mut neighbors = Vec::new();
2767 for edge in self.store.outgoing(id) {
2768 if let Some(target) = self.store.get(&edge.target) {
2769 neighbors.push(NeighborInfo {
2770 id: target.id.clone(),
2771 title: target.title.clone(),
2772 relationship: edge.rel_type.clone(),
2773 direction: Direction::Outgoing,
2774 });
2775 }
2776 }
2777 for edge in self.store.incoming(id) {
2778 if let Some(source) = self.store.get(&edge.from) {
2779 neighbors.push(NeighborInfo {
2780 id: source.id.clone(),
2781 title: source.title.clone(),
2782 relationship: edge.rel_type.clone(),
2783 direction: Direction::Incoming,
2784 });
2785 }
2786 }
2787 Some(ContextResult {
2788 entity_id: entity.id.clone(),
2789 community,
2790 neighbors,
2791 })
2792 }
2793
2794 /// Lazily-built per-mem search index map. The map carries one
2795 /// entry per writable mem. Build cost scales with entity count;
2796 /// expect hundreds-of-ms for thousand-entity workspaces. Not
2797 /// available on `wasm32` targets — search lives behind the bridge
2798 /// (see [`Self::search`] for the typed refuse).
2799 #[cfg(not(target_arch = "wasm32"))]
2800 pub fn search_indexes(&self) -> &HashMap<String, MemIndex> {
2801 if let Some((memo_key, _)) = self.search_indexes_memo.get() {
2802 debug_assert_eq!(
2803 *memo_key,
2804 self.derived_key(),
2805 "search memo key lags the engine — a mutation path missed invalidate_search_indexes"
2806 );
2807 }
2808 &self
2809 .search_indexes_memo
2810 .get_or_init(|| (self.derived_key(), build_all(&self.store, &self.schemas)))
2811 .1
2812 }
2813
2814 /// Drop the cached per-mem search index map. No-op on `wasm32`
2815 /// where no index exists; the method stays present so mutation
2816 /// hooks can call it unconditionally.
2817 /// Incrementally maintain the search-index memo for a known
2818 /// touched-id set: replace or remove
2819 /// exactly the touched documents in place and advance the memo's
2820 /// key, instead of dropping the whole map. Semantics:
2821 ///
2822 /// - Memo empty → nothing to maintain; the next read builds fresh.
2823 /// - Memo current (key matches) → no-op (rollback already landed).
2824 /// - Schemas epoch moved → the index FIELD SET may have changed:
2825 /// the named, scoped fallback — drop the memo for a full
2826 /// rebuild. Never a silent widening: this is the one case the
2827 /// plan names (schema-shape change).
2828 /// - Otherwise: per touched id, a real non-stub entity in the
2829 /// store is re-indexed (delete-then-add on the id term), and an
2830 /// absent or stub entry is removed — stubs stay excluded exactly
2831 /// as the bulk build excludes them. Touched mems' writers
2832 /// commit; any tantivy error falls back to dropping the memo
2833 /// (warn-logged), never to serving a stale index.
2834 #[cfg(not(target_arch = "wasm32"))]
2835 pub(crate) fn maintain_search_indexes(&mut self, touched: &[crate::EntityId]) {
2836 let current = super::DerivedKey {
2837 store_generation: self.store.generation(),
2838 schemas_epoch: self.schemas_epoch,
2839 };
2840 let Some((memo_key, indexes)) = self.search_indexes_memo.get_mut() else {
2841 return;
2842 };
2843 if *memo_key == current {
2844 return;
2845 }
2846 if memo_key.schemas_epoch != current.schemas_epoch {
2847 self.search_indexes_memo = OnceCell::new();
2848 return;
2849 }
2850 let mut touched_mems: std::collections::HashSet<&str> = std::collections::HashSet::new();
2851 for id in touched {
2852 let Some(idx) = indexes.get_mut(id.mem()) else {
2853 continue;
2854 };
2855 let result = match self.store.get(id) {
2856 Some(entity) if !entity.stub => idx.index_entity(entity),
2857 _ => idx.remove_entity(id),
2858 };
2859 if let Err(e) = result {
2860 tracing::warn!(
2861 id = id.as_ref(),
2862 error = %e,
2863 "incremental index maintenance failed; dropping the memo for a full rebuild"
2864 );
2865 self.search_indexes_memo = OnceCell::new();
2866 return;
2867 }
2868 touched_mems.insert(id.mem());
2869 }
2870 for (mem, idx) in indexes.iter_mut() {
2871 if !touched_mems.contains(mem.as_str()) {
2872 continue;
2873 }
2874 if let Err(e) = idx.commit() {
2875 tracing::warn!(
2876 mem = mem.as_str(),
2877 error = %e,
2878 "incremental index commit failed; dropping the memo for a full rebuild"
2879 );
2880 self.search_indexes_memo = OnceCell::new();
2881 return;
2882 }
2883 }
2884 *memo_key = current;
2885 }
2886
2887 /// No-op shim on `wasm32`, mirroring `invalidate_search_indexes`
2888 /// so mutation paths call it unconditionally.
2889 #[cfg(target_arch = "wasm32")]
2890 pub(crate) fn maintain_search_indexes(&mut self, _touched: &[crate::EntityId]) {}
2891
2892 /// Unconditionally drop the search-index memo, regardless of its
2893 /// generation. The forced variant exists for embedders that want
2894 /// to release the index's memory in a long-lived process (or force
2895 /// a from-scratch rebuild for verification); the generation-checked
2896 /// [`Self::invalidate_search_indexes`] stays the mutation-path
2897 /// hook.
2898 pub fn drop_search_indexes(&mut self) {
2899 #[cfg(not(target_arch = "wasm32"))]
2900 {
2901 self.search_indexes_memo = OnceCell::new();
2902 }
2903 }
2904
2905 pub fn invalidate_search_indexes(&mut self) {
2906 #[cfg(not(target_arch = "wasm32"))]
2907 {
2908 // Same generation check as `invalidate_communities`: keep
2909 // the memo when the store still sits at its generation
2910 // (the batch-rollback case), clear otherwise.
2911 if let Some((memo_key, _)) = self.search_indexes_memo.get()
2912 && *memo_key == self.derived_key()
2913 {
2914 return;
2915 }
2916 self.search_indexes_memo = OnceCell::new();
2917 }
2918 }
2919
2920 /// Filter the in-memory store by metadata only (no text match).
2921 #[cfg(not(target_arch = "wasm32"))]
2922 pub fn list(&self, scope: &SearchScope) -> crate::ops::ListResult {
2923 let fallback = engine_fallback_type();
2924 crate::ops::search::list(&self.store, scope, fallback.as_ref(), &self.schemas)
2925 }
2926
2927 /// Run a search against the lazily-built index map. Returns
2928 /// [`EngineError::SearchUnavailable`] on `wasm32` targets — browser
2929 /// consumers route search to the bridge; the local
2930 /// engine never builds a tantivy index in WASM. Native targets get
2931 /// the same shape as before, wrapped in `Ok`.
2932 pub fn search(&self, scope: &SearchScope) -> Result<SearchResult, EngineError> {
2933 // A mem filter naming a quarantined OR nonexistent mem refuses
2934 // typed `UNKNOWN_MEM`, matching every other mem-naming surface. A
2935 // success with 0 hits (the old nonexistent-mem behaviour, with a
2936 // missing-index warning) is indistinguishable from a true empty
2937 // result — the one thing a typed surface must never be.
2938 if let Some(mem) = scope.mem.as_deref()
2939 && (self.quarantine_reason(mem).is_some() || !self.mem_router.is_visible(mem))
2940 {
2941 return Err(self.unknown_mem_error(mem));
2942 }
2943 #[cfg(target_arch = "wasm32")]
2944 {
2945 let _ = scope;
2946 return Err(EngineError::SearchUnavailable);
2947 }
2948 #[cfg(not(target_arch = "wasm32"))]
2949 {
2950 let fallback = engine_fallback_type();
2951 Ok(crate::ops::search::search(
2952 &self.store,
2953 scope,
2954 fallback.as_ref(),
2955 self.search_indexes(),
2956 &self.schemas,
2957 ))
2958 }
2959 }
2960
2961 /// All mem-relative entity paths under `mem`. Delegates to
2962 /// the backend's `list_entities`. Order is backend-defined.
2963 pub fn list_entities(&self, mem: &str) -> Result<Vec<PathBuf>, EngineError> {
2964 let m = self.find_mount(mem)?;
2965 m.backend.list_entities().map_err(EngineError::Backend)
2966 }
2967
2968 /// Raw bytes for a single entity (`Ok(None)` if absent).
2969 pub fn read_entity(&self, mem: &str, rel_path: &Path) -> Result<Option<Vec<u8>>, EngineError> {
2970 let m = self.find_mount(mem)?;
2971 m.backend
2972 .read_entity(rel_path)
2973 .map_err(EngineError::Backend)
2974 }
2975
2976 /// Provenance entries for `mem` since `cursor`. Cursor shape is
2977 /// backend-specific (RFC-3339 timestamp for folder, commit SHA for
2978 /// git-branch); `None` means "from the beginning".
2979 pub fn read_provenance(
2980 &self,
2981 mem: &str,
2982 cursor: Option<&str>,
2983 ) -> Result<Vec<Provenance>, EngineError> {
2984 let m = self.find_mount(mem)?;
2985 m.backend
2986 .read_provenance(cursor)
2987 .map_err(EngineError::Backend)
2988 }
2989
2990 /// Capability declared on the mount for `mem`. Surfaced for
2991 /// callers that need to gate before dispatching a write — the
2992 /// engine itself does not yet enforce capability (mutation paths
2993 /// land in a later session).
2994 pub fn capability(&self, mem: &str) -> Result<crate::workspace::MountCapability, EngineError> {
2995 let m = self.find_mount(mem)?;
2996 Ok(m.mount.capability)
2997 }
2998
2999 /// Returns `true` when `from`'s source mem is mounted with
3000 /// [`crate::workspace::MountCapability::ReadOnly`]. Returns
3001 /// `false` for Write-Mems and for mems whose mount is absent
3002 /// from the router (no mount → no ReadOnly assertion can be
3003 /// made; the absence is treated as not-ReadOnly so consumers
3004 /// don't trip on transient lookup misses).
3005 ///
3006 /// Plan body §"Single edge source in the store" specifies this
3007 /// helper as the derived-on-demand alternative to adding a new
3008 /// field on [`crate::store::Edge`]. Strict-invariant validators
3009 /// and surfaces that want to highlight cross-mount references
3010 /// call this rather than pattern-matching on a per-edge marker.
3011 /// The information is fully derivable from the current mount
3012 /// roster, so no new state needs to live on the edge itself.
3013 pub fn edge_is_from_readonly(&self, from: &EntityId) -> bool {
3014 match self.capability(from.mem()) {
3015 Ok(crate::workspace::MountCapability::ReadOnly) => true,
3016 Ok(crate::workspace::MountCapability::Write) | Err(_) => false,
3017 }
3018 }
3019
3020 /// Whether a cross-mem edge from `from_mem` to `to_mem` is
3021 /// permitted under the current [`crate::WorkspaceSettings`]
3022 /// cross-mem link policy.
3023 ///
3024 /// Resolution rules (matches full's `mem_router` semantics):
3025 /// 1. Same-mem edge (`from_mem == to_mem`) → always
3026 /// allowed; the policy gates *cross*-mem edges only.
3027 /// 2. Explicit `cross_mem_links[from_mem]`:
3028 /// - `"*"` (wildcard) → allowed regardless of target.
3029 /// - `["a", ...]` (allowlist) → allowed iff `to_mem` is in
3030 /// the list.
3031 /// 3. Per-create-rule `default_cross_links` synthesis — if
3032 /// rule (1) didn't grant permission and `from_mem` matches
3033 /// a `[[mem_management.create]]` rule whose
3034 /// `default_cross_links` is set, the synthesised value
3035 /// contributes:
3036 /// - `"*"` → allowed regardless of target.
3037 /// - `["a", ...]` → allowed iff `to_mem` is in the list.
3038 /// 4. Otherwise → denied (default-deny posture).
3039 ///
3040 /// The synthesis layer compiles a [`crate::mem_management::CreateRuleSet`]
3041 /// lazily on first call and caches it; [`Self::set_settings`]
3042 /// invalidates the cache. Compilation failure (malformed glob
3043 /// in a rule) logs a warning and the synthesis layer is silently
3044 /// skipped — the resolver still returns `true` from explicit
3045 /// policy alone, so a half-broken config doesn't lock out edges
3046 /// the operator did intend to allow. Operators who want hard
3047 /// validation pre-compile via
3048 /// [`crate::mem_management::CreateRuleSet::new`] before
3049 /// calling [`Self::set_settings`].
3050 ///
3051 /// The MCP `memstead_relate` handler's cross-mem gate consumes
3052 /// this method directly.
3053 pub fn cross_mem_link_allowed(&self, from_mem: &str, to_mem: &str) -> bool {
3054 use memstead_schema::workspace_config::CrossLinkValue;
3055 if from_mem == to_mem {
3056 return true;
3057 }
3058
3059 // Step 1: explicit cross_mem_links policy.
3060 if let Some(value) = self.settings.cross_mem_links.get(from_mem) {
3061 match value {
3062 CrossLinkValue::Wildcard => return true,
3063 CrossLinkValue::List(targets) => {
3064 if targets.iter().any(|t| t == to_mem) {
3065 return true;
3066 }
3067 // Fall through to synthesis check — a List that
3068 // doesn't include the target may still allow it
3069 // via per-rule default_cross_links union.
3070 }
3071 }
3072 }
3073
3074 // Step 2: per-create-rule default_cross_links synthesis.
3075 let rule_set = self.create_rule_set_memo.get_or_init(|| {
3076 crate::mem_management::CreateRuleSet::new(
3077 self.settings.mem_create_rules.clone(),
3078 )
3079 .unwrap_or_else(|err| {
3080 tracing::warn!(
3081 error = %err,
3082 "cross_mem_link_allowed: failed to compile mem_create_rules — synthesis disabled (resolver falls back to explicit-policy-only)"
3083 );
3084 crate::mem_management::CreateRuleSet::default()
3085 })
3086 });
3087
3088 // Compose the same `<mem_path>/<name>` candidate the create-rule
3089 // composer matched against. The rule globs are keyed on the composed
3090 // lifecycle path (e.g. `memstead/project`, compiled with
3091 // `literal_separator`), not the bare leaf name — matching
3092 // `from_mem` alone silently misses, so synthesis denied a link
3093 // that `memstead_overview` rendered as rule-granted (the
3094 // leaf-vs-composed-path divergence). Flat-layout mems (no
3095 // hierarchical path) keep the bare leaf, matching their bare rule.
3096 let candidate = match self.mount(from_mem).and_then(|m| m.mem_path()) {
3097 Some(path) => format!("{path}/{from_mem}"),
3098 None => from_mem.to_string(),
3099 };
3100 if let Some(matched) = rule_set.first_match(std::path::Path::new(&candidate))
3101 && let Some(synth) = matched.default_cross_links.as_ref()
3102 {
3103 return match synth {
3104 CrossLinkValue::Wildcard => true,
3105 CrossLinkValue::List(targets) => targets.iter().any(|t| t == to_mem),
3106 };
3107 }
3108
3109 false
3110 }
3111
3112 pub(super) fn find_mount(&self, mem: &str) -> Result<&MountedBackend, EngineError> {
3113 self.mounts
3114 .iter()
3115 .find(|m| m.mount.mem == mem)
3116 .ok_or_else(|| self.unknown_mem_error(mem))
3117 }
3118}
3119
3120/// The base path of an anchor artifact ref — the locator suffixes a
3121/// medium may append (`@<commit>`, `#<span>`) stripped so the reverse
3122/// lookup compares paths, not versioned/located refs.
3123pub(crate) fn anchor_base_path(artifact: &str) -> &str {
3124 let cut = artifact.find(['@', '#']).unwrap_or(artifact.len());
3125 &artifact[..cut]
3126}
3127
3128/// One mem's standalone anchor-verification report — the counts plus
3129/// the per-anchor rows, in sidecar order.
3130#[derive(Debug, Clone, Default, serde::Serialize)]
3131pub struct MemAnchorVerification {
3132 pub mem: String,
3133 /// The anchors sidecar could not be read: the parse or IO reason. When
3134 /// set, no row was counted — every count below is zero because nothing
3135 /// was measured, not because the mem is clean — `fully_adjudicated`
3136 /// reads false and the population reads unknown. One condition, one
3137 /// code (`ANCHORS_SIDECAR_UNREADABLE`), rendered by every surface from
3138 /// this field; no surface parses the sidecar on its own.
3139 #[serde(skip_serializing_if = "Option::is_none")]
3140 pub sidecar_error: Option<String>,
3141 /// The positive figure with the population it was computed over
3142 /// ([`crate::anchor::AnchorResolutionFigure`]): `resolves` (the wire
3143 /// name is the `AnchorState` wire form; `resolved` was retired on
3144 /// 2026-09-02, one name per state), `population` and
3145 /// `fully_adjudicated`, serialized at this level. The count is never
3146 /// reachable apart from its statement.
3147 #[serde(flatten)]
3148 pub figure: crate::anchor::AnchorResolutionFigure,
3149 /// Source present, hash differs, stability `stable` — real drift.
3150 pub drifted: usize,
3151 /// Hash differs under `unstable` stability, or a hash is missing on
3152 /// either side — flagged for re-examination, never called drift.
3153 pub recheck: usize,
3154 /// Source absent: a MEASURED failure. The artifact the anchor names is
3155 /// not there.
3156 pub unresolvable: usize,
3157 /// The anchor could not be observed at all this pass, so nothing about it
3158 /// was measured. Its own count,
3159 /// because `unresolvable` used to swallow it: a reader on the surface you
3160 /// reach WITHOUT a binding could not tell a measured failure from an
3161 /// absent measurement, which is the one distinction that surface exists to
3162 /// make.
3163 pub unobserved: usize,
3164 /// Rows whose ENTITY is gone (consistency-sweep 03/02). Its own class,
3165 /// counted apart from the states above: those describe the artifact end,
3166 /// and a vanished entity says nothing about the source. Folding it into
3167 /// `unresolvable` would name the wrong repair.
3168 pub dangling: usize,
3169 /// Why the entity end could not be reconciled this pass, when it could
3170 /// not. `dangling: 0` means "none found" only when this is `None`.
3171 pub unreconciled: Option<String>,
3172 pub anchors: Vec<VerifiedAnchor>,
3173 /// Supplied observations whose artifact matched no `url` anchor of the
3174 /// mem — reported, never silently dropped, never applied to anything.
3175 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3176 pub unmatched_observations: Vec<String>,
3177 /// The `last_observed` records this verification produced from supplied
3178 /// observations, for the caller to commit through
3179 /// [`Engine::record_anchor_observations`]. Engine-internal.
3180 #[serde(skip)]
3181 pub recordable_observations: Vec<RecordedObservation>,
3182}
3183
3184/// One observation to record onto a sidecar row (the `last_observed`
3185/// field), addressed by the `(entity, artifact)` pair.
3186#[derive(Debug, Clone, PartialEq, Eq)]
3187pub struct RecordedObservation {
3188 pub entity: String,
3189 pub artifact: String,
3190 pub observation: crate::anchor::AnchorObservation,
3191}
3192
3193/// Observer-supplied observations keyed by artifact — the input of
3194/// [`Engine::verify_mem_anchors_with`].
3195pub type SuppliedObservations =
3196 std::collections::BTreeMap<String, crate::anchor::SuppliedObservation>;
3197
3198/// What one observation of an anchor yielded: the resolved state, the
3199/// hash it saw (when any), and — for an observation that was not made
3200/// live this pass — when it was made.
3201#[derive(Debug, Clone, PartialEq, Eq)]
3202struct Observed {
3203 state: crate::anchor::AnchorState,
3204 hash: Option<String>,
3205 at: Option<String>,
3206}
3207
3208impl Observed {
3209 /// A live observation made this pass (path and entity grains).
3210 fn live((state, hash): (crate::anchor::AnchorState, Option<String>)) -> Self {
3211 Observed {
3212 state,
3213 hash,
3214 at: None,
3215 }
3216 }
3217}
3218
3219impl MemAnchorVerification {
3220 /// The figure this report's counts yield for `resolves` resolving rows:
3221 /// the count with the population statement it was computed over
3222 /// (consistency-sweep 03/05, criteria 1 and 3): what the figures cover,
3223 /// and how much of it the pass could not adjudicate.
3224 ///
3225 /// A resolution figure alone is read as health. Every W3 finding made that
3226 /// figure mean less than a reader assumes, and none of them made it wrong
3227 /// in a way anyone could see. The figure type renders the number and its
3228 /// population as ONE unit, so a surface cannot show the number and omit
3229 /// the caveat: it gets both or neither.
3230 fn figure_over(&self, resolves: usize) -> crate::anchor::AnchorResolutionFigure {
3231 // `recheck` belongs on ONE side of this sentence. A first version put
3232 // it in both: counted as adjudicated and then reported as not, so the
3233 // same rows appeared twice and the two numbers could not be reconciled
3234 // by a reader. A recheck row is a row whose drift could NOT be
3235 // asserted, which is the definition of unadjudicated.
3236 if let Some(why) = &self.sidecar_error {
3237 return crate::anchor::AnchorResolutionFigure::uncounted(format!(
3238 "population unknown: the anchors sidecar could not be read ({why}); no row was \
3239 counted, and zero counts here are not a clean mem"
3240 ));
3241 }
3242 let adjudicated = resolves + self.drifted + self.unresolvable;
3243 let unadjudicated = self.recheck + self.unobserved;
3244 let mut s = format!(
3245 "over {} counted row(s): {adjudicated} adjudicated, {unadjudicated} not (recheck {}, unobserved {})",
3246 adjudicated + unadjudicated,
3247 self.recheck,
3248 self.unobserved
3249 );
3250 if self.dangling > 0 {
3251 s.push_str(&format!(
3252 "; {} row(s) excluded, naming an entity the mem no longer holds",
3253 self.dangling
3254 ));
3255 }
3256 if let Some(why) = &self.unreconciled {
3257 s.push_str(&format!(
3258 "; the entity end was NOT reconciled ({why}), so dangling rows would not have been detected"
3259 ));
3260 }
3261 // False means the figures rest on an incomplete measurement, which
3262 // is not the same as a failed one.
3263 let fully_adjudicated =
3264 self.recheck == 0 && self.unobserved == 0 && self.unreconciled.is_none();
3265 crate::anchor::AnchorResolutionFigure::new(resolves, s, fully_adjudicated)
3266 .expect("the population statement is never empty")
3267 }
3268}
3269
3270/// One anchor's verification row.
3271#[derive(Debug, Clone, serde::Serialize)]
3272pub struct VerifiedAnchor {
3273 pub entity_id: String,
3274 pub artifact: String,
3275 pub grain: String,
3276 pub class: String,
3277 /// `resolves` | `drifted` | `recheck` | `unresolvable` (artifact gone) |
3278 /// `unobserved` (not measured this pass) | `dangling` (the entity is
3279 /// gone). The wire vocabulary of this field, which is NOT the engine's
3280 /// `AnchorState` enum: that has four variants describing the artifact
3281 /// end, and the last two here are conditions beside them.
3282 pub state: String,
3283 #[serde(skip_serializing_if = "Option::is_none")]
3284 pub observed_hash: Option<String>,
3285 /// When the observation this row's state rests on was made — present
3286 /// only for a row resolved from a supplied or recorded observation (a
3287 /// `url` row); live observations carry none.
3288 #[serde(skip_serializing_if = "Option::is_none")]
3289 pub observed_at: Option<String>,
3290 /// Whole days between `observed_at` and this run — how long the row has
3291 /// gone unobserved. `Some(0)` for an observation made today.
3292 #[serde(skip_serializing_if = "Option::is_none")]
3293 pub unobserved_for_days: Option<u64>,
3294 /// Whether this row's state came from an observation supplied to this
3295 /// run (as opposed to a live or a previously recorded one).
3296 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3297 pub observation_supplied: bool,
3298}
3299
3300/// Whether `anchor` references `path`. `tree`-grain anchors match `path`
3301/// itself and anything beneath the tree; every other grain matches by
3302/// exact base-path equality.
3303/// A stored anchor paired with its live resolution state, when observable.
3304/// See [`Engine::entity_anchors_resolved`] for how `state` is produced and
3305/// when it is `None` (unobserved, never fabricated).
3306#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
3307pub struct ResolvedAnchor {
3308 /// The durable anchor record (flattened on the wire so the resolved shape
3309 /// is the stored anchor plus a `state` field).
3310 #[serde(flatten)]
3311 pub anchor: crate::anchor::Anchor,
3312 /// The live resolution state, or `None` when the engine could not observe
3313 /// the source artifact this pass: a `url` grain, no workspace root, an
3314 /// ambiguous or absent path medium, or an `entity` grain whose mem is not
3315 /// mounted. That last case is load-bearing — an unmounted mem is not a mem
3316 /// of deleted entities, so it must read as unobserved rather than
3317 /// `Orphaned`, which prune would act on.
3318 #[serde(skip_serializing_if = "Option::is_none")]
3319 pub state: Option<crate::anchor::AnchorState>,
3320 /// The prepared-content hash the observation computed this pass —
3321 /// present only for a hash-bearing (`anchored` / `derived`) anchor whose
3322 /// artifact could be read: a `file` / `span` anchor resolving to a
3323 /// readable file, or an `entity` anchor whose mem is mounted (hashed over
3324 /// the canonical rendered markdown, so the value means the same thing in
3325 /// both namespaces). The verify pass's backfill leg records it onto a
3326 /// hash-less anchor. Engine-internal
3327 /// observation detail, deliberately not serialized: the wire shape stays
3328 /// the stored anchor plus `state`.
3329 #[serde(skip)]
3330 pub observed_hash: Option<String>,
3331 /// When the observation `state` rests on was made, for a row whose
3332 /// observation is supplied or recorded rather than live (a `url` row).
3333 /// Additive: absent on every live-observed row.
3334 #[serde(skip_serializing_if = "Option::is_none")]
3335 pub observed_at: Option<String>,
3336}
3337
3338/// What an anchor's `source` name resolves to in its mem's bindings: the
3339/// declared pointer (the filesystem root a source-dialect artifact path
3340/// joins onto, decision 26) and the declared preparation (what the
3341/// preparation registry prepares the artifact as before hashing —
3342/// touchpoint A of [`crate::preparation`]).
3343#[derive(Debug, Clone, PartialEq, Eq)]
3344pub(crate) struct AnchorSourceJoin {
3345 /// The source's declared `pointer`.
3346 pub(crate) pointer: String,
3347 /// The source's declared `preparation`, if any.
3348 pub(crate) preparation: Option<String>,
3349 /// The declaring source itself — its scope is what a `tree` anchor's
3350 /// prepared form enumerates under a code-map preparation.
3351 pub(crate) source: crate::pipeline::Source,
3352 /// The binding's `deny_paths`, applied on top of the source scope.
3353 pub(crate) deny_paths: Vec<String>,
3354}
3355
3356/// Observe a single path-namespace anchor against `root` (its medium's
3357/// filesystem root) and resolve its live state plus — for a present
3358/// hash-bearing (`anchored` / `derived`) `file` / `span` anchor — the
3359/// artifact's **prepared-content hash**
3360/// ([`crate::anchor::prepared_content_hash`]). `None` when the anchor's
3361/// grain does not reference a filesystem path.
3362///
3363/// The computed hash is what lets [`crate::anchor::resolve_anchor`]
3364/// adjudicate `drifted` vs `resolves` deterministically against the recorded
3365/// hash. The prepared form is the registry's rule for the anchor's
3366/// source's preparation ([`crate::preparation::path_prepared_hash`]): a
3367/// `span` anchor hashes its whole containing file (the span locator selects
3368/// within it; the file is the hashed unit), except under a **delivery
3369/// preparation**, where a `<path>#<key>` span names one delivery unit (the
3370/// unit's own text is the hashed unit, and a key the file no longer yields
3371/// is an absent artifact); under a **code-map** preparation a file or span
3372/// hashes the interface digest, and a `tree` hashes the code map of every
3373/// scoped file under it. A `tree` under any other preparation hashes the
3374/// plain per-file prepared-content map of its scoped files, so tree anchors
3375/// adjudicate deterministically like file anchors. A `tree` with no
3376/// resolvable source-join (the enumeration scope is undefined without one),
3377/// a partial enumeration, and a read failure observe no hash — those
3378/// resolve `recheck`, never a fabricated `drifted`. Non-hash classes
3379/// (`authored` / `informed-by`) skip the read entirely, so an anchor-less or
3380/// hash-free mem pays no observation cost.
3381fn observe_path_anchor(
3382 root: &Path,
3383 anchor: &crate::anchor::Anchor,
3384 join: Option<&AnchorSourceJoin>,
3385) -> Option<(crate::anchor::AnchorState, Option<String>)> {
3386 use crate::anchor::AnchorGrain;
3387 match anchor.grain {
3388 AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => {}
3389 AnchorGrain::Url | AnchorGrain::Entity => return None,
3390 }
3391 let source_pointer = join.map(|j| j.pointer.as_str());
3392 let preparation = join.and_then(|j| j.preparation.as_deref());
3393 let base = anchor_base_path(&anchor.artifact);
3394 // Decision 29: the source-join is authoritative — an artifact path is
3395 // source-relative first (joined onto the declaring source's pointer,
3396 // which may deliberately leave the workspace root for out-of-root
3397 // pointers); the workspace-relative form is tried only when the
3398 // source-join does not resolve. The candidate set is the shared
3399 // [`artifact_candidates`] rule, so resolution, the write gate, and the
3400 // population matcher read one artifact the same way.
3401 let path = {
3402 let candidates = artifact_candidates(source_pointer.unwrap_or(""), base);
3403 candidates
3404 .iter()
3405 .map(|c| root.join(c))
3406 .find(|p| p.exists())
3407 .unwrap_or_else(|| root.join(base))
3408 };
3409 if !path.exists() {
3410 return Some((
3411 crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
3412 None,
3413 ));
3414 }
3415 let current_hash = if !anchor.class.is_hash_bearing() {
3416 None
3417 } else if matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span) && path.is_file() {
3418 match std::fs::read(&path).ok().map(|bytes| {
3419 crate::preparation::path_prepared_hash(
3420 preparation,
3421 &anchor.artifact,
3422 anchor.grain,
3423 &bytes,
3424 )
3425 }) {
3426 Some(crate::preparation::PathPrepared::Hash(h)) => Some(h),
3427 Some(crate::preparation::PathPrepared::UnitAbsent) => {
3428 return Some((
3429 crate::anchor::resolve_anchor(
3430 anchor,
3431 &crate::anchor::ArtifactObservation::Absent,
3432 ),
3433 None,
3434 ));
3435 }
3436 Some(crate::preparation::PathPrepared::NoHash) | None => None,
3437 }
3438 } else if anchor.grain == AnchorGrain::Tree
3439 && path.is_dir()
3440 && let Some(join) = join
3441 {
3442 // The tree's prepared form: a digest over every scoped file under
3443 // the tree, by the declaring source's own scope and the binding's
3444 // deny paths — the code map under a code-map preparation, the plain
3445 // per-file prepared-content map otherwise, so a tree anchor
3446 // adjudicates deterministically instead of resting in `recheck`
3447 // forever. The path the anchor names is workspace-relative or
3448 // source-relative; the enumeration is workspace-relative, so compare
3449 // the resolved absolute paths. A PARTIAL enumeration (malformed or
3450 // retired-dialect scope pattern) observes no hash — a digest over a
3451 // set that is not the population would silently change a stored
3452 // tree-anchor hash; no-hash resolves `recheck`, the same posture as
3453 // a failed read.
3454 let enumeration = crate::ingest::cursor::enumerate_facet_files_reported(
3455 &join.source,
3456 &join.deny_paths,
3457 root,
3458 );
3459 if enumeration.is_partial() {
3460 None
3461 } else if preparation == Some(crate::preparation::CODE_MAP) {
3462 let files: Vec<(String, String)> = enumeration
3463 .files
3464 .into_iter()
3465 .filter(|f| root.join(f).starts_with(&path))
3466 .filter_map(|f| {
3467 std::fs::read(root.join(&f))
3468 .ok()
3469 .map(|bytes| (f, String::from_utf8_lossy(&bytes).into_owned()))
3470 })
3471 .collect();
3472 Some(crate::anchor::prepared_content_hash(
3473 crate::preparation::code_map_tree_digest(&files).as_bytes(),
3474 ))
3475 } else {
3476 let files: Vec<(String, Vec<u8>)> = enumeration
3477 .files
3478 .into_iter()
3479 .filter(|f| root.join(f).starts_with(&path))
3480 .filter_map(|f| std::fs::read(root.join(&f)).ok().map(|bytes| (f, bytes)))
3481 .collect();
3482 Some(crate::anchor::prepared_content_hash(
3483 crate::preparation::plain_tree_digest(&files).as_bytes(),
3484 ))
3485 }
3486 } else {
3487 None
3488 };
3489 let observation = crate::anchor::ArtifactObservation::Present {
3490 current_hash: current_hash.clone(),
3491 };
3492 Some((
3493 crate::anchor::resolve_anchor(anchor, &observation),
3494 current_hash,
3495 ))
3496}
3497
3498/// Deterministic fingerprint of a PARSED schema for the
3499/// authoring-drift equivalence check. Compares semantic content, never
3500/// raw bytes: YAML comments (the CLI-injected editor-header lines) and
3501/// whitespace vanish at parse time, and `Schema.types` — a `HashMap`
3502/// with nondeterministic iteration order — is rendered sorted by type
3503/// name so two loads of equivalent packages always fingerprint alike.
3504fn schema_parsed_fingerprint(schema: &memstead_schema::Schema) -> String {
3505 let mut keys: Vec<&String> = schema.types.keys().collect();
3506 keys.sort();
3507 let types: Vec<String> = keys
3508 .iter()
3509 .map(|k| format!("{k}={:?}", schema.types[k.as_str()]))
3510 .collect();
3511 format!(
3512 "{:?}|{}|{}",
3513 schema.manifest,
3514 schema.version,
3515 types.join(";")
3516 )
3517}
3518
3519fn anchor_references_path(anchor: &crate::anchor::Anchor, path: &str) -> bool {
3520 let base = anchor_base_path(&anchor.artifact);
3521 path_references(base, anchor.grain == crate::anchor::AnchorGrain::Tree, path)
3522}
3523
3524/// Whether `base` (a file path, or a tree root when `is_tree`) references
3525/// `path` — exact match, or containment for a tree.
3526fn path_references(base: &str, is_tree: bool, path: &str) -> bool {
3527 if base == path {
3528 return true;
3529 }
3530 if is_tree {
3531 let prefix = base.strip_suffix('/').unwrap_or(base);
3532 return path.starts_with(&format!("{prefix}/"));
3533 }
3534 false
3535}
3536
3537/// Join a source pointer and a source-relative artifact path into the
3538/// pointer-joined (workspace-relative) form — the decision-26 dialect
3539/// bridge. Plain string concatenation with a separator: the pointer is
3540/// workspace-relative (and may climb out via `..`), the artifact is
3541/// source-relative; no canonicalization here, the filesystem resolves it.
3542pub(crate) fn join_pointer(pointer: &str, base: &str) -> String {
3543 let pointer = pointer.trim_end_matches('/');
3544 if pointer.is_empty() || pointer == "." {
3545 base.to_string()
3546 } else {
3547 format!("{pointer}/{base}")
3548 }
3549}
3550
3551/// How a source-relative artifact id resolved ACROSS a binding's primary
3552/// sources — the cross-source counterpart of [`artifact_candidates`], which
3553/// answers only within ONE source.
3554///
3555/// The two questions are genuinely different and only this one can be
3556/// ambiguous. `artifact_candidates` settles which reading wins under a single
3557/// pointer (decision 29: source-join first, workspace-relative fallback). It
3558/// takes one pointer and has no opinion on two sources both carrying
3559/// `docs/a.md`. That case has exactly one home, the exclude fold, and used to
3560/// take the first source that matched — so the source listed first in the
3561/// binding silently won, which is the wrong-target write this type exists to
3562/// prevent.
3563#[derive(Debug, Clone, PartialEq, Eq)]
3564pub(crate) enum CrossSourceArtifact {
3565 /// No source's join lands on a member of the enumerated set.
3566 Unresolved,
3567 /// Exactly one does; this is the canonical id to record.
3568 Unique(String),
3569 /// Several do. Sorted and deduplicated, so the refusal names them in a
3570 /// stable order and the caller never has to pick.
3571 Ambiguous(Vec<String>),
3572}
3573
3574/// Resolve a requested artifact id against a binding's primary sources.
3575///
3576/// `canonical_for` maps one source's base and the requested id to the
3577/// workspace-relative form, returning `None` when that form is not a member
3578/// of the enumerated source set. The caller owns that predicate because the
3579/// membership test differs by surface; what is shared, and what lives here,
3580/// is the rule that several matches are an ambiguity to refuse rather than a
3581/// choice to make silently.
3582pub(crate) fn resolve_across_sources<'a, I, F>(
3583 bases: I,
3584 requested: &str,
3585 canonical_for: F,
3586) -> CrossSourceArtifact
3587where
3588 I: IntoIterator<Item = &'a std::path::PathBuf>,
3589 F: Fn(&std::path::PathBuf, &str) -> Option<String>,
3590{
3591 let mut hits: Vec<String> = bases
3592 .into_iter()
3593 .filter_map(|base| canonical_for(base, requested))
3594 .collect();
3595 hits.sort();
3596 hits.dedup();
3597 match hits.len() {
3598 0 => CrossSourceArtifact::Unresolved,
3599 1 => CrossSourceArtifact::Unique(hits.remove(0)),
3600 _ => CrossSourceArtifact::Ambiguous(hits),
3601 }
3602}
3603
3604/// The candidate workspace-relative forms an anchor artifact could denote
3605/// under its declaring source's pointer, in the ratified priority (bundle
3606/// decision 29): the source-join first, the workspace-relative form as the
3607/// fallback. **The single implementation of that rule** — resolution, the
3608/// write-time gate, and the population scope matcher all construct their
3609/// candidate set here, so one artifact cannot read differently across the
3610/// three (each site then applies its own predicate: existence for
3611/// resolution and the gate, glob membership for the matcher).
3612///
3613/// One lexical clarification rides with the rule: an artifact that climbs
3614/// (`../…`) never joins. An artifact of a source never climbs OUT of that
3615/// source, so such a path is already the workspace-relative form; joining
3616/// anyway fabricates `<ptr>/../…`, which the filesystem then resolves into a
3617/// sibling tree — a false resolution for an existence test and a false
3618/// in-scope for a `**` glob. An artifact already carrying the pointer prefix
3619/// is NOT suppressed: on a self-nested layout both readings exist and the
3620/// decision's priority — source-join wins — settles it deterministically.
3621pub(crate) fn artifact_candidates(pointer: &str, base: &str) -> Vec<String> {
3622 let pointer = pointer.trim_end_matches('/');
3623 if pointer.is_empty() || pointer == "." {
3624 return vec![base.to_string()];
3625 }
3626 if base.starts_with("../") || base == ".." {
3627 return vec![base.to_string()];
3628 }
3629 vec![format!("{pointer}/{base}"), base.to_string()]
3630}
3631
3632#[cfg(test)]
3633mod tests {
3634 use std::path::Path;
3635
3636 use tempfile::TempDir;
3637
3638 use crate::backend::{BackendError, MemBackend};
3639 use crate::engine::test_helpers::*;
3640 use crate::engine::{Engine, EngineError, RelateEntityArgs};
3641 use crate::entity::EntityId;
3642 use crate::ops::{Direction, SearchScope, WarningHint};
3643 use crate::provenance::Provenance;
3644 use crate::storage::{ArchiveBackend, FilesystemMemWriter, MemWriter};
3645
3646 use crate::vcs::CommitContext;
3647 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
3648
3649 /// The shared decision-29 candidate rule: source-join first,
3650 /// workspace-relative fallback; a pointer-less (or `.`) source has one
3651 /// reading; a climbing `../…` artifact never joins (the fabricated
3652 /// `<ptr>/../…` would resolve into a sibling tree).
3653 #[test]
3654 fn artifact_candidates_follow_decision_29_priority() {
3655 use super::artifact_candidates;
3656 assert_eq!(artifact_candidates("", "a/b.rs"), vec!["a/b.rs"]);
3657 assert_eq!(artifact_candidates(".", "a/b.rs"), vec!["a/b.rs"]);
3658 assert_eq!(artifact_candidates("./", "a/b.rs"), vec!["a/b.rs"]);
3659 assert_eq!(
3660 artifact_candidates("sub", "a/b.rs"),
3661 vec!["sub/a/b.rs", "a/b.rs"]
3662 );
3663 assert_eq!(
3664 artifact_candidates("sub/", "a/b.rs"),
3665 vec!["sub/a/b.rs", "a/b.rs"]
3666 );
3667 // Self-nesting is settled by priority, not suppression: the artifact
3668 // already carrying the pointer prefix still offers the join first.
3669 assert_eq!(
3670 artifact_candidates("sub", "sub/x.rs"),
3671 vec!["sub/sub/x.rs", "sub/x.rs"]
3672 );
3673 // A climbing artifact is already the workspace-relative form.
3674 assert_eq!(
3675 artifact_candidates("sub", "../dev/x.md"),
3676 vec!["../dev/x.md"]
3677 );
3678 assert_eq!(
3679 artifact_candidates("../dev", "../dev/x.md"),
3680 vec!["../dev/x.md"]
3681 );
3682 assert_eq!(artifact_candidates("sub", ".."), vec![".."]);
3683 }
3684
3685 /// `schema_origin` is the trust-classification authority: a built-in
3686 /// (or workspace-authored) schema is first-party; a schema whose
3687 /// `(name, version)` is in neither catalogue is third-party — the safe
3688 /// default for an origin the engine cannot vouch for.
3689 #[test]
3690 fn schema_origin_classifies_builtin_first_party_and_unknown_third_party() {
3691 use std::sync::Arc;
3692
3693 use crate::render::OriginClass;
3694
3695 let tmp = TempDir::new().unwrap();
3696 let engine = Engine::from_mounts(vec![(
3697 folder_mount("specs", tmp.path().to_path_buf()),
3698 Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf())) as Box<dyn MemBackend>,
3699 )])
3700 .unwrap();
3701
3702 // A built-in schema (the catalogue the engine resolved against).
3703 let builtin = engine.builtin_schemas()[0].clone();
3704 assert_eq!(
3705 engine.schema_origin(&builtin),
3706 OriginClass::FirstParty,
3707 "a built-in schema is first-party"
3708 );
3709
3710 // A schema whose version is in no catalogue — a stand-in for a
3711 // schema that entered from outside the workspace. Same name, a
3712 // version the engine never loaded.
3713 let foreign = Arc::new(memstead_schema::Schema {
3714 manifest: builtin.manifest.clone(),
3715 version: semver::Version::new(99, 0, 0),
3716 types: builtin.types.clone(),
3717 });
3718 assert_eq!(
3719 engine.schema_origin(&foreign),
3720 OriginClass::ThirdParty,
3721 "a schema in neither catalogue classifies third-party (safe default)"
3722 );
3723 }
3724
3725 /// `mem_origin_class` classifies a writable mount first-party (its
3726 /// content is authored in this workspace) and a read-only mount
3727 /// third-party (registry-installed read-mem or adopted foreign
3728 /// folder/clone — quoted, untrusted data). An unknown mem is
3729 /// third-party (the safe default).
3730 #[test]
3731 fn mem_origin_class_writable_first_party_readonly_third_party() {
3732 use crate::render::OriginClass;
3733
3734 let tmp = TempDir::new().unwrap();
3735 // Writable folder mem.
3736 let writable_dir = tmp.path().join("writable");
3737 std::fs::create_dir_all(&writable_dir).unwrap();
3738 let writer = FilesystemMemWriter::new(writable_dir.clone());
3739
3740 // Read-only archive mem.
3741 let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
3742 let archive_path = build_archive(tmp.path(), "ext", &[("ext.md", body.as_bytes())]);
3743
3744 let engine = Engine::from_mounts(vec![
3745 (
3746 folder_mount("local", writable_dir),
3747 Box::new(writer) as Box<dyn MemBackend>,
3748 ),
3749 (
3750 archive_mount("external", archive_path.clone()),
3751 Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
3752 ),
3753 ])
3754 .unwrap();
3755
3756 assert_eq!(
3757 engine.mem_origin_class("local"),
3758 OriginClass::FirstParty,
3759 "a writable mount is first-party"
3760 );
3761 assert_eq!(
3762 engine.mem_origin_class("external"),
3763 OriginClass::ThirdParty,
3764 "a read-only mount is third-party"
3765 );
3766 assert_eq!(
3767 engine.mem_origin_class("no-such-mem"),
3768 OriginClass::ThirdParty,
3769 "an unknown mem is third-party (safe default)"
3770 );
3771 }
3772
3773 /// `declare_mem_origin` lets the embedding deployment vouch for one
3774 /// read-only mount as first-party (the curated hosted read tier),
3775 /// overriding the writability inference for that mem only — sibling
3776 /// read-only mounts keep the safe third-party default.
3777 #[test]
3778 fn declared_origin_overrides_inference_per_mem() {
3779 use crate::render::OriginClass;
3780
3781 let tmp = TempDir::new().unwrap();
3782 let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
3783 let vouched_path = build_archive(tmp.path(), "vouched", &[("v.md", body.as_bytes())]);
3784 let other_path = build_archive(tmp.path(), "other", &[("o.md", body.as_bytes())]);
3785
3786 let mut engine = Engine::from_mounts(vec![
3787 (
3788 archive_mount("vouched", vouched_path.clone()),
3789 Box::new(ArchiveBackend::new(vouched_path)) as Box<dyn MemBackend>,
3790 ),
3791 (
3792 archive_mount("other", other_path.clone()),
3793 Box::new(ArchiveBackend::new(other_path)) as Box<dyn MemBackend>,
3794 ),
3795 ])
3796 .unwrap();
3797
3798 engine.declare_mem_origin("vouched", OriginClass::FirstParty);
3799
3800 assert_eq!(
3801 engine.mem_origin_class("vouched"),
3802 OriginClass::FirstParty,
3803 "the deployment's declaration wins over the read-only inference"
3804 );
3805 assert_eq!(
3806 engine.mem_origin_class("other"),
3807 OriginClass::ThirdParty,
3808 "an undeclared sibling mount keeps the safe default"
3809 );
3810 }
3811
3812 /// The adopt-gate: a non-built-in schema is first-party only once a
3813 /// writable mount pins it (the operator authors against it here).
3814 /// Pinned only by a read-only mount — a registry read-mem or an
3815 /// adopted foreign folder/clone — it stays third-party, so
3816 /// `memstead_schema` serves it structural-only.
3817 #[test]
3818 fn schema_origin_third_party_until_pinned_by_a_writable_mount() {
3819 use memstead_schema::SchemaRef;
3820
3821 use crate::render::OriginClass;
3822
3823 let manifest = r#"name: trust-test
3824version: 0.1.0
3825description: adopt-gate test schema
3826when_to_use: tests
3827types:
3828 - doc
3829relationships:
3830 mode: strict
3831 definitions:
3832 - name: _default
3833 description: fallback
3834 default_weight: 1.0
3835community:
3836 resolution: 1.0
3837 seed: 42
3838"#;
3839 let pin = SchemaRef::new("trust-test", semver::Version::new(0, 1, 0));
3840
3841 let mk_engine = |cap: MountCapability| -> Engine {
3842 let tmp = TempDir::new().unwrap();
3843 let schemas_dir = tmp.path().join("schemas");
3844 std::fs::create_dir_all(&schemas_dir).unwrap();
3845 write_schema_files_with_default_type(&schemas_dir, "trust-test", manifest, &["doc"]);
3846 let mem_dir = tmp.path().join("mem");
3847 std::fs::create_dir_all(&mem_dir).unwrap();
3848 let mount = Mount {
3849 mem: "v".to_string(),
3850 schema: Some(pin.clone()),
3851 storage: MountStorage::Folder {
3852 path: mem_dir.clone(),
3853 },
3854 capability: cap,
3855 lifecycle: MountLifecycle::Eager,
3856 cross_linkable: true,
3857 migration_target: None,
3858 };
3859 let backend = Box::new(FilesystemMemWriter::new(mem_dir)) as Box<dyn MemBackend>;
3860 // Keep `tmp` alive for the engine's lifetime by leaking it —
3861 // the test process is short-lived and the folder must outlast
3862 // the closure.
3863 std::mem::forget(tmp);
3864 Engine::from_mounts_with_schemas_dir(vec![(mount, backend)], Some(&schemas_dir))
3865 .unwrap()
3866 };
3867
3868 // Read-only mount: the foreign schema is never adopted → third-party.
3869 let ro = mk_engine(MountCapability::ReadOnly);
3870 let schema = ro.schemas().get("v").expect("schema resolved").clone();
3871 assert_eq!(
3872 ro.schema_origin(&schema),
3873 OriginClass::ThirdParty,
3874 "a non-built-in schema pinned only by a read-only mount is third-party"
3875 );
3876
3877 // Writable mount pinning the same schema: adopted → first-party.
3878 let rw = mk_engine(MountCapability::Write);
3879 let schema = rw.schemas().get("v").expect("schema resolved").clone();
3880 assert_eq!(
3881 rw.schema_origin(&schema),
3882 OriginClass::FirstParty,
3883 "a writable mount pinning the schema adopts it → first-party"
3884 );
3885 }
3886
3887 /// Consumer read path: an installed (archive-backed) mem that ships
3888 /// a `.memstead/provenance.json` payload surfaces per-entity authoring
3889 /// provenance through `archive_provenance_for`. A noted entity carries
3890 /// its rationale; an entity authored without a note is absent from the
3891 /// payload and reads as provenance-absent (no fabricated value); the
3892 /// `history` disposition records that full history is not shipped.
3893 #[test]
3894 fn archive_provenance_surfaces_per_entity_and_reports_absence() {
3895 use memstead_schema::History;
3896
3897 let tmp = TempDir::new().unwrap();
3898 let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
3899 let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
3900 let beta = b"---\ntype: spec\n---\n# Beta\n\n## Identity\n\nb\n\n## Purpose\n\np\n";
3901 // alpha noted; beta deliberately absent from the payload.
3902 let provenance = br#"{"format":1,"history":"summarised","entities":{"alpha":{"rationale":"why alpha exists","kind":"create","timestamp":"2026-06-24T00:00:00Z","actor":"agent"}}}"#;
3903 let archive = build_archive(
3904 tmp.path(),
3905 "seed",
3906 &[
3907 (".memstead/config.json", config),
3908 ("alpha.md", alpha),
3909 ("beta.md", beta),
3910 (".memstead/provenance.json", provenance),
3911 ],
3912 );
3913 let engine = Engine::from_mounts(vec![(
3914 archive_mount("seed", archive.clone()),
3915 Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
3916 )])
3917 .unwrap();
3918
3919 let prov = engine
3920 .archive_provenance_for("seed")
3921 .expect("provenance payload read from the archive");
3922 assert_eq!(
3923 prov.history,
3924 History::Summarised,
3925 "history-not-shipped is observable"
3926 );
3927 assert_eq!(
3928 prov.entity("alpha").and_then(|r| r.rationale.as_deref()),
3929 Some("why alpha exists"),
3930 "noted entity surfaces its rationale"
3931 );
3932 assert!(
3933 prov.entity("beta").is_none(),
3934 "unnoted entity is absent (reported absent, not fabricated)"
3935 );
3936 }
3937
3938 /// A pre-provenance archive (no `.memstead/provenance.json`) reads as
3939 /// provenance uniformly absent — the additive contract: a newer engine
3940 /// installing an old archive reports no provenance, never an error.
3941 #[test]
3942 fn archive_without_provenance_reports_absent() {
3943 let tmp = TempDir::new().unwrap();
3944 let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
3945 let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
3946 let archive = build_archive(
3947 tmp.path(),
3948 "seed",
3949 &[(".memstead/config.json", config), ("alpha.md", alpha)],
3950 );
3951 let engine = Engine::from_mounts(vec![(
3952 archive_mount("seed", archive.clone()),
3953 Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
3954 )])
3955 .unwrap();
3956 assert!(
3957 engine.archive_provenance_for("seed").is_none(),
3958 "an archive without a provenance payload reports provenance absent"
3959 );
3960 }
3961
3962 #[test]
3963 fn folder_mount_routes_reads_to_filesystem_backend() {
3964 let tmp = TempDir::new().unwrap();
3965 let mem_dir = tmp.path().to_path_buf();
3966 let writer = FilesystemMemWriter::new(mem_dir.clone());
3967 // MemWriter and MemBackend share method names; the
3968 // module-top `use` brings both into scope. Seed via fully-
3969 // qualified MemWriter calls so dot-syntax stays unambiguous.
3970 <FilesystemMemWriter as MemWriter>::write_entity(&writer, Path::new("a.md"), b"alpha")
3971 .unwrap();
3972 <FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
3973 .unwrap();
3974
3975 let engine = Engine::from_mounts(vec![(
3976 folder_mount("specs", mem_dir),
3977 Box::new(writer) as Box<dyn MemBackend>,
3978 )])
3979 .unwrap();
3980
3981 let mut paths: Vec<String> = engine
3982 .list_entities("specs")
3983 .unwrap()
3984 .into_iter()
3985 .map(|p| p.to_string_lossy().into_owned())
3986 .collect();
3987 paths.sort();
3988 assert_eq!(paths, vec!["a.md".to_string()]);
3989
3990 assert_eq!(
3991 engine.read_entity("specs", Path::new("a.md")).unwrap(),
3992 Some(b"alpha".to_vec())
3993 );
3994 }
3995
3996 #[test]
3997 fn heterogeneous_mounts_route_to_correct_backend() {
3998 let tmp = TempDir::new().unwrap();
3999
4000 // Folder mem.
4001 let folder_dir = tmp.path().join("folder-mem");
4002 std::fs::create_dir_all(&folder_dir).unwrap();
4003 let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
4004 <FilesystemMemWriter as MemWriter>::write_entity(
4005 &folder_writer,
4006 Path::new("local.md"),
4007 b"local",
4008 )
4009 .unwrap();
4010 <FilesystemMemWriter as MemWriter>::commit(
4011 &folder_writer,
4012 "seed",
4013 &CommitContext::internal(),
4014 )
4015 .unwrap();
4016
4017 // Archive mem.
4018 let archive_path = build_archive(
4019 tmp.path(),
4020 "external",
4021 &[("ext.md", b"external"), ("dir/nested.md", b"nested")],
4022 );
4023
4024 let engine = Engine::from_mounts(vec![
4025 (
4026 folder_mount("local", folder_dir),
4027 Box::new(folder_writer) as Box<dyn MemBackend>,
4028 ),
4029 (
4030 archive_mount("external", archive_path.clone()),
4031 Box::new(ArchiveBackend::new(archive_path)),
4032 ),
4033 ])
4034 .unwrap();
4035
4036 // Routes correctly by mem name.
4037 assert_eq!(engine.mem_names(), vec!["local", "external"]);
4038 assert_eq!(
4039 engine.read_entity("local", Path::new("local.md")).unwrap(),
4040 Some(b"local".to_vec())
4041 );
4042 assert_eq!(
4043 engine.read_entity("external", Path::new("ext.md")).unwrap(),
4044 Some(b"external".to_vec())
4045 );
4046 assert_eq!(
4047 engine
4048 .read_entity("external", Path::new("dir/nested.md"))
4049 .unwrap(),
4050 Some(b"nested".to_vec())
4051 );
4052 // Cross-routing: reading a path from the wrong mem → None
4053 // (the backend doesn't have it), not an error.
4054 assert_eq!(
4055 engine.read_entity("local", Path::new("ext.md")).unwrap(),
4056 None
4057 );
4058 assert_eq!(
4059 engine
4060 .read_entity("external", Path::new("local.md"))
4061 .unwrap(),
4062 None
4063 );
4064 }
4065
4066 #[test]
4067 fn edge_is_from_readonly_classifies_every_edge_by_source_mount_capability() {
4068 // `engine.edge_is_from_readonly` is the derived-on-demand
4069 // alternative to adding a per-edge marker: construct a mixed
4070 // workspace (one Write-Mem + one ReadOnly archive with
4071 // cross-mem wiki-links) and walk every edge in the store,
4072 // asserting each edge's source-mount capability.
4073 let tmp = TempDir::new().unwrap();
4074
4075 // Write folder mem `local` with a spec-shaped entity that
4076 // declares an explicit cross-mem relation into the archive
4077 // (under the alias model edges originate from `## Relationships`).
4078 let folder_dir = tmp.path().join("local-mem");
4079 std::fs::create_dir_all(&folder_dir).unwrap();
4080 let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
4081 let local_md = b"---\ntype: spec\n---\n# Note\n\n## Identity\n\nsee [[external:archived]] for prior context.\n\n## Relationships\n\n- **REFERENCES**: [[external:archived]]\n";
4082 <FilesystemMemWriter as MemWriter>::write_entity(
4083 &folder_writer,
4084 Path::new("note.md"),
4085 local_md,
4086 )
4087 .unwrap();
4088 <FilesystemMemWriter as MemWriter>::commit(
4089 &folder_writer,
4090 "seed",
4091 &CommitContext::internal(),
4092 )
4093 .unwrap();
4094
4095 // ReadOnly archive mem `external` with a spec-shaped entity
4096 // declaring an explicit cross-mem relation back to the local
4097 // note.
4098 let archive_md = b"---\ntype: spec\n---\n# Archived\n\n## Identity\n\nrefers back to [[local:note]] for the current revision.\n\n## Relationships\n\n- **REFERENCES**: [[local:note]]\n";
4099 let archive_path = build_archive(tmp.path(), "external", &[("archived.md", archive_md)]);
4100
4101 let engine = Engine::from_mounts(vec![
4102 (
4103 folder_mount("local", folder_dir),
4104 Box::new(folder_writer) as Box<dyn MemBackend>,
4105 ),
4106 (
4107 archive_mount("external", archive_path.clone()),
4108 Box::new(ArchiveBackend::new(archive_path)),
4109 ),
4110 ])
4111 .unwrap();
4112
4113 // Sanity: both entities are real, both mems are mounted.
4114 let local_id = EntityId::new("local", "note");
4115 let archived_id = EntityId::new("external", "archived");
4116 assert!(engine.get_entity(&local_id).is_some());
4117 assert!(engine.get_entity(&archived_id).is_some());
4118 assert!(matches!(
4119 engine.capability("local").unwrap(),
4120 MountCapability::Write
4121 ));
4122 assert!(matches!(
4123 engine.capability("external").unwrap(),
4124 MountCapability::ReadOnly
4125 ));
4126
4127 // Walk every edge in the store. For each (from, edge) pair,
4128 // `edge_is_from_readonly(from)` must return true iff the
4129 // source mount's capability is ReadOnly. The fixture's two
4130 // wiki-links produce one edge from each mem — both halves
4131 // exercise both branches of the helper.
4132 let mut seen_write_edge = false;
4133 let mut seen_readonly_edge = false;
4134 for from in engine.store().all_ids().cloned().collect::<Vec<_>>() {
4135 for _edge in engine.store().outgoing(&from) {
4136 let is_ro = engine.edge_is_from_readonly(&from);
4137 match engine.capability(from.mem()).unwrap() {
4138 MountCapability::Write => {
4139 assert!(
4140 !is_ro,
4141 "edge from write mem {} reported as ReadOnly",
4142 from.mem()
4143 );
4144 seen_write_edge = true;
4145 }
4146 MountCapability::ReadOnly => {
4147 assert!(
4148 is_ro,
4149 "edge from readonly mem {} reported as Write",
4150 from.mem()
4151 );
4152 seen_readonly_edge = true;
4153 }
4154 }
4155 }
4156 }
4157 assert!(
4158 seen_write_edge,
4159 "fixture must produce at least one edge from a write mem"
4160 );
4161 assert!(
4162 seen_readonly_edge,
4163 "fixture must produce at least one edge from a readonly mem"
4164 );
4165
4166 // Helper also reports `false` for mems absent from the
4167 // router — no mount → no ReadOnly assertion can be made.
4168 let phantom = EntityId::new("missing-mem", "phantom");
4169 assert!(
4170 !engine.edge_is_from_readonly(&phantom),
4171 "absent mount must not be reported as ReadOnly"
4172 );
4173 }
4174
4175 // ---- Engine::changes_since wrapper ------------------------------
4176
4177 #[test]
4178 fn cross_mem_link_allowed_same_mem_always_true() {
4179 // Self-edges (from == to) bypass the cross-mem policy
4180 // entirely — the policy gates *cross*-mem edges only.
4181 let tmp = TempDir::new().unwrap();
4182 let engine = build_demo_engine(&tmp);
4183 assert!(engine.cross_mem_link_allowed("specs", "specs"));
4184 // Even when the mem doesn't exist (not enrolled in
4185 // settings.cross_mem_links), same-mem returns true —
4186 // the engine doesn't validate mem existence here, just the
4187 // policy.
4188 assert!(engine.cross_mem_link_allowed("anywhere", "anywhere"));
4189 }
4190
4191 #[test]
4192 fn cross_mem_link_allowed_absent_denies_by_default() {
4193 // No entry in cross_mem_links for `from_mem` → denied.
4194 // Default-deny is the V1 posture; operators opt in.
4195 let tmp = TempDir::new().unwrap();
4196 let engine = build_demo_engine(&tmp);
4197 assert!(!engine.cross_mem_link_allowed("specs", "engine"));
4198 assert!(!engine.cross_mem_link_allowed("missing", "anywhere"));
4199 }
4200
4201 #[test]
4202 fn cross_mem_link_allowed_wildcard_admits_any_target() {
4203 use memstead_schema::workspace_config::CrossLinkValue;
4204 let tmp = TempDir::new().unwrap();
4205 let mut engine = build_demo_engine(&tmp);
4206 let mut settings = crate::workspace::WorkspaceSettings::default();
4207 settings
4208 .cross_mem_links
4209 .insert("specs".to_string(), CrossLinkValue::Wildcard);
4210 engine.set_settings(settings);
4211 assert!(engine.cross_mem_link_allowed("specs", "engine"));
4212 assert!(engine.cross_mem_link_allowed("specs", "macos"));
4213 assert!(engine.cross_mem_link_allowed("specs", "any-other"));
4214 // Reverse direction is independent — no policy entry for
4215 // engine→specs means denied.
4216 assert!(!engine.cross_mem_link_allowed("engine", "specs"));
4217 }
4218
4219 #[test]
4220 fn cross_mem_link_allowed_allowlist_enforces_membership() {
4221 use memstead_schema::workspace_config::CrossLinkValue;
4222 let tmp = TempDir::new().unwrap();
4223 let mut engine = build_demo_engine(&tmp);
4224 let mut settings = crate::workspace::WorkspaceSettings::default();
4225 settings.cross_mem_links.insert(
4226 "specs".to_string(),
4227 CrossLinkValue::List(vec!["engine".to_string(), "macos".to_string()]),
4228 );
4229 engine.set_settings(settings);
4230 assert!(engine.cross_mem_link_allowed("specs", "engine"));
4231 assert!(engine.cross_mem_link_allowed("specs", "macos"));
4232 assert!(!engine.cross_mem_link_allowed("specs", "external"));
4233 }
4234
4235 #[test]
4236 fn cross_mem_link_allowed_synthesises_from_matching_create_rule_wildcard() {
4237 // No explicit cross_mem_links entry, but a create rule
4238 // matches `from_mem` and carries default_cross_links = "*".
4239 // Synthesis grants permission to any target.
4240 use memstead_schema::workspace_config::CrossLinkValue;
4241 let tmp = TempDir::new().unwrap();
4242 let mut engine = build_demo_engine(&tmp);
4243 let mut settings = crate::workspace::WorkspaceSettings::default();
4244 settings
4245 .mem_create_rules
4246 .push(crate::workspace::CreateRuleSetting {
4247 pattern: "exec-*".to_string(),
4248 schemas: vec!["default".to_string()],
4249 default_cross_links: Some(CrossLinkValue::Wildcard),
4250 });
4251 engine.set_settings(settings);
4252 // No explicit policy; synthesis grants permission for any
4253 // target because the rule's value is Wildcard.
4254 assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
4255 assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
4256 // Mem that doesn't match any rule → still denied.
4257 assert!(!engine.cross_mem_link_allowed("orphan", "specs"));
4258 }
4259
4260 /// #42: synthesis matches a hierarchical mem by composing the same
4261 /// `<mem_path>/<name>` candidate the create-rule glob is keyed on,
4262 /// not the bare leaf. Before the fix, `from_mem = "project"` could
4263 /// never match a `memstead/*` rule (the leaf-vs-composed-path
4264 /// divergence), so enforcement denied a link `memstead_overview`
4265 /// rendered as rule-granted.
4266 #[test]
4267 fn cross_mem_link_allowed_synthesises_for_hierarchical_mem() {
4268 use memstead_schema::workspace_config::CrossLinkValue;
4269 let tmp = TempDir::new().unwrap();
4270 let mem_dir = tmp.path().to_path_buf();
4271 // Mount `project` with a hierarchical branch so its `mem_path()`
4272 // is "memstead" and the composed candidate is "memstead/project".
4273 // The Folder backend handles loading; only the Mount's storage
4274 // feeds `mem_path()`.
4275 let mount = Mount {
4276 mem: "project".into(),
4277 schema: Some(pin("default")),
4278 storage: MountStorage::GitBranch {
4279 gitdir: mem_dir.join(".git"),
4280 branch: "memstead/project".into(),
4281 },
4282 capability: MountCapability::Write,
4283 lifecycle: MountLifecycle::Eager,
4284 cross_linkable: true,
4285 migration_target: None,
4286 };
4287 let writer = FilesystemMemWriter::new(mem_dir.clone());
4288 let mut engine =
4289 Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
4290 let mut settings = crate::workspace::WorkspaceSettings::default();
4291 settings
4292 .mem_create_rules
4293 .push(crate::workspace::CreateRuleSetting {
4294 pattern: "memstead/*".to_string(),
4295 schemas: vec!["default".to_string()],
4296 default_cross_links: Some(CrossLinkValue::List(vec!["engine".to_string()])),
4297 });
4298 engine.set_settings(settings);
4299 assert!(
4300 engine.cross_mem_link_allowed("project", "engine"),
4301 "synthesis must match via the composed `memstead/project` candidate"
4302 );
4303 assert!(
4304 !engine.cross_mem_link_allowed("project", "macos"),
4305 "a target outside the rule's default_cross_links is still denied"
4306 );
4307 }
4308
4309 #[test]
4310 fn cross_mem_link_allowed_synthesises_from_matching_create_rule_list() {
4311 // Create rule's default_cross_links is a list — synthesis
4312 // grants permission to listed targets only.
4313 use memstead_schema::workspace_config::CrossLinkValue;
4314 let tmp = TempDir::new().unwrap();
4315 let mut engine = build_demo_engine(&tmp);
4316 let mut settings = crate::workspace::WorkspaceSettings::default();
4317 settings
4318 .mem_create_rules
4319 .push(crate::workspace::CreateRuleSetting {
4320 pattern: "exec-*".to_string(),
4321 schemas: vec!["default".to_string()],
4322 default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
4323 });
4324 engine.set_settings(settings);
4325 assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
4326 // Target not in the synthesised list → denied.
4327 assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
4328 }
4329
4330 #[test]
4331 fn cross_mem_link_allowed_explicit_policy_wins_over_synthesis() {
4332 // Explicit cross_mem_links wildcard fires first; the
4333 // synthesis layer is never consulted (and would deny).
4334 use memstead_schema::workspace_config::CrossLinkValue;
4335 let tmp = TempDir::new().unwrap();
4336 let mut engine = build_demo_engine(&tmp);
4337 let mut settings = crate::workspace::WorkspaceSettings::default();
4338 settings
4339 .cross_mem_links
4340 .insert("exec-foo".to_string(), CrossLinkValue::Wildcard);
4341 // The synthesis layer would deny `exec-foo → engine` (no
4342 // matching rule), but explicit policy returns true first.
4343 engine.set_settings(settings);
4344 assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
4345 }
4346
4347 #[test]
4348 fn cross_mem_link_allowed_synthesis_unions_into_explicit_list() {
4349 // Explicit list = ["specs"]; create rule synthesises = ["macos"].
4350 // Effective allowed targets: union ({specs, macos}).
4351 use memstead_schema::workspace_config::CrossLinkValue;
4352 let tmp = TempDir::new().unwrap();
4353 let mut engine = build_demo_engine(&tmp);
4354 let mut settings = crate::workspace::WorkspaceSettings::default();
4355 settings.cross_mem_links.insert(
4356 "exec-foo".to_string(),
4357 CrossLinkValue::List(vec!["specs".to_string()]),
4358 );
4359 settings
4360 .mem_create_rules
4361 .push(crate::workspace::CreateRuleSetting {
4362 pattern: "exec-*".to_string(),
4363 schemas: vec!["default".to_string()],
4364 default_cross_links: Some(CrossLinkValue::List(vec!["macos".to_string()])),
4365 });
4366 engine.set_settings(settings);
4367 // Explicit allowlist contains specs → allowed.
4368 assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
4369 // Synthesis layer adds macos → allowed.
4370 assert!(engine.cross_mem_link_allowed("exec-foo", "macos"));
4371 // Neither layer allows engine → denied.
4372 assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
4373 }
4374
4375 #[test]
4376 fn cross_mem_link_allowed_set_settings_invalidates_compiled_rule_cache() {
4377 // After set_settings, a fresh policy must be reflected on the
4378 // next call — the lazy memo can't return stale rules.
4379 use memstead_schema::workspace_config::CrossLinkValue;
4380 let tmp = TempDir::new().unwrap();
4381 let mut engine = build_demo_engine(&tmp);
4382
4383 // First settings: a rule allows exec-* → specs via synthesis.
4384 let mut s1 = crate::workspace::WorkspaceSettings::default();
4385 s1.mem_create_rules
4386 .push(crate::workspace::CreateRuleSetting {
4387 pattern: "exec-*".to_string(),
4388 schemas: vec!["default".to_string()],
4389 default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
4390 });
4391 engine.set_settings(s1);
4392 assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
4393
4394 // Replace settings: the rule no longer carries
4395 // default_cross_links. Cache must invalidate so the next
4396 // call sees the new policy.
4397 let mut s2 = crate::workspace::WorkspaceSettings::default();
4398 s2.mem_create_rules
4399 .push(crate::workspace::CreateRuleSetting {
4400 pattern: "exec-*".to_string(),
4401 schemas: vec!["default".to_string()],
4402 default_cross_links: None,
4403 });
4404 engine.set_settings(s2);
4405 assert!(!engine.cross_mem_link_allowed("exec-foo", "specs"));
4406 }
4407
4408 #[test]
4409 fn cross_mem_link_allowed_malformed_glob_falls_back_to_explicit_policy() {
4410 // Malformed pattern in a create rule causes CreateRuleSet
4411 // compilation to fail; the resolver logs and disables
4412 // synthesis, but explicit cross_mem_links still works.
4413 use memstead_schema::workspace_config::CrossLinkValue;
4414 let tmp = TempDir::new().unwrap();
4415 let mut engine = build_demo_engine(&tmp);
4416 let mut settings = crate::workspace::WorkspaceSettings::default();
4417 settings
4418 .mem_create_rules
4419 .push(crate::workspace::CreateRuleSetting {
4420 pattern: "[unclosed".to_string(),
4421 schemas: vec!["default".to_string()],
4422 default_cross_links: Some(CrossLinkValue::Wildcard),
4423 });
4424 // Explicit policy still works.
4425 settings
4426 .cross_mem_links
4427 .insert("specs".to_string(), CrossLinkValue::Wildcard);
4428 engine.set_settings(settings);
4429 // Explicit policy: specs → engine allowed.
4430 assert!(engine.cross_mem_link_allowed("specs", "engine"));
4431 // Synthesis disabled (compilation failed); rule's would-be
4432 // wildcard doesn't apply.
4433 assert!(!engine.cross_mem_link_allowed("orphan", "anything"));
4434 }
4435
4436 #[test]
4437 fn cross_mem_link_allowed_empty_list_denies_all_cross_mem_targets() {
4438 // [cross_mem_links] specs = [] is the explicit
4439 // "intentionally locked down" shape — same effect as
4440 // default-deny but operator-acknowledged.
4441 use memstead_schema::workspace_config::CrossLinkValue;
4442 let tmp = TempDir::new().unwrap();
4443 let mut engine = build_demo_engine(&tmp);
4444 let mut settings = crate::workspace::WorkspaceSettings::default();
4445 settings
4446 .cross_mem_links
4447 .insert("specs".to_string(), CrossLinkValue::List(Vec::new()));
4448 engine.set_settings(settings);
4449 // Same-mem still passes — policy only gates cross-mem.
4450 assert!(engine.cross_mem_link_allowed("specs", "specs"));
4451 // Cross-mem denied to every target.
4452 assert!(!engine.cross_mem_link_allowed("specs", "engine"));
4453 assert!(!engine.cross_mem_link_allowed("specs", "anything"));
4454 }
4455
4456 #[test]
4457 fn from_mounts_load_warnings_merge_into_health_summary() {
4458 let tmp = TempDir::new().unwrap();
4459 let mem_dir = tmp.path().to_path_buf();
4460 let body = "---\ntype: spec\n---\n# Dup2\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
4461 std::fs::write(mem_dir.join("dup2.md"), body).unwrap();
4462
4463 let writer = FilesystemMemWriter::new(mem_dir.clone());
4464 let engine = Engine::from_mounts(vec![(
4465 folder_mount("specs", mem_dir),
4466 Box::new(writer) as Box<dyn MemBackend>,
4467 )])
4468 .unwrap();
4469
4470 let summary = engine.health();
4471 assert!(
4472 summary
4473 .warnings
4474 .iter()
4475 .any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
4476 "health() must merge load_warnings into summary.warnings: {:?}",
4477 summary.warnings,
4478 );
4479 }
4480
4481 #[test]
4482 fn workspace_root_accessor_is_none_for_engine_built_from_mounts() {
4483 let tmp = TempDir::new().unwrap();
4484 let mem_dir = tmp.path().to_path_buf();
4485 let writer = FilesystemMemWriter::new(mem_dir.clone());
4486 // Newest default generation so the clean-boot assertion below
4487 // isn't tripped by the SCHEMA_GENERATIONS_BEHIND hint.
4488 let mut mount = folder_mount("specs", mem_dir);
4489 mount.schema = Some("default@1.3.0".parse().unwrap());
4490 let engine =
4491 Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
4492 assert!(
4493 engine.workspace_root().is_none(),
4494 "from_mounts has no workspace path",
4495 );
4496 // An entity-less mount reports itself empty; nothing else.
4497 assert!(
4498 engine
4499 .load_warnings()
4500 .iter()
4501 .all(|w| w.code() == "MOUNT_UNBACKED"),
4502 "{:?}",
4503 engine.load_warnings()
4504 );
4505 }
4506
4507 #[test]
4508 fn health_omits_outer_repo_warning_when_workspace_root_unset() {
4509 let tmp = TempDir::new().unwrap();
4510 let mem_dir = tmp.path().to_path_buf();
4511 let writer = FilesystemMemWriter::new(mem_dir.clone());
4512 let engine = Engine::from_mounts(vec![(
4513 folder_mount("specs", mem_dir),
4514 Box::new(writer) as Box<dyn MemBackend>,
4515 )])
4516 .unwrap();
4517 let health = engine.health();
4518 assert!(
4519 !health
4520 .warnings
4521 .iter()
4522 .any(|w| matches!(w, WarningHint::OuterRepoNotIgnoringMemRepo { .. })),
4523 "outer-repo check must skip when workspace_root is None",
4524 );
4525 }
4526
4527 #[test]
4528 fn writable_mem_names_filters_by_capability() {
4529 let tmp = TempDir::new().unwrap();
4530 let mem_dir = tmp.path().to_path_buf();
4531 let writer = FilesystemMemWriter::new(mem_dir.clone());
4532 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4533
4534 let engine = Engine::from_mounts(vec![
4535 (
4536 folder_mount("writable", mem_dir),
4537 Box::new(writer) as Box<dyn MemBackend>,
4538 ),
4539 (
4540 archive_mount("sealed", archive_path.clone()),
4541 Box::new(ArchiveBackend::new(archive_path)),
4542 ),
4543 ])
4544 .unwrap();
4545
4546 // Only the writable mount surfaces; the archive (read-only)
4547 // is filtered out.
4548 let names = engine.writable_mem_names();
4549 assert_eq!(names, vec!["writable"]);
4550 }
4551
4552 /// The default writable mem is
4553 /// the FIRST writable mount in declaration order — the stable seed,
4554 /// not the alphabetically-first name. `test` is declared first;
4555 /// `other` sorts ahead alphabetically but is declared second, so it
4556 /// is NOT the default. This is the invariant that stops a second
4557 /// mem from silently retargeting omitted-`mem` writes.
4558 #[test]
4559 fn default_writable_mem_is_declaration_first_not_alphabetical() {
4560 let tmp = TempDir::new().unwrap();
4561 let test_dir = tmp.path().join("test");
4562 let other_dir = tmp.path().join("other");
4563 std::fs::create_dir_all(&test_dir).unwrap();
4564 std::fs::create_dir_all(&other_dir).unwrap();
4565
4566 let engine = Engine::from_mounts(vec![
4567 (
4568 folder_mount("test", test_dir.clone()),
4569 Box::new(FilesystemMemWriter::new(test_dir)) as Box<dyn MemBackend>,
4570 ),
4571 (
4572 folder_mount("other", other_dir.clone()),
4573 Box::new(FilesystemMemWriter::new(other_dir)) as Box<dyn MemBackend>,
4574 ),
4575 ])
4576 .unwrap();
4577
4578 assert_eq!(
4579 engine.default_writable_mem(),
4580 Some("test"),
4581 "default must be the declaration-first writable mem, not the alphabetically-first",
4582 );
4583 }
4584
4585 /// Reverse declaration order to prove the default tracks declaration
4586 /// order rather than a fixed name: with `other` declared first it
4587 /// becomes the default. Together with the test above this pins the
4588 /// lean as mount order, not name sort.
4589 #[test]
4590 fn default_writable_mem_follows_declaration_order() {
4591 let tmp = TempDir::new().unwrap();
4592 let other_dir = tmp.path().join("other");
4593 let test_dir = tmp.path().join("test");
4594 std::fs::create_dir_all(&other_dir).unwrap();
4595 std::fs::create_dir_all(&test_dir).unwrap();
4596
4597 let engine = Engine::from_mounts(vec![
4598 (
4599 folder_mount("other", other_dir.clone()),
4600 Box::new(FilesystemMemWriter::new(other_dir)) as Box<dyn MemBackend>,
4601 ),
4602 (
4603 folder_mount("test", test_dir.clone()),
4604 Box::new(FilesystemMemWriter::new(test_dir)) as Box<dyn MemBackend>,
4605 ),
4606 ])
4607 .unwrap();
4608
4609 assert_eq!(engine.default_writable_mem(), Some("other"));
4610 }
4611
4612 /// A read-only-only workspace has no default writable mem.
4613 #[test]
4614 fn default_writable_mem_none_without_writable_mount() {
4615 let tmp = TempDir::new().unwrap();
4616 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4617 let engine = Engine::from_mounts(vec![(
4618 archive_mount("sealed", archive_path.clone()),
4619 Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
4620 )])
4621 .unwrap();
4622 assert_eq!(engine.default_writable_mem(), None);
4623 }
4624
4625 #[test]
4626 fn folder_path_for_mem_returns_path_for_folder_mounts_only() {
4627 let tmp = TempDir::new().unwrap();
4628 let mem_dir = tmp.path().join("specs");
4629 std::fs::create_dir_all(&mem_dir).unwrap();
4630 let writer = FilesystemMemWriter::new(mem_dir.clone());
4631 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4632
4633 let engine = Engine::from_mounts(vec![
4634 (
4635 folder_mount("specs", mem_dir.clone()),
4636 Box::new(writer) as Box<dyn MemBackend>,
4637 ),
4638 (
4639 archive_mount("sealed", archive_path.clone()),
4640 Box::new(ArchiveBackend::new(archive_path)),
4641 ),
4642 ])
4643 .unwrap();
4644
4645 // Folder mount returns its path.
4646 assert_eq!(engine.folder_path_for_mem("specs"), Some(mem_dir.as_path()),);
4647 // Archive mount returns None — caller branches on storage type.
4648 assert_eq!(engine.folder_path_for_mem("sealed"), None);
4649 // Unknown mem returns None — same as Engine::mount.
4650 assert_eq!(engine.folder_path_for_mem("missing"), None);
4651 }
4652
4653 #[test]
4654 fn mount_accessor_returns_public_mount_shape() {
4655 // Build a heterogeneous engine and verify Engine::mount /
4656 // Engine::mounts surface the operator-facing Mount records.
4657 // Handlers branch on MountStorage variants through this
4658 // accessor (replacing full's gitdir_for / worktree_for /
4659 // mem_head_sha / mem_config_for direct-engine
4660 // accessors).
4661 let tmp = TempDir::new().unwrap();
4662 let mem_dir = tmp.path().to_path_buf();
4663 let writer = FilesystemMemWriter::new(mem_dir.clone());
4664 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4665
4666 let engine = Engine::from_mounts(vec![
4667 (
4668 folder_mount("writable", mem_dir.clone()),
4669 Box::new(writer) as Box<dyn MemBackend>,
4670 ),
4671 (
4672 archive_mount("sealed", archive_path.clone()),
4673 Box::new(ArchiveBackend::new(archive_path.clone())),
4674 ),
4675 ])
4676 .unwrap();
4677
4678 // Known mems: each returns a Mount whose storage variant
4679 // matches what the caller passed at construction.
4680 let folder = engine.mount("writable").expect("known mem");
4681 assert!(matches!(folder.storage, MountStorage::Folder { .. }));
4682 assert_eq!(folder.capability, MountCapability::Write);
4683
4684 let archive = engine.mount("sealed").expect("known mem");
4685 match &archive.storage {
4686 MountStorage::Archive { path } => assert_eq!(path, &archive_path),
4687 other => panic!("expected Archive storage, got {other:?}"),
4688 }
4689 assert_eq!(archive.capability, MountCapability::ReadOnly);
4690
4691 // Unknown mem — None, no panic, no error.
4692 assert!(engine.mount("missing").is_none());
4693
4694 // Engine::mounts enumerates every mount in declaration order.
4695 let mounts = engine.mounts();
4696 assert_eq!(mounts.len(), 2);
4697 assert_eq!(mounts[0].mem, "writable");
4698 assert_eq!(mounts[1].mem, "sealed");
4699 }
4700
4701 #[test]
4702 fn mem_router_writable_set_matches_writable_mount_capability() {
4703 // Build an engine with one writable folder mount and one
4704 // read-only archive mount; the router's writable set must
4705 // equal the writable mount's name only.
4706 let tmp = TempDir::new().unwrap();
4707 let mem_dir = tmp.path().join("specs");
4708 std::fs::create_dir_all(&mem_dir).unwrap();
4709 let writer = FilesystemMemWriter::new(mem_dir.clone());
4710 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4711
4712 let engine = Engine::from_mounts(vec![
4713 (
4714 folder_mount("specs", mem_dir.clone()),
4715 Box::new(writer) as Box<dyn MemBackend>,
4716 ),
4717 (
4718 archive_mount("ext", archive_path.clone()),
4719 Box::new(ArchiveBackend::new(archive_path)),
4720 ),
4721 ])
4722 .unwrap();
4723
4724 let router = engine.mem_router();
4725 assert!(router.is_writable("specs"));
4726 assert!(!router.is_writable("ext"));
4727 assert!(router.is_visible("specs"));
4728 assert!(router.is_visible("ext"));
4729 let writable: std::collections::HashSet<&String> = router.writable_mems().iter().collect();
4730 assert_eq!(writable.len(), 1);
4731 assert!(writable.contains(&"specs".to_string()));
4732 }
4733
4734 #[test]
4735 fn mem_router_origin_is_explicit_toml_for_workspace_mounts() {
4736 // Every mount built via `from_mounts` lands as
4737 // `MemOrigin::ExplicitToml` — the file-adapter origin.
4738 // `RuntimeCreated` is reserved for `memstead_mem_create`
4739 // runtime registrations once that handler migrates onto
4740 // the unified engine.
4741 let tmp = TempDir::new().unwrap();
4742 let mem_dir = tmp.path().join("specs");
4743 std::fs::create_dir_all(&mem_dir).unwrap();
4744 let writer = FilesystemMemWriter::new(mem_dir.clone());
4745
4746 let engine = Engine::from_mounts(vec![(
4747 folder_mount("specs", mem_dir),
4748 Box::new(writer) as Box<dyn MemBackend>,
4749 )])
4750 .unwrap();
4751
4752 let origin = engine
4753 .mem_router()
4754 .origin_for_mem("specs")
4755 .expect("known mem");
4756 assert_eq!(origin.kind(), "explicit");
4757 }
4758
4759 #[test]
4760 fn mem_router_dir_for_writable_folder_mount_matches_storage_path() {
4761 // Folder-backed writable mounts surface the storage path
4762 // via `dir_for_mem`. Handlers consuming the router for
4763 // per-mem path resolution rely on this.
4764 let tmp = TempDir::new().unwrap();
4765 let mem_dir = tmp.path().join("specs");
4766 std::fs::create_dir_all(&mem_dir).unwrap();
4767 let writer = FilesystemMemWriter::new(mem_dir.clone());
4768
4769 let engine = Engine::from_mounts(vec![(
4770 folder_mount("specs", mem_dir.clone()),
4771 Box::new(writer) as Box<dyn MemBackend>,
4772 )])
4773 .unwrap();
4774
4775 assert_eq!(
4776 engine.mem_router().dir_for_mem("specs"),
4777 Some(mem_dir.as_path()),
4778 );
4779 assert_eq!(engine.mem_router().dir_for_mem("unknown"), None);
4780 }
4781
4782 #[test]
4783 fn mem_router_archive_path_for_read_only_archive_mount() {
4784 // Read-only archive mounts register via `add_read_only` so
4785 // `archive_path_for_mem` resolves the archive's on-disk
4786 // location.
4787 let tmp = TempDir::new().unwrap();
4788 let mem_dir = tmp.path().join("specs");
4789 std::fs::create_dir_all(&mem_dir).unwrap();
4790 let writer = FilesystemMemWriter::new(mem_dir.clone());
4791 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4792
4793 let engine = Engine::from_mounts(vec![
4794 (
4795 folder_mount("specs", mem_dir),
4796 Box::new(writer) as Box<dyn MemBackend>,
4797 ),
4798 (
4799 archive_mount("ext", archive_path.clone()),
4800 Box::new(ArchiveBackend::new(archive_path.clone())),
4801 ),
4802 ])
4803 .unwrap();
4804
4805 let router = engine.mem_router();
4806 assert_eq!(
4807 router.archive_path_for_mem("ext"),
4808 Some(archive_path.as_path()),
4809 );
4810 // Writable folder mount has no archive path.
4811 assert_eq!(router.archive_path_for_mem("specs"), None);
4812 }
4813
4814 #[test]
4815 fn read_mem_config_via_backend_trait_folder_reads_bytes() {
4816 // Direct trait call against FilesystemMemWriter. Verifies
4817 // the backend-side primitive returns the raw bytes the
4818 // engine then parses.
4819 let tmp = TempDir::new().unwrap();
4820 let mem_dir = tmp.path().to_path_buf();
4821 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
4822 let body = br#"{
4823 "format": 1,
4824 "schema": "default@1.0.0",
4825 "writeGuidance": { "tone": "neutral" }
4826 }"#;
4827 std::fs::write(mem_dir.join(".memstead").join("config.json"), body).unwrap();
4828
4829 let writer = FilesystemMemWriter::new(mem_dir);
4830 let result = MemBackend::read_mem_config(&writer).unwrap();
4831 let bytes = result.expect("config bytes must surface");
4832 let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4833 assert_eq!(parsed["schema"], "default@1.0.0");
4834 }
4835
4836 #[test]
4837 fn read_mem_config_via_backend_trait_folder_missing_returns_none() {
4838 let tmp = TempDir::new().unwrap();
4839 let mem_dir = tmp.path().to_path_buf();
4840 let writer = FilesystemMemWriter::new(mem_dir);
4841 let result = MemBackend::read_mem_config(&writer).unwrap();
4842 assert!(result.is_none());
4843 }
4844
4845 #[test]
4846 fn read_mem_config_via_backend_trait_archive_reads_bytes() {
4847 // Build an archive containing .memstead/config.json and verify
4848 // the ArchiveBackend impl returns its bytes.
4849 let tmp = TempDir::new().unwrap();
4850 let archive_path = tmp.path().join("seed.mem");
4851 let body = br#"{
4852 "format": 1,
4853 "schema": "default@1.0.0",
4854 "writeGuidance": { "tone": "archive" }
4855 }"#;
4856 {
4857 let file = std::fs::File::create(&archive_path).unwrap();
4858 let mut writer = zip::ZipWriter::new(file);
4859 writer
4860 .start_file(
4861 ".memstead/config.json",
4862 zip::write::SimpleFileOptions::default(),
4863 )
4864 .unwrap();
4865 use std::io::Write;
4866 writer.write_all(body).unwrap();
4867 writer.finish().unwrap();
4868 }
4869
4870 let backend = ArchiveBackend::new(archive_path);
4871 let result = MemBackend::read_mem_config(&backend).unwrap();
4872 let bytes = result.expect("config bytes must surface");
4873 let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
4874 assert_eq!(parsed["writeGuidance"]["tone"], "archive");
4875 }
4876
4877 #[test]
4878 fn mem_config_for_returns_none_when_no_config_file_present() {
4879 // Folder backend without a `.memstead/config.json` file. The
4880 // accessor must lenient — return None, not error.
4881 let tmp = TempDir::new().unwrap();
4882 let mem_dir = tmp.path().to_path_buf();
4883 let writer = FilesystemMemWriter::new(mem_dir.clone());
4884 let engine = Engine::from_mounts(vec![(
4885 folder_mount("specs", mem_dir),
4886 Box::new(writer) as Box<dyn MemBackend>,
4887 )])
4888 .unwrap();
4889 assert!(engine.mem_config_for("specs").is_none());
4890 }
4891
4892 #[test]
4893 fn mem_config_for_returns_some_when_config_file_present() {
4894 // Drop a valid `.memstead/config.json` into the mem dir,
4895 // build the engine, and assert the accessor surfaces a
4896 // MemConfig with the right shape (write_guidance entries
4897 // round-trip).
4898 let tmp = TempDir::new().unwrap();
4899 let mem_dir = tmp.path().to_path_buf();
4900 std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
4901 let config_body = r#"{
4902 "format": 1,
4903 "schema": "default@1.0.0",
4904 "writeGuidance": {
4905 "tone": "neutral",
4906 "voice": "active"
4907 }
4908 }"#;
4909 std::fs::write(mem_dir.join(".memstead").join("config.json"), config_body).unwrap();
4910
4911 let writer = FilesystemMemWriter::new(mem_dir.clone());
4912 let engine = Engine::from_mounts(vec![(
4913 folder_mount("specs", mem_dir),
4914 Box::new(writer) as Box<dyn MemBackend>,
4915 )])
4916 .unwrap();
4917
4918 let cfg = engine
4919 .mem_config_for("specs")
4920 .expect("mem_config should load");
4921 assert_eq!(cfg.write_guidance.len(), 2);
4922 assert_eq!(
4923 cfg.write_guidance.get("tone").and_then(|v| v.as_str()),
4924 Some("neutral"),
4925 );
4926 assert_eq!(
4927 cfg.write_guidance.get("voice").and_then(|v| v.as_str()),
4928 Some("active"),
4929 );
4930 }
4931
4932 #[test]
4933 fn mem_config_for_unknown_mem_returns_none() {
4934 // Lenient accessor — unknown names get None, not Err.
4935 let tmp = TempDir::new().unwrap();
4936 let mem_dir = tmp.path().to_path_buf();
4937 let writer = FilesystemMemWriter::new(mem_dir.clone());
4938 let engine = Engine::from_mounts(vec![(
4939 folder_mount("specs", mem_dir),
4940 Box::new(writer) as Box<dyn MemBackend>,
4941 )])
4942 .unwrap();
4943 assert!(engine.mem_config_for("missing").is_none());
4944 }
4945
4946 #[test]
4947 fn mem_config_for_archive_mount_returns_none() {
4948 // Archive backends carry mem_config = None in V1 (the
4949 // read-from-storage path is deferred to a follow-up).
4950 let tmp = TempDir::new().unwrap();
4951 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
4952 let engine = Engine::from_mounts(vec![(
4953 archive_mount("ext", archive_path.clone()),
4954 Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
4955 )])
4956 .unwrap();
4957 assert!(engine.mem_config_for("ext").is_none());
4958 }
4959
4960 #[test]
4961 fn mem_configs_named_iterates_only_mounts_with_config() {
4962 // Two folder mounts; one has a config file, one doesn't.
4963 // The iterator yields exactly the configured one — verifies
4964 // the filter_map shape and that the name comes from the
4965 // mount record (authoritative), not the config body.
4966 let tmp = TempDir::new().unwrap();
4967 let with_config = tmp.path().join("specs");
4968 let without_config = tmp.path().join("memos");
4969 std::fs::create_dir_all(with_config.join(".memstead")).unwrap();
4970 std::fs::create_dir_all(&without_config).unwrap();
4971 let config_body = r#"{
4972 "format": 1,
4973 "schema": "default@1.0.0",
4974 "writeGuidance": { "tone": "neutral" }
4975 }"#;
4976 std::fs::write(
4977 with_config.join(".memstead").join("config.json"),
4978 config_body,
4979 )
4980 .unwrap();
4981
4982 let engine = Engine::from_mounts(vec![
4983 (
4984 folder_mount("specs", with_config.clone()),
4985 Box::new(FilesystemMemWriter::new(with_config)) as Box<dyn MemBackend>,
4986 ),
4987 (
4988 folder_mount("memos", without_config.clone()),
4989 Box::new(FilesystemMemWriter::new(without_config)) as Box<dyn MemBackend>,
4990 ),
4991 ])
4992 .unwrap();
4993
4994 let yielded: Vec<(&str, usize)> = engine
4995 .mem_configs_named()
4996 .map(|(name, cfg)| (name, cfg.write_guidance.len()))
4997 .collect();
4998 assert_eq!(yielded, vec![("specs", 1)]);
4999 }
5000
5001 #[test]
5002 fn schema_for_returns_some_for_known_mem_and_none_for_unknown() {
5003 // Every mount registers a schema (resolved from its pin at
5004 // boot). Lookup by mem name surfaces the same Arc that
5005 // mutations resolve internally; unknown names return None.
5006 let tmp = TempDir::new().unwrap();
5007 let mem_dir = tmp.path().to_path_buf();
5008 let writer = FilesystemMemWriter::new(mem_dir.clone());
5009 let engine = Engine::from_mounts(vec![(
5010 folder_mount("specs", mem_dir),
5011 Box::new(writer) as Box<dyn MemBackend>,
5012 )])
5013 .unwrap();
5014 assert!(engine.schema_for("specs").is_some());
5015 assert!(engine.schema_for("missing").is_none());
5016 }
5017
5018 #[test]
5019 fn gitdir_for_unknown_mem_returns_unknown_mem() {
5020 let tmp = TempDir::new().unwrap();
5021 let mem_dir = tmp.path().to_path_buf();
5022 let writer = FilesystemMemWriter::new(mem_dir.clone());
5023 let engine = Engine::from_mounts(vec![(
5024 folder_mount("specs", mem_dir),
5025 Box::new(writer) as Box<dyn MemBackend>,
5026 )])
5027 .unwrap();
5028 let err = engine.gitdir_for("missing").unwrap_err();
5029 assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
5030 }
5031
5032 #[test]
5033 fn gitdir_for_folder_mount_returns_no_gitdir_error() {
5034 // Folder mounts do not have a gitdir — full's contract surfaces
5035 // a mem-level error, not UnknownMem. Mirror that here.
5036 let tmp = TempDir::new().unwrap();
5037 let mem_dir = tmp.path().to_path_buf();
5038 let writer = FilesystemMemWriter::new(mem_dir.clone());
5039 let engine = Engine::from_mounts(vec![(
5040 folder_mount("specs", mem_dir),
5041 Box::new(writer) as Box<dyn MemBackend>,
5042 )])
5043 .unwrap();
5044 let err = engine.gitdir_for("specs").unwrap_err();
5045 match err {
5046 EngineError::Mem(msg) => assert!(msg.contains("no resolved gitdir")),
5047 other => panic!("expected EngineError::Mem, got {other:?}"),
5048 }
5049 }
5050
5051 #[test]
5052 fn worktree_for_folder_mount_returns_storage_path() {
5053 let tmp = TempDir::new().unwrap();
5054 let mem_dir = tmp.path().to_path_buf();
5055 let writer = FilesystemMemWriter::new(mem_dir.clone());
5056 let engine = Engine::from_mounts(vec![(
5057 folder_mount("specs", mem_dir.clone()),
5058 Box::new(writer) as Box<dyn MemBackend>,
5059 )])
5060 .unwrap();
5061 let worktree = engine.worktree_for("specs").unwrap();
5062 assert_eq!(worktree, mem_dir);
5063 }
5064
5065 #[test]
5066 fn worktree_for_unknown_mem_returns_unknown_mem() {
5067 let tmp = TempDir::new().unwrap();
5068 let mem_dir = tmp.path().to_path_buf();
5069 let writer = FilesystemMemWriter::new(mem_dir.clone());
5070 let engine = Engine::from_mounts(vec![(
5071 folder_mount("specs", mem_dir),
5072 Box::new(writer) as Box<dyn MemBackend>,
5073 )])
5074 .unwrap();
5075 let err = engine.worktree_for("missing").unwrap_err();
5076 assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
5077 }
5078
5079 #[test]
5080 fn worktree_for_archive_mount_returns_archive_backed_error() {
5081 let tmp = TempDir::new().unwrap();
5082 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
5083 let engine = Engine::from_mounts(vec![(
5084 archive_mount("ext", archive_path.clone()),
5085 Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
5086 )])
5087 .unwrap();
5088 let err = engine.worktree_for("ext").unwrap_err();
5089 match err {
5090 EngineError::Mem(msg) => assert!(msg.contains("archive-backed")),
5091 other => panic!("expected EngineError::Mem, got {other:?}"),
5092 }
5093 }
5094
5095 #[test]
5096 fn mem_head_sha_for_folder_mount_is_none() {
5097 // Folder backend doesn't track a head; current_head() returns
5098 // Ok(None) at construction; mem_head_sha returns Ok(None).
5099 let tmp = TempDir::new().unwrap();
5100 let mem_dir = tmp.path().to_path_buf();
5101 let writer = FilesystemMemWriter::new(mem_dir.clone());
5102 let engine = Engine::from_mounts(vec![(
5103 folder_mount("specs", mem_dir),
5104 Box::new(writer) as Box<dyn MemBackend>,
5105 )])
5106 .unwrap();
5107 let head = engine.mem_head_sha("specs").unwrap();
5108 assert_eq!(head, None);
5109 }
5110
5111 #[test]
5112 fn mem_head_sha_unknown_mem_returns_unknown_mem() {
5113 let tmp = TempDir::new().unwrap();
5114 let mem_dir = tmp.path().to_path_buf();
5115 let writer = FilesystemMemWriter::new(mem_dir.clone());
5116 let engine = Engine::from_mounts(vec![(
5117 folder_mount("specs", mem_dir),
5118 Box::new(writer) as Box<dyn MemBackend>,
5119 )])
5120 .unwrap();
5121 let err = engine.mem_head_sha("missing").unwrap_err();
5122 assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
5123 }
5124
5125 #[test]
5126 fn capability_surfaces_per_mount() {
5127 let tmp = TempDir::new().unwrap();
5128 let mem_dir = tmp.path().to_path_buf();
5129 let writer = FilesystemMemWriter::new(mem_dir.clone());
5130 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
5131
5132 let engine = Engine::from_mounts(vec![
5133 (
5134 folder_mount("writable", mem_dir),
5135 Box::new(writer) as Box<dyn MemBackend>,
5136 ),
5137 (
5138 archive_mount("read-only", archive_path.clone()),
5139 Box::new(ArchiveBackend::new(archive_path)),
5140 ),
5141 ])
5142 .unwrap();
5143
5144 assert_eq!(
5145 engine.capability("writable").unwrap(),
5146 MountCapability::Write
5147 );
5148 assert_eq!(
5149 engine.capability("read-only").unwrap(),
5150 MountCapability::ReadOnly
5151 );
5152 assert!(matches!(
5153 engine.capability("missing"),
5154 Err(EngineError::UnknownMem(_))
5155 ));
5156 }
5157
5158 #[test]
5159 fn read_provenance_routes_through_backend() {
5160 let tmp = TempDir::new().unwrap();
5161 let mem_dir = tmp.path().to_path_buf();
5162 let writer = FilesystemMemWriter::new(mem_dir.clone());
5163
5164 // Append a provenance record via the backend trait directly,
5165 // then read it back through the engine.
5166 let backend_handle: &dyn MemBackend = &writer;
5167 backend_handle
5168 .append_provenance(&Provenance::new(
5169 std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
5170 crate::ProvenanceKind::Create,
5171 Some("v:e".into()),
5172 crate::vcs::Actor::Cli,
5173 None,
5174 Some("first".into()),
5175 ))
5176 .unwrap();
5177
5178 let engine = Engine::from_mounts(vec![(
5179 folder_mount("specs", mem_dir),
5180 Box::new(writer) as Box<dyn MemBackend>,
5181 )])
5182 .unwrap();
5183
5184 let records = engine.read_provenance("specs", None).unwrap();
5185 assert_eq!(records.len(), 1);
5186 assert_eq!(records[0].kind, crate::ProvenanceKind::Create);
5187 assert_eq!(records[0].entity.as_deref(), Some("v:e"));
5188 assert_eq!(records[0].note.as_deref(), Some("first"));
5189 }
5190
5191 #[test]
5192 fn archive_mount_returns_sealed_indirectly_through_backend_layer() {
5193 // The engine doesn't yet expose mutation methods, but an
5194 // archive backend held on a Mount with ReadOnly capability is
5195 // still a `&dyn MemBackend` whose write methods return
5196 // Sealed. This test locks the trait routing — when the engine
5197 // gains write methods in a later session, capability gating +
5198 // backend Sealed errors must agree.
5199 let tmp = TempDir::new().unwrap();
5200 let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
5201 let backend = ArchiveBackend::new(archive_path);
5202 match MemBackend::write_entity(&backend, Path::new("x.md"), b"x") {
5203 Err(BackendError::Sealed) => {}
5204 other => panic!("expected Sealed, got {other:?}"),
5205 }
5206 }
5207
5208 // ---- Read-side delegates ----------------------------------------
5209 //
5210 // These tests pin the surface that the MCP migration consumes
5211 // (stats, health, context, communities, search, list, orphans,
5212 // stubs, most_connected, missing_required_outgoing). They run
5213 // against a folder-mount engine with a small fixture of created
5214 // entities and one relate edge — enough to exercise both the
5215 // graph-query path and the cache-invalidation hooks.
5216
5217 /// Generation-keyed memos (flywheel W8/01). Four claims: repeated
5218 /// reads serve the memo; a REFUSED engine batch leaves the memo
5219 /// untouched (the refusal path calls no hook — pinned so it stays
5220 /// cheap); a memo computed from an INTERIM (mid-batch) state never
5221 /// survives a rollback as fresh — the store-carried generation is
5222 /// what lets the invalidation hook adjudicate that correctly; and
5223 /// a real mutation invalidates, with the recomputation identical
5224 /// to a from-scratch detection (the criterion-3 identity oracle
5225 /// for the mechanism).
5226 #[test]
5227 fn generation_keyed_memos_survive_rollback_and_track_mutations() {
5228 use indexmap::IndexMap;
5229
5230 let tmp = TempDir::new().unwrap();
5231 let mut engine = build_demo_engine(&tmp);
5232
5233 // 1. Repeated reads: cell filled once, generation stable.
5234 let _ = engine.communities();
5235 let memo_gen_before = engine.community_memo.get().expect("memo filled").0;
5236 let _ = engine.communities();
5237 assert_eq!(
5238 engine.community_memo.get().expect("still filled").0,
5239 memo_gen_before,
5240 "repeated reads must serve the memo"
5241 );
5242
5243 // 2. A REFUSED engine batch rolls the store back and leaves
5244 // the memo untouched — refusal stays recompute-free.
5245 let bare = |id: crate::EntityId| crate::engine::UpdateEntityArgs {
5246 anchors: Vec::new(),
5247 anchors_unset: Vec::new(),
5248 id,
5249 expected_hash: None,
5250 sections: IndexMap::new(),
5251 append_sections: IndexMap::new(),
5252 patch_sections: IndexMap::new(),
5253 sections_unset: Vec::new(),
5254 metadata: IndexMap::new(),
5255 metadata_unset: Vec::new(),
5256 declare_relations: Vec::new(),
5257 dry_run: false,
5258 relations_unset: Vec::new(),
5259 };
5260 let mut real = bare(crate::EntityId::new("specs", "source-one"));
5261 real.append_sections
5262 .insert("identity".to_string(), "appended line".to_string());
5263 let missing = bare(crate::EntityId::new("specs", "does-not-exist"));
5264 let (actor, client) = cli_actor();
5265 let result = engine
5266 .batch_update(
5267 vec![(real, None), (missing, None)],
5268 actor,
5269 Some(&client),
5270 false,
5271 )
5272 .expect("refused batch returns a report-all envelope");
5273 assert!(
5274 !result.applied,
5275 "the missing target refuses the whole batch"
5276 );
5277 assert_eq!(
5278 engine.community_memo.get().map(|m| m.0),
5279 Some(memo_gen_before),
5280 "a refused batch must leave the pre-batch memo standing"
5281 );
5282 assert_eq!(
5283 engine.store().generation(),
5284 memo_gen_before.store_generation,
5285 "rollback restored the store to the memo's generation"
5286 );
5287
5288 // 3. The dangerous direction: a memo computed from an INTERIM
5289 // state (simulated batch staging) must not survive the
5290 // rollback as fresh. The store-carried generation is what the
5291 // invalidation hook adjudicates with.
5292 let snapshot = engine.store.clone();
5293 let interim_id = crate::EntityId::new("specs", "interim-only");
5294 let mut interim = engine
5295 .store
5296 .get(&crate::EntityId::new("specs", "source-one"))
5297 .expect("demo entity present")
5298 .clone();
5299 interim.id = interim_id.clone();
5300 interim.title = "Interim Only".to_string();
5301 engine.store.upsert(interim_id, interim);
5302 engine.invalidate_communities();
5303 let _ = engine.communities();
5304 let interim_gen = engine.community_memo.get().expect("interim memo").0;
5305 assert_ne!(interim_gen, memo_gen_before);
5306 engine.store = snapshot; // rollback, generation restored with it
5307 engine.invalidate_communities();
5308 engine.invalidate_search_indexes();
5309 if let Some((g, _)) = engine.community_memo.get() {
5310 assert_ne!(
5311 *g, interim_gen,
5312 "a rolled-back interim state must never be served as fresh"
5313 );
5314 }
5315 assert!(
5316 !engine
5317 .communities()
5318 .entity_cluster_map
5319 .keys()
5320 .any(|id| id.contains("interim-only")),
5321 "the partition served after rollback reflects the restored store, not the interim one"
5322 );
5323
5324 // 4. A real mutation invalidates; the recomputation equals a
5325 // from-scratch detection and sees the new entity.
5326 let (actor, client) = cli_actor();
5327 engine
5328 .create_entity(
5329 empty_create_args("specs", "Fourth Entity"),
5330 actor,
5331 Some(&client),
5332 None,
5333 )
5334 .unwrap();
5335 assert!(
5336 engine
5337 .communities()
5338 .entity_cluster_map
5339 .keys()
5340 .any(|id| id.contains("fourth-entity")),
5341 "recomputed partition sees the new entity"
5342 );
5343 let fresh = {
5344 let schema = engine
5345 .schemas
5346 .iter()
5347 .min_by(|a, b| a.0.cmp(b.0))
5348 .map(|(_, s)| s.clone())
5349 .expect("demo engine has a schema");
5350 let schema_for_weights = schema.clone();
5351 crate::graph::community::detect_communities(
5352 engine.store(),
5353 schema.manifest.community.resolution,
5354 schema.manifest.community.seed,
5355 move |rel_type| {
5356 schema_for_weights
5357 .manifest
5358 .relationships
5359 .definitions
5360 .iter()
5361 .find(|d| d.name == rel_type)
5362 .map(|d| d.default_weight as f64)
5363 .unwrap_or(1.0)
5364 },
5365 )
5366 };
5367 assert_eq!(
5368 engine.communities().entity_cluster_map,
5369 fresh.entity_cluster_map,
5370 "memo must equal a from-scratch detection over the current store"
5371 );
5372 }
5373
5374 fn build_demo_engine(tmp: &TempDir) -> Engine {
5375 let mem_dir = tmp.path().to_path_buf();
5376 let writer = FilesystemMemWriter::new(mem_dir.clone());
5377 let mut engine = Engine::from_mounts(vec![(
5378 folder_mount("specs", mem_dir),
5379 Box::new(writer) as Box<dyn MemBackend>,
5380 )])
5381 .unwrap();
5382 let (actor, client) = cli_actor();
5383 let source = engine
5384 .create_entity(
5385 empty_create_args("specs", "Source One"),
5386 actor,
5387 Some(&client),
5388 None,
5389 )
5390 .unwrap();
5391 let target = engine
5392 .create_entity(
5393 empty_create_args("specs", "Target Two"),
5394 actor,
5395 Some(&client),
5396 None,
5397 )
5398 .unwrap();
5399 engine
5400 .create_entity(
5401 empty_create_args("specs", "Lonely Three"),
5402 actor,
5403 Some(&client),
5404 None,
5405 )
5406 .unwrap();
5407 engine
5408 .relate_entity(
5409 RelateEntityArgs {
5410 source: source.id.clone(),
5411 expected_hash: Some(source.content_hash.clone()),
5412 rel_type: "USES".to_string(),
5413 target: target.id.clone(),
5414 remove: false,
5415 description: None,
5416 dry_run: false,
5417 },
5418 actor,
5419 Some(&client),
5420 None,
5421 )
5422 .unwrap();
5423 engine
5424 }
5425
5426 #[test]
5427 fn status_reports_per_engine_counts() {
5428 let tmp = TempDir::new().unwrap();
5429 let engine = build_demo_engine(&tmp);
5430 let stats = engine.status();
5431 assert_eq!(stats.entity_count, 3);
5432 assert_eq!(stats.edge_count, 1);
5433 assert_eq!(stats.mem_count, 1);
5434 assert_eq!(stats.types_in_use, vec!["spec".to_string()]);
5435 assert_eq!(stats.edge_types.get("USES"), Some(&1));
5436 }
5437
5438 #[test]
5439 fn orphans_lists_unconnected_real_entities() {
5440 let tmp = TempDir::new().unwrap();
5441 let engine = build_demo_engine(&tmp);
5442 let orphans = engine.orphans();
5443 assert_eq!(orphans.len(), 1);
5444 assert_eq!(orphans[0].as_ref(), "specs--lonely-three");
5445 }
5446
5447 /// #49: the orphan/community headlines can be attributed per pinned
5448 /// schema. Single-mem here, so one bucket — but it proves the
5449 /// attribution keys by `schema_of(mem)` and that the per-schema
5450 /// counts sum to the raw total (which a health surface keeps verbatim).
5451 #[test]
5452 fn schema_breakdowns_attribute_to_mem_pin() {
5453 let tmp = TempDir::new().unwrap();
5454 let engine = build_demo_engine(&tmp);
5455
5456 let orphans = engine.orphans();
5457 let orphans_by_schema = engine.orphans_by_schema(&orphans);
5458 assert_eq!(
5459 orphans_by_schema.values().sum::<usize>(),
5460 orphans.len(),
5461 "per-schema orphan counts must sum to the raw total"
5462 );
5463 assert_eq!(orphans_by_schema.len(), 1, "one mem ⇒ one schema bucket");
5464 let (schema, count) = orphans_by_schema.iter().next().unwrap();
5465 assert!(!schema.is_empty(), "specs mem is pinned: {schema:?}");
5466 assert_eq!(*count, 1);
5467
5468 // communities_by_schema buckets the demo mem's clusters under the
5469 // same pin; with one schema, its values sum to the global count.
5470 let mems: Vec<String> = engine.mounts().iter().map(|m| m.mem.clone()).collect();
5471 let communities_by_schema = engine.communities_by_schema(&mems);
5472 assert_eq!(communities_by_schema.len(), 1);
5473 assert_eq!(
5474 communities_by_schema.values().sum::<usize>(),
5475 engine.communities().count,
5476 );
5477 }
5478
5479 #[test]
5480 fn stubs_lists_unresolved_link_targets() {
5481 let tmp = TempDir::new().unwrap();
5482 let mem_dir = tmp.path().to_path_buf();
5483 let writer = FilesystemMemWriter::new(mem_dir.clone());
5484 let mut engine = Engine::from_mounts(vec![(
5485 folder_mount("specs", mem_dir),
5486 Box::new(writer) as Box<dyn MemBackend>,
5487 )])
5488 .unwrap();
5489 let (actor, client) = cli_actor();
5490 let source = engine
5491 .create_entity(
5492 empty_create_args("specs", "Holder"),
5493 actor,
5494 Some(&client),
5495 None,
5496 )
5497 .unwrap();
5498 // Relate to a non-existent target — relate_entity creates a
5499 // stub for the target so the edge can land.
5500 engine
5501 .relate_entity(
5502 RelateEntityArgs {
5503 source: source.id.clone(),
5504 expected_hash: Some(source.content_hash.clone()),
5505 rel_type: "USES".to_string(),
5506 target: EntityId::new("specs", "ghost"),
5507 remove: false,
5508 description: None,
5509 dry_run: false,
5510 },
5511 actor,
5512 Some(&client),
5513 None,
5514 )
5515 .unwrap();
5516 let stubs = engine.stubs();
5517 assert!(
5518 stubs.iter().any(|(id, _)| id.as_ref() == "specs--ghost"),
5519 "expected ghost stub: {stubs:?}"
5520 );
5521 }
5522
5523 #[test]
5524 fn most_connected_orders_by_degree() {
5525 let tmp = TempDir::new().unwrap();
5526 let engine = build_demo_engine(&tmp);
5527 let top = engine.most_connected(5);
5528 assert_eq!(top.len(), 3);
5529 // Source and Target each have one edge; Lonely has zero.
5530 let zero_degree: Vec<_> = top
5531 .iter()
5532 .filter(|c| c.total == 0)
5533 .map(|c| c.id.as_ref().to_string())
5534 .collect();
5535 assert_eq!(zero_degree, vec!["specs--lonely-three".to_string()]);
5536 }
5537
5538 #[test]
5539 fn health_returns_per_engine_summary() {
5540 let tmp = TempDir::new().unwrap();
5541 let engine = build_demo_engine(&tmp);
5542 let health = engine.health();
5543 // `memstead_create` refuses on missing required sections, so
5544 // entities built through `empty_create_args` carry the
5545 // helper-seeded `identity` + `purpose` bodies and no longer
5546 // surface as missing-fields. Health remains the read-side
5547 // tolerance surface for legacy on-disk drift — covered by
5548 // the loader-tolerance tests that hand-craft pre-strict
5549 // markdown files.
5550 assert!(
5551 health
5552 .missing_fields
5553 .iter()
5554 .all(|r| r.id.as_ref() != "specs--source-one"),
5555 "post-strict-create fixture must not surface as missing-fields; got {:?}",
5556 health.missing_fields,
5557 );
5558 }
5559
5560 #[test]
5561 fn context_carries_neighbors_and_community() {
5562 let tmp = TempDir::new().unwrap();
5563 let engine = build_demo_engine(&tmp);
5564 let source_id = EntityId::new("specs", "source-one");
5565 let ctx = engine.context(&source_id).unwrap();
5566 assert_eq!(ctx.entity_id, source_id);
5567 assert_eq!(ctx.neighbors.len(), 1);
5568 assert_eq!(ctx.neighbors[0].relationship, "USES");
5569 assert!(matches!(ctx.neighbors[0].direction, Direction::Outgoing));
5570 }
5571
5572 #[test]
5573 fn communities_caches_louvain_until_invalidated() {
5574 let tmp = TempDir::new().unwrap();
5575 let mut engine = build_demo_engine(&tmp);
5576 // Population reflects the current store at first call.
5577 let entities_before = engine.communities().entity_cluster_map.len();
5578 // Cache hit — repeat call returns same data.
5579 assert_eq!(
5580 engine.communities().entity_cluster_map.len(),
5581 entities_before
5582 );
5583 // Mutation invalidates the cache; next call re-runs against
5584 // the post-mutation store and includes the new entity.
5585 let (actor, client) = cli_actor();
5586 engine
5587 .create_entity(
5588 empty_create_args("specs", "Disturber"),
5589 actor,
5590 Some(&client),
5591 None,
5592 )
5593 .unwrap();
5594 let entities_after = engine.communities().entity_cluster_map.len();
5595 assert_eq!(
5596 entities_after,
5597 entities_before + 1,
5598 "create_entity should have invalidated community cache and added the new entity"
5599 );
5600 }
5601
5602 #[test]
5603 fn list_filters_by_metadata_only() {
5604 let tmp = TempDir::new().unwrap();
5605 let engine = build_demo_engine(&tmp);
5606 let scope = SearchScope {
5607 entity_type: Some("spec".to_string()),
5608 ..Default::default()
5609 };
5610 let result = engine.list(&scope);
5611 // Three real spec entities created; stubs / non-spec types absent.
5612 assert_eq!(result.hits.len(), 3);
5613 }
5614
5615 #[test]
5616 fn list_applies_schema_declared_filter_on_non_default_schema_mem() {
5617 // A mem pinned to `planning` (non-default schema). The
5618 // `decision` type declares `status` with `filterable: equality`.
5619 // Pre-fix, filter dispatch consulted only the built-in default
5620 // schema via `type_by_name`, missed `status`, silently bypassed
5621 // the filter, and emitted the misleading "unknown filter key"
5622 // warning. Post-fix, the filter is honored and no warning fires.
5623 let tmp = TempDir::new().unwrap();
5624 let mem_dir = tmp.path().to_path_buf();
5625 let writer = FilesystemMemWriter::new(mem_dir.clone());
5626 let mount = Mount {
5627 mem: "planning".to_string(),
5628 schema: Some(memstead_schema::SchemaRef::new(
5629 "planning",
5630 semver::Version::new(0, 1, 0),
5631 )),
5632 storage: MountStorage::Folder { path: mem_dir },
5633 capability: MountCapability::Write,
5634 lifecycle: MountLifecycle::Eager,
5635 cross_linkable: true,
5636 migration_target: None,
5637 };
5638 let mut engine =
5639 Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
5640 let (actor, client) = cli_actor();
5641
5642 // Two decisions with different status values; required fields
5643 // (decision/context/consequences sections, decided_on, deciders)
5644 // get placeholder defaults — the test only cares about the
5645 // status field's filterability.
5646 for (title, status) in &[("Skip Postgres", "accepted"), ("Use SQLite", "proposed")] {
5647 let mut metadata = indexmap::IndexMap::new();
5648 metadata.insert("status".to_string(), status.to_string());
5649 metadata.insert("deciders".to_string(), "alice".to_string());
5650 metadata.insert("decided_on".to_string(), "2026-05-19".to_string());
5651 let args = crate::engine::CreateEntityArgs {
5652 anchors: Vec::new(),
5653 mem: "planning".to_string(),
5654 title: title.to_string(),
5655 entity_type: "decision".to_string(),
5656 sections: indexmap::IndexMap::from_iter([
5657 ("decision".to_string(), "We chose this.".to_string()),
5658 ("context".to_string(), "Single-user dev.".to_string()),
5659 ("consequences".to_string(), "Lose multi-writer.".to_string()),
5660 ]),
5661 metadata,
5662 relations: Vec::new(),
5663 dry_run: false,
5664 };
5665 engine
5666 .create_entity(args, actor, Some(&client), None)
5667 .unwrap();
5668 }
5669
5670 // Filter on the schema-declared filterable field.
5671 let scope = SearchScope {
5672 entity_type: Some("decision".to_string()),
5673 filters: std::collections::HashMap::from([(
5674 "status".to_string(),
5675 "accepted".to_string(),
5676 )]),
5677 ..Default::default()
5678 };
5679 let result = engine.list(&scope);
5680 assert_eq!(
5681 result.hits.len(),
5682 1,
5683 "filter on schema-declared field must select only matching entities"
5684 );
5685 assert_eq!(result.hits[0].title, "Skip Postgres");
5686 assert!(
5687 result.warnings.is_empty(),
5688 "no warning should fire when the filter is declared by the mem's pinned schema: {:?}",
5689 result.warnings
5690 );
5691 }
5692
5693 #[test]
5694 fn search_returns_results_against_built_index() {
5695 let tmp = TempDir::new().unwrap();
5696 let engine = build_demo_engine(&tmp);
5697 let scope = SearchScope {
5698 query: Some(crate::ops::Query {
5699 any: vec!["source".to_string()],
5700 ..Default::default()
5701 }),
5702 ..Default::default()
5703 };
5704 let result = engine.search(&scope).expect("native search returns Ok");
5705 assert!(result.total >= 1, "expected ≥1 hit for source: {result:?}");
5706 assert!(
5707 result
5708 .hits
5709 .iter()
5710 .any(|h| h.id.as_ref() == "specs--source-one"),
5711 "expected source-one in hits: {result:?}"
5712 );
5713 }
5714
5715 // ---- Engine::from_workspace_root (folder boot path) ------------
5716}