memstead_base/engine/query/health.rs
1//! Derived health: communities and labelling, the orphan, stub and connectivity reads, the constraint, conformance and consistency findings, the signals, and the health report they compose into.
2
3use super::*;
4
5impl Engine {
6 /// Lazy community-detection cache. First call runs Louvain
7 /// against the current store using one pinned schema for
8 /// `community.{resolution, seed}` and the per-rel weights.
9 /// Subsequent calls return the cached result. Mutations invalidate
10 /// the cache via [`Self::invalidate_communities`].
11 ///
12 /// One detection run per engine. The partition is workspace-global,
13 /// so it needs a single source for the Louvain parameters; that
14 /// source is the schema of the lexicographically-first mem name —
15 /// a stable key, so the partition is deterministic across processes
16 /// even when mounts pin heterogeneous schemas. For a single-schema
17 /// workspace every mem's schema is identical, so the choice of
18 /// key is immaterial there.
19 pub fn communities(&self) -> &LouvainOutput {
20 // Generation sanity: a stored memo must match the live store
21 // generation — the mutation hooks clear stale memos before any
22 // read can arrive here. A mismatch would mean a mutation path
23 // skipped its invalidation call (the exact silent-staleness
24 // bug the generation exists to catch).
25 if let Some((memo_key, _)) = self.community_memo.get() {
26 debug_assert_eq!(
27 *memo_key,
28 self.derived_key(),
29 "community memo key lags the engine — a mutation path missed invalidate_communities"
30 );
31 }
32 &self
33 .community_memo
34 .get_or_init(|| (self.derived_key(), self.compute_communities()))
35 .1
36 }
37
38 /// The current validity key for derived-structure memos: store
39 /// generation plus schemas epoch (see [`crate::engine::DerivedKey`]).
40 pub fn derived_key(&self) -> crate::engine::DerivedKey {
41 crate::engine::DerivedKey {
42 store_generation: self.store.generation(),
43 schemas_epoch: self.schemas_epoch,
44 }
45 }
46
47 fn compute_communities(&self) -> LouvainOutput {
48 {
49 // Select the parameter schema by a stable key (smallest
50 // mem name) rather than unordered-map iteration, so the
51 // partition does not vary between processes. Fall back to
52 // the builtin default for the empty-mounts case (caller
53 // still gets a valid empty Louvain result against an empty
54 // store).
55 let schema = self
56 .schemas
57 .iter()
58 .min_by(|a, b| a.0.cmp(b.0))
59 .map(|(_, s)| s.clone())
60 .unwrap_or_else(Schema::builtin_default);
61 let manifest = &schema.manifest;
62 let resolution = manifest.community.resolution;
63 let seed = manifest.community.seed;
64 let schema_for_weights = schema.clone();
65 detect_communities(&self.store, resolution, seed, move |rel_type| {
66 schema_for_weights
67 .manifest
68 .relationships
69 .definitions
70 .iter()
71 .find(|d| d.name == rel_type)
72 .map(|d| d.default_weight as f64)
73 .unwrap_or(1.0)
74 })
75 }
76 }
77
78 /// Drop the cached community detection result and the grounded
79 /// labelling memo — unless the store still sits at the generation
80 /// each memo was computed from (flywheel W8/01). The keep case is
81 /// exactly the batch-rollback path: the restored snapshot restored
82 /// the generation with it, so the memo describes the live state
83 /// and recomputing it would be pure waste. Every real mutation
84 /// bumps the generation first, so those clears behave as before.
85 /// Coupling the labelling reset here means every site that already
86 /// invalidates communities (all mutation paths, drift reload,
87 /// quarantine attach/detach, apply-commit) invalidates the
88 /// labelling too, so a stale label can never outlive the state
89 /// change that moved it.
90 pub fn invalidate_communities(&mut self) {
91 let key = self.derived_key();
92 if !matches!(self.community_memo.get(), Some((k, _)) if *k == key) {
93 self.community_memo = OnceCell::new();
94 }
95 if !matches!(self.labelling_memo.get(), Some((k, _)) if *k == key) {
96 self.labelling_memo = OnceCell::new();
97 }
98 // The foreign-entity marks ride here for the same reason the
99 // labelling does: a proposal merge lands entities and calls this,
100 // so the map a read consults can never outlive the merge that
101 // changed it.
102 if !matches!(self.foreign_entities_memo.get(), Some((k, _)) if *k == key) {
103 self.foreign_entities_memo = OnceCell::new();
104 }
105 }
106
107 /// The grounded labelling of one mem — `None` when its pinned
108 /// schema declares no `relationships.labelling`. Computed on
109 /// first access for every declaring mem, memoised until the next
110 /// invalidation; generation-keyed like `community_memo`.
111 pub fn mem_labelling(&self, mem: &str) -> Option<&crate::ops::labelling::MemLabelling> {
112 // Generation sanity, same contract as `communities()`: a
113 // stored memo must match the live derived key — a mismatch
114 // means a mutation path missed invalidate_communities.
115 if let Some((memo_key, _)) = self.labelling_memo.get() {
116 debug_assert_eq!(
117 *memo_key,
118 self.derived_key(),
119 "labelling memo key lags the engine — a mutation path missed invalidate_communities"
120 );
121 }
122 let (_, map) = self.labelling_memo.get_or_init(|| {
123 let mut out = std::collections::HashMap::new();
124 for (mem_name, schema) in &self.schemas {
125 if let Some(lab) = crate::ops::labelling::labelling_of(schema) {
126 out.insert(
127 mem_name.clone(),
128 crate::ops::labelling::compute_mem_labelling(
129 &self.store,
130 mem_name,
131 &lab.attack,
132 ),
133 );
134 }
135 }
136 (self.derived_key(), out)
137 });
138 map.get(mem)
139 }
140
141 /// One entity's served labelling view — `None` when the entity is
142 /// a stub or its mem's schema declares no labelling; serving
143 /// surfaces then keep their byte-identical payloads. The shape
144 /// block is present exactly when the declaration carries a
145 /// `support` walk.
146 pub fn computed_labelling(
147 &self,
148 entity: &Entity,
149 ) -> Option<crate::ops::labelling::LabellingView> {
150 use crate::ops::labelling::{Label, compute_shape, labelling_of};
151 if entity.stub {
152 return None;
153 }
154 let schema = self.schemas.get(entity.mem.as_str())?;
155 let lab = labelling_of(schema)?;
156 let mem_lab = self.mem_labelling(entity.mem.as_str())?;
157 let label = *mem_lab.labels.get(entity.id.0.as_str())?;
158 let defeated_by = if label == Label::Defeated {
159 mem_lab.accepted_attackers_of(entity.id.0.as_str())
160 } else {
161 Vec::new()
162 };
163 let undecided_by = if label == Label::Undecided {
164 mem_lab.undecided_attackers_of(entity.id.0.as_str())
165 } else {
166 Vec::new()
167 };
168 let shape = lab.support.as_ref().map(|walk| {
169 let label_of = |id: &EntityId| -> Option<Label> {
170 self.mem_labelling(id.mem())
171 .and_then(|ml| ml.labels.get(id.0.as_str()).copied())
172 };
173 compute_shape(&self.store, &entity.id, walk, &label_of)
174 });
175 Some(crate::ops::labelling::LabellingView {
176 label,
177 defeated_by,
178 undecided_by,
179 shape,
180 })
181 }
182
183 /// The `labelling` health axis payload — per declaring mem:
184 /// counts per label, the defeated list with its accepted
185 /// attackers, the undecided list with its open attacker set, and
186 /// the excluded cross-mem attack-edge count. One composer shared
187 /// by the CLI health command and the MCP server.
188 pub fn health_labelling_axis(&self, mem_filter: Option<&str>) -> serde_json::Value {
189 use crate::ops::labelling::Label;
190 let mut mems = serde_json::Map::new();
191 let mut mem_names: Vec<&String> = self.schemas.keys().collect();
192 mem_names.sort();
193 for mem in mem_names {
194 if let Some(v) = mem_filter
195 && mem != v
196 {
197 continue;
198 }
199 let Some(ml) = self.mem_labelling(mem) else {
200 continue;
201 };
202 let mut accepted = 0usize;
203 let mut defeated: Vec<serde_json::Value> = Vec::new();
204 let mut undecided: Vec<serde_json::Value> = Vec::new();
205 for (id, label) in &ml.labels {
206 match label {
207 Label::Accepted => accepted += 1,
208 Label::Defeated => defeated.push(serde_json::json!({
209 "id": id,
210 "defeated_by": ml.accepted_attackers_of(id),
211 })),
212 Label::Undecided => undecided.push(serde_json::json!({
213 "id": id,
214 "undecided_by": ml.undecided_attackers_of(id),
215 })),
216 }
217 }
218 mems.insert(
219 mem.clone(),
220 serde_json::json!({
221 "counts": {
222 "accepted": accepted,
223 "defeated": defeated.len(),
224 "undecided": undecided.len(),
225 },
226 "defeated": defeated,
227 "undecided": undecided,
228 "cross_mem_edges_excluded": ml.cross_mem_edges_excluded,
229 }),
230 );
231 }
232 serde_json::Value::Object(mems)
233 }
234
235 /// Real entities with no incoming or outgoing edges — leaf-declared
236 /// types exempt (their edge-less entities are terminal by
237 /// construction; see [`Self::leaf_population`]).
238 pub fn orphans(&self) -> Vec<EntityId> {
239 crate::graph::query::find_orphans_with_schemas(&self.store, &self.schemas)
240 }
241
242 /// Count of real entities per leaf-declared type, keyed
243 /// `<schema_ref>:<type>` — the visible population the orphan
244 /// exemption covers.
245 pub fn leaf_population(&self) -> std::collections::BTreeMap<String, usize> {
246 crate::graph::query::leaf_population(&self.store, &self.schemas)
247 }
248
249 /// Stub entities with their referencer ids.
250 pub fn stubs(&self) -> Vec<(EntityId, Vec<EntityId>)> {
251 crate::graph::query::find_stubs(&self.store)
252 }
253
254 /// Top `limit` entities by total degree.
255 pub fn most_connected(&self, limit: usize) -> Vec<crate::graph::query::Connectivity> {
256 crate::graph::query::most_connected(&self.store, limit)
257 }
258
259 /// Entities whose type's `required_outgoing` blocks are not yet
260 /// satisfied. `mem_filter = None` scans every mem; `Some(v)`
261 /// scans only that mem.
262 pub fn missing_required_outgoing(
263 &self,
264 mem_filter: Option<&str>,
265 ) -> Vec<crate::ops::health::MissingRequiredOutgoingReport> {
266 crate::ops::health::collect_missing_required_outgoing(
267 &self.store,
268 mem_filter,
269 &self.schemas,
270 )
271 }
272
273 /// Standing violations of declared `constraints` (the health
274 /// `constraints` include) — every non-stub entity whose type
275 /// declares constraints its current state violates, in
276 /// deterministic `(mem, id)` order.
277 pub fn constraint_findings(
278 &self,
279 mem_filter: Option<&str>,
280 ) -> Vec<crate::ops::health::ConstraintFindingReport> {
281 let check_provider = self.check_standing_provider();
282 crate::ops::health::collect_constraint_findings(
283 &self.store,
284 mem_filter,
285 &self.schemas,
286 Some(&check_provider),
287 )
288 }
289
290 /// The evaluated aggregate signals for one entity — `None` when
291 /// the mem has no schema, the type is unknown or a stub, or the
292 /// type declares no signals; serving surfaces then keep their
293 /// byte-identical payloads.
294 pub fn computed_signals(
295 &self,
296 entity: &Entity,
297 ) -> Option<Vec<crate::ops::signals::ComputedSignal>> {
298 if entity.stub {
299 return None;
300 }
301 let schema = self.schemas.get(entity.mem.as_str())?;
302 let td = schema.types.get(entity.entity_type.as_str())?;
303 if td.signals.is_empty() {
304 return None;
305 }
306 Some(crate::ops::signals::compute_signals(
307 &self.store,
308 td,
309 &entity.id,
310 ))
311 }
312
313 /// Every entity carrying at least one signal above `none` — the
314 /// include-gated `signals` health axis.
315 pub fn signal_reports(
316 &self,
317 mem_filter: Option<&str>,
318 ) -> Vec<crate::ops::health::SignalReport> {
319 crate::ops::health::collect_signal_reports(&self.store, mem_filter, &self.schemas)
320 }
321
322 /// The `signals` health axis payload — the entity roster plus
323 /// per-level counts. One composer shared by the CLI health
324 /// command and the MCP server so the axis cannot drift
325 /// between surfaces.
326 pub fn health_signals_axis(&self, mem_filter: Option<&str>) -> serde_json::Value {
327 use memstead_schema::SignalLevel;
328 let reports = self.signal_reports(mem_filter);
329 let mut notice = 0usize;
330 let mut warn = 0usize;
331 for r in &reports {
332 for s in &r.signals {
333 match s.level {
334 Some(SignalLevel::Notice) => notice += 1,
335 Some(SignalLevel::Warn) => warn += 1,
336 None => {}
337 }
338 }
339 }
340 serde_json::json!({
341 "entities": reports,
342 "counts": { "notice": notice, "warn": warn },
343 })
344 }
345
346 /// Defective section-format declarations the loaded schemas carry
347 /// (lenient boot recorded them; install would have refused).
348 pub fn schema_format_defects(&self) -> Vec<crate::ops::health::SchemaFormatDefect> {
349 crate::ops::health::collect_schema_format_defects(&self.schemas)
350 }
351
352 /// Conformance-axis integrity findings for one mem — which
353 /// entities a write would refuse under the effective schema, and
354 /// why. `target_schema = None` lints against the mem's current
355 /// pin; `Some(ref)` lints against that schema instead (resolved
356 /// among mem-pinned, workspace, and built-in schemas).
357 pub fn conformance_findings(
358 &self,
359 mem: &str,
360 target_schema: Option<&memstead_schema::SchemaRef>,
361 ) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
362 let pinned = self
363 .schemas
364 .get(mem)
365 .ok_or_else(|| self.unknown_mem_error(mem))?;
366 let effective: Arc<Schema> = match target_schema {
367 None => pinned.clone(),
368 Some(target) => self.resolve_schema_by_ref(target).ok_or_else(|| {
369 let consulted: Vec<_> = self
370 .workspace_schemas
371 .iter()
372 .chain(self.builtin_schemas.iter())
373 .cloned()
374 .collect();
375 EngineError::SchemaNotFound {
376 mem: mem.to_string(),
377 pin: target.as_display(),
378 sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
379 &target.name,
380 &target.version,
381 &consulted,
382 ),
383 install_hint: None,
384 }
385 .with_schema_install_probe(self.workspace_root())
386 })?,
387 };
388 Ok(crate::ops::integrity::conformance_findings(
389 &self.store,
390 mem,
391 &effective,
392 &self.schemas,
393 ))
394 }
395
396 /// What `mem`'s entity BODIES carry that their types do not declare
397 /// (consistency-sweep 04/01): headings absorbed into the catch-all,
398 /// headings repeated so that later bodies were not kept, and frontmatter
399 /// keys the next write will drop.
400 ///
401 /// A folder mem's ledger set against its file set, per mem.
402 ///
403 /// **Folder mems only, and that is the point.** On a
404 /// git-branch mem the change set is a real two-tree diff against the
405 /// committed tree, so ledger-versus-files divergence is structurally
406 /// impossible; emitting an always-clean version of this check there would
407 /// be a surface asserting something it never had to establish, which is
408 /// the failure class this bundle exists to remove. Such a mem is absent
409 /// from the map rather than present and empty.
410 pub fn ledger_reconciliation(
411 &self,
412 ) -> std::collections::BTreeMap<String, crate::filesystem::changelog::LedgerReconciliation>
413 {
414 let mut out = std::collections::BTreeMap::new();
415 for m in &self.mounts {
416 let crate::workspace::MountStorage::Folder { path } = &m.mount.storage else {
417 continue;
418 };
419 if let Ok(r) = crate::filesystem::changelog::reconcile_ledger(path) {
420 out.insert(m.mount.mem.clone(), r);
421 }
422 }
423 out
424 }
425
426 /// Separate from [`Self::conformance_findings`] on purpose. These are
427 /// observations, not violations: absorbing an undeclared heading is the
428 /// catch-all working as designed, and reporting it as a finding would fail
429 /// every mem that uses the feature. What a reader needs here is whether the
430 /// content SURVIVES, which each observation states.
431 pub fn body_observations(
432 &self,
433 mem: &str,
434 target_schema: Option<&memstead_schema::SchemaRef>,
435 ) -> Result<Vec<crate::ops::integrity::BodyObservation>, EngineError> {
436 let pinned = self
437 .schemas
438 .get(mem)
439 .ok_or_else(|| self.unknown_mem_error(mem))?;
440 let effective: Arc<Schema> = match target_schema {
441 None => pinned.clone(),
442 Some(target) => {
443 self.resolve_schema_by_ref(target)
444 .ok_or_else(|| EngineError::SchemaNotFound {
445 mem: mem.to_string(),
446 pin: target.as_display(),
447 sources: Vec::new(),
448 install_hint: None,
449 })?
450 }
451 };
452 Ok(crate::ops::integrity::body_observations(
453 &self.store,
454 mem,
455 &effective,
456 ))
457 }
458
459 /// Resolve an exact `name@version` ref against every schema this
460 /// engine can see: mem-pinned, workspace-authored, built-in.
461 /// `None` when no loaded schema matches.
462 pub(crate) fn resolve_schema_by_ref(
463 &self,
464 target: &memstead_schema::SchemaRef,
465 ) -> Option<Arc<Schema>> {
466 self.schemas
467 .values()
468 .chain(self.workspace_schemas.iter())
469 .chain(self.builtin_schemas.iter())
470 .find(|s| {
471 let (name, version) = s.id();
472 name == target.name && version == target.version
473 })
474 .cloned()
475 }
476
477 /// The mem's `Mount.schema` expectation assertion, when set.
478 /// `None` for unknown mems *and* for mems whose mount carries no
479 /// assertion (the authoritative pin then lives in the backend
480 /// config; the resolved active schema, not this, is the effective pin).
481 pub fn schema_pin(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
482 self.mounts
483 .iter()
484 .find(|m| m.mount.mem == mem)
485 .and_then(|m| m.mount.schema.clone())
486 }
487
488 /// The mem's in-flight migration target, when dual-pin state is
489 /// active. `None` for settled or unknown mems.
490 pub fn migration_target(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
491 self.mounts
492 .iter()
493 .find(|m| m.mount.mem == mem)
494 .and_then(|m| m.mount.migration_target.clone())
495 }
496
497 /// Consistency-axis integrity findings for one mem — the
498 /// pre-existing graph-coherence categories (dangling links, stubs)
499 /// plus cross-mem edges the workspace grant table no longer permits,
500 /// projected into the `{ id, axis, code, detail }` finding shape.
501 pub fn consistency_findings(
502 &self,
503 mem: &str,
504 ) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
505 if !self.schemas.contains_key(mem) {
506 return Err(self.unknown_mem_error(mem));
507 }
508 let mut findings = crate::ops::integrity::consistency_findings(
509 &self.store,
510 mem,
511 // The one grant resolver, the same one the write gate calls. Every
512 // consumer of the axis reaches it through this funnel, so there is
513 // no site where a second answer could be written (04/07).
514 &|from, to| self.cross_mem_link_allowed(from, to),
515 // The mount set, so an edge into a mem that is not mounted is
516 // reported as the dangling finding it is and never as a grant
517 // the table still names.
518 &|target| self.mount(target).is_some(),
519 );
520 // The provenance layer's own consistency: a sidecar the engine cannot
521 // read is a finding on the mem, beside the entity-level ones. Without
522 // it every anchor surface reads zero rows over this mem and calls
523 // that clean (backlog, found by the evidence-engine grader 2026-09-02).
524 if let Some(why) = self.anchors_sidecar_error(mem) {
525 findings.push(crate::ops::integrity::IntegrityFinding {
526 id: mem.to_string(),
527 axis: crate::ops::integrity::IntegrityAxis::Consistency,
528 code: "ANCHORS_SIDECAR_UNREADABLE".to_string(),
529 detail: serde_json::json!({
530 "mem": mem,
531 "reason": why,
532 "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",
533 }),
534 });
535 }
536 Ok(findings)
537 }
538
539 /// Every cross-mem edge the workspace's current grant resolution does
540 /// not permit, across every visible mem.
541 ///
542 /// A projection of [`Self::consistency_findings`] filtered to the one
543 /// code, not a second scan: the revoke path and the health axis must
544 /// never be able to answer differently about the same edge, and the
545 /// surest way to guarantee that is for one of them to BE the other.
546 ///
547 /// Call it after the grant edit has landed and the settings have been
548 /// reloaded — the answer is "what does the CURRENT policy leave
549 /// unbacked", which is what an operator revoking a grant wants to know.
550 ///
551 /// Takes `&mut self` because it must load lazily-deferred mems first. A
552 /// deferred mem's entities are not in the store, so scanning without the
553 /// load would report zero ungranted edges for it and call that clean —
554 /// which is precisely the silent all-clear this whole axis exists to
555 /// prevent. The long-lived server engines carry lazy mounts; the CLI's
556 /// fresh boot does not, so this only bites on the surface where it is
557 /// hardest to notice.
558 pub fn ungranted_cross_mem_edges(&mut self) -> Vec<crate::ops::integrity::IntegrityFinding> {
559 self.ensure_mems_loaded(None);
560 let mut mems: Vec<&String> = self.schemas.keys().collect();
561 mems.sort();
562 mems.into_iter()
563 .filter_map(|mem| self.consistency_findings(mem).ok())
564 .flatten()
565 .filter(|f| f.code == "CROSS_MEM_EDGE_UNGRANTED")
566 .collect()
567 }
568
569 /// The edges that went from permitted to unpermitted between two
570 /// readings of [`Self::ungranted_cross_mem_edges`] — what a policy edit
571 /// just orphaned, as opposed to what was already orphaned before it.
572 ///
573 /// A revocation that reported the whole standing set would blame this
574 /// edit for every edge some earlier unrelated revocation left behind,
575 /// which is a different and less useful claim.
576 pub fn newly_ungranted(
577 before: &[crate::ops::integrity::IntegrityFinding],
578 after: Vec<crate::ops::integrity::IntegrityFinding>,
579 ) -> Vec<crate::ops::integrity::IntegrityFinding> {
580 let seen: std::collections::BTreeSet<(String, String)> = before
581 .iter()
582 .map(|f| (f.id.clone(), f.detail["target_id"].to_string()))
583 .collect();
584 after
585 .into_iter()
586 .filter(|f| !seen.contains(&(f.id.clone(), f.detail["target_id"].to_string())))
587 .collect()
588 }
589
590 /// Engine-wide health summary across every mount.
591 pub fn health(&self) -> crate::ops::HealthSummary {
592 self.health_inner(None)
593 }
594
595 /// Health summary scoped to one visible mem. The scans and
596 /// structural counts narrow to that mem; workspace-level facts
597 /// (quarantine roster, boot diagnosis, workspace-scoped warnings)
598 /// stay global — an agent scoping to one mem must still see them.
599 /// A name that is quarantined or not on the visible roster refuses
600 /// `UNKNOWN_MEM` — the same gate `search` applies to its `mem`
601 /// filter, so "no such mem" and "healthy mem, nothing to report"
602 /// can never be confused. `None` is the engine-wide sweep.
603 pub fn health_scoped(
604 &self,
605 mem: Option<&str>,
606 ) -> Result<crate::ops::HealthSummary, crate::EngineError> {
607 if let Some(name) = mem
608 && (self.quarantine_reason(name).is_some() || !self.mem_router.is_visible(name))
609 {
610 return Err(self.unknown_mem_error(name));
611 }
612 Ok(self.health_inner(mem))
613 }
614
615 fn health_inner(&self, mem: Option<&str>) -> crate::ops::HealthSummary {
616 let fallback = engine_fallback_type();
617 let mut summary =
618 crate::ops::health::compute_health(&self.store, fallback.as_ref(), &self.schemas, mem);
619 self.apply_anchor_clock(&mut summary, mem);
620 // Merge in load-time drift warnings so every caller of
621 // Engine::health — MCP handler, Swift FFI, direct CLI —
622 // sees the SuspiciousNestedPrefix / DuplicateSectionHeading
623 // findings without reaching into private engine state. The
624 // MCP handler further appends request-scoped warnings on
625 // top. Mirrors full's merge.
626 if !self.load_warnings.is_empty() {
627 let mut merged = self.load_warnings.clone();
628 merged.append(&mut summary.warnings);
629 summary.warnings = merged;
630 }
631 // A standing property, reported here rather than on every boot: a
632 // folder mem's drift cursor is its own ledger, which only the engine
633 // writes, so an edit made to its files by anything else is invisible
634 // and reads keep serving the pre-edit content. Silence about that is
635 // the one outcome this forbids. Git-branch mems are
636 // absent: their change set is a real two-tree diff, so the condition
637 // cannot arise.
638 for m in &self.mounts {
639 if matches!(
640 m.mount.storage,
641 crate::workspace::MountStorage::Folder { .. }
642 ) && mem.is_none_or(|scope| scope == m.mount.mem)
643 {
644 summary
645 .warnings
646 .push(crate::ops::WarningHint::OutOfBandEditsUndetected {
647 mem: m.mount.mem.clone(),
648 });
649 }
650 }
651 // Quarantine roster — a boot-honesty fact, present whenever
652 // non-empty, never behind an include gate. Empty (and omitted
653 // from the wire) on a healthy workspace.
654 summary.quarantined = self
655 .quarantined
656 .iter()
657 .map(|q| crate::ops::QuarantinedMemReport {
658 mem: q.mount.mem.clone(),
659 reason_code: q.reason_code.clone(),
660 reason_message: q.reason_message.clone(),
661 })
662 .collect();
663 // Per-file load failures ride the report unconditionally, like
664 // the quarantine roster — each entry's message names the remedy
665 // (the merge-conflict refusal names `memstead conflicts
666 // resolve`), and a remedy only a library accessor carries is a
667 // capability nobody finds at the moment it is needed.
668 summary.load_errors = self
669 .load_errors
670 .iter()
671 .map(|(path, msg)| crate::ops::LoadErrorReport {
672 file: path.display().to_string(),
673 error: msg.clone(),
674 })
675 .collect();
676 summary.boot_diagnosis = self
677 .boot_diagnosis
678 .as_ref()
679 .map(|(code, message)| serde_json::json!({ "code": code, "message": message }));
680 // Surface OUTER_REPO_NOT_IGNORING_MEM_REPO when the
681 // workspace is embedded inside a git repository whose
682 // .gitignore does not list `mem-repo/`. Skipped when
683 // workspace_root is unset (engine built ad-hoc from a mount
684 // list).
685 if let Some(root) = self.workspace_root.as_deref()
686 && let Some(outer) = crate::workspace_root::find_enclosing_git_repo(root)
687 && !crate::workspace_root::outer_repo_ignores_mem_repo(&outer, root)
688 {
689 summary
690 .warnings
691 .push(WarningHint::OuterRepoNotIgnoringMemRepo {
692 outer_repo_root: outer.display().to_string(),
693 workspace_root: root.display().to_string(),
694 });
695 }
696 // Authoring-drift axis: for every pinned schema whose sealed
697 // copy carries an install-provenance stamp, report a MISSING
698 // authoring package (stamped path gone) or a DIVERGED one
699 // (present but no longer parsed-equivalent to the seal).
700 // Unstamped schemas — sealed pre-stamp, built-ins, archive
701 // installs — produce no finding. Read-only on both copies.
702 summary.warnings.extend(self.authoring_drift_findings());
703 // Rot axis for the pins the drift axis skips: an UNSTAMPED
704 // sealed package whose content no longer passes current-
705 // language authoring validation gets its own low-tier hint —
706 // the holding runs fine on the tolerant seal, but the package
707 // (and the unlocatable authoring source it came from) is no
708 // longer installable, and nothing else would say so before the
709 // next install attempt. A parsing unstamped package stays
710 // silent; stamped pins are the drift axis's business.
711 summary.warnings.extend(self.unstamped_rot_findings());
712 // Under a mem scope, mem-attributable warnings narrow to the
713 // scoped mem; workspace- and request-scoped warnings return
714 // `None` from `source_mem()` and stay visible regardless.
715 // Mirrors the health composer's filter.
716 if let Some(v) = mem {
717 summary
718 .warnings
719 .retain(|w| w.source_mem().is_none_or(|wv| wv == v));
720 }
721 summary
722 }
723
724 /// Compute the authoring-drift findings for every stamped pinned
725 /// schema. See the call site in [`Self::health`] for the axis
726 /// contract; returns an empty list when no workspace root is set
727 /// (ad-hoc mount-list engines have no authoring tree to check).
728 fn authoring_drift_findings(&self) -> Vec<WarningHint> {
729 let Some(root) = self.workspace_root.as_deref() else {
730 return Vec::new();
731 };
732 // Group pinning mems by (name, version) — BTreeMap for a
733 // deterministic finding order.
734 let mut pins: std::collections::BTreeMap<(String, String), Vec<String>> =
735 std::collections::BTreeMap::new();
736 for (mem, schema) in &self.schemas {
737 let (name, version) = schema.id();
738 pins.entry((name.to_string(), version.to_string()))
739 .or_default()
740 .push(mem.clone());
741 }
742 let mut out = Vec::new();
743 for ((name, version), mut mems) in pins {
744 mems.sort();
745 let Some(stamped_path) = self.read_install_provenance(root, &name, &version) else {
746 continue;
747 };
748 let schema_ref = format!("{name}@{version}");
749 // A workspace-relative stamp (the portable form the installer
750 // writes for in-workspace authoring dirs) resolves against
751 // THIS workspace root, so the axis checks real drift on every
752 // clone instead of reporting another machine's absolute path
753 // as missing. Absolute stamps stay machine-pinned as-is.
754 let stamped = std::path::Path::new(&stamped_path);
755 let resolved: std::path::PathBuf = if stamped.is_absolute() {
756 stamped.to_path_buf()
757 } else {
758 root.join(stamped)
759 };
760 let authoring = resolved.as_path();
761 if !authoring.is_dir() {
762 out.push(WarningHint::SchemaAuthoringSourceMissing {
763 schema_ref,
764 stamped_path,
765 mems,
766 });
767 continue;
768 }
769 let sealed = self
770 .schemas
771 .get(&mems[0])
772 .expect("mems collected from self.schemas keys")
773 .clone();
774 match memstead_schema::load_schema_from_dir(authoring) {
775 Err(e) => out.push(WarningHint::SchemaAuthoringSourceDiverged {
776 schema_ref,
777 stamped_path,
778 mems,
779 detail: format!("the authoring package no longer loads: {e}"),
780 }),
781 Ok(authored) => {
782 if schema_parsed_fingerprint(&authored) != schema_parsed_fingerprint(&sealed) {
783 out.push(WarningHint::SchemaAuthoringSourceDiverged {
784 schema_ref,
785 stamped_path,
786 mems,
787 detail: "the parsed authoring package differs from the sealed copy \
788 the engine runs on"
789 .to_string(),
790 });
791 }
792 }
793 }
794 }
795 out
796 }
797
798 /// Compute the rot findings for every UNSTAMPED pinned schema: read
799 /// the sealed package's content back (folder seal directory, or the
800 /// `__MEMSTEAD:schemas/` ref via the ops bundle) and run the
801 /// authoring-tier check over it. A pin with a stamp is skipped (the
802 /// divergence axis owns it); a pin with no readable sealed package
803 /// — built-ins resolving from the embedded catalogue — is skipped
804 /// too (nothing on disk can rot). See the call site in
805 /// [`Self::health`] for the axis contract.
806 fn unstamped_rot_findings(&self) -> Vec<WarningHint> {
807 let Some(root) = self.workspace_root.as_deref() else {
808 return Vec::new();
809 };
810 let mut pins: std::collections::BTreeMap<(String, String), Vec<String>> =
811 std::collections::BTreeMap::new();
812 for (mem, schema) in &self.schemas {
813 let (name, version) = schema.id();
814 pins.entry((name.to_string(), version.to_string()))
815 .or_default()
816 .push(mem.clone());
817 }
818 let mut out = Vec::new();
819 for ((name, version), mut mems) in pins {
820 mems.sort();
821 if self
822 .read_install_provenance(root, &name, &version)
823 .is_some()
824 {
825 continue; // stamped — the divergence axis checks it
826 }
827 let schema_ref = format!("{name}@{version}");
828 // Folder seal: the sealed package is a real directory the
829 // authoring loader can probe directly.
830 let sealed_dir = root.join(".memstead").join("schemas").join(&schema_ref);
831 let detail: Option<String> = if sealed_dir.join("schema.yaml").is_file() {
832 memstead_schema::load_schema_from_dir(&sealed_dir)
833 .err()
834 .map(|e| e.to_string())
835 } else if let Some((manifest, types)) = self.read_sealed_package_yamls(&name, &version)
836 {
837 memstead_schema::loader::check_package_reauthorable(&manifest, &types)
838 .err()
839 .map(|e| e.to_string())
840 } else {
841 None // no sealed copy anywhere — embedded builtin
842 };
843 if let Some(detail) = detail {
844 out.push(WarningHint::SchemaUnstampedSourceRot {
845 schema_ref,
846 mems,
847 detail,
848 });
849 }
850 }
851 out
852 }
853
854 /// Read a sealed package's `schema.yaml` + `types/*.yaml` back from
855 /// the `__MEMSTEAD:schemas/` ref, reconstructing the type-file names
856 /// from the pinned parsed schema's type roster (seal-time authoring
857 /// enforces stem == declared type name). `None` when the ops bundle
858 /// or the package is absent — the embedded-builtin state.
859 fn read_sealed_package_yamls(
860 &self,
861 name: &str,
862 version: &str,
863 ) -> Option<(String, Vec<(String, String)>)> {
864 let ops = self.git_branch_ops()?;
865 let root = self.workspace_root.as_deref()?;
866 let gitdir = self
867 .mounts
868 .iter()
869 .find_map(|m| match &m.mount.storage {
870 crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
871 _ => None,
872 })
873 .or_else(|| {
874 let g = root.join("mem-repo").join(".git");
875 g.is_dir().then_some(g)
876 })?;
877 let read = |rel: &str| -> Option<String> {
878 (ops.read_schema_file)(&gitdir, name, version, rel)
879 .ok()
880 .flatten()
881 .and_then(|bytes| String::from_utf8(bytes).ok())
882 };
883 let manifest = read("schema.yaml")?;
884 let schema = self
885 .schemas
886 .values()
887 .find(|s| {
888 let (n, v) = s.id();
889 n == name && v.to_string() == version
890 })?
891 .clone();
892 let mut type_names: Vec<String> = schema.types.keys().cloned().collect();
893 type_names.sort();
894 let mut types = Vec::new();
895 for t in type_names {
896 if let Some(body) = read(&format!("types/{t}.yaml")) {
897 types.push((t, body));
898 }
899 }
900 Some((manifest, types))
901 }
902
903 /// Read the install-provenance stamp for a sealed schema package,
904 /// checking the folder location first
905 /// (`.memstead/schemas/<name>@<version>/`) and falling back to the
906 /// `__MEMSTEAD:schemas/` ref via the git-branch ops bundle when
907 /// wired. `None` when no stamp exists anywhere — the normal state
908 /// for pre-stamp seals, built-ins, and archive installs.
909 fn read_install_provenance(&self, root: &Path, name: &str, version: &str) -> Option<String> {
910 let folder_stamp = root
911 .join(".memstead")
912 .join("schemas")
913 .join(format!("{name}@{version}"))
914 .join(memstead_schema::INSTALL_PROVENANCE_FILE);
915 let bytes = if folder_stamp.is_file() {
916 std::fs::read(&folder_stamp).ok()
917 } else {
918 let ops = self.git_branch_ops()?;
919 let gitdir = self
920 .mounts
921 .iter()
922 .find_map(|m| match &m.mount.storage {
923 crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
924 Some(gitdir.clone())
925 }
926 _ => None,
927 })
928 .or_else(|| {
929 let g = root.join("mem-repo").join(".git");
930 g.is_dir().then_some(g)
931 })?;
932 (ops.read_schema_file)(
933 &gitdir,
934 name,
935 version,
936 memstead_schema::INSTALL_PROVENANCE_FILE,
937 )
938 .ok()
939 .flatten()
940 }?;
941 let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
942 v.get("authoring_path")?.as_str().map(String::from)
943 }
944}